@btc-vision/wallet-sdk 2.2.0-beta.0 → 2.2.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/network/index.ts","../src/address/index.ts","../src/keyring/hd-keyring.ts","../src/keyring/simple-keyring.ts","../src/keyring/key-export.ts","../src/message/backend.ts","../src/message/signing.ts","../src/message/bip322.ts","../src/wallet/local-wallet.ts","../src/types/index.ts"],"sourcesContent":["/**\n * OPNet Wallet SDK - Network Module\n * Network configuration and conversion utilities.\n */\n\nimport { type Network, networks } from '@btc-vision/bitcoin';\nimport { WalletNetworks } from '@btc-vision/transaction';\n\n/**\n * Convert WalletNetworks enum to @btc-vision/bitcoin Network object\n */\nexport function toNetwork(networkType: WalletNetworks): Network {\n switch (networkType) {\n case WalletNetworks.Mainnet: {\n return networks.bitcoin;\n }\n case WalletNetworks.Testnet: {\n return networks.testnet;\n }\n case WalletNetworks.Regtest: {\n return networks.regtest;\n }\n }\n}\n\n/**\n * Convert @btc-vision/bitcoin Network object to WalletNetworks enum\n */\nexport function toNetworkType(network: Network): WalletNetworks {\n if (network.bech32 === networks.bitcoin.bech32) {\n return WalletNetworks.Mainnet;\n }\n if (network.bech32 === networks.testnet.bech32) {\n return WalletNetworks.Testnet;\n }\n return WalletNetworks.Regtest;\n}\n\n/**\n * Get the bech32 prefix for a network type\n */\nexport function getBech32Prefix(networkType: WalletNetworks): string {\n const network = toNetwork(networkType);\n return network.bech32;\n}\n\n/**\n * Detect network type from an address\n */\nexport function detectNetworkFromAddress(address: string): WalletNetworks | null {\n if (address.startsWith('bc1') || address.startsWith('1') || address.startsWith('3')) {\n return WalletNetworks.Mainnet;\n }\n if (address.startsWith('tb1') || address.startsWith('m') || address.startsWith('n') || address.startsWith('2')) {\n return WalletNetworks.Testnet;\n }\n if (address.startsWith('bcrt1')) {\n return WalletNetworks.Regtest;\n }\n return null;\n}\n\n/**\n * Validate that an address matches the expected network\n */\nexport function validateAddressNetwork(address: string, expectedNetwork: WalletNetworks): boolean {\n const detectedNetwork = detectNetworkFromAddress(address);\n return detectedNetwork === expectedNetwork;\n}\n","/**\r\n * OPNet Wallet SDK - Address Module\r\n * Address generation, validation, and conversion utilities.\r\n * Uses @btc-vision/transaction AddressVerificator for all operations.\r\n */\r\n\r\nimport { address as bitcoinAddress, fromHex, type Network, networks, type Payment, payments, toHex } from '@btc-vision/bitcoin';\r\nimport { createPublicKey, createXOnlyPublicKey, fromHexInternal } from '@btc-vision/ecpair';\r\nimport { AddressTypes, AddressVerificator, WalletNetworks } from '@btc-vision/transaction';\r\nimport { toNetwork } from '@/network';\r\nimport type { DecodedAddress } from '@/types';\r\n\r\n/**\r\n * Generate a Bitcoin address from a public key\r\n */\r\nexport function publicKeyToAddress(publicKey: Uint8Array | string, addressType: AddressTypes, network: Network): string {\r\n const pubkeyBytes: Uint8Array = typeof publicKey === 'string' ? fromHexInternal(publicKey) : publicKey;\r\n\r\n switch (addressType) {\r\n case AddressTypes.P2PKH: {\r\n const payment = payments.p2pkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2PKH address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2WPKH: {\r\n const payment = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2WPKH address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2TR: {\r\n const xOnly: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\r\n const payment = payments.p2tr({ internalPubkey: createXOnlyPublicKey(xOnly), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2TR address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\r\n const p2wpkh = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n const payment = payments.p2sh({ redeem: p2wpkh, network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2SH-P2WPKH address');\r\n }\r\n return payment.address;\r\n }\r\n default: {\r\n throw new Error(`Unsupported address type: ${addressType as string}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generate a payment object from a public key\r\n */\r\nexport function publicKeyToPayment(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n network: Network\r\n): Payment {\r\n const pubkeyBytes: Uint8Array = typeof publicKey === 'string' ? fromHexInternal(publicKey) : publicKey;\r\n\r\n switch (addressType) {\r\n case AddressTypes.P2PKH: {\r\n return payments.p2pkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n }\r\n case AddressTypes.P2WPKH: {\r\n return payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n }\r\n case AddressTypes.P2TR: {\r\n const xOnly: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\r\n return payments.p2tr({ internalPubkey: createXOnlyPublicKey(xOnly), network });\r\n }\r\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\r\n const p2wpkh = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n return payments.p2sh({ redeem: p2wpkh, network });\r\n }\r\n default: {\r\n throw new Error(`Unsupported address type: ${addressType as string}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generate scriptPubKey from a public key\r\n */\r\nexport function publicKeyToScriptPubKey(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n network: Network\r\n): Uint8Array {\r\n const payment = publicKeyToPayment(publicKey, addressType, network);\r\n if (!payment.output) {\r\n throw new Error('Failed to generate script pubkey');\r\n }\r\n return payment.output;\r\n}\r\n\r\n/**\r\n * Convert an address to its scriptPubKey\r\n */\r\nexport function addressToScriptPubKey(address: string, network: Network): Uint8Array {\r\n return bitcoinAddress.toOutputScript(address, network);\r\n}\r\n\r\n/**\r\n * Convert scriptPubKey to an address\r\n */\r\nexport function scriptPubKeyToAddress(scriptPubKey: Uint8Array | string, network: Network): string {\r\n const script = typeof scriptPubKey === 'string' ? fromHex(scriptPubKey) : scriptPubKey;\r\n return bitcoinAddress.fromOutputScript(script, network);\r\n}\r\n\r\n/**\r\n * Validate if an address is valid for the given network\r\n */\r\nexport function isValidAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.detectAddressType(address, network) !== null;\r\n}\r\n\r\n/**\r\n * Detect the address type from an address string\r\n */\r\nexport function detectAddressType(address: string, network: Network): AddressTypes | null {\r\n return AddressVerificator.detectAddressType(address, network);\r\n}\r\n\r\n/**\r\n * Decode an address to get its network type, address type, and scriptPubKey\r\n */\r\nexport function decodeAddress(address: string): DecodedAddress | null {\r\n const mainnet = networks.bitcoin;\r\n const testnet = networks.testnet;\r\n const regtest = networks.regtest;\r\n\r\n // Try each network to decode the address\r\n const networksToTry: { network: Network; networkType: WalletNetworks }[] = [\r\n { network: mainnet, networkType: WalletNetworks.Mainnet },\r\n { network: testnet, networkType: WalletNetworks.Testnet },\r\n { network: regtest, networkType: WalletNetworks.Regtest }\r\n ];\r\n\r\n for (const { network, networkType } of networksToTry) {\r\n try {\r\n const scriptPubKey = bitcoinAddress.toOutputScript(address, network);\r\n const addressType = detectAddressType(address, network);\r\n\r\n if (addressType !== null) {\r\n return {\r\n networkType,\r\n addressType,\r\n scriptPubKey\r\n };\r\n }\r\n } catch {\r\n // Try next network\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * Validate a public key using AddressVerificator\r\n */\r\nexport function isValidPublicKey(publicKey: Uint8Array | string, network: Network): boolean {\r\n const pubkeyHex = typeof publicKey === 'string' ? publicKey : toHex(publicKey);\r\n return AddressVerificator.isValidPublicKey(pubkeyHex, network);\r\n}\r\n\r\n/**\r\n * Validate a Taproot (P2TR) address\r\n */\r\nexport function isValidP2TRAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isValidP2TRAddress(address, network);\r\n}\r\n\r\n/**\r\n * Check if an address is P2WPKH\r\n */\r\nexport function isP2WPKHAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isP2WPKHAddress(address, network);\r\n}\r\n\r\n/**\r\n * Check if an address is P2PKH or P2SH\r\n */\r\nexport function isP2PKHOrP2SHAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isP2PKHOrP2SH(address, network);\r\n}\r\n\r\n/**\r\n * Convert WalletNetworks to Network and validate address\r\n */\r\nexport function isValidAddressForNetworkType(address: string, networkType: WalletNetworks): boolean {\r\n const network = toNetwork(networkType);\r\n return isValidAddress(address, network);\r\n}\r\n\r\n/**\r\n * Get address type with WalletNetworks parameter\r\n */\r\nexport function getAddressType(address: string, networkType: WalletNetworks): AddressTypes | null {\r\n const network = toNetwork(networkType);\r\n return detectAddressType(address, network);\r\n}\r\n\r\n/**\r\n * Convert WalletNetworks-based operations to Network-based\r\n */\r\nexport function publicKeyToAddressWithNetworkType(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n networkType: WalletNetworks\r\n): string {\r\n const network = toNetwork(networkType);\r\n return publicKeyToAddress(publicKey, addressType, network);\r\n}\r\n","/**\r\n * OPNet Wallet SDK - HD Keyring\r\n * Hierarchical Deterministic keyring with quantum-resistant (ML-DSA) support.\r\n * Uses @btc-vision/transaction Mnemonic class for BIP39 + BIP360 key derivation.\r\n */\r\n\r\nimport { isTaprootInput, type Network, networks, Psbt } from '@btc-vision/bitcoin';\r\nimport { createBytes32, createMessageHash, fromHexInternal, toHex, type UniversalSigner } from '@btc-vision/ecpair';\r\nimport {\r\n AddressTypes,\r\n MLDSASecurityLevel,\r\n Mnemonic,\r\n MnemonicStrength,\r\n type QuantumBIP32Interface,\r\n Wallet\r\n} from '@btc-vision/transaction';\r\nimport { publicKeyToAddress } from '@/address';\r\nimport type { AccountAddresses, AccountInfo, HdKeyringOptions, ToSignInput } from '@/types';\r\n\r\n/**\r\n * HD Keyring with quantum-resistant cryptography support.\r\n * Supports BIP39 mnemonic phrases with BIP360 quantum key derivation.\r\n */\r\nexport class HdKeyring {\r\n public static readonly type = 'HD Key Tree';\r\n public readonly type = HdKeyring.type;\r\n\r\n private mnemonic: Mnemonic | null = null;\r\n private readonly wallets: Map<number, Wallet> = new Map();\r\n private readonly activeIndexes: number[] = [];\r\n private readonly network: Network;\r\n private readonly securityLevel: MLDSASecurityLevel;\r\n private readonly passphrase: string;\r\n private addressType: AddressTypes;\r\n private readonly _hdPath: string;\r\n\r\n constructor(options: Partial<HdKeyringOptions>) {\r\n if (!options.network) {\r\n throw new Error('HdKeyring: Network option is required');\r\n }\r\n\r\n this.network = options.network;\r\n this.securityLevel = options?.securityLevel ?? MLDSASecurityLevel.LEVEL2;\r\n this.passphrase = options?.passphrase ?? '';\r\n this.addressType = options?.addressType ?? AddressTypes.P2TR;\r\n this._hdPath = options?.hdPath ?? '';\r\n\r\n if (options?.mnemonic !== undefined) {\r\n this.initFromMnemonic(options.mnemonic);\r\n\r\n if (options.activeIndexes !== undefined && options.activeIndexes.length > 0) {\r\n this.activateAccounts([...options.activeIndexes]);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get the HD derivation path\r\n */\r\n public get hdPath(): string {\r\n return this._hdPath;\r\n }\r\n\r\n /**\r\n * Generate a new mnemonic with quantum support\r\n */\r\n public static generate(\r\n strength: MnemonicStrength = MnemonicStrength.MAXIMUM,\r\n passphrase = '',\r\n network: Network = networks.bitcoin,\r\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\r\n ): HdKeyring {\r\n const mnemonic = Mnemonic.generate(strength, passphrase, network, securityLevel);\r\n const keyring = new HdKeyring({\r\n network,\r\n securityLevel,\r\n passphrase\r\n });\r\n keyring.mnemonic = mnemonic;\r\n return keyring;\r\n }\r\n\r\n /**\r\n * Initialize from an existing mnemonic phrase\r\n */\r\n public initFromMnemonic(phrase: string): void {\r\n if (this.mnemonic !== null) {\r\n throw new Error('HdKeyring: Mnemonic already initialized');\r\n }\r\n\r\n this.mnemonic = new Mnemonic(phrase, this.passphrase, this.network, this.securityLevel);\r\n }\r\n\r\n /**\r\n * Get the mnemonic phrase\r\n */\r\n public getMnemonic(): string {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n return this.mnemonic.phrase;\r\n }\r\n\r\n /**\r\n * Check if keyring has a mnemonic\r\n */\r\n public hasMnemonic(): boolean {\r\n return this.mnemonic !== null;\r\n }\r\n\r\n /**\r\n * Derive a wallet at a specific index.\r\n * Uses custom hdPath if set, otherwise uses Unisat-compatible derivation.\r\n */\r\n public deriveWallet(index: number): Wallet {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n\r\n const cached = this.wallets.get(index);\r\n if (cached !== undefined) {\r\n return cached;\r\n }\r\n\r\n let wallet: Wallet;\r\n\r\n // Check if using a custom HD path\r\n if (this.isCustomHdPath()) {\r\n // Build the full classical path: hdPath + /index\r\n const classicalPath = `${this._hdPath}/${index}`;\r\n // Quantum path always uses BIP360 with coin type 0 for mainnet\r\n const coinType = this.network === networks.bitcoin ? 0 : 1;\r\n const quantumPath = `m/360'/${coinType}'/0'/0/${index}`;\r\n wallet = this.mnemonic.deriveCustomPath(classicalPath, quantumPath);\r\n } else {\r\n wallet = this.mnemonic.deriveOPWallet(this.addressType, index);\r\n }\r\n\r\n this.wallets.set(index, wallet);\r\n return wallet;\r\n }\r\n\r\n /**\r\n * Derive a wallet using standard (non-Unisat) derivation\r\n */\r\n public deriveStandardWallet(index: number): Wallet {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n\r\n return this.mnemonic.derive(index);\r\n }\r\n\r\n /**\r\n * Add new accounts to the keyring\r\n */\r\n public addAccounts(numberOfAccounts = 1): string[] {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n\r\n const newPublicKeys: string[] = [];\r\n let currentIndex = 0;\r\n\r\n while (newPublicKeys.length < numberOfAccounts) {\r\n if (!this.activeIndexes.includes(currentIndex)) {\r\n const wallet = this.deriveWallet(currentIndex);\r\n this.activeIndexes.push(currentIndex);\r\n newPublicKeys.push(wallet.toPublicKeyHex());\r\n }\r\n currentIndex++;\r\n }\r\n\r\n return newPublicKeys;\r\n }\r\n\r\n /**\r\n * Activate specific account indexes\r\n */\r\n public activateAccounts(indexes: number[]): string[] {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n\r\n const publicKeys: string[] = [];\r\n\r\n for (const index of indexes) {\r\n if (!this.activeIndexes.includes(index)) {\r\n const wallet = this.deriveWallet(index);\r\n this.activeIndexes.push(index);\r\n publicKeys.push(wallet.toPublicKeyHex());\r\n } else {\r\n const wallet = this.wallets.get(index);\r\n if (wallet !== undefined) {\r\n publicKeys.push(wallet.toPublicKeyHex());\r\n }\r\n }\r\n }\r\n\r\n return publicKeys;\r\n }\r\n\r\n /**\r\n * Get all active account public keys\r\n */\r\n public getAccounts(): string[] {\r\n return this.activeIndexes.map((index) => {\r\n const wallet = this.wallets.get(index);\r\n if (wallet === undefined) {\r\n throw new Error(`HdKeyring: Wallet at index ${index} not found`);\r\n }\r\n return wallet.toPublicKeyHex();\r\n });\r\n }\r\n\r\n /**\r\n * Get detailed account info for all active accounts\r\n */\r\n public getAccountsInfo(): AccountInfo[] {\r\n return this.activeIndexes.map((index) => {\r\n const wallet = this.wallets.get(index);\r\n if (wallet === undefined) {\r\n throw new Error(`HdKeyring: Wallet at index ${index} not found`);\r\n }\r\n\r\n const addresses: AccountAddresses = {\r\n p2pkh: wallet.legacy,\r\n p2wpkh: wallet.p2wpkh,\r\n p2tr: wallet.p2tr,\r\n p2shP2wpkh: wallet.segwitLegacy\r\n };\r\n\r\n return {\r\n index,\r\n publicKey: wallet.toPublicKeyHex(),\r\n quantumPublicKey: wallet.quantumPublicKeyHex,\r\n addresses\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Get quantum public key for an account\r\n */\r\n public getQuantumPublicKey(publicKey: string): string {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n return wallet.quantumPublicKeyHex;\r\n }\r\n\r\n /**\r\n * Get the index for a public key\r\n */\r\n public getIndexByPublicKey(publicKey: string): number | null {\r\n for (const [index, wallet] of this.wallets.entries()) {\r\n if (wallet.toPublicKeyHex() === publicKey) {\r\n return index;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Get addresses for a specific public key\r\n */\r\n public getAddressesForPublicKey(publicKey: string): AccountAddresses {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n return {\r\n p2pkh: wallet.legacy,\r\n p2wpkh: wallet.p2wpkh,\r\n p2tr: wallet.p2tr,\r\n p2shP2wpkh: wallet.segwitLegacy\r\n };\r\n }\r\n\r\n /**\r\n * Get an address for a public key and address type\r\n */\r\n public getAddress(publicKey: string, addressType: AddressTypes): string {\r\n const pubkeyBytes: Uint8Array = fromHexInternal(publicKey);\r\n return publicKeyToAddress(pubkeyBytes, addressType, this.network);\r\n }\r\n\r\n /**\r\n * Remove an account by public key\r\n */\r\n public removeAccount(publicKey: string): void {\r\n const index = this.getIndexByPublicKey(publicKey);\r\n if (index === null) {\r\n throw new Error(`HdKeyring: Account with public key ${publicKey} not found`);\r\n }\r\n\r\n const activeIdx = this.activeIndexes.indexOf(index);\r\n if (activeIdx !== -1) {\r\n this.activeIndexes.splice(activeIdx, 1);\r\n }\r\n this.wallets.delete(index);\r\n }\r\n\r\n /**\r\n * Export the private key for an account\r\n */\r\n public exportAccount(publicKey: string): string {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n return wallet.toPrivateKeyHex();\r\n }\r\n\r\n /**\r\n * Sign a PSBT transaction\r\n */\r\n public signTransaction(psbt: Psbt, inputs: readonly ToSignInput[]): Psbt {\r\n for (const input of inputs) {\r\n const wallet = this.findWalletByPublicKey(input.publicKey);\r\n const psbtInput = psbt.data.inputs[input.index];\r\n\r\n if (psbtInput === undefined) {\r\n throw new Error(`HdKeyring: Input at index ${input.index} not found`);\r\n }\r\n\r\n const keypair = wallet.keypair;\r\n const sighashTypes = input.sighashTypes !== undefined ? [...input.sighashTypes] : undefined;\r\n\r\n if (isTaprootInput(psbtInput) && input.disableTweakSigner !== true) {\r\n // For taproot, use tweaked signer\r\n const internalPubkey: Uint8Array = wallet.publicKey.subarray(1, 33);\r\n const tweakedKeypair: UniversalSigner = keypair.tweak(createBytes32(internalPubkey));\r\n psbt.signInput(input.index, tweakedKeypair, sighashTypes);\r\n } else {\r\n psbt.signInput(input.index, keypair, sighashTypes);\r\n }\r\n }\r\n\r\n return psbt;\r\n }\r\n\r\n /**\r\n * Sign arbitrary data with ECDSA or Schnorr\r\n */\r\n public signData(publicKey: string, data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n const dataHash = createMessageHash(fromHexInternal(data));\r\n\r\n if (type === 'ecdsa') {\r\n return toHex(wallet.keypair.sign(dataHash));\r\n }\r\n\r\n if (wallet.keypair.signSchnorr === undefined) {\r\n throw new Error('HdKeyring: Schnorr signing not supported by this keypair');\r\n }\r\n\r\n return toHex(wallet.keypair.signSchnorr(dataHash));\r\n }\r\n\r\n /**\r\n * Get the Wallet for a public key\r\n */\r\n public getWallet(publicKey: string): Wallet {\r\n return this.findWalletByPublicKey(publicKey);\r\n }\r\n\r\n /**\r\n * Serialize the keyring state\r\n */\r\n public serialize(): HdKeyringOptions {\r\n return {\r\n mnemonic: this.mnemonic?.phrase,\r\n passphrase: this.passphrase,\r\n network: this.network,\r\n securityLevel: this.securityLevel,\r\n activeIndexes: [...this.activeIndexes],\r\n addressType: this.addressType,\r\n hdPath: this._hdPath\r\n };\r\n }\r\n\r\n /**\r\n * Get active indexes\r\n */\r\n public getActiveIndexes(): readonly number[] {\r\n return [...this.activeIndexes];\r\n }\r\n\r\n /**\r\n * Change the address type for new derivations\r\n */\r\n public setAddressType(addressType: AddressTypes): void {\r\n this.addressType = addressType;\r\n }\r\n\r\n /**\r\n * Get current address type\r\n */\r\n public getAddressType(): AddressTypes {\r\n return this.addressType;\r\n }\r\n\r\n /**\r\n * Get the security level\r\n */\r\n public getSecurityLevel(): MLDSASecurityLevel {\r\n return this.securityLevel;\r\n }\r\n\r\n /**\r\n * Get the network\r\n */\r\n public getNetwork(): Network {\r\n return this.network;\r\n }\r\n\r\n /**\r\n * Get paginated addresses for display\r\n */\r\n public getAddressesPage(page: number, perPage = 5): { address: string; index: number }[] {\r\n if (this.mnemonic === null) {\r\n throw new Error('HdKeyring: No mnemonic initialized');\r\n }\r\n\r\n const start = page * perPage;\r\n const end = start + perPage;\r\n const results: { address: string; index: number }[] = [];\r\n\r\n for (let i = start; i < end; i++) {\r\n let wallet: Wallet;\r\n\r\n if (this.isCustomHdPath()) {\r\n const classicalPath = `${this._hdPath}/${i}`;\r\n const coinType = this.network === networks.bitcoin ? 0 : 1;\r\n const quantumPath = `m/360'/${coinType}'/0'/0/${i}`;\r\n wallet = this.mnemonic.deriveCustomPath(classicalPath, quantumPath);\r\n } else {\r\n wallet = this.mnemonic.deriveOPWallet(this.addressType, i);\r\n }\r\n\r\n const address = this.getAddressFromWallet(wallet);\r\n results.push({ address, index: i });\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Get the chain code for a wallet\r\n */\r\n public getChainCode(publicKey: string): Uint8Array {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n return Uint8Array.from(wallet.chainCode);\r\n }\r\n\r\n /**\r\n * Get ML-DSA keypair for quantum operations\r\n */\r\n public getMLDSAKeypair(publicKey: string): QuantumBIP32Interface {\r\n const wallet = this.findWalletByPublicKey(publicKey);\r\n return wallet.mldsaKeypair;\r\n }\r\n\r\n /**\r\n * Check if the current hdPath is a custom (non-standard) path\r\n */\r\n private isCustomHdPath(): boolean {\r\n // Standard BIP paths for common address types\r\n const standardPaths: Partial<Record<AddressTypes, string>> = {\r\n [AddressTypes.P2PKH]: \"m/44'/0'/0'/0\",\r\n [AddressTypes.P2WPKH]: \"m/84'/0'/0'/0\",\r\n [AddressTypes.P2TR]: \"m/86'/0'/0'/0\",\r\n [AddressTypes.P2SH_OR_P2SH_P2WPKH]: \"m/49'/0'/0'/0\"\r\n };\r\n\r\n const standardPath = standardPaths[this.addressType];\r\n\r\n // If no standard path exists for this address type, any non-empty path is \"custom\"\r\n if (standardPath === undefined) {\r\n return this._hdPath !== '';\r\n }\r\n\r\n // Also check without trailing /0 for base paths like m/84'/0'/0'\r\n const standardPathBase = standardPath.slice(0, -2); // Remove /0\r\n\r\n return !this._hdPath.includes(standardPathBase) && this._hdPath !== '';\r\n }\r\n\r\n private findWalletByPublicKey(publicKey: string): Wallet {\r\n for (const wallet of this.wallets.values()) {\r\n if (wallet.toPublicKeyHex() === publicKey) {\r\n return wallet;\r\n }\r\n }\r\n throw new Error(`HdKeyring: Wallet with public key ${publicKey} not found`);\r\n }\r\n\r\n private getAddressFromWallet(wallet: Wallet): string {\r\n switch (this.addressType) {\r\n case AddressTypes.P2PKH: {\r\n return wallet.legacy;\r\n }\r\n case AddressTypes.P2WPKH: {\r\n return wallet.p2wpkh;\r\n }\r\n case AddressTypes.P2TR: {\r\n return wallet.p2tr;\r\n }\r\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\r\n return wallet.segwitLegacy;\r\n }\r\n default: {\r\n return wallet.p2tr;\r\n }\r\n }\r\n }\r\n}\r\n","/**\r\n * OPNet Wallet SDK - Simple Keyring\r\n * Single key pair management with quantum-resistant (ML-DSA) support.\r\n * For WIF/private key imports, requires either:\r\n * 1. A quantum private key to be assigned on import\r\n * 2. Generation of a fresh quantum key pair\r\n */\r\n\r\nimport { crypto as bitcoinCrypto, isTaprootInput, type Network, networks, Psbt } from '@btc-vision/bitcoin';\r\nimport {\r\n AddressTypes,\r\n EcKeyPair,\r\n MLDSASecurityLevel,\r\n QuantumBIP32Factory,\r\n type QuantumBIP32Interface\r\n} from '@btc-vision/transaction';\r\nimport { getMLDSAConfig } from '@btc-vision/bip32';\r\nimport { type UniversalSigner, createBytes32, createMessageHash, createSignature, createSchnorrSignature, toHex, fromHexInternal, concatBytes } from '@btc-vision/ecpair';\r\nimport { publicKeyToAddress } from '@/address';\r\nimport type { AccountAddresses, SimpleKeyringOptions, ToSignInput } from '@/types';\r\n\r\n// Chain code is always 32 bytes\r\nconst CHAINCODE_BYTES = 32;\r\n\r\n/**\r\n * Simple Keyring for single key pair management with quantum support.\r\n * When importing from WIF or private key, a quantum key must be provided or generated.\r\n */\r\nexport class SimpleKeyring {\r\n public static readonly type = 'Simple Key Pair';\r\n public readonly type = SimpleKeyring.type;\r\n\r\n private readonly network: Network;\r\n private readonly securityLevel: MLDSASecurityLevel;\r\n private keypair: UniversalSigner | null = null;\r\n private quantumKeypair: QuantumBIP32Interface | null = null;\r\n private chainCode: Uint8Array = new Uint8Array(32);\r\n\r\n constructor(options: Partial<SimpleKeyringOptions>) {\r\n if (!options?.network) {\r\n throw new Error('SimpleKeyring: Network option is required');\r\n }\r\n\r\n this.network = options.network;\r\n this.securityLevel = options?.securityLevel ?? MLDSASecurityLevel.LEVEL2;\r\n\r\n if (options?.privateKey !== undefined) {\r\n this.importPrivateKey(options.privateKey, options.quantumPrivateKey);\r\n }\r\n }\r\n\r\n /**\r\n * Generate a new random key pair with quantum support\r\n */\r\n public static generate(\r\n network: Network = networks.bitcoin,\r\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\r\n ): SimpleKeyring {\r\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\r\n\r\n // Generate random classical keypair\r\n keyring.keypair = EcKeyPair.generateRandomKeyPair(network);\r\n\r\n // Generate random quantum keypair\r\n const seed: Uint8Array = crypto.getRandomValues(new Uint8Array(64));\r\n keyring.quantumKeypair = QuantumBIP32Factory.fromSeed(seed, network, securityLevel);\r\n keyring.chainCode = Uint8Array.from(keyring.quantumKeypair.chainCode);\r\n\r\n return keyring;\r\n }\r\n\r\n /**\r\n * Import from WIF (Wallet Import Format) with optional quantum key.\r\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\r\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\r\n */\r\n public static fromWIF(\r\n wif: string,\r\n quantumPrivateKey: string | undefined,\r\n network: Network = networks.bitcoin,\r\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\r\n ): SimpleKeyring {\r\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\r\n keyring.keypair = EcKeyPair.fromWIF(wif, network);\r\n\r\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\r\n keyring.importQuantumKey(quantumPrivateKey);\r\n }\r\n // Do NOT auto-generate quantum key - user must explicitly migrate\r\n\r\n return keyring;\r\n }\r\n\r\n /**\r\n * Import from hex private key with optional quantum key.\r\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\r\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\r\n */\r\n public static fromPrivateKey(\r\n privateKeyHex: string,\r\n quantumPrivateKey: string | undefined,\r\n network: Network = networks.bitcoin,\r\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\r\n ): SimpleKeyring {\r\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\r\n keyring.keypair = EcKeyPair.fromPrivateKey(fromHexInternal(privateKeyHex), network);\r\n\r\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\r\n keyring.importQuantumKey(quantumPrivateKey);\r\n }\r\n // Do NOT auto-generate quantum key - user must explicitly migrate\r\n\r\n return keyring;\r\n }\r\n\r\n /**\r\n * Import a private key (WIF or hex format).\r\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\r\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\r\n */\r\n public importPrivateKey(privateKey: string, quantumPrivateKey?: string): void {\r\n if (privateKey === '') {\r\n return;\r\n }\r\n\r\n // Determine if WIF or hex\r\n if (privateKey.length === 64) {\r\n // Hex format\r\n this.keypair = EcKeyPair.fromPrivateKey(fromHexInternal(privateKey), this.network);\r\n } else {\r\n // WIF format\r\n this.keypair = EcKeyPair.fromWIF(privateKey, this.network);\r\n }\r\n\r\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\r\n this.importQuantumKey(quantumPrivateKey);\r\n }\r\n // Do NOT auto-generate quantum key - user must explicitly migrate\r\n }\r\n\r\n /**\r\n * Import an existing quantum private key.\r\n * Supports both:\r\n * - Key only (e.g., 2560 bytes for ML-DSA-44)\r\n * - Key + chaincode (e.g., 2560 + 32 = 2592 bytes for ML-DSA-44)\r\n */\r\n public importQuantumKey(quantumPrivateKeyHex: string): void {\r\n const privateKeyBytes: Uint8Array = fromHexInternal(quantumPrivateKeyHex);\r\n\r\n // Get expected MLDSA private key size for the security level\r\n const mldsaConfig = getMLDSAConfig(this.securityLevel, this.network);\r\n const expectedKeySize: number = mldsaConfig.privateKeySize;\r\n const expectedKeyWithChaincodeSize: number = expectedKeySize + CHAINCODE_BYTES;\r\n\r\n // Determine if chaincode is present based on the key length\r\n const hasChaincode: boolean = privateKeyBytes.length === expectedKeyWithChaincodeSize;\r\n const isKeyOnly: boolean = privateKeyBytes.length === expectedKeySize;\r\n\r\n if (!hasChaincode && !isKeyOnly) {\r\n throw new Error(\r\n `Invalid quantum key length: ${privateKeyBytes.length} bytes. ` +\r\n `Expected ${expectedKeySize} bytes (key only) or ${expectedKeyWithChaincodeSize} bytes (key + chaincode).`\r\n );\r\n }\r\n\r\n if (hasChaincode) {\r\n // Extract chaincode from the end of the key\r\n this.chainCode = privateKeyBytes.slice(-CHAINCODE_BYTES);\r\n const keyWithoutChainCode: Uint8Array = privateKeyBytes.slice(0, -CHAINCODE_BYTES);\r\n this.quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\r\n keyWithoutChainCode,\r\n this.chainCode,\r\n this.network,\r\n this.securityLevel\r\n );\r\n } else {\r\n // Key only - generate a random chaincode\r\n this.chainCode = crypto.getRandomValues(new Uint8Array(CHAINCODE_BYTES));\r\n this.quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\r\n privateKeyBytes,\r\n this.chainCode,\r\n this.network,\r\n this.securityLevel\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Generate a fresh quantum key pair\r\n */\r\n public generateFreshQuantumKey(): void {\r\n const seed: Uint8Array = crypto.getRandomValues(new Uint8Array(64));\r\n this.quantumKeypair = QuantumBIP32Factory.fromSeed(seed, this.network, this.securityLevel);\r\n this.chainCode = Uint8Array.from(this.quantumKeypair.chainCode);\r\n }\r\n\r\n /**\r\n * Check if keyring has both classical and quantum keys\r\n */\r\n public hasKeys(): boolean {\r\n return this.keypair !== null && this.quantumKeypair !== null;\r\n }\r\n\r\n /**\r\n * Check if keyring has the classical keypair (may or may not have quantum key)\r\n */\r\n public hasClassicalKey(): boolean {\r\n return this.keypair !== null;\r\n }\r\n\r\n /**\r\n * Check if keyring has a quantum keypair\r\n */\r\n public hasQuantumKey(): boolean {\r\n return this.quantumKeypair !== null;\r\n }\r\n\r\n /**\r\n * Check if quantum migration is needed (has classical but no quantum key)\r\n */\r\n public needsQuantumMigration(): boolean {\r\n return this.keypair !== null && this.quantumKeypair === null;\r\n }\r\n\r\n /**\r\n * Get the classical public key\r\n */\r\n public getPublicKey(): string {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n return toHex(this.keypair.publicKey);\r\n }\r\n\r\n /**\r\n * Get the quantum public key\r\n * @throws Error if no quantum keypair is initialized\r\n */\r\n public getQuantumPublicKey(): string {\r\n if (this.quantumKeypair === null) {\r\n throw new Error('SimpleKeyring: No quantum keypair initialized');\r\n }\r\n return toHex(this.quantumKeypair.publicKey);\r\n }\r\n\r\n /**\r\n * Get the quantum public key if available, or undefined if not initialized\r\n */\r\n public getQuantumPublicKeyOrUndefined(): string | undefined {\r\n if (this.quantumKeypair === null) {\r\n return undefined;\r\n }\r\n return toHex(this.quantumKeypair.publicKey);\r\n }\r\n\r\n /**\r\n * Get the quantum public key hash (universal identifier)\r\n */\r\n public getQuantumPublicKeyHash(): string {\r\n if (this.quantumKeypair === null) {\r\n throw new Error('SimpleKeyring: No quantum keypair initialized');\r\n }\r\n // SHA256 hash of the quantum public key\r\n const hash: Uint8Array = bitcoinCrypto.sha256(this.quantumKeypair.publicKey);\r\n return toHex(hash);\r\n }\r\n\r\n /**\r\n * Clear the quantum keypair (used for reverting failed imports)\r\n */\r\n public clearQuantumKey(): void {\r\n this.quantumKeypair = null;\r\n this.chainCode = new Uint8Array(32);\r\n }\r\n\r\n /**\r\n * Get all accounts (returns array with single public key)\r\n */\r\n public getAccounts(): string[] {\r\n if (this.keypair === null) {\r\n return [];\r\n }\r\n return [this.getPublicKey()];\r\n }\r\n\r\n /**\r\n * Get addresses for the key pair\r\n */\r\n public getAddresses(): AccountAddresses {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n\r\n const pubkey = this.keypair.publicKey;\r\n\r\n return {\r\n p2pkh: publicKeyToAddress(pubkey, AddressTypes.P2PKH, this.network),\r\n p2wpkh: publicKeyToAddress(pubkey, AddressTypes.P2WPKH, this.network),\r\n p2tr: publicKeyToAddress(pubkey, AddressTypes.P2TR, this.network),\r\n p2shP2wpkh: publicKeyToAddress(pubkey, AddressTypes.P2SH_OR_P2SH_P2WPKH, this.network)\r\n };\r\n }\r\n\r\n /**\r\n * Get an address for a specific type\r\n */\r\n public getAddress(addressType: AddressTypes): string {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n return publicKeyToAddress(this.keypair.publicKey, addressType, this.network);\r\n }\r\n\r\n /**\r\n * Export the classical private key\r\n */\r\n public exportPrivateKey(): string {\r\n if (this.keypair?.privateKey === undefined) {\r\n throw new Error('SimpleKeyring: No private key available');\r\n }\r\n return toHex(this.keypair.privateKey);\r\n }\r\n\r\n /**\r\n * Export the quantum private key with chain code (for backup/restore)\r\n */\r\n public exportQuantumPrivateKey(): string {\r\n if (this.quantumKeypair?.privateKey === undefined) {\r\n throw new Error('SimpleKeyring: No quantum private key available');\r\n }\r\n // Combine private key and chain code for full export\r\n return toHex(concatBytes(this.quantumKeypair.privateKey, this.chainCode));\r\n }\r\n\r\n /**\r\n * Export the raw quantum private key WITHOUT chain code (for Wallet.fromWif)\r\n */\r\n public exportRawQuantumPrivateKey(): string {\r\n if (this.quantumKeypair?.privateKey === undefined) {\r\n throw new Error('SimpleKeyring: No quantum private key available');\r\n }\r\n return toHex(this.quantumKeypair.privateKey);\r\n }\r\n\r\n /**\r\n * Export the chain code (for use with Wallet.fromWif separately)\r\n */\r\n public exportChainCode(): Uint8Array {\r\n return this.chainCode;\r\n }\r\n\r\n /**\r\n * Export WIF format\r\n */\r\n public exportWIF(): string {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n return this.keypair.toWIF();\r\n }\r\n\r\n /**\r\n * Sign a PSBT transaction\r\n */\r\n public signTransaction(psbt: Psbt, inputs: readonly ToSignInput[]): Psbt {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n\r\n for (const input of inputs) {\r\n const psbtInput = psbt.data.inputs[input.index];\r\n\r\n if (psbtInput === undefined) {\r\n throw new Error(`SimpleKeyring: Input at index ${input.index} not found`);\r\n }\r\n\r\n if (isTaprootInput(psbtInput) && input.disableTweakSigner !== true) {\r\n const tweakedSigner: UniversalSigner = this.keypair.tweak(createBytes32(this.keypair.publicKey.subarray(1, 33)));\r\n psbt.signInput(input.index, tweakedSigner, input.sighashTypes ? [...input.sighashTypes] : undefined);\r\n } else {\r\n psbt.signInput(input.index, this.keypair, input.sighashTypes ? [...input.sighashTypes] : undefined);\r\n }\r\n }\r\n\r\n return psbt;\r\n }\r\n\r\n /**\r\n * Sign arbitrary data with ECDSA or Schnorr\r\n */\r\n public signData(data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n\r\n const dataHash = createMessageHash(fromHexInternal(data));\r\n\r\n if (type === 'ecdsa') {\r\n return toHex(this.keypair.sign(dataHash));\r\n }\r\n\r\n if (this.keypair.signSchnorr === undefined) {\r\n throw new Error('SimpleKeyring: Schnorr signing not supported by this keypair');\r\n }\r\n\r\n return toHex(this.keypair.signSchnorr(dataHash));\r\n }\r\n\r\n /**\r\n * Verify a signature\r\n */\r\n public verify(data: string, signature: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): boolean {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n\r\n const dataHash = createMessageHash(fromHexInternal(data));\r\n\r\n if (type === 'ecdsa') {\r\n return this.keypair.verify(dataHash, createSignature(fromHexInternal(signature)));\r\n }\r\n\r\n return this.keypair.verifySchnorr(dataHash, createSchnorrSignature(fromHexInternal(signature)));\r\n }\r\n\r\n /**\r\n * Get the keypair\r\n */\r\n public getKeypair(): UniversalSigner {\r\n if (this.keypair === null) {\r\n throw new Error('SimpleKeyring: No keypair initialized');\r\n }\r\n return this.keypair;\r\n }\r\n\r\n /**\r\n * Get the quantum keypair\r\n */\r\n public getQuantumKeypair(): QuantumBIP32Interface {\r\n if (this.quantumKeypair === null) {\r\n throw new Error('SimpleKeyring: No quantum keypair initialized');\r\n }\r\n return this.quantumKeypair;\r\n }\r\n\r\n /**\r\n * Get the chain code\r\n */\r\n public getChainCode(): Uint8Array {\r\n return this.chainCode;\r\n }\r\n\r\n /**\r\n * Get the security level\r\n */\r\n public getSecurityLevel(): MLDSASecurityLevel {\r\n return this.securityLevel;\r\n }\r\n\r\n /**\r\n * Get the network\r\n */\r\n public getNetwork(): Network {\r\n return this.network;\r\n }\r\n\r\n /**\r\n * Serialize the keyring state (excludes private keys for safety)\r\n */\r\n public serialize(): SimpleKeyringOptions {\r\n let quantumPrivateKey: string | undefined;\r\n try {\r\n quantumPrivateKey = this.exportQuantumPrivateKey();\r\n } catch {\r\n // No quantum key available - that's fine for wallets that haven't migrated\r\n quantumPrivateKey = undefined;\r\n }\r\n\r\n return {\r\n privateKey: this.exportPrivateKey(),\r\n quantumPrivateKey,\r\n network: this.network,\r\n securityLevel: this.securityLevel\r\n };\r\n }\r\n\r\n /**\r\n * Remove the key (clear keyring)\r\n */\r\n public clear(): void {\r\n this.keypair = null;\r\n this.quantumKeypair = null;\r\n this.chainCode = new Uint8Array(32);\r\n }\r\n}\r\n","/**\r\n * OPNet Wallet SDK - Unified Key Export\r\n * Provides a single export format that contains both classical and quantum keys.\r\n * This allows users to export their complete wallet state in one operation.\r\n */\r\n\r\nimport { crypto as bitcoinCrypto, type Network, networks } from '@btc-vision/bitcoin';\r\nimport { EcKeyPair, MLDSASecurityLevel, QuantumBIP32Factory } from '@btc-vision/transaction';\r\nimport { type UniversalSigner, fromHexInternal, toHex } from '@btc-vision/ecpair';\r\nimport type { ExportedWallet } from '@/types';\r\n\r\nconst EXPORT_VERSION = 1;\r\nconst MAGIC_HEADER = 'OPNET_WALLET_V1';\r\n\r\n/**\r\n * Unified wallet export format\r\n */\r\nexport interface UnifiedWalletExport {\r\n readonly magic: string;\r\n readonly version: number;\r\n readonly network: string;\r\n readonly classical: {\r\n readonly privateKey: string;\r\n readonly publicKey: string;\r\n };\r\n readonly quantum: {\r\n readonly privateKey: string;\r\n readonly publicKey: string;\r\n readonly securityLevel: MLDSASecurityLevel;\r\n readonly chainCode: string;\r\n };\r\n readonly checksum: string;\r\n}\r\n\r\n/**\r\n * Calculate checksum for wallet export data\r\n */\r\nconst textEncoder = new TextEncoder();\r\n\r\nfunction calculateChecksum(data: string): string {\r\n const hash: Uint8Array = bitcoinCrypto.sha256(textEncoder.encode(data));\r\n return toHex(hash.subarray(0, 4));\r\n}\r\n\r\n/**\r\n * Get network name from Network object\r\n */\r\nfunction getNetworkName(network: Network): string {\r\n if (network.bech32 === networks.bitcoin.bech32) {\r\n return 'mainnet';\r\n }\r\n if (network.bech32 === networks.testnet.bech32) {\r\n return 'testnet';\r\n }\r\n return 'regtest';\r\n}\r\n\r\n/**\r\n * Get Network object from network name\r\n */\r\nfunction getNetworkFromName(name: string): Network {\r\n switch (name) {\r\n case 'mainnet': {\r\n return networks.bitcoin;\r\n }\r\n case 'testnet': {\r\n return networks.testnet;\r\n }\r\n case 'regtest': {\r\n return networks.regtest;\r\n }\r\n default: {\r\n return networks.bitcoin;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Export wallet keys to unified format\r\n */\r\nexport function exportWallet(\r\n classicalPrivateKey: Uint8Array,\r\n classicalPublicKey: Uint8Array,\r\n quantumPrivateKey: Uint8Array,\r\n quantumPublicKey: Uint8Array,\r\n chainCode: Uint8Array,\r\n securityLevel: MLDSASecurityLevel,\r\n network: Network\r\n): UnifiedWalletExport {\r\n const exportData: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: MAGIC_HEADER,\r\n version: EXPORT_VERSION,\r\n network: getNetworkName(network),\r\n classical: {\r\n privateKey: toHex(classicalPrivateKey),\r\n publicKey: toHex(classicalPublicKey)\r\n },\r\n quantum: {\r\n privateKey: toHex(quantumPrivateKey),\r\n publicKey: toHex(quantumPublicKey),\r\n securityLevel,\r\n chainCode: toHex(chainCode)\r\n }\r\n };\r\n\r\n const dataString = JSON.stringify(exportData);\r\n const checksum = calculateChecksum(dataString);\r\n\r\n return {\r\n ...exportData,\r\n checksum\r\n };\r\n}\r\n\r\n/**\r\n * Import wallet keys from unified format\r\n */\r\nexport function importWallet(exportData: UnifiedWalletExport): {\r\n keypair: UniversalSigner;\r\n quantumKeypair: ReturnType<typeof QuantumBIP32Factory.fromPrivateKey>;\r\n network: Network;\r\n securityLevel: MLDSASecurityLevel;\r\n chainCode: Uint8Array;\r\n} {\r\n // Validate magic header\r\n if (exportData.magic !== MAGIC_HEADER) {\r\n throw new Error('Invalid wallet export format: wrong magic header');\r\n }\r\n\r\n // Validate version\r\n if (exportData.version !== EXPORT_VERSION) {\r\n throw new Error(`Unsupported wallet export version: ${exportData.version}`);\r\n }\r\n\r\n // Validate checksum\r\n const dataWithoutChecksum: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: exportData.magic,\r\n version: exportData.version,\r\n network: exportData.network,\r\n classical: exportData.classical,\r\n quantum: exportData.quantum\r\n };\r\n const expectedChecksum = calculateChecksum(JSON.stringify(dataWithoutChecksum));\r\n if (exportData.checksum !== expectedChecksum) {\r\n throw new Error('Invalid wallet export: checksum mismatch');\r\n }\r\n\r\n const network: Network = getNetworkFromName(exportData.network);\r\n const chainCode: Uint8Array = fromHexInternal(exportData.quantum.chainCode);\r\n\r\n // Restore classical keypair\r\n const classicalPrivateKey: Uint8Array = fromHexInternal(exportData.classical.privateKey);\r\n const keypair: UniversalSigner = EcKeyPair.fromPrivateKey(classicalPrivateKey, network);\r\n\r\n // Restore quantum keypair\r\n const quantumPrivateKey: Uint8Array = fromHexInternal(exportData.quantum.privateKey);\r\n const quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\r\n quantumPrivateKey,\r\n chainCode,\r\n network,\r\n exportData.quantum.securityLevel\r\n );\r\n\r\n return {\r\n keypair,\r\n quantumKeypair,\r\n network,\r\n securityLevel: exportData.quantum.securityLevel,\r\n chainCode\r\n };\r\n}\r\n\r\n/**\r\n * Serialize unified export to string (base64 encoded JSON)\r\n */\r\nexport function serializeExport(exportData: UnifiedWalletExport): string {\r\n const json: string = JSON.stringify(exportData);\r\n return btoa(json);\r\n}\r\n\r\n/**\r\n * Deserialize string to unified export\r\n */\r\nexport function deserializeExport(serialized: string): UnifiedWalletExport {\r\n try {\r\n const json: string = atob(serialized);\r\n return JSON.parse(json) as UnifiedWalletExport;\r\n } catch {\r\n throw new Error('Invalid wallet export: failed to deserialize');\r\n }\r\n}\r\n\r\n/**\r\n * Export wallet to portable string format\r\n */\r\nexport function exportWalletToString(\r\n classicalPrivateKey: Uint8Array,\r\n classicalPublicKey: Uint8Array,\r\n quantumPrivateKey: Uint8Array,\r\n quantumPublicKey: Uint8Array,\r\n chainCode: Uint8Array,\r\n securityLevel: MLDSASecurityLevel,\r\n network: Network\r\n): string {\r\n const exportData = exportWallet(\r\n classicalPrivateKey,\r\n classicalPublicKey,\r\n quantumPrivateKey,\r\n quantumPublicKey,\r\n chainCode,\r\n securityLevel,\r\n network\r\n );\r\n return serializeExport(exportData);\r\n}\r\n\r\n/**\r\n * Import wallet from portable string format\r\n */\r\nexport function importWalletFromString(serialized: string): {\r\n keypair: UniversalSigner;\r\n quantumKeypair: ReturnType<typeof QuantumBIP32Factory.fromPrivateKey>;\r\n network: Network;\r\n securityLevel: MLDSASecurityLevel;\r\n chainCode: Uint8Array;\r\n} {\r\n const exportData = deserializeExport(serialized);\r\n return importWallet(exportData);\r\n}\r\n\r\n/**\r\n * Validate export data without importing\r\n */\r\nexport function validateExport(exportData: UnifiedWalletExport): boolean {\r\n try {\r\n if (exportData.magic !== MAGIC_HEADER) {\r\n return false;\r\n }\r\n\r\n if (exportData.version !== EXPORT_VERSION) {\r\n return false;\r\n }\r\n\r\n const dataWithoutChecksum: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: exportData.magic,\r\n version: exportData.version,\r\n network: exportData.network,\r\n classical: exportData.classical,\r\n quantum: exportData.quantum\r\n };\r\n const expectedChecksum = calculateChecksum(JSON.stringify(dataWithoutChecksum));\r\n\r\n return exportData.checksum === expectedChecksum;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Convert legacy ExportedWallet format to unified format\r\n */\r\nexport function fromLegacyExport(legacy: ExportedWallet, network: Network): UnifiedWalletExport {\r\n const classicalPrivateKey: Uint8Array = fromHexInternal(legacy.classicalPrivateKey);\r\n const keypair: UniversalSigner = EcKeyPair.fromPrivateKey(classicalPrivateKey, network);\r\n\r\n const exportData: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: MAGIC_HEADER,\r\n version: EXPORT_VERSION,\r\n network: getNetworkName(network),\r\n classical: {\r\n privateKey: legacy.classicalPrivateKey,\r\n publicKey: toHex(keypair.publicKey)\r\n },\r\n quantum: {\r\n privateKey: legacy.quantumPrivateKey,\r\n publicKey: legacy.quantumPublicKey,\r\n securityLevel: legacy.securityLevel,\r\n chainCode: legacy.chainCode\r\n }\r\n };\r\n\r\n const dataString = JSON.stringify(exportData);\r\n const checksum = calculateChecksum(dataString);\r\n\r\n return {\r\n ...exportData,\r\n checksum\r\n };\r\n}\r\n","import { createNobleBackend, type NobleBackend } from '@btc-vision/ecpair';\r\n\r\nlet backend: NobleBackend | undefined;\r\n\r\nexport function getNobleBackend(): NobleBackend {\r\n backend ??= createNobleBackend();\r\n return backend;\r\n}\r\n","/**\r\n * OPNet Wallet SDK - Message Signing Module\r\n * Message signing and verification using classical (Schnorr/ECDSA) and quantum (ML-DSA) signatures.\r\n * Uses @btc-vision/transaction MessageSigner for all operations.\r\n */\r\n\r\nimport { type Network, networks } from '@btc-vision/bitcoin';\r\nimport {\r\n MessageSigner,\r\n MLDSASecurityLevel,\r\n QuantumBIP32Factory,\r\n type QuantumBIP32Interface\r\n} from '@btc-vision/transaction';\r\nimport { type UniversalSigner, createMessageHash, createPublicKey, createSignature } from '@btc-vision/ecpair';\r\nimport { getNobleBackend } from './backend.js';\r\nimport type { SignatureType, SignedMessage } from '@/types';\r\n\r\n/**\r\n * Message input type - can be string or Uint8Array\r\n */\r\nexport type MessageInput = string | Uint8Array;\r\n\r\n/**\r\n * Result of ML-DSA signature operation\r\n */\r\nexport interface MLDSASignatureResult {\r\n readonly message: MessageInput;\r\n readonly signature: Uint8Array;\r\n readonly publicKey: Uint8Array;\r\n readonly securityLevel: MLDSASecurityLevel;\r\n}\r\n\r\n/**\r\n * Result of Schnorr signature operation\r\n */\r\nexport interface SchnorrSignatureResult {\r\n readonly message: MessageInput;\r\n readonly signature: Uint8Array;\r\n readonly publicKey: Uint8Array;\r\n}\r\n\r\n/**\r\n * Sign a message with ML-DSA (quantum-resistant)\r\n */\r\nexport function signMLDSA(keypair: QuantumBIP32Interface, message: MessageInput): MLDSASignatureResult {\r\n const result = MessageSigner.signMLDSAMessage(keypair, message);\r\n return {\r\n message: result.message,\r\n signature: result.signature,\r\n publicKey: result.publicKey,\r\n securityLevel: result.securityLevel\r\n };\r\n}\r\n\r\n/**\r\n * Verify an ML-DSA signature\r\n */\r\nexport function verifyMLDSA(\r\n publicKey: Uint8Array,\r\n chainCode: Uint8Array,\r\n network: Network,\r\n securityLevel: MLDSASecurityLevel,\r\n message: MessageInput,\r\n signature: Uint8Array\r\n): boolean {\r\n const keypair = QuantumBIP32Factory.fromPublicKey(publicKey, chainCode, network, securityLevel);\r\n return MessageSigner.verifyMLDSASignature(keypair, message, signature);\r\n}\r\n\r\n/**\r\n * Verify an ML-DSA signature using an existing keypair\r\n */\r\nexport function verifyMLDSAWithKeypair(\r\n keypair: QuantumBIP32Interface,\r\n message: MessageInput,\r\n signature: Uint8Array\r\n): boolean {\r\n return MessageSigner.verifyMLDSASignature(keypair, message, signature);\r\n}\r\n\r\n/**\r\n * Sign a message with Schnorr (classical)\r\n */\r\nexport function signSchnorr(keypair: UniversalSigner, message: MessageInput): SchnorrSignatureResult {\r\n const result = MessageSigner.signMessage(keypair, message);\r\n return {\r\n message: result.message,\r\n signature: result.signature,\r\n publicKey: keypair.publicKey\r\n };\r\n}\r\n\r\n/**\r\n * Verify a Schnorr signature\r\n */\r\nexport function verifySchnorr(publicKey: Uint8Array, message: MessageInput, signature: Uint8Array): boolean {\r\n return MessageSigner.verifySignature(publicKey, message, signature);\r\n}\r\n\r\n/**\r\n * Sign a message with tweaked key for Taproot\r\n */\r\nexport function signTweakedSchnorr(\r\n keypair: UniversalSigner,\r\n message: MessageInput,\r\n network: Network = networks.bitcoin\r\n): SchnorrSignatureResult {\r\n const result = MessageSigner.tweakAndSignMessage(keypair, message, network);\r\n return {\r\n message: result.message,\r\n signature: result.signature,\r\n publicKey: keypair.publicKey\r\n };\r\n}\r\n\r\n/**\r\n * Verify a tweaked Schnorr signature\r\n */\r\nexport function verifyTweakedSchnorr(\r\n publicKey: Uint8Array,\r\n message: MessageInput,\r\n signature: Uint8Array\r\n): boolean {\r\n return MessageSigner.tweakAndVerifySignature(publicKey, message, signature);\r\n}\r\n\r\n/**\r\n * Sign message with automatic type selection\r\n */\r\nexport function signMessage(\r\n keypair: UniversalSigner | QuantumBIP32Interface,\r\n message: MessageInput,\r\n signatureType: SignatureType\r\n): SignedMessage {\r\n const messageBytes: Uint8Array = toUint8Array(message);\r\n switch (signatureType) {\r\n case 'mldsa': {\r\n if (!isQuantumKeypair(keypair)) {\r\n throw new Error('ML-DSA signing requires a quantum keypair');\r\n }\r\n const result = signMLDSA(keypair, message);\r\n return {\r\n message: messageBytes,\r\n signature: result.signature,\r\n publicKey: result.publicKey,\r\n signatureType: 'mldsa',\r\n securityLevel: result.securityLevel\r\n };\r\n }\r\n case 'schnorr': {\r\n if (isQuantumKeypair(keypair)) {\r\n throw new Error('Schnorr signing requires a classical keypair');\r\n }\r\n const result = signSchnorr(keypair, message);\r\n return {\r\n message: messageBytes,\r\n signature: result.signature,\r\n publicKey: result.publicKey,\r\n signatureType: 'schnorr'\r\n };\r\n }\r\n case 'ecdsa': {\r\n if (isQuantumKeypair(keypair)) {\r\n throw new Error('ECDSA signing requires a classical keypair');\r\n }\r\n const hash = MessageSigner.sha256(messageBytes);\r\n const signature = keypair.sign(createMessageHash(hash));\r\n return {\r\n message: messageBytes,\r\n signature,\r\n publicKey: keypair.publicKey,\r\n signatureType: 'ecdsa'\r\n };\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Verify message with automatic type detection\r\n */\r\nexport function verifyMessage(\r\n publicKey: Uint8Array,\r\n message: MessageInput,\r\n signature: Uint8Array,\r\n signatureType: SignatureType,\r\n chainCode?: Uint8Array,\r\n network?: Network,\r\n securityLevel?: MLDSASecurityLevel\r\n): boolean {\r\n switch (signatureType) {\r\n case 'mldsa': {\r\n if (chainCode === undefined || network === undefined || securityLevel === undefined) {\r\n throw new Error('ML-DSA verification requires chainCode, network, and securityLevel');\r\n }\r\n return verifyMLDSA(publicKey, chainCode, network, securityLevel, message, signature);\r\n }\r\n case 'schnorr': {\r\n return verifySchnorr(publicKey, message, signature);\r\n }\r\n case 'ecdsa': {\r\n const ecdsaBytes: Uint8Array = toUint8Array(message);\r\n const hash: Uint8Array = MessageSigner.sha256(ecdsaBytes);\r\n return getNobleBackend().verify(createMessageHash(hash), createPublicKey(publicKey), createSignature(signature));\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Type guard to check if keypair is quantum\r\n */\r\nfunction isQuantumKeypair(keypair: UniversalSigner | QuantumBIP32Interface): keypair is QuantumBIP32Interface {\r\n return 'securityLevel' in keypair && 'chainCode' in keypair;\r\n}\r\n\r\nconst textEncoder = new TextEncoder();\r\n\r\nfunction toUint8Array(message: MessageInput): Uint8Array {\r\n if (typeof message === 'string') {\r\n return textEncoder.encode(message);\r\n }\r\n return message;\r\n}\r\n\r\n// Re-export MessageSigner for direct usage\r\nexport { MessageSigner };\r\n","/**\r\n * OPNet Wallet SDK - BIP322 Message Signing\r\n * BIP322 simple message signing and verification.\r\n * Reference: https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\r\n */\r\n\r\nimport {\r\n address as bitcoinAddress,\r\n alloc,\r\n concat,\r\n crypto as bitcoinCrypto,\r\n fromHex,\r\n type Bytes32,\r\n type Network,\r\n type PublicKey,\r\n type Satoshi,\r\n type Script,\r\n Psbt,\r\n PsbtTransaction,\r\n script as bitcoinScript,\r\n toSatoshi,\r\n Transaction,\r\n type ValidateSigFunction,\r\n} from '@btc-vision/bitcoin';\r\nimport { type MessageHash, createMessageHash, createPublicKey, createSchnorrSignature, createSignature, createXOnlyPublicKey } from '@btc-vision/ecpair';\r\nimport { AddressTypes, WalletNetworks } from '@btc-vision/transaction';\r\nimport { detectAddressType } from '@/address';\r\nimport { toNetwork } from '@/network';\r\nimport type { Bip322Signature } from '@/types';\r\nimport { getNobleBackend } from './backend.js';\r\n\r\nconst textEncoder = new TextEncoder();\r\nconst ZERO_SATOSHI: Satoshi = toSatoshi(0n);\r\n\r\nfunction toBase64(bytes: Uint8Array): string {\r\n let binary = '';\r\n for (const byte of bytes) {\r\n binary += String.fromCharCode(byte);\r\n }\r\n return btoa(binary);\r\n}\r\n\r\nfunction fromBase64Bytes(base64: string): Uint8Array {\r\n const binary: string = atob(base64);\r\n const bytes = new Uint8Array(binary.length);\r\n for (let i = 0; i < binary.length; i++) {\r\n bytes[i] = binary.charCodeAt(i);\r\n }\r\n return bytes;\r\n}\r\n\r\n/**\r\n * Supported address types for BIP322 signing\r\n */\r\nconst SUPPORTED_ADDRESS_TYPES = [AddressTypes.P2WPKH, AddressTypes.P2TR];\r\n\r\n/**\r\n * Compute the BIP322 message hash\r\n */\r\nfunction computeBip322Hash(message: string | Uint8Array): Uint8Array {\r\n const tag = 'BIP0322-signed-message';\r\n const tagHash = bitcoinCrypto.sha256(textEncoder.encode(tag));\r\n const messageBytes: Uint8Array = typeof message === 'string' ? textEncoder.encode(message) : message;\r\n return bitcoinCrypto.sha256(concat([tagHash, tagHash, messageBytes]));\r\n}\r\n\r\n/**\r\n * Encode a buffer as a variable-length string for witness serialization\r\n */\r\nfunction encodeVarString(buf: Uint8Array): Uint8Array {\r\n const varint = bitcoinScript.number.encode(buf.length);\r\n return concat([varint, buf]);\r\n}\r\n\r\n/**\r\n * Generate a PSBT for BIP322 simple message signing\r\n */\r\nexport function generateBip322Psbt(message: string | Uint8Array, address: string, network: Network): Psbt {\r\n const outputScript = bitcoinAddress.toOutputScript(address, network);\r\n const addressType = detectAddressType(address, network);\r\n\r\n if (addressType === null || !SUPPORTED_ADDRESS_TYPES.includes(addressType)) {\r\n throw new Error(`BIP322: Address type not supported for signing. Got: ${String(addressType)}`);\r\n }\r\n\r\n const messageHash = computeBip322Hash(message);\r\n const prevoutHash = alloc(32) as Bytes32;\r\n const prevoutIndex = 0xffffffff;\r\n const sequence = 0;\r\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\r\n\r\n // Create \"to spend\" transaction\r\n const txToSpend = new Transaction();\r\n txToSpend.version = 0;\r\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\r\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\r\n\r\n // Create PSBT to sign\r\n const psbt = new Psbt({ network });\r\n psbt.setVersion(0);\r\n psbt.addInput({\r\n hash: txToSpend.getHash(),\r\n index: 0,\r\n sequence: 0,\r\n witnessUtxo: {\r\n script: outputScript as Script,\r\n value: ZERO_SATOSHI\r\n }\r\n });\r\n psbt.addOutput({\r\n script: fromHex('6a') as Script, // OP_RETURN\r\n value: ZERO_SATOSHI\r\n });\r\n\r\n return psbt;\r\n}\r\n\r\n/**\r\n * Extract signature from a signed BIP322 PSBT\r\n */\r\nexport function extractBip322Signature(psbt: Psbt): string {\r\n const tx = psbt.extractTransaction();\r\n const witness = tx.ins[0]?.witness;\r\n\r\n if (witness === undefined || witness.length === 0) {\r\n throw new Error('BIP322: No witness data found in signed transaction');\r\n }\r\n\r\n // Encode witness stack\r\n const varintLength = bitcoinScript.number.encode(witness.length);\r\n const encodedWitness = concat([varintLength, ...witness.map((w) => encodeVarString(w))]);\r\n\r\n return toBase64(encodedWitness);\r\n}\r\n\r\n/**\r\n * Sign a message using BIP322 simple format\r\n */\r\nexport async function signBip322Message(\r\n message: string | Uint8Array,\r\n address: string,\r\n network: Network,\r\n signPsbt: (psbt: Psbt) => Promise<Psbt>\r\n): Promise<string> {\r\n const psbt = generateBip322Psbt(message, address, network);\r\n const signedPsbt = await signPsbt(psbt);\r\n signedPsbt.finalizeAllInputs();\r\n return extractBip322Signature(signedPsbt);\r\n}\r\n\r\n/**\r\n * ECDSA signature validator\r\n */\r\nconst ecdsaValidator: ValidateSigFunction = (pubkey: PublicKey, msghash: MessageHash, signature: Uint8Array): boolean => {\r\n try {\r\n const decoded = bitcoinScript.signature.decode(signature);\r\n return getNobleBackend().verify(createMessageHash(msghash), createPublicKey(pubkey), createSignature(decoded.signature));\r\n } catch {\r\n return false;\r\n }\r\n};\r\n\r\n/**\r\n * Schnorr signature validator\r\n */\r\nfunction schnorrValidator(pubkey: Uint8Array, msghash: Uint8Array, signature: Uint8Array): boolean {\r\n try {\r\n const xOnlyPubkey = pubkey.length === 33 ? pubkey.subarray(1, 33) : pubkey;\r\n return getNobleBackend().verifySchnorr(createMessageHash(msghash), createXOnlyPublicKey(xOnlyPubkey), createSchnorrSignature(signature));\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Verify a BIP322 simple message signature for P2TR addresses\r\n */\r\nfunction verifyBip322P2TR(address: string, message: string | Uint8Array, signature: string, network: Network): boolean {\r\n try {\r\n const outputScript = bitcoinAddress.toOutputScript(address, network);\r\n const messageHash = computeBip322Hash(message);\r\n\r\n const prevoutHash = alloc(32) as Bytes32;\r\n const prevoutIndex = 0xffffffff;\r\n const sequence = 0;\r\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\r\n\r\n // Reconstruct \"to spend\" transaction\r\n const txToSpend = new Transaction();\r\n txToSpend.version = 0;\r\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\r\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\r\n\r\n // Decode signature\r\n const signatureData = fromBase64Bytes(signature);\r\n const decompiled = bitcoinScript.decompile(signatureData.subarray(1));\r\n\r\n if (!Array.isArray(decompiled) || decompiled.length === 0) {\r\n return false;\r\n }\r\n\r\n const sig = decompiled[0];\r\n if (!(sig instanceof Uint8Array)) {\r\n return false;\r\n }\r\n\r\n // Extract pubkey from output script (x-only format)\r\n const pubkey = concat([fromHex('02'), outputScript.subarray(2)]);\r\n\r\n // Create PSBT for verification\r\n const psbt = new Psbt({ network });\r\n psbt.setVersion(0);\r\n psbt.addInput({\r\n hash: txToSpend.getHash(),\r\n index: 0,\r\n sequence: 0,\r\n witnessUtxo: {\r\n script: outputScript as Script,\r\n value: ZERO_SATOSHI\r\n }\r\n });\r\n psbt.addOutput({\r\n script: fromHex('6a') as Script,\r\n value: ZERO_SATOSHI\r\n });\r\n\r\n // Compute taproot sighash using public API\r\n const psbtTx = psbt.data.globalMap.unsignedTx as PsbtTransaction;\r\n const txForHash: Transaction = psbtTx.tx;\r\n const tapKeyHash = txForHash.hashForWitnessV1(0, [outputScript as Script], [ZERO_SATOSHI], Transaction.SIGHASH_DEFAULT);\r\n\r\n return schnorrValidator(pubkey, tapKeyHash, sig);\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Verify a BIP322 simple message signature for P2WPKH addresses\r\n */\r\nfunction verifyBip322P2WPKH(address: string, message: string | Uint8Array, signature: string, network: Network): boolean {\r\n try {\r\n const outputScript = bitcoinAddress.toOutputScript(address, network);\r\n const messageHash = computeBip322Hash(message);\r\n\r\n const prevoutHash = alloc(32) as Bytes32;\r\n const prevoutIndex = 0xffffffff;\r\n const sequence = 0;\r\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\r\n\r\n // Reconstruct \"to spend\" transaction\r\n const txToSpend = new Transaction();\r\n txToSpend.version = 0;\r\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\r\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\r\n\r\n // Decode signature\r\n const signatureData = fromBase64Bytes(signature);\r\n const decompiled = bitcoinScript.decompile(signatureData.subarray(1));\r\n\r\n if (!Array.isArray(decompiled) || decompiled.length < 2) {\r\n return false;\r\n }\r\n\r\n const sig = decompiled[0];\r\n const pubkey = decompiled[1];\r\n\r\n if (!(sig instanceof Uint8Array) || !(pubkey instanceof Uint8Array)) {\r\n return false;\r\n }\r\n\r\n // Create PSBT for verification\r\n const psbt = new Psbt({ network });\r\n psbt.setVersion(0);\r\n psbt.addInput({\r\n hash: txToSpend.getHash(),\r\n index: 0,\r\n sequence: 0,\r\n witnessUtxo: {\r\n script: outputScript as Script,\r\n value: ZERO_SATOSHI\r\n }\r\n });\r\n psbt.addOutput({\r\n script: fromHex('6a') as Script,\r\n value: ZERO_SATOSHI\r\n });\r\n\r\n psbt.updateInput(0, {\r\n partialSig: [\r\n {\r\n pubkey: pubkey as PublicKey,\r\n signature: sig\r\n }\r\n ]\r\n });\r\n\r\n return psbt.validateSignaturesOfAllInputs(ecdsaValidator);\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Verify a BIP322 simple message signature\r\n */\r\nexport function verifyBip322Message(\r\n address: string,\r\n message: string | Uint8Array,\r\n signature: string,\r\n network: Network\r\n): boolean {\r\n const addressType = detectAddressType(address, network);\r\n\r\n if (addressType === null) {\r\n return false;\r\n }\r\n\r\n switch (addressType) {\r\n case AddressTypes.P2TR: {\r\n return verifyBip322P2TR(address, message, signature, network);\r\n }\r\n case AddressTypes.P2WPKH: {\r\n return verifyBip322P2WPKH(address, message, signature, network);\r\n }\r\n default: {\r\n return false;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Sign a message using BIP322 with WalletNetworks parameter\r\n */\r\nexport async function signBip322MessageWithNetworkType(\r\n message: string | Uint8Array,\r\n address: string,\r\n networkType: WalletNetworks,\r\n signPsbt: (psbt: Psbt) => Promise<Psbt>\r\n): Promise<Bip322Signature> {\r\n const network = toNetwork(networkType);\r\n const signature = await signBip322Message(message, address, network, signPsbt);\r\n\r\n return {\r\n address,\r\n message,\r\n signature,\r\n networkType\r\n };\r\n}\r\n\r\n/**\r\n * Verify a BIP322 signature with WalletNetworks parameter\r\n */\r\nexport function verifyBip322MessageWithNetworkType(\r\n address: string,\r\n message: string | Uint8Array,\r\n signature: string,\r\n networkType: WalletNetworks\r\n): boolean {\r\n const network = toNetwork(networkType);\r\n return verifyBip322Message(address, message, signature, network);\r\n}\r\n","/**\r\n * OPNet Wallet SDK - Local Wallet\r\n * Full-featured local wallet implementation with quantum support.\r\n */\r\n\r\nimport { equals, type Network, networks, payments, Psbt, Transaction, type XOnlyPublicKey } from '@btc-vision/bitcoin';\r\nimport { createXOnlyPublicKey, fromHexInternal, toHex, concatBytes } from '@btc-vision/ecpair';\r\nimport { AddressTypes } from '@btc-vision/transaction';\r\nimport { publicKeyToAddress, scriptPubKeyToAddress } from '@/address';\r\nimport { HdKeyring } from '@/keyring';\r\nimport { SimpleKeyring } from '@/keyring';\r\nimport { signBip322Message, signMLDSA, signSchnorr } from '@/message';\r\nimport type { AbstractWallet, MessageSigningMethod, SignPsbtOptions, ToSignInput } from '@/types';\r\n\r\n/**\r\n * Local wallet implementation with full signing capabilities.\r\n */\r\nexport class LocalWallet implements AbstractWallet {\r\n private readonly keyring: SimpleKeyring | HdKeyring;\r\n private readonly network: Network;\r\n private readonly addressType: AddressTypes;\r\n private readonly publicKey: string;\r\n private readonly address: string;\r\n\r\n private constructor(\r\n keyring: SimpleKeyring | HdKeyring,\r\n network: Network,\r\n addressType: AddressTypes,\r\n publicKey: string\r\n ) {\r\n this.keyring = keyring;\r\n this.network = network;\r\n this.addressType = addressType;\r\n this.publicKey = publicKey;\r\n this.address = publicKeyToAddress(fromHexInternal(publicKey), addressType, network);\r\n }\r\n\r\n /**\r\n * Create wallet from WIF\r\n */\r\n public static fromWIF(\r\n wif: string,\r\n addressType: AddressTypes = AddressTypes.P2TR,\r\n network: Network,\r\n quantumPrivateKey?: string\r\n ): LocalWallet {\r\n const keyring = SimpleKeyring.fromWIF(wif, quantumPrivateKey, network);\r\n const publicKey = keyring.getPublicKey();\r\n return new LocalWallet(keyring, network, addressType, publicKey);\r\n }\r\n\r\n /**\r\n * Create wallet from private key hex\r\n */\r\n public static fromPrivateKey(\r\n privateKeyHex: string,\r\n addressType: AddressTypes = AddressTypes.P2TR,\r\n network: Network,\r\n quantumPrivateKey?: string\r\n ): LocalWallet {\r\n const keyring = SimpleKeyring.fromPrivateKey(privateKeyHex, quantumPrivateKey, network);\r\n const publicKey = keyring.getPublicKey();\r\n return new LocalWallet(keyring, network, addressType, publicKey);\r\n }\r\n\r\n /**\r\n * Create wallet from mnemonic\r\n */\r\n public static fromMnemonic(\r\n mnemonic: string,\r\n addressType: AddressTypes = AddressTypes.P2TR,\r\n network: Network,\r\n passphrase?: string,\r\n accountIndex = 0\r\n ): LocalWallet {\r\n const keyring = new HdKeyring({\r\n mnemonic,\r\n passphrase,\r\n network,\r\n addressType,\r\n activeIndexes: [accountIndex]\r\n });\r\n const accounts = keyring.getAccounts();\r\n const publicKey = accounts[0];\r\n if (publicKey === undefined) {\r\n throw new Error('Failed to derive wallet from mnemonic');\r\n }\r\n return new LocalWallet(keyring, network, addressType, publicKey);\r\n }\r\n\r\n /**\r\n * Create a random wallet\r\n */\r\n public static random(\r\n addressType: AddressTypes = AddressTypes.P2TR,\r\n network: Network = networks.bitcoin\r\n ): LocalWallet {\r\n const keyring = SimpleKeyring.generate(network);\r\n const publicKey = keyring.getPublicKey();\r\n return new LocalWallet(keyring, network, addressType, publicKey);\r\n }\r\n\r\n /**\r\n * Get the wallet address\r\n */\r\n public getAddress(): string {\r\n return this.address;\r\n }\r\n\r\n /**\r\n * Get the public key\r\n */\r\n public getPublicKey(): string {\r\n return this.publicKey;\r\n }\r\n\r\n /**\r\n * Get the quantum public key\r\n */\r\n public getQuantumPublicKey(): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.getQuantumPublicKey();\r\n }\r\n return this.keyring.getQuantumPublicKey(this.publicKey);\r\n }\r\n\r\n /**\r\n * Get the network\r\n */\r\n public getNetwork(): Network {\r\n return this.network;\r\n }\r\n\r\n /**\r\n * Get the address type\r\n */\r\n public getAddressType(): AddressTypes {\r\n return this.addressType;\r\n }\r\n\r\n /**\r\n * Sign a PSBT\r\n */\r\n public signPsbt(psbt: Psbt, opts?: SignPsbtOptions): Psbt {\r\n const options = opts ?? { autoFinalized: true, toSignInputs: [] };\r\n const inputs = this.formatInputsToSign(psbt, options);\r\n\r\n if (inputs.length === 0) {\r\n throw new Error('LocalWallet: No inputs to sign');\r\n }\r\n\r\n // Add tapInternalKey for P2TR inputs if missing\r\n for (const input of inputs) {\r\n const psbtInput = psbt.data.inputs[input.index];\r\n if (psbtInput === undefined) {\r\n continue;\r\n }\r\n\r\n const isNotSigned = !(psbtInput.finalScriptSig ?? psbtInput.finalScriptWitness);\r\n const isP2TR = this.addressType === AddressTypes.P2TR;\r\n const lostInternalPubkey = psbtInput.tapInternalKey === undefined;\r\n\r\n if (isNotSigned && isP2TR && lostInternalPubkey) {\r\n const pubkeyBytes: Uint8Array = fromHexInternal(this.publicKey);\r\n const xOnlyBytes: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\r\n const tapInternalKey: XOnlyPublicKey = createXOnlyPublicKey(xOnlyBytes);\r\n const { output } = payments.p2tr({\r\n internalPubkey: tapInternalKey,\r\n network: this.network\r\n });\r\n if (output !== undefined && psbtInput.witnessUtxo !== undefined && equals(psbtInput.witnessUtxo.script, output)) {\r\n psbtInput.tapInternalKey = tapInternalKey;\r\n }\r\n }\r\n }\r\n\r\n // Sign transaction\r\n if (this.keyring instanceof SimpleKeyring) {\r\n this.keyring.signTransaction(psbt, inputs);\r\n } else {\r\n this.keyring.signTransaction(psbt, inputs);\r\n }\r\n\r\n // Finalize if requested\r\n if (options.autoFinalized === true) {\r\n for (const input of inputs) {\r\n psbt.finalizeInput(input.index);\r\n }\r\n }\r\n\r\n return psbt;\r\n }\r\n\r\n /**\r\n * Sign a message\r\n */\r\n public async signMessage(message: string | Uint8Array, method: MessageSigningMethod): Promise<string> {\r\n switch (method) {\r\n case 'bip322-simple': {\r\n return await signBip322Message(message, this.address, this.network, (psbt) => {\r\n return Promise.resolve(this.signPsbt(psbt, { autoFinalized: false }));\r\n });\r\n }\r\n case 'ecdsa':\r\n case 'schnorr': {\r\n const keypair = this.getKeypair();\r\n const result = signSchnorr(keypair, message);\r\n return toHex(result.signature);\r\n }\r\n case 'mldsa': {\r\n const quantumKeypair = this.getQuantumKeypair();\r\n const result = signMLDSA(quantumKeypair, message);\r\n return toHex(result.signature);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sign raw data\r\n */\r\n public signData(data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.signData(data, type);\r\n }\r\n return this.keyring.signData(this.publicKey, data, type);\r\n }\r\n\r\n /**\r\n * Export the private key\r\n */\r\n public exportPrivateKey(): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.exportPrivateKey();\r\n }\r\n return this.keyring.exportAccount(this.publicKey);\r\n }\r\n\r\n /**\r\n * Export the quantum private key WITH chain code (for backup/restore)\r\n */\r\n public exportQuantumPrivateKey(): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.exportQuantumPrivateKey();\r\n }\r\n // For HD keyrings, get the quantum key from the derived wallet\r\n const wallet = this.keyring.getWallet(this.publicKey);\r\n const mldsaPrivateKey: Uint8Array | undefined = wallet.mldsaKeypair.privateKey;\r\n if (mldsaPrivateKey === undefined) {\r\n throw new Error('LocalWallet: No quantum private key available');\r\n }\r\n return toHex(concatBytes(mldsaPrivateKey, wallet.chainCode));\r\n }\r\n\r\n /**\r\n * Export the raw quantum private key WITHOUT chain code (for Wallet.fromWif)\r\n */\r\n public exportRawQuantumPrivateKey(): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.exportRawQuantumPrivateKey();\r\n }\r\n // For HD keyrings, get the quantum key from the derived wallet\r\n const wallet = this.keyring.getWallet(this.publicKey);\r\n const mldsaPrivateKey: Uint8Array | undefined = wallet.mldsaKeypair.privateKey;\r\n if (mldsaPrivateKey === undefined) {\r\n throw new Error('LocalWallet: No quantum private key available');\r\n }\r\n return toHex(mldsaPrivateKey);\r\n }\r\n\r\n /**\r\n * Export the chain code\r\n */\r\n public exportChainCode(): Uint8Array {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.exportChainCode();\r\n }\r\n // For HD keyrings, get chain code from the derived wallet\r\n return this.keyring.getChainCode(this.publicKey);\r\n }\r\n\r\n /**\r\n * Export WIF\r\n */\r\n public exportWIF(): string {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.exportWIF();\r\n }\r\n throw new Error('LocalWallet: Cannot export WIF from HD keyring directly');\r\n }\r\n\r\n private getKeypair(): ReturnType<SimpleKeyring['getKeypair']> {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.getKeypair();\r\n }\r\n return this.keyring.getWallet(this.publicKey).keypair;\r\n }\r\n\r\n private getQuantumKeypair(): ReturnType<SimpleKeyring['getQuantumKeypair']> {\r\n if (this.keyring instanceof SimpleKeyring) {\r\n return this.keyring.getQuantumKeypair();\r\n }\r\n return this.keyring.getMLDSAKeypair(this.publicKey);\r\n }\r\n\r\n private formatInputsToSign(psbt: Psbt, options: SignPsbtOptions): ToSignInput[] {\r\n const toSignInputs: ToSignInput[] = [];\r\n\r\n if (options.toSignInputs !== undefined && options.toSignInputs.length > 0) {\r\n for (const input of options.toSignInputs) {\r\n const index = input.index;\r\n\r\n if ('address' in input) {\r\n if (input.address !== this.address) {\r\n throw new Error(`LocalWallet: Address mismatch at input ${index}`);\r\n }\r\n } else if ('publicKey' in input) {\r\n if (input.publicKey !== this.publicKey) {\r\n throw new Error(`LocalWallet: Public key mismatch at input ${index}`);\r\n }\r\n }\r\n\r\n const toSignInput: ToSignInput = {\r\n index,\r\n publicKey: this.publicKey\r\n };\r\n if (input.sighashTypes !== undefined) {\r\n (toSignInput as { sighashTypes?: readonly number[] }).sighashTypes = input.sighashTypes;\r\n }\r\n if (input.disableTweakSigner !== undefined) {\r\n (toSignInput as { disableTweakSigner?: boolean }).disableTweakSigner = input.disableTweakSigner;\r\n }\r\n toSignInputs.push(toSignInput);\r\n }\r\n } else {\r\n // Auto-detect inputs to sign\r\n for (let i = 0; i < psbt.data.inputs.length; i++) {\r\n const input = psbt.data.inputs[i];\r\n if (input === undefined) {\r\n continue;\r\n }\r\n\r\n let script: Uint8Array | undefined;\r\n if (input.witnessUtxo !== undefined) {\r\n script = input.witnessUtxo.script;\r\n } else if (input.nonWitnessUtxo !== undefined) {\r\n const tx = psbt.txInputs[i];\r\n if (tx !== undefined) {\r\n const nonWitnessTx = Transaction.fromBuffer(input.nonWitnessUtxo);\r\n const output = nonWitnessTx.outs[tx.index];\r\n script = output?.script;\r\n }\r\n }\r\n\r\n const isSigned = input.finalScriptSig ?? input.finalScriptWitness;\r\n\r\n if (script !== undefined && isSigned === undefined) {\r\n const address = scriptPubKeyToAddress(script, this.network);\r\n if (address === this.address) {\r\n const toSignInput: ToSignInput = {\r\n index: i,\r\n publicKey: this.publicKey\r\n };\r\n if (input.sighashType !== undefined) {\r\n (toSignInput as { sighashTypes?: readonly number[] }).sighashTypes = [input.sighashType];\r\n }\r\n toSignInputs.push(toSignInput);\r\n }\r\n }\r\n }\r\n }\r\n\r\n return toSignInputs;\r\n }\r\n}\r\n","/**\r\n * OPNet Wallet SDK Type Definitions\r\n * All core types and interfaces for the wallet SDK.\r\n */\r\n\r\nimport type { Network, Psbt } from '@btc-vision/bitcoin';\r\nimport { AddressTypes, MLDSASecurityLevel, type QuantumBIP32Interface, WalletNetworks } from '@btc-vision/transaction';\r\nimport type { UniversalSigner } from '@btc-vision/ecpair';\r\n\r\n/**\r\n * Signature type for message signing operations\r\n */\r\nexport type SignatureType = 'ecdsa' | 'schnorr' | 'mldsa';\r\n\r\n/**\r\n * Message signing method types\r\n */\r\nexport type MessageSigningMethod = 'bip322-simple' | 'ecdsa' | 'schnorr' | 'mldsa';\r\n\r\n/**\r\n * Base interface for inputs to sign in a PSBT\r\n */\r\nexport interface BaseSignInput {\r\n readonly index: number;\r\n readonly sighashTypes?: readonly number[];\r\n readonly disableTweakSigner?: boolean;\r\n}\r\n\r\n/**\r\n * Sign input with address specification\r\n */\r\nexport interface AddressSignInput extends BaseSignInput {\r\n readonly address: string;\r\n}\r\n\r\n/**\r\n * Sign input with public key specification\r\n */\r\nexport interface PublicKeySignInput extends BaseSignInput {\r\n readonly publicKey: string;\r\n}\r\n\r\n/**\r\n * Union type for sign inputs\r\n */\r\nexport type SignInput = AddressSignInput | PublicKeySignInput;\r\n\r\n/**\r\n * Options for signing PSBTs\r\n */\r\nexport interface SignPsbtOptions {\r\n readonly autoFinalized?: boolean;\r\n readonly toSignInputs?: readonly SignInput[];\r\n}\r\n\r\n/**\r\n * Internal representation of inputs to sign\r\n */\r\nexport interface ToSignInput {\r\n readonly index: number;\r\n readonly publicKey: string;\r\n readonly sighashTypes?: readonly number[];\r\n readonly disableTweakSigner?: boolean;\r\n}\r\n\r\n/**\r\n * Result of an address decode operation\r\n */\r\nexport interface DecodedAddress {\r\n readonly networkType: WalletNetworks;\r\n readonly addressType: AddressTypes;\r\n readonly scriptPubKey: Uint8Array;\r\n}\r\n\r\n/**\r\n * Quantum key pair information\r\n */\r\nexport interface QuantumKeyInfo {\r\n readonly publicKey: Uint8Array;\r\n readonly securityLevel: MLDSASecurityLevel;\r\n}\r\n\r\n/**\r\n * Classical key pair information\r\n */\r\nexport interface ClassicalKeyInfo {\r\n readonly publicKey: Uint8Array;\r\n readonly privateKey?: Uint8Array;\r\n}\r\n\r\n/**\r\n * Combined wallet key information (classical + quantum)\r\n */\r\nexport interface WalletKeyInfo {\r\n readonly classical: ClassicalKeyInfo;\r\n readonly quantum: QuantumKeyInfo;\r\n readonly chainCode: Uint8Array;\r\n}\r\n\r\n/**\r\n * Exported wallet format for unified key export\r\n */\r\nexport interface ExportedWallet {\r\n readonly version: number;\r\n readonly classicalPrivateKey: string;\r\n readonly quantumPrivateKey: string;\r\n readonly quantumPublicKey: string;\r\n readonly securityLevel: MLDSASecurityLevel;\r\n readonly chainCode: string;\r\n}\r\n\r\n/**\r\n * Mnemonic options for wallet generation\r\n */\r\nexport interface MnemonicOptions {\r\n readonly phrase?: string;\r\n readonly passphrase?: string;\r\n readonly network?: Network;\r\n readonly securityLevel?: MLDSASecurityLevel;\r\n}\r\n\r\n/**\r\n * HD derivation options\r\n */\r\nexport interface DerivationOptions {\r\n readonly addressType?: AddressTypes;\r\n readonly account?: number;\r\n readonly change?: boolean;\r\n readonly index?: number;\r\n}\r\n\r\n/**\r\n * Keyring serialization options\r\n */\r\nexport interface KeyringSerializeOptions {\r\n readonly includePrivateKeys?: boolean;\r\n}\r\n\r\n/**\r\n * HD Keyring deserialization options\r\n */\r\nexport interface HdKeyringOptions {\r\n readonly mnemonic?: string | undefined;\r\n readonly passphrase?: string | undefined;\r\n readonly network?: Network | undefined;\r\n readonly securityLevel?: MLDSASecurityLevel | undefined;\r\n readonly activeIndexes?: readonly number[] | undefined;\r\n readonly addressType?: AddressTypes | undefined;\r\n readonly hdPath?: string | undefined;\r\n}\r\n\r\n/**\r\n * Simple keyring options for WIF/private key import\r\n */\r\nexport interface SimpleKeyringOptions {\r\n readonly privateKey: string;\r\n readonly quantumPrivateKey?: string | undefined;\r\n readonly network?: Network | undefined;\r\n readonly securityLevel?: MLDSASecurityLevel | undefined;\r\n}\r\n\r\n/**\r\n * Message signature result\r\n */\r\nexport interface SignedMessage {\r\n readonly message: string | Uint8Array;\r\n readonly signature: Uint8Array;\r\n readonly publicKey: Uint8Array;\r\n readonly signatureType: SignatureType;\r\n readonly securityLevel?: MLDSASecurityLevel;\r\n}\r\n\r\n/**\r\n * BIP322 signature result\r\n */\r\nexport interface Bip322Signature {\r\n readonly address: string;\r\n readonly message: string | Uint8Array;\r\n readonly signature: string;\r\n readonly networkType: WalletNetworks;\r\n}\r\n\r\n/**\r\n * Wallet account information\r\n */\r\nexport interface AccountInfo {\r\n readonly index: number;\r\n readonly publicKey: string;\r\n readonly quantumPublicKey: string;\r\n readonly addresses: AccountAddresses;\r\n}\r\n\r\n/**\r\n * All address types for an account\r\n */\r\nexport interface AccountAddresses {\r\n readonly p2pkh?: string;\r\n readonly p2wpkh?: string;\r\n readonly p2tr?: string;\r\n readonly p2shP2wpkh?: string;\r\n}\r\n\r\n/**\r\n * Abstract wallet interface\r\n */\r\nexport interface AbstractWallet {\r\n signPsbt(psbt: Psbt, opts?: SignPsbtOptions): Promise<Psbt> | Psbt;\r\n signMessage(message: string | Uint8Array, method: MessageSigningMethod): Promise<string>;\r\n}\r\n\r\n/**\r\n * Keystone hardware wallet key information\r\n */\r\nexport interface KeystoneKey {\r\n readonly path: string;\r\n readonly extendedPublicKey: string;\r\n}\r\n\r\n/**\r\n * Keystone keyring options\r\n */\r\nexport interface KeystoneKeyringOptions {\r\n readonly mfp: string;\r\n readonly keys: readonly KeystoneKey[];\r\n readonly network?: Network;\r\n readonly activeIndexes?: readonly number[];\r\n readonly addressType?: AddressTypes;\r\n}\r\n\r\n/**\r\n * Type guard to check if sign input has address\r\n */\r\nexport function isAddressSignInput(input: SignInput): input is AddressSignInput {\r\n return 'address' in input;\r\n}\r\n\r\n/**\r\n * Type guard to check if sign input has public key\r\n */\r\nexport function isPublicKeySignInput(input: SignInput): input is PublicKeySignInput {\r\n return 'publicKey' in input;\r\n}\r\n\r\n/**\r\n * Re-export UniversalSigner for convenience\r\n */\r\nexport type { UniversalSigner, QuantumBIP32Interface };\r\n"],"names":["toNetwork","networkType","WalletNetworks","Mainnet","networks","bitcoin","Testnet","testnet","Regtest","regtest","detectNetworkFromAddress","address","startsWith","publicKeyToAddress","publicKey","addressType","network","pubkeyBytes","fromHexInternal","AddressTypes","P2PKH","payment","payments","p2pkh","pubkey","createPublicKey","Error","P2WPKH","p2wpkh","P2TR","xOnly","length","subarray","p2tr","internalPubkey","createXOnlyPublicKey","P2SH_OR_P2SH_P2WPKH","p2sh","redeem","publicKeyToPayment","scriptPubKeyToAddress","scriptPubKey","script","fromHex","bitcoinAddress","fromOutputScript","isValidAddress","AddressVerificator","detectAddressType","HdKeyring","static","type","mnemonic","wallets","Map","activeIndexes","securityLevel","passphrase","_hdPath","constructor","options","this","MLDSASecurityLevel","LEVEL2","hdPath","initFromMnemonic","activateAccounts","generate","strength","MnemonicStrength","MAXIMUM","Mnemonic","keyring","phrase","getMnemonic","hasMnemonic","deriveWallet","index","cached","get","wallet","isCustomHdPath","classicalPath","quantumPath","deriveCustomPath","deriveOPWallet","set","deriveStandardWallet","derive","addAccounts","numberOfAccounts","newPublicKeys","currentIndex","includes","push","toPublicKeyHex","indexes","publicKeys","getAccounts","map","getAccountsInfo","addresses","legacy","p2shP2wpkh","segwitLegacy","quantumPublicKey","quantumPublicKeyHex","getQuantumPublicKey","findWalletByPublicKey","getIndexByPublicKey","entries","getAddressesForPublicKey","getAddress","removeAccount","activeIdx","indexOf","splice","delete","exportAccount","toPrivateKeyHex","signTransaction","psbt","inputs","input","psbtInput","data","keypair","sighashTypes","isTaprootInput","disableTweakSigner","tweakedKeypair","tweak","createBytes32","signInput","signData","dataHash","createMessageHash","toHex","sign","signSchnorr","getWallet","serialize","getActiveIndexes","setAddressType","getAddressType","getSecurityLevel","getNetwork","getAddressesPage","page","perPage","start","end","results","i","getAddressFromWallet","getChainCode","Uint8Array","from","chainCode","getMLDSAKeypair","mldsaKeypair","standardPath","standardPathBase","slice","values","SimpleKeyring","quantumKeypair","privateKey","importPrivateKey","quantumPrivateKey","EcKeyPair","generateRandomKeyPair","seed","crypto","getRandomValues","QuantumBIP32Factory","fromSeed","fromWIF","wif","importQuantumKey","fromPrivateKey","privateKeyHex","quantumPrivateKeyHex","privateKeyBytes","expectedKeySize","getMLDSAConfig","privateKeySize","expectedKeyWithChaincodeSize","hasChaincode","isKeyOnly","keyWithoutChainCode","generateFreshQuantumKey","hasKeys","hasClassicalKey","hasQuantumKey","needsQuantumMigration","getPublicKey","getQuantumPublicKeyOrUndefined","getQuantumPublicKeyHash","hash","bitcoinCrypto","sha256","clearQuantumKey","getAddresses","exportPrivateKey","exportQuantumPrivateKey","concatBytes","exportRawQuantumPrivateKey","exportChainCode","exportWIF","toWIF","tweakedSigner","verify","signature","createSignature","verifySchnorr","createSchnorrSignature","getKeypair","getQuantumKeypair","clear","MAGIC_HEADER","textEncoder","TextEncoder","calculateChecksum","encode","getNetworkName","bech32","exportWallet","classicalPrivateKey","classicalPublicKey","exportData","magic","version","classical","quantum","checksum","JSON","stringify","importWallet","dataWithoutChecksum","expectedChecksum","name","getNetworkFromName","serializeExport","json","btoa","deserializeExport","serialized","atob","parse","backend","getNobleBackend","createNobleBackend","signMLDSA","message","result","MessageSigner","signMLDSAMessage","verifyMLDSA","fromPublicKey","verifyMLDSASignature","signMessage","verifySignature","isQuantumKeypair","toUint8Array","ZERO_SATOSHI","toSatoshi","fromBase64Bytes","base64","binary","bytes","charCodeAt","SUPPORTED_ADDRESS_TYPES","computeBip322Hash","tagHash","messageBytes","concat","generateBip322Psbt","outputScript","toOutputScript","String","messageHash","prevoutHash","alloc","scriptSig","txToSpend","Transaction","addInput","addOutput","Psbt","setVersion","getHash","sequence","witnessUtxo","value","extractBip322Signature","tx","extractTransaction","witness","ins","varintLength","bitcoinScript","number","byte","fromCharCode","toBase64","w","buf","varint","encodeVarString","async","signBip322Message","signPsbt","signedPsbt","finalizeAllInputs","ecdsaValidator","msghash","decoded","decode","verifyBip322P2TR","prevoutIndex","signatureData","decompiled","decompile","Array","isArray","sig","txForHash","globalMap","unsignedTx","xOnlyPubkey","schnorrValidator","hashForWitnessV1","SIGHASH_DEFAULT","verifyBip322Message","updateInput","partialSig","validateSignaturesOfAllInputs","verifyBip322P2WPKH","LocalWallet","fromMnemonic","accountIndex","random","opts","autoFinalized","toSignInputs","formatInputsToSign","isNotSigned","finalScriptSig","finalScriptWitness","isP2TR","lostInternalPubkey","tapInternalKey","xOnlyBytes","output","equals","finalizeInput","method","Promise","resolve","mldsaPrivateKey","toSignInput","nonWitnessUtxo","txInputs","fromBuffer","outs","isSigned","sighashType","mainnet","networksToTry","isP2PKHOrP2SH","isP2WPKHAddress","isValidP2TRAddress","pubkeyHex","isValidPublicKey","signatureType","tweakAndSignMessage","expectedNetwork","ecdsaBytes","tweakAndVerifySignature"],"mappings":"2NAWO,SAASA,EAAUC,GACtB,OAAQA,GACJ,KAAKC,EAAAA,eAAeC,QAChB,OAAO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AAkB,IAAdzN,QAAuC,IAAZ9I,QAA2C,IAAlBwC,EACpD,MAAM,IAAI9B,MAAM,sEAEpB,OAAOwO,EAAYpP,EAAWgJ,EAAW9I,EAASwC,EAAesM,EAASzC,GAE9E,IAAK,UACD,OAAOE,EAAczM,EAAWgP,EAASzC,GAE7C,IAAK,QAAS,CACV,MAAMqK,EAAyBlH,EAAaV,GACtCvD,EAAmByD,EAAAA,cAAcvD,OAAOiL,GAC9C,OAAO/H,IAAkBvC,OAAO5E,EAAAA,kBAAkB+D,GAAO9K,EAAAA,gBAAgBX,GAAYwM,kBAAgBD,GACzG,EAER,uDAvFO,SACHvM,EACAgP,EACAzC,GAEA,OAAO2C,EAAAA,cAAc2H,wBAAwB7W,EAAWgP,EAASzC,EACrE"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/network/index.ts","../src/address/index.ts","../src/keyring/hd-keyring.ts","../src/keyring/simple-keyring.ts","../src/keyring/key-export.ts","../src/message/backend.ts","../src/message/signing.ts","../src/message/bip322.ts","../src/wallet/local-wallet.ts","../src/types/index.ts"],"sourcesContent":["/**\r\n * OPNet Wallet SDK - Network Module\r\n * Network configuration and conversion utilities.\r\n */\r\n\r\nimport { type Network, networks } from '@btc-vision/bitcoin';\r\nimport { WalletNetworks } from '@btc-vision/transaction';\r\n\r\n/**\r\n * Convert WalletNetworks enum to @btc-vision/bitcoin Network object\r\n */\r\nexport function toNetwork(networkType: WalletNetworks): Network {\r\n switch (networkType) {\r\n case WalletNetworks.Mainnet: {\r\n return networks.bitcoin;\r\n }\r\n\r\n case WalletNetworks.Testnet: {\r\n return networks.testnet;\r\n }\r\n\r\n case WalletNetworks.Regtest: {\r\n return networks.regtest;\r\n }\r\n\r\n case WalletNetworks.OpnetTestnet: {\r\n return networks.opnetTestnet;\r\n }\r\n\r\n default: {\r\n throw new Error(`Unsupported network type: ${networkType}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Convert @btc-vision/bitcoin Network object to WalletNetworks enum\r\n */\r\nexport function toNetworkType(network: Network): WalletNetworks {\r\n if (network.bech32 === networks.bitcoin.bech32) {\r\n return WalletNetworks.Mainnet;\r\n }\r\n\r\n if (network.bech32 === networks.testnet.bech32) {\r\n return WalletNetworks.Testnet;\r\n }\r\n\r\n if (network.bech32 === networks.opnetTestnet.bech32) {\r\n return WalletNetworks.OpnetTestnet;\r\n }\r\n\r\n return WalletNetworks.Regtest;\r\n}\r\n\r\n/**\r\n * Get the bech32 prefix for a network type\r\n */\r\nexport function getBech32Prefix(networkType: WalletNetworks): string {\r\n const network = toNetwork(networkType);\r\n return network.bech32;\r\n}\r\n\r\n/**\r\n * Detect network type from an address.\r\n *\r\n * Handles bech32/bech32m (segwit), base58 P2PKH and P2SH formats.\r\n * Order matters: more specific prefixes (bcrt1, opt1) are checked before\r\n * shorter ones (bc1, tb1) to avoid false matches.\r\n */\r\nexport function detectNetworkFromAddress(address: string): WalletNetworks | null {\r\n // Bech32/bech32m — check longest prefixes first to avoid false matches\r\n // Regtest: bcrt1...\r\n if (address.startsWith(`${networks.regtest.bech32}1`)) {\r\n return WalletNetworks.Regtest;\r\n }\r\n\r\n // OPNet Testnet: opt1...\r\n if (address.startsWith(`${networks.opnetTestnet.bech32}1`)) {\r\n return WalletNetworks.OpnetTestnet;\r\n }\r\n\r\n // Mainnet: bc1... (also covers legacy 1... and 3...)\r\n if (address.startsWith(`${networks.bitcoin.bech32}1`)) {\r\n return WalletNetworks.Mainnet;\r\n }\r\n\r\n // Testnet: tb1...\r\n if (address.startsWith(`${networks.testnet.bech32}1`)) {\r\n return WalletNetworks.Testnet;\r\n }\r\n\r\n // Base58 legacy addresses (P2PKH / P2SH)\r\n // Mainnet P2PKH starts with 1, P2SH starts with 3\r\n if (address.startsWith('1') || address.startsWith('3')) {\r\n return WalletNetworks.Mainnet;\r\n }\r\n\r\n // Testnet/Regtest P2PKH starts with m or n, P2SH starts with 2\r\n // (Regtest and testnet share the same base58 prefixes)\r\n if (address.startsWith('m') || address.startsWith('n') || address.startsWith('2')) {\r\n return WalletNetworks.Testnet;\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * Validate that an address matches the expected network\r\n */\r\nexport function validateAddressNetwork(address: string, expectedNetwork: WalletNetworks): boolean {\r\n const detectedNetwork = detectNetworkFromAddress(address);\r\n return detectedNetwork === expectedNetwork;\r\n}\r\n","/**\r\n * OPNet Wallet SDK - Address Module\r\n * Address generation, validation, and conversion utilities.\r\n * Uses @btc-vision/transaction AddressVerificator for all operations.\r\n */\r\n\r\nimport { address as bitcoinAddress, fromHex, type Network, networks, type Payment, payments, toHex } from '@btc-vision/bitcoin';\r\nimport { createPublicKey, createXOnlyPublicKey, fromHexInternal } from '@btc-vision/ecpair';\r\nimport { AddressTypes, AddressVerificator, WalletNetworks } from '@btc-vision/transaction';\r\nimport { toNetwork } from '@/network';\r\nimport type { DecodedAddress } from '@/types';\r\n\r\n/**\r\n * Generate a Bitcoin address from a public key\r\n */\r\nexport function publicKeyToAddress(publicKey: Uint8Array | string, addressType: AddressTypes, network: Network): string {\r\n const pubkeyBytes: Uint8Array = typeof publicKey === 'string' ? fromHexInternal(publicKey) : publicKey;\r\n\r\n switch (addressType) {\r\n case AddressTypes.P2PKH: {\r\n const payment = payments.p2pkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2PKH address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2WPKH: {\r\n const payment = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2WPKH address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2TR: {\r\n const xOnly: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\r\n const payment = payments.p2tr({ internalPubkey: createXOnlyPublicKey(xOnly), network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2TR address');\r\n }\r\n return payment.address;\r\n }\r\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\r\n const p2wpkh = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n const payment = payments.p2sh({ redeem: p2wpkh, network });\r\n if (payment.address === undefined) {\r\n throw new Error('Failed to generate P2SH-P2WPKH address');\r\n }\r\n return payment.address;\r\n }\r\n default: {\r\n throw new Error(`Unsupported address type: ${addressType as string}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generate a payment object from a public key\r\n */\r\nexport function publicKeyToPayment(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n network: Network\r\n): Payment {\r\n const pubkeyBytes: Uint8Array = typeof publicKey === 'string' ? fromHexInternal(publicKey) : publicKey;\r\n\r\n switch (addressType) {\r\n case AddressTypes.P2PKH: {\r\n return payments.p2pkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n }\r\n case AddressTypes.P2WPKH: {\r\n return payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n }\r\n case AddressTypes.P2TR: {\r\n const xOnly: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\r\n return payments.p2tr({ internalPubkey: createXOnlyPublicKey(xOnly), network });\r\n }\r\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\r\n const p2wpkh = payments.p2wpkh({ pubkey: createPublicKey(pubkeyBytes), network });\r\n return payments.p2sh({ redeem: p2wpkh, network });\r\n }\r\n default: {\r\n throw new Error(`Unsupported address type: ${addressType as string}`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Generate scriptPubKey from a public key\r\n */\r\nexport function publicKeyToScriptPubKey(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n network: Network\r\n): Uint8Array {\r\n const payment = publicKeyToPayment(publicKey, addressType, network);\r\n if (!payment.output) {\r\n throw new Error('Failed to generate script pubkey');\r\n }\r\n return payment.output;\r\n}\r\n\r\n/**\r\n * Convert an address to its scriptPubKey\r\n */\r\nexport function addressToScriptPubKey(address: string, network: Network): Uint8Array {\r\n return bitcoinAddress.toOutputScript(address, network);\r\n}\r\n\r\n/**\r\n * Convert scriptPubKey to an address\r\n */\r\nexport function scriptPubKeyToAddress(scriptPubKey: Uint8Array | string, network: Network): string {\r\n const script = typeof scriptPubKey === 'string' ? fromHex(scriptPubKey) : scriptPubKey;\r\n return bitcoinAddress.fromOutputScript(script, network);\r\n}\r\n\r\n/**\r\n * Validate if an address is valid for the given network\r\n */\r\nexport function isValidAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.detectAddressType(address, network) !== null;\r\n}\r\n\r\n/**\r\n * Detect the address type from an address string\r\n */\r\nexport function detectAddressType(address: string, network: Network): AddressTypes | null {\r\n return AddressVerificator.detectAddressType(address, network);\r\n}\r\n\r\n/**\r\n * Decode an address to get its network type, address type, and scriptPubKey\r\n */\r\nexport function decodeAddress(address: string): DecodedAddress | null {\r\n // Try each network to decode the address\r\n const networksToTry: { network: Network; networkType: WalletNetworks }[] = [\r\n { network: networks.bitcoin, networkType: WalletNetworks.Mainnet },\r\n { network: networks.opnetTestnet, networkType: WalletNetworks.OpnetTestnet },\r\n { network: networks.testnet, networkType: WalletNetworks.Testnet },\r\n { network: networks.regtest, networkType: WalletNetworks.Regtest }\r\n ];\r\n\r\n for (const { network, networkType } of networksToTry) {\r\n try {\r\n const scriptPubKey = bitcoinAddress.toOutputScript(address, network);\r\n const addressType = detectAddressType(address, network);\r\n\r\n if (addressType !== null) {\r\n return {\r\n networkType,\r\n addressType,\r\n scriptPubKey\r\n };\r\n }\r\n } catch {\r\n // Try next network\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * Validate a public key using AddressVerificator\r\n */\r\nexport function isValidPublicKey(publicKey: Uint8Array | string, network: Network): boolean {\r\n const pubkeyHex = typeof publicKey === 'string' ? publicKey : toHex(publicKey);\r\n return AddressVerificator.isValidPublicKey(pubkeyHex, network);\r\n}\r\n\r\n/**\r\n * Validate a Taproot (P2TR) address\r\n */\r\nexport function isValidP2TRAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isValidP2TRAddress(address, network);\r\n}\r\n\r\n/**\r\n * Check if an address is P2WPKH\r\n */\r\nexport function isP2WPKHAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isP2WPKHAddress(address, network);\r\n}\r\n\r\n/**\r\n * Check if an address is P2PKH or P2SH\r\n */\r\nexport function isP2PKHOrP2SHAddress(address: string, network: Network): boolean {\r\n return AddressVerificator.isP2PKHOrP2SH(address, network);\r\n}\r\n\r\n/**\r\n * Convert WalletNetworks to Network and validate address\r\n */\r\nexport function isValidAddressForNetworkType(address: string, networkType: WalletNetworks): boolean {\r\n const network = toNetwork(networkType);\r\n return isValidAddress(address, network);\r\n}\r\n\r\n/**\r\n * Get address type with WalletNetworks parameter\r\n */\r\nexport function getAddressType(address: string, networkType: WalletNetworks): AddressTypes | null {\r\n const network = toNetwork(networkType);\r\n return detectAddressType(address, network);\r\n}\r\n\r\n/**\r\n * Convert WalletNetworks-based operations to Network-based\r\n */\r\nexport function publicKeyToAddressWithNetworkType(\r\n publicKey: Uint8Array | string,\r\n addressType: AddressTypes,\r\n networkType: WalletNetworks\r\n): string {\r\n const network = toNetwork(networkType);\r\n return publicKeyToAddress(publicKey, addressType, network);\r\n}\r\n","/**\n * OPNet Wallet SDK - HD Keyring\n * Hierarchical Deterministic keyring with quantum-resistant (ML-DSA) support.\n * Uses @btc-vision/transaction Mnemonic class for BIP39 + BIP360 key derivation.\n */\n\nimport { isTaprootInput, type Network, networks, Psbt } from '@btc-vision/bitcoin';\nimport { createBytes32, createMessageHash, fromHexInternal, toHex, type UniversalSigner } from '@btc-vision/ecpair';\nimport {\n AddressTypes,\n MLDSASecurityLevel,\n Mnemonic,\n MnemonicStrength,\n type QuantumBIP32Interface,\n Wallet\n} from '@btc-vision/transaction';\nimport { publicKeyToAddress } from '@/address';\nimport type { AccountAddresses, AccountInfo, HdKeyringOptions, ToSignInput } from '@/types';\n\n/**\n * HD Keyring with quantum-resistant cryptography support.\n * Supports BIP39 mnemonic phrases with BIP360 quantum key derivation.\n */\nexport class HdKeyring {\n public static readonly type = 'HD Key Tree';\n public readonly type = HdKeyring.type;\n\n private mnemonic: Mnemonic | null = null;\n private readonly wallets: Map<number, Wallet> = new Map();\n private readonly activeIndexes: number[] = [];\n private readonly network: Network;\n private readonly securityLevel: MLDSASecurityLevel;\n private readonly passphrase: string;\n private addressType: AddressTypes;\n private readonly _hdPath: string;\n\n constructor(options: Partial<HdKeyringOptions>) {\n if (!options.network) {\n throw new Error('HdKeyring: Network option is required');\n }\n\n this.network = options.network;\n this.securityLevel = options?.securityLevel ?? MLDSASecurityLevel.LEVEL2;\n this.passphrase = options?.passphrase ?? '';\n this.addressType = options?.addressType ?? AddressTypes.P2TR;\n this._hdPath = options?.hdPath ?? '';\n\n if (options?.mnemonic !== undefined) {\n this.initFromMnemonic(options.mnemonic);\n\n if (options.activeIndexes !== undefined && options.activeIndexes.length > 0) {\n this.activateAccounts([...options.activeIndexes]);\n }\n }\n }\n\n /**\n * Get the HD derivation path\n */\n public get hdPath(): string {\n return this._hdPath;\n }\n\n /**\n * Generate a new mnemonic with quantum support\n */\n public static generate(\n strength: MnemonicStrength = MnemonicStrength.MAXIMUM,\n passphrase = '',\n network: Network = networks.bitcoin,\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\n ): HdKeyring {\n const mnemonic = Mnemonic.generate(strength, passphrase, network, securityLevel);\n const keyring = new HdKeyring({\n network,\n securityLevel,\n passphrase\n });\n keyring.mnemonic = mnemonic;\n return keyring;\n }\n\n /**\n * Initialize from an existing mnemonic phrase\n */\n public initFromMnemonic(phrase: string): void {\n if (this.mnemonic !== null) {\n throw new Error('HdKeyring: Mnemonic already initialized');\n }\n\n this.mnemonic = new Mnemonic(phrase, this.passphrase, this.network, this.securityLevel);\n }\n\n /**\n * Get the mnemonic phrase\n */\n public getMnemonic(): string {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n return this.mnemonic.phrase;\n }\n\n /**\n * Check if keyring has a mnemonic\n */\n public hasMnemonic(): boolean {\n return this.mnemonic !== null;\n }\n\n /**\n * Derive a wallet at a specific index.\n * Uses custom hdPath if set, otherwise uses Unisat-compatible derivation.\n */\n public deriveWallet(index: number): Wallet {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n\n const cached = this.wallets.get(index);\n if (cached !== undefined) {\n return cached;\n }\n\n let wallet: Wallet;\n\n // Check if using a custom HD path\n if (this.isCustomHdPath()) {\n // Build the full classical path: hdPath + /index\n const classicalPath = `${this._hdPath}/${index}`;\n // Quantum path always uses BIP360 with coin type 0 for mainnet\n const coinType = this.network === networks.bitcoin ? 0 : 1;\n const quantumPath = `m/360'/${coinType}'/0'/0/${index}`;\n wallet = this.mnemonic.deriveCustomPath(classicalPath, quantumPath);\n } else {\n wallet = this.mnemonic.deriveOPWallet(this.addressType, index);\n }\n\n this.wallets.set(index, wallet);\n return wallet;\n }\n\n /**\n * Derive a wallet using standard (non-Unisat) derivation\n */\n public deriveStandardWallet(index: number): Wallet {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n\n return this.mnemonic.derive(index);\n }\n\n /**\n * Add new accounts to the keyring\n */\n public addAccounts(numberOfAccounts = 1): string[] {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n\n const newPublicKeys: string[] = [];\n let currentIndex = 0;\n\n while (newPublicKeys.length < numberOfAccounts) {\n if (!this.activeIndexes.includes(currentIndex)) {\n const wallet = this.deriveWallet(currentIndex);\n this.activeIndexes.push(currentIndex);\n newPublicKeys.push(wallet.toPublicKeyHex());\n }\n currentIndex++;\n }\n\n return newPublicKeys;\n }\n\n /**\n * Activate specific account indexes\n */\n public activateAccounts(indexes: number[]): string[] {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n\n const publicKeys: string[] = [];\n\n for (const index of indexes) {\n if (!this.activeIndexes.includes(index)) {\n const wallet = this.deriveWallet(index);\n this.activeIndexes.push(index);\n publicKeys.push(wallet.toPublicKeyHex());\n } else {\n const wallet = this.wallets.get(index);\n if (wallet !== undefined) {\n publicKeys.push(wallet.toPublicKeyHex());\n }\n }\n }\n\n return publicKeys;\n }\n\n /**\n * Get all active account public keys\n */\n public getAccounts(): string[] {\n return this.activeIndexes.map((index) => {\n const wallet = this.wallets.get(index);\n if (wallet === undefined) {\n throw new Error(`HdKeyring: Wallet at index ${index} not found`);\n }\n return wallet.toPublicKeyHex();\n });\n }\n\n /**\n * Get detailed account info for all active accounts\n */\n public getAccountsInfo(): AccountInfo[] {\n return this.activeIndexes.map((index) => {\n const wallet = this.wallets.get(index);\n if (wallet === undefined) {\n throw new Error(`HdKeyring: Wallet at index ${index} not found`);\n }\n\n const addresses: AccountAddresses = {\n p2pkh: wallet.legacy,\n p2wpkh: wallet.p2wpkh,\n p2tr: wallet.p2tr,\n p2shP2wpkh: wallet.segwitLegacy\n };\n\n return {\n index,\n publicKey: wallet.toPublicKeyHex(),\n quantumPublicKey: wallet.quantumPublicKeyHex,\n addresses\n };\n });\n }\n\n /**\n * Get quantum public key for an account\n */\n public getQuantumPublicKey(publicKey: string): string {\n const wallet = this.findWalletByPublicKey(publicKey);\n return wallet.quantumPublicKeyHex;\n }\n\n /**\n * Get the index for a public key\n */\n public getIndexByPublicKey(publicKey: string): number | null {\n for (const [index, wallet] of this.wallets.entries()) {\n if (wallet.toPublicKeyHex() === publicKey) {\n return index;\n }\n }\n return null;\n }\n\n /**\n * Get addresses for a specific public key\n */\n public getAddressesForPublicKey(publicKey: string): AccountAddresses {\n const wallet = this.findWalletByPublicKey(publicKey);\n return {\n p2pkh: wallet.legacy,\n p2wpkh: wallet.p2wpkh,\n p2tr: wallet.p2tr,\n p2shP2wpkh: wallet.segwitLegacy\n };\n }\n\n /**\n * Get an address for a public key and address type\n */\n public getAddress(publicKey: string, addressType: AddressTypes): string {\n const pubkeyBytes: Uint8Array = fromHexInternal(publicKey);\n return publicKeyToAddress(pubkeyBytes, addressType, this.network);\n }\n\n /**\n * Remove an account by public key\n */\n public removeAccount(publicKey: string): void {\n const index = this.getIndexByPublicKey(publicKey);\n if (index === null) {\n throw new Error(`HdKeyring: Account with public key ${publicKey} not found`);\n }\n\n const activeIdx = this.activeIndexes.indexOf(index);\n if (activeIdx !== -1) {\n this.activeIndexes.splice(activeIdx, 1);\n }\n this.wallets.delete(index);\n }\n\n /**\n * Export the private key for an account\n */\n public exportAccount(publicKey: string): string {\n const wallet = this.findWalletByPublicKey(publicKey);\n return wallet.toPrivateKeyHex();\n }\n\n /**\n * Sign a PSBT transaction\n */\n public signTransaction(psbt: Psbt, inputs: readonly ToSignInput[]): Psbt {\n for (const input of inputs) {\n const wallet = this.findWalletByPublicKey(input.publicKey);\n const psbtInput = psbt.data.inputs[input.index];\n\n if (psbtInput === undefined) {\n throw new Error(`HdKeyring: Input at index ${input.index} not found`);\n }\n\n const keypair = wallet.keypair;\n const sighashTypes = input.sighashTypes !== undefined ? [...input.sighashTypes] : undefined;\n\n if (isTaprootInput(psbtInput) && input.disableTweakSigner !== true) {\n // For taproot, use tweaked signer\n const internalPubkey: Uint8Array = wallet.publicKey.subarray(1, 33);\n const tweakedKeypair: UniversalSigner = keypair.tweak(createBytes32(internalPubkey));\n psbt.signInput(input.index, tweakedKeypair, sighashTypes);\n } else {\n psbt.signInput(input.index, keypair, sighashTypes);\n }\n }\n\n return psbt;\n }\n\n /**\n * Sign arbitrary data with ECDSA or Schnorr\n */\n public signData(publicKey: string, data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\n const wallet = this.findWalletByPublicKey(publicKey);\n const dataHash = createMessageHash(fromHexInternal(data));\n\n if (type === 'ecdsa') {\n return toHex(wallet.keypair.sign(dataHash));\n }\n\n if (wallet.keypair.signSchnorr === undefined) {\n throw new Error('HdKeyring: Schnorr signing not supported by this keypair');\n }\n\n return toHex(wallet.keypair.signSchnorr(dataHash));\n }\n\n /**\n * Get the Wallet for a public key\n */\n public getWallet(publicKey: string): Wallet {\n return this.findWalletByPublicKey(publicKey);\n }\n\n /**\n * Serialize the keyring state\n */\n public serialize(): HdKeyringOptions {\n return {\n mnemonic: this.mnemonic?.phrase,\n passphrase: this.passphrase,\n network: this.network,\n securityLevel: this.securityLevel,\n activeIndexes: [...this.activeIndexes],\n addressType: this.addressType,\n hdPath: this._hdPath\n };\n }\n\n /**\n * Get active indexes\n */\n public getActiveIndexes(): readonly number[] {\n return [...this.activeIndexes];\n }\n\n /**\n * Change the address type for new derivations\n */\n public setAddressType(addressType: AddressTypes): void {\n this.addressType = addressType;\n }\n\n /**\n * Get current address type\n */\n public getAddressType(): AddressTypes {\n return this.addressType;\n }\n\n /**\n * Get the security level\n */\n public getSecurityLevel(): MLDSASecurityLevel {\n return this.securityLevel;\n }\n\n /**\n * Get the network\n */\n public getNetwork(): Network {\n return this.network;\n }\n\n /**\n * Get paginated addresses for display\n */\n public getAddressesPage(page: number, perPage = 5): { address: string; index: number }[] {\n if (this.mnemonic === null) {\n throw new Error('HdKeyring: No mnemonic initialized');\n }\n\n const start = page * perPage;\n const end = start + perPage;\n const results: { address: string; index: number }[] = [];\n\n for (let i = start; i < end; i++) {\n let wallet: Wallet;\n\n if (this.isCustomHdPath()) {\n const classicalPath = `${this._hdPath}/${i}`;\n const coinType = this.network === networks.bitcoin ? 0 : 1;\n const quantumPath = `m/360'/${coinType}'/0'/0/${i}`;\n wallet = this.mnemonic.deriveCustomPath(classicalPath, quantumPath);\n } else {\n wallet = this.mnemonic.deriveOPWallet(this.addressType, i);\n }\n\n const address = this.getAddressFromWallet(wallet);\n results.push({ address, index: i });\n }\n\n return results;\n }\n\n /**\n * Get the chain code for a wallet\n */\n public getChainCode(publicKey: string): Uint8Array {\n const wallet = this.findWalletByPublicKey(publicKey);\n return Uint8Array.from(wallet.chainCode);\n }\n\n /**\n * Get ML-DSA keypair for quantum operations\n */\n public getMLDSAKeypair(publicKey: string): QuantumBIP32Interface {\n const wallet = this.findWalletByPublicKey(publicKey);\n return wallet.mldsaKeypair;\n }\n\n /**\n * Check if the current hdPath is a custom (non-standard) path\n */\n private isCustomHdPath(): boolean {\n // Standard BIP paths for common address types\n const standardPaths: Partial<Record<AddressTypes, string>> = {\n [AddressTypes.P2PKH]: \"m/44'/0'/0'/0\",\n [AddressTypes.P2WPKH]: \"m/84'/0'/0'/0\",\n [AddressTypes.P2TR]: \"m/86'/0'/0'/0\",\n [AddressTypes.P2SH_OR_P2SH_P2WPKH]: \"m/49'/0'/0'/0\"\n };\n\n const standardPath = standardPaths[this.addressType];\n\n // If no standard path exists for this address type, any non-empty path is \"custom\"\n if (standardPath === undefined) {\n return this._hdPath !== '';\n }\n\n // Also check without trailing /0 for base paths like m/84'/0'/0'\n const standardPathBase = standardPath.slice(0, -2); // Remove /0\n\n return !this._hdPath.includes(standardPathBase) && this._hdPath !== '';\n }\n\n private findWalletByPublicKey(publicKey: string): Wallet {\n for (const wallet of this.wallets.values()) {\n if (wallet.toPublicKeyHex() === publicKey) {\n return wallet;\n }\n }\n throw new Error(`HdKeyring: Wallet with public key ${publicKey} not found`);\n }\n\n private getAddressFromWallet(wallet: Wallet): string {\n switch (this.addressType) {\n case AddressTypes.P2PKH: {\n return wallet.legacy;\n }\n case AddressTypes.P2WPKH: {\n return wallet.p2wpkh;\n }\n case AddressTypes.P2TR: {\n return wallet.p2tr;\n }\n case AddressTypes.P2SH_OR_P2SH_P2WPKH: {\n return wallet.segwitLegacy;\n }\n default: {\n return wallet.p2tr;\n }\n }\n }\n}\n","/**\n * OPNet Wallet SDK - Simple Keyring\n * Single key pair management with quantum-resistant (ML-DSA) support.\n * For WIF/private key imports, requires either:\n * 1. A quantum private key to be assigned on import\n * 2. Generation of a fresh quantum key pair\n */\n\nimport { crypto as bitcoinCrypto, isTaprootInput, type Network, networks, Psbt } from '@btc-vision/bitcoin';\nimport {\n AddressTypes,\n EcKeyPair,\n MLDSASecurityLevel,\n QuantumBIP32Factory,\n type QuantumBIP32Interface\n} from '@btc-vision/transaction';\nimport { getMLDSAConfig } from '@btc-vision/bip32';\nimport { type UniversalSigner, createBytes32, createMessageHash, createSignature, createSchnorrSignature, toHex, fromHexInternal, concatBytes } from '@btc-vision/ecpair';\nimport { publicKeyToAddress } from '@/address';\nimport type { AccountAddresses, SimpleKeyringOptions, ToSignInput } from '@/types';\n\n// Chain code is always 32 bytes\nconst CHAINCODE_BYTES = 32;\n\n/**\n * Simple Keyring for single key pair management with quantum support.\n * When importing from WIF or private key, a quantum key must be provided or generated.\n */\nexport class SimpleKeyring {\n public static readonly type = 'Simple Key Pair';\n public readonly type = SimpleKeyring.type;\n\n private readonly network: Network;\n private readonly securityLevel: MLDSASecurityLevel;\n private keypair: UniversalSigner | null = null;\n private quantumKeypair: QuantumBIP32Interface | null = null;\n private chainCode: Uint8Array = new Uint8Array(32);\n\n constructor(options: Partial<SimpleKeyringOptions>) {\n if (!options?.network) {\n throw new Error('SimpleKeyring: Network option is required');\n }\n\n this.network = options.network;\n this.securityLevel = options?.securityLevel ?? MLDSASecurityLevel.LEVEL2;\n\n if (options?.privateKey !== undefined) {\n this.importPrivateKey(options.privateKey, options.quantumPrivateKey);\n }\n }\n\n /**\n * Generate a new random key pair with quantum support\n */\n public static generate(\n network: Network = networks.bitcoin,\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\n ): SimpleKeyring {\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\n\n // Generate random classical keypair\n keyring.keypair = EcKeyPair.generateRandomKeyPair(network);\n\n // Generate random quantum keypair\n const seed: Uint8Array = crypto.getRandomValues(new Uint8Array(64));\n keyring.quantumKeypair = QuantumBIP32Factory.fromSeed(seed, network, securityLevel);\n keyring.chainCode = Uint8Array.from(keyring.quantumKeypair.chainCode);\n\n return keyring;\n }\n\n /**\n * Import from WIF (Wallet Import Format) with optional quantum key.\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\n */\n public static fromWIF(\n wif: string,\n quantumPrivateKey: string | undefined,\n network: Network = networks.bitcoin,\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\n ): SimpleKeyring {\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\n keyring.keypair = EcKeyPair.fromWIF(wif, network);\n\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\n keyring.importQuantumKey(quantumPrivateKey);\n }\n // Do NOT auto-generate quantum key - user must explicitly migrate\n\n return keyring;\n }\n\n /**\n * Import from hex private key with optional quantum key.\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\n */\n public static fromPrivateKey(\n privateKeyHex: string,\n quantumPrivateKey: string | undefined,\n network: Network = networks.bitcoin,\n securityLevel: MLDSASecurityLevel = MLDSASecurityLevel.LEVEL2\n ): SimpleKeyring {\n const keyring = new SimpleKeyring({ network, securityLevel, privateKey: '' });\n keyring.keypair = EcKeyPair.fromPrivateKey(fromHexInternal(privateKeyHex), network);\n\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\n keyring.importQuantumKey(quantumPrivateKey);\n }\n // Do NOT auto-generate quantum key - user must explicitly migrate\n\n return keyring;\n }\n\n /**\n * Import a private key (WIF or hex format).\n * If no quantum key is provided, the keyring will NOT have a quantum keypair.\n * The quantum key must be explicitly set later via importQuantumKey() or generateFreshQuantumKey().\n */\n public importPrivateKey(privateKey: string, quantumPrivateKey?: string): void {\n if (privateKey === '') {\n return;\n }\n\n // Determine if WIF or hex\n if (privateKey.length === 64) {\n // Hex format\n this.keypair = EcKeyPair.fromPrivateKey(fromHexInternal(privateKey), this.network);\n } else {\n // WIF format\n this.keypair = EcKeyPair.fromWIF(privateKey, this.network);\n }\n\n if (quantumPrivateKey !== undefined && quantumPrivateKey !== '') {\n this.importQuantumKey(quantumPrivateKey);\n }\n // Do NOT auto-generate quantum key - user must explicitly migrate\n }\n\n /**\n * Import an existing quantum private key.\n * Supports both:\n * - Key only (e.g., 2560 bytes for ML-DSA-44)\n * - Key + chaincode (e.g., 2560 + 32 = 2592 bytes for ML-DSA-44)\n */\n public importQuantumKey(quantumPrivateKeyHex: string): void {\n const privateKeyBytes: Uint8Array = fromHexInternal(quantumPrivateKeyHex);\n\n // Get expected MLDSA private key size for the security level\n const mldsaConfig = getMLDSAConfig(this.securityLevel, this.network);\n const expectedKeySize: number = mldsaConfig.privateKeySize;\n const expectedKeyWithChaincodeSize: number = expectedKeySize + CHAINCODE_BYTES;\n\n // Determine if chaincode is present based on the key length\n const hasChaincode: boolean = privateKeyBytes.length === expectedKeyWithChaincodeSize;\n const isKeyOnly: boolean = privateKeyBytes.length === expectedKeySize;\n\n if (!hasChaincode && !isKeyOnly) {\n throw new Error(\n `Invalid quantum key length: ${privateKeyBytes.length} bytes. ` +\n `Expected ${expectedKeySize} bytes (key only) or ${expectedKeyWithChaincodeSize} bytes (key + chaincode).`\n );\n }\n\n if (hasChaincode) {\n // Extract chaincode from the end of the key\n this.chainCode = privateKeyBytes.slice(-CHAINCODE_BYTES);\n const keyWithoutChainCode: Uint8Array = privateKeyBytes.slice(0, -CHAINCODE_BYTES);\n this.quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\n keyWithoutChainCode,\n this.chainCode,\n this.network,\n this.securityLevel\n );\n } else {\n // Key only - generate a random chaincode\n this.chainCode = crypto.getRandomValues(new Uint8Array(CHAINCODE_BYTES));\n this.quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\n privateKeyBytes,\n this.chainCode,\n this.network,\n this.securityLevel\n );\n }\n }\n\n /**\n * Generate a fresh quantum key pair\n */\n public generateFreshQuantumKey(): void {\n const seed: Uint8Array = crypto.getRandomValues(new Uint8Array(64));\n this.quantumKeypair = QuantumBIP32Factory.fromSeed(seed, this.network, this.securityLevel);\n this.chainCode = Uint8Array.from(this.quantumKeypair.chainCode);\n }\n\n /**\n * Check if keyring has both classical and quantum keys\n */\n public hasKeys(): boolean {\n return this.keypair !== null && this.quantumKeypair !== null;\n }\n\n /**\n * Check if keyring has the classical keypair (may or may not have quantum key)\n */\n public hasClassicalKey(): boolean {\n return this.keypair !== null;\n }\n\n /**\n * Check if keyring has a quantum keypair\n */\n public hasQuantumKey(): boolean {\n return this.quantumKeypair !== null;\n }\n\n /**\n * Check if quantum migration is needed (has classical but no quantum key)\n */\n public needsQuantumMigration(): boolean {\n return this.keypair !== null && this.quantumKeypair === null;\n }\n\n /**\n * Get the classical public key\n */\n public getPublicKey(): string {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n return toHex(this.keypair.publicKey);\n }\n\n /**\n * Get the quantum public key\n * @throws Error if no quantum keypair is initialized\n */\n public getQuantumPublicKey(): string {\n if (this.quantumKeypair === null) {\n throw new Error('SimpleKeyring: No quantum keypair initialized');\n }\n return toHex(this.quantumKeypair.publicKey);\n }\n\n /**\n * Get the quantum public key if available, or undefined if not initialized\n */\n public getQuantumPublicKeyOrUndefined(): string | undefined {\n if (this.quantumKeypair === null) {\n return undefined;\n }\n return toHex(this.quantumKeypair.publicKey);\n }\n\n /**\n * Get the quantum public key hash (universal identifier)\n */\n public getQuantumPublicKeyHash(): string {\n if (this.quantumKeypair === null) {\n throw new Error('SimpleKeyring: No quantum keypair initialized');\n }\n // SHA256 hash of the quantum public key\n const hash: Uint8Array = bitcoinCrypto.sha256(this.quantumKeypair.publicKey);\n return toHex(hash);\n }\n\n /**\n * Clear the quantum keypair (used for reverting failed imports)\n */\n public clearQuantumKey(): void {\n this.quantumKeypair = null;\n this.chainCode = new Uint8Array(32);\n }\n\n /**\n * Get all accounts (returns array with single public key)\n */\n public getAccounts(): string[] {\n if (this.keypair === null) {\n return [];\n }\n return [this.getPublicKey()];\n }\n\n /**\n * Get addresses for the key pair\n */\n public getAddresses(): AccountAddresses {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n\n const pubkey = this.keypair.publicKey;\n\n return {\n p2pkh: publicKeyToAddress(pubkey, AddressTypes.P2PKH, this.network),\n p2wpkh: publicKeyToAddress(pubkey, AddressTypes.P2WPKH, this.network),\n p2tr: publicKeyToAddress(pubkey, AddressTypes.P2TR, this.network),\n p2shP2wpkh: publicKeyToAddress(pubkey, AddressTypes.P2SH_OR_P2SH_P2WPKH, this.network)\n };\n }\n\n /**\n * Get an address for a specific type\n */\n public getAddress(addressType: AddressTypes): string {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n return publicKeyToAddress(this.keypair.publicKey, addressType, this.network);\n }\n\n /**\n * Export the classical private key\n */\n public exportPrivateKey(): string {\n if (this.keypair?.privateKey === undefined) {\n throw new Error('SimpleKeyring: No private key available');\n }\n return toHex(this.keypair.privateKey);\n }\n\n /**\n * Export the quantum private key with chain code (for backup/restore)\n */\n public exportQuantumPrivateKey(): string {\n if (this.quantumKeypair?.privateKey === undefined) {\n throw new Error('SimpleKeyring: No quantum private key available');\n }\n // Combine private key and chain code for full export\n return toHex(concatBytes(this.quantumKeypair.privateKey, this.chainCode));\n }\n\n /**\n * Export the raw quantum private key WITHOUT chain code (for Wallet.fromWif)\n */\n public exportRawQuantumPrivateKey(): string {\n if (this.quantumKeypair?.privateKey === undefined) {\n throw new Error('SimpleKeyring: No quantum private key available');\n }\n return toHex(this.quantumKeypair.privateKey);\n }\n\n /**\n * Export the chain code (for use with Wallet.fromWif separately)\n */\n public exportChainCode(): Uint8Array {\n return this.chainCode;\n }\n\n /**\n * Export WIF format\n */\n public exportWIF(): string {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n return this.keypair.toWIF();\n }\n\n /**\n * Sign a PSBT transaction\n */\n public signTransaction(psbt: Psbt, inputs: readonly ToSignInput[]): Psbt {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n\n for (const input of inputs) {\n const psbtInput = psbt.data.inputs[input.index];\n\n if (psbtInput === undefined) {\n throw new Error(`SimpleKeyring: Input at index ${input.index} not found`);\n }\n\n if (isTaprootInput(psbtInput) && input.disableTweakSigner !== true) {\n const tweakedSigner: UniversalSigner = this.keypair.tweak(createBytes32(this.keypair.publicKey.subarray(1, 33)));\n psbt.signInput(input.index, tweakedSigner, input.sighashTypes ? [...input.sighashTypes] : undefined);\n } else {\n psbt.signInput(input.index, this.keypair, input.sighashTypes ? [...input.sighashTypes] : undefined);\n }\n }\n\n return psbt;\n }\n\n /**\n * Sign arbitrary data with ECDSA or Schnorr\n */\n public signData(data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n\n const dataHash = createMessageHash(fromHexInternal(data));\n\n if (type === 'ecdsa') {\n return toHex(this.keypair.sign(dataHash));\n }\n\n if (this.keypair.signSchnorr === undefined) {\n throw new Error('SimpleKeyring: Schnorr signing not supported by this keypair');\n }\n\n return toHex(this.keypair.signSchnorr(dataHash));\n }\n\n /**\n * Verify a signature\n */\n public verify(data: string, signature: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): boolean {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n\n const dataHash = createMessageHash(fromHexInternal(data));\n\n if (type === 'ecdsa') {\n return this.keypair.verify(dataHash, createSignature(fromHexInternal(signature)));\n }\n\n return this.keypair.verifySchnorr(dataHash, createSchnorrSignature(fromHexInternal(signature)));\n }\n\n /**\n * Get the keypair\n */\n public getKeypair(): UniversalSigner {\n if (this.keypair === null) {\n throw new Error('SimpleKeyring: No keypair initialized');\n }\n return this.keypair;\n }\n\n /**\n * Get the quantum keypair\n */\n public getQuantumKeypair(): QuantumBIP32Interface {\n if (this.quantumKeypair === null) {\n throw new Error('SimpleKeyring: No quantum keypair initialized');\n }\n return this.quantumKeypair;\n }\n\n /**\n * Get the chain code\n */\n public getChainCode(): Uint8Array {\n return this.chainCode;\n }\n\n /**\n * Get the security level\n */\n public getSecurityLevel(): MLDSASecurityLevel {\n return this.securityLevel;\n }\n\n /**\n * Get the network\n */\n public getNetwork(): Network {\n return this.network;\n }\n\n /**\n * Serialize the keyring state (excludes private keys for safety)\n */\n public serialize(): SimpleKeyringOptions {\n let quantumPrivateKey: string | undefined;\n try {\n quantumPrivateKey = this.exportQuantumPrivateKey();\n } catch {\n // No quantum key available - that's fine for wallets that haven't migrated\n quantumPrivateKey = undefined;\n }\n\n return {\n privateKey: this.exportPrivateKey(),\n quantumPrivateKey,\n network: this.network,\n securityLevel: this.securityLevel\n };\n }\n\n /**\n * Remove the key (clear keyring)\n */\n public clear(): void {\n this.keypair = null;\n this.quantumKeypair = null;\n this.chainCode = new Uint8Array(32);\n }\n}\n","/**\r\n * OPNet Wallet SDK - Unified Key Export\r\n * Provides a single export format that contains both classical and quantum keys.\r\n * This allows users to export their complete wallet state in one operation.\r\n */\r\n\r\nimport { crypto as bitcoinCrypto, type Network, networks } from '@btc-vision/bitcoin';\r\nimport { EcKeyPair, MLDSASecurityLevel, QuantumBIP32Factory, WalletNetworks } from '@btc-vision/transaction';\r\nimport { fromHexInternal, toHex, type UniversalSigner } from '@btc-vision/ecpair';\r\nimport type { ExportedWallet } from '@/types';\r\nimport { toNetwork, toNetworkType } from '@/network';\r\n\r\nconst EXPORT_VERSION = 1;\r\nconst MAGIC_HEADER = 'OPNET_WALLET_V1';\r\n\r\n/**\r\n * Unified wallet export format\r\n */\r\nexport interface UnifiedWalletExport {\r\n readonly magic: string;\r\n readonly version: number;\r\n readonly network: string;\r\n readonly classical: {\r\n readonly privateKey: string;\r\n readonly publicKey: string;\r\n };\r\n readonly quantum: {\r\n readonly privateKey: string;\r\n readonly publicKey: string;\r\n readonly securityLevel: MLDSASecurityLevel;\r\n readonly chainCode: string;\r\n };\r\n readonly checksum: string;\r\n}\r\n\r\n/**\r\n * Calculate checksum for wallet export data\r\n */\r\nconst textEncoder = new TextEncoder();\r\n\r\nfunction calculateChecksum(data: string): string {\r\n const hash: Uint8Array = bitcoinCrypto.sha256(textEncoder.encode(data));\r\n return toHex(hash.subarray(0, 4));\r\n}\r\n\r\n/**\r\n * Get network name from Network object (serialized as WalletNetworks enum value)\r\n */\r\nfunction getNetworkName(network: Network): string {\r\n return toNetworkType(network);\r\n}\r\n\r\n/**\r\n * Get Network object from network name (WalletNetworks enum value)\r\n */\r\nfunction getNetworkFromName(name: string): Network {\r\n const walletNetwork = name as WalletNetworks;\r\n\r\n // Validate it's a known enum value, fall back to mainnet for unknown\r\n if (Object.values(WalletNetworks).includes(walletNetwork)) {\r\n return toNetwork(walletNetwork);\r\n }\r\n\r\n return networks.bitcoin;\r\n}\r\n\r\n/**\r\n * Export wallet keys to unified format\r\n */\r\nexport function exportWallet(\r\n classicalPrivateKey: Uint8Array,\r\n classicalPublicKey: Uint8Array,\r\n quantumPrivateKey: Uint8Array,\r\n quantumPublicKey: Uint8Array,\r\n chainCode: Uint8Array,\r\n securityLevel: MLDSASecurityLevel,\r\n network: Network\r\n): UnifiedWalletExport {\r\n const exportData: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: MAGIC_HEADER,\r\n version: EXPORT_VERSION,\r\n network: getNetworkName(network),\r\n classical: {\r\n privateKey: toHex(classicalPrivateKey),\r\n publicKey: toHex(classicalPublicKey)\r\n },\r\n quantum: {\r\n privateKey: toHex(quantumPrivateKey),\r\n publicKey: toHex(quantumPublicKey),\r\n securityLevel,\r\n chainCode: toHex(chainCode)\r\n }\r\n };\r\n\r\n const dataString = JSON.stringify(exportData);\r\n const checksum = calculateChecksum(dataString);\r\n\r\n return {\r\n ...exportData,\r\n checksum\r\n };\r\n}\r\n\r\n/**\r\n * Import wallet keys from unified format\r\n */\r\nexport function importWallet(exportData: UnifiedWalletExport): {\r\n keypair: UniversalSigner;\r\n quantumKeypair: ReturnType<typeof QuantumBIP32Factory.fromPrivateKey>;\r\n network: Network;\r\n securityLevel: MLDSASecurityLevel;\r\n chainCode: Uint8Array;\r\n} {\r\n // Validate magic header\r\n if (exportData.magic !== MAGIC_HEADER) {\r\n throw new Error('Invalid wallet export format: wrong magic header');\r\n }\r\n\r\n // Validate version\r\n if (exportData.version !== EXPORT_VERSION) {\r\n throw new Error(`Unsupported wallet export version: ${exportData.version}`);\r\n }\r\n\r\n // Validate checksum\r\n const dataWithoutChecksum: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: exportData.magic,\r\n version: exportData.version,\r\n network: exportData.network,\r\n classical: exportData.classical,\r\n quantum: exportData.quantum\r\n };\r\n const expectedChecksum = calculateChecksum(JSON.stringify(dataWithoutChecksum));\r\n if (exportData.checksum !== expectedChecksum) {\r\n throw new Error('Invalid wallet export: checksum mismatch');\r\n }\r\n\r\n const network: Network = getNetworkFromName(exportData.network);\r\n const chainCode: Uint8Array = fromHexInternal(exportData.quantum.chainCode);\r\n\r\n // Restore classical keypair\r\n const classicalPrivateKey: Uint8Array = fromHexInternal(exportData.classical.privateKey);\r\n const keypair: UniversalSigner = EcKeyPair.fromPrivateKey(classicalPrivateKey, network);\r\n\r\n // Restore quantum keypair\r\n const quantumPrivateKey: Uint8Array = fromHexInternal(exportData.quantum.privateKey);\r\n const quantumKeypair = QuantumBIP32Factory.fromPrivateKey(\r\n quantumPrivateKey,\r\n chainCode,\r\n network,\r\n exportData.quantum.securityLevel\r\n );\r\n\r\n return {\r\n keypair,\r\n quantumKeypair,\r\n network,\r\n securityLevel: exportData.quantum.securityLevel,\r\n chainCode\r\n };\r\n}\r\n\r\n/**\r\n * Serialize unified export to string (base64 encoded JSON)\r\n */\r\nexport function serializeExport(exportData: UnifiedWalletExport): string {\r\n const json: string = JSON.stringify(exportData);\r\n return btoa(json);\r\n}\r\n\r\n/**\r\n * Deserialize string to unified export\r\n */\r\nexport function deserializeExport(serialized: string): UnifiedWalletExport {\r\n try {\r\n const json: string = atob(serialized);\r\n return JSON.parse(json) as UnifiedWalletExport;\r\n } catch {\r\n throw new Error('Invalid wallet export: failed to deserialize');\r\n }\r\n}\r\n\r\n/**\r\n * Export wallet to portable string format\r\n */\r\nexport function exportWalletToString(\r\n classicalPrivateKey: Uint8Array,\r\n classicalPublicKey: Uint8Array,\r\n quantumPrivateKey: Uint8Array,\r\n quantumPublicKey: Uint8Array,\r\n chainCode: Uint8Array,\r\n securityLevel: MLDSASecurityLevel,\r\n network: Network\r\n): string {\r\n const exportData = exportWallet(\r\n classicalPrivateKey,\r\n classicalPublicKey,\r\n quantumPrivateKey,\r\n quantumPublicKey,\r\n chainCode,\r\n securityLevel,\r\n network\r\n );\r\n return serializeExport(exportData);\r\n}\r\n\r\n/**\r\n * Import wallet from portable string format\r\n */\r\nexport function importWalletFromString(serialized: string): {\r\n keypair: UniversalSigner;\r\n quantumKeypair: ReturnType<typeof QuantumBIP32Factory.fromPrivateKey>;\r\n network: Network;\r\n securityLevel: MLDSASecurityLevel;\r\n chainCode: Uint8Array;\r\n} {\r\n const exportData = deserializeExport(serialized);\r\n return importWallet(exportData);\r\n}\r\n\r\n/**\r\n * Validate export data without importing\r\n */\r\nexport function validateExport(exportData: UnifiedWalletExport): boolean {\r\n try {\r\n if (exportData.magic !== MAGIC_HEADER) {\r\n return false;\r\n }\r\n\r\n if (exportData.version !== EXPORT_VERSION) {\r\n return false;\r\n }\r\n\r\n const dataWithoutChecksum: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: exportData.magic,\r\n version: exportData.version,\r\n network: exportData.network,\r\n classical: exportData.classical,\r\n quantum: exportData.quantum\r\n };\r\n const expectedChecksum = calculateChecksum(JSON.stringify(dataWithoutChecksum));\r\n\r\n return exportData.checksum === expectedChecksum;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Convert legacy ExportedWallet format to unified format\r\n */\r\nexport function fromLegacyExport(legacy: ExportedWallet, network: Network): UnifiedWalletExport {\r\n const classicalPrivateKey: Uint8Array = fromHexInternal(legacy.classicalPrivateKey);\r\n const keypair: UniversalSigner = EcKeyPair.fromPrivateKey(classicalPrivateKey, network);\r\n\r\n const exportData: Omit<UnifiedWalletExport, 'checksum'> = {\r\n magic: MAGIC_HEADER,\r\n version: EXPORT_VERSION,\r\n network: getNetworkName(network),\r\n classical: {\r\n privateKey: legacy.classicalPrivateKey,\r\n publicKey: toHex(keypair.publicKey)\r\n },\r\n quantum: {\r\n privateKey: legacy.quantumPrivateKey,\r\n publicKey: legacy.quantumPublicKey,\r\n securityLevel: legacy.securityLevel,\r\n chainCode: legacy.chainCode\r\n }\r\n };\r\n\r\n const dataString = JSON.stringify(exportData);\r\n const checksum = calculateChecksum(dataString);\r\n\r\n return {\r\n ...exportData,\r\n checksum\r\n };\r\n}\r\n","import { createNobleBackend, type NobleBackend } from '@btc-vision/ecpair';\n\nlet backend: NobleBackend | undefined;\n\nexport function getNobleBackend(): NobleBackend {\n backend ??= createNobleBackend();\n return backend;\n}\n","/**\n * OPNet Wallet SDK - Message Signing Module\n * Message signing and verification using classical (Schnorr/ECDSA) and quantum (ML-DSA) signatures.\n * Uses @btc-vision/transaction MessageSigner for all operations.\n */\n\nimport { type Network, networks } from '@btc-vision/bitcoin';\nimport {\n MessageSigner,\n MLDSASecurityLevel,\n QuantumBIP32Factory,\n type QuantumBIP32Interface\n} from '@btc-vision/transaction';\nimport { type UniversalSigner, createMessageHash, createPublicKey, createSignature } from '@btc-vision/ecpair';\nimport { getNobleBackend } from './backend.js';\nimport type { SignatureType, SignedMessage } from '@/types';\n\n/**\n * Message input type - can be string or Uint8Array\n */\nexport type MessageInput = string | Uint8Array;\n\n/**\n * Result of ML-DSA signature operation\n */\nexport interface MLDSASignatureResult {\n readonly message: MessageInput;\n readonly signature: Uint8Array;\n readonly publicKey: Uint8Array;\n readonly securityLevel: MLDSASecurityLevel;\n}\n\n/**\n * Result of Schnorr signature operation\n */\nexport interface SchnorrSignatureResult {\n readonly message: MessageInput;\n readonly signature: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\n/**\n * Sign a message with ML-DSA (quantum-resistant)\n */\nexport function signMLDSA(keypair: QuantumBIP32Interface, message: MessageInput): MLDSASignatureResult {\n const result = MessageSigner.signMLDSAMessage(keypair, message);\n return {\n message: result.message,\n signature: result.signature,\n publicKey: result.publicKey,\n securityLevel: result.securityLevel\n };\n}\n\n/**\n * Verify an ML-DSA signature\n */\nexport function verifyMLDSA(\n publicKey: Uint8Array,\n chainCode: Uint8Array,\n network: Network,\n securityLevel: MLDSASecurityLevel,\n message: MessageInput,\n signature: Uint8Array\n): boolean {\n const keypair = QuantumBIP32Factory.fromPublicKey(publicKey, chainCode, network, securityLevel);\n return MessageSigner.verifyMLDSASignature(keypair, message, signature);\n}\n\n/**\n * Verify an ML-DSA signature using an existing keypair\n */\nexport function verifyMLDSAWithKeypair(\n keypair: QuantumBIP32Interface,\n message: MessageInput,\n signature: Uint8Array\n): boolean {\n return MessageSigner.verifyMLDSASignature(keypair, message, signature);\n}\n\n/**\n * Sign a message with Schnorr (classical)\n */\nexport function signSchnorr(keypair: UniversalSigner, message: MessageInput): SchnorrSignatureResult {\n const result = MessageSigner.signMessage(keypair, message);\n return {\n message: result.message,\n signature: result.signature,\n publicKey: keypair.publicKey\n };\n}\n\n/**\n * Verify a Schnorr signature\n */\nexport function verifySchnorr(publicKey: Uint8Array, message: MessageInput, signature: Uint8Array): boolean {\n return MessageSigner.verifySignature(publicKey, message, signature);\n}\n\n/**\n * Sign a message with tweaked key for Taproot\n */\nexport function signTweakedSchnorr(\n keypair: UniversalSigner,\n message: MessageInput,\n network: Network = networks.bitcoin\n): SchnorrSignatureResult {\n const result = MessageSigner.tweakAndSignMessage(keypair, message, network);\n return {\n message: result.message,\n signature: result.signature,\n publicKey: keypair.publicKey\n };\n}\n\n/**\n * Verify a tweaked Schnorr signature\n */\nexport function verifyTweakedSchnorr(\n publicKey: Uint8Array,\n message: MessageInput,\n signature: Uint8Array\n): boolean {\n return MessageSigner.tweakAndVerifySignature(publicKey, message, signature);\n}\n\n/**\n * Sign message with automatic type selection\n */\nexport function signMessage(\n keypair: UniversalSigner | QuantumBIP32Interface,\n message: MessageInput,\n signatureType: SignatureType\n): SignedMessage {\n const messageBytes: Uint8Array = toUint8Array(message);\n switch (signatureType) {\n case 'mldsa': {\n if (!isQuantumKeypair(keypair)) {\n throw new Error('ML-DSA signing requires a quantum keypair');\n }\n const result = signMLDSA(keypair, message);\n return {\n message: messageBytes,\n signature: result.signature,\n publicKey: result.publicKey,\n signatureType: 'mldsa',\n securityLevel: result.securityLevel\n };\n }\n case 'schnorr': {\n if (isQuantumKeypair(keypair)) {\n throw new Error('Schnorr signing requires a classical keypair');\n }\n const result = signSchnorr(keypair, message);\n return {\n message: messageBytes,\n signature: result.signature,\n publicKey: result.publicKey,\n signatureType: 'schnorr'\n };\n }\n case 'ecdsa': {\n if (isQuantumKeypair(keypair)) {\n throw new Error('ECDSA signing requires a classical keypair');\n }\n const hash = MessageSigner.sha256(messageBytes);\n const signature = keypair.sign(createMessageHash(hash));\n return {\n message: messageBytes,\n signature,\n publicKey: keypair.publicKey,\n signatureType: 'ecdsa'\n };\n }\n }\n}\n\n/**\n * Verify message with automatic type detection\n */\nexport function verifyMessage(\n publicKey: Uint8Array,\n message: MessageInput,\n signature: Uint8Array,\n signatureType: SignatureType,\n chainCode?: Uint8Array,\n network?: Network,\n securityLevel?: MLDSASecurityLevel\n): boolean {\n switch (signatureType) {\n case 'mldsa': {\n if (chainCode === undefined || network === undefined || securityLevel === undefined) {\n throw new Error('ML-DSA verification requires chainCode, network, and securityLevel');\n }\n return verifyMLDSA(publicKey, chainCode, network, securityLevel, message, signature);\n }\n case 'schnorr': {\n return verifySchnorr(publicKey, message, signature);\n }\n case 'ecdsa': {\n const ecdsaBytes: Uint8Array = toUint8Array(message);\n const hash: Uint8Array = MessageSigner.sha256(ecdsaBytes);\n return getNobleBackend().verify(createMessageHash(hash), createPublicKey(publicKey), createSignature(signature));\n }\n }\n}\n\n/**\n * Type guard to check if keypair is quantum\n */\nfunction isQuantumKeypair(keypair: UniversalSigner | QuantumBIP32Interface): keypair is QuantumBIP32Interface {\n return 'securityLevel' in keypair && 'chainCode' in keypair;\n}\n\nconst textEncoder = new TextEncoder();\n\nfunction toUint8Array(message: MessageInput): Uint8Array {\n if (typeof message === 'string') {\n return textEncoder.encode(message);\n }\n return message;\n}\n\n// Re-export MessageSigner for direct usage\nexport { MessageSigner };\n","/**\n * OPNet Wallet SDK - BIP322 Message Signing\n * BIP322 simple message signing and verification.\n * Reference: https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\n */\n\nimport {\n address as bitcoinAddress,\n alloc,\n concat,\n crypto as bitcoinCrypto,\n fromHex,\n type Bytes32,\n type Network,\n type PublicKey,\n type Satoshi,\n type Script,\n Psbt,\n PsbtTransaction,\n script as bitcoinScript,\n toSatoshi,\n Transaction,\n type ValidateSigFunction,\n} from '@btc-vision/bitcoin';\nimport { type MessageHash, createMessageHash, createPublicKey, createSchnorrSignature, createSignature, createXOnlyPublicKey } from '@btc-vision/ecpair';\nimport { AddressTypes, WalletNetworks } from '@btc-vision/transaction';\nimport { detectAddressType } from '@/address';\nimport { toNetwork } from '@/network';\nimport type { Bip322Signature } from '@/types';\nimport { getNobleBackend } from './backend.js';\n\nconst textEncoder = new TextEncoder();\nconst ZERO_SATOSHI: Satoshi = toSatoshi(0n);\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\nfunction fromBase64Bytes(base64: string): Uint8Array {\n const binary: string = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Supported address types for BIP322 signing\n */\nconst SUPPORTED_ADDRESS_TYPES = [AddressTypes.P2WPKH, AddressTypes.P2TR];\n\n/**\n * Compute the BIP322 message hash\n */\nfunction computeBip322Hash(message: string | Uint8Array): Uint8Array {\n const tag = 'BIP0322-signed-message';\n const tagHash = bitcoinCrypto.sha256(textEncoder.encode(tag));\n const messageBytes: Uint8Array = typeof message === 'string' ? textEncoder.encode(message) : message;\n return bitcoinCrypto.sha256(concat([tagHash, tagHash, messageBytes]));\n}\n\n/**\n * Encode a buffer as a variable-length string for witness serialization\n */\nfunction encodeVarString(buf: Uint8Array): Uint8Array {\n const varint = bitcoinScript.number.encode(buf.length);\n return concat([varint, buf]);\n}\n\n/**\n * Generate a PSBT for BIP322 simple message signing\n */\nexport function generateBip322Psbt(message: string | Uint8Array, address: string, network: Network): Psbt {\n const outputScript = bitcoinAddress.toOutputScript(address, network);\n const addressType = detectAddressType(address, network);\n\n if (addressType === null || !SUPPORTED_ADDRESS_TYPES.includes(addressType)) {\n throw new Error(`BIP322: Address type not supported for signing. Got: ${String(addressType)}`);\n }\n\n const messageHash = computeBip322Hash(message);\n const prevoutHash = alloc(32) as Bytes32;\n const prevoutIndex = 0xffffffff;\n const sequence = 0;\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\n\n // Create \"to spend\" transaction\n const txToSpend = new Transaction();\n txToSpend.version = 0;\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\n\n // Create PSBT to sign\n const psbt = new Psbt({ network });\n psbt.setVersion(0);\n psbt.addInput({\n hash: txToSpend.getHash(),\n index: 0,\n sequence: 0,\n witnessUtxo: {\n script: outputScript as Script,\n value: ZERO_SATOSHI\n }\n });\n psbt.addOutput({\n script: fromHex('6a') as Script, // OP_RETURN\n value: ZERO_SATOSHI\n });\n\n return psbt;\n}\n\n/**\n * Extract signature from a signed BIP322 PSBT\n */\nexport function extractBip322Signature(psbt: Psbt): string {\n const tx = psbt.extractTransaction();\n const witness = tx.ins[0]?.witness;\n\n if (witness === undefined || witness.length === 0) {\n throw new Error('BIP322: No witness data found in signed transaction');\n }\n\n // Encode witness stack\n const varintLength = bitcoinScript.number.encode(witness.length);\n const encodedWitness = concat([varintLength, ...witness.map((w) => encodeVarString(w))]);\n\n return toBase64(encodedWitness);\n}\n\n/**\n * Sign a message using BIP322 simple format\n */\nexport async function signBip322Message(\n message: string | Uint8Array,\n address: string,\n network: Network,\n signPsbt: (psbt: Psbt) => Promise<Psbt>\n): Promise<string> {\n const psbt = generateBip322Psbt(message, address, network);\n const signedPsbt = await signPsbt(psbt);\n signedPsbt.finalizeAllInputs();\n return extractBip322Signature(signedPsbt);\n}\n\n/**\n * ECDSA signature validator\n */\nconst ecdsaValidator: ValidateSigFunction = (pubkey: PublicKey, msghash: MessageHash, signature: Uint8Array): boolean => {\n try {\n const decoded = bitcoinScript.signature.decode(signature);\n return getNobleBackend().verify(createMessageHash(msghash), createPublicKey(pubkey), createSignature(decoded.signature));\n } catch {\n return false;\n }\n};\n\n/**\n * Schnorr signature validator\n */\nfunction schnorrValidator(pubkey: Uint8Array, msghash: Uint8Array, signature: Uint8Array): boolean {\n try {\n const xOnlyPubkey = pubkey.length === 33 ? pubkey.subarray(1, 33) : pubkey;\n return getNobleBackend().verifySchnorr(createMessageHash(msghash), createXOnlyPublicKey(xOnlyPubkey), createSchnorrSignature(signature));\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP322 simple message signature for P2TR addresses\n */\nfunction verifyBip322P2TR(address: string, message: string | Uint8Array, signature: string, network: Network): boolean {\n try {\n const outputScript = bitcoinAddress.toOutputScript(address, network);\n const messageHash = computeBip322Hash(message);\n\n const prevoutHash = alloc(32) as Bytes32;\n const prevoutIndex = 0xffffffff;\n const sequence = 0;\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\n\n // Reconstruct \"to spend\" transaction\n const txToSpend = new Transaction();\n txToSpend.version = 0;\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\n\n // Decode signature\n const signatureData = fromBase64Bytes(signature);\n const decompiled = bitcoinScript.decompile(signatureData.subarray(1));\n\n if (!Array.isArray(decompiled) || decompiled.length === 0) {\n return false;\n }\n\n const sig = decompiled[0];\n if (!(sig instanceof Uint8Array)) {\n return false;\n }\n\n // Extract pubkey from output script (x-only format)\n const pubkey = concat([fromHex('02'), outputScript.subarray(2)]);\n\n // Create PSBT for verification\n const psbt = new Psbt({ network });\n psbt.setVersion(0);\n psbt.addInput({\n hash: txToSpend.getHash(),\n index: 0,\n sequence: 0,\n witnessUtxo: {\n script: outputScript as Script,\n value: ZERO_SATOSHI\n }\n });\n psbt.addOutput({\n script: fromHex('6a') as Script,\n value: ZERO_SATOSHI\n });\n\n // Compute taproot sighash using public API\n const psbtTx = psbt.data.globalMap.unsignedTx as PsbtTransaction;\n const txForHash: Transaction = psbtTx.tx;\n const tapKeyHash = txForHash.hashForWitnessV1(0, [outputScript as Script], [ZERO_SATOSHI], Transaction.SIGHASH_DEFAULT);\n\n return schnorrValidator(pubkey, tapKeyHash, sig);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP322 simple message signature for P2WPKH addresses\n */\nfunction verifyBip322P2WPKH(address: string, message: string | Uint8Array, signature: string, network: Network): boolean {\n try {\n const outputScript = bitcoinAddress.toOutputScript(address, network);\n const messageHash = computeBip322Hash(message);\n\n const prevoutHash = alloc(32) as Bytes32;\n const prevoutIndex = 0xffffffff;\n const sequence = 0;\n const scriptSig = concat([fromHex('0020'), messageHash]) as Script;\n\n // Reconstruct \"to spend\" transaction\n const txToSpend = new Transaction();\n txToSpend.version = 0;\n txToSpend.addInput(prevoutHash, prevoutIndex, sequence, scriptSig);\n txToSpend.addOutput(outputScript as Script, ZERO_SATOSHI);\n\n // Decode signature\n const signatureData = fromBase64Bytes(signature);\n const decompiled = bitcoinScript.decompile(signatureData.subarray(1));\n\n if (!Array.isArray(decompiled) || decompiled.length < 2) {\n return false;\n }\n\n const sig = decompiled[0];\n const pubkey = decompiled[1];\n\n if (!(sig instanceof Uint8Array) || !(pubkey instanceof Uint8Array)) {\n return false;\n }\n\n // Create PSBT for verification\n const psbt = new Psbt({ network });\n psbt.setVersion(0);\n psbt.addInput({\n hash: txToSpend.getHash(),\n index: 0,\n sequence: 0,\n witnessUtxo: {\n script: outputScript as Script,\n value: ZERO_SATOSHI\n }\n });\n psbt.addOutput({\n script: fromHex('6a') as Script,\n value: ZERO_SATOSHI\n });\n\n psbt.updateInput(0, {\n partialSig: [\n {\n pubkey: pubkey as PublicKey,\n signature: sig\n }\n ]\n });\n\n return psbt.validateSignaturesOfAllInputs(ecdsaValidator);\n } catch {\n return false;\n }\n}\n\n/**\n * Verify a BIP322 simple message signature\n */\nexport function verifyBip322Message(\n address: string,\n message: string | Uint8Array,\n signature: string,\n network: Network\n): boolean {\n const addressType = detectAddressType(address, network);\n\n if (addressType === null) {\n return false;\n }\n\n switch (addressType) {\n case AddressTypes.P2TR: {\n return verifyBip322P2TR(address, message, signature, network);\n }\n case AddressTypes.P2WPKH: {\n return verifyBip322P2WPKH(address, message, signature, network);\n }\n default: {\n return false;\n }\n }\n}\n\n/**\n * Sign a message using BIP322 with WalletNetworks parameter\n */\nexport async function signBip322MessageWithNetworkType(\n message: string | Uint8Array,\n address: string,\n networkType: WalletNetworks,\n signPsbt: (psbt: Psbt) => Promise<Psbt>\n): Promise<Bip322Signature> {\n const network = toNetwork(networkType);\n const signature = await signBip322Message(message, address, network, signPsbt);\n\n return {\n address,\n message,\n signature,\n networkType\n };\n}\n\n/**\n * Verify a BIP322 signature with WalletNetworks parameter\n */\nexport function verifyBip322MessageWithNetworkType(\n address: string,\n message: string | Uint8Array,\n signature: string,\n networkType: WalletNetworks\n): boolean {\n const network = toNetwork(networkType);\n return verifyBip322Message(address, message, signature, network);\n}\n","/**\n * OPNet Wallet SDK - Local Wallet\n * Full-featured local wallet implementation with quantum support.\n */\n\nimport { equals, type Network, networks, payments, Psbt, Transaction, type XOnlyPublicKey } from '@btc-vision/bitcoin';\nimport { createXOnlyPublicKey, fromHexInternal, toHex, concatBytes } from '@btc-vision/ecpair';\nimport { AddressTypes } from '@btc-vision/transaction';\nimport { publicKeyToAddress, scriptPubKeyToAddress } from '@/address';\nimport { HdKeyring } from '@/keyring';\nimport { SimpleKeyring } from '@/keyring';\nimport { signBip322Message, signMLDSA, signSchnorr } from '@/message';\nimport type { AbstractWallet, MessageSigningMethod, SignPsbtOptions, ToSignInput } from '@/types';\n\n/**\n * Local wallet implementation with full signing capabilities.\n */\nexport class LocalWallet implements AbstractWallet {\n private readonly keyring: SimpleKeyring | HdKeyring;\n private readonly network: Network;\n private readonly addressType: AddressTypes;\n private readonly publicKey: string;\n private readonly address: string;\n\n private constructor(\n keyring: SimpleKeyring | HdKeyring,\n network: Network,\n addressType: AddressTypes,\n publicKey: string\n ) {\n this.keyring = keyring;\n this.network = network;\n this.addressType = addressType;\n this.publicKey = publicKey;\n this.address = publicKeyToAddress(fromHexInternal(publicKey), addressType, network);\n }\n\n /**\n * Create wallet from WIF\n */\n public static fromWIF(\n wif: string,\n addressType: AddressTypes = AddressTypes.P2TR,\n network: Network,\n quantumPrivateKey?: string\n ): LocalWallet {\n const keyring = SimpleKeyring.fromWIF(wif, quantumPrivateKey, network);\n const publicKey = keyring.getPublicKey();\n return new LocalWallet(keyring, network, addressType, publicKey);\n }\n\n /**\n * Create wallet from private key hex\n */\n public static fromPrivateKey(\n privateKeyHex: string,\n addressType: AddressTypes = AddressTypes.P2TR,\n network: Network,\n quantumPrivateKey?: string\n ): LocalWallet {\n const keyring = SimpleKeyring.fromPrivateKey(privateKeyHex, quantumPrivateKey, network);\n const publicKey = keyring.getPublicKey();\n return new LocalWallet(keyring, network, addressType, publicKey);\n }\n\n /**\n * Create wallet from mnemonic\n */\n public static fromMnemonic(\n mnemonic: string,\n addressType: AddressTypes = AddressTypes.P2TR,\n network: Network,\n passphrase?: string,\n accountIndex = 0\n ): LocalWallet {\n const keyring = new HdKeyring({\n mnemonic,\n passphrase,\n network,\n addressType,\n activeIndexes: [accountIndex]\n });\n const accounts = keyring.getAccounts();\n const publicKey = accounts[0];\n if (publicKey === undefined) {\n throw new Error('Failed to derive wallet from mnemonic');\n }\n return new LocalWallet(keyring, network, addressType, publicKey);\n }\n\n /**\n * Create a random wallet\n */\n public static random(\n addressType: AddressTypes = AddressTypes.P2TR,\n network: Network = networks.bitcoin\n ): LocalWallet {\n const keyring = SimpleKeyring.generate(network);\n const publicKey = keyring.getPublicKey();\n return new LocalWallet(keyring, network, addressType, publicKey);\n }\n\n /**\n * Get the wallet address\n */\n public getAddress(): string {\n return this.address;\n }\n\n /**\n * Get the public key\n */\n public getPublicKey(): string {\n return this.publicKey;\n }\n\n /**\n * Get the quantum public key\n */\n public getQuantumPublicKey(): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.getQuantumPublicKey();\n }\n return this.keyring.getQuantumPublicKey(this.publicKey);\n }\n\n /**\n * Get the network\n */\n public getNetwork(): Network {\n return this.network;\n }\n\n /**\n * Get the address type\n */\n public getAddressType(): AddressTypes {\n return this.addressType;\n }\n\n /**\n * Sign a PSBT\n */\n public signPsbt(psbt: Psbt, opts?: SignPsbtOptions): Psbt {\n const options = opts ?? { autoFinalized: true, toSignInputs: [] };\n const inputs = this.formatInputsToSign(psbt, options);\n\n if (inputs.length === 0) {\n throw new Error('LocalWallet: No inputs to sign');\n }\n\n // Add tapInternalKey for P2TR inputs if missing\n for (const input of inputs) {\n const psbtInput = psbt.data.inputs[input.index];\n if (psbtInput === undefined) {\n continue;\n }\n\n const isNotSigned = !(psbtInput.finalScriptSig ?? psbtInput.finalScriptWitness);\n const isP2TR = this.addressType === AddressTypes.P2TR;\n const lostInternalPubkey = psbtInput.tapInternalKey === undefined;\n\n if (isNotSigned && isP2TR && lostInternalPubkey) {\n const pubkeyBytes: Uint8Array = fromHexInternal(this.publicKey);\n const xOnlyBytes: Uint8Array = pubkeyBytes.length === 33 ? pubkeyBytes.subarray(1, 33) : pubkeyBytes;\n const tapInternalKey: XOnlyPublicKey = createXOnlyPublicKey(xOnlyBytes);\n const { output } = payments.p2tr({\n internalPubkey: tapInternalKey,\n network: this.network\n });\n if (output !== undefined && psbtInput.witnessUtxo !== undefined && equals(psbtInput.witnessUtxo.script, output)) {\n psbtInput.tapInternalKey = tapInternalKey;\n }\n }\n }\n\n // Sign transaction\n if (this.keyring instanceof SimpleKeyring) {\n this.keyring.signTransaction(psbt, inputs);\n } else {\n this.keyring.signTransaction(psbt, inputs);\n }\n\n // Finalize if requested\n if (options.autoFinalized === true) {\n for (const input of inputs) {\n psbt.finalizeInput(input.index);\n }\n }\n\n return psbt;\n }\n\n /**\n * Sign a message\n */\n public async signMessage(message: string | Uint8Array, method: MessageSigningMethod): Promise<string> {\n switch (method) {\n case 'bip322-simple': {\n return await signBip322Message(message, this.address, this.network, (psbt) => {\n return Promise.resolve(this.signPsbt(psbt, { autoFinalized: false }));\n });\n }\n case 'ecdsa':\n case 'schnorr': {\n const keypair = this.getKeypair();\n const result = signSchnorr(keypair, message);\n return toHex(result.signature);\n }\n case 'mldsa': {\n const quantumKeypair = this.getQuantumKeypair();\n const result = signMLDSA(quantumKeypair, message);\n return toHex(result.signature);\n }\n }\n }\n\n /**\n * Sign raw data\n */\n public signData(data: string, type: 'ecdsa' | 'schnorr' = 'ecdsa'): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.signData(data, type);\n }\n return this.keyring.signData(this.publicKey, data, type);\n }\n\n /**\n * Export the private key\n */\n public exportPrivateKey(): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.exportPrivateKey();\n }\n return this.keyring.exportAccount(this.publicKey);\n }\n\n /**\n * Export the quantum private key WITH chain code (for backup/restore)\n */\n public exportQuantumPrivateKey(): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.exportQuantumPrivateKey();\n }\n // For HD keyrings, get the quantum key from the derived wallet\n const wallet = this.keyring.getWallet(this.publicKey);\n const mldsaPrivateKey: Uint8Array | undefined = wallet.mldsaKeypair.privateKey;\n if (mldsaPrivateKey === undefined) {\n throw new Error('LocalWallet: No quantum private key available');\n }\n return toHex(concatBytes(mldsaPrivateKey, wallet.chainCode));\n }\n\n /**\n * Export the raw quantum private key WITHOUT chain code (for Wallet.fromWif)\n */\n public exportRawQuantumPrivateKey(): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.exportRawQuantumPrivateKey();\n }\n // For HD keyrings, get the quantum key from the derived wallet\n const wallet = this.keyring.getWallet(this.publicKey);\n const mldsaPrivateKey: Uint8Array | undefined = wallet.mldsaKeypair.privateKey;\n if (mldsaPrivateKey === undefined) {\n throw new Error('LocalWallet: No quantum private key available');\n }\n return toHex(mldsaPrivateKey);\n }\n\n /**\n * Export the chain code\n */\n public exportChainCode(): Uint8Array {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.exportChainCode();\n }\n // For HD keyrings, get chain code from the derived wallet\n return this.keyring.getChainCode(this.publicKey);\n }\n\n /**\n * Export WIF\n */\n public exportWIF(): string {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.exportWIF();\n }\n throw new Error('LocalWallet: Cannot export WIF from HD keyring directly');\n }\n\n private getKeypair(): ReturnType<SimpleKeyring['getKeypair']> {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.getKeypair();\n }\n return this.keyring.getWallet(this.publicKey).keypair;\n }\n\n private getQuantumKeypair(): ReturnType<SimpleKeyring['getQuantumKeypair']> {\n if (this.keyring instanceof SimpleKeyring) {\n return this.keyring.getQuantumKeypair();\n }\n return this.keyring.getMLDSAKeypair(this.publicKey);\n }\n\n private formatInputsToSign(psbt: Psbt, options: SignPsbtOptions): ToSignInput[] {\n const toSignInputs: ToSignInput[] = [];\n\n if (options.toSignInputs !== undefined && options.toSignInputs.length > 0) {\n for (const input of options.toSignInputs) {\n const index = input.index;\n\n if ('address' in input) {\n if (input.address !== this.address) {\n throw new Error(`LocalWallet: Address mismatch at input ${index}`);\n }\n } else if ('publicKey' in input) {\n if (input.publicKey !== this.publicKey) {\n throw new Error(`LocalWallet: Public key mismatch at input ${index}`);\n }\n }\n\n const toSignInput: ToSignInput = {\n index,\n publicKey: this.publicKey\n };\n if (input.sighashTypes !== undefined) {\n (toSignInput as { sighashTypes?: readonly number[] }).sighashTypes = input.sighashTypes;\n }\n if (input.disableTweakSigner !== undefined) {\n (toSignInput as { disableTweakSigner?: boolean }).disableTweakSigner = input.disableTweakSigner;\n }\n toSignInputs.push(toSignInput);\n }\n } else {\n // Auto-detect inputs to sign\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const input = psbt.data.inputs[i];\n if (input === undefined) {\n continue;\n }\n\n let script: Uint8Array | undefined;\n if (input.witnessUtxo !== undefined) {\n script = input.witnessUtxo.script;\n } else if (input.nonWitnessUtxo !== undefined) {\n const tx = psbt.txInputs[i];\n if (tx !== undefined) {\n const nonWitnessTx = Transaction.fromBuffer(input.nonWitnessUtxo);\n const output = nonWitnessTx.outs[tx.index];\n script = output?.script;\n }\n }\n\n const isSigned = input.finalScriptSig ?? input.finalScriptWitness;\n\n if (script !== undefined && isSigned === undefined) {\n const address = scriptPubKeyToAddress(script, this.network);\n if (address === this.address) {\n const toSignInput: ToSignInput = {\n index: i,\n publicKey: this.publicKey\n };\n if (input.sighashType !== undefined) {\n (toSignInput as { sighashTypes?: readonly number[] }).sighashTypes = [input.sighashType];\n }\n toSignInputs.push(toSignInput);\n }\n }\n }\n }\n\n return toSignInputs;\n }\n}\n","/**\n * OPNet Wallet SDK Type Definitions\n * All core types and interfaces for the wallet SDK.\n */\n\nimport type { Network, Psbt } from '@btc-vision/bitcoin';\nimport { AddressTypes, MLDSASecurityLevel, type QuantumBIP32Interface, WalletNetworks } from '@btc-vision/transaction';\nimport type { UniversalSigner } from '@btc-vision/ecpair';\n\n/**\n * Signature type for message signing operations\n */\nexport type SignatureType = 'ecdsa' | 'schnorr' | 'mldsa';\n\n/**\n * Message signing method types\n */\nexport type MessageSigningMethod = 'bip322-simple' | 'ecdsa' | 'schnorr' | 'mldsa';\n\n/**\n * Base interface for inputs to sign in a PSBT\n */\nexport interface BaseSignInput {\n readonly index: number;\n readonly sighashTypes?: readonly number[];\n readonly disableTweakSigner?: boolean;\n}\n\n/**\n * Sign input with address specification\n */\nexport interface AddressSignInput extends BaseSignInput {\n readonly address: string;\n}\n\n/**\n * Sign input with public key specification\n */\nexport interface PublicKeySignInput extends BaseSignInput {\n readonly publicKey: string;\n}\n\n/**\n * Union type for sign inputs\n */\nexport type SignInput = AddressSignInput | PublicKeySignInput;\n\n/**\n * Options for signing PSBTs\n */\nexport interface SignPsbtOptions {\n readonly autoFinalized?: boolean;\n readonly toSignInputs?: readonly SignInput[];\n}\n\n/**\n * Internal representation of inputs to sign\n */\nexport interface ToSignInput {\n readonly index: number;\n readonly publicKey: string;\n readonly sighashTypes?: readonly number[];\n readonly disableTweakSigner?: boolean;\n}\n\n/**\n * Result of an address decode operation\n */\nexport interface DecodedAddress {\n readonly networkType: WalletNetworks;\n readonly addressType: AddressTypes;\n readonly scriptPubKey: Uint8Array;\n}\n\n/**\n * Quantum key pair information\n */\nexport interface QuantumKeyInfo {\n readonly publicKey: Uint8Array;\n readonly securityLevel: MLDSASecurityLevel;\n}\n\n/**\n * Classical key pair information\n */\nexport interface ClassicalKeyInfo {\n readonly publicKey: Uint8Array;\n readonly privateKey?: Uint8Array;\n}\n\n/**\n * Combined wallet key information (classical + quantum)\n */\nexport interface WalletKeyInfo {\n readonly classical: ClassicalKeyInfo;\n readonly quantum: QuantumKeyInfo;\n readonly chainCode: Uint8Array;\n}\n\n/**\n * Exported wallet format for unified key export\n */\nexport interface ExportedWallet {\n readonly version: number;\n readonly classicalPrivateKey: string;\n readonly quantumPrivateKey: string;\n readonly quantumPublicKey: string;\n readonly securityLevel: MLDSASecurityLevel;\n readonly chainCode: string;\n}\n\n/**\n * Mnemonic options for wallet generation\n */\nexport interface MnemonicOptions {\n readonly phrase?: string;\n readonly passphrase?: string;\n readonly network?: Network;\n readonly securityLevel?: MLDSASecurityLevel;\n}\n\n/**\n * HD derivation options\n */\nexport interface DerivationOptions {\n readonly addressType?: AddressTypes;\n readonly account?: number;\n readonly change?: boolean;\n readonly index?: number;\n}\n\n/**\n * Keyring serialization options\n */\nexport interface KeyringSerializeOptions {\n readonly includePrivateKeys?: boolean;\n}\n\n/**\n * HD Keyring deserialization options\n */\nexport interface HdKeyringOptions {\n readonly mnemonic?: string | undefined;\n readonly passphrase?: string | undefined;\n readonly network?: Network | undefined;\n readonly securityLevel?: MLDSASecurityLevel | undefined;\n readonly activeIndexes?: readonly number[] | undefined;\n readonly addressType?: AddressTypes | undefined;\n readonly hdPath?: string | undefined;\n}\n\n/**\n * Simple keyring options for WIF/private key import\n */\nexport interface SimpleKeyringOptions {\n readonly privateKey: string;\n readonly quantumPrivateKey?: string | undefined;\n readonly network?: Network | undefined;\n readonly securityLevel?: MLDSASecurityLevel | undefined;\n}\n\n/**\n * Message signature result\n */\nexport interface SignedMessage {\n readonly message: string | Uint8Array;\n readonly signature: Uint8Array;\n readonly publicKey: Uint8Array;\n readonly signatureType: SignatureType;\n readonly securityLevel?: MLDSASecurityLevel;\n}\n\n/**\n * BIP322 signature result\n */\nexport interface Bip322Signature {\n readonly address: string;\n readonly message: string | Uint8Array;\n readonly signature: string;\n readonly networkType: WalletNetworks;\n}\n\n/**\n * Wallet account information\n */\nexport interface AccountInfo {\n readonly index: number;\n readonly publicKey: string;\n readonly quantumPublicKey: string;\n readonly addresses: AccountAddresses;\n}\n\n/**\n * All address types for an account\n */\nexport interface AccountAddresses {\n readonly p2pkh?: string;\n readonly p2wpkh?: string;\n readonly p2tr?: string;\n readonly p2shP2wpkh?: string;\n}\n\n/**\n * Abstract wallet interface\n */\nexport interface AbstractWallet {\n signPsbt(psbt: Psbt, opts?: SignPsbtOptions): Promise<Psbt> | Psbt;\n signMessage(message: string | Uint8Array, method: MessageSigningMethod): Promise<string>;\n}\n\n/**\n * Keystone hardware wallet key information\n */\nexport interface KeystoneKey {\n readonly path: string;\n readonly extendedPublicKey: string;\n}\n\n/**\n * Keystone keyring options\n */\nexport interface KeystoneKeyringOptions {\n readonly mfp: string;\n readonly keys: readonly KeystoneKey[];\n readonly network?: Network;\n readonly activeIndexes?: readonly number[];\n readonly addressType?: AddressTypes;\n}\n\n/**\n * Type guard to check if sign input has address\n */\nexport function isAddressSignInput(input: SignInput): input is AddressSignInput {\n return 'address' in input;\n}\n\n/**\n * Type guard to check if sign input has public key\n */\nexport function isPublicKeySignInput(input: SignInput): input is PublicKeySignInput {\n return 'publicKey' in input;\n}\n\n/**\n * Re-export UniversalSigner for convenience\n */\nexport type { UniversalSigner, QuantumBIP32Interface };\n"],"names":["toNetwork","networkType","WalletNetworks","Mainnet","networks","bitcoin","Testnet","testnet","Regtest","regtest","OpnetTestnet","opnetTestnet","Error","toNetworkType","network","bech32","detectNetworkFromAddress","address","startsWith","publicKeyToAddress","publicKey","addressType","pubkeyBytes","fromHexInternal","AddressTypes","P2PKH","payment","payments","p2pkh","pubkey","createPublicKey","P2WPKH","p2wpkh","P2TR","xOnly","length","subarray","p2tr","internalPubkey","createXOnlyPublicKey","P2SH_OR_P2SH_P2WPKH","p2sh","redeem","publicKeyToPayment","scriptPubKeyToAddress","scriptPubKey","script","fromHex","bitcoinAddress","fromOutputScript","isValidAddress","AddressVerificator","detectAddressType","HdKeyring","static","type","mnemonic","wallets","Map","activeIndexes","securityLevel","passphrase","_hdPath","constructor","options","this","MLDSASecurityLevel","LEVEL2","hdPath","initFromMnemonic","activateAccounts","generate","strength","MnemonicStrength","MAXIMUM","Mnemonic","keyring","phrase","getMnemonic","hasMnemonic","deriveWallet","index","cached","get","wallet","isCustomHdPath","classicalPath","quantumPath","deriveCustomPath","deriveOPWallet","set","deriveStandardWallet","derive","addAccounts","numberOfAccounts","newPublicKeys","currentIndex","includes","push","toPublicKeyHex","indexes","publicKeys","getAccounts","map","getAccountsInfo","addresses","legacy","p2shP2wpkh","segwitLegacy","quantumPublicKey","quantumPublicKeyHex","getQuantumPublicKey","findWalletByPublicKey","getIndexByPublicKey","entries","getAddressesForPublicKey","getAddress","removeAccount","activeIdx","indexOf","splice","delete","exportAccount","toPrivateKeyHex","signTransaction","psbt","inputs","input","psbtInput","data","keypair","sighashTypes","isTaprootInput","disableTweakSigner","tweakedKeypair","tweak","createBytes32","signInput","signData","dataHash","createMessageHash","toHex","sign","signSchnorr","getWallet","serialize","getActiveIndexes","setAddressType","getAddressType","getSecurityLevel","getNetwork","getAddressesPage","page","perPage","start","end","results","i","getAddressFromWallet","getChainCode","Uint8Array","from","chainCode","getMLDSAKeypair","mldsaKeypair","standardPath","standardPathBase","slice","values","SimpleKeyring","quantumKeypair","privateKey","importPrivateKey","quantumPrivateKey","EcKeyPair","generateRandomKeyPair","seed","crypto","getRandomValues","QuantumBIP32Factory","fromSeed","fromWIF","wif","importQuantumKey","fromPrivateKey","privateKeyHex","quantumPrivateKeyHex","privateKeyBytes","expectedKeySize","getMLDSAConfig","privateKeySize","expectedKeyWithChaincodeSize","hasChaincode","isKeyOnly","keyWithoutChainCode","generateFreshQuantumKey","hasKeys","hasClassicalKey","hasQuantumKey","needsQuantumMigration","getPublicKey","getQuantumPublicKeyOrUndefined","getQuantumPublicKeyHash","hash","bitcoinCrypto","sha256","clearQuantumKey","getAddresses","exportPrivateKey","exportQuantumPrivateKey","concatBytes","exportRawQuantumPrivateKey","exportChainCode","exportWIF","toWIF","tweakedSigner","verify","signature","createSignature","verifySchnorr","createSchnorrSignature","getKeypair","getQuantumKeypair","clear","MAGIC_HEADER","textEncoder","TextEncoder","calculateChecksum","encode","getNetworkName","exportWallet","classicalPrivateKey","classicalPublicKey","exportData","magic","version","classical","quantum","checksum","JSON","stringify","importWallet","dataWithoutChecksum","expectedChecksum","name","walletNetwork","Object","getNetworkFromName","serializeExport","json","btoa","deserializeExport","serialized","atob","parse","backend","getNobleBackend","createNobleBackend","signMLDSA","message","result","MessageSigner","signMLDSAMessage","verifyMLDSA","fromPublicKey","verifyMLDSASignature","signMessage","verifySignature","isQuantumKeypair","toUint8Array","ZERO_SATOSHI","toSatoshi","fromBase64Bytes","base64","binary","bytes","charCodeAt","SUPPORTED_ADDRESS_TYPES","computeBip322Hash","tagHash","messageBytes","concat","generateBip322Psbt","outputScript","toOutputScript","String","messageHash","prevoutHash","alloc","scriptSig","txToSpend","Transaction","addInput","addOutput","Psbt","setVersion","getHash","sequence","witnessUtxo","value","extractBip322Signature","tx","extractTransaction","witness","ins","varintLength","bitcoinScript","number","byte","fromCharCode","toBase64","w","buf","varint","encodeVarString","async","signBip322Message","signPsbt","signedPsbt","finalizeAllInputs","ecdsaValidator","msghash","decoded","decode","verifyBip322P2TR","prevoutIndex","signatureData","decompiled","decompile","Array","isArray","sig","txForHash","globalMap","unsignedTx","xOnlyPubkey","schnorrValidator","hashForWitnessV1","SIGHASH_DEFAULT","verifyBip322Message","updateInput","partialSig","validateSignaturesOfAllInputs","verifyBip322P2WPKH","LocalWallet","fromMnemonic","accountIndex","random","opts","autoFinalized","toSignInputs","formatInputsToSign","isNotSigned","finalScriptSig","finalScriptWitness","isP2TR","lostInternalPubkey","tapInternalKey","xOnlyBytes","output","equals","finalizeInput","method","Promise","resolve","mldsaPrivateKey","toSignInput","nonWitnessUtxo","txInputs","fromBuffer","outs","isSigned","sighashType","networksToTry","isP2PKHOrP2SH","isP2WPKHAddress","isValidP2TRAddress","pubkeyHex","isValidPublicKey","signatureType","tweakAndSignMessage","expectedNetwork","ecdsaBytes","tweakAndVerifySignature"],"mappings":"2NAWO,SAASA,EAAUC,GACtB,OAAQA,GACJ,KAAKC,EAAAA,eAAeC,QAChB,OAAOC,EAAAA,SAASC,QAGpB,KAAKH,EAAAA,eAAeI,QAChB,OAAOF,EAAAA,SAASG,QAGpB,KAAKL,EAAAA,eAAeM,QAChB,OAAOJ,EAAAA,SAASK,QAGpB,KAAKP,EAAAA,eAAeQ,aAChB,OAAON,EAAAA,SAASO,aAGpB,QACI,MAAM,IAAIC,MAAM,6BAA6BX,KAGzD,CAKO,SAASY,EAAcC,GAC1B,OAAIA,EAAQC,SAAWX,WAASC,QAAQU,OAC7Bb,EAAAA,eAAeC,QAGtBW,EAAQC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