{"version":3,"file":"barrel-yj6W0K7y.mjs","names":["isBytes","atitle","anumber","abytes","aobject","createView","hasHexBuiltin","bytesToHex","hexToBytes","concatBytes","randomBytes","createView","sha256","aarray","abytes","abytes_","anumber","anumber_","astring","bytesToHex_","concatBytes","concatBytes_","hexToBytes_","isBytes","isBytes_","randomBytes_","_0n","_1n","validateObject","_0n","_1n","_2n","_3n","_4n","_8n","gcd","_0n","_1n","_4n","isBytes","_0n","abytes","_2n","_0n","_1n","randomBytes","wcRandomBytes","concatBytes","abytes","isBytes","hmac","nobleHmac","_0n","_2n","sha256","concatBytes","hasEven","abytes","randomBytes","isBytes","equalBytes","isBytes","concatBytes","_0n","_1n","_2n","_8n","baseHex","_0n","vld","secp","_2n","packedUtils","nobleSha256","_0n","_1n","P.wrap","P.apply","P.bytes","P.array","P.struct","P.U32LE","P.U64LE","P.I32LE","P.flag","P.flagged","P.validate","_0n","_1n","P.validate","P.bytes","P.struct","P.U32BE","P.array","P.U32LE","P.U8","P.apply","concatBytes","P.EMPTY","P.I64LE","P.NULL","P.prefix","P.wrap","P.magic","P.string","u.isBytes","u.equalBytes","P.apply","P.validate","P.wrap","u.sha256","u.hash160","u.tagSchnorr","u.concatBytes","P.EMPTY","u.reverseObject","u.taprootTweakPrivKey","u.pubSchnorr","rows","P.struct","P.bytes","P.U32LE","u.taprootTweakPubkey","u.compareBytes","u.tagSchnorr","psbt.mergeKeyMap","psbt.PSBTInput","psbt.cleanPSBTFields","psbt.PSBTOutput","u.sha256x2","psbt.PSBTOutputUnsignedKeys","u.sha256","u.pubECDSA","u.hash160","u.signSchnorr","u.signECDSA","psbt.combineKeyMap","psbt.PSBTGlobal","__exportAll","rpcSuccessResponseMessageSchema","rpcErrorResponseMessageSchema","v","fromNumH","n","fromNumL","setU64FromNum","h","l","view","byteOffset","isLE","isBytes$4","a","atitle$1","title","anumber$2","abytes$2","value","length","bytes","ofLen","got","message","ahash","aobject$1","label","aopts","proto","aexists","instance","checkFinished","aoutput","out","min","clean","arrays","i","createView$1","arr","rotr","word","shift","rotl","hasHexBuiltin$1","hexes","bytesToHex$1","hex","asciiToBase16","ch","hexToBytes$1","error","hl","al","array","ai","hi","n1","n2","char","concatBytes$3","sum","res","pad","checkOpts","defaults","opts","createHasher","hashCons","info","hashC","msg","tmp","randomBytes$1","bytesLength","cr","oidNist","suffix","Chi","b","c","Maj","HashMD","blockLen","outputLen","padOffset","data","len","processed","pos","take","dataView","buffer","oview","outLen","state","destroyed","finished","to","SHA256_IV","SHA256_K","SHA256_W","SHA2_32B","IV","A","B","C","D","E","F","G","H","offset","W15","W2","s0","s1","sigma1","T1","T2","_SHA256","sha256$1","aarray$1","item","inner","abytes$1","anumber$1","astring$1","prefix","aobject","afunction","bytesToHex","concatBytes$2","hexToBytes","isBytes$3","randomBytes","_0n$10","_1n$7","atitle","abool","abignumber","isPosBig","asafenumber","numberToHexUnpadded","num","hexToNumber","bytesToNumberBE","bytesToNumberLE","copyBytes","numberToBytesBE","expectedLen","numberToBytesLE","asciiToBytes","ascii","charCode","inRange","max","aInRange","bitLen","bitMask","createHmacDrbg","hashLen","qByteLen","hmacFn","u8n","NULL","byte0","byte1","k","reset","msgs","reseed","seed","gen","sl","pred","validateObject$1","object","fields","optFields","checkField","fieldName","val","isOpt","expectedType","current","iter","f","_0n$9","_1n$6","_2n$5","_3n$1","_4n$2","_5n","_7n","_8n$2","_9n","_15n","_16n","POW_WINDOWED_MIN","mod","result","pow","modulo","power","d","p","digits","table","w","digit","pow2","x","invert","number","u","q","r","m","invertCt","prime","an","inverse","assertIsSquare","Fp","root","aoddModulus","order","fnName","sqrt3mod4","p1div4","sqrt5mod8","p5div8","nv","sqrt9mod16","Fp_","Field","P","tn","tonelliShanks","c1","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","e3","Q","S","Z","_Fp","FpLegendre","cc","Q1div2","M","t","R","t_tmp","exponent","FpSqrt","FIELD_FIELDS","validateField","field","name","FpInvertBatch","nums","passZero","inverted","multipliedAcc","acc","invertedAcc","p1mod2","powered","yes","zero","no","nLength","nBitLength","bits","_nBitLength","FIELD_SQRT","_Field","ORDER","_nbitLength","nByteLength","lhs","rhs","sqrt","allowedLengths","modFromBytes","BYTES","padded","scalar","skipValidation","lst","condition","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","mapHashToField","key","fieldLen","minLen","reduced","_0n$8","_1n$5","_4n$1","TABLE_BYTES_MAX","validatePointCons","pc","Point","normalizeZ","validateMSMPoints","points","invertedZs","validateW","W","validateTableBytes","numPoints","fpBytes","probeRandomBytes","probe","validateMSMScalars","scalars","maxScalar","s","pointWindowSizes","getWindowSize","oddMultiples","dbl","j","size","wnafDigits","half","mask","signedWindowDigits","shiftBy","windows","wnafWalk","bit","tables","ScalarMultiplier","comp","base","point","precomputes","start","idx","sel","neg","entries","entry","transform","blind","window","cofactor","mulAddUnsafe","allowOversized","createField","createCurveFields","type","FpFnLE","CURVE","curveOpts","Fn","params","createKeygen","secretKey","randomSecretKey","getPublicKey","_HMAC","hash","buf","canXOF","oHash","iHash","hmac","hmac_","_0n$7","_DER","tag","dataLen","lenLen","first","isLong","lengthBytes","int","tlv","maxScalarBytes","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","sig","seq","DER","divNearest","den","_2n$4","_splitEndoScalar","_0n$6","a1","b1","a2","b2","basis","k1","k2","k1neg","k2neg","MAX_NUM","_1n$4","validateSigFormat","format","validateSigOpts","optsn","optName","def","_3n","_4n","weierstrass","validated","extraOpts","CURVE_ORDER","endoOpts","randomBytes$2","endo","lengths","getWLengths","assertCompressionIsSupported","pointToBytes","allowInfinityPoint","bx","isCompressed","hasEvenY","y","pprefix","pointFromBytes","uncomp","head","tail","y2","weierstrassEquation","sqrtError","err","evenY","L","isValidXY","encodePoint","toBytes","decodePoint","fromBytes","b3","mulA","x2","x3","left","right","_4a3","_27b2","acoord","banZero","aprjpoint","other","splitEndoScalarN","pushWnafPair","psi","validityCache","X","Y","wnaf","windowSize","isLazy","X1","Y1","Z1","X2","Y2","Z2","U1","U2","X3","Y3","Z3","t0","t1","t2","t3","t4","t5","normalize","sc","iz","invertedZ","is0","zz","isTorsionFree","clearCofactor","ecdh","randomBytes_","ecdhOpts","isValidSecretKey","isValidPublicKey","publicKey","publicKeyUncompressed","isProbPub","isPub","isSec","getSharedSecret","secretKeyA","publicKeyB","utils","keygen","ecdsa","hash_","ecdsaOpts","randomBytes$3","hmac$1","fnBits","blindLength","csprng","defaultSigOpts","hasLargeRecoveryLifts","isBiggerThanHalfOrder","validateRS","assertFieldSignIsSupported","getRecoveryBit","assertRecoverableCurve","validateSigLength","sizer","Signature","recovery","recid","radj","ir","bits2int_modN","messageHash","u1","u2","rb","sb","bits2int","delta","ORDER_MASK","int2octets","validateMsgAndHash","prehash","prepSig","h1int","seedArgs","extraEntropy","k2sig","kBytes","ibk","bm","bd","ik","normS","lowS","sign","verify","signature","end","is","recoverPublicKey","secp256k1_CURVE","secp256k1_ENDO","_0n$5","_2n$3","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b11","b22","b44","b88","Fpk1","Pointk1","secp256k1","TAGGED_HASH_PREFIXES","taggedHash","messages","tagP","tagH","affineXToBytes","hasEven$1","schnorrGetExtPubKey","d_","priv","affine","BASE","lift_x","xx","challenge","args","schnorrGetPublicKey","schnorrSign","px","auxRand","rand","k_","rx","e","schnorrVerify","pub","schnorr","Rho160","Id160","Pi160","idxLR","idxL","idxR","shifts160","shiftsL160","shiftsR160","Kl160","Kr160","ripemd_f","group","z","BUF_160","_RIPEMD160","h0","h1","h2","h3","h4","ar","bl","br","cl","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sr","tl","tr","ripemd160","freeze","fn","isBytes$2","abytes","isArrayOf","isString","afn","input","astr","anumber","anumArr","chain","id","wrap","from","powers","u8ToNumArr","u8","asciiDecoder","decoder","B2S_CHUNK","charcodesToString","codes","radix2","carry","alphabet","letters","encTable","decTable","code","aliases","alias","target","slen","unsafeWrapper","checksum","_fn","payload","oldChecksum","newChecksum","RADIX_BASE_N_MAX_LENGTH","radixBaseN","blen","zeros","nlimbs","limbs","odd","groups","cur","GROUP","top","g","dlen","used","gval","factor","valueBytes","limb","genBaseN","abc","radix","str","radix58","genBase58","base58","createBase58check","sha256","_sha256","BECH_ALPHABET","BECH_UPPERCASE_PRINTABLE","assertBech32Printable","wordsToU8","words","POLYMOD_GENERATORS","bech32Polymod","pre","chk","bechChecksum","encodingConst","genBech32","ENCODING_CONST","encoding","_words","toWords","fromWords","fromWordsUnsafe","encode","limit","plen","actualLength","lowered","decode","sepIndex","decodeUnsafe","decodeToBytes","encodeFromBytes","bech32","bech32m","_isWellFormed","utf8err","utf8Fallback","cp","utf8","_utf8Encoder","_utf8Decoder","utf8Builtin","hexFallback","hasHexBuiltin","hexBuiltin","EMPTY","restrictedKeys","validateFieldName","equalBytes$1","createFindBytes","needle","byte","back","findBytes","equal","aBytes","isBytes$1","bBytes","concatBytes$1","createView","_0n$4","_1n$3","_2n$2","_8n$1","_10n","_255n","isPlainObject","obj","isNum","hasOwn","lengthCoder","isCoder","byteLen","Path","Bitset","bs","bsLen","chunk","allowRewrite","BITS","lastMask","FULL_MASK","lastPos","last","canSet","stack","objFn","text","parts","path","objPath","_Reader","parent","parentOffset","notRead","formatted","slice","peek","_Writer","buffers","ptr","swapEndianness","checkMinimalBigintBytes","le","fail","signed","checkBounds","signBit","_wrap","_inner","validate","isBaseCoder","elm","dict","seen","numberBigint","tsEnum","decimal","precision","round","decimalMask","sep","frac","intS","fracS","fracLen","match","reverse","coder","coders","bigint","sized","minimal","bLen","next","sBit","U256LE","U64LE","I64LE","intView","validateSigned","maxVal","U32LE","U32BE","I32LE","U16LE","U8","createBytes","_length","_isb","terminator","findTerminator","tPos","apply","string","innerValue","flag","flagValue","xor","marker","hasFlag","validateDefaultSlot","valueObj","defObj","nan","flagged","hasDef","present","magic","check","constant","constantObj","sizeof","struct","_w","_r","startPos","progress","abigint","_0n$3","aarray","astring","validateObject","_2n$1","hasEven","isBytes","concatBytes","equalBytes","hash160","sha256x2","pubSchnorr","pubECDSA","privateKey","LOW_R_BOUND","hasLowR","signECDSA","lowR","counter","signSchnorr","tagSchnorr","PubT","validatePubkey","tapTweak","taprootTweakPrivKey","privKey","seckey0","seckey","merkleRoot","taprootTweakPubkey","pubKey","parity","NETWORK","compareBytes","reverseObject","_0n$2","_1n$2","_2n","_8n","U8_MAX","COMPACT_DIRECT_MAX","OP","OPNames","ScriptNum","abs","bytesLimit","forceMinimal","OpToNum","op","scriptPushLen","read","Script","o","CompactSize","limits","limitsList","stop","b0","_","CompactSizeLen","_VarBytes","VarBytes","_RawWitness","RawWitness","BTCArray","RawInput","RawOutput","_RawTx","validateRawTx","tx","RawTx","RawOldTx","unknowns","mode","_0n$1","_1n$1","PubKeyECDSA","PubKeyECDSACompressed","PubKeySchnorr","SignatureSchnorr","RawWitnessWire","BIP32Der","TaprootBIP32Der","GlobalXPUB","xpub","tapScriptSigKey","_TaprootControlBlock","TaprootControlBlock","cb","tapTree","tree","maxDepth","depth","leaves","BytesInf","ProprietaryKey","Bytes20","Bytes32","Bytes64","Bytes66","MuSig2Participants","MuSig2Key","_key","_raw","raw","SilentPaymentInfo","DNSSECProof","PSBTInfo","kc","vc","reqInc","allowInc","silentIgnore","PSBTGlobal","PSBTInput","PSBTInputFinalKeys","PSBTInputSignatureKeys","PSBTOutput","PSBTOutputUnsignedKeys","PSBTKeyPair","PSBTKeyInfo","PSBTUnknownKey","PSBTKeyMap","byType","psbtEnum","_value","add","kStr","kv","noKey","_name","PSBTInputCoder","PSBTOutputCoder","PSBTGlobalCoder","inp","der","_RawPSBTV0","_RawPSBTV2","validatePSBTFields","_lst","version","cleanPSBTFields","_k","validatePSBT","inputCount","outputCount","outputsLeft","mergeKeyMap","allowedFields","_val","_cur","_allowedFields","unknownMode","unknown","proprietaryMode","proprietary","kC","vC","cannotChange","oldKV","newKV","map","oldVal","newVal","combineKeyMap","_current","_other","keyCoder","valueCoder","RawPSBTV0","RawPSBTV2","P2A_PROGRAM","OutP2A","isValidPubkey","OutScripts","pubkeys","_OutScript","OutScript","_WitnessOutScript","checkWSH","witnessScript","checkScript","hasWsh","script","redeemScript","tapLeafVersion","tapLeafHash","base58check","validateWitness","programToWitness","network","formatKey","hashed","Address","address","program","_0n","_1n","U64_MAX","EMPTY32","EMPTY_OUTPUT","toVsize","weight","stripCodeSeparator","DEFAULT_SEQUENCE","cloneDeep","SignatureHash","SigHash","SigHashNames","getTaprootKeys","internalKey","outputBeforeSign","inputBeforeSign","cleanExtensions","rejectStrip","cleanTxModifiable","cleanFinalInput","_i","extensions","TxHashIdx","validateSigHash","unpackSighash","masked","hashType","sighashScope","sighash","normalizeUnknowns","legacy","fallback","validateOpts","_opts","cs","checkTaprootInputCommitments","output","prevScript","hasTaprootCommitments","checkOutputKey","outputKey","outputParity","controlBlock","scriptWithVersion","leafVersion","sibling","LOCKTIME_THRESHOLD","validateRequiredLocktimes","height","time","resolvePSBTLocktime","hasRequirements","heightSupported","timeSupported","inputs","hasHeight","hasTime","validateInput","prevOut","Transaction","txid","disableScriptCheck","inputSignatures","_input","taproot","inputSignedKeys","getPrevOut","prev","normalizeInput","nonWitnessUtxo","getInputType","txType","defaultSighash","lastScript","child","allowLegacyWitnessUtxo","kind","allowMissing","flags","hasOpaqueFinal","hasSingle","signatures","isAny","isNone","isSingle","parsed","psbt_","e0","PSBTVersion","unsigned","lockTime","outputStart","outputs","global","inputSighash","actual","declared","keys","addInput","addOutput","sigInputs","sigOutputs","varLen","hasWitnesses","witness","withScriptSig","withWitness","_ignoreSignStatus","status","normalized","nextLockTime","amount","prevOutScript","inputIdx","tmpTx","inputHash","sequenceHash","outputHash","outType","inType","spendType","leafScript","annex","leafVer","codeSeparator","inputType","canSign","leaf","pubKeyHash","deriveSigners","rows","signers","row","allowedSighash","_auxRand","prevOuts","schnorrPub","taprootPubKey","_script","scriptDecoded","ver","hasPubkey","leafs","smallest","smallestSize","unsupported","outScript","scriptSig","added","sigIdx","custom","recognized","csEncoded","finalized","inputScript","finalScriptSig","finalScriptWitness","thisV2","otherV2","thisLockTime","otherLockTime","unsignedTx","txModifiable","policy","thisGlobal","otherGlobal","fallbackLocktime","hasOpaqueFinalizedV0","currentFinal","otherFinal","combined","candidate","PSBT_OPTIONS","isFinalized","isReady","template","segwit","parsePsbt","finalizeReadyInputs","index","checkResponse","response","Signer","ccc","client","provider","request","currentNetwork","stops","unregister","replacer","listener","psbtHex","inputsToSign","options","signedPsbtBase64","psbtBase64","signedPsbt","getProviderById","providerId","part","getXverseSigners","windowRef","preferredNetworks","barrel_exports"],"sources":["../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/secp256k1.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/legacy.js","../../../node_modules/.pnpm/@scure+base@2.4.0/node_modules/@scure/base/index.ts","../../../node_modules/.pnpm/micro-packed@0.11.1/node_modules/micro-packed/index.js","../../../node_modules/.pnpm/@scure+btc-signer@2.4.1/node_modules/@scure/btc-signer/utils.js","../../../node_modules/.pnpm/@scure+btc-signer@2.4.1/node_modules/@scure/btc-signer/script.js","../../../node_modules/.pnpm/@scure+btc-signer@2.4.1/node_modules/@scure/btc-signer/psbt.js","../../../node_modules/.pnpm/@scure+btc-signer@2.4.1/node_modules/@scure/btc-signer/payment.js","../../../node_modules/.pnpm/@scure+btc-signer@2.4.1/node_modules/@scure/btc-signer/transaction.js","../../btc-psbt/src/index.ts","../src/signer.ts","../src/signersFactory.ts","../src/barrel.ts"],"sourcesContent":["const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n    if (le)\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n    const len = lst.length;\n    let Ah = new Uint32Array(len);\n    let Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n    const h = fromNumH(n);\n    const l = fromNumL(n);\n    view.setUint32(byteOffset, isLE ? l : h, isLE);\n    view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n    // The fallback still requires a real ArrayBuffer view, so plain\n    // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n    // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n    return (a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) &&\n            a.constructor.name === 'Uint8Array' &&\n            'BYTES_PER_ELEMENT' in a &&\n            a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n    if (typeof n !== 'number')\n        throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n    if (!Number.isSafeInteger(n) || n < 0)\n        throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n    return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n    if (typeof value !== 'boolean')\n        throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n    return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n    // Success path first: this runs at the start of every update() / digestInto(), and the\n    // common `abytes(data)` form must not pay for length handling it does not use.\n    if (isBytes(value) && (length === undefined || value.length === length))\n        return value;\n    // Error path: recompute freely to build the exact message.\n    if (length !== undefined)\n        anumber(length, 'length');\n    const bytes = isBytes(value);\n    const ofLen = length !== undefined ? ` of length ${length}` : '';\n    const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n    const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n    if (!bytes)\n        throw new TypeError(message);\n    throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n    // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n    // because callers use it at byte-validation boundaries before mutating the detached copy.\n    return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n    if (typeof h !== 'function' || typeof h.create !== 'function')\n        throw new TypeError('expected hash wrapped by utils.createHasher');\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n    // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n    // validation and can produce empty outputs instead of failing fast.\n    if (h.outputLen < 1 || h.blockLen < 1)\n        throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n    if (value === null || typeof value !== 'object' || Array.isArray(value))\n        throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n    aobject(value, label);\n    const proto = Object.getPrototypeOf(value);\n    if (proto !== Object.prototype && proto !== null)\n        throw new TypeError(`\"${label}\" expected plain object`);\n    // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n    // prototype setter. Reject it before merging so inherited option values cannot be injected.\n    if (Object.hasOwn(value, '__proto__'))\n        throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n    // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n    // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n    if (instance.destroyed)\n        throw new Error('hash was destroyed');\n    if (checkFinished && instance.finished)\n        throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n    abytes(out, undefined, 'output');\n    // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n    // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n    const min = instance.outputLen;\n    if (!(out.length >= min)) {\n        throw new RangeError('\"output\" expected length >= ' + min);\n    }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n    return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n    ? (n) => n\n    : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n *   On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n    ? (u) => u\n    : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n    return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n        : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n            : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n                : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new TypeError('hex string expected, got ' + typeof hex);\n    if (hasHexBuiltin) {\n        try {\n            return Uint8Array.fromHex(hex);\n        }\n        catch (error) {\n            if (error instanceof SyntaxError)\n                throw new RangeError(error.message);\n            throw error;\n        }\n    }\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n    }\n    return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n    const host = globalThis;\n    if (typeof host.scheduler?.yield === 'function') {\n        const promise = host.scheduler.yield();\n        // Keep the original scheduler rejection; this handler exists only for cleanup.\n        if (onReject)\n            promise.catch(onReject);\n        return promise;\n    }\n    return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n    anumber(iters, 'iters');\n    anumber(tick, 'tick');\n    if (typeof cb !== 'function')\n        throw new TypeError('callback must be a function');\n    // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n    let ts = Date.now();\n    for (let i = 0; i < iters; i++) {\n        cb(i);\n        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n        const diff = Date.now() - ts;\n        if (diff >= 0 && diff < tick)\n            continue;\n        await nextTick(onReject);\n        // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n        ts = Date.now();\n    }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new TypeError('string expected');\n    const encoded = new TextEncoder().encode(str);\n    try {\n        // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n        // buffer can then wipe it independently of TextEncoder's temporary result.\n        return new Uint8Array(encoded); // https://bugzil.la/1681809\n    }\n    finally {\n        clean(encoded);\n    }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n    if (typeof data === 'string')\n        return utf8ToBytes(data);\n    return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n    aobject(object, title);\n    aobject(fields, 'fields');\n    aobject(optFields, 'optFields');\n    function checkField(fieldName, expectedType, isOpt) {\n        const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n        // Config fields must be explicit own properties. Optional inherited values are rejected too\n        // because callers keep reading the same options object after validation.\n        const val = object[fieldName];\n        // Runtime objects such as Field instances intentionally satisfy required method slots\n        // via their shared prototype.\n        if (!Object.hasOwn(object, fieldName) &&\n            (isOpt ? val !== undefined : expectedType !== 'function')) {\n            throw new TypeError(`${label} is invalid: expected own property`);\n        }\n        if (isOpt && val === undefined)\n            return;\n        const current = typeof val;\n        if (current !== expectedType || val === null)\n            throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n    }\n    const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n    iter(fields, false);\n    iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n    aopts(defaults, 'defaults');\n    if (opts !== undefined)\n        aopts(opts, title);\n    // Callers read optional fields directly, so omitted values must not fall through to ambient\n    // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n    const merged = Object.assign(Object.create(null), defaults, opts);\n    return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n *   Wrapper construction eagerly calls `hashCons(undefined)` once to read\n *   `outputLen` / `blockLen`, so constructor side effects happen at module\n *   init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n    if (typeof hashCons !== 'function')\n        throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n    info = checkOpts({}, info, 'info');\n    const hashC = (msg, opts) => hashCons(opts)\n        .update(msg)\n        .digest();\n    const tmp = hashCons(undefined);\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.canXOF = tmp.canXOF;\n    hashC.create = (opts) => hashCons(opts);\n    Object.assign(hashC, info);\n    return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n    // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n    anumber(bytesLength, 'bytesLength');\n    const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n    if (typeof cr?.getRandomValues !== 'function')\n        throw new Error('crypto.getRandomValues must be defined');\n    // Web Cryptography API Level 2 §10.1.1:\n    // if `byteLength > 65536`, throw `QuotaExceededError`.\n    // Keep the guard explicit so callers can see the quota in code\n    // instead of discovering it by reading the spec or host errors.\n    // This wrapper surfaces the same quota as a stable library RangeError.\n    if (bytesLength > 65536)\n        throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n    return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n *   The helper accepts any byte even though only the documented NIST hash\n *   suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n    // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n    // Larger suffix values would need base-128 OID encoding and a different length byte.\n    oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n    return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n    return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n    blockLen;\n    outputLen;\n    canXOF = false;\n    padOffset;\n    isLE;\n    // For partial updates less than block size\n    buffer;\n    view;\n    finished = false;\n    length = 0;\n    pos = 0;\n    destroyed = false;\n    constructor(blockLen, outputLen, padOffset, isLE) {\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.padOffset = padOffset;\n        this.isLE = isLE;\n        this.buffer = new Uint8Array(blockLen);\n        this.view = createView(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        const { view, buffer, blockLen } = this;\n        const len = data.length;\n        let processed = false;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path only when there is no buffered partial block: `take === blockLen` implies\n            // `this.pos === 0`, so we can process full blocks directly from the input view.\n            if (take === blockLen) {\n                const dataView = createView(data);\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(dataView, pos);\n                processed = true;\n                continue;\n            }\n            // When the whole input is buffered in one go (common for short messages), passing `data`\n            // directly avoids allocating a subarray view.\n            buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(view, 0);\n                this.pos = 0;\n                processed = true;\n            }\n        }\n        this.length += data.length;\n        // Shared schedule buffers only pick up input-derived words inside process(); if everything\n        // was buffered without processing, there is nothing to zero.\n        if (processed)\n            this.roundClean();\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        // Padding\n        // We can avoid allocation of buffer for padding completely if it\n        // was previously not allocated here. But it won't change performance.\n        const { buffer, view, blockLen, isLE } = this;\n        let { pos } = this;\n        // append the bit '1' to the message, then zero-pad the rest of the block\n        buffer[pos++] = 0b10000000;\n        buffer.fill(0, pos);\n        // we have less than padOffset left in buffer, so we cannot put length in\n        // current block, need process it and pad again\n        if (this.padOffset > blockLen - pos) {\n            this.process(view, 0);\n            buffer.fill(0);\n        }\n        // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n        // the padding fill above, and JS will overflow before user input can make that half non-zero.\n        // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n        // integer below 2**53, so the split inside the helper stays exact).\n        setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n        this.process(view, 0);\n        // The final block above is processed outside update(), so the shared message-schedule\n        // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n        this.roundClean();\n        // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n        const oview = out === buffer ? view : createView(out);\n        const len = this.outputLen;\n        // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n        const outLen = len / 4;\n        const state = this.get();\n        // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n        if (len % 4 || outLen > state.length)\n            throw new Error('invalid outputLen');\n        for (let i = 0; i < outLen; i++)\n            oview.setUint32(4 * i, state[i], isLE);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n        // fresh bytes to the caller.\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneIntoMeta(to) {\n        const { buffer, length, finished, destroyed, pos } = this;\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n        // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n        if (pos)\n            to.buffer.set(buffer); // Avoid a hot modulo guard.\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n    // We cannot use array here since array allows indexing by variable\n    // which means optimizer/compiler cannot use registers.\n    // Numeric initializers matter: starting the fields as `undefined` changes\n    // V8's field representation and makes sha256 3x slower (measured).\n    A = 0;\n    B = 0;\n    C = 0;\n    D = 0;\n    E = 0;\n    F = 0;\n    G = 0;\n    H = 0;\n    constructor(outputLen, IV) {\n        super(64, outputLen, 8, false);\n        this.A = IV[0] | 0;\n        this.B = IV[1] | 0;\n        this.C = IV[2] | 0;\n        this.D = IV[3] | 0;\n        this.E = IV[4] | 0;\n        this.F = IV[5] | 0;\n        this.G = IV[6] | 0;\n        this.H = IV[7] | 0;\n    }\n    get() {\n        const { A, B, C, D, E, F, G, H } = this;\n        return [A, B, C, D, E, F, G, H];\n    }\n    // prettier-ignore\n    set(A, B, C, D, E, F, G, H) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n        this.E = E | 0;\n        this.F = F | 0;\n        this.G = G | 0;\n        this.H = H | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4)\n            SHA256_W[i] = view.getUint32(offset, false);\n        for (let i = 16; i < 64; i++) {\n            const W15 = SHA256_W[i - 15];\n            const W2 = SHA256_W[i - 2];\n            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n        }\n        // Compression function main loop, 64 rounds\n        let { A, B, C, D, E, F, G, H } = this;\n        for (let i = 0; i < 64; i++) {\n            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n            const T2 = (sigma0 + Maj(A, B, C)) | 0;\n            H = G;\n            G = F;\n            F = E;\n            E = (D + T1) | 0;\n            D = C;\n            C = B;\n            B = A;\n            A = (T1 + T2) | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        E = (E + this.E) | 0;\n        F = (F + this.F) | 0;\n        G = (G + this.G) | 0;\n        H = (H + this.H) | 0;\n        this.set(A, B, C, D, E, F, G, H);\n    }\n    roundClean() {\n        clean(SHA256_W);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        this.set(0, 0, 0, 0, 0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n    constructor() {\n        super(32, SHA256_IV);\n    }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n    constructor() {\n        super(28, SHA224_IV);\n    }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n    // We cannot use array here since array allows indexing by variable\n    // which means optimizer/compiler cannot use registers.\n    // h -- high 32 bits, l -- low 32 bits\n    // Numeric initializers matter: starting the fields as `undefined` changes\n    // V8's field representation and slows hashing down (measured on sha256).\n    Ah = 0;\n    Al = 0;\n    Bh = 0;\n    Bl = 0;\n    Ch = 0;\n    Cl = 0;\n    Dh = 0;\n    Dl = 0;\n    Eh = 0;\n    El = 0;\n    Fh = 0;\n    Fl = 0;\n    Gh = 0;\n    Gl = 0;\n    Hh = 0;\n    Hl = 0;\n    constructor(outputLen, IV) {\n        super(128, outputLen, 16, false);\n        this.Ah = IV[0] | 0;\n        this.Al = IV[1] | 0;\n        this.Bh = IV[2] | 0;\n        this.Bl = IV[3] | 0;\n        this.Ch = IV[4] | 0;\n        this.Cl = IV[5] | 0;\n        this.Dh = IV[6] | 0;\n        this.Dl = IV[7] | 0;\n        this.Eh = IV[8] | 0;\n        this.El = IV[9] | 0;\n        this.Fh = IV[10] | 0;\n        this.Fl = IV[11] | 0;\n        this.Gh = IV[12] | 0;\n        this.Gl = IV[13] | 0;\n        this.Hh = IV[14] | 0;\n        this.Hl = IV[15] | 0;\n    }\n    // prettier-ignore\n    get() {\n        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n    }\n    // prettier-ignore\n    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n        this.Ah = Ah | 0;\n        this.Al = Al | 0;\n        this.Bh = Bh | 0;\n        this.Bl = Bl | 0;\n        this.Ch = Ch | 0;\n        this.Cl = Cl | 0;\n        this.Dh = Dh | 0;\n        this.Dl = Dl | 0;\n        this.Eh = Eh | 0;\n        this.El = El | 0;\n        this.Fh = Fh | 0;\n        this.Fl = Fl | 0;\n        this.Gh = Gh | 0;\n        this.Gl = Gl | 0;\n        this.Hh = Hh | 0;\n        this.Hl = Hl | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4) {\n            SHA512_W_H[i] = view.getUint32(offset);\n            SHA512_W_L[i] = view.getUint32((offset += 4));\n        }\n        for (let i = 16; i < 80; i++) {\n            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n            const W15h = SHA512_W_H[i - 15] | 0;\n            const W15l = SHA512_W_L[i - 15] | 0;\n            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n            const W2h = SHA512_W_H[i - 2] | 0;\n            const W2l = SHA512_W_L[i - 2] | 0;\n            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n            // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n            SHA512_W_H[i] = SUMh | 0;\n            SHA512_W_L[i] = SUMl | 0;\n        }\n        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        // Compression function main loop, 80 rounds\n        for (let i = 0; i < 80; i++) {\n            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n            const CHIl = (El & Fl) ^ (~El & Gl);\n            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n            // prettier-ignore\n            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n            const T1l = T1ll | 0;\n            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n            Hh = Gh | 0;\n            Hl = Gl | 0;\n            Gh = Fh | 0;\n            Gl = Fl | 0;\n            Fh = Eh | 0;\n            Fl = El | 0;\n            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n            Dh = Ch | 0;\n            Dl = Cl | 0;\n            Ch = Bh | 0;\n            Cl = Bl | 0;\n            Bh = Ah | 0;\n            Bl = Al | 0;\n            const All = u64.add3L(T1l, sigma0l, MAJl);\n            Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n            Al = All | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n    }\n    roundClean() {\n        clean(SHA512_W_H, SHA512_W_L);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        clean(this.buffer);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n    constructor() {\n        super(64, SHA512_IV);\n    }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n    constructor() {\n        super(48, SHA384_IV);\n    }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n    constructor() {\n        super(28, T224_IV);\n    }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n    constructor() {\n        super(32, T256_IV);\n    }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n    if (!Array.isArray(item))\n        throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n    for (let i = 0; i < item.length; i++)\n        inner(item[i], `${title}[${i}]`);\n    return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n    if (typeof value !== 'string') {\n        const prefix = title && `\"${title}\" `;\n        throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n    }\n    return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n    if (value === null || typeof value !== 'object' || Array.isArray(value))\n        throw new TypeError(title === 'object'\n            ? 'expected valid options object'\n            : `\"${title}\" expected object, got type=${typeof value}`);\n    return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n    if (typeof value !== 'function')\n        throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n    return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n    if (typeof value !== 'boolean')\n        throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n    return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n    if (typeof n === 'bigint') {\n        if (!isPosBig(n))\n            throw new RangeError('positive bigint expected, got ' + n);\n    }\n    else\n        anumber(n);\n    return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n    if (typeof value !== 'number') {\n        const prefix = title && `\"${title}\" `;\n        throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n    }\n    if (!Number.isSafeInteger(value)) {\n        const prefix = title && `\"${title}\" `;\n        throw new RangeError(prefix + 'expected safe integer, got ' + value);\n    }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n    const hex = abignumber(num).toString(16);\n    return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n    if (typeof hex !== 'string')\n        throw new TypeError('hex string expected, got ' + typeof hex);\n    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n    return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n    return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n    anumber_(len);\n    if (len === 0)\n        throw new Error('zero output length is invalid');\n    n = abignumber(n);\n    const expectedLen = len * 2;\n    const hex = n.toString(16);\n    // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n    if (hex.length > expectedLen)\n        throw new RangeError('number is too large');\n    return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n    return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n    return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n    a = abytes(a);\n    b = abytes(b);\n    if (a.length !== b.length)\n        return false;\n    let diff = 0;\n    for (let i = 0; i < a.length; i++)\n        diff |= a[i] ^ b[i];\n    return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n    // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n    // because callers use it at byte-validation boundaries before mutating the detached copy.\n    return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n    if (typeof ascii !== 'string')\n        throw new TypeError('ascii string expected, got ' + typeof ascii);\n    return Uint8Array.from(ascii, (c, i) => {\n        const charCode = c.charCodeAt(0);\n        if (c.length !== 1 || charCode > 127) {\n            throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n        }\n        return charCode;\n    });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n    return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n    // consider P=256n, min=0n, max=P\n    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n    // - our way is the cleanest:               `inRange('x', x, 0n, P)\n    if (!inRange(n, min, max))\n        throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n    // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n    // contract bug and must not silently collapse to zero bits.\n    if (n < _0n)\n        throw new Error('expected non-negative bigint, got ' + n);\n    // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n    return n === _0n ? 0 : n.toString(2).length;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n *   bigint shift semantics; because the mask is built as `1n << pos`,\n *   they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n    if (typeof n !== 'bigint')\n        throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n    asafenumber(pos, 'pos');\n    return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n *   so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n    if (typeof n !== 'bigint')\n        throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n    asafenumber(pos, 'pos');\n    abool(value, 'value');\n    const mask = _1n << BigInt(pos);\n    // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n    return value ? n | mask : n & ~mask;\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n *   semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n    asafenumber(n, 'n');\n    return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n *   is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n *   other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n    anumber_(hashLen, 'hashLen');\n    anumber_(qByteLen, 'qByteLen');\n    if (typeof hmacFn !== 'function')\n        throw new TypeError('hmacFn must be a function');\n    // creates Uint8Array\n    const u8n = (len) => new Uint8Array(len);\n    const NULL = Uint8Array.of();\n    const byte0 = Uint8Array.of(0x00);\n    const byte1 = Uint8Array.of(0x01);\n    const _maxDrbgIters = 1000;\n    // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n    // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n    let v = u8n(hashLen);\n    // Steps B and C of RFC6979 3.2.\n    let k = u8n(hashLen);\n    let i = 0; // Iterations counter, will throw when over 1000\n    const reset = () => {\n        v.fill(1);\n        k.fill(0);\n        i = 0;\n    };\n    // hmac(k)(v, ...values)\n    const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n    const reseed = (seed = NULL) => {\n        // HMAC-DRBG reseed() function. Steps D-G\n        k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n        v = h(); // v = hmac(k || v)\n        if (seed.length === 0)\n            return;\n        k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n        v = h(); // v = hmac(k || v)\n    };\n    const gen = () => {\n        // HMAC-DRBG generate() function\n        if (i++ >= _maxDrbgIters)\n            throw new Error('drbg: tried max amount of iterations');\n        let len = 0;\n        const out = [];\n        while (len < qByteLen) {\n            v = h();\n            const sl = v.slice();\n            out.push(sl);\n            len += v.length;\n        }\n        return concatBytes(...out);\n    };\n    const genUntil = (seed, pred) => {\n        reset();\n        reseed(seed); // Steps D-G\n        let res = undefined; // Step H: grind until the predicate accepts a candidate.\n        // Falsy values like 0 are valid outputs.\n        while ((res = pred(gen())) === undefined)\n            reseed();\n        reset();\n        return res;\n    };\n    return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n    aobject(object, title);\n    aobject(fields, 'fields');\n    aobject(optFields, 'optFields');\n    function checkField(fieldName, expectedType, isOpt) {\n        const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n        // Config fields must be explicit own properties. Optional inherited values are rejected too\n        // because callers keep reading the same options object after validation.\n        const val = object[fieldName];\n        // Runtime objects such as Field instances intentionally satisfy required method slots\n        // via their shared prototype.\n        if (!Object.hasOwn(object, fieldName) &&\n            (isOpt ? val !== undefined : expectedType !== 'function')) {\n            throw new TypeError(`${label} is invalid: expected own property`);\n        }\n        if (isOpt && val === undefined)\n            return;\n        const current = typeof val;\n        if (current !== expectedType || val === null)\n            throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n    }\n    const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n    iter(fields, false);\n    iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n *   notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n    throw new Error('not implemented');\n};\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n    if (b <= _0n)\n        throw new Error('mod: expected positive modulus, got ' + b);\n    const result = a % b;\n    return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n    if (modulo <= _1n)\n        throw new Error('pow: expected modulus > 1, got ' + modulo);\n    // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n    if (typeof power !== 'bigint')\n        throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n    if (power < _0n)\n        throw new Error('invalid exponent, negatives unsupported');\n    if (power === _0n)\n        return _1n;\n    if (power === _1n)\n        return num;\n    let d = num % modulo;\n    if (d < _0n)\n        d += modulo;\n    // Control flow in both branches below depends only on the exponent, never on `num` — invertCt()\n    // relies on that for its (public-exponent) secret-independence guarantee.\n    if (power < POW_WINDOWED_MIN) {\n        // Square-and-multiply: cheaper than the windowed path for short exponents.\n        let p = _1n;\n        while (power > _0n) {\n            if (power & _1n)\n                p = (p * d) % modulo;\n            d = (d * d) % modulo;\n            power >>= _1n;\n        }\n        return p;\n    }\n    // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n    // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n    // 256-bit exponents of sqrt / Legendre / invertCt.\n    const digits = [];\n    while (power > _0n) {\n        digits.push(Number(power & _15n));\n        power >>= _4n;\n    }\n    const table = new Array(16);\n    table[0] = _1n;\n    table[1] = d;\n    for (let i = 2; i < 16; i++)\n        table[i] = (table[i - 1] * d) % modulo;\n    let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n    for (let w = digits.length - 2; w >= 0; w--) {\n        p = (p * p) % modulo;\n        p = (p * p) % modulo;\n        p = (p * p) % modulo;\n        p = (p * p) % modulo;\n        const digit = digits[w];\n        if (digit !== 0)\n            p = (p * table[digit]) % modulo;\n    }\n    return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n    if (modulo <= _1n)\n        throw new Error('pow2: expected modulus > 1, got ' + modulo);\n    if (power < _0n)\n        throw new Error('pow2: expected non-negative exponent, got ' + power);\n    let res = x;\n    while (power-- > _0n) {\n        res *= res;\n        res %= modulo;\n    }\n    return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n    if (number === _0n)\n        throw new Error('invert: expected non-zero number');\n    // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n    // useless inverse 0. Reject it like pow() and invertCt() do.\n    if (modulo <= _1n)\n        throw new Error('invert: expected modulus > 1, got ' + modulo);\n    // This is variable-time: the loop count depends on `number`. For a secret-independent\n    // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n    let a = mod(number, modulo);\n    let b = modulo;\n    // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n    // never affects the output, so it is not computed.\n    // prettier-ignore\n    let x = _0n, u = _1n;\n    while (a !== _0n) {\n        const q = b / a;\n        const r = b - a * q;\n        const m = x - u * q;\n        // prettier-ignore\n        b = a, a = r, x = u, u = m;\n    }\n    const gcd = b;\n    if (gcd !== _1n)\n        throw new Error('invert: does not exist');\n    return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time — JS bigint\n * multiplication/reduction is still value-dependent — and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n *   {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n    if (prime <= _1n)\n        throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n    const an = mod(a, prime);\n    if (an === _0n)\n        throw new Error('invertCt: expected non-zero number');\n    // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n    const inverse = pow(an, prime - _2n, prime);\n    // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n    if (mod(an * inverse, prime) !== _1n)\n        throw new Error('invertCt: does not exist');\n    return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n    const F = Fp;\n    if (!F.eql(F.sqr(root), n))\n        throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions — (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 — truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n    if ((order & _1n) === _0n)\n        throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n    const F = Fp;\n    const p1div4 = (F.ORDER + _1n) / _4n;\n    const root = F.pow(n, p1div4);\n    assertIsSquare(F, root, n);\n    return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n    const F = Fp;\n    const p5div8 = (F.ORDER - _5n) / _8n;\n    const n2 = F.mul(n, _2n);\n    const v = F.pow(n2, p5div8);\n    const nv = F.mul(n, v);\n    const i = F.mul(F.mul(nv, _2n), v);\n    const root = F.mul(nv, F.sub(i, F.ONE));\n    assertIsSquare(F, root, n);\n    return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n    const Fp_ = Field(P);\n    const tn = tonelliShanks(P);\n    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic\n    return ((Fp, n) => {\n        const F = Fp;\n        let tv1 = F.pow(n, c4); //  1. tv1 = x^c4\n        let tv2 = F.mul(tv1, c1); //  2. tv2 = c1 * tv1\n        const tv3 = F.mul(tv1, c2); //  3. tv3 = c2 * tv1\n        const tv4 = F.mul(tv1, c3); //  4. tv4 = c3 * tv1\n        const e1 = F.eql(F.sqr(tv2), n); //  5.  e1 = (tv2^2) == x\n        const e2 = F.eql(F.sqr(tv3), n); //  6.  e2 = (tv3^2) == x\n        tv1 = F.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n        tv2 = F.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n        const e3 = F.eql(F.sqr(tv2), n); //  9.  e3 = (tv2^2) == x\n        const root = F.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2\n        assertIsSquare(F, root, n);\n        return root;\n    });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n    // Initialization (precomputation).\n    // Caching initialization could boost perf by 7%.\n    if (P < _3n)\n        throw new Error('sqrt is not defined for small field');\n    aoddModulus(P, 'tonelliShanks');\n    // Factor P - 1 = Q * 2^S, where Q is odd\n    let Q = P - _1n;\n    let S = 0;\n    while (Q % _2n === _0n) {\n        Q /= _2n;\n        S++;\n    }\n    // Find the first quadratic non-residue Z >= 2\n    let Z = _2n;\n    const _Fp = Field(P);\n    while (FpLegendre(_Fp, Z) === 1) {\n        // Basic primality test for P. After x iterations, chance of\n        // not finding quadratic non-residue is 2^x, so 2^1000.\n        if (Z++ > 1000)\n            throw new Error('Cannot find square root: probably non-prime P');\n    }\n    // Fast-path; usually done before Z, but we do \"primality test\".\n    if (S === 1)\n        return sqrt3mod4;\n    // Slow-path\n    // TODO: test on Fp2 and others\n    let cc = _Fp.pow(Z, Q); // c = z^Q\n    const Q1div2 = (Q + _1n) / _2n;\n    return function tonelliSlow(Fp, n) {\n        const F = Fp;\n        if (F.is0(n))\n            return n;\n        // Check if n is a quadratic residue using Legendre symbol\n        if (FpLegendre(F, n) !== 1)\n            throw new Error('Cannot find square root');\n        // Initialize variables for the main loop\n        let M = S;\n        let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n        let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n        let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n        // Main loop\n        // while t != 1\n        while (!F.eql(t, F.ONE)) {\n            // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n            // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n            if (F.is0(t))\n                throw new Error('Cannot find square root: probably non-prime P');\n            let i = 1;\n            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n            let t_tmp = F.sqr(t); // t^(2^1)\n            while (!F.eql(t_tmp, F.ONE)) {\n                i++;\n                t_tmp = F.sqr(t_tmp); // t^(2^2)...\n                if (i === M)\n                    throw new Error('Cannot find square root');\n            }\n            // Calculate the exponent for b: 2^(M - i - 1)\n            const exponent = _1n << BigInt(M - i - 1); // bigint is important\n            const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n            // Update variables\n            M = i;\n            c = F.sqr(b); // c = b^2\n            t = F.mul(t, c); // t = (t * b^2)\n            R = F.mul(R, b); // R = R*b\n        }\n        return R;\n    };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n *   behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n    aoddModulus(P, 'Fp.sqrt');\n    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n    if (P % _4n === _3n)\n        return sqrt3mod4;\n    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n    if (P % _8n === _5n)\n        return sqrt5mod8;\n    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n    if (P % _16n === _9n)\n        return sqrt9mod16(P);\n    // Tonelli-Shanks algorithm\n    return tonelliShanks(P);\n}\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n    'eql', 'add', 'sub', 'mul', 'pow', 'div',\n    'addN', 'subN', 'mulN', 'sqrN'\n];\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n *   does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n *   field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field) {\n    aobject(field, 'field');\n    if (typeof field.ORDER !== 'bigint')\n        throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n    // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n    // infinite metadata breaks encoders and caches.\n    asafenumber(field.BYTES, 'BYTES');\n    asafenumber(field.BITS, 'BITS');\n    for (const name of FIELD_FIELDS)\n        afunction(field[name], 'field.' + name);\n    // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n    // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n    if (field.BYTES < 1 || field.BITS < 1)\n        throw new Error('invalid field: expected BYTES/BITS > 0');\n    if (field.ORDER <= _1n)\n        throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n    return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n    validateField(Fp);\n    const F = Fp;\n    // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n    // false and would silently return ONE.\n    if (typeof power !== 'bigint')\n        throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n    if (power < _0n)\n        throw new Error('invalid exponent, negatives unsupported');\n    if (power === _0n)\n        return F.ONE;\n    if (power === _1n)\n        return num;\n    if (power < POW_WINDOWED_MIN) {\n        // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n        // sbox x^5), which would waste the 14-multiplication table build.\n        let p = F.ONE;\n        let d = num;\n        while (power > _0n) {\n            if (power & _1n)\n                p = F.mul(p, d);\n            d = F.sqr(d);\n            power >>= _1n;\n        }\n        return p;\n    }\n    // Fixed 4-bit windows, MSB-first — same shape as pow() above, over generic field ops.\n    // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n    const digits = [];\n    while (power > _0n) {\n        digits.push(Number(power & _15n));\n        power >>= _4n;\n    }\n    const table = new Array(16);\n    table[0] = F.ONE;\n    table[1] = num;\n    for (let i = 2; i < 16; i++)\n        table[i] = F.mul(table[i - 1], num);\n    let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n    for (let w = digits.length - 2; w >= 0; w--) {\n        p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n        const digit = digits[w];\n        if (digit !== 0)\n            p = F.mul(p, table[digit]);\n    }\n    return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n    validateField(Fp);\n    aarray(nums, 'nums');\n    abool(passZero, 'passZero');\n    const F = Fp;\n    const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n    // Walk from first to last, multiply them by each other MOD p\n    const multipliedAcc = nums.reduce((acc, num, i) => {\n        if (F.is0(num))\n            return acc;\n        inverted[i] = acc;\n        return F.mul(acc, num);\n    }, F.ONE);\n    // Invert last element\n    const invertedAcc = F.inv(multipliedAcc);\n    // Walk from last to first, multiply them by inverted each other MOD p\n    nums.reduceRight((acc, num, i) => {\n        if (F.is0(num))\n            return acc;\n        // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n        inverted[i] = F.mul(acc, inverted[i]);\n        return F.mul(acc, num);\n    }, invertedAcc);\n    return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n    validateField(Fp);\n    const F = Fp;\n    return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0    if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n    validateField(Fp);\n    const F = Fp;\n    aoddModulus(F.ORDER, 'FpLegendre');\n    // We can use 3rd argument as optional cache of this value\n    // but seems unneeded for now. The operation is very fast.\n    const p1mod2 = (F.ORDER - _1n) / _2n;\n    const powered = F.pow(n, p1mod2);\n    const yes = F.eql(powered, F.ONE);\n    const zero = F.eql(powered, F.ZERO);\n    const no = F.eql(powered, F.neg(F.ONE));\n    if (!yes && !zero && !no)\n        throw new Error('invalid Legendre symbol result');\n    return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n *   residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n    const l = FpLegendre(Fp, n);\n    // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n    return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n *   value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n    // Bit size, byte size of CURVE.n\n    if (nBitLength !== undefined)\n        anumber(nBitLength);\n    if (n <= _0n)\n        throw new Error('invalid n length: expected positive n, got ' + n);\n    if (nBitLength !== undefined && nBitLength < 1)\n        throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n    const bits = bitLen(n);\n    // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n    // any math that relies on the derived field metadata.\n    if (nBitLength !== undefined && nBitLength < bits)\n        throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n    const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n    const nByteLength = Math.ceil(_nBitLength / 8);\n    return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n    ORDER;\n    BITS;\n    BYTES;\n    isLE;\n    ZERO = _0n;\n    ONE = _1n;\n    _lengths;\n    _mod;\n    constructor(ORDER, opts = {}) {\n        // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n        // would stop modeling field arithmetic.\n        if (ORDER <= _1n)\n            throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n        let _nbitLength = undefined;\n        this.isLE = false;\n        if (opts != null && typeof opts === 'object') {\n            // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n            if (typeof opts.BITS === 'number')\n                _nbitLength = opts.BITS;\n            if (typeof opts.sqrt === 'function')\n                // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n                // explicitly instead of relying on writable prototype shadowing via assignment.\n                Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n            if (typeof opts.isLE === 'boolean')\n                this.isLE = opts.isLE;\n            if (opts.allowedLengths)\n                this._lengths = Object.freeze(opts.allowedLengths.slice());\n            if (typeof opts.modFromBytes === 'boolean')\n                this._mod = opts.modFromBytes;\n        }\n        const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n        if (nByteLength > 2048)\n            throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n        this.ORDER = ORDER;\n        this.BITS = nBitLength;\n        this.BYTES = nByteLength;\n        Object.freeze(this);\n    }\n    create(num) {\n        return mod(num, this.ORDER);\n    }\n    isValid(num) {\n        if (typeof num !== 'bigint')\n            throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n        return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n    }\n    is0(num) {\n        return num === _0n;\n    }\n    // is valid and invertible\n    isValidNot0(num) {\n        return !this.is0(num) && this.isValid(num);\n    }\n    isOdd(num) {\n        return (num & _1n) === _1n;\n    }\n    neg(num) {\n        return mod(-num, this.ORDER);\n    }\n    eql(lhs, rhs) {\n        return lhs === rhs;\n    }\n    sqr(num) {\n        return mod(num * num, this.ORDER);\n    }\n    add(lhs, rhs) {\n        return mod(lhs + rhs, this.ORDER);\n    }\n    sub(lhs, rhs) {\n        return mod(lhs - rhs, this.ORDER);\n    }\n    mul(lhs, rhs) {\n        return mod(lhs * rhs, this.ORDER);\n    }\n    pow(num, power) {\n        return pow(num, power, this.ORDER);\n    }\n    div(lhs, rhs) {\n        return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n    }\n    // Same as above, but doesn't normalize\n    sqrN(num) {\n        return num * num;\n    }\n    addN(lhs, rhs) {\n        return lhs + rhs;\n    }\n    subN(lhs, rhs) {\n        return lhs - rhs;\n    }\n    mulN(lhs, rhs) {\n        return lhs * rhs;\n    }\n    inv(num) {\n        return invert(num, this.ORDER);\n    }\n    sqrt(num) {\n        // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n        // the field instance itself mutable.\n        let sqrt = FIELD_SQRT.get(this);\n        if (!sqrt)\n            FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n        return sqrt(this, num);\n    }\n    toBytes(num) {\n        // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n        // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n        // residues here and reduce or validate them elsewhere.\n        return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n    }\n    fromBytes(bytes, skipValidation = false) {\n        abytes(bytes);\n        const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n        if (allowedLengths) {\n            // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n            // padded into zero and silently decode as a field element.\n            if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n                throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n            }\n            const padded = new Uint8Array(BYTES);\n            // isLE add 0 to right, !isLE to the left.\n            padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n            bytes = padded;\n        }\n        if (bytes.length !== BYTES)\n            throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n        let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n        if (modFromBytes)\n            scalar = mod(scalar, ORDER);\n        if (!skipValidation)\n            if (!this.isValid(scalar))\n                throw new Error('invalid field element: outside of range 0..ORDER');\n        // Range validation is optional here because some protocols intentionally decode raw residues\n        // and reduce or validate them elsewhere.\n        return scalar;\n    }\n    // TODO: we don't need it here, move out to separate fn\n    invertBatch(lst) {\n        // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n        // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n        // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n        return FpInvertBatch(this, lst, true);\n    }\n    // We can't move this out because Fp6, Fp12 implement it\n    // and it's unclear what to return in there.\n    cmov(a, b, condition) {\n        // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n        // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n        abool(condition, 'condition');\n        return condition ? b : a;\n    }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n *   into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n    // Freeze the shared method surface before any instance is reachable; otherwise callers can\n    // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n    // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n    // that never construct a field; the call is idempotent and cheap.\n    Object.freeze(_Field.prototype);\n    return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n *   which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n    validateField(Fp);\n    const F = Fp;\n    if (!F.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = F.sqrt(elm);\n    return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n    validateField(Fp);\n    const F = Fp;\n    if (!F.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = F.sqrt(elm);\n    return F.isOdd(root) ? F.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n *   order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n    if (typeof fieldOrder !== 'bigint')\n        throw new Error('field order must be bigint');\n    // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n    if (fieldOrder <= _1n)\n        throw new Error('field order must be greater than 1');\n    // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n    const bitLength = bitLen(fieldOrder - _1n);\n    return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n    const length = getFieldBytesLength(fieldOrder);\n    return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n    abytes(key);\n    const len = key.length;\n    const fieldLen = getFieldBytesLength(fieldOrder);\n    const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n    // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n    // inputs: easier to reason about JS timing / allocation behavior.\n    if (len < minLen || len > 1024)\n        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n    // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n    // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n    // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n    // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n    // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n    const reduced = mod(num, fieldOrder - _1n) + _1n;\n    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n    const pc = Point;\n    if (typeof pc !== 'function')\n        throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n    afunction(pc.fromAffine, 'Point.fromAffine');\n    afunction(pc.fromBytes, 'Point.fromBytes');\n    afunction(pc.fromHex, 'Point.fromHex');\n    // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n    // fail here with a typed error instead of an `undefined` access later.\n    aobject(pc.BASE, 'Point.BASE');\n    aobject(pc.ZERO, 'Point.ZERO');\n    validateField(pc.Fp);\n    validateField(pc.Fn);\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n    // Match MSM helpers: reject malformed public inputs before reading projective internals.\n    validatePointCons(c);\n    validateMSMPoints(points, c);\n    // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n    // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n    // is0 handling instead of using the batch inverse.\n    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n    if (!Number.isSafeInteger(W) || W < min || W > bits)\n        throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n    const bytes = numPoints * (4 * fpBytes + 128);\n    if (bytes > TABLE_BYTES_MAX)\n        throw new Error('invalid window size: table would need ~' +\n            Math.ceil(bytes / 2 ** 20) +\n            ' MiB, max ' +\n            TABLE_BYTES_MAX / 2 ** 20 +\n            ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable —\n * throws or returns malformed bytes — so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n    if (randomBytes === undefined)\n        return undefined;\n    afunction(randomBytes, 'randomBytes');\n    try {\n        const probe = randomBytes(length);\n        if (!isBytes(probe) || probe.length !== length)\n            return undefined;\n    }\n    catch {\n        return undefined;\n    }\n    return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n    aarray(points, 'points');\n    points.forEach((p, i) => {\n        if (!(p instanceof c))\n            throw new Error('invalid point at index ' + i);\n    });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n    if (!Array.isArray(scalars))\n        throw new Error('array of scalars expected');\n    scalars.forEach((s, i) => {\n        const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n        if (!ok)\n            throw new Error('invalid scalar at index ' + i);\n    });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n    // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n    return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */\nfunction oddMultiples(p, size) {\n    const dbl = p.double();\n    const t = [p];\n    for (let j = 1; j < size; j++)\n        t.push(t[j - 1].add(dbl));\n    return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).\n */\nfunction wnafDigits(n, W) {\n    const size = 2 ** W;\n    const half = size / 2;\n    const mask = BigInt(size - 1);\n    const d = [];\n    while (n > _0n) {\n        let w = 0;\n        if (n & _1n) {\n            w = Number(n & mask); // n mod 2^W, odd\n            if (w >= half)\n                w -= size; // signed residue\n            n -= BigInt(w); // n - w ≡ 0 mod 2^W: next W−1 digits are zero\n        }\n        d.push(w);\n        n >>= _1n;\n    }\n    return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with\n * digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n    const size = 2 ** W;\n    const half = size / 2;\n    const mask = BigInt(size - 1);\n    const shiftBy = BigInt(W);\n    const d = [];\n    for (let w = 0; w < windows; w++) {\n        let v = Number(n & mask);\n        n >>= shiftBy;\n        if (v > half) {\n            v -= size; // negative digit, carry into the next window\n            n += _1n;\n        }\n        d.push(v);\n    }\n    // Internal invariant: leftover bits mean the window count did not cover the scalar.\n    if (n !== _0n)\n        throw new Error('invalid wnaf');\n    return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n    let max = 0;\n    for (const d of digits)\n        max = Math.max(max, d.length);\n    let acc = zero;\n    for (let bit = max - 1; bit >= 0; bit--) {\n        if (bit !== max - 1)\n            acc = acc.double();\n        for (let i = 0; i < digits.length; i++) {\n            const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n            if (w) {\n                const item = tables[i][(Math.abs(w) - 1) >> 1];\n                acc = acc.add(w < 0 ? item.negate() : item);\n            }\n        }\n    }\n    return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings\n *   are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n *   (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n *   widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n    Point;\n    BASE;\n    ZERO;\n    randomBytes;\n    wnafPrecomputes = new WeakMap();\n    baseCanBeBlinded;\n    bits;\n    // Parametrized with a given Point class (not individual point)\n    constructor(Point, randomBytes) {\n        validatePointCons(Point);\n        // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n        // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n        // unblinded constant-time path instead of throwing on every multiply(). The shape of\n        // returned bytes is still validated on every blinded call, where breakage fails closed.\n        this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n        this.Point = Point;\n        this.BASE = Point.BASE;\n        this.ZERO = Point.ZERO;\n        this.bits = Point.Fn.BITS;\n    }\n    /**\n     * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n     * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,\n     * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n     * window absorbs the final carry of signed-digit recoding.\n     * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.\n     * @param point - Point instance\n     * @param W - window size\n     * @param bits - scalar bitlength the table must cover\n     */\n    buildWnafTable(point, W, bits) {\n        // W needs no re-validation: its only source is setWindowSize(), which enforces\n        // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n        // resulting table at ~2 GiB (sized against the wider blinded layout).\n        const windows = Math.ceil(bits / W) + 1;\n        const half = 2 ** (W - 1);\n        const comp = [];\n        let base = point;\n        for (let w = 0; w < windows; w++) {\n            let acc = base;\n            for (let i = 0; i < half; i++) {\n                comp.push(acc);\n                acc = acc.add(base);\n            }\n            base = comp[comp.length - 1].double(); // 2⋅(2^(W−1)⋅base) = next window's base\n        }\n        return { W, bits, windows, comp };\n    }\n    /**\n     * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n     * Constant-time: fixed window count with one table addition per window — zero digits feed\n     * the fake accumulator — and no doublings; the lookup scans the whole window slice.\n     * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n     * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n     * signedWindowDigits throws if `n` exceeds the table.\n     * @returns real and fake (for const-time) points\n     */\n    wnafCachedCT(precomputes, n) {\n        const { W, windows, comp } = precomputes;\n        const half = 2 ** (W - 1);\n        const digits = signedWindowDigits(n, W, windows);\n        let p = this.ZERO;\n        let f = this.BASE;\n        for (let w = 0; w < windows; w++) {\n            const digit = digits[w];\n            const start = w * half;\n            // Data-oblivious select: touch every entry of the window before the digit branch.\n            const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n            let sel = comp[start];\n            for (let i = 1; i < half; i++)\n                sel = i === idx ? comp[start + i] : sel;\n            const neg = sel.negate(); // compute both signs; the digit only picks one\n            if (digit === 0)\n                f = f.add(comp[start]);\n            else\n                p = p.add(digit < 0 ? neg : sel);\n        }\n        return { p, f };\n    }\n    // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n    // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n    // incompatible `transform(...)` layouts and expect a separate cache entry.\n    getWnafPrecomputes(W, point, bits, transform) {\n        let entries = this.wnafPrecomputes.get(point);\n        let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n        if (!comp) {\n            comp = this.buildWnafTable(point, W, bits);\n            if (typeof transform === 'function')\n                comp = { ...comp, comp: transform(comp.comp) };\n            if (!entries) {\n                entries = [];\n                this.wnafPrecomputes.set(point, entries);\n            }\n            entries.push(comp);\n        }\n        return comp;\n    }\n    assertPoint(point) {\n        if (!(point instanceof this.Point))\n            throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n    }\n    // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n    // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n    // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n    validateMulInput(point, scalar) {\n        this.assertPoint(point);\n        if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n            throw new Error('invalid scalar');\n    }\n    // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n    // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n    // multiply. `n` must be < 2^bits.\n    runCT(point, n, bits, transform) {\n        const W = getWindowSize(point);\n        if (W === 1)\n            return this.fixedWindowCT(point, n, bits);\n        return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n    }\n    mulCT(point, scalar, transform) {\n        this.validateMulInput(point, scalar);\n        return this.runCT(point, scalar, this.bits, transform);\n    }\n    mulCTBlinded(point, scalar, transform) {\n        this.validateMulInput(point, scalar);\n        // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n        // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n        // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n        // Fail before building the (large) precompute table if randomness is unavailable.\n        if (this.randomBytes === undefined)\n            throw new Error('randomBytes is required for scalar blinding');\n        const bits = this.Point.Fn.BITS + BLIND_BITS;\n        const blind = this.randomBytes(BLIND_BYTES);\n        if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n            throw new Error('randomBytes returned invalid byte array');\n        // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n        // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n        //   is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n        // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n        //   blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n        //   ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n        //   guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n        //   only ever holds a small carry, never a full digit.\n        blind[0] = (blind[0] & 0x3f) | 0x80;\n        // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n        // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n        // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n        // each, so the add count is independent of scalar (constant-time).\n        const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n        return this.runCT(point, n, bits, transform);\n    }\n    /**\n     * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n     * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n     * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n     * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n     * every table entry, and one addition (adds the identity when the window digit is 0 — never\n     * skipped).\n     *\n     * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n     * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n     * projective form (no normalizeZ): normalizing this small a table costs more than the\n     * mixed-add savings it would buy for a single multiply.\n     * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n     * (this path needs no fake accumulator — its op-count is already scalar-independent).\n     */\n    fixedWindowCT(point, n, bits) {\n        const W = FW_WINDOW;\n        const size = 1 << W;\n        const mask = bitMask(W);\n        // Flat table [O, point, 2*point, ..., (size-1)*point].\n        const table = new Array(size);\n        table[0] = this.ZERO;\n        for (let i = 1; i < size; i++)\n            table[i] = table[i - 1].add(point);\n        // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n        const windows = Math.ceil(bits / W);\n        let acc = this.ZERO;\n        for (let window = windows - 1; window >= 0; window--) {\n            // W doublings per window; skipped for the first (topmost) window, where acc is still the\n            // identity. The skip is scalar-independent: it depends only on the loop index.\n            if (window !== windows - 1)\n                for (let d = 0; d < W; d++)\n                    acc = acc.double();\n            const digit = Number((n >> BigInt(window * W)) & mask);\n            // Data-oblivious select: touch every entry, same as wnafCachedCT.\n            let sel = table[0];\n            for (let i = 1; i < size; i++)\n                sel = i === digit ? table[i] : sel;\n            acc = acc.add(sel); // one add per window, even for digit 0\n        }\n        return { p: acc, f: acc };\n    }\n    shouldBlind(point, cofactor) {\n        // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n        if (this.randomBytes === undefined)\n            return false;\n        if (cofactor === _1n)\n            return true;\n        if (point !== this.BASE)\n            return false;\n        if (this.baseCanBeBlinded === undefined)\n            this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n        return this.baseCanBeBlinded;\n    }\n    mulSecret(point, scalar, cofactor, transform) {\n        return this.shouldBlind(point, cofactor)\n            ? this.mulCTBlinded(point, scalar, transform)\n            : this.mulCT(point, scalar, transform);\n    }\n    mulUnsafe(point, scalar, transform) {\n        this.assertPoint(point);\n        if (!isPosBig(scalar))\n            throw new Error('invalid scalar');\n        const W = getWindowSize(point);\n        // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 —\n        // a cached table would be thrown away after one use. `allowOversized` swaps the\n        // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n        //\n        // Oversized scalar could happen when:\n        // a) user passes large scalar on their own (rare)\n        // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n        if (W === 1 || scalar >= this.Point.Fn.ORDER)\n            return mulAddUnsafe(this.Point, [point], [scalar], true);\n        // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n        // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n        // this path while doubling the cached-table code surface.\n        const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n        return this.wnafCachedCT(precomputes, scalar).p;\n    }\n    // Remembers the window size used for precomputed wNAF multiplication of the given point\n    // and drops any previously built tables. Usually only the base point is precomputed.\n    // W=1 resets the point to the un-precomputed (table-less) paths.\n    // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n    setWindowSize(point, W) {\n        this.assertPoint(point);\n        validateW(W, this.bits);\n        // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n        const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n        validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n        pointWindowSizes.set(point, W);\n        this.wnafPrecomputes.delete(point);\n    }\n    // True when a window size is set: tables themselves are built lazily on first multiply.\n    hasWindowSize(point) {\n        return getWindowSize(point) !== 1;\n    }\n}\n/**\n * Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF\n * (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n *   Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n *   (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss–Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n    validatePointCons(c);\n    validateMSMPoints(points, c);\n    abool(allowOversized, 'allowOversized');\n    // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n    validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n    if (points.length !== scalars.length)\n        throw new Error('arrays of points and scalars must have equal length');\n    const tables = points.map((p) => oddMultiples(p, 4));\n    const digits = scalars.map((n) => wnafDigits(n, 4));\n    return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 — but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n    // 0 is accepted in scalars\n    validatePointCons(c);\n    const fieldN = c.Fn;\n    validateMSMPoints(points, c);\n    validateMSMScalars(scalars, fieldN);\n    const plength = points.length;\n    const slength = scalars.length;\n    if (plength !== slength)\n        throw new Error('arrays of points and scalars must have equal length');\n    const zero = c.ZERO;\n    // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n    if (plength === 0)\n        return zero;\n    const wbits = bitLen(BigInt(plength));\n    let windowSize = 1; // bits\n    if (wbits > 12)\n        windowSize = wbits - 3;\n    else if (wbits > 4)\n        windowSize = wbits - 2;\n    else if (wbits > 0)\n        windowSize = 2;\n    const MASK = bitMask(windowSize);\n    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n    let sum = zero;\n    for (let i = lastBits; i >= 0; i -= windowSize) {\n        buckets.fill(zero);\n        for (let j = 0; j < slength; j++) {\n            const scalar = scalars[j];\n            const wbits = Number((scalar >> BigInt(i)) & MASK);\n            buckets[wbits] = buckets[wbits].add(points[j]);\n        }\n        let resI = zero; // not using this will do small speed-up, but will lose ct\n        // Skip first bucket, because it is zero\n        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n            sumI = sumI.add(buckets[j]);\n            resI = resI.add(sumI);\n        }\n        sum = sum.add(resI);\n        if (i !== 0)\n            for (let j = 0; j < windowSize; j++)\n                sum = sum.double();\n    }\n    return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W−1)−1)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) — one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) — the\n * \"interleaving\" method of Möller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L⋅2^(W−2)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n *   per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n *   `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n    validatePointCons(c);\n    const fieldN = c.Fn;\n    // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n    validateW(windowSize, fieldN.BITS, 2);\n    validateMSMPoints(points, c);\n    validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n    const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n    return (scalars) => {\n        validateMSMScalars(scalars, fieldN);\n        if (scalars.length > points.length)\n            throw new Error('array of scalars must not be larger than array of points');\n        return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n    };\n}\nfunction createField(order, field, isLE) {\n    if (field) {\n        // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n        // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n        // behavior.\n        if (field.ORDER !== order)\n            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n        validateField(field);\n        return field;\n    }\n    else {\n        return Field(order, { isLE });\n    }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n *   - `Fp` (optional): Optional base-field override.\n *   - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n *   p: 17n,\n *   n: 19n,\n *   h: 1n,\n *   a: 2n,\n *   b: 2n,\n *   Gx: 5n,\n *   Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n    if (type !== 'weierstrass' && type !== 'edwards')\n        throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n    if (FpFnLE === undefined)\n        FpFnLE = type === 'edwards';\n    if (!CURVE || typeof CURVE !== 'object')\n        throw new Error(`expected valid ${type} CURVE object`);\n    // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n    validateObject(curveOpts);\n    for (const p of ['p', 'n', 'h']) {\n        const val = CURVE[p];\n        if (!(isPosBig(val) && val !== _0n))\n            throw new Error(`CURVE.${p} must be positive bigint`);\n    }\n    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n    const _b = type === 'weierstrass' ? 'b' : 'd';\n    const params = ['Gx', 'Gy', 'a', _b];\n    for (const p of params) {\n        // @ts-ignore\n        if (!Fp.isValid(CURVE[p]))\n            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n    }\n    CURVE = Object.freeze(Object.assign({}, CURVE));\n    return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n    return function keygen(seed) {\n        const secretKey = randomSecretKey(seed);\n        return { secretKey, publicKey: getPublicKey(secretKey) };\n    };\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 §3 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n    oHash;\n    iHash;\n    blockLen;\n    outputLen;\n    canXOF = false;\n    finished = false;\n    destroyed = false;\n    constructor(hash, key) {\n        ahash(hash);\n        abytes(key, undefined, 'key');\n        this.iHash = hash.create();\n        if (typeof this.iHash.update !== 'function')\n            throw new Error('expected Hash instance');\n        this.blockLen = this.iHash.blockLen;\n        this.outputLen = this.iHash.outputLen;\n        const blockLen = this.blockLen;\n        const pad = new Uint8Array(blockLen);\n        // blockLen can be bigger than outputLen\n        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36;\n        this.iHash.update(pad);\n        // By doing update (processing of the first block) of the outer hash here,\n        // we can re-use it between multiple calls via clone.\n        this.oHash = hash.create();\n        // Undo internal XOR && apply outer XOR\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36 ^ 0x5c;\n        this.oHash.update(pad);\n        clean(pad);\n    }\n    update(buf) {\n        aexists(this);\n        this.iHash.update(buf);\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        const buf = out.subarray(0, this.outputLen);\n        // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n        // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n        this.iHash.digestInto(buf);\n        this.oHash.update(buf);\n        this.oHash.digestInto(buf);\n        this.destroy();\n    }\n    digest() {\n        const out = new Uint8Array(this.oHash.outputLen);\n        this.digestInto(out);\n        return out;\n    }\n    _cloneInto(to) {\n        // Create new instance without calling constructor since the key\n        // is already in state and we don't know it.\n        to ||= Object.create(Object.getPrototypeOf(this), {});\n        const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n        to = to;\n        to.finished = finished;\n        to.destroyed = destroyed;\n        to.blockLen = blockLen;\n        to.outputLen = outputLen;\n        to.canXOF = canXOF;\n        to.oHash = oHash._cloneInto(to.oHash);\n        to.iHash = iHash._cloneInto(to.iHash);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n    destroy() {\n        this.destroyed = true;\n        this.oHash.destroy();\n        this.iHash.destroy();\n    }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n    const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n    hmac_.create = (hash, key) => new _HMAC(hash, key);\n    return hmac_;\n})();\n","/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n    constructor(m = '') {\n        super(m);\n    }\n}\n// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n    // asn.1 DER encoding utils\n    Err: DERErr,\n    // Basic building block is TLV (Tag-Length-Value)\n    _tlv: {\n        encode: (tag, data) => {\n            const { Err: E } = _DER;\n            asafenumber(tag, 'tag');\n            if (tag < 0 || tag > 255)\n                throw new E('tlv.encode: wrong tag');\n            astring(data, 'data');\n            // Internal helper: callers hand this already-validated hex payload, so we only enforce\n            // byte alignment here instead of re-validating every nibble.\n            if (data.length & 1)\n                throw new E('tlv.encode: unpadded data');\n            const dataLen = data.length / 2;\n            const len = numberToHexUnpadded(dataLen);\n            if ((len.length / 2) & 0b1000_0000)\n                throw new E('tlv.encode: long form length too big');\n            // length of length with long form flag\n            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n            const t = numberToHexUnpadded(tag);\n            return t + lenLen + len + data;\n        },\n        // v - value, l - left bytes (unparsed)\n        decode(tag, data) {\n            const { Err: E } = _DER;\n            data = abytes(data, undefined, 'DER data');\n            let pos = 0;\n            if (tag < 0 || tag > 255)\n                throw new E('tlv.decode: wrong tag');\n            if (data.length < 2 || data[pos++] !== tag)\n                throw new E('tlv.decode: wrong tlv');\n            const first = data[pos++];\n            // First bit of first length byte is the short/long form flag.\n            const isLong = !!(first & 0b1000_0000);\n            let length = 0;\n            if (!isLong)\n                length = first;\n            else {\n                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n                const lenLen = first & 0b0111_1111;\n                if (!lenLen)\n                    throw new E('tlv.decode(long): indefinite length not supported');\n                // This would overflow u32 in JS.\n                if (lenLen > 4)\n                    throw new E('tlv.decode(long): byte length is too big');\n                const lengthBytes = data.subarray(pos, pos + lenLen);\n                if (lengthBytes.length !== lenLen)\n                    throw new E('tlv.decode: length bytes not complete');\n                if (lengthBytes[0] === 0)\n                    throw new E('tlv.decode(long): zero leftmost byte');\n                for (const b of lengthBytes)\n                    length = (length << 8) | b;\n                pos += lenLen;\n                if (length < 128)\n                    throw new E('tlv.decode(long): not minimal encoding');\n            }\n            const v = data.subarray(pos, pos + length);\n            if (v.length !== length)\n                throw new E('tlv.decode: wrong value length');\n            return { v, l: data.subarray(pos + length) };\n        },\n    },\n    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n    // since we always use positive integers here. It must always be empty:\n    // - add zero byte if exists\n    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n    _int: {\n        encode(num) {\n            const { Err: E } = _DER;\n            abignumber(num);\n            if (num < _0n)\n                throw new E('integer: negative integers are not allowed');\n            let hex = numberToHexUnpadded(num);\n            // Pad with zero byte if negative flag is present\n            if (Number.parseInt(hex[0], 16) & 0b1000)\n                hex = '00' + hex;\n            if (hex.length & 1)\n                throw new E('unexpected DER parsing assertion: unpadded hex');\n            return hex;\n        },\n        decode(data) {\n            const { Err: E } = _DER;\n            if (data.length < 1)\n                throw new E('invalid signature integer: empty');\n            if (data[0] & 0b1000_0000)\n                throw new E('invalid signature integer: negative');\n            // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n            if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n                throw new E('invalid signature integer: unnecessary leading zero');\n            return bytesToNumberBE(data);\n        },\n    },\n    toSig(bytes, maxScalarBytes) {\n        // parse DER signature\n        const { Err: E, _int: int, _tlv: tlv } = _DER;\n        if (maxScalarBytes !== undefined) {\n            asafenumber(maxScalarBytes, 'maxScalarBytes');\n            if (maxScalarBytes < 1)\n                throw new E('invalid signature: maxScalarBytes must be positive');\n        }\n        const data = abytes(bytes, undefined, 'signature');\n        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n        if (seqLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n        if (sLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        // Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.\n        if (maxScalarBytes !== undefined &&\n            (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))\n            throw new E('invalid signature: integer too large');\n        return { r: int.decode(rBytes), s: int.decode(sBytes) };\n    },\n    hexFromSig(sig) {\n        const { _tlv: tlv, _int: int } = _DER;\n        validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\n        const rs = tlv.encode(0x02, int.encode(sig.r));\n        const ss = tlv.encode(0x02, int.encode(sig.s));\n        const seq = rs + ss;\n        return tlv.encode(0x30, seq);\n    },\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER = /* @__PURE__ */ (() => {\n    Object.freeze(_DER._tlv);\n    Object.freeze(_DER._int);\n    return Object.freeze(_DER);\n})();\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\n    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n    // Since part can be negative, we need to do this on point.\n    // Callers must provide a reduced GLV basis whose vectors satisfy\n    // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.\n    // Reject unreduced scalars instead of silently treating them mod n.\n    aInRange('scalar', k, _0n, n);\n    // TODO: verifyScalar function which consumes lambda\n    const [[a1, b1], [a2, b2]] = basis;\n    const c1 = divNearest(b2 * k, n);\n    const c2 = divNearest(-b1 * k, n);\n    // |k1|/|k2| is < sqrt(N), but can be negative.\n    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n    let k1 = k - c1 * a1 - c2 * a2;\n    let k2 = -c1 * b1 - c2 * b2;\n    const k1neg = k1 < _0n;\n    const k2neg = k2 < _0n;\n    if (k1neg)\n        k1 = -k1;\n    if (k2neg)\n        k2 = -k2;\n    // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n    // relies on the halves being short. This should only happen on wrong bases.\n    // Also, the math inside is complex enough that this guard is worth keeping.\n    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n        throw new Error('splitScalar (endomorphism): failed for k');\n    }\n    return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n    if (!['compact', 'recovered', 'der'].includes(format))\n        throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n    return format;\n}\nfunction validateSigOpts(opts, def) {\n    validateObject(opts);\n    const optsn = {};\n    // Normalize only the declared option subset from `def`; unknown keys are\n    // intentionally ignored so shared / superset option bags stay valid here too.\n    // `extraEntropy` stays an opaque payload until the signing path consumes it.\n    for (let optName of Object.keys(def)) {\n        // @ts-ignore\n        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n    }\n    abool(optsn.lowS, 'lowS');\n    abool(optsn.prehash, 'prehash');\n    if (optsn.format !== undefined)\n        validateSigFormat(optsn.format);\n    return optsn;\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n *   p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n *   n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n *   h: 1n,\n *   a: 0n,\n *   b: 7n,\n *   Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n *   Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(params, extraOpts = {}) {\n    const validated = createCurveFields('weierstrass', params, extraOpts);\n    const Fp = validated.Fp;\n    const Fn = validated.Fn;\n    let CURVE = validated.CURVE;\n    const { h: cofactor, n: CURVE_ORDER } = CURVE;\n    validateObject(extraOpts, {}, {\n        allowInfinityPoint: 'boolean',\n        clearCofactor: 'function',\n        isTorsionFree: 'function',\n        fromBytes: 'function',\n        toBytes: 'function',\n        endo: 'object',\n        randomBytes: 'function',\n    });\n    // Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of\n    // the caller's options must not change arithmetic, subgroup, or codec policy.\n    const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;\n    const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n    if (endoOpts) {\n        if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {\n            throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n        }\n    }\n    const endo = endoOpts\n        ? {\n            beta: endoOpts.beta,\n            basises: endoOpts.basises.map((basis) => [...basis]),\n        }\n        : undefined;\n    const lengths = getWLengths(Fp, Fn);\n    function assertCompressionIsSupported() {\n        if (!Fp.isOdd)\n            throw new Error('compression is not supported: Field does not have .isOdd()');\n    }\n    // Implements IEEE P1363 point encoding\n    function pointToBytes(_c, point, isCompressed) {\n        // Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the\n        // encoder would emit an all-zero byte string that decodes back as a different point. Only\n        // curves that opt into infinity as a public point value get the SEC 1 byte form.\n        if (point.is0()) {\n            if (!allowInfinityPoint)\n                throw new Error('bad point: ZERO');\n            return Uint8Array.of(0); // SEC 1 v2.0 §2.3.3\n        }\n        const { x, y } = point.toAffine();\n        const bx = Fp.toBytes(x);\n        abool(isCompressed, 'isCompressed');\n        if (isCompressed) {\n            assertCompressionIsSupported();\n            const hasEvenY = !Fp.isOdd(y);\n            return concatBytes(pprefix(hasEvenY), bx);\n        }\n        else {\n            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n        }\n    }\n    function pointFromBytes(bytes) {\n        abytes(bytes, undefined, 'Point');\n        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n        const length = bytes.length;\n        const head = bytes[0];\n        const tail = bytes.subarray(1);\n        // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 rejects infinity as a public key.\n        // Leaving 0x00 undecodable by default makes that rejection structural rather than a check:\n        // callers reuse this parser as the strict key boundary, and infinity is simply not\n        // expressible. Curves where infinity is a real wire value opt into the codec instead.\n        // secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n        if (allowInfinityPoint && length === 1 && head === 0x00)\n            return { x: Fp.ZERO, y: Fp.ZERO };\n        // No actual validation is done here: use .assertValidity()\n        if (length === comp && (head === 0x02 || head === 0x03)) {\n            const x = Fp.fromBytes(tail);\n            if (!Fp.isValid(x))\n                throw new Error('bad point: is not on curve, wrong x');\n            const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n            let y;\n            try {\n                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n            }\n            catch (sqrtError) {\n                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n                throw new Error('bad point: is not on curve, sqrt error' + err);\n            }\n            assertCompressionIsSupported();\n            const evenY = Fp.isOdd(y);\n            const evenH = (head & 1) === 1; // ECDSA-specific\n            if (evenH !== evenY)\n                y = Fp.neg(y);\n            return { x, y };\n        }\n        else if (length === uncomp && head === 0x04) {\n            // TODO: more checks\n            const L = Fp.BYTES;\n            const x = Fp.fromBytes(tail.subarray(0, L));\n            const y = Fp.fromBytes(tail.subarray(L, L * 2));\n            if (!isValidXY(x, y))\n                throw new Error('bad point: is not on curve');\n            return { x, y };\n        }\n        else {\n            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n        }\n    }\n    const encodePoint = toBytes === undefined ? pointToBytes : toBytes;\n    const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;\n    // Hoisted from double() / add(): curve params never change after construction.\n    // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n    // the selection depends only on public curve constants.\n    const b3 = Fp.mul(CURVE.b, _3n);\n    const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n    function weierstrassEquation(x) {\n        const x2 = Fp.sqr(x);\n        const x3 = Fp.mul(x2, x);\n        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n    }\n    // TODO: move top-level\n    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n    function isValidXY(x, y) {\n        const left = Fp.sqr(y);\n        const right = weierstrassEquation(x); // x³ + ax + b\n        return Fp.eql(left, right);\n    }\n    // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n    // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n    // Test 1: equation y² = x³ + ax + b should work for generator point.\n    if (!isValidXY(CURVE.Gx, CURVE.Gy))\n        throw new Error('bad curve params: generator point');\n    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n    // Guarantees curve is genus-1, smooth (non-singular).\n    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n    if (Fp.is0(Fp.add(_4a3, _27b2)))\n        throw new Error('bad curve params: a or b');\n    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n    function acoord(title, n, banZero = false) {\n        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n            throw new Error(`bad point coordinate ${title}`);\n        // Extension-field elements are objects. Keep point coordinates detached from caller-owned\n        // objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive\n        // field elements (bigints in shipped prime fields) are already immutable values.\n        return typeof n === 'object' && n !== null ? Fp.create(n) : n;\n    }\n    function aprjpoint(other) {\n        if (!(other instanceof Point))\n            throw new Error('Weierstrass Point expected');\n    }\n    function splitEndoScalarN(k) {\n        if (!endo || !endo.basises)\n            throw new Error('no endo');\n        return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n    }\n    /**\n     * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n     * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n     * pairs against P and ψ(P) = (β⋅x, y), halving the walk's shared doubling chain;\n     * split signs fold into the points.\n     */\n    function pushWnafPair(points, scalars, p, k) {\n        if (!Fn.isValid(k))\n            throw new RangeError('invalid scalar: out of range'); // 0 is valid\n        if (endo) {\n            const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n            const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n            points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n            scalars.push(k1, k2);\n        }\n        else {\n            points.push(p);\n            scalars.push(k);\n        }\n    }\n    // Successful assertValidity() results are cached: Point instances are frozen at construction,\n    // so on-curve + subgroup facts cannot change afterwards. Only success is cached — invalid\n    // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n    // cost a scalar multiplication and the same instance is re-validated across layers\n    // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n    const validityCache = new WeakSet();\n    /**\n     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n     * Default Point works in 2d / affine coordinates: (x, y).\n     * We're doing calculations in projective, because its operations don't require costly inversion.\n     */\n    class Point {\n        static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n        static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n        static Fp = Fp;\n        static Fn = Fn;\n        X;\n        Y;\n        Z;\n        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n        constructor(X, Y, Z) {\n            this.X = acoord('x', X);\n            // This is not just about ZERO / infinity: ambient curves can have real\n            // finite points with y=0. Those points are 2-torsion, so they cannot lie\n            // in the odd prime-order subgroups this point type is meant to represent.\n            this.Y = acoord('y', Y, true);\n            this.Z = acoord('z', Z);\n            Object.freeze(this);\n        }\n        static CURVE() {\n            return CURVE;\n        }\n        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n        static fromAffine(p) {\n            const { x, y } = p || {};\n            if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n                throw new Error('invalid affine point');\n            if (p instanceof Point)\n                throw new Error('projective point not allowed');\n            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n            if (Fp.is0(x) && Fp.is0(y))\n                return Point.ZERO;\n            return new Point(x, y, Fp.ONE);\n        }\n        static fromBytes(bytes) {\n            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n            P.assertValidity();\n            return P;\n        }\n        static fromHex(hex) {\n            return Point.fromBytes(hexToBytes(hex));\n        }\n        get x() {\n            return this.toAffine().x;\n        }\n        get y() {\n            return this.toAffine().y;\n        }\n        /**\n         * @param isLazy - true will defer table computation until the first multiplication\n         */\n        precompute(windowSize = 6, isLazy = true) {\n            wnaf.setWindowSize(this, windowSize);\n            if (!isLazy)\n                this.multiply(_3n); // random number\n            return this;\n        }\n        // TODO: return `this`\n        /** A point on curve is valid if it conforms to equation. */\n        assertValidity() {\n            const p = this;\n            if (p.is0()) {\n                // (0, 1, 0) aka ZERO is invalid in most contexts.\n                // In BLS, ZERO can be serialized, so we allow it.\n                // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n                // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n                if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n                    return;\n                throw new Error('bad point: ZERO');\n            }\n            if (validityCache.has(p))\n                return;\n            // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n            const { x, y } = p.toAffine();\n            if (!Fp.isValid(x) || !Fp.isValid(y))\n                throw new Error('bad point: x or y not field elements');\n            if (!isValidXY(x, y))\n                throw new Error('bad point: equation left != right');\n            if (!p.isTorsionFree())\n                throw new Error('bad point: not in prime-order subgroup');\n            validityCache.add(p);\n        }\n        hasEvenY() {\n            const { y } = this.toAffine();\n            if (!Fp.isOdd)\n                throw new Error(\"Field doesn't support isOdd\");\n            return !Fp.isOdd(y);\n        }\n        /** Compare one point to another. */\n        equals(other) {\n            aprjpoint(other);\n            const { X: X1, Y: Y1, Z: Z1 } = this;\n            const { X: X2, Y: Y2, Z: Z2 } = other;\n            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n            return U1 && U2;\n        }\n        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n        negate() {\n            return new Point(this.X, Fp.neg(this.Y), this.Z);\n        }\n        // Renes-Costello-Batina exception-free doubling formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 3\n        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n        double() {\n            const { X: X1, Y: Y1, Z: Z1 } = this;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            let t0 = Fp.mul(X1, X1); // step 1\n            let t1 = Fp.mul(Y1, Y1);\n            let t2 = Fp.mul(Z1, Z1);\n            let t3 = Fp.mul(X1, Y1);\n            t3 = Fp.add(t3, t3); // step 5\n            Z3 = Fp.mul(X1, Z1);\n            Z3 = Fp.add(Z3, Z3);\n            X3 = mulA(Z3);\n            Y3 = Fp.mul(b3, t2);\n            Y3 = Fp.add(X3, Y3); // step 10\n            X3 = Fp.sub(t1, Y3);\n            Y3 = Fp.add(t1, Y3);\n            Y3 = Fp.mul(X3, Y3);\n            X3 = Fp.mul(t3, X3);\n            Z3 = Fp.mul(b3, Z3); // step 15\n            t2 = mulA(t2);\n            t3 = Fp.sub(t0, t2);\n            t3 = mulA(t3);\n            t3 = Fp.add(t3, Z3);\n            Z3 = Fp.add(t0, t0); // step 20\n            t0 = Fp.add(Z3, t0);\n            t0 = Fp.add(t0, t2);\n            t0 = Fp.mul(t0, t3);\n            Y3 = Fp.add(Y3, t0);\n            t2 = Fp.mul(Y1, Z1); // step 25\n            t2 = Fp.add(t2, t2);\n            t0 = Fp.mul(t2, t3);\n            X3 = Fp.sub(X3, t0);\n            Z3 = Fp.mul(t2, t1);\n            Z3 = Fp.add(Z3, Z3); // step 30\n            Z3 = Fp.add(Z3, Z3);\n            return new Point(X3, Y3, Z3);\n        }\n        // Renes-Costello-Batina exception-free addition formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 1\n        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n        add(other) {\n            aprjpoint(other);\n            const { X: X1, Y: Y1, Z: Z1 } = this;\n            const { X: X2, Y: Y2, Z: Z2 } = other;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            let t0 = Fp.mul(X1, X2); // step 1\n            let t1 = Fp.mul(Y1, Y2);\n            let t2 = Fp.mul(Z1, Z2);\n            let t3 = Fp.add(X1, Y1);\n            let t4 = Fp.add(X2, Y2); // step 5\n            t3 = Fp.mul(t3, t4);\n            t4 = Fp.add(t0, t1);\n            t3 = Fp.sub(t3, t4);\n            t4 = Fp.add(X1, Z1);\n            let t5 = Fp.add(X2, Z2); // step 10\n            t4 = Fp.mul(t4, t5);\n            t5 = Fp.add(t0, t2);\n            t4 = Fp.sub(t4, t5);\n            t5 = Fp.add(Y1, Z1);\n            X3 = Fp.add(Y2, Z2); // step 15\n            t5 = Fp.mul(t5, X3);\n            X3 = Fp.add(t1, t2);\n            t5 = Fp.sub(t5, X3);\n            Z3 = mulA(t4);\n            X3 = Fp.mul(b3, t2); // step 20\n            Z3 = Fp.add(X3, Z3);\n            X3 = Fp.sub(t1, Z3);\n            Z3 = Fp.add(t1, Z3);\n            Y3 = Fp.mul(X3, Z3);\n            t1 = Fp.add(t0, t0); // step 25\n            t1 = Fp.add(t1, t0);\n            t2 = mulA(t2);\n            t4 = Fp.mul(b3, t4);\n            t1 = Fp.add(t1, t2);\n            t2 = Fp.sub(t0, t2); // step 30\n            t2 = mulA(t2);\n            t4 = Fp.add(t4, t2);\n            t0 = Fp.mul(t1, t4);\n            Y3 = Fp.add(Y3, t0);\n            t0 = Fp.mul(t5, t4); // step 35\n            X3 = Fp.mul(t3, X3);\n            X3 = Fp.sub(X3, t0);\n            t0 = Fp.mul(t3, t1);\n            Z3 = Fp.mul(t5, Z3);\n            Z3 = Fp.add(Z3, t0); // step 40\n            return new Point(X3, Y3, Z3);\n        }\n        subtract(other) {\n            // Validate before calling `negate()` so wrong inputs fail with the point guard\n            // instead of leaking a foreign `negate()` error.\n            aprjpoint(other);\n            return this.add(other.negate());\n        }\n        is0() {\n            return this.equals(Point.ZERO);\n        }\n        /**\n         * Constant time multiplication.\n         * Uses precomputed tables (signed fixed-window wNAF) when available.\n         * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n         * @param scalar - by which the point would be multiplied\n         * @returns New point\n         */\n        multiply(scalar) {\n            // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n            // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n            // and failing closed is safer than silently producing the identity point.\n            if (!Fn.isValidNot0(scalar))\n                throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n            const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n            return normalize([p, f])[0];\n        }\n        /**\n         * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n         * when available (two half-width scalars sharing one halved doubling chain).\n         * It's faster, but should only be used when you don't care about\n         * an exposed secret key e.g. sig verification, which works over *public* keys.\n         */\n        multiplyUnsafe(scalar) {\n            const p = this;\n            const sc = scalar;\n            // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n            // Reducing them mod n would turn bad caller input into an accidental identity point.\n            if (!Fn.isValid(sc))\n                throw new RangeError('invalid scalar: out of range'); // 0 is valid\n            if (sc === _0n || p.is0())\n                return Point.ZERO;\n            if (sc === _1n)\n                return p;\n            if (wnaf.hasWindowSize(this))\n                return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n            const points = [];\n            const scalars = [];\n            pushWnafPair(points, scalars, p, sc);\n            return mulAddUnsafe(Point, points, scalars);\n        }\n        /**\n         * Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).\n         * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n         * (when available) halves the chain again by splitting each scalar into two half-width\n         * parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.\n         * Only for public scalars.\n         */\n        mulAddUnsafe(a, other, b) {\n            aprjpoint(other);\n            const points = [];\n            const scalars = [];\n            pushWnafPair(points, scalars, this, a);\n            pushWnafPair(points, scalars, other, b);\n            return mulAddUnsafe(Point, points, scalars);\n        }\n        /**\n         * Converts Projective point to affine (x, y) coordinates.\n         * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n         * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n         */\n        toAffine(invertedZ) {\n            const p = this;\n            let iz = invertedZ;\n            if (iz != null && !Fp.isValid(iz))\n                throw new RangeError('\"invertedZ\" expected valid field element');\n            const { X, Y, Z } = p;\n            // Fast-path for normalized points\n            if (Fp.eql(Z, Fp.ONE))\n                return { x: X, y: Y };\n            const is0 = p.is0();\n            // If invZ was 0, we return zero point. However we still want to execute\n            // all operations, so we replace invZ with a random number, 1.\n            if (iz == null)\n                iz = is0 ? Fp.ONE : Fp.inv(Z);\n            const x = Fp.mul(X, iz);\n            const y = Fp.mul(Y, iz);\n            const zz = Fp.mul(Z, iz);\n            if (is0)\n                return { x: Fp.ZERO, y: Fp.ZERO };\n            if (!Fp.eql(zz, Fp.ONE))\n                throw new Error('invZ was invalid');\n            return { x, y };\n        }\n        /**\n         * Checks whether Point is free of torsion elements (is in prime subgroup).\n         * Always torsion-free for cofactor=1 curves.\n         */\n        isTorsionFree() {\n            if (cofactor === _1n)\n                return true;\n            if (isTorsionFree)\n                return isTorsionFree(Point, this);\n            // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n            return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n        }\n        clearCofactor() {\n            if (cofactor === _1n)\n                return this; // Fast-path\n            if (clearCofactor)\n                return clearCofactor(Point, this);\n            // Default fallback assumes the cofactor fits the usual subgroup-scalar\n            // multiplyUnsafe() contract. Curves with larger / structured cofactors\n            // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n            return this.multiplyUnsafe(cofactor);\n        }\n        isSmallOrder() {\n            if (cofactor === _1n)\n                return this.is0(); // Fast-path\n            return this.clearCofactor().is0();\n        }\n        toBytes(isCompressed = true) {\n            abool(isCompressed, 'isCompressed');\n            // assertValidity() covers on-curve and subgroup membership. The encoder below repeats the\n            // infinity check rather than relying on this call, so it stays correct for any caller.\n            this.assertValidity();\n            return encodePoint(Point, this, isCompressed);\n        }\n        toHex(isCompressed = true) {\n            return bytesToHex(this.toBytes(isCompressed));\n        }\n        toString() {\n            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n        }\n    }\n    const normalize = (points) => normalizeZ(Point, points);\n    const wnaf = new ScalarMultiplier(Point, randomBytes);\n    // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n    // Disable for tiny toy curves, with scalar fields < 6 bits.\n    if (wnaf.bits >= 6)\n        Point.BASE.precompute(6);\n    Object.freeze(Point.prototype);\n    Object.freeze(Point);\n    return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\n    return {\n        secretKey: Fn.BYTES,\n        publicKey: 1 + Fp.BYTES,\n        publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n        publicKeyHasPrefix: true,\n        // Raw compact `(r || s)` signature width; DER and recovered signatures use\n        // different lengths outside this helper.\n        signature: 2 * Fn.BYTES,\n    };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n *   - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n    validatePointCons(Point);\n    const { Fn } = Point;\n    const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n    // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n    // minimum even on toy curves.\n    const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n        seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n    });\n    function isValidSecretKey(secretKey) {\n        try {\n            const num = Fn.fromBytes(secretKey);\n            return Fn.isValidNot0(num);\n        }\n        catch (error) {\n            return false;\n        }\n    }\n    function isValidPublicKey(publicKey, isCompressed) {\n        const { publicKey: comp, publicKeyUncompressed } = lengths;\n        try {\n            const l = publicKey.length;\n            if (isCompressed === true && l !== comp)\n                return false;\n            if (isCompressed === false && l !== publicKeyUncompressed)\n                return false;\n            // SEC 1 §3.2.2: the identity is never a valid public key, even on curves whose codec\n            // can decode it.\n            return !Point.fromBytes(publicKey).is0();\n        }\n        catch (error) {\n            return false;\n        }\n    }\n    /**\n     * Produces cryptographically secure secret key from random of size\n     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n     */\n    function randomSecretKey(seed) {\n        seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n    }\n    /**\n     * Computes public key for a secret key. Checks for validity of the secret key.\n     * @param isCompressed - whether to return compact (default), or full key\n     * @returns Public key, full when isCompressed=false; short when isCompressed=true\n     */\n    function getPublicKey(secretKey, isCompressed = true) {\n        return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n    }\n    /**\n     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n     */\n    function isProbPub(item) {\n        const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n        const allowedLengths = Fn._lengths;\n        if (!isBytes(item))\n            return undefined;\n        const l = abytes(item, undefined, 'key').length;\n        const isPub = l === publicKey || l === publicKeyUncompressed;\n        const isSec = l === secretKey || !!allowedLengths?.includes(l);\n        // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n        if (isPub && isSec)\n            return undefined;\n        return isPub;\n    }\n    /**\n     * ECDH (Elliptic Curve Diffie Hellman).\n     * Computes encoded shared point from secret key A and public key B.\n     * Checks: 1) secret key validity 2) shared key is on-curve.\n     * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n     * Returns the encoded shared point on purpose: callers that need `x_P`\n     * can derive it from the encoded point, but `x_P` alone cannot recover the\n     * point/parity back.\n     * This helper only exposes the fully validated public-key path, not cofactor DH.\n     * @param isCompressed - whether to return compact (default), or full key\n     * @returns shared point encoding\n     */\n    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n        if (isProbPub(secretKeyA) === true)\n            throw new Error('first arg must be private key');\n        if (isProbPub(publicKeyB) === false)\n            throw new Error('second arg must be public key');\n        const s = Fn.fromBytes(secretKeyA);\n        const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n        if (b.is0())\n            throw new Error('invalid public key: point at infinity');\n        return b.multiply(s).toBytes(isCompressed);\n    }\n    const utils = {\n        isValidSecretKey,\n        isValidPublicKey,\n        randomSecretKey,\n    };\n    const keygen = createKeygen(randomSecretKey, getPublicKey);\n    Object.freeze(utils);\n    Object.freeze(lengths);\n    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n *   - `lowS`: Default low-S policy.\n *   - `hmac`: HMAC implementation used by RFC6979 DRBG.\n *   - `randomBytes`: Optional RNG override.\n *   - `bits2int`: Optional hash-to-int conversion override.\n *   - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n    validatePointCons(Point);\n    // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n    const hash_ = hash;\n    ahash(hash_);\n    validateObject(ecdsaOpts, {}, {\n        hmac: 'function',\n        lowS: 'boolean',\n        randomBytes: 'function',\n        bits2int: 'function',\n        bits2int_modN: 'function',\n    });\n    const opts = Object.assign({}, ecdsaOpts);\n    const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n    const hmac = opts.hmac === undefined\n        ? (key, msg) => nobleHmac(hash_, key, msg)\n        : opts.hmac;\n    const { Fp, Fn } = Point;\n    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n    // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n    // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n    // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n    // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n    // blinded call, where breakage fails closed.\n    const blindLength = getMinHashLength(CURVE_ORDER);\n    const csprng = probeRandomBytes(randomBytes, blindLength);\n    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n    const defaultSigOpts = {\n        prehash: true,\n        lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n        format: 'compact',\n        extraEntropy: false,\n    };\n    // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n    // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n    // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n    // smallest such lift is 1 + 2n, not 2n.\n    const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n    function isBiggerThanHalfOrder(number) {\n        const HALF = CURVE_ORDER >> _1n;\n        return number > HALF;\n    }\n    function validateRS(title, num) {\n        if (!Fn.isValidNot0(num))\n            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n        return num;\n    }\n    function assertFieldSignIsSupported() {\n        if (!Fp.isOdd)\n            throw new Error(\"Field doesn't support isOdd\");\n    }\n    // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n    // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n    function getRecoveryBit(x, y, r) {\n        assertFieldSignIsSupported();\n        return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n    }\n    function assertRecoverableCurve() {\n        // ECDSA recovery only supports curves where the current recovery id can distinguish\n        // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n        // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n        // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n        // To easily get i, we either need to:\n        // a. increase amount of valid recid values (4, 5...); OR\n        // b. prohibit recovered signatures for those curves.\n        if (hasLargeRecoveryLifts)\n            throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n    }\n    function validateSigLength(bytes, format) {\n        validateSigFormat(format);\n        const size = lengths.signature;\n        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n        return abytes(bytes, sizer);\n    }\n    /**\n     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n     */\n    class Signature {\n        r;\n        s;\n        recovery;\n        constructor(r, s, recovery) {\n            this.r = validateRS('r', r); // r in [1..N-1];\n            this.s = validateRS('s', s); // s in [1..N-1];\n            if (recovery != null) {\n                assertRecoverableCurve();\n                if (![0, 1, 2, 3].includes(recovery))\n                    throw new Error('invalid recovery id');\n                this.recovery = recovery;\n            }\n            Object.freeze(this);\n        }\n        static fromBytes(bytes, format = defaultSigOpts.format) {\n            validateSigLength(bytes, format);\n            let recid;\n            if (format === 'der') {\n                // Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the\n                // total bound conservative so malformed inputs are rejected before parsing any INTEGER.\n                if (bytes.length > 2 * Fn.BYTES + 16)\n                    throw new DER.Err('invalid signature: DER signature too long');\n                const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);\n                return new Signature(r, s);\n            }\n            if (format === 'recovered') {\n                recid = bytes[0];\n                format = 'compact';\n                bytes = bytes.subarray(1);\n            }\n            const L = lengths.signature / 2;\n            const r = bytes.subarray(0, L);\n            const s = bytes.subarray(L, L * 2);\n            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n        }\n        static fromHex(hex, format) {\n            return this.fromBytes(hexToBytes(hex), format);\n        }\n        assertRecovery() {\n            const { recovery } = this;\n            if (recovery == null)\n                throw new Error('invalid recovery id: must be present');\n            return recovery;\n        }\n        addRecoveryBit(recovery) {\n            return new Signature(this.r, this.s, recovery);\n        }\n        // Unlike the top-level helper below, this method expects a digest that has\n        // already been hashed to the curve's message representative.\n        recoverPublicKey(messageHash) {\n            const { r, s } = this;\n            const recovery = this.assertRecovery();\n            const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n            if (!Fp.isValid(radj))\n                throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n            const x = Fp.toBytes(radj);\n            const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n            const ir = Fn.inv(radj); // r^-1\n            const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n            const u1 = Fn.create(-h * ir); // -hr^-1\n            const u2 = Fn.create(s * ir); // sr^-1\n            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n            const Q = Point.BASE.mulAddUnsafe(u1, R, u2);\n            if (Q.is0())\n                throw new Error('invalid recovery: point at infinify');\n            Q.assertValidity();\n            return Q;\n        }\n        // Signatures should be low-s, to prevent malleability.\n        hasHighS() {\n            return isBiggerThanHalfOrder(this.s);\n        }\n        toBytes(format = defaultSigOpts.format) {\n            validateSigFormat(format);\n            if (format === 'der')\n                return hexToBytes(DER.hexFromSig(this));\n            const { r, s } = this;\n            const rb = Fn.toBytes(r);\n            const sb = Fn.toBytes(s);\n            if (format === 'recovered') {\n                assertRecoverableCurve();\n                return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n            }\n            return concatBytes(rb, sb);\n        }\n        toHex(format) {\n            return bytesToHex(this.toBytes(format));\n        }\n    }\n    Object.freeze(Signature.prototype);\n    Object.freeze(Signature);\n    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n    const bits2int = opts.bits2int === undefined\n        ? function bits2int_def(bytes) {\n            // Our custom check \"just in case\", for protection against DoS\n            if (bytes.length > 8192)\n                throw new Error('input is too large');\n            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n            // for some cases, since bytes.length * 8 is not actual bitLength.\n            const num = bytesToNumberBE(bytes); // check for == u8 done here\n            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n            return delta > 0 ? num >> BigInt(delta) : num;\n        }\n        : opts.bits2int;\n    const bits2int_modN = opts.bits2int_modN === undefined\n        ? function bits2int_modN_def(bytes) {\n            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n        }\n        : opts.bits2int_modN;\n    const ORDER_MASK = bitMask(fnBits);\n    // Pads output with zero as per spec.\n    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n    function int2octets(num) {\n        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n        return Fn.toBytes(num);\n    }\n    function validateMsgAndHash(message, prehash) {\n        abytes(message, undefined, 'message');\n        return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\n    }\n    /**\n     * Steps A, D of RFC6979 3.2.\n     * Creates RFC6979 seed; converts msg/privKey to numbers.\n     * Used only in sign, not in verify.\n     *\n     * Warning: we cannot assume here that message has same amount of bytes as curve order,\n     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n     */\n    function prepSig(message, secretKey, opts) {\n        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n        // We can't later call bits2octets, since nested bits2int is broken for curves\n        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n        const h1int = bits2int_modN(message);\n        const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n        if (!Fn.isValidNot0(d))\n            throw new Error('invalid private key');\n        const seedArgs = [int2octets(d), int2octets(h1int)];\n        // extraEntropy. RFC6979 3.6: additional k' (optional).\n        if (extraEntropy != null && extraEntropy !== false) {\n            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n            // gen random bytes OR pass as-is\n            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n            seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n        }\n        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n        const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n        // Converts signature params into point w r/s, checks result for validity.\n        // To transform k => Signature:\n        // q = k⋅G\n        // r = q.x mod n\n        // s = k^-1(m + rd) mod n\n        // The nonce inversion is blinded: with random b ∈ [1,n−1], s = (bk)^-1(bm + bdr) per\n        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n        // loop count depends on its input (cf. Minerva), but here it only ever sees b·k — uniformly\n        // random, independent of k — so its timing reveals nothing about the nonce; b also masks d in\n        // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n        // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n        function k2sig(kBytes) {\n            // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n            // Important: all mod() calls here must be done over N\n            const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n            if (!Fn.isValidNot0(k))\n                return; // Valid scalars (including k) must be in 1..N-1\n            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n            const r = Fn.create(q.x); // r = q.x mod n\n            if (r === _0n)\n                return;\n            let s;\n            if (csprng !== undefined) {\n                // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n                const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n                const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n                const bm = Fn.mul(b, m);\n                const bd = Fn.mul(b, d);\n                s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n            }\n            else {\n                const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n                s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n            }\n            if (s === _0n)\n                return;\n            let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)\n            let normS = s;\n            if (lowS && isBiggerThanHalfOrder(s)) {\n                normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n                recovery ^= 1;\n            }\n            return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n        }\n        return { seed, k2sig };\n    }\n    /**\n     * Signs a message or message hash with a secret key.\n     * With the default `prehash: true`, raw message bytes are hashed internally;\n     * only `{ prehash: false }` expects a caller-supplied digest.\n     *\n     * ```\n     * sign(m, d) where\n     *   k = rfc6979_hmac_drbg(m, d)\n     *   (x, y) = G × k\n     *   r = x mod n\n     *   s = (m + dr) / k mod n\n     * ```\n     */\n    function sign(message, secretKey, opts = {}) {\n        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n        const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n        return sig.toBytes(opts.format);\n    }\n    /**\n     * Verifies a signature against message and public key.\n     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n     *\n     * ```\n     * verify(r, s, h, P) where\n     *   u1 = hs^-1 mod n\n     *   u2 = rs^-1 mod n\n     *   R = u1⋅G + u2⋅P\n     *   mod(R.x, n) == r\n     * ```\n     */\n    function verify(signature, message, publicKey, opts = {}) {\n        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n        publicKey = abytes(publicKey, undefined, 'publicKey');\n        message = validateMsgAndHash(message, prehash);\n        if (!isBytes(signature)) {\n            const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n            throw new Error('verify expects Uint8Array signature' + end);\n        }\n        validateSigLength(signature, format); // execute this twice because we want loud error\n        try {\n            const sig = Signature.fromBytes(signature, format);\n            const P = Point.fromBytes(publicKey);\n            // SEC 1 verification keys must not be the identity, even when the generic point decoder\n            // permits infinity for another protocol (for example, a pairing curve).\n            if (P.is0())\n                return false;\n            if (lowS && sig.hasHighS())\n                return false;\n            const { r, s } = sig;\n            const h = bits2int_modN(message); // mod n, not mod p\n            const is = Fn.inv(s); // s^-1 mod n\n            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n            const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1⋅G + u2⋅P, joint Strauss–Shamir\n            if (R.is0())\n                return false;\n            const q = R.toAffine();\n            const v = Fn.create(q.x); // v = R.x mod n\n            if (v !== r)\n                return false;\n            // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n            // so binding the signature to its recovery id only needs R's parity/overflow bits.\n            if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n                return false;\n            return true;\n        }\n        catch (e) {\n            return false;\n        }\n    }\n    function recoverPublicKey(signature, message, opts = {}) {\n        // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n        // bytes first unless the caller passes `{ prehash: false }`.\n        const { prehash } = validateSigOpts(opts, defaultSigOpts);\n        message = validateMsgAndHash(message, prehash);\n        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n    }\n    // utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.\n    return Object.freeze({\n        keygen,\n        getPublicKey,\n        getSharedSecret,\n        utils,\n        lengths,\n        Point,\n        sign,\n        verify,\n        recoverPublicKey,\n        Signature,\n        hash: hash_,\n    });\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createFROST, } from \"./abstract/frost.js\";\nimport { createHasher, isogenyMap, mapToCurveSimpleSWU, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, copyBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n    h: BigInt(1),\n    a: BigInt(0),\n    b: BigInt(7),\n    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n    basises: [\n        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n    ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n    const P = secp256k1_CURVE.p;\n    // prettier-ignore\n    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n    // prettier-ignore\n    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n    const b2 = (y * y * y) % P; // x^3, 11\n    const b3 = (b2 * b2 * y) % P; // x^7\n    const b6 = (pow2(b3, _3n, P) * b3) % P;\n    const b9 = (pow2(b6, _3n, P) * b3) % P;\n    const b11 = (pow2(b9, _2n, P) * b2) % P;\n    const b22 = (pow2(b11, _11n, P) * b11) % P;\n    const b44 = (pow2(b22, _22n, P) * b22) % P;\n    const b88 = (pow2(b44, _44n, P) * b44) % P;\n    const b176 = (pow2(b88, _88n, P) * b88) % P;\n    const b220 = (pow2(b176, _44n, P) * b44) % P;\n    const b223 = (pow2(b220, _3n, P) * b3) % P;\n    const t1 = (pow2(b223, _23n, P) * b22) % P;\n    const t2 = (pow2(t1, _6n, P) * b2) % P;\n    const root = pow2(t2, _2n, P);\n    if (!Fpk1.eql(Fpk1.sqr(root), y))\n        throw new Error('Cannot find square root');\n    return root;\n}\nconst Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n    Fp: Fpk1,\n    endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = Object.create(null);\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag, ...messages) {\n    let tagP = TAGGED_HASH_PREFIXES[tag];\n    if (tagP === undefined) {\n        const tagH = sha256(asciiToBytes(tag));\n        tagP = concatBytes(tagH, tagH);\n        TAGGED_HASH_PREFIXES[tag] = tagP;\n    }\n    return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst affineXToBytes = ({ x }) => Fpk1.toBytes(x);\nconst hasEven = (y) => !Fpk1.isOdd(y);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n    const { Fn, BASE } = Pointk1;\n    const d_ = Fn.fromBytes(abytes(priv, 32, 'secretKey'));\n    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n    const affine = p.toAffine();\n    const scalar = hasEven(affine.y) ? d_ : Fn.neg(d_);\n    return { scalar, bytes: affineXToBytes(affine) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n    const Fp = Fpk1;\n    if (!Fp.isValidNot0(x))\n        throw new Error('invalid x: Fail if x ≥ p');\n    const xx = Fp.sqr(x);\n    const c = Fp.add(Fp.mulN(xx, x), BigInt(7)); // Let c = x³ + 7 mod p.\n    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n    // Return the unique point P such that x(P) = x and\n    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n    if (!hasEven(y))\n        y = Fp.neg(y);\n    const p = Pointk1.fromAffine({ x, y });\n    p.assertValidity();\n    return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args) {\n    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey) {\n    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n    const { Fn, BASE } = Pointk1;\n    // Snapshot once: nonce, challenge, and self-verification must use one transcript.\n    const m = copyBytes(abytes(message, undefined, 'message'));\n    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n    const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n    // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n    // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n    // here: that helper parses canonical secret keys and rejects rand >= n instead\n    // of reducing the nonce hash modulo the group order.\n    const k_ = Fn.create(num(rand));\n    // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G.\"\n    if (k_ === _0n)\n        throw new Error('sign failed: k is zero');\n    const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n    const affine = p.toAffine();\n    const k = hasEven(affine.y) ? k_ : Fn.neg(k_);\n    const rx = affineXToBytes(affine);\n    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n    sig.set(rx, 0);\n    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n    // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n    if (!schnorrVerify(sig, m, px))\n        throw new Error('sign: Invalid signature produced');\n    return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n    const { Fp, Fn, BASE } = Pointk1;\n    const sig = abytes(signature, 64, 'signature');\n    const m = abytes(message, undefined, 'message');\n    const pub = abytes(publicKey, 32, 'publicKey');\n    try {\n        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n        const rBytes = sig.subarray(0, 32);\n        const r = num(rBytes); // Let r = int(sig[0:32]); fail if r ≥ p.\n        if (!Fp.isValidNot0(r))\n            return false;\n        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n        // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n        // s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as\n        // crafted edge cases and fail closed instead of carrying that extra verification surface.\n        if (!Fn.isValidNot0(s))\n            return false;\n        // int(challenge(bytes(r) || bytes(P) || m)) % n\n        const e = challenge(rBytes, pointToBytes(P), m);\n        // R = s⋅G - e⋅P, where -eP == (n-e)P\n        const R = BASE.mulAddUnsafe(s, P, Fn.neg(e)); // s⋅G + (-e)⋅P, joint Strauss–Shamir\n        const { x, y } = R.toAffine();\n        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n        if (R.is0() || !hasEven(y) || !Fp.eql(x, r))\n            return false;\n        return true;\n    }\n    catch (error) {\n        return false;\n    }\n}\nexport const __TEST = /* @__PURE__ */ Object.freeze({ lift_x, frostTweakPublic, frostTweakSecret });\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n    const size = 32;\n    const seedLength = 48;\n    const randomSecretKey = (seed) => {\n        seed = seed === undefined ? randomBytes(seedLength) : seed;\n        return mapHashToField(abytes(seed, seedLength, 'seed'), secp256k1_CURVE.n);\n    };\n    return Object.freeze({\n        keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n        getPublicKey: schnorrGetPublicKey,\n        sign: schnorrSign,\n        verify: schnorrVerify,\n        Point: Pointk1,\n        utils: Object.freeze({\n            randomSecretKey,\n            taggedHash,\n            lift_x,\n            pointToBytes,\n        }),\n        lengths: Object.freeze({\n            secretKey: size,\n            publicKey: size,\n            publicKeyHasPrefix: false,\n            signature: size * 2,\n            seed: seedLength,\n        }),\n    });\n})();\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n    // xNum\n    [\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n    ],\n    // xDen\n    [\n        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n    ],\n    // yNum\n    [\n        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n    ],\n    // yDen\n    [\n        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n    ],\n].map((i) => i.map((j) => BigInt(j)))))();\n// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU;\nconst getMapSWU = () => mapSWU ||\n    (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n        // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n        // defer it to first use; after that the cached mapper is reused directly.\n        A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n        B: BigInt('1771'),\n        Z: Fpk1.create(BigInt('-11')),\n    }));\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n    const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n    return isoMap(x, y);\n}, {\n    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n    p: Fpk1.ORDER,\n    m: 1,\n    k: 128,\n    expand: 'xmd',\n    hash: sha256,\n}))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({\n    name: 'FROST-secp256k1-SHA256-v1',\n    Point: Pointk1,\n    hashToScalar: secp256k1_hasher.hashToScalar,\n    hash: sha256,\n}))();\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point, merkleRoot) {\n    if (merkleRoot === undefined)\n        return _0n;\n    const x = pointToBytes(point);\n    const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n    // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n    // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n    if (!Pointk1.Fn.isValid(t))\n        throw new Error('invalid TapTweak hash');\n    return t;\n}\nfunction frostPubToEvenY(pub) {\n    const VK = Pointk1.fromBytes(pub.commitments[0]);\n    // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n    if (hasEven(VK.y))\n        return pub;\n    return {\n        signers: { min: pub.signers.min, max: pub.signers.max },\n        commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n        verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [\n            k,\n            Pointk1.fromBytes(v).negate().toBytes(),\n        ])),\n    };\n}\nfunction frostSecretToEvenY(s, pub) {\n    const VK = Pointk1.fromBytes(pub.commitments[0]);\n    // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n    if (hasEven(VK.y))\n        return s;\n    const Fn = Pointk1.Fn;\n    return {\n        ...s,\n        signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n    };\n}\nfunction frostNoncesToEvenY(groupCommitment, nonces) {\n    if (hasEven(groupCommitment.y))\n        return nonces;\n    const Fn = Pointk1.Fn;\n    return {\n        binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n        hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n    };\n}\nfunction frostTweakSecret(s, pub, merkleRoot) {\n    const Fn = Pointk1.Fn;\n    const keyPackage = frostSecretToEvenY(s, pub);\n    const evenPub = frostPubToEvenY(pub);\n    const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n    const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n    return {\n        identifier: keyPackage.identifier,\n        signingShare,\n    };\n}\nfunction frostTweakPublic(pub, merkleRoot) {\n    const PKPackage = frostPubToEvenY(pub);\n    const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n    // Disabled TapTweak (t=0): return the even-Y-normalized package as-is. multiply() rejects\n    // zero scalars, and adding [0]G would be a no-op anyway.\n    if (t === _0n)\n        return PKPackage;\n    const tp = Pointk1.BASE.multiply(t);\n    const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());\n    const verifyingShares = {};\n    for (const k in PKPackage.verifyingShares) {\n        verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n    }\n    return {\n        signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n        commitments,\n        verifyingShares,\n    };\n}\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST = /* @__PURE__ */ (() => createFROST({\n    name: 'FROST-secp256k1-SHA256-TR-v1',\n    Point: Pointk1,\n    hashToScalar: secp256k1_hasher.hashToScalar,\n    hash: sha256,\n    // Taproot related hacks\n    parsePublicKey(publicKey) {\n        // External Taproot keys are x-only, but local key packages still use compressed points.\n        if (publicKey.length === 32)\n            return lift_x(bytesToNumberBE(publicKey));\n        if (publicKey.length === 33)\n            return Pointk1.fromBytes(publicKey);\n        throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n    },\n    adjustScalar(n) {\n        const PK = Pointk1.BASE.multiply(n);\n        return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n    },\n    adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n    challenge(R, PK, msg) {\n        return challenge(pointToBytes(R), pointToBytes(PK), msg);\n    },\n    adjustNonces: frostNoncesToEvenY,\n    adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n    adjustPublic: frostPubToEvenY,\n    adjustSecret: frostSecretToEvenY,\n    adjustTx: {\n        // Compat with official implementation\n        encode: (tx) => tx.subarray(1),\n        decode: (tx) => concatBytes(Uint8Array.of(0x02), tx),\n    },\n    adjustDKG: (k) => {\n        // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n        // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n        const merkleRoot = new Uint8Array(0);\n        return {\n            public: frostTweakPublic(k.public, merkleRoot),\n            secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n        };\n    },\n}))();\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA-1 state from RFC 3174 §6.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n    0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n    A = SHA1_IV[0] | 0;\n    B = SHA1_IV[1] | 0;\n    C = SHA1_IV[2] | 0;\n    D = SHA1_IV[3] | 0;\n    E = SHA1_IV[4] | 0;\n    constructor() {\n        super(64, 20, 8, false);\n    }\n    get() {\n        const { A, B, C, D, E } = this;\n        return [A, B, C, D, E];\n    }\n    set(A, B, C, D, E) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n        this.E = E | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        for (let i = 0; i < 16; i++, offset += 4)\n            SHA1_W[i] = view.getUint32(offset, false);\n        for (let i = 16; i < 80; i++)\n            SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n        // Compression function main loop, 80 rounds\n        let { A, B, C, D, E } = this;\n        for (let i = 0; i < 80; i++) {\n            let F, K;\n            if (i < 20) {\n                F = Chi(B, C, D);\n                K = 0x5a827999;\n            }\n            else if (i < 40) {\n                F = B ^ C ^ D;\n                K = 0x6ed9eba1;\n            }\n            else if (i < 60) {\n                F = Maj(B, C, D);\n                K = 0x8f1bbcdc;\n            }\n            else {\n                F = B ^ C ^ D;\n                K = 0xca62c1d6;\n            }\n            const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n            E = D;\n            D = C;\n            C = rotl(B, 30);\n            B = A;\n            A = T;\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        E = (E + this.E) | 0;\n        this.set(A, B, C, D, E);\n    }\n    roundClean() {\n        clean(SHA1_W);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        this.set(0, 0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n// RFC 1321 §3.4 per-round rotate amounts, flattened to 64 entries so the round loop\n// avoids allocating a 4-element array literal every round (measured ~5% of md5).\nconst MD5_SHIFTS = /* @__PURE__ */ (() => {\n    const S = [\n        [7, 12, 17, 22],\n        [5, 9, 14, 20],\n        [4, 11, 16, 23],\n        [6, 10, 15, 21],\n    ];\n    return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);\n})();\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n    A = MD5_IV[0] | 0;\n    B = MD5_IV[1] | 0;\n    C = MD5_IV[2] | 0;\n    D = MD5_IV[3] | 0;\n    constructor() {\n        super(64, 16, 8, true);\n    }\n    get() {\n        const { A, B, C, D } = this;\n        return [A, B, C, D];\n    }\n    set(A, B, C, D) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        for (let i = 0; i < 16; i++, offset += 4)\n            MD5_W[i] = view.getUint32(offset, true);\n        // Compression function main loop, 64 rounds\n        let { A, B, C, D } = this;\n        for (let i = 0; i < 64; i++) {\n            let F, g;\n            if (i < 16) {\n                F = Chi(B, C, D);\n                g = i;\n            }\n            else if (i < 32) {\n                // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n                F = Chi(D, B, C);\n                g = (5 * i + 1) % 16;\n            }\n            else if (i < 48) {\n                F = B ^ C ^ D;\n                g = (3 * i + 5) % 16;\n            }\n            else {\n                F = C ^ (B | ~D);\n                g = (7 * i) % 16;\n            }\n            F = F + A + K[i] + MD5_W[g];\n            A = D;\n            D = C;\n            C = B;\n            B = B + rotl(F, MD5_SHIFTS[i]);\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        this.set(A, B, C, D);\n    }\n    roundClean() {\n        clean(MD5_W);\n    }\n    destroy() {\n        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n        // update()/digest() callable on reused instances.\n        this.destroyed = true;\n        this.set(0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n    const L = [Id160];\n    const R = [Pi160];\n    const res = [L, R];\n    for (let i = 0; i < 4; i++)\n        for (let j of res)\n            j.push(j[i].map((k) => Rho160[k]));\n    return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n    [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n    [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n    [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n    [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n    [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n    0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n    0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group, x, y, z) {\n    if (group === 0)\n        return x ^ y ^ z;\n    if (group === 1)\n        return (x & y) | (~x & z);\n    if (group === 2)\n        return (x | ~y) ^ z;\n    if (group === 3)\n        return (x & z) | (y & ~z);\n    return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD {\n    h0 = 0x67452301 | 0;\n    h1 = 0xefcdab89 | 0;\n    h2 = 0x98badcfe | 0;\n    h3 = 0x10325476 | 0;\n    h4 = 0xc3d2e1f0 | 0;\n    constructor() {\n        super(64, 20, 8, true);\n    }\n    get() {\n        const { h0, h1, h2, h3, h4 } = this;\n        return [h0, h1, h2, h3, h4];\n    }\n    set(h0, h1, h2, h3, h4) {\n        this.h0 = h0 | 0;\n        this.h1 = h1 | 0;\n        this.h2 = h2 | 0;\n        this.h3 = h3 | 0;\n        this.h4 = h4 | 0;\n    }\n    _cloneInto(to) {\n        (to ||= new this.constructor()).set(...this.get());\n        return this._cloneIntoMeta(to);\n    }\n    process(view, offset) {\n        for (let i = 0; i < 16; i++, offset += 4)\n            BUF_160[i] = view.getUint32(offset, true);\n        // prettier-ignore\n        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n        // Instead of iterating 0 to 80, we split it into 5 groups\n        // And use the groups in constants, functions, etc. Much simpler\n        for (let group = 0; group < 5; group++) {\n            const rGroup = 4 - group;\n            const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n            const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n            const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n            for (let i = 0; i < 16; i++) {\n                const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n                al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n            }\n            // 2 loops are 10% faster\n            for (let i = 0; i < 16; i++) {\n                const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n                ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n            }\n        }\n        // Add the compressed chunk to the current hash value\n        // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n        this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n    }\n    roundClean() {\n        clean(BUF_160);\n    }\n    destroy() {\n        this.destroyed = true;\n        clean(this.buffer);\n        this.set(0, 0, 0, 0, 0);\n    }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n/** Transforms values between two representations. */\nexport interface Coder<F, T> {\n  /**\n   * Converts a value from the input representation to the output representation.\n   * @param from - Value in the source representation.\n   * @returns Converted value.\n   */\n  encode(from: F): T;\n  /**\n   * Converts a value from the output representation back to the input representation.\n   * @param to - Value in the target representation.\n   * @returns Converted value.\n   */\n  decode(to: T): F;\n}\n\n/** Coder that works with byte arrays and strings. */\nexport interface BytesCoder extends Coder<Uint8Array, string> {\n  /**\n   * Encodes bytes into a string representation.\n   * @param data - Bytes to encode.\n   * @returns Encoded string.\n   */\n  encode: (data: Uint8Array) => string;\n  /**\n   * Decodes a string representation into raw bytes.\n   * @param str - Encoded string.\n   * @returns Decoded bytes.\n   */\n  decode: (str: string) => Uint8Array;\n}\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n  ? BigInt64Array\n  : T extends BigUint64Array\n    ? BigUint64Array\n    : T extends Float32Array\n      ? Float32Array\n      : T extends Float64Array\n        ? Float64Array\n        : T extends Int16Array\n          ? Int16Array\n          : T extends Int32Array\n            ? Int32Array\n            : T extends Int8Array\n              ? Int8Array\n              : T extends Uint16Array\n                ? Uint16Array\n                : T extends Uint32Array\n                  ? Uint32Array\n                  : T extends Uint8ClampedArray\n                    ? Uint8ClampedArray\n                    : T extends Uint8Array\n                      ? Uint8Array\n                      : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n  ? ReturnType<typeof BigInt64Array.of>\n  : T extends BigUint64Array\n    ? ReturnType<typeof BigUint64Array.of>\n    : T extends Float32Array\n      ? ReturnType<typeof Float32Array.of>\n      : T extends Float64Array\n        ? ReturnType<typeof Float64Array.of>\n        : T extends Int16Array\n          ? ReturnType<typeof Int16Array.of>\n          : T extends Int32Array\n            ? ReturnType<typeof Int32Array.of>\n            : T extends Int8Array\n              ? ReturnType<typeof Int8Array.of>\n              : T extends Uint16Array\n                ? ReturnType<typeof Uint16Array.of>\n                : T extends Uint32Array\n                  ? ReturnType<typeof Uint32Array.of>\n                  : T extends Uint8ClampedArray\n                    ? ReturnType<typeof Uint8ClampedArray.of>\n                    : T extends Uint8Array\n                      ? ReturnType<typeof Uint8Array.of>\n                      : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n  | T\n  | ([TypedArg<T>] extends [never]\n      ? T extends (...args: infer A) => infer R\n        ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n            [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n          }\n        : T extends [infer A, ...infer R]\n          ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n          : T extends readonly [infer A, ...infer R]\n            ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n            : T extends (infer A)[]\n              ? TArg<A>[]\n              : T extends readonly (infer A)[]\n                ? readonly TArg<A>[]\n                : T extends Promise<infer A>\n                  ? Promise<TArg<A>>\n                  : T extends object\n                    ? { [K in keyof T]: TArg<T[K]> }\n                    : T\n      : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n  ? T &\n      ([TypedRet<T>] extends [never]\n        ? T extends (...args: infer A) => infer R\n          ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n              [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n            }\n          : T extends [infer A, ...infer R]\n            ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n            : T extends readonly [infer A, ...infer R]\n              ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n              : T extends (infer A)[]\n                ? TRet<A>[]\n                : T extends readonly (infer A)[]\n                  ? readonly TRet<A>[]\n                  : T extends Promise<infer A>\n                    ? Promise<TRet<A>>\n                    : T extends object\n                      ? { [K in keyof T]: TRet<T[K]> }\n                      : T\n        : TypedRet<T>)\n  : never;\n\n// Freeze the result of a thunk. `/* @__PURE__ */ freeze(() => expr)` keeps the whole\n// initializer tree-shakable: the annotated call's only argument is a function literal,\n// so bundlers drop everything (inner chain()/alphabet() calls included) when unused.\nconst freeze = <T>(fn: () => T): Readonly<T> => Object.freeze(fn());\n\nfunction isBytes(a: unknown): a is Uint8Array {\n  // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n  // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n  // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n  // fallback on byte-oriented views.\n  return (\n    a instanceof Uint8Array ||\n    (ArrayBuffer.isView(a) &&\n      a.constructor.name === 'Uint8Array' &&\n      'BYTES_PER_ELEMENT' in a &&\n      a.BYTES_PER_ELEMENT === 1)\n  );\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: TArg<Uint8Array | undefined>): void {\n  if (!isBytes(b)) throw new TypeError('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n  if (!Array.isArray(arr)) return false;\n  if (arr.length === 0) return true;\n  if (isString) {\n    return arr.every((item) => typeof item === 'string');\n  } else {\n    return arr.every((item) => Number.isSafeInteger(item));\n  }\n}\n\nfunction afn(input: Function): input is Function {\n  if (typeof input !== 'function') throw new TypeError('function expected');\n  return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n  if (typeof input !== 'string') throw new TypeError(`${label}: string expected`);\n  return true;\n}\n\nfunction anumber(n: number, title = 'number'): void {\n  if (typeof n !== 'number') throw new TypeError(`${title}: expected number, got ${typeof n}`);\n  if (!Number.isSafeInteger(n)) throw new RangeError(`${title}: expected safe integer, got ${n}`);\n}\n\nfunction anumArr(label: string, input: number[]) {\n  if (!isArrayOf(false, input)) throw new TypeError(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like <string, number>, <number, bytes>, <bytes, float>\ntype Chain = [Coder<any, any>, ...Coder<any, any>[]];\n// Extract info from Coder type\ntype Input<F> = F extends Coder<infer T, any> ? T : never;\ntype Output<F> = F extends Coder<any, infer T> ? T : never;\n// Generic function for arrays\ntype First<T> = T extends [infer U, ...any[]] ? U : never;\ntype Last<T> = T extends [...any[], infer U] ? U : never;\ntype Tail<T> = T extends [any, ...infer U] ? U : never;\n\ntype AsChain<C extends Chain, Rest = Tail<C>> = {\n  // C[K] = Coder<Input<C[K]>, Input<Rest[k]>>\n  [K in keyof C]: Coder<Input<C[K]>, Input<K extends keyof Rest ? Rest[K] : any>>;\n};\n\nfunction chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>, Output<Last<T>>> {\n  const id = (a: any) => a;\n  // Wrap call in closure so JIT can inline calls\n  const wrap = (a: any, b: any) => (c: any) => a(b(c));\n  // Construct chain of args[-1].encode(args[-2].encode([...]))\n  const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n  // Construct chain of args[0].decode(args[1].decode(...))\n  const decode = args.map((x) => x.decode).reduce(wrap, id);\n  return { encode, decode };\n}\n\nfunction normalize<T>(fn: (val: T) => T): Coder<T, T> {\n  afn(fn);\n  return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\nconst powers: number[] = /* @__PURE__ */ (() => {\n  let res = [];\n  for (let i = 0; i < 40; i++) res.push(2 ** i);\n  return res;\n})();\n// Indexed copy loops instead of Array.from / Uint8Array.from: those go through the\n// iterator protocol on typed arrays, which is ~10x slower and would swamp the fast\n// links' gains on the conversion boundaries.\nfunction u8ToNumArr(u8: TArg<Uint8Array>, len: number = u8.length): number[] {\n  const res = new Array<number>(len);\n  for (let i = 0; i < len; i++) res[i] = u8[i]!;\n  return res;\n}\n// Fast-path links\n// ---------------\n// Used by every built-in codec. Links exchange Uint8Array buffers of digit values /\n// char codes instead of number[] / string[] of single-char strings, avoiding per-symbol\n// heap allocations. Only usable for single-char ASCII alphabets of <= 128 symbols\n// (Int8Array reverse-table limit) with bits in (0..8]. The generic \"Slow\" originals\n// (multi-char alphabets, digits above 255, bits up to 32) were removed from the library;\n// they live on in test/slow.ts as the differential-testing reference.\n// Validation must stay in sync with the Slow versions: same canonical-padding\n// strictness on decode, same rejection of unknown letters.\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n// UTF-8 TextDecoder builds a string from ASCII codes 2x faster than `TextDecoder('latin1')`\n// (4x on freshly allocated, our exact case).\n// All codes here are < 128 (range is validated elsewhere): UTF-8 agrees with ASCII byte-for-byte.\n// UTF-8 needs no ICU, so the probe only guards runtimes without TextDecoder at all (Hermes).\nconst asciiDecoder: { decode: (codes: Uint8Array) => string } | undefined = /* @__PURE__ */ (() => {\n  try {\n    const decoder = new TextDecoder();\n    // Self-check on the domain we use (codes < 128): reject broken polyfills at\n    // probe time instead of producing corrupted codec output later.\n    return decoder.decode(Uint8Array.of(0x41, 0x30, 0x2b, 0x7f)) === 'A0+\\x7f'\n      ? decoder\n      : undefined;\n  } catch (e) {\n    return undefined;\n  }\n})();\n\nconst B2S_CHUNK = 8192; // char codes per String.fromCharCode call, avoids arg-count limits\nfunction charcodesToString(codes: TArg<Uint8Array>): string {\n  const len = codes.length;\n  // Measured crossover: the TextDecoder's per-call setup dominates below ~12 chars,\n  // where String.fromCharCode wins (bech32 checksums, base58xmr blocks).\n  if (asciiDecoder !== undefined && len >= 12) return asciiDecoder.decode(codes);\n  if (len <= B2S_CHUNK) return String.fromCharCode.apply(null, codes as unknown as number[]);\n  let res = '';\n  for (let i = 0; i < len; i += B2S_CHUNK)\n    res += String.fromCharCode.apply(null, codes.subarray(i, i + B2S_CHUNK) as unknown as number[]);\n  return res;\n}\n\n/**\n * Linear 8 <-> bits regrouping (radix2Slow semantics), with Uint8Array digits and\n * preallocated output.\n */\nfunction radix2(bits: number): TRet<Coder<Uint8Array, Uint8Array>> {\n  anumber(bits);\n  if (bits <= 0 || bits > 8) throw new RangeError('radix2: bits should be in (0..8]');\n  const mask = powers[bits]! - 1;\n  return {\n    encode: (bytes: TArg<Uint8Array>) => {\n      abytes(bytes);\n      const len = bytes.length;\n      // 8->bits with zero-bit padding of the last digit, like convertRadix2(padding=true)\n      const res = new Uint8Array(Math.ceil((len * 8) / bits));\n      let carry = 0;\n      let pos = 0;\n      let j = 0;\n      for (let i = 0; i < len; ) {\n        // At most 7 residual bits plus 24 new bits fit in the signed 32-bit carry.\n        if (i + 2 < len) {\n          carry = (carry << 24) | (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!;\n          pos += 24;\n          i += 3;\n        } else {\n          // Constant mask instead of convertRadix2's exact powers[pos]-1 cleanup: with\n          // bits <= 8 the residual is pos <= 7 bits, so carry needs at most pos + 8 <= 15\n          // meaningful bits. Stale bits in [pos, 16) shift to >= bits on extraction and\n          // are removed by `& mask` there and in the tail below.\n          carry = ((carry << 8) | bytes[i]!) & 0xffff;\n          pos += 8;\n          i++;\n        }\n        // Each input adds at least `bits`, so the first extraction is unconditional.\n        for (;;) {\n          pos -= bits;\n          res[j++] = (carry >> pos) & mask;\n          if (pos < bits) break;\n        }\n      }\n      if (pos > 0) res[j] = (carry << (bits - pos)) & mask;\n      return res as TRet<Uint8Array>;\n    },\n    decode: (digits: TArg<Uint8Array>) => {\n      // bits->8, strict canonical form, like convertRadix2(padding=false):\n      // rejects leftover whole input words and non-zero pad bits.\n      const len = digits.length;\n      const res = new Uint8Array(Math.floor((len * bits) / 8));\n      let carry = 0;\n      let pos = 0;\n      let j = 0;\n      for (let i = 0; i < len; i++) {\n        // Same constant-mask carry bound as encode: pos <= 7 residual plus bits <= 8\n        // incoming keeps meaningful carry within 15 bits; stale bits above pos are\n        // masked out on extraction and in the tail check below.\n        carry = ((carry << bits) | digits[i]!) & 0xffff;\n        pos += bits;\n        for (; pos >= 8; pos -= 8) res[j++] = (carry >> (pos - 8)) & 0xff;\n      }\n      carry = (carry << (8 - pos)) & 0xff;\n      if (pos >= bits) throw new Error('Excess padding');\n      if (carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n      return res as TRet<Uint8Array>;\n    },\n  };\n}\n\n/**\n * Digit <-> letter mapping fused with string join (chain(alphabetSlow(letters), join(''))\n * semantics), via char-code lookup tables.\n */\nfunction alphabet(\n  letters: string,\n  aliases?: Record<string, string>\n): TRet<Coder<Uint8Array, string>> {\n  const len = letters.length;\n  // Larger indexes would wrap in the Int8Array reverse table and decode to wrong digits.\n  if (len > 128) throw new Error('alphabet: max 128 letters');\n  const encTable = new Uint8Array(len);\n  const decTable = new Int8Array(128).fill(-1);\n  for (let i = 0; i < len; i++) {\n    const code = letters.charCodeAt(i);\n    if (letters.codePointAt(i) !== code || code > 127)\n      throw new Error('alphabet: single-char ASCII letters only');\n    encTable[i] = code;\n    decTable[code] = i;\n  }\n  // Aliases decode like their canonical letter (e.g. hex case-folding), without a\n  // separate normalization pass over the input string.\n  if (aliases !== undefined) {\n    for (const alias of Object.keys(aliases)) {\n      const code = alias.charCodeAt(0);\n      const target = decTable[aliases[alias]!.charCodeAt(0)];\n      if (alias.length !== 1 || code > 127 || target === undefined || target === -1)\n        throw new Error(`alphabet: invalid alias ${alias}`);\n      decTable[code] = target;\n    }\n  }\n  return {\n    encode: (digits: TArg<Uint8Array>): string => {\n      const codes = new Uint8Array(digits.length);\n      for (let i = 0; i < digits.length; i++) {\n        const d = digits[i]!;\n        const code = encTable[d];\n        // Reuse the table lookup's bounds result for the required per-digit range check.\n        // Chained radix2 always emits digits < 2**bits === len; check anyway so a\n        // mismatched chain throws (like alphabetSlow) instead of silently emitting letter 0.\n        if (code === undefined) throw new Error(`alphabet.encode: invalid digit ${d}`);\n        codes[i] = code;\n      }\n      return charcodesToString(codes);\n    },\n    decode: (input: string): TRet<Uint8Array> => {\n      // Uniform label: this is the decode entry link for nopad codecs, padding for padded\n      // ones. Keeps \"decode: string expected\" identical across all built-in codecs\n      // (released 2.x said \"join.decode: string expected\").\n      astr('decode', input);\n      const slen = input.length;\n      const digits = new Uint8Array(slen);\n      for (let i = 0; i < slen; i++) {\n        const code = input.charCodeAt(i);\n        const digit = code < 128 ? decTable[code]! : -1;\n        if (digit === -1) throw new Error(`Unknown letter \"${input[i]}\". Allowed: ${letters}`);\n        digits[i] = digit;\n      }\n      return digits as TRet<Uint8Array>;\n    },\n  };\n}\n\n/**\n * Pad / unpad (paddingSlow semantics), on the joined string.\n */\nfunction padding(bits: number, chr = '='): Coder<string, string> {\n  anumber(bits);\n  astr('padding', chr);\n  return {\n    encode(data: string): string {\n      while ((data.length * bits) % 8) data += chr;\n      return data;\n    },\n    decode(input: string): string {\n      // Uniform label, see alphabet.decode above.\n      astr('decode', input);\n      let end = input.length;\n      if ((end * bits) % 8) throw new Error('padding: invalid length');\n      for (; end > 0 && input[end - 1] === chr; end--) {\n        const byte = (end - 1) * bits;\n        if (byte % 8 === 0) throw new Error('padding: excess padding');\n      }\n      return input.slice(0, end);\n    },\n  };\n}\n\ntype ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;\ntype BytesFn = (data: TArg<Uint8Array>) => TRet<Uint8Array>;\nfunction unsafeWrapper<T extends (...args: any) => any>(fn: T) {\n  afn(fn);\n  return function (...args: ArgumentTypes<T>): ReturnType<T> | void {\n    // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n    // Do not wrap code that needs to preserve exception details.\n    try {\n      return fn.apply(null, args);\n    } catch (e) {}\n  };\n}\n\nfunction checksum(len: number, fn: TArg<BytesFn>): TRet<Coder<Uint8Array, Uint8Array>> {\n  anumber(len);\n  // Reject degenerate zero-byte checksums up front so callers don't accidentally\n  // build a no-op checksum stage.\n  if (len <= 0) throw new RangeError(`checksum length must be positive: ${len}`);\n  afn(fn);\n  const _fn = fn as BytesFn;\n  // Uses the first `len` bytes of fn(data) in both directions.\n  // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n  return {\n    encode(data: TArg<Uint8Array>) {\n      abytes(data);\n      const sum = _fn(data).slice(0, len);\n      const res = new Uint8Array(data.length + len);\n      res.set(data);\n      res.set(sum, data.length);\n      return res;\n    },\n    decode(data: TArg<Uint8Array>) {\n      abytes(data);\n      const payload = data.slice(0, -len);\n      const oldChecksum = data.slice(-len);\n      const newChecksum = _fn(payload).slice(0, len);\n      for (let i = 0; i < len; i++)\n        if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n      return payload;\n    },\n  };\n}\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 §8 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(4), alphabet('0123456789ABCDEF'))\n);\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'))\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'))\n);\nconst BASE32_CROCKFORD_ASCII = /^[\\x00-\\x7f]*$/;\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(\n    radix2(5),\n    alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n    normalize((s: string) => {\n      astr('base32crockford.decode', s);\n      const upper = s.toUpperCase();\n      if (s !== upper && !BASE32_CROCKFORD_ASCII.test(s))\n        throw new Error('base32crockford.decode: ASCII expected');\n      return upper.replace(/O/g, '0').replace(/[IL]/g, '1');\n    })\n  )\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n  typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n  typeof (Uint8Array as any).fromBase64 === 'function')();\n\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 §3.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n  astr('base64', s);\n  const alphabet = isUrl ? 'base64url' : 'base64';\n  // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n  // And checking just for whitespace makes decoding about 3x faster than a full range check.\n  // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n  if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error('invalid base64');\n  return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/** base64 from RFC 4648. Padded. Pure JS version */\nconst base64Fallback: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(\n    radix2(6),\n    alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n    padding(6)\n  )\n);\n\n/** base64url from RFC 4648. Padded. Pure JS version */\nconst base64urlFallback: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(\n    radix2(6),\n    alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n    padding(6)\n  )\n);\n\n/**\n * base64 from RFC 4648. Padded.\n * Alternative variants: `base64nopad`, `base64url`, `base64urlnopad`.\n * Utilizes native `Uint8Array.fromBase64` builtin, otherwise falls back to `base64fallback` when it's unavailable.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64(); },\n  decode(s) { return decodeBase64Builtin(s, false); },\n} : base64Fallback);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'))\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n  encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n  decode(s) { return decodeBase64Builtin(s, true); },\n} : base64urlFallback);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'))\n);\n\n// baseN radix code (base58, base36)\n// ---------------------------------\n// Base conversion 256 <-> BASE done on 16-bit limbs, five baseN digits (one divmod by\n// BASE**5) per pass, ~10x fewer inner-loop iterations than digit-at-a-time conversion.\n// Exactness: every intermediate is a non-negative integer below 2**53, so float64\n// arithmetic (including Math.floor of the quotients) is exact for any GROUP = BASE**5 < 2**30:\n// - encode: carry * 2**16 + limb < BASE**5 * 2**16 < 2**46\n// - decode: limb * BASE**5 + carry < 2**16 * BASE**5 + 2**30 < 2**46\n// Still O(n^2) overall like any positional-base conversion — see the base58 DoS note.\n// GROUP literals (not `BASE ** 5`) so bundlers can drop unused coders as dead code.\nconst B58_GROUP = 656356768; // 58**5 < 2**30\nconst B36_GROUP = 60466176; // 36**5 < 2**26\nconst RADIX_BASE_N_MAX_LENGTH = 65536;\nconst BASE_N_MAX_BYTES = 2048;\nconst BASE_N_MAX_CHARS = 4096;\n\nconst radixBaseN = (BASE: number, GROUP: number): TRet<Coder<Uint8Array, Uint8Array>> => ({\n  encode: (bytes: TArg<Uint8Array>) => {\n    abytes(bytes);\n    const blen = bytes.length;\n    if (blen === 0) return new Uint8Array(0) as TRet<Uint8Array>;\n    if (blen >= RADIX_BASE_N_MAX_LENGTH) throw new Error('invalid length');\n    // Leading zero bytes map 1:1 to leading zero digits (at most blen-1 explicit zeros;\n    // an all-zero value still contributes one digit below).\n    let zeros = 0;\n    while (zeros < blen - 1 && bytes[zeros] === 0) zeros++;\n    // Pack big-endian 16-bit limbs; odd length makes the top limb a single byte.\n    const nlimbs = Math.ceil(blen / 2);\n    const limbs = new Uint16Array(nlimbs);\n    const odd = blen & 1;\n    if (odd) limbs[0] = bytes[0]!;\n    for (let i = odd, j = odd; i < blen; i += 2, j++) limbs[j] = (bytes[i]! << 8) | bytes[i + 1]!;\n    // Repeated divmod by BASE**5; each pass emits one 5-digit group, least significant\n    // first. No carry-overflow guard like convertRadix had: that one faced arbitrary\n    // caller-chosen bases, while these bounds are static and proven exact above.\n    const groups: number[] = [];\n    let pos = 0; // limbs before pos are known zero\n    while (pos < nlimbs) {\n      let carry = 0;\n      for (let i = pos; i < nlimbs; i++) {\n        const cur = carry * 0x10000 + limbs[i]!;\n        const q = Math.floor(cur / GROUP);\n        carry = cur - q * GROUP;\n        limbs[i] = q;\n        if (q === 0 && i === pos) pos++;\n      }\n      groups.push(carry);\n    }\n    // The top group is nonzero unless the whole value is zero, so total significant\n    // digit count is 5 per full group plus the top group's own width. (Writing 5 digits\n    // per group and trimming via subarray is smaller code, but the offset view slows\n    // encode ~25% and base58xmr 2x — measured.)\n    const top = groups.length - 1;\n    let sig = top * 5;\n    for (let v = groups[top]!; ; v = Math.floor(v / BASE)) {\n      sig++;\n      if (v < BASE) break;\n    }\n    const res = new Uint8Array(zeros + sig); // leading zero digits are already 0\n    let j = res.length - 1;\n    for (let g = 0; g < top; g++) {\n      let v = groups[g]!;\n      for (let k = 0; k < 5; k++) {\n        res[j--] = v % BASE;\n        v = Math.floor(v / BASE);\n      }\n    }\n    for (let v = groups[top]!; j >= zeros; v = Math.floor(v / BASE)) res[j--] = v % BASE;\n    return res as TRet<Uint8Array>;\n  },\n  decode: (digits: TArg<Uint8Array>) => {\n    abytes(digits);\n    const dlen = digits.length;\n    if (dlen === 0) return new Uint8Array(0) as TRet<Uint8Array>;\n    if (dlen >= RADIX_BASE_N_MAX_LENGTH) throw new Error('invalid length');\n    let zeros = 0;\n    while (zeros < dlen - 1 && digits[zeros] === 0) zeros++;\n    // Multiply-accumulate 16-bit limbs (little-endian, `used` live) group by group,\n    // most significant group first; the first group may be shorter than 5 digits, and\n    // its BASE**group factor falls out of the digit fold.\n    const limbs = new Uint16Array(Math.ceil((dlen * 6) / 16) + 1);\n    let used = 0;\n    let i = 0;\n    let group = dlen % 5 || 5;\n    while (i < dlen) {\n      let gval = 0;\n      let factor = 1;\n      for (const end = i + group; i < end; i++) {\n        const d = digits[i]!;\n        // Unreachable through the public chain (alphabet emits digits < BASE); guards\n        // internal misuse from silently corrupting output.\n        if (d >= BASE) throw new Error(`invalid integer: ${d}`);\n        gval = gval * BASE + d;\n        factor *= BASE;\n      }\n      group = 5;\n      let carry = gval;\n      for (let k = 0; k < used; k++) {\n        const cur = limbs[k]! * factor + carry;\n        carry = Math.floor(cur / 0x10000);\n        limbs[k] = cur - carry * 0x10000;\n      }\n      for (; carry > 0; carry = Math.floor(carry / 0x10000)) limbs[used++] = carry % 0x10000;\n    }\n    // used === 0 means the value is zero: it still contributes one byte, like a lone\n    // zero digit does.\n    const valueBytes = used === 0 ? 1 : used * 2 - (limbs[used - 1]! < 256 ? 1 : 0);\n    const res = new Uint8Array(zeros + valueBytes); // leading zero bytes are already 0\n    let j = res.length - 1;\n    for (let k = 0; k < used; k++) {\n      const limb = limbs[k]!;\n      res[j--] = limb & 0xff;\n      if (j >= zeros) res[j--] = limb >> 8;\n    }\n    return res as TRet<Uint8Array>;\n  },\n});\n\nconst genBaseN = (radix: TRet<Coder<Uint8Array, Uint8Array>>, abc: string): TRet<BytesCoder> => {\n  const letters = alphabet(abc);\n  return {\n    encode(bytes: TArg<Uint8Array>): string {\n      abytes(bytes);\n      if (bytes.length > BASE_N_MAX_BYTES) throw new Error('invalid length');\n      return letters.encode(radix.encode(bytes));\n    },\n    decode(str: string): TRet<Uint8Array> {\n      astr('baseN.decode', str);\n      if (str.length > BASE_N_MAX_CHARS) throw new Error('invalid length');\n      return radix.decode(letters.decode(str)) as TRet<Uint8Array>;\n    },\n  } as TRet<BytesCoder>;\n};\n\nconst radix58: TRet<Coder<Uint8Array, Uint8Array>> = /* @__PURE__ */ radixBaseN(58, B58_GROUP);\n\n/**\n * base36: lowercase alphanumeric, big-endian positional (multibase `k` payload,\n * used by e.g. IPNS/CID addresses). Leading zero bytes map to leading `0` digits.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base36.encode(Uint8Array.from([0, 1, 2]));\n * base36.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base36: BytesCoder = /* @__PURE__ */ freeze(() =>\n  genBaseN(radixBaseN(36, B36_GROUP), '0123456789abcdefghijklmnopqrstuvwxyz')\n);\n\nconst genBase58 = (abc: string) => genBaseN(radix58, abc);\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58: BytesCoder = /* @__PURE__ */ freeze(() =>\n  genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')\n);\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr: BytesCoder = /* @__PURE__ */ freeze(() =>\n  genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ')\n);\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp: BytesCoder = /* @__PURE__ */ freeze(() =>\n  genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz')\n);\n\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr: BytesCoder = /* @__PURE__ */ freeze(() => ({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    let res = '';\n    for (let i = 0; i < data.length; i += 8) {\n      const block = data.subarray(i, i + 8);\n      res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n    }\n    return res;\n  },\n  decode(str: string) {\n    astr('base58xmr.decode', str);\n    const strLen = str.length;\n    // Only the last block may be short, and only to one of the XMR_BLOCK_LEN widths —\n    // so the output length is known up front and blocks write into place. Growing a\n    // number[] via concat per block was quadratic; this keeps decode linear like the\n    // block encoding always intended.\n    const tailChars = strLen % 11;\n    const tailBytes = tailChars === 0 ? 0 : XMR_BLOCK_LEN.indexOf(tailChars);\n    if (tailBytes === -1) throw new Error(`base58xmr: invalid block length ${tailChars}`);\n    const res = new Uint8Array(Math.floor(strLen / 11) * 8 + tailBytes);\n    let w = 0;\n    for (let i = 0; i < strLen; i += 11) {\n      const slice = str.slice(i, i + 11);\n      const blockLen = slice.length === 11 ? 8 : tailBytes;\n      const block = base58.decode(slice);\n      for (let j = 0; j < block.length - blockLen; j++) {\n        if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n      }\n      for (let j = block.length - blockLen; j < block.length; j++) res[w++] = block[j]!;\n    }\n    return res;\n  },\n}));\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256: TArg<BytesFn>): BytesCoder => {\n  // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n  afn(sha256);\n  const _sha256 = sha256 as BytesFn;\n  return chain(\n    checksum(4, (data: TArg<Uint8Array>) => _sha256(_sha256(data))),\n    base58\n  );\n};\n\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check: (sha256: TArg<BytesFn>) => BytesCoder = createBase58check;\n\n// Bech32 code\n// -----------\n/** Result of bech32 decoding. */\nexport interface Bech32Decoded<Prefix extends string = string> {\n  /** Human-readable bech32 prefix. */\n  prefix: Prefix;\n  /** Decoded 5-bit word payload. */\n  words: number[];\n}\n/** Result of bech32 decoding with original bytes attached. */\nexport interface Bech32DecodedWithArray<Prefix extends string = string> {\n  /** Human-readable bech32 prefix. */\n  prefix: Prefix;\n  /** Decoded 5-bit word payload. */\n  words: number[];\n  /** Decoded payload converted back into raw bytes. */\n  bytes: Uint8Array;\n}\n\n// BIP 173 character table.\n// Callers adapt the public number[] words API to Uint8Array at the edges (wordsToU8 below):\n// feeding number[] into alphabet.encode would work at runtime, but it turns the shared\n// hot loop polymorphic and measurably slows the RFC 4648 codecs using the same literal.\nconst BECH_ALPHABET: Coder<Uint8Array, string> = /* @__PURE__ */ alphabet(\n  'qpzry9x8gf2tvdw0s3jn54khce6mua7l'\n);\nconst BECH_UPPERCASE_PRINTABLE = /^[\\x21-\\x60\\x7b-\\x7e]+$/;\n\nfunction assertBech32Printable(label: string, value: string): void {\n  for (let i = 0; i < value.length; i++) {\n    const c = value.charCodeAt(i);\n    if (c < 33 || c > 126) throw new Error(`${label}: printable ASCII expected`);\n  }\n}\n\n// Range-checks while packing: a plain copy would silently wrap out-of-range words\n// (256 -> 0 would encode to a valid letter). Same message the old slow alphabet threw.\nfunction wordsToU8(words: number[]): Uint8Array {\n  const len = words.length;\n  const res = new Uint8Array(len);\n  for (let i = 0; i < len; i++) {\n    const w = words[i]!;\n    if (w < 0 || w >= 32) throw new Error(`alphabet.encode: invalid digit ${w}`);\n    res[i] = w;\n  }\n  return res;\n}\n\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre: number): number {\n  const b = pre >> 25;\n  let chk = (pre & 0x1ffffff) << 5;\n  for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n    if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n  }\n  return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n  const len = prefix.length;\n  let chk = 1;\n  for (let i = 0; i < len; i++) {\n    const c = prefix.charCodeAt(i);\n    if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n    chk = bech32Polymod(chk) ^ (c >> 5);\n  }\n  chk = bech32Polymod(chk);\n  for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n  for (let v of words) chk = bech32Polymod(chk) ^ v;\n  for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n  // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n  chk ^= encodingConst;\n  const sum = new Uint8Array(6);\n  for (let i = 0; i < 6; i++) sum[i] = (chk >>> (5 * (5 - i))) & 31;\n  return BECH_ALPHABET.encode(sum);\n}\n\n/** bech32 codec surface. */\nexport interface Bech32 {\n  /**\n   * Encodes a human-readable prefix and 5-bit words into a bech32 string.\n   * @param prefix - Human-readable prefix.\n   * @param words - 5-bit words or raw bytes.\n   * @param limit - Maximum accepted output length, or `false` to disable the limit.\n   * @returns Encoded bech32 string.\n   */\n  encode<Prefix extends string>(\n    prefix: Prefix,\n    words: number[] | Uint8Array,\n    limit?: number | false\n  ): `${Lowercase<Prefix>}1${string}`;\n  /**\n   * Decodes a bech32 string into prefix and words.\n   * @param str - Encoded bech32 string.\n   * @param limit - Maximum accepted input length, or `false` to disable the limit.\n   * @returns Decoded prefix and 5-bit words.\n   */\n  decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  decode(str: string, limit?: number | false): Bech32Decoded;\n  /**\n   * Encodes raw bytes by first converting them to 5-bit words.\n   * @param prefix - Human-readable prefix.\n   * @param bytes - Raw bytes to encode.\n   * @returns Encoded bech32 string.\n   */\n  encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n  /**\n   * Decodes a bech32 string and converts the payload back into bytes.\n   * @param str - Encoded bech32 string.\n   * @param limit - Maximum accepted input length, or `false` to disable the limit.\n   * @returns Decoded prefix, words, and bytes.\n   */\n  decodeToBytes(str: string, limit?: number | false): Bech32DecodedWithArray;\n  /**\n   * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input.\n   * @param str - Encoded bech32 string.\n   * @param limit - Maximum accepted input length, or `false` to disable the limit.\n   * @returns Decoded prefix and words, or `undefined` for invalid input.\n   */\n  decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;\n  /**\n   * Converts 5-bit words back into raw bytes.\n   * @param to - 5-bit words to decode.\n   * @returns Decoded bytes.\n   */\n  fromWords(to: number[]): Uint8Array;\n  /**\n   * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing.\n   * @param to - 5-bit words to decode.\n   * @returns Decoded bytes, or `undefined` for invalid input.\n   */\n  fromWordsUnsafe(to: number[]): void | Uint8Array;\n  /**\n   * Converts raw bytes into 5-bit words for bech32 encoding.\n   * @param from - Raw bytes to convert.\n   * @returns 5-bit words.\n   */\n  toWords(from: Uint8Array): number[];\n}\nfunction genBech32(encoding: 'bech32' | 'bech32m'): TRet<Bech32> {\n  // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n  const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n  // Public API words are number[], so adapt the fast radix2's Uint8Array protocol at the edge.\n  const _words = radix2(5);\n  const toWords = (from: TArg<Uint8Array>): number[] => {\n    abytes(from);\n    // Dedicated 8->5 regrouping (radix2(5).encode semantics) writing the public number[]\n    // directly; encode-into-Uint8Array plus a copy loop measurably regressed this hot path.\n    const len = from.length;\n    const res = new Array<number>(Math.ceil((len * 8) / 5));\n    let carry = 0;\n    let pos = 0;\n    let j = 0;\n    for (let i = 0; i < len; i++) {\n      // No carry cleanup needed: stale bits sit above pos and every extraction (including\n      // the tail below) masks with `& 31`, so they never reach the output. Masking carry\n      // here measurably slowed the loop.\n      carry = (carry << 8) | from[i]!;\n      pos += 8;\n      for (; pos >= 5; pos -= 5) res[j++] = (carry >> (pos - 5)) & 31;\n    }\n    if (pos > 0) res[j] = (carry << (5 - pos)) & 31;\n    return res;\n  };\n  const fromWords = (to: number[]): TRet<Uint8Array> => {\n    anumArr('radix2.decode', to);\n    // Range-check while packing into the byte buffer: a plain copy would silently\n    // truncate out-of-range words. Rejecting negatives is a deliberate fix — the old\n    // convertRadix2 path silently corrupted output for them.\n    const len = to.length;\n    const digits = new Uint8Array(len);\n    for (let i = 0; i < len; i++) {\n      const w = to[i]!;\n      if (w < 0 || w >= 32) throw new Error(`convertRadix2: invalid word=${w}`);\n      digits[i] = w;\n    }\n    return _words.decode(digits) as TRet<Uint8Array>;\n  };\n  const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n  function encode<Prefix extends string>(\n    prefix: Prefix,\n    words: TArg<number[] | Uint8Array>,\n    limit: number | false = 90\n  ): `${Lowercase<Prefix>}1${string}` {\n    astr('bech32.encode prefix', prefix);\n    if (limit !== false) anumber(limit, 'limit');\n    if (isBytes(words)) words = u8ToNumArr(words);\n    anumArr('bech32.encode', words);\n    const plen = prefix.length;\n    if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n    // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n    const actualLength = plen + 7 + words.length;\n    if (limit !== false && actualLength > limit)\n      throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n    assertBech32Printable('bech32.encode prefix', prefix);\n    const lowered = prefix.toLowerCase();\n    const sum = bechChecksum(lowered, words, ENCODING_CONST);\n    return `${lowered}1${BECH_ALPHABET.encode(wordsToU8(words))}${sum}` as `${Lowercase<Prefix>}1${string}`;\n  }\n\n  function decode<Prefix extends string>(\n    str: `${Prefix}1${string}`,\n    limit?: number | false\n  ): Bech32Decoded<Prefix>;\n  function decode(str: string, limit?: number | false): Bech32Decoded;\n  function decode(str: string, limit: number | false = 90): Bech32Decoded {\n    astr('bech32.decode input', str);\n    if (limit !== false) anumber(limit, 'limit');\n    const slen = str.length;\n    // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n    if (slen < 8 || (limit !== false && slen > limit))\n      throw new TypeError(`invalid string length ${slen}, expected (8..${limit})`);\n    // don't allow mixed case\n    const lowered = str.toLowerCase();\n    if (str !== lowered) {\n      // Case folding is the only way a non-ASCII input can become valid: unchanged\n      // characters are rejected by the prefix and alphabet checks below.\n      if (!BECH_UPPERCASE_PRINTABLE.test(str)) {\n        assertBech32Printable('bech32.decode input', str);\n        throw new Error(`mixed-case string not allowed`);\n      }\n    }\n    const sepIndex = lowered.lastIndexOf('1');\n    if (sepIndex === 0 || sepIndex === -1) throw new Error(`invalid separator \"1\"`);\n    const prefix = lowered.slice(0, sepIndex);\n    const data = lowered.slice(sepIndex + 1);\n    if (data.length < 6) throw new Error('invalid data length');\n    const digits = BECH_ALPHABET.decode(data);\n    const words = u8ToNumArr(digits, digits.length - 6);\n    const sum = bechChecksum(prefix, words, ENCODING_CONST);\n    if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}`);\n    return { prefix, words };\n  }\n\n  const decodeUnsafe = unsafeWrapper(decode);\n\n  function decodeToBytes(str: string, limit: number | false = 90): TRet<Bech32DecodedWithArray> {\n    const { prefix, words } = decode(str, limit);\n    return {\n      prefix,\n      words,\n      bytes: fromWords(words) as TRet<Uint8Array>,\n    } as TRet<Bech32DecodedWithArray>;\n  }\n\n  function encodeFromBytes(prefix: string, bytes: TArg<Uint8Array>) {\n    // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n    return encode(prefix, toWords(bytes));\n  }\n\n  return {\n    encode,\n    decode,\n    encodeFromBytes,\n    decodeToBytes,\n    decodeUnsafe,\n    fromWords,\n    fromWordsUnsafe,\n    toWords,\n  };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32: TRet<Bech32> = /* @__PURE__ */ freeze(() => genBech32('bech32'));\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m: TRet<Bech32> = /* @__PURE__ */ freeze(() => genBech32('bech32m'));\n\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii: TRet<BytesCoder> = /* @__PURE__ */ freeze(() => ({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    for (let i = 0; i < data.length; i++) {\n      const byte = data[i]!;\n      // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n      // Latin-1/UTF-8. Validating up front keeps the error position exact while the\n      // string itself is built in bulk (~3x faster at 1KB than per-char concat).\n      if (byte > 127) throw new RangeError(`non-ASCII byte ${byte} at ${i}`);\n    }\n    return charcodesToString(data);\n  },\n  decode(str: string) {\n    if (typeof str !== 'string') throw new TypeError('ascii string expected, got ' + typeof str);\n    const res = new Uint8Array(str.length);\n    for (let i = 0; i < str.length; i++) {\n      // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n      // exact error positions.\n      const charCode = str.charCodeAt(i);\n      if (charCode > 127) throw new RangeError(`non-ASCII char \"${str[i]}\" (${charCode}) at ${i}`);\n      res[i] = charCode;\n    }\n    return res;\n  },\n}));\n\nconst _isWellFormedShim = (str: string): boolean => {\n  // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n  // isWellFormed on our tests/fuzz corpus.\n  try {\n    return encodeURI(str) !== null;\n  } catch {\n    return false;\n  }\n};\nconst _isWellFormed: (str: string) => boolean = /* @__PURE__ */ (() =>\n  // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\n  typeof ('' as any).isWellFormed === 'function'\n    ? (str) => (str as any).isWellFormed()\n    : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8err = (i: number) => new TypeError(`invalid utf8 at byte ${i}`);\nconst utf8Fallback: BytesCoder = /* @__PURE__ */ freeze(() => ({\n  encode(data: TArg<Uint8Array>) {\n    abytes(data);\n    let res = '';\n    for (let i = 0; i < data.length; ) {\n      const a = data[i++]!;\n      if (a < 0b1000_0000) {\n        res += String.fromCharCode(a);\n        continue;\n      }\n      if (a < 0b1100_0010 || i >= data.length) throw utf8err(i - 1);\n      const b = data[i++]!;\n      if ((b & 0b1100_0000) !== 0b1000_0000) throw utf8err(i - 1);\n      let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n      if (a >= 0b1110_0000) {\n        if (i >= data.length) throw utf8err(i - 1);\n        const c = data[i++]!;\n        if (\n          (c & 0b1100_0000) !== 0b1000_0000 ||\n          (a === 0b1110_0000 && b < 0b1010_0000) ||\n          (a === 0xed && b >= 0b1010_0000)\n        )\n          throw utf8err(i - 1);\n        cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n        if (a >= 0b1111_0000) {\n          if (i >= data.length) throw utf8err(i - 1);\n          const d = data[i++]!;\n          if (\n            a > 0b1111_0100 ||\n            (d & 0b1100_0000) !== 0b1000_0000 ||\n            (a === 0b1111_0000 && b < 0b1001_0000) ||\n            (a === 0b1111_0100 && b >= 0b1001_0000)\n          )\n            throw utf8err(i - 1);\n          cp =\n            ((a & 7) << 18) |\n            ((b & 0b0011_1111) << 12) |\n            ((c & 0b0011_1111) << 6) |\n            (d & 0b0011_1111);\n        }\n      }\n      if (cp < 0x10000) res += String.fromCharCode(cp);\n      else {\n        cp -= 0x10000;\n        res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n      }\n    }\n    return res;\n  },\n  decode(str: string) {\n    astr('utf8', str);\n    if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n    // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n    // large Node inputs.\n    const res = new Uint8Array(str.length * 3);\n    let pos = 0;\n    for (let i = 0; i < str.length; i++) {\n      let c = str.charCodeAt(i);\n      if (c < 0b1000_0000) {\n        res[pos++] = c;\n        continue;\n      }\n      if (c >= 0xd800 && c <= 0xdfff) {\n        const d = str.charCodeAt(++i);\n        c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n      }\n      if (c >= 0x10000) {\n        res[pos++] = (c >> 18) | 0b1111_0000;\n        res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n      } else if (c >= 0x800) res[pos++] = (c >> 12) | 0b1110_0000;\n      else res[pos++] = (c >> 6) | 0b1100_0000;\n      if (c >= 0x800) res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n      res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n    }\n    return res.subarray(0, pos);\n  },\n}));\n\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n *   throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n *   lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = /* @__PURE__ */ freeze(() => {\n  let _utf8Encoder: any;\n  let _utf8Decoder: any;\n  const utf8Builtin: BytesCoder = {\n    // ignoreBOM preserves an explicit leading U+FEFF;\n    // fatal rejects invalid UTF-8 bytes instead of replacing them.\n    encode(data) {\n      abytes(data);\n      return (\n        _utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))\n      ).decode(data);\n    },\n    decode(str) {\n      astr('utf8', str);\n      if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n      return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n    },\n  };\n  return {\n    // Select each direction once at module init, since\n    // TextEncoder and TextDecoder can exist independently.\n    encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n    decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n  };\n});\n\n/** Lowercase hex with case-insensitive decoding. Pure JS version. */\nconst hexFallback: BytesCoder = /* @__PURE__ */ freeze(() =>\n  chain(\n    radix2(4),\n    // Case-insensitive decode via table aliases instead of a toLowerCase pass.\n    alphabet('0123456789abcdef', { A: 'a', B: 'b', C: 'c', D: 'd', E: 'e', F: 'f' }),\n    normalize((s: string) => {\n      // astr first: same non-string message as the native path, and no `s.length`\n      // access on null / undefined while building the error.\n      astr('hex', s);\n      if (s.length % 2 !== 0) throw new TypeError(`hex.decode: odd-length string (${s.length})`);\n      return s;\n    })\n  )\n);\n\n// Keep internal parity probes behind a test-only export.\nexport const __TESTS: {\n  alphabet: typeof alphabet;\n  base64Fallback: BytesCoder;\n  base64urlFallback: BytesCoder;\n  hexFallback: BytesCoder;\n  radix2: typeof radix2;\n  radix58: typeof radix58;\n  checksum: typeof checksum;\n  utf8Fallback: BytesCoder;\n  _isWellFormedShim: (str: string) => boolean;\n} = /* @__PURE__ */ freeze(() => ({\n  alphabet: alphabet,\n  base64Fallback: base64Fallback,\n  base64urlFallback: base64urlFallback,\n  hexFallback: hexFallback,\n  radix2: radix2,\n  radix58: radix58,\n  checksum: checksum,\n  utf8Fallback: utf8Fallback,\n  _isWellFormedShim: _isWellFormedShim,\n}));\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n  // Require both directions before enabling the native hex path so encode/decode stay symmetric.\n  typeof (Uint8Array as any).from([]).toHex === 'function' &&\n  typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n  // Keep local type guards so the native path preserves library-level input errors.\n  // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n  encode(data) { abytes(data); return (data as any).toHex(); },\n  // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n  decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = /* @__PURE__ */ freeze(() =>\n  hasHexBuiltin ? hexBuiltin : hexFallback\n);\n","import { hex as baseHex, utf8 } from '@scure/base';\n/**\n * Define complex binary structures using composable primitives.\n * Main ideas:\n * - Encode / decode can be chained, same as in `scure-base`\n * - A complex structure can be created from an array and struct of primitive types\n * - Strings / bytes are arrays with specific optimizations: we can just read bytes directly\n *   without creating plain array first and reading each byte separately.\n * - Types are inferred from definition\n * @module\n * @example\n * Define a struct with numbers, strings, bytes, and nested arrays.\n * ```ts\n * import * as P from 'micro-packed';\n * const s = P.struct({\n *   field1: P.U32BE, // 32-bit unsigned big-endian integer\n *   field2: P.string(P.U8), // String with U8 length prefix\n *   field3: P.bytes(32), // 32 bytes\n *   field4: P.array(P.U16BE, P.struct({ // Array of structs with U16BE length\n *     subField1: P.U64BE, // 64-bit unsigned big-endian integer\n *     subField2: P.string(10) // 10-byte string\n *   }))\n * });\n * ```\n */\n// TODO: remove dependency on scure-base & inline?\n/*\nExports can be groupped like this:\n\n- Primitive types: P.bytes, P.string, P.hex, P.constant, P.pointer\n- Complex types: P.array, P.struct, P.tuple, P.map, P.tag, P.mappedTag\n- Padding, prefix, magic: P.padLeft, P.padRight, P.prefix, P.magic, P.magicBytes\n- Flags: P.flag, P.flagged, P.optional\n- Wrappers: P.apply, P.wrap, P.lazy\n- Bit fiddling: P.bits, P.bitset\n- utils: P.validate, coders.decimal\n- Debugger\n*/\n/**\n * Shortcut to zero-length (empty) byte array.\n * Keep public Bytes typing, not TRet<Bytes>, so variables inferred from this\n * constant can later accept caller-owned Bytes backed by any ArrayBufferLike.\n */\nexport const EMPTY = /* @__PURE__ */ Uint8Array.of();\n/**\n * Shortcut to one-element (element is 0) byte array.\n * Keep the same public Bytes typing rationale as EMPTY.\n */\nexport const NULL = /* @__PURE__ */ Uint8Array.of(0);\n/** Prototype-sensitive names cannot roundtrip as normal fields on plain decoded objects. */\nconst restrictedKeys = /* @__PURE__ */ new Set(['__proto__', 'constructor', 'prototype']);\nconst validateFieldName = (name, label) => {\n    if (typeof name !== 'string')\n        throw new Error(`${label} should be string, got ${typeof name}`);\n    if (name.includes('..'))\n        throw new TypeError(`${label} ${name} cannot contain path parent ..`);\n    if (name.includes('/'))\n        throw new TypeError(`${label} ${name} cannot contain path separator /`);\n    if (restrictedKeys.has(name))\n        throw new Error(`${label} ${name} is reserved`);\n};\n/** Checks if two Uint8Arrays are equal. Not constant-time. */\nfunction equalBytes(a, b) {\n    if (a.length !== b.length)\n        return false;\n    for (let i = 0; i < a.length; i++)\n        if (a[i] !== b[i])\n            return false;\n    return true;\n}\nfunction createFindBytes(needle) {\n    if (needle.length === 1) {\n        const byte = needle[0];\n        return (data, pos = 0) => {\n            const idx = data.indexOf(byte, pos);\n            return idx === -1 ? undefined : idx;\n        };\n    }\n    // KMP avoids quadratic scans on repeated-prefix terminators.\n    const back = new Uint32Array(needle.length);\n    for (let i = 1, j = 0; i < needle.length; i++) {\n        while (j && needle[i] !== needle[j])\n            j = back[j - 1];\n        if (needle[i] === needle[j])\n            back[i] = ++j;\n    }\n    return (data, pos = 0) => {\n        for (let i = pos, j = 0; i < data.length; i++) {\n            while (j && data[i] !== needle[j])\n                j = back[j - 1];\n            if (data[i] !== needle[j])\n                continue;\n            if (++j === needle.length)\n                return i - needle.length + 1;\n        }\n        return undefined;\n    };\n}\nconst findBytes = (needle, data, pos = 0) => createFindBytes(needle)(data, pos);\n/** Compares values used as encoded-domain constants; byte arrays compare by contents. */\nfunction equal(a, b) {\n    const aBytes = isBytes(a);\n    const bBytes = isBytes(b);\n    if (aBytes || bBytes)\n        return aBytes && bBytes && equalBytes(a, b);\n    return a === b;\n}\n/** Checks if the given value is a Uint8Array. */\nfunction isBytes(a) {\n    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n    // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n    // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps\n    // the fallback on byte-oriented views.\n    return (a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) &&\n            a.constructor.name === 'Uint8Array' &&\n            'BYTES_PER_ELEMENT' in a &&\n            a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Concatenates multiple Uint8Arrays.\n * Engines limit functions to 65K+ arguments.\n * @param arrays Array of Uint8Array elements\n * @returns Concatenated Uint8Array\n */\nfunction concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        if (!isBytes(a))\n            throw new Error('Uint8Array expected');\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n/**\n * Creates DataView from Uint8Array\n * @param arr - bytes\n * @returns DataView\n */\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _8n = /* @__PURE__ */ BigInt(8);\nconst _10n = /* @__PURE__ */ BigInt(10);\nconst _255n = /* @__PURE__ */ BigInt(255);\n/**\n * Checks if the provided value is object-like for option/schema bags.\n * This intentionally matches noble-curves and noble-hashes by using the\n * `[object Object]` tag instead of rejecting class/proxy/env objects by prototype;\n * stricter checks caused compatibility reports in proxied environments.\n * Array, Uint8Array and others are not plain objects.\n * @param obj - The value to be checked.\n */\nfunction isPlainObject(obj) {\n    return Object.prototype.toString.call(obj) === '[object Object]';\n}\nfunction isNum(num) {\n    return Number.isSafeInteger(num);\n}\nconst hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);\n/**\n * Miscellaneous helpers reused by the coder internals and tests.\n * @example\n * Reuse a couple of byte helpers without pulling in the full namespace.\n * ```ts\n * import { utils } from 'micro-packed';\n * const left = Uint8Array.of(1);\n * const right = Uint8Array.of(2);\n * utils.equalBytes(utils.concatBytes(left, right), Uint8Array.of(1, 2));\n * ```\n */\nexport const utils = /* @__PURE__ */ Object.freeze({\n    equalBytes,\n    isBytes,\n    isCoder,\n    checkBounds,\n    concatBytes,\n    createView,\n    isPlainObject,\n});\n// NOTE: we can't have terminator separate function, since it won't know about boundaries\n// E.g. array of U16LE ([1,2,3]) would be [1, 0, 2, 0, 3, 0]\n// But terminator will find array at index '1', which happens to be inside of an element itself\n/**\n * Can be:\n * - Dynamic (CoderType)\n * - Fixed (number)\n * - Terminated (usually zero): Uint8Array with terminator\n * - Field path to field with length (string)\n * - Infinity (null) - decodes until end of buffer\n * Used in:\n * - bytes (string, prefix is implementation of bytes)\n * - array\n */\nconst lengthCoder = (len) => {\n    if (len !== null && typeof len !== 'string' && !isCoder(len) && !isBytes(len) && !isNum(len)) {\n        // Constructor argument validation uses TypeError.\n        // Stream/data failures keep contextual Error paths.\n        throw new TypeError(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${len} (${typeof len})`);\n    }\n    if (typeof len === 'number' && len < 0)\n        throw new Error(`lengthCoder: wrong length=${len}`);\n    if (isBytes(len) && !len.length)\n        throw new Error('lengthCoder: empty terminator');\n    return {\n        encodeStream(w, value) {\n            if (len === null)\n                return;\n            if (isCoder(len))\n                return len.encodeStream(w, value);\n            let byteLen;\n            if (typeof len === 'number')\n                byteLen = len;\n            else if (typeof len === 'string')\n                byteLen = Path.resolve(w.stack, len);\n            if (typeof byteLen === 'bigint')\n                byteLen = Number(byteLen);\n            if (!isNum(byteLen) || byteLen < 0 || byteLen !== value)\n                throw w.err(`Wrong length: ${byteLen} len=${len} exp=${value} (${typeof value})`);\n        },\n        decodeStream(r) {\n            let byteLen;\n            if (isCoder(len))\n                byteLen = len.decodeStream(r);\n            else if (typeof len === 'number')\n                byteLen = len;\n            else if (typeof len === 'string')\n                byteLen = Path.resolve(r.stack, len);\n            if (typeof byteLen === 'bigint')\n                byteLen = Number(byteLen);\n            else if (typeof byteLen !== 'number')\n                throw r.err(`Wrong length: ${byteLen}`);\n            if (!isNum(byteLen) || byteLen < 0)\n                throw r.err(`Wrong length: ${byteLen}`);\n            return byteLen;\n        },\n    };\n};\n/**\n * Small bitset structure to store position of ranges that have been read.\n * Can be more efficient when internal trees are utilized at the cost of complexity.\n * Needs `O(N/8)` memory for parsing.\n * Purpose: if there are pointers in parsed structure,\n * they can cause read of two distinct ranges:\n * [0-32, 64-128], which means 'pos' is not enough to handle them\n */\nconst Bitset = /* @__PURE__ */ Object.freeze({\n    BITS: 32,\n    FULL_MASK: -1 >>> 0, // 1<<32 will overflow\n    len: (len) => {\n        if (!isNum(len) || len < 0)\n            throw new Error(`wrong len=${len}`);\n        return Math.ceil(len / 32);\n    },\n    create: (len) => new Uint32Array(Bitset.len(len)),\n    clean: (bs) => bs.fill(0),\n    debug: (bs) => Array.from(bs).map((i) => (i >>> 0).toString(2).padStart(32, '0')),\n    checkLen: (bs, len) => {\n        if (Bitset.len(len) === bs.length)\n            return;\n        throw new Error(`wrong length=${bs.length}. Expected: ${Bitset.len(len)}`);\n    },\n    chunkLen: (bsLen, pos, len) => {\n        if (!isNum(bsLen) || bsLen < 0)\n            throw new Error(`wrong bsLen=${bsLen}`);\n        if (!isNum(pos) || pos < 0)\n            throw new Error(`wrong pos=${pos}`);\n        if (!isNum(len) || len < 0)\n            throw new Error(`wrong len=${len}`);\n        if (pos > bsLen - len)\n            throw new Error(`wrong range=${pos}/${len} of ${bsLen}`);\n    },\n    set: (bs, chunk, value, allowRewrite = true) => {\n        if (!isNum(chunk) || chunk < 0 || chunk >= bs.length)\n            return false;\n        if (!allowRewrite && (bs[chunk] & value) !== 0)\n            return false;\n        bs[chunk] |= value;\n        return true;\n    },\n    pos: (pos, i) => ({\n        chunk: Math.floor((pos + i) / 32),\n        mask: 1 << (32 - ((pos + i) % 32) - 1),\n    }),\n    indices: (bs, len, invert = false) => {\n        Bitset.checkLen(bs, len);\n        const { FULL_MASK, BITS } = Bitset;\n        const left = BITS - (len % BITS);\n        const lastMask = left ? (FULL_MASK >>> left) << left : FULL_MASK;\n        const res = [];\n        for (let i = 0; i < bs.length; i++) {\n            let c = bs[i];\n            if (invert)\n                c = ~c; // allows to gen unset elements\n            // apply mask to last element, so we won't iterate non-existent items\n            if (i === bs.length - 1)\n                c &= lastMask;\n            if (c === 0)\n                continue; // fast-path\n            for (let j = 0; j < BITS; j++) {\n                const m = 1 << (BITS - j - 1);\n                if (c & m)\n                    res.push(i * BITS + j);\n            }\n        }\n        return res;\n    },\n    range: (arr) => {\n        // Bitset.indices() returns sorted unique positions; this helper only merges adjacent runs.\n        const res = [];\n        let cur;\n        for (const i of arr) {\n            if (cur === undefined || i !== cur.pos + cur.length)\n                res.push((cur = { pos: i, length: 1 }));\n            else\n                cur.length += 1;\n        }\n        return res;\n    },\n    rangeDebug: (bs, len, invert = false) => `[${Bitset.range(Bitset.indices(bs, len, invert))\n        .map((i) => `(${i.pos}/${i.length})`)\n        .join(', ')}]`,\n    setRange: (bs, bsLen, pos, len, allowRewrite = true) => {\n        Bitset.chunkLen(bsLen, pos, len);\n        // Empty ranges are valid reader-bookkeeping no-ops; mask math below assumes at least one bit.\n        if (len === 0)\n            return true;\n        const { FULL_MASK, BITS } = Bitset;\n        // Try to set range with maximum efficiency:\n        // - first chunk is always    '0000[1111]' (only right ones)\n        // - middle chunks are set to '[1111 1111]' (all ones)\n        // - last chunk is always     '[1111]0000' (only left ones)\n        // - max operations:          (N/32) + 2 (first and last)\n        const first = pos % BITS ? Math.floor(pos / BITS) : undefined;\n        const lastPos = pos + len;\n        const last = lastPos % BITS ? Math.floor(lastPos / BITS) : undefined;\n        const canSet = (chunk, value) => chunk >= 0 && chunk < bs.length && (bs[chunk] & value) === 0;\n        if (!allowRewrite) {\n            // Check the whole range before writing so a late overlap cannot leave earlier chunks mutated.\n            if (first !== undefined && first === last) {\n                if (!canSet(first, (FULL_MASK >>> (BITS - len)) << (BITS - len - pos)))\n                    return false;\n            }\n            else {\n                if (first !== undefined && !canSet(first, FULL_MASK >>> pos % BITS))\n                    return false;\n                const start = first !== undefined ? first + 1 : pos / BITS;\n                const end = last !== undefined ? last : lastPos / BITS;\n                for (let i = start; i < end; i++)\n                    if (!canSet(i, FULL_MASK))\n                        return false;\n                if (last !== undefined && first !== last)\n                    if (!canSet(last, FULL_MASK << (BITS - (lastPos % BITS))))\n                        return false;\n            }\n        }\n        // special case, whole range inside single chunk\n        if (first !== undefined && first === last)\n            return Bitset.set(bs, first, (FULL_MASK >>> (BITS - len)) << (BITS - len - pos), allowRewrite);\n        if (first !== undefined) {\n            // first chunk\n            if (!Bitset.set(bs, first, FULL_MASK >>> pos % BITS, allowRewrite))\n                return false;\n        }\n        // middle chunks\n        const start = first !== undefined ? first + 1 : pos / BITS;\n        const end = last !== undefined ? last : lastPos / BITS;\n        for (let i = start; i < end; i++)\n            if (!Bitset.set(bs, i, FULL_MASK, allowRewrite))\n                return false;\n        if (last !== undefined && first !== last)\n            if (!Bitset.set(bs, last, FULL_MASK << (BITS - (lastPos % BITS)), allowRewrite))\n                // last chunk\n                return false;\n        return true;\n    },\n});\nconst Path = /* @__PURE__ */ Object.freeze({\n    /**\n     * Internal method for handling stack of paths (debug, errors, dynamic fields via path)\n     * `.pop()` always happens after the wrapped function.\n     * Fields inside the object are tracked via Reader/Writer enterField()/exitField(),\n     * which the debugger overrides to observe per-field byte ranges.\n     * NOTE: we don't want to do '.pop' on error!\n     */\n    pushObj: (stack, obj, objFn) => {\n        stack.push({ obj });\n        objFn();\n        stack.pop();\n    },\n    path: (stack) => {\n        const res = [];\n        for (const i of stack)\n            if (i.field !== undefined)\n                res.push(i.field === '' ? '\"\"' : `${i.field}`);\n        // Path.err() uses this string for user-visible context. Empty keys need explicit rendering so\n        // field(\"\") is distinguishable from the root path; slash-containing keys are still raw.\n        return res.join('/');\n    },\n    err: (name, stack, msg) => {\n        const text = `${name}(${Path.path(stack)}): ${typeof msg === 'string' ? msg : msg.message}`;\n        // Path context is the primary diagnostic. Do not attach `cause`: Node inspection expands nested\n        // cause stacks and makes the original, path-prefixed failure harder to scan.\n        // Keep specific validation classes after adding the path prefix. Otherwise public coder\n        // APIs flatten inner TypeError / RangeError guards back to plain Error.\n        const err = msg instanceof TypeError\n            ? new TypeError(text)\n            : msg instanceof RangeError\n                ? new RangeError(text)\n                : new Error(text);\n        if (msg instanceof Error && msg.stack) {\n            const from = `${msg.name}: ${msg.message}`;\n            const to = `${err.name}: ${err.message}`;\n            err.stack = msg.stack.startsWith(from) ? `${to}${msg.stack.slice(from.length)}` : msg.stack;\n        }\n        return err;\n    },\n    resolve: (stack, path) => {\n        const parts = path.split('/');\n        // Leading '..' segments mean parent traversal and '/' separates nested fields, so literal\n        // keys using those tokens are not addressable through this helper.\n        const objPath = stack.map((i) => i.obj);\n        let i = 0;\n        for (; i < parts.length; i++) {\n            if (parts[i] === '..')\n                objPath.pop();\n            else\n                break;\n        }\n        let cur = objPath.pop();\n        for (; i < parts.length; i++) {\n            if (!cur || cur[parts[i]] === undefined)\n                return undefined;\n            cur = cur[parts[i]];\n        }\n        return cur;\n    },\n});\n/**\n * Internal structure. Reader class for reading from a byte array.\n * `stack` is internal: for debugger and logging\n * @class Reader\n */\nclass _Reader {\n    pos = 0;\n    data;\n    opts;\n    stack;\n    parent;\n    parentOffset;\n    bitBuf = 0;\n    bitPos = 0;\n    bs; // bitset\n    view;\n    constructor(data, opts = {}, stack = [], parent = undefined, parentOffset = 0) {\n        if (!isBytes(data))\n            throw new TypeError(`Reader: expected Uint8Array, got ${typeof data}`);\n        if (!isPlainObject(opts))\n            throw new TypeError(`ReaderOpts: expected plain object, got ${opts}`);\n        if (opts.allowUnreadBytes !== undefined && typeof opts.allowUnreadBytes !== 'boolean')\n            throw new TypeError(`ReaderOpts.allowUnreadBytes: expected boolean, got ${typeof opts.allowUnreadBytes}`);\n        if (opts.allowMultipleReads !== undefined && typeof opts.allowMultipleReads !== 'boolean')\n            throw new TypeError(`ReaderOpts.allowMultipleReads: expected boolean, got ${typeof opts.allowMultipleReads}`);\n        this.data = data;\n        this.opts = opts;\n        this.stack = stack;\n        this.parent = parent;\n        this.parentOffset = parentOffset;\n        this.view = createView(data);\n    }\n    /** Internal method for pointers. */\n    _enablePointers() {\n        // Pointer decoding enables tracking before the pointed child reader starts consuming bytes, so\n        // only the root reader owns the bitset and seeds it from the already-consumed prefix.\n        if (this.parent)\n            return this.parent._enablePointers();\n        if (this.bs)\n            return;\n        this.bs = Bitset.create(this.data.length);\n        Bitset.setRange(this.bs, this.data.length, 0, this.pos, this.opts.allowMultipleReads);\n    }\n    markBytesBS(pos, len) {\n        if (this.parent)\n            return this.parent.markBytesBS(this.parentOffset + pos, len);\n        if (!len)\n            return true;\n        // Before pointers are enabled there is no bitset yet, so linear cursor checks remain the only\n        // guard; overlap tracking starts only after _enablePointers() allocates the root bitset.\n        if (!this.bs)\n            return true;\n        return Bitset.setRange(this.bs, this.data.length, pos, len, false);\n    }\n    markBytes(len) {\n        const pos = this.pos;\n        const res = this.markBytesBS(pos, len);\n        // Keep failed overlap reads at their start so diagnostics point at the repeated span.\n        if (!this.opts.allowMultipleReads && !res)\n            throw this.err(`multiple read pos=${pos} len=${len}`);\n        this.pos += len;\n        return res;\n    }\n    pushObj(obj, objFn) {\n        return Path.pushObj(this.stack, obj, objFn);\n    }\n    enterField(field) {\n        const last = this.stack[this.stack.length - 1];\n        // A field outside any pushObj() scope or nested inside another field is a coder bug.\n        if (last === undefined || last.field !== undefined)\n            throw this.err(`enterField: invalid stack state, field=${field}`);\n        last.field = field;\n    }\n    // Intentionally not called on throw, so Path.err() can report the failing leaf.\n    exitField() {\n        this.stack[this.stack.length - 1].field = undefined;\n    }\n    readView(n, fn) {\n        if (!isNum(n) || n < 0)\n            throw this.err(`readView: wrong length=${n}`);\n        if (this.pos + n > this.data.length)\n            throw this.err('readView: Unexpected end of buffer');\n        const res = fn(this.view, this.pos);\n        this.markBytes(n);\n        return res;\n    }\n    // read bytes by absolute offset\n    absBytes(n) {\n        if (!isNum(n) || n < 0 || n > this.data.length)\n            throw new Error('Unexpected end of buffer');\n        return this.data.subarray(n);\n    }\n    finish() {\n        // ReaderOpts documents allowUnreadBytes as \"Allow decoding to finish with unread trailing\n        // bytes.\" Prefix decoders may intentionally parse only a value from a larger byte array, so\n        // this skips all final unread-input checks, including residual bits and pointer-read gaps.\n        if (this.opts.allowUnreadBytes)\n            return;\n        if (this.bitPos) {\n            throw this.err(`${this.bitPos} bits left after unpack: ${baseHex.encode(this.data.subarray(this.pos))}`);\n        }\n        if (this.bs && !this.parent) {\n            const notRead = Bitset.indices(this.bs, this.data.length, true);\n            if (notRead.length) {\n                const formatted = Bitset.range(notRead)\n                    .map(({ pos, length }) => `(${pos}/${length})[${baseHex.encode(this.data.subarray(pos, pos + length))}]`)\n                    .join(', ');\n                throw this.err(`unread byte ranges: ${formatted} (total=${this.data.length})`);\n            }\n            else\n                return; // all bytes read, everything is ok\n        }\n        // Default: no pointers enabled\n        if (!this.isEnd()) {\n            throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${baseHex.encode(this.data.subarray(this.pos))}`);\n        }\n    }\n    // User methods\n    err(msg) {\n        return Path.err('Reader', this.stack, msg);\n    }\n    offsetReader(n) {\n        if (!isNum(n) || n < 0 || n > this.data.length)\n            throw this.err('offsetReader: Unexpected end of buffer');\n        return new _Reader(this.absBytes(n), this.opts, this.stack, this, n);\n    }\n    bytes(n, peek = false) {\n        if (this.bitPos)\n            throw this.err('readBytes: bitPos not empty');\n        if (!isNum(n) || n < 0)\n            throw this.err(`readBytes: wrong length=${n}`);\n        if (this.pos + n > this.data.length)\n            throw this.err('readBytes: Unexpected end of buffer');\n        const slice = this.data.subarray(this.pos, this.pos + n);\n        if (!peek)\n            this.markBytes(n);\n        return slice;\n    }\n    byte(peek = false) {\n        if (this.bitPos)\n            throw this.err('readByte: bitPos not empty');\n        if (this.pos + 1 > this.data.length)\n            throw this.err('readByte: Unexpected end of buffer');\n        const data = this.data[this.pos];\n        if (!peek)\n            this.markBytes(1);\n        return data;\n    }\n    get leftBytes() {\n        return this.data.length - this.pos;\n    }\n    get totalBytes() {\n        return this.data.length;\n    }\n    isEnd() {\n        return this.pos >= this.data.length && !this.bitPos;\n    }\n    progress() {\n        return this.pos * 8 - this.bitPos;\n    }\n    // bits are read in BE mode (left to right): (0b1000_0000).readBits(1) == 1\n    bits(bits) {\n        // Reject before bitwise shifts: JS coerces negative/fractional shift counts into other widths.\n        if (!isNum(bits) || bits < 0)\n            throw this.err(`BitReader: wrong length=${bits}`);\n        if (bits > 32)\n            throw this.err('BitReader: cannot read more than 32 bits in single call');\n        let out = 0;\n        while (bits) {\n            if (!this.bitPos) {\n                this.bitBuf = this.byte();\n                this.bitPos = 8;\n            }\n            const take = Math.min(bits, this.bitPos);\n            this.bitPos -= take;\n            out = (out << take) | ((this.bitBuf >> this.bitPos) & (2 ** take - 1));\n            this.bitBuf &= 2 ** this.bitPos - 1;\n            bits -= take;\n        }\n        // Fix signed integers\n        return out >>> 0;\n    }\n    find(needle, pos = this.pos) {\n        if (!isBytes(needle))\n            throw this.err(`find: needle is not bytes! ${needle}`);\n        if (this.bitPos)\n            throw this.err('find: bitPos not empty');\n        if (!needle.length)\n            throw this.err(`find: needle is empty`);\n        if (!isNum(pos) || pos < 0)\n            throw this.err(`find: wrong pos=${pos}`);\n        return findBytes(needle, this.data, pos);\n    }\n}\nclass _Writer {\n    pos = 0;\n    stack;\n    // Small writes are carved out of writer-owned chunks; caller-provided bytes() buffers are kept\n    // by reference between them. A single realloc'd buffer was measured slower for tiny encodes\n    // (basic/encode bench: 395ns -> 560ns), copy-on-grow is what chunking avoids.\n    buffers = [];\n    // Every chunk ever allocated by this writer, so finish(clean) can zeroize them whole.\n    chunks = [];\n    chunk;\n    chunkView; // lazy: only writeView() needs it\n    chunkPos = 0;\n    run;\n    nextChunkSize = 0; // 0 = size the first chunk to the first write\n    ptrs = [];\n    bitBuf = 0;\n    bitPos = 0;\n    finished = false;\n    constructor(stack = []) {\n        this.stack = stack;\n    }\n    // Reserves `len` contiguous writer-owned bytes and returns their offset inside `this.chunk`.\n    carve(len) {\n        if (this.chunk === undefined || this.chunk.length - this.chunkPos < len) {\n            // Chunks grow geometrically to amortize allocations, capped to bound over-allocation and\n            // zeroization work. The 64-byte floor keeps small encodes in one chunk (one lazy DataView).\n            const size = Math.max(len, this.nextChunkSize, 64);\n            this.nextChunkSize = Math.min(size * 8, 4096);\n            this.chunk = new Uint8Array(size);\n            this.chunkView = undefined;\n            this.chunkPos = 0;\n            this.run = undefined;\n            this.chunks.push(this.chunk);\n        }\n        const pos = this.chunkPos;\n        if (this.run === undefined) {\n            this.run = { chunk: this.chunk, start: pos, end: pos + len };\n            this.buffers.push(this.run);\n        }\n        else\n            this.run.end += len;\n        this.chunkPos = pos + len;\n        this.pos += len;\n        return pos;\n    }\n    pushObj(obj, objFn) {\n        return Path.pushObj(this.stack, obj, objFn);\n    }\n    enterField(field) {\n        const last = this.stack[this.stack.length - 1];\n        // A field outside any pushObj() scope or nested inside another field is a coder bug.\n        if (last === undefined || last.field !== undefined)\n            throw this.err(`enterField: invalid stack state, field=${field}`);\n        last.field = field;\n    }\n    // Intentionally not called on throw, so Path.err() can report the failing leaf.\n    exitField() {\n        this.stack[this.stack.length - 1].field = undefined;\n    }\n    writeView(len, fn) {\n        if (this.finished)\n            throw this.err('buffer: finished');\n        if (!isNum(len) || len < 0 || len > 8)\n            throw new Error(`wrong writeView length=${len}`);\n        if (this.bitPos)\n            throw this.err('writeBytes: ends with non-empty bit buffer');\n        const pos = this.carve(len);\n        if (this.chunkView === undefined)\n            this.chunkView = createView(this.chunk);\n        fn(this.chunkView, pos);\n    }\n    // User methods\n    err(msg) {\n        // Finished-state guards call err('buffer: finished'), so err itself must not recurse there.\n        return Path.err('Writer', this.stack, msg);\n    }\n    bytes(b) {\n        if (this.finished)\n            throw this.err('buffer: finished');\n        if (this.bitPos)\n            throw this.err('writeBytes: ends with non-empty bit buffer');\n        if (!isBytes(b))\n            throw this.err(`writeBytes: expected Uint8Array, got ${typeof b}`);\n        // Keep caller-provided buffers by reference until finish(); mutating them afterwards changes\n        // the encoded output.\n        this.buffers.push(b);\n        // Later carved writes must not merge into a run that would be emitted before `b`.\n        this.run = undefined;\n        this.pos += b.length;\n    }\n    byte(b) {\n        if (this.finished)\n            throw this.err('buffer: finished');\n        if (this.bitPos)\n            throw this.err('writeByte: ends with non-empty bit buffer');\n        if (!isNum(b) || b < 0 || b > 255)\n            throw this.err(`writeByte: wrong value=${b}`);\n        // carve() first: it may allocate/replace this.chunk.\n        const pos = this.carve(1);\n        this.chunk[pos] = b;\n    }\n    finish(clean = true) {\n        if (this.finished)\n            throw this.err('buffer: finished');\n        if (this.bitPos)\n            throw this.err('buffer: ends with non-empty bit buffer');\n        // Can't use concatBytes, because it limits amount of arguments (65K).\n        const buffers = this.buffers;\n        let sum = 0;\n        for (let i = 0; i < buffers.length; i++) {\n            const b = buffers[i];\n            sum += isBytes(b) ? b.length : b.end - b.start;\n        }\n        for (let i = 0; i < this.ptrs.length; i++)\n            sum += this.ptrs[i].buffer.length;\n        const buf = new Uint8Array(sum);\n        let pad = 0;\n        for (let i = 0; i < buffers.length; i++) {\n            const b = buffers[i];\n            if (isBytes(b)) {\n                buf.set(b, pad);\n                pad += b.length;\n            }\n            else {\n                buf.set(b.chunk.subarray(b.start, b.end), pad);\n                pad += b.end - b.start;\n            }\n        }\n        for (let i = 0; i < this.ptrs.length; i++) {\n            buf.set(this.ptrs[i].buffer, pad);\n            pad += this.ptrs[i].buffer.length;\n        }\n        for (let pos = this.pos, i = 0; i < this.ptrs.length; i++) {\n            const ptr = this.ptrs[i];\n            buf.set(ptr.ptr.encode(pos), ptr.pos);\n            pos += ptr.buffer.length;\n        }\n        // Cleanup\n        if (clean) {\n            // bytes() keeps caller-provided buffers by reference, so only writer-owned chunks are\n            // zeroized — whole, including unused tails: same hygiene as per-buffer cleanup.\n            for (const c of this.chunks)\n                c.fill(0);\n            this.chunks = [];\n            this.chunk = undefined;\n            this.chunkView = undefined;\n            this.chunkPos = 0;\n            this.run = undefined;\n            this.buffers = [];\n            for (const p of this.ptrs)\n                p.buffer.fill(0);\n            this.ptrs = [];\n            this.finished = true;\n            this.bitBuf = 0;\n        }\n        return buf;\n    }\n    bits(value, bits) {\n        if (this.finished)\n            throw this.err('buffer: finished');\n        // Reject before bitwise shifts: JS coerces negative/fractional values and widths.\n        if (!isNum(bits) || bits < 0)\n            throw this.err(`writeBits: wrong length=${bits}`);\n        if (bits > 32)\n            throw this.err('writeBits: cannot write more than 32 bits in single call');\n        if (!isNum(value) || value < 0)\n            throw this.err(`writeBits: wrong value=${value}`);\n        if (value >= 2 ** bits)\n            throw this.err(`writeBits: value (${value}) >= 2**bits (${bits})`);\n        while (bits) {\n            const take = Math.min(bits, 8 - this.bitPos);\n            this.bitBuf = (this.bitBuf << take) | (value >> (bits - take));\n            this.bitPos += take;\n            bits -= take;\n            value &= 2 ** bits - 1;\n            if (this.bitPos === 8) {\n                this.bitPos = 0;\n                // carve() first: it may allocate/replace this.chunk. The Uint8Array store wraps mod 256,\n                // matching the previous `new Uint8Array([bitBuf])` semantics for int32-coerced values.\n                const pos = this.carve(1);\n                this.chunk[pos] = this.bitBuf;\n            }\n        }\n    }\n}\n// Immutable LE<->BE\nconst swapEndianness = (b) => Uint8Array.from(b).reverse();\nfunction checkMinimalBigintBytes(value, le, signed, err) {\n    if (!value.length)\n        return;\n    const b = le ? swapEndianness(value) : value;\n    const fail = () => {\n        throw err('bigint: non-minimal encoding');\n    };\n    if (!signed) {\n        if (b[0] === 0)\n            fail();\n        return;\n    }\n    // Encoders emit the shortest signed two's-complement byte string that preserves the sign bit.\n    if (b[0] === 0 && (b.length === 1 || (b[1] & 128) === 0))\n        fail();\n    if (b.length > 1 && b[0] === 255 && (b[1] & 128) !== 0)\n        fail();\n}\n/** Internal function for checking bit bounds of bigint in signed/unsinged form */\nfunction checkBounds(value, bits, signed) {\n    if (signed) {\n        if (bits <= _0n)\n            throw new Error(`checkBounds: signed bits must be positive, got ${bits}`);\n        // [-(2**(32-1)), 2**(32-1)-1]\n        const signBit = _2n ** (bits - _1n);\n        if (value < -signBit || value >= signBit)\n            throw new Error(`value out of signed bounds. Expected ${-signBit} <= ${value} < ${signBit}`);\n    }\n    else {\n        // [0, 2**32-1]\n        const max = _2n ** bits;\n        if (_0n > value || value >= max)\n            throw new Error(`value out of unsigned bounds. Expected 0 <= ${value} < ${max}`);\n    }\n}\nfunction _wrap(inner) {\n    const _inner = inner;\n    return {\n        // NOTE: we cannot export validate here, since it is likely mistake.\n        // Raw inner throws propagate unchanged; path-aware errors must use w.err/r.err or validate().\n        encodeStream: _inner.encodeStream,\n        decodeStream: _inner.decodeStream,\n        size: _inner.size,\n        encode: (value) => {\n            const w = new _Writer();\n            _inner.encodeStream(w, value);\n            return w.finish();\n        },\n        decode: (data, opts = {}) => {\n            if (!isBytes(data))\n                throw new TypeError(`decode: expected Uint8Array, got ${typeof data}`);\n            const r = new _Reader(data, opts);\n            const res = _inner.decodeStream(r);\n            r.finish();\n            return res;\n        },\n    };\n}\n/**\n * Validates a value before encoding and after decoding using a provided function.\n * @param inner - The inner CoderType.\n * @param fn - The validation function.\n * @returns CoderType which check value with validation function.\n * @throws On wrong inner coder or validator argument types. {@link TypeError}\n * @example\n * Reject values outside the accepted range during both encode and decode.\n * ```ts\n * import * as P from 'micro-packed';\n * const val = (n: number) => {\n *   if (n > 10) throw new Error(`${n} > 10`);\n *   return n;\n * };\n *\n * // Checks that values are <= 10 during encoding and decoding.\n * const RangedInt = P.validate(P.U32LE, val);\n * ```\n */\nexport function validate(inner, fn) {\n    if (!isCoder(inner))\n        throw new TypeError(`validate: invalid inner value ${inner}`);\n    if (typeof fn !== 'function')\n        throw new TypeError('validate: fn should be function');\n    return _wrap({\n        size: inner.size,\n        encodeStream: (w, value) => {\n            let res;\n            try {\n                res = fn(value);\n            }\n            catch (e) {\n                // Validator callbacks are caller code: if they throw non-Error garbage, diagnostics are on\n                // them. Review policy: \"if they throw garbage, then it is on them\".\n                throw w.err(e);\n            }\n            inner.encodeStream(w, res);\n        },\n        decodeStream: (r) => {\n            const res = inner.decodeStream(r);\n            try {\n                return fn(res);\n            }\n            catch (e) {\n                throw r.err(e);\n            }\n        },\n    });\n}\n/**\n * Wraps a stream encoder into a generic encoder and optionally validation function\n * @param inner - Stream coder with optional validation hook.\n * @returns The wrapped CoderType.\n * @throws On wrong wrapped stream-coder shapes. {@link TypeError}\n * @example\n * Start from stream methods, then add validation if needed.\n * ```ts\n * import * as P from 'micro-packed';\n * const U8 = P.wrap({\n *   encodeStream: (w, value) => w.byte(value),\n *   decodeStream: (r) => r.byte(),\n * });\n * const checkedU8 = P.wrap({\n *   encodeStream: (w, value) => w.byte(value),\n *   decodeStream: (r) => r.byte(),\n *   validate: (n: number) => {\n *    if (n > 10) throw new Error(`${n} > 10`);\n *    return n;\n *   }\n * });\n * ```\n */\n// Keep this as a plain contextual object type instead of TArg<>/TRet<> helpers:\n// recursive object mapping breaks unannotated encodeStream/decodeStream parameters,\n// and _wrap() already returns the CoderType<T> shape without byte-array normalization.\nexport const wrap = (inner) => {\n    const _inner = inner;\n    // Public wrap() is the boundary for raw stream coders; reject malformed shapes before a\n    // half-constructed coder fails later during encode/decode.\n    if (!isPlainObject(_inner))\n        throw new TypeError(`wrap: invalid inner value ${_inner}`);\n    if (typeof _inner.encodeStream !== 'function')\n        throw new TypeError('wrap: encodeStream should be function');\n    if (typeof _inner.decodeStream !== 'function')\n        throw new TypeError('wrap: decodeStream should be function');\n    if (_inner.size !== undefined && (!isNum(_inner.size) || _inner.size < 0))\n        throw new TypeError(`wrap: invalid size ${_inner.size}`);\n    if (_inner.validate !== undefined && typeof _inner.validate !== 'function')\n        throw new TypeError('wrap: validate should be function');\n    const res = _wrap(_inner);\n    return _inner.validate !== undefined ? validate(res, _inner.validate) : res;\n};\nconst isBaseCoder = (elm) => isPlainObject(elm) && typeof elm.decode === 'function' && typeof elm.encode === 'function';\n/**\n * Checks if the given value is a CoderType.\n * @param elm - The value to check.\n * @returns True if the value is a CoderType, false otherwise.\n * @example\n * Guard unknown values before calling encode/decode helpers on them.\n * ```ts\n * import { isCoder, U8 } from 'micro-packed';\n * isCoder(U8);\n * ```\n */\nexport function isCoder(elm) {\n    return (isPlainObject(elm) &&\n        isBaseCoder(elm) &&\n        typeof elm.encodeStream === 'function' &&\n        typeof elm.decodeStream === 'function' &&\n        (elm.size === undefined || (isNum(elm.size) && elm.size >= 0)));\n}\n// Coders (like in @scure/base) for common operations\n/**\n * Base coder for working with dictionaries (records, objects, key-value map)\n * Dictionary is dynamic type like: `[key: string, value: any][]`\n * @returns base coder that encodes/decodes between arrays of key-value tuples and dictionaries.\n * @example\n * Convert between tuple entries and a plain object record.\n * ```ts\n * import * as P from 'micro-packed';\n * const dict: P.CoderType<Record<string, number>> = P.apply(\n *  P.array(P.U16BE, P.tuple([P.cstring, P.U32LE] as const)),\n *  P.coders.dict()\n * );\n * ```\n */\nfunction dict() {\n    return {\n        encode: (from) => {\n            if (!Array.isArray(from))\n                throw new Error('array expected');\n            const to = {};\n            const seen = new Set();\n            for (const item of from) {\n                if (!Array.isArray(item) || item.length !== 2)\n                    throw new Error(`array of two elements expected`);\n                const name = item[0];\n                const value = item[1];\n                validateFieldName(name, 'dict: key');\n                // Stored undefined is still a present key, so duplicate detection cannot inspect values.\n                if (seen.has(name))\n                    throw new Error(`key(${name}) appears twice in struct`);\n                seen.add(name);\n                to[name] = value;\n            }\n            return to;\n        },\n        decode: (to) => {\n            if (!isPlainObject(to))\n                throw new Error(`expected plain object, got ${to}`);\n            for (const name in to)\n                validateFieldName(name, 'dict: key');\n            return Object.entries(to);\n        },\n    };\n}\n/**\n * Safely converts bigint to number.\n * Sometimes pointers / tags use u64 or other big numbers which cannot be represented by number,\n * but we still can use them since real value will be smaller than u32\n */\nconst numberBigint = /* @__PURE__ */ Object.freeze({\n    encode: (from) => {\n        if (typeof from !== 'bigint')\n            throw new Error(`expected bigint, got ${typeof from}`);\n        if (from > BigInt(Number.MAX_SAFE_INTEGER))\n            throw new Error(`element bigger than MAX_SAFE_INTEGER=${from}`);\n        // Number() silently rounds bigint values outside the safe integer range on either side.\n        if (from < BigInt(Number.MIN_SAFE_INTEGER))\n            throw new Error(`element smaller than MIN_SAFE_INTEGER=${from}`);\n        return Number(from);\n    },\n    decode: (to) => {\n        if (!isNum(to))\n            throw new Error('element is not a safe integer');\n        return BigInt(to);\n    },\n});\n/**\n * Base coder for working with TypeScript enums.\n * @param e - TypeScript enum.\n * @returns base coder that encodes/decodes between numbers and enum keys.\n * @example\n * Map enum numbers to their string keys and back.\n * ```ts\n * import * as P from 'micro-packed';\n * enum Color { Red, Green, Blue }\n * const colorCoder = P.coders.tsEnum(Color);\n * colorCoder.encode(Color.Red); // 'Red'\n * colorCoder.decode('Green'); // 1\n * ```\n */\nfunction tsEnum(e) {\n    if (!isPlainObject(e))\n        throw new Error('plain object expected');\n    return {\n        encode: (from) => {\n            if (!isNum(from) || !(from in e))\n                throw new Error(`wrong value ${from}`);\n            return e[from];\n        },\n        decode: (to) => {\n            if (typeof to !== 'string')\n                throw new Error(`wrong value ${typeof to}`);\n            const value = e[to];\n            // TypeScript numeric enums include reverse-map keys like \"0\"; decode accepts names only.\n            if (!hasOwn(e, to) || !isNum(value))\n                throw new Error(`wrong value ${to}`);\n            return value;\n        },\n    };\n}\n/**\n * Base coder for working with decimal numbers.\n * @param precision - Number of decimal places.\n * @param round - Round fraction part if bigger than precision (throws error by default)\n * @returns base coder that encodes/decodes between bigints and decimal strings.\n * @example\n * Convert bigint amounts into fixed-precision decimal strings.\n * ```ts\n * import * as P from 'micro-packed';\n * const decimal8 = P.coders.decimal(8);\n * decimal8.encode(630880845n); // '6.30880845'\n * decimal8.decode('6.30880845'); // 630880845n\n * ```\n */\nfunction decimal(precision, round = false) {\n    if (!isNum(precision) || precision < 0)\n        throw new Error(`decimal/precision: wrong value ${precision}`);\n    if (typeof round !== 'boolean')\n        throw new Error(`decimal/round: expected boolean, got ${typeof round}`);\n    const decimalMask = _10n ** BigInt(precision);\n    return {\n        encode: (from) => {\n            if (typeof from !== 'bigint')\n                throw new Error(`expected bigint, got ${typeof from}`);\n            let s = (from < _0n ? -from : from).toString(10);\n            let sep = s.length - precision;\n            if (sep < 0) {\n                s = s.padStart(s.length - sep, '0');\n                sep = 0;\n            }\n            let i = s.length - 1;\n            for (; i >= sep && s[i] === '0'; i--)\n                ;\n            let int = s.slice(0, sep);\n            let frac = s.slice(sep, i + 1);\n            if (!int)\n                int = '0';\n            if (from < _0n)\n                int = '-' + int;\n            if (!frac)\n                return int;\n            return `${int}.${frac}`;\n        },\n        decode: (to) => {\n            if (typeof to !== 'string')\n                throw new Error(`expected string, got ${typeof to}`);\n            let neg = false;\n            if (to.startsWith('-')) {\n                neg = true;\n                to = to.slice(1);\n            }\n            if (!/^(0|[1-9]\\d*)(\\.\\d+)?$/.test(to))\n                throw new Error(`wrong string value=${to}`);\n            let sep = to.indexOf('.');\n            sep = sep === -1 ? to.length : sep;\n            // Split by separator and strip trailing zeros from fraction.\n            // Always returns [string, string]; .split() doesn't.\n            const intS = to.slice(0, sep);\n            const fracS = to.slice(sep + 1).replace(/0+$/, '');\n            const int = BigInt(intS) * decimalMask;\n            if (!round && fracS.length > precision) {\n                throw new Error(`fractional part cannot be represented with this precision (num=${to}, prec=${precision})`);\n            }\n            const fracLen = Math.min(fracS.length, precision);\n            const frac = BigInt(fracS.slice(0, fracLen)) * _10n ** BigInt(precision - fracLen);\n            const value = int + frac;\n            // All negative zero spellings collapse to 0n, so reject after parsing.\n            if (neg && value === _0n)\n                throw new Error(`negative zero is not allowed`);\n            return neg ? -value : value;\n        },\n    };\n}\n/**\n * Combines multiple coders into a single coder, allowing conditional\n * encoding/decoding based on input.\n * Acts as a parser combinator, splitting complex conditional coders into smaller parts.\n *\n *   `encode = [Ae, Be]; decode = [Ad, Bd]`\n *   ->\n *   `match([{encode: Ae, decode: Ad}, {encode: Be; decode: Bd}])`\n *\n * @param lst - Array of coders to match.\n * @returns Combined coder for conditional encoding/decoding.\n */\nfunction match(lst) {\n    if (!Array.isArray(lst))\n        throw new Error(`expected array, got ${typeof lst}`);\n    for (const i of lst)\n        if (!isBaseCoder(i))\n            throw new Error(`wrong base coder ${i}`);\n    return {\n        encode: (from) => {\n            for (const c of lst) {\n                let elm;\n                try {\n                    elm = c.encode(from);\n                }\n                catch {\n                    // match() is a branch selector: coders may signal \"not this branch\" by throwing.\n                    continue;\n                }\n                if (elm !== undefined)\n                    return elm;\n            }\n            throw new Error(`match/encode: cannot find match in ${from}`);\n        },\n        decode: (to) => {\n            for (const c of lst) {\n                let elm;\n                try {\n                    elm = c.decode(to);\n                }\n                catch {\n                    // match() is a branch selector: coders may signal \"not this branch\" by throwing.\n                    continue;\n                }\n                if (elm !== undefined)\n                    return elm;\n            }\n            throw new Error(`match/decode: cannot find match in ${to}`);\n        },\n    };\n}\n/** Reverses direction of coder */\nconst reverse = (coder) => {\n    if (!isBaseCoder(coder))\n        throw new Error('BaseCoder expected');\n    // Call through the source coder so method-style encode/decode implementations keep their receiver.\n    return { encode: (to) => coder.decode(to), decode: (from) => coder.encode(from) };\n};\n/**\n * Collection of reusable base coders and helpers.\n * @example\n * Build a reusable decimal-string adapter.\n * ```ts\n * import { coders } from 'micro-packed';\n * const decimal2 = coders.decimal(2);\n * decimal2.encode(123n); // '1.23'\n * ```\n */\nexport const coders = /* @__PURE__ */ Object.freeze({ dict, numberBigint, tsEnum, decimal, match, reverse });\n/**\n * CoderType for parsing individual bits.\n * NOTE: Structure should parse whole amount of bytes before it can start parsing byte-level elements.\n * @param len - Number of bits to parse.\n * @returns CoderType representing the parsed bits.\n * @throws On invalid bit-length configuration or bit values. {@link Error}\n * @throws On wrong argument types forwarded into wrapped numeric validators. {@link TypeError}\n * @example\n * Pack several bit fields into a single byte.\n * ```ts\n * import * as P from 'micro-packed';\n * const s = P.struct({ magic: P.bits(1), version: P.bits(1), tag: P.bits(4), len: P.bits(2) });\n * ```\n */\nexport const bits = (len) => {\n    // Reader/Writer bit helpers operate on one 0..32-bit chunk; reject impossible coders up front.\n    if (!isNum(len) || len < 0 || len > 32)\n        throw new Error(`bits: wrong length ${len} (${typeof len})`);\n    return wrap({\n        encodeStream: (w, value) => w.bits(value, len),\n        decodeStream: (r) => r.bits(len),\n        validate: (value) => {\n            if (!isNum(value))\n                throw new Error(`bits: wrong value ${value}`);\n            return value;\n        },\n    });\n};\n/**\n * CoderType for working with bigint values.\n * Unsized bigint values should be wrapped in a container (e.g., bytes or string).\n *\n * `0n = Uint8Array.of()`\n *\n * `1n = new Uint8Array([1n])`\n *\n * Please open issue, if you need different behavior for zero.\n *\n * @param size - Size of the bigint in bytes.\n * @param le - Whether to use little-endian byte order.\n * @param signed - Whether the bigint is signed.\n * @param sized - Whether the bigint should have a fixed size.\n * @param minimal - Whether unsized decoding should reject redundant zero/sign-extension bytes.\n * Without it, `01` and `00 01` decode to the same value (a malleability vector): set\n * `minimal: true` whenever encodings must be canonical (consensus data, signed payloads).\n * @returns CoderType representing the bigint value.\n * @throws On invalid bigint coder configuration or out-of-bounds bigint values. {@link Error}\n * @throws On wrong builder argument or wrapped numeric value types. {@link TypeError}\n * @example\n * Define a 512-bit unsigned big-endian integer coder.\n * ```ts\n * import * as P from 'micro-packed';\n * // Define a CoderType for a 512-bit unsigned big-endian integer.\n * const U512BE = P.bigint(64, false, false, true);\n * ```\n */\nexport const bigint = (size, le = false, signed = false, sized = true, minimal = false) => {\n    // Size is used in exponent math below; reject non-positive widths before raw RangeErrors leak.\n    if (!isNum(size) || size <= 0)\n        throw new Error(`bigint/size: wrong value ${size}`);\n    if (typeof le !== 'boolean')\n        throw new Error(`bigint/le: expected boolean, got ${typeof le}`);\n    if (typeof signed !== 'boolean')\n        throw new Error(`bigint/signed: expected boolean, got ${typeof signed}`);\n    if (typeof sized !== 'boolean')\n        throw new Error(`bigint/sized: expected boolean, got ${typeof sized}`);\n    if (typeof minimal !== 'boolean')\n        throw new Error(`bigint/minimal: expected boolean, got ${typeof minimal}`);\n    const bLen = BigInt(size);\n    const signBit = _2n ** (_8n * bLen - _1n);\n    return wrap({\n        size: sized ? size : undefined,\n        encodeStream: (w, value) => {\n            const zero = value === _0n;\n            if (signed && value < 0)\n                value = value | signBit;\n            // Fill big-endian in place; trimming below relies on BE order.\n            let res = new Uint8Array(size);\n            for (let i = size - 1; i >= 0; i--) {\n                res[i] = Number(value & _255n);\n                value >>= _8n;\n            }\n            if (!sized) {\n                let pos = 0;\n                if (signed) {\n                    // Keep signed unsized encodings minimal but unambiguous for input-width signed decode.\n                    for (; pos < res.length - 1; pos++) {\n                        const next = res[pos + 1];\n                        if (res[pos] === 0 && (next & 128) === 0)\n                            continue;\n                        if (res[pos] === 255 && (next & 128) !== 0)\n                            continue;\n                        break;\n                    }\n                    res = zero ? res.subarray(res.length) : res.subarray(pos);\n                }\n                else {\n                    for (; pos < res.length; pos++)\n                        if (res[pos] !== 0)\n                            break;\n                    res = res.subarray(pos); // remove leading zeros\n                }\n            }\n            w.bytes(le ? res.reverse() : res);\n        },\n        decodeStream: (r) => {\n            // TODO: for le we can read until first zero?\n            const value = r.bytes(sized ? size : Math.min(size, r.leftBytes));\n            if (!sized && minimal)\n                checkMinimalBigintBytes(value, le, signed, (msg) => r.err(msg));\n            // Accumulate most-significant byte first: avoids swapEndianness copy and per-byte shift bigints.\n            let res = _0n;\n            if (le)\n                for (let i = value.length - 1; i >= 0; i--)\n                    res = (res << _8n) | BigInt(value[i]);\n            else\n                for (let i = 0; i < value.length; i++)\n                    res = (res << _8n) | BigInt(value[i]);\n            const sBit = sized || !value.length ? signBit : _2n ** (_8n * BigInt(value.length) - _1n);\n            if (signed && res & sBit)\n                res = (res ^ sBit) - sBit;\n            return res;\n        },\n        validate: (value) => {\n            if (typeof value !== 'bigint')\n                throw new Error(`bigint: invalid value: ${value}`);\n            checkBounds(value, _8n * bLen, !!signed);\n            return value;\n        },\n    });\n};\n/** Unsigned 256-bit little-endian integer CoderType. */\nexport const U256LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(32, true));\n/** Unsigned 256-bit big-endian integer CoderType. */\nexport const U256BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(32, false));\n/** Signed 256-bit little-endian integer CoderType. */\nexport const I256LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(32, true, true));\n/** Signed 256-bit big-endian integer CoderType. */\nexport const I256BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(32, false, true));\n/** Unsigned 128-bit little-endian integer CoderType. */\nexport const U128LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(16, true));\n/** Unsigned 128-bit big-endian integer CoderType. */\nexport const U128BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(16, false));\n/** Signed 128-bit little-endian integer CoderType. */\nexport const I128LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(16, true, true));\n/** Signed 128-bit big-endian integer CoderType. */\nexport const I128BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(16, false, true));\n/** Unsigned 64-bit little-endian integer CoderType. */\nexport const U64LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(8, true));\n/** Unsigned 64-bit big-endian integer CoderType. */\nexport const U64BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(8, false));\n/** Signed 64-bit little-endian integer CoderType. */\nexport const I64LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(8, true, true));\n/** Signed 64-bit big-endian integer CoderType. */\nexport const I64BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ bigint(8, false, true));\n/**\n * CoderType for working with number values (up to 6 bytes/48 bits).\n * Unsized int values should be wrapped in a container (e.g., bytes or string).\n *\n * `0 = Uint8Array.of()`\n *\n * `1 = new Uint8Array([1n])`\n *\n * Please open issue, if you need different behavior for zero.\n *\n * @param size - Size of the number in bytes.\n * @param le - Whether to use little-endian byte order.\n * @param signed - Whether the number is signed.\n * @param sized - Whether the number should have a fixed size.\n * @param minimal - Whether unsized decoding should reject redundant zero/sign-extension bytes.\n * Without it, `01` and `00 01` decode to the same value (a malleability vector): set\n * `minimal: true` whenever encodings must be canonical (consensus data, signed payloads).\n * @returns CoderType representing the number value.\n * @throws On invalid number-coder configuration or out-of-bounds values. {@link Error}\n * @throws On wrong builder argument or wrapped numeric value types. {@link TypeError}\n * @example\n * Create a coder for JavaScript numbers up to 48 bits wide.\n * ```ts\n * import * as P from 'micro-packed';\n * const int24 = P.int(3, false); // Define a coder for a 24-bit unsigned big-endian integer\n * ```\n */\nexport const int = (size, le = false, signed = false, sized = true, minimal = false) => {\n    if (!isNum(size) || size <= 0)\n        throw new Error(`int/size: wrong value ${size}`);\n    if (typeof le !== 'boolean')\n        throw new Error(`int/le: expected boolean, got ${typeof le}`);\n    if (typeof signed !== 'boolean')\n        throw new Error(`int/signed: expected boolean, got ${typeof signed}`);\n    if (typeof sized !== 'boolean')\n        throw new Error(`int/sized: expected boolean, got ${typeof sized}`);\n    if (typeof minimal !== 'boolean')\n        throw new Error(`int/minimal: expected boolean, got ${typeof minimal}`);\n    if (size > 6)\n        throw new Error('int supports size up to 6 bytes (48 bits): use bigints instead');\n    return apply(bigint(size, le, signed, sized, minimal), coders.numberBigint);\n};\nconst view = (len, opts) => wrap({\n    size: len,\n    encodeStream: (w, value) => w.writeView(len, (view, pos) => opts.write(view, pos, value)),\n    decodeStream: (r) => r.readView(len, opts.read),\n    validate: (value) => {\n        if (typeof value !== 'number')\n            throw new TypeError(`viewCoder: expected number, got ${typeof value}`);\n        if (opts.validate)\n            opts.validate(value);\n        return value;\n    },\n});\nconst intView = (len, signed, opts) => {\n    const bits = len * 8;\n    const signBit = 2 ** (bits - 1);\n    // Inlined checkBounds for integer\n    const validateSigned = (value) => {\n        if (!isNum(value))\n            throw new TypeError(`sintView: value is not safe integer: ${value}`);\n        if (value < -signBit || value >= signBit) {\n            throw new RangeError(`sintView: value out of bounds. Expected ${-signBit} <= ${value} < ${signBit}`);\n        }\n    };\n    const maxVal = 2 ** bits;\n    const validateUnsigned = (value) => {\n        if (!isNum(value))\n            throw new TypeError(`uintView: value is not safe integer: ${value}`);\n        if (0 > value || value >= maxVal) {\n            throw new RangeError(`uintView: value out of bounds. Expected 0 <= ${value} < ${maxVal}`);\n        }\n    };\n    return view(len, {\n        write: opts.write,\n        read: opts.read,\n        validate: signed ? validateSigned : validateUnsigned,\n    });\n};\n/** Unsigned 32-bit little-endian integer CoderType. */\nexport const U32LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(4, false, {\n    read: (view, pos) => view.getUint32(pos, true),\n    write: (view, pos, value) => view.setUint32(pos, value, true),\n}));\n/** Unsigned 32-bit big-endian integer CoderType. */\nexport const U32BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(4, false, {\n    read: (view, pos) => view.getUint32(pos, false),\n    write: (view, pos, value) => view.setUint32(pos, value, false),\n}));\n/** Signed 32-bit little-endian integer CoderType. */\nexport const I32LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(4, true, {\n    read: (view, pos) => view.getInt32(pos, true),\n    write: (view, pos, value) => view.setInt32(pos, value, true),\n}));\n/** Signed 32-bit big-endian integer CoderType. */\nexport const I32BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(4, true, {\n    read: (view, pos) => view.getInt32(pos, false),\n    write: (view, pos, value) => view.setInt32(pos, value, false),\n}));\n/** Unsigned 16-bit little-endian integer CoderType. */\nexport const U16LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(2, false, {\n    read: (view, pos) => view.getUint16(pos, true),\n    write: (view, pos, value) => view.setUint16(pos, value, true),\n}));\n/** Unsigned 16-bit big-endian integer CoderType. */\nexport const U16BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(2, false, {\n    read: (view, pos) => view.getUint16(pos, false),\n    write: (view, pos, value) => view.setUint16(pos, value, false),\n}));\n/** Signed 16-bit little-endian integer CoderType. */\nexport const I16LE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(2, true, {\n    read: (view, pos) => view.getInt16(pos, true),\n    write: (view, pos, value) => view.setInt16(pos, value, true),\n}));\n/** Signed 16-bit big-endian integer CoderType. */\nexport const I16BE = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(2, true, {\n    read: (view, pos) => view.getInt16(pos, false),\n    write: (view, pos, value) => view.setInt16(pos, value, false),\n}));\n/** Unsigned 8-bit integer CoderType. */\nexport const U8 = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(1, false, {\n    read: (view, pos) => view.getUint8(pos),\n    write: (view, pos, value) => view.setUint8(pos, value),\n}));\n/** Signed 8-bit integer CoderType. */\nexport const I8 = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ intView(1, true, {\n    read: (view, pos) => view.getInt8(pos),\n    write: (view, pos, value) => view.setInt8(pos, value),\n}));\n// Floats\nconst canonicalNaN = (len, le) => {\n    const buf = new Uint8Array(len);\n    const v = createView(buf);\n    if (len === 4)\n        v.setFloat32(0, NaN, le);\n    else\n        v.setFloat64(0, NaN, le);\n    return buf;\n};\nconst f32 = (le = false) => {\n    const nan = canonicalNaN(4, le);\n    const nanBits = createView(nan).getUint32(0, le);\n    return wrap({\n        size: 4,\n        encodeStream: (w, value) => {\n            if (Number.isNaN(value))\n                return w.bytes(nan);\n            return w.writeView(4, (view, pos) => view.setFloat32(pos, value, le));\n        },\n        decodeStream: (r) => {\n            const _r = r;\n            return _r.readView(4, (view, pos) => {\n                const value = view.getFloat32(pos, le);\n                if (Number.isNaN(value) && view.getUint32(pos, le) !== nanBits)\n                    throw _r.err('f32: non-canonical NaN');\n                return value;\n            });\n        },\n        validate: (value) => {\n            if (typeof value !== 'number')\n                throw new TypeError(`viewCoder: expected number, got ${typeof value}`);\n            if (Math.fround(value) !== value && !Number.isNaN(value))\n                throw new Error(`f32: wrong value=${value}`);\n            return value;\n        },\n    });\n};\nconst f64 = (le = false) => {\n    const nan = canonicalNaN(8, le);\n    const nanLeft = createView(nan).getUint32(0, le);\n    const nanRight = createView(nan).getUint32(4, le);\n    return wrap({\n        size: 8,\n        encodeStream: (w, value) => {\n            if (Number.isNaN(value))\n                return w.bytes(nan);\n            return w.writeView(8, (view, pos) => view.setFloat64(pos, value, le));\n        },\n        decodeStream: (r) => {\n            const _r = r;\n            return _r.readView(8, (view, pos) => {\n                const value = view.getFloat64(pos, le);\n                if (Number.isNaN(value) &&\n                    (view.getUint32(pos, le) !== nanLeft || view.getUint32(pos + 4, le) !== nanRight))\n                    throw _r.err('f64: non-canonical NaN');\n                return value;\n            });\n        },\n        validate: (value) => {\n            if (typeof value !== 'number')\n                throw new TypeError(`viewCoder: expected number, got ${typeof value}`);\n            return value;\n        },\n    });\n};\n/** 32-bit big-endian floating point CoderType (\"binary32\", IEEE 754-2008). */\nexport const F32BE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ f32(false));\n/** 32-bit little-endian floating point  CoderType (\"binary32\", IEEE 754-2008). */\nexport const F32LE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ f32(true));\n/** 64-bit big-endian floating point type (\"binary64\", IEEE 754-2008). */\nexport const F64BE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ f64(false));\n/** 64-bit little-endian floating point type (\"binary64\", IEEE 754-2008). */\nexport const F64LE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ f64(true));\n/** Boolean CoderType. */\nexport const bool = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ wrap({\n    size: 1,\n    encodeStream: (w, value) => w.byte(value ? 1 : 0),\n    decodeStream: (r) => {\n        const value = r.byte();\n        if (value !== 0 && value !== 1)\n            throw r.err(`bool: invalid value ${value}`);\n        return value === 1;\n    },\n    validate: (value) => {\n        if (typeof value !== 'boolean')\n            throw new TypeError(`bool: invalid value ${value}`);\n        return value;\n    },\n}));\n/**\n * Bytes CoderType with a specified length and endianness.\n * The bytes can have:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - Length mode: CoderType for dynamic size, number for fixed size,\n * Uint8Array for terminator mode, or null to parse until end of buffer.\n * @param le - Whether to use little-endian byte order.\n * @returns CoderType representing the bytes.\n * @throws If the byte layout or terminator handling is invalid. {@link Error}\n * @throws On wrong byte-coder argument or value types. {@link TypeError}\n * @example\n * Use fixed-size, length-prefixed, or trailing byte arrays.\n * ```ts\n * import * as P from 'micro-packed';\n * const dynamicBytes = P.bytes(P.U16BE, false);\n * const fixedBytes = P.bytes(32, false); // Fixed size bytes\n * const unknownBytes = P.bytes(null, false); // Unknown size bytes, will parse until end of buffer\n * const zeroTerminatedBytes = P.bytes(Uint8Array.of(0), false); // Zero-terminated bytes\n * ```\n */\nconst createBytes = (len, le = false) => {\n    if (typeof le !== 'boolean')\n        throw new TypeError(`bytes/le: expected boolean, got ${typeof le}`);\n    const _length = lengthCoder(len);\n    const _isb = isBytes(len);\n    // Snapshot terminator bytes so the precomputed matcher and emitted terminator stay consistent.\n    const terminator = _isb ? Uint8Array.from(len) : undefined;\n    const findTerminator = terminator && terminator.length ? createFindBytes(terminator) : undefined;\n    return wrap({\n        size: typeof len === 'number' ? len : undefined,\n        encodeStream: (w, value) => {\n            if (!_isb)\n                _length.encodeStream(w, value.length);\n            w.bytes((le ? swapEndianness(value) : value));\n            if (terminator)\n                w.bytes(terminator);\n        },\n        decodeStream: (r) => {\n            let bytes;\n            if (terminator) {\n                const tPos = r.find(terminator);\n                // Position 0 is a valid empty payload before the terminator; only undefined means not found.\n                if (tPos === undefined)\n                    throw r.err(`bytes: cannot find terminator`);\n                bytes = r.bytes(tPos - r.pos);\n                r.bytes(terminator.length);\n            }\n            else {\n                bytes = r.bytes(len === null ? r.leftBytes : _length.decodeStream(r));\n            }\n            return (le ? swapEndianness(bytes) : bytes);\n        },\n        validate: (value) => {\n            if (!isBytes(value))\n                throw new TypeError(`bytes: invalid value ${value}`);\n            if (findTerminator) {\n                const data = le ? swapEndianness(value) : value;\n                if (findTerminator(data) !== undefined)\n                    throw new Error('bytes: value contains terminator');\n            }\n            return value;\n        },\n    });\n};\nexport { createBytes as bytes, createHex as hex };\n/**\n * Prefix-encoded value using a length prefix and an inner CoderType.\n * The prefix can have:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - Length mode: CoderType for dynamic size, number for fixed size,\n * Uint8Array for terminator mode, or null to parse until end of buffer.\n * @param inner - CoderType for the actual value to be prefix-encoded.\n * @returns CoderType representing the prefix-encoded value.\n * @throws If the prefix configuration or wrapped coding step is invalid. {@link Error}\n * @throws On wrong prefix-coder argument types. {@link TypeError}\n * @example\n * Prefix a payload with either a dynamic or fixed byte count.\n * ```ts\n * import * as P from 'micro-packed';\n * // Dynamic size prefix: prefixed with P.U16BE byte length.\n * const dynamicPrefix = P.prefix(P.U16BE, P.bytes(null));\n * // Fixed size prefix: always 10 bytes.\n * const fixedPrefix = P.prefix(10, P.bytes(null));\n * ```\n */\nexport function prefix(len, inner) {\n    // Constructor argument validation uses TypeError, same as apply/array/struct.\n    if (!isCoder(inner))\n        throw new TypeError(`prefix: invalid inner value ${inner}`);\n    return apply(createBytes(len), reverse(inner));\n}\n/**\n * String CoderType with a specified length and endianness.\n * The string can be:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - Length mode: CoderType for dynamic size, number for fixed size,\n * Uint8Array for terminator mode, or null to parse until end of buffer.\n * @param le - Whether to use little-endian byte order.\n * Note: UTF-8 has no endian variant; `le` reverses the encoded byte sequence\n * via the underlying byte coder.\n * @returns CoderType representing the string.\n * @throws If the underlying byte layout is invalid. {@link Error}\n * @throws On wrong string-coder argument or value types. {@link TypeError}\n * @example\n * Use fixed-size, length-prefixed, or trailing UTF-8 strings.\n * ```ts\n * import * as P from 'micro-packed';\n * // Dynamic string prefixed with P.U16BE string length.\n * const dynamicString = P.string(P.U16BE, false);\n * const fixedString = P.string(10, false);\n * // Unknown size string, parsed until end of buffer.\n * const unknownString = P.string(null, false);\n * const nullTerminatedString = P.cstring; // NUL-terminated string\n * const _cstring = P.string(Uint8Array.of(0)); // Same thing\n * ```\n */\nexport const string = (len, le = false) => validate(apply(createBytes(len, le), utf8), (value) => {\n    // TextEncoder/TextDecoder will fail on non-string, but we create more readable errors earlier\n    if (typeof value !== 'string')\n        throw new Error(`expected string, got ${typeof value}`);\n    return value;\n});\n/** NUL-terminated string CoderType. */\n// Both factory calls need PURE markers so single-export treeshake bundles drop unused cstring.\nexport const cstring = /* @__PURE__ */ Object.freeze(\n/* @__PURE__ */ string(NULL));\n/**\n * Hexadecimal string CoderType with a specified length, endianness, and optional 0x prefix.\n * @param len - Length mode: CoderType for dynamic size, number for fixed size,\n * Uint8Array for terminator mode, or null to parse until end of buffer.\n * @param options - Hex-specific endianness and prefix options. See {@link HexOpts}.\n * Use `isLE` to decode bytes as little-endian before converting to hex, and\n * `with0x` to add and require a `0x` prefix.\n * @returns CoderType representing the hexadecimal string.\n * @throws If the underlying byte layout or `0x` prefix handling is invalid. {@link Error}\n * @throws On wrong hex-coder argument or value types. {@link TypeError}\n * @example\n * Encode bytes as hex, optionally little-endian and with a `0x` prefix.\n * ```ts\n * import * as P from 'micro-packed';\n * // Hex string with 0x prefix and U16BE length.\n * const dynamicHex = P.hex(P.U16BE, {isLE: false, with0x: true});\n * // Fixed-length 32-byte hex string without 0x prefix.\n * const fixedHex = P.hex(32, {isLE: false, with0x: false});\n * ```\n */\nconst createHex = (len, options = { isLE: false, with0x: false }) => {\n    // HexOpts fields are optional independently; omitted fields keep the default behavior.\n    const isLE = options.isLE === undefined ? false : options.isLE;\n    const prefix = options.with0x === undefined ? false : options.with0x;\n    if (typeof isLE !== 'boolean')\n        throw new Error(`hex/isLE: expected boolean, got ${typeof isLE}`);\n    if (typeof prefix !== 'boolean')\n        throw new Error(`hex/with0x: expected boolean, got ${typeof prefix}`);\n    let inner = apply(createBytes(len, isLE), baseHex);\n    if (prefix) {\n        inner = apply(inner, {\n            encode: (value) => `0x${value}`,\n            decode: (value) => {\n                if (!value.startsWith('0x'))\n                    throw new Error('hex(with0x=true).encode input should start with 0x');\n                return value.slice(2);\n            },\n        });\n    }\n    return inner;\n};\n/**\n * Applies a base coder to a CoderType.\n * @param inner - The inner CoderType.\n * @param base - The base coder to apply.\n * @returns CoderType representing the transformed value.\n * @throws On wrong inner-coder or base-coder argument types. {@link TypeError}\n * @example\n * Reuse a base coder on top of a binary bytes coder.\n * ```ts\n * import * as P from 'micro-packed';\n * import { hex as baseHex } from '@scure/base';\n * const hexCoder = P.apply(P.bytes(32), baseHex); // will decode bytes into a hex string\n * ```\n */\nexport function apply(inner, base) {\n    // Constructor guards are documented TypeErrors and should name the rejected argument.\n    if (!isCoder(inner))\n        throw new TypeError(`apply: invalid inner value ${inner}`);\n    if (!isBaseCoder(base))\n        throw new TypeError(`apply: invalid base value ${base}`);\n    return wrap({\n        size: inner.size,\n        encodeStream: (w, value) => {\n            let innerValue;\n            try {\n                innerValue = base.decode(value);\n            }\n            catch (e) {\n                throw w.err('' + e);\n            }\n            return inner.encodeStream(w, innerValue);\n        },\n        decodeStream: (r) => {\n            const innerValue = inner.decodeStream(r);\n            try {\n                return base.encode(innerValue);\n            }\n            catch (e) {\n                throw r.err('' + e);\n            }\n        },\n    });\n}\n/**\n * Lazy CoderType that is evaluated at runtime.\n * @param fn - A function that returns the CoderType.\n * @returns CoderType representing the lazy value.\n * @throws On wrong lazy-factory argument types. {@link TypeError}\n * @example\n * Define a recursive tree without referencing the coder before it exists.\n * ```ts\n * import * as P from 'micro-packed';\n * type Tree = { name: string; children: Tree[] };\n * const tree = P.struct({\n *   name: P.cstring,\n *   children: P.array(\n *     P.U16BE,\n *     P.lazy((): P.CoderType<Tree> => tree)\n *   ),\n * });\n * ```\n */\nexport function lazy(fn) {\n    if (typeof fn !== 'function')\n        throw new TypeError(`lazy: expected function, got ${typeof fn}`);\n    return wrap({\n        encodeStream: (w, value) => fn().encodeStream(w, value),\n        decodeStream: (r) => fn().decodeStream(r),\n    });\n}\n/**\n * Flag CoderType that encodes/decodes a boolean value based on the presence of a marker.\n * @param flagValue - Marker value.\n * @param xor - Whether to invert the flag behavior.\n * @returns CoderType representing the flag value.\n * @throws On wrong flag argument or value types. {@link TypeError}\n * @throws If the marker is empty. {@link Error}\n *\n * WARNING: a flag is decoded by peeking at the next bytes, so the field that follows it\n * must never be able to start with the marker bytes. Otherwise encode/decode is\n * ambiguous: `{ flag: absent, data: <starts with marker> }` re-decodes as\n * `{ flag: present, data: <rest> }`. There is no local guard against this (the flag\n * cannot see the following coder); choose a marker that cannot collide, or place the\n * flag where collision is impossible (e.g. before fixed-alphabet data).\n * @example\n * Toggle a boolean based on whether a marker is present.\n * ```ts\n * import * as P from 'micro-packed';\n * // Encodes true as u8a([0x01, 0x02]), false as u8a([]).\n * const flag = P.flag(new Uint8Array([0x01, 0x02]));\n * // Encodes true as u8a([]), false as u8a([0x01, 0x02]).\n * const flagXor = P.flag(new Uint8Array([0x01, 0x02]), true);\n * const s = P.struct({ f: P.flag(new Uint8Array([0x0, 0x1])), f2: P.flagged('f', P.U32BE) });\n * ```\n */\nexport const flag = (flagValue, xor = false) => {\n    if (!isBytes(flagValue))\n        throw new TypeError(`flag/flagValue: expected Uint8Array, got ${typeof flagValue}`);\n    // Empty markers cannot distinguish presence from absence, so one boolean state is lost.\n    if (flagValue.length === 0)\n        throw new Error('flag/flagValue: empty marker');\n    if (typeof xor !== 'boolean')\n        throw new TypeError(`flag/xor: expected boolean, got ${typeof xor}`);\n    const marker = Uint8Array.from(flagValue);\n    return wrap({\n        // Marker flags encode one state as empty, so encoded length depends on the boolean value.\n        size: undefined,\n        encodeStream: (w, value) => {\n            if (!!value !== xor)\n                w.bytes(marker);\n        },\n        decodeStream: (r) => {\n            let hasFlag = r.leftBytes >= marker.length;\n            if (hasFlag) {\n                hasFlag = equalBytes(r.bytes(marker.length, true), marker);\n                // Found flag, advance cursor position\n                if (hasFlag)\n                    r.bytes(marker.length);\n            }\n            return hasFlag !== xor; // hasFlag ^ xor\n        },\n        validate: (value) => {\n            if (value !== undefined && typeof value !== 'boolean')\n                throw new Error(`flag: expected boolean value or undefined, got ${typeof value}`);\n            return value;\n        },\n    });\n};\n/**\n * Absent-flag default slots must hold the canonical default encoding: otherwise they\n * carry arbitrary bytes that vanish on re-encode (malleability). Object defaults follow\n * magic(): decoded values are fresh objects and deep-equal semantics are out of scope,\n * so comparison is skipped only when both sides are non-byte objects.\n * Contextual stream coders cannot be compared as standalone bytes, so normalizing coders must\n * receive a decoder-canonical default. NaN is the exception because it cannot equal itself.\n */\nfunction validateDefaultSlot(r, value, def) {\n    const valueObj = value !== null && typeof value === 'object' && !isBytes(value);\n    const defObj = def !== null && typeof def === 'object' && !isBytes(def);\n    const nan = typeof value === 'number' &&\n        typeof def === 'number' &&\n        Number.isNaN(value) &&\n        Number.isNaN(def);\n    if ((!valueObj || !defObj) && !equal(value, def) && !nan)\n        throw r.err(`default: invalid value ${value} !== ${def}`);\n}\n/**\n * Conditional CoderType that encodes/decodes a value only if a flag is present.\n * @param path - Path to the flag value or a CoderType for the flag.\n * @param inner - Inner CoderType for the value.\n * @param def - Optional default value to use if the flag is not present.\n * @returns CoderType representing the conditional value.\n * @throws On wrong flag-path or inner-coder argument types. {@link TypeError}\n * @example\n * Decode a field only when a sibling flag is present.\n * ```ts\n * import * as P from 'micro-packed';\n * const s = P.struct({\n *   f: P.flag(new Uint8Array([0x0, 0x1])),\n *   f2: P.flagged('f', P.U32BE)\n * });\n * ```\n *\n * @example\n * Supply a default when the sibling flag is missing.\n * ```ts\n * import * as P from 'micro-packed';\n * const s2 = P.struct({\n *   f: P.flag(new Uint8Array([0x0, 0x1])),\n *   f2: P.flagged('f', P.U32BE, 123)\n * });\n * ```\n */\nexport function flagged(path, inner, def) {\n    if (typeof path !== 'string' && !isCoder(path))\n        throw new TypeError(`flagged: wrong path=${path}`);\n    if (!isCoder(inner))\n        throw new TypeError(`flagged: invalid inner value ${inner}`);\n    const hasDef = def !== undefined;\n    return wrap({\n        encodeStream: (w, value) => {\n            if (typeof path === 'string') {\n                if (Path.resolve(w.stack, path))\n                    inner.encodeStream(w, value);\n                else if (hasDef)\n                    inner.encodeStream(w, def);\n            }\n            else {\n                // Falsy values like 0 are valid payloads/defaults; only undefined means absent.\n                const present = value !== undefined;\n                path.encodeStream(w, present);\n                if (present)\n                    inner.encodeStream(w, value);\n                else if (hasDef)\n                    inner.encodeStream(w, def);\n            }\n        },\n        decodeStream: (r) => {\n            let hasFlag = false;\n            if (typeof path === 'string')\n                hasFlag = !!Path.resolve(r.stack, path);\n            else\n                hasFlag = path.decodeStream(r);\n            // If there is a flag -- decode and return value\n            if (hasFlag)\n                return inner.decodeStream(r);\n            else if (hasDef)\n                validateDefaultSlot(r, inner.decodeStream(r), def);\n            return;\n        },\n    });\n}\n/**\n * Optional CoderType that encodes/decodes a value based on a flag.\n * @param flag - CoderType for the flag value.\n * @param inner - Inner CoderType for the value.\n * @param def - Optional default value to use if the flag is not present.\n * @returns CoderType representing the optional value.\n * @throws On wrong flag-coder or inner-coder argument types. {@link TypeError}\n * @example\n * Decode a value only when a marker flag is present.\n * ```ts\n * import * as P from 'micro-packed';\n * const optional = P.optional(P.flag(new Uint8Array([0x0, 0x1])), P.U32BE);\n * ```\n *\n * @example\n * Provide a fallback value when the marker flag is absent.\n * ```ts\n * import * as P from 'micro-packed';\n * const optionalWithDefault = P.optional(P.flag(new Uint8Array([0x0, 0x1])), P.U32BE, 123);\n * ```\n */\nexport function optional(flag, inner, def) {\n    if (!isCoder(flag) || !isCoder(inner))\n        throw new TypeError(`optional: invalid flag or inner value flag=${flag} inner=${inner}`);\n    const hasDef = def !== undefined;\n    return wrap({\n        size: hasDef && flag.size !== undefined && inner.size !== undefined\n            ? flag.size + inner.size\n            : undefined,\n        encodeStream: (w, value) => {\n            // Falsy values like 0 are valid payloads/defaults; only undefined means absent.\n            const present = value !== undefined;\n            flag.encodeStream(w, present);\n            if (present)\n                inner.encodeStream(w, value);\n            else if (hasDef)\n                inner.encodeStream(w, def);\n        },\n        decodeStream: (r) => {\n            if (flag.decodeStream(r))\n                return inner.decodeStream(r);\n            else if (hasDef)\n                validateDefaultSlot(r, inner.decodeStream(r), def);\n            return;\n        },\n    });\n}\n/**\n * Magic value CoderType that encodes/decodes a constant value.\n * This can be used to check for a specific magic value or byte sequence\n * at the beginning of a data structure.\n * @param inner - Inner CoderType for the value.\n * @param constant - Constant value.\n * @param check - Whether to check the decoded value against the constant.\n * @returns CoderType representing the magic value.\n * @throws On wrong magic-coder argument types. {@link TypeError}\n * @example\n * Require a specific encoded value at this position in the stream.\n * ```ts\n * import * as P from 'micro-packed';\n * const magicU8 = P.magic(P.U8, 0x42);\n * ```\n */\nexport function magic(inner, constant, check = true) {\n    if (!isCoder(inner))\n        throw new TypeError(`magic: invalid inner value ${inner}`);\n    if (typeof check !== 'boolean')\n        throw new TypeError(`magic: expected boolean, got ${typeof check}`);\n    return wrap({\n        size: inner.size,\n        encodeStream: (w, _value) => inner.encodeStream(w, constant),\n        decodeStream: (r) => {\n            const value = inner.decodeStream(r);\n            // check=false still consumes the encoded field but intentionally skips constant comparison.\n            // Generic object equality would need deep-equal semantics, and decoded structs are fresh\n            // objects. Skip only when both sides are non-byte objects; mismatched primitive/object or\n            // byte/object pairs are still comparable and should reject.\n            const valueObj = value !== null && typeof value === 'object' && !isBytes(value);\n            const constantObj = constant !== null && typeof constant === 'object' && !isBytes(constant);\n            const canCompare = !valueObj || !constantObj;\n            if (check && canCompare && !equal(value, constant)) {\n                throw r.err(`magic: invalid value: ${value} !== ${constant}`);\n            }\n            return;\n        },\n        validate: (value) => {\n            if (value !== undefined)\n                throw new Error(`magic: wrong value=${typeof value}`);\n            return value;\n        },\n    });\n}\n/**\n * Magic bytes CoderType that encodes/decodes a constant byte array or string.\n * @param constant - Constant byte array or string.\n * @returns CoderType representing the magic bytes.\n * @throws If the constant check fails or the wrapped coder rejects the bytes. {@link Error}\n * @throws On wrong magic-bytes argument types. {@link TypeError}\n * Note: Uint8Array constants are copied during construction.\n * @example\n * Match a fixed byte or string marker without producing a value.\n * ```ts\n * import * as P from 'micro-packed';\n * const magicBytes = P.magicBytes('MAGIC');\n * ```\n */\nexport const magicBytes = (constant) => {\n    if (typeof constant !== 'string' && !isBytes(constant))\n        throw new TypeError(`magicBytes: expected Uint8Array or string, got ${typeof constant}`);\n    const c = typeof constant === 'string' ? utf8.decode(constant) : Uint8Array.from(constant);\n    return magic(createBytes(c.length), c);\n};\n/**\n * Creates a CoderType for a constant value. The function enforces this value during encoding,\n * ensuring it matches the provided constant. During decoding, it always returns the constant value.\n * The actual value is not written to or read from any byte stream; it's used only for validation.\n *\n * @param c - Constant value.\n * @returns CoderType representing the constant value.\n * @throws On wrong constant values passed during encoding. {@link TypeError}\n * Note: object constants are compared and returned by reference.\n * @example\n * Hide an always-constant field behind a regular coder.\n * ```ts\n * import * as P from 'micro-packed';\n * const constantU8 = P.constant(123);\n * ```\n */\nexport function constant(c) {\n    return wrap({\n        // Constants validate state but do not consume bytes, so fixed-size compositions can stay fixed.\n        size: 0,\n        encodeStream: (_w, value) => {\n            if (value !== c)\n                throw new TypeError(`constant: invalid value ${value} (exp: ${c})`);\n        },\n        decodeStream: (_r) => c,\n    });\n}\nfunction sizeof(fields) {\n    let size = 0;\n    for (const f of fields) {\n        if (f.size === undefined)\n            return;\n        if (!isNum(f.size))\n            throw new Error(`sizeof: wrong element size=${f.size}`);\n        size += f.size;\n    }\n    return size;\n}\n/**\n * Structure of composable primitives (C/Rust struct)\n * @param fields - Object mapping field names to CoderTypes.\n * @returns CoderType representing the structure.\n * @throws If the structure definition or encoded struct value is invalid. {@link Error}\n * @throws On wrong structure argument types. {@link TypeError}\n * Note: the fields object is retained by reference; mutating it after\n * construction can change encoding\n * while leaving fixed-size metadata unchanged.\n * @example\n * Combine named fields into a single structured coder.\n * ```ts\n * import * as P from 'micro-packed';\n * const myStruct = P.struct({\n *   id: P.U32BE,\n *   name: P.string(P.U8),\n *   nested: P.struct({\n *     flag: P.bool,\n *     value: P.I16LE\n *   })\n * });\n * ```\n */\nexport function struct(fields) {\n    if (!isPlainObject(fields))\n        throw new TypeError(`struct: expected plain object, got ${fields}`);\n    // Size metadata must use the same enumerable field set as encode/decode; Object.values() skips\n    // inherited fields that for...in will still encode.\n    const coders = [];\n    for (const name in fields) {\n        // String paths use '/' as the nested-field separator, so accepting it in struct keys makes\n        // diagnostics and Path.resolve() lookups ambiguous.\n        validateFieldName(name, 'struct: field');\n        if (!isCoder(fields[name]))\n            throw new TypeError(`struct: field ${name} is not CoderType`);\n        coders.push(fields[name]);\n    }\n    return wrap({\n        size: sizeof(coders),\n        encodeStream: (w, value) => {\n            const _w = w;\n            _w.pushObj(value, () => {\n                for (const name in fields) {\n                    _w.enterField(name);\n                    fields[name].encodeStream(w, value[name]);\n                    _w.exitField();\n                }\n            });\n        },\n        decodeStream: (r) => {\n            const res = {};\n            const _r = r;\n            _r.pushObj(res, () => {\n                for (const name in fields) {\n                    _r.enterField(name);\n                    res[name] = fields[name].decodeStream(r);\n                    _r.exitField();\n                }\n            });\n            return res;\n        },\n        validate: (value) => {\n            if (typeof value !== 'object' || value === null)\n                throw new Error(`struct: invalid value ${value}`);\n            return value;\n        },\n    });\n}\n/**\n * Tuple (unnamed structure) of CoderTypes. Same as struct but with unnamed fields.\n * @param fields - Array of CoderTypes.\n * @returns CoderType representing the tuple.\n * @throws If the tuple definition or encoded tuple value is invalid. {@link Error}\n * @throws On wrong tuple argument types. {@link TypeError}\n * Note: unbounded coders such as `array(null, ...)` should be last or length-prefixed; otherwise\n * they can consume bytes intended for later fields.\n * Note: the fields array is retained by reference; mutating it after construction can change encoding\n * while leaving fixed-size metadata unchanged.\n * @example\n * Combine several coders into an ordered fixed-length tuple.\n * ```ts\n * import * as P from 'micro-packed';\n * const myTuple = P.tuple([P.U8, P.U16LE, P.string(P.U8)]);\n * ```\n */\nexport function tuple(fields) {\n    if (!Array.isArray(fields))\n        throw new TypeError(`Packed.Tuple: got ${typeof fields} instead of array`);\n    for (let i = 0; i < fields.length; i++) {\n        if (!isCoder(fields[i]))\n            throw new TypeError(`tuple: field ${i} is not CoderType`);\n    }\n    return wrap({\n        size: sizeof(fields),\n        encodeStream: (w, value) => {\n            // TODO: fix types\n            if (!Array.isArray(value))\n                throw w.err(`tuple: invalid value ${value}`);\n            const _w = w;\n            _w.pushObj(value, () => {\n                for (let i = 0; i < fields.length; i++) {\n                    _w.enterField(i);\n                    fields[i].encodeStream(w, value[i]);\n                    _w.exitField();\n                }\n            });\n        },\n        decodeStream: (r) => {\n            const res = [];\n            const _r = r;\n            _r.pushObj(res, () => {\n                for (let i = 0; i < fields.length; i++) {\n                    _r.enterField(i);\n                    res.push(fields[i].decodeStream(r));\n                    _r.exitField();\n                }\n            });\n            return res;\n        },\n        validate: (value) => {\n            if (!Array.isArray(value))\n                throw new Error(`tuple: invalid value ${value}`);\n            if (value.length !== fields.length)\n                throw new Error(`tuple: wrong length=${value.length}, expected ${fields.length}`);\n            return value;\n        },\n    });\n}\n/**\n * Array of items (inner type) with a specified length.\n * @param len - Length mode: CoderType for dynamic size, number for fixed size,\n * Uint8Array for terminator mode, or null to parse until end of buffer.\n * @param inner - CoderType for encoding/decoding each array item.\n * @returns CoderType representing the array.\n * @throws If the array definition or encoded array elements are invalid. {@link Error}\n * @throws On wrong array-coder argument types. {@link TypeError}\n * Note: Uint8Array terminators are copied during construction.\n * @example\n * Build dynamic, fixed-size, and trailing arrays from one item coder.\n * ```ts\n * import * as P from 'micro-packed';\n * const child = P.U8;\n * // Dynamic array prefixed with P.U16BE array length.\n * const a1 = P.array(P.U16BE, child);\n * const a2 = P.array(4, child); // Fixed size array\n * // Unknown size array, parsed until end of buffer.\n * const a3 = P.array(null, child);\n * // Zero-terminated array; terminator can be any buffer.\n * const a4 = P.array(Uint8Array.of(0), child);\n * ```\n */\nexport function array(len, inner) {\n    // Constructor argument validation uses TypeError.\n    // Array data failures still come from reader/writer errors.\n    if (!isCoder(inner))\n        throw new TypeError(`array: invalid inner value ${inner}`);\n    const terminator = isBytes(len) ? Uint8Array.from(len) : undefined;\n    // By construction length is inside array (otherwise there will be various incorrect stack states)\n    // But forcing users always write '..' seems like bad idea. Also, breaking change.\n    const _length = lengthCoder(typeof len === 'string' ? `../${len}` : terminator || len);\n    // Unbounded arrays must make cursor progress; zero-size children would loop forever.\n    if (len === null && inner.size === 0)\n        throw new Error('array: null length cannot use zero-size inner');\n    // Stream-provided lengths are attacker-controlled: a zero-size inner would allocate\n    // `length` elements without consuming input (memory DoS). Fixed number lengths are\n    // schema constants and stay allowed; terminator arrays have runtime progress checks.\n    if ((isCoder(len) || typeof len === 'string') && inner.size === 0)\n        throw new Error('array: dynamic length cannot use zero-size inner');\n    return wrap({\n        // `size: 0` is a valid fixed-size hint and must compose through arrays/tuples/structs.\n        size: typeof len === 'number' && inner.size !== undefined ? len * inner.size : undefined,\n        encodeStream: (w, value) => {\n            const _w = w;\n            _w.pushObj(value, () => {\n                if (!terminator)\n                    _length.encodeStream(w, value.length);\n                for (let i = 0; i < value.length; i++) {\n                    _w.enterField(i);\n                    const elm = value[i];\n                    const startPos = _w.pos;\n                    inner.encodeStream(w, elm);\n                    // Terminator is bigger than elm size, so skip\n                    if (terminator && terminator.length <= _w.pos - startPos) {\n                        const data = _w.finish(false).subarray(startPos, _w.pos);\n                        // There is still possible case when multiple elements create terminator,\n                        // but it is hard to catch here, will be very slow\n                        if (equalBytes(data.subarray(0, terminator.length), terminator))\n                            throw _w.err(`array: inner element encoding same as separator. elm=${elm} data=${data}`);\n                    }\n                    _w.exitField();\n                }\n            });\n            if (terminator)\n                w.bytes(terminator);\n        },\n        decodeStream: (r) => {\n            const res = [];\n            const _r = r;\n            _r.pushObj(res, () => {\n                if (len === null) {\n                    for (let i = 0; !r.isEnd(); i++) {\n                        _r.enterField(i);\n                        // Dynamic coders can advertise unknown size while consuming zero bits; unbounded\n                        // loops must check actual progress instead of trusting size metadata.\n                        const progress = _r.progress();\n                        res.push(inner.decodeStream(r));\n                        if (_r.progress() === progress)\n                            throw r.err('array: inner decoder did not consume input');\n                        _r.exitField();\n                        if (inner.size && r.leftBytes < inner.size)\n                            break;\n                    }\n                }\n                else if (terminator) {\n                    for (let i = 0;; i++) {\n                        if (equalBytes(r.bytes(terminator.length, true), terminator)) {\n                            // Advance cursor position if terminator found\n                            r.bytes(terminator.length);\n                            break;\n                        }\n                        _r.enterField(i);\n                        const progress = _r.progress();\n                        res.push(inner.decodeStream(r));\n                        if (_r.progress() === progress)\n                            throw r.err('array: inner decoder did not consume input');\n                        _r.exitField();\n                    }\n                }\n                else {\n                    _r.enterField('arrayLen');\n                    const length = _length.decodeStream(r);\n                    _r.exitField();\n                    // Fixed-size elements consume exactly `size` bytes each: reject impossible lengths\n                    // before element decoding so hostile length prefixes fail fast without allocations.\n                    if (inner.size && length * inner.size > r.leftBytes)\n                        throw r.err(`array: length=${length} elements of size=${inner.size} exceed ${r.leftBytes} bytes left`);\n                    for (let i = 0; i < length; i++) {\n                        _r.enterField(i);\n                        res.push(inner.decodeStream(r));\n                        _r.exitField();\n                    }\n                }\n            });\n            return res;\n        },\n        validate: (value) => {\n            if (!Array.isArray(value))\n                throw new Error(`array: invalid value ${value}`);\n            return value;\n        },\n    });\n}\n/**\n * Mapping between encoded values and string representations.\n * @param inner - CoderType for encoded values.\n * @param variants - Object mapping string representations to encoded values.\n * @returns CoderType representing the mapping.\n * @throws If mapping variants are invalid or raw variant values are duplicate. {@link Error}\n * @throws On wrong mapping argument types. {@link TypeError}\n * Note: variants are copied into lookup maps at construction; mutating the\n * original object later does not update the coder.\n * Note: construction does not run the inner coder. Path-dependent coders need\n * encode/decode stack context that does not exist at construction, so selected\n * variant values are validated by the inner coder only when encoded or decoded.\n * @example\n * Map encoded numbers to a small set of string labels.\n * ```ts\n * import * as P from 'micro-packed';\n * const numberMap = P.map(P.U8, {\n *   'one': 1,\n *   'two': 2,\n *   'three': 3\n * });\n *\n * const byteMap = P.map(P.hex(2), {\n *   'ab': '6162',\n *   'cd': '6364'\n * });\n * ```\n */\nexport function map(inner, variants) {\n    if (!isCoder(inner))\n        throw new TypeError(`map: invalid inner value ${inner}`);\n    if (!isPlainObject(variants))\n        throw new TypeError(`map: variants should be plain object`);\n    const variantValues = new Map();\n    const variantNames = new Map();\n    const primitiveTypes = ['string', 'number', 'bigint', 'boolean', 'undefined', 'null'];\n    for (const k in variants) {\n        const value = variants[k];\n        // Object values such as Uint8Array are not stable reverse-map keys; wrap bytes in a primitive\n        // coder first, e.g. apply(bytes(...), hex).\n        if (!primitiveTypes.includes(value === null ? 'null' : typeof value))\n            throw new TypeError(`map: variant ${k} should be primitive`);\n        if (variantNames.has(value))\n            throw new Error(`map: duplicate value for ${k} and ${variantNames.get(value)}`);\n        variantValues.set(k, value);\n        variantNames.set(value, k);\n    }\n    return wrap({\n        size: inner.size,\n        encodeStream: (w, value) => {\n            if (!variantValues.has(value))\n                throw w.err(`Map: unknown variant: ${value}`);\n            inner.encodeStream(w, variantValues.get(value));\n        },\n        decodeStream: (r) => {\n            const variant = inner.decodeStream(r);\n            const name = variantNames.get(variant);\n            if (name === undefined)\n                throw r.err(`Enum: unknown value: ${variant} ${Array.from(variantNames.keys())}`);\n            return name;\n        },\n        validate: (value) => {\n            if (typeof value !== 'string')\n                throw new Error(`map: invalid value ${value}`);\n            if (!variantValues.has(value))\n                throw new Error(`Map: unknown variant: ${value}`);\n            return value;\n        },\n    });\n}\n/**\n * Tagged union of CoderTypes, where the tag value determines which CoderType to use.\n * The decoded value will have the structure `\\{ TAG: number, data: ... \\}`.\n * @param tag - CoderType for the tag value.\n * @param variants - Object mapping tag values to CoderTypes.\n * @returns CoderType representing the tagged union.\n * @throws On wrong tag-coder or variant-map argument types. {@link TypeError}\n * Note: variants are copied into a lookup map at construction; mutating the\n * original object later does not update the coder.\n * Note: construction does not run the tag coder. Path-dependent tag coders need\n * encode/decode stack context that does not exist at construction, so callers\n * are responsible for providing tag keys that the tag coder can encode/decode.\n * @example\n * Switch between payload coders based on a leading tag byte.\n * ```ts\n * import * as P from 'micro-packed';\n * const taggedUnion = P.tag(P.U8, {\n *   0x01: P.array(P.U16LE, P.U8),\n *   0x02: P.string(P.U8),\n *   0x03: P.U32BE\n * });\n *\n * const encoded = taggedUnion.encode({ TAG: 0x01, data: [1, 2] });\n * const decoded = taggedUnion.decode(encoded);\n * ```\n */\nexport function tag(tag, variants) {\n    if (!isCoder(tag))\n        throw new TypeError(`tag: invalid tag value ${tag}`);\n    if (!isPlainObject(variants))\n        throw new TypeError(`tag: variants should be plain object`);\n    const variantCoders = new Map();\n    for (const name in variants) {\n        if (!isCoder(variants[name]))\n            throw new TypeError(`tag: variant ${name} is not CoderType`);\n        variantCoders.set(name, variants[name]);\n        const num = Number(name);\n        // Object keys are strings; mirror canonical integer keys as numbers so numeric tag coders still\n        // decode to the same arm without running the tag coder at construction.\n        if (isNum(num) && String(num) === name)\n            variantCoders.set(num, variants[name]);\n    }\n    let size;\n    let dataSize;\n    let dynamic = tag.size === undefined;\n    // Tagged unions have a fixed size only when every arm contributes the same fixed payload size.\n    for (const name in variants) {\n        const cur = variants[name].size;\n        if (cur === undefined || (dataSize !== undefined && cur !== dataSize))\n            dynamic = true;\n        dataSize = cur;\n    }\n    if (!dynamic && dataSize !== undefined)\n        size = tag.size + dataSize;\n    return wrap({\n        size,\n        encodeStream: (w, value) => {\n            const { TAG, data } = value;\n            const dataType = variantCoders.get(TAG);\n            if (!dataType)\n                throw w.err(`Tag: invalid tag ${TAG.toString()}`);\n            tag.encodeStream(w, TAG);\n            dataType.encodeStream(w, data);\n        },\n        decodeStream: (r) => {\n            const TAG = tag.decodeStream(r);\n            const dataType = variantCoders.get(TAG);\n            if (!dataType)\n                throw r.err(`Tag: invalid tag ${TAG}`);\n            return { TAG, data: dataType.decodeStream(r) };\n        },\n        validate: (value) => {\n            const { TAG } = value;\n            const dataType = variantCoders.get(TAG);\n            if (!dataType)\n                throw new Error(`Tag: invalid tag ${TAG.toString()}`);\n            return value;\n        },\n    });\n}\n/**\n * Mapping between encoded values, string representations, and CoderTypes using a tag CoderType.\n * @param tagCoder - CoderType for the tag value.\n * @param variants - Object mapping string representations to [tag value, CoderType] pairs.\n * @returns CoderType representing the mapping.\n * @throws If the mapped-tag table is invalid, raw tag values are duplicate,\n * or the selected variant is invalid. {@link Error}\n * @throws On wrong tag-coder or variant-map argument types. {@link TypeError}\n * Note: construction does not run the tag coder. Path-dependent tag coders need\n * encode/decode stack context that does not exist at construction, so callers\n * are responsible for providing tag values that the tag coder can encode/decode.\n * Note: variant pairs are copied at construction; mutating the original variants\n * object or pair arrays later does not update the coder.\n * @example\n * Use string tags in TypeScript while encoding them as compact numeric tags.\n * ```ts\n * import * as P from 'micro-packed';\n * type Value =\n *   | { TAG: 'uint'; data: number }\n *   | { TAG: 'array'; data: Value[] };\n * const value: P.CoderType<Value> = P.mappedTag(P.U8, {\n *   uint: [0, P.U8],\n *   array: [1, P.array(P.U8, P.lazy(() => value))],\n * });\n * value.encode({ TAG: 'array', data: [{ TAG: 'uint', data: 5 }] });\n * ```\n */\nexport function mappedTag(tagCoder, variants) {\n    if (!isCoder(tagCoder))\n        throw new TypeError(`mappedTag: invalid tag value ${tagCoder}`);\n    if (!isPlainObject(variants))\n        throw new TypeError(`mappedTag: variants should be plain object`);\n    const mapValue = new Map();\n    const tagValue = new Map();\n    for (const key in variants) {\n        const v = variants[key];\n        mapValue.set(key, v[0]);\n        tagValue.set(key, v[1]);\n    }\n    // Object.fromEntries creates \"__proto__\" as an own data field; assignment to plain {}\n    // would instead mutate the temporary object's prototype before map()/tag() see it.\n    const mapped = Object.fromEntries(mapValue);\n    const tagged = Object.fromEntries(tagValue);\n    return tag(map(tagCoder, mapped), tagged);\n}\n/**\n * Bitset of boolean values with optional padding.\n * @param names - An array of string names for the bitset values.\n * @param pad - Whether to pad the bitset to a multiple of 8 bits.\n * @param strict - Whether to reject duplicate names and non-zero padding bits.\n * @returns CoderType representing the bitset.\n * @typeParam Names - Bit names preserved in the returned record.\n * @throws If the bitset definition or encoded bitset values are invalid. {@link Error}\n * @throws On wrong bitset argument types. {@link TypeError}\n * Note: bits follow `names` order and are written most-significant-bit first\n * within each byte; non-byte-aligned `pad=false` bitsets must be composed with\n * more bit-level coders.\n * Note: strict mode is the default: it rejects duplicate names and non-zero padding\n * bits, since ignored padding bits are a malleability vector (hidden data survives\n * decode and vanishes on re-encode). Pass `strict: false` only for legacy data that\n * requires repeated names or junk padding.\n * Note: the names array is retained by reference. Do not mutate it after construction:\n * doing so invalidates size metadata and breaks encoding and decoding.\n * @example\n * Pack several named booleans into a compact bitset.\n * ```ts\n * import * as P from 'micro-packed';\n * const myBitset = P.bitset(['flag1', 'flag2', 'flag3', 'flag4'], true);\n * ```\n */\nexport function bitset(names, pad = false, strict = true) {\n    if (typeof pad !== 'boolean')\n        throw new TypeError(`bitset/pad: expected boolean, got ${typeof pad}`);\n    if (typeof strict !== 'boolean')\n        throw new TypeError(`bitset/strict: expected boolean, got ${typeof strict}`);\n    if (!Array.isArray(names))\n        throw new TypeError('bitset/names: expected array');\n    const nameSet = new Set();\n    for (const name of names) {\n        if (typeof name !== 'string')\n            throw new TypeError('bitset/names: expected array of strings');\n        if (strict && nameSet.has(name))\n            throw new Error(`bitset/names: duplicate name ${name}`);\n        validateFieldName(name, 'bitset/names: name');\n        nameSet.add(name);\n    }\n    return wrap({\n        // Padded and byte-aligned bitsets consume whole bytes, so fixed-size compositions can stay fixed.\n        size: pad || names.length % 8 === 0 ? Math.ceil(names.length / 8) : undefined,\n        encodeStream: (w, value) => {\n            const vals = value;\n            for (let i = 0; i < names.length; i++)\n                w.bits(hasOwn(vals, names[i]) ? +vals[names[i]] : 0, 1);\n            if (pad && names.length % 8)\n                w.bits(0, 8 - (names.length % 8));\n        },\n        decodeStream: (r) => {\n            const out = {};\n            for (let i = 0; i < names.length; i++)\n                out[names[i]] = !!r.bits(1);\n            if (pad && names.length % 8) {\n                const padding = r.bits(8 - (names.length % 8));\n                // Encoders always write zero padding; strict mode rejects alternate encodings with hidden set bits.\n                if (strict && padding)\n                    throw r.err('bitset: non-zero padding bits');\n            }\n            return out;\n        },\n        validate: (value) => {\n            if (!isPlainObject(value))\n                throw new Error(`bitset: invalid value ${value}`);\n            const vals = value;\n            for (const name of names) {\n                if (!hasOwn(vals, name))\n                    continue;\n                if (typeof vals[name] !== 'boolean')\n                    throw new Error(`bitset: expected boolean for ${name}`);\n            }\n            return value;\n        },\n    });\n}\n/**\n * Padding function which always returns zero.\n * @param i - Zero-based padding byte index.\n * @returns Always returns `0`.\n * @example\n * Use the default zero padding helper with padLeft/padRight.\n * ```ts\n * import { U16BE, ZeroPad, padLeft } from 'micro-packed';\n * padLeft(4, U16BE, ZeroPad);\n * ```\n */\nexport const ZeroPad = (_) => 0;\nfunction padLength(blockSize, len) {\n    // Padding counts bytes already written/read; negative lengths invert modulo math.\n    if (!isNum(len) || len < 0)\n        throw new Error(`padLength: wrong length=${len}`);\n    if (len % blockSize === 0)\n        return 0;\n    return blockSize - (len % blockSize);\n}\nfunction padByte(label, padFn, i, err) {\n    const value = padFn(i);\n    if (!isNum(value) || value < 0 || value > 255)\n        throw err(`${label}: wrong padding byte at ${i}: ${value}`);\n    return value;\n}\nfunction writePadding(label, w, padFn, len) {\n    for (let i = 0; i < len; i++)\n        w.byte(padByte(label, padFn, i, (msg) => w.err(msg)));\n}\nfunction checkPadding(label, r, padFn, len) {\n    const padding = r.bytes(len);\n    for (let i = 0; i < padding.length; i++) {\n        const expected = padByte(label, padFn, i, (msg) => r.err(msg));\n        if (padding[i] !== expected)\n            throw r.err(`${label}: invalid padding byte at ${i}: ${padding[i]} !== ${expected}`);\n    }\n}\n/**\n * Pads a CoderType with a specified block size and padding function on the left side.\n * @param blockSize - Block size for padding (positive safe integer).\n * @param inner - Inner CoderType to pad.\n * @param padFn - Padding function to use. If not provided, zero padding is used.\n * @returns CoderType representing the padded value.\n * Decode validates that padding bytes match `padFn`, preventing alternate encodings with hidden\n * padding data.\n * @throws If the padding configuration or wrapped coder is invalid. {@link Error}\n * @throws On wrong padding argument types. {@link TypeError}\n * @example\n * Left-pad a value to the next block boundary.\n * ```ts\n * import * as P from 'micro-packed';\n * const paddedU32BE = P.padLeft(4, P.U32BE);\n *\n * const paddedBytes = P.padLeft(16, P.bytes(8), (i) => i + 1);\n * ```\n */\nexport function padLeft(blockSize, inner, padFn) {\n    if (!isNum(blockSize) || blockSize <= 0)\n        throw new TypeError(`padLeft: wrong blockSize=${blockSize}`);\n    if (!isCoder(inner))\n        throw new TypeError(`padLeft: invalid inner value ${inner}`);\n    if (padFn !== undefined && typeof padFn !== 'function')\n        throw new TypeError(`padLeft: wrong padFn=${typeof padFn}`);\n    const _padFn = padFn || ZeroPad;\n    // `size: 0` is fixed-size and should pad as zero bytes; only undefined means dynamic.\n    if (inner.size === undefined)\n        throw new Error('padLeft cannot have dynamic size');\n    const size = inner.size;\n    return wrap({\n        size: size + padLength(blockSize, size),\n        encodeStream: (w, value) => {\n            const padBytes = padLength(blockSize, size);\n            writePadding('padLeft', w, _padFn, padBytes);\n            inner.encodeStream(w, value);\n        },\n        decodeStream: (r) => {\n            checkPadding('padLeft', r, _padFn, padLength(blockSize, size));\n            return inner.decodeStream(r);\n        },\n    });\n}\n/**\n * Pads a CoderType with a specified block size and padding function on the right side.\n * @param blockSize - Block size for padding (positive safe integer).\n * @param inner - Inner CoderType to pad.\n * @param padFn - Padding function to use. If not provided, zero padding is used.\n * @returns CoderType representing the padded value.\n * Decode validates that padding bytes match `padFn`, preventing alternate encodings with hidden\n * padding data.\n * @throws If the padding configuration or wrapped coder is invalid. {@link Error}\n * @throws On wrong padding argument types. {@link TypeError}\n * @example\n * Right-pad a value to the next block boundary.\n * ```ts\n * import * as P from 'micro-packed';\n * const paddedU16BE = P.padRight(2, P.U16BE);\n *\n * const paddedBytes = P.padRight(8, P.bytes(null), (i) => i + 1);\n * ```\n */\nexport function padRight(blockSize, inner, padFn) {\n    if (!isCoder(inner))\n        throw new TypeError(`padRight: invalid inner value ${inner}`);\n    if (!isNum(blockSize) || blockSize <= 0)\n        throw new TypeError(`padRight: wrong blockSize=${blockSize}`);\n    if (padFn !== undefined && typeof padFn !== 'function')\n        throw new TypeError(`padRight: wrong padFn=${typeof padFn}`);\n    const _padFn = padFn || ZeroPad;\n    const size = inner.size;\n    return wrap({\n        // `size: 0` is fixed-size and should pad as zero bytes; only undefined means dynamic.\n        size: size === undefined ? undefined : size + padLength(blockSize, size),\n        encodeStream: (w, value) => {\n            const _w = w;\n            const pos = _w.pos;\n            inner.encodeStream(w, value);\n            const padBytes = padLength(blockSize, _w.pos - pos);\n            writePadding('padRight', w, _padFn, padBytes);\n        },\n        decodeStream: (r) => {\n            const start = r.pos;\n            const res = inner.decodeStream(r);\n            checkPadding('padRight', r, _padFn, padLength(blockSize, r.pos - start));\n            return res;\n        },\n    });\n}\n/**\n * Pointer to a value using a pointer CoderType and an inner CoderType.\n * Pointers are scoped, and the next pointer in the dereference chain is offset by the previous one.\n * By default (if no 'allowMultipleReads' in ReaderOpts is set) is safe, since\n * same region of memory cannot be read multiple times.\n * @param ptr - CoderType for the pointer value.\n * @param inner - CoderType for encoding/decoding the pointed value.\n * @param sized - Whether the in-place pointer slot should report a fixed size.\n * @returns CoderType representing the pointer to the value.\n * @throws If the pointer configuration or pointed value decoding is invalid. {@link Error}\n * @throws On wrong pointer-coder argument types. {@link TypeError}\n * @example\n * Jump to a pointed value and decode it with another coder.\n * ```ts\n * import * as P from 'micro-packed';\n * const pointerToU8 = P.pointer(P.U16BE, P.U8); // Pointer to a single U8 value\n * ```\n */\nexport function pointer(ptr, inner, sized = false) {\n    if (!isCoder(ptr))\n        throw new TypeError(`pointer: invalid ptr value ${ptr}`);\n    if (!isCoder(inner))\n        throw new TypeError(`pointer: invalid inner value ${inner}`);\n    if (typeof sized !== 'boolean')\n        throw new TypeError(`pointer/sized: expected boolean, got ${typeof sized}`);\n    if (!ptr.size)\n        throw new Error('unsized pointer');\n    return wrap({\n        // Pointer payloads are appended by Writer.finish().\n        // Size only describes the in-place pointer slot\n        // so surrounding structs/arrays can lay out the fixed section before pointed data.\n        size: sized ? ptr.size : undefined,\n        encodeStream: (w, value) => {\n            const _w = w;\n            const start = _w.pos;\n            ptr.encodeStream(w, 0);\n            _w.ptrs.push({ pos: start, ptr, buffer: inner.encode(value) });\n        },\n        decodeStream: (r) => {\n            const ptrVal = ptr.decodeStream(r);\n            r._enablePointers();\n            return inner.decodeStream(r.offsetReader(ptrVal));\n        },\n    });\n}\n// Internal methods for test purposes only.\n// Note: _TEST exposes live internal namespaces by reference for tests.\n// Mutating them changes runtime behavior.\nexport const _TEST = /* @__PURE__ */ Object.freeze({\n    _bitset: Bitset,\n    _padLength: padLength,\n    _findBytes: findBytes,\n    _Reader,\n    _Writer,\n    Path,\n});\n","import { schnorr, secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { abytes, bytesToNumberBE, numberToBytesBE } from '@noble/curves/utils.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\nimport {} from '@noble/hashes/utils.js';\nimport { utils as packedUtils, U32LE } from 'micro-packed';\nexport { abytes, validateObject as vld } from '@noble/curves/utils.js';\nexport {} from '@noble/hashes/utils.js';\n/**\n * Validates that a value is a non-negative bigint.\n * @param n - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The same bigint.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a satoshi amount before transaction encoding.\n * ```ts\n * abigint(1n, 'amount');\n * ```\n */\nexport function abigint(n, title = 'value') {\n    if (typeof n !== 'bigint')\n        throw new TypeError(`\"${title}\" expected bigint, got type=${typeof n}`);\n    if (n < _0n)\n        throw new RangeError(`\"${title}\" expected non-negative bigint, got ${n}`);\n    return n;\n}\nimport { validateObject as vld } from '@noble/curves/utils.js';\nexport function aarray(item, title, inner = () => { }) {\n    if (!Array.isArray(item))\n        throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n    for (let i = 0; i < item.length; i++)\n        inner(item[i], `${title}[${i}]`);\n    return item;\n}\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n    if (typeof value !== 'string') {\n        const prefix = title && `\"${title}\" `;\n        throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n    }\n    return value;\n}\nexport function validateObject(object, fields = {}, optFields = {}, _title = 'object') {\n    return vld(object, fields, optFields);\n}\nconst Point = /* @__PURE__ */ (() => secp.Point)();\nconst Fn = /* @__PURE__ */ (() => Point.Fn)();\nconst CURVE_ORDER = /* @__PURE__ */ (() => Point.Fn.ORDER)();\n// Be friendly to bad ECMAScript parsers by not using bigint literals.\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _2n = /* @__PURE__ */ BigInt(2);\n/**\n * Checks whether a curve y-coordinate is even.\n * @param y - y-coordinate to inspect\n * @returns `true` when the coordinate is even.\n * @example\n * Check whether a point coordinate has even parity.\n * ```ts\n * hasEven(2n);\n * ```\n */\nexport const hasEven = (y) => y % _2n === _0n;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - value to inspect\n * @returns `true` when the value is a Uint8Array.\n * @example\n * Check whether an unknown value is already bytes.\n * ```ts\n * isBytes(new Uint8Array([1]));\n * ```\n */\nexport const isBytes = /* @__PURE__ */ (() => packedUtils.isBytes)();\n/**\n * Concatenates byte arrays into a single Uint8Array.\n * @param arrays - byte arrays to concatenate\n * @returns Concatenated byte array.\n * @example\n * Join several byte chunks before hashing or signing them.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport const concatBytes = \n/* @__PURE__ */ (() => packedUtils.concatBytes)();\n/**\n * Compares two byte arrays for equality.\n * @param a - first byte array\n * @param b - second byte array\n * @returns `true` when both arrays contain the same bytes.\n * @example\n * Compare two serialized values without converting them first.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport const equalBytes = \n/* @__PURE__ */ (() => packedUtils.equalBytes)();\n/**\n * SHA-256 hash function.\n * @param msg - bytes to hash\n * @returns SHA-256 digest.\n * @example\n * Hash a byte array with SHA-256.\n * ```ts\n * sha256(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ (() => nobleSha256)();\n/**\n * HASH160 helper used by classic Bitcoin addresses.\n * @param msg - bytes to hash\n * @returns RIPEMD160(SHA256(msg)).\n * @example\n * Derive the HASH160 used by legacy address formats.\n * ```ts\n * hash160(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const hash160 = (msg) => ripemd160(sha256(msg));\n/**\n * Double-SHA256 helper used by Bitcoin transaction ids.\n * @param msgs - message parts to concatenate and hash\n * @returns SHA256(SHA256(concat(msgs))).\n * @example\n * Compute the double-SHA256 used by txids and sighashes.\n * ```ts\n * sha256x2(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport const sha256x2 = (...msgs) => sha256(sha256(concatBytes(...msgs)));\n/**\n * Generates a random secp256k1 private key.\n * @returns Random 32-byte private key.\n * @example\n * Generate a fresh secp256k1 private key for signing.\n * ```ts\n * const privKey = randomPrivateKeyBytes();\n * ```\n */\nexport const randomPrivateKeyBytes = () => schnorr.utils.randomSecretKey();\n/**\n * Derives a BIP340 Schnorr public key from a private key.\n * @param priv - private key bytes\n * @returns X-only public key bytes.\n * @example\n * Derive the x-only public key used by Schnorr and Taproot.\n * ```ts\n * import { pubSchnorr, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * pubSchnorr(randomPrivateKeyBytes());\n * ```\n */\nexport const pubSchnorr = (priv) => schnorr.getPublicKey(priv);\n/**\n * Derives a secp256k1 ECDSA public key from a private key.\n * @param privateKey - private key bytes\n * @param isCompressed - whether to return the compressed form\n * @returns Serialized public key bytes.\n * @example\n * Derive the normal secp256k1 public key for legacy or SegWit scripts.\n * ```ts\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * pubECDSA(randomPrivateKeyBytes());\n * ```\n */\nexport const pubECDSA = (privateKey, isCompressed) => secp.getPublicKey(privateKey, isCompressed);\n// low-r signature grinding. Used to reduce tx size by 1 byte.\n// noble/secp256k1 does not support the feature: it is not used outside of BTC.\n// We implement it manually, because in BTC it's common.\n// Not best way, but closest to bitcoin implementation (easier to check)\n// Hoisted: the bound is constant; no need to redo the bigint division on every\n// grinding-loop iteration. n/2 < 2^255, so r < n/2 guarantees the 32-byte DER r.\nconst LOW_R_BOUND = /* @__PURE__ */ (() => CURVE_ORDER / _2n)();\nconst hasLowR = (sig) => sig.r < LOW_R_BOUND;\n/**\n * Signs a 32-byte hash with ECDSA and returns DER encoding.\n * @param hash - message hash to sign\n * @param privateKey - signer private key\n * @param lowR - whether to grind for low-R signatures\n * @returns DER-encoded signature bytes.\n * @throws If low-R grinding overflows or ECDSA signing fails validation. {@link Error}\n * @example\n * Hash a message first, then create the DER-encoded ECDSA signature.\n * ```ts\n * import { randomPrivateKeyBytes, sha256, signECDSA } from '@scure/btc-signer/utils.js';\n * signECDSA(sha256(new Uint8Array([1, 2, 3])), randomPrivateKeyBytes());\n * ```\n */\nexport function signECDSA(hash, privateKey, lowR = false) {\n    // signECDSA is the 32-byte sighash wrapper for BTC callers, so reject arbitrary-length\n    // messages here instead of silently signing them with prehash disabled.\n    abytes(hash, 32, 'hash');\n    let sig = secp.Signature.fromBytes(secp.sign(hash, privateKey, { prehash: false }));\n    if (lowR && !hasLowR(sig)) {\n        const extraEntropy = new Uint8Array(32);\n        let counter = 0;\n        while (!hasLowR(sig)) {\n            extraEntropy.set(U32LE.encode(counter++));\n            sig = secp.Signature.fromBytes(secp.sign(hash, privateKey, { prehash: false, extraEntropy }));\n            if (counter > 4294967295)\n                throw new Error('lowR counter overflow: report the error');\n        }\n    }\n    return sig.toBytes('der');\n}\n/**\n * BIP340 Schnorr signing function.\n * @param message - 32-byte message digest\n * @param secretKey - signer private key\n * @param auxRand - optional auxiliary randomness\n * @returns Schnorr signature bytes.\n * @example\n * Sign a 32-byte digest with the built-in BIP340 helper.\n * ```ts\n * import { randomPrivateKeyBytes, sha256, signSchnorr } from '@scure/btc-signer/utils.js';\n * const msg = sha256(new Uint8Array([1, 2, 3]));\n * signSchnorr(msg, randomPrivateKeyBytes());\n * ```\n */\nexport const signSchnorr = (message, secretKey, auxRand) => schnorr.sign(message, secretKey, auxRand);\n/**\n * Tagged-hash helper used by Schnorr and taproot constructions.\n * @param tag - tagged-hash domain separator\n * @param messages - message parts hashed under the tag\n * @returns Tagged SHA-256 digest.\n * @example\n * Build the tagged hash used by Taproot leaves or tweaks.\n * ```ts\n * import { tagSchnorr } from '@scure/btc-signer/utils.js';\n * tagSchnorr('TapLeaf', Uint8Array.of(0xc0), Uint8Array.of(0x51));\n * ```\n */\nexport const tagSchnorr = (tag, ...messages) => schnorr.utils.taggedHash(tag, ...messages);\n/** Public key format tags used by validation helpers. */\nexport const PubT = /* @__PURE__ */ (() => Object.freeze({\n    ecdsa: 0,\n    schnorr: 1,\n}))();\n/**\n * Validates a public key against the expected Bitcoin key encoding.\n * @param pub - public key bytes to validate\n * @param type - expected public key format\n * @returns The validated public key bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Reject keys that do not match the encoding required by the current script path.\n * ```ts\n * import {\n *   PubT,\n *   pubECDSA,\n *   randomPrivateKeyBytes,\n *   validatePubkey,\n * } from '@scure/btc-signer/utils.js';\n * validatePubkey(pubECDSA(randomPrivateKeyBytes()), PubT.ecdsa);\n * ```\n */\nexport function validatePubkey(pub, type) {\n    const len = pub.length;\n    if (type === PubT.ecdsa) {\n        if (len === 32)\n            throw new RangeError('Expected non-Schnorr key');\n        Point.fromBytes(pub); // does assertValidity\n        return pub;\n    }\n    else if (type === PubT.schnorr) {\n        if (len !== 32)\n            throw new RangeError('Expected 32-byte Schnorr key');\n        schnorr.utils.lift_x(bytesToNumberBE(pub));\n        return pub;\n    }\n    else {\n        throw new TypeError('Unknown key type');\n    }\n}\n/**\n * Computes the Taproot tweak scalar from an internal key and merkle root.\n * @param a - internal key bytes\n * @param b - optional merkle root bytes\n * @returns Taproot tweak scalar.\n * @throws If the tweak scalar is outside the curve order. {@link Error}\n * @example\n * Combine the internal key and Merkle root into the Taproot tweak scalar.\n * ```ts\n * import { pubSchnorr, randomPrivateKeyBytes, tapTweak } from '@scure/btc-signer/utils.js';\n * tapTweak(pubSchnorr(randomPrivateKeyBytes()), new Uint8Array());\n * ```\n */\nexport function tapTweak(a, b) {\n    const u = schnorr.utils;\n    const t = u.taggedHash('TapTweak', a, b);\n    const tn = bytesToNumberBE(t);\n    if (tn >= CURVE_ORDER)\n        throw new Error('tweak higher than curve order');\n    return tn;\n}\n/**\n * Tweaks a private key for Taproot key-path spending.\n * @param privKey - internal private key bytes\n * @param merkleRoot - optional taproot merkle root\n * @returns Tweaked private key bytes.\n * @throws If the Taproot tweak scalar is outside the curve order. {@link Error}\n * @example\n * Derive the tweaked Taproot key-path secret from the internal private key.\n * ```ts\n * import { randomPrivateKeyBytes, taprootTweakPrivKey } from '@scure/btc-signer/utils.js';\n * taprootTweakPrivKey(randomPrivateKeyBytes());\n * ```\n */\nexport function taprootTweakPrivKey(privKey, merkleRoot = Uint8Array.of()) {\n    const u = schnorr.utils;\n    // BIP341 taproot_tweak_seckey starts with `seckey0 = int_from_bytes(seckey0)`, and\n    // BIP340 defines `int(x)` only for `x` as a 32-byte array, so reject other widths here.\n    abytes(privKey, 32, 'privKey');\n    const seckey0 = bytesToNumberBE(privKey); // seckey0 = int_from_bytes(seckey0)\n    const P = Point.BASE.multiply(seckey0); // P = point_mul(G, seckey0)\n    // seckey = seckey0 if has_even_y(P) else SECP256K1_ORDER - seckey0\n    const seckey = hasEven(P.y) ? seckey0 : Fn.neg(seckey0);\n    const xP = u.pointToBytes(P);\n    // t = int_from_bytes(tagged_hash(\"TapTweak\", bytes_from_int(x(P)) + h)); >= SECP256K1_ORDER check\n    const t = tapTweak(xP, merkleRoot);\n    // bytes_from_int((seckey + t) % SECP256K1_ORDER)\n    return numberToBytesBE(Fn.add(seckey, t), 32);\n}\n/**\n * Tweaks a Schnorr public key for Taproot key-path spending.\n * @param pubKey - x-only internal public key\n * @param h - taproot merkle root\n * @returns Tweaked public key and output-key parity.\n * @throws If the Taproot tweak scalar is outside the curve order. {@link Error}\n * @example\n * Derive the final Taproot output key from the internal key and Merkle root.\n * ```ts\n * import {\n *   pubSchnorr,\n *   randomPrivateKeyBytes,\n *   taprootTweakPubkey,\n * } from '@scure/btc-signer/utils.js';\n * taprootTweakPubkey(pubSchnorr(randomPrivateKeyBytes()), new Uint8Array());\n * ```\n */\nexport function taprootTweakPubkey(pubKey, h) {\n    const u = schnorr.utils;\n    // BIP341 taproot_tweak_pubkey feeds `pubkey` into `int_from_bytes(pubkey)`, and\n    // BIP340 defines `int(x)` only for `x` as a 32-byte array, so reject other widths here.\n    abytes(pubKey, 32, 'pubKey');\n    const t = tapTweak(pubKey, h); // t = int_from_bytes(tagged_hash(\"TapTweak\", pubkey + h))\n    const P = u.lift_x(bytesToNumberBE(pubKey)); // P = lift_x(int_from_bytes(pubkey))\n    const Q = P.add(Point.BASE.multiply(t)); // Q = point_add(P, point_mul(G, t))\n    const parity = hasEven(Q.y) ? 0 : 1; // 0 if has_even_y(Q) else 1\n    return [u.pointToBytes(Q), parity]; // bytes_from_int(x(Q))\n}\n// Another stupid decision, where lack of standard affects security.\n// Multisig needs to be generated with some key.\n// We are using the BIP 341/bitcoinjs-lib approach:\n// SHA256(uncompressedDER(SECP256K1_GENERATOR_POINT))\n// It is possible to switch SECP256K1_GENERATOR_POINT with some random point;\n// but it's too complex to prove.\n// Also used by bitcoin-core and bitcoinjs-lib\n// This is the fixed BIP 341 H example, not the privacy-preserving H + rG variant.\n// Downstream helpers use exact-byte equality with it to recognize\n// library-generated script-only outputs.\n// Keep the value used by library internals private: exported Uint8Arrays are mutable, so the\n// public compatibility export below cannot safely be a source of cryptographic key material.\nconst INTERNAL_TAPROOT_NUMS = /* @__PURE__ */ (() => sha256(Point.BASE.toBytes(false)))();\n/**\n * Standard unspendable internal key used for script-only Taproot outputs.\n * @deprecated Use {@link taprootNumsKey} to receive an owned copy.\n */\nexport const TAPROOT_UNSPENDABLE_KEY = /* @__PURE__ */ (() => Uint8Array.from(INTERNAL_TAPROOT_NUMS))();\n/**\n * Returns an owned copy of the library's stable Taproot NUMS key.\n * @returns A new 32-byte NUMS key copy.\n * @example\n * Obtain an internal key without sharing mutable exported storage.\n * ```ts\n * import { taprootNumsKey } from '@scure/btc-signer/utils.js';\n * const internalKey = taprootNumsKey();\n * ```\n */\nexport function taprootNumsKey() {\n    return Uint8Array.from(INTERNAL_TAPROOT_NUMS);\n}\n/** Bitcoin mainnet network parameters. */\nexport const NETWORK = /* @__PURE__ */ Object.freeze({\n    bech32: 'bc',\n    pubKeyHash: 0x00,\n    scriptHash: 0x05,\n    wif: 0x80,\n});\n/** Bitcoin testnet network parameters. */\nexport const TEST_NETWORK = /* @__PURE__ */ Object.freeze({\n    bech32: 'tb',\n    pubKeyHash: 0x6f,\n    scriptHash: 0xc4,\n    wif: 0xef,\n});\n// Exported for tests, internal method\n/**\n * Lexicographically compares two byte arrays.\n * @param a - first byte array\n * @param b - second byte array\n * @returns `-1`, `0`, or `1` depending on the ordering.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Compare two serialized keys using Bitcoin's byte ordering.\n * ```ts\n * compareBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function compareBytes(a, b) {\n    if (!isBytes(a) || !isBytes(b))\n        throw new TypeError(`cmp: wrong type a=${typeof a} b=${typeof b}`);\n    // -1 -> a<b, 0 -> a==b, 1 -> a>b\n    const len = Math.min(a.length, b.length);\n    for (let i = 0; i < len; i++)\n        if (a[i] != b[i])\n            return Math.sign(a[i] - b[i]);\n    return Math.sign(a.length - b.length);\n}\n// Reverses key<->values\n/**\n * Reverses an object's keys and values.\n * @param obj - object to reverse\n * @returns Object with original values mapped back to keys.\n * @throws If duplicate values would collide while reversing the object. {@link Error}\n * @example\n * Flip a lookup table so the values become keys.\n * ```ts\n * reverseObject({ a: 1, b: 2 });\n * ```\n */\nexport function reverseObject(obj) {\n    // Keep a raw dictionary shape so enum-like tables can reverse values like\n    // `toString` without colliding with inherited Object prototype properties.\n    const res = Object.create(null);\n    for (const k in obj) {\n        if (res[obj[k]] !== undefined)\n            throw new Error('duplicate key');\n        res[obj[k]] = k;\n    }\n    return res;\n}\n","import * as P from 'micro-packed';\nimport { aarray, abytes, isBytes, reverseObject, } from \"./utils.js\";\n/**\n * Maximum byte size allowed for a single pushed script element.\n * BIP 342 keeps this 520-byte stack-element limit even though tapscript removes\n * the old 10,000-byte overall script-size cap.\n */\nexport const MAX_SCRIPT_BYTE_LENGTH = 520;\n// Be friendly to bad ECMAScript parsers by not using bigint literals.\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);\nconst U8_MAX = /* @__PURE__ */ BigInt(0xff);\nconst COMPACT_DIRECT_MAX = /* @__PURE__ */ BigInt(0xfc);\n// prettier-ignore\n/**\n * Bitcoin Script opcode table.\n * @example\n * Use opcode numbers when you need the raw byte form instead of Script mnemonics.\n * ```ts\n * import { OP } from '@scure/btc-signer/script.js';\n * new Uint8Array([OP.OP_1, OP.OP_2, OP.CHECKMULTISIG]);\n * ```\n */\nexport const OP = /* @__PURE__ */ Object.freeze({\n    OP_0: 0, PUSHDATA1: 76, PUSHDATA2: 77, PUSHDATA4: 78, '1NEGATE': 79,\n    RESERVED: 80,\n    OP_1: 81, OP_2: 82, OP_3: 83, OP_4: 84, OP_5: 85, OP_6: 86, OP_7: 87, OP_8: 88, OP_9: 89,\n    OP_10: 90, OP_11: 91, OP_12: 92, OP_13: 93, OP_14: 94, OP_15: 95, OP_16: 96,\n    // Control\n    NOP: 97, VER: 98, IF: 99, NOTIF: 100, VERIF: 101, VERNOTIF: 102, ELSE: 103, ENDIF: 104, VERIFY: 105, RETURN: 106,\n    // Stack\n    TOALTSTACK: 107, FROMALTSTACK: 108, '2DROP': 109, '2DUP': 110, '3DUP': 111, '2OVER': 112, '2ROT': 113, '2SWAP': 114,\n    IFDUP: 115, DEPTH: 116, DROP: 117, DUP: 118, NIP: 119, OVER: 120, PICK: 121, ROLL: 122, ROT: 123, SWAP: 124, TUCK: 125,\n    // Splice\n    CAT: 126, SUBSTR: 127, LEFT: 128, RIGHT: 129, SIZE: 130,\n    // Boolean logic\n    INVERT: 131, AND: 132, OR: 133, XOR: 134, EQUAL: 135, EQUALVERIFY: 136, RESERVED1: 137, RESERVED2: 138,\n    // Numbers\n    '1ADD': 139, '1SUB': 140, '2MUL': 141, '2DIV': 142,\n    NEGATE: 143, ABS: 144, NOT: 145, '0NOTEQUAL': 146,\n    ADD: 147, SUB: 148, MUL: 149, DIV: 150, MOD: 151, LSHIFT: 152, RSHIFT: 153, BOOLAND: 154, BOOLOR: 155,\n    NUMEQUAL: 156, NUMEQUALVERIFY: 157, NUMNOTEQUAL: 158, LESSTHAN: 159, GREATERTHAN: 160,\n    LESSTHANOREQUAL: 161, GREATERTHANOREQUAL: 162, MIN: 163, MAX: 164, WITHIN: 165,\n    // Crypto\n    RIPEMD160: 166, SHA1: 167, SHA256: 168, HASH160: 169, HASH256: 170, CODESEPARATOR: 171,\n    CHECKSIG: 172, CHECKSIGVERIFY: 173, CHECKMULTISIG: 174, CHECKMULTISIGVERIFY: 175,\n    // Expansion\n    NOP1: 176, CHECKLOCKTIMEVERIFY: 177, CHECKSEQUENCEVERIFY: 178, NOP4: 179, NOP5: 180, NOP6: 181, NOP7: 182, NOP8: 183, NOP9: 184, NOP10: 185,\n    // BIP 342\n    CHECKSIGADD: 186,\n    // Invalid\n    INVALID: 255,\n});\n/**\n * Reverse lookup map from opcode numbers back to names.\n * @example\n * Turn parsed opcode numbers back into their mnemonic names.\n * ```ts\n * import { OP, OPNames } from '@scure/btc-signer/script.js';\n * OPNames[OP.CHECKSIG];\n * ```\n */\nexport const OPNames = /* @__PURE__ */ (() => Object.freeze(reverseObject(OP)))();\n// We can encode almost any number as ScriptNum, however, parsing will be a problem\n// since we can't know if buffer is a number or something else.\n/**\n * Coder for Bitcoin Script numbers.\n * bytesLimit only constrains decode. encode still serializes any bigint in\n * Script's signed-magnitude byte form so higher-level consumers can enforce\n * opcode-specific 4-byte or 5-byte bounds separately.\n * @param bytesLimit - maximum decoded length in bytes\n * @param forceMinimal - whether to reject non-minimal encodings\n * @returns Script number coder.\n * @example\n * Encode a small integer using Script number rules.\n * ```ts\n * ScriptNum().encode(1n);\n * ```\n */\nexport function ScriptNum(bytesLimit = 6, forceMinimal = false) {\n    return P.wrap({\n        encodeStream: (w, value) => {\n            if (value === _0n)\n                return;\n            const neg = value < 0;\n            const val = BigInt(value);\n            const nums = [];\n            for (let abs = neg ? -val : val; abs; abs >>= _8n)\n                nums.push(Number(abs & U8_MAX));\n            if (nums[nums.length - 1] >= 0x80)\n                nums.push(neg ? 0x80 : 0);\n            else if (neg)\n                nums[nums.length - 1] |= 0x80;\n            w.bytes(new Uint8Array(nums));\n        },\n        decodeStream: (r) => {\n            const len = r.leftBytes;\n            if (len > bytesLimit)\n                throw new Error(`ScriptNum: number (${len}) bigger than limit=${bytesLimit}`);\n            if (len === 0)\n                return _0n;\n            // Read the payload once instead of peeking for the minimality check and\n            // then re-reading it byte-by-byte through the Reader.\n            const data = r.bytes(len);\n            if (forceMinimal) {\n                // MSB is zero (without sign bit) -> not minimally encoded\n                if ((data[len - 1] & 0x7f) === 0) {\n                    // exception\n                    if (len <= 1 || (data[len - 2] & 0x80) === 0)\n                        throw new Error('Non-minimally encoded ScriptNum');\n                }\n            }\n            let res = _0n;\n            for (let i = 0; i < len; ++i)\n                res |= BigInt(data[i]) << (_8n * BigInt(i));\n            if (data[len - 1] >= 0x80) {\n                res &= (_2n ** BigInt(len * 8) - _1n) >> _1n;\n                res = -res;\n            }\n            return res;\n        },\n    });\n}\n/**\n * Attempts to decode a numeric script element into a JavaScript number.\n * Accepts decoded small integers already represented as JS numbers and pushed\n * `ScriptNum` byte payloads, but does not interpret opcode mnemonics like `1NEGATE`.\n * @param op - script element to decode\n * @param bytesLimit - maximum encoded length in bytes\n * @param forceMinimal - whether to enforce minimal `ScriptNum` encoding\n * @returns Decoded number, or `undefined` when the element is not a JS number or valid `ScriptNum` bytes.\n * @example\n * Decode a script element back into a JavaScript number when possible.\n * ```ts\n * OpToNum(1);\n * ```\n */\nexport function OpToNum(op, bytesLimit = 4, forceMinimal = true) {\n    if (typeof op === 'number')\n        return op;\n    if (isBytes(op)) {\n        try {\n            const val = ScriptNum(bytesLimit, forceMinimal).decode(op);\n            // Symmetric safe-integer bound: large negative values would otherwise\n            // coerce through Number() with silent precision loss.\n            if (val > Number.MAX_SAFE_INTEGER || val < -Number.MAX_SAFE_INTEGER)\n                return;\n            return Number(val);\n        }\n        catch (e) {\n            return;\n        }\n    }\n    return;\n}\n// Shared raw pushdata-length parser. Keep this aligned with Script.decodeStream\n// so byte-preserving walkers can skip pushed data without semantic decode/re-encode.\n/**\n * Returns the pushed-data length for a push opcode.\n * @param op - opcode byte already read from the script stream\n * @param read - callback that reads the following 1/2/4-byte little-endian length\n * @returns Push length for data-carrying opcodes, or `undefined` for non-push opcodes.\n * @throws If the opcode falls through the recognized push-opcode set unexpectedly.\n * {@link Error}\n */\nexport const scriptPushLen = (op, read) => {\n    if (!(OP.OP_0 < op && op <= OP.PUSHDATA4))\n        return;\n    if (op < OP.PUSHDATA1)\n        return op;\n    if (op === OP.PUSHDATA1)\n        return read(1);\n    if (op === OP.PUSHDATA2)\n        return read(2);\n    if (op === OP.PUSHDATA4)\n        return read(4);\n    throw new Error('Should be not possible');\n};\n// Converts script bytes to parsed script\n// 5221030000000000000000000000000000000000000000000000000000000000000001210300000000000000000000000000000000000000000000000000000000000000022103000000000000000000000000000000000000000000000000000000000000000353ae\n// =>\n// OP_2\n//   030000000000000000000000000000000000000000000000000000000000000001\n//   030000000000000000000000000000000000000000000000000000000000000002\n//   030000000000000000000000000000000000000000000000000000000000000003\n//   OP_3\n//   CHECKMULTISIG\n// This is a semantic AST codec, not a byte-preserving parser: encode\n// canonicalizes small integers to OP_n and chooses the shortest push opcode,\n// so decode(...)+encode(...) rewrites non-minimal push spellings.\n/**\n * Bitcoin script coder.\n * @example\n * Encode a short script from opcode mnemonics and small integers.\n * ```ts\n * Script.encode(['OP_1', 'OP_2']);\n * ```\n */\nexport const Script = /* @__PURE__ */ (() => Object.freeze(P.wrap({\n    encodeStream: (w, value) => {\n        aarray(value, 'value');\n        for (let o of value) {\n            if (typeof o === 'string') {\n                const op = OP[o];\n                // OP is a plain object, so inherited Object.prototype keys ('toString',\n                // 'constructor', ...) are not opcodes and must be rejected here too.\n                if (typeof op !== 'number')\n                    throw new Error(`Unknown opcode=${o}`);\n                w.byte(op);\n                continue;\n            }\n            else if (typeof o === 'number') {\n                if (o === 0x00) {\n                    w.byte(0x00);\n                    continue;\n                }\n                else if (o === -1) {\n                    // BIP62 minimal push / number rules spell numeric -1 as OP_1NEGATE\n                    // instead of a pushed ScriptNum payload 0x81.\n                    w.byte(OP['1NEGATE']);\n                    continue;\n                }\n                else if (1 <= o && o <= 16) {\n                    w.byte(OP.OP_1 - 1 + o);\n                    continue;\n                }\n            }\n            // Encode big numbers\n            if (typeof o === 'number')\n                o = ScriptNum().encode(BigInt(o));\n            abytes(o, undefined, 'value');\n            // Bytes\n            const len = o.length;\n            if (len < OP.PUSHDATA1)\n                w.byte(len);\n            else if (len <= 0xff) {\n                w.byte(OP.PUSHDATA1);\n                w.byte(len);\n            }\n            else if (len <= 0xffff) {\n                w.byte(OP.PUSHDATA2);\n                w.bytes(P.U16LE.encode(len));\n            }\n            else {\n                w.byte(OP.PUSHDATA4);\n                w.bytes(P.U32LE.encode(len));\n            }\n            w.bytes(o);\n        }\n    },\n    decodeStream: (r) => {\n        const out = [];\n        while (!r.isEnd()) {\n            const cur = r.byte();\n            const len = scriptPushLen(cur, (bytes) => {\n                if (bytes === 1)\n                    return P.U8.decodeStream(r);\n                if (bytes === 2)\n                    return P.U16LE.decodeStream(r);\n                return P.U32LE.decodeStream(r);\n            });\n            if (len !== undefined) {\n                out.push(r.bytes(len));\n            }\n            else if (cur === 0x00) {\n                out.push(0);\n            }\n            else if (OP.OP_1 <= cur && cur <= OP.OP_16) {\n                out.push(cur - (OP.OP_1 - 1));\n            }\n            else {\n                const op = OPNames[cur];\n                if (op === undefined)\n                    throw new Error(`Unknown opcode=${cur.toString(16)}`);\n                out.push(op);\n            }\n        }\n        return out;\n    },\n})))();\n/**\n * Bitcoin CompactSize integer coder.\n * @example\n * Encode a CompactSize integer for wire serialization.\n * ```ts\n * CompactSize.encode(1n);\n * ```\n */\nexport const CompactSize = /* @__PURE__ */ (() => {\n    // BTC specific variable length integer encoding\n    // https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer\n    const limits = {\n        0xfd: [0xfd, 2, BigInt(0xfd), BigInt(0xffff)],\n        0xfe: [0xfe, 4, BigInt(0x10000), BigInt(0xffffffff)],\n        0xff: [0xff, 8, BigInt(0x100000000), BigInt('0xffffffffffffffff')],\n    };\n    // Hoisted: Object.values() would otherwise allocate a fresh array on every encode.\n    const limitsList = Object.values(limits);\n    return Object.freeze(P.wrap({\n        encodeStream: (w, value) => {\n            if (typeof value === 'number')\n                value = BigInt(value);\n            if (_0n <= value && value <= COMPACT_DIRECT_MAX)\n                return w.byte(Number(value));\n            for (const [flag, bytes, start, stop] of limitsList) {\n                if (start > value || value > stop)\n                    continue;\n                w.byte(flag);\n                for (let i = 0; i < bytes; i++)\n                    w.byte(Number((value >> (_8n * BigInt(i))) & U8_MAX));\n                return;\n            }\n            throw w.err(`VarInt too big: ${value}`);\n        },\n        decodeStream: (r) => {\n            const b0 = r.byte();\n            if (b0 <= 0xfc)\n                return BigInt(b0);\n            const [_, bytes, start] = limits[b0];\n            let num = _0n;\n            for (let i = 0; i < bytes; i++)\n                num |= BigInt(r.byte()) << (_8n * BigInt(i));\n            // BIP 152 / BIP 174: CompactSize fields must use the shortest encoding,\n            // so wider prefixes for smaller values are rejected here.\n            if (num < start)\n                throw r.err(`Wrong CompactSize(${8 * bytes})`);\n            return num;\n        },\n    }));\n})();\n// Same thing, but in number instead of bigint. Checks for safe integer inside\n/**\n * CompactSize coder that decodes into JavaScript numbers.\n * @example\n * Use the number-based CompactSize helper when the value fits a JS number.\n * ```ts\n * CompactSizeLen.encode(1);\n * ```\n */\nexport const CompactSizeLen = /* @__PURE__ */ (() => Object.freeze(P.apply(CompactSize, P.coders.numberBigint)))();\n// ui8a of size <CompactSize>\n// Keep an unwrapped local coder for raw transaction structs. The exported VarBytes surface uses\n// TRet for declaration stability, but RawInput/RawOutput still need the old internal field shape.\nconst _VarBytes = /* @__PURE__ */ (() => Object.freeze(P.bytes(CompactSize)))();\n/**\n * Length-prefixed byte array coder.\n * @example\n * Prefix a byte array with its CompactSize length.\n * ```ts\n * VarBytes.encode(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const VarBytes = _VarBytes;\n// SegWit v0 stack of witness buffers\n// Raw witness serialization is reused across witness versions and PSBT\n// finalScriptWitness values; version-specific stack and element limits are\n// enforced by the spending rules, not by this byte codec.\n// Same split for raw witness stacks: export the wrapped surface, but keep the raw tx struct coder\n// on the unwrapped local alias so witness arrays inside RawTx keep their previous internal shape.\nconst _RawWitness = /* @__PURE__ */ (() => Object.freeze(P.array(CompactSizeLen, _VarBytes)))();\n/**\n * SegWit witness stack coder.\n * @example\n * Encode one witness stack for a SegWit input.\n * ```ts\n * RawWitness.encode([new Uint8Array([1])]);\n * ```\n */\nexport const RawWitness = _RawWitness;\n// Array of size <CompactSize>\n/**\n * Coder for CompactSize-prefixed arrays.\n * @param t - element coder\n * @returns Array coder.\n * @example\n * CompactSize-prefix a small list of fixed-width integers.\n * ```ts\n * import * as P from 'micro-packed';\n * import { BTCArray } from '@scure/btc-signer/script.js';\n * BTCArray(P.U8).encode([1, 2, 3]);\n * ```\n */\nexport const BTCArray = (t) => P.array(CompactSize, t);\n/**\n * Raw Bitcoin transaction input coder.\n * @example\n * Encode one transaction input exactly as it appears on the wire.\n * ```ts\n * import { hex } from '@scure/base';\n * import { RawInput } from '@scure/btc-signer/script.js';\n * RawInput.encode({\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n *   finalScriptSig: new Uint8Array([0x51]),\n *   sequence: 0xffffffff,\n * });\n * ```\n */\nexport const RawInput = /* @__PURE__ */ (() => Object.freeze(P.struct({\n    txid: P.bytes(32, true), // hash(prev_tx),\n    index: P.U32LE, // output number of previous tx\n    finalScriptSig: _VarBytes, // btc merges input and output script, executes it. If ok = tx passes\n    sequence: P.U32LE, // ?\n})))();\n/**\n * Raw Bitcoin transaction output coder.\n * @example\n * Encode one transaction output with amount and scriptPubKey.\n * ```ts\n * import { RawOutput } from '@scure/btc-signer/script.js';\n * RawOutput.encode({ amount: 1n, script: new Uint8Array([0x51]) });\n * ```\n */\nexport const RawOutput = /* @__PURE__ */ (() => Object.freeze(P.struct({ amount: P.U64LE, script: _VarBytes })))();\n// https://en.bitcoin.it/wiki/Protocol_documentation#tx\nconst _RawTx = /* @__PURE__ */ (() => P.struct({\n    version: P.I32LE,\n    segwitFlag: P.flag(new Uint8Array([0x00, 0x01])),\n    inputs: BTCArray(RawInput),\n    outputs: BTCArray(RawOutput),\n    // BIP144 does not encode a witness-count field; one RawWitness entry is\n    // implied for each txin and follows the same order as inputs.\n    witnesses: P.flagged('segwitFlag', P.array('inputs/length', _RawWitness)),\n    // < 500000000\tBlock number at which this transaction is unlocked\n    // >= 500000000\tUNIX timestamp at which this transaction is unlocked\n    // Handled as part of PSBTv2\n    lockTime: P.U32LE,\n}))();\nfunction validateRawTx(tx) {\n    // BIP 144: if every per-input witness field is empty, callers must use the old\n    // serialization format instead of the marker/flag witness form.\n    if (tx.segwitFlag && tx.witnesses && tx.witnesses.every((w) => !w.length))\n        throw new Error('Segwit flag with only empty witness fields');\n    return tx;\n}\n/**\n * Raw Bitcoin transaction coder.\n * @example\n * Encode a SegWit transaction with one input, one output, and one witness stack.\n * ```ts\n * import { hex } from '@scure/base';\n * import { RawTx } from '@scure/btc-signer/script.js';\n * RawTx.encode({\n *   version: 2,\n *   segwitFlag: true,\n *   inputs: [{\n *     txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *     index: 0,\n *     finalScriptSig: new Uint8Array(),\n *     sequence: 0xffffffff,\n *   }],\n *   outputs: [{ amount: 1n, script: new Uint8Array([0x51]) }],\n *   witnesses: [[new Uint8Array([1])]],\n *   lockTime: 0,\n * });\n * ```\n */\nexport const RawTx = /* @__PURE__ */ (() => Object.freeze(P.validate(_RawTx, validateRawTx)))();\n// Pre-SegWit serialization format (for PSBTv0)\n/**\n * Pre-SegWit transaction coder used by PSBTv0.\n * @example\n * Encode the legacy unsigned transaction format used inside PSBTv0 globals.\n * ```ts\n * import { hex } from '@scure/base';\n * import { RawOldTx } from '@scure/btc-signer/script.js';\n * RawOldTx.encode({\n *   version: 2,\n *   inputs: [{\n *     txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *     index: 0,\n *     finalScriptSig: new Uint8Array(),\n *     sequence: 0xffffffff,\n *   }],\n *   outputs: [{ amount: 1n, script: new Uint8Array([0x51]) }],\n *   lockTime: 0,\n * });\n * ```\n */\nexport const RawOldTx = /* @__PURE__ */ (() => Object.freeze(P.struct({\n    version: P.I32LE,\n    inputs: BTCArray(RawInput),\n    outputs: BTCArray(RawOutput),\n    lockTime: P.U32LE,\n})))();\n","import { hex } from '@scure/base';\nimport { anumber, concatBytes } from '@noble/hashes/utils.js';\nimport * as P from 'micro-packed';\nimport { CompactSize, CompactSizeLen, RawOldTx, RawOutput, RawTx, RawWitness, VarBytes, } from \"./script.js\";\nimport { aarray, compareBytes, equalBytes, PubT, validateObject, validatePubkey, } from \"./utils.js\";\nconst unknowns = (mode, name) => {\n    if (mode === true)\n        return 'ignore';\n    if (mode === false)\n        return 'strip';\n    if (mode === 'ignore' || mode === 'strip' || mode === 'strict')\n        return mode;\n    throw new Error(`PSBT: invalid ${name} policy=${mode}`);\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals.\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1);\n// BIP174 keydata only says \"public key\", so legacy PSBT ECDSA fields still accept both\n// compressed (33-byte) and uncompressed (65-byte) SEC1 encodings, but not x-only keys.\nconst PubKeyECDSA = /* @__PURE__ */ (() => P.validate(P.bytes(null), (pub) => validatePubkey(pub, PubT.ecdsa)))();\n// BIP32 serialized xpub payloads specifically store `ser_P(K)`, which is always the 33-byte\n// compressed SEC1 encoding of the public key rather than the looser legacy PSBT \"any ECDSA pubkey\".\nconst PubKeyECDSACompressed = /* @__PURE__ */ (() => P.validate(P.bytes(33), (pub) => validatePubkey(pub, PubT.ecdsa)))();\n// BIP371 taproot PSBT key fields use 32-byte x-only pubkeys, so this coder keeps the\n// fixed-length check and then reuses the shared Schnorr pubkey validator.\nconst PubKeySchnorr = /* @__PURE__ */ (() => P.validate(P.bytes(32), (pub) => validatePubkey(pub, PubT.schnorr)))();\n// BIP371 taproot signature fields carry the 64-byte Schnorr signature, plus an optional\n// trailing sighash byte when the signer used anything other than the default key-path mode.\nconst SignatureSchnorr = /* @__PURE__ */ (() => P.validate(P.bytes(null), (sig) => {\n    if (sig.length !== 64 && sig.length !== 65)\n        throw new Error('Schnorr signature should be 64 or 65 bytes long');\n    return sig;\n}))();\n// PSBTInput.finalScriptWitness should keep the historical decoded witness-stack shape even though\n// the exported RawWitness coder now uses TRet for declaration stability.\nconst RawWitnessWire = RawWitness;\n// BIP174 stores the 4-byte master fingerprint as-is, then appends each child index in\n// 32-bit little-endian order; cross-field checks like xpub depth matching live above this.\nconst BIP32Der = /* @__PURE__ */ (() => P.struct({\n    fingerprint: P.U32BE,\n    path: P.array(null, P.U32LE),\n}))();\n// BIP371 prepends the shared BIP32 derivation payload with the tapleaf-hash list; internal keys\n// use `hashes.length === 0`, while script-path keys list the leaves that actually use that pubkey.\nconst TaprootBIP32Der = /* @__PURE__ */ (() => P.struct({\n    hashes: P.array(CompactSizeLen, P.bytes(32)),\n    der: BIP32Der,\n}))();\n// BIP174 `PSBT_GLOBAL_XPUB` says the key is \"The 78 byte serialized extended public key as\n// defined by BIP 32\", so decode it to the actual BIP32 field layout instead of preserving an\n// opaque blob. We intentionally do not hardcode version-byte policy here because BIP32 version\n// bytes vary by network / deployment; this layer just parses the field and enforces the BIP32\n// import rules that are independent of network selection.\nconst GlobalXPUB = /* @__PURE__ */ (() => P.validate(P.struct({\n    version: P.U32BE,\n    depth: P.U8,\n    parentFingerprint: P.U32BE,\n    childNumber: P.U32BE,\n    chainCode: P.bytes(32),\n    // BIP32 serialization stores the public key as the final 33-byte `ser_P(K)` field and says\n    // importing an extended public key must verify that point data corresponds to the curve.\n    publicKey: PubKeyECDSACompressed,\n}), (xpub) => {\n    // BIP32 serialization says master nodes use depth 0 with zero parent\n    // fingerprint and zero child number. The invalid examples explicitly\n    // include zero-depth xpubs with either field non-zero.\n    if (xpub.depth === 0 && xpub.parentFingerprint !== 0)\n        throw new Error('GlobalXPUB: depth=0 requires parentFingerprint=0');\n    if (xpub.depth === 0 && xpub.childNumber !== 0)\n        throw new Error('GlobalXPUB: depth=0 requires childNumber=0');\n    return xpub;\n}))();\n// BIP371 puts the x-only pubkey and leaf hash into the key side of `PSBT_IN_TAP_SCRIPT_SIG`;\n// the actual 64/65-byte Schnorr signature stays in the value side under `SignatureSchnorr`.\nconst tapScriptSigKey = /* @__PURE__ */ (() => P.struct({ pubKey: PubKeySchnorr, leafHash: P.bytes(32) }))();\n// Complex structure for PSBT fields\n// <control byte with leaf version and parity bit> <internal key p> <C> <E> <AB>\n// Raw BIP341 control-block layout only; the exported TaprootControlBlock wrapper adds the\n// `0..128` Merkle-depth bound, and later taproot logic checks version/parity semantics.\nconst _TaprootControlBlock = /* @__PURE__ */ (() => P.struct({\n    version: P.U8, // With parity :(\n    internalKey: P.bytes(32),\n    merklePath: P.array(null, P.bytes(32)),\n}))();\n/**\n * Taproot control block coder.\n * @example\n * Encode the Taproot control block attached to a script-path witness.\n * ```ts\n * import { TaprootControlBlock } from '@scure/btc-signer/psbt.js';\n * import { pubSchnorr, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * TaprootControlBlock.encode({\n *   version: 0xc0,\n *   internalKey: pubSchnorr(randomPrivateKeyBytes()),\n *   merklePath: [],\n * });\n * ```\n */\nexport const TaprootControlBlock = /* @__PURE__ */ (() => Object.freeze(P.validate(_TaprootControlBlock, (cb) => {\n    // BIP 341 control blocks are raw 33+32m byte records; this PSBT coder only enforces\n    // the length/depth shape here and leaves curve / leaf-version validation to taproot logic.\n    if (cb.merklePath.length > 128)\n        throw new Error('TaprootControlBlock: merklePath should be of length 0..128 (inclusive)');\n    return cb;\n})))();\n// BIP371 says PSBT_OUT_TAP_TREE is one or more tuples in DFS order so the Taproot tree can be\n// reconstructed. Validate both the non-empty requirement and that the leaf-depth sequence really\n// describes a complete left-to-right DFS walk of a binary tree, not just arbitrary tuples.\n// {<8-bit uint depth> <8-bit uint leaf version> <compact size uint scriptlen> <bytes script>}*\nconst tapTree = /* @__PURE__ */ (() => P.validate(P.array(null, P.struct({\n    depth: P.U8,\n    version: P.U8,\n    script: VarBytes,\n})), (tree) => {\n    if (tree.length < 1)\n        throw new Error('tapTree: expected at least one tuple');\n    let path = Array(tree[0].depth).fill(0);\n    let maxDepth = tree[0].depth;\n    for (let i = 1; i < tree.length; i++) {\n        const { depth } = tree[i];\n        if (depth > maxDepth)\n            maxDepth = depth;\n        let j = path.length - 1;\n        while (j >= 0 && path[j] === 1)\n            j--;\n        if (j < 0)\n            throw new Error('tapTree: tuples must be in DFS order');\n        const next = path.slice(0, j);\n        next.push(1);\n        if (depth < next.length)\n            throw new Error('tapTree: tuples must be in DFS order');\n        while (next.length < depth)\n            next.push(0);\n        path = next;\n    }\n    let leaves = _0n;\n    for (let i = 0; i < tree.length; i++)\n        leaves += _1n << BigInt(maxDepth - tree[i].depth);\n    if (leaves !== _1n << BigInt(maxDepth))\n        throw new Error('tapTree: tuples must describe a complete binary tree');\n    return tree;\n}))();\n// Shared raw PSBT byte payload coder for fields whose BIP174 value format is just opaque bytes;\n// field-specific structure and length checks still live at the individual field definitions.\n// Keep a distinct name here so the byte coder does not collide with the Bytes type alias.\nconst BytesInf = /* @__PURE__ */ P.bytes(null);\n// PSBTKeyMap emits the 0xfc type byte itself, so the public value remains only the bytes after it.\n// Validate that raw suffix here: otherwise a caller-supplied leading 0xfc becomes a 252-byte\n// identifier declaration which scure can relay but Bitcoin Core cannot parse.\nconst ProprietaryKey = /* @__PURE__ */ (() => {\n    const suffix = P.struct({\n        identifier: P.bytes(CompactSizeLen),\n        subtype: CompactSizeLen,\n        data: BytesInf,\n    });\n    return P.validate(BytesInf, (key) => {\n        try {\n            suffix.decode(key);\n        }\n        catch (error) {\n            const message = error instanceof Error ? error.message : String(error);\n            throw new Error(`Proprietary key: expected BIP174 identifier and subtype, got ${message}`);\n        }\n        return key;\n    });\n})();\n// Shared 20-byte key-data helper for the BIP174 RIPEMD160 and HASH160 preimage maps.\nconst Bytes20 = /* @__PURE__ */ P.bytes(20);\n// Shared 32-byte helper for fixed-size hash / txid / merkle-root byte fields; any stronger\n// semantics such as x-only pubkey validity still need to be enforced by the field that uses it.\nconst Bytes32 = /* @__PURE__ */ P.bytes(32);\nconst Bytes64 = /* @__PURE__ */ P.bytes(64);\nconst Bytes66 = /* @__PURE__ */ P.bytes(66);\n// BIP373 uses the same aggregate-key participant list in input and output maps.\nconst MuSig2Participants = /* @__PURE__ */ (() => P.array(null, PubKeyECDSACompressed))();\n// BIP373 keys append an optional tapleaf hash to participant || aggregate. A structured key keeps\n// the optional hash distinct while preserving the exact 66/98-byte wire encoding.\nconst MuSig2Key = /* @__PURE__ */ (() => P.apply(BytesInf, {\n    decode: (key) => {\n        const _key = key;\n        return concatBytes(PubKeyECDSACompressed.encode(_key.participantPubkey), PubKeyECDSACompressed.encode(_key.aggregatePubkey), _key.leafHash === undefined ? P.EMPTY : Bytes32.encode(_key.leafHash));\n    },\n    encode: (raw) => {\n        const _raw = raw;\n        if (_raw.length !== 66 && _raw.length !== 98)\n            throw new Error(`MuSig2 key: expected 66 or 98 bytes, got ${_raw.length}`);\n        const key = {\n            participantPubkey: PubKeyECDSACompressed.decode(_raw.subarray(0, 33)),\n            aggregatePubkey: PubKeyECDSACompressed.decode(_raw.subarray(33, 66)),\n        };\n        if (_raw.length === 98)\n            key.leafHash = Bytes32.decode(_raw.subarray(66));\n        return key;\n    },\n}))();\nconst SilentPaymentInfo = /* @__PURE__ */ (() => P.struct({ scanKey: PubKeyECDSACompressed, spendKey: PubKeyECDSACompressed }))();\n// BIP353 prefixes the human-readable name with one byte; the RFC9102 proof is opaque here.\nconst DNSSECProof = /* @__PURE__ */ (() => P.struct({ name: P.bytes(P.U8), proof: BytesInf }))();\n// jsbt mutate checks exported PSBT tables recursively, so freeze each field tuple and its\n// nested version arrays here while preserving the original coder slot types for local inference.\nconst PSBTInfo = (type, kc, vc, reqInc, allowInc, silentIgnore) => \n/* @__PURE__ */ Object.freeze([\n    type,\n    kc && typeof kc === 'object' ? Object.freeze(kc) : kc,\n    vc && typeof vc === 'object' ? Object.freeze(vc) : vc,\n    Object.freeze([...reqInc]),\n    Object.freeze([...allowInc]),\n    silentIgnore,\n]);\n// versionsRequiringExclusing = !versionsAllowsInclusion (as set)\n// {name: [tag, keyCoder, valueCoder, versionsRequiringInclusion,\n// versionsRequiringExclusing, versionsAllowsInclusion, silentIgnore]}\n// SilentIgnore: we use some v2 fields for v1 representation too,\n// so we just clean them before serialize.\n// Tables from BIP-0174 (https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki)\n// prettier-ignore\n/**\n * PSBT global key definitions.\n * @example\n * Keep only the fields that are valid for the target PSBT version before serializing.\n * ```ts\n * import { PSBTGlobal, cleanPSBTFields } from '@scure/btc-signer/psbt.js';\n * cleanPSBTFields(2, PSBTGlobal, { txVersion: 2, inputCount: 1, outputCount: 1 });\n * ```\n */\nexport const PSBTGlobal = /* @__PURE__ */ (() => Object.freeze({\n    unsignedTx: PSBTInfo(0x00, false, RawOldTx, [0], [0], false),\n    // BIP174 also requires the serialized xpub depth to match the number of path elements in the\n    // paired derivation value, so callers still need that cross-field check above this raw table.\n    xpub: PSBTInfo(0x01, GlobalXPUB, BIP32Der, [], [0, 2], false),\n    txVersion: PSBTInfo(0x02, false, P.U32LE, [2], [2], false),\n    fallbackLocktime: PSBTInfo(0x03, false, P.U32LE, [], [2], false),\n    inputCount: PSBTInfo(0x04, false, CompactSizeLen, [2], [2], false),\n    outputCount: PSBTInfo(0x05, false, CompactSizeLen, [2], [2], false),\n    // TODO: bitfield\n    txModifiable: PSBTInfo(0x06, false, P.U8, [], [2], false),\n    // These assigned extension fields must not fall through the unknown-field policy.\n    spEcdhShare: PSBTInfo(0x07, PubKeyECDSACompressed, PubKeyECDSACompressed, [], [2], false),\n    spDleq: PSBTInfo(0x08, PubKeyECDSACompressed, Bytes64, [], [2], false),\n    genericSignedMessage: PSBTInfo(0x09, false, BytesInf, [], [0, 2], false),\n    version: PSBTInfo(0xfb, false, P.U32LE, [], [0, 2], false),\n    proprietary: PSBTInfo(0xfc, ProprietaryKey, BytesInf, [], [0, 2], false),\n}))();\n// prettier-ignore\n/**\n * PSBT input key definitions.\n * @example\n * Strip input fields that do not belong in the requested PSBT version.\n * ```ts\n * import { hex } from '@scure/base';\n * import { PSBTInput, cleanPSBTFields } from '@scure/btc-signer/psbt.js';\n * cleanPSBTFields(2, PSBTInput, {\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n *   witnessUtxo: { amount: 2n, script: new Uint8Array([0x51]) },\n * });\n * ```\n */\nexport const PSBTInput = /* @__PURE__ */ (() => Object.freeze({\n    nonWitnessUtxo: PSBTInfo(0x00, false, RawTx, [], [0, 2], false),\n    witnessUtxo: PSBTInfo(0x01, false, RawOutput, [], [0, 2], false),\n    partialSig: PSBTInfo(0x02, PubKeyECDSA, BytesInf, [], [0, 2], false),\n    sighashType: PSBTInfo(0x03, false, P.U32LE, [], [0, 2], false),\n    redeemScript: PSBTInfo(0x04, false, BytesInf, [], [0, 2], false),\n    witnessScript: PSBTInfo(0x05, false, BytesInf, [], [0, 2], false),\n    bip32Derivation: PSBTInfo(0x06, PubKeyECDSA, BIP32Der, [], [0, 2], false),\n    finalScriptSig: PSBTInfo(0x07, false, BytesInf, [], [0, 2], false),\n    finalScriptWitness: PSBTInfo(0x08, false, RawWitnessWire, [], [0, 2], false),\n    porCommitment: PSBTInfo(0x09, false, BytesInf, [], [0, 2], false),\n    ripemd160: PSBTInfo(0x0a, Bytes20, BytesInf, [], [0, 2], false),\n    sha256: PSBTInfo(0x0b, Bytes32, BytesInf, [], [0, 2], false),\n    hash160: PSBTInfo(0x0c, Bytes20, BytesInf, [], [0, 2], false),\n    hash256: PSBTInfo(0x0d, Bytes32, BytesInf, [], [0, 2], false),\n    // BIP174/BIP370 serialize PREVIOUS_TXID in standard byte order, while the rest of this repo\n    // historically keeps TransactionInput.txid in display-order bytes matching `Transaction.id`.\n    // Reverse at this PSBTv2 boundary so internal txid semantics stay aligned with the raw-tx path.\n    txid: PSBTInfo(0x0e, false, P.bytes(32, true), [2], [2], true),\n    index: PSBTInfo(0x0f, false, P.U32LE, [2], [2], true),\n    sequence: PSBTInfo(0x10, false, P.U32LE, [], [2], true),\n    requiredTimeLocktime: PSBTInfo(0x11, false, P.U32LE, [], [2], false),\n    requiredHeightLocktime: PSBTInfo(0x12, false, P.U32LE, [], [2], false),\n    tapKeySig: PSBTInfo(0x13, false, SignatureSchnorr, [], [0, 2], false),\n    tapScriptSig: PSBTInfo(0x14, tapScriptSigKey, SignatureSchnorr, [], [0, 2], false),\n    tapLeafScript: PSBTInfo(0x15, TaprootControlBlock, BytesInf, [], [0, 2], false),\n    // BIP371 key data here is a 32-byte x-only pubkey, so reuse the shared Schnorr pubkey coder\n    // instead of accepting arbitrary 32-byte blobs that only fail much later in taproot flows.\n    tapBip32Derivation: PSBTInfo(0x16, PubKeySchnorr, TaprootBIP32Der, [], [0, 2], false),\n    tapInternalKey: PSBTInfo(0x17, false, PubKeySchnorr, [], [0, 2], false),\n    tapMerkleRoot: PSBTInfo(0x18, false, Bytes32, [], [0, 2], false),\n    p2cKeyTweak: PSBTInfo(0x19, PubKeyECDSACompressed, Bytes32, [], [0, 2], false),\n    musig2ParticipantPubkeys: PSBTInfo(0x1a, PubKeyECDSACompressed, MuSig2Participants, [], [0, 2], false),\n    musig2PubNonce: PSBTInfo(0x1b, MuSig2Key, Bytes66, [], [0, 2], false),\n    musig2PartialSig: PSBTInfo(0x1c, MuSig2Key, Bytes32, [], [0, 2], false),\n    spEcdhShare: PSBTInfo(0x1d, PubKeyECDSACompressed, PubKeyECDSACompressed, [], [2], false),\n    spDleq: PSBTInfo(0x1e, PubKeyECDSACompressed, Bytes64, [], [2], false),\n    spSpendBip32Derivation: PSBTInfo(0x1f, PubKeyECDSACompressed, BIP32Der, [], [2], false),\n    spTweak: PSBTInfo(0x20, false, Bytes32, [], [2], false),\n    proprietary: PSBTInfo(0xfc, ProprietaryKey, BytesInf, [], [0, 2], false),\n}))();\n// All other keys removed when finalizing\n/**\n * Input fields preserved after finalization.\n * @example\n * Use the allowlist when stripping transient signing fields after finalization.\n * ```ts\n * import { PSBTInputFinalKeys } from '@scure/btc-signer/psbt.js';\n * const finalKeys = new Set(PSBTInputFinalKeys);\n * finalKeys.has('finalScriptWitness');\n * ```\n */\nexport const PSBTInputFinalKeys = /* @__PURE__ */ Object.freeze([\n    // PSBTv2 extractors rebuild the final transaction from per-input fields, so\n    // finalized inputs still need txid/index, any non-default sequence, and locktime requirements\n    // even though BIP174's generic cleanup is stricter.\n    'txid',\n    'sequence',\n    'index',\n    'witnessUtxo',\n    'nonWitnessUtxo',\n    'requiredTimeLocktime',\n    'requiredHeightLocktime',\n    'finalScriptSig',\n    'finalScriptWitness',\n    'unknown',\n]);\n/**\n * Signature and final-satisfaction fields used while reopening a finalized input.\n * @example\n * Finalized inputs may remove their existing satisfaction before further mutation.\n * ```ts\n * import { PSBTInputSignatureKeys } from '@scure/btc-signer/psbt.js';\n * const mutableKeys = new Set(PSBTInputSignatureKeys);\n * mutableKeys.has('tapScriptSig');\n * ```\n */\nexport const PSBTInputSignatureKeys = /* @__PURE__ */ Object.freeze([\n    'partialSig',\n    'finalScriptSig',\n    'finalScriptWitness',\n    'tapKeySig',\n    'tapScriptSig',\n]);\n/**\n * A static list cannot describe mutable input fields because that depends on each signature's\n * algorithm, sighash, and target index.\n * @deprecated Use {@link PSBTInputSignatureKeys} only for signature/final-satisfaction records;\n * transaction mutation is enforced by {@link Transaction.updateInput}.\n */\nexport const PSBTInputUnsignedKeys = PSBTInputSignatureKeys;\n// prettier-ignore\n/**\n * PSBT output key definitions.\n * @example\n * Strip output fields that are not valid for the target PSBT version.\n * ```ts\n * import { PSBTOutput, cleanPSBTFields } from '@scure/btc-signer/psbt.js';\n * cleanPSBTFields(2, PSBTOutput, { amount: 2n, script: new Uint8Array([0x51]) });\n * ```\n */\nexport const PSBTOutput = /* @__PURE__ */ (() => Object.freeze({\n    redeemScript: PSBTInfo(0x00, false, BytesInf, [], [0, 2], false),\n    witnessScript: PSBTInfo(0x01, false, BytesInf, [], [0, 2], false),\n    bip32Derivation: PSBTInfo(0x02, PubKeyECDSA, BIP32Der, [], [0, 2], false),\n    // BIP174/BIP370 serialize PSBT_OUT_AMOUNT as a signed int64 on the wire; semantic output\n    // validity still rejects negative transaction amounts in `PSBTOutputCoder` below.\n    amount: PSBTInfo(0x03, false, P.I64LE, [2], [2], true),\n    script: PSBTInfo(0x04, false, BytesInf, [2], [2], true),\n    tapInternalKey: PSBTInfo(0x05, false, PubKeySchnorr, [], [0, 2], false),\n    // BIP371 expects a non-empty DFS-ordered list of tapleaf tuples here so wallets can\n    // reconstruct the same Taproot tree, not just an arbitrary list of serialized leaves.\n    tapTree: PSBTInfo(0x06, false, tapTree, [], [0, 2], false),\n    tapBip32Derivation: PSBTInfo(0x07, PubKeySchnorr, TaprootBIP32Der, [], [0, 2], false),\n    musig2ParticipantPubkeys: PSBTInfo(0x08, PubKeyECDSACompressed, MuSig2Participants, [], [0, 2], false),\n    spV0Info: PSBTInfo(0x09, false, SilentPaymentInfo, [], [2], false),\n    spV0Label: PSBTInfo(0x0a, false, P.U32LE, [], [2], false),\n    dnssecProof: PSBTInfo(0x35, false, DNSSECProof, [], [0, 2], false),\n    proprietary: PSBTInfo(0xfc, ProprietaryKey, BytesInf, [], [0, 2], false),\n}))();\n// Can be modified even on signed input\n/**\n * Output fields that may still change after signing starts.\n * @example\n * PSBTv2 outputs are fully committed once signing starts, so the set stays empty.\n * ```ts\n * import { PSBTOutputUnsignedKeys } from '@scure/btc-signer/psbt.js';\n * const mutableKeys = new Set(PSBTOutputUnsignedKeys);\n * mutableKeys.size; // 0\n * ```\n */\nexport const PSBTOutputUnsignedKeys = /* @__PURE__ */ Object.freeze([]);\n// Signed outputs have no replace/remove exceptions: once a signature actually commits to a given\n// output, every field on that output is frozen. SIGHASH_NONE leaves outputs fully mutable, and\n// SIGHASH_SINGLE only freezes the matching output index.\n// Raw BIP174 keypair framing only: `<key><value>` records terminated by `0x00`.\n// Uniqueness, keyed-vs-unkeyed rules, and per-type decoding live one layer up in `PSBTKeyMap`.\nconst PSBTKeyPair = /* @__PURE__ */ (() => P.array(P.NULL, P.struct({\n    //  <key> := <keylen> <keytype> <keydata> WHERE keylen = len(keytype)+len(keydata)\n    key: P.prefix(CompactSizeLen, P.struct({ type: CompactSizeLen, key: P.bytes(null) })),\n    //  <value> := <valuelen> <valuedata>\n    value: P.bytes(CompactSizeLen),\n})))();\nfunction PSBTKeyInfo(info) {\n    // Name the tuple slots once so version-filter helpers do not depend on raw positional indexing.\n    const [type, kc, vc, reqInc, allowInc, silentIgnore] = info;\n    return { type, kc, vc, reqInc, allowInc, silentIgnore };\n}\nconst PSBTUnknownKey = /* @__PURE__ */ (() => \n// Raw unknown/proprietary field key: compact-size keytype plus opaque keydata for pass-through.\nP.struct({ type: CompactSizeLen, key: P.bytes(null) }))();\n// Key cannot be 'unknown', value coder cannot be array for elements with empty key\nfunction PSBTKeyMap(psbtEnum) {\n    // -> Record<type, [keyName, ...coders]>\n    const byType = {};\n    for (const k in psbtEnum) {\n        const [num, kc, vc] = psbtEnum[k];\n        byType[num] = [k, kc, vc];\n    }\n    return P.wrap({\n        encodeStream: (w, value) => {\n            const _value = value;\n            let out = [];\n            const seen = {};\n            const add = (key, value) => {\n                const _value = value;\n                // BIP174 defines `<key> := <keylen> <keytype> <keydata>` and says repeated `<keytype>`\n                // entries are allowed within one `<map>` as long as the full `<key>` stays unique.\n                // `<keylen>` is derived from `<keytype><keydata>`, so `PSBTUnknownKey` is enough here.\n                const kStr = hex.encode(PSBTUnknownKey.encode(key));\n                if (seen[kStr])\n                    throw new Error(`PSBT: duplicate key=${kStr}`);\n                seen[kStr] = true;\n                out.push({ key, value: _value });\n            };\n            // Because we use order of psbtEnum, keymap is sorted here\n            for (const name in psbtEnum) {\n                const val = _value[name];\n                if (val === undefined)\n                    continue;\n                const [type, kc, vc] = psbtEnum[name];\n                if (!kc) {\n                    add({ type, key: P.EMPTY }, vc.encode(val));\n                }\n                else {\n                    // BIP174 allows repeated `<keytype>` values inside one `<map>`, but the full `<key>`\n                    // must stay unique, so keyed rows are sorted and then deduped by serialized key bytes.\n                    const kv = val.map(([k, v]) => [\n                        kc.encode(k),\n                        vc.encode(v),\n                    ]);\n                    // sort by keys\n                    kv.sort((a, b) => compareBytes(a[0], b[0]));\n                    for (const [key, value] of kv)\n                        add({ key, type }, value);\n                }\n            }\n            if (_value.unknown) {\n                _value.unknown.sort((a, b) => compareBytes(a[0].key, b[0].key));\n                for (const [k, v] of _value.unknown)\n                    add(k, v);\n            }\n            PSBTKeyPair.encodeStream(w, out);\n        },\n        decodeStream: (r) => {\n            const raw = PSBTKeyPair.decodeStream(r);\n            const out = {};\n            const noKey = {};\n            const seen = {};\n            for (const elm of raw) {\n                const kStr = hex.encode(PSBTUnknownKey.encode(elm.key));\n                if (seen[kStr])\n                    throw new Error(`PSBT: duplicate key=${kStr}`);\n                seen[kStr] = true;\n                let name = 'unknown';\n                let key = elm.key.key;\n                let value = elm.value;\n                if (byType[elm.key.type]) {\n                    const [_name, kc, vc] = byType[elm.key.type];\n                    name = _name;\n                    if (!kc && key.length) {\n                        throw new Error(`PSBT: Non-empty key for ${name} (key=${hex.encode(key)} value=${hex.encode(value)}`);\n                    }\n                    key = kc ? kc.decode(key) : undefined;\n                    value = vc.decode(value);\n                    if (!kc) {\n                        if (out[name])\n                            throw new Error(`PSBT: Same keys: ${name} (key=${key} value=${value})`);\n                        out[name] = value;\n                        noKey[name] = true;\n                        continue;\n                    }\n                }\n                else {\n                    // For unknown: add key type inside key\n                    key = { type: elm.key.type, key: elm.key.key };\n                }\n                // Only keyed elements at this point.\n                // BIP174 uniqueness is over the full serialized `<key>` bytes within one map, not only keytype.\n                // Empty-key rows are rejected above; keyed duplicates need an explicit check before this append path.\n                if (noKey[name])\n                    throw new Error(`PSBT: Key type with empty key and no key=${name} val=${value}`);\n                if (!out[name])\n                    out[name] = [];\n                out[name].push([key, value]);\n            }\n            return out;\n        },\n    });\n}\n/**\n * Validated PSBT input coder.\n * @example\n * Validate a decoded PSBT input before serializing it back to bytes.\n * ```ts\n * import { hex } from '@scure/base';\n * import { PSBTInputCoder } from '@scure/btc-signer/psbt.js';\n * PSBTInputCoder.encode({\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n *   witnessUtxo: { amount: 1n, script: new Uint8Array([0x51]) },\n * });\n * ```\n */\nexport const PSBTInputCoder = /* @__PURE__ */ (() => Object.freeze(P.validate(PSBTKeyMap(PSBTInput), (i) => {\n    // This wrapper adds input-level invariants after raw PSBT key-map decoding.\n    // Row-level key validation and duplicate-key rejection still depend on the underlying table/map helpers.\n    if (i.finalScriptWitness && !i.finalScriptWitness.length)\n        throw new Error('validateInput: empty finalScriptWitness');\n    //if (i.finalScriptSig && !i.finalScriptSig.length) throw new Error('validateInput: empty finalScriptSig');\n    if (i.partialSig && !i.partialSig.length)\n        throw new Error('Empty partialSig');\n    if (i.partialSig)\n        for (const [k] of i.partialSig)\n            validatePubkey(k, PubT.ecdsa);\n    if (i.bip32Derivation)\n        for (const [k] of i.bip32Derivation)\n            validatePubkey(k, PubT.ecdsa);\n    // Locktime = unsigned little endian integer greater than or equal to 500000000 representing\n    if (i.requiredTimeLocktime !== undefined && i.requiredTimeLocktime < 500000000)\n        throw new Error(`validateInput: wrong timeLocktime=${i.requiredTimeLocktime}`);\n    // unsigned little endian integer greater than 0 and less than 500000000\n    if (i.requiredHeightLocktime !== undefined &&\n        (i.requiredHeightLocktime <= 0 || i.requiredHeightLocktime >= 500000000))\n        throw new Error(`validateInput: wrong heighLocktime=${i.requiredHeightLocktime}`);\n    if (i.tapLeafScript) {\n        // tap leaf version appears here twice: in control block and at the end of script\n        for (const [k, v] of i.tapLeafScript) {\n            if ((k.version & 0b1111_1110) !== v[v.length - 1])\n                throw new Error('validateInput: tapLeafScript version mimatch');\n            if (v[v.length - 1] & 1)\n                throw new Error('validateInput: tapLeafScript version has parity bit!');\n        }\n    }\n    return i;\n})))();\n/**\n * Validated PSBT output coder.\n * @example\n * Validate a decoded PSBT output before serializing it back to bytes.\n * ```ts\n * import { PSBTOutputCoder } from '@scure/btc-signer/psbt.js';\n * PSBTOutputCoder.encode({ amount: 1n, script: new Uint8Array([0x51]) });\n * ```\n */\nexport const PSBTOutputCoder = /* @__PURE__ */ (() => Object.freeze(P.validate(PSBTKeyMap(PSBTOutput), (o) => {\n    // This wrapper only adds output-level invariants after raw key-map decoding.\n    // Duplicate-key rejection still depends on the key-map helper; tapTree structure is validated\n    // in the field coder itself because BIP371 constrains the tuple value, not just the row shape.\n    // BIP174/BIP370 define PSBT_OUT_AMOUNT as a signed int64 transport field, but it still\n    // represents the transaction output amount in satoshis, so negative output values are invalid.\n    if (o.amount !== undefined && o.amount < _0n)\n        throw new Error(`validateOutput: wrong amount=${o.amount}`);\n    if (o.bip32Derivation)\n        for (const [k] of o.bip32Derivation)\n            validatePubkey(k, PubT.ecdsa);\n    return o;\n})))();\nconst PSBTGlobalCoder = /* @__PURE__ */ (() => P.validate(PSBTKeyMap(PSBTGlobal), (g) => {\n    // This wrapper adds the BIP174/BIP370 cross-field invariants after raw global key-map decoding.\n    // `PSBT_GLOBAL_XPUB` stores the serialized xpub plus a separate derivation value, and BIP174\n    // says the number of 32-bit indexes in that derivation path must match the xpub depth.\n    const version = g.version || 0;\n    if (version === 0) {\n        if (!g.unsignedTx)\n            throw new Error('PSBTv0: missing unsignedTx');\n        for (const inp of g.unsignedTx.inputs)\n            if (inp.finalScriptSig && inp.finalScriptSig.length)\n                throw new Error('PSBTv0: input scriptSig found in unsignedTx');\n    }\n    for (const [xpub, der] of g.xpub || []) {\n        if (xpub.depth !== der.path.length)\n            throw new Error(`PSBT_GLOBAL_XPUB: xpub depth=${xpub.depth} must match derivation path length=${der.path.length}`);\n    }\n    return g;\n}))();\nexport const _RawPSBTV0 = /* @__PURE__ */ (() => Object.freeze(P.struct({\n    magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),\n    global: PSBTGlobalCoder,\n    // Raw v0 framing follows the unsigned transaction for input-map count; the stricter\n    // one-map-per-input/output reconciliation happens in `RawPSBTV0` / `validatePSBT`.\n    inputs: P.array('global/unsignedTx/inputs/length', PSBTInputCoder),\n    outputs: P.array(null, PSBTOutputCoder),\n})))();\nexport const _RawPSBTV2 = /* @__PURE__ */ (() => Object.freeze(P.struct({\n    magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),\n    global: PSBTGlobalCoder,\n    // Raw v2 framing takes map counts from the global PSBTv2 count fields; deeper version\n    // and per-field validation still happens in `RawPSBTV2` / `validatePSBT`.\n    inputs: P.array('global/inputCount', PSBTInputCoder),\n    outputs: P.array('global/outputCount', PSBTOutputCoder),\n})))();\nexport const _DebugPSBT = /* @__PURE__ */ (() => Object.freeze(P.struct({\n    magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),\n    // Debug-only normalized view: maps become plain objects, so key order is intentionally ignored\n    // and duplicate keys fail while decoding instead of being preserved for byte-level diagnostics.\n    // Each `items[i]` is one raw PSBT map (`global`, then inputs, then outputs), keyed by the\n    // full serialized PSBT key bytes as hex rather than decoded field names.\n    items: P.array(null, P.apply(P.array(P.NULL, P.tuple([P.hex(CompactSizeLen), P.bytes(CompactSize)])), P.coders.dict())),\n})))();\nfunction validatePSBTFields(version, info, lst) {\n    const _lst = lst;\n    // Enforce the BIP174/BIP370 field-table columns directly: reject rows whose\n    // \"Versions Allowing Inclusion\" excludes this version and require rows whose\n    // \"Versions Requiring Inclusion\" includes it.\n    for (const k in _lst) {\n        if (k === 'unknown')\n            continue;\n        if (!info[k])\n            continue;\n        const { allowInc } = PSBTKeyInfo(info[k]);\n        if (!allowInc.includes(version))\n            throw new Error(`PSBTv${version}: field ${k} is not allowed`);\n    }\n    for (const k in info) {\n        const { reqInc } = PSBTKeyInfo(info[k]);\n        if (reqInc.includes(version) && _lst[k] === undefined)\n            throw new Error(`PSBTv${version}: missing required field ${k}`);\n    }\n}\n/**\n * Removes fields that are not valid for the requested PSBT version.\n * @param version - target PSBT version\n * @param info - PSBT field definition table\n * @param lst - decoded PSBT key map\n * @returns Filtered PSBT key map.\n * @throws If a field cannot be serialized in the requested PSBT version. {@link Error}\n * @example\n * Drop fields that are not allowed in the target PSBT version before encoding.\n * ```ts\n * import { hex } from '@scure/base';\n * import { PSBTInput, cleanPSBTFields } from '@scure/btc-signer/psbt.js';\n * cleanPSBTFields(2, PSBTInput, {\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n * });\n * ```\n */\nexport function cleanPSBTFields(version, info, lst) {\n    anumber(version, 'version');\n    validateObject(info, {}, {}, 'info');\n    validateObject(lst, {}, {}, 'lst');\n    const _lst = lst;\n    const out = {};\n    for (const _k in _lst) {\n        const k = _k;\n        // Serializer-side compatibility filter: preserve unknown pass-through fields, silently drop\n        // rows explicitly marked `silentIgnore`, and throw on other rows the target version forbids.\n        if (k !== 'unknown') {\n            if (!info[k])\n                continue;\n            const { allowInc, silentIgnore } = PSBTKeyInfo(info[k]);\n            if (!allowInc.includes(version)) {\n                if (silentIgnore)\n                    continue;\n                throw new Error(`Failed to serialize in PSBTv${version}: ${k} but versions allows inclusion=${allowInc}`);\n            }\n        }\n        out[k] = _lst[k];\n    }\n    return out;\n}\nfunction validatePSBT(tx) {\n    const version = (tx && tx.global && tx.global.version) || 0;\n    validatePSBTFields(version, PSBTGlobal, tx.global);\n    for (const i of tx.inputs)\n        validatePSBTFields(version, PSBTInput, i);\n    for (const o of tx.outputs)\n        validatePSBTFields(version, PSBTOutput, o);\n    // BIP174 defines `<psbt> := <magic> <global-map> <input-map>* <output-map>*`, so after decode the\n    // number of input/output maps should match the unsigned tx. PSBTv2 makes the same shape explicit\n    // through `inputCount` / `outputCount`. Input maps are count-framed and must match exactly.\n    const inputCount = !version ? tx.global.unsignedTx.inputs.length : tx.global.inputCount;\n    if (tx.inputs.length !== inputCount)\n        throw new Error(`Wrong number of input maps=${tx.inputs.length}, expected=${inputCount}`);\n    // PSBTv0 compatibility mode may append exactly one empty output map when the unsigned\n    // transaction has no outputs. bip174js additionally inserts an empty input map when there are\n    // no inputs; count-framing makes that map appear before the real output maps in this array.\n    // PSBTv2 map counts remain strict.\n    const outputCount = !version ? tx.global.unsignedTx.outputs.length : tx.global.outputCount;\n    if (tx.outputs.length < outputCount)\n        throw new Error('Not outputs inputs');\n    const hasBip174InputMap = version === 0 &&\n        inputCount === 0 &&\n        Object.keys(tx.outputs[0] || {}).length === 0 &&\n        ((outputCount > 0 && tx.outputs.length === outputCount + 1) ||\n            (outputCount === 0 && tx.outputs.length === 2 && Object.keys(tx.outputs[1]).length === 0));\n    if (hasBip174InputMap)\n        return tx;\n    const outputsLeft = tx.outputs.slice(outputCount);\n    if (outputsLeft.length > 1 ||\n        (outputsLeft.length && (version !== 0 || Object.keys(outputsLeft[0]).length)))\n        throw new Error(`Unexpected outputs left in tx=${outputsLeft}`);\n    return tx;\n}\n/**\n * Merges two PSBT key maps while preserving keyed-field uniqueness.\n * @param psbtEnum - PSBT field definition table\n * @param val - new values to merge in\n * @param cur - existing decoded PSBT key map\n * @param allowedFields - fields still allowed to change\n * @param unknown - handling policy for unknown PSBT fields\n * @param proprietary - handling policy for proprietary PSBT fields\n * @returns Merged PSBT key map.\n * @throws If keyed PSBT fields conflict or signed fields would be removed. {@link Error}\n * @example\n * Merge an updated `witnessUtxo` into an existing decoded input map.\n * ```ts\n * import { hex } from '@scure/base';\n * import { PSBTInput, mergeKeyMap } from '@scure/btc-signer/psbt.js';\n * mergeKeyMap(\n *   PSBTInput,\n *   { witnessUtxo: { amount: 2n, script: new Uint8Array([0x51]) } },\n *   {\n *     txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *     index: 0,\n *   }\n * );\n * ```\n */\nexport function mergeKeyMap(psbtEnum, val, cur, allowedFields, unknown = 'strip', proprietary = 'strip') {\n    validateObject(psbtEnum, {}, {}, 'psbtEnum');\n    validateObject(val, {}, {}, 'val');\n    if (cur !== undefined)\n        validateObject(cur, {}, {}, 'cur');\n    if (allowedFields !== undefined)\n        aarray(allowedFields, 'allowedFields');\n    const _val = val;\n    const _cur = cur;\n    const _allowedFields = allowedFields;\n    const unknownMode = unknowns(unknown, 'unknown');\n    const proprietaryMode = unknowns(proprietary, 'proprietary');\n    for (const [name, mode] of [\n        ['unknown', unknownMode],\n        ['proprietary', proprietaryMode],\n    ]) {\n        if (mode !== 'strict')\n            continue;\n        if (_val[name]?.length ||\n            _cur?.[name]?.length)\n            throw new Error(`PSBT: ${name} PSBT field is not allowed in strict mode`);\n    }\n    const res = { ..._cur, ..._val };\n    // All arguments can be provided as hex\n    for (const k in psbtEnum) {\n        const key = k;\n        if (k === 'proprietary' && proprietaryMode !== 'ignore')\n            continue;\n        const [_, kC, vC] = psbtEnum[key];\n        const cannotChange = _allowedFields && !_allowedFields.includes(k);\n        if (_val[k] === undefined && k in _val) {\n            if (cannotChange)\n                throw new Error(`Cannot remove signed field=${k}`);\n            delete res[k];\n        }\n        else if (kC) {\n            const oldKV = (_cur && _cur[k] ? _cur[k] : []);\n            let newKV = _val[key];\n            if (newKV) {\n                if (!Array.isArray(newKV))\n                    throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);\n                // Decode hex in k-v\n                newKV = newKV.map((val) => {\n                    if (val.length !== 2)\n                        throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);\n                    return [\n                        typeof val[0] === 'string' ? kC.decode(hex.decode(val[0])) : val[0],\n                        typeof val[1] === 'string' ? vC.decode(hex.decode(val[1])) : val[1],\n                    ];\n                });\n                const map = {};\n                const add = (kStr, k, v) => {\n                    if (map[kStr] === undefined) {\n                        map[kStr] = [k, v];\n                        return;\n                    }\n                    const oldVal = hex.encode(vC.encode(map[kStr][1]));\n                    const newVal = hex.encode(vC.encode(v));\n                    if (oldVal !== newVal)\n                        throw new Error(`keyMap(${key}): same key=${kStr} oldVal=${oldVal} newVal=${newVal}`);\n                };\n                for (const [k, v] of oldKV) {\n                    const kStr = hex.encode(kC.encode(k));\n                    add(kStr, k, v);\n                }\n                for (const [k, v] of newKV) {\n                    const kStr = hex.encode(kC.encode(k));\n                    // undefined removes previous value\n                    if (v === undefined) {\n                        if (cannotChange)\n                            throw new Error(`Cannot remove signed field=${key}/${k}`);\n                        delete map[kStr];\n                    }\n                    else {\n                        if (cannotChange && map[kStr] === undefined)\n                            throw new Error(`Cannot add signed field=${key}/${kStr}`);\n                        add(kStr, k, v);\n                    }\n                }\n                res[key] = Object.values(map);\n            }\n        }\n        else {\n            if (typeof res[k] === 'string')\n                res[k] = vC.decode(hex.decode(res[k]));\n            if (cannotChange && k in _val) {\n                if (!_cur || _cur[k] === undefined)\n                    throw new Error(`Cannot add signed field=${k}`);\n                let current = _cur[k];\n                if (typeof current === 'string')\n                    current = vC.decode(hex.decode(current));\n                if (!equalBytes(vC.encode(res[k]), vC.encode(current)))\n                    throw new Error(`Cannot change signed field=${k}`);\n            }\n        }\n    }\n    if (unknownMode === 'ignore' && _val.unknown) {\n        // Unknown PSBT rows are stripped by default here, but explicit ignore mode is pass-through.\n        // Merge them by full serialized unknown key so repeated updates do not clobber earlier opaque rows.\n        const map = {};\n        for (const [k, v] of _cur?.unknown || [])\n            map[hex.encode(PSBTUnknownKey.encode(k))] = [k, v];\n        for (const [k, v] of _val.unknown) {\n            const kStr = hex.encode(PSBTUnknownKey.encode(k));\n            if (map[kStr] === undefined) {\n                map[kStr] = [k, v];\n                continue;\n            }\n            const oldVal = hex.encode(BytesInf.encode(map[kStr][1]));\n            const newVal = hex.encode(BytesInf.encode(v));\n            if (oldVal !== newVal)\n                throw new Error(`keyMap(unknown): same key=${kStr} oldVal=${oldVal} newVal=${newVal}`);\n        }\n        res.unknown = Object.values(map);\n    }\n    // Remove properties outside the table, except opaque rows in explicit ignore mode.\n    for (const k in res) {\n        if (!psbtEnum[k]) {\n            if (unknownMode === 'ignore' && k === 'unknown')\n                continue;\n            delete res[k];\n        }\n    }\n    if (unknownMode !== 'ignore')\n        delete res.unknown;\n    if (proprietaryMode !== 'ignore')\n        delete res.proprietary;\n    return res;\n}\n/**\n * Combines two independently produced PSBT maps without choosing between conflicting scalar\n * values. Keyed fields retain {@link mergeKeyMap}'s union semantics.\n * @param psbtEnum - PSBT field definition table\n * @param current - first map\n * @param other - second map\n * @param unknown - handling policy for unknown PSBT fields\n * @param proprietary - handling policy for proprietary PSBT fields\n * @returns The symmetric map union.\n * @throws If both maps provide different values for the same scalar field. {@link Error}\n * @example\n * Combine disjoint global metadata without choosing an operand as authoritative.\n * ```ts\n * import { combineKeyMap, PSBTGlobal } from '@scure/btc-signer/psbt.js';\n * combineKeyMap(PSBTGlobal, { txVersion: 2 }, { fallbackLocktime: 0 });\n * ```\n */\nexport function combineKeyMap(psbtEnum, current, other, unknown = 'strip', proprietary = 'strip') {\n    validateObject(psbtEnum, {}, {}, 'psbtEnum');\n    validateObject(current, {}, {}, 'current');\n    validateObject(other, {}, {}, 'other');\n    const _current = current;\n    const _other = other;\n    for (const k in psbtEnum) {\n        const key = k;\n        const [_, keyCoder, valueCoder] = psbtEnum[key];\n        if (keyCoder || _current[key] === undefined || _other[key] === undefined)\n            continue;\n        let a = _current[key];\n        let b = _other[key];\n        if (typeof a === 'string')\n            a = valueCoder.decode(hex.decode(a));\n        if (typeof b === 'string')\n            b = valueCoder.decode(hex.decode(b));\n        if (!equalBytes(valueCoder.encode(a), valueCoder.encode(b)))\n            throw new Error(`Cannot combine conflicting field=${k}`);\n    }\n    return mergeKeyMap(psbtEnum, _other, _current, undefined, unknown, proprietary);\n}\n/** Validated PSBTv0 coder. */\n// This wrapper only layers `validatePSBT`'s PSBTv0 field/count reconciliation on top of\n// `_RawPSBTV0`; field-specific payload invariants still depend on the nested coders/tables.\nexport const RawPSBTV0 = /* @__PURE__ */ (() => Object.freeze(P.validate(_RawPSBTV0, validatePSBT)))();\n/** Validated PSBTv2 coder. */\n// This wrapper only layers `validatePSBT`'s PSBTv2 required-field/count reconciliation on top\n// of `_RawPSBTV2`; nested input/output/global field invariants still depend on the coders below.\nexport const RawPSBTV2 = /* @__PURE__ */ (() => Object.freeze(P.validate(_RawPSBTV2, validatePSBT)))();\n","import { bech32, bech32m, createBase58check, hex } from '@scure/base';\nimport { anumber } from '@noble/hashes/utils.js';\nimport { abytes } from '@noble/curves/utils.js';\nimport * as P from 'micro-packed';\nimport { TaprootControlBlock } from \"./psbt.js\";\nimport { MAX_SCRIPT_BYTE_LENGTH, OpToNum, Script, VarBytes } from \"./script.js\";\nimport * as u from \"./utils.js\";\nimport { NETWORK } from \"./utils.js\";\n// Pay to Anchor (P2A)\n// BIP433 Pay-to-Anchor witness program bytes; the scriptPubKey is `OP_1 <0x4e73>`.\nconst P2A_PROGRAM = /* @__PURE__ */ Uint8Array.from([0x4e, 0x73]);\nconst OutP2A = {\n    encode(from) {\n        // BIP433 defines P2A as the exact OP_1 <0x4e73> scriptPubKey.\n        if (from.length !== 2 ||\n            from[0] !== 1 ||\n            !u.isBytes(from[1]) ||\n            !u.equalBytes(from[1], P2A_PROGRAM))\n            return;\n        return { type: 'p2a', script: Script.encode(from) };\n    },\n    decode: (to) => {\n        if (to.type !== 'p2a')\n            return;\n        // The decoded object keeps `script` for caller convenience, but the `p2a`\n        // tag always canonicalizes back to the fixed BIP433 script.\n        return [1, Uint8Array.from(P2A_PROGRAM)];\n    },\n};\nfunction isValidPubkey(pub, type) {\n    // Payment coders use a boolean guard here and normalize validatePubkey failures to false.\n    try {\n        u.validatePubkey(pub, type);\n        return true;\n    }\n    catch (e) {\n        return false;\n    }\n}\nconst OutPK = {\n    encode(from) {\n        // BIP380/BIP381 `pk(KEY)` only admits SEC1 ECDSA pubkeys here; x-only\n        // 32-byte CHECKSIG scripts are left for the later tapscript coders.\n        if (from.length !== 2 ||\n            !u.isBytes(from[0]) ||\n            !isValidPubkey(from[0], u.PubT.ecdsa) ||\n            from[1] !== 'CHECKSIG')\n            return;\n        return { type: 'pk', pubkey: from[0] };\n    },\n    decode: (to) => {\n        if (to.type !== 'pk')\n            return;\n        // OutScript validates `pk.pubkey` before this branch emits the canonical\n        // `<pubkey> CHECKSIG` script.\n        return [to.pubkey, 'CHECKSIG'];\n    },\n};\nconst OutPKH = {\n    encode(from) {\n        if (from.length !== 5 || from[0] !== 'DUP' || from[1] !== 'HASH160' || !u.isBytes(from[2]))\n            return;\n        // Require the exact 20-byte HASH160 here so near-miss scripts fall through\n        // to OutUnknown instead of throwing in the OutScript validator on decode.\n        if (from[2].length !== 20)\n            return;\n        if (from[3] !== 'EQUALVERIFY' || from[4] !== 'CHECKSIG')\n            return;\n        return { type: 'pkh', hash: from[2] };\n    },\n    // OutScript validates `pkh.hash` before this branch emits the canonical\n    // `DUP HASH160 <hash> EQUALVERIFY CHECKSIG` script.\n    decode: (to) => (to.type === 'pkh'\n        ? ['DUP', 'HASH160', to.hash, 'EQUALVERIFY', 'CHECKSIG']\n        : undefined),\n};\nconst OutSH = {\n    encode(from) {\n        if (from.length !== 3 || from[0] !== 'HASH160' || !u.isBytes(from[1]) || from[2] !== 'EQUAL')\n            return;\n        // Require the exact 20-byte HASH160 here so near-miss scripts fall through\n        // to OutUnknown instead of throwing in the OutScript validator on decode.\n        if (from[1].length !== 20)\n            return;\n        return { type: 'sh', hash: from[1] };\n    },\n    // OutScript validates `sh.hash` before this branch emits the canonical\n    // `HASH160 <hash> EQUAL` script.\n    decode: (to) => (to.type === 'sh' ? ['HASH160', to.hash, 'EQUAL'] : undefined),\n};\nconst OutWSH = {\n    encode(from) {\n        if (from.length !== 2 || from[0] !== 0 || !u.isBytes(from[1]))\n            return;\n        // BIP382 `wsh()` is specifically the version-0 32-byte witness program.\n        // Other witness versions stay with the later coders.\n        if (from[1].length !== 32)\n            return;\n        return { type: 'wsh', hash: from[1] };\n    },\n    // OutScript validates `wsh.hash` before this branch emits the canonical\n    // version-0 32-byte witness program.\n    decode: (to) => (to.type === 'wsh' ? [0, to.hash] : undefined),\n};\nconst OutWPKH = {\n    encode(from) {\n        if (from.length !== 2 || from[0] !== 0 || !u.isBytes(from[1]))\n            return;\n        // BIP382 `wpkh()` is specifically the version-0 20-byte witness program.\n        // Compressed-key restrictions are enforced upstream, and other witness\n        // versions stay with the later coders.\n        if (from[1].length !== 20)\n            return;\n        return { type: 'wpkh', hash: from[1] };\n    },\n    // OutScript validates `wpkh.hash` before this branch emits the canonical\n    // version-0 20-byte witness program.\n    decode: (to) => (to.type === 'wpkh' ? [0, to.hash] : undefined),\n};\nconst OutMS = {\n    encode(from) {\n        const last = from.length - 1;\n        if (from[last] !== 'CHECKMULTISIG')\n            return;\n        const m = from[0];\n        const n = from[last - 1];\n        if (typeof m !== 'number' || typeof n !== 'number')\n            return;\n        const pubkeys = from.slice(1, -2);\n        if (n !== pubkeys.length)\n            return;\n        // Require valid ECDSA pubkeys and `0 < m <= n` here so near-miss\n        // CHECKMULTISIG scripts (garbage keys, degenerate 0-of-0) fall through to\n        // OutUnknown instead of throwing in the OutScript validator on decode.\n        // Script.decode only yields 0..16 for opcode numbers, so n <= 16 holds.\n        for (const pub of pubkeys)\n            if (!u.isBytes(pub) || !isValidPubkey(pub, u.PubT.ecdsa))\n                return;\n        if (!Number.isSafeInteger(m) || m < 1 || m > n)\n            return;\n        // We don't need n here because it is the same as pubkeys.length.\n        return { type: 'ms', m, pubkeys: pubkeys };\n    },\n    // checkmultisig(n, ..pubkeys, m)\n    decode: (to) => \n    // OutScript validates multisig pubkeys and `0 < m <= n <= 16`.\n    // This branch only emits the canonical `m <pubkeys...> n CHECKMULTISIG`\n    // script.\n    (to.type === 'ms'\n        ? [to.m, ...to.pubkeys, to.pubkeys.length, 'CHECKMULTISIG']\n        : undefined),\n};\nconst OutTR = {\n    encode(from) {\n        // BIP141 witness programs are `OP_0..OP_16` followed by a direct 2..40-byte push.\n        // BIP341 assigns native taproot meaning only to version 1 with a 32-byte x-only program;\n        // other OP_1 program lengths remain reserved future witness programs and should fall through.\n        if (from.length !== 2 || from[0] !== 1 || !u.isBytes(from[1]) || from[1].length !== 32)\n            return;\n        // A 32-byte v1 program with an off-curve x coordinate is a fundable but\n        // taproot-unspendable output; classify it as unknown instead of throwing\n        // in the OutScript validator on decode.\n        if (!isValidPubkey(from[1], u.PubT.schnorr))\n            return;\n        return { type: 'tr', pubkey: from[1] };\n    },\n    // OutScript validates `tr.pubkey` before this branch emits the canonical\n    // version-1 32-byte witness program.\n    decode: (to) => (to.type === 'tr' ? [1, to.pubkey] : undefined),\n};\nconst OutTRNS = {\n    encode(from) {\n        const last = from.length - 1;\n        if (from[last] !== 'CHECKSIG')\n            return;\n        const pubkeys = [];\n        // On error return, since it can be different script\n        for (let i = 0; i < last; i++) {\n            const elm = from[i];\n            if (i & 1) {\n                if (elm !== 'CHECKSIGVERIFY' || i === last - 1)\n                    return;\n                continue;\n            }\n            // Require actual Schnorr pubkeys here so near-miss `<bytes> CHECKSIG`\n            // scripts fall through to OutUnknown instead of failing later.\n            if (!u.isBytes(elm) || !isValidPubkey(elm, u.PubT.schnorr))\n                return;\n            pubkeys.push(elm);\n        }\n        // BIP342 \"Using a k-of-k script for every combination\" documents the shape\n        // `<pubkey_1> CHECKSIGVERIFY ... <pubkey_n> CHECKSIG`; this matcher only\n        // classifies that embedded-pubkey form, so bare CHECKSIG stays unknown.\n        if (!pubkeys.length || pubkeys.length > 999)\n            return;\n        return { type: 'tr_ns', pubkeys };\n    },\n    decode: (to) => {\n        if (to.type !== 'tr_ns')\n            return;\n        const out = [];\n        for (let i = 0; i < to.pubkeys.length - 1; i++)\n            out.push(to.pubkeys[i], 'CHECKSIGVERIFY');\n        // This branch assumes at least one Schnorr pubkey; [] would otherwise emit\n        // `[undefined, CHECKSIG]` and only fail later in Script.encode.\n        out.push(to.pubkeys[to.pubkeys.length - 1], 'CHECKSIG');\n        return out;\n    },\n};\nconst OutTRMS = {\n    encode(from) {\n        const last = from.length - 1;\n        if (from[last] !== 'NUMEQUAL' || from[1] !== 'CHECKSIG')\n            return;\n        const pubkeys = [];\n        const m = OpToNum(from[last - 1]);\n        if (typeof m !== 'number')\n            return;\n        for (let i = 0; i < last - 1; i++) {\n            const elm = from[i];\n            // Structural mismatches should fall through to OutUnknown instead of\n            // throwing from the tr_ms matcher.\n            if (i & 1) {\n                if (elm !== (i === 1 ? 'CHECKSIG' : 'CHECKSIGADD'))\n                    return;\n                continue;\n            }\n            // Require actual Schnorr pubkeys here (same as tr_ns) so near-miss\n            // CHECKSIGADD scripts fall through to OutUnknown instead of throwing\n            // in the OutScript validator on decode.\n            if (!u.isBytes(elm) || !isValidPubkey(elm, u.PubT.schnorr))\n                return;\n            pubkeys.push(elm);\n        }\n        if (!Number.isSafeInteger(m) || m < 1 || m > pubkeys.length || pubkeys.length > 999)\n            return;\n        return { type: 'tr_ms', pubkeys, m };\n    },\n    decode: (to) => {\n        if (to.type !== 'tr_ms')\n            return;\n        const out = [to.pubkeys[0], 'CHECKSIG'];\n        for (let i = 1; i < to.pubkeys.length; i++)\n            out.push(to.pubkeys[i], 'CHECKSIGADD');\n        // This branch assumes `m` was already validated as an integer ScriptNum;\n        // fractional JS numbers would otherwise serialize as a different threshold.\n        out.push(to.m, 'NUMEQUAL');\n        return out;\n    },\n};\nconst OutUnknown = {\n    encode(from) {\n        // This is the catch-all fallback for scripts no structured coder recognized,\n        // so earlier matchers must return `undefined` instead of throwing on mismatch.\n        // Because this reserializes the parsed Script AST, unknown scripts preserve\n        // semantics but not original non-minimal push spellings.\n        return { type: 'unknown', script: Script.encode(from) };\n    },\n    decode: (to) => \n    // This reparses `unknown.script` through the semantic Script codec, so raw\n    // bytes must still be syntactically parseable and may canonicalize on re-encode.\n    (to.type === 'unknown' ? Script.decode(to.script) : undefined),\n};\n// /Payments\nconst OutScripts = /* @__PURE__ */ (() => [\n    // Order is semantic: specific structured coders run first and the catch-all\n    // unknown fallback must stay last.\n    OutP2A,\n    OutPK,\n    OutPKH,\n    OutSH,\n    OutWSH,\n    OutWPKH,\n    OutMS,\n    OutTR,\n    OutTRNS,\n    OutTRMS,\n    OutUnknown,\n])();\n// TODO: we can support user supplied output scripts now\n// - addOutScript\n// - removeOutScript\n// - We can do that as log we modify array in-place\n// - Actually is very hard, since there is sign/finalize logic\n// Raw composition of semantic Script parsing with the ordered output-script\n// matcher; OutScript adds the higher-level validation layer on top.\nconst _OutScript = /* @__PURE__ */ (() => P.apply(Script, P.coders.match(OutScripts)))();\n// We can validate this once, because of packed & coders\n/**\n * Coder for recognized Bitcoin output scripts.\n * @example\n * Decode a serialized output script back into the tagged payment descriptor.\n * ```ts\n * import { OutScript, p2wpkh } from '@scure/btc-signer/payment.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * const pay = p2wpkh(pubECDSA(randomPrivateKeyBytes()));\n * OutScript.decode(pay.script);\n * ```\n */\nexport const OutScript = /* @__PURE__ */ (() => Object.freeze(P.validate(_OutScript, (i) => {\n    if (i.type === 'pk' && !isValidPubkey(i.pubkey, u.PubT.ecdsa))\n        throw new Error('OutScript/pk: wrong key');\n    if ((i.type === 'pkh' || i.type === 'sh' || i.type === 'wpkh') &&\n        (!u.isBytes(i.hash) || i.hash.length !== 20))\n        throw new Error(`OutScript/${i.type}: wrong hash`);\n    if (i.type === 'wsh' && (!u.isBytes(i.hash) || i.hash.length !== 32))\n        throw new Error(`OutScript/wsh: wrong hash`);\n    if (i.type === 'tr' && (!u.isBytes(i.pubkey) || !isValidPubkey(i.pubkey, u.PubT.schnorr)))\n        throw new Error('OutScript/tr: wrong taproot public key');\n    if (i.type === 'ms' || i.type === 'tr_ns' || i.type === 'tr_ms')\n        if (!Array.isArray(i.pubkeys))\n            throw new Error('OutScript/multisig: wrong pubkeys array');\n    if (i.type === 'ms') {\n        const n = i.pubkeys.length;\n        for (const p of i.pubkeys)\n            if (!isValidPubkey(p, u.PubT.ecdsa))\n                throw new Error('OutScript/multisig: wrong pubkey');\n        // Range checks are not enough here: non-integer JS numbers like 1.5 would\n        // otherwise slip through and serialize as a different ScriptNum threshold.\n        anumber(i.m, 'm');\n        if (i.m <= 0 || n > 16 || i.m > n)\n            throw new Error('OutScript/multisig: invalid params');\n    }\n    if (i.type === 'tr_ns' || i.type === 'tr_ms') {\n        const n = i.pubkeys.length;\n        // BIP342 keeps the 1,000-element stack limit. Both supported tapscript multisig forms\n        // start with n signatures and then push a pubkey, so n must stay at or below 999.\n        if (n > 999)\n            throw new Error(`OutScript/${i.type}: invalid params`);\n        for (const p of i.pubkeys)\n            if (!isValidPubkey(p, u.PubT.schnorr))\n                throw new Error(`OutScript/${i.type}: wrong pubkey`);\n    }\n    if (i.type === 'tr_ms') {\n        const n = i.pubkeys.length;\n        anumber(i.m, 'm');\n        if (i.m <= 0 || i.m > n)\n            throw new Error('OutScript/tr_ms: invalid params');\n    }\n    return i;\n})))();\n// Internal raw-aware boundary for actual scriptPubKeys and P2SH-nested witness programs. Generic\n// OutScript remains semantic because witnessScript and tapscript children may use the same opcodes\n// without claiming BIP141 witness-program framing.\nexport const _WitnessOutScript = /* @__PURE__ */ (() => Object.freeze(P.wrap({\n    encodeStream: (w, value) => OutScript.encodeStream(w, value),\n    decodeStream: (r) => {\n        const raw = r.bytes(r.leftBytes);\n        const out = OutScript.decode(raw);\n        // Script.decode normalizes push opcodes, but BIP141 recognition requires the exact direct\n        // push. Reject only when this explicit outer-program boundary is selected by the caller.\n        if (out &&\n            (out.type === 'p2a' || out.type === 'wpkh' || out.type === 'wsh' || out.type === 'tr') &&\n            !u.equalBytes(raw, OutScript.encode(out)))\n            throw new Error('OutScript: non-canonical witness program');\n        return out;\n    },\n})))();\n// Basic sanity check for scripts\nfunction checkWSH(s, witnessScript) {\n    if (!u.equalBytes(s.hash, u.sha256(witnessScript)))\n        throw new Error('checkScript: wsh wrong witnessScript hash');\n    // BIP141 only requires the witnessScript hash match; the type-based rejects\n    // below are an extra descriptor sanity layer for BIP382 invalid-descriptor\n    // bullets `wpkh() nested in wsh()` and `wsh() nested in wsh()`.\n    const w = OutScript.decode(witnessScript);\n    if (w.type === 'tr' || w.type === 'tr_ns' || w.type === 'tr_ms')\n        throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2SH`);\n    if (w.type === 'wpkh' || w.type === 'wsh' || w.type === 'sh')\n        throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2WSH`);\n}\n/**\n * Validates that nested redeem and witness scripts match their wrappers.\n * @param script - top-level output script\n * @param redeemScript - optional redeem script for P2SH wrappers\n * @param witnessScript - optional witness script for P2WSH wrappers\n * @throws If the script nesting is invalid or unsupported. {@link Error}\n * @example\n * Verify that wrapped scripts and hashes still match after custom edits.\n * ```ts\n * import { hex } from '@scure/base';\n * import { checkScript, p2pkh, p2sh } from '@scure/btc-signer/payment.js';\n * const wrapped = p2sh(\n *   p2pkh(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'))\n * );\n * checkScript(wrapped.script, wrapped.redeemScript);\n * ```\n */\nexport function checkScript(script, redeemScript, witnessScript) {\n    let hasWsh = false;\n    let r = undefined;\n    if (script) {\n        const s = _WitnessOutScript.decode(script);\n        // BIP174 Data Signers Check For bullets: provided redeemScript must match\n        // the scriptPubKey, and provided witnessScript must match the scriptPubKey\n        // or redeemScript instead of being silently ignored as stray metadata.\n        // ms||pk maybe work, but there will be no address, hard to spend\n        if (s.type === 'tr_ns' || s.type === 'tr_ms' || s.type === 'ms' || s.type == 'pk')\n            throw new Error(`checkScript: non-wrapped ${s.type}`);\n        if (redeemScript) {\n            if (s.type !== 'sh')\n                throw new Error('checkScript: redeemScript without P2SH');\n            if (!u.equalBytes(s.hash, u.hash160(redeemScript)))\n                throw new Error('checkScript: sh wrong redeemScript hash');\n            r = _WitnessOutScript.decode(redeemScript);\n            if (r?.type === 'tr' || r?.type === 'tr_ns' || r?.type === 'tr_ms')\n                throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);\n            // Not sure if this unspendable, but we cannot represent this via PSBT\n            if (r?.type === 'sh')\n                throw new Error('checkScript: P2SH cannot be wrapped in P2SH');\n        }\n        if (s.type === 'wsh') {\n            hasWsh = true;\n            if (witnessScript)\n                checkWSH(s, witnessScript);\n        }\n    }\n    if (redeemScript) {\n        if (r === undefined)\n            r = _WitnessOutScript.decode(redeemScript);\n        if (r?.type === 'wsh') {\n            hasWsh = true;\n            if (witnessScript)\n                checkWSH(r, witnessScript);\n        }\n    }\n    if (witnessScript && !hasWsh)\n        throw new Error('checkScript: witnessScript without P2WSH');\n}\nfunction uniqPubkey(pubkeys, type) {\n    const map = {};\n    for (const pub of pubkeys) {\n        u.validatePubkey(pub, type);\n        let normalized = pub;\n        if (type === u.PubT.ecdsa && pub.length === 65) {\n            // Compressed and uncompressed SEC1 encodings can represent the same curve point. Normalize\n            // valid uncompressed keys before comparing so one signer cannot occupy multiple threshold\n            // slots merely by changing the serialization. `allowSamePubkeys` remains the explicit\n            // compatibility escape hatch for callers that intentionally construct duplicate-key scripts.\n            normalized = new Uint8Array(33);\n            normalized[0] = 2 | (pub[64] & 1);\n            normalized.set(pub.subarray(1, 33), 1);\n        }\n        const key = hex.encode(normalized);\n        if (map[key])\n            throw new Error(`Multisig: non-uniq pubkey: ${pubkeys.map(hex.encode)}`);\n        map[key] = true;\n    }\n}\n/**\n * Builds a pay-to-public-key script.\n * @param pubkey - compressed or uncompressed ECDSA public key\n * @param _network - unused network placeholder for API consistency\n * @returns P2PK descriptor.\n * @throws If the public key cannot be encoded as a P2PK output. {@link Error}\n * @example\n * Build a bare pay-to-public-key output.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2pk } from '@scure/btc-signer/payment.js';\n * p2pk(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'));\n * ```\n */\nexport const p2pk = (pubkey, _network = NETWORK) => {\n    // network is unused\n    if (!isValidPubkey(pubkey, u.PubT.ecdsa))\n        throw new Error('P2PK: invalid publicKey');\n    return {\n        type: 'pk',\n        script: OutScript.encode({ type: 'pk', pubkey }),\n    };\n};\n/**\n * Builds a P2PKH output from a public key.\n * @param publicKey - compressed or uncompressed ECDSA public key bytes; HASH160 commits to the exact encoding\n * @param network - address network parameters\n * @returns P2PKH descriptor.\n * @throws If the public key cannot be encoded as a P2PKH output. {@link Error}\n * @example\n * Build a classic pay-to-public-key-hash output.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2pkh } from '@scure/btc-signer/payment.js';\n * p2pkh(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'));\n * ```\n */\nexport const p2pkh = (publicKey, network = NETWORK) => {\n    if (!isValidPubkey(publicKey, u.PubT.ecdsa))\n        throw new Error('P2PKH: invalid publicKey');\n    const hash = u.hash160(publicKey);\n    return {\n        type: 'pkh',\n        script: OutScript.encode({ type: 'pkh', hash }),\n        address: Address(network).encode({ type: 'pkh', hash }),\n        hash,\n    };\n};\nconst checkCanonicalScript = (script, name, allowNonCanonicalScript) => {\n    if (allowNonCanonicalScript)\n        return;\n    const decoded = Script.decode(script);\n    const nonMinimalNumber = decoded.some((op) => u.isBytes(op) && op.length === 1 && ((1 <= op[0] && op[0] <= 16) || op[0] === 0x81));\n    // Core's default MINIMALDATA policy rejects these spends from its mempool, so address-producing\n    // helpers require an explicit opt-in even though the original bytes remain consensus-valid.\n    if (nonMinimalNumber || !u.equalBytes(script, Script.encode(decoded))) {\n        const wrapper = name === 'redeemScript' ? 'P2SH' : 'P2WSH';\n        throw new Error(`${wrapper}: non-canonical ${name}`);\n    }\n};\n/**\n * Wraps a child script inside P2SH.\n * @param child - child payment descriptor to wrap\n * @param network - address network parameters\n * @param allowNonCanonicalScript - whether to create an address for a non-minimal child script\n * @returns P2SH descriptor preserving witness metadata when present.\n * @throws If the wrapped script combination is invalid or unsupported. {@link Error}\n * @example\n * Wrap a child script in P2SH so it gets a base58 address form.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2pk, p2sh, p2wsh } from '@scure/btc-signer/payment.js';\n * p2sh(p2wsh(p2pk(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'))));\n * ```\n */\nexport const p2sh = (child, network = NETWORK, allowNonCanonicalScript = false) => {\n    u.validateObject(child, {}, {}, 'child');\n    // It is already tested inside noble-hashes and checkScript\n    // BIP16 redeemScripts are pushed by scriptSig, so anything over the 520-byte pushed-element\n    // limit would be fundable by HASH160 but unspendable once wrapped in P2SH.\n    const c = child;\n    const cs = c.script;\n    if (!u.isBytes(cs))\n        throw new Error(`Wrong script: ${typeof c.script}, expected Uint8Array`);\n    if (cs.length > MAX_SCRIPT_BYTE_LENGTH)\n        throw new Error(`P2SH: redeemScript exceeds ${MAX_SCRIPT_BYTE_LENGTH}-byte push limit: len=${cs.length}`);\n    checkCanonicalScript(cs, 'redeemScript', allowNonCanonicalScript);\n    const hash = u.hash160(cs);\n    const out = { type: 'sh', hash };\n    const script = OutScript.encode(out);\n    const address = Address(network).encode(out);\n    checkScript(script, cs, c.witnessScript);\n    if (c.witnessScript) {\n        return {\n            type: 'sh',\n            redeemScript: cs,\n            script,\n            address,\n            hash,\n            witnessScript: c.witnessScript,\n        };\n    }\n    else {\n        return {\n            type: 'sh',\n            redeemScript: cs,\n            script,\n            address,\n            hash,\n        };\n    }\n};\n/**\n * Wraps a child script inside native SegWit P2WSH.\n * @param child - child payment descriptor to wrap\n * @param network - address network parameters\n * @param allowNonCanonicalScript - whether to create an address for a non-minimal child script\n * @returns P2WSH descriptor.\n * @throws If the wrapped script combination is invalid or unsupported. {@link Error}\n * @example\n * Wrap a child script in native SegWit P2WSH.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2pk, p2wsh } from '@scure/btc-signer/payment.js';\n * p2wsh(p2pk(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798')));\n * ```\n */\nexport const p2wsh = (child, network = NETWORK, allowNonCanonicalScript = false) => {\n    u.validateObject(child, {}, {}, 'child');\n    const cs = child.script;\n    if (!u.isBytes(cs))\n        throw new Error(`Wrong script: ${typeof cs}, expected Uint8Array`);\n    // BIP141 P2WSH says the witness \"must consist of ... a serialized script (witnessScript)\"\n    // and that witnessScript is limited to 10,000 bytes, so larger wrapped scripts must reject.\n    if (cs.length > 10000)\n        throw new Error('P2WSH: witnessScript exceeds 10,000 bytes');\n    checkCanonicalScript(cs, 'witnessScript', allowNonCanonicalScript);\n    const hash = u.sha256(cs);\n    const script = OutScript.encode({ type: 'wsh', hash });\n    checkScript(script, undefined, cs);\n    return {\n        type: 'wsh',\n        witnessScript: cs,\n        script,\n        address: Address(network).encode({ type: 'wsh', hash }),\n        hash,\n    };\n};\n/**\n * Builds a native SegWit P2WPKH output from a public key.\n * @param publicKey - compressed ECDSA public key\n * @param network - address network parameters\n * @returns P2WPKH descriptor.\n * @throws If the public key cannot be encoded as a P2WPKH output. {@link Error}\n * @example\n * Build a native SegWit pay-to-public-key-hash output.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2wpkh } from '@scure/btc-signer/payment.js';\n * p2wpkh(hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'));\n * ```\n */\nexport const p2wpkh = (publicKey, network = NETWORK) => {\n    if (!isValidPubkey(publicKey, u.PubT.ecdsa))\n        throw new Error('P2WPKH: invalid publicKey');\n    // BIP 143 default policy: version-0 witness programs MUST use 33-byte compressed ECDSA keys.\n    if (publicKey.length === 65)\n        throw new Error('P2WPKH: uncompressed public key');\n    const hash = u.hash160(publicKey);\n    return {\n        type: 'wpkh',\n        script: OutScript.encode({ type: 'wpkh', hash }),\n        address: Address(network).encode({ type: 'wpkh', hash }),\n        hash,\n    };\n};\n/**\n * Builds a bare multisig script.\n * @param m - number of required signatures\n * @param pubkeys - participating public keys\n * @param allowSamePubkeys - whether duplicate keys are allowed\n * @returns P2MS descriptor.\n * @throws If the multisig parameters are invalid. {@link Error}\n * @example\n * Build a bare multisig output script.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2ms } from '@scure/btc-signer/payment.js';\n * p2ms(1, [hex.decode('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798')], true);\n * ```\n */\nexport const p2ms = (m, pubkeys, allowSamePubkeys = false) => {\n    // BIP 11 only standardized bare multisig up to 3 keys; this helper still permits up to 16\n    // because the same script shape is commonly wrapped by p2sh()/p2wsh() instead of used bare.\n    if (!allowSamePubkeys)\n        uniqPubkey(pubkeys, u.PubT.ecdsa);\n    return {\n        type: 'ms',\n        script: OutScript.encode({ type: 'ms', pubkeys, m }),\n    };\n};\nfunction checkTaprootScript(script, internalPubKey, allowUnknownOutputs = false, customScripts) {\n    const out = OutScript.decode(script);\n    if (out.type === 'unknown') {\n        // NOTE: this check should be before allowUnknownOutputs, otherwise it will\n        // disable custom. All custom scripts for taproot should have prefix 'tr_'\n        if (customScripts) {\n            const cs = P.apply(Script, P.coders.match(customScripts));\n            let c;\n            // match() throws when no custom coder matches; treat that as \"not a custom\n            // script\" so the allowUnknownOutputs escape below stays reachable.\n            try {\n                c = cs.decode(script);\n            }\n            catch (e) {\n                c = undefined;\n            }\n            if (c !== undefined) {\n                if (!u.astring(c.type, 'c.type').startsWith('tr_'))\n                    throw new Error(`P2TR: invalid custom type=${c.type}`);\n                return;\n            }\n        }\n        if (allowUnknownOutputs)\n            return;\n    }\n    if (!['tr_ns', 'tr_ms'].includes(out.type))\n        throw new Error(`P2TR: invalid leaf script=${out.type}`);\n    const outms = out;\n    if (!allowUnknownOutputs && outms.pubkeys) {\n        for (const p of outms.pubkeys) {\n            if (u.equalBytes(p, u.taprootNumsKey()))\n                throw new Error('Unspendable taproot key in leaf script');\n            // It's likely a mistake at this point:\n            // 1. p2tr(A, p2tr_ns(2, [A, B])) == p2tr(A, p2tr_pk(B)) (A or B key)\n            // but will take more space and fees.\n            // 2. For multi-sig p2tr(A, p2tr_ns(2, [A, B, C])) it's probably a security issue:\n            // User creates 2 of 3 multisig of keys [A, B, C],\n            // but key A always can spend whole output without signatures from other keys.\n            // p2tr(A, p2tr_ns(2, [B, C, D])) is ok: A or (B and C) or (B and D) or (C and D)\n            if (u.equalBytes(p, internalPubKey)) {\n                throw new Error('Using P2TR with leaf script with same key as internal key is not supported');\n            }\n        }\n    }\n}\n// Helper for generating binary tree from list, with weights\n/**\n * Converts a flat list of weighted leaves into a binary taproot tree.\n * @param taprootList - weighted leaves to arrange\n * @returns Binary taproot script tree.\n * @throws If the list is empty and cannot describe any tree. {@link Error}\n * @example\n * Start from a flat weighted list, then let the helper build the binary tree shape.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2tr_pk, taprootListToTree } from '@scure/btc-signer/payment.js';\n * taprootListToTree([\n *   p2tr_pk(hex.decode('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9')),\n *   p2tr_pk(hex.decode('dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659')),\n * ]);\n * ```\n */\nexport function taprootListToTree(taprootList) {\n    u.aarray(taprootList, 'taprootList', (leaf, title) => {\n        // p2tr reduces non-binary trees through this helper, so nested branch arrays are valid here.\n        if (Array.isArray(leaf))\n            return;\n        u.validateObject(leaf, {}, {}, title);\n        // This helper only arranges weighted tree nodes; p2tr validates leaf scripts while hashing.\n        if (leaf.weight !== undefined)\n            anumber(leaf.weight, title + '.weight');\n    });\n    // Empty flat lists cannot represent a taproot script tree; omit the tree entirely for\n    // key-path-only outputs instead of passing [] here, otherwise this helper would return\n    // undefined and downstream taproot tree walkers would fail much later on a non-tree value.\n    if (!taprootList.length)\n        throw new Error('taprootListToTree: empty tree');\n    // Clone input in order to not corrupt it\n    const lst = Array.from(taprootList);\n    // We have at least 2 elements => can create branch\n    while (lst.length >= 2) {\n        // Sort: elements with smallest weight are in the end of queue\n        lst.sort((a, b) => (b.weight || 1) - (a.weight || 1));\n        const b = lst.pop();\n        const a = lst.pop();\n        const weight = (a?.weight || 1) + (b?.weight || 1);\n        lst.push({\n            weight,\n            // Unwrap children array\n            // TODO: Very hard to remove any here\n            childs: [a?.childs || a, b?.childs || b],\n        });\n    }\n    // At this point there is always 1 element in lst\n    const last = lst[0];\n    return (last?.childs || last);\n}\nfunction taprootAddPath(tree, path = []) {\n    if (!tree)\n        throw new Error(`taprootAddPath: empty tree`);\n    if (tree.type === 'leaf')\n        return { ...tree, path };\n    if (tree.type !== 'branch')\n        throw new Error(`taprootAddPath: wrong type=${tree}`);\n    return {\n        ...tree,\n        path,\n        // BIP 341 control blocks serialize sibling hashes from leaf to root, so prepend the\n        // current sibling before descending into the child subtree.\n        left: taprootAddPath(tree.left, [tree.right.hash, ...path]),\n        right: taprootAddPath(tree.right, [tree.left.hash, ...path]),\n    };\n}\nfunction taprootWalkTree(tree) {\n    if (!tree)\n        throw new Error(`taprootAddPath: empty tree`);\n    if (tree.type === 'leaf')\n        return [tree];\n    if (tree.type !== 'branch')\n        throw new Error(`taprootWalkTree: wrong type=${tree}`);\n    // Keep a stable left-to-right DFS leaf order when flattening the annotated tree.\n    return [...taprootWalkTree(tree.left), ...taprootWalkTree(tree.right)];\n}\n// BIP 341 control blocks can encode at most 128 sibling hashes.\nconst TAPROOT_MAX_DEPTH = 128;\nfunction taprootHashTree(tree, internalPubKey, allowUnknownOutputs = false, customScripts, depth = 0) {\n    // Reject before inspecting or descending into the next node, which also bounds the\n    // recursion used by the path annotation and tree-flattening passes below.\n    if (depth > TAPROOT_MAX_DEPTH)\n        throw new RangeError(`P2TR: tree depth exceeds ${TAPROOT_MAX_DEPTH}`);\n    if (tree === undefined)\n        throw new Error('taprootHashTree: empty tree');\n    if (!Array.isArray(tree) && !P.utils.isPlainObject(tree))\n        throw new TypeError('\"tree\" expected object or array, got type=' + typeof tree);\n    if (Array.isArray(tree) && tree.length === 1)\n        tree = tree[0];\n    // Terminal node (leaf)\n    if (!Array.isArray(tree)) {\n        u.validateObject(tree, {}, {}, 'tree');\n        const version = tree.leafVersion;\n        const { script: leafScript } = tree;\n        // Earliest tree walk where we can validate tapScripts\n        if (tree.tapLeafScript || (tree.tapMerkleRoot && !u.equalBytes(tree.tapMerkleRoot, P.EMPTY)))\n            throw new Error('P2TR: tapRoot leafScript cannot have tree');\n        const script = typeof leafScript === 'string'\n            ? hex.decode(leafScript)\n            : abytes(leafScript, undefined, 'tree.script');\n        checkTaprootScript(script, internalPubKey, allowUnknownOutputs, customScripts);\n        return {\n            type: 'leaf',\n            version,\n            script,\n            hash: tapLeafHash(script, tapLeafVersion(version)),\n        };\n    }\n    // If tree / branch is not binary tree, convert it\n    if (tree.length !== 2)\n        tree = taprootListToTree(tree);\n    if (tree.length !== 2)\n        throw new Error('hashTree: non binary tree!');\n    // branch\n    // Both nodes should exist\n    const left = taprootHashTree(tree[0], internalPubKey, allowUnknownOutputs, customScripts, depth + 1);\n    const right = taprootHashTree(tree[1], internalPubKey, allowUnknownOutputs, customScripts, depth + 1);\n    // BIP 341 sorts TapBranch child hashes lexicographically for hashing, but the original\n    // left/right structure still determines the control-block sibling paths for each leaf.\n    let [lH, rH] = [left.hash, right.hash];\n    if (u.compareBytes(rH, lH) === -1)\n        [lH, rH] = [rH, lH];\n    return {\n        type: 'branch',\n        left,\n        right,\n        hash: u.tagSchnorr('TapBranch', lH, rH),\n    };\n}\n/** Default tapleaf version used by taproot script-path outputs before adding the parity bit. */\nexport const TAP_LEAF_VERSION = 0xc0;\nconst tapLeafVersion = (version) => {\n    if (version === undefined)\n        return TAP_LEAF_VERSION;\n    anumber(version, 'leafVersion');\n    // BIP341 script-path validation defines the effective leaf version as `v = c[0] & 0xfe`\n    // and says it cannot be odd or `0x50`; tapleaf hashes also serialize this as one byte.\n    if (version > 0xfe || version === 0x50 || !!(version & 1))\n        throw new Error(`P2TR: invalid leafVersion=${version}`);\n    return version;\n};\n/**\n * Computes the tagged hash of a tapleaf script.\n * @param script - tapleaf script bytes\n * @param version - base even tapleaf version byte (for tapscript, `0xc0`)\n * @returns Tapleaf hash.\n * @throws If the tapleaf version is not a valid even one-byte version.\n * {@link Error}\n * @example\n * Hash a finalized tapscript leaf before placing it into a Merkle tree.\n * ```ts\n * tapLeafHash(new Uint8Array([0x51]));\n * ```\n */\nexport const tapLeafHash = (script, version = TAP_LEAF_VERSION) => u.tagSchnorr('TapLeaf', new Uint8Array([tapLeafVersion(version)]), VarBytes.encode(script));\nexport function p2tr(internalPubKey, tree, network = NETWORK, allowUnknownOutputs = false, customScripts) {\n    // Unspendable\n    if (!internalPubKey && !tree)\n        throw new Error('p2tr: should have pubKey or scriptTree (or both)');\n    const pubKey = typeof internalPubKey === 'string'\n        ? hex.decode(internalPubKey)\n        : (internalPubKey ?? u.taprootNumsKey());\n    if (!isValidPubkey(pubKey, u.PubT.schnorr))\n        throw new Error('p2tr: non-schnorr pubkey');\n    if (tree) {\n        let hashedTree = taprootAddPath(taprootHashTree(tree, pubKey, allowUnknownOutputs, customScripts));\n        const tapMerkleRoot = hashedTree.hash;\n        const [tweakedPubkey, parity] = u.taprootTweakPubkey(pubKey, tapMerkleRoot);\n        const tapLeafScript = [];\n        const leaves = taprootWalkTree(hashedTree).map((l) => {\n            const version = tapLeafVersion(l.version);\n            // Leaf versions are stored as the base even byte; only the control block adds the\n            // output-key parity bit required by BIP 341 script-path spending.\n            const controlBlock = {\n                version: version + parity,\n                internalKey: pubKey,\n                merklePath: l.path,\n            };\n            // Skip an encode/decode copy for performance; callers must treat returned metadata as\n            // immutable.\n            tapLeafScript.push([controlBlock, u.concatBytes(l.script, new Uint8Array([version]))]);\n            return { ...l, controlBlock: TaprootControlBlock.encode(controlBlock) };\n        });\n        return {\n            type: 'tr',\n            script: OutScript.encode({ type: 'tr', pubkey: tweakedPubkey }),\n            address: Address(network).encode({ type: 'tr', pubkey: tweakedPubkey }),\n            // For tests\n            tweakedPubkey,\n            // PSBT stuff\n            tapInternalKey: pubKey,\n            leaves,\n            tapLeafScript,\n            tapMerkleRoot,\n        };\n    }\n    else {\n        // BIP 341 / BIP 86: key-only Taproot still tweaks with the empty Merkle root so the\n        // output commits to an unspendable script path instead of leaving the key untweaked.\n        const tweakedPubkey = u.taprootTweakPubkey(pubKey, P.EMPTY)[0];\n        return {\n            type: 'tr',\n            script: OutScript.encode({ type: 'tr', pubkey: tweakedPubkey }),\n            address: Address(network).encode({ type: 'tr', pubkey: tweakedPubkey }),\n            // For tests\n            tweakedPubkey,\n            // PSBT stuff\n            tapInternalKey: pubKey,\n        };\n    }\n}\n/** Maximum number of combinations materialized by one default helper call. */\nexport const MAX_COMBINATIONS = 4096;\nconst combinationCount = (n, m) => {\n    const k = Math.min(m, n - m);\n    let count = 1;\n    for (let i = 1; i <= k; i++) {\n        count = (count * (n - k + i)) / i;\n        if (!Number.isSafeInteger(count))\n            return Number.POSITIVE_INFINITY;\n    }\n    return count;\n};\n// Returns all combinations of size M from lst\n/**\n * Returns all size-`m` combinations from a list.\n * @param m - size of each combination\n * @param list - input items to combine\n * @param maxCombinations - maximum result rows to materialize\n * @returns Array of combinations.\n * @throws If the combination size or input list is invalid. {@link Error}\n * @throws If the requested result exceeds the materialization limit. {@link RangeError}\n * @example\n * Enumerate all size-two subsets of a short list.\n * ```ts\n * combinations(2, [1, 2, 3]);\n * ```\n */\nexport function combinations(m, list, maxCombinations = MAX_COMBINATIONS) {\n    const res = [];\n    if (!Array.isArray(list))\n        throw new Error('combinations: lst arg should be array');\n    const n = list.length;\n    anumber(m, 'm');\n    anumber(maxCombinations, 'maxCombinations');\n    if (m < 1 || m > n)\n        throw new Error('combinations: m must satisfy 1 <= m <= lst.length');\n    if (maxCombinations < 1)\n        throw new Error('combinations: maxCombinations must be >= 1');\n    const count = combinationCount(n, m);\n    if (count > maxCombinations)\n        throw new RangeError(`combinations: C(${n}, ${m}) exceeds materialization limit=${maxCombinations}`);\n    /*\n    Basically works as M nested loops like:\n    for (;idx[0]<lst.length;idx[0]++) for (idx[1]=idx[0]+1;idx[1]<lst.length;idx[1]++)\n    but since we cannot create nested loops dynamically, we unroll it to a single loop\n    */\n    // This unrolled-loop implementation assumes an integer 1 <= m <= n; zero, negative, and\n    // fractional m values need an explicit guard before entering the loop.\n    const idx = Array.from({ length: m }, (_, i) => i);\n    const last = idx.length - 1;\n    main: for (;;) {\n        res.push(idx.map((i) => list[i]));\n        idx[last] += 1;\n        let i = last;\n        // Propagate increment\n        // idx[i] cannot be bigger than n-m+i, otherwise last elements in right part will overflow\n        for (; i >= 0 && idx[i] > n - m + i; i--) {\n            idx[i] = 0;\n            // Overflow in idx[0], break\n            if (i === 0)\n                break main;\n            idx[i - 1] += 1;\n        }\n        // Propagate: idx[i+1] = idx[idx]+1\n        for (i += 1; i < idx.length; i++)\n            idx[i] = idx[i - 1] + 1;\n    }\n    return res;\n}\n/**\n * Builds the leaf set for an M-of-N `CHECKSIGVERIFY` taproot policy.\n * @param m - number of required signatures\n * @param pubkeys - participating Schnorr public keys\n * @param allowSamePubkeys - whether duplicate keys are allowed\n * @returns Array of taproot leaf descriptors.\n * @throws If the taproot multisig parameters are invalid. {@link Error}\n * @throws If the requested leaf set exceeds the materialization limit. {@link RangeError}\n * @example\n * Build the leaf set for an M-of-N taproot `CHECKSIGVERIFY` policy.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2tr_ns } from '@scure/btc-signer/payment.js';\n * p2tr_ns(1, [hex.decode('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9')], true);\n * ```\n */\nexport const p2tr_ns = (m, pubkeys, allowSamePubkeys = false) => {\n    anumber(m, 'm');\n    if (m > 999)\n        throw new Error('OutScript/tr_ns: invalid params');\n    // Enforce the allocation bound before doing curve work on an attacker-controlled key list.\n    const keySets = combinations(m, pubkeys);\n    if (allowSamePubkeys) {\n        for (const pubkey of pubkeys)\n            u.validatePubkey(pubkey, u.PubT.schnorr);\n    }\n    else\n        uniqPubkey(pubkeys, u.PubT.schnorr);\n    return keySets.map((keys) => {\n        // Keys were validated once above. Encoding through OutScript here would repeat lift_x for\n        // every key in every combination, turning a bounded leaf set into avoidable curve-level work.\n        const ops = [];\n        for (let i = 0; i < keys.length - 1; i++)\n            ops.push(keys[i], 'CHECKSIGVERIFY');\n        ops.push(keys[keys.length - 1], 'CHECKSIG');\n        return {\n            type: 'tr_ns',\n            script: Script.encode(ops),\n        };\n    });\n};\n/**\n * Builds a single-key taproot leaf script.\n * BIP 341 design guidance: if this is the most likely single-key spend path, prefer\n * using that key as the `p2tr()` internal key instead of forcing it into a script leaf.\n * @param pubkey - Schnorr public key\n * @returns Taproot single-key leaf descriptor.\n * @throws If the taproot single-key leaf cannot be encoded. {@link Error}\n * @throws If the delegated leaf policy exceeds its supported range. {@link RangeError}\n * @example\n * Build a single-key tapscript leaf.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2tr_pk } from '@scure/btc-signer/payment.js';\n * p2tr_pk(hex.decode('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9'));\n * ```\n */\nexport const p2tr_pk = (pubkey) => p2tr_ns(1, [pubkey], undefined)[0];\n/**\n * Builds a `CHECKSIGADD` taproot multisig leaf.\n * @param m - number of required signatures\n * @param pubkeys - participating Schnorr public keys\n * @param allowSamePubkeys - whether duplicate keys are allowed\n * @returns Taproot multisig leaf descriptor.\n * @throws If the taproot multisig parameters are invalid. {@link Error}\n * @example\n * Build a `CHECKSIGADD` taproot multisig leaf.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2tr_ms } from '@scure/btc-signer/payment.js';\n * p2tr_ms(1, [hex.decode('f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9')], true);\n * ```\n */\nexport function p2tr_ms(m, pubkeys, allowSamePubkeys = false) {\n    if (!allowSamePubkeys)\n        uniqPubkey(pubkeys, u.PubT.schnorr);\n    return {\n        type: 'tr_ms',\n        script: OutScript.encode({ type: 'tr_ms', pubkeys, m }),\n    };\n}\n// Simple pubkey address, without complex scripts\n/**\n * Derives a simple address from a private key.\n * @param type - address type to derive\n * @param privKey - private key bytes\n * @param network - address network parameters\n * @returns Encoded Bitcoin address.\n * @throws If the requested address type is unknown. {@link Error}\n * @throws If a key-derived script value is outside its supported range. {@link RangeError}\n * @example\n * Pick the output type first, then derive the matching address from the private key.\n * ```ts\n * import { getAddress } from '@scure/btc-signer/payment.js';\n * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * getAddress('wpkh', randomPrivateKeyBytes());\n * ```\n */\nexport function getAddress(type, privKey, network = NETWORK) {\n    u.astring(type, 'type');\n    if (type === 'tr') {\n        return p2tr(u.pubSchnorr(privKey), undefined, network).address;\n    }\n    // This convenience wrapper always uses the compressed ECDSA public key; derive\n    // `pubECDSA(privKey, false)` and call `p2pkh(...)` directly for legacy uncompressed P2PKH.\n    const pubKey = u.pubECDSA(privKey);\n    if (type === 'pkh')\n        return p2pkh(pubKey, network).address;\n    if (type === 'wpkh')\n        return p2wpkh(pubKey, network).address;\n    throw new Error(`getAddress: unknown type=${type}`);\n}\n// BIP67 defines canonical multisig ordering only for compressed pubkeys; this helper still sorts\n// raw bytes generically, and higher-level callers may accept uncompressed participants for compat.\nexport const _sortPubkeys = (pubkeys) => Array.from(pubkeys).sort(u.compareBytes);\n/**\n * Builds a classic M-of-N multisig output, wrapped in P2SH or P2WSH.\n * @param m - number of required signatures\n * @param pubkeys - participating public keys\n * @param sorted - whether to sort the public keys first\n * @param witness - whether to wrap the result as native SegWit\n * @param network - address network parameters\n * @returns Multisig payment descriptor.\n * @throws If the multisig parameters or wrapped script are invalid. {@link Error}\n * @example\n * Wrap a classic 2-of-2 script into an addressable multisig output.\n * ```ts\n * import { multisig } from '@scure/btc-signer/payment.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * multisig(\n *   2,\n *   [pubECDSA(randomPrivateKeyBytes()), pubECDSA(randomPrivateKeyBytes())],\n *   true,\n *   true\n * );\n * ```\n */\nexport function multisig(m, pubkeys, sorted = false, witness = false, network = NETWORK) {\n    // BIP 143 default policy: version-0 witness programs should use compressed ECDSA pubkeys only;\n    // witness multisig callers must avoid uncompressed keys because p2ms accepts generic ECDSA encodings.\n    // BIP 16 caps spendable compressed-key P2SH multisig at 15 pubkeys because larger redeem scripts\n    // exceed the 520-byte push limit; use witness=true for larger classic multisig sets.\n    const ms = p2ms(m, sorted ? _sortPubkeys(pubkeys) : pubkeys);\n    return (witness ? p2wsh(ms, network) : p2sh(ms, network));\n}\n/**\n * Builds a multisig output after lexicographically sorting the keys.\n * @param m - number of required signatures\n * @param pubkeys - participating public keys\n * @param witness - whether to wrap the result as native SegWit\n * @param network - address network parameters\n * @returns Sorted multisig payment descriptor.\n * @throws If the multisig parameters or wrapped script are invalid. {@link Error}\n * @example\n * Sort public keys deterministically before constructing the multisig address.\n * ```ts\n * import { sortedMultisig } from '@scure/btc-signer/payment.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * sortedMultisig(\n *   2,\n *   [pubECDSA(randomPrivateKeyBytes()), pubECDSA(randomPrivateKeyBytes())],\n *   true\n * );\n * ```\n */\nexport function sortedMultisig(m, pubkeys, witness = false, network = NETWORK) {\n    // BIP67 canonical multisig is compressed-only, but this wrapper intentionally keeps the generic\n    // sorted-multisig behavior and still allows uncompressed participant keys for compatibility.\n    return multisig(m, pubkeys, true, witness, network);\n}\nconst base58check = /* @__PURE__ */ createBase58check(u.sha256);\nfunction validateWitness(version, data) {\n    if (data.length < 2 || data.length > 40)\n        throw new Error('Witness: invalid length');\n    if (version > 16)\n        throw new Error('Witness: invalid version');\n    if (version === 0 && !(data.length === 20 || data.length === 32))\n        throw new Error('Witness: invalid length for version');\n}\nfunction programToWitness(version, data, network = NETWORK) {\n    validateWitness(version, data);\n    // BIP 350 keeps segwit v0 on Bech32, while witness versions 1+ switch to Bech32m.\n    const coder = version === 0 ? bech32 : bech32m;\n    return coder.encode(network.bech32, [version].concat(coder.toWords(data)));\n}\nfunction formatKey(hashed, prefix) {\n    // Legacy Base58Check paths all serialize [version-byte || payload] before checksumming.\n    return base58check.encode(u.concatBytes(Uint8Array.from(prefix), hashed));\n}\n/**\n * Wallet-import-format coder for private keys.\n * @param network - address network parameters\n * @returns WIF coder.\n * @example\n * Encode or decode wallet-import-format private keys.\n * ```ts\n * const coder = WIF();\n * coder.encode(new Uint8Array(32).fill(1));\n * ```\n */\nexport function WIF(network = NETWORK) {\n    return {\n        encode(privKey) {\n            // Compressed WIF is exactly 32 private-key bytes plus the 0x01 suffix; shorter or longer\n            // inputs must be rejected instead of being silently padded or truncated by subarray().\n            abytes(privKey, 32, 'privKey');\n            const compressed = u.concatBytes(privKey, new Uint8Array([0x01]));\n            return formatKey(compressed.subarray(0, 33), [network.wif]);\n        },\n        decode(wif) {\n            let parsed = base58check.decode(wif);\n            if (parsed[0] !== network.wif)\n                throw new Error('Wrong WIF prefix');\n            parsed = parsed.subarray(1);\n            // Check what it is. Compressed flag?\n            if (parsed.length !== 33)\n                throw new Error('Wrong WIF length');\n            if (parsed[32] !== 0x01)\n                throw new Error('Wrong WIF postfix');\n            return parsed.subarray(0, -1);\n        },\n    };\n}\n// Returns OutType, which can be used to create outscript\n/**\n * Address encoder/decoder for a specific Bitcoin network.\n * @param network - address network parameters\n * @returns Address coder backed by the provided network.\n * @example\n * Create a network-specific address coder and encode a payment descriptor.\n * ```ts\n * import { Address, p2wpkh } from '@scure/btc-signer/payment.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * const coder = Address();\n * coder.encode(p2wpkh(pubECDSA(randomPrivateKeyBytes())));\n * ```\n */\nexport function Address(network = NETWORK) {\n    u.validateObject(network, {}, {}, 'network');\n    return {\n        encode(from) {\n            u.validateObject(from, {}, {}, 'from');\n            const { type } = from;\n            u.astring(type, 'from.type');\n            if (type === 'wpkh')\n                return programToWitness(0, from.hash, network);\n            else if (type === 'wsh')\n                return programToWitness(0, from.hash, network);\n            else if (type === 'tr')\n                return programToWitness(1, from.pubkey, network);\n            // BIP433 P2A is the fixed v1 witness program 0x4e73 ('bc1pfeessrawgf').\n            else if (type === 'p2a')\n                return programToWitness(1, P2A_PROGRAM, network);\n            else if (type === 'pkh')\n                return formatKey(from.hash, [network.pubKeyHash]);\n            else if (type === 'sh')\n                return formatKey(from.hash, [network.scriptHash]);\n            throw new Error(`Unknown address type=${type}`);\n        },\n        decode(address) {\n            u.astring(address, 'address');\n            if (address.length < 14 || address.length > 74)\n                throw new Error('Invalid address length');\n            // Bech32\n            if (network.bech32 && address.toLowerCase().startsWith(`${network.bech32}1`)) {\n                let res;\n                try {\n                    res = bech32.decode(address);\n                    if (res.words[0] !== 0)\n                        throw new Error(`bech32: wrong version=${res.words[0]}`);\n                }\n                catch (_) {\n                    // Starting from version 1 it is decoded as bech32m\n                    res = bech32m.decode(address);\n                    if (res.words[0] === 0)\n                        throw new Error(`bech32m: wrong version=${res.words[0]}`);\n                }\n                if (res.prefix !== network.bech32)\n                    throw new Error(`wrong bech32 prefix=${res.prefix}`);\n                const [version, ...program] = res.words;\n                const data = bech32.fromWords(program);\n                validateWitness(version, data);\n                if (version === 0 && data.length === 32)\n                    return { type: 'wsh', hash: data };\n                else if (version === 0 && data.length === 20)\n                    return { type: 'wpkh', hash: data };\n                else if (version === 1 && data.length === 32)\n                    return { type: 'tr', pubkey: data };\n                else if (version === 1 && u.equalBytes(data, P2A_PROGRAM))\n                    return { type: 'p2a', script: Script.encode([1, data]) };\n                // Future witness versions can still be valid addresses, but this helper\n                // only returns typed descriptors for recognized v0, taproot and P2A templates.\n                else\n                    throw new Error('Unknown witness program');\n            }\n            const data = base58check.decode(address);\n            if (data.length !== 21)\n                throw new Error('Invalid base58 address');\n            // Pay To Public Key Hash\n            if (data[0] === network.pubKeyHash) {\n                return { type: 'pkh', hash: data.slice(1) };\n            }\n            else if (data[0] === network.scriptHash) {\n                return {\n                    type: 'sh',\n                    hash: data.slice(1),\n                };\n            }\n            throw new Error(`Invalid address prefix=${data[0]}`);\n        },\n    };\n}\n","import { hex } from '@scure/base';\nimport { anumber } from '@noble/hashes/utils.js';\nimport * as P from 'micro-packed';\nimport { Address, OutScript, _WitnessOutScript, checkScript, tapLeafHash, } from \"./payment.js\";\nimport * as psbt from \"./psbt.js\";\nimport { CompactSizeLen, OP, RawOldTx, RawInput, RawOutput, RawTx, RawWitness, Script, scriptPushLen, VarBytes, } from \"./script.js\";\nimport * as u from \"./utils.js\";\nimport { NETWORK, abigint, concatBytes, equalBytes, isBytes, validateObject, } from \"./utils.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals.\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1);\nconst U64_MAX = /* @__PURE__ */ BigInt('0xffffffffffffffff');\nconst EMPTY32 = /* @__PURE__ */ new Uint8Array(32);\nconst EMPTY_OUTPUT = {\n    amount: U64_MAX,\n    script: P.EMPTY,\n};\n/**\n * Converts transaction weight units into virtual bytes.\n * @param weight - transaction weight\n * @returns Rounded-up virtual size.\n * @example\n * Convert transaction weight units into virtual bytes.\n * ```ts\n * toVsize(4);\n * ```\n */\nexport const toVsize = (weight) => Math.ceil(weight / 4);\nconst stripCodeSeparator = (script) => {\n    // Reuse Script's raw pushdata-length parser here. Legacy sighash must remove\n    // only actual OP_CODESEPARATOR opcodes while preserving every other original\n    // byte, because semantic decode/re-encode would change the signed digest.\n    let start = 0;\n    const out = [];\n    for (let i = 0; i < script.length;) {\n        const pos = i;\n        const op = script[i++];\n        if (op === OP.CODESEPARATOR) {\n            if (start < pos)\n                out.push(script.subarray(start, pos));\n            start = i;\n            continue;\n        }\n        const len = scriptPushLen(op, (bytes) => {\n            if (i + bytes > script.length)\n                throw new Error('Unexpected end of script');\n            let len = 0;\n            for (let j = 0; j < bytes; j++)\n                len |= script[i + j] << (8 * j);\n            i += bytes;\n            return len;\n        });\n        if (len === undefined)\n            continue;\n        i += len;\n        if (i > script.length)\n            throw new Error('Unexpected end of script');\n    }\n    if (start === 0)\n        return script;\n    if (start < script.length)\n        out.push(script.subarray(start));\n    return (out.length ? concatBytes(...out) : P.EMPTY);\n};\n/** Decimal precision used for BTC string formatting. */\nexport const PRECISION = 8;\n/** Default transaction version used for newly created transactions. */\nexport const DEFAULT_VERSION = 2;\n/** Default transaction locktime. */\nexport const DEFAULT_LOCKTIME = 0;\n/** Default input sequence number.\n * Final (`0xffffffff`): matches the PSBT omission default and disables nLockTime/CLTV semantics\n * unless callers choose a lower sequence explicitly (for example `0xfffffffe` with lockTime).\n */\nexport const DEFAULT_SEQUENCE = 4294967295;\n/**\n * Decimal coder for BTC-denominated strings.\n * This is a fixed-precision BTC-string to satoshi-bigint helper, not a validator\n * for transaction/PSBT output amounts. Signed values are intentional here, so\n * callers can reuse the helper for display/history-style deltas as well as\n * unsigned transfer amounts. It keeps the BTC scale at 8 fractional digits and\n * rejects over-precise inputs instead of rounding.\n * @example\n * Convert between satoshi bigint values and BTC-denominated decimal strings.\n * ```ts\n * Decimal.encode(1n);\n * ```\n */\nexport const Decimal = /* @__PURE__ */ (() => Object.freeze(P.coders.decimal(PRECISION)))();\n// Same as value || def, but doesn't overwrites zero ('0', 0, 0n, etc)\n/**\n * Returns a fallback only when the value is `undefined`.\n * @param value - optional value\n * @param def - fallback value\n * @returns `value` when defined, otherwise `def`.\n * @example\n * Keep zero-like values but replace `undefined` with a fallback.\n * ```ts\n * def(undefined, 1);\n * ```\n */\nexport const def = (value, def) => (value === undefined ? def : value);\n/**\n * Deep-clones plain transaction data structures.\n * @param obj - value to clone\n * @returns Deep copy of the input value.\n * @throws If the value contains an unsupported runtime type. {@link Error}\n * @example\n * Clone plain transaction data structures before mutating them.\n * ```ts\n * cloneDeep({ a: [new Uint8Array([1])] });\n * ```\n */\nexport function cloneDeep(obj) {\n    if (Array.isArray(obj))\n        return obj.map((i) => cloneDeep(i));\n    // slice of nodejs Buffer doesn't copy\n    else if (isBytes(obj))\n        return Uint8Array.from(obj);\n    // immutable\n    else if (['number', 'bigint', 'boolean', 'string', 'undefined'].includes(typeof obj))\n        return obj;\n    // null is object\n    else if (obj === null)\n        return obj;\n    // should be last, so it won't catch other types\n    else if (typeof obj === 'object') {\n        return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, cloneDeep(v)]));\n    }\n    // Don't interpolate unsupported values here: Symbol string coercion would\n    // throw before cloneDeep can surface its own stable helper error.\n    throw new Error(`cloneDeep: unknown type=${typeof obj}`);\n}\n/**\n * Internal, exported only for backwards-compat. Use `SigHash` instead.\n * @deprecated Use {@link SigHash} instead.\n * @example\n * Combine the legacy bit flags when interoperating with older code.\n * ```ts\n * SignatureHash.ALL | SignatureHash.ANYONECANPAY;\n * ```\n */\nexport const SignatureHash = /* @__PURE__ */ (() => Object.freeze({\n    DEFAULT: 0,\n    ALL: 1,\n    NONE: 2,\n    SINGLE: 3,\n    ANYONECANPAY: 0x80,\n}))();\n/**\n * Common signature hash flag combinations.\n * @example\n * Use the predefined signature-hash combinations exported by the library.\n * ```ts\n * SigHash.SINGLE_ANYONECANPAY;\n * ```\n */\nexport const SigHash = /* @__PURE__ */ (() => Object.freeze({\n    DEFAULT: SignatureHash.DEFAULT,\n    ALL: SignatureHash.ALL,\n    NONE: SignatureHash.NONE,\n    SINGLE: SignatureHash.SINGLE,\n    // BIP341 only permits 0x00, 0x01, 0x02, 0x03, 0x81, 0x82, and 0x83 for taproot, so\n    // the mechanical `DEFAULT | ANYONECANPAY` combination (0x80) is invalid and not exported.\n    // DEFAULT_ANYONECANPAY: SignatureHash.DEFAULT | SignatureHash.ANYONECANPAY,\n    ALL_ANYONECANPAY: SignatureHash.ALL | SignatureHash.ANYONECANPAY,\n    NONE_ANYONECANPAY: SignatureHash.NONE | SignatureHash.ANYONECANPAY,\n    SINGLE_ANYONECANPAY: SignatureHash.SINGLE | SignatureHash.ANYONECANPAY,\n}))();\n/** Reverse lookup table for signature hash flag names. */\nexport const SigHashNames = /* @__PURE__ */ (() => Object.freeze(u.reverseObject(SigHash)))();\nfunction getTaprootKeys(privKey, pubKey, internalKey, merkleRoot = P.EMPTY) {\n    if (equalBytes(internalKey, pubKey)) {\n        privKey = u.taprootTweakPrivKey(privKey, merkleRoot);\n        pubKey = u.pubSchnorr(privKey);\n    }\n    return { privKey, pubKey };\n}\n// Force check amount/script\nfunction outputBeforeSign(i) {\n    if (i.script === undefined || i.amount === undefined)\n        throw new Error('Transaction/output: script and amount required');\n    return { script: i.script, amount: i.amount };\n}\n// Force check index/txid/sequence\n/**\n * Normalizes a PSBT input into the fields needed for signing.\n * @param i - PSBT input to validate\n * @returns Input fields required for signing.\n * @throws If the input is missing `txid` or `index`. {@link Error}\n * @example\n * Fill in defaults for the fields the signer expects to see.\n * ```ts\n * import { hex } from '@scure/base';\n * import { inputBeforeSign } from '@scure/btc-signer/transaction.js';\n * inputBeforeSign({\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n * });\n * ```\n */\nexport function inputBeforeSign(i) {\n    validateObject(i, {}, {}, 'i');\n    if (i.txid === undefined || i.index === undefined)\n        throw new Error('Transaction/input: txid and index required');\n    const res = {\n        txid: i.txid,\n        index: i.index,\n        sequence: def(i.sequence, DEFAULT_SEQUENCE),\n        finalScriptSig: def(i.finalScriptSig, P.EMPTY),\n    };\n    // This helper is the public \"normalize for signing\" boundary, so reuse RawInput's existing\n    // wire-shape checks here instead of letting malformed runtime field types fail much later.\n    RawInput.encode(res);\n    return res;\n}\nconst cleanExtensions = (map, unknownMode, proprietaryMode, rejectStrip = false) => {\n    const out = { ...map };\n    for (const [name, mode] of [\n        ['unknown', unknownMode],\n        ['proprietary', proprietaryMode],\n    ]) {\n        const value = out[name];\n        // Policy cleanup must not reinterpret malformed caller metadata as an empty keyed map.\n        if (value !== undefined)\n            u.aarray(value, `${name} PSBT field`);\n        const rows = value;\n        if (!rows?.length) {\n            delete out[name];\n            continue;\n        }\n        if (mode === 'strict')\n            throw new Error(`PSBT: ${name} PSBT field is not allowed in strict mode`);\n        if (mode === 'strip') {\n            // Silent stripping is appropriate at relay/cleanup boundaries. On direct mutation it would\n            // hide a caller bug by accepting metadata that can never become transaction state.\n            if (rejectStrip)\n                throw new Error(`PSBT: ${name} PSBT field cannot be supplied when policy is strip`);\n            delete out[name];\n        }\n    }\n    return out;\n};\nconst cleanTxModifiable = (value, mode) => {\n    if (value === undefined || !(value & ~0b111))\n        return value;\n    if (mode === 'strict')\n        throw new Error('PSBT: unknown txModifiable bits in strict mode');\n    return mode === 'strip' ? value & 0b111 : value;\n};\nfunction cleanFinalInput(i, unknownMode = 'strip', proprietaryMode = 'strip') {\n    const _i = i;\n    const extensions = cleanExtensions(_i, unknownMode, proprietaryMode);\n    if (extensions.unknown)\n        _i.unknown = extensions.unknown;\n    else\n        delete _i.unknown;\n    if (extensions.proprietary)\n        _i.proprietary = extensions.proprietary;\n    else\n        delete _i.proprietary;\n    // BIP174 finalizers clear non-final input metadata after constructing final scripts/witnesses.\n    // That intentionally drops sighashType here, so post-finalize mutation becomes conservative\n    // until callers explicitly clear satisfaction by removing finalScriptSig/finalScriptWitness.\n    for (const _k in _i) {\n        const k = _k;\n        // Proprietary records are cleanup metadata too, but callers may need their opaque protocol\n        // state after finalization for PSBT coordination outside transaction extraction. An empty\n        // keyed list encodes no records, so canonicalize it to absence like its serialized clone.\n        if (proprietaryMode === 'ignore' && k === 'proprietary' && _i.proprietary?.length)\n            continue;\n        if (!psbt.PSBTInputFinalKeys.includes(k))\n            delete _i[k];\n    }\n}\n// (TxHash, Idx)\nconst TxHashIdx = /* @__PURE__ */ (() => P.struct({ txid: P.bytes(32, true), index: P.U32LE }))();\nfunction validateSigHash(s) {\n    if (typeof s !== 'number' || typeof SigHashNames[s] !== 'string')\n        throw new Error(`Invalid SigHash=${s}`);\n    return s;\n}\nfunction unpackSighash(hashType) {\n    const masked = hashType & 0b0011111;\n    return {\n        isAny: !!(hashType & SignatureHash.ANYONECANPAY),\n        isNone: masked === SignatureHash.NONE,\n        isSingle: masked === SignatureHash.SINGLE,\n    };\n}\nconst sighashScope = (sighash) => ({\n    sigInputs: sighash & SignatureHash.ANYONECANPAY,\n    sigOutputs: sighash === SignatureHash.DEFAULT ? SignatureHash.ALL : sighash & 0b11,\n});\nconst normalizeUnknowns = (name, mode, legacy, fallback = 'strip') => {\n    const alias = legacy === undefined ? undefined : legacy ? 'ignore' : 'strip';\n    if (mode !== undefined && mode !== 'ignore' && mode !== 'strip' && mode !== 'strict')\n        throw new Error(`Transaction options wrong value: ${name}=${mode}`);\n    if (mode !== undefined && alias !== undefined && mode !== alias)\n        throw new Error(`Transaction options: conflicting ${name} options`);\n    return mode || alias || fallback;\n};\nfunction validateOpts(opts) {\n    if (opts !== undefined)\n        validateObject(opts, {}, {}, 'opts');\n    const _opts = {\n        ...opts,\n        // Defaults\n        version: def(opts.version, DEFAULT_VERSION),\n        lockTime: def(opts.lockTime, 0),\n        PSBTVersion: def(opts.PSBTVersion, 0),\n    };\n    // Normalize deprecated aliases on the owned copy so they still affect tx.opts without rewriting the\n    // caller-owned options object passed to the constructor.\n    if (typeof _opts.allowUnknowInput !== 'undefined')\n        _opts.allowUnknownInputs = _opts.allowUnknowInput;\n    if (typeof _opts.allowUnknowOutput !== 'undefined')\n        _opts.allowUnknownOutputs = _opts.allowUnknowOutput;\n    if (_opts.allowMissingTxModifiable === undefined)\n        _opts.allowMissingTxModifiable = true;\n    if (typeof _opts.lockTime !== 'number')\n        throw new Error('Transaction lock time should be number');\n    P.U32LE.encode(_opts.lockTime); // Additional range checks that lockTime\n    // There is no PSBT v1, and any new version will probably have fields which we don't know how to parse, which\n    // can lead to constructing broken transactions\n    if (_opts.PSBTVersion !== 0 && _opts.PSBTVersion !== 2)\n        throw new Error(`Unknown PSBT version ${_opts.PSBTVersion}`);\n    // Flags\n    for (const k of [\n        'allowUnknownVersion',\n        'allowUnknownOutputs',\n        'allowUnknownInputs',\n        'disableScriptCheck',\n        'bip174jsCompat',\n        'allowLegacyWitnessUtxo',\n        'strictPrevoutValidation',\n        'lowR',\n        'allowUnknown',\n        'allowMissingTxModifiable',\n    ]) {\n        const v = _opts[k];\n        if (v === undefined)\n            continue; // optional\n        if (typeof v !== 'boolean')\n            throw new Error(`Transation options wrong type: ${k}=${v} (${typeof v})`);\n    }\n    _opts.unknown = normalizeUnknowns('unknown', _opts.unknown, _opts.allowUnknown);\n    _opts.proprietary = normalizeUnknowns('proprietary', _opts.proprietary, undefined, _opts.unknown);\n    // 0 and -1 happens in tests\n    // With allowUnknownVersion any numeric version is fine; the ternary was inverted\n    // before 2026-07 (audit), which made the option throw for every numeric version.\n    if (_opts.allowUnknownVersion\n        ? typeof _opts.version !== 'number'\n        : ![-1, 0, 1, 2, 3].includes(_opts.version))\n        throw new Error(`Unknown version: ${_opts.version}`);\n    P.I32LE.encode(_opts.version); // Validate the signed transaction-version wire domain.\n    if (_opts.customScripts !== undefined) {\n        const cs = _opts.customScripts;\n        if (!Array.isArray(cs)) {\n            throw new Error(`wrong custom scripts type (expected array): customScripts=${cs} (${typeof cs})`);\n        }\n        for (const s of cs) {\n            if (typeof s.encode !== 'function' || typeof s.decode !== 'function')\n                throw new Error(`wrong script=${s} (${typeof s})`);\n            if (s.finalizeTaproot !== undefined && typeof s.finalizeTaproot !== 'function')\n                throw new Error(`wrong script=${s} (${typeof s})`);\n        }\n    }\n    return Object.freeze(_opts);\n}\nfunction checkTaprootInputCommitments(input, prevScript) {\n    const output = _WitnessOutScript.decode(prevScript);\n    const hasTaprootCommitments = input.tapInternalKey !== undefined ||\n        input.tapMerkleRoot !== undefined ||\n        // Repeated keyed fields only exist on the PSBT wire when at least one entry is encoded.\n        !!input.tapLeafScript?.length;\n    if (output.type !== 'tr') {\n        if (hasTaprootCommitments)\n            throw new Error('validateInput: Taproot metadata without P2TR previous output');\n        return;\n    }\n    const checkOutputKey = (internalKey, merkleRoot, parity) => {\n        const [outputKey, outputParity] = u.taprootTweakPubkey(internalKey, merkleRoot);\n        if (!equalBytes(outputKey, output.pubkey))\n            throw new Error('validateInput: Taproot commitment does not match previous output');\n        if (parity !== undefined && outputParity !== parity)\n            throw new Error('validateInput: Taproot control-block parity does not match previous output');\n    };\n    if (input.tapLeafScript) {\n        for (const [controlBlock, scriptWithVersion] of input.tapLeafScript) {\n            const leafVersion = scriptWithVersion[scriptWithVersion.length - 1];\n            const script = scriptWithVersion.subarray(0, -1);\n            let merkleRoot = tapLeafHash(script, leafVersion);\n            for (const sibling of controlBlock.merklePath) {\n                merkleRoot =\n                    u.compareBytes(sibling, merkleRoot) === -1\n                        ? u.tagSchnorr('TapBranch', sibling, merkleRoot)\n                        : u.tagSchnorr('TapBranch', merkleRoot, sibling);\n            }\n            checkOutputKey(controlBlock.internalKey, merkleRoot, controlBlock.version & 1);\n            if (input.tapInternalKey && !equalBytes(input.tapInternalKey, controlBlock.internalKey))\n                throw new Error('validateInput: tapInternalKey does not match Taproot control block');\n            if (input.tapMerkleRoot && !equalBytes(input.tapMerkleRoot, merkleRoot))\n                throw new Error('validateInput: tapMerkleRoot does not match Taproot control block');\n        }\n    }\n    // A tree-bearing input can omit the aggregate root while still providing independently\n    // verifiable control blocks. With no leaves, an internal key without a root describes the\n    // standard key-only (empty-root) commitment.\n    if (input.tapInternalKey && (input.tapMerkleRoot || !input.tapLeafScript?.length))\n        checkOutputKey(input.tapInternalKey, input.tapMerkleRoot || P.EMPTY);\n}\nconst LOCKTIME_THRESHOLD = 500_000_000;\nfunction validateRequiredLocktimes(input) {\n    const height = input.requiredHeightLocktime;\n    if (height !== undefined) {\n        anumber(height, 'requiredHeightLocktime');\n        if (height === 0 || height >= LOCKTIME_THRESHOLD)\n            throw new RangeError(`requiredHeightLocktime must be between 1 and ${LOCKTIME_THRESHOLD - 1}, got ${height}`);\n    }\n    const time = input.requiredTimeLocktime;\n    if (time !== undefined) {\n        anumber(time, 'requiredTimeLocktime');\n        if (time < LOCKTIME_THRESHOLD || time > 0xffffffff)\n            throw new RangeError(`requiredTimeLocktime must be between ${LOCKTIME_THRESHOLD} and 4294967295, got ${time}`);\n    }\n}\nfunction resolvePSBTLocktime(inputs, fallback = DEFAULT_LOCKTIME) {\n    let height = DEFAULT_LOCKTIME;\n    let time = DEFAULT_LOCKTIME;\n    let hasRequirements = false;\n    let heightSupported = true;\n    let timeSupported = true;\n    for (const input of inputs) {\n        validateRequiredLocktimes(input);\n        const hasHeight = input.requiredHeightLocktime !== undefined;\n        const hasTime = input.requiredTimeLocktime !== undefined;\n        if (!hasHeight && !hasTime)\n            continue;\n        hasRequirements = true;\n        if (hasHeight)\n            height = Math.max(height, input.requiredHeightLocktime);\n        else\n            heightSupported = false;\n        if (hasTime)\n            time = Math.max(time, input.requiredTimeLocktime);\n        else\n            timeSupported = false;\n    }\n    if (!hasRequirements)\n        return fallback;\n    // BIP370 requires height when every relevant input supports both domains.\n    if (heightSupported)\n        return height;\n    if (timeSupported)\n        return time;\n    throw new Error('PSBTv2: incompatible height-based and time-based locktime requirements');\n}\n// NOTE: we cannot do this inside PSBTInput coder, because there is no index/txid at this point!\nfunction validateInput(i, disableScriptCheck = false) {\n    validateObject(i, {}, {}, 'i');\n    const _i = i;\n    validateRequiredLocktimes(_i);\n    let prevOut;\n    if (_i.nonWitnessUtxo && _i.index !== undefined) {\n        const last = _i.nonWitnessUtxo.outputs.length - 1;\n        if (_i.index > last)\n            throw new Error(`validateInput: index(${_i.index}) not in nonWitnessUtxo`);\n        prevOut = _i.nonWitnessUtxo.outputs[_i.index];\n        if (_i.witnessUtxo &&\n            (!equalBytes(_i.witnessUtxo.script, prevOut.script) ||\n                _i.witnessUtxo.amount !== prevOut.amount))\n            throw new Error('validateInput: witnessUtxo different from nonWitnessUtxo');\n        if (_i.txid) {\n            const outputs = _i.nonWitnessUtxo.outputs;\n            if (outputs.length - 1 < _i.index)\n                throw new Error('nonWitnessUtxo: incorect output index');\n            // At this point, we are using previous tx output to create new input.\n            // Script safety checks are unnecessary:\n            // - User has no control over previous tx. If somebody send money in same tx\n            //   as unspendable output, we still want user able to spend money\n            // - We still want some checks to notify user about possible errors early\n            //   in case user wants to use wrong input by mistake\n            // - Worst case: tx will be rejected by nodes. Still better than disallowing user\n            //   to spend real input, no matter how broken it looks\n            const tx = Transaction.fromRaw(RawTx.encode(_i.nonWitnessUtxo), {\n                allowUnknownOutputs: true,\n                disableScriptCheck: true,\n                allowUnknownInputs: true,\n                // Consensus does not restrict nVersion; a previous tx with a non-standard\n                // version is still spendable and its txid must still be verifiable.\n                allowUnknownVersion: true,\n            });\n            const txid = hex.encode(_i.txid);\n            // BIP174 requires the provided nonWitnessUtxo to hash to the prevout txid even when the\n            // previous transaction is otherwise non-final; finality does not make its serialized txid optional.\n            // Keep the historical TransactionInput.txid convention here: internal txid bytes match\n            // `Transaction.id` (display-order hex), while raw-tx / PSBT boundary coders are responsible\n            // for any byte-order conversions required by their wire formats.\n            if (tx.id !== txid)\n                throw new Error(`nonWitnessUtxo: wrong txid, exp=${txid} got=${tx.id}`);\n        }\n    }\n    else if (_i.witnessUtxo)\n        prevOut = _i.witnessUtxo;\n    if (prevOut && !disableScriptCheck) {\n        checkScript(prevOut.script, _i.redeemScript, _i.witnessScript);\n        checkTaprootInputCommitments(_i, prevOut.script);\n    }\n    return _i;\n}\nconst inputSignatures = (input) => {\n    const _input = input;\n    const res = [];\n    const add = (signature, taproot, scriptPath = false) => {\n        const sig = signature;\n        if (!sig.length)\n            return;\n        // Taproot's 64-byte encoding omits the SIGHASH_DEFAULT byte; every other PSBT signature\n        // carries its sighash in the final byte, including signatures imported from another signer.\n        const sighash = taproot && sig.length === 64 ? SignatureHash.DEFAULT : sig[sig.length - 1];\n        res.push({ sighash, taproot, scriptPath });\n    };\n    for (const [, signature] of _input.partialSig || [])\n        add(signature, false);\n    if (_input.tapKeySig)\n        add(_input.tapKeySig, true);\n    for (const [, signature] of _input.tapScriptSig || [])\n        add(signature, true, true);\n    return res;\n};\nconst inputSignedKeys = {\n    // sighashType is signer policy rather than a digest byte, but changing it after one signature\n    // exists would make later signers interpret the same input under a different policy.\n    self: ['txid', 'index', 'sequence', 'nonWitnessUtxo', 'witnessUtxo', 'sighashType'],\n    ecdsa: ['redeemScript', 'witnessScript'],\n    tapscript: ['tapLeafScript'],\n    cross: ['txid', 'index'],\n    prevout: ['nonWitnessUtxo', 'witnessUtxo'],\n};\n// Normalizes input\n/**\n * Extracts the previous output referenced by an input.\n * @param input - PSBT input with previous output data\n * @returns Previous output information.\n * @throws If the input does not contain usable previous-output information. {@link Error}\n * @example\n * Read the previous output from either `witnessUtxo` or `nonWitnessUtxo`.\n * ```ts\n * getPrevOut({ witnessUtxo: { amount: 1n, script: new Uint8Array([0x51]) } });\n * ```\n */\nexport function getPrevOut(input) {\n    validateObject(input, {}, {}, 'input');\n    const _input = input;\n    if (_input.nonWitnessUtxo) {\n        if (_input.index === undefined)\n            throw new Error('Unknown input index');\n        // BIP174 `PSBT_IN_NON_WITNESS_UTXO` is the full spent transaction, so the\n        // input outpoint index must name an existing output instead of leaking a\n        // synthetic `undefined` prevout into later signing / estimation callers.\n        if (!Number.isSafeInteger(_input.index) ||\n            _input.index < 0 ||\n            _input.index >= _input.nonWitnessUtxo.outputs.length)\n            throw new Error(`Wrong input index=${_input.index}`);\n        return _input.nonWitnessUtxo.outputs[_input.index];\n    }\n    else if ('witnessUtxo' in _input) {\n        // The presence check catches malformed provided values; narrow after the guard for TS.\n        const prev = _input.witnessUtxo;\n        validateObject(prev, {}, {}, 'input.witnessUtxo');\n        abigint(prev.amount, 'input.witnessUtxo.amount');\n        if (!isBytes(prev.script))\n            throw new TypeError('\"input.witnessUtxo.script\" expected Uint8Array, got type=' + typeof prev.script);\n        return prev;\n    }\n    else\n        throw new Error('Cannot find previous output info');\n}\n/**\n * Normalizes a transaction input update into canonical PSBT form.\n * @param i - input update to normalize\n * @param cur - existing input value to merge with\n * @param allowedFields - fields that may still change on signed inputs\n * @param disableScriptCheck - whether to skip wrapper and Taproot commitment sanity checks\n * @param unknown - handling policy for unknown PSBT fields\n * @param proprietary - handling policy for proprietary PSBT fields\n * @returns Normalized PSBT input.\n * @throws If the update conflicts with the existing input or its signatures. {@link Error}\n * @throws If a numeric input field is outside its wire or protocol range. {@link RangeError}\n * @example\n * Accept hex txids from callers in the same display-order form used by `Transaction.id`, then\n * normalize them into the repo's internal `TransactionInput` shape.\n * ```ts\n * import { hex } from '@scure/base';\n * import { normalizeInput } from '@scure/btc-signer/transaction.js';\n * normalizeInput({\n *   txid: '0000000000000000000000000000000000000000000000000000000000000001',\n *   index: 0,\n *   witnessUtxo: { amount: 1n, script: new Uint8Array([0x51]) },\n * });\n * ```\n */\nexport function normalizeInput(i, cur, allowedFields, disableScriptCheck = false, unknown = 'strip', proprietary = 'strip') {\n    validateObject(i, {}, {}, 'i');\n    if (cur !== undefined)\n        validateObject(cur, {}, {}, 'cur');\n    if (allowedFields !== undefined)\n        u.aarray(allowedFields, 'allowedFields');\n    const _i = i;\n    const _cur = cur;\n    const _allowedFields = allowedFields;\n    let { nonWitnessUtxo, txid } = _i;\n    // String support for common fields. We usually prefer Uint8Array to avoid errors\n    // like hex looking string accidentally passed, however, in case of nonWitnessUtxo\n    // it is better to expect string, since constructing this complex object will be\n    // difficult for user\n    if (typeof nonWitnessUtxo === 'string')\n        nonWitnessUtxo = hex.decode(nonWitnessUtxo);\n    if (isBytes(nonWitnessUtxo))\n        nonWitnessUtxo = RawTx.decode(nonWitnessUtxo);\n    if (!('nonWitnessUtxo' in _i) && nonWitnessUtxo === undefined)\n        nonWitnessUtxo = _cur?.nonWitnessUtxo;\n    if (typeof txid === 'string')\n        txid = hex.decode(txid);\n    // TODO: if we have nonWitnessUtxo, we can extract txId from here\n    if (txid === undefined)\n        txid = _cur?.txid;\n    let res = { ..._cur, ..._i, nonWitnessUtxo, txid };\n    if (!('nonWitnessUtxo' in _i) && res.nonWitnessUtxo === undefined)\n        delete res.nonWitnessUtxo;\n    if (res.sequence === undefined)\n        res.sequence = DEFAULT_SEQUENCE;\n    if (res.tapMerkleRoot === null)\n        delete res.tapMerkleRoot;\n    res = psbt.mergeKeyMap(psbt.PSBTInput, res, _cur, _allowedFields, unknown, proprietary);\n    // An actual empty repeated field emits no PSBT keypairs. Canonicalize only arrays so malformed\n    // falsy values still reach the PSBT coder's validation instead of becoming valid absence.\n    if (Array.isArray(res.tapLeafScript) && !res.tapLeafScript.length)\n        delete res.tapLeafScript;\n    validateRequiredLocktimes(res);\n    // Public PSBT coder surface is wrapped with TArg/TRet for TS compatibility; normalizeInput keeps\n    // the repo's historical raw internal shape and casts only at the validation boundary here.\n    psbt.PSBTInputCoder.encode(res); // Validates that everything is correct at this point\n    // Direct construction and UTXO selection consume nonWitnessUtxo amounts without crossing a\n    // PSBT serialization boundary. Enforce the same outpoint binding here so a mismatched previous\n    // transaction cannot understate a legacy input amount and turn the difference into mining fees.\n    return validateInput(res, disableScriptCheck);\n}\n/**\n * Determines how an input should be signed and finalized.\n * Wrapper consistency is expected to be validated earlier by {@link normalizeInput}\n * and {@link checkScript}; this helper classifies already-normalized inputs and is\n * not a standalone redeemScript/witnessScript correctness gate for raw caller input.\n * @param input - PSBT input to inspect\n * @param allowLegacyWitnessUtxo - whether legacy inputs may rely on witness UTXO data only\n * @returns Input classification including transaction type and sighash defaults.\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Detect how the signer should treat a SegWit input from its previous output script.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2wpkh } from '@scure/btc-signer/payment.js';\n * import { getInputType } from '@scure/btc-signer/transaction.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * getInputType({\n *   witnessUtxo: {\n *     amount: 1n,\n *     script: p2wpkh(pubECDSA(randomPrivateKeyBytes())).script,\n *   },\n * });\n * ```\n */\nexport function getInputType(input, allowLegacyWitnessUtxo = false) {\n    const _input = input;\n    let txType = 'legacy';\n    let defaultSighash = SignatureHash.ALL;\n    const prevOut = getPrevOut(_input);\n    const first = _WitnessOutScript.decode(prevOut.script);\n    let type = first.type;\n    let cur = first;\n    const stack = [first];\n    // Classification is semantic, but legacy/BIP143 scriptCode and finalization must retain the\n    // exact committed spelling (including consensus-valid non-minimal pushes).\n    let lastScript = prevOut.script;\n    if (first.type === 'tr') {\n        // Expected invariant: taproot inputs use PSBT_IN_TAP_* metadata only;\n        // legacy redeemScript/witnessScript fields belong to P2SH/P2WSH paths.\n        defaultSighash = SignatureHash.DEFAULT;\n        return {\n            txType: 'taproot',\n            type: 'tr',\n            last: first,\n            lastScript: prevOut.script,\n            defaultSighash,\n            sighash: _input.sighashType || defaultSighash,\n        };\n    }\n    else {\n        if (first.type === 'wpkh' || first.type === 'wsh')\n            txType = 'segwit';\n        if (first.type === 'sh') {\n            if (!_input.redeemScript)\n                throw new Error('inputType: sh without redeemScript');\n            let child = _WitnessOutScript.decode(_input.redeemScript);\n            if (child.type === 'wpkh' || child.type === 'wsh')\n                txType = 'segwit';\n            stack.push(child);\n            cur = child;\n            lastScript = _input.redeemScript;\n            type += `-${child.type}`;\n        }\n        // wsh can be inside sh\n        if (cur.type === 'wsh') {\n            if (!_input.witnessScript)\n                throw new Error('inputType: wsh without witnessScript');\n            let child = OutScript.decode(_input.witnessScript);\n            if (child.type === 'wsh')\n                txType = 'segwit';\n            stack.push(child);\n            cur = child;\n            lastScript = _input.witnessScript;\n            type += `-${child.type}`;\n        }\n        const last = stack[stack.length - 1];\n        if (last.type === 'sh' || last.type === 'wsh')\n            throw new Error('inputType: sh/wsh cannot be terminal type');\n        const res = {\n            type,\n            txType,\n            last,\n            lastScript,\n            defaultSighash,\n            sighash: _input.sighashType || defaultSighash,\n        };\n        if (txType === 'legacy' && !allowLegacyWitnessUtxo && !_input.nonWitnessUtxo) {\n            throw new Error(`Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure`);\n        }\n        return res;\n    }\n}\n/**\n * Mutable Bitcoin transaction and PSBT helper.\n * @param opts - Transaction construction and PSBT serialization options. See {@link TxOpts}.\n * @example\n * Create a transaction, add one spend, and export it as PSBT.\n * ```ts\n * import { hex } from '@scure/base';\n * import { p2wpkh } from '@scure/btc-signer/payment.js';\n * import { Transaction } from '@scure/btc-signer/transaction.js';\n * import { pubECDSA, randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';\n * const spend = p2wpkh(pubECDSA(randomPrivateKeyBytes()));\n * const tx = new Transaction();\n * tx.addInput({\n *   txid: hex.decode('0000000000000000000000000000000000000000000000000000000000000001'),\n *   index: 0,\n *   witnessUtxo: { amount: 2n, script: spend.script },\n * });\n * tx.addOutput({ script: spend.script, amount: 1n });\n * tx.toPSBT();\n * ```\n */\nexport class Transaction {\n    global = {};\n    inputs = []; // use getInput()\n    outputs = []; // use getOutput()\n    opts;\n    constructor(opts = {}) {\n        const _opts = (this.opts = validateOpts(opts));\n        // Merge with global structure of PSBTv2\n        // Bitcoin Core sets fallback even when it is zero. Matching its common encoding reduces the\n        // fingerprint of locally created PSBTv2s; imported PSBTs replace this map and retain omission.\n        this.global.fallbackLocktime = _opts.lockTime;\n        this.global.txVersion = _opts.version;\n        // A locally-created PSBTv2 is still under construction. Imported PSBTs replace this global\n        // map below, so an omitted field there retains BIP370's immutable meaning.\n        if (_opts.PSBTVersion === 2)\n            this.global.txModifiable = 0b011;\n    }\n    isPSBTv2() {\n        return (this.global.version ?? this.opts.PSBTVersion) === 2;\n    }\n    requireTxModifiable(bit, kind) {\n        if (!this.isPSBTv2())\n            return;\n        if (!(this.txModifiablePolicy() & bit))\n            throw new Error(`PSBTv2: ${kind} are not modifiable`);\n    }\n    txModifiablePolicy(allowMissing = this.opts.allowMissingTxModifiable, unknownMode = this.opts.unknown) {\n        if (!this.isPSBTv2())\n            return 0b011;\n        if (this.global.txModifiable !== undefined)\n            return cleanTxModifiable(this.global.txModifiable, unknownMode);\n        return allowMissing ? 0b011 : 0;\n    }\n    modifiable(allowMissing = this.opts.allowMissingTxModifiable, unknownMode = this.opts.unknown) {\n        let flags = this.txModifiablePolicy(allowMissing, unknownMode);\n        let hasOpaqueFinal = false;\n        let hasSingle = false;\n        for (let idx = 0; idx < this.inputs.length; idx++) {\n            const signatures = inputSignatures(this.inputs[idx]);\n            if (!signatures.length && this.inputStatus(idx) === 'finalized')\n                hasOpaqueFinal = true;\n            for (const { sighash } of signatures) {\n                const { isAny, isNone, isSingle } = unpackSighash(sighash);\n                if (!isAny)\n                    flags &= ~0b001;\n                if (!isNone)\n                    flags &= ~0b010;\n                if (isSingle)\n                    hasSingle = true;\n            }\n        }\n        // Bit 2 summarizes signatures rather than granting policy. Preserve an imported summary for\n        // opaque or externally managed state, and union in every signature visible to this object.\n        if (hasSingle)\n            flags |= 0b100;\n        // PSBTv0 and legacy field-less PSBTv2 cannot describe an opaque finalized sighash. Promotion\n        // must therefore deny both mutations instead of manufacturing permissions from absence.\n        if (hasOpaqueFinal && this.global.txModifiable === undefined)\n            flags &= ~0b011;\n        return flags;\n    }\n    get txModifiable() {\n        return this.modifiable();\n    }\n    // Import\n    static fromRaw(raw, opts = {}) {\n        const parsed = RawTx.decode(raw);\n        const tx = new Transaction({ ...opts, version: parsed.version, lockTime: parsed.lockTime });\n        for (const o of parsed.outputs)\n            tx.addOutput(o);\n        tx.outputs = parsed.outputs;\n        tx.inputs = parsed.inputs;\n        if (parsed.witnesses) {\n            for (let i = 0; i < parsed.witnesses.length; i++)\n                tx.inputs[i].finalScriptWitness = parsed.witnesses[i];\n        }\n        return tx;\n    }\n    // PSBT\n    static fromPSBT(psbt_, opts = {}) {\n        let parsed;\n        try {\n            parsed = psbt.RawPSBTV0.decode(psbt_);\n        }\n        catch (e0) {\n            try {\n                parsed = psbt.RawPSBTV2.decode(psbt_);\n            }\n            catch (e2) {\n                // Throw error for v0 parsing, since it popular, otherwise it would be shadowed by v2 error\n                throw e0;\n            }\n        }\n        const PSBTVersion = parsed.global.version || 0;\n        if (PSBTVersion !== 0 && PSBTVersion !== 2)\n            throw new Error(`Wrong PSBT version=${PSBTVersion}`);\n        const unsigned = parsed.global.unsignedTx;\n        const version = PSBTVersion === 0 ? unsigned?.version : parsed.global.txVersion;\n        const lockTime = PSBTVersion === 0 ? unsigned?.lockTime : parsed.global.fallbackLocktime;\n        const tx = new Transaction({ ...opts, version, lockTime, PSBTVersion });\n        // We need slice here, because otherwise\n        const inputCount = PSBTVersion === 0 ? unsigned?.inputs.length : parsed.global.inputCount;\n        tx.inputs = parsed.inputs.slice(0, inputCount).map((i, j) => {\n            const input = {\n                ...parsed.global.unsignedTx?.inputs[j],\n                ...i,\n            };\n            // The unsigned transaction's empty scriptSig is framing, not a PSBT_IN_FINAL_SCRIPTSIG\n            // record. Keeping it makes combination conflict with an otherwise identical finalized PSBT.\n            if (!i.finalScriptSig?.length)\n                delete input.finalScriptSig;\n            return validateInput(input, tx.opts.disableScriptCheck);\n        });\n        const outputCount = PSBTVersion === 0 ? unsigned?.outputs.length : parsed.global.outputCount;\n        // bip174js writes a phantom empty input map when a PSBTv0 transaction has zero inputs. Raw v0\n        // framing necessarily reads it as the first output map, so skip it before pairing real maps\n        // with the unsigned transaction's declared outputs.\n        const hasBip174InputMap = PSBTVersion === 0 &&\n            inputCount === 0 &&\n            Object.keys(parsed.outputs[0] || {}).length === 0 &&\n            ((outputCount > 0 && parsed.outputs.length === outputCount + 1) ||\n                (outputCount === 0 &&\n                    parsed.outputs.length === 2 &&\n                    Object.keys(parsed.outputs[1]).length === 0));\n        const outputStart = hasBip174InputMap ? 1 : 0;\n        tx.outputs = parsed.outputs.slice(outputStart, outputStart + outputCount).map((i, j) => ({\n            ...i,\n            ...parsed.global.unsignedTx?.outputs[j],\n        }));\n        const unknownMode = tx.opts.unknown;\n        const proprietaryMode = tx.opts.proprietary;\n        // Unknown PSBT rows can carry opaque metadata between participants. The documented default is\n        // to strip them; callers that need forward compatibility must opt in explicitly. Proprietary\n        // (0xfc) rows follow the same explicit policy, which defaults to the resolved unknown mode.\n        tx.global = cleanExtensions({ ...parsed.global, txVersion: version }, unknownMode, proprietaryMode);\n        tx.inputs = tx.inputs.map((input) => cleanExtensions(input, unknownMode, proprietaryMode));\n        tx.outputs = tx.outputs.map((output) => cleanExtensions(output, unknownMode, proprietaryMode));\n        if (tx.global.txModifiable !== undefined)\n            tx.global.txModifiable = cleanTxModifiable(tx.global.txModifiable, unknownMode);\n        // A high-level Transaction must have a determinable nLockTime. Raw PSBT coders can still be\n        // used by callers that need to inspect or relay a structurally valid but incompatible PSBT.\n        resolvePSBTLocktime(tx.inputs, tx.global.fallbackLocktime ?? DEFAULT_LOCKTIME);\n        // PSBTv0 always provides nLockTime in its unsigned transaction. Retain zero internally too so\n        // promotion to v2 matches fresh construction and Bitcoin Core rather than gaining a\n        // fingerprint.\n        if (PSBTVersion === 0)\n            tx.global.fallbackLocktime = def(lockTime, DEFAULT_LOCKTIME);\n        return tx;\n    }\n    // Prefer `global.version` when present so cross-version combiners can serialize at the highest\n    // required PSBT version without mutating the frozen transaction options object.\n    toPSBT(PSBTVersion = this.global.version || this.opts.PSBTVersion) {\n        if (PSBTVersion !== undefined)\n            anumber(PSBTVersion, 'PSBTVersion');\n        if (PSBTVersion !== 0 && PSBTVersion !== 2)\n            throw new Error(`Wrong PSBT version=${PSBTVersion}`);\n        // if (PSBTVersion === 0 && this.inputs.length === 0) {\n        //   throw new Error(\n        //     'PSBT version=0 export for transaction without inputs disabled, please use version=2. Please check `toPSBT` method for explanation.'\n        //   );\n        // }\n        const inputs = this.inputs.map((i) => cleanExtensions(\n        // For PSBTv0 the prevout txid/index live in global.unsignedTx rather than the input map, so\n        // validate the full transaction input before version filtering drops those fields.\n        psbt.cleanPSBTFields(PSBTVersion, psbt.PSBTInput, validateInput(i, this.opts.disableScriptCheck)), this.opts.unknown, this.opts.proprietary));\n        for (const inp of inputs) {\n            // Don't serialize empty fields\n            if (inp.partialSig && !inp.partialSig.length)\n                delete inp.partialSig;\n            if (inp.finalScriptSig && !inp.finalScriptSig.length)\n                delete inp.finalScriptSig;\n            if (inp.finalScriptWitness && !inp.finalScriptWitness.length)\n                delete inp.finalScriptWitness;\n        }\n        const outputs = this.outputs.map((i) => cleanExtensions(psbt.cleanPSBTFields(PSBTVersion, psbt.PSBTOutput, i), this.opts.unknown, this.opts.proprietary));\n        const global = cleanExtensions({ ...this.global }, this.opts.unknown, this.opts.proprietary);\n        if (global.txModifiable !== undefined)\n            global.txModifiable = cleanTxModifiable(global.txModifiable, this.opts.unknown);\n        if (PSBTVersion === 0) {\n            /*\n            - Bitcoin raw transaction expects to have at least 1 input because it uses case with zero inputs as marker for SegWit\n            - this means we cannot serialize raw tx with zero inputs since it will be parsed as SegWit tx\n            - Parsing of PSBTv0 depends on unsignedTx (it looks for input count here)\n            - BIP-174 requires old serialization format (without witnesses) inside global, which solves this\n            */\n            global.unsignedTx = RawOldTx.decode(RawOldTx.encode({\n                version: this.version,\n                lockTime: this.lockTime,\n                inputs: this.inputs\n                    .map((i) => inputBeforeSign(i))\n                    .map((i) => ({\n                    ...i,\n                    finalScriptSig: P.EMPTY,\n                })),\n                outputs: this.outputs.map((o) => outputBeforeSign(o)),\n            }));\n            delete global.fallbackLocktime;\n            delete global.txVersion;\n            // PSBTv0 carries the unsigned transaction as one blob, so the PSBTv2 framing fields must be\n            // removed here. Keeping `global.version` would make validation treat this rebuilt v0 map as\n            // PSBTv2 and reject the required `unsignedTx` field. Transaction-modifiable is also v2-only;\n            // its restrictions remain represented by the signatures when explicitly converting to v0.\n            delete global.inputCount;\n            delete global.outputCount;\n            delete global.version;\n            delete global.txModifiable;\n        }\n        else {\n            // Cross-version merges and v0->v2 re-exports can still carry the PSBTv0 unsignedTx blob in\n            // `this.global`, but PSBTv2 serializes the transaction through split global/input/output\n            // fields instead, so drop the stale v0-only field before PSBTv2 validation/encoding.\n            delete global.unsignedTx;\n            global.version = PSBTVersion;\n            global.txVersion = this.version;\n            global.inputCount = this.inputs.length;\n            global.outputCount = this.outputs.length;\n            // Core serializes this optional field exactly as stored. Preserve no-op v2 round-trips;\n            // only v0 promotion and the explicit legacy-omission compatibility mode materialize policy.\n            if (!this.isPSBTv2() ||\n                (global.txModifiable === undefined && this.opts.allowMissingTxModifiable))\n                global.txModifiable = this.txModifiable;\n        }\n        // bip174js historically emits one empty output map for a PSBTv0 transaction with no outputs.\n        // Input maps are count-framed by the unsigned transaction, so a phantom input map cannot be\n        // represented: with zero inputs it would be decoded as an output map instead. PSBTv2 has\n        // explicit counts for both map arrays and does not use this compatibility encoding.\n        if (this.opts.bip174jsCompat && PSBTVersion === 0 && !outputs.length)\n            outputs.push({});\n        const raw = { global, inputs, outputs };\n        return PSBTVersion === 0\n            ? psbt.RawPSBTV0.encode(raw)\n            : psbt.RawPSBTV2.encode(raw);\n    }\n    // BIP370 lockTime (https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#determining-lock-time)\n    get lockTime() {\n        return resolvePSBTLocktime(this.inputs, this.global.fallbackLocktime ?? DEFAULT_LOCKTIME);\n    }\n    get version() {\n        // Should be not possible\n        if (this.global.txVersion === undefined)\n            throw new Error('No global.txVersion');\n        return this.global.txVersion;\n    }\n    inputStatus(idx) {\n        this.checkInputIdx(idx);\n        const input = this.inputs[idx];\n        // Finalized\n        if (input.finalScriptSig && input.finalScriptSig.length)\n            return 'finalized';\n        if (input.finalScriptWitness && input.finalScriptWitness.length)\n            return 'finalized';\n        // Signed taproot\n        if (input.tapKeySig)\n            return 'signed';\n        if (input.tapScriptSig && input.tapScriptSig.length)\n            return 'signed';\n        // Signed\n        if (input.partialSig && input.partialSig.length)\n            return 'signed';\n        return 'unsigned';\n    }\n    cleanFinalInput(input) {\n        // Core preserves producer policy during finalization. Once cleanup makes signatures opaque,\n        // signStatus conservatively locks transaction mutation until the input is explicitly reopened.\n        cleanFinalInput(input, this.opts.unknown, this.opts.proprietary);\n        if (this.global.txModifiable !== undefined)\n            this.global.txModifiable = cleanTxModifiable(this.global.txModifiable, this.opts.unknown);\n    }\n    // Cannot replace unpackSighash, tests rely on very generic implemenetation with signing inputs outside of range\n    // We will lose some vectors -> smaller test coverage of preimages (very important!)\n    inputSighash(idx) {\n        this.checkInputIdx(idx);\n        const inputSighash = this.inputs[idx].sighashType;\n        const sighash = inputSighash === undefined ? SignatureHash.DEFAULT : inputSighash;\n        // ALL or DEFAULT -- everything signed\n        // NONE           -- all inputs + no outputs\n        // SINGLE         -- all inputs + output with same index\n        // ALL + ANYONE   -- specific input + all outputs\n        // NONE + ANYONE  -- specific input + no outputs\n        // SINGLE         -- specific inputs + output with same index\n        return sighashScope(sighash);\n    }\n    // Very nice for debug purposes, but slow. If there is too much inputs/outputs to add, will be quadratic.\n    // Some cache will be nice, but there chance to have bugs with cache invalidation\n    signatures() {\n        const res = [];\n        for (let idx = 0; idx < this.inputs.length; idx++) {\n            const actual = inputSignatures(this.inputs[idx]);\n            for (const signature of actual)\n                res.push({ idx, ...signature });\n            if (actual.length || this.inputStatus(idx) !== 'finalized')\n                continue;\n            let taproot = true;\n            try {\n                taproot = _WitnessOutScript.decode(getPrevOut(this.inputs[idx]).script).type === 'tr';\n            }\n            catch {\n                // Finalization may remove the data needed to classify an imported opaque signature.\n                // Treating it as Taproot conservatively protects the larger all-prevout commitment.\n            }\n            const declared = this.inputs[idx].sighashType;\n            const sighash = declared === undefined ? SignatureHash.DEFAULT : declared;\n            res.push({ idx, sighash, taproot, scriptPath: taproot });\n        }\n        return res;\n    }\n    signedInputKeys(idx, signatures = this.signatures()) {\n        const res = new Set();\n        const add = (keys) => {\n            for (const key of keys)\n                res.add(key);\n        };\n        for (const signature of signatures) {\n            const { isAny, isNone, isSingle } = unpackSighash(signature.sighash);\n            if (signature.idx === idx) {\n                add(inputSignedKeys.self);\n                if (signature.taproot) {\n                    if (signature.scriptPath)\n                        add(inputSignedKeys.tapscript);\n                }\n                else\n                    add(inputSignedKeys.ecdsa);\n            }\n            else if (!isAny) {\n                add(inputSignedKeys.cross);\n                // Legacy and BIP143 omit other sequences for NONE/SINGLE. BIP341 commits every sequence\n                // whenever ANYONECANPAY is absent, independently of the output sighash mode.\n                if (signature.taproot || (!isNone && !isSingle))\n                    res.add('sequence');\n                if (signature.taproot)\n                    add(inputSignedKeys.prevout);\n            }\n        }\n        return [...res];\n    }\n    signStatus(signatures = this.signatures()) {\n        // if addInput or addOutput is not possible, then all inputs or outputs are signed\n        let addInput = true, addOutput = true;\n        let inputs = [], outputs = [];\n        for (const { idx, sighash } of signatures) {\n            const { sigInputs, sigOutputs } = sighashScope(sighash);\n            // Input type\n            if (sigInputs === SignatureHash.ANYONECANPAY) {\n                if (!inputs.includes(idx))\n                    inputs.push(idx);\n            }\n            else\n                addInput = false;\n            // Output type\n            if (sigOutputs === SignatureHash.ALL)\n                addOutput = false;\n            else if (sigOutputs === SignatureHash.SINGLE) {\n                if (!outputs.includes(idx))\n                    outputs.push(idx);\n            }\n            else if (sigOutputs === SignatureHash.NONE) {\n                // Doesn't affect any outputs at all\n            }\n            else\n                throw new Error(`Wrong signature hash output type: ${sigOutputs}`);\n        }\n        return { addInput, addOutput, inputs, outputs };\n    }\n    get isFinal() {\n        for (let idx = 0; idx < this.inputs.length; idx++)\n            if (this.inputStatus(idx) !== 'finalized')\n                return false;\n        return true;\n    }\n    // Info utils\n    get hasWitnesses() {\n        for (const i of this.inputs)\n            if (i.finalScriptWitness && i.finalScriptWitness.length)\n                return true;\n        return false;\n    }\n    // https://en.bitcoin.it/wiki/Weight_units\n    get weight() {\n        if (!this.isFinal)\n            throw new Error('Transaction is not finalized');\n        // Serialized length of VarBytes(data) without allocating the encoded copy\n        const varLen = (dataLen) => CompactSizeLen.encode(dataLen).length + dataLen;\n        const hasWitnesses = this.hasWitnesses;\n        let out = 32;\n        // Outputs\n        const outputs = this.outputs.map(outputBeforeSign);\n        out += 4 * CompactSizeLen.encode(this.outputs.length).length;\n        for (const o of outputs)\n            out += 32 + 4 * varLen(o.script.length);\n        // Inputs\n        if (hasWitnesses)\n            out += 2;\n        out += 4 * CompactSizeLen.encode(this.inputs.length).length;\n        for (const i of this.inputs) {\n            out += 160 + 4 * varLen((i.finalScriptSig || P.EMPTY).length);\n            // Once segwit serialization is active, every input contributes one witness vector, including\n            // legacy inputs whose empty vector still encodes as a single zero-item-count byte.\n            if (hasWitnesses) {\n                const witness = i.finalScriptWitness || [];\n                out += CompactSizeLen.encode(witness.length).length;\n                for (const w of witness)\n                    out += varLen(w.length);\n            }\n        }\n        return out;\n    }\n    get vsize() {\n        return toVsize(this.weight);\n    }\n    toBytes(withScriptSig = false, withWitness = false) {\n        return RawTx.encode({\n            version: this.version,\n            lockTime: this.lockTime,\n            inputs: this.inputs.map(inputBeforeSign).map((i) => ({\n                ...i,\n                finalScriptSig: (withScriptSig && i.finalScriptSig) || P.EMPTY,\n            })),\n            outputs: this.outputs.map(outputBeforeSign),\n            witnesses: this.inputs.map((i) => i.finalScriptWitness || []),\n            segwitFlag: withWitness && this.hasWitnesses,\n        });\n    }\n    get unsignedTx() {\n        return this.toBytes(false, false);\n    }\n    get hex() {\n        return hex.encode(this.toBytes(true, this.hasWitnesses));\n    }\n    get hash() {\n        return hex.encode(u.sha256x2(this.toBytes(true)));\n    }\n    get id() {\n        return hex.encode(u.sha256x2(this.toBytes(true)).reverse());\n    }\n    // Input stuff\n    checkInputIdx(idx) {\n        anumber(idx, 'idx');\n        if (idx >= this.inputs.length)\n            throw new Error(`Wrong input index=${idx}`);\n    }\n    validatePrevoutsForSigning() {\n        if (!this.opts.strictPrevoutValidation)\n            return;\n        for (let i = 0; i < this.inputs.length; i++) {\n            const input = this.inputs[i];\n            if (!input.nonWitnessUtxo) {\n                throw new Error(`Transaction/sign: strictPrevoutValidation requires nonWitnessUtxo for input=${i}`);\n            }\n            if (input.txid === undefined || input.index === undefined) {\n                throw new Error(`Transaction/sign: strictPrevoutValidation requires an outpoint for input=${i}`);\n            }\n            // A full previous transaction is only a trusted amount/script commitment after its txid and\n            // selected output have been checked against the unsigned transaction. Also cross-check a\n            // redundant witnessUtxo when one is present.\n            validateInput(input, this.opts.disableScriptCheck);\n        }\n    }\n    getInput(idx) {\n        this.checkInputIdx(idx);\n        return cloneDeep(this.inputs[idx]);\n    }\n    get inputsLength() {\n        return this.inputs.length;\n    }\n    // Modification\n    addInput(input, _ignoreSignStatus = false) {\n        validateObject(input, {}, {}, 'input');\n        cleanExtensions(input, this.opts.unknown, this.opts.proprietary, true);\n        this.requireTxModifiable(0b001, 'inputs');\n        const signatures = _ignoreSignStatus ? undefined : this.signatures();\n        const status = signatures && this.signStatus(signatures);\n        if (status && !status.addInput)\n            throw new Error('Tx has signed inputs, cannot add new one');\n        // normalizeInput preserves nested caller-owned byte arrays, so detach them here before the\n        // new input becomes transaction state and later caller mutation can rewrite it by aliasing.\n        const normalized = cloneDeep(normalizeInput(input, undefined, undefined, this.opts.disableScriptCheck, this.opts.unknown, this.opts.proprietary));\n        const nextLockTime = resolvePSBTLocktime([...this.inputs, normalized], this.global.fallbackLocktime ?? DEFAULT_LOCKTIME);\n        // ANYONECANPAY permits adding an outpoint, but every signature still commits to nLockTime.\n        if (signatures?.length && nextLockTime !== this.lockTime)\n            throw new Error('Tx has signed inputs, cannot change lockTime');\n        this.inputs.push(normalized);\n        return this.inputs.length - 1;\n    }\n    updateInput(idx, input, _ignoreSignStatus = false) {\n        this.checkInputIdx(idx);\n        cleanExtensions(input, this.opts.unknown, this.opts.proprietary, true);\n        let allowedFields;\n        const signatures = _ignoreSignStatus ? undefined : this.signatures();\n        if (signatures?.length) {\n            if (this.inputStatus(idx) === 'finalized') {\n                // Once finalized, only already-present signature/final fields may be repeated or removed.\n                // In particular, do not let a native-SegWit final witness gain a stray finalScriptSig.\n                allowedFields = psbt.PSBTInputSignatureKeys.filter((key) => this.inputs[idx][key] !== undefined);\n            }\n            else {\n                const signed = new Set(this.signedInputKeys(idx, signatures));\n                if (signed.size)\n                    allowedFields = Object.keys(psbt.PSBTInput).filter((key) => !signed.has(key));\n            }\n        }\n        // normalizeInput preserves nested caller-owned byte arrays, so detach the merged result here\n        // before the updated input becomes transaction state and later caller mutation can rewrite it.\n        const normalized = cloneDeep(normalizeInput(input, this.inputs[idx], allowedFields, this.opts.disableScriptCheck, this.opts.unknown, this.opts.proprietary));\n        const inputs = this.inputs.slice();\n        inputs[idx] = normalized;\n        const nextLockTime = resolvePSBTLocktime(inputs, this.global.fallbackLocktime ?? DEFAULT_LOCKTIME);\n        if (signatures?.length && nextLockTime !== this.lockTime)\n            throw new Error('Tx has signed inputs, cannot change lockTime');\n        const current = this.inputs[idx];\n        const transactionChanged = current.index !== normalized.index ||\n            def(current.sequence, DEFAULT_SEQUENCE) !== def(normalized.sequence, DEFAULT_SEQUENCE) ||\n            (current.txid === undefined\n                ? normalized.txid !== undefined\n                : normalized.txid === undefined || !equalBytes(current.txid, normalized.txid)) ||\n            nextLockTime !== this.lockTime;\n        if (transactionChanged)\n            this.requireTxModifiable(0b001, 'inputs');\n        this.inputs[idx] = normalized;\n    }\n    // Output stuff\n    checkOutputIdx(idx) {\n        anumber(idx, 'idx');\n        if (idx >= this.outputs.length)\n            throw new Error(`Wrong output index=${idx}`);\n    }\n    getOutput(idx) {\n        this.checkOutputIdx(idx);\n        return cloneDeep(this.outputs[idx]);\n    }\n    getOutputAddress(idx, network = NETWORK) {\n        const out = this.getOutput(idx);\n        if (!out.script)\n            return;\n        return Address(network).encode(_WitnessOutScript.decode(out.script));\n    }\n    get outputsLength() {\n        return this.outputs.length;\n    }\n    normalizeOutput(o, cur, allowedFields) {\n        validateObject(o, {}, {}, 'o');\n        let { amount, script } = o;\n        if (amount === undefined)\n            amount = cur?.amount;\n        amount = abigint(amount, 'o.amount');\n        if (typeof script === 'string')\n            script = hex.decode(script);\n        if (script === undefined)\n            script = cur?.script;\n        let res = { ...cur, ...o, amount, script };\n        if (res.amount === undefined)\n            delete res.amount;\n        res = psbt.mergeKeyMap(psbt.PSBTOutput, res, cur, allowedFields, this.opts.unknown, this.opts.proprietary);\n        psbt.PSBTOutputCoder.encode(res);\n        if (res.script &&\n            !this.opts.allowUnknownOutputs &&\n            _WitnessOutScript.decode(res.script).type === 'unknown') {\n            throw new Error('Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure');\n        }\n        if (!this.opts.disableScriptCheck)\n            checkScript(res.script, res.redeemScript, res.witnessScript);\n        return res;\n    }\n    addOutput(o, _ignoreSignStatus = false) {\n        cleanExtensions(o, this.opts.unknown, this.opts.proprietary, true);\n        this.requireTxModifiable(0b010, 'outputs');\n        const status = _ignoreSignStatus ? undefined : this.signStatus();\n        // Appending the previously missing same-index output changes a SIGHASH_SINGLE digest.\n        if (status && (!status.addOutput || status.outputs.includes(this.outputs.length)))\n            throw new Error('Tx has signed outputs, cannot add new one');\n        // normalizeOutput preserves nested caller-owned script bytes, so detach them here before the\n        // new output becomes transaction state and later caller mutation can rewrite it by aliasing.\n        this.outputs.push(cloneDeep(this.normalizeOutput(o)));\n        return this.outputs.length - 1;\n    }\n    updateOutput(idx, output, _ignoreSignStatus = false) {\n        this.checkOutputIdx(idx);\n        cleanExtensions(output, this.opts.unknown, this.opts.proprietary, true);\n        let allowedFields = undefined;\n        if (!_ignoreSignStatus) {\n            const status = this.signStatus();\n            if (!status.addOutput || status.outputs.includes(idx))\n                allowedFields = psbt.PSBTOutputUnsignedKeys;\n        }\n        // updateOutput replaces stored state with normalizeOutput(...) directly, so detach the result\n        // before storing it or later caller mutation of `output.script` will rewrite transaction state.\n        const current = this.outputs[idx];\n        const normalized = cloneDeep(this.normalizeOutput(output, current, allowedFields));\n        const transactionChanged = current.amount !== normalized.amount ||\n            (current.script === undefined\n                ? normalized.script !== undefined\n                : normalized.script === undefined || !equalBytes(current.script, normalized.script));\n        if (transactionChanged)\n            this.requireTxModifiable(0b010, 'outputs');\n        this.outputs[idx] = normalized;\n    }\n    addOutputAddress(address, amount, network = NETWORK) {\n        return this.addOutput({\n            // Address.decode() only returns recognized descriptors here, but its wrapped output type\n            // still carries `undefined` for coder parity, so narrow before feeding OutScript.encode().\n            script: OutScript.encode(Address(network).decode(address)),\n            amount,\n        });\n    }\n    // Utils\n    get fee() {\n        let res = _0n;\n        for (const i of this.inputs) {\n            const prevOut = getPrevOut(i);\n            if (!prevOut)\n                throw new Error('Empty input amount');\n            res += prevOut.amount;\n        }\n        const outputs = this.outputs.map(outputBeforeSign);\n        for (const o of outputs)\n            res -= o.amount;\n        return res;\n    }\n    // Signing\n    // Based on https://github.com/bitcoin/bitcoin/blob/5871b5b5ab57a0caf9b7514eb162c491c83281d5/test/functional/test_framework/script.py#L624\n    // There is optimization opportunity to re-use hashes for multiple inputs for witness v0/v1,\n    // but we are trying to be less complicated for audit purpose for now.\n    preimageLegacy(idx, prevOutScript, hashType) {\n        const { isAny, isNone, isSingle } = unpackSighash(hashType);\n        if (idx < 0 || !Number.isSafeInteger(idx))\n            throw new Error(`Invalid input idx=${idx}`);\n        if ((isSingle && idx >= this.outputs.length) || idx >= this.inputs.length)\n            // Bitcoin Core passes uint256::ONE's internal little-endian bytes directly to ECDSA.\n            return P.U256LE.encode(_1n);\n        prevOutScript = stripCodeSeparator(prevOutScript);\n        let inputs = this.inputs\n            .map(inputBeforeSign)\n            .map((input, inputIdx) => ({\n            ...input,\n            finalScriptSig: inputIdx === idx ? prevOutScript : P.EMPTY,\n        }));\n        if (isAny)\n            inputs = [inputs[idx]];\n        else if (isNone || isSingle) {\n            inputs = inputs.map((input, inputIdx) => ({\n                ...input,\n                sequence: inputIdx === idx ? input.sequence : 0,\n            }));\n        }\n        let outputs = this.outputs.map(outputBeforeSign);\n        if (isNone)\n            outputs = [];\n        else if (isSingle) {\n            outputs = outputs\n                .slice(0, idx)\n                .fill(EMPTY_OUTPUT)\n                .concat([outputs[idx]]);\n        }\n        const tmpTx = RawTx.encode({\n            lockTime: this.lockTime,\n            version: this.version,\n            segwitFlag: false,\n            inputs,\n            outputs,\n        });\n        return u.sha256x2(tmpTx, P.I32LE.encode(hashType));\n    }\n    preimageWitnessV0(idx, prevOutScript, hashType, amount) {\n        // BIP143 serializes txTo.vin[nIn].prevout and txTo.vin[nIn].nSequence, so reject an invalid\n        // nIn explicitly instead of leaking a later undefined-input TypeError from inputs[idx].\n        anumber(idx, 'idx');\n        if (idx >= this.inputs.length)\n            throw new Error(`Invalid input idx=${idx}`);\n        const { isAny, isNone, isSingle } = unpackSighash(hashType);\n        let inputHash = EMPTY32;\n        let sequenceHash = EMPTY32;\n        let outputHash = EMPTY32;\n        const inputs = this.inputs.map(inputBeforeSign);\n        const outputs = this.outputs.map(outputBeforeSign);\n        if (!isAny)\n            inputHash = u.sha256x2(...inputs.map(TxHashIdx.encode));\n        if (!isAny && !isSingle && !isNone)\n            sequenceHash = u.sha256x2(...inputs.map((i) => P.U32LE.encode(i.sequence)));\n        if (!isSingle && !isNone) {\n            outputHash = u.sha256x2(...outputs.map(RawOutput.encode));\n        }\n        else if (isSingle && idx < outputs.length)\n            outputHash = u.sha256x2(RawOutput.encode(outputs[idx]));\n        const input = inputs[idx];\n        return u.sha256x2(P.I32LE.encode(this.version), inputHash, sequenceHash, P.bytes(32, true).encode(input.txid), P.U32LE.encode(input.index), VarBytes.encode(prevOutScript), P.U64LE.encode(amount), P.U32LE.encode(input.sequence), outputHash, P.U32LE.encode(this.lockTime), P.U32LE.encode(hashType));\n    }\n    preimageWitnessV1(idx, prevOutScript, hashType, amount, codeSeparator = -1, leafScript, leafVer = 0xc0, annex) {\n        // BIP341 SigMsg commits either to input_index or to the selected input's outpoint/amount/script/\n        // sequence under ANYONECANPAY, so reject an invalid index explicitly instead of hashing a\n        // nonexistent input or leaking a later integer-encoding RangeError for negative idx.\n        anumber(idx, 'idx');\n        if (idx >= this.inputs.length)\n            throw new Error(`Invalid input idx=${idx}`);\n        u.aarray(amount, 'amount');\n        u.aarray(prevOutScript, 'prevOutScript');\n        if (this.inputs.length !== amount.length)\n            throw new Error(`Invalid amounts array=${amount}`);\n        if (this.inputs.length !== prevOutScript.length)\n            throw new Error(`Invalid prevOutScript array=${prevOutScript}`);\n        const out = [\n            P.U8.encode(0),\n            P.U8.encode(hashType), // U8 sigHash\n            P.I32LE.encode(this.version),\n            P.U32LE.encode(this.lockTime),\n        ];\n        const outType = hashType === SignatureHash.DEFAULT ? SignatureHash.ALL : hashType & 0b11;\n        const inType = hashType & SignatureHash.ANYONECANPAY;\n        const inputs = this.inputs.map(inputBeforeSign);\n        const outputs = this.outputs.map(outputBeforeSign);\n        // Unlike legacy and segwit v0, BIP341 defines no digest for SINGLE when the\n        // corresponding output does not exist. Returning a digest here would produce\n        // signatures that consensus can never accept.\n        if (outType === SignatureHash.SINGLE && idx >= outputs.length) {\n            throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${idx}`);\n        }\n        if (inType !== SignatureHash.ANYONECANPAY) {\n            out.push(...[\n                inputs.map(TxHashIdx.encode),\n                amount.map(P.U64LE.encode),\n                prevOutScript.map(VarBytes.encode),\n                inputs.map((i) => P.U32LE.encode(i.sequence)),\n            ].map((i) => u.sha256(concatBytes(...i))));\n        }\n        if (outType === SignatureHash.ALL) {\n            out.push(u.sha256(concatBytes(...outputs.map(RawOutput.encode))));\n        }\n        const spendType = (annex ? 1 : 0) | (leafScript ? 2 : 0);\n        out.push(new Uint8Array([spendType]));\n        if (inType === SignatureHash.ANYONECANPAY) {\n            const inp = inputs[idx];\n            out.push(TxHashIdx.encode(inp), P.U64LE.encode(amount[idx]), VarBytes.encode(prevOutScript[idx]), P.U32LE.encode(inp.sequence));\n        }\n        else\n            out.push(P.U32LE.encode(idx));\n        if (spendType & 1)\n            out.push(u.sha256(VarBytes.encode(annex || P.EMPTY)));\n        if (outType === SignatureHash.SINGLE)\n            out.push(u.sha256(RawOutput.encode(outputs[idx])));\n        if (leafScript)\n            out.push(tapLeafHash(leafScript, leafVer), P.U8.encode(0), P.I32LE.encode(codeSeparator));\n        return u.tagSchnorr('TapSighash', ...out);\n    }\n    // Signer can be privateKey OR instance of bip32 HD stuff\n    signIdx(privateKey, idx, allowedSighash, _auxRand) {\n        if (!isBytes(privateKey)) {\n            // HDKey is a structural external instance, so plain-object validation would\n            // reject valid signers.\n            if (!privateKey ||\n                typeof privateKey !== 'object' ||\n                typeof privateKey.deriveChild !== 'function')\n                throw new TypeError('\"privateKey\" expected Uint8Array or HDKey, got type=' + typeof privateKey);\n        }\n        this.checkInputIdx(idx);\n        this.validatePrevoutsForSigning();\n        const input = validateInput(this.inputs[idx], this.opts.disableScriptCheck);\n        const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);\n        const canSign = (privateKey) => {\n            if (inputType.txType === 'taproot') {\n                const pubKey = u.pubSchnorr(privateKey);\n                if (input.tapInternalKey && equalBytes(pubKey, input.tapInternalKey))\n                    return true;\n                if (!input.tapLeafScript)\n                    return false;\n                for (const [_, leaf] of input.tapLeafScript) {\n                    for (const op of Script.decode(leaf.subarray(0, -1))) {\n                        if (isBytes(op) && equalBytes(op, pubKey))\n                            return true;\n                    }\n                }\n                return false;\n            }\n            const pubKey = u.pubECDSA(privateKey);\n            const pubKeyHash = u.hash160(pubKey);\n            for (const op of Script.decode(inputType.lastScript)) {\n                if (isBytes(op) && (equalBytes(op, pubKey) || equalBytes(op, pubKeyHash)))\n                    return true;\n            }\n            return false;\n        };\n        // Expected invariant: HD signing should use bip32Derivation for legacy/segwit inputs,\n        // tapBip32Derivation for taproot inputs, and preserve caller sighash/auxRand constraints.\n        if (!isBytes(privateKey)) {\n            const root = privateKey;\n            const deriveSigners = (label, rows, pubKey) => {\n                if (!rows || !rows.length)\n                    throw new Error(`${label}: empty`);\n                const signers = rows\n                    .filter((row) => row.fingerprint == root.fingerprint)\n                    .map((row) => {\n                    let s = root;\n                    for (const i of row.path)\n                        s = s.deriveChild(i);\n                    if (!equalBytes(pubKey(s), row.pubKey))\n                        throw new Error(`${label}: wrong pubKey`);\n                    if (!s.privateKey)\n                        throw new Error(`${label}: no privateKey`);\n                    return s;\n                });\n                if (!signers.length)\n                    throw new Error(`${label}: no items with fingerprint=${root.fingerprint}`);\n                return signers;\n            };\n            const signers = inputType.txType === 'taproot'\n                ? // BIP371 PSBT_IN_TAP_BIP32_DERIVATION stores x-only pubkeys plus `der`, so taproot HD\n                    // signing must derive against that map instead of legacy bip32Derivation.\n                    deriveSigners('tapBip32Derivation', input.tapBip32Derivation?.map(([pubKey, { der }]) => ({\n                        pubKey,\n                        fingerprint: der.fingerprint,\n                        path: der.path,\n                    })), (s) => s.publicKey.slice(1))\n                : deriveSigners('bip32Derivation', input.bip32Derivation?.map(([pubKey, der]) => ({\n                    pubKey,\n                    fingerprint: der.fingerprint,\n                    path: der.path,\n                })), (s) => s.publicKey);\n            let signed = false;\n            for (const s of signers) {\n                // PSBT may legitimately carry multiple same-fingerprint derivation entries (multisig or\n                // taproot internal/script-path keys). Skip unrelated derived children instead of aborting\n                // the whole HD signing attempt on the first non-applicable candidate.\n                if (!canSign(s.privateKey))\n                    continue;\n                if (this.signIdx(s.privateKey, idx, allowedSighash, _auxRand))\n                    signed = true;\n            }\n            if (signed)\n                return true;\n            if (inputType.txType === 'taproot')\n                throw new Error('No taproot scripts signed');\n            throw new Error(`Input script doesn't have pubKey: ${inputType.lastScript}`);\n        }\n        // Sighash checks\n        // Just for compat with bitcoinjs-lib, so users won't face unexpected behaviour.\n        if (!allowedSighash)\n            allowedSighash = [inputType.defaultSighash];\n        else\n            allowedSighash.forEach(validateSigHash);\n        const sighash = inputType.sighash;\n        if (!allowedSighash.includes(sighash)) {\n            throw new Error(`Input with not allowed sigHash=${sighash}. Allowed: ${allowedSighash.join(', ')}`);\n        }\n        // It is possible to sign these inputs for legacy/segwit v0 (but no taproot!),\n        // however this was because of bug in bitcoin-core, which remains here because of consensus.\n        // If this is absolutely neccessary for your case, please open issue.\n        // We disable it to avoid complicated workflow where SINGLE will block adding new outputs\n        const { sigOutputs } = this.inputSighash(idx);\n        if (sigOutputs === SignatureHash.SINGLE && idx >= this.outputs.length) {\n            throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${idx}`);\n        }\n        // Actual signing\n        // Taproot\n        const prevOut = getPrevOut(input);\n        if (inputType.txType === 'taproot') {\n            const prevOuts = this.inputs.map(getPrevOut);\n            const prevOutScript = prevOuts.map((i) => i.script);\n            const amount = prevOuts.map((i) => i.amount);\n            let signed = false;\n            let schnorrPub = u.pubSchnorr(privateKey);\n            let merkleRoot = input.tapMerkleRoot || P.EMPTY;\n            if (input.tapInternalKey) {\n                // internal + tweak = tweaked key\n                // if internal key == current public key, we need to tweak private key,\n                // otherwise sign as is. bitcoinjs implementation always wants tweaked\n                // priv key to be provided\n                const { pubKey, privKey } = getTaprootKeys(privateKey, schnorrPub, input.tapInternalKey, merkleRoot);\n                const [taprootPubKey, _] = u.taprootTweakPubkey(input.tapInternalKey, merkleRoot);\n                if (equalBytes(taprootPubKey, pubKey)) {\n                    const hash = this.preimageWitnessV1(idx, prevOutScript, sighash, amount);\n                    const sig = concatBytes(u.signSchnorr(hash, privKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);\n                    this.updateInput(idx, { tapKeySig: sig }, true);\n                    signed = true;\n                }\n            }\n            if (input.tapLeafScript) {\n                input.tapScriptSig = input.tapScriptSig || [];\n                for (const [_, _script] of input.tapLeafScript) {\n                    const script = _script.subarray(0, -1);\n                    const scriptDecoded = Script.decode(script);\n                    const ver = _script[_script.length - 1];\n                    const hash = tapLeafHash(script, ver);\n                    // NOTE: no need to tweak internal key here, since we don't support nested p2tr\n                    const pos = scriptDecoded.findIndex((i) => isBytes(i) && equalBytes(i, schnorrPub));\n                    // Skip if there is no public key in tapLeafScript\n                    if (pos === -1)\n                        continue;\n                    const msg = this.preimageWitnessV1(idx, prevOutScript, sighash, amount, undefined, script, ver);\n                    const sig = concatBytes(u.signSchnorr(msg, privateKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);\n                    this.updateInput(idx, { tapScriptSig: [[{ pubKey: schnorrPub, leafHash: hash }, sig]] }, true);\n                    signed = true;\n                }\n            }\n            if (!signed)\n                throw new Error('No taproot scripts signed');\n            return true;\n        }\n        else {\n            // only compressed keys are supported for now\n            const pubKey = u.pubECDSA(privateKey);\n            // TODO: replace with explicit checks\n            // Check if script has public key or its has inside\n            let hasPubkey = false;\n            const pubKeyHash = u.hash160(pubKey);\n            for (const i of Script.decode(inputType.lastScript)) {\n                if (isBytes(i) && (equalBytes(i, pubKey) || equalBytes(i, pubKeyHash)))\n                    hasPubkey = true;\n            }\n            if (!hasPubkey)\n                throw new Error(`Input script doesn't have pubKey: ${inputType.lastScript}`);\n            let hash;\n            if (inputType.txType === 'legacy') {\n                hash = this.preimageLegacy(idx, inputType.lastScript, sighash);\n            }\n            else if (inputType.txType === 'segwit') {\n                let script = inputType.lastScript;\n                // If wpkh OR sh-wpkh, wsh-wpkh is impossible, so looks ok\n                if (inputType.last.type === 'wpkh')\n                    script = OutScript.encode({ type: 'pkh', hash: inputType.last.hash });\n                hash = this.preimageWitnessV0(idx, script, sighash, prevOut.amount);\n            }\n            else\n                throw new Error(`Transaction/sign: unknown tx type: ${inputType.txType}`);\n            const sig = u.signECDSA(hash, privateKey, this.opts.lowR);\n            this.updateInput(idx, {\n                partialSig: [[pubKey, concatBytes(sig, new Uint8Array([sighash]))]],\n            }, true);\n        }\n        return true;\n    }\n    // This is bad API. Will work if user creates and signs tx, but if\n    // there is some complex workflow with exchanging PSBT and signing them,\n    // then it is better to validate which output user signs. How could a better API look like?\n    // Example: user adds input, sends to another party, then signs received input (mixer etc),\n    // another user can add different input for same key and user will sign it.\n    // Even worse: another user can add bip32 derivation, and spend money from different address.\n    // Better api: signIdx\n    sign(privateKey, allowedSighash, _auxRand) {\n        // Check transaction-wide strict requirements outside the per-input catch below so callers get\n        // the actionable validation error instead of the generic \"No inputs signed\" result.\n        this.validatePrevoutsForSigning();\n        let num = 0;\n        for (let i = 0; i < this.inputs.length; i++) {\n            try {\n                if (this.signIdx(privateKey, i, allowedSighash, _auxRand))\n                    num++;\n            }\n            catch (e) { }\n        }\n        if (!num)\n            throw new Error('No inputs signed');\n        return num;\n    }\n    finalizeIdx(idx) {\n        this.checkInputIdx(idx);\n        if (this.fee < _0n)\n            throw new Error('Outputs spends more than inputs amount');\n        const input = this.inputs[idx];\n        // Validate strict extension policy before constructing satisfaction so a rejection is atomic.\n        cleanExtensions(input, this.opts.unknown, this.opts.proprietary);\n        cleanTxModifiable(this.global.txModifiable, this.opts.unknown);\n        const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);\n        // Taproot finalize\n        if (inputType.txType === 'taproot') {\n            if (input.tapKeySig)\n                input.finalScriptWitness = [input.tapKeySig];\n            else if (input.tapLeafScript && input.tapScriptSig) {\n                // Preserve the old shallowest-path tie-break without mutating caller-visible leaf order.\n                const leafs = input.tapLeafScript\n                    .slice()\n                    .sort((a, b) => psbt.TaprootControlBlock.encode(a[0]).length -\n                    psbt.TaprootControlBlock.encode(b[0]).length);\n                let smallest;\n                let smallestSize = Number.POSITIVE_INFINITY;\n                let unsupported = false;\n                for (const [cb, _script] of leafs) {\n                    // Last byte is version\n                    const script = _script.slice(0, -1);\n                    const ver = _script[_script.length - 1];\n                    const outScript = OutScript.decode(script);\n                    const hash = tapLeafHash(script, ver);\n                    const scriptSig = input.tapScriptSig.filter((i) => equalBytes(i[0].leafHash, hash));\n                    let signatures = [];\n                    let witness;\n                    if (outScript.type === 'tr_ms') {\n                        const m = outScript.m;\n                        const pubkeys = outScript.pubkeys;\n                        let added = 0;\n                        for (const pub of pubkeys) {\n                            const sigIdx = scriptSig.findIndex((i) => equalBytes(i[0].pubKey, pub));\n                            // Should have exact amount of signatures (more -- will fail)\n                            if (added === m || sigIdx === -1) {\n                                signatures.push(P.EMPTY);\n                                continue;\n                            }\n                            signatures.push(scriptSig[sigIdx][1]);\n                            added++;\n                        }\n                        // Should be exact same as m\n                        if (added !== m)\n                            continue;\n                    }\n                    else if (outScript.type === 'tr_ns') {\n                        for (const pub of outScript.pubkeys) {\n                            const sigIdx = scriptSig.findIndex((i) => equalBytes(i[0].pubKey, pub));\n                            if (sigIdx === -1)\n                                continue;\n                            signatures.push(scriptSig[sigIdx][1]);\n                        }\n                        if (signatures.length !== outScript.pubkeys.length)\n                            continue;\n                    }\n                    else if (outScript.type === 'unknown' && this.opts.allowUnknownInputs) {\n                        // Trying our best to sign what we can\n                        const scriptDecoded = Script.decode(script);\n                        signatures = scriptSig\n                            .map(([{ pubKey }, signature]) => {\n                            const pos = scriptDecoded.findIndex((i) => isBytes(i) && equalBytes(i, pubKey));\n                            if (pos === -1)\n                                throw new Error('finalize/taproot: cannot find position of pubkey in script');\n                            return { signature, pos };\n                        })\n                            // Reverse order (because witness is stack and we take last element first from it)\n                            .sort((a, b) => a.pos - b.pos)\n                            .map((i) => i.signature);\n                        if (!signatures.length)\n                            continue;\n                    }\n                    else {\n                        const custom = this.opts.customScripts;\n                        let recognized = false;\n                        if (custom) {\n                            for (const c of custom) {\n                                if (!c.finalizeTaproot)\n                                    continue;\n                                const scriptDecoded = Script.decode(script);\n                                const csEncoded = c.encode(scriptDecoded);\n                                if (csEncoded === undefined)\n                                    continue;\n                                recognized = true;\n                                // Do not catch hook errors here. `undefined` means no satisfaction, while a throw\n                                // from a matching custom finalizer reports broken leaf/signature data and must\n                                // abort even when another leaf has already produced a valid witness candidate.\n                                const finalized = c.finalizeTaproot(script, csEncoded, scriptSig);\n                                if (!finalized)\n                                    continue;\n                                witness = finalized.concat(psbt.TaprootControlBlock.encode(cb));\n                                break;\n                            }\n                        }\n                        // Minimum search inspects every leaf, so an unsupported path cannot block an already\n                        // complete known path merely because it appears later. Retain the old error when no\n                        // supported satisfaction exists at all.\n                        if (!witness && !recognized && scriptSig.length)\n                            unsupported = true;\n                        if (!witness)\n                            continue;\n                    }\n                    // Witness is stack, so last element will be used first\n                    witness ||= signatures.reverse().concat([script, psbt.TaprootControlBlock.encode(cb)]);\n                    const size = RawWitness.encode(witness).length;\n                    if (size >= smallestSize)\n                        continue;\n                    smallest = witness;\n                    smallestSize = size;\n                }\n                if (!smallest && unsupported)\n                    throw new Error('Finalize: Unknown tapLeafScript');\n                if (!smallest)\n                    throw new Error('finalize/taproot: empty witness');\n                input.finalScriptWitness = smallest;\n            }\n            else\n                throw new Error('finalize/taproot: unknown input');\n            // BIP174 Input Finalizer: if scriptSig is empty for an input, 0x07 remains unset.\n            delete input.finalScriptSig;\n            this.cleanFinalInput(input);\n            return;\n        }\n        if (!input.partialSig || !input.partialSig.length)\n            throw new Error('Not enough partial sign');\n        let inputScript = P.EMPTY;\n        let witness = [];\n        // TODO: move input scripts closer to payments/output scripts\n        // Multisig\n        if (inputType.last.type === 'ms') {\n            const m = inputType.last.m;\n            const pubkeys = inputType.last.pubkeys;\n            let signatures = [];\n            // partial: [pubkey, sign]\n            for (const pub of pubkeys) {\n                const sign = input.partialSig.find((s) => equalBytes(pub, s[0]));\n                if (!sign)\n                    continue;\n                signatures.push(sign[1]);\n            }\n            signatures = signatures.slice(0, m);\n            if (signatures.length !== m) {\n                throw new Error(`Multisig: wrong signatures count, m=${m} n=${pubkeys.length} signatures=${signatures.length}`);\n            }\n            inputScript = Script.encode([0, ...signatures]);\n        }\n        else if (inputType.last.type === 'pk') {\n            inputScript = Script.encode([input.partialSig[0][1]]);\n        }\n        else if (inputType.last.type === 'pkh') {\n            inputScript = Script.encode([input.partialSig[0][1], input.partialSig[0][0]]);\n        }\n        else if (inputType.last.type === 'wpkh') {\n            inputScript = P.EMPTY;\n            witness = [input.partialSig[0][1], input.partialSig[0][0]];\n        }\n        else if (inputType.last.type === 'unknown' && !this.opts.allowUnknownInputs)\n            throw new Error('Unknown inputs not allowed');\n        // Create final scripts (generic part)\n        let finalScriptSig, finalScriptWitness;\n        if (inputType.type.includes('wsh-')) {\n            // P2WSH\n            if (inputScript.length && inputType.lastScript.length) {\n                witness = Script.decode(inputScript).map((i) => {\n                    if (i === 0)\n                        return P.EMPTY;\n                    if (isBytes(i))\n                        return i;\n                    throw new Error(`Wrong witness op=${i}`);\n                });\n            }\n            witness = witness.concat(inputType.lastScript);\n        }\n        if (inputType.txType === 'segwit')\n            finalScriptWitness = witness;\n        if (inputType.type.startsWith('sh-wsh-')) {\n            finalScriptSig = Script.encode([Script.encode([0, u.sha256(inputType.lastScript)])]);\n        }\n        else if (inputType.type.startsWith('sh-')) {\n            finalScriptSig = Script.encode([...Script.decode(inputScript), inputType.lastScript]);\n        }\n        else if (inputType.type.startsWith('wsh-')) {\n        }\n        else if (inputType.txType !== 'segwit')\n            finalScriptSig = inputScript;\n        if (!finalScriptSig && !finalScriptWitness)\n            throw new Error('Unknown error finalizing input');\n        if (finalScriptSig)\n            input.finalScriptSig = finalScriptSig;\n        if (finalScriptWitness)\n            input.finalScriptWitness = finalScriptWitness;\n        this.cleanFinalInput(input);\n    }\n    finalize() {\n        for (let i = 0; i < this.inputs.length; i++)\n            this.finalizeIdx(i);\n    }\n    extract() {\n        if (!this.isFinal)\n            throw new Error('Transaction has unfinalized inputs');\n        if (!this.outputs.length)\n            throw new Error('Transaction has no outputs');\n        if (this.fee < _0n)\n            throw new Error('Outputs spends more than inputs amount');\n        return this.toBytes(true, true);\n    }\n    combine(other) {\n        if (!(other instanceof Transaction))\n            throw new TypeError('\"other\" expected Transaction, got type=' + typeof other);\n        // Match main's accumulator model: operation policy belongs to the receiver that is mutated.\n        const opts = this.opts;\n        // BIP174 combiners merge same-transaction PSBTs across versions and emit the highest required\n        // version, so PSBTVersion mismatches are normalized below instead of treated as conflicts.\n        const PSBTVersion = Math.max(this.opts.PSBTVersion || 0, other.opts.PSBTVersion || 0);\n        if (this.opts.version !== other.opts.version)\n            throw new Error(`Transaction/combine: different version this=${this.opts.version} ` +\n                `other=${other.opts.version}`);\n        const thisV2 = this.isPSBTv2();\n        const otherV2 = other.isPSBTv2();\n        if (!thisV2 || !otherV2) {\n            const thisLockTime = this.lockTime;\n            const otherLockTime = other.lockTime;\n            if (thisLockTime !== otherLockTime)\n                throw new Error(`Transaction/combine: different lockTime this=${thisLockTime} other=${otherLockTime}`);\n        }\n        for (const k of ['inputs', 'outputs']) {\n            if (this[k].length !== other[k].length) {\n                throw new Error(`Transaction/combine: different ${k} length this=${this[k].length} other=${other[k].length}`);\n            }\n        }\n        // Same-transaction checks must compare the normalized unsigned tx bytes here: PSBTv0 stores\n        // `global.unsignedTx`, while PSBTv2 reconstructs the same transaction from split fields.\n        const unsignedTx = this.unsignedTx;\n        if (!equalBytes(unsignedTx, other.unsignedTx))\n            throw new Error(`Transaction/combine: different unsigned tx`);\n        let txModifiable;\n        if (thisV2 && otherV2) {\n            // Core combines the stored optional bytes without deriving replacements from signatures.\n            // Only explicit legacy-omission compatibility gives an absent field an effective value.\n            const policy = (tx) => {\n                if (tx.global.txModifiable !== undefined)\n                    return cleanTxModifiable(tx.global.txModifiable, opts.unknown);\n                return opts.allowMissingTxModifiable ? tx.modifiable(true, opts.unknown) : 0;\n            };\n            const a = policy(this);\n            const b = policy(other);\n            // Known mutability permissions use intersection and SIGHASH_SINGLE presence uses union.\n            // Future flag bits must agree because this implementation does not know how to merge them.\n            if ((a & ~0b111) !== (b & ~0b111))\n                throw new Error('Transaction/combine: conflicting unknown txModifiable flags');\n            txModifiable = (a & ~0b111) | (a & b & 0b011) | ((a | b) & 0b100);\n            // Preserve Core's optional-field semantics when neither participant supplied policy.\n            if (txModifiable === 0 &&\n                this.global.txModifiable === undefined &&\n                other.global.txModifiable === undefined &&\n                !opts.allowMissingTxModifiable)\n                txModifiable = undefined;\n        }\n        else if (thisV2)\n            txModifiable = this.modifiable(opts.allowMissingTxModifiable, opts.unknown);\n        else if (otherV2)\n            txModifiable = other.modifiable(opts.allowMissingTxModifiable, opts.unknown);\n        const thisGlobal = { ...this.global };\n        const otherGlobal = { ...other.global };\n        // PSBTv0 has no fallback-locktime field: fromPSBT caches unsignedTx.nLockTime there only for\n        // effective-locktime resolution and v2 promotion. Do not merge that cache as a v2 wire value.\n        if (thisV2 !== otherV2) {\n            if (!thisV2)\n                delete thisGlobal.fallbackLocktime;\n            if (!otherV2)\n                delete otherGlobal.fallbackLocktime;\n            // BIP174 permits v0 to encode version zero explicitly or omit it. Remove only that v0\n            // spelling before scalar conflicts; retaining the v2 field anchors repeated promotion when\n            // the accumulator's original options still target v0.\n            if (!thisV2)\n                delete thisGlobal.version;\n            if (!otherV2)\n                delete otherGlobal.version;\n        }\n        // Transaction-modifiable has dedicated bitwise merge rules above. Fallback locktime is only\n        // one input to the effective locktime resolved from the combined input maps, so retain receiver\n        // precedence and validate the resulting unsigned transaction after those maps merge below.\n        const fallbackLocktime = thisGlobal.fallbackLocktime !== undefined\n            ? thisGlobal.fallbackLocktime\n            : otherGlobal.fallbackLocktime;\n        delete thisGlobal.txModifiable;\n        delete otherGlobal.txModifiable;\n        delete thisGlobal.fallbackLocktime;\n        delete otherGlobal.fallbackLocktime;\n        // Every ordinary global scalar must agree when both participants provide it; silently choosing\n        // either value can detach extension metadata such as a BIP322 message from its signatures.\n        const global = psbt.combineKeyMap(psbt.PSBTGlobal, thisGlobal, otherGlobal, opts.unknown, opts.proprietary);\n        if (fallbackLocktime !== undefined)\n            global.fallbackLocktime = fallbackLocktime;\n        if (PSBTVersion)\n            global.version = PSBTVersion;\n        if (txModifiable === undefined)\n            delete global.txModifiable;\n        else\n            global.txModifiable = txModifiable;\n        let hasOpaqueFinalizedV0 = false;\n        const inputs = this.inputs.map((current, i) => {\n            const currentFinal = this.inputStatus(i) === 'finalized';\n            const otherFinal = other.inputStatus(i) === 'finalized';\n            // Finalized v0 maps no longer contain the partial signatures needed to derive v2 flags.\n            if ((!thisV2 && currentFinal) || (!otherV2 && otherFinal))\n                hasOpaqueFinalizedV0 = true;\n            if (currentFinal && otherFinal) {\n                // Two finalized PSBTs must describe the same complete satisfaction. Requiring matching\n                // presence as well as matching values prevents combining witness-only and scriptSig-only\n                // final states into a third, unreviewed satisfaction.\n                for (const k of ['finalScriptSig', 'finalScriptWitness']) {\n                    const currentHas = !!this.inputs[i][k]?.length;\n                    const otherHas = !!other.inputs[i][k]?.length;\n                    if (currentHas !== otherHas)\n                        throw new Error(`Transaction/combine: different finalized field=${k} input=${i}`);\n                }\n            }\n            const combined = psbt.combineKeyMap(psbt.PSBTInput, current, other.inputs[i], opts.unknown, opts.proprietary);\n            // A final satisfaction supersedes partial signatures and transient signing metadata. This\n            // also avoids manufacturing a contradictory final+partial input from two valid PSBTs.\n            if (currentFinal || otherFinal)\n                cleanFinalInput(combined, opts.unknown, opts.proprietary);\n            return cloneDeep(normalizeInput(combined, undefined, undefined, opts.disableScriptCheck, opts.unknown, opts.proprietary));\n        });\n        // A promoted opaque satisfaction may commit to both transaction halves. Clear only known\n        // permissions; retain a v2 participant's SIGHASH_SINGLE indicator and any future flag bits.\n        if (hasOpaqueFinalizedV0 && global.txModifiable !== undefined)\n            global.txModifiable &= ~0b011;\n        const candidate = new Transaction({ ...opts, PSBTVersion });\n        const outputs = this.outputs.map((current, i) => {\n            const combined = psbt.combineKeyMap(psbt.PSBTOutput, current, other.outputs[i], opts.unknown, opts.proprietary);\n            return cloneDeep(candidate.normalizeOutput(combined));\n        });\n        // Build and validate a detached candidate before touching the receiver. Combining\n        // complementary v2 locktime fields can otherwise create a different unsigned transaction.\n        candidate.global = global;\n        candidate.inputs = inputs;\n        candidate.outputs = outputs;\n        // A v0 input map can contribute signatures while the combined transaction is promoted to v2.\n        // All-v2 restrictions were already intersected above, preserving mutual field omission.\n        if ((!thisV2 || !otherV2) && candidate.isPSBTv2())\n            candidate.global.txModifiable = candidate.txModifiable;\n        if (!equalBytes(candidate.unsignedTx, unsignedTx))\n            throw new Error('Transaction/combine: combined unsigned tx differs');\n        this.global = candidate.global;\n        this.inputs = candidate.inputs;\n        this.outputs = candidate.outputs;\n        return this;\n    }\n    clone() {\n        // deepClone probably faster, but this enforces that encoding is valid\n        return Transaction.fromPSBT(this.toPSBT(), this.opts);\n    }\n}\n/**\n * Merges multiple PSBT blobs into one.\n * @param psbts - PSBT byte arrays to combine\n * @param opts - Transaction parsing, combination, and serialization options. See {@link TxOpts}.\n * @returns Combined PSBT bytes.\n * @throws If the PSBT list is empty or the partial transactions cannot be combined. {@link Error}\n * @example\n * Merge separate partially signed PSBTs that share the same unsigned transaction.\n * ```ts\n * import { PSBTCombine, Transaction } from '@scure/btc-signer/transaction.js';\n * const psbt = new Transaction().toPSBT();\n * PSBTCombine([psbt, psbt]);\n * ```\n */\nexport function PSBTCombine(psbts, opts = {}) {\n    if (!psbts || !Array.isArray(psbts) || !psbts.length)\n        throw new Error('PSBTCombine: wrong PSBT list');\n    // Options affect both map cleanup during combination and the encoding of the returned PSBT.\n    const combineOpts = opts;\n    const tx = Transaction.fromPSBT(psbts[0], combineOpts);\n    for (let i = 1; i < psbts.length; i++)\n        tx.combine(Transaction.fromPSBT(psbts[i], tx.opts));\n    return tx.toPSBT(combineOpts.PSBTVersion);\n}\n// Copy-pasted from bip32 derive, maybe do something like 'bip32.parsePath'?\nconst HARDENED_OFFSET = 0x80000000;\n/**\n * Parses a BIP32 path string into child indices.\n * @param path - derivation path such as `m/0'/1`\n * @returns Array of encoded child indices.\n * @throws If the derivation path syntax or child indices are invalid. {@link Error}\n * @example\n * Parse a BIP32 derivation path into hardened and unhardened indices.\n * ```ts\n * bip32Path(\"m/0'/1\");\n * ```\n */\nexport function bip32Path(path) {\n    const out = [];\n    // PSBT key-origin records only carry raw child indices, so this convenience\n    // parser normalizes textual BIP32 roots into the same integer path array and\n    // uses apostrophe suffixes for hardening.\n    if (!/^[mM]'?/.test(path))\n        throw new Error('Path must start with \"m\" or \"M\"');\n    if (/^[mM]'?$/.test(path))\n        return out;\n    const parts = path.replace(/^[mM]'?\\//, '').split('/');\n    // BIP32 Serialization format `* 1 byte: depth`: extended keys cap depth at\n    // 255, so deeper text paths cannot roundtrip.\n    if (parts.length > 255)\n        throw new Error('Path depth exceeds 255');\n    for (const c of parts) {\n        const m = /^(\\d+)('?)$/.exec(c);\n        if (!m || m.length !== 3)\n            throw new Error(`Invalid child index: ${c}`);\n        let idx = +m[1];\n        if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET)\n            throw new Error('Invalid index');\n        // hardened key\n        if (m[2] === \"'\")\n            idx += HARDENED_OFFSET;\n        out.push(idx);\n    }\n    return out;\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { OutScript, Transaction, type TxOpts } from \"@scure/btc-signer\";\nimport { tapLeafHash } from \"@scure/btc-signer/payment.js\";\nimport { getPrevOut } from \"@scure/btc-signer/transaction.js\";\nimport { equalBytes, hash160 } from \"@scure/btc-signer/utils.js\";\n\nexport const PSBT_OPTIONS: Readonly<TxOpts> = {\n  unknown: \"ignore\",\n  proprietary: \"ignore\",\n};\ntype Input = ReturnType<Transaction[\"getInput\"]>;\n\nexport function isFinalized(input: Input): boolean {\n  return !!(input.finalScriptSig?.length || input.finalScriptWitness?.length);\n}\n\n/** Match the signatures scure's built-in finalizer will use, without constructing a witness. */\nfunction isReady(input: Input): boolean {\n  if (isFinalized(input) || (!input.witnessUtxo && !input.nonWitnessUtxo)) {\n    return false;\n  }\n  let script = OutScript.decode(getPrevOut(input).script);\n  if (script.type === \"tr\") {\n    if (input.tapKeySig?.length) {\n      return true;\n    }\n    return (\n      input.tapLeafScript?.some(([, leaf]) => {\n        const code = leaf.subarray(0, -1);\n        const template = OutScript.decode(code);\n        if (template.type !== \"tr_ms\" && template.type !== \"tr_ns\") {\n          return false;\n        }\n        const hash = tapLeafHash(code, leaf[leaf.length - 1]);\n        const count = template.pubkeys.filter((pub) =>\n          input.tapScriptSig?.some(\n            ([key, signature]) =>\n              signature.length &&\n              equalBytes(key.pubKey, pub) &&\n              equalBytes(key.leafHash, hash),\n          ),\n        ).length;\n        return (\n          count >=\n          (template.type === \"tr_ms\" ? template.m : template.pubkeys.length)\n        );\n      }) ?? false\n    );\n  }\n  if (script.type === \"sh\") {\n    if (!input.redeemScript) {\n      return false;\n    }\n    script = OutScript.decode(input.redeemScript);\n  }\n  const segwit = script.type === \"wpkh\" || script.type === \"wsh\";\n  if (script.type === \"wsh\") {\n    if (!input.witnessScript) {\n      return false;\n    }\n    script = OutScript.decode(input.witnessScript);\n  }\n  if (!segwit && !input.nonWitnessUtxo) {\n    return false;\n  }\n  const signature = input.partialSig?.[0];\n  switch (script.type) {\n    case \"pkh\":\n    case \"wpkh\":\n      return (\n        !!signature?.[1].length &&\n        equalBytes(hash160(signature[0]), script.hash)\n      );\n    case \"pk\":\n      return (\n        !!signature?.[1].length &&\n        secp256k1.Point.fromBytes(signature[0]).equals(\n          secp256k1.Point.fromBytes(script.pubkey),\n        )\n      );\n    case \"ms\":\n      return (\n        script.pubkeys.filter((pub) =>\n          input.partialSig?.some(\n            ([key, sig]) => sig.length && equalBytes(key, pub),\n          ),\n        ).length >= script.m\n      );\n    default:\n      return false;\n  }\n}\n\n/** Parse a complete wallet PSBT using stock scure. */\nexport function parsePsbt(bytes: Uint8Array): Transaction {\n  return Transaction.fromPSBT(bytes, PSBT_OPTIONS);\n}\n\n/** Finalize ready inputs in the original transaction; preserve incomplete inputs. */\nexport function finalizeReadyInputs(tx: Transaction): void {\n  for (let index = 0; index < tx.inputsLength; index++) {\n    if (!isReady(tx.getInput(index))) {\n      continue;\n    }\n    try {\n      tx.finalizeIdx(index);\n    } catch (error) {\n      throw new Error(`Failed to finalize PSBT input #${index}.`, {\n        cause: error,\n      });\n    }\n  }\n}\n","import { finalizeReadyInputs, isFinalized, parsePsbt } from \"@ckb-ccc/btc-psbt\";\nimport { ccc } from \"@ckb-ccc/core\";\nimport * as v from \"valibot\";\nimport {\n  Address,\n  AddressPurpose,\n  BtcProvider,\n  MessageSigningProtocols,\n  Requests,\n  Return,\n  RpcErrorCode,\n  RpcResponse,\n  WalletNetworkName,\n  rpcErrorResponseMessageSchema,\n  rpcSuccessResponseMessageSchema,\n} from \"./advancedBarrel.js\";\n\nasync function checkResponse<T extends keyof Requests>(\n  response: Promise<RpcResponse<T>>,\n): Promise<Return<T>> {\n  const res = await response;\n  if (v.is(rpcErrorResponseMessageSchema, res)) {\n    // eslint-disable-next-line @typescript-eslint/only-throw-error\n    throw res.error;\n  }\n\n  if (v.is(rpcSuccessResponseMessageSchema, res)) {\n    return res.result;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/only-throw-error\n  throw {\n    code: RpcErrorCode.INTERNAL_ERROR,\n    message: \"Received unknown response from provider.\",\n    data: res,\n  };\n}\n\n/**\n * Class representing a Bitcoin signer that extends SignerBtc\n * @public\n */\nexport class Signer extends ccc.SignerBtc {\n  private addressCache: Promise<Address | undefined> | undefined;\n\n  /**\n   * Creates an instance of Signer.\n   * @param client - The client instance.\n   * @param provider - The provider instance.\n   */\n  constructor(\n    client: ccc.Client,\n    public readonly provider: BtcProvider,\n    _preferredNetworks?: ccc.NetworkPreference[],\n    public readonly network?: WalletNetworkName,\n  ) {\n    super(client);\n  }\n\n  async assertAddress(): Promise<Address> {\n    const request = this.addressCache ?? this.requestAddress();\n    this.addressCache = request;\n\n    let address: Address | undefined;\n    try {\n      address = await request;\n    } catch (error) {\n      if (this.addressCache === request) {\n        this.addressCache = undefined;\n      }\n      throw error;\n    }\n\n    if (address) {\n      return address;\n    }\n    this.addressCache = undefined;\n    throw Error(\"Not connected\");\n  }\n\n  private async requestAddress(): Promise<Address | undefined> {\n    if (this.network && (await this.getNetwork()) !== this.network) {\n      return;\n    }\n\n    return (\n      await checkResponse(\n        this.provider.request(\"getAddresses\", {\n          purposes: [AddressPurpose.Payment],\n        }),\n      )\n    ).addresses[0];\n  }\n\n  /**\n   * Gets the Bitcoin account address.\n   * @returns A promise that resolves to the Bitcoin account address.\n   */\n  async getBtcAccount(): Promise<string> {\n    return (await this.assertAddress()).address;\n  }\n\n  /**\n   * Gets the Bitcoin public key.\n   * @returns A promise that resolves to the Bitcoin public key.\n   */\n  async getBtcPublicKey(): Promise<ccc.Hex> {\n    return ccc.hexFrom((await this.assertAddress()).publicKey);\n  }\n\n  /**\n   * Connects to the provider by requesting accounts.\n   * @returns A promise that resolves when the connection is established.\n   */\n  async connect(): Promise<void> {\n    if (await this.isConnected()) {\n      return;\n    }\n\n    await checkResponse(\n      this.provider.request(\"wallet_requestPermissions\", undefined),\n    );\n    const currentNetwork = this.network ? await this.getNetwork() : undefined;\n    if (this.network && currentNetwork !== this.network) {\n      await checkResponse(\n        this.provider.request(\"wallet_changeNetwork\", { name: this.network }),\n      );\n      this.addressCache = undefined;\n    }\n  }\n\n  async disconnect(): Promise<void> {\n    this.addressCache = undefined;\n  }\n\n  onReplaced(listener: () => void): () => void {\n    const stops: (() => void)[] = [];\n    const stop = () => {\n      stops.splice(0).forEach((unregister) => unregister());\n    };\n    const replacer = () => {\n      listener();\n      stop();\n    };\n    stops.push(\n      this.provider.addListener(\"accountChange\", replacer),\n      this.provider.addListener(\"networkChange\", replacer),\n    );\n\n    return stop;\n  }\n\n  /**\n   * Checks if the signer is connected.\n   * @returns A promise that resolves to true if connected, false otherwise.\n   */\n  async isConnected(): Promise<boolean> {\n    try {\n      const address = await this.requestAddress();\n      if (address) {\n        this.addressCache = Promise.resolve(address);\n      } else {\n        this.addressCache = undefined;\n      }\n      return address !== undefined;\n    } catch (_error) {\n      this.addressCache = undefined;\n      return false;\n    }\n  }\n\n  private async getNetwork(): Promise<WalletNetworkName> {\n    return (\n      await checkResponse(this.provider.request(\"wallet_getNetwork\", null))\n    ).bitcoin.name;\n  }\n\n  /**\n   * Signs a raw message with the Bitcoin account.\n   * @param message - The message to sign.\n   * @returns A promise that resolves to the signed message.\n   */\n  async signMessageRaw(message: string | ccc.BytesLike): Promise<string> {\n    const challenge =\n      typeof message === \"string\" ? message : ccc.hexFrom(message).slice(2);\n\n    return (\n      await checkResponse(\n        this.provider.request(\"signMessage\", {\n          message: challenge,\n          address: (await this.assertAddress()).address,\n          protocol: MessageSigningProtocols.ECDSA,\n        }),\n      )\n    ).signature;\n  }\n\n  private async prepareSignPsbtParams(\n    psbtHex: ccc.Hex,\n    options: ccc.SignPsbtOptions,\n  ): Promise<{\n    psbtBase64: string;\n    signInputs: Record<string, number[]>;\n  }> {\n    const unsigned = parsePsbt(ccc.bytesFrom(psbtHex));\n    const inputsToSign = [...options.inputsToSign];\n\n    if (!inputsToSign.length) {\n      const address = await this.getBtcAccount();\n      for (let index = 0; index < unsigned.inputsLength; index++) {\n        const input = unsigned.getInput(index);\n        if (\n          !isFinalized(input) &&\n          !input.tapKeySig &&\n          !input.partialSig?.length &&\n          !input.tapScriptSig?.length\n        ) {\n          inputsToSign.push(ccc.InputToSign.from({ index, address }));\n        }\n      }\n    }\n\n    const psbtBase64 = ccc.bytesTo(psbtHex, \"base64\");\n\n    const signInputs = inputsToSign.reduce(\n      (acc, input) => {\n        if (!input.address) {\n          throw new Error(\n            \"Xverse only supports signing with address. Please provide 'address' in inputsToSign.\",\n          );\n        }\n        if (acc[input.address]) {\n          acc[input.address].push(input.index);\n        } else {\n          acc[input.address] = [input.index];\n        }\n        return acc;\n      },\n      {} as Record<string, number[]>,\n    );\n\n    return { psbtBase64, signInputs };\n  }\n\n  /**\n   * Signs a PSBT using Xverse wallet.\n   *\n   * @param psbtHex - The hex string of PSBT to sign.\n   * @param options - Options for signing the PSBT\n   * @returns A promise that resolves to the signed PSBT as a Hex string\n   *\n   * @remarks\n   * Xverse accepts:\n   * - psbt: A string representing the PSBT to sign, encoded in base64\n   * - signInputs: A Record<string, number[]> where:\n   *   - keys are the addresses to use for signing\n   *   - values are the indexes of the inputs to sign with each address\n   *\n   * Xverse returns:\n   * - psbt: The base64 encoded signed PSBT, which is not finalized\n   *\n   * Xverse has no equivalent of `autoFinalized`, so when it is enabled the\n   * ready supported inputs are finalized locally after signing. The RPC does not\n   * support `sighashTypes` or `disableTweakSigner`.\n   *\n   * @see https://docs.xverse.app/sats-connect/bitcoin-methods/signpsbt\n   */\n  async signPsbt(\n    psbtHex: ccc.HexLike,\n    options?: ccc.SignPsbtOptionsLike,\n  ): Promise<ccc.Hex> {\n    const normalized = ccc.SignPsbtOptions.from(options);\n    const { psbtBase64, signInputs } = await this.prepareSignPsbtParams(\n      ccc.hexFrom(psbtHex),\n      normalized,\n    );\n\n    const signedPsbtBase64 = (\n      await checkResponse(\n        this.provider.request(\"signPsbt\", {\n          psbt: psbtBase64,\n          signInputs,\n          broadcast: false,\n        }),\n      )\n    ).psbt;\n\n    const signedPsbt = parsePsbt(ccc.bytesFrom(signedPsbtBase64, \"base64\"));\n    if (!normalized.autoFinalized) {\n      return ccc.hexFrom(signedPsbt.toPSBT());\n    }\n    finalizeReadyInputs(signedPsbt);\n    return ccc.hexFrom(signedPsbt.toPSBT());\n  }\n\n  /**\n   * Broadcasts a PSBT to the Bitcoin network.\n   *\n   * @remarks\n   * Xverse does not support broadcasting a signed PSBT directly.\n   * It only supports \"Sign and Broadcast\" as a single atomic operation via `signAndBroadcastPsbt`.\n   */\n  async broadcastPsbt(\n    _psbtHex: ccc.HexLike,\n    _options?: ccc.SignPsbtOptionsLike,\n  ): Promise<ccc.Hex> {\n    throw new Error(\n      \"Xverse does not support broadcasting signed PSBTs directly. Use signAndBroadcastPsbt instead.\",\n    );\n  }\n\n  async signAndBroadcastPsbt(\n    psbtHex: ccc.HexLike,\n    options?: ccc.SignPsbtOptionsLike,\n  ): Promise<ccc.Hex> {\n    // Xverse finalizes and broadcasts on its own side, so autoFinalized is\n    // not needed here.\n    const { psbtBase64, signInputs } = await this.prepareSignPsbtParams(\n      ccc.hexFrom(psbtHex),\n      ccc.SignPsbtOptions.from(options),\n    );\n\n    const result = await checkResponse(\n      this.provider.request(\"signPsbt\", {\n        psbt: psbtBase64,\n        signInputs,\n        broadcast: true,\n      }),\n    );\n\n    if (!result.txid) {\n      throw new Error(\"Failed to broadcast PSBT\");\n    }\n\n    return ccc.hexFrom(result.txid);\n  }\n}\n","import { ccc } from \"@ckb-ccc/core\";\nimport { BtcProvider, Provider } from \"./advancedBarrel.js\";\nimport { Signer } from \"./signer.js\";\n\nfunction getProviderById(providerId: string) {\n  return (\n    providerId\n      ?.split(\".\")\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return\n      .reduce((acc: any, part) => acc?.[part], window) as BtcProvider\n  );\n}\n\n/**\n * Retrieves the Xverse signer if available.\n * @public\n *\n * @param client - The client instance.\n * @returns All Xverse Signer instances\n */\nexport function getXverseSigners(\n  client: ccc.Client,\n  preferredNetworks?: ccc.NetworkPreference[],\n): { wallet: ccc.Wallet; signerInfo: ccc.SignerInfo }[] {\n  const windowRef = window as {\n    BitcoinProvider?: BtcProvider;\n    XverseProviders?: {\n      BitcoinProvider?: BtcProvider;\n    };\n    btc_providers?: Provider[];\n  };\n\n  const signers = (() => {\n    if (windowRef.btc_providers) {\n      return windowRef.btc_providers.flatMap((provider) => {\n        const networks =\n          provider.name === \"Xverse Wallet\" ||\n          (provider.methods?.includes(\"wallet_getNetwork\") &&\n            provider.methods.includes(\"wallet_changeNetwork\"))\n            ? ([\"Mainnet\", \"Testnet4\", \"Signet\", \"Regtest\"] as const)\n            : ([undefined] as const);\n\n        return networks\n          .filter(\n            (network) =>\n              client.addressPrefix !== \"ckb\" || network === \"Mainnet\",\n          )\n          .map((network) => ({\n            wallet: {\n              name: provider.name,\n              icon: provider.icon,\n            },\n            signerInfo: {\n              name: network && network !== \"Mainnet\" ? `BTC ${network}` : \"BTC\",\n              signer: new Signer(\n                client,\n                getProviderById(provider.id),\n                preferredNetworks,\n                network,\n              ),\n            },\n          }));\n      });\n    }\n\n    return [];\n  })();\n\n  return signers;\n}\n","export * from \"./signer.js\";\nexport * from \"./signersFactory.js\";\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],"mappings":"A,2KA2BA,MAAM8I,EAAY,GAAOC,EAAI,GAAK,GAAM,EAClCC,EAAY,GAAMD,IAAM,EAG9B,SAASE,EAAc,EAAM,EAAY,EAAG,EAAM,CAC9C,IAAMC,EAAIJ,EAAS,CAAC,EACdK,EAAIH,EAAS,CAAC,EACpBI,EAAK,UAAUC,EAAYC,EAAOH,EAAID,EAAGI,CAAI,EAC7CF,EAAK,UAAUC,EAAa,EAAGC,EAAOJ,EAAIC,EAAGG,CAAI,CACrD,CC1BA,SAAgBtJ,EAAQ,EAAG,CAKvB,OAAQwJ,aAAa,YAChB,YAAY,OAAOA,CAAC,GACjBA,EAAE,YAAY,OAAS,cACvB,sBAAuBA,GACvBA,EAAE,oBAAsB,CACpC,CAGA,MAAMvJ,EAAU,GAAWyJ,EAAQ,IAAIA,EAAM,IAAM,GAcnD,SAAgBxJ,EAAQ,EAAG,EAAQ,GAAI,CACnC,GAAI,OAAO6I,GAAM,SACb,MAAU,UAAU9I,EAAOyJ,CAAK,EAAI,wBAA0B,OAAOX,CAAC,EAC1E,GAAI,CAAC,OAAO,cAAcA,CAAC,GAAKA,EAAI,EAChC,MAAU,WAAW9I,EAAOyJ,CAAK,EAAI,8BAAgCX,CAAC,EAC1E,OAAOA,CACX,CAgCA,SAAgB5I,EAAO,EAAO,EAAQ,EAAQ,GAAI,CAG9C,GAAIH,EAAQ6J,CAAK,IAAMC,IAAW,IAAA,IAAaD,EAAM,SAAWC,GAC5D,OAAOD,EAEPC,IAAW,IAAA,IACXH,EAAQG,EAAQ,QAAQ,EAC5B,IAAMC,EAAQ/J,EAAQ6J,CAAK,EACrBG,EAAQF,IAAW,IAAA,GAAqC,GAAzB,cAAcA,IAC7CG,EAAMF,EAAQ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