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

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.d.ts CHANGED
@@ -113,7 +113,11 @@ export declare function deserializeExport(serialized: string): UnifiedWalletExpo
113
113
  export declare function detectAddressType(address: string, network: Network): AddressTypes | null;
114
114
 
115
115
  /**
116
- * Detect network type from an address
116
+ * Detect network type from an address.
117
+ *
118
+ * Handles bech32/bech32m (segwit), base58 P2PKH and P2SH formats.
119
+ * Order matters: more specific prefixes (bcrt1, opt1) are checked before
120
+ * shorter ones (bc1, tb1) to avoid false matches.
117
121
  */
118
122
  export declare function detectNetworkFromAddress(address: string): WalletNetworks | null;
119
123
 
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{WalletNetworks as e,AddressVerificator as t,AddressTypes as i,MLDSASecurityLevel as r,MnemonicStrength as n,Mnemonic as s,EcKeyPair as a,QuantumBIP32Factory as o,MessageSigner as u}from"@btc-vision/transaction";import{networks as c,address as h,toHex as y,payments as l,fromHex as p,isTaprootInput as d,crypto as g,toSatoshi as w,script as m,concat as f,alloc as K,Transaction as k,Psbt as v,equals as P}from"@btc-vision/bitcoin";import{fromHexInternal as b,createPublicKey as x,createXOnlyPublicKey as S,createBytes32 as T,createMessageHash as E,toHex as H,concatBytes as W,createSignature as L,createSchnorrSignature as I,createNobleBackend as A}from"@btc-vision/ecpair";import{getMLDSAConfig as q}from"@btc-vision/bip32";function C(t){switch(t){case e.Mainnet:return c.bitcoin;case e.Testnet:return c.testnet;case e.Regtest:return c.regtest}}function N(t){return t.bech32===c.bitcoin.bech32?e.Mainnet:t.bech32===c.testnet.bech32?e.Testnet:e.Regtest}function R(e){return C(e).bech32}function O(t){return t.startsWith("bc1")||t.startsWith("1")||t.startsWith("3")?e.Mainnet:t.startsWith("tb1")||t.startsWith("m")||t.startsWith("n")||t.startsWith("2")?e.Testnet:t.startsWith("bcrt1")?e.Regtest:null}function U(e,t){return O(e)===t}function z(e,t,r){const n="string"==typeof e?b(e):e;switch(t){case i.P2PKH:{const e=l.p2pkh({pubkey:x(n),network:r});if(void 0===e.address)throw new Error("Failed to generate P2PKH address");return e.address}case i.P2WPKH:{const e=l.p2wpkh({pubkey:x(n),network:r});if(void 0===e.address)throw new Error("Failed to generate P2WPKH address");return e.address}case i.P2TR:{const e=33===n.length?n.subarray(1,33):n,t=l.p2tr({internalPubkey:S(e),network:r});if(void 0===t.address)throw new Error("Failed to generate P2TR address");return t.address}case i.P2SH_OR_P2SH_P2WPKH:{const e=l.p2wpkh({pubkey:x(n),network:r}),t=l.p2sh({redeem:e,network:r});if(void 0===t.address)throw new Error("Failed to generate P2SH-P2WPKH address");return t.address}default:throw new Error(`Unsupported address type: ${t}`)}}function F(e,t,r){const n="string"==typeof e?b(e):e;switch(t){case i.P2PKH:return l.p2pkh({pubkey:x(n),network:r});case i.P2WPKH:return l.p2wpkh({pubkey:x(n),network:r});case i.P2TR:{const e=33===n.length?n.subarray(1,33):n;return l.p2tr({internalPubkey:S(e),network:r})}case i.P2SH_OR_P2SH_P2WPKH:{const e=l.p2wpkh({pubkey:x(n),network:r});return l.p2sh({redeem:e,network:r})}default:throw new Error(`Unsupported address type: ${t}`)}}function M(e,t,i){const r=F(e,t,i);if(!r.output)throw new Error("Failed to generate script pubkey");return r.output}function _(e,t){return h.toOutputScript(e,t)}function Q(e,t){const i="string"==typeof e?p(e):e;return h.fromOutputScript(i,t)}function $(e,i){return null!==t.detectAddressType(e,i)}function V(e,i){return t.detectAddressType(e,i)}function D(t){const i=c.bitcoin,r=c.testnet,n=c.regtest,s=[{network:i,networkType:e.Mainnet},{network:r,networkType:e.Testnet},{network:n,networkType:e.Regtest}];for(const{network:e,networkType:a}of s)try{const i=h.toOutputScript(t,e),r=V(t,e);if(null!==r)return{networkType:a,addressType:r,scriptPubKey:i}}catch{}return null}function B(e,i){const r="string"==typeof e?e:y(e);return t.isValidPublicKey(r,i)}function J(e,i){return t.isValidP2TRAddress(e,i)}function G(e,i){return t.isP2WPKHAddress(e,i)}function X(e,i){return t.isP2PKHOrP2SH(e,i)}function j(e,t){return $(e,C(t))}function Y(e,t){return V(e,C(t))}function Z(e,t,i){return z(e,t,C(i))}class ee{static type="HD Key Tree";type=ee.type;mnemonic=null;wallets=/* @__PURE__ */new Map;activeIndexes=[];network;securityLevel;passphrase;addressType;_hdPath;constructor(e){if(!e.network)throw new Error("HdKeyring: Network option is required");this.network=e.network,this.securityLevel=e?.securityLevel??r.LEVEL2,this.passphrase=e?.passphrase??"",this.addressType=e?.addressType??i.P2TR,this._hdPath=e?.hdPath??"",void 0!==e?.mnemonic&&(this.initFromMnemonic(e.mnemonic),void 0!==e.activeIndexes&&e.activeIndexes.length>0&&this.activateAccounts([...e.activeIndexes]))}get hdPath(){return this._hdPath}static generate(e=n.MAXIMUM,t="",i=c.bitcoin,a=r.LEVEL2){const o=s.generate(e,t,i,a),u=new ee({network:i,securityLevel:a,passphrase:t});return u.mnemonic=o,u}initFromMnemonic(e){if(null!==this.mnemonic)throw new Error("HdKeyring: Mnemonic already initialized");this.mnemonic=new s(e,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 t=this.wallets.get(e);if(void 0!==t)return t;let i;if(this.isCustomHdPath()){const t=`${this._hdPath}/${e}`,r=`m/360'/${this.network===c.bitcoin?0:1}'/0'/0/${e}`;i=this.mnemonic.deriveCustomPath(t,r)}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 i=0;for(;t.length<e;){if(!this.activeIndexes.includes(i)){const e=this.deriveWallet(i);this.activeIndexes.push(i),t.push(e.toPublicKeyHex())}i++}return t}activateAccounts(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];for(const i of e)if(this.activeIndexes.includes(i)){const e=this.wallets.get(i);void 0!==e&&t.push(e.toPublicKeyHex())}else{const e=this.deriveWallet(i);this.activeIndexes.push(i),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 i={p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy};return{index:e,publicKey:t.toPublicKeyHex(),quantumPublicKey:t.quantumPublicKeyHex,addresses:i}})}getQuantumPublicKey(e){return this.findWalletByPublicKey(e).quantumPublicKeyHex}getIndexByPublicKey(e){for(const[t,i]of this.wallets.entries())if(i.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 z(b(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 i=this.activeIndexes.indexOf(t);-1!==i&&this.activeIndexes.splice(i,1),this.wallets.delete(t)}exportAccount(e){return this.findWalletByPublicKey(e).toPrivateKeyHex()}signTransaction(e,t){for(const i of t){const t=this.findWalletByPublicKey(i.publicKey),r=e.data.inputs[i.index];if(void 0===r)throw new Error(`HdKeyring: Input at index ${i.index} not found`);const n=t.keypair,s=void 0!==i.sighashTypes?[...i.sighashTypes]:void 0;if(d(r)&&!0!==i.disableTweakSigner){const r=t.publicKey.subarray(1,33),a=n.tweak(T(r));e.signInput(i.index,a,s)}else e.signInput(i.index,n,s)}return e}signData(e,t,i="ecdsa"){const r=this.findWalletByPublicKey(e),n=E(b(t));if("ecdsa"===i)return H(r.keypair.sign(n));if(void 0===r.keypair.signSchnorr)throw new Error("HdKeyring: Schnorr signing not supported by this keypair");return H(r.keypair.signSchnorr(n))}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,t=5){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const i=e*t,r=i+t,n=[];for(let s=i;s<r;s++){let e;if(this.isCustomHdPath()){const t=`${this._hdPath}/${s}`,i=`m/360'/${this.network===c.bitcoin?0:1}'/0'/0/${s}`;e=this.mnemonic.deriveCustomPath(t,i)}else e=this.mnemonic.deriveOPWallet(this.addressType,s);const t=this.getAddressFromWallet(e);n.push({address:t,index:s})}return n}getChainCode(e){const t=this.findWalletByPublicKey(e);return Uint8Array.from(t.chainCode)}getMLDSAKeypair(e){return this.findWalletByPublicKey(e).mldsaKeypair}isCustomHdPath(){const e={[i.P2PKH]:"m/44'/0'/0'/0",[i.P2WPKH]:"m/84'/0'/0'/0",[i.P2TR]:"m/86'/0'/0'/0",[i.P2SH_OR_P2SH_P2WPKH]:"m/49'/0'/0'/0"}[this.addressType];if(void 0===e)return""!==this._hdPath;const t=e.slice(0,-2);return!this._hdPath.includes(t)&&""!==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(e){switch(this.addressType){case i.P2PKH:return e.legacy;case i.P2WPKH:return e.p2wpkh;case i.P2TR:return e.p2tr;case i.P2SH_OR_P2SH_P2WPKH:return e.segwitLegacy;default:return e.p2tr}}}class te{static type="Simple Key Pair";type=te.type;network;securityLevel;keypair=null;quantumKeypair=null;chainCode=new Uint8Array(32);constructor(e){if(!e?.network)throw new Error("SimpleKeyring: Network option is required");this.network=e.network,this.securityLevel=e?.securityLevel??r.LEVEL2,void 0!==e?.privateKey&&this.importPrivateKey(e.privateKey,e.quantumPrivateKey)}static generate(e=c.bitcoin,t=r.LEVEL2){const i=new te({network:e,securityLevel:t,privateKey:""});i.keypair=a.generateRandomKeyPair(e);const n=crypto.getRandomValues(new Uint8Array(64));return i.quantumKeypair=o.fromSeed(n,e,t),i.chainCode=Uint8Array.from(i.quantumKeypair.chainCode),i}static fromWIF(e,t,i=c.bitcoin,n=r.LEVEL2){const s=new te({network:i,securityLevel:n,privateKey:""});return s.keypair=a.fromWIF(e,i),void 0!==t&&""!==t&&s.importQuantumKey(t),s}static fromPrivateKey(e,t,i=c.bitcoin,n=r.LEVEL2){const s=new te({network:i,securityLevel:n,privateKey:""});return s.keypair=a.fromPrivateKey(b(e),i),void 0!==t&&""!==t&&s.importQuantumKey(t),s}importPrivateKey(e,t){""!==e&&(64===e.length?this.keypair=a.fromPrivateKey(b(e),this.network):this.keypair=a.fromWIF(e,this.network),void 0!==t&&""!==t&&this.importQuantumKey(t))}importQuantumKey(e){const t=b(e),i=q(this.securityLevel,this.network).privateKeySize,r=i+32,n=t.length===r,s=t.length===i;if(!n&&!s)throw new Error(`Invalid quantum key length: ${t.length} bytes. Expected ${i} bytes (key only) or ${r} bytes (key + chaincode).`);if(n){this.chainCode=t.slice(-32);const e=t.slice(0,-32);this.quantumKeypair=o.fromPrivateKey(e,this.chainCode,this.network,this.securityLevel)}else this.chainCode=crypto.getRandomValues(new Uint8Array(32)),this.quantumKeypair=o.fromPrivateKey(t,this.chainCode,this.network,this.securityLevel)}generateFreshQuantumKey(){const e=crypto.getRandomValues(new Uint8Array(64));this.quantumKeypair=o.fromSeed(e,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 H(this.keypair.publicKey)}getQuantumPublicKey(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return H(this.quantumKeypair.publicKey)}getQuantumPublicKeyOrUndefined(){if(null!==this.quantumKeypair)return H(this.quantumKeypair.publicKey)}getQuantumPublicKeyHash(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");const e=g.sha256(this.quantumKeypair.publicKey);return H(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 e=this.keypair.publicKey;return{p2pkh:z(e,i.P2PKH,this.network),p2wpkh:z(e,i.P2WPKH,this.network),p2tr:z(e,i.P2TR,this.network),p2shP2wpkh:z(e,i.P2SH_OR_P2SH_P2WPKH,this.network)}}getAddress(e){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return z(this.keypair.publicKey,e,this.network)}exportPrivateKey(){if(void 0===this.keypair?.privateKey)throw new Error("SimpleKeyring: No private key available");return H(this.keypair.privateKey)}exportQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return H(W(this.quantumKeypair.privateKey,this.chainCode))}exportRawQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return H(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,t){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");for(const i of t){const t=e.data.inputs[i.index];if(void 0===t)throw new Error(`SimpleKeyring: Input at index ${i.index} not found`);if(d(t)&&!0!==i.disableTweakSigner){const t=this.keypair.tweak(T(this.keypair.publicKey.subarray(1,33)));e.signInput(i.index,t,i.sighashTypes?[...i.sighashTypes]:void 0)}else e.signInput(i.index,this.keypair,i.sighashTypes?[...i.sighashTypes]:void 0)}return e}signData(e,t="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const i=E(b(e));if("ecdsa"===t)return H(this.keypair.sign(i));if(void 0===this.keypair.signSchnorr)throw new Error("SimpleKeyring: Schnorr signing not supported by this keypair");return H(this.keypair.signSchnorr(i))}verify(e,t,i="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const r=E(b(e));return"ecdsa"===i?this.keypair.verify(r,L(b(t))):this.keypair.verifySchnorr(r,I(b(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 ie="OPNET_WALLET_V1",re=new TextEncoder;function ne(e){const t=g.sha256(re.encode(e));return H(t.subarray(0,4))}function se(e){return e.bech32===c.bitcoin.bech32?"mainnet":e.bech32===c.testnet.bech32?"testnet":"regtest"}function ae(e,t,i,r,n,s,a){const o={magic:ie,version:1,network:se(a),classical:{privateKey:H(e),publicKey:H(t)},quantum:{privateKey:H(i),publicKey:H(r),securityLevel:s,chainCode:H(n)}},u=ne(JSON.stringify(o));return{...o,checksum:u}}function oe(e){if(e.magic!==ie)throw new Error("Invalid wallet export format: wrong magic header");if(1!==e.version)throw new Error(`Unsupported wallet export version: ${e.version}`);const t={magic:e.magic,version:e.version,network:e.network,classical:e.classical,quantum:e.quantum},i=ne(JSON.stringify(t));if(e.checksum!==i)throw new Error("Invalid wallet export: checksum mismatch");const r=function(e){switch(e){case"mainnet":default:return c.bitcoin;case"testnet":return c.testnet;case"regtest":return c.regtest}}(e.network),n=b(e.quantum.chainCode),s=b(e.classical.privateKey),u=a.fromPrivateKey(s,r),h=b(e.quantum.privateKey);return{keypair:u,quantumKeypair:o.fromPrivateKey(h,n,r,e.quantum.securityLevel),network:r,securityLevel:e.quantum.securityLevel,chainCode:n}}function ue(e){const t=JSON.stringify(e);return btoa(t)}function ce(e){try{const t=atob(e);return JSON.parse(t)}catch{throw new Error("Invalid wallet export: failed to deserialize")}}function he(e,t,i,r,n,s,a){return ue(ae(e,t,i,r,n,s,a))}function ye(e){return oe(ce(e))}function le(e){try{if(e.magic!==ie)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},i=ne(JSON.stringify(t));return e.checksum===i}catch{return!1}}function pe(e,t){const i=b(e.classicalPrivateKey),r=a.fromPrivateKey(i,t),n={magic:ie,version:1,network:se(t),classical:{privateKey:e.classicalPrivateKey,publicKey:H(r.publicKey)},quantum:{privateKey:e.quantumPrivateKey,publicKey:e.quantumPublicKey,securityLevel:e.securityLevel,chainCode:e.chainCode}},s=ne(JSON.stringify(n));return{...n,checksum:s}}let de;function ge(){return de??=A(),de}function we(e,t){const i=u.signMLDSAMessage(e,t);return{message:i.message,signature:i.signature,publicKey:i.publicKey,securityLevel:i.securityLevel}}function me(e,t,i,r,n,s){const a=o.fromPublicKey(e,t,i,r);return u.verifyMLDSASignature(a,n,s)}function fe(e,t,i){return u.verifyMLDSASignature(e,t,i)}function Ke(e,t){const i=u.signMessage(e,t);return{message:i.message,signature:i.signature,publicKey:e.publicKey}}function ke(e,t,i){return u.verifySignature(e,t,i)}function ve(e,t,i=c.bitcoin){const r=u.tweakAndSignMessage(e,t,i);return{message:r.message,signature:r.signature,publicKey:e.publicKey}}function Pe(e,t,i){return u.tweakAndVerifySignature(e,t,i)}function be(e,t,i){const r=Ee(t);switch(i){case"mldsa":{if(!Se(e))throw new Error("ML-DSA signing requires a quantum keypair");const i=we(e,t);return{message:r,signature:i.signature,publicKey:i.publicKey,signatureType:"mldsa",securityLevel:i.securityLevel}}case"schnorr":{if(Se(e))throw new Error("Schnorr signing requires a classical keypair");const i=Ke(e,t);return{message:r,signature:i.signature,publicKey:i.publicKey,signatureType:"schnorr"}}case"ecdsa":{if(Se(e))throw new Error("ECDSA signing requires a classical keypair");const t=u.sha256(r);return{message:r,signature:e.sign(E(t)),publicKey:e.publicKey,signatureType:"ecdsa"}}}}function xe(e,t,i,r,n,s,a){switch(r){case"mldsa":if(void 0===n||void 0===s||void 0===a)throw new Error("ML-DSA verification requires chainCode, network, and securityLevel");return me(e,n,s,a,t,i);case"schnorr":return ke(e,t,i);case"ecdsa":{const r=Ee(t),n=u.sha256(r);return ge().verify(E(n),x(e),L(i))}}}function Se(e){return"securityLevel"in e&&"chainCode"in e}const Te=new TextEncoder;function Ee(e){return"string"==typeof e?Te.encode(e):e}const He=new TextEncoder,We=w(0n);function Le(e){const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i}const Ie=[i.P2WPKH,i.P2TR];function Ae(e){const t=g.sha256(He.encode("BIP0322-signed-message")),i="string"==typeof e?He.encode(e):e;return g.sha256(f([t,t,i]))}function qe(e,t,i){const r=h.toOutputScript(t,i),n=V(t,i);if(null===n||!Ie.includes(n))throw new Error(`BIP322: Address type not supported for signing. Got: ${String(n)}`);const s=Ae(e),a=K(32),o=f([p("0020"),s]),u=new k;u.version=0,u.addInput(a,4294967295,0,o),u.addOutput(r,We);const c=new v({network:i});return c.setVersion(0),c.addInput({hash:u.getHash(),index:0,sequence:0,witnessUtxo:{script:r,value:We}}),c.addOutput({script:p("6a"),value:We}),c}function Ce(e){const t=e.extractTransaction(),i=t.ins[0]?.witness;if(void 0===i||0===i.length)throw new Error("BIP322: No witness data found in signed transaction");const r=m.number.encode(i.length);return function(e){let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}(f([r,...i.map(e=>function(e){const t=m.number.encode(e.length);return f([t,e])}(e))]))}async function Ne(e,t,i,r){const n=qe(e,t,i),s=await r(n);return s.finalizeAllInputs(),Ce(s)}const Re=(e,t,i)=>{try{const r=m.signature.decode(i);return ge().verify(E(t),x(e),L(r.signature))}catch{return!1}};function Oe(e,t,i,r){try{const n=h.toOutputScript(e,r),s=Ae(t),a=K(32),o=4294967295,u=0,c=f([p("0020"),s]),y=new k;y.version=0,y.addInput(a,o,u,c),y.addOutput(n,We);const l=Le(i),d=m.decompile(l.subarray(1));if(!Array.isArray(d)||0===d.length)return!1;const g=d[0];if(!(g instanceof Uint8Array))return!1;const w=f([p("02"),n.subarray(2)]),P=new v({network:r});P.setVersion(0),P.addInput({hash:y.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:We}}),P.addOutput({script:p("6a"),value:We});const b=P.data.globalMap.unsignedTx.tx;return function(e,t,i){try{const r=33===e.length?e.subarray(1,33):e;return ge().verifySchnorr(E(t),S(r),I(i))}catch{return!1}}(w,b.hashForWitnessV1(0,[n],[We],k.SIGHASH_DEFAULT),g)}catch{return!1}}function Ue(e,t,r,n){const s=V(e,n);if(null===s)return!1;switch(s){case i.P2TR:return Oe(e,t,r,n);case i.P2WPKH:return function(e,t,i,r){try{const n=h.toOutputScript(e,r),s=Ae(t),a=K(32),o=4294967295,u=0,c=f([p("0020"),s]),y=new k;y.version=0,y.addInput(a,o,u,c),y.addOutput(n,We);const l=Le(i),d=m.decompile(l.subarray(1));if(!Array.isArray(d)||d.length<2)return!1;const g=d[0],w=d[1];if(!(g instanceof Uint8Array&&w instanceof Uint8Array))return!1;const P=new v({network:r});return P.setVersion(0),P.addInput({hash:y.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:We}}),P.addOutput({script:p("6a"),value:We}),P.updateInput(0,{partialSig:[{pubkey:w,signature:g}]}),P.validateSignaturesOfAllInputs(Re)}catch{return!1}}(e,t,r,n);default:return!1}}async function ze(e,t,i,r){const n=C(i);return{address:t,message:e,signature:await Ne(e,t,n,r),networkType:i}}function Fe(e,t,i,r){return Ue(e,t,i,C(r))}class Me{keyring;network;addressType;publicKey;address;constructor(e,t,i,r){this.keyring=e,this.network=t,this.addressType=i,this.publicKey=r,this.address=z(b(r),i,t)}static fromWIF(e,t=i.P2TR,r,n){const s=te.fromWIF(e,n,r),a=s.getPublicKey();return new Me(s,r,t,a)}static fromPrivateKey(e,t=i.P2TR,r,n){const s=te.fromPrivateKey(e,n,r),a=s.getPublicKey();return new Me(s,r,t,a)}static fromMnemonic(e,t=i.P2TR,r,n,s=0){const a=new ee({mnemonic:e,passphrase:n,network:r,addressType:t,activeIndexes:[s]}),o=a.getAccounts()[0];if(void 0===o)throw new Error("Failed to derive wallet from mnemonic");return new Me(a,r,t,o)}static random(e=i.P2TR,t=c.bitcoin){const r=te.generate(t),n=r.getPublicKey();return new Me(r,t,e,n)}getAddress(){return this.address}getPublicKey(){return this.publicKey}getQuantumPublicKey(){return this.keyring instanceof te?this.keyring.getQuantumPublicKey():this.keyring.getQuantumPublicKey(this.publicKey)}getNetwork(){return this.network}getAddressType(){return this.addressType}signPsbt(e,t){const r=t??{autoFinalized:!0,toSignInputs:[]},n=this.formatInputsToSign(e,r);if(0===n.length)throw new Error("LocalWallet: No inputs to sign");for(const s of n){const t=e.data.inputs[s.index];if(void 0===t)continue;const r=!(t.finalScriptSig??t.finalScriptWitness),n=this.addressType===i.P2TR,a=void 0===t.tapInternalKey;if(r&&n&&a){const e=b(this.publicKey),i=33===e.length?e.subarray(1,33):e,r=S(i),{output:n}=l.p2tr({internalPubkey:r,network:this.network});void 0!==n&&void 0!==t.witnessUtxo&&P(t.witnessUtxo.script,n)&&(t.tapInternalKey=r)}}if(this.keyring,this.keyring.signTransaction(e,n),!0===r.autoFinalized)for(const i of n)e.finalizeInput(i.index);return e}async signMessage(e,t){switch(t){case"bip322-simple":return await Ne(e,this.address,this.network,e=>Promise.resolve(this.signPsbt(e,{autoFinalized:!1})));case"ecdsa":case"schnorr":{const t=Ke(this.getKeypair(),e);return H(t.signature)}case"mldsa":{const t=we(this.getQuantumKeypair(),e);return H(t.signature)}}}signData(e,t="ecdsa"){return this.keyring instanceof te?this.keyring.signData(e,t):this.keyring.signData(this.publicKey,e,t)}exportPrivateKey(){return this.keyring instanceof te?this.keyring.exportPrivateKey():this.keyring.exportAccount(this.publicKey)}exportQuantumPrivateKey(){if(this.keyring instanceof te)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 H(W(t,e.chainCode))}exportRawQuantumPrivateKey(){if(this.keyring instanceof te)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 H(e)}exportChainCode(){return this.keyring instanceof te?this.keyring.exportChainCode():this.keyring.getChainCode(this.publicKey)}exportWIF(){if(this.keyring instanceof te)return this.keyring.exportWIF();throw new Error("LocalWallet: Cannot export WIF from HD keyring directly")}getKeypair(){return this.keyring instanceof te?this.keyring.getKeypair():this.keyring.getWallet(this.publicKey).keypair}getQuantumKeypair(){return this.keyring instanceof te?this.keyring.getQuantumKeypair():this.keyring.getMLDSAKeypair(this.publicKey)}formatInputsToSign(e,t){const i=[];if(void 0!==t.toSignInputs&&t.toSignInputs.length>0)for(const r of t.toSignInputs){const e=r.index;if("address"in r){if(r.address!==this.address)throw new Error(`LocalWallet: Address mismatch at input ${e}`)}else if("publicKey"in r&&r.publicKey!==this.publicKey)throw new Error(`LocalWallet: Public key mismatch at input ${e}`);const t={index:e,publicKey:this.publicKey};void 0!==r.sighashTypes&&(t.sighashTypes=r.sighashTypes),void 0!==r.disableTweakSigner&&(t.disableTweakSigner=r.disableTweakSigner),i.push(t)}else for(let r=0;r<e.data.inputs.length;r++){const t=e.data.inputs[r];if(void 0===t)continue;let n;if(void 0!==t.witnessUtxo)n=t.witnessUtxo.script;else if(void 0!==t.nonWitnessUtxo){const i=e.txInputs[r];if(void 0!==i){const e=k.fromBuffer(t.nonWitnessUtxo).outs[i.index];n=e?.script}}const s=t.finalScriptSig??t.finalScriptWitness;if(void 0!==n&&void 0===s){if(Q(n,this.network)===this.address){const e={index:r,publicKey:this.publicKey};void 0!==t.sighashType&&(e.sighashTypes=[t.sighashType]),i.push(e)}}}return i}}function _e(e){return"address"in e}function Qe(e){return"publicKey"in e}export{ee as HdKeyring,Me as LocalWallet,te as SimpleKeyring,_ as addressToScriptPubKey,D as decodeAddress,ce as deserializeExport,V as detectAddressType,O as detectNetworkFromAddress,ae as exportWallet,he as exportWalletToString,Ce as extractBip322Signature,pe as fromLegacyExport,qe as generateBip322Psbt,Y as getAddressType,R as getBech32Prefix,ge as getNobleBackend,oe as importWallet,ye as importWalletFromString,_e as isAddressSignInput,X as isP2PKHOrP2SHAddress,G as isP2WPKHAddress,Qe as isPublicKeySignInput,$ as isValidAddress,j as isValidAddressForNetworkType,J as isValidP2TRAddress,B as isValidPublicKey,z as publicKeyToAddress,Z as publicKeyToAddressWithNetworkType,F as publicKeyToPayment,M as publicKeyToScriptPubKey,Q as scriptPubKeyToAddress,ue as serializeExport,Ne as signBip322Message,ze as signBip322MessageWithNetworkType,we as signMLDSA,be as signMessage,Ke as signSchnorr,ve as signTweakedSchnorr,C as toNetwork,N as toNetworkType,U as validateAddressNetwork,le as validateExport,Ue as verifyBip322Message,Fe as verifyBip322MessageWithNetworkType,me as verifyMLDSA,fe as verifyMLDSAWithKeypair,xe as verifyMessage,ke as verifySchnorr,Pe as verifyTweakedSchnorr};
2
- //# sourceMappingURL=index.esm.js.map
1
+ import{AddressTypes as e,AddressVerificator as t,EcKeyPair as i,MLDSASecurityLevel as r,MessageSigner as n,Mnemonic as s,MnemonicStrength as a,QuantumBIP32Factory as o,WalletNetworks as u}from"@btc-vision/transaction";import{Psbt as c,Transaction as h,address as y,alloc as l,concat as p,crypto as d,equals as g,fromHex as w,isTaprootInput as m,networks as f,payments as K,script as k,toHex as v,toSatoshi as P}from"@btc-vision/bitcoin";import{concatBytes as b,createBytes32 as x,createMessageHash as S,createNobleBackend as T,createPublicKey as E,createSchnorrSignature as H,createSignature as W,createXOnlyPublicKey as L,fromHexInternal as I,toHex as A}from"@btc-vision/ecpair";import{getMLDSAConfig as q}from"@btc-vision/bip32";function C(e){switch(e){case u.Mainnet:return f.bitcoin;case u.Testnet:return f.testnet;case u.Regtest:return f.regtest;case u.OpnetTestnet:return f.opnetTestnet;default:throw new Error(`Unsupported network type: ${e}`)}}function N(e){return e.bech32===f.bitcoin.bech32?u.Mainnet:e.bech32===f.testnet.bech32?u.Testnet:e.bech32===f.opnetTestnet.bech32?u.OpnetTestnet:u.Regtest}function O(e){return C(e).bech32}function R(e){return e.startsWith(`${f.regtest.bech32}1`)?u.Regtest:e.startsWith(`${f.opnetTestnet.bech32}1`)?u.OpnetTestnet:e.startsWith(`${f.bitcoin.bech32}1`)?u.Mainnet:e.startsWith(`${f.testnet.bech32}1`)?u.Testnet:e.startsWith("1")||e.startsWith("3")?u.Mainnet:e.startsWith("m")||e.startsWith("n")||e.startsWith("2")?u.Testnet:null}function U(e,t){return R(e)===t}function M(t,i,r){const n="string"==typeof t?I(t):t;switch(i){case e.P2PKH:{const e=K.p2pkh({pubkey:E(n),network:r});if(void 0===e.address)throw new Error("Failed to generate P2PKH address");return e.address}case e.P2WPKH:{const e=K.p2wpkh({pubkey:E(n),network:r});if(void 0===e.address)throw new Error("Failed to generate P2WPKH address");return e.address}case e.P2TR:{const e=33===n.length?n.subarray(1,33):n,t=K.p2tr({internalPubkey:L(e),network:r});if(void 0===t.address)throw new Error("Failed to generate P2TR address");return t.address}case e.P2SH_OR_P2SH_P2WPKH:{const e=K.p2wpkh({pubkey:E(n),network:r}),t=K.p2sh({redeem:e,network:r});if(void 0===t.address)throw new Error("Failed to generate P2SH-P2WPKH address");return t.address}default:throw new Error(`Unsupported address type: ${i}`)}}function $(t,i,r){const n="string"==typeof t?I(t):t;switch(i){case e.P2PKH:return K.p2pkh({pubkey:E(n),network:r});case e.P2WPKH:return K.p2wpkh({pubkey:E(n),network:r});case e.P2TR:{const e=33===n.length?n.subarray(1,33):n;return K.p2tr({internalPubkey:L(e),network:r})}case e.P2SH_OR_P2SH_P2WPKH:{const e=K.p2wpkh({pubkey:E(n),network:r});return K.p2sh({redeem:e,network:r})}default:throw new Error(`Unsupported address type: ${i}`)}}function z(e,t,i){const r=$(e,t,i);if(!r.output)throw new Error("Failed to generate script pubkey");return r.output}function F(e,t){return y.toOutputScript(e,t)}function _(e,t){const i="string"==typeof e?w(e):e;return y.fromOutputScript(i,t)}function Q(e,i){return null!==t.detectAddressType(e,i)}function V(e,i){return t.detectAddressType(e,i)}function D(e){const t=[{network:f.bitcoin,networkType:u.Mainnet},{network:f.opnetTestnet,networkType:u.OpnetTestnet},{network:f.testnet,networkType:u.Testnet},{network:f.regtest,networkType:u.Regtest}];for(const{network:i,networkType:r}of t)try{const t=y.toOutputScript(e,i),n=V(e,i);if(null!==n)return{networkType:r,addressType:n,scriptPubKey:t}}catch{}return null}function B(e,i){const r="string"==typeof e?e:v(e);return t.isValidPublicKey(r,i)}function J(e,i){return t.isValidP2TRAddress(e,i)}function G(e,i){return t.isP2WPKHAddress(e,i)}function j(e,i){return t.isP2PKHOrP2SH(e,i)}function X(e,t){return Q(e,C(t))}function Y(e,t){return V(e,C(t))}function Z(e,t,i){return M(e,t,C(i))}var ee,te=class t{static type="HD Key Tree";type=t.type;mnemonic=null;wallets=/* @__PURE__ */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??r.LEVEL2,this.passphrase=t?.passphrase??"",this.addressType=t?.addressType??e.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(e=a.MAXIMUM,i="",n=f.bitcoin,o=r.LEVEL2){const u=s.generate(e,i,n,o),c=new t({network:n,securityLevel:o,passphrase:i});return c.mnemonic=u,c}initFromMnemonic(e){if(null!==this.mnemonic)throw new Error("HdKeyring: Mnemonic already initialized");this.mnemonic=new s(e,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 t=this.wallets.get(e);if(void 0!==t)return t;let i;if(this.isCustomHdPath()){const t=`${this._hdPath}/${e}`,r=`m/360'/${this.network===f.bitcoin?0:1}'/0'/0/${e}`;i=this.mnemonic.deriveCustomPath(t,r)}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 i=0;for(;t.length<e;){if(!this.activeIndexes.includes(i)){const e=this.deriveWallet(i);this.activeIndexes.push(i),t.push(e.toPublicKeyHex())}i++}return t}activateAccounts(e){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const t=[];for(const i of e)if(this.activeIndexes.includes(i)){const e=this.wallets.get(i);void 0!==e&&t.push(e.toPublicKeyHex())}else{const e=this.deriveWallet(i);this.activeIndexes.push(i),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 i={p2pkh:t.legacy,p2wpkh:t.p2wpkh,p2tr:t.p2tr,p2shP2wpkh:t.segwitLegacy};return{index:e,publicKey:t.toPublicKeyHex(),quantumPublicKey:t.quantumPublicKeyHex,addresses:i}})}getQuantumPublicKey(e){return this.findWalletByPublicKey(e).quantumPublicKeyHex}getIndexByPublicKey(e){for(const[t,i]of this.wallets.entries())if(i.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 M(I(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 i=this.activeIndexes.indexOf(t);-1!==i&&this.activeIndexes.splice(i,1),this.wallets.delete(t)}exportAccount(e){return this.findWalletByPublicKey(e).toPrivateKeyHex()}signTransaction(e,t){for(const i of t){const t=this.findWalletByPublicKey(i.publicKey),r=e.data.inputs[i.index];if(void 0===r)throw new Error(`HdKeyring: Input at index ${i.index} not found`);const n=t.keypair,s=void 0!==i.sighashTypes?[...i.sighashTypes]:void 0;if(m(r)&&!0!==i.disableTweakSigner){const r=t.publicKey.subarray(1,33),a=n.tweak(x(r));e.signInput(i.index,a,s)}else e.signInput(i.index,n,s)}return e}signData(e,t,i="ecdsa"){const r=this.findWalletByPublicKey(e),n=S(I(t));if("ecdsa"===i)return A(r.keypair.sign(n));if(void 0===r.keypair.signSchnorr)throw new Error("HdKeyring: Schnorr signing not supported by this keypair");return A(r.keypair.signSchnorr(n))}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,t=5){if(null===this.mnemonic)throw new Error("HdKeyring: No mnemonic initialized");const i=e*t,r=i+t,n=[];for(let s=i;s<r;s++){let e;if(this.isCustomHdPath()){const t=`${this._hdPath}/${s}`,i=`m/360'/${this.network===f.bitcoin?0:1}'/0'/0/${s}`;e=this.mnemonic.deriveCustomPath(t,i)}else e=this.mnemonic.deriveOPWallet(this.addressType,s);const t=this.getAddressFromWallet(e);n.push({address:t,index:s})}return n}getChainCode(e){const t=this.findWalletByPublicKey(e);return Uint8Array.from(t.chainCode)}getMLDSAKeypair(e){return this.findWalletByPublicKey(e).mldsaKeypair}isCustomHdPath(){const t={[e.P2PKH]:"m/44'/0'/0'/0",[e.P2WPKH]:"m/84'/0'/0'/0",[e.P2TR]:"m/86'/0'/0'/0",[e.P2SH_OR_P2SH_P2WPKH]:"m/49'/0'/0'/0"}[this.addressType];if(void 0===t)return""!==this._hdPath;const i=t.slice(0,-2);return!this._hdPath.includes(i)&&""!==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.P2PKH:return t.legacy;case e.P2WPKH:return t.p2wpkh;case e.P2TR:return t.p2tr;case e.P2SH_OR_P2SH_P2WPKH:return t.segwitLegacy;default:return t.p2tr}}},ie=class t{static type="Simple Key Pair";type=t.type;network;securityLevel;keypair=null;quantumKeypair=null;chainCode=new Uint8Array(32);constructor(e){if(!e?.network)throw new Error("SimpleKeyring: Network option is required");this.network=e.network,this.securityLevel=e?.securityLevel??r.LEVEL2,void 0!==e?.privateKey&&this.importPrivateKey(e.privateKey,e.quantumPrivateKey)}static generate(e=f.bitcoin,n=r.LEVEL2){const s=new t({network:e,securityLevel:n,privateKey:""});s.keypair=i.generateRandomKeyPair(e);const a=crypto.getRandomValues(new Uint8Array(64));return s.quantumKeypair=o.fromSeed(a,e,n),s.chainCode=Uint8Array.from(s.quantumKeypair.chainCode),s}static fromWIF(e,n,s=f.bitcoin,a=r.LEVEL2){const o=new t({network:s,securityLevel:a,privateKey:""});return o.keypair=i.fromWIF(e,s),void 0!==n&&""!==n&&o.importQuantumKey(n),o}static fromPrivateKey(e,n,s=f.bitcoin,a=r.LEVEL2){const o=new t({network:s,securityLevel:a,privateKey:""});return o.keypair=i.fromPrivateKey(I(e),s),void 0!==n&&""!==n&&o.importQuantumKey(n),o}importPrivateKey(e,t){""!==e&&(64===e.length?this.keypair=i.fromPrivateKey(I(e),this.network):this.keypair=i.fromWIF(e,this.network),void 0!==t&&""!==t&&this.importQuantumKey(t))}importQuantumKey(e){const t=I(e),i=q(this.securityLevel,this.network).privateKeySize,r=i+32,n=t.length===r,s=t.length===i;if(!n&&!s)throw new Error(`Invalid quantum key length: ${t.length} bytes. Expected ${i} bytes (key only) or ${r} bytes (key + chaincode).`);if(n){this.chainCode=t.slice(-32);const e=t.slice(0,-32);this.quantumKeypair=o.fromPrivateKey(e,this.chainCode,this.network,this.securityLevel)}else this.chainCode=crypto.getRandomValues(new Uint8Array(32)),this.quantumKeypair=o.fromPrivateKey(t,this.chainCode,this.network,this.securityLevel)}generateFreshQuantumKey(){const e=crypto.getRandomValues(new Uint8Array(64));this.quantumKeypair=o.fromSeed(e,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 A(this.keypair.publicKey)}getQuantumPublicKey(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return A(this.quantumKeypair.publicKey)}getQuantumPublicKeyOrUndefined(){if(null!==this.quantumKeypair)return A(this.quantumKeypair.publicKey)}getQuantumPublicKeyHash(){if(null===this.quantumKeypair)throw new Error("SimpleKeyring: No quantum keypair initialized");return A(d.sha256(this.quantumKeypair.publicKey))}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:M(t,e.P2PKH,this.network),p2wpkh:M(t,e.P2WPKH,this.network),p2tr:M(t,e.P2TR,this.network),p2shP2wpkh:M(t,e.P2SH_OR_P2SH_P2WPKH,this.network)}}getAddress(e){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");return M(this.keypair.publicKey,e,this.network)}exportPrivateKey(){if(void 0===this.keypair?.privateKey)throw new Error("SimpleKeyring: No private key available");return A(this.keypair.privateKey)}exportQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return A(b(this.quantumKeypair.privateKey,this.chainCode))}exportRawQuantumPrivateKey(){if(void 0===this.quantumKeypair?.privateKey)throw new Error("SimpleKeyring: No quantum private key available");return A(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,t){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");for(const i of t){const t=e.data.inputs[i.index];if(void 0===t)throw new Error(`SimpleKeyring: Input at index ${i.index} not found`);if(m(t)&&!0!==i.disableTweakSigner){const t=this.keypair.tweak(x(this.keypair.publicKey.subarray(1,33)));e.signInput(i.index,t,i.sighashTypes?[...i.sighashTypes]:void 0)}else e.signInput(i.index,this.keypair,i.sighashTypes?[...i.sighashTypes]:void 0)}return e}signData(e,t="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const i=S(I(e));if("ecdsa"===t)return A(this.keypair.sign(i));if(void 0===this.keypair.signSchnorr)throw new Error("SimpleKeyring: Schnorr signing not supported by this keypair");return A(this.keypair.signSchnorr(i))}verify(e,t,i="ecdsa"){if(null===this.keypair)throw new Error("SimpleKeyring: No keypair initialized");const r=S(I(e));return"ecdsa"===i?this.keypair.verify(r,W(I(t))):this.keypair.verifySchnorr(r,H(I(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)}},re="OPNET_WALLET_V1",ne=new TextEncoder;function se(e){return A(d.sha256(ne.encode(e)).subarray(0,4))}function ae(e){return N(e)}function oe(e,t,i,r,n,s,a){const o={magic:re,version:1,network:ae(a),classical:{privateKey:A(e),publicKey:A(t)},quantum:{privateKey:A(i),publicKey:A(r),securityLevel:s,chainCode:A(n)}},u=se(JSON.stringify(o));return{...o,checksum:u}}function ue(e){if(e.magic!==re)throw new Error("Invalid wallet export format: wrong magic header");if(1!==e.version)throw new Error(`Unsupported wallet export version: ${e.version}`);const t={magic:e.magic,version:e.version,network:e.network,classical:e.classical,quantum:e.quantum},r=se(JSON.stringify(t));if(e.checksum!==r)throw new Error("Invalid wallet export: checksum mismatch");const n=function(e){const t=e;return Object.values(u).includes(t)?C(t):f.bitcoin}(e.network),s=I(e.quantum.chainCode),a=I(e.classical.privateKey),c=i.fromPrivateKey(a,n),h=I(e.quantum.privateKey);return{keypair:c,quantumKeypair:o.fromPrivateKey(h,s,n,e.quantum.securityLevel),network:n,securityLevel:e.quantum.securityLevel,chainCode:s}}function ce(e){const t=JSON.stringify(e);return btoa(t)}function he(e){try{const t=atob(e);return JSON.parse(t)}catch{throw new Error("Invalid wallet export: failed to deserialize")}}function ye(e,t,i,r,n,s,a){return ce(oe(e,t,i,r,n,s,a))}function le(e){return ue(he(e))}function pe(e){try{if(e.magic!==re)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},i=se(JSON.stringify(t));return e.checksum===i}catch{return!1}}function de(e,t){const r=I(e.classicalPrivateKey),n=i.fromPrivateKey(r,t),s={magic:re,version:1,network:ae(t),classical:{privateKey:e.classicalPrivateKey,publicKey:A(n.publicKey)},quantum:{privateKey:e.quantumPrivateKey,publicKey:e.quantumPublicKey,securityLevel:e.securityLevel,chainCode:e.chainCode}},a=se(JSON.stringify(s));return{...s,checksum:a}}function ge(){return ee??=T(),ee}function we(e,t){const i=n.signMLDSAMessage(e,t);return{message:i.message,signature:i.signature,publicKey:i.publicKey,securityLevel:i.securityLevel}}function me(e,t,i,r,s,a){const u=o.fromPublicKey(e,t,i,r);return n.verifyMLDSASignature(u,s,a)}function fe(e,t,i){return n.verifyMLDSASignature(e,t,i)}function Ke(e,t){const i=n.signMessage(e,t);return{message:i.message,signature:i.signature,publicKey:e.publicKey}}function ke(e,t,i){return n.verifySignature(e,t,i)}function ve(e,t,i=f.bitcoin){const r=n.tweakAndSignMessage(e,t,i);return{message:r.message,signature:r.signature,publicKey:e.publicKey}}function Pe(e,t,i){return n.tweakAndVerifySignature(e,t,i)}function be(e,t,i){const r=Ee(t);switch(i){case"mldsa":{if(!Se(e))throw new Error("ML-DSA signing requires a quantum keypair");const i=we(e,t);return{message:r,signature:i.signature,publicKey:i.publicKey,signatureType:"mldsa",securityLevel:i.securityLevel}}case"schnorr":{if(Se(e))throw new Error("Schnorr signing requires a classical keypair");const i=Ke(e,t);return{message:r,signature:i.signature,publicKey:i.publicKey,signatureType:"schnorr"}}case"ecdsa":{if(Se(e))throw new Error("ECDSA signing requires a classical keypair");const t=n.sha256(r);return{message:r,signature:e.sign(S(t)),publicKey:e.publicKey,signatureType:"ecdsa"}}}}function xe(e,t,i,r,s,a,o){switch(r){case"mldsa":if(void 0===s||void 0===a||void 0===o)throw new Error("ML-DSA verification requires chainCode, network, and securityLevel");return me(e,s,a,o,t,i);case"schnorr":return ke(e,t,i);case"ecdsa":{const r=Ee(t),s=n.sha256(r);return ge().verify(S(s),E(e),W(i))}}}function Se(e){return"securityLevel"in e&&"chainCode"in e}var Te=new TextEncoder;function Ee(e){return"string"==typeof e?Te.encode(e):e}var He=new TextEncoder,We=P(0n);function Le(e){const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i}var Ie=[e.P2WPKH,e.P2TR];function Ae(e){const t=d.sha256(He.encode("BIP0322-signed-message")),i="string"==typeof e?He.encode(e):e;return d.sha256(p([t,t,i]))}function qe(e,t,i){const r=y.toOutputScript(t,i),n=V(t,i);if(null===n||!Ie.includes(n))throw new Error(`BIP322: Address type not supported for signing. Got: ${String(n)}`);const s=Ae(e),a=l(32),o=p([w("0020"),s]),u=new h;u.version=0,u.addInput(a,4294967295,0,o),u.addOutput(r,We);const d=new c({network:i});return d.setVersion(0),d.addInput({hash:u.getHash(),index:0,sequence:0,witnessUtxo:{script:r,value:We}}),d.addOutput({script:w("6a"),value:We}),d}function Ce(e){const t=e.extractTransaction().ins[0]?.witness;if(void 0===t||0===t.length)throw new Error("BIP322: No witness data found in signed transaction");return function(e){let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}(p([k.number.encode(t.length),...t.map(e=>{return t=e,p([k.number.encode(t.length),t]);var t})]))}async function Ne(e,t,i,r){const n=await r(qe(e,t,i));return n.finalizeAllInputs(),Ce(n)}var Oe=(e,t,i)=>{try{const r=k.signature.decode(i);return ge().verify(S(t),E(e),W(r.signature))}catch{return!1}};function Re(e,t,i,r){try{const n=y.toOutputScript(e,r),s=Ae(t),a=l(32),o=4294967295,u=0,d=p([w("0020"),s]),g=new h;g.version=0,g.addInput(a,o,u,d),g.addOutput(n,We);const m=Le(i),f=k.decompile(m.subarray(1));if(!Array.isArray(f)||0===f.length)return!1;const K=f[0];if(!(K instanceof Uint8Array))return!1;const v=p([w("02"),n.subarray(2)]),P=new c({network:r});return P.setVersion(0),P.addInput({hash:g.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:We}}),P.addOutput({script:w("6a"),value:We}),function(e,t,i){try{const r=33===e.length?e.subarray(1,33):e;return ge().verifySchnorr(S(t),L(r),H(i))}catch{return!1}}(v,P.data.globalMap.unsignedTx.tx.hashForWitnessV1(0,[n],[We],h.SIGHASH_DEFAULT),K)}catch{return!1}}function Ue(e,t,i,r){try{const n=y.toOutputScript(e,r),s=Ae(t),a=l(32),o=4294967295,u=0,d=p([w("0020"),s]),g=new h;g.version=0,g.addInput(a,o,u,d),g.addOutput(n,We);const m=Le(i),f=k.decompile(m.subarray(1));if(!Array.isArray(f)||f.length<2)return!1;const K=f[0],v=f[1];if(!(K instanceof Uint8Array&&v instanceof Uint8Array))return!1;const P=new c({network:r});return P.setVersion(0),P.addInput({hash:g.getHash(),index:0,sequence:0,witnessUtxo:{script:n,value:We}}),P.addOutput({script:w("6a"),value:We}),P.updateInput(0,{partialSig:[{pubkey:v,signature:K}]}),P.validateSignaturesOfAllInputs(Oe)}catch{return!1}}function Me(t,i,r,n){const s=V(t,n);if(null===s)return!1;switch(s){case e.P2TR:return Re(t,i,r,n);case e.P2WPKH:return Ue(t,i,r,n);default:return!1}}async function $e(e,t,i,r){return{address:t,message:e,signature:await Ne(e,t,C(i),r),networkType:i}}function ze(e,t,i,r){return Me(e,t,i,C(r))}var Fe=class t{keyring;network;addressType;publicKey;address;constructor(e,t,i,r){this.keyring=e,this.network=t,this.addressType=i,this.publicKey=r,this.address=M(I(r),i,t)}static fromWIF(i,r=e.P2TR,n,s){const a=ie.fromWIF(i,s,n);return new t(a,n,r,a.getPublicKey())}static fromPrivateKey(i,r=e.P2TR,n,s){const a=ie.fromPrivateKey(i,s,n);return new t(a,n,r,a.getPublicKey())}static fromMnemonic(i,r=e.P2TR,n,s,a=0){const o=new te({mnemonic:i,passphrase:s,network:n,addressType:r,activeIndexes:[a]}),u=o.getAccounts()[0];if(void 0===u)throw new Error("Failed to derive wallet from mnemonic");return new t(o,n,r,u)}static random(i=e.P2TR,r=f.bitcoin){const n=ie.generate(r);return new t(n,r,i,n.getPublicKey())}getAddress(){return this.address}getPublicKey(){return this.publicKey}getQuantumPublicKey(){return this.keyring instanceof ie?this.keyring.getQuantumPublicKey():this.keyring.getQuantumPublicKey(this.publicKey)}getNetwork(){return this.network}getAddressType(){return this.addressType}signPsbt(t,i){const r=i??{autoFinalized:!0,toSignInputs:[]},n=this.formatInputsToSign(t,r);if(0===n.length)throw new Error("LocalWallet: No inputs to sign");for(const s of n){const i=t.data.inputs[s.index];if(void 0===i)continue;const r=!(i.finalScriptSig??i.finalScriptWitness),n=this.addressType===e.P2TR,a=void 0===i.tapInternalKey;if(r&&n&&a){const e=I(this.publicKey),t=L(33===e.length?e.subarray(1,33):e),{output:r}=K.p2tr({internalPubkey:t,network:this.network});void 0!==r&&void 0!==i.witnessUtxo&&g(i.witnessUtxo.script,r)&&(i.tapInternalKey=t)}}if(this.keyring,this.keyring.signTransaction(t,n),!0===r.autoFinalized)for(const e of n)t.finalizeInput(e.index);return t}async signMessage(e,t){switch(t){case"bip322-simple":return await Ne(e,this.address,this.network,e=>Promise.resolve(this.signPsbt(e,{autoFinalized:!1})));case"ecdsa":case"schnorr":return A(Ke(this.getKeypair(),e).signature);case"mldsa":return A(we(this.getQuantumKeypair(),e).signature)}}signData(e,t="ecdsa"){return this.keyring instanceof ie?this.keyring.signData(e,t):this.keyring.signData(this.publicKey,e,t)}exportPrivateKey(){return this.keyring instanceof ie?this.keyring.exportPrivateKey():this.keyring.exportAccount(this.publicKey)}exportQuantumPrivateKey(){if(this.keyring instanceof ie)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 A(b(t,e.chainCode))}exportRawQuantumPrivateKey(){if(this.keyring instanceof ie)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 A(e)}exportChainCode(){return this.keyring instanceof ie?this.keyring.exportChainCode():this.keyring.getChainCode(this.publicKey)}exportWIF(){if(this.keyring instanceof ie)return this.keyring.exportWIF();throw new Error("LocalWallet: Cannot export WIF from HD keyring directly")}getKeypair(){return this.keyring instanceof ie?this.keyring.getKeypair():this.keyring.getWallet(this.publicKey).keypair}getQuantumKeypair(){return this.keyring instanceof ie?this.keyring.getQuantumKeypair():this.keyring.getMLDSAKeypair(this.publicKey)}formatInputsToSign(e,t){const i=[];if(void 0!==t.toSignInputs&&t.toSignInputs.length>0)for(const r of t.toSignInputs){const e=r.index;if("address"in r){if(r.address!==this.address)throw new Error(`LocalWallet: Address mismatch at input ${e}`)}else if("publicKey"in r&&r.publicKey!==this.publicKey)throw new Error(`LocalWallet: Public key mismatch at input ${e}`);const t={index:e,publicKey:this.publicKey};void 0!==r.sighashTypes&&(t.sighashTypes=r.sighashTypes),void 0!==r.disableTweakSigner&&(t.disableTweakSigner=r.disableTweakSigner),i.push(t)}else for(let r=0;r<e.data.inputs.length;r++){const t=e.data.inputs[r];if(void 0===t)continue;let n;if(void 0!==t.witnessUtxo)n=t.witnessUtxo.script;else if(void 0!==t.nonWitnessUtxo){const i=e.txInputs[r];void 0!==i&&(n=h.fromBuffer(t.nonWitnessUtxo).outs[i.index]?.script)}const s=t.finalScriptSig??t.finalScriptWitness;if(void 0!==n&&void 0===s&&_(n,this.network)===this.address){const e={index:r,publicKey:this.publicKey};void 0!==t.sighashType&&(e.sighashTypes=[t.sighashType]),i.push(e)}}return i}};function _e(e){return"address"in e}function Qe(e){return"publicKey"in e}export{te as HdKeyring,Fe as LocalWallet,ie as SimpleKeyring,F as addressToScriptPubKey,D as decodeAddress,he as deserializeExport,V as detectAddressType,R as detectNetworkFromAddress,oe as exportWallet,ye as exportWalletToString,Ce as extractBip322Signature,de as fromLegacyExport,qe as generateBip322Psbt,Y as getAddressType,O as getBech32Prefix,ge as getNobleBackend,ue as importWallet,le as importWalletFromString,_e as isAddressSignInput,j as isP2PKHOrP2SHAddress,G as isP2WPKHAddress,Qe as isPublicKeySignInput,Q as isValidAddress,X as isValidAddressForNetworkType,J as isValidP2TRAddress,B as isValidPublicKey,M as publicKeyToAddress,Z as publicKeyToAddressWithNetworkType,$ as publicKeyToPayment,z as publicKeyToScriptPubKey,_ as scriptPubKeyToAddress,ce as serializeExport,Ne as signBip322Message,$e as signBip322MessageWithNetworkType,we as signMLDSA,be as signMessage,Ke as signSchnorr,ve as signTweakedSchnorr,C as toNetwork,N as toNetworkType,U as validateAddressNetwork,pe as validateExport,Me as verifyBip322Message,ze as verifyBip322MessageWithNetworkType,me as verifyMLDSA,fe as verifyMLDSAWithKeypair,xe as verifyMessage,ke as verifySchnorr,Pe as verifyTweakedSchnorr};
2
+ //# sourceMappingURL=index.esm.js.map