@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.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@btc-vision/transaction"),t=require("@btc-vision/bitcoin"),r=require("@btc-vision/ecpair"),i=require("@btc-vision/bip32");function n(r){switch(r){case e.WalletNetworks.Mainnet:return t.networks.bitcoin;case e.WalletNetworks.Testnet:return t.networks.testnet;case e.WalletNetworks.Regtest:return t.networks.regtest}}function s(t){return t.startsWith("bc1")||t.startsWith("1")||t.startsWith("3")?e.WalletNetworks.Mainnet:t.startsWith("tb1")||t.startsWith("m")||t.startsWith("n")||t.startsWith("2")?e.WalletNetworks.Testnet:t.startsWith("bcrt1")?e.WalletNetworks.Regtest:null}function a(i,n,s){const a="string"==typeof i?r.fromHexInternal(i):i;switch(n){case e.AddressTypes.P2PKH:{const e=t.payments.p2pkh({pubkey:r.createPublicKey(a),network:s});if(void 0===e.address)throw new Error("Failed to generate P2PKH address");return e.address}case e.AddressTypes.P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});if(void 0===e.address)throw new Error("Failed to generate P2WPKH address");return e.address}case e.AddressTypes.P2TR:{const e=33===a.length?a.subarray(1,33):a,i=t.payments.p2tr({internalPubkey:r.createXOnlyPublicKey(e),network:s});if(void 0===i.address)throw new Error("Failed to generate P2TR address");return i.address}case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s}),i=t.payments.p2sh({redeem:e,network:s});if(void 0===i.address)throw new Error("Failed to generate P2SH-P2WPKH address");return i.address}default:throw new Error(`Unsupported address type: ${n}`)}}function o(i,n,s){const a="string"==typeof i?r.fromHexInternal(i):i;switch(n){case e.AddressTypes.P2PKH:return t.payments.p2pkh({pubkey:r.createPublicKey(a),network:s});case e.AddressTypes.P2WPKH:return t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});case e.AddressTypes.P2TR:{const e=33===a.length?a.subarray(1,33):a;return t.payments.p2tr({internalPubkey:r.createXOnlyPublicKey(e),network:s})}case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});return t.payments.p2sh({redeem:e,network:s})}default:throw new Error(`Unsupported address type: ${n}`)}}function u(e,r){const i="string"==typeof e?t.fromHex(e):e;return t.address.fromOutputScript(i,r)}function c(t,r){return null!==e.AddressVerificator.detectAddressType(t,r)}function y(t,r){return e.AddressVerificator.detectAddressType(t,r)}class l{static type="HD Key Tree";type=l.type;mnemonic=null;wallets=new Map;activeIndexes=[];network;securityLevel;passphrase;addressType;_hdPath;constructor(t){if(!t.network)throw new Error("HdKeyring: Network option is required");this.network=t.network,this.securityLevel=t?.securityLevel??e.MLDSASecurityLevel.LEVEL2,this.passphrase=t?.passphrase??"",this.addressType=t?.addressType??e.AddressTypes.P2TR,this._hdPath=t?.hdPath??"",void 0!==t?.mnemonic&&(this.initFromMnemonic(t.mnemonic),void 0!==t.activeIndexes&&t.activeIndexes.length>0&&this.activateAccounts([...t.activeIndexes]))}get hdPath(){return this._hdPath}static generate(r=e.MnemonicStrength.MAXIMUM,i="",n=t.networks.bitcoin,s=e.MLDSASecurityLevel.LEVEL2){const a=e.Mnemonic.generate(r,i,n,s),o=new l({network:n,securityLevel:s,passphrase:i});return o.mnemonic=a,o}initFromMnemonic(t){if(null!==this.mnemonic)throw new Error("HdKeyring: Mnemonic already initialized");this.mnemonic=new e.Mnemonic(t,this.passphrase,this.network,this.securityLevel)}getMnemonic(){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");return this.mnemonic.phrase}hasMnemonic(){return null!==this.mnemonic}deriveWallet(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const r=this.wallets.get(e);if(void 0!==r)return r;let i;if(this.isCustomHdPath()){const r=`${this._hdPath}/${e}`,n=`m/360'/${this.network===t.networks.bitcoin?0:1}'/0'/0/${e}`;i=this.mnemonic.deriveCustomPath(r,n)}else i=this.mnemonic.deriveOPWallet(this.addressType,e);return this.wallets.set(e,i),i}deriveStandardWallet(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");return this.mnemonic.derive(e)}addAccounts(e=1){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];let r=0;for(;t.length<e;){if(!this.activeIndexes.includes(r)){const e=this.deriveWallet(r);this.activeIndexes.push(r),t.push(e.toPublicKeyHex())}r++}return t}activateAccounts(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];for(const r of e)if(this.activeIndexes.includes(r)){const e=this.wallets.get(r);void 0!==e&&t.push(e.toPublicKeyHex())}else{const e=this.deriveWallet(r);this.activeIndexes.push(r),t.push(e.toPublicKeyHex())}return t}getAccounts(){return this.activeIndexes.map(e=>{const t=this.wallets.get(e);if(void 0===t)throw new Error(`HdKeyring: Wallet at index ${e} not found`);return t.toPublicKeyHex()})}getAccountsInfo(){return this.activeIndexes.map(e=>{const t=this.wallets.get(e);if(void 0===t)throw new Error(`HdKeyring: Wallet at index ${e} not found`);const r={p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy};return{index:e,publicKey:t.toPublicKeyHex(),quantumPublicKey:t.quantumPublicKeyHex,addresses:r}})}getQuantumPublicKey(e){return this.findWalletByPublicKey(e).quantumPublicKeyHex}getIndexByPublicKey(e){for(const[t,r]of this.wallets.entries())if(r.toPublicKeyHex()===e)return t;return null}getAddressesForPublicKey(e){const t=this.findWalletByPublicKey(e);return{p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy}}getAddress(e,t){return a(r.fromHexInternal(e),t,this.network)}removeAccount(e){const t=this.getIndexByPublicKey(e);if(null===t)throw new Error(`HdKeyring: Account with public key ${e} not found`);const r=this.activeIndexes.indexOf(t);-1!==r&&this.activeIndexes.splice(r,1),this.wallets.delete(t)}exportAccount(e){return this.findWalletByPublicKey(e).toPrivateKeyHex()}signTransaction(e,i){for(const n of i){const i=this.findWalletByPublicKey(n.publicKey),s=e.data.inputs[n.index];if(void 0===s)throw new Error(`HdKeyring: Input at index ${n.index} not found`);const a=i.keypair,o=void 0!==n.sighashTypes?[...n.sighashTypes]:void 0;if(t.isTaprootInput(s)&&!0!==n.disableTweakSigner){const t=i.publicKey.subarray(1,33),s=a.tweak(r.createBytes32(t));e.signInput(n.index,s,o)}else e.signInput(n.index,a,o)}return e}signData(e,t,i="ecdsa"){const n=this.findWalletByPublicKey(e),s=r.createMessageHash(r.fromHexInternal(t));if("ecdsa"===i)return r.toHex(n.keypair.sign(s));if(void 0===n.keypair.signSchnorr)throw new Error("HdKeyring: Schnorr signing not supported by this keypair");return r.toHex(n.keypair.signSchnorr(s))}getWallet(e){return this.findWalletByPublicKey(e)}serialize(){return{mnemonic:this.mnemonic?.phrase,passphrase:this.passphrase,network:this.network,securityLevel:this.securityLevel,activeIndexes:[...this.activeIndexes],addressType:this.addressType,hdPath:this._hdPath}}getActiveIndexes(){return[...this.activeIndexes]}setAddressType(e){this.addressType=e}getAddressType(){return this.addressType}getSecurityLevel(){return this.securityLevel}getNetwork(){return this.network}getAddressesPage(e,r=5){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const i=e*r,n=i+r,s=[];for(let a=i;a<n;a++){let e;if(this.isCustomHdPath()){const r=`${this._hdPath}/${a}`,i=`m/360'/${this.network===t.networks.bitcoin?0:1}'/0'/0/${a}`;e=this.mnemonic.deriveCustomPath(r,i)}else e=this.mnemonic.deriveOPWallet(this.addressType,a);const r=this.getAddressFromWallet(e);s.push({address:r,index:a})}return s}getChainCode(e){const t=this.findWalletByPublicKey(e);return Uint8Array.from(t.chainCode)}getMLDSAKeypair(e){return this.findWalletByPublicKey(e).mldsaKeypair}isCustomHdPath(){const t={[e.AddressTypes.P2PKH]:"m/44'/0'/0'/0",[e.AddressTypes.P2WPKH]:"m/84'/0'/0'/0",[e.AddressTypes.P2TR]:"m/86'/0'/0'/0",[e.AddressTypes.P2SH_OR_P2SH_P2WPKH]:"m/49'/0'/0'/0"}[this.addressType];if(void 0===t)return""!==this._hdPath;const r=t.slice(0,-2);return!this._hdPath.includes(r)&&""!==this._hdPath}findWalletByPublicKey(e){for(const t of this.wallets.values())if(t.toPublicKeyHex()===e)return t;throw new Error(`HdKeyring: Wallet with public key ${e} not found`)}getAddressFromWallet(t){switch(this.addressType){case e.AddressTypes.P2PKH:return t.legacy;case e.AddressTypes.P2WPKH:return t.p2wpkh;case e.AddressTypes.P2TR:return t.p2tr;case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:return t.segwitLegacy;default:return t.p2tr}}}class p{static type="Simple Key Pair";type=p.type;network;securityLevel;keypair=null;quantumKeypair=null;chainCode=new Uint8Array(32);constructor(t){if(!t?.network)throw new Error("SimpleKeyring: Network option is required");this.network=t.network,this.securityLevel=t?.securityLevel??e.MLDSASecurityLevel.LEVEL2,void 0!==t?.privateKey&&this.importPrivateKey(t.privateKey,t.quantumPrivateKey)}static generate(r=t.networks.bitcoin,i=e.MLDSASecurityLevel.LEVEL2){const n=new p({network:r,securityLevel:i,privateKey:""});n.keypair=e.EcKeyPair.generateRandomKeyPair(r);const s=crypto.getRandomValues(new Uint8Array(64));return n.quantumKeypair=e.QuantumBIP32Factory.fromSeed(s,r,i),n.chainCode=Uint8Array.from(n.quantumKeypair.chainCode),n}static fromWIF(r,i,n=t.networks.bitcoin,s=e.MLDSASecurityLevel.LEVEL2){const a=new p({network:n,securityLevel:s,privateKey:""});return a.keypair=e.EcKeyPair.fromWIF(r,n),void 0!==i&&""!==i&&a.importQuantumKey(i),a}static fromPrivateKey(i,n,s=t.networks.bitcoin,a=e.MLDSASecurityLevel.LEVEL2){const o=new p({network:s,securityLevel:a,privateKey:""});return o.keypair=e.EcKeyPair.fromPrivateKey(r.fromHexInternal(i),s),void 0!==n&&""!==n&&o.importQuantumKey(n),o}importPrivateKey(t,i){""!==t&&(64===t.length?this.keypair=e.EcKeyPair.fromPrivateKey(r.fromHexInternal(t),this.network):this.keypair=e.EcKeyPair.fromWIF(t,this.network),void 0!==i&&""!==i&&this.importQuantumKey(i))}importQuantumKey(t){const n=r.fromHexInternal(t),s=i.getMLDSAConfig(this.securityLevel,this.network).privateKeySize,a=s+32,o=n.length===a,u=n.length===s;if(!o&&!u)throw new Error(`Invalid quantum key length: ${n.length} bytes. Expected ${s} bytes (key only) or ${a} bytes (key + chaincode).`);if(o){this.chainCode=n.slice(-32);const t=n.slice(0,-32);this.quantumKeypair=e.QuantumBIP32Factory.fromPrivateKey(t,this.chainCode,this.network,this.securityLevel)}else this.chainCode=crypto.getRandomValues(new Uint8Array(32)),this.quantumKeypair=e.QuantumBIP32Factory.fromPrivateKey(n,this.chainCode,this.network,this.securityLevel)}generateFreshQuantumKey(){const t=crypto.getRandomValues(new Uint8Array(64));this.quantumKeypair=e.QuantumBIP32Factory.fromSeed(t,this.network,this.securityLevel),this.chainCode=Uint8Array.from(this.quantumKeypair.chainCode)}hasKeys(){return null!==this.keypair&&null!==this.quantumKeypair}hasClassicalKey(){return null!==this.keypair}hasQuantumKey(){return null!==this.quantumKeypair}needsQuantumMigration(){return null!==this.keypair&&null===this.quantumKeypair}getPublicKey(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return r.toHex(this.keypair.publicKey)}getQuantumPublicKey(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return r.toHex(this.quantumKeypair.publicKey)}getQuantumPublicKeyOrUndefined(){if(null!==this.quantumKeypair)return r.toHex(this.quantumKeypair.publicKey)}getQuantumPublicKeyHash(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");const e=t.crypto.sha256(this.quantumKeypair.publicKey);return r.toHex(e)}clearQuantumKey(){this.quantumKeypair=null,this.chainCode=new Uint8Array(32)}getAccounts(){return null===this.keypair?[]:[this.getPublicKey()]}getAddresses(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const t=this.keypair.publicKey;return{p2pkh:a(t,e.AddressTypes.P2PKH,this.network),p2wpkh:a(t,e.AddressTypes.P2WPKH,this.network),p2tr:a(t,e.AddressTypes.P2TR,this.network),p2shP2wpkh:a(t,e.AddressTypes.P2SH_OR_P2SH_P2WPKH,this.network)}}getAddress(e){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return a(this.keypair.publicKey,e,this.network)}exportPrivateKey(){if(void 0===this.keypair?.privateKey)throw new Error("SimpleKeyring: No private key available");return r.toHex(this.keypair.privateKey)}exportQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return r.toHex(r.concatBytes(this.quantumKeypair.privateKey,this.chainCode))}exportRawQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return r.toHex(this.quantumKeypair.privateKey)}exportChainCode(){return this.chainCode}exportWIF(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return this.keypair.toWIF()}signTransaction(e,i){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");for(const n of i){const i=e.data.inputs[n.index];if(void 0===i)throw new Error(`SimpleKeyring: Input at index ${n.index} not found`);if(t.isTaprootInput(i)&&!0!==n.disableTweakSigner){const t=this.keypair.tweak(r.createBytes32(this.keypair.publicKey.subarray(1,33)));e.signInput(n.index,t,n.sighashTypes?[...n.sighashTypes]:void 0)}else e.signInput(n.index,this.keypair,n.sighashTypes?[...n.sighashTypes]:void 0)}return e}signData(e,t="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const i=r.createMessageHash(r.fromHexInternal(e));if("ecdsa"===t)return r.toHex(this.keypair.sign(i));if(void 0===this.keypair.signSchnorr)throw new Error("SimpleKeyring: Schnorr signing not supported by this keypair");return r.toHex(this.keypair.signSchnorr(i))}verify(e,t,i="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const n=r.createMessageHash(r.fromHexInternal(e));return"ecdsa"===i?this.keypair.verify(n,r.createSignature(r.fromHexInternal(t))):this.keypair.verifySchnorr(n,r.createSchnorrSignature(r.fromHexInternal(t)))}getKeypair(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return this.keypair}getQuantumKeypair(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return this.quantumKeypair}getChainCode(){return this.chainCode}getSecurityLevel(){return this.securityLevel}getNetwork(){return this.network}serialize(){let e;try{e=this.exportQuantumPrivateKey()}catch{e=void 0}return{privateKey:this.exportPrivateKey(),quantumPrivateKey:e,network:this.network,securityLevel:this.securityLevel}}clear(){this.keypair=null,this.quantumKeypair=null,this.chainCode=new Uint8Array(32)}}const d="OPNET_WALLET_V1",h=new TextEncoder;function g(e){const i=t.crypto.sha256(h.encode(e));return r.toHex(i.subarray(0,4))}function w(e){return e.bech32===t.networks.bitcoin.bech32?"mainnet":e.bech32===t.networks.testnet.bech32?"testnet":"regtest"}function m(e,t,i,n,s,a,o){const u={magic:d,version:1,network:w(o),classical:{privateKey:r.toHex(e),publicKey:r.toHex(t)},quantum:{privateKey:r.toHex(i),publicKey:r.toHex(n),securityLevel:a,chainCode:r.toHex(s)}},c=g(JSON.stringify(u));return{...u,checksum:c}}function f(i){if(i.magic!==d)throw new Error("Invalid wallet export format: wrong magic header");if(1!==i.version)throw new Error(`Unsupported wallet export version: ${i.version}`);const n={magic:i.magic,version:i.version,network:i.network,classical:i.classical,quantum:i.quantum},s=g(JSON.stringify(n));if(i.checksum!==s)throw new Error("Invalid wallet export: checksum mismatch");const a=function(e){switch(e){case"mainnet":default:return t.networks.bitcoin;case"testnet":return t.networks.testnet;case"regtest":return t.networks.regtest}}(i.network),o=r.fromHexInternal(i.quantum.chainCode),u=r.fromHexInternal(i.classical.privateKey),c=e.EcKeyPair.fromPrivateKey(u,a),y=r.fromHexInternal(i.quantum.privateKey);return{keypair:c,quantumKeypair:e.QuantumBIP32Factory.fromPrivateKey(y,o,a,i.quantum.securityLevel),network:a,securityLevel:i.quantum.securityLevel,chainCode:o}}function K(e){const t=JSON.stringify(e);return btoa(t)}function k(e){try{const t=atob(e);return JSON.parse(t)}catch{throw new Error("Invalid wallet export: failed to deserialize")}}let v;function P(){return v??=r.createNobleBackend(),v}function x(t,r){const i=e.MessageSigner.signMLDSAMessage(t,r);return{message:i.message,signature:i.signature,publicKey:i.publicKey,securityLevel:i.securityLevel}}function b(t,r,i,n,s,a){const o=e.QuantumBIP32Factory.fromPublicKey(t,r,i,n);return e.MessageSigner.verifyMLDSASignature(o,s,a)}function S(t,r){const i=e.MessageSigner.signMessage(t,r);return{message:i.message,signature:i.signature,publicKey:t.publicKey}}function T(t,r,i){return e.MessageSigner.verifySignature(t,r,i)}function H(e){return"securityLevel"in e&&"chainCode"in e}const A=new TextEncoder;function I(e){return"string"==typeof e?A.encode(e):e}const W=new TextEncoder,E=t.toSatoshi(0n);function L(e){const t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}const q=[e.AddressTypes.P2WPKH,e.AddressTypes.P2TR];function M(e){const r=t.crypto.sha256(W.encode("BIP0322-signed-message")),i="string"==typeof e?W.encode(e):e;return t.crypto.sha256(t.concat([r,r,i]))}function N(e,r,i){const n=t.address.toOutputScript(r,i),s=y(r,i);if(null===s||!q.includes(s))throw new Error(`BIP322: Address type not supported for signing. Got: ${String(s)}`);const a=M(e),o=t.alloc(32),u=t.concat([t.fromHex("0020"),a]),c=new t.Transaction;c.version=0,c.addInput(o,4294967295,0,u),c.addOutput(n,E);const l=new t.Psbt({network:i});return l.setVersion(0),l.addInput({hash:c.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:E}}),l.addOutput({script:t.fromHex("6a"),value:E}),l}function C(e){const r=e.extractTransaction(),i=r.ins[0]?.witness;if(void 0===i||0===i.length)throw new Error("BIP322: No witness data found in signed transaction");const n=t.script.number.encode(i.length);return function(e){let t="";for(const r of e)t+=String.fromCharCode(r);return btoa(t)}(t.concat([n,...i.map(e=>function(e){const r=t.script.number.encode(e.length);return t.concat([r,e])}(e))]))}async function F(e,t,r,i){const n=N(e,t,r),s=await i(n);return s.finalizeAllInputs(),C(s)}const O=(e,i,n)=>{try{const s=t.script.signature.decode(n);return P().verify(r.createMessageHash(i),r.createPublicKey(e),r.createSignature(s.signature))}catch{return!1}};function B(e,i,n,s){try{const a=t.address.toOutputScript(e,s),o=M(i),u=t.alloc(32),c=4294967295,y=0,l=t.concat([t.fromHex("0020"),o]),p=new t.Transaction;p.version=0,p.addInput(u,c,y,l),p.addOutput(a,E);const d=L(n),h=t.script.decompile(d.subarray(1));if(!Array.isArray(h)||0===h.length)return!1;const g=h[0];if(!(g instanceof Uint8Array))return!1;const w=t.concat([t.fromHex("02"),a.subarray(2)]),m=new t.Psbt({network:s});m.setVersion(0),m.addInput({hash:p.getHash(),index:0,sequence:0,witnessUtxo:{script:a,value:E}}),m.addOutput({script:t.fromHex("6a"),value:E});const f=m.data.globalMap.unsignedTx.tx;return function(e,t,i){try{const n=33===e.length?e.subarray(1,33):e;return P().verifySchnorr(r.createMessageHash(t),r.createXOnlyPublicKey(n),r.createSchnorrSignature(i))}catch{return!1}}(w,f.hashForWitnessV1(0,[a],[E],t.Transaction.SIGHASH_DEFAULT),g)}catch{return!1}}function Q(r,i,n,s){const a=y(r,s);if(null===a)return!1;switch(a){case e.AddressTypes.P2TR:return B(r,i,n,s);case e.AddressTypes.P2WPKH:return function(e,r,i,n){try{const s=t.address.toOutputScript(e,n),a=M(r),o=t.alloc(32),u=4294967295,c=0,y=t.concat([t.fromHex("0020"),a]),l=new t.Transaction;l.version=0,l.addInput(o,u,c,y),l.addOutput(s,E);const p=L(i),d=t.script.decompile(p.subarray(1));if(!Array.isArray(d)||d.length<2)return!1;const h=d[0],g=d[1];if(!(h instanceof Uint8Array&&g instanceof Uint8Array))return!1;const w=new t.Psbt({network:n});return w.setVersion(0),w.addInput({hash:l.getHash(),index:0,sequence:0,witnessUtxo:{script:s,value:E}}),w.addOutput({script:t.fromHex("6a"),value:E}),w.updateInput(0,{partialSig:[{pubkey:g,signature:h}]}),w.validateSignaturesOfAllInputs(O)}catch{return!1}}(r,i,n,s);default:return!1}}class R{keyring;network;addressType;publicKey;address;constructor(e,t,i,n){this.keyring=e,this.network=t,this.addressType=i,this.publicKey=n,this.address=a(r.fromHexInternal(n),i,t)}static fromWIF(t,r=e.AddressTypes.P2TR,i,n){const s=p.fromWIF(t,n,i),a=s.getPublicKey();return new R(s,i,r,a)}static fromPrivateKey(t,r=e.AddressTypes.P2TR,i,n){const s=p.fromPrivateKey(t,n,i),a=s.getPublicKey();return new R(s,i,r,a)}static fromMnemonic(t,r=e.AddressTypes.P2TR,i,n,s=0){const a=new l({mnemonic:t,passphrase:n,network:i,addressType:r,activeIndexes:[s]}),o=a.getAccounts()[0];if(void 0===o)throw new Error("Failed to derive wallet from mnemonic");return new R(a,i,r,o)}static random(r=e.AddressTypes.P2TR,i=t.networks.bitcoin){const n=p.generate(i),s=n.getPublicKey();return new R(n,i,r,s)}getAddress(){return this.address}getPublicKey(){return this.publicKey}getQuantumPublicKey(){return this.keyring instanceof p?this.keyring.getQuantumPublicKey():this.keyring.getQuantumPublicKey(this.publicKey)}getNetwork(){return this.network}getAddressType(){return this.addressType}signPsbt(i,n){const s=n??{autoFinalized:!0,toSignInputs:[]},a=this.formatInputsToSign(i,s);if(0===a.length)throw new Error("LocalWallet: No inputs to sign");for(const o of a){const n=i.data.inputs[o.index];if(void 0===n)continue;const s=!(n.finalScriptSig??n.finalScriptWitness),a=this.addressType===e.AddressTypes.P2TR,u=void 0===n.tapInternalKey;if(s&&a&&u){const e=r.fromHexInternal(this.publicKey),i=33===e.length?e.subarray(1,33):e,s=r.createXOnlyPublicKey(i),{output:a}=t.payments.p2tr({internalPubkey:s,network:this.network});void 0!==a&&void 0!==n.witnessUtxo&&t.equals(n.witnessUtxo.script,a)&&(n.tapInternalKey=s)}}if(this.keyring,this.keyring.signTransaction(i,a),!0===s.autoFinalized)for(const e of a)i.finalizeInput(e.index);return i}async signMessage(e,t){switch(t){case"bip322-simple":return await F(e,this.address,this.network,e=>Promise.resolve(this.signPsbt(e,{autoFinalized:!1})));case"ecdsa":case"schnorr":{const t=S(this.getKeypair(),e);return r.toHex(t.signature)}case"mldsa":{const t=x(this.getQuantumKeypair(),e);return r.toHex(t.signature)}}}signData(e,t="ecdsa"){return this.keyring instanceof p?this.keyring.signData(e,t):this.keyring.signData(this.publicKey,e,t)}exportPrivateKey(){return this.keyring instanceof p?this.keyring.exportPrivateKey():this.keyring.exportAccount(this.publicKey)}exportQuantumPrivateKey(){if(this.keyring instanceof p)return this.keyring.exportQuantumPrivateKey();const e=this.keyring.getWallet(this.publicKey),t=e.mldsaKeypair.privateKey;if(void 0===t)throw new Error("LocalWallet: No quantum private key available");return r.toHex(r.concatBytes(t,e.chainCode))}exportRawQuantumPrivateKey(){if(this.keyring instanceof p)return this.keyring.exportRawQuantumPrivateKey();const e=this.keyring.getWallet(this.publicKey).mldsaKeypair.privateKey;if(void 0===e)throw new Error("LocalWallet: No quantum private key available");return r.toHex(e)}exportChainCode(){return this.keyring instanceof p?this.keyring.exportChainCode():this.keyring.getChainCode(this.publicKey)}exportWIF(){if(this.keyring instanceof p)return this.keyring.exportWIF();throw new Error("LocalWallet: Cannot export WIF from HD keyring directly")}getKeypair(){return this.keyring instanceof p?this.keyring.getKeypair():this.keyring.getWallet(this.publicKey).keypair}getQuantumKeypair(){return this.keyring instanceof p?this.keyring.getQuantumKeypair():this.keyring.getMLDSAKeypair(this.publicKey)}formatInputsToSign(e,r){const i=[];if(void 0!==r.toSignInputs&&r.toSignInputs.length>0)for(const t of r.toSignInputs){const e=t.index;if("address"in t){if(t.address!==this.address)throw new Error(`LocalWallet: Address mismatch at input ${e}`)}else if("publicKey"in t&&t.publicKey!==this.publicKey)throw new Error(`LocalWallet: Public key mismatch at input ${e}`);const r={index:e,publicKey:this.publicKey};void 0!==t.sighashTypes&&(r.sighashTypes=t.sighashTypes),void 0!==t.disableTweakSigner&&(r.disableTweakSigner=t.disableTweakSigner),i.push(r)}else for(let n=0;n<e.data.inputs.length;n++){const r=e.data.inputs[n];if(void 0===r)continue;let s;if(void 0!==r.witnessUtxo)s=r.witnessUtxo.script;else if(void 0!==r.nonWitnessUtxo){const i=e.txInputs[n];if(void 0!==i){const e=t.Transaction.fromBuffer(r.nonWitnessUtxo).outs[i.index];s=e?.script}}const a=r.finalScriptSig??r.finalScriptWitness;if(void 0!==s&&void 0===a){if(u(s,this.network)===this.address){const e={index:n,publicKey:this.publicKey};void 0!==r.sighashType&&(e.sighashTypes=[r.sighashType]),i.push(e)}}}return i}}exports.HdKeyring=l,exports.LocalWallet=R,exports.SimpleKeyring=p,exports.addressToScriptPubKey=function(e,r){return t.address.toOutputScript(e,r)},exports.decodeAddress=function(r){const i=t.networks.bitcoin,n=t.networks.testnet,s=t.networks.regtest,a=[{network:i,networkType:e.WalletNetworks.Mainnet},{network:n,networkType:e.WalletNetworks.Testnet},{network:s,networkType:e.WalletNetworks.Regtest}];for(const{network:e,networkType:o}of a)try{const i=t.address.toOutputScript(r,e),n=y(r,e);if(null!==n)return{networkType:o,addressType:n,scriptPubKey:i}}catch{}return null},exports.deserializeExport=k,exports.detectAddressType=y,exports.detectNetworkFromAddress=s,exports.exportWallet=m,exports.exportWalletToString=function(e,t,r,i,n,s,a){return K(m(e,t,r,i,n,s,a))},exports.extractBip322Signature=C,exports.fromLegacyExport=function(t,i){const n=r.fromHexInternal(t.classicalPrivateKey),s=e.EcKeyPair.fromPrivateKey(n,i),a={magic:d,version:1,network:w(i),classical:{privateKey:t.classicalPrivateKey,publicKey:r.toHex(s.publicKey)},quantum:{privateKey:t.quantumPrivateKey,publicKey:t.quantumPublicKey,securityLevel:t.securityLevel,chainCode:t.chainCode}},o=g(JSON.stringify(a));return{...a,checksum:o}},exports.generateBip322Psbt=N,exports.getAddressType=function(e,t){return y(e,n(t))},exports.getBech32Prefix=function(e){return n(e).bech32},exports.getNobleBackend=P,exports.importWallet=f,exports.importWalletFromString=function(e){return f(k(e))},exports.isAddressSignInput=function(e){return"address"in e},exports.isP2PKHOrP2SHAddress=function(t,r){return e.AddressVerificator.isP2PKHOrP2SH(t,r)},exports.isP2WPKHAddress=function(t,r){return e.AddressVerificator.isP2WPKHAddress(t,r)},exports.isPublicKeySignInput=function(e){return"publicKey"in e},exports.isValidAddress=c,exports.isValidAddressForNetworkType=function(e,t){return c(e,n(t))},exports.isValidP2TRAddress=function(t,r){return e.AddressVerificator.isValidP2TRAddress(t,r)},exports.isValidPublicKey=function(r,i){const n="string"==typeof r?r:t.toHex(r);return e.AddressVerificator.isValidPublicKey(n,i)},exports.publicKeyToAddress=a,exports.publicKeyToAddressWithNetworkType=function(e,t,r){return a(e,t,n(r))},exports.publicKeyToPayment=o,exports.publicKeyToScriptPubKey=function(e,t,r){const i=o(e,t,r);if(!i.output)throw new Error("Failed to generate script pubkey");return i.output},exports.scriptPubKeyToAddress=u,exports.serializeExport=K,exports.signBip322Message=F,exports.signBip322MessageWithNetworkType=async function(e,t,r,i){const s=n(r);return{address:t,message:e,signature:await F(e,t,s,i),networkType:r}},exports.signMLDSA=x,exports.signMessage=function(t,i,n){const s=I(i);switch(n){case"mldsa":{if(!H(t))throw new Error("ML-DSA signing requires a quantum keypair");const e=x(t,i);return{message:s,signature:e.signature,publicKey:e.publicKey,signatureType:"mldsa",securityLevel:e.securityLevel}}case"schnorr":{if(H(t))throw new Error("Schnorr signing requires a classical keypair");const e=S(t,i);return{message:s,signature:e.signature,publicKey:e.publicKey,signatureType:"schnorr"}}case"ecdsa":{if(H(t))throw new Error("ECDSA signing requires a classical keypair");const i=e.MessageSigner.sha256(s);return{message:s,signature:t.sign(r.createMessageHash(i)),publicKey:t.publicKey,signatureType:"ecdsa"}}}},exports.signSchnorr=S,exports.signTweakedSchnorr=function(r,i,n=t.networks.bitcoin){const s=e.MessageSigner.tweakAndSignMessage(r,i,n);return{message:s.message,signature:s.signature,publicKey:r.publicKey}},exports.toNetwork=n,exports.toNetworkType=function(r){return r.bech32===t.networks.bitcoin.bech32?e.WalletNetworks.Mainnet:r.bech32===t.networks.testnet.bech32?e.WalletNetworks.Testnet:e.WalletNetworks.Regtest},exports.validateAddressNetwork=function(e,t){return s(e)===t},exports.validateExport=function(e){try{if(e.magic!==d)return!1;if(1!==e.version)return!1;const t={magic:e.magic,version:e.version,network:e.network,classical:e.classical,quantum:e.quantum},r=g(JSON.stringify(t));return e.checksum===r}catch{return!1}},exports.verifyBip322Message=Q,exports.verifyBip322MessageWithNetworkType=function(e,t,r,i){return Q(e,t,r,n(i))},exports.verifyMLDSA=b,exports.verifyMLDSAWithKeypair=function(t,r,i){return e.MessageSigner.verifyMLDSASignature(t,r,i)},exports.verifyMessage=function(t,i,n,s,a,o,u){switch(s){case"mldsa":if(void 0===a||void 0===o||void 0===u)throw new Error("ML-DSA verification requires chainCode, network, and securityLevel");return b(t,a,o,u,i,n);case"schnorr":return T(t,i,n);case"ecdsa":{const s=I(i),a=e.MessageSigner.sha256(s);return P().verify(r.createMessageHash(a),r.createPublicKey(t),r.createSignature(n))}}},exports.verifySchnorr=T,exports.verifyTweakedSchnorr=function(t,r,i){return e.MessageSigner.tweakAndVerifySignature(t,r,i)};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@btc-vision/transaction"),t=require("@btc-vision/bitcoin"),r=require("@btc-vision/ecpair"),i=require("@btc-vision/bip32");function n(r){switch(r){case e.WalletNetworks.Mainnet:return t.networks.bitcoin;case e.WalletNetworks.Testnet:return t.networks.testnet;case e.WalletNetworks.Regtest:return t.networks.regtest;case e.WalletNetworks.OpnetTestnet:return t.networks.opnetTestnet;default:throw new Error(`Unsupported network type: ${r}`)}}function s(r){return r.bech32===t.networks.bitcoin.bech32?e.WalletNetworks.Mainnet:r.bech32===t.networks.testnet.bech32?e.WalletNetworks.Testnet:r.bech32===t.networks.opnetTestnet.bech32?e.WalletNetworks.OpnetTestnet:e.WalletNetworks.Regtest}function a(r){return r.startsWith(`${t.networks.regtest.bech32}1`)?e.WalletNetworks.Regtest:r.startsWith(`${t.networks.opnetTestnet.bech32}1`)?e.WalletNetworks.OpnetTestnet:r.startsWith(`${t.networks.bitcoin.bech32}1`)?e.WalletNetworks.Mainnet:r.startsWith(`${t.networks.testnet.bech32}1`)?e.WalletNetworks.Testnet:r.startsWith("1")||r.startsWith("3")?e.WalletNetworks.Mainnet:r.startsWith("m")||r.startsWith("n")||r.startsWith("2")?e.WalletNetworks.Testnet:null}function o(i,n,s){const a="string"==typeof i?r.fromHexInternal(i):i;switch(n){case e.AddressTypes.P2PKH:{const e=t.payments.p2pkh({pubkey:r.createPublicKey(a),network:s});if(void 0===e.address)throw new Error("Failed to generate P2PKH address");return e.address}case e.AddressTypes.P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});if(void 0===e.address)throw new Error("Failed to generate P2WPKH address");return e.address}case e.AddressTypes.P2TR:{const e=33===a.length?a.subarray(1,33):a,i=t.payments.p2tr({internalPubkey:r.createXOnlyPublicKey(e),network:s});if(void 0===i.address)throw new Error("Failed to generate P2TR address");return i.address}case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s}),i=t.payments.p2sh({redeem:e,network:s});if(void 0===i.address)throw new Error("Failed to generate P2SH-P2WPKH address");return i.address}default:throw new Error(`Unsupported address type: ${n}`)}}function u(i,n,s){const a="string"==typeof i?r.fromHexInternal(i):i;switch(n){case e.AddressTypes.P2PKH:return t.payments.p2pkh({pubkey:r.createPublicKey(a),network:s});case e.AddressTypes.P2WPKH:return t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});case e.AddressTypes.P2TR:{const e=33===a.length?a.subarray(1,33):a;return t.payments.p2tr({internalPubkey:r.createXOnlyPublicKey(e),network:s})}case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:{const e=t.payments.p2wpkh({pubkey:r.createPublicKey(a),network:s});return t.payments.p2sh({redeem:e,network:s})}default:throw new Error(`Unsupported address type: ${n}`)}}function c(e,r){const i="string"==typeof e?t.fromHex(e):e;return t.address.fromOutputScript(i,r)}function y(t,r){return null!==e.AddressVerificator.detectAddressType(t,r)}function l(t,r){return e.AddressVerificator.detectAddressType(t,r)}class p{static type="HD Key Tree";type=p.type;mnemonic=null;wallets=new Map;activeIndexes=[];network;securityLevel;passphrase;addressType;_hdPath;constructor(t){if(!t.network)throw new Error("HdKeyring: Network option is required");this.network=t.network,this.securityLevel=t?.securityLevel??e.MLDSASecurityLevel.LEVEL2,this.passphrase=t?.passphrase??"",this.addressType=t?.addressType??e.AddressTypes.P2TR,this._hdPath=t?.hdPath??"",void 0!==t?.mnemonic&&(this.initFromMnemonic(t.mnemonic),void 0!==t.activeIndexes&&t.activeIndexes.length>0&&this.activateAccounts([...t.activeIndexes]))}get hdPath(){return this._hdPath}static generate(r=e.MnemonicStrength.MAXIMUM,i="",n=t.networks.bitcoin,s=e.MLDSASecurityLevel.LEVEL2){const a=e.Mnemonic.generate(r,i,n,s),o=new p({network:n,securityLevel:s,passphrase:i});return o.mnemonic=a,o}initFromMnemonic(t){if(null!==this.mnemonic)throw new Error("HdKeyring: Mnemonic already initialized");this.mnemonic=new e.Mnemonic(t,this.passphrase,this.network,this.securityLevel)}getMnemonic(){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");return this.mnemonic.phrase}hasMnemonic(){return null!==this.mnemonic}deriveWallet(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const r=this.wallets.get(e);if(void 0!==r)return r;let i;if(this.isCustomHdPath()){const r=`${this._hdPath}/${e}`,n=`m/360'/${this.network===t.networks.bitcoin?0:1}'/0'/0/${e}`;i=this.mnemonic.deriveCustomPath(r,n)}else i=this.mnemonic.deriveOPWallet(this.addressType,e);return this.wallets.set(e,i),i}deriveStandardWallet(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");return this.mnemonic.derive(e)}addAccounts(e=1){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];let r=0;for(;t.length<e;){if(!this.activeIndexes.includes(r)){const e=this.deriveWallet(r);this.activeIndexes.push(r),t.push(e.toPublicKeyHex())}r++}return t}activateAccounts(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];for(const r of e)if(this.activeIndexes.includes(r)){const e=this.wallets.get(r);void 0!==e&&t.push(e.toPublicKeyHex())}else{const e=this.deriveWallet(r);this.activeIndexes.push(r),t.push(e.toPublicKeyHex())}return t}getAccounts(){return this.activeIndexes.map(e=>{const t=this.wallets.get(e);if(void 0===t)throw new Error(`HdKeyring: Wallet at index ${e} not found`);return t.toPublicKeyHex()})}getAccountsInfo(){return this.activeIndexes.map(e=>{const t=this.wallets.get(e);if(void 0===t)throw new Error(`HdKeyring: Wallet at index ${e} not found`);const r={p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy};return{index:e,publicKey:t.toPublicKeyHex(),quantumPublicKey:t.quantumPublicKeyHex,addresses:r}})}getQuantumPublicKey(e){return this.findWalletByPublicKey(e).quantumPublicKeyHex}getIndexByPublicKey(e){for(const[t,r]of this.wallets.entries())if(r.toPublicKeyHex()===e)return t;return null}getAddressesForPublicKey(e){const t=this.findWalletByPublicKey(e);return{p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy}}getAddress(e,t){return o(r.fromHexInternal(e),t,this.network)}removeAccount(e){const t=this.getIndexByPublicKey(e);if(null===t)throw new Error(`HdKeyring: Account with public key ${e} not found`);const r=this.activeIndexes.indexOf(t);-1!==r&&this.activeIndexes.splice(r,1),this.wallets.delete(t)}exportAccount(e){return this.findWalletByPublicKey(e).toPrivateKeyHex()}signTransaction(e,i){for(const n of i){const i=this.findWalletByPublicKey(n.publicKey),s=e.data.inputs[n.index];if(void 0===s)throw new Error(`HdKeyring: Input at index ${n.index} not found`);const a=i.keypair,o=void 0!==n.sighashTypes?[...n.sighashTypes]:void 0;if(t.isTaprootInput(s)&&!0!==n.disableTweakSigner){const t=i.publicKey.subarray(1,33),s=a.tweak(r.createBytes32(t));e.signInput(n.index,s,o)}else e.signInput(n.index,a,o)}return e}signData(e,t,i="ecdsa"){const n=this.findWalletByPublicKey(e),s=r.createMessageHash(r.fromHexInternal(t));if("ecdsa"===i)return r.toHex(n.keypair.sign(s));if(void 0===n.keypair.signSchnorr)throw new Error("HdKeyring: Schnorr signing not supported by this keypair");return r.toHex(n.keypair.signSchnorr(s))}getWallet(e){return this.findWalletByPublicKey(e)}serialize(){return{mnemonic:this.mnemonic?.phrase,passphrase:this.passphrase,network:this.network,securityLevel:this.securityLevel,activeIndexes:[...this.activeIndexes],addressType:this.addressType,hdPath:this._hdPath}}getActiveIndexes(){return[...this.activeIndexes]}setAddressType(e){this.addressType=e}getAddressType(){return this.addressType}getSecurityLevel(){return this.securityLevel}getNetwork(){return this.network}getAddressesPage(e,r=5){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const i=e*r,n=i+r,s=[];for(let a=i;a<n;a++){let e;if(this.isCustomHdPath()){const r=`${this._hdPath}/${a}`,i=`m/360'/${this.network===t.networks.bitcoin?0:1}'/0'/0/${a}`;e=this.mnemonic.deriveCustomPath(r,i)}else e=this.mnemonic.deriveOPWallet(this.addressType,a);const r=this.getAddressFromWallet(e);s.push({address:r,index:a})}return s}getChainCode(e){const t=this.findWalletByPublicKey(e);return Uint8Array.from(t.chainCode)}getMLDSAKeypair(e){return this.findWalletByPublicKey(e).mldsaKeypair}isCustomHdPath(){const t={[e.AddressTypes.P2PKH]:"m/44'/0'/0'/0",[e.AddressTypes.P2WPKH]:"m/84'/0'/0'/0",[e.AddressTypes.P2TR]:"m/86'/0'/0'/0",[e.AddressTypes.P2SH_OR_P2SH_P2WPKH]:"m/49'/0'/0'/0"}[this.addressType];if(void 0===t)return""!==this._hdPath;const r=t.slice(0,-2);return!this._hdPath.includes(r)&&""!==this._hdPath}findWalletByPublicKey(e){for(const t of this.wallets.values())if(t.toPublicKeyHex()===e)return t;throw new Error(`HdKeyring: Wallet with public key ${e} not found`)}getAddressFromWallet(t){switch(this.addressType){case e.AddressTypes.P2PKH:return t.legacy;case e.AddressTypes.P2WPKH:return t.p2wpkh;case e.AddressTypes.P2TR:return t.p2tr;case e.AddressTypes.P2SH_OR_P2SH_P2WPKH:return t.segwitLegacy;default:return t.p2tr}}}class d{static type="Simple Key Pair";type=d.type;network;securityLevel;keypair=null;quantumKeypair=null;chainCode=new Uint8Array(32);constructor(t){if(!t?.network)throw new Error("SimpleKeyring: Network option is required");this.network=t.network,this.securityLevel=t?.securityLevel??e.MLDSASecurityLevel.LEVEL2,void 0!==t?.privateKey&&this.importPrivateKey(t.privateKey,t.quantumPrivateKey)}static generate(r=t.networks.bitcoin,i=e.MLDSASecurityLevel.LEVEL2){const n=new d({network:r,securityLevel:i,privateKey:""});n.keypair=e.EcKeyPair.generateRandomKeyPair(r);const s=crypto.getRandomValues(new Uint8Array(64));return n.quantumKeypair=e.QuantumBIP32Factory.fromSeed(s,r,i),n.chainCode=Uint8Array.from(n.quantumKeypair.chainCode),n}static fromWIF(r,i,n=t.networks.bitcoin,s=e.MLDSASecurityLevel.LEVEL2){const a=new d({network:n,securityLevel:s,privateKey:""});return a.keypair=e.EcKeyPair.fromWIF(r,n),void 0!==i&&""!==i&&a.importQuantumKey(i),a}static fromPrivateKey(i,n,s=t.networks.bitcoin,a=e.MLDSASecurityLevel.LEVEL2){const o=new d({network:s,securityLevel:a,privateKey:""});return o.keypair=e.EcKeyPair.fromPrivateKey(r.fromHexInternal(i),s),void 0!==n&&""!==n&&o.importQuantumKey(n),o}importPrivateKey(t,i){""!==t&&(64===t.length?this.keypair=e.EcKeyPair.fromPrivateKey(r.fromHexInternal(t),this.network):this.keypair=e.EcKeyPair.fromWIF(t,this.network),void 0!==i&&""!==i&&this.importQuantumKey(i))}importQuantumKey(t){const n=r.fromHexInternal(t),s=i.getMLDSAConfig(this.securityLevel,this.network).privateKeySize,a=s+32,o=n.length===a,u=n.length===s;if(!o&&!u)throw new Error(`Invalid quantum key length: ${n.length} bytes. Expected ${s} bytes (key only) or ${a} bytes (key + chaincode).`);if(o){this.chainCode=n.slice(-32);const t=n.slice(0,-32);this.quantumKeypair=e.QuantumBIP32Factory.fromPrivateKey(t,this.chainCode,this.network,this.securityLevel)}else this.chainCode=crypto.getRandomValues(new Uint8Array(32)),this.quantumKeypair=e.QuantumBIP32Factory.fromPrivateKey(n,this.chainCode,this.network,this.securityLevel)}generateFreshQuantumKey(){const t=crypto.getRandomValues(new Uint8Array(64));this.quantumKeypair=e.QuantumBIP32Factory.fromSeed(t,this.network,this.securityLevel),this.chainCode=Uint8Array.from(this.quantumKeypair.chainCode)}hasKeys(){return null!==this.keypair&&null!==this.quantumKeypair}hasClassicalKey(){return null!==this.keypair}hasQuantumKey(){return null!==this.quantumKeypair}needsQuantumMigration(){return null!==this.keypair&&null===this.quantumKeypair}getPublicKey(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return r.toHex(this.keypair.publicKey)}getQuantumPublicKey(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return r.toHex(this.quantumKeypair.publicKey)}getQuantumPublicKeyOrUndefined(){if(null!==this.quantumKeypair)return r.toHex(this.quantumKeypair.publicKey)}getQuantumPublicKeyHash(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");const e=t.crypto.sha256(this.quantumKeypair.publicKey);return r.toHex(e)}clearQuantumKey(){this.quantumKeypair=null,this.chainCode=new Uint8Array(32)}getAccounts(){return null===this.keypair?[]:[this.getPublicKey()]}getAddresses(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const t=this.keypair.publicKey;return{p2pkh:o(t,e.AddressTypes.P2PKH,this.network),p2wpkh:o(t,e.AddressTypes.P2WPKH,this.network),p2tr:o(t,e.AddressTypes.P2TR,this.network),p2shP2wpkh:o(t,e.AddressTypes.P2SH_OR_P2SH_P2WPKH,this.network)}}getAddress(e){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return o(this.keypair.publicKey,e,this.network)}exportPrivateKey(){if(void 0===this.keypair?.privateKey)throw new Error("SimpleKeyring: No private key available");return r.toHex(this.keypair.privateKey)}exportQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return r.toHex(r.concatBytes(this.quantumKeypair.privateKey,this.chainCode))}exportRawQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return r.toHex(this.quantumKeypair.privateKey)}exportChainCode(){return this.chainCode}exportWIF(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return this.keypair.toWIF()}signTransaction(e,i){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");for(const n of i){const i=e.data.inputs[n.index];if(void 0===i)throw new Error(`SimpleKeyring: Input at index ${n.index} not found`);if(t.isTaprootInput(i)&&!0!==n.disableTweakSigner){const t=this.keypair.tweak(r.createBytes32(this.keypair.publicKey.subarray(1,33)));e.signInput(n.index,t,n.sighashTypes?[...n.sighashTypes]:void 0)}else e.signInput(n.index,this.keypair,n.sighashTypes?[...n.sighashTypes]:void 0)}return e}signData(e,t="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const i=r.createMessageHash(r.fromHexInternal(e));if("ecdsa"===t)return r.toHex(this.keypair.sign(i));if(void 0===this.keypair.signSchnorr)throw new Error("SimpleKeyring: Schnorr signing not supported by this keypair");return r.toHex(this.keypair.signSchnorr(i))}verify(e,t,i="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const n=r.createMessageHash(r.fromHexInternal(e));return"ecdsa"===i?this.keypair.verify(n,r.createSignature(r.fromHexInternal(t))):this.keypair.verifySchnorr(n,r.createSchnorrSignature(r.fromHexInternal(t)))}getKeypair(){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return this.keypair}getQuantumKeypair(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return this.quantumKeypair}getChainCode(){return this.chainCode}getSecurityLevel(){return this.securityLevel}getNetwork(){return this.network}serialize(){let e;try{e=this.exportQuantumPrivateKey()}catch{e=void 0}return{privateKey:this.exportPrivateKey(),quantumPrivateKey:e,network:this.network,securityLevel:this.securityLevel}}clear(){this.keypair=null,this.quantumKeypair=null,this.chainCode=new Uint8Array(32)}}const h="OPNET_WALLET_V1",g=new TextEncoder;function w(e){const i=t.crypto.sha256(g.encode(e));return r.toHex(i.subarray(0,4))}function m(e){return s(e)}function f(e,t,i,n,s,a,o){const u={magic:h,version:1,network:m(o),classical:{privateKey:r.toHex(e),publicKey:r.toHex(t)},quantum:{privateKey:r.toHex(i),publicKey:r.toHex(n),securityLevel:a,chainCode:r.toHex(s)}},c=w(JSON.stringify(u));return{...u,checksum:c}}function k(i){if(i.magic!==h)throw new Error("Invalid wallet export format: wrong magic header");if(1!==i.version)throw new Error(`Unsupported wallet export version: ${i.version}`);const s={magic:i.magic,version:i.version,network:i.network,classical:i.classical,quantum:i.quantum},a=w(JSON.stringify(s));if(i.checksum!==a)throw new Error("Invalid wallet export: checksum mismatch");const o=function(r){const i=r;return Object.values(e.WalletNetworks).includes(i)?n(i):t.networks.bitcoin}(i.network),u=r.fromHexInternal(i.quantum.chainCode),c=r.fromHexInternal(i.classical.privateKey),y=e.EcKeyPair.fromPrivateKey(c,o),l=r.fromHexInternal(i.quantum.privateKey);return{keypair:y,quantumKeypair:e.QuantumBIP32Factory.fromPrivateKey(l,u,o,i.quantum.securityLevel),network:o,securityLevel:i.quantum.securityLevel,chainCode:u}}function K(e){const t=JSON.stringify(e);return btoa(t)}function v(e){try{const t=atob(e);return JSON.parse(t)}catch{throw new Error("Invalid wallet export: failed to deserialize")}}let P;function x(){return P??=r.createNobleBackend(),P}function b(t,r){const i=e.MessageSigner.signMLDSAMessage(t,r);return{message:i.message,signature:i.signature,publicKey:i.publicKey,securityLevel:i.securityLevel}}function T(t,r,i,n,s,a){const o=e.QuantumBIP32Factory.fromPublicKey(t,r,i,n);return e.MessageSigner.verifyMLDSASignature(o,s,a)}function S(t,r){const i=e.MessageSigner.signMessage(t,r);return{message:i.message,signature:i.signature,publicKey:t.publicKey}}function H(t,r,i){return e.MessageSigner.verifySignature(t,r,i)}function A(e){return"securityLevel"in e&&"chainCode"in e}const W=new TextEncoder;function I(e){return"string"==typeof e?W.encode(e):e}const E=new TextEncoder,L=t.toSatoshi(0n);function q(e){const t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}const N=[e.AddressTypes.P2WPKH,e.AddressTypes.P2TR];function M(e){const r=t.crypto.sha256(E.encode("BIP0322-signed-message")),i="string"==typeof e?E.encode(e):e;return t.crypto.sha256(t.concat([r,r,i]))}function C(e,r,i){const n=t.address.toOutputScript(r,i),s=l(r,i);if(null===s||!N.includes(s))throw new Error(`BIP322: Address type not supported for signing. Got: ${String(s)}`);const a=M(e),o=t.alloc(32),u=t.concat([t.fromHex("0020"),a]),c=new t.Transaction;c.version=0,c.addInput(o,4294967295,0,u),c.addOutput(n,L);const y=new t.Psbt({network:i});return y.setVersion(0),y.addInput({hash:c.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:L}}),y.addOutput({script:t.fromHex("6a"),value:L}),y}function O(e){const r=e.extractTransaction(),i=r.ins[0]?.witness;if(void 0===i||0===i.length)throw new Error("BIP322: No witness data found in signed transaction");const n=t.script.number.encode(i.length);return function(e){let t="";for(const r of e)t+=String.fromCharCode(r);return btoa(t)}(t.concat([n,...i.map(e=>function(e){const r=t.script.number.encode(e.length);return t.concat([r,e])}(e))]))}async function F(e,t,r,i){const n=C(e,t,r),s=await i(n);return s.finalizeAllInputs(),O(s)}const B=(e,i,n)=>{try{const s=t.script.signature.decode(n);return x().verify(r.createMessageHash(i),r.createPublicKey(e),r.createSignature(s.signature))}catch{return!1}};function Q(e,i,n,s){try{const a=t.address.toOutputScript(e,s),o=M(i),u=t.alloc(32),c=4294967295,y=0,l=t.concat([t.fromHex("0020"),o]),p=new t.Transaction;p.version=0,p.addInput(u,c,y,l),p.addOutput(a,L);const d=q(n),h=t.script.decompile(d.subarray(1));if(!Array.isArray(h)||0===h.length)return!1;const g=h[0];if(!(g instanceof Uint8Array))return!1;const w=t.concat([t.fromHex("02"),a.subarray(2)]),m=new t.Psbt({network:s});m.setVersion(0),m.addInput({hash:p.getHash(),index:0,sequence:0,witnessUtxo:{script:a,value:L}}),m.addOutput({script:t.fromHex("6a"),value:L});const f=m.data.globalMap.unsignedTx.tx;return function(e,t,i){try{const n=33===e.length?e.subarray(1,33):e;return x().verifySchnorr(r.createMessageHash(t),r.createXOnlyPublicKey(n),r.createSchnorrSignature(i))}catch{return!1}}(w,f.hashForWitnessV1(0,[a],[L],t.Transaction.SIGHASH_DEFAULT),g)}catch{return!1}}function R(r,i,n,s){const a=l(r,s);if(null===a)return!1;switch(a){case e.AddressTypes.P2TR:return Q(r,i,n,s);case e.AddressTypes.P2WPKH:return function(e,r,i,n){try{const s=t.address.toOutputScript(e,n),a=M(r),o=t.alloc(32),u=4294967295,c=0,y=t.concat([t.fromHex("0020"),a]),l=new t.Transaction;l.version=0,l.addInput(o,u,c,y),l.addOutput(s,L);const p=q(i),d=t.script.decompile(p.subarray(1));if(!Array.isArray(d)||d.length<2)return!1;const h=d[0],g=d[1];if(!(h instanceof Uint8Array&&g instanceof Uint8Array))return!1;const w=new t.Psbt({network:n});return w.setVersion(0),w.addInput({hash:l.getHash(),index:0,sequence:0,witnessUtxo:{script:s,value:L}}),w.addOutput({script:t.fromHex("6a"),value:L}),w.updateInput(0,{partialSig:[{pubkey:g,signature:h}]}),w.validateSignaturesOfAllInputs(B)}catch{return!1}}(r,i,n,s);default:return!1}}class z{keyring;network;addressType;publicKey;address;constructor(e,t,i,n){this.keyring=e,this.network=t,this.addressType=i,this.publicKey=n,this.address=o(r.fromHexInternal(n),i,t)}static fromWIF(t,r=e.AddressTypes.P2TR,i,n){const s=d.fromWIF(t,n,i),a=s.getPublicKey();return new z(s,i,r,a)}static fromPrivateKey(t,r=e.AddressTypes.P2TR,i,n){const s=d.fromPrivateKey(t,n,i),a=s.getPublicKey();return new z(s,i,r,a)}static fromMnemonic(t,r=e.AddressTypes.P2TR,i,n,s=0){const a=new p({mnemonic:t,passphrase:n,network:i,addressType:r,activeIndexes:[s]}),o=a.getAccounts()[0];if(void 0===o)throw new Error("Failed to derive wallet from mnemonic");return new z(a,i,r,o)}static random(r=e.AddressTypes.P2TR,i=t.networks.bitcoin){const n=d.generate(i),s=n.getPublicKey();return new z(n,i,r,s)}getAddress(){return this.address}getPublicKey(){return this.publicKey}getQuantumPublicKey(){return this.keyring instanceof d?this.keyring.getQuantumPublicKey():this.keyring.getQuantumPublicKey(this.publicKey)}getNetwork(){return this.network}getAddressType(){return this.addressType}signPsbt(i,n){const s=n??{autoFinalized:!0,toSignInputs:[]},a=this.formatInputsToSign(i,s);if(0===a.length)throw new Error("LocalWallet: No inputs to sign");for(const o of a){const n=i.data.inputs[o.index];if(void 0===n)continue;const s=!(n.finalScriptSig??n.finalScriptWitness),a=this.addressType===e.AddressTypes.P2TR,u=void 0===n.tapInternalKey;if(s&&a&&u){const e=r.fromHexInternal(this.publicKey),i=33===e.length?e.subarray(1,33):e,s=r.createXOnlyPublicKey(i),{output:a}=t.payments.p2tr({internalPubkey:s,network:this.network});void 0!==a&&void 0!==n.witnessUtxo&&t.equals(n.witnessUtxo.script,a)&&(n.tapInternalKey=s)}}if(this.keyring,this.keyring.signTransaction(i,a),!0===s.autoFinalized)for(const e of a)i.finalizeInput(e.index);return i}async signMessage(e,t){switch(t){case"bip322-simple":return await F(e,this.address,this.network,e=>Promise.resolve(this.signPsbt(e,{autoFinalized:!1})));case"ecdsa":case"schnorr":{const t=S(this.getKeypair(),e);return r.toHex(t.signature)}case"mldsa":{const t=b(this.getQuantumKeypair(),e);return r.toHex(t.signature)}}}signData(e,t="ecdsa"){return this.keyring instanceof d?this.keyring.signData(e,t):this.keyring.signData(this.publicKey,e,t)}exportPrivateKey(){return this.keyring instanceof d?this.keyring.exportPrivateKey():this.keyring.exportAccount(this.publicKey)}exportQuantumPrivateKey(){if(this.keyring instanceof d)return this.keyring.exportQuantumPrivateKey();const e=this.keyring.getWallet(this.publicKey),t=e.mldsaKeypair.privateKey;if(void 0===t)throw new Error("LocalWallet: No quantum private key available");return r.toHex(r.concatBytes(t,e.chainCode))}exportRawQuantumPrivateKey(){if(this.keyring instanceof d)return this.keyring.exportRawQuantumPrivateKey();const e=this.keyring.getWallet(this.publicKey).mldsaKeypair.privateKey;if(void 0===e)throw new Error("LocalWallet: No quantum private key available");return r.toHex(e)}exportChainCode(){return this.keyring instanceof d?this.keyring.exportChainCode():this.keyring.getChainCode(this.publicKey)}exportWIF(){if(this.keyring instanceof d)return this.keyring.exportWIF();throw new Error("LocalWallet: Cannot export WIF from HD keyring directly")}getKeypair(){return this.keyring instanceof d?this.keyring.getKeypair():this.keyring.getWallet(this.publicKey).keypair}getQuantumKeypair(){return this.keyring instanceof d?this.keyring.getQuantumKeypair():this.keyring.getMLDSAKeypair(this.publicKey)}formatInputsToSign(e,r){const i=[];if(void 0!==r.toSignInputs&&r.toSignInputs.length>0)for(const t of r.toSignInputs){const e=t.index;if("address"in t){if(t.address!==this.address)throw new Error(`LocalWallet: Address mismatch at input ${e}`)}else if("publicKey"in t&&t.publicKey!==this.publicKey)throw new Error(`LocalWallet: Public key mismatch at input ${e}`);const r={index:e,publicKey:this.publicKey};void 0!==t.sighashTypes&&(r.sighashTypes=t.sighashTypes),void 0!==t.disableTweakSigner&&(r.disableTweakSigner=t.disableTweakSigner),i.push(r)}else for(let n=0;n<e.data.inputs.length;n++){const r=e.data.inputs[n];if(void 0===r)continue;let s;if(void 0!==r.witnessUtxo)s=r.witnessUtxo.script;else if(void 0!==r.nonWitnessUtxo){const i=e.txInputs[n];if(void 0!==i){const e=t.Transaction.fromBuffer(r.nonWitnessUtxo).outs[i.index];s=e?.script}}const a=r.finalScriptSig??r.finalScriptWitness;if(void 0!==s&&void 0===a){if(c(s,this.network)===this.address){const e={index:n,publicKey:this.publicKey};void 0!==r.sighashType&&(e.sighashTypes=[r.sighashType]),i.push(e)}}}return i}}exports.HdKeyring=p,exports.LocalWallet=z,exports.SimpleKeyring=d,exports.addressToScriptPubKey=function(e,r){return t.address.toOutputScript(e,r)},exports.decodeAddress=function(r){const i=[{network:t.networks.bitcoin,networkType:e.WalletNetworks.Mainnet},{network:t.networks.opnetTestnet,networkType:e.WalletNetworks.OpnetTestnet},{network:t.networks.testnet,networkType:e.WalletNetworks.Testnet},{network:t.networks.regtest,networkType:e.WalletNetworks.Regtest}];for(const{network:e,networkType:n}of i)try{const i=t.address.toOutputScript(r,e),s=l(r,e);if(null!==s)return{networkType:n,addressType:s,scriptPubKey:i}}catch{}return null},exports.deserializeExport=v,exports.detectAddressType=l,exports.detectNetworkFromAddress=a,exports.exportWallet=f,exports.exportWalletToString=function(e,t,r,i,n,s,a){return K(f(e,t,r,i,n,s,a))},exports.extractBip322Signature=O,exports.fromLegacyExport=function(t,i){const n=r.fromHexInternal(t.classicalPrivateKey),s=e.EcKeyPair.fromPrivateKey(n,i),a={magic:h,version:1,network:m(i),classical:{privateKey:t.classicalPrivateKey,publicKey:r.toHex(s.publicKey)},quantum:{privateKey:t.quantumPrivateKey,publicKey:t.quantumPublicKey,securityLevel:t.securityLevel,chainCode:t.chainCode}},o=w(JSON.stringify(a));return{...a,checksum:o}},exports.generateBip322Psbt=C,exports.getAddressType=function(e,t){return l(e,n(t))},exports.getBech32Prefix=function(e){return n(e).bech32},exports.getNobleBackend=x,exports.importWallet=k,exports.importWalletFromString=function(e){return k(v(e))},exports.isAddressSignInput=function(e){return"address"in e},exports.isP2PKHOrP2SHAddress=function(t,r){return e.AddressVerificator.isP2PKHOrP2SH(t,r)},exports.isP2WPKHAddress=function(t,r){return e.AddressVerificator.isP2WPKHAddress(t,r)},exports.isPublicKeySignInput=function(e){return"publicKey"in e},exports.isValidAddress=y,exports.isValidAddressForNetworkType=function(e,t){return y(e,n(t))},exports.isValidP2TRAddress=function(t,r){return e.AddressVerificator.isValidP2TRAddress(t,r)},exports.isValidPublicKey=function(r,i){const n="string"==typeof r?r:t.toHex(r);return e.AddressVerificator.isValidPublicKey(n,i)},exports.publicKeyToAddress=o,exports.publicKeyToAddressWithNetworkType=function(e,t,r){return o(e,t,n(r))},exports.publicKeyToPayment=u,exports.publicKeyToScriptPubKey=function(e,t,r){const i=u(e,t,r);if(!i.output)throw new Error("Failed to generate script pubkey");return i.output},exports.scriptPubKeyToAddress=c,exports.serializeExport=K,exports.signBip322Message=F,exports.signBip322MessageWithNetworkType=async function(e,t,r,i){const s=n(r);return{address:t,message:e,signature:await F(e,t,s,i),networkType:r}},exports.signMLDSA=b,exports.signMessage=function(t,i,n){const s=I(i);switch(n){case"mldsa":{if(!A(t))throw new Error("ML-DSA signing requires a quantum keypair");const e=b(t,i);return{message:s,signature:e.signature,publicKey:e.publicKey,signatureType:"mldsa",securityLevel:e.securityLevel}}case"schnorr":{if(A(t))throw new Error("Schnorr signing requires a classical keypair");const e=S(t,i);return{message:s,signature:e.signature,publicKey:e.publicKey,signatureType:"schnorr"}}case"ecdsa":{if(A(t))throw new Error("ECDSA signing requires a classical keypair");const i=e.MessageSigner.sha256(s);return{message:s,signature:t.sign(r.createMessageHash(i)),publicKey:t.publicKey,signatureType:"ecdsa"}}}},exports.signSchnorr=S,exports.signTweakedSchnorr=function(r,i,n=t.networks.bitcoin){const s=e.MessageSigner.tweakAndSignMessage(r,i,n);return{message:s.message,signature:s.signature,publicKey:r.publicKey}},exports.toNetwork=n,exports.toNetworkType=s,exports.validateAddressNetwork=function(e,t){return a(e)===t},exports.validateExport=function(e){try{if(e.magic!==h)return!1;if(1!==e.version)return!1;const t={magic:e.magic,version:e.version,network:e.network,classical:e.classical,quantum:e.quantum},r=w(JSON.stringify(t));return e.checksum===r}catch{return!1}},exports.verifyBip322Message=R,exports.verifyBip322MessageWithNetworkType=function(e,t,r,i){return R(e,t,r,n(i))},exports.verifyMLDSA=T,exports.verifyMLDSAWithKeypair=function(t,r,i){return e.MessageSigner.verifyMLDSASignature(t,r,i)},exports.verifyMessage=function(t,i,n,s,a,o,u){switch(s){case"mldsa":if(void 0===a||void 0===o||void 0===u)throw new Error("ML-DSA verification requires chainCode, network, and securityLevel");return T(t,a,o,u,i,n);case"schnorr":return H(t,i,n);case"ecdsa":{const s=I(i),a=e.MessageSigner.sha256(s);return x().verify(r.createMessageHash(a),r.createPublicKey(t),r.createSignature(n))}}},exports.verifySchnorr=H,exports.verifyTweakedSchnorr=function(t,r,i){return e.MessageSigner.tweakAndVerifySignature(t,r,i)};
2
2
  //# sourceMappingURL=index.cjs.js.map