@bsv/sdk 1.9.31 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/package.json +2 -3
- package/dist/cjs/src/auth/Peer.js +11 -18
- package/dist/cjs/src/auth/Peer.js.map +1 -1
- package/dist/cjs/src/auth/SessionManager.js.map +1 -1
- package/dist/cjs/src/auth/certificates/Certificate.js +8 -18
- package/dist/cjs/src/auth/certificates/Certificate.js.map +1 -1
- package/dist/cjs/src/auth/certificates/MasterCertificate.js +9 -19
- package/dist/cjs/src/auth/certificates/MasterCertificate.js.map +1 -1
- package/dist/cjs/src/auth/certificates/VerifiableCertificate.js +7 -17
- package/dist/cjs/src/auth/certificates/VerifiableCertificate.js.map +1 -1
- package/dist/cjs/src/auth/certificates/__tests/CompletedProtoWallet.js.map +1 -1
- package/dist/cjs/src/auth/clients/AuthFetch.js +7 -17
- package/dist/cjs/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/cjs/src/auth/clients/__tests__/AuthFetch.test.js.map +1 -1
- package/dist/cjs/src/auth/transports/SimplifiedFetchTransport.js +7 -17
- package/dist/cjs/src/auth/transports/SimplifiedFetchTransport.js.map +1 -1
- package/dist/cjs/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js +7 -17
- package/dist/cjs/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js.map +1 -1
- package/dist/cjs/src/auth/utils/createNonce.js +9 -18
- package/dist/cjs/src/auth/utils/createNonce.js.map +1 -1
- package/dist/cjs/src/auth/utils/validateCertificates.js.map +1 -1
- package/dist/cjs/src/auth/utils/verifyNonce.js +9 -18
- package/dist/cjs/src/auth/utils/verifyNonce.js.map +1 -1
- package/dist/cjs/src/compat/BSM.js +7 -17
- package/dist/cjs/src/compat/BSM.js.map +1 -1
- package/dist/cjs/src/compat/ECIES.js +7 -17
- package/dist/cjs/src/compat/ECIES.js.map +1 -1
- package/dist/cjs/src/compat/HD.js +7 -17
- package/dist/cjs/src/compat/HD.js.map +1 -1
- package/dist/cjs/src/compat/Mnemonic.js +7 -17
- package/dist/cjs/src/compat/Mnemonic.js.map +1 -1
- package/dist/cjs/src/compat/Utxo.js +1 -1
- package/dist/cjs/src/compat/Utxo.js.map +1 -1
- package/dist/cjs/src/compat/index.js +7 -17
- package/dist/cjs/src/compat/index.js.map +1 -1
- package/dist/cjs/src/identity/ContactsManager.js +1 -1
- package/dist/cjs/src/identity/ContactsManager.js.map +1 -1
- package/dist/cjs/src/identity/IdentityClient.js.map +1 -1
- package/dist/cjs/src/kvstore/GlobalKVStore.js +10 -20
- package/dist/cjs/src/kvstore/GlobalKVStore.js.map +1 -1
- package/dist/cjs/src/kvstore/LocalKVStore.js +7 -17
- package/dist/cjs/src/kvstore/LocalKVStore.js.map +1 -1
- package/dist/cjs/src/kvstore/kvStoreInterpreter.js +7 -17
- package/dist/cjs/src/kvstore/kvStoreInterpreter.js.map +1 -1
- package/dist/cjs/src/messages/EncryptedMessage.js +0 -19
- package/dist/cjs/src/messages/EncryptedMessage.js.map +1 -1
- package/dist/cjs/src/messages/SignedMessage.js.map +1 -1
- package/dist/cjs/src/messages/index.js +7 -17
- package/dist/cjs/src/messages/index.js.map +1 -1
- package/dist/cjs/src/overlay-tools/Historian.js.map +1 -1
- package/dist/cjs/src/overlay-tools/HostReputationTracker.js.map +1 -1
- package/dist/cjs/src/overlay-tools/LookupResolver.js +7 -17
- package/dist/cjs/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/cjs/src/overlay-tools/OverlayAdminTokenTemplate.js.map +1 -1
- package/dist/cjs/src/overlay-tools/SHIPBroadcaster.js +7 -17
- package/dist/cjs/src/overlay-tools/SHIPBroadcaster.js.map +1 -1
- package/dist/cjs/src/overlay-tools/withDoubleSpendRetry.js +2 -1
- package/dist/cjs/src/overlay-tools/withDoubleSpendRetry.js.map +1 -1
- package/dist/cjs/src/primitives/AESGCM.js +32 -77
- package/dist/cjs/src/primitives/AESGCM.js.map +1 -1
- package/dist/cjs/src/primitives/BigNumber.js.map +1 -1
- package/dist/cjs/src/primitives/Curve.js.map +1 -1
- package/dist/cjs/src/primitives/DRBG.js.map +1 -1
- package/dist/cjs/src/primitives/ECDSA.js +23 -22
- package/dist/cjs/src/primitives/ECDSA.js.map +1 -1
- package/dist/cjs/src/primitives/Hash.js +6 -6
- package/dist/cjs/src/primitives/Hash.js.map +1 -1
- package/dist/cjs/src/primitives/JacobianPoint.js.map +1 -1
- package/dist/cjs/src/primitives/K256.js.map +1 -1
- package/dist/cjs/src/primitives/Mersenne.js.map +1 -1
- package/dist/cjs/src/primitives/MontgomoryMethod.js.map +1 -1
- package/dist/cjs/src/primitives/Point.js +6 -63
- package/dist/cjs/src/primitives/Point.js.map +1 -1
- package/dist/cjs/src/primitives/Polynomial.js.map +1 -1
- package/dist/cjs/src/primitives/PrivateKey.js +9 -46
- package/dist/cjs/src/primitives/PrivateKey.js.map +1 -1
- package/dist/cjs/src/primitives/PublicKey.js +1 -1
- package/dist/cjs/src/primitives/PublicKey.js.map +1 -1
- package/dist/cjs/src/primitives/Random.js.map +1 -1
- package/dist/cjs/src/primitives/ReductionContext.js.map +1 -1
- package/dist/cjs/src/primitives/Schnorr.js.map +1 -1
- package/dist/cjs/src/primitives/Secp256r1.js.map +1 -1
- package/dist/cjs/src/primitives/Signature.js.map +1 -1
- package/dist/cjs/src/primitives/SymmetricKey.js.map +1 -1
- package/dist/cjs/src/primitives/TransactionSignature.js +7 -17
- package/dist/cjs/src/primitives/TransactionSignature.js.map +1 -1
- package/dist/cjs/src/primitives/hex.js +3 -2
- package/dist/cjs/src/primitives/hex.js.map +1 -1
- package/dist/cjs/src/primitives/index.js +7 -17
- package/dist/cjs/src/primitives/index.js.map +1 -1
- package/dist/cjs/src/primitives/utils.js +15 -123
- package/dist/cjs/src/primitives/utils.js.map +1 -1
- package/dist/cjs/src/registry/RegistryClient.js +2 -2
- package/dist/cjs/src/registry/RegistryClient.js.map +1 -1
- package/dist/cjs/src/script/OP.js +3 -3
- package/dist/cjs/src/script/OP.js.map +1 -1
- package/dist/cjs/src/script/Script.js.map +1 -1
- package/dist/cjs/src/script/Spend.js +7 -17
- package/dist/cjs/src/script/Spend.js.map +1 -1
- package/dist/cjs/src/script/templates/P2PKH.js.map +1 -1
- package/dist/cjs/src/script/templates/PushDrop.js.map +1 -1
- package/dist/cjs/src/script/templates/RPuzzle.js.map +1 -1
- package/dist/cjs/src/storage/StorageDownloader.js.map +1 -1
- package/dist/cjs/src/storage/StorageUploader.js +7 -17
- package/dist/cjs/src/storage/StorageUploader.js.map +1 -1
- package/dist/cjs/src/storage/StorageUtils.js.map +1 -1
- package/dist/cjs/src/storage/__test/StorageDownloader.test.js +171 -0
- package/dist/cjs/src/storage/__test/StorageDownloader.test.js.map +1 -0
- package/dist/cjs/src/storage/__test/StorageUploader.test.js +163 -0
- package/dist/cjs/src/storage/__test/StorageUploader.test.js.map +1 -0
- package/dist/cjs/src/storage/__test/StorageUtils.test.js +97 -0
- package/dist/cjs/src/storage/__test/StorageUtils.test.js.map +1 -0
- package/dist/cjs/src/storage/index.js +7 -17
- package/dist/cjs/src/storage/index.js.map +1 -1
- package/dist/cjs/src/totp/totp.js.map +1 -1
- package/dist/cjs/src/transaction/Beef.js.map +1 -1
- package/dist/cjs/src/transaction/BeefParty.js.map +1 -1
- package/dist/cjs/src/transaction/BeefTx.js.map +1 -1
- package/dist/cjs/src/transaction/Broadcaster.js +3 -2
- package/dist/cjs/src/transaction/Broadcaster.js.map +1 -1
- package/dist/cjs/src/transaction/MerklePath.js.map +1 -1
- package/dist/cjs/src/transaction/Transaction.js +1 -1
- package/dist/cjs/src/transaction/Transaction.js.map +1 -1
- package/dist/cjs/src/transaction/broadcasters/ARC.js.map +1 -1
- package/dist/cjs/src/transaction/broadcasters/DefaultBroadcaster.js +2 -1
- package/dist/cjs/src/transaction/broadcasters/DefaultBroadcaster.js.map +1 -1
- package/dist/cjs/src/transaction/broadcasters/Teranode.js.map +1 -1
- package/dist/cjs/src/transaction/broadcasters/WhatsOnChainBroadcaster.js.map +1 -1
- package/dist/cjs/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -1
- package/dist/cjs/src/transaction/chaintrackers/DefaultChainTracker.js +2 -1
- package/dist/cjs/src/transaction/chaintrackers/DefaultChainTracker.js.map +1 -1
- package/dist/cjs/src/transaction/chaintrackers/WhatsOnChain.js.map +1 -1
- package/dist/cjs/src/transaction/fee-models/LivePolicy.js.map +1 -1
- package/dist/cjs/src/transaction/fee-models/SatoshisPerKilobyte.js.map +1 -1
- package/dist/cjs/src/transaction/http/BinaryFetchClient.js +2 -2
- package/dist/cjs/src/transaction/http/BinaryFetchClient.js.map +1 -1
- package/dist/cjs/src/transaction/http/DefaultHttpClient.js +2 -1
- package/dist/cjs/src/transaction/http/DefaultHttpClient.js.map +1 -1
- package/dist/cjs/src/transaction/http/NodejsHttpClient.js.map +1 -1
- package/dist/cjs/src/wallet/CachedKeyDeriver.js.map +1 -1
- package/dist/cjs/src/wallet/KeyDeriver.js.map +1 -1
- package/dist/cjs/src/wallet/ProtoWallet.js +1 -1
- package/dist/cjs/src/wallet/ProtoWallet.js.map +1 -1
- package/dist/cjs/src/wallet/WalletClient.js.map +1 -1
- package/dist/cjs/src/wallet/WalletError.js.map +1 -1
- package/dist/cjs/src/wallet/index.js +7 -17
- package/dist/cjs/src/wallet/index.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/HTTPWalletJSON.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/HTTPWalletWire.js +7 -17
- package/dist/cjs/src/wallet/substrates/HTTPWalletWire.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/ReactNativeWebView.js +7 -17
- package/dist/cjs/src/wallet/substrates/ReactNativeWebView.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/WalletWireProcessor.js +7 -17
- package/dist/cjs/src/wallet/substrates/WalletWireProcessor.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/WalletWireTransceiver.js +7 -17
- package/dist/cjs/src/wallet/substrates/WalletWireTransceiver.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/XDM.js +7 -17
- package/dist/cjs/src/wallet/substrates/XDM.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js +2 -1
- package/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js.map +1 -1
- package/dist/cjs/src/wallet/substrates/window.CWI.js.map +1 -1
- package/dist/cjs/src/wallet/validationHelpers.js +41 -51
- package/dist/cjs/src/wallet/validationHelpers.js.map +1 -1
- package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
- package/dist/esm/src/auth/Peer.js +4 -1
- package/dist/esm/src/auth/Peer.js.map +1 -1
- package/dist/esm/src/auth/SessionManager.js.map +1 -1
- package/dist/esm/src/auth/certificates/Certificate.js +1 -1
- package/dist/esm/src/auth/certificates/Certificate.js.map +1 -1
- package/dist/esm/src/auth/certificates/MasterCertificate.js +2 -2
- package/dist/esm/src/auth/certificates/MasterCertificate.js.map +1 -1
- package/dist/esm/src/auth/certificates/VerifiableCertificate.js.map +1 -1
- package/dist/esm/src/auth/certificates/__tests/CompletedProtoWallet.js.map +1 -1
- package/dist/esm/src/auth/clients/AuthFetch.js.map +1 -1
- package/dist/esm/src/auth/clients/__tests__/AuthFetch.test.js.map +1 -1
- package/dist/esm/src/auth/transports/SimplifiedFetchTransport.js.map +1 -1
- package/dist/esm/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js.map +1 -1
- package/dist/esm/src/auth/utils/validateCertificates.js.map +1 -1
- package/dist/esm/src/compat/BSM.js.map +1 -1
- package/dist/esm/src/compat/ECIES.js.map +1 -1
- package/dist/esm/src/compat/HD.js.map +1 -1
- package/dist/esm/src/compat/Mnemonic.js.map +1 -1
- package/dist/esm/src/identity/ContactsManager.js +1 -1
- package/dist/esm/src/identity/ContactsManager.js.map +1 -1
- package/dist/esm/src/identity/IdentityClient.js.map +1 -1
- package/dist/esm/src/kvstore/GlobalKVStore.js +3 -3
- package/dist/esm/src/kvstore/GlobalKVStore.js.map +1 -1
- package/dist/esm/src/kvstore/LocalKVStore.js.map +1 -1
- package/dist/esm/src/kvstore/kvStoreInterpreter.js.map +1 -1
- package/dist/esm/src/messages/EncryptedMessage.js +0 -19
- package/dist/esm/src/messages/EncryptedMessage.js.map +1 -1
- package/dist/esm/src/messages/SignedMessage.js.map +1 -1
- package/dist/esm/src/overlay-tools/Historian.js.map +1 -1
- package/dist/esm/src/overlay-tools/HostReputationTracker.js.map +1 -1
- package/dist/esm/src/overlay-tools/LookupResolver.js.map +1 -1
- package/dist/esm/src/overlay-tools/OverlayAdminTokenTemplate.js.map +1 -1
- package/dist/esm/src/overlay-tools/SHIPBroadcaster.js.map +1 -1
- package/dist/esm/src/overlay-tools/withDoubleSpendRetry.js.map +1 -1
- package/dist/esm/src/primitives/AESGCM.js +26 -71
- package/dist/esm/src/primitives/AESGCM.js.map +1 -1
- package/dist/esm/src/primitives/BigNumber.js.map +1 -1
- package/dist/esm/src/primitives/Curve.js.map +1 -1
- package/dist/esm/src/primitives/DRBG.js.map +1 -1
- package/dist/esm/src/primitives/ECDSA.js +23 -22
- package/dist/esm/src/primitives/ECDSA.js.map +1 -1
- package/dist/esm/src/primitives/Hash.js.map +1 -1
- package/dist/esm/src/primitives/JacobianPoint.js.map +1 -1
- package/dist/esm/src/primitives/K256.js.map +1 -1
- package/dist/esm/src/primitives/Mersenne.js.map +1 -1
- package/dist/esm/src/primitives/MontgomoryMethod.js.map +1 -1
- package/dist/esm/src/primitives/Point.js +4 -61
- package/dist/esm/src/primitives/Point.js.map +1 -1
- package/dist/esm/src/primitives/Polynomial.js.map +1 -1
- package/dist/esm/src/primitives/PrivateKey.js +2 -29
- package/dist/esm/src/primitives/PrivateKey.js.map +1 -1
- package/dist/esm/src/primitives/PublicKey.js +1 -1
- package/dist/esm/src/primitives/PublicKey.js.map +1 -1
- package/dist/esm/src/primitives/Random.js.map +1 -1
- package/dist/esm/src/primitives/ReductionContext.js.map +1 -1
- package/dist/esm/src/primitives/Schnorr.js.map +1 -1
- package/dist/esm/src/primitives/Secp256r1.js.map +1 -1
- package/dist/esm/src/primitives/Signature.js.map +1 -1
- package/dist/esm/src/primitives/SymmetricKey.js.map +1 -1
- package/dist/esm/src/primitives/TransactionSignature.js.map +1 -1
- package/dist/esm/src/primitives/hex.js.map +1 -1
- package/dist/esm/src/primitives/utils.js +10 -118
- package/dist/esm/src/primitives/utils.js.map +1 -1
- package/dist/esm/src/registry/RegistryClient.js.map +1 -1
- package/dist/esm/src/script/OP.js +3 -3
- package/dist/esm/src/script/OP.js.map +1 -1
- package/dist/esm/src/script/Script.js.map +1 -1
- package/dist/esm/src/script/Spend.js.map +1 -1
- package/dist/esm/src/script/templates/P2PKH.js.map +1 -1
- package/dist/esm/src/script/templates/PushDrop.js.map +1 -1
- package/dist/esm/src/script/templates/RPuzzle.js.map +1 -1
- package/dist/esm/src/storage/StorageDownloader.js.map +1 -1
- package/dist/esm/src/storage/StorageUploader.js.map +1 -1
- package/dist/esm/src/storage/StorageUtils.js.map +1 -1
- package/dist/esm/src/storage/__test/StorageDownloader.test.js +166 -0
- package/dist/esm/src/storage/__test/StorageDownloader.test.js.map +1 -0
- package/dist/esm/src/storage/__test/StorageUploader.test.js +135 -0
- package/dist/esm/src/storage/__test/StorageUploader.test.js.map +1 -0
- package/dist/esm/src/storage/__test/StorageUtils.test.js +72 -0
- package/dist/esm/src/storage/__test/StorageUtils.test.js.map +1 -0
- package/dist/esm/src/totp/totp.js.map +1 -1
- package/dist/esm/src/transaction/Beef.js.map +1 -1
- package/dist/esm/src/transaction/BeefParty.js.map +1 -1
- package/dist/esm/src/transaction/BeefTx.js.map +1 -1
- package/dist/esm/src/transaction/MerklePath.js.map +1 -1
- package/dist/esm/src/transaction/Transaction.js +1 -1
- package/dist/esm/src/transaction/Transaction.js.map +1 -1
- package/dist/esm/src/transaction/broadcasters/ARC.js.map +1 -1
- package/dist/esm/src/transaction/broadcasters/Teranode.js.map +1 -1
- package/dist/esm/src/transaction/broadcasters/WhatsOnChainBroadcaster.js.map +1 -1
- package/dist/esm/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -1
- package/dist/esm/src/transaction/chaintrackers/WhatsOnChain.js.map +1 -1
- package/dist/esm/src/transaction/fee-models/LivePolicy.js.map +1 -1
- package/dist/esm/src/transaction/fee-models/SatoshisPerKilobyte.js.map +1 -1
- package/dist/esm/src/transaction/http/BinaryFetchClient.js.map +1 -1
- package/dist/esm/src/transaction/http/DefaultHttpClient.js.map +1 -1
- package/dist/esm/src/transaction/http/NodejsHttpClient.js.map +1 -1
- package/dist/esm/src/wallet/CachedKeyDeriver.js.map +1 -1
- package/dist/esm/src/wallet/KeyDeriver.js.map +1 -1
- package/dist/esm/src/wallet/ProtoWallet.js +1 -1
- package/dist/esm/src/wallet/ProtoWallet.js.map +1 -1
- package/dist/esm/src/wallet/WalletClient.js.map +1 -1
- package/dist/esm/src/wallet/WalletError.js.map +1 -1
- package/dist/esm/src/wallet/substrates/HTTPWalletJSON.js.map +1 -1
- package/dist/esm/src/wallet/substrates/HTTPWalletWire.js.map +1 -1
- package/dist/esm/src/wallet/substrates/ReactNativeWebView.js.map +1 -1
- package/dist/esm/src/wallet/substrates/WalletWireProcessor.js.map +1 -1
- package/dist/esm/src/wallet/substrates/WalletWireTransceiver.js.map +1 -1
- package/dist/esm/src/wallet/substrates/XDM.js.map +1 -1
- package/dist/esm/src/wallet/substrates/utils/toOriginHeader.js.map +1 -1
- package/dist/esm/src/wallet/substrates/window.CWI.js.map +1 -1
- package/dist/esm/src/wallet/validationHelpers.js +1 -1
- package/dist/esm/src/wallet/validationHelpers.js.map +1 -1
- package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
- package/dist/types/src/auth/Peer.d.ts.map +1 -1
- package/dist/types/src/auth/certificates/MasterCertificate.d.ts.map +1 -1
- package/dist/types/src/auth/utils/getVerifiableCertificates.d.ts.map +1 -1
- package/dist/types/src/auth/utils/validateCertificates.d.ts.map +1 -1
- package/dist/types/src/compat/BSM.d.ts +1 -1
- package/dist/types/src/compat/BSM.d.ts.map +1 -1
- package/dist/types/src/messages/EncryptedMessage.d.ts +0 -19
- package/dist/types/src/messages/EncryptedMessage.d.ts.map +1 -1
- package/dist/types/src/messages/SignedMessage.d.ts.map +1 -1
- package/dist/types/src/primitives/AESGCM.d.ts +0 -18
- package/dist/types/src/primitives/AESGCM.d.ts.map +1 -1
- package/dist/types/src/primitives/ECDSA.d.ts.map +1 -1
- package/dist/types/src/primitives/Hash.d.ts +8 -8
- package/dist/types/src/primitives/Hash.d.ts.map +1 -1
- package/dist/types/src/primitives/Point.d.ts +0 -1
- package/dist/types/src/primitives/Point.d.ts.map +1 -1
- package/dist/types/src/primitives/PrivateKey.d.ts +0 -27
- package/dist/types/src/primitives/PrivateKey.d.ts.map +1 -1
- package/dist/types/src/primitives/Random.d.ts.map +1 -1
- package/dist/types/src/primitives/Secp256r1.d.ts.map +1 -1
- package/dist/types/src/primitives/utils.d.ts +3 -3
- package/dist/types/src/primitives/utils.d.ts.map +1 -1
- package/dist/types/src/storage/StorageUtils.d.ts.map +1 -1
- package/dist/types/src/storage/__test/StorageDownloader.test.d.ts +2 -0
- package/dist/types/src/storage/__test/StorageDownloader.test.d.ts.map +1 -0
- package/dist/types/src/storage/__test/StorageUploader.test.d.ts +2 -0
- package/dist/types/src/storage/__test/StorageUploader.test.d.ts.map +1 -0
- package/dist/types/src/storage/__test/StorageUtils.test.d.ts +2 -0
- package/dist/types/src/storage/__test/StorageUtils.test.d.ts.map +1 -0
- package/dist/types/src/transaction/Beef.d.ts +2 -2
- package/dist/types/src/transaction/Beef.d.ts.map +1 -1
- package/dist/types/src/transaction/http/BinaryFetchClient.d.ts +2 -0
- package/dist/types/src/transaction/http/BinaryFetchClient.d.ts.map +1 -1
- package/dist/types/tsconfig.types.tsbuildinfo +1 -1
- package/dist/umd/bundle.js +3 -3
- package/dist/umd/bundle.js.map +1 -1
- package/docs/reference/messages.md +0 -24
- package/docs/reference/primitives.md +17 -82
- package/package.json +2 -3
- package/src/auth/Peer.ts +4 -1
- package/src/messages/EncryptedMessage.ts +0 -19
- package/src/primitives/AESGCM.ts +34 -75
- package/src/primitives/PrivateKey.ts +0 -27
- package/src/primitives/__tests/AESGCM.test.ts +0 -31
- package/src/primitives/__tests/utils.test.ts +30 -7
- package/src/primitives/utils.ts +2 -127
package/dist/umd/bundle.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,()=>(()=>{"use strict";let e,t,r,i,n;var a,s,o,c,l,h,u,d,f={};f.d=(e,t)=>{for(var r in t)f.o(t,r)&&!f.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},f.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),f.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var p={};f.r(p),f.d(p,{walletErrors:()=>u,HTTPWalletWire:()=>iB,BEEF_V1:()=>rG,BEEF_V2:()=>rY,SignedMessage:()=>m,StorageUtils:()=>k,TopicBroadcaster:()=>nW,KeyShares:()=>t0,BlockHeadersService:()=>r9,MerklePath:()=>rW,RPuzzle:()=>rR,PrivateKey:()=>t1,StorageDownloader:()=>n0,CompletedProtoWallet:()=>nE,isBroadcastResponse:()=>r1,XDM:()=>i_,binaryHttpClient:()=>r5,LookupResolver:()=>n$,LivePolicy:()=>rU,HD:()=>iu,KeyDeriver:()=>iS,defaultBroadcaster:()=>rM,LocalKVStore:()=>ae,ProtoWallet:()=>iP,verifyNonce:()=>nN,AuthFetch:()=>nV,FetchHttpClient:()=>rL,Secp256r1:()=>rv,UnlockingScript:()=>rP,ECIES:()=>iw,Random:()=>tJ,TOTP:()=>iI,ARC:()=>rq,Curve:()=>tU,SHIPCast:()=>nW,ECDSA:()=>y,DEFAULT_SLAP_TRACKERS:()=>nH,GlobalKVStore:()=>as,MasterCertificate:()=>nS,VerifiableCertificate:()=>nx,WERR_INVALID_PARAMETER:()=>iF,SessionManager:()=>nP,SHIPBroadcaster:()=>nW,StorageUploader:()=>nQ,SymmetricKey:()=>rl,WERR_REVIEW_ACTIONS:()=>iD,WalletErrors:()=>iA,WhatsOnChain:()=>r$,WindowCWISubstrate:()=>iN,defaultChainTracker:()=>rz,fromUtxo:()=>iv,validateCertificates:()=>n_,EncryptedMessage:()=>w,Spend:()=>rT,DEFAULT_TESTNET_SLAP_TRACKERS:()=>nq,Hash:()=>g,OverlayAdminTokenTemplate:()=>nD,Mnemonic:()=>ip,NodejsHttpClient:()=>rF,Schnorr:()=>rd,HTTPWalletJSON:()=>iK,LockingScript:()=>rE,PushDrop:()=>rV,Script:()=>rx,ScriptEvaluationError:()=>rN,WERR_INSUFFICIENT_FUNDS:()=>iL,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>n2,HTTPSOverlayLookupFacilitator:()=>nM,BigNumber:()=>P,Beef:()=>rZ,PublicKey:()=>tX,RegistryClient:()=>n7,Transaction:()=>r0,WalletWireProcessor:()=>nk,BeefTx:()=>rj,TransactionSignature:()=>ru,Certificate:()=>iT,WalletWireTransceiver:()=>iR,createNonce:()=>nO,KNOWN_IDENTITY_TYPES:()=>n8,TX_DATA_FORMAT:()=>l,defaultIdentity:()=>n1,getVerifiableCertificates:()=>nA,HTTPSOverlayBroadcastFacilitator:()=>nz,Peer:()=>nC,ReactNativeWebView:()=>iH,Signature:()=>tF,PointInFiniteField:()=>tZ,Teranode:()=>r7,WhatsOnChainBroadcaster:()=>r3,CachedKeyDeriver:()=>ix,defaultHttpClient:()=>rK,withDoubleSpendRetry:()=>nj,SimplifiedFetchTransport:()=>nB,Polynomial:()=>tQ,OP:()=>rk,P2PKH:()=>rC,WalletError:()=>iO,deserializeWalletProtocol:()=>n9,isBroadcastFailure:()=>r2,BeefParty:()=>r8,SecurityLevels:()=>h,Point:()=>tD,BSM:()=>v,ATOMIC_BEEF:()=>rJ,SatoshisPerKilobyte:()=>rD,WalletClient:()=>nI,Validation:()=>I,IdentityClient:()=>n5,Utils:()=>b});var g={};f.r(g),f.d(g,{RIPEMD160:()=>Y,SHA1:()=>Z,SHA1HMAC:()=>et,SHA256:()=>J,SHA256HMAC:()=>ee,SHA512:()=>Q,SHA512HMAC:()=>er,hash160:()=>ec,hash256:()=>eo,htonl:()=>F,pbkdf2:()=>eQ,realHtonl:()=>e2,ripemd160:()=>ei,sha1:()=>en,sha256:()=>ea,sha256hmac:()=>el,sha512:()=>es,sha512hmac:()=>eh,swapBytes32:()=>e0,toArray:()=>U});var b={};f.r(b),f.d(b,{Reader:()=>td,Writer:()=>tu,base64ToArray:()=>tr,constantTimeEquals:()=>ty,encode:()=>tn,fromBase58:()=>to,fromBase58Check:()=>th,minimallyEncode:()=>tf,toArray:()=>e9,toBase58:()=>tc,toBase58Check:()=>tl,toBase64:()=>ta,toHex:()=>e7,toUTF8:()=>ti,verifyNotNull:()=>tb,zero2:()=>e6});var y={};f.r(y),f.d(y,{sign:()=>tW,verify:()=>tj});var m={};f.r(m),f.d(m,{sign:()=>it,verify:()=>ir});var w={};f.r(w),f.d(w,{decrypt:()=>is,encrypt:()=>ia});var v={};f.r(v),f.d(v,{magicHash:()=>ic,sign:()=>il,verify:()=>ih});var I={};f.r(I),f.d(I,{isHexString:()=>i3,parseWalletOutpoint:()=>iq,specOpThrowReviewActions:()=>nv,validateAbortActionArgs:()=>nt,validateAcquireDirectCertificateArgs:()=>np,validateAcquireIssuanceCertificateArgs:()=>nf,validateBase64String:()=>i1,validateBasketInsertion:()=>ni,validateCreateActionArgs:()=>i7,validateCreateActionInput:()=>i6,validateCreateActionOptions:()=>i5,validateCreateActionOutput:()=>i4,validateDiscoverByAttributesArgs:()=>ny,validateDiscoverByIdentityKeyArgs:()=>nb,validateInteger:()=>ij,validateInternalizeActionArgs:()=>ns,validateInternalizeOutput:()=>nn,validateListActionsArgs:()=>nw,validateListCertificatesArgs:()=>nu,validateListOutputsArgs:()=>nm,validateOptionalInteger:()=>iW,validateOptionalOutpointString:()=>no,validateOriginator:()=>na,validateOutpointString:()=>nc,validatePositiveIntegerOrZero:()=>iX,validateProveCertificateArgs:()=>ng,validateRelinquishCertificateArgs:()=>nh,validateRelinquishOutputArgs:()=>nl,validateSatoshis:()=>iz,validateSignActionArgs:()=>ne,validateSignActionOptions:()=>i9,validateStringLength:()=>iG,validateWalletPayment:()=>nr});var k={};f.r(k),f.d(k,{getHashFromURL:()=>nJ,getURLForFile:()=>nY,getURLForHash:()=>nG,isValidURL:()=>nZ,normalizeURL:()=>nX});let S="undefined"!=typeof globalThis?globalThis.Buffer:void 0,x=null!=S&&"function"==typeof S.from,E=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)E[48+e]=e;for(let e=0;e<6;e++)E[65+e]=10+e,E[97+e]=10+e;class P{static zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];static groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];static groupBases=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(P.wordSize);static WORD_MASK=(1n<<P.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=0x3ffffff;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1"),0n===this._magnitude?this._sign=0:this._sign=+(1===e)}get _computedWordsArray(){if(0n===this._magnitude)return[0];let e=[],t=this._magnitude;for(;t>0n;)e.push(Number(t&P.WORD_MASK)),t>>=P.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){let e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;let t=Array(this._nominalWordLength).fill(0);for(let r=0;r<e.length;r++)t[r]=e[r];return t}set words(e){let t=this._sign,r=0n,i=e.length>0?e.length:1;for(let t=i-1;t>=0;t--){let i=void 0===e[t]?0:e[t];r=r<<P.WORD_SIZE_BIGINT|BigInt(i&Number(P.WORD_MASK))}this._magnitude=r,this._sign=t,this._nominalWordLength=i,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof P||null!==e&&"object"==typeof e&&e.constructor?.wordSize===P.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return 0>e.cmp(t)?e:t}constructor(e=0,t=10,r="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===e&&(e=0),null===e)return void this._initializeState(0n,0);if("bigint"==typeof e){this._initializeState(e<0n?-e:e,+(e<0n)),this.normSign();return}let i=t,n=r;if(("le"===t||"be"===t)&&(n=t,i=10),"number"==typeof e)return void this.initNumber(e,n);if(Array.isArray(e))return void this.initArray(e,n);if("string"==typeof e){"hex"===i&&(i=16),this.assert("number"==typeof i&&i===(0|i)&&i>=2&&i<=36,"Base must be an integer between 2 and 36");const t=e.toString().replace(/\s+/g,"");let r=0,a=0;t.startsWith("-")?(r++,a=1):t.startsWith("+")&&r++;const s=t.substring(r);if(0===s.length){this._initializeState(0n,1===a&&t.startsWith("-")?1:0),this.normSign();return}if(16===i){let e;if("le"===n){const e=[];let t=s;t.length%2!=0&&(t="0"+t);for(let r=0;r<t.length;r+=2){const i=parseInt(t.substring(r,r+2),16);if(isNaN(i))throw Error("Invalid character in "+t);e.push(i)}this.initArray(e,"le"),this._sign=a,this.normSign();return}try{e=BigInt("0x"+s)}catch(e){throw Error("Invalid character in "+s)}this._initializeState(e,a),this.normSign()}else try{if(this._parseBaseString(s,i),this._sign=a,this.normSign(),"le"===n){const e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw Error("Invalid character");throw e}}else 0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0)}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw Error("Base must be between 2 and 36");let r="",i=e>0n?e:-e,n=BigInt(t);for(;i>0n;)r="0123456789abcdefghijklmnopqrstuvwxyz"[Number(i%n)]+r,i/=n;return r}_parseBaseString(e,t){if(0===e.length){this._magnitude=0n,this._finishInitialization();return}this._magnitude=0n;let r=BigInt(t),i=P.groupSizes[t],n=BigInt(P.groupBases[t]);(0===i||0n===n)&&(0===(i=Math.floor(Math.log(0x3ffffff)/Math.log(t)))&&(i=1),n=r**BigInt(i));let a=0,s=e.length,o=s%i;if(0===o&&s>0&&(o=i),o>0){let r=e.substring(a,a+o);this._magnitude=BigInt(this._parseBaseWord(r,t)),a+=o}for(;a<s;){let r=e.substring(a,a+i),s=BigInt(this._parseBaseWord(r,t));this._magnitude=this._magnitude*n+s,a+=i}this._finishInitialization()}_parseBaseWord(e,t){let r=0;for(let i=0;i<e.length;i++){let n,a=e.charCodeAt(i);if(a>=48&&a<=57)n=a-48;else if(a>=65&&a<=90)n=a-65+10;else if(a>=97&&a<=122)n=a-97+10;else throw Error("Invalid character: "+e[i]);if(n>=t)throw Error("Invalid character");r=r*t+n}return r}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{let e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/P.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=P.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),+(e<0)),"le"===t){let e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let r=0n;if("be"===t)for(let t=0;t<e.length;t++)r=r<<8n|BigInt(255&e[t]);else for(let t=e.length-1;t>=0;t--)r=r<<8n|BigInt(255&e[t]);return this._initializeState(r,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){let e=new P(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let r=P.groupSizes[e],i=BigInt(P.groupBases[e]);(0===r||0n===i)&&(0===(r=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)))&&(r=1),i=BigInt(e)**BigInt(r));let n="",a=this._magnitude;for(;a>0n;){let t=a%i;a/=i;let s=this._bigIntToStringInBase(t,e);if(a>0n){let e=r-s.length;n=e>0&&e<P.zeros.length?P.zeros[e]+s+n:e>0?"0".repeat(e)+s+n:s+n}else n=s+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}toNumber(){let e=this._getSignedValue();if(e>P.MAX_SAFE_INTEGER_BIGINT||e<P.MIN_SAFE_INTEGER_BIGINT)throw Error("Number can only safely store up to 53 bits");return Number(e)}toBigInt(){return this._getSignedValue()}toJSON(){let e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let r=this._magnitude,i=t?0:e.length-1,n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===r&&i>=0&&i<e.length)e[i]=0;else if(i>=0&&i<e.length)e[i]=Number(255n&r);else break;r>>=8n,i+=n}}toArray(e="be",t){this.strip();let r=this.byteLength(),i=t??Math.max(1,r);this.assert(r<=i,"byte array longer than desired length"),this.assert(i>0,"Requested array length <= 0");let n=Array(i).fill(0);return 0n===this._magnitude&&i>0?n:0n===this._magnitude&&0===i?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){let t=e.bitLength();if(0===t)return[];let r=Array(t),i=e._magnitude;for(let e=0;e<t;e++)r[e]=+((i>>BigInt(e)&1n)!==0n);return r}toBitArray(){return P.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;(1n&t)===0n&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);let t=BigInt(e),r=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(r=(1n<<t)+r),r&=(1n<<t)-1n;let i=new P(0n);return i._initializeState(r,0),i}fromTwos(e){this.assert(e>=0);let t=BigInt(e),r=this._magnitude;if(e>0&&(r>>t-1n&1n)!==0n&&0===this._sign){let e=new P(0n);return e._setValueFromSigned(r-(1n<<t)),e}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=+(1!==this._sign)),this}_iuop(e,t){let r=t(this._magnitude,e._magnitude),i=t===((e,t)=>e^t),n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,(e,t)=>e|t)}iuand(e){return this._iuop(e,(e,t)=>e&t)}iuxor(e){return this._iuop(e,(e,t)=>e^t)}_iop(e,t){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t)}ior(e){return this._iop(e,(e,t)=>e|t)}iand(e){return this._iop(e,(e,t)=>e&t)}ixor(e){return this._iop(e,(e,t)=>e^t)}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);let t=BigInt(e);this._magnitude=~this._magnitude&(1n<<t)-1n;let r=0===e?1:Math.ceil(e/P.wordSize);return this._nominalWordLength=Math.max(1,r),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,r)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);let r=BigInt(e);1===t||!0===t?this._magnitude|=1n<<r:this._magnitude&=~(1n<<r);let i=Math.floor(e/P.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,i),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){let t=new P(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){let t=new P(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){let t=new P(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=P.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){let e=new P(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new P(1n);let t=new P(1n),r=this.clone(),i=e.clone(),n=r.isNeg(),a=i.isOdd();for(n&&r.ineg();!i.isZero();)i.isOdd()&&t.imul(r),r.isqr(),i.iushrn(1);return n&&a&&t.ineg(),t}static normalizeNonNegativeBigInt(e,t){if("number"==typeof e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return BigInt(e)}if(e<0n)throw Error(`${t} must be a non-negative integer`);return e}iushln(e){let t=P.normalizeNonNegativeBigInt(e,"Shift bits");return 0n===t?this:(this._magnitude<<=t,this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,r){let i=P.normalizeNonNegativeBigInt(e,"Shift bits");if(0n===i)return null!=r&&r._initializeState(0n,0),this;if(null!=r){let e=this._magnitude&(1n<<i)-1n;r._initializeState(e,0)}return this._magnitude>>=i,this._finishInitialization(),this.strip()}ishrn(e,t,r){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,r)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),(this._magnitude>>BigInt(e)&1n)!==0n}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");let t=BigInt(e);this._magnitude&=0n===t?0n:(1n<<t)-1n;let r=0===e?1:Math.max(1,Math.ceil(e/P.wordSize));return this._nominalWordLength=r,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,r),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=P.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=P.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,r){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){let e=new P(0n);return{div:"mod"!==t?e:null,mod:"div"!==t?e:null}}let i=this._getSignedValue(),n=e._getSignedValue(),a=null,s=null;"mod"!==t&&(a=i/n),"div"!==t&&(s=i%n,!0===r&&s<0n&&(s+=n<0n?-n:n));let o=null!==a?new P(0n):null;null!==o&&null!==a&&o._setValueFromSigned(a);let c=null!==s?new P(0n):null;return null!==c&&null!==s&&c._setValueFromSigned(s),{div:o,mod:c}}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());let t=this._getSignedValue(),r=e._getSignedValue(),i=t/r,n=t%r;if(0n===n){let e=new P(0n);return e._setValueFromSigned(i),e}2n*(n<0n?-n:n)>=(r<0n?-r:r)&&(t>0n&&r>0n||t<0n&&r<0n?i+=1n:i-=1n);let a=new P(0n);return a._setValueFromSigned(i),a}modrn(e){this.assert(0!==e,"Division by zero in modrn");let t=BigInt(Math.abs(e));if(0n===t)throw Error("Division by zero in modrn");let r=this._magnitude%t;return e<0?Number(-r):Number(r)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=P.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),r=e._magnitude,i=1n,n=0n,a=0n,s=1n;for(;0n!==r;){let e=t/r,o=r;r=t%r,t=o,o=n,n=i-e*n,i=o,o=s,s=a-e*s,a=o}let o=new P(0n);o._setValueFromSigned(i);let c=new P(0n);c._setValueFromSigned(a);let l=new P(0n);return l._initializeState(t<0n?-t:t,0),{a:o,b:c,gcd:l}}gcd(e){let t=this._magnitude,r=e._magnitude;if(0n===t){let e=new P(0n);return e._setValueFromSigned(r),e.iabs()}if(0n===r){let e=new P(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==r;){let e=t%r;t=r,r=e}let i=new P(0n);return i._initializeState(t,0),i}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");let t=this.egcd(e);if(!t.gcd.eqn(1))throw Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);let t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=P.MAX_IMULN_ARG,"Number is too big");let t=this._getSignedValue(),r=BigInt(e);return t<r?-1:+(t>r)}cmp(e){let t=this._getSignedValue(),r=e._getSignedValue();return t<r?-1:+(t>r)}ucmp(e){return this._magnitude<e._magnitude?-1:+(this._magnitude>e._magnitude)}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return -1===this.cmpn(e)}lt(e){return -1===this.cmp(e)}lten(e){return 0>=this.cmpn(e)}lte(e){return 0>=this.cmp(e)}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let r="be";return("little"===t||"le"===t)&&(r="le"),new P(e,16,r)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);let r=2*e;for(;t.length<r;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new P(e,16)}static fromNumber(e){return new P(e)}static fromString(e,t){return new P(e,t)}static fromSm(e,t="big"){if(0===e.length)return new P(0n);let r=e.slice();"little"===t&&r.reverse();let i=0;r.length>0&&(128&r[0])!=0&&(i=1,r[0]&=127);let n=0n;if(x){let e=S.from(r).toString("hex");n=0===e.length?0n:BigInt("0x"+e)}else{let e="";for(let t of r)e+=t<16?"0"+t.toString(16):t.toString(16);n=0===e.length?0n:BigInt("0x"+e)}let a=new P(0n);return a._initializeState(n,i),a}toSm(e="big"){let t;if(0n===this._magnitude)return 1===this._sign?[128]:[];let r=this._getMinimalHex();r.length%2!=0&&(r="0"+r);let i=Array(r.length/2);for(let e=0,t=0;e<r.length;e+=2){let n=E[r.charCodeAt(e)],a=E[r.charCodeAt(e+1)];i[t++]=(15&n)<<4|15&a}return 1===this._sign?(128&i[0])!=0?t=[128,...i]:(t=i.slice(),t[0]|=128):t=(128&i[0])!=0?[0,...i]:i.slice(),"little"===e?t.reverse():t}static fromBits(e,t=!1){let r=e>>>24,i=8388607&e,n=(8388608&e)!=0;if(t&&n)throw Error("negative bit set");if(0===r&&0===i){if(n&&t)throw Error("negative bit set for zero value");return new P(0n)}let a=new P(i);return r<=3?a.iushrn((3-r)*8):a.iushln((r-3)*8),n&&a.ineg(),a}toBits(){let e;if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),r=this.abs(),i=r.toArray("be"),n=0;for(;n<i.length-1&&0===i[n];)n++;let a=(i=i.slice(n)).length;if(0!==a||r.isZero()||(i=[0],a=1),r.isZero()&&(a=0,i=[]),0===a)e=0;else if(a<=3){e=0;for(let t=0;t<a;t++)e=e<<8|i[t]}else e=i[0]<<16|i[1]<<8|i[2];(8388608&e)!=0&&a<=255&&(e>>>=8,a++);let s=a<<24|e;return t&&(s|=8388608),s>>>0}static fromScriptNum(e,t=!1,r){if(void 0!==r&&e.length>r)throw Error("script number overflow");if(0===e.length)return new P(0n);if(t&&(127&e[e.length-1])==0&&(e.length<=1||(128&e[e.length-2])==0))throw Error("non-minimally encoded script number");return P.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){let t;this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let r=this.umod(e)._magnitude,i=e._magnitude,n=1n,a=0n,s=e._magnitude;for(;r>1n&&i>1n;){let e=0;for(;(r>>BigInt(e)&1n)===0n;)e++;if(e>0){r>>=BigInt(e);for(let t=0;t<e;++t)(1n&n)!==0n&&(n+=s),n>>=1n}let t=0;for(;(i>>BigInt(t)&1n)===0n;)t++;if(t>0){i>>=BigInt(t);for(let e=0;e<t;++e)(1n&a)!==0n&&(a+=s),a>>=1n}r>=i?(r-=i,n-=a):(i-=r,a-=n)}if(1n===r)t=n;else if(1n===i)t=a;else if(0n===r&&1n===i)t=a;else if(0n===i&&1n===r)t=n;else throw Error("_invmp: GCD is not 1, inverse does not exist. aVal="+r+", bVal="+i);(t%=s)<0n&&(t+=s);let o=new P(0n);return o._initializeState(t,0),o}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class N{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new P(t,16),this.n=this.p.bitLength(),this.k=new P(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let e=new P(BigInt(0)),t=Math.ceil(this.n/P.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){let t;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),t=e.bitLength();while(t>this.n);let r=t<this.n?-1:e.ucmp(this.p);return 0===r?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class O extends N{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){let r=e.words,i=e.length,n=Math.min(i,9),a=Array(n+ +(i>9)).fill(0);for(let e=0;e<n;e++)a[e]=r[e];let s=n;if(i<=9){let r=Array(s);for(let e=0;e<s;++e)r[e]=a[e];t.words=r,e.words=[0];return}let o=r[9];a[s++]=4194303&o;let c=Array(s);for(let e=0;e<s;++e)c[e]=a[e];t.words=c;let l=Array(Math.max(1,i-9)).fill(0),h=0;for(let e=10;e<i;e++){let t=0|r[e];h<l.length&&(l[h++]=(4194303&t)<<4|o>>>22),o=t}o>>>=22,h<l.length?l[h++]=o:0!==o&&l.length;let u=Array(h);for(let e=0;e<h;++e)u[e]=l[e];e.words=u}imulK(e){let t=e.words,r=e.length,i=r+2,n=Array(i).fill(0);for(let e=0;e<r;e++)n[e]=t[e];let a=0;for(let e=0;e<i;e++){let t=0|n[e];a+=977*t,n[e]=0x3ffffff&a,a=64*t+(a/0x4000000|0)}return e.words=n,e}}class A{prime;m;constructor(e){if("k256"===e){const e=new O;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert((e.negative|t.negative)==0,"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(P.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);let r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(e,t){this.verify2(e,t);let r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(e,t){this.verify2(e,t);let r=e.sub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r.forceRed(this)}isub(e,t){this.verify2(e,t);let r=e.isub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();let t=this.m.andln(3);if(this.assert(t%2==1),3===t){let t=this.m.add(new P(1)).iushrn(2);return this.pow(e,t)}let r=this.m.subn(1),i=0;for(;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);this.assert(!r.isZero());let n=new P(1).toRed(this),a=n.redNeg(),s=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new P(2*o*o).toRed(this);for(;0!==this.pow(c,s).cmp(a);)c.redIAdd(a);let l=this.pow(c,r),h=this.pow(e,r.addn(1).iushrn(1)),u=this.pow(e,r),d=i;for(;0!==u.cmp(n);){let e=u,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<d);let r=this.pow(l,new P(1).iushln(d-t-1));h=h.redMul(r),l=r.redSqr(),u=u.redMul(l),d=t}return h}invm(e){let t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(t.isZero())return new P(1).toRed(this);if(0===t.cmpn(1))return e.clone();let r=Array(16);r[0]=new P(1).toRed(this),r[1]=e;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],e);let n=r[0],a=0,s=0,o=t.bitLength()%26;for(0===o&&(o=26),i=t.length-1;i>=0;i--){let e=t.words[i];for(let t=o-1;t>=0;t--){let o=e>>t&1;if(n!==r[0]&&(n=this.sqr(n)),0===o&&0===a){s=0;continue}a<<=1,a|=o,(4==++s||0===i&&0===t)&&(n=this.mul(n,r[a]),s=0,a=0)}o=26}return n}convertTo(e){let t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){let t=e.clone();return t.red=null,t}}class _ extends A{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new P(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;let r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):0>n.cmpn(0)&&(a=n.iadd(this.m)),a.forceRed(this)}mul(e,t){if(e.isZero()||t.isZero())return new P(0).forceRed(this);let r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):0>n.cmpn(0)&&(a=n.iadd(this.m)),a.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class T{curve;type;precomputed;constructor(e){this.curve=new tU,this.type=e,this.precomputed=null}}class C extends T{x;y;z;zOne;constructor(e,t,r){super("jacobian"),null===e&&null===t&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new P(0)):(P.isBN(e)||(e=new P(e,16)),this.x=e,P.isBN(t)||(t=new P(t,16)),this.y=t,P.isBN(r)||(r=new P(r,16)),this.z=r),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new P(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new tD(null,null);let e=this.z.redInvm(),t=e.redSqr();return new tD(this.x.redMul(t),this.y.redMul(t).redMul(e))}neg(){return new C(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))if(0!==c.cmpn(0))return new C(null,null,null);else return this.dbl();let l=o.redSqr(),h=l.redMul(o),u=i.redMul(l),d=c.redSqr().redIAdd(h).redISub(u).redISub(u),f=c.redMul(u.redISub(d)).redISub(a.redMul(h));return new C(d,f,this.z.redMul(e.z).redMul(o))}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw Error("Point coordinates cannot be null");let t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))if(0!==o.cmpn(0))return new C(null,null,null);else return this.dbl();let c=s.redSqr(),l=c.redMul(s),h=r.redMul(c),u=o.redSqr().redIAdd(l).redISub(h).redISub(h),d=o.redMul(h.redISub(u)).redISub(n.redMul(l));return new C(u,d,this.z.redMul(s))}dblp(e){if(0===e||this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}dbl(){let e,t,r;if(this.isInfinity())return this;if(this.zOne){let i=this.x.redSqr(),n=this.y.redSqr(),a=n.redSqr(),s=this.x.redAdd(n).redSqr().redISub(i).redISub(a);s=s.redIAdd(s);let o=i.redAdd(i).redIAdd(i),c=o.redSqr().redISub(s).redISub(s),l=a.redIAdd(a);l=(l=l.redIAdd(l)).redIAdd(l),e=c,t=o.redMul(s.redISub(c)).redISub(l),r=this.y.redAdd(this.y)}else{let i=this.x.redSqr(),n=this.y.redSqr(),a=n.redSqr(),s=this.x.redAdd(n).redSqr().redISub(i).redISub(a);s=s.redIAdd(s);let o=i.redAdd(i).redIAdd(i),c=o.redSqr(),l=a.redIAdd(a);l=(l=l.redIAdd(l)).redIAdd(l),e=c.redISub(s).redISub(s),t=o.redMul(s.redISub(e)).redISub(l),r=(r=this.y.redMul(this.z)).redIAdd(r)}return new C(e,t,r)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e||this.isInfinity()&&e.isInfinity())return!0;if(this.isInfinity()!==e.isInfinity())return!1;let t=this.z.redSqr(),r=e.z.redSqr();if(0!==this.x.redMul(r).redISub(e.x.redMul(t)).cmpn(0))return!1;let i=t.redMul(this.z),n=r.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(i)).cmpn(0)}eqXToP(e){let t=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(r))return!0;let i=e.clone();if(null===this.curve||null==this.curve.redN)throw Error("Curve or redN is not initialized.");let n=this.curve.redN.redMul(t);for(;0>i.cmp(this.curve.p)&&(i.iadd(this.curve.n),!(i.cmp(this.curve.p)>=0));)if(r.redIAdd(n),0===this.x.cmp(r))return!0;return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}let R=/^[0-9a-fA-F]*$/;function B(e){if("string"!=typeof e)throw TypeError("Invalid hex string");if(0!==e.length&&!R.test(e))throw Error("Invalid hex string")}let V=(e,t="Hash assertion failed")=>{if(!e)throw Error(t)};class D{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw Error("Not implemented")}_digest(){throw Error("Not implemented")}_digestHex(){throw Error("Not implemented")}update(e,t){if(e=U(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){let t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,r,i){let n=r-0;V(n%4==0);let a=Array(n/4);for(let t=0,r=0;t<a.length;t++,r+=4){let n;n="big"===i?e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]:e[r+3]<<24|e[r+2]<<16|e[r+1]<<8|e[r],a[t]=n>>>0}return a}(e,0,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),V(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),V(null===this.pending),this._digestHex()}_pad(){let e,t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw Error("Message too long for this hash function");let r=this._delta8,i=r-(t+this.padLength)%r,n=Array(i+this.padLength);for(e=1,n[0]=128;e<i;e++)n[e]=0;let a=this.padLength,s=1n<<BigInt(8*a),o=8n*BigInt(t);if(o>=s)throw Error("Message too long for this hash function");if("big"===this.endian){let t=Array(a);for(let e=a-1;e>=0;e--)t[e]=Number(255n&o),o>>=8n;for(let r=0;r<a;r++)n[e++]=t[r]}else for(let t=0;t<a;t++)n[e++]=Number(255n&o),o>>=8n;return n}}function U(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];let r=[];if("string"==typeof e)if("hex"!==t){let t=0;for(let a=0;a<e.length;a++){let s=e.charCodeAt(a);if(s<128)r[t++]=s;else if(s<2048)r[t++]=s>>6|192,r[t++]=63&s|128;else{var i,n;(i=e,n=a,(64512&i.charCodeAt(n))!=55296||n<0||n+1>=i.length?1:(64512&i.charCodeAt(n+1))!=56320)?r[t++]=s>>12|224:(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++a)),r[t++]=s>>18|240,r[t++]=s>>12&63|128),r[t++]=s>>6&63|128,r[t++]=63&s|128}}}else{B(e),e=function(e){if(B(e),0===e.length)return"";let t=e.toLowerCase();return t.length%2!=0&&(t="0"+t),t}(e);for(let t=0;t<e.length;t+=2)r.push(parseInt(e[t]+e[t+1],16))}else for(let t=0;t<e.length;t++)r[t]=0|e[t];return r}function F(e){return e0(e)}function L(e,t){let r="";for(let i=0;i<e.length;i++){let n=e[i];"little"===t&&(n=e0(n)),r+=function(e){if(7===e.length)return"0"+e;if(6===e.length)return"00"+e;if(5===e.length)return"000"+e;if(4===e.length)return"0000"+e;if(3===e.length)return"00000"+e;else if(2===e.length)return"000000"+e;else if(1===e.length)return"0000000"+e;else return e}(n.toString(16))}return r}function K(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function H(e,t){let r=Array(4*e.length);for(let i=0,n=0;i<e.length;i++,n+=4){let a=e[i];"big"===t?(r[n]=a>>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r}function q(e,t){return e>>>t|e<<32-t}function M(e,t){return e<<t|e>>>32-t}function $(e,t){return e+t>>>0}let z=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],W=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],j=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],X=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function G(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}class Y extends D{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.endian="little"}_update(e,t){var r,i,n,a,s,o;let c,l=this.h[0],h=this.h[1],u=this.h[2],d=this.h[3],f=this.h[4],p=l,g=h,b=u,y=d,m=f;for(let w=0;w<80;w++){c=$(M((r=l,i=G(w,h,u,d),r+i+e[z[w]+t]+((s=w)<=15?0:s<=31?0x5a827999:s<=47?0x6ed9eba1:s<=63?0x8f1bbcdc:0xa953fd4e)>>>0),j[w]),f),l=f,f=d,d=M(u,10),u=h,h=c,c=$(M((n=p,a=G(79-w,g,b,y),n+a+e[W[w]+t]+((o=w)<=15?0x50a28be6:o<=31?0x5c4dd124:o<=47?0x6d703ef3:0x7a6d76e9*!!(o<=63))>>>0),X[w]),m),p=m,m=y,y=M(b,10),b=g,g=c}c=this.h[1]+u+y>>>0,this.h[1]=this.h[2]+d+m>>>0,this.h[2]=this.h[3]+f+p>>>0,this.h[3]=this.h[4]+l+g>>>0,this.h[4]=this.h[0]+h+b>>>0,this.h[0]=c}_digest(){return H(this.h,"little")}_digestHex(){return L(this.h,"little")}}class J{h;constructor(){this.h=new eH}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(U(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return K(this.h.digest())}}class Z extends D{h;W;k;constructor(){super(512,160,80,64),this.k=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.W=Array(80)}_update(e,t){let r,i=this.W;for(void 0===t&&(t=0),r=0;r<16;r++)i[r]=e[t+r];for(;r<i.length;r++)i[r]=M(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let n=this.h[0],a=this.h[1],s=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){var l,h,u,d,f,p,g,b,y;let e=~~(r/20),t=(d=M(n,5),l=a,h=s,u=o,f=0===e?(p=l)&h^~p&u:1===e||3===e?l^h^u:2===e?(g=l)&(b=h)^g&(y=u)^b&y:0,d+f+c+i[r]+this.k[e]>>>0);c=o,o=s,s=M(a,30),a=n,n=t}this.h[0]=$(this.h[0],n),this.h[1]=$(this.h[1],a),this.h[2]=$(this.h[2],s),this.h[3]=$(this.h[3],o),this.h[4]=$(this.h[4],c)}_digest(){return H(this.h,"big")}_digestHex(){return L(this.h,"big")}}class Q{h;constructor(){this.h=new eG}update(e,t){let r=Uint8Array.from(U(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return K(this.h.digest())}}class ee{h;blockSize=64;outSize=32;constructor(e){const t=e instanceof Uint8Array?e:Uint8Array.from(U(e,"string"==typeof e?"hex":void 0));this.h=new eJ(eq,t)}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(U(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return K(this.h.digest())}}class et{inner;outer;blockSize=64;constructor(e){let t;for((e=U(e,"hex")).length>this.blockSize&&(e=new Z().update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(t=0,this.inner=new Z().update(e);t<e.length;t++)e[t]^=106;this.outer=new Z().update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class er{h;blockSize=128;outSize=32;constructor(e){const t=e instanceof Uint8Array?e:Uint8Array.from(U(e,"string"==typeof e?"hex":void 0));this.h=new eJ(eY,t)}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(U(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return K(this.h.digest())}}let ei=(e,t)=>new Y().update(e,t).digest(),en=(e,t)=>new Z().update(e,t).digest(),ea=(e,t)=>new J().update(e,t).digest(),es=(e,t)=>new Q().update(e,t).digest(),eo=(e,t)=>{let r=new J().update(e,t).digest();return new J().update(r).digest()},ec=(e,t)=>{let r=new J().update(e,t).digest();return new Y().update(r).digest()},el=(e,t,r)=>new ee(e).update(t,r).digest(),eh=(e,t,r)=>new er(e).update(t,r).digest();function eu(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got ${e}`)}function ed(e,...t){if(!(e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length)){let r=t.join(",");throw Error(`Uint8Array expected of length ${r}, got length=${e.length}`)}}function ef(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");eu(e.outputLen),eu(e.blockLen)}function ep(e,t=!0){if(!0===e.destroyed)throw Error("Hash instance has been destroyed");if(t&&!0===e.finished)throw Error("Hash#digest() has already been called")}function eg(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function eb(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ey(e){return"string"==typeof e&&(e=em(e)),ed(e),e}function em(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ew(e){return"string"==typeof e&&(e=em(e)),ed(e),e}class ev{}function eI(e){let t=t=>e().update(ey(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}let ek=BigInt(0x100000000-1),eS=BigInt(32),ex=(e,t,r)=>e>>>r,eE=(e,t,r)=>e<<32-r|t>>>r,eP=(e,t,r)=>e>>>r|t<<32-r,eN=(e,t,r)=>e<<32-r|t>>>r,eO=(e,t,r)=>e<<64-r|t>>>r-32,eA=(e,t,r)=>e>>>r-32|t<<64-r;function e_(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/0x100000000|0)|0,l:0|n}}let eT=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),eC=(e,t,r,i)=>t+r+i+(e/0x100000000|0)|0,eR=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),eB=(e,t,r,i,n)=>t+r+i+n+(e/0x100000000|0)|0,eV=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),eD=(e,t,r,i,n,a)=>t+r+i+n+a+(e/0x100000000|0)|0;class eU extends ev{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=eb(this.buffer)}update(e){ep(this),ed(e=ey(e));let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let a=0;a<n;){let s=Math.min(i-this.pos,n-a);if(s===i){let t=eb(e);for(;i<=n-a;a+=i)this.process(t,a);continue}r.set(e.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ep(this);ed(e);let t=this.outputLen;if(e.length<t)throw Error(`digestInto() expects output buffer of length at least ${t}`);this.finished=!0;let{buffer:r,view:i,blockLen:n,isLE:a}=this,{pos:s}=this;r[s++]=128,eg(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(i,0),s=0);for(let e=s;e<n;e++)r[e]=0;(function(e,t,r,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,i);let n=BigInt(32),a=BigInt(0xffffffff),s=Number(r>>n&a),o=Number(r&a),c=4*!!i,l=4*!i;e.setUint32(t+c,s,i),e.setUint32(t+l,o,i)})(i,n-8,BigInt(8*this.length),a),this.process(i,0);let o=eb(e),c=this.outputLen;if(c%4!=0)throw Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,h=this.get();if(l>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)o.setUint32(4*e,h[e],a)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:r,length:i,finished:n,destroyed:a,pos:s}=this;return e.destroyed=a,e.finished=n,e.length=i,e.pos=s,i%t!=0&&e.buffer.set(r),e}clone(){return this._cloneInto()}}let eF=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),eL=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),eK=new Uint32Array(64);class eH extends eU{A=0|eF[0];B=0|eF[1];C=0|eF[2];D=0|eF[3];E=0|eF[4];F=0|eF[5];G=0|eF[6];H=0|eF[7];constructor(e=32){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:a,G:s,H:o}=this;return[e,t,r,i,n,a,s,o]}set(e,t,r,i,n,a,s,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|i,this.E=0|n,this.F=0|a,this.G=0|s,this.H=0|o}process(e,t){var r,i,n,a,s,o,c,l,h;for(let r=0;r<16;r++,t+=4)eK[r]=e.getUint32(t);for(let e=16;e<64;e++){let t=eK[e-15],r=eK[e-2],i=q(t,7)^q(t,18)^t>>>3,n=q(r,17)^q(r,19)^r>>>10;eK[e]=$($(i,eK[e-7]),$(n,eK[e-16]))}let{A:u,B:d,C:f,D:p,E:g,F:b,G:y,H:m}=this;for(let e=0;e<64;e++){let t=(n=m,a=q(r=g,6)^q(r,11)^q(r,25),s=(i=g)&b^~i&y,n+a+s+eL[e]+eK[e]>>>0),w=$(q(o=u,2)^q(o,13)^q(o,22),(c=u)&(l=d)^c&(h=f)^l&h);m=y,y=b,b=g,g=$(p,t),p=f,f=d,d=u,u=$(t,w)}this.A=$(this.A,u),this.B=$(this.B,d),this.C=$(this.C,f),this.D=$(this.D,p),this.E=$(this.E,g),this.F=$(this.F,b),this.G=$(this.G,y),this.H=$(this.H,m)}roundClean(){eg(eK)}destroy(){eg(this.buffer),this.set(0,0,0,0,0,0,0,0)}}let eq=eI(()=>new eH),eM=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),e$=function(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let a=0;a<r;a++){let{h:r,l:s}=function(e,t=!1){return t?{h:Number(e&ek),l:Number(e>>eS&ek)}:{h:0|Number(e>>eS&ek),l:0|Number(e&ek)}}(e[a],t);i[a]=r,n[a]=s}return[i,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),ez=e$[0],eW=e$[1],ej=new Uint32Array(80),eX=new Uint32Array(80);class eG extends eU{Ah=0|eM[0];Al=0|eM[1];Bh=0|eM[2];Bl=0|eM[3];Ch=0|eM[4];Cl=0|eM[5];Dh=0|eM[6];Dl=0|eM[7];Eh=0|eM[8];El=0|eM[9];Fh=0|eM[10];Fl=0|eM[11];Gh=0|eM[12];Gl=0|eM[13];Hh=0|eM[14];Hl=0|eM[15];constructor(e=64){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:a,Dh:s,Dl:o,Eh:c,El:l,Fh:h,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,r,i,n,a,s,o,c,l,h,u,d,f,p,g]}set(e,t,r,i,n,a,s,o,c,l,h,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|i,this.Ch=0|n,this.Cl=0|a,this.Dh=0|s,this.Dl=0|o,this.Eh=0|c,this.El=0|l,this.Fh=0|h,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)ej[r]=e.getUint32(t),eX[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|ej[e-15],r=0|eX[e-15],i=eP(t,r,1)^eP(t,r,8)^ex(t,r,7),n=eN(t,r,1)^eN(t,r,8)^eE(t,r,7),a=0|ej[e-2],s=0|eX[e-2],o=eP(a,s,19)^eO(a,s,61)^ex(a,s,6),c=eR(n,eN(a,s,19)^eA(a,s,61)^eE(a,s,6),eX[e-7],eX[e-16]),l=eB(c,i,o,ej[e-7],ej[e-16]);ej[e]=0|l,eX[e]=0|c}let{Ah:r,Al:i,Bh:n,Bl:a,Ch:s,Cl:o,Dh:c,Dl:l,Eh:h,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:b,Hl:y}=this;for(let e=0;e<80;e++){let t=eP(h,u,14)^eP(h,u,18)^eO(h,u,41),m=eN(h,u,14)^eN(h,u,18)^eA(h,u,41),w=h&d^~h&p,v=eV(y,m,u&f^~u&g,eW[e],eX[e]),I=eD(v,b,t,w,ez[e],ej[e]),k=0|v,S=eP(r,i,28)^eO(r,i,34)^eO(r,i,39),x=eN(r,i,28)^eA(r,i,34)^eA(r,i,39),E=r&n^r&s^n&s,P=i&a^i&o^a&o;b=0|p,y=0|g,p=0|d,g=0|f,d=0|h,f=0|u,({h:h,l:u}=e_(0|c,0|l,0|I,0|k)),c=0|s,l=0|o,s=0|n,o=0|a,n=0|r,a=0|i;let N=eT(x,P,k);r=eC(N,S,E,I),i=0|N}({h:r,l:i}=e_(r,i,this.Ah,this.Al)),({h:n,l:a}=e_(n,a,this.Bh,this.Bl)),({h:s,l:o}=e_(s,o,this.Ch,this.Cl)),({h:c,l:l}=e_(c,l,this.Dh,this.Dl)),({h:h,l:u}=e_(h,u,this.Eh,this.El)),({h:d,l:f}=e_(d,f,this.Fh,this.Fl)),({h:p,l:g}=e_(p,g,this.Gh,this.Gl)),({h:b,l:y}=e_(b,y,this.Hh,this.Hl)),this.set(r,i,n,a,s,o,c,l,h,u,d,f,p,g,b,y)}roundClean(){eg(ej,eX)}destroy(){eg(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let eY=eI(()=>new eG);class eJ extends ev{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){super(),ef(e);const r=ey(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?e.create().update(r).digest():r);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),eg(n)}update(e){return ep(this),this.iHash.update(e),this}digestInto(e){ep(this),ed(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:i,destroyed:n,blockLen:a,outputLen:s}=this;return e.finished=i,e.destroyed=n,e.blockLen=a,e.outputLen=s,e.oHash=t._cloneInto(e.oHash??void 0),e.iHash=r._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let eZ=(e,t,r)=>new eJ(e,t).update(r).digest();function eQ(e,t,r,i,n="sha512"){if("sha512"!==n)throw Error("Only sha512 is supported in this PBKDF2 implementation");try{let a=require("crypto");if("function"==typeof a.pbkdf2Sync){let s=Buffer.from(e),o=Buffer.from(t);return[...a.pbkdf2Sync(s,o,r,i,n)]}}catch{}return Array.from(function(e,t,r,i){let n;ef(e);let{c:a,dkLen:s}=Object.assign({dkLen:32},i);if(eu(a),eu(s),a<1)throw Error("iterations (c) should be >= 1");let o=ew(t),c=ew(r),l=new Uint8Array(s),h=eZ.create(e,o),u=h._cloneInto().update(c),d=new Uint8Array(4),f=eb(d),p=new Uint8Array(h.outputLen);for(let e=1,t=0;t<s;e++,t+=h.outputLen){let r=l.subarray(t,t+h.outputLen);f.setInt32(0,e,!1),(n=u._cloneInto(n)).update(d).digestInto(p),r.set(p.subarray(0,r.length));for(let e=1;e<a;e++){h._cloneInto(n).update(p).digestInto(p);for(let e=0;e<r.length;e++)r[e]^=p[e]}}return h.destroy(),u.destroy(),null!=n&&n.destroy(),eg(p),l}(eY,Uint8Array.from(e),Uint8Array.from(t),{c:r,dkLen:i}))}function e0(e){return(e>>>24|e>>>8&65280|e<<8&0xff0000|(255&e)<<24)>>>0}eZ.create=(e,t)=>new eJ(e,t);let e1=(r=new Uint32Array(t=new ArrayBuffer(4)),i=new Uint8Array(t),r[0]=0x1020304,4===i[0]);function e2(e){return e1?e0(e):e>>>0}let e8="undefined"!=typeof globalThis?globalThis.Buffer:void 0,e3=null!=e8&&"function"==typeof e8.from,e6=e=>e.length%2==1?"0"+e:e,e4="0123456789abcdef",e5=Array(256);for(let e=0;e<256;e++)e5[e]=e4[e>>4&15]+e4[15&e];let e7=e=>{if(e3)return e8.from(e).toString("hex");if(0===e.length)return"";let t=Array(e.length);for(let r=0;r<e.length;r++)t[r]=e5[255&e[r]];return t.join("")},e9=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,e=>0|e);switch(t){case"hex":return tt(e);case"base64":return tr(e);default:var r=e;let i=[];for(let e=0;e<r.length;e++){let t=r.codePointAt(e);if(void 0===t)throw Error(`Index out of range: ${e}`);let n=t;n>65535?e++:n>=55296&&n<=57343&&(n=65533),n<=127?i.push(n):n<=2047?i.push(192|n>>6,128|63&n):n<=65535?i.push(224|n>>12,128|n>>6&63,128|63&n):i.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}return i}},te=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)te[48+e]=e;for(let e=0;e<6;e++)te[65+e]=10+e,te[97+e]=10+e;let tt=e=>{B(e);let t=e.length%2==0?e:"0"+e;if(e3)return Array.from(e8.from(t,"hex"));let r=Array(t.length/2),i=0;for(let e=0;e<t.length;e+=2){let n=te[t.charCodeAt(e)],a=te[t.charCodeAt(e+1)];r[i++]=n<<4|a}return r};function tr(e){if("string"!=typeof e)throw TypeError("msg must be a string");let t=e.trim().replace(/[\r\n\t\f\v ]+/g,""),r=(t=t.replace(/-/g,"+").replace(/_/g,"/")).indexOf("=");if(-1!==r){let e=t.slice(r);if(!/^={1,2}$/.test(e)||t.slice(0,r).includes("="))throw Error("Invalid base64 padding");t=t.slice(0,r)}let i=[],n=0,a=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e),s=-1;if(r>=65&&r<=90)s=r-65;else if(r>=97&&r<=122)s=r-97+26;else if(r>=48&&r<=57)s=r-48+52;else if(43===r)s=62;else if(47===r)s=63;else throw Error(`Invalid base64 character at index ${e}`);for(n=n<<6|s,a+=6;a>=8;)a-=8,i.push(n>>a&255),n&=(1<<a)-1}return i}let ti=e=>{let t="";for(let r=0;r<e.length;r++){let i=e[r];if(i<=127){t+=String.fromCharCode(i);continue}let n=()=>{t+="�"};if(i>=192&&i<=223){if(r+1>=e.length){n();continue}let a=e[r+1];if((192&a)!=128){n(),r+=1;continue}t+=String.fromCharCode((31&i)<<6|63&a),r+=1;continue}if(i>=224&&i<=239){if(r+2>=e.length){n();continue}let a=e[r+1],s=e[r+2];if((192&a)!=128||(192&s)!=128){n(),r+=2;continue}t+=String.fromCharCode((15&i)<<12|(63&a)<<6|63&s),r+=2;continue}if(i>=240&&i<=247){if(r+3>=e.length){n();continue}let a=e[r+1],s=e[r+2],o=e[r+3];if((192&a)!=128||(192&s)!=128||(192&o)!=128){n(),r+=3;continue}let c=((7&i)<<18|(63&a)<<12|(63&s)<<6|63&o)-65536;t+=String.fromCharCode(55296+(c>>10),56320+(1023&c)),r+=3;continue}n()}return t},tn=(e,t)=>{switch(t){case"hex":return e7(e);case"utf8":return ti(e);default:return e}};function ta(e){let t,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="";for(t=0;t<e.length;t+=3){let n=e[t],a=t+1<e.length?e[t+1]:0,s=t+2<e.length?e[t+2]:0,o=n>>2,c=(3&n)<<4|a>>4,l=(15&a)<<2|s>>6,h=63&s;i+=r.charAt(o)+r.charAt(c),i+=t+1<e.length?r.charAt(l):"=",i+=t+2<e.length?r.charAt(h):"="}return i}let ts="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",to=e=>{let t;if(""===e||"string"!=typeof e)throw Error(`Expected base58 string but got “${e}”`);let r=e.match(/[IOl0]/gmu);if(null!==r)throw Error(`Invalid base58 character “${r.join("")}”`);let i=e.match(/^1+/gmu),n=null!==i?i[0].length:0,a=(e.length-n)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(n),...(e.match(/./gmu)??[]).map(e=>ts.indexOf(e)).reduce((e,t)=>e=e.map(e=>{let r=58*e+t;return t=r>>8,r}),new Uint8Array(a)).reverse().filter((t=!1,e=>t=t||e))])]},tc=e=>{let t=Array(256).fill(-1);for(let e=0;e<ts.length;++e)t[ts.charCodeAt(e)]=e;let r=[];for(let i of e){let e=i;for(let i=0;i<r.length;++i){let n=(t[r[i]]<<8)+e;r[i]=ts.charCodeAt(n%58),e=n/58|0}for(;0!==e;)r.push(ts.charCodeAt(e%58)),e=e/58|0}for(let t of e)if(0!==t)break;else r.push(49);return r.reverse(),String.fromCharCode(...r)},tl=(e,t=[0])=>{let r=eo([...t,...e]);return tc(r=[...t,...e,...r.slice(0,4)])},th=(e,t,r=1)=>{let i=to(e),n=i.slice(0,r),a=i.slice(r,-4),s=[...n,...a];return s=eo(s),i.slice(-4).forEach((e,t)=>{if(e!==s[t])throw Error("Invalid checksum")}),"hex"===t&&(n=e7(n),a=e7(a)),{prefix:n,data:a}};class tu{bufs;length;constructor(e){for(const t of(this.bufs=void 0!==e?e:[],this.length=0,this.bufs))this.length+=t.length}getLength(){return this.length}toUint8Array(){let e=new Uint8Array(this.length),t=0;for(let r of this.bufs)e.set(r,t),t+=r.length;return e}toArray(){let e=Array(this.length),t=0;for(let r of this.bufs)if(r instanceof Uint8Array)for(let i=0;i<r.length;i++)e[t++]=r[i];else for(let i=0;i<r.length;i++)e[t++]=r[i];return e}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){let t=Array(e.length);for(let r=0;r<t.length;r++)t[r]=e[e.length-1-r];return this.write(t)}writeUInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeUInt16BE(e){return this.write([e>>8&255,255&e])}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){return this.write([255&e,e>>8&255])}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){return this.write([e>>24&255,e>>16&255,e>>8&255,255&e])}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){return this.write([255&e,e>>8&255,e>>16&255,e>>24&255])}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){let t=new P(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){let t=tu.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=tu.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<0)return this.varIntBn(new P(e));if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<0x100000000)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{let r=0|e,i=0|Math.floor(e/0x100000000);t=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return t}static varIntBn(e){let t;if(e.isNeg()&&(e=e.add(tg)),e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){let r=e.toNumber();t=[253,255&r,r>>8&255]}else if(e.lt(new P(0x100000000))){let r=e.toNumber();t=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{let r=new tu;r.writeUInt8(255),r.writeUInt64LEBn(e),t=r.toArray()}return t}}class td{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,r=this.pos+e;return this.pos=r,this.bin.slice(t,r)}readReverse(e=this.length){let t=Array(e);for(let r=0;r<e;r++)t[r]=this.bin[this.pos+e-1-r];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)!=0?e-256:e}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)!=0?e-65536:e}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)!=0?e-65536:e}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)!=0?e-0x100000000:e}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)!=0?e-0x100000000:e}readUInt64BEBn(){let e=new P(this.bin.slice(this.pos,this.pos+8));return this.pos=this.pos+8,e}readUInt64LEBn(){return new P(this.readReverse(8))}readInt64LEBn(){let e=new P(this.readReverse(8));return e.gte(tp)&&(e=e.sub(tg)),e}readVarIntNum(e=!0){let t,r=this.readUInt8();switch(r){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new P(2).pow(new P(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return r}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new P(this.readUInt16LE());case 254:return new P(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new P(e)}}}let tf=e=>{if(0===e.length)return e;let t=e[e.length-1];if((127&t)!=0)return e;if(1===e.length)return[];if((128&e[e.length-2])!=0)return e;for(let r=e.length-1;r>0;r--)if(0!==e[r-1])if((128&e[r-1])!=0)return e[r]=t,e.slice(0,r+1);else return e[r-1]|=t,e.slice(0,r);return[]},tp=new P(2).pow(new P(63)),tg=new P(2).pow(new P(64));function tb(e,t="Expected a valid value, but got undefined or null."){if(null==e)throw Error(t);return e}function ty(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}function tm(e,t,r){let i=-e,n=(t.X^r.X)&i,a=(t.Y^r.Y)&i,s=(t.Z^r.Z)&i;t.X^=n,r.X^=n,t.Y^=a,r.Y^=a,t.Z^=s,r.Z^=s}let tw=(1n<<256n)-1n;function tv(e){let t=e>>256n;return t=(e=(e&tw)+(t<<32n)+977n*t)>>256n,(e=(e&tw)+(t<<32n)+977n*t)>=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn&&(e-=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),e}let tI=e=>tv((e%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn)%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),tk=(e,t)=>e>=t?e-t:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-(t-e),tS=(e,t)=>tv(e*t),tx=e=>{let t=1n,r=0n,i=tI(e),n=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;for(;i>1n;){let e=n/i;[t,r]=[r-t*e,t],[i,n]=[n-i*e,i]}return tI(t)},tE=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+1n>>2n,tP=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),tN=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),tO=new Map,tA=e=>{let{X:t,Y:r,Z:i}=e;if(0n===r)return{X:0n,Y:1n,Z:0n};let n=tS(r,r),a=tS(4n,tS(t,n)),s=tS(3n,tS(t,t)),o=tk(tS(s,s),tS(2n,a)),c=tk(tS(s,tk(a,o)),tS(8n,tS(n,n)));return{X:o,Y:c,Z:tS(2n,tS(r,i))}},t_=(e,t)=>{if(0n===e.Z)return t;if(0n===t.Z)return e;let r=tS(e.Z,e.Z),i=tS(t.Z,t.Z),n=tS(e.X,i),a=tS(t.X,r),s=tS(e.Y,tS(i,t.Z)),o=tS(t.Y,tS(r,e.Z)),c=tk(a,n),l=tk(o,s);if(0n===c)return 0n===l?tA(e):{X:0n,Y:1n,Z:0n};let h=tS(c,c),u=tS(c,h),d=tS(n,h),f=tk(tk(tS(l,l),u),tS(2n,d)),p=tk(tS(l,tk(d,f)),tS(s,u));return{X:f,Y:p,Z:tS(c,tS(e.Z,t.Z))}},tT=e=>0n===e.Z?e:{X:e.X,Y:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-e.Y,Z:e.Z},tC=(e,t,r=5)=>{let i,n=`${r}:${t.x.toString(16)}:${t.y.toString(16)}`,a=tO.get(n);if(void 0===a){let e=1<<r-1;a=Array(e),i={X:t.x,Y:t.y,Z:1n},a[0]=i;let s=tA(i);for(let t=1;t<e;t++)a[t]=t_(a[t-1],s);tO.set(n,a)}else i=a[0];let s=[],o=1n<<BigInt(r),c=o>>1n,l=e;for(;l>0n;)if((1n&l)===0n)s.push(0),l>>=1n;else{let e=l&o-1n;e>c&&(e-=o),s.push(Number(e)),l-=e,l>>=1n}let h={X:0n,Y:1n,Z:0n};for(let e=s.length-1;e>=0;e--){h=tA(h);let t=s[e];if(0!==t){let e=Math.abs(t)>>1;h=t_(h,t>0?a[e]:tT(a[e]))}}return h},tR=e=>{let t=e%0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;return t<0n&&(t+=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n),t},tB=(e,t)=>tR(e*t),tV=e=>{let t=1n,r=0n,i=tR(e),n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;for(;i>1n;){let e=n/i;[t,r]=[r-t*e,t],[i,n]=[n-i*e,i]}return tR(t)};class tD extends T{x;y;inf;static _assertOnCurve(e){if(!e.validate())throw Error("Invalid point");return e}static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e[e.length-1]%2!=0)throw Error("Point string value is wrong length")}else if(7===e[0]&&e[e.length-1]%2!=1)throw Error("Point string value is wrong length");let t=new tD(e.slice(1,33),e.slice(33,65));return tD._assertOnCurve(t)}if((2===e[0]||3===e[0])&&e.length-1==32)return tD._assertOnCurve(tD.fromX(e.slice(1,33),3===e[0]));throw Error("Unknown point format")}static fromString(e){let t=e9(e,"hex");return tD._assertOnCurve(tD.fromDER(t))}static fromX(e,t){var r;let i,n,a=P.isBN(e)?BigInt("0x"+e.toString(16)):"string"==typeof e?BigInt("0x"+e):Array.isArray(e)?BigInt("0x"+e7(e)):BigInt(e),s=(n=((e,t)=>{let r=1n;for(e=tI(e);t>0n;)(1n&t)!==0n&&(r=tS(r,e)),e=tS(e,e),t>>=1n;return r})(r=tv(tS(tS(i=a=tI(a),i),a)+7n),tE),tS(n,n)!==tI(r)?null:n);if(null===s)throw Error("Invalid point");let o=s;(1n&o)!==(t?1n:0n)&&(o=tk(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,o));let c=new P(a.toString(16),16),l=new P(o.toString(16),16);return tD._assertOnCurve(new tD(c,l))}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));let r=new tD(e[0],e[1],t);if(r=tD._assertOnCurve(r),"object"!=typeof e[2]||null===e[2])return r;let i=e[2],n=e=>{let r=new tD(e[0],e[1],t);return tD._assertOnCurve(r)};return r.precomputed={beta:null,doubles:"object"==typeof i.doubles&&null!==i.doubles?{step:i.doubles.step,points:[r].concat(i.doubles.points.map(n))}:void 0,naf:"object"==typeof i.naf&&null!==i.naf?{wnd:i.naf.wnd,points:[r].concat(i.naf.points.map(n))}:void 0},r}constructor(e,t,r=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(P.isBN(e)||(e=new P(e,16)),this.x=e,P.isBN(t)||(t=new P(t,16)),this.y=t,r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{let e,t=BigInt("0x"+this.x.fromRed().toString(16)),r=BigInt("0x"+this.y.fromRed().toString(16)),i=tS(r,r),n=(e=tS(tS(t,t),t),tv(e+7n));return i===n}catch{return!1}}encode(e=!0,t){let r;if(this.inf)return"hex"===t?"00":[0];let i=this.curve.p.byteLength(),n=this.getX().toArray("be",i);return(r=e?[this.getY().isEven()?2:3].concat(n):[4].concat(n,this.getY().toArray("be",i)),"hex"!==t)?r:e7(r)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e)||this.x?.cmp(e.x??new P(0))===0)return new tD(null,null);let t=t_({X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},{X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:1n});if(0n===t.Z)return new tD(null,null);let r=tx(t.Z),i=tS(r,r),n=tS(t.X,i),a=tS(t.Y,tS(i,r));return new tD(n.toString(16),a.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));if(0n===t)return new tD(null,null);let r=tA({X:e,Y:t,Z:1n}),i=tx(r.Z),n=tS(i,i),a=tS(r.X,n),s=tS(r.Y,tS(n,i));return new tD(a.toString(16),s.toString(16))}getX(){return(this.x??new P(0)).fromRed()}getY(){return(this.y??new P(0)).fromRed()}mul(e){let t,r;if(P.isBN(e)||(e=new P(e,16)),this.inf)return this;let i=e.isNeg(),n=BigInt("0x"+(i?e.neg():e).toString(16));if(0n===(n=tI(n))||0n===n)return new tD(null,null);if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");this===this.curve.g?(t=tP,r=tN):(t=BigInt("0x"+this.x.fromRed().toString(16)),r=BigInt("0x"+this.y.fromRed().toString(16)));let a=tC(n,{x:t,y:r});if(0n===a.Z)return new tD(null,null);let s=tx(a.Z),o=tS(s,s),c=tS(a.X,o),l=tS(a.Y,tS(o,s)),h=new tD(new P(c.toString(16),16),new P(l.toString(16),16));return i?h.neg():h}mulCT(e){if(P.isBN(e)||(e=new P(e,16)),this.inf)return new tD(null,null);let t=e.isNeg(),r=BigInt("0x"+(t?e.neg():e).toString(16));if(0n===(r=tI(r)))return new tD(null,null);let i=this===this.curve.g?tP:BigInt("0x"+this.getX().toString(16)),n=this===this.curve.g?tN:BigInt("0x"+this.getY().toString(16)),a={X:0n,Y:1n,Z:0n},s={X:i,Y:n,Z:1n},o=r.toString(2);for(let e=0;e<o.length;e++){let t="1"===o[e]?1n:0n;tm(t,a,s),s=t_(a,s),tm(t,a=tA(a),s)}if(0n===a.Z)return new tD(null,null);let c=tx(a.Z),l=tS(c,c),h=tS(a.X,l),u=tS(a.Y,tS(l,c)),d=new tD(h.toString(16),u.toString(16));return t?d.neg():d}mulAdd(e,t,r){return this._endoWnafMulAdd([this,t],[e,r])}jmulAdd(e,t,r){return this._endoWnafMulAdd([this,t],[e,r],!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new P(0)).cmp(e.x??new P(0))&&0===(this.y??new P(0)).cmp(e.y??new P(0)))}neg(e){if(this.inf)return this;let t=new tD(this.x,(this.y??new P(0)).redNeg());if(!0===e&&null!=this.precomputed){let e=this.precomputed;t.precomputed={naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(e=>e.neg())}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(e=>e.neg())}:void 0,beta:void 0}}return t}dblp(e){let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}toJ(){return this.inf?new C(null,null,null):new C(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;let e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;let t=new tD((this.x??new P(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){let r=this.curve,i=e=>{if(null===e.x)throw Error("p.x is null");if(void 0===r.endo||null===r.endo)throw Error("curve.endo is undefined");return new tD(e.x.redMul(r.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(i)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(i)}:void 0}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw Error("_fixedNafMul requires precomputed values for the point");let t=this._getDoubles(),r=this.curve.getNAF(e,1,this.curve._bitLength),i=(1<<t.step+1)-(t.step%2==0?2:1);i/=3;let n=[];for(let e=0;e<r.length;e+=t.step){let i=0;for(let n=e+t.step-1;n>=e;n--)i=(i<<1)+r[n];n.push(i)}let a=new C(null,null,null),s=new C(null,null,null);for(let e=i;e>0;e--){for(let r=0;r<n.length;r++){let i=n[r];i===e?s=s.mixedAdd(t.points[r]):i===-e&&(s=s.mixedAdd(t.points[r].neg()))}a=a.add(s)}return a.toP()}_wnafMulAdd(e,t,r,i,n){let a=this.curve._wnafT1.map(e=>e.toNumber()),s=this.curve._wnafT2.map(()=>[]),o=this.curve._wnafT3.map(()=>[]),c=0;for(let r=0;r<i;r++){let i=t[r]._getNAFPoints(e);a[r]=i.wnd,s[r]=i.points}for(let e=i-1;e>=1;e-=2){let i=e-1,n=e;if(1!==a[i]||1!==a[n]){o[i]=this.curve.getNAF(r[i],a[i],this.curve._bitLength),o[n]=this.curve.getNAF(r[n],a[n],this.curve._bitLength),c=Math.max(o[i].length,c),c=Math.max(o[n].length,c);continue}let l=[t[i],null,null,t[n]];0===(t[i].y??new P(0)).cmp(t[n].y??new P(0))?(l[1]=t[i].add(t[n]),l[2]=t[i].toJ().mixedAdd(t[n].neg())):0===(t[i].y??new P(0)).cmp((t[n].y??new P(0)).redNeg())?(l[1]=t[i].toJ().mixedAdd(t[n]),l[2]=t[i].add(t[n].neg())):(l[1]=t[i].toJ().mixedAdd(t[n]),l[2]=t[i].toJ().mixedAdd(t[n].neg()));let h=[-3,-1,-5,-7,0,7,5,1,3],u=this.curve.getJSF(r[i],r[n]);c=Math.max(u[0].length,c),o[i]=Array(c),o[n]=Array(c);for(let e=0;e<c;e++){let t=0|u[0][e],r=0|u[1][e];o[i][e]=h[(t+1)*3+(r+1)],o[n][e]=0,s[i]=l}}let l=new C(null,null,null),h=this.curve._wnafT4;for(let e=c;e>=0;e--){let t=0;for(;e>=0;){let r=!0;for(let t=0;t<i;t++)h[t]=new P("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(r=!1);if(!r)break;t++,e--}if(e>=0&&t++,l=l.dblp(t),e<0)break;let r=new P(1),n=new P(2);for(let e=0;e<i;e++){let t,i=h[e];0!==i.cmpn(0)&&(l="affine"===(t=i.isNeg()?s[e][i.neg().sub(r).div(n).toNumber()].neg():s[e][i.sub(r).div(n).toNumber()]).type?l.mixedAdd(t):l.add(t))}}for(let e=0;e<i;e++)s[e]=[];return!0===n?l:l.toP()}_endoWnafMulAdd(e,t,r){let i,n=Array(2*e.length),a=Array(2*e.length);for(i=0;i<e.length;i++){let r=this.curve._endoSplit(t[i]),s=e[i],o=s._getBeta()??new tD(null,null);0!==r.k1.negative&&(r.k1.ineg(),s=s.neg(!0)),0!==r.k2.negative&&(r.k2.ineg(),o=o.neg(!0)),n[2*i]=s,n[2*i+1]=o,a[2*i]=r.k1,a[2*i+1]=r.k2}let s=this._wnafMulAdd(1,n,a,2*i,r);for(let e=0;e<2*i;e++)n[e]=null,a[e]=null;return s}_hasDoubles(e){if(null==this.precomputed)return!1;let t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;let r=[this],i=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)i=i.dbl();r.push(i)}return{step:e??1,points:r}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;let t=[this],r=(1<<e)-1,i=1===r?null:this.dbl();for(let e=1;e<r;e++)null!==i&&(t[e]=t[e-1].add(i));return{wnd:e,points:t}}}class tU{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw Error(t)}getNAF(e,t,r){let i=Array(Math.max(e.bitLength(),r)+1);i.fill(0);let n=1<<t+1,a=e.clone();for(let e=0;e<i.length;e++){let t,r=a.andln(n-1);a.isOdd()?(t=r>(n>>1)-1?(n>>1)-r:r,a.isubn(t)):t=0,i[e]=t,a.iushrn(1)}return i}getJSF(e,t){let r=[[],[]];e=e.clone(),t=t.clone();let i=0,n=0;for(;e.cmpn(-i)>0||t.cmpn(-n)>0;){let a,s,o=e.andln(3)+i&3,c=t.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),(1&o)==0)a=0;else{let t=e.andln(7)+i&7;a=(3===t||5===t)&&2===c?-o:o}if(r[0].push(a),(1&c)==0)s=0;else{let e=t.andln(7)+n&7;s=(3===e||5===e)&&2===o?-c:c}r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r}static cachedProperty(e,t,r){let i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(e){return"string"==typeof e?e9(e,"hex"):e}static intFromLE(e){return new P(e,"hex","le")}constructor(){if(void 0!==e)return e;e=this;const t={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new P(t.p,16),this.red=new A(t.prime),this.zero=new P(0).toRed(this.red),this.one=new P(1).toRed(this.red),this.two=new P(2).toRed(this.red),this.n=new P(t.n,16),this.g=tD.fromJSON(t.g,t.gRed),this._wnafT1=[,,,,],this._wnafT2=[,,,,],this._wnafT3=[,,,,],this._wnafT4=[,,,,],this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new P(t.a,16).toRed(this.red),this.b=new P(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=[,,,,],this._endoWnafT2=[,,,,]}_getEndomorphism(e){let t,r,i;if(this.zeroA&&1===this.p.modrn(3)){if(void 0!==e.beta)t=new P(e.beta,16).toRed(this.red);else{let e=this._getEndoRoots(this.p);if(null===e)throw Error("Failed to get endomorphism roots for beta.");t=(t=0>e[0].cmp(e[1])?e[0]:e[1]).toRed(this.red)}if(void 0!==e.lambda)r=new P(e.lambda,16);else{let e=this._getEndoRoots(this.n);if(null===e)throw Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw Error("Curve generator point (g) is not defined.");let i=this.g.mul(e[0])?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=e[0];else{if(r=e[1],null==this.g)throw Error("Curve generator point (g) is not defined.");let i=this.g.mul(r)?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null==i||null==n)throw Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");tU.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof e.basis&&null!==e.basis?e.basis.map(function(e){return{a:new P(e.a,16),b:new P(e.b,16)}}):this._getEndoBasis(r),{beta:t,lambda:r,basis:i}}}_getEndoRoots(e){let t=e===this.p?this.red:new _(e),r=new P(2).toRed(t).redInvm(),i=r.redNeg(),n=new P(3).toRed(t).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(e){let t,r,i,n,a,s,o=this.n.ushrn(Math.floor(this.n.bitLength()/2)),c=e,l=this.n.clone(),h=new P(1),u=new P(0),d=new P(0),f=new P(1),p=new P(0),g=0,b=new P(0),y=new P(0);for(;0!==c.cmpn(0);){let e=l.div(c);b=l.sub(e.mul(c)),y=d.sub(e.mul(h));let a=f.sub(e.mul(u));if(void 0===i&&0>b.cmp(o))t=p.neg(),r=h,i=b.neg(),n=y;else if(void 0!==i&&2==++g)break;p=b,l=c,c=b,d=h,h=y,f=u,u=a}if(void 0===t||void 0===r||void 0===i||void 0===n)throw Error("Failed to compute Endo Basis values");a=b.neg(),s=y;let m=i.sqr().add(n.sqr());return a.sqr().add(s.sqr()).cmp(m)>=0&&(a=t,s=r),0!==i.negative&&(i=i.neg(),n=n.neg()),0!==a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a:a,b:s}]}_endoSplit(e){if(null==this.endo)throw Error("Endomorphism is not defined.");let t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),l=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(l).neg()}}validate(e){if(e.inf)return!0;let t=e.x,r=e.y;if(null===t||null===r)throw Error("Point coordinates cannot be null");let i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class tF{r;s;static fromDER(e,t){let r=(e,t)=>{let r=e[t.place++];if((128&r)==0)return r;throw Error("Invalid DER entity length")};e=e9(e,t);let i=new class{place;constructor(){this.place=0}};if(48!==e[i.place++])throw Error("Signature DER must start with 0x30");if(r(e,i)+i.place!==e.length||2!==e[i.place++])throw Error("Signature DER invalid");let n=r(e,i),a=e.slice(i.place,n+i.place);if(i.place+=n,2!==e[i.place++])throw Error("Signature DER invalid");let s=r(e,i);if(e.length!==s+i.place)throw Error("Invalid R-length in signature DER");let o=e.slice(i.place,s+i.place);if(0===a[0])if((128&a[1])!=0)a=a.slice(1);else throw Error("Invalid R-value in signature DER");if(0===o[0])if((128&o[1])!=0)o=o.slice(1);else throw Error("Invalid S-value in signature DER");return new tF(new P(a),new P(o))}static fromCompact(e,t){if(65!==(e=e9(e,t)).length)throw Error("Invalid Compact Signature");let r=e[0];if(r<27||r>=35)throw Error("Invalid Compact Byte");return new tF(new P(e.slice(1,33)),new P(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,r){return tj(new P(ea(e,r),16),this,t)}toString(e){return this.toDER(e)}toDER(e){let t=(e,t)=>{if(t<128)e.push(t);else throw Error("len must be < 0x80")},r=e=>{let t=0,r=e.length-1;for(;0===e[t]&&(128&e[t+1])==0&&t<r;)t++;return 0===t?e:e.slice(t)},i=this.r.toArray(),n=this.s.toArray();for((128&i[0])!=0&&(i=[0].concat(i)),(128&n[0])!=0&&(n=[0].concat(n)),i=r(i),n=r(n);0===n[0]&&(128&n[1])==0;)n=n.slice(1);let a=[2];t(a,i.length),(a=a.concat(i)).push(2),t(a,n.length);let s=a.concat(n),o=[48];return(t(o,s.length),o=o.concat(s),"hex"===e)?e7(o):"base64"===e?ta(o):o}toCompact(e,t,r){if(e<0||e>3)throw Error("Invalid recovery param");if("boolean"!=typeof t)throw Error("Invalid compressed param");let i=27+e;t&&(i+=4);let n=[i];return(n=(n=n.concat(this.r.toArray("be",32))).concat(this.s.toArray("be",32)),"hex"===r)?e7(n):"base64"===r?ta(n):n}RecoverPublicKey(e,t){let r=this.r,i=this.s,n=new tU,a=n.n,s=n.g,o=0!=e>>1?r.add(a):r,c=tD.fromX(o,(1&e)!=0);if(!c.mul(a).isInfinity())throw Error("nR is not at infinity");let l=t.neg().umod(a),h=r.invm(a),u=h.mul(i).umod(a),d=h.mul(l).umod(a),f=new tX(s.mul(d).add(c.mul(u)));return f.validate(),f}CalculateRecoveryFactor(e,t){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,t)}catch{continue}if(e.eq(i))return r}throw Error("Unable to find valid recovery factor")}}class tL{K;V;constructor(e,t){const r=e9(e,"hex"),i=e9(t,"hex");if(32!==r.length)throw Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==i.length)throw Error("Nonce must be exactly 32 bytes (256 bits)");const n=r.concat(i);this.K=Array(32),this.V=Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(n)}hmac(){return new ee(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);let r=t.slice(0,e);return this.update(),e7(r)}}function tK(e,t,r=new tU){let i=8*e.byteLength()-r.n.bitLength();return(i>0&&e.iushrn(i),null===t&&e.cmp(r.n)>=0)?e.sub(r.n):e}function tH(e){let t=e.toArray("be"),r=0n;for(let e=0;e<t.length;e++)r=r<<8n|BigInt(t[e]);return r}let tq=new tU,tM=tq.n.byteLength(),t$=tq.n.subn(1),tz=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n>>1n,tW=(e,t,r=!1,i)=>{let n=tH(e=tK(e)),a=tH(t),s=new tL(t.toArray("be",tM),e.toArray("be",tM));for(let e=0;;e++){let t="function"==typeof i?i(e):P.isBN(i)?i:new P(s.generate(tM),16);if(null==t)throw Error("k is undefined");if(0>(t=tK(t,!0)).cmpn(1)||t.cmp(t$)>0){if(P.isBN(i))throw Error("Invalid fixed custom K value (must be >1 and <N-1)");continue}let o=tq.g.mulCT(t);if(o.isInfinity()){if(P.isBN(i))throw Error("Invalid fixed custom K value (k\xb7G at infinity)");continue}let c=tR(BigInt("0x"+o.getX().toString(16)));if(0n===c){if(P.isBN(i))throw Error("Invalid fixed custom K value (r == 0)");continue}let l=tV(BigInt("0x"+t.toString(16))),h=tR(n+tB(c,a)),u=tB(l,h);if(0n===u){if(P.isBN(i))throw Error("Invalid fixed custom K value (s == 0)");continue}return r&&u>tz&&(u=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n-u),new tF(new P(c.toString(16),16),new P(u.toString(16),16))}},tj=(e,t,r)=>{let i=tH(e);if(null==r.x||null==r.y)throw Error("Invalid public key: missing coordinates.");let n={x:tH(r.x),y:tH(r.y)},{r:a,s}={r:tH(t.r),s:tH(t.s)};if(a<=0n||a>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n||s<=0n||s>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n)return!1;let o=tV(s);if(0n===o)return!1;let c=tB(i,o),l=tB(a,o),h=t_(tC(c,{x:tP,y:tN}),tC(l,n));if(0n===h.Z)return!1;let u=tx(h.Z),d=tS(u,u);return tR(tS(h.X,d))===a};class tX extends tD{static fromPrivateKey(e){let t=new tU().g.mul(e);return new tX(t.x,t.y)}static fromString(e){let t=tD.fromString(e);return new tX(t.x,t.y)}static fromDER(e){let t=tD.fromDER(e);return new tX(t.x,t.y)}constructor(e,t=null,r=!0){if(e instanceof tD)super(e.getX(),e.getY());else{if(null===t&&r&&"string"==typeof e&&(66===e.length||130===e.length))throw Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,r)}}deriveSharedSecret(e){if(!this.validate())throw Error("Public key not valid for ECDH secret derivation");return this.mulCT(e)}verify(e,t,r){return tj(new P(ea(e,r),16),t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){let t=ec(this.encode(!0));return"hex"===e?e7(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else if("mainnet"===e||"main"===e)e=[0];else throw Error(`Invalid prefix ${e}`);return tl(this.toHash(),e)}deriveChild(e,t,r,i){let n;if("function"==typeof i){let t=i(e,this);void 0!==t?n=t:(n=this.deriveSharedSecret(e),"function"==typeof r&&r(e,this,n))}else n=this.deriveSharedSecret(e);let a=e9(t,"utf8"),s=el(n.encode(!0),a),o=new tU().g.mul(new P(s)),c=this.add(o);return new tX(c.x,c.y)}static fromMsgHashAndCompactSignature(e,t,r){let i=e9(t,r);if(65!==i.length)throw Error("Invalid Compact Signature");let n=i[0];if(n<27||n>=35)throw Error("Invalid Compact Byte");let a=i[0]-27;return a>3&&(a-=4),new tF(new P(i.slice(1,33)),new P(i.slice(33,65))).RecoverPublicKey(a,e)}}class tG{_rand;getRandomValues(e,t){let r=new Uint8Array(t);return e.crypto.getRandomValues(r),Array.from(r)}constructor(){const e=()=>{throw Error("No secure random number generator is available in this environment.")};if(this._rand=e,"undefined"!=typeof globalThis&&"function"==typeof globalThis.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis,e);return}if("undefined"!=typeof process&&process.release?.name==="node")try{const e=require("crypto");if("function"==typeof e.randomBytes){this._rand=t=>Array.from(e.randomBytes(t));return}}catch(e){}if("undefined"!=typeof self&&"function"==typeof self.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(self,e);return}if("undefined"!=typeof window&&"function"==typeof window.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(window,e);return}this._rand=e}generate(e){return this._rand(e)}}let tY=null,tJ=e=>(null==tY&&(tY=new tG),tY.generate(e));class tZ{x;y;constructor(e,t){const r=new tU().p;this.x=e.umod(r),this.y=t.umod(r)}toString(){return tc(this.x.toArray())+"."+tc(this.y.toArray())}static fromString(e){let[t,r]=e.split(".");return new tZ(new P(to(t)),new P(to(r)))}}class tQ{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){let r=new tU().p,i=[new tZ(new P(0),new P(e.toArray()))];for(let e=1;e<t;e++){let e=new P(tJ(32)).umod(r),t=new P(tJ(32)).umod(r);i.push(new tZ(e,t))}return new tQ(i)}valueAt(e){let t=new tU().p,r=new P(0);for(let i=0;i<this.threshold;i++){let n=this.points[i].y;for(let r=0;r<this.threshold;r++)if(i!==r){let a=this.points[r].x,s=this.points[i].x,o=e.sub(a).umod(t),c=s.sub(a).umod(t).invm(t),l=o.mul(c).umod(t);n=n.mul(l).umod(t)}r=r.add(n).umod(t)}return r}}class t0{points;threshold;integrity;constructor(e,t,r){this.points=e,this.threshold=t,this.integrity=r}static fromBackupFormat(e){let t=0,r="";return new t0(e.map((e,i)=>{let n=e.split(".");if(4!==n.length)throw Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+e);let[a,s,o,c]=n;if(void 0===o)throw Error("Threshold not found in share "+i.toString());if(void 0===c)throw Error("Integrity not found in share "+i.toString());let l=parseInt(o);if(0!==i&&t!==l)throw Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw Error("Integrity mismatch in share "+i.toString());return t=l,r=c,tZ.fromString([a,s].join("."))}),t,r)}toBackupFormat(){return this.points.map(e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class t1 extends P{static fromRandom(){return new t1(tJ(32))}static fromString(e,t="hex"){return new t1(super.fromString(e,t).toArray())}static fromHex(e){return new t1(super.fromHex(e,"big"))}static fromWif(e,t=1){let r=th(e,void 0,t);if(33!==r.data.length)throw Error("Invalid WIF length");if(1!==r.data[32])throw Error("Invalid WIF padding");return new t1(r.data.slice(0,32))}constructor(e=0,t=10,r="be",i="apply"){if(e instanceof P?(super(),e.copy(this)):super(e,t,r),"nocheck"!==i){const e=this.checkInField();if(!e.inField){if("error"===i)throw Error("Input is out of field");P.move(this,e.modN)}}}checkInField(){let e=new tU,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,r=!0,i){return tW(new P(ea(e,t),16),this,r,i)}verify(e,t,r){return tj(new P(ea(e,r),16),t,this.toPublicKey())}toPublicKey(){let e=new tU().g.mulCT(this);return new tX(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw Error("Value is out of field");return tl([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw Error("Public key not valid for ECDH secret derivation");return e.mulCT(this)}deriveChild(e,t,r,i){let n;if("function"==typeof i){let t=i(this,e);void 0!==t?n=t:(n=this.deriveSharedSecret(e),"function"==typeof r&&r(this,e,n))}else n=this.deriveSharedSecret(e);let a=e9(t,"utf8"),s=el(n.encode(!0),a),o=new tU;return new t1(this.add(new P(s)).mod(o.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw Error("threshold and totalShares must be numbers");if(e<2)throw Error("threshold must be at least 2");if(t<2)throw Error("totalShares must be at least 2");if(e>t)throw Error("threshold should be less than or equal to totalShares");let r=tQ.fromPrivateKey(this,e),i=[],n=new Set,a=new tU,s=tJ(64);for(let e=0;e<t;e++){let t,o=0;do if(t=new P(eh(s,[e,o,...tJ(32)])).umod(a.p),++o>5)throw Error("Failed to generate unique x coordinate after 5 attempts");while(t.isZero()||n.has(t.toString()));n.add(t.toString());let c=r.valueAt(t);i.push(new tZ(t,c))}return new t0(i,e,this.toPublicKey().toHash("hex").slice(0,8))}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return t1.fromKeyShares(t0.fromBackupFormat(e))}static fromKeyShares(e){let{points:t,threshold:r,integrity:i}=e;if(r<2)throw Error("threshold must be at least 2");if(t.length<r)throw Error(`At least ${r} shares are required to reconstruct the private key`);for(let e=0;e<r;e++)for(let i=e+1;i<r;i++)if(t[e].x.eq(t[i].x))throw Error("Duplicate share detected, each must be unique.");let n=new t1(new tQ(t,r).valueAt(new P(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==i)throw Error("Integrity hash mismatch");return n}}let t2=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),t8=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(e=>new Uint8Array(e)),t3=new Uint8Array(256),t6=new Uint8Array(256);for(let e=0;e<256;e++){let t=(e<<1^27*((128&e)!=0))&255;t3[e]=t,t6[e]=t^e}function t4(e,t,r){for(let i=0;i<4;i++){let n=t[r+i];for(let t=0;t<4;t++)e[t][i]^=n[t]}}function t5(e){for(let t=0;t<4;t++)e[t]=t2[e[t]]}function t7(e,t){let r,i,n,a,s=[[],[],[],[]],o=[],c=Array.from(t);if(16===c.length)a=11;else if(24===c.length)a=13;else if(32===c.length)a=15;else throw Error("Illegal key length: "+String(c.length));let l=function(e,t){let r=t.length/4,i=[];for(let e=0;e<t.length;e++)e%4==0&&i.push([]),i[e>>2].push(t[e]);for(let t=r;t<4*e;t++){i[t]=[];let e=i[t-1].slice();if(t%r==0){!function(e){let t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}(e),t5(e);let i=t8[t/r];for(let t=0;t<4;t++)e[t]^=i[t]}else r>6&&t%r==4&&t5(e);for(let n=0;n<4;n++)i[t][n]=i[t-r][n]^e[n]}return i}(a,c);for(let t=0;t<4;t++)s[0][t]=e[4*t],s[1][t]=e[4*t+1],s[2][t]=e[4*t+2],s[3][t]=e[4*t+3];for(t4(s,l,0),n=1;n<a;n++){for(let e=0;e<4;e++)for(let t=0;t<4;t++)s[e][t]=t2[s[e][t]];!function(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];let r=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=r,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}(s),n+1<a&&function(e){for(let t=0;t<4;t++){let r=e[0][t],i=e[1][t],n=e[2][t],a=e[3][t];e[0][t]=t3[r]^t6[i]^n^a,e[1][t]=r^t3[i]^t6[n]^a,e[2][t]=r^i^t3[n]^t6[a],e[3][t]=t6[r]^i^n^t3[a]}}(s),t4(s,l,4*n)}for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(s[i][r]);return o}let t9=function(e){if(e<0||e>Number.MAX_SAFE_INTEGER)throw Error("getBytes64: value out of range");let t=Math.floor(e/0x100000000),r=e>>>0;return[t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r]},re=function(e){return new Uint8Array(e)},rt=((n=new Uint8Array(16))[0]=225,n),rr=(...e)=>{let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return r},ri=function(e){let t=0,r=0;for(let i=0;i<e.length;i++)r=t,t=1&e[i],e[i]=e[i]>>1,0!==r&&(e[i]=128|e[i]);return e},rn=function(e,t){let r=t.slice(),i=re(16);for(let t=0;t<16;t++){let n=e[t];for(let e=7;e>=0;e--){let t=255&-(n>>e&1);for(let e=0;e<16;e++)i[e]^=r[e]&t;let a=255&-(1&r[15]);ri(r);for(let e=0;e<16;e++)r[e]^=rt[e]&a}}return i},ra=function(e){let t=e.slice();for(let e=15;e>11&&(t[e]=t[e]+1&255,0===t[e]);e--);return t};function rs(e,t){let r=re(16),i=new Uint8Array(16);for(let n=0;n<e.length;n+=16){i.set(r);for(let t=0;t<16;t++)i[t]^=e[n+t]??0;r=rn(i,t)}return r}function ro(e,t,r){if(0===e.length)return new Uint8Array(0);let i=new Uint8Array(e.length),n=t.slice(),a=0,s=Math.ceil(e.length/16);for(let t=0;t<s;t++){let o=t7(n,r),c=Math.min(16,e.length-a);for(let t=0;t<c;t++)i[a]=e[a]^o[t],a++;t+1<s&&(n=ra(n))}return i}function rc(e){let t,r,i=8*e.length;t=0===e.length?16:e.length%16==0?0:16-e.length%16;let n=new Uint8Array(16+e.length+t+16);r=16,n.set(e,r),r+=e.length,r+=t;let a=t9(0);n.set(a,r),r+=8;let s=t9(i);return n.set(s,r),n}class rl extends P{static fromRandom(){return new rl(tJ(32))}encrypt(e,t){let r=new Uint8Array(tJ(32)),{result:i,authenticationTag:n}=function(e,t,r){let i;if(0===t.length)throw Error("Initialization vector must not be empty");if(0===r.length)throw Error("Key must not be empty");let n=new Uint8Array(t7(re(16),r));if(12===t.length)i=rr(t,re(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=rr(e,re(16-e.length%16)));let r=t9(8*t.length);i=rs(rr(e,re(8),new Uint8Array(r)),n)}let a=ro(e,ra(i),r),s=ro(rs(rc(a),n),i,r);return{result:a,authenticationTag:s}}(new Uint8Array(e9(e,t)),r,new Uint8Array(this.toArray("be",32))),a=new Uint8Array(r.length+i.length+n.length),s=0;return a.set(r,s),s+=r.length,a.set(i,s),s+=i.length,a.set(n,s),tn(Array.from(a),t)}decrypt(e,t){let r=new Uint8Array(e9(e,t));if(r.length<48)throw Error("Ciphertext too short");let i=r.slice(0,32),n=r.length-16,a=function(e,t,r,i){let n;if(0===e.length)throw Error("Cipher text must not be empty");if(0===t.length)throw Error("Initialization vector must not be empty");if(0===i.length)throw Error("Key must not be empty");let a=new Uint8Array(t7(re(16),i));if(12===t.length)n=rr(t,re(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=rr(e,re(16-e.length%16)));let r=t9(8*t.length);n=rs(rr(e,re(8),new Uint8Array(r)),a)}let s=ro(e,ra(n),i),o=ro(rs(rc(e),a),n,i);if(o.length!==r.length)return null;let c=0;for(let e=0;e<o.length;e++)c|=o[e]^r[e];return 0!==c?null:s}(r.slice(32,n),i,r.slice(n),new Uint8Array(this.toArray("be",32)));if(null===a)throw Error("Decryption failed!");return tn(Array.from(a),t)}}let rh=new Uint8Array(0);class ru extends tF{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let t=e.cache,r={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},i=[...e.otherInputs];function n(t){let r=new tu;if(void 0===t)for(let t of e.outputs){let e=t.satoshis??0;r.writeUInt64LE(e);let i=t.lockingScript?.toUint8Array()??rh;r.writeVarIntNum(i.length),r.write(i)}else{let i=e.outputs[t];if(void 0===i)throw Error(`Output at index ${t} does not exist`);let n=i.satoshis??0;r.writeUInt64LE(n);let a=i.lockingScript?.toUint8Array()??rh;r.writeVarIntNum(a.length),r.write(a)}return eo(r.toUint8Array())}i.splice(e.inputIndex,0,r);let a=Array(32).fill(0),s=Array(32).fill(0),o=Array(32).fill(0);if((e.scope&ru.SIGHASH_ANYONECANPAY)==0&&(t?.hashPrevouts!=null?a=t.hashPrevouts:(a=(()=>{let e=new tu;for(let t of i){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(e9(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}return eo(e.toUint8Array())})(),null!=t&&(t.hashPrevouts=a))),(e.scope&ru.SIGHASH_ANYONECANPAY)==0&&(31&e.scope)!==ru.SIGHASH_SINGLE&&(31&e.scope)!==ru.SIGHASH_NONE&&(t?.hashSequence!=null?s=t.hashSequence:(s=(()=>{let e=new tu;for(let t of i){let r=t.sequence??0xffffffff;e.writeUInt32LE(r)}return eo(e.toUint8Array())})(),null!=t&&(t.hashSequence=s))),(31&e.scope)!==ru.SIGHASH_SINGLE&&(31&e.scope)!==ru.SIGHASH_NONE)t?.hashOutputsAll!=null?o=t.hashOutputsAll:(o=n(),null!=t&&(t.hashOutputsAll=o));else if((31&e.scope)===ru.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length){let r=e.inputIndex,i=t?.hashOutputsSingle?.get(r);null!=i?o=i:(o=n(r),null!=t&&(null==t.hashOutputsSingle&&(t.hashOutputsSingle=new Map),t.hashOutputsSingle.set(r,o)))}let c=new tu;c.writeInt32LE(e.transactionVersion),c.write(a),c.write(s),c.writeReverse(e9(e.sourceTXID,"hex")),c.writeUInt32LE(e.sourceOutputIndex);let l=e.subscript.toUint8Array();c.writeVarIntNum(l.length),c.write(l),c.writeUInt64LE(e.sourceSatoshis);let h=r.sequence;return c.writeUInt32LE(h),c.write(o),c.writeUInt32LE(e.lockTime),c.writeUInt32LE(e.scope>>>0),c.toUint8Array()}static fromChecksigFormat(e){if(0===e.length)return new ru(new P(1),new P(1),1);let t=e[e.length-1],r=e.slice(0,e.length-1),i=tF.fromDER(r);return new ru(i.r,i.s,t)}constructor(e,t,r){super(e,t),this.scope=r}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new P("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class rd{curve;constructor(){this.curve=new tU}generateProof(e,t,r,i){let n=t1.fromRandom(),a=n.toPublicKey(),s=r.mul(n),o=this.computeChallenge(t,r,i,s,a);return{R:a,SPrime:s,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,r,i){let{R:n,SPrime:a,z:s}=i,o=this.computeChallenge(e,t,r,a,n),c=this.curve.g.mul(s),l=n.add(e.mul(o));if(!c.eq(l))return!1;let h=t.mul(s),u=a.add(r.mul(o));return!!h.eq(u)}computeChallenge(e,t,r,i,n){return new P(ea([...e.encode(!0),...t.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)])).umod(this.curve.n)}}let rf=/^[0-9a-fA-F]+$/,rp=BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),rg=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),rb=rp-3n,ry=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),rm={x:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),y:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},rw=rg>>1n;class rv{p=rp;n=rg;a=rb;b=ry;g=rm;mod(e,t=this.p){let r=e%t;return r>=0n?r:r+t}modInv(e,t){if(0n===e||t<=0n)throw Error("Invalid mod inverse input");let[r,i]=[this.mod(e,t),t],[n,a]=[1n,0n];for(;0n!==i;){let e=r/i;[r,i]=[i,r-e*i],[n,a]=[a,n-e*a]}if(1n!==r)throw Error("Inverse does not exist");return this.mod(n,t)}modPow(e,t,r){if(1n===r)return 0n;let i=1n,n=this.mod(e,r),a=t;for(;a>0n;)(1n&a)===1n&&(i=this.mod(i*n,r)),a>>=1n,n=this.mod(n*n,r);return i}isInfinity(e){return null===e}assertOnCurve(e){if(this.isInfinity(e))return;let{x:t,y:r}=e;if(this.mod(r*r)!==this.mod(this.mod(t*t*t+this.a*t)+this.b))throw Error("Point is not on secp256r1")}pointFromAffine(e,t){let r={x:this.mod(e),y:this.mod(t)};return this.assertOnCurve(r),r}pointFromHex(e){if(e.startsWith("04")){let t=BigInt("0x"+e.slice(2,66)),r=BigInt("0x"+e.slice(66));return this.pointFromAffine(t,r)}if(e.startsWith("02")||e.startsWith("03")){let t=BigInt("0x"+e.slice(2)),r=this.mod(this.mod(t*t*t+this.a*t)+this.b),i=this.modPow(r,this.p+1n>>2n,this.p),n=(1n&i)===1n===e.startsWith("03")?i:this.p-i;return this.pointFromAffine(t,n)}throw Error("Invalid point encoding")}pointToHex(e,t=!1){if(this.isInfinity(e))return"00";let r=this.to32BytesHex(e.x),i=this.to32BytesHex(e.y);return t?((1n&e.y)===0n?"02":"03")+r:"04"+r+i}addPoints(e,t){if(this.isInfinity(e))return t;if(this.isInfinity(t))return e;let{x:r,y:i}=e,{x:n,y:a}=t;if(r===n)return i===a?this.doublePoint(e):null;let s=this.mod((a-i)*this.modInv(n-r,this.p)),o=this.mod(s*s-r-n),c=this.mod(s*(r-o)-i);return{x:o,y:c}}doublePoint(e){if(this.isInfinity(e))return e;if(0n===e.y)return null;let t=this.mod((3n*e.x*e.x+this.a)*this.modInv(2n*e.y,this.p)),r=this.mod(t*t-2n*e.x),i=this.mod(t*(e.x-r)-e.y);return{x:r,y:i}}add(e,t){return this.addPoints(e,t)}multiply(e,t){if(0n===t||this.isInfinity(e))return null;let r=this.mod(t,this.n),i=null,n=e;for(;r>0n;)(1n&r)===1n&&(i=this.addPoints(i,n)),n=this.doublePoint(n),r>>=1n;return i}multiplyBase(e){return this.multiply(this.g,e)}isOnCurve(e){try{return this.assertOnCurve(e),!0}catch(e){return!1}}generatePrivateKeyHex(){return this.to32BytesHex(this.randomScalar())}randomScalar(){for(;;){let e=BigInt("0x"+e7(tJ(32)));if(e>0n&&e<this.n)return e}}normalizePrivateKey(e){let t=this.mod(e,this.n);if(0n===t)throw Error("Invalid private key");return t}toScalar(e){if("bigint"==typeof e)return this.normalizePrivateKey(e);let t=e.startsWith("0x")?e.slice(2):e;if(!rf.test(t)||0===t.length||t.length>64)throw Error("Private key must be a hex string <= 32 bytes");let r=BigInt("0x"+t.padStart(64,"0"));return this.normalizePrivateKey(r)}publicKeyFromPrivate(e){let t=this.toScalar(e);return this.multiplyBase(t)}sign(e,t,r={}){let{prehashed:i=!1,nonce:n}=r,a=this.toScalar(t),s=this.normalizeMessage(e,i),o=this.bytesToScalar(s),c=n??this.deterministicNonce(a,s);for(;;){let e=this.multiplyBase(c);if(this.isInfinity(e)){c=n??this.deterministicNonce(a,s);continue}let t=this.mod(e.x,this.n);if(0n===t){c=n??this.deterministicNonce(a,s);continue}let r=this.modInv(c,this.n),i=this.mod(r*(o+t*a),this.n);if(0n===i){c=n??this.deterministicNonce(a,s);continue}return i>rw&&(i=this.n-i),{r:this.to32BytesHex(t),s:this.to32BytesHex(i)}}}verify(e,t,r,i={}){let n,{prehashed:a=!1}=i;try{n="string"==typeof r?this.pointFromHex(r):r}catch{return!1}if(null==n||!this.isOnCurve(n))return!1;let s="bigint"==typeof t.r?t.r:BigInt("0x"+t.r),o="bigint"==typeof t.s?t.s:BigInt("0x"+t.s);if(s<=0n||s>=this.n||o<=0n||o>=this.n)return!1;let c=this.bytesToScalar(this.normalizeMessage(e,a)),l=this.modInv(o,this.n),h=this.mod(c*l,this.n),u=this.mod(s*l,this.n),d=this.addPoints(this.multiplyBase(h),this.multiply(n,u));return!this.isInfinity(d)&&this.mod(d.x,this.n)===s}normalizeMessage(e,t){let r=this.toBytes(e);return t?r:new Uint8Array(ea(r))}bytesToScalar(e){return BigInt("0x"+e7(Array.from(e)))%this.n}deterministicNonce(e,t){let r=e9(this.to32BytesHex(e),"hex"),i=0;for(;i<1024;){let e=BigInt("0x"+e7(el(r,0===i?Array.from(t):Array.from(t).concat([255&i]))))%this.n;if(e>0n)return e;i++}throw Error("Failed to derive deterministic nonce")}toBytes(e){if("string"==typeof e){let t=rf.test(e)&&e.length%2==0;return Uint8Array.from(e9(e,t?"hex":"utf8"))}if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unsupported message format")}to32BytesHex(e){return e.toString(16).padStart(64,"0")}}let rI={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,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,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(let e in rI)rI[rI[e]]=e;let rk=rI,rS="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class rx{_chunks;parsed;rawBytesCache;hexCache;static fromASM(e){let t=[],r=e.split(" "),i=0;for(;i<r.length;){let e,n=r[i],a=0;if(n.startsWith("OP_")&&void 0!==rk[n]&&(e=n,a=rk[n]),"0"===n)a=0,t.push({op:a}),i+=1;else if("-1"===n)a=rk.OP_1NEGATE,t.push({op:a}),i+=1;else if(void 0===e){let e=r[i];e.length%2!=0&&(e="0"+e);let n=e9(e,"hex");if(tn(n,"hex")!==e)throw Error("invalid hex string in script");let s=n.length;s>=0&&s<rk.OP_PUSHDATA1?a=s:s<256?a=rk.OP_PUSHDATA1:s<65536?a=rk.OP_PUSHDATA2:s<0x100000000&&(a=rk.OP_PUSHDATA4),t.push({data:n,op:a}),i+=1}else a===rk.OP_PUSHDATA1||a===rk.OP_PUSHDATA2||a===rk.OP_PUSHDATA4?(t.push({data:e9(r[i+2],"hex"),op:a}),i+=3):(t.push({op:a}),i+=1)}return new rx(t)}static fromHex(e){if(0===e.length)return rx.fromBinary([]);if(e.length%2!=0)throw Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(e))throw Error("Some elements in this string are not hex encoded.");let t=e9(e,"hex");return new rx([],Uint8Array.from(t),e.toLowerCase(),!1)}static fromBinary(e){return new rx([],Uint8Array.from(e),void 0,!1)}constructor(e=[],t,r,i=!0){this._chunks=e,this.parsed=i,this.rawBytesCache=t,this.hexCache=r}get chunks(){return this.ensureParsed(),this._chunks}set chunks(e){this._chunks=e,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=rx.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let e="";for(let t=0;t<this.chunks.length;t++){let r=this.chunks[t];e+=this._chunkToString(r)}return e.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes());let e=null!=rS?rS.from(this.rawBytesCache).toString("hex"):tn(Array.from(this.rawBytesCache),"hex");return this.hexCache=e,e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes()),this.rawBytesCache}writeScript(e){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.invalidateSerializationCaches(),this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.invalidateSerializationCaches(),this.chunks[e]={op:t},this}writeBn(e){if(this.invalidateSerializationCaches(),e.cmpn(0)===rk.OP_0)this.chunks.push({op:rk.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:rk.OP_1NEGATE});else if(e.cmpn(1)>=0&&0>=e.cmpn(16))this.chunks.push({op:e.toNumber()+rk.OP_1-1});else{let t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;this.invalidateSerializationCaches();let r=e.length>0?e:void 0;if(e.length>0&&e.length<rk.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=rk.OP_0;else if(e.length<256)t=rk.OP_PUSHDATA1;else if(e.length<65536)t=rk.OP_PUSHDATA2;else if(e.length<0x100000000)t=rk.OP_PUSHDATA4;else throw Error("You can't push that much data");return this.chunks.push({data:r,op:t}),this}writeNumber(e){return this.invalidateSerializationCaches(),this.writeBn(new P(e)),this}removeCodeseparators(){this.invalidateSerializationCaches();let e=[];for(let t=0;t<this.chunks.length;t++)this.chunks[t].op!==rk.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this}findAndDelete(e){this.invalidateSerializationCaches();let t=e.toHex();for(let e=0;e<this.chunks.length;e++)t===new rx([this.chunks[e]]).toHex()&&this.chunks.splice(e,1);return this}isPushOnly(){for(let e=0;e<this.chunks.length;e++)if(this.chunks[e].op>rk.OP_16)return!1;return!0}isLockingScript(){throw Error("Not implemented")}isUnlockingScript(){throw Error("Not implemented")}static computeSerializedLength(e){let t=0;for(let r of e){if(t+=1,null==r.data)continue;let e=r.data.length;if(r.op===rk.OP_RETURN){t+=e;break}r.op<rk.OP_PUSHDATA1?t+=e:r.op===rk.OP_PUSHDATA1?t+=1+e:r.op===rk.OP_PUSHDATA2?t+=2+e:r.op===rk.OP_PUSHDATA4&&(t+=4+e)}return t}serializeChunksToBytes(){let e=this.chunks,t=new Uint8Array(rx.computeSerializedLength(e)),r=0;for(let i=0;i<e.length;i++){let n=e[i];if(t[r++]=n.op,null!=n.data){if(n.op===rk.OP_RETURN){t.set(n.data,r),r+=n.data.length;break}r=rx.writeChunkData(t,r,n.op,n.data)}}return t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(e,t,r,i){let n=i.length;if(r<rk.OP_PUSHDATA1)return e.set(i,t),t+n;if(r===rk.OP_PUSHDATA1)return e[t++]=255&n,e.set(i,t),t+n;if(r===rk.OP_PUSHDATA2)return e[t++]=255&n,e[t++]=n>>8&255,e.set(i,t),t+n;if(r===rk.OP_PUSHDATA4){let r=n>>>0;return e[t++]=255&r,e[t++]=r>>8&255,e[t++]=r>>16&255,e[t++]=r>>24&255,e.set(i,t),t+n}return t}static parseChunks(e){let t=[],r=e.length,i=0,n=0;for(;i<r;){let a=e[i++]??0;if(a===rk.OP_RETURN&&0===n){t.push({op:a,data:rx.copyRange(e,i,r)});break}if(a===rk.OP_IF||a===rk.OP_NOTIF||a===rk.OP_VERIF||a===rk.OP_VERNOTIF?n++:a===rk.OP_ENDIF&&n--,a>0&&a<rk.OP_PUSHDATA1){let n=Math.min(i+a,r);t.push({data:rx.copyRange(e,i,n),op:a}),i=n}else if(a===rk.OP_PUSHDATA1){let n=i<r?e[i++]??0:0,s=Math.min(i+n,r);t.push({data:rx.copyRange(e,i,s),op:a}),i=s}else if(a===rk.OP_PUSHDATA2){let n=(e[i]??0)|(e[i+1]??0)<<8,s=Math.min((i=Math.min(i+2,r))+n,r);t.push({data:rx.copyRange(e,i,s),op:a}),i=s}else if(a===rk.OP_PUSHDATA4){let n=((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16|(e[i+3]??0)<<24)>>>0,s=Math.min((i=Math.min(i+4,r))+n,r);t.push({data:rx.copyRange(e,i,s),op:a}),i=s}else t.push({op:a})}return t}static copyRange(e,t,r){let i=Math.max(r-t,0),n=Array(i);for(let r=0;r<i;r++)n[r]=e[t+r]??0;return n}_chunkToString(e){let t=e.op,r="";if(void 0===e.data){let e=rk[t];r=`${r} ${e}`}else r=`${r} ${e7(e.data)}`;return r}}class rE extends rx{isLockingScript(){return!0}isUnlockingScript(){return!1}}class rP extends rx{isLockingScript(){return!1}isUnlockingScript(){return!0}}class rN extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(e){const t=e.stackState.map(e=>null!=e&&void 0!==e.length?e7(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),r=e.altStackState.map(e=>null!=e&&void 0!==e.length?e7(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),i=`Context: ${e.context}, PC: ${e.programCounter}`,n=`Stack: [${t}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,a=`AltStack: [${r}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`;super(`Script evaluation error: ${e.message}
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,()=>(()=>{"use strict";let e;var t,r,i,n,a={};a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};a.r(s),a.d(s,{Signature:()=>t_,SHIPCast:()=>nF,BEEF_V1:()=>rH,BEEF_V2:()=>rq,BeefParty:()=>rX,Polynomial:()=>t$,SHIPBroadcaster:()=>nF,KNOWN_IDENTITY_TYPES:()=>nX,Utils:()=>c,KeyDeriver:()=>ig,SignedMessage:()=>h,SymmetricKey:()=>rt,LocalKVStore:()=>n2,WhatsOnChain:()=>rD,IdentityClient:()=>nQ,ScriptEvaluationError:()=>rw,defaultHttpClient:()=>rC,verifyNonce:()=>nw,RPuzzle:()=>rE,WalletClient:()=>nf,walletErrors:()=>i,SatoshisPerKilobyte:()=>rO,PrivateKey:()=>tW,defaultIdentity:()=>nj,KeyShares:()=>tz,XDM:()=>ik,HTTPSOverlayBroadcastFacilitator:()=>nU,Certificate:()=>iS,HD:()=>ir,CompletedProtoWallet:()=>ny,AuthFetch:()=>nN,NodejsHttpClient:()=>r_,ProtoWallet:()=>im,StorageUtils:()=>p,Validation:()=>f,CachedKeyDeriver:()=>ib,withDoubleSpendRetry:()=>nL,ECIES:()=>ih,HTTPWalletWire:()=>iP,PointInFiniteField:()=>tM,ARC:()=>rB,Curve:()=>tA,MasterCertificate:()=>ng,ECDSA:()=>l,GlobalKVStore:()=>n7,Random:()=>tq,TOTP:()=>id,VerifiableCertificate:()=>nb,WindowCWISubstrate:()=>iw,defaultChainTracker:()=>rU,DEFAULT_SLAP_TRACKERS:()=>nR,ReactNativeWebView:()=>iR,DEFAULT_IDENTITY_CLIENT_OPTIONS:()=>nG,WalletErrors:()=>iI,WalletError:()=>iv,StorageUploader:()=>nz,BlockHeadersService:()=>r1,Spend:()=>rS,Hash:()=>o,validateCertificates:()=>nk,Schnorr:()=>rn,Script:()=>rb,TX_DATA_FORMAT:()=>t,WalletWireTransceiver:()=>iE,EncryptedMessage:()=>u,TransactionSignature:()=>ri,fromUtxo:()=>iu,Beef:()=>r$,HTTPWalletJSON:()=>iC,OverlayAdminTokenTemplate:()=>nO,SimplifiedFetchTransport:()=>nP,TopicBroadcaster:()=>nF,BeefTx:()=>rL,MerklePath:()=>rF,WhatsOnChainBroadcaster:()=>rJ,defaultBroadcaster:()=>rV,getVerifiableCertificates:()=>nI,WERR_INSUFFICIENT_FUNDS:()=>iT,LockingScript:()=>ry,HTTPSOverlayLookupFacilitator:()=>nV,FetchHttpClient:()=>rT,Peer:()=>nx,LookupResolver:()=>nD,PublicKey:()=>tL,binaryHttpClient:()=>rQ,StorageDownloader:()=>nW,BigNumber:()=>m,Secp256r1:()=>rd,SecurityLevels:()=>r,SessionManager:()=>nm,WalletWireProcessor:()=>np,createNonce:()=>nv,WERR_INVALID_PARAMETER:()=>i_,isBroadcastResponse:()=>rj,OP:()=>rp,P2PKH:()=>rx,WERR_REVIEW_ACTIONS:()=>iO,Teranode:()=>r0,UnlockingScript:()=>rm,LivePolicy:()=>rA,deserializeWalletProtocol:()=>n1,RegistryClient:()=>n0,Point:()=>tO,BSM:()=>d,Mnemonic:()=>ia,isBroadcastFailure:()=>rG,Transaction:()=>rW,PushDrop:()=>rN,ATOMIC_BEEF:()=>rM,DEFAULT_TESTNET_SLAP_TRACKERS:()=>nB});var o={};a.r(o),a.d(o,{RIPEMD160:()=>q,SHA1:()=>$,SHA1HMAC:()=>j,SHA256:()=>M,SHA256HMAC:()=>W,SHA512:()=>z,SHA512HMAC:()=>G,hash160:()=>ee,hash256:()=>Q,htonl:()=>_,pbkdf2:()=>ez,realHtonl:()=>eG,ripemd160:()=>X,sha1:()=>J,sha256:()=>Y,sha256hmac:()=>et,sha512:()=>Z,sha512hmac:()=>er,swapBytes32:()=>eW,toArray:()=>A});var c={};a.r(c),a.d(c,{Reader:()=>tn,Writer:()=>ti,base64ToArray:()=>e3,constantTimeEquals:()=>tl,encode:()=>e6,fromBase58:()=>e9,fromBase58Check:()=>tr,minimallyEncode:()=>ta,toArray:()=>e1,toBase58:()=>te,toBase58Check:()=>tt,toBase64:()=>e5,toHex:()=>e0,toUTF8:()=>e4,verifyNotNull:()=>tc,zero2:()=>eY});var l={};a.r(l),a.d(l,{sign:()=>tU,verify:()=>tF});var h={};a.r(h),a.d(h,{sign:()=>r8,verify:()=>r3});var u={};a.r(u),a.d(u,{decrypt:()=>r5,encrypt:()=>r6});var d={};a.r(d),a.d(d,{magicHash:()=>r9,sign:()=>ie,verify:()=>it});var f={};a.r(f),a.d(f,{isHexString:()=>iJ,parseWalletOutpoint:()=>iB,specOpThrowReviewActions:()=>nd,validateAbortActionArgs:()=>i8,validateAcquireDirectCertificateArgs:()=>ns,validateAcquireIssuanceCertificateArgs:()=>na,validateBase64String:()=>ij,validateBasketInsertion:()=>i4,validateCreateActionArgs:()=>i0,validateCreateActionInput:()=>iY,validateCreateActionOptions:()=>iQ,validateCreateActionOutput:()=>iZ,validateDiscoverByAttributesArgs:()=>nl,validateDiscoverByIdentityKeyArgs:()=>nc,validateInteger:()=>iL,validateInternalizeActionArgs:()=>i7,validateInternalizeOutput:()=>i6,validateListActionsArgs:()=>nu,validateListCertificatesArgs:()=>ni,validateListOutputsArgs:()=>nh,validateOptionalInteger:()=>iF,validateOptionalOutpointString:()=>i9,validateOriginator:()=>i5,validateOutpointString:()=>ne,validatePositiveIntegerOrZero:()=>iK,validateProveCertificateArgs:()=>no,validateRelinquishCertificateArgs:()=>nr,validateRelinquishOutputArgs:()=>nt,validateSatoshis:()=>iU,validateSignActionArgs:()=>i2,validateSignActionOptions:()=>i1,validateStringLength:()=>iH,validateWalletPayment:()=>i3});var p={};a.r(p),a.d(p,{getHashFromURL:()=>nM,getURLForFile:()=>nq,getURLForHash:()=>nH,isValidURL:()=>n$,normalizeURL:()=>nK});let g="undefined"!=typeof globalThis?globalThis.Buffer:void 0,b=null!=g&&"function"==typeof g.from,y=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)y[48+e]=e;for(let e=0;e<6;e++)y[65+e]=10+e,y[97+e]=10+e;class m{static zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];static groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];static groupBases=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(m.wordSize);static WORD_MASK=(1n<<m.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=0x3ffffff;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;_magnitude;_sign;_nominalWordLength;red;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1"),0n===this._magnitude?this._sign=0:this._sign=+(1===e)}get _computedWordsArray(){if(0n===this._magnitude)return[0];let e=[],t=this._magnitude;for(;t>0n;)e.push(Number(t&m.WORD_MASK)),t>>=m.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){let e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;let t=Array(this._nominalWordLength).fill(0);for(let r=0;r<e.length;r++)t[r]=e[r];return t}set words(e){let t=this._sign,r=0n,i=e.length>0?e.length:1;for(let t=i-1;t>=0;t--){let i=void 0===e[t]?0:e[t];r=r<<m.WORD_SIZE_BIGINT|BigInt(i&Number(m.WORD_MASK))}this._magnitude=r,this._sign=t,this._nominalWordLength=i,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof m||null!==e&&"object"==typeof e&&e.constructor?.wordSize===m.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return 0>e.cmp(t)?e:t}constructor(e=0,t=10,r="be"){if(this._magnitude=0n,this._sign=0,this._nominalWordLength=1,this.red=null,void 0===e&&(e=0),null===e)return void this._initializeState(0n,0);if("bigint"==typeof e){this._initializeState(e<0n?-e:e,+(e<0n)),this.normSign();return}let i=t,n=r;if(("le"===t||"be"===t)&&(n=t,i=10),"number"==typeof e)return void this.initNumber(e,n);if(Array.isArray(e))return void this.initArray(e,n);if("string"==typeof e){"hex"===i&&(i=16),this.assert("number"==typeof i&&i===(0|i)&&i>=2&&i<=36,"Base must be an integer between 2 and 36");let t=e.toString().replace(/\s+/g,""),r=0,a=0;t.startsWith("-")?(r++,a=1):t.startsWith("+")&&r++;let s=t.substring(r);if(0===s.length){this._initializeState(0n,1===a&&t.startsWith("-")?1:0),this.normSign();return}if(16===i){let e;if("le"===n){let e=[],t=s;t.length%2!=0&&(t="0"+t);for(let r=0;r<t.length;r+=2){let i=parseInt(t.substring(r,r+2),16);if(isNaN(i))throw Error("Invalid character in "+t);e.push(i)}this.initArray(e,"le"),this._sign=a,this.normSign();return}try{e=BigInt("0x"+s)}catch(e){throw Error("Invalid character in "+s)}this._initializeState(e,a),this.normSign()}else try{if(this._parseBaseString(s,i),this._sign=a,this.normSign(),"le"===n){let e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){if(e.message.includes("Invalid character in string")||e.message.includes("Invalid digit for base")||e.message.startsWith("Invalid character:"))throw Error("Invalid character");throw e}}else 0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0)}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw Error("Base must be between 2 and 36");let r="",i=e>0n?e:-e,n=BigInt(t);for(;i>0n;)r="0123456789abcdefghijklmnopqrstuvwxyz"[Number(i%n)]+r,i/=n;return r}_parseBaseString(e,t){if(0===e.length){this._magnitude=0n,this._finishInitialization();return}this._magnitude=0n;let r=BigInt(t),i=m.groupSizes[t],n=BigInt(m.groupBases[t]);(0===i||0n===n)&&(0===(i=Math.floor(Math.log(0x3ffffff)/Math.log(t)))&&(i=1),n=r**BigInt(i));let a=0,s=e.length,o=s%i;if(0===o&&s>0&&(o=i),o>0){let r=e.substring(a,a+o);this._magnitude=BigInt(this._parseBaseWord(r,t)),a+=o}for(;a<s;){let r=e.substring(a,a+i),s=BigInt(this._parseBaseWord(r,t));this._magnitude=this._magnitude*n+s,a+=i}this._finishInitialization()}_parseBaseWord(e,t){let r=0;for(let i=0;i<e.length;i++){let n,a=e.charCodeAt(i);if(a>=48&&a<=57)n=a-48;else if(a>=65&&a<=90)n=a-65+10;else if(a>=97&&a<=122)n=a-97+10;else throw Error("Invalid character: "+e[i]);if(n>=t)throw Error("Invalid character");r=r*t+n}return r}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{let e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/m.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=m.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),+(e<0)),"le"===t){let e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let r=0n;if("be"===t)for(let t=0;t<e.length;t++)r=r<<8n|BigInt(255&e[t]);else for(let t=e.length-1;t>=0;t--)r=r<<8n|BigInt(255&e[t]);return this._initializeState(r,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){let e=new m(0n);return this.copy(e),e}expand(e){return this.assert(e>=0,"Expand size must be non-negative"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null!==this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}toString(e=10,t=1){if(16===e||"hex"===e){let e=this._getMinimalHex();if(t>1)for("0"!==e&&e.length%2!=0&&(e="0"+e);e.length%t!=0;)e="0"+e;return(this.isNeg()?"-":"")+e}if("number"!=typeof e||e<2||e>36||e%1!=0)throw Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude){let e="0";if(t>1)for(;e.length<t;)e="0"+e;return e}let r=m.groupSizes[e],i=BigInt(m.groupBases[e]);(0===r||0n===i)&&(0===(r=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)))&&(r=1),i=BigInt(e)**BigInt(r));let n="",a=this._magnitude;for(;a>0n;){let t=a%i;a/=i;let s=this._bigIntToStringInBase(t,e);if(a>0n){let e=r-s.length;n=e>0&&e<m.zeros.length?m.zeros[e]+s+n:e>0?"0".repeat(e)+s+n:s+n}else n=s+n}if(t>0)for(;n.length<t;)n="0"+n;return(1===this._sign?"-":"")+n}toNumber(){let e=this._getSignedValue();if(e>m.MAX_SAFE_INTEGER_BIGINT||e<m.MIN_SAFE_INTEGER_BIGINT)throw Error("Number can only safely store up to 53 bits");return Number(e)}toBigInt(){return this._getSignedValue()}toJSON(){let e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let r=this._magnitude,i=t?0:e.length-1,n=t?1:-1;for(let t=0;t<e.length;++t){if(0n===r&&i>=0&&i<e.length)e[i]=0;else if(i>=0&&i<e.length)e[i]=Number(255n&r);else break;r>>=8n,i+=n}}toArray(e="be",t){this.strip();let r=this.byteLength(),i=t??Math.max(1,r);this.assert(r<=i,"byte array longer than desired length"),this.assert(i>0,"Requested array length <= 0");let n=Array(i).fill(0);return 0n===this._magnitude&&i>0?n:0n===this._magnitude&&0===i?[]:(this.toArrayLikeGeneric(n,"le"===e),n)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){let t=e.bitLength();if(0===t)return[];let r=Array(t),i=e._magnitude;for(let e=0;e<t;e++)r[e]=+((i>>BigInt(e)&1n)!==0n);return r}toBitArray(){return m.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;(1n&t)===0n&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);let t=BigInt(e),r=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(r=(1n<<t)+r),r&=(1n<<t)-1n;let i=new m(0n);return i._initializeState(r,0),i}fromTwos(e){this.assert(e>=0);let t=BigInt(e),r=this._magnitude;if(e>0&&(r>>t-1n&1n)!==0n&&0===this._sign){let e=new m(0n);return e._setValueFromSigned(r-(1n<<t)),e}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=+(1!==this._sign)),this}_iuop(e,t){let r=t(this._magnitude,e._magnitude),i=t===((e,t)=>e^t),n=this._nominalWordLength;return i&&(n=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),i&&(this._nominalWordLength=Math.max(this._nominalWordLength,n)),this.strip()}iuor(e){return this._iuop(e,(e,t)=>e|t)}iuand(e){return this._iuop(e,(e,t)=>e&t)}iuxor(e){return this._iuop(e,(e,t)=>e^t)}_iop(e,t){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t)}ior(e){return this._iop(e,(e,t)=>e|t)}iand(e){return this._iop(e,(e,t)=>e&t)}ixor(e){return this._iop(e,(e,t)=>e^t)}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);let t=BigInt(e);this._magnitude=~this._magnitude&(1n<<t)-1n;let r=0===e?1:Math.ceil(e/m.wordSize);return this._nominalWordLength=Math.max(1,r),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,r)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);let r=BigInt(e);1===t||!0===t?this._magnitude|=1n<<r:this._magnitude&=~(1n<<r);let i=Math.floor(e/m.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,i),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){let t=new m(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){let t=new m(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){let t=new m(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=m.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){let e=new m(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new m(1n);let t=new m(1n),r=this.clone(),i=e.clone(),n=r.isNeg(),a=i.isOdd();for(n&&r.ineg();!i.isZero();)i.isOdd()&&t.imul(r),r.isqr(),i.iushrn(1);return n&&a&&t.ineg(),t}static normalizeNonNegativeBigInt(e,t){if("number"==typeof e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return BigInt(e)}if(e<0n)throw Error(`${t} must be a non-negative integer`);return e}iushln(e){let t=m.normalizeNonNegativeBigInt(e,"Shift bits");return 0n===t?this:(this._magnitude<<=t,this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,r){let i=m.normalizeNonNegativeBigInt(e,"Shift bits");if(0n===i)return null!=r&&r._initializeState(0n,0),this;if(null!=r){let e=this._magnitude&(1n<<i)-1n;r._initializeState(e,0)}return this._magnitude>>=i,this._finishInitialization(),this.strip()}ishrn(e,t,r){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,r)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),(this._magnitude>>BigInt(e)&1n)!==0n}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");let t=BigInt(e);this._magnitude&=0n===t?0n:(1n<<t)-1n;let r=0===e?1:Math.max(1,Math.ceil(e/m.wordSize));return this._nominalWordLength=r,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,r),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=m.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=m.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,r){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){let e=new m(0n);return{div:"mod"!==t?e:null,mod:"div"!==t?e:null}}let i=this._getSignedValue(),n=e._getSignedValue(),a=null,s=null;"mod"!==t&&(a=i/n),"div"!==t&&(s=i%n,!0===r&&s<0n&&(s+=n<0n?-n:n));let o=null!==a?new m(0n):null;null!==o&&null!==a&&o._setValueFromSigned(a);let c=null!==s?new m(0n):null;return null!==c&&null!==s&&c._setValueFromSigned(s),{div:o,mod:c}}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());let t=this._getSignedValue(),r=e._getSignedValue(),i=t/r,n=t%r;if(0n===n){let e=new m(0n);return e._setValueFromSigned(i),e}2n*(n<0n?-n:n)>=(r<0n?-r:r)&&(t>0n&&r>0n||t<0n&&r<0n?i+=1n:i-=1n);let a=new m(0n);return a._setValueFromSigned(i),a}modrn(e){this.assert(0!==e,"Division by zero in modrn");let t=BigInt(Math.abs(e));if(0n===t)throw Error("Division by zero in modrn");let r=this._magnitude%t;return e<0?Number(-r):Number(r)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=m.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),r=e._magnitude,i=1n,n=0n,a=0n,s=1n;for(;0n!==r;){let e=t/r,o=r;r=t%r,t=o,o=n,n=i-e*n,i=o,o=s,s=a-e*s,a=o}let o=new m(0n);o._setValueFromSigned(i);let c=new m(0n);c._setValueFromSigned(a);let l=new m(0n);return l._initializeState(t<0n?-t:t,0),{a:o,b:c,gcd:l}}gcd(e){let t=this._magnitude,r=e._magnitude;if(0n===t){let e=new m(0n);return e._setValueFromSigned(r),e.iabs()}if(0n===r){let e=new m(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==r;){let e=t%r;t=r,r=e}let i=new m(0n);return i._initializeState(t,0),i}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");let t=this.egcd(e);if(!t.gcd.eqn(1))throw Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n===0n}isOdd(){return this._magnitude%2n===1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);let t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=m.MAX_IMULN_ARG,"Number is too big");let t=this._getSignedValue(),r=BigInt(e);return t<r?-1:+(t>r)}cmp(e){let t=this._getSignedValue(),r=e._getSignedValue();return t<r?-1:+(t>r)}ucmp(e){return this._magnitude<e._magnitude?-1:+(this._magnitude>e._magnitude)}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return -1===this.cmpn(e)}lt(e){return -1===this.cmp(e)}lten(e){return 0>=this.cmpn(e)}lte(e){return 0>=this.cmp(e)}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let r="be";return("little"===t||"le"===t)&&(r="le"),new m(e,16,r)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);let r=2*e;for(;t.length<r;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new m(e,16)}static fromNumber(e){return new m(e)}static fromString(e,t){return new m(e,t)}static fromSm(e,t="big"){if(0===e.length)return new m(0n);let r=e.slice();"little"===t&&r.reverse();let i=0;r.length>0&&(128&r[0])!=0&&(i=1,r[0]&=127);let n=0n;if(b){let e=g.from(r).toString("hex");n=0===e.length?0n:BigInt("0x"+e)}else{let e="";for(let t of r)e+=t<16?"0"+t.toString(16):t.toString(16);n=0===e.length?0n:BigInt("0x"+e)}let a=new m(0n);return a._initializeState(n,i),a}toSm(e="big"){let t;if(0n===this._magnitude)return 1===this._sign?[128]:[];let r=this._getMinimalHex();r.length%2!=0&&(r="0"+r);let i=Array(r.length/2);for(let e=0,t=0;e<r.length;e+=2){let n=y[r.charCodeAt(e)],a=y[r.charCodeAt(e+1)];i[t++]=(15&n)<<4|15&a}return 1===this._sign?(128&i[0])!=0?t=[128,...i]:(t=i.slice(),t[0]|=128):t=(128&i[0])!=0?[0,...i]:i.slice(),"little"===e?t.reverse():t}static fromBits(e,t=!1){let r=e>>>24,i=8388607&e,n=(8388608&e)!=0;if(t&&n)throw Error("negative bit set");if(0===r&&0===i){if(n&&t)throw Error("negative bit set for zero value");return new m(0n)}let a=new m(i);return r<=3?a.iushrn((3-r)*8):a.iushln((r-3)*8),n&&a.ineg(),a}toBits(){let e;if(this.strip(),this.isZero()&&!this.isNeg())return 0;let t=this.isNeg(),r=this.abs(),i=r.toArray("be"),n=0;for(;n<i.length-1&&0===i[n];)n++;let a=(i=i.slice(n)).length;if(0!==a||r.isZero()||(i=[0],a=1),r.isZero()&&(a=0,i=[]),0===a)e=0;else if(a<=3){e=0;for(let t=0;t<a;t++)e=e<<8|i[t]}else e=i[0]<<16|i[1]<<8|i[2];(8388608&e)!=0&&a<=255&&(e>>>=8,a++);let s=a<<24|e;return t&&(s|=8388608),s>>>0}static fromScriptNum(e,t=!1,r){if(void 0!==r&&e.length>r)throw Error("script number overflow");if(0===e.length)return new m(0n);if(t&&(127&e[e.length-1])==0&&(e.length<=1||(128&e[e.length-2])==0))throw Error("non-minimally encoded script number");return m.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){let t;this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");let r=this.umod(e)._magnitude,i=e._magnitude,n=1n,a=0n,s=e._magnitude;for(;r>1n&&i>1n;){let e=0;for(;(r>>BigInt(e)&1n)===0n;)e++;if(e>0){r>>=BigInt(e);for(let t=0;t<e;++t)(1n&n)!==0n&&(n+=s),n>>=1n}let t=0;for(;(i>>BigInt(t)&1n)===0n;)t++;if(t>0){i>>=BigInt(t);for(let e=0;e<t;++e)(1n&a)!==0n&&(a+=s),a>>=1n}r>=i?(r-=i,n-=a):(i-=r,a-=n)}if(1n===r)t=n;else if(1n===i)t=a;else if(0n===r&&1n===i)t=a;else if(0n===i&&1n===r)t=n;else throw Error("_invmp: GCD is not 1, inverse does not exist. aVal="+r+", bVal="+i);(t%=s)<0n&&(t+=s);let o=new m(0n);return o._initializeState(t,0),o}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}class w{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new m(t,16),this.n=this.p.bitLength(),this.k=new m(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){let e=new m(BigInt(0)),t=Math.ceil(this.n/m.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){let t;do this.split(e,this.tmp),this.imulK(e),e.iadd(this.tmp),t=e.bitLength();while(t>this.n);let r=t<this.n?-1:e.ucmp(this.p);return 0===r?e.words=[0]:r>0&&e.isub(this.p),e.strip(),e}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class v extends w{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){let r=e.words,i=e.length,n=Math.min(i,9),a=Array(n+ +(i>9)).fill(0);for(let e=0;e<n;e++)a[e]=r[e];let s=n;if(i<=9){let r=Array(s);for(let e=0;e<s;++e)r[e]=a[e];t.words=r,e.words=[0];return}let o=r[9];a[s++]=4194303&o;let c=Array(s);for(let e=0;e<s;++e)c[e]=a[e];t.words=c;let l=Array(Math.max(1,i-9)).fill(0),h=0;for(let e=10;e<i;e++){let t=0|r[e];h<l.length&&(l[h++]=(4194303&t)<<4|o>>>22),o=t}o>>>=22,h<l.length?l[h++]=o:0!==o&&l.length;let u=Array(h);for(let e=0;e<h;++e)u[e]=l[e];e.words=u}imulK(e){let t=e.words,r=e.length,i=r+2,n=Array(i).fill(0);for(let e=0;e<r;e++)n[e]=t[e];let a=0;for(let e=0;e<i;e++){let t=0|n[e];a+=977*t,n[e]=0x3ffffff&a,a=64*t+(a/0x4000000|0)}return e.words=n,e}}class I{prime;m;constructor(e){if("k256"===e){let e=new v;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert((e.negative|t.negative)==0,"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(m.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);let r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r.forceRed(this)}iadd(e,t){this.verify2(e,t);let r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r}sub(e,t){this.verify2(e,t);let r=e.sub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r.forceRed(this)}isub(e,t){this.verify2(e,t);let r=e.isub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();let t=this.m.andln(3);if(this.assert(t%2==1),3===t){let t=this.m.add(new m(1)).iushrn(2);return this.pow(e,t)}let r=this.m.subn(1),i=0;for(;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);this.assert(!r.isZero());let n=new m(1).toRed(this),a=n.redNeg(),s=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new m(2*o*o).toRed(this);for(;0!==this.pow(c,s).cmp(a);)c.redIAdd(a);let l=this.pow(c,r),h=this.pow(e,r.addn(1).iushrn(1)),u=this.pow(e,r),d=i;for(;0!==u.cmp(n);){let e=u,t=0;for(;0!==e.cmp(n);t++)e=e.redSqr();this.assert(t<d);let r=this.pow(l,new m(1).iushln(d-t-1));h=h.redMul(r),l=r.redSqr(),u=u.redMul(l),d=t}return h}invm(e){let t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(t.isZero())return new m(1).toRed(this);if(0===t.cmpn(1))return e.clone();let r=Array(16);r[0]=new m(1).toRed(this),r[1]=e;let i=2;for(;i<r.length;i++)r[i]=this.mul(r[i-1],e);let n=r[0],a=0,s=0,o=t.bitLength()%26;for(0===o&&(o=26),i=t.length-1;i>=0;i--){let e=t.words[i];for(let t=o-1;t>=0;t--){let o=e>>t&1;if(n!==r[0]&&(n=this.sqr(n)),0===o&&0===a){s=0;continue}a<<=1,a|=o,(4==++s||0===i&&0===t)&&(n=this.mul(n,r[a]),s=0,a=0)}o=26}return n}convertTo(e){let t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){let t=e.clone();return t.red=null,t}}class k extends I{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new m(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){let t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;let r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):0>n.cmpn(0)&&(a=n.iadd(this.m)),a.forceRed(this)}mul(e,t){if(e.isZero()||t.isZero())return new m(0).forceRed(this);let r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),n=r.isub(i).iushrn(this.shift),a=n;return n.cmp(this.m)>=0?a=n.isub(this.m):0>n.cmpn(0)&&(a=n.iadd(this.m)),a.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}class S{curve;type;precomputed;constructor(e){this.curve=new tA,this.type=e,this.precomputed=null}}class x extends S{x;y;z;zOne;constructor(e,t,r){super("jacobian"),null===e&&null===t&&null===r?(this.x=this.curve.one,this.y=this.curve.one,this.z=new m(0)):(m.isBN(e)||(e=new m(e,16)),this.x=e,m.isBN(t)||(t=new m(t,16)),this.y=t,m.isBN(r)||(r=new m(r,16)),this.z=r),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new m(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new tO(null,null);let e=this.z.redInvm(),t=e.redSqr();return new tO(this.x.redMul(t),this.y.redMul(t).redMul(e))}neg(){return new x(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;let t=e.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(t),n=e.x.redMul(r),a=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(r.redMul(this.z)),o=i.redSub(n),c=a.redSub(s);if(0===o.cmpn(0))if(0!==c.cmpn(0))return new x(null,null,null);else return this.dbl();let l=o.redSqr(),h=l.redMul(o),u=i.redMul(l),d=c.redSqr().redIAdd(h).redISub(u).redISub(u),f=c.redMul(u.redISub(d)).redISub(a.redMul(h));return new x(d,f,this.z.redMul(e.z).redMul(o))}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw Error("Point coordinates cannot be null");let t=this.z.redSqr(),r=this.x,i=e.x.redMul(t),n=this.y,a=e.y.redMul(t).redMul(this.z),s=r.redSub(i),o=n.redSub(a);if(0===s.cmpn(0))if(0!==o.cmpn(0))return new x(null,null,null);else return this.dbl();let c=s.redSqr(),l=c.redMul(s),h=r.redMul(c),u=o.redSqr().redIAdd(l).redISub(h).redISub(h),d=o.redMul(h.redISub(u)).redISub(n.redMul(l));return new x(u,d,this.z.redMul(s))}dblp(e){if(0===e||this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}dbl(){let e,t,r;if(this.isInfinity())return this;if(this.zOne){let i=this.x.redSqr(),n=this.y.redSqr(),a=n.redSqr(),s=this.x.redAdd(n).redSqr().redISub(i).redISub(a);s=s.redIAdd(s);let o=i.redAdd(i).redIAdd(i),c=o.redSqr().redISub(s).redISub(s),l=a.redIAdd(a);l=(l=l.redIAdd(l)).redIAdd(l),e=c,t=o.redMul(s.redISub(c)).redISub(l),r=this.y.redAdd(this.y)}else{let i=this.x.redSqr(),n=this.y.redSqr(),a=n.redSqr(),s=this.x.redAdd(n).redSqr().redISub(i).redISub(a);s=s.redIAdd(s);let o=i.redAdd(i).redIAdd(i),c=o.redSqr(),l=a.redIAdd(a);l=(l=l.redIAdd(l)).redIAdd(l),e=c.redISub(s).redISub(s),t=o.redMul(s.redISub(e)).redISub(l),r=(r=this.y.redMul(this.z)).redIAdd(r)}return new x(e,t,r)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e||this.isInfinity()&&e.isInfinity())return!0;if(this.isInfinity()!==e.isInfinity())return!1;let t=this.z.redSqr(),r=e.z.redSqr();if(0!==this.x.redMul(r).redISub(e.x.redMul(t)).cmpn(0))return!1;let i=t.redMul(this.z),n=r.redMul(e.z);return 0===this.y.redMul(n).redISub(e.y.redMul(i)).cmpn(0)}eqXToP(e){let t=this.z.redSqr(),r=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(r))return!0;let i=e.clone();if(null===this.curve||null==this.curve.redN)throw Error("Curve or redN is not initialized.");let n=this.curve.redN.redMul(t);for(;0>i.cmp(this.curve.p)&&(i.iadd(this.curve.n),!(i.cmp(this.curve.p)>=0));)if(r.redIAdd(n),0===this.x.cmp(r))return!0;return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}let E=/^[0-9a-fA-F]*$/;function P(e){if("string"!=typeof e)throw TypeError("Invalid hex string");if(0!==e.length&&!E.test(e))throw Error("Invalid hex string")}let N=(e,t="Hash assertion failed")=>{if(!e)throw Error(t)};class O{pending;pendingTotal;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,r,i){this.pending=null,this.pendingTotal=0,this.blockSize=e,this.outSize=t,this.hmacStrength=r,this.padLength=i/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw Error("Not implemented")}_digest(){throw Error("Not implemented")}_digestHex(){throw Error("Not implemented")}update(e,t){if(e=A(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){let t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,r,i){let n=r-0;N(n%4==0);let a=Array(n/4);for(let r=0,n=t;r<a.length;r++,n+=4){let t;t="big"===i?e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3]:e[n+3]<<24|e[n+2]<<16|e[n+1]<<8|e[n],a[r]=t>>>0}return a}(e,0,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),N(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),N(null===this.pending),this._digestHex()}_pad(){let e,t=this.pendingTotal;if(!Number.isSafeInteger(t)||t<0)throw Error("Message too long for this hash function");let r=this._delta8,i=r-(t+this.padLength)%r,n=Array(i+this.padLength);for(e=1,n[0]=128;e<i;e++)n[e]=0;let a=this.padLength,s=1n<<BigInt(8*a),o=8n*BigInt(t);if(o>=s)throw Error("Message too long for this hash function");if("big"===this.endian){let t=Array(a);for(let e=a-1;e>=0;e--)t[e]=Number(255n&o),o>>=8n;for(let r=0;r<a;r++)n[e++]=t[r]}else for(let t=0;t<a;t++)n[e++]=Number(255n&o),o>>=8n;return n}}function A(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];let r=[];if("string"==typeof e)if("hex"!==t){let t=0;for(let a=0;a<e.length;a++){let s=e.charCodeAt(a);if(s<128)r[t++]=s;else if(s<2048)r[t++]=s>>6|192,r[t++]=63&s|128;else{var i,n;(i=e,n=a,(64512&i.charCodeAt(n))!=55296||n<0||n+1>=i.length?1:(64512&i.charCodeAt(n+1))!=56320)?r[t++]=s>>12|224:(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++a)),r[t++]=s>>18|240,r[t++]=s>>12&63|128),r[t++]=s>>6&63|128,r[t++]=63&s|128}}}else{P(e),e=function(e){if(P(e),0===e.length)return"";let t=e.toLowerCase();return t.length%2!=0&&(t="0"+t),t}(e);for(let t=0;t<e.length;t+=2)r.push(parseInt(e[t]+e[t+1],16))}else for(let t=0;t<e.length;t++)r[t]=0|e[t];return r}function _(e){return eW(e)}function T(e,t){let r="";for(let i=0;i<e.length;i++){let n=e[i];"little"===t&&(n=eW(n)),r+=function(e){if(7===e.length)return"0"+e;if(6===e.length)return"00"+e;if(5===e.length)return"000"+e;if(4===e.length)return"0000"+e;if(3===e.length)return"00000"+e;else if(2===e.length)return"000000"+e;else if(1===e.length)return"0000000"+e;else return e}(n.toString(16))}return r}function C(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function R(e,t){let r=Array(4*e.length);for(let i=0,n=0;i<e.length;i++,n+=4){let a=e[i];"big"===t?(r[n]=a>>>24,r[n+1]=a>>>16&255,r[n+2]=a>>>8&255,r[n+3]=255&a):(r[n+3]=a>>>24,r[n+2]=a>>>16&255,r[n+1]=a>>>8&255,r[n]=255&a)}return r}function B(e,t){return e>>>t|e<<32-t}function V(e,t){return e<<t|e>>>32-t}function D(e,t){return e+t>>>0}let U=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],F=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],L=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],K=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function H(e,t,r,i){return e<=15?t^r^i:e<=31?t&r|~t&i:e<=47?(t|~r)^i:e<=63?t&i|r&~i:t^(r|~i)}class q extends O{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.endian="little"}_update(e,t){var r,i,n,a,s,o;let c,l=this.h[0],h=this.h[1],u=this.h[2],d=this.h[3],f=this.h[4],p=l,g=h,b=u,y=d,m=f;for(let w=0;w<80;w++){c=D(V((r=l,i=H(w,h,u,d),r+i+e[U[w]+t]+((s=w)<=15?0:s<=31?0x5a827999:s<=47?0x6ed9eba1:s<=63?0x8f1bbcdc:0xa953fd4e)>>>0),L[w]),f),l=f,f=d,d=V(u,10),u=h,h=c,c=D(V((n=p,a=H(79-w,g,b,y),n+a+e[F[w]+t]+((o=w)<=15?0x50a28be6:o<=31?0x5c4dd124:o<=47?0x6d703ef3:0x7a6d76e9*!!(o<=63))>>>0),K[w]),m),p=m,m=y,y=V(b,10),b=g,g=c}c=this.h[1]+u+y>>>0,this.h[1]=this.h[2]+d+m>>>0,this.h[2]=this.h[3]+f+p>>>0,this.h[3]=this.h[4]+l+g>>>0,this.h[4]=this.h[0]+h+b>>>0,this.h[0]=c}_digest(){return R(this.h,"little")}_digestHex(){return T(this.h,"little")}}class M{h;constructor(){this.h=new eR}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(A(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return C(this.h.digest())}}class $ extends O{h;W;k;constructor(){super(512,160,80,64),this.k=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],this.h=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],this.W=Array(80)}_update(e,t){let r,i=this.W;for(void 0===t&&(t=0),r=0;r<16;r++)i[r]=e[t+r];for(;r<i.length;r++)i[r]=V(i[r-3]^i[r-8]^i[r-14]^i[r-16],1);let n=this.h[0],a=this.h[1],s=this.h[2],o=this.h[3],c=this.h[4];for(r=0;r<i.length;r++){var l,h,u,d,f,p,g,b,y;let e=~~(r/20),t=(d=V(n,5),l=a,h=s,u=o,f=0===e?(p=l)&h^~p&u:1===e||3===e?l^h^u:2===e?(g=l)&(b=h)^g&(y=u)^b&y:0,d+f+c+i[r]+this.k[e]>>>0);c=o,o=s,s=V(a,30),a=n,n=t}this.h[0]=D(this.h[0],n),this.h[1]=D(this.h[1],a),this.h[2]=D(this.h[2],s),this.h[3]=D(this.h[3],o),this.h[4]=D(this.h[4],c)}_digest(){return R(this.h,"big")}_digestHex(){return T(this.h,"big")}}class z{h;constructor(){this.h=new eH}update(e,t){let r=Uint8Array.from(A(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return C(this.h.digest())}}class W{h;blockSize=64;outSize=32;constructor(e){let t=e instanceof Uint8Array?e:Uint8Array.from(A(e,"string"==typeof e?"hex":void 0));this.h=new eM(eB,t)}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(A(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return C(this.h.digest())}}class j{inner;outer;blockSize=64;constructor(e){let t;for((e=A(e,"hex")).length>this.blockSize&&(e=new $().update(e).digest()),t=e.length;t<this.blockSize;t++)e.push(0);for(t=0;t<e.length;t++)e[t]^=54;for(t=0,this.inner=new $().update(e);t<e.length;t++)e[t]^=106;this.outer=new $().update(e)}update(e,t){return this.inner.update(e,t),this}digest(){return this.outer.update(this.inner.digest()),this.outer.digest()}digestHex(){return this.outer.update(this.inner.digest()),this.outer.digestHex()}}class G{h;blockSize=128;outSize=32;constructor(e){let t=e instanceof Uint8Array?e:Uint8Array.from(A(e,"string"==typeof e?"hex":void 0));this.h=new eM(eq,t)}update(e,t){let r=e instanceof Uint8Array?e:Uint8Array.from(A(e,t));return this.h.update(r),this}digest(){return Array.from(this.h.digest())}digestHex(){return C(this.h.digest())}}let X=(e,t)=>new q().update(e,t).digest(),J=(e,t)=>new $().update(e,t).digest(),Y=(e,t)=>new M().update(e,t).digest(),Z=(e,t)=>new z().update(e,t).digest(),Q=(e,t)=>{let r=new M().update(e,t).digest();return new M().update(r).digest()},ee=(e,t)=>{let r=new M().update(e,t).digest();return new q().update(r).digest()},et=(e,t,r)=>new W(e).update(t,r).digest(),er=(e,t,r)=>new G(e).update(t,r).digest();function ei(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`positive integer expected, got ${e}`)}function en(e,...t){if(!(e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length)){let r=t.join(",");throw Error(`Uint8Array expected of length ${r}, got length=${e.length}`)}}function ea(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");ei(e.outputLen),ei(e.blockLen)}function es(e,t=!0){if(!0===e.destroyed)throw Error("Hash instance has been destroyed");if(t&&!0===e.finished)throw Error("Hash#digest() has already been called")}function eo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ec(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function el(e){return"string"==typeof e&&(e=eh(e)),en(e),e}function eh(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function eu(e){return"string"==typeof e&&(e=eh(e)),en(e),e}class ed{}function ef(e){let t=t=>e().update(el(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}let ep=BigInt(0x100000000-1),eg=BigInt(32),eb=(e,t,r)=>e>>>r,ey=(e,t,r)=>e<<32-r|t>>>r,em=(e,t,r)=>e>>>r|t<<32-r,ew=(e,t,r)=>e<<32-r|t>>>r,ev=(e,t,r)=>e<<64-r|t>>>r-32,eI=(e,t,r)=>e>>>r-32|t<<64-r;function ek(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/0x100000000|0)|0,l:0|n}}let eS=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),ex=(e,t,r,i)=>t+r+i+(e/0x100000000|0)|0,eE=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),eP=(e,t,r,i,n)=>t+r+i+n+(e/0x100000000|0)|0,eN=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),eO=(e,t,r,i,n,a)=>t+r+i+n+a+(e/0x100000000|0)|0;class eA extends ed{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ec(this.buffer)}update(e){es(this),en(e=el(e));let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let a=0;a<n;){let s=Math.min(i-this.pos,n-a);if(s===i){let t=ec(e);for(;i<=n-a;a+=i)this.process(t,a);continue}r.set(e.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){es(this);en(e);let t=this.outputLen;if(e.length<t)throw Error(`digestInto() expects output buffer of length at least ${t}`);this.finished=!0;let{buffer:r,view:i,blockLen:n,isLE:a}=this,{pos:s}=this;r[s++]=128,eo(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(i,0),s=0);for(let e=s;e<n;e++)r[e]=0;(function(e,t,r,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,i);let n=BigInt(32),a=BigInt(0xffffffff),s=Number(r>>n&a),o=Number(r&a),c=4*!!i,l=4*!i;e.setUint32(t+c,s,i),e.setUint32(t+l,o,i)})(i,n-8,BigInt(8*this.length),a),this.process(i,0);let o=ec(e),c=this.outputLen;if(c%4!=0)throw Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,h=this.get();if(l>h.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)o.setUint32(4*e,h[e],a)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:r,length:i,finished:n,destroyed:a,pos:s}=this;return e.destroyed=a,e.finished=n,e.length=i,e.pos=s,i%t!=0&&e.buffer.set(r),e}clone(){return this._cloneInto()}}let e_=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),eT=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),eC=new Uint32Array(64);class eR extends eA{A=0|e_[0];B=0|e_[1];C=0|e_[2];D=0|e_[3];E=0|e_[4];F=0|e_[5];G=0|e_[6];H=0|e_[7];constructor(e=32){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:a,G:s,H:o}=this;return[e,t,r,i,n,a,s,o]}set(e,t,r,i,n,a,s,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|i,this.E=0|n,this.F=0|a,this.G=0|s,this.H=0|o}process(e,t){var r,i,n,a,s,o,c,l,h;for(let r=0;r<16;r++,t+=4)eC[r]=e.getUint32(t);for(let e=16;e<64;e++){let t=eC[e-15],r=eC[e-2],i=B(t,7)^B(t,18)^t>>>3,n=B(r,17)^B(r,19)^r>>>10;eC[e]=D(D(i,eC[e-7]),D(n,eC[e-16]))}let{A:u,B:d,C:f,D:p,E:g,F:b,G:y,H:m}=this;for(let e=0;e<64;e++){let t=(n=m,a=B(r=g,6)^B(r,11)^B(r,25),s=(i=g)&b^~i&y,n+a+s+eT[e]+eC[e]>>>0),w=D(B(o=u,2)^B(o,13)^B(o,22),(c=u)&(l=d)^c&(h=f)^l&h);m=y,y=b,b=g,g=D(p,t),p=f,f=d,d=u,u=D(t,w)}this.A=D(this.A,u),this.B=D(this.B,d),this.C=D(this.C,f),this.D=D(this.D,p),this.E=D(this.E,g),this.F=D(this.F,b),this.G=D(this.G,y),this.H=D(this.H,m)}roundClean(){eo(eC)}destroy(){eo(this.buffer),this.set(0,0,0,0,0,0,0,0)}}let eB=ef(()=>new eR),eV=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),eD=function(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let a=0;a<r;a++){let{h:r,l:s}=function(e,t=!1){return t?{h:Number(e&ep),l:Number(e>>eg&ep)}:{h:0|Number(e>>eg&ep),l:0|Number(e&ep)}}(e[a],t);i[a]=r,n[a]=s}return[i,n]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),eU=eD[0],eF=eD[1],eL=new Uint32Array(80),eK=new Uint32Array(80);class eH extends eA{Ah=0|eV[0];Al=0|eV[1];Bh=0|eV[2];Bl=0|eV[3];Ch=0|eV[4];Cl=0|eV[5];Dh=0|eV[6];Dl=0|eV[7];Eh=0|eV[8];El=0|eV[9];Fh=0|eV[10];Fl=0|eV[11];Gh=0|eV[12];Gl=0|eV[13];Hh=0|eV[14];Hl=0|eV[15];constructor(e=64){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:a,Dh:s,Dl:o,Eh:c,El:l,Fh:h,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,r,i,n,a,s,o,c,l,h,u,d,f,p,g]}set(e,t,r,i,n,a,s,o,c,l,h,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|i,this.Ch=0|n,this.Cl=0|a,this.Dh=0|s,this.Dl=0|o,this.Eh=0|c,this.El=0|l,this.Fh=0|h,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)eL[r]=e.getUint32(t),eK[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|eL[e-15],r=0|eK[e-15],i=em(t,r,1)^em(t,r,8)^eb(t,r,7),n=ew(t,r,1)^ew(t,r,8)^ey(t,r,7),a=0|eL[e-2],s=0|eK[e-2],o=em(a,s,19)^ev(a,s,61)^eb(a,s,6),c=eE(n,ew(a,s,19)^eI(a,s,61)^ey(a,s,6),eK[e-7],eK[e-16]),l=eP(c,i,o,eL[e-7],eL[e-16]);eL[e]=0|l,eK[e]=0|c}let{Ah:r,Al:i,Bh:n,Bl:a,Ch:s,Cl:o,Dh:c,Dl:l,Eh:h,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:b,Hl:y}=this;for(let e=0;e<80;e++){let t=em(h,u,14)^em(h,u,18)^ev(h,u,41),m=ew(h,u,14)^ew(h,u,18)^eI(h,u,41),w=h&d^~h&p,v=eN(y,m,u&f^~u&g,eF[e],eK[e]),I=eO(v,b,t,w,eU[e],eL[e]),k=0|v,S=em(r,i,28)^ev(r,i,34)^ev(r,i,39),x=ew(r,i,28)^eI(r,i,34)^eI(r,i,39),E=r&n^r&s^n&s,P=i&a^i&o^a&o;b=0|p,y=0|g,p=0|d,g=0|f,d=0|h,f=0|u,({h:h,l:u}=ek(0|c,0|l,0|I,0|k)),c=0|s,l=0|o,s=0|n,o=0|a,n=0|r,a=0|i;let N=eS(x,P,k);r=ex(N,S,E,I),i=0|N}({h:r,l:i}=ek(r,i,this.Ah,this.Al)),({h:n,l:a}=ek(n,a,this.Bh,this.Bl)),({h:s,l:o}=ek(s,o,this.Ch,this.Cl)),({h:c,l:l}=ek(c,l,this.Dh,this.Dl)),({h:h,l:u}=ek(h,u,this.Eh,this.El)),({h:d,l:f}=ek(d,f,this.Fh,this.Fl)),({h:p,l:g}=ek(p,g,this.Gh,this.Gl)),({h:b,l:y}=ek(b,y,this.Hh,this.Hl)),this.set(r,i,n,a,s,o,c,l,h,u,d,f,p,g,b,y)}roundClean(){eo(eL,eK)}destroy(){eo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let eq=ef(()=>new eH);class eM extends ed{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){super(),ea(e);let r=el(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?e.create().update(r).digest():r);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),eo(n)}update(e){return es(this),this.iHash.update(e),this}digestInto(e){es(this),en(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:i,destroyed:n,blockLen:a,outputLen:s}=this;return e.finished=i,e.destroyed=n,e.blockLen=a,e.outputLen=s,e.oHash=t._cloneInto(e.oHash??void 0),e.iHash=r._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let e$=(e,t,r)=>new eM(e,t).update(r).digest();function ez(e,t,r,i,n="sha512"){if("sha512"!==n)throw Error("Only sha512 is supported in this PBKDF2 implementation");try{let a=require("crypto");if("function"==typeof a.pbkdf2Sync){let s=Buffer.from(e),o=Buffer.from(t);return[...a.pbkdf2Sync(s,o,r,i,n)]}}catch{}return Array.from(function(e,t,r,i){let n;ea(e);let{c:a,dkLen:s}=Object.assign({dkLen:32},i);if(ei(a),ei(s),a<1)throw Error("iterations (c) should be >= 1");let o=eu(t),c=eu(r),l=new Uint8Array(s),h=e$.create(e,o),u=h._cloneInto().update(c),d=new Uint8Array(4),f=ec(d),p=new Uint8Array(h.outputLen);for(let e=1,t=0;t<s;e++,t+=h.outputLen){let r=l.subarray(t,t+h.outputLen);f.setInt32(0,e,!1),(n=u._cloneInto(n)).update(d).digestInto(p),r.set(p.subarray(0,r.length));for(let e=1;e<a;e++){h._cloneInto(n).update(p).digestInto(p);for(let e=0;e<r.length;e++)r[e]^=p[e]}}return h.destroy(),u.destroy(),null!=n&&n.destroy(),eo(p),l}(eq,Uint8Array.from(e),Uint8Array.from(t),{c:r,dkLen:i}))}function eW(e){return(e>>>24|e>>>8&65280|e<<8&0xff0000|(255&e)<<24)>>>0}e$.create=(e,t)=>new eM(e,t);let ej=(()=>{let e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);return t[0]=0x1020304,4===r[0]})();function eG(e){return ej?eW(e):e>>>0}let eX="undefined"!=typeof globalThis?globalThis.Buffer:void 0,eJ=null!=eX&&"function"==typeof eX.from,eY=e=>e.length%2==1?"0"+e:e,eZ="0123456789abcdef",eQ=Array(256);for(let e=0;e<256;e++)eQ[e]=eZ[e>>4&15]+eZ[15&e];let e0=e=>{if(eJ)return eX.from(e).toString("hex");if(0===e.length)return"";let t=Array(e.length);for(let r=0;r<e.length;r++)t[r]=eQ[255&e[r]];return t.join("")},e1=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,e=>0|e);switch(t){case"hex":return e8(e);case"base64":return e3(e);default:var r;return r=e,Array.from(new TextEncoder().encode(r))}},e2=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)e2[48+e]=e;for(let e=0;e<6;e++)e2[65+e]=10+e,e2[97+e]=10+e;let e8=e=>{P(e);let t=e.length%2==0?e:"0"+e;if(eJ)return Array.from(eX.from(t,"hex"));let r=Array(t.length/2),i=0;for(let e=0;e<t.length;e+=2){let n=e2[t.charCodeAt(e)],a=e2[t.charCodeAt(e+1)];r[i++]=n<<4|a}return r};function e3(e){if("string"!=typeof e)throw TypeError("msg must be a string");let t=e.trim().replace(/[\r\n\t\f\v ]+/g,""),r=(t=t.replace(/-/g,"+").replace(/_/g,"/")).indexOf("=");if(-1!==r){let e=t.slice(r);if(!/^={1,2}$/.test(e)||t.slice(0,r).includes("="))throw Error("Invalid base64 padding");t=t.slice(0,r)}let i=[],n=0,a=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e),s=-1;if(r>=65&&r<=90)s=r-65;else if(r>=97&&r<=122)s=r-97+26;else if(r>=48&&r<=57)s=r-48+52;else if(43===r)s=62;else if(47===r)s=63;else throw Error(`Invalid base64 character at index ${e}`);for(n=n<<6|s,a+=6;a>=8;)a-=8,i.push(n>>a&255),n&=(1<<a)-1}return i}let e4=e=>new TextDecoder().decode(new Uint8Array(e)),e6=(e,t)=>{switch(t){case"hex":return e0(e);case"utf8":return e4(e);default:return e}};function e5(e){let t,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="";for(t=0;t<e.length;t+=3){let n=e[t],a=t+1<e.length?e[t+1]:0,s=t+2<e.length?e[t+2]:0,o=n>>2,c=(3&n)<<4|a>>4,l=(15&a)<<2|s>>6,h=63&s;i+=r.charAt(o)+r.charAt(c),i+=t+1<e.length?r.charAt(l):"=",i+=t+2<e.length?r.charAt(h):"="}return i}let e7="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",e9=e=>{if(""===e||"string"!=typeof e)throw Error(`Expected base58 string but got “${e}”`);let t=e.match(/[IOl0]/gmu);if(null!==t)throw Error(`Invalid base58 character “${t.join("")}”`);let r=e.match(/^1+/gmu),i=null!==r?r[0].length:0,n=(e.length-i)*(Math.log(58)/Math.log(256))+1>>>0;return[...new Uint8Array([...new Uint8Array(i),...(e.match(/./gmu)??[]).map(e=>e7.indexOf(e)).reduce((e,t)=>e=e.map(e=>{let r=58*e+t;return t=r>>8,r}),new Uint8Array(n)).reverse().filter((e=>t=>e=e||t)(!1))])]},te=e=>{let t=Array(256).fill(-1);for(let e=0;e<e7.length;++e)t[e7.charCodeAt(e)]=e;let r=[];for(let i of e){let e=i;for(let i=0;i<r.length;++i){let n=(t[r[i]]<<8)+e;r[i]=e7.charCodeAt(n%58),e=n/58|0}for(;0!==e;)r.push(e7.charCodeAt(e%58)),e=e/58|0}for(let t of e)if(0!==t)break;else r.push(49);return r.reverse(),String.fromCharCode(...r)},tt=(e,t=[0])=>{let r=Q([...t,...e]);return te(r=[...t,...e,...r.slice(0,4)])},tr=(e,t,r=1)=>{let i=e9(e),n=i.slice(0,r),a=i.slice(r,-4),s=[...n,...a];return s=Q(s),i.slice(-4).forEach((e,t)=>{if(e!==s[t])throw Error("Invalid checksum")}),"hex"===t&&(n=e0(n),a=e0(a)),{prefix:n,data:a}};class ti{bufs;length;constructor(e){for(let t of(this.bufs=void 0!==e?e:[],this.length=0,this.bufs))this.length+=t.length}getLength(){return this.length}toUint8Array(){let e=new Uint8Array(this.length),t=0;for(let r of this.bufs)e.set(r,t),t+=r.length;return e}toArray(){let e=Array(this.length),t=0;for(let r of this.bufs)if(r instanceof Uint8Array)for(let i=0;i<r.length;i++)e[t++]=r[i];else for(let i=0;i<r.length;i++)e[t++]=r[i];return e}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){let t=Array(e.length);for(let r=0;r<t.length;r++)t[r]=e[e.length-1-r];return this.write(t)}writeUInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeInt8(e){let t=[,];return t[0]=255&e,this.write(t),this}writeUInt16BE(e){return this.write([e>>8&255,255&e])}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){return this.write([255&e,e>>8&255])}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){return this.write([e>>24&255,e>>16&255,e>>8&255,255&e])}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){return this.write([255&e,e>>8&255,e>>16&255,e>>24&255])}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){let t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){let t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){let t=new m(e).toArray("be",8);return this.writeReverse(t),this}writeVarIntNum(e){let t=ti.varIntNum(e);return this.write(t),this}writeVarIntBn(e){let t=ti.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<0)return this.varIntBn(new m(e));if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<0x100000000)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{let r=0|e,i=0|Math.floor(e/0x100000000);t=[255,255&r,r>>8&255,r>>16&255,r>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]}return t}static varIntBn(e){let t;if(e.isNeg()&&(e=e.add(to)),e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){let r=e.toNumber();t=[253,255&r,r>>8&255]}else if(e.lt(new m(0x100000000))){let r=e.toNumber();t=[254,255&r,r>>8&255,r>>16&255,r>>24&255]}else{let r=new ti;r.writeUInt8(255),r.writeUInt64LEBn(e),t=r.toArray()}return t}}class tn{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){let t=this.pos,r=this.pos+e;return this.pos=r,this.bin.slice(t,r)}readReverse(e=this.length){let t=Array(e);for(let r=0;r<e;r++)t[r]=this.bin[this.pos+e-1-r];return this.pos+=e,t}readUInt8(){let e=this.bin[this.pos];return this.pos+=1,e}readInt8(){let e=this.bin[this.pos];return this.pos+=1,(128&e)!=0?e-256:e}readUInt16BE(){let e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){let e=this.readUInt16BE();return(32768&e)!=0?e-65536:e}readUInt16LE(){let e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){let e=this.readUInt16LE();return(32768&e)!=0?e-65536:e}readUInt32BE(){let e=0x1000000*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){let e=this.readUInt32BE();return(0x80000000&e)!=0?e-0x100000000:e}readUInt32LE(){let e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){let e=this.readUInt32LE();return(0x80000000&e)!=0?e-0x100000000:e}readUInt64BEBn(){let e=new m(this.bin.slice(this.pos,this.pos+8));return this.pos=this.pos+8,e}readUInt64LEBn(){return new m(this.readReverse(8))}readInt64LEBn(){let e=new m(this.readReverse(8));return e.gte(ts)&&(e=e.sub(to)),e}readVarIntNum(e=!0){let t,r=this.readUInt8();switch(r){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if((t=e?this.readInt64LEBn():this.readUInt64LEBn()).lte(new m(2).pow(new m(53))))return t.toNumber();throw Error("number too large to retain precision - use readVarIntBn");default:return r}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){let e=this.readUInt8();switch(e){case 253:return new m(this.readUInt16LE());case 254:return new m(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new m(e)}}}let ta=e=>{if(0===e.length)return e;let t=e[e.length-1];if((127&t)!=0)return e;if(1===e.length)return[];if((128&e[e.length-2])!=0)return e;for(let r=e.length-1;r>0;r--)if(0!==e[r-1])if((128&e[r-1])!=0)return e[r]=t,e.slice(0,r+1);else return e[r-1]|=t,e.slice(0,r);return[]},ts=new m(2).pow(new m(63)),to=new m(2).pow(new m(64));function tc(e,t="Expected a valid value, but got undefined or null."){if(null==e)throw Error(t);return e}function tl(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}let th=(1n<<256n)-1n;function tu(e){let t=e>>256n;return t=(e=(e&th)+(t<<32n)+977n*t)>>256n,(e=(e&th)+(t<<32n)+977n*t)>=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn&&(e-=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),e}let td=e=>tu((e%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn)%0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn),tf=(e,t)=>e>=t?e-t:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-(t-e),tp=(e,t)=>tu(e*t),tg=(e,t)=>tu(e+t),tb=e=>{let t=1n,r=0n,i=td(e),n=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;for(;i>1n;){let e=n/i;[t,r]=[r-t*e,t],[i,n]=[n-i*e,i]}return td(t)},ty=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn+1n>>2n,tm=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),tw=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),tv=new Map,tI=e=>{let{X:t,Y:r,Z:i}=e;if(0n===r)return{X:0n,Y:1n,Z:0n};let n=tp(r,r),a=tp(4n,tp(t,n)),s=tp(3n,tp(t,t)),o=tf(tp(s,s),tp(2n,a)),c=tf(tp(s,tf(a,o)),tp(8n,tp(n,n)));return{X:o,Y:c,Z:tp(2n,tp(r,i))}},tk=(e,t)=>{if(0n===e.Z)return t;if(0n===t.Z)return e;let r=tp(e.Z,e.Z),i=tp(t.Z,t.Z),n=tp(e.X,i),a=tp(t.X,r),s=tp(e.Y,tp(i,t.Z)),o=tp(t.Y,tp(r,e.Z)),c=tf(a,n),l=tf(o,s);if(0n===c)return 0n===l?tI(e):{X:0n,Y:1n,Z:0n};let h=tp(c,c),u=tp(c,h),d=tp(n,h),f=tf(tf(tp(l,l),u),tp(2n,d)),p=tf(tp(l,tf(d,f)),tp(s,u));return{X:f,Y:p,Z:tp(c,tp(e.Z,t.Z))}},tS=e=>0n===e.Z?e:{X:e.X,Y:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn-e.Y,Z:e.Z},tx=(e,t,r=5)=>{let i,n=`${r}:${t.x.toString(16)}:${t.y.toString(16)}`,a=tv.get(n);if(void 0===a){let e=1<<r-1;a=Array(e),i={X:t.x,Y:t.y,Z:1n},a[0]=i;let s=tI(i);for(let t=1;t<e;t++)a[t]=tk(a[t-1],s);tv.set(n,a)}else i=a[0];let s=[],o=1n<<BigInt(r),c=o>>1n,l=e;for(;l>0n;)if((1n&l)===0n)s.push(0),l>>=1n;else{let e=l&o-1n;e>c&&(e-=o),s.push(Number(e)),l-=e,l>>=1n}let h={X:0n,Y:1n,Z:0n};for(let e=s.length-1;e>=0;e--){h=tI(h);let t=s[e];if(0!==t){let e=Math.abs(t)>>1;h=tk(h,t>0?a[e]:tS(a[e]))}}return h},tE=e=>{let t=e%0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;return t<0n&&(t+=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n),t},tP=(e,t)=>tE(e*t),tN=e=>{let t=1n,r=0n,i=tE(e),n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;for(;i>1n;){let e=n/i;[t,r]=[r-t*e,t],[i,n]=[n-i*e,i]}return tE(t)};class tO extends S{x;y;inf;static _assertOnCurve(e){if(!e.validate())throw Error("Invalid point");return e}static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e[e.length-1]%2!=0)throw Error("Point string value is wrong length")}else if(7===e[0]&&e[e.length-1]%2!=1)throw Error("Point string value is wrong length");let t=new tO(e.slice(1,33),e.slice(33,65));return tO._assertOnCurve(t)}if((2===e[0]||3===e[0])&&e.length-1==32)return tO._assertOnCurve(tO.fromX(e.slice(1,33),3===e[0]));throw Error("Unknown point format")}static fromString(e){let t=e1(e,"hex");return tO._assertOnCurve(tO.fromDER(t))}static fromX(e,t){let r,i=m.isBN(e)?BigInt("0x"+e.toString(16)):"string"==typeof e?BigInt("0x"+e):Array.isArray(e)?BigInt("0x"+e0(e)):BigInt(e),n=(e=>{let t=((e,t)=>{let r=1n;for(e=td(e);t>0n;)(1n&t)!==0n&&(r=tp(r,e)),e=tp(e,e),t>>=1n;return r})(e,ty);return tp(t,t)!==td(e)?null:t})(tg(tp(tp(r=i=td(i),r),i),7n));if(null===n)throw Error("Invalid point");let a=n;(1n&a)!==(t?1n:0n)&&(a=tf(0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,a));let s=new m(i.toString(16),16),o=new m(a.toString(16),16);return tO._assertOnCurve(new tO(s,o))}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));let r=new tO(e[0],e[1],t);if(r=tO._assertOnCurve(r),"object"!=typeof e[2]||null===e[2])return r;let i=e[2],n=e=>{let r=new tO(e[0],e[1],t);return tO._assertOnCurve(r)};return r.precomputed={beta:null,doubles:"object"==typeof i.doubles&&null!==i.doubles?{step:i.doubles.step,points:[r].concat(i.doubles.points.map(n))}:void 0,naf:"object"==typeof i.naf&&null!==i.naf?{wnd:i.naf.wnd,points:[r].concat(i.naf.points.map(n))}:void 0},r}constructor(e,t,r=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(m.isBN(e)||(e=new m(e,16)),this.x=e,m.isBN(t)||(t=new m(t,16)),this.y=t,r&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{let e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16)),r=tp(t,t),i=tg(tp(tp(e,e),e),7n);return r===i}catch{return!1}}encode(e=!0,t){let r;if(this.inf)return"hex"===t?"00":[0];let i=this.curve.p.byteLength(),n=this.getX().toArray("be",i);return(r=e?[this.getY().isEven()?2:3].concat(n):[4].concat(n,this.getY().toArray("be",i)),"hex"!==t)?r:e0(r)}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null!=this.precomputed.doubles?{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)}:void 0,naf:null!=this.precomputed.naf?{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}:void 0}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e)||this.x?.cmp(e.x??new m(0))===0)return new tO(null,null);let t=tk({X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},{X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:1n});if(0n===t.Z)return new tO(null,null);let r=tb(t.Z),i=tp(r,r),n=tp(t.X,i),a=tp(t.Y,tp(i,r));return new tO(n.toString(16),a.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");let e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));if(0n===t)return new tO(null,null);let r=tI({X:e,Y:t,Z:1n}),i=tb(r.Z),n=tp(i,i),a=tp(r.X,n),s=tp(r.Y,tp(n,i));return new tO(a.toString(16),s.toString(16))}getX(){return(this.x??new m(0)).fromRed()}getY(){return(this.y??new m(0)).fromRed()}mul(e){let t,r;if(m.isBN(e)||(e=new m(e,16)),this.inf)return this;let i=BigInt("0x"+e.toString(16)),n=i<0n;if(n&&(i=-i),0n===(i=td(i)))return new tO(null,null);if(null===this.x||null===this.y)throw Error("Point coordinates cannot be null");this===this.curve.g?(t=tm,r=tw):(t=BigInt("0x"+this.x.fromRed().toString(16)),r=BigInt("0x"+this.y.fromRed().toString(16)));let a=tx(i,{x:t,y:r});if(0n===a.Z)return new tO(null,null);let s=tb(a.Z),o=tp(s,s),c=tp(a.X,o),l=tp(a.Y,tp(o,s)),h=new tO(new m(c.toString(16),16),new m(l.toString(16),16));return n?h.neg():h}mulAdd(e,t,r){return this._endoWnafMulAdd([this,t],[e,r])}jmulAdd(e,t,r){return this._endoWnafMulAdd([this,t],[e,r],!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new m(0)).cmp(e.x??new m(0))&&0===(this.y??new m(0)).cmp(e.y??new m(0)))}neg(e){if(this.inf)return this;let t=new tO(this.x,(this.y??new m(0)).redNeg());if(!0===e&&null!=this.precomputed){let e=this.precomputed;t.precomputed={naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(e=>e.neg())}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(e=>e.neg())}:void 0,beta:void 0}}return t}dblp(e){let t=this;for(let r=0;r<e;r++)t=t.dbl();return t}toJ(){return this.inf?new x(null,null,null):new x(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;let e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;let t=new tO((this.x??new m(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){let r=this.curve,i=e=>{if(null===e.x)throw Error("p.x is null");if(void 0===r.endo||null===r.endo)throw Error("curve.endo is undefined");return new tO(e.x.redMul(r.endo.beta),e.y)};e.beta=t,t.precomputed={beta:null,naf:null!=e.naf?{wnd:e.naf.wnd,points:e.naf.points.map(i)}:void 0,doubles:null!=e.doubles?{step:e.doubles.step,points:e.doubles.points.map(i)}:void 0}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw Error("_fixedNafMul requires precomputed values for the point");let t=this._getDoubles(),r=this.curve.getNAF(e,1,this.curve._bitLength),i=(1<<t.step+1)-(t.step%2==0?2:1);i/=3;let n=[];for(let e=0;e<r.length;e+=t.step){let i=0;for(let n=e+t.step-1;n>=e;n--)i=(i<<1)+r[n];n.push(i)}let a=new x(null,null,null),s=new x(null,null,null);for(let e=i;e>0;e--){for(let r=0;r<n.length;r++){let i=n[r];i===e?s=s.mixedAdd(t.points[r]):i===-e&&(s=s.mixedAdd(t.points[r].neg()))}a=a.add(s)}return a.toP()}_wnafMulAdd(e,t,r,i,n){let a=this.curve._wnafT1.map(e=>e.toNumber()),s=this.curve._wnafT2.map(()=>[]),o=this.curve._wnafT3.map(()=>[]),c=0;for(let r=0;r<i;r++){let i=t[r]._getNAFPoints(e);a[r]=i.wnd,s[r]=i.points}for(let e=i-1;e>=1;e-=2){let i=e-1,n=e;if(1!==a[i]||1!==a[n]){o[i]=this.curve.getNAF(r[i],a[i],this.curve._bitLength),o[n]=this.curve.getNAF(r[n],a[n],this.curve._bitLength),c=Math.max(o[i].length,c),c=Math.max(o[n].length,c);continue}let l=[t[i],null,null,t[n]];0===(t[i].y??new m(0)).cmp(t[n].y??new m(0))?(l[1]=t[i].add(t[n]),l[2]=t[i].toJ().mixedAdd(t[n].neg())):0===(t[i].y??new m(0)).cmp((t[n].y??new m(0)).redNeg())?(l[1]=t[i].toJ().mixedAdd(t[n]),l[2]=t[i].add(t[n].neg())):(l[1]=t[i].toJ().mixedAdd(t[n]),l[2]=t[i].toJ().mixedAdd(t[n].neg()));let h=[-3,-1,-5,-7,0,7,5,1,3],u=this.curve.getJSF(r[i],r[n]);c=Math.max(u[0].length,c),o[i]=Array(c),o[n]=Array(c);for(let e=0;e<c;e++){let t=0|u[0][e],r=0|u[1][e];o[i][e]=h[(t+1)*3+(r+1)],o[n][e]=0,s[i]=l}}let l=new x(null,null,null),h=this.curve._wnafT4;for(let e=c;e>=0;e--){let t=0;for(;e>=0;){let r=!0;for(let t=0;t<i;t++)h[t]=new m("number"==typeof o[t][e]?o[t][e]:0),h[t].isZero()||(r=!1);if(!r)break;t++,e--}if(e>=0&&t++,l=l.dblp(t),e<0)break;let r=new m(1),n=new m(2);for(let e=0;e<i;e++){let t,i=h[e];0!==i.cmpn(0)&&(l="affine"===(t=i.isNeg()?s[e][i.neg().sub(r).div(n).toNumber()].neg():s[e][i.sub(r).div(n).toNumber()]).type?l.mixedAdd(t):l.add(t))}}for(let e=0;e<i;e++)s[e]=[];return!0===n?l:l.toP()}_endoWnafMulAdd(e,t,r){let i,n=Array(2*e.length),a=Array(2*e.length);for(i=0;i<e.length;i++){let r=this.curve._endoSplit(t[i]),s=e[i],o=s._getBeta()??new tO(null,null);0!==r.k1.negative&&(r.k1.ineg(),s=s.neg(!0)),0!==r.k2.negative&&(r.k2.ineg(),o=o.neg(!0)),n[2*i]=s,n[2*i+1]=o,a[2*i]=r.k1,a[2*i+1]=r.k2}let s=this._wnafMulAdd(1,n,a,2*i,r);for(let e=0;e<2*i;e++)n[e]=null,a[e]=null;return s}_hasDoubles(e){if(null==this.precomputed)return!1;let t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;let r=[this],i=this;for(let n=0;n<(t??0);n+=e??1){for(let t=0;t<(e??1);t++)i=i.dbl();r.push(i)}return{step:e??1,points:r}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;let t=[this],r=(1<<e)-1,i=1===r?null:this.dbl();for(let e=1;e<r;e++)null!==i&&(t[e]=t[e-1].add(i));return{wnd:e,points:t}}}class tA{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw Error(t)}getNAF(e,t,r){let i=Array(Math.max(e.bitLength(),r)+1);i.fill(0);let n=1<<t+1,a=e.clone();for(let e=0;e<i.length;e++){let t,r=a.andln(n-1);a.isOdd()?(t=r>(n>>1)-1?(n>>1)-r:r,a.isubn(t)):t=0,i[e]=t,a.iushrn(1)}return i}getJSF(e,t){let r=[[],[]];e=e.clone(),t=t.clone();let i=0,n=0;for(;e.cmpn(-i)>0||t.cmpn(-n)>0;){let a,s,o=e.andln(3)+i&3,c=t.andln(3)+n&3;if(3===o&&(o=-1),3===c&&(c=-1),(1&o)==0)a=0;else{let t=e.andln(7)+i&7;a=(3===t||5===t)&&2===c?-o:o}if(r[0].push(a),(1&c)==0)s=0;else{let e=t.andln(7)+n&7;s=(3===e||5===e)&&2===o?-c:c}r[1].push(s),2*i===a+1&&(i=1-i),2*n===s+1&&(n=1-n),e.iushrn(1),t.iushrn(1)}return r}static cachedProperty(e,t,r){let i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=r.call(this)}}static parseBytes(e){return"string"==typeof e?e1(e,"hex"):e}static intFromLE(e){return new m(e,"hex","le")}constructor(){if(void 0!==e)return e;e=this;let t={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new m(t.p,16),this.red=new I(t.prime),this.zero=new m(0).toRed(this.red),this.one=new m(1).toRed(this.red),this.two=new m(2).toRed(this.red),this.n=new m(t.n,16),this.g=tO.fromJSON(t.g,t.gRed),this._wnafT1=[,,,,],this._wnafT2=[,,,,],this._wnafT3=[,,,,],this._wnafT4=[,,,,],this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new m(t.a,16).toRed(this.red),this.b=new m(t.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(t),this._endoWnafT1=[,,,,],this._endoWnafT2=[,,,,]}_getEndomorphism(e){let t,r,i;if(this.zeroA&&1===this.p.modrn(3)){if(void 0!==e.beta)t=new m(e.beta,16).toRed(this.red);else{let e=this._getEndoRoots(this.p);if(null===e)throw Error("Failed to get endomorphism roots for beta.");t=(t=0>e[0].cmp(e[1])?e[0]:e[1]).toRed(this.red)}if(void 0!==e.lambda)r=new m(e.lambda,16);else{let e=this._getEndoRoots(this.n);if(null===e)throw Error("Failed to get endomorphism roots for lambda.");if(null==this.g)throw Error("Curve generator point (g) is not defined.");let i=this.g.mul(e[0])?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null!=i&&null!=n&&0===i.cmp(n))r=e[0];else{if(r=e[1],null==this.g)throw Error("Curve generator point (g) is not defined.");let i=this.g.mul(r)?.x,n=null!=this.g.x?this.g.x.redMul(t):void 0;if(null==i||null==n)throw Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");tA.assert(0===i.cmp(n),"Lambda selection does not match computed beta.")}}return i="object"==typeof e.basis&&null!==e.basis?e.basis.map(function(e){return{a:new m(e.a,16),b:new m(e.b,16)}}):this._getEndoBasis(r),{beta:t,lambda:r,basis:i}}}_getEndoRoots(e){let t=e===this.p?this.red:new k(e),r=new m(2).toRed(t).redInvm(),i=r.redNeg(),n=new m(3).toRed(t).redNeg().redSqrt().redMul(r);return[i.redAdd(n).fromRed(),i.redSub(n).fromRed()]}_getEndoBasis(e){let t,r,i,n,a,s,o=this.n.ushrn(Math.floor(this.n.bitLength()/2)),c=e,l=this.n.clone(),h=new m(1),u=new m(0),d=new m(0),f=new m(1),p=new m(0),g=0,b=new m(0),y=new m(0);for(;0!==c.cmpn(0);){let e=l.div(c);b=l.sub(e.mul(c)),y=d.sub(e.mul(h));let a=f.sub(e.mul(u));if(void 0===i&&0>b.cmp(o))t=p.neg(),r=h,i=b.neg(),n=y;else if(void 0!==i&&2==++g)break;p=b,l=c,c=b,d=h,h=y,f=u,u=a}if(void 0===t||void 0===r||void 0===i||void 0===n)throw Error("Failed to compute Endo Basis values");a=b.neg(),s=y;let w=i.sqr().add(n.sqr());return a.sqr().add(s.sqr()).cmp(w)>=0&&(a=t,s=r),0!==i.negative&&(i=i.neg(),n=n.neg()),0!==a.negative&&(a=a.neg(),s=s.neg()),[{a:i,b:n},{a:a,b:s}]}_endoSplit(e){if(null==this.endo)throw Error("Endomorphism is not defined.");let t=this.endo.basis,r=t[0],i=t[1],n=i.b.mul(e).divRound(this.n),a=r.b.neg().mul(e).divRound(this.n),s=n.mul(r.a),o=a.mul(i.a),c=n.mul(r.b),l=a.mul(i.b);return{k1:e.sub(s).sub(o),k2:c.add(l).neg()}}validate(e){if(e.inf)return!0;let t=e.x,r=e.y;if(null===t||null===r)throw Error("Point coordinates cannot be null");let i=this.a.redMul(t),n=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===r.redSqr().redISub(n).cmpn(0)}}class t_{r;s;static fromDER(e,t){let r=(e,t)=>{let r=e[t.place++];if((128&r)==0)return r;throw Error("Invalid DER entity length")};e=e1(e,t);let i=new class{place;constructor(){this.place=0}};if(48!==e[i.place++])throw Error("Signature DER must start with 0x30");if(r(e,i)+i.place!==e.length||2!==e[i.place++])throw Error("Signature DER invalid");let n=r(e,i),a=e.slice(i.place,n+i.place);if(i.place+=n,2!==e[i.place++])throw Error("Signature DER invalid");let s=r(e,i);if(e.length!==s+i.place)throw Error("Invalid R-length in signature DER");let o=e.slice(i.place,s+i.place);if(0===a[0])if((128&a[1])!=0)a=a.slice(1);else throw Error("Invalid R-value in signature DER");if(0===o[0])if((128&o[1])!=0)o=o.slice(1);else throw Error("Invalid S-value in signature DER");return new t_(new m(a),new m(o))}static fromCompact(e,t){if(65!==(e=e1(e,t)).length)throw Error("Invalid Compact Signature");let r=e[0];if(r<27||r>=35)throw Error("Invalid Compact Byte");return new t_(new m(e.slice(1,33)),new m(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,r){return tF(new m(Y(e,r),16),this,t)}toString(e){return this.toDER(e)}toDER(e){let t=(e,t)=>{if(t<128)e.push(t);else throw Error("len must be < 0x80")},r=e=>{let t=0,r=e.length-1;for(;0===e[t]&&(128&e[t+1])==0&&t<r;)t++;return 0===t?e:e.slice(t)},i=this.r.toArray(),n=this.s.toArray();for((128&i[0])!=0&&(i=[0].concat(i)),(128&n[0])!=0&&(n=[0].concat(n)),i=r(i),n=r(n);0===n[0]&&(128&n[1])==0;)n=n.slice(1);let a=[2];t(a,i.length),(a=a.concat(i)).push(2),t(a,n.length);let s=a.concat(n),o=[48];return(t(o,s.length),o=o.concat(s),"hex"===e)?e0(o):"base64"===e?e5(o):o}toCompact(e,t,r){if(e<0||e>3)throw Error("Invalid recovery param");if("boolean"!=typeof t)throw Error("Invalid compressed param");let i=27+e;t&&(i+=4);let n=[i];return(n=(n=n.concat(this.r.toArray("be",32))).concat(this.s.toArray("be",32)),"hex"===r)?e0(n):"base64"===r?e5(n):n}RecoverPublicKey(e,t){let r=this.r,i=this.s,n=new tA,a=n.n,s=n.g,o=0!=e>>1?r.add(a):r,c=tO.fromX(o,(1&e)!=0);if(!c.mul(a).isInfinity())throw Error("nR is not at infinity");let l=t.neg().umod(a),h=r.invm(a),u=h.mul(i).umod(a),d=h.mul(l).umod(a),f=new tL(s.mul(d).add(c.mul(u)));return f.validate(),f}CalculateRecoveryFactor(e,t){for(let r=0;r<4;r++){let i;try{i=this.RecoverPublicKey(r,t)}catch{continue}if(e.eq(i))return r}throw Error("Unable to find valid recovery factor")}}class tT{K;V;constructor(e,t){let r=e1(e,"hex"),i=e1(t,"hex");if(32!==r.length)throw Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==i.length)throw Error("Nonce must be exactly 32 bytes (256 bits)");let n=r.concat(i);this.K=Array(32),this.V=Array(32);for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(n)}hmac(){return new W(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);let r=t.slice(0,e);return this.update(),e0(r)}}function tC(e,t,r=new tA){let i=8*e.byteLength()-r.n.bitLength();return(i>0&&e.iushrn(i),null===t&&e.cmp(r.n)>=0)?e.sub(r.n):e}let tR=new tA,tB=tR.n.byteLength(),tV=tR.n.subn(1),tD=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n>>1n,tU=(e,t,r=!1,i)=>{let n=BigInt("0x"+(e=tC(e)).toString(16)),a=BigInt("0x"+t.toString(16)),s=new tT(t.toArray("be",tB),e.toArray("be",tB));for(let e=0;;e++){let t="function"==typeof i?i(e):m.isBN(i)?i:new m(s.generate(tB),16);if(null==t)throw Error("k is undefined");if(0>(t=tC(t,!0)).cmpn(1)||t.cmp(tV)>0){if(m.isBN(i))throw Error("Invalid fixed custom K value (must be >1 and <N‑1)");continue}let o=BigInt("0x"+t.toString(16)),c=tx(o,{x:tm,y:tw});if(0n===c.Z){if(m.isBN(i))throw Error("Invalid fixed custom K value (k\xb7G at infinity)");continue}let l=tb(c.Z),h=tp(l,l),u=tE(tp(c.X,h));if(0n===u){if(m.isBN(i))throw Error("Invalid fixed custom K value (r == 0)");continue}let d=tN(o),f=tE(n+tP(u,a)),p=tP(d,f);if(0n===p){if(m.isBN(i))throw Error("Invalid fixed custom K value (s == 0)");continue}return r&&p>tD&&(p=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n-p),new t_(new m(u.toString(16),16),new m(p.toString(16),16))}},tF=(e,t,r)=>{let i=BigInt("0x"+e.toString(16));if(null==r.x||null==r.y)throw Error("Invalid public key: missing coordinates.");let n={x:BigInt("0x"+r.x.toString(16)),y:BigInt("0x"+r.y.toString(16))},{r:a,s}={r:BigInt("0x"+t.r.toString(16)),s:BigInt("0x"+t.s.toString(16))};if(a<=0n||a>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n||s<=0n||s>=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n)return!1;let o=tN(s);if(0n===o)return!1;let c=tP(i,o),l=tP(a,o),h=tk(tx(c,{x:tm,y:tw}),tx(l,n));if(0n===h.Z)return!1;let u=tb(h.Z),d=tp(u,u);return tE(tp(h.X,d))===a};class tL extends tO{static fromPrivateKey(e){let t=new tA().g.mul(e);return new tL(t.x,t.y)}static fromString(e){let t=tO.fromString(e);return new tL(t.x,t.y)}static fromDER(e){let t=tO.fromDER(e);return new tL(t.x,t.y)}constructor(e,t=null,r=!0){if(e instanceof tO)super(e.getX(),e.getY());else{if(null===t&&r&&"string"==typeof e&&(66===e.length||130===e.length))throw Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,r)}}deriveSharedSecret(e){if(!this.validate())throw Error("Public key not valid for ECDH secret derivation");return this.mul(e)}verify(e,t,r){return tF(new m(Y(e,r),16),t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){let t=ee(this.encode(!0));return"hex"===e?e0(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else if("mainnet"===e||"main"===e)e=[0];else throw Error(`Invalid prefix ${e}`);return tt(this.toHash(),e)}deriveChild(e,t,r,i){let n;if("function"==typeof i){let t=i(e,this);void 0!==t?n=t:(n=this.deriveSharedSecret(e),"function"==typeof r&&r(e,this,n))}else n=this.deriveSharedSecret(e);let a=e1(t,"utf8"),s=et(n.encode(!0),a),o=new tA().g.mul(new m(s)),c=this.add(o);return new tL(c.x,c.y)}static fromMsgHashAndCompactSignature(e,t,r){let i=e1(t,r);if(65!==i.length)throw Error("Invalid Compact Signature");let n=i[0];if(n<27||n>=35)throw Error("Invalid Compact Byte");let a=i[0]-27;return a>3&&(a-=4),new t_(new m(i.slice(1,33)),new m(i.slice(33,65))).RecoverPublicKey(a,e)}}class tK{_rand;getRandomValues(e,t){let r=new Uint8Array(t);return e.crypto.getRandomValues(r),Array.from(r)}constructor(){let e=()=>{throw Error("No secure random number generator is available in this environment.")};if(this._rand=e,"undefined"!=typeof globalThis&&"function"==typeof globalThis.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(globalThis,e);return}if("undefined"!=typeof process&&process.release?.name==="node")try{let e=require("crypto");if("function"==typeof e.randomBytes){this._rand=t=>Array.from(e.randomBytes(t));return}}catch(e){}if("undefined"!=typeof self&&"function"==typeof self.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(self,e);return}if("undefined"!=typeof window&&"function"==typeof window.crypto?.getRandomValues){this._rand=e=>this.getRandomValues(window,e);return}this._rand=e}generate(e){return this._rand(e)}}let tH=null,tq=e=>(null==tH&&(tH=new tK),tH.generate(e));class tM{x;y;constructor(e,t){let r=new tA().p;this.x=e.umod(r),this.y=t.umod(r)}toString(){return te(this.x.toArray())+"."+te(this.y.toArray())}static fromString(e){let[t,r]=e.split(".");return new tM(new m(e9(t)),new m(e9(r)))}}class t${points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){let r=new tA().p,i=[new tM(new m(0),new m(e.toArray()))];for(let e=1;e<t;e++){let e=new m(tq(32)).umod(r),t=new m(tq(32)).umod(r);i.push(new tM(e,t))}return new t$(i)}valueAt(e){let t=new tA().p,r=new m(0);for(let i=0;i<this.threshold;i++){let n=this.points[i].y;for(let r=0;r<this.threshold;r++)if(i!==r){let a=this.points[r].x,s=this.points[i].x,o=e.sub(a).umod(t),c=s.sub(a).umod(t).invm(t),l=o.mul(c).umod(t);n=n.mul(l).umod(t)}r=r.add(n).umod(t)}return r}}class tz{points;threshold;integrity;constructor(e,t,r){this.points=e,this.threshold=t,this.integrity=r}static fromBackupFormat(e){let t=0,r="";return new tz(e.map((e,i)=>{let n=e.split(".");if(4!==n.length)throw Error("Invalid share format in share "+i.toString()+'. Expected format: "x.y.t.i" - received '+e);let[a,s,o,c]=n;if(void 0===o)throw Error("Threshold not found in share "+i.toString());if(void 0===c)throw Error("Integrity not found in share "+i.toString());let l=parseInt(o);if(0!==i&&t!==l)throw Error("Threshold mismatch in share "+i.toString());if(0!==i&&r!==c)throw Error("Integrity mismatch in share "+i.toString());return t=l,r=c,tM.fromString([a,s].join("."))}),t,r)}toBackupFormat(){return this.points.map(e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class tW extends m{static fromRandom(){return new tW(tq(32))}static fromString(e,t="hex"){return new tW(super.fromString(e,t).toArray())}static fromHex(e){return new tW(super.fromHex(e,"big"))}static fromWif(e,t=1){let r=tr(e,void 0,t);if(33!==r.data.length)throw Error("Invalid WIF length");if(1!==r.data[32])throw Error("Invalid WIF padding");return new tW(r.data.slice(0,32))}constructor(e=0,t=10,r="be",i="apply"){if(e instanceof m?(super(),e.copy(this)):super(e,t,r),"nocheck"!==i){let e=this.checkInField();if(!e.inField){if("error"===i)throw Error("Input is out of field");m.move(this,e.modN)}}}checkInField(){let e=new tA,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,r=!0,i){return tU(new m(Y(e,t),16),this,r,i)}verify(e,t,r){return tF(new m(Y(e,r),16),t,this.toPublicKey())}toPublicKey(){let e=new tA().g.mul(this);return new tL(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw Error("Value is out of field");return tt([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw Error("Public key not valid for ECDH secret derivation");return e.mul(this)}deriveChild(e,t,r,i){let n;if("function"==typeof i){let t=i(this,e);void 0!==t?n=t:(n=this.deriveSharedSecret(e),"function"==typeof r&&r(this,e,n))}else n=this.deriveSharedSecret(e);let a=e1(t,"utf8"),s=et(n.encode(!0),a),o=new tA;return new tW(this.add(new m(s)).mod(o.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw Error("threshold and totalShares must be numbers");if(e<2)throw Error("threshold must be at least 2");if(t<2)throw Error("totalShares must be at least 2");if(e>t)throw Error("threshold should be less than or equal to totalShares");let r=t$.fromPrivateKey(this,e),i=[],n=new Set,a=new tA,s=tq(64);for(let e=0;e<t;e++){let t,o=0;do if(t=new m(er(s,[e,o,...tq(32)])).umod(a.p),++o>5)throw Error("Failed to generate unique x coordinate after 5 attempts");while(t.isZero()||n.has(t.toString()));n.add(t.toString());let c=r.valueAt(t);i.push(new tM(t,c))}return new tz(i,e,this.toPublicKey().toHash("hex").slice(0,8))}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return tW.fromKeyShares(tz.fromBackupFormat(e))}static fromKeyShares(e){let{points:t,threshold:r,integrity:i}=e;if(r<2)throw Error("threshold must be at least 2");if(t.length<r)throw Error(`At least ${r} shares are required to reconstruct the private key`);for(let e=0;e<r;e++)for(let i=e+1;i<r;i++)if(t[e].x.eq(t[i].x))throw Error("Duplicate share detected, each must be unique.");let n=new tW(new t$(t,r).valueAt(new m(0)).toArray());if(n.toPublicKey().toHash("hex").slice(0,8)!==i)throw Error("Integrity hash mismatch");return n}}let tj=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),tG=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(e=>new Uint8Array(e)),tX=new Uint8Array(256),tJ=new Uint8Array(256);for(let e=0;e<256;e++){let t=(e<<1^27*((128&e)!=0))&255;tX[e]=t,tJ[e]=t^e}function tY(e,t,r){for(let i=0;i<4;i++){let n=t[r+i];for(let t=0;t<4;t++)e[t][i]^=n[t]}}function tZ(e){for(let t=0;t<4;t++)e[t]=tj[e[t]]}function tQ(e,t){let r,i,n,a,s=[[],[],[],[]],o=[],c=Array.from(t);if(16===c.length)a=11;else if(24===c.length)a=13;else if(32===c.length)a=15;else throw Error("Illegal key length: "+String(c.length));let l=function(e,t){let r=t.length/4,i=[];for(let e=0;e<t.length;e++)e%4==0&&i.push([]),i[e>>2].push(t[e]);for(let t=r;t<4*e;t++){i[t]=[];let e=i[t-1].slice();if(t%r==0){let i=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=i,tZ(e);let n=tG[t/r];for(let t=0;t<4;t++)e[t]^=n[t]}else r>6&&t%r==4&&tZ(e);for(let n=0;n<4;n++)i[t][n]=i[t-r][n]^e[n]}return i}(a,c);for(let t=0;t<4;t++)s[0][t]=e[4*t],s[1][t]=e[4*t+1],s[2][t]=e[4*t+2],s[3][t]=e[4*t+3];for(tY(s,l,0),n=1;n<a;n++){for(let e=0;e<4;e++)for(let t=0;t<4;t++)s[e][t]=tj[s[e][t]];!function(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];let r=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=r,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}(s),n+1<a&&function(e){for(let t=0;t<4;t++){let r=e[0][t],i=e[1][t],n=e[2][t],a=e[3][t];e[0][t]=tX[r]^tJ[i]^n^a,e[1][t]=r^tX[i]^tJ[n]^a,e[2][t]=r^i^tX[n]^tJ[a],e[3][t]=tJ[r]^i^n^tX[a]}}(s),tY(s,l,4*n)}for(r=0;r<4;r++)for(i=0;i<4;i++)o.push(s[i][r]);return o}let t0=function(e){if(e<0||e>Number.MAX_SAFE_INTEGER)throw Error("getBytes64: value out of range");let t=Math.floor(e/0x100000000),r=e>>>0;return[t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r]},t1=function(e){return new Uint8Array(e)},t2=(()=>{let e=new Uint8Array(16);return e[0]=225,e})(),t8=(...e)=>{let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return r},t3=function(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r]??0},t4=function(e){let t=0,r=0;for(let i=0;i<e.length;i++)r=t,t=1&e[i],e[i]=e[i]>>1,0!==r&&(e[i]=128|e[i]);return e},t6=function(e,t){let r=t.slice(),i=t1(16);for(let t=0;t<16;t++)for(let n=7;n>=0;n--)(e[t]&1<<n)!=0&&t3(i,r),(1&r[15])!=0?(t4(r),t3(r,t2)):t4(r);return i},t5=function(e){let t=e.slice();for(let e=15;e>11&&(t[e]=t[e]+1&255,0===t[e]);e--);return t};function t7(e,t){let r=t1(16),i=new Uint8Array(16);for(let n=0;n<e.length;n+=16){i.set(r);for(let t=0;t<16;t++)i[t]^=e[n+t]??0;r=t6(i,t)}return r}function t9(e,t,r){if(0===e.length)return new Uint8Array(0);let i=new Uint8Array(e.length),n=t.slice(),a=0,s=Math.ceil(e.length/16);for(let t=0;t<s;t++){let o=tQ(n,r),c=Math.min(16,e.length-a);for(let t=0;t<c;t++)i[a]=e[a]^o[t],a++;t+1<s&&(n=t5(n))}return i}function re(e){let t,r,i=8*e.length;t=0===e.length?16:e.length%16==0?0:16-e.length%16;let n=new Uint8Array(16+e.length+t+16);r=16,n.set(e,r),r+=e.length,r+=t;let a=t0(0);n.set(a,r),r+=8;let s=t0(i);return n.set(s,r),n}class rt extends m{static fromRandom(){return new rt(tq(32))}encrypt(e,t){let r=new Uint8Array(tq(32)),{result:i,authenticationTag:n}=function(e,t,r){let i;if(0===t.length)throw Error("Initialization vector must not be empty");if(0===r.length)throw Error("Key must not be empty");let n=new Uint8Array(tQ(t1(16),r));if(12===t.length)i=t8(t,t1(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=t8(e,t1(16-e.length%16)));let r=t0(8*t.length);i=t7(t8(e,t1(8),new Uint8Array(r)),n)}let a=t9(e,t5(i),r),s=t9(t7(re(a),n),i,r);return{result:a,authenticationTag:s}}(new Uint8Array(e1(e,t)),r,new Uint8Array(this.toArray("be",32))),a=new Uint8Array(r.length+i.length+n.length),s=0;return a.set(r,s),s+=r.length,a.set(i,s),s+=i.length,a.set(n,s),e6(Array.from(a),t)}decrypt(e,t){let r=new Uint8Array(e1(e,t));if(r.length<48)throw Error("Ciphertext too short");let i=r.slice(0,32),n=r.length-16,a=r.slice(32,n),s=function(e,t,r,i){let n;if(0===e.length)throw Error("Cipher text must not be empty");if(0===t.length)throw Error("Initialization vector must not be empty");if(0===i.length)throw Error("Key must not be empty");let a=new Uint8Array(tQ(t1(16),i));if(12===t.length)n=t8(t,t1(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=t8(e,t1(16-e.length%16)));let r=t0(8*t.length);n=t7(t8(e,t1(8),new Uint8Array(r)),a)}let s=t9(e,t5(n),i),o=t9(t7(re(e),a),n,i);if(o.length!==r.length)return null;let c=0;for(let e=0;e<o.length;e++)c|=o[e]^r[e];return 0!==c?null:s}(a,i,r.slice(n),new Uint8Array(this.toArray("be",32)));if(null===s)throw Error("Decryption failed!");return e6(Array.from(s),t)}}let rr=new Uint8Array(0);class ri extends t_{static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_FORKID=64;static SIGHASH_ANYONECANPAY=128;scope;static format(e){return Array.from(this.formatBytes(e))}static formatBytes(e){let t=e.cache,r={sourceTXID:e.sourceTXID,sourceOutputIndex:e.sourceOutputIndex,sequence:e.inputSequence},i=[...e.otherInputs];function n(t){let r=new ti;if(void 0===t)for(let t of e.outputs){let e=t.satoshis??0;r.writeUInt64LE(e);let i=t.lockingScript?.toUint8Array()??rr;r.writeVarIntNum(i.length),r.write(i)}else{let i=e.outputs[t];if(void 0===i)throw Error(`Output at index ${t} does not exist`);let n=i.satoshis??0;r.writeUInt64LE(n);let a=i.lockingScript?.toUint8Array()??rr;r.writeVarIntNum(a.length),r.write(a)}return Q(r.toUint8Array())}i.splice(e.inputIndex,0,r);let a=Array(32).fill(0),s=Array(32).fill(0),o=Array(32).fill(0);if((e.scope&ri.SIGHASH_ANYONECANPAY)==0&&(t?.hashPrevouts!=null?a=t.hashPrevouts:(a=(()=>{let e=new ti;for(let t of i){if(void 0===t.sourceTXID){if(null==t.sourceTransaction)throw Error("Missing sourceTransaction for input");e.write(t.sourceTransaction.hash())}else e.writeReverse(e1(t.sourceTXID,"hex"));e.writeUInt32LE(t.sourceOutputIndex)}return Q(e.toUint8Array())})(),null!=t&&(t.hashPrevouts=a))),(e.scope&ri.SIGHASH_ANYONECANPAY)==0&&(31&e.scope)!==ri.SIGHASH_SINGLE&&(31&e.scope)!==ri.SIGHASH_NONE&&(t?.hashSequence!=null?s=t.hashSequence:(s=(()=>{let e=new ti;for(let t of i){let r=t.sequence??0xffffffff;e.writeUInt32LE(r)}return Q(e.toUint8Array())})(),null!=t&&(t.hashSequence=s))),(31&e.scope)!==ri.SIGHASH_SINGLE&&(31&e.scope)!==ri.SIGHASH_NONE)t?.hashOutputsAll!=null?o=t.hashOutputsAll:(o=n(),null!=t&&(t.hashOutputsAll=o));else if((31&e.scope)===ri.SIGHASH_SINGLE&&e.inputIndex<e.outputs.length){let r=e.inputIndex,i=t?.hashOutputsSingle?.get(r);null!=i?o=i:(o=n(r),null!=t&&(null==t.hashOutputsSingle&&(t.hashOutputsSingle=new Map),t.hashOutputsSingle.set(r,o)))}let c=new ti;c.writeInt32LE(e.transactionVersion),c.write(a),c.write(s),c.writeReverse(e1(e.sourceTXID,"hex")),c.writeUInt32LE(e.sourceOutputIndex);let l=e.subscript.toUint8Array();c.writeVarIntNum(l.length),c.write(l),c.writeUInt64LE(e.sourceSatoshis);let h=r.sequence;return c.writeUInt32LE(h),c.write(o),c.writeUInt32LE(e.lockTime),c.writeUInt32LE(e.scope>>>0),c.toUint8Array()}static fromChecksigFormat(e){if(0===e.length){let e=new m(1);return new ri(e,new m(1),1)}let t=e[e.length-1],r=e.slice(0,e.length-1),i=t_.fromDER(r);return new ri(i.r,i.s,t)}constructor(e,t,r){super(e,t),this.scope=r}hasLowS(){return!(this.s.ltn(1)||this.s.gt(new m("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))}toChecksigFormat(){return[...this.toDER(),this.scope]}}class rn{curve;constructor(){this.curve=new tA}generateProof(e,t,r,i){let n=tW.fromRandom(),a=n.toPublicKey(),s=r.mul(n),o=this.computeChallenge(t,r,i,s,a);return{R:a,SPrime:s,z:n.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,r,i){let{R:n,SPrime:a,z:s}=i,o=this.computeChallenge(e,t,r,a,n),c=this.curve.g.mul(s),l=n.add(e.mul(o));if(!c.eq(l))return!1;let h=t.mul(s),u=a.add(r.mul(o));return!!h.eq(u)}computeChallenge(e,t,r,i,n){return new m(Y([...e.encode(!0),...t.encode(!0),...r.encode(!0),...i.encode(!0),...n.encode(!0)])).umod(this.curve.n)}}let ra=/^[0-9a-fA-F]+$/,rs=BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),ro=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),rc=rs-3n,rl=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),rh={x:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),y:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},ru=ro>>1n;class rd{p=rs;n=ro;a=rc;b=rl;g=rh;mod(e,t=this.p){let r=e%t;return r>=0n?r:r+t}modInv(e,t){if(0n===e||t<=0n)throw Error("Invalid mod inverse input");let[r,i]=[this.mod(e,t),t],[n,a]=[1n,0n];for(;0n!==i;){let e=r/i;[r,i]=[i,r-e*i],[n,a]=[a,n-e*a]}if(1n!==r)throw Error("Inverse does not exist");return this.mod(n,t)}modPow(e,t,r){if(1n===r)return 0n;let i=1n,n=this.mod(e,r),a=t;for(;a>0n;)(1n&a)===1n&&(i=this.mod(i*n,r)),a>>=1n,n=this.mod(n*n,r);return i}isInfinity(e){return null===e}assertOnCurve(e){if(this.isInfinity(e))return;let{x:t,y:r}=e;if(this.mod(r*r)!==this.mod(this.mod(t*t*t+this.a*t)+this.b))throw Error("Point is not on secp256r1")}pointFromAffine(e,t){let r={x:this.mod(e),y:this.mod(t)};return this.assertOnCurve(r),r}pointFromHex(e){if(e.startsWith("04")){let t=BigInt("0x"+e.slice(2,66)),r=BigInt("0x"+e.slice(66));return this.pointFromAffine(t,r)}if(e.startsWith("02")||e.startsWith("03")){let t=BigInt("0x"+e.slice(2)),r=this.mod(this.mod(t*t*t+this.a*t)+this.b),i=this.modPow(r,this.p+1n>>2n,this.p),n=(1n&i)===1n===e.startsWith("03")?i:this.p-i;return this.pointFromAffine(t,n)}throw Error("Invalid point encoding")}pointToHex(e,t=!1){if(this.isInfinity(e))return"00";let r=this.to32BytesHex(e.x),i=this.to32BytesHex(e.y);return t?((1n&e.y)===0n?"02":"03")+r:"04"+r+i}addPoints(e,t){if(this.isInfinity(e))return t;if(this.isInfinity(t))return e;let{x:r,y:i}=e,{x:n,y:a}=t;if(r===n)return i===a?this.doublePoint(e):null;let s=this.mod((a-i)*this.modInv(n-r,this.p)),o=this.mod(s*s-r-n),c=this.mod(s*(r-o)-i);return{x:o,y:c}}doublePoint(e){if(this.isInfinity(e))return e;if(0n===e.y)return null;let t=this.mod((3n*e.x*e.x+this.a)*this.modInv(2n*e.y,this.p)),r=this.mod(t*t-2n*e.x),i=this.mod(t*(e.x-r)-e.y);return{x:r,y:i}}add(e,t){return this.addPoints(e,t)}multiply(e,t){if(0n===t||this.isInfinity(e))return null;let r=this.mod(t,this.n),i=null,n=e;for(;r>0n;)(1n&r)===1n&&(i=this.addPoints(i,n)),n=this.doublePoint(n),r>>=1n;return i}multiplyBase(e){return this.multiply(this.g,e)}isOnCurve(e){try{return this.assertOnCurve(e),!0}catch(e){return!1}}generatePrivateKeyHex(){return this.to32BytesHex(this.randomScalar())}randomScalar(){for(;;){let e=BigInt("0x"+e0(tq(32)));if(e>0n&&e<this.n)return e}}normalizePrivateKey(e){let t=this.mod(e,this.n);if(0n===t)throw Error("Invalid private key");return t}toScalar(e){if("bigint"==typeof e)return this.normalizePrivateKey(e);let t=e.startsWith("0x")?e.slice(2):e;if(!ra.test(t)||0===t.length||t.length>64)throw Error("Private key must be a hex string <= 32 bytes");let r=BigInt("0x"+t.padStart(64,"0"));return this.normalizePrivateKey(r)}publicKeyFromPrivate(e){let t=this.toScalar(e);return this.multiplyBase(t)}sign(e,t,r={}){let{prehashed:i=!1,nonce:n}=r,a=this.toScalar(t),s=this.normalizeMessage(e,i),o=this.bytesToScalar(s),c=n??this.deterministicNonce(a,s);for(;;){let e=this.multiplyBase(c);if(this.isInfinity(e)){c=n??this.deterministicNonce(a,s);continue}let t=this.mod(e.x,this.n);if(0n===t){c=n??this.deterministicNonce(a,s);continue}let r=this.modInv(c,this.n),i=this.mod(r*(o+t*a),this.n);if(0n===i){c=n??this.deterministicNonce(a,s);continue}return i>ru&&(i=this.n-i),{r:this.to32BytesHex(t),s:this.to32BytesHex(i)}}}verify(e,t,r,i={}){let n,{prehashed:a=!1}=i;try{n="string"==typeof r?this.pointFromHex(r):r}catch{return!1}if(null==n||!this.isOnCurve(n))return!1;let s="bigint"==typeof t.r?t.r:BigInt("0x"+t.r),o="bigint"==typeof t.s?t.s:BigInt("0x"+t.s);if(s<=0n||s>=this.n||o<=0n||o>=this.n)return!1;let c=this.bytesToScalar(this.normalizeMessage(e,a)),l=this.modInv(o,this.n),h=this.mod(c*l,this.n),u=this.mod(s*l,this.n),d=this.addPoints(this.multiplyBase(h),this.multiply(n,u));return!this.isInfinity(d)&&this.mod(d.x,this.n)===s}normalizeMessage(e,t){let r=this.toBytes(e);return t?r:new Uint8Array(Y(r))}bytesToScalar(e){return BigInt("0x"+e0(Array.from(e)))%this.n}deterministicNonce(e,t){let r=e1(this.to32BytesHex(e),"hex"),i=0;for(;i<1024;){let e=BigInt("0x"+e0(et(r,0===i?Array.from(t):Array.from(t).concat([255&i]))))%this.n;if(e>0n)return e;i++}throw Error("Failed to derive deterministic nonce")}toBytes(e){if("string"==typeof e){let t=ra.test(e)&&e.length%2==0;return Uint8Array.from(e1(e,t?"hex":"utf8"))}if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unsupported message format")}to32BytesHex(e){return e.toString(16).padStart(64,"0")}}let rf={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,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,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_SPLIT:127,OP_LEFT:128,OP_NUM2BIN:128,OP_RIGHT:129,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_NOP11:186,OP_NOP12:187,OP_NOP13:188,OP_NOP14:189,OP_NOP15:190,OP_NOP16:191,OP_NOP17:192,OP_NOP18:193,OP_NOP19:194,OP_NOP20:195,OP_NOP21:196,OP_NOP22:197,OP_NOP23:198,OP_NOP24:199,OP_NOP25:200,OP_NOP26:201,OP_NOP27:202,OP_NOP28:203,OP_NOP29:204,OP_NOP30:205,OP_NOP31:206,OP_NOP32:207,OP_NOP33:208,OP_NOP34:209,OP_NOP35:210,OP_NOP36:211,OP_NOP37:212,OP_NOP38:213,OP_NOP39:214,OP_NOP40:215,OP_NOP41:216,OP_NOP42:217,OP_NOP43:218,OP_NOP44:219,OP_NOP45:220,OP_NOP46:221,OP_NOP47:222,OP_NOP48:223,OP_NOP49:224,OP_NOP50:225,OP_NOP51:226,OP_NOP52:227,OP_NOP53:228,OP_NOP54:229,OP_NOP55:230,OP_NOP56:231,OP_NOP57:232,OP_NOP58:233,OP_NOP59:234,OP_NOP60:235,OP_NOP61:236,OP_NOP62:237,OP_NOP63:238,OP_NOP64:239,OP_NOP65:240,OP_NOP66:241,OP_NOP67:242,OP_NOP68:243,OP_NOP69:244,OP_NOP70:245,OP_NOP71:246,OP_NOP72:247,OP_NOP73:248,OP_NOP77:252,OP_SMALLDATA:249,OP_SMALLINTEGER:250,OP_PUBKEYS:251,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};for(let e in rf)rf[rf[e]]=e;let rp=rf,rg="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class rb{_chunks;parsed;rawBytesCache;hexCache;static fromASM(e){let t=[],r=e.split(" "),i=0;for(;i<r.length;){let e,n=r[i],a=0;if(n.startsWith("OP_")&&void 0!==rp[n]&&(e=n,a=rp[n]),"0"===n)a=0,t.push({op:a}),i+=1;else if("-1"===n)a=rp.OP_1NEGATE,t.push({op:a}),i+=1;else if(void 0===e){let e=r[i];e.length%2!=0&&(e="0"+e);let n=e1(e,"hex");if(e6(n,"hex")!==e)throw Error("invalid hex string in script");let s=n.length;s>=0&&s<rp.OP_PUSHDATA1?a=s:s<256?a=rp.OP_PUSHDATA1:s<65536?a=rp.OP_PUSHDATA2:s<0x100000000&&(a=rp.OP_PUSHDATA4),t.push({data:n,op:a}),i+=1}else a===rp.OP_PUSHDATA1||a===rp.OP_PUSHDATA2||a===rp.OP_PUSHDATA4?(t.push({data:e1(r[i+2],"hex"),op:a}),i+=3):(t.push({op:a}),i+=1)}return new rb(t)}static fromHex(e){if(0===e.length)return rb.fromBinary([]);if(e.length%2!=0)throw Error("There is an uneven number of characters in the string which suggests it is not hex encoded.");if(!/^[0-9a-fA-F]+$/.test(e))throw Error("Some elements in this string are not hex encoded.");let t=e1(e,"hex");return new rb([],Uint8Array.from(t),e.toLowerCase(),!1)}static fromBinary(e){return new rb([],Uint8Array.from(e),void 0,!1)}constructor(e=[],t,r,i=!0){this._chunks=e,this.parsed=i,this.rawBytesCache=t,this.hexCache=r}get chunks(){return this.ensureParsed(),this._chunks}set chunks(e){this._chunks=e,this.parsed=!0,this.invalidateSerializationCaches()}ensureParsed(){this.parsed||(null!=this.rawBytesCache?this._chunks=rb.parseChunks(this.rawBytesCache):this._chunks=[],this.parsed=!0)}toASM(){let e="";for(let t=0;t<this.chunks.length;t++){let r=this.chunks[t];e+=this._chunkToString(r)}return e.slice(1)}toHex(){if(null!=this.hexCache)return this.hexCache;null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes());let e=null!=rg?rg.from(this.rawBytesCache).toString("hex"):e6(Array.from(this.rawBytesCache),"hex");return this.hexCache=e,e}toBinary(){return Array.from(this.toUint8Array())}toUint8Array(){return null==this.rawBytesCache&&(this.rawBytesCache=this.serializeChunksToBytes()),this.rawBytesCache}writeScript(e){return this.invalidateSerializationCaches(),this.chunks=this.chunks.concat(e.chunks),this}writeOpCode(e){return this.invalidateSerializationCaches(),this.chunks.push({op:e}),this}setChunkOpCode(e,t){return this.invalidateSerializationCaches(),this.chunks[e]={op:t},this}writeBn(e){if(this.invalidateSerializationCaches(),e.cmpn(0)===rp.OP_0)this.chunks.push({op:rp.OP_0});else if(0===e.cmpn(-1))this.chunks.push({op:rp.OP_1NEGATE});else if(e.cmpn(1)>=0&&0>=e.cmpn(16))this.chunks.push({op:e.toNumber()+rp.OP_1-1});else{let t=e.toSm("little");this.writeBin(t)}return this}writeBin(e){let t;this.invalidateSerializationCaches();let r=e.length>0?e:void 0;if(e.length>0&&e.length<rp.OP_PUSHDATA1)t=e.length;else if(0===e.length)t=rp.OP_0;else if(e.length<256)t=rp.OP_PUSHDATA1;else if(e.length<65536)t=rp.OP_PUSHDATA2;else if(e.length<0x100000000)t=rp.OP_PUSHDATA4;else throw Error("You can't push that much data");return this.chunks.push({data:r,op:t}),this}writeNumber(e){return this.invalidateSerializationCaches(),this.writeBn(new m(e)),this}removeCodeseparators(){this.invalidateSerializationCaches();let e=[];for(let t=0;t<this.chunks.length;t++)this.chunks[t].op!==rp.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this}findAndDelete(e){this.invalidateSerializationCaches();let t=e.toHex();for(let e=0;e<this.chunks.length;e++)t===new rb([this.chunks[e]]).toHex()&&this.chunks.splice(e,1);return this}isPushOnly(){for(let e=0;e<this.chunks.length;e++)if(this.chunks[e].op>rp.OP_16)return!1;return!0}isLockingScript(){throw Error("Not implemented")}isUnlockingScript(){throw Error("Not implemented")}static computeSerializedLength(e){let t=0;for(let r of e){if(t+=1,null==r.data)continue;let e=r.data.length;if(r.op===rp.OP_RETURN){t+=e;break}r.op<rp.OP_PUSHDATA1?t+=e:r.op===rp.OP_PUSHDATA1?t+=1+e:r.op===rp.OP_PUSHDATA2?t+=2+e:r.op===rp.OP_PUSHDATA4&&(t+=4+e)}return t}serializeChunksToBytes(){let e=this.chunks,t=new Uint8Array(rb.computeSerializedLength(e)),r=0;for(let i=0;i<e.length;i++){let n=e[i];if(t[r++]=n.op,null!=n.data){if(n.op===rp.OP_RETURN){t.set(n.data,r),r+=n.data.length;break}r=rb.writeChunkData(t,r,n.op,n.data)}}return t}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}static writeChunkData(e,t,r,i){let n=i.length;if(r<rp.OP_PUSHDATA1)return e.set(i,t),t+n;if(r===rp.OP_PUSHDATA1)return e[t++]=255&n,e.set(i,t),t+n;if(r===rp.OP_PUSHDATA2)return e[t++]=255&n,e[t++]=n>>8&255,e.set(i,t),t+n;if(r===rp.OP_PUSHDATA4){let r=n>>>0;return e[t++]=255&r,e[t++]=r>>8&255,e[t++]=r>>16&255,e[t++]=r>>24&255,e.set(i,t),t+n}return t}static parseChunks(e){let t=[],r=e.length,i=0,n=0;for(;i<r;){let a=e[i++]??0;if(a===rp.OP_RETURN&&0===n){t.push({op:a,data:rb.copyRange(e,i,r)});break}if(a===rp.OP_IF||a===rp.OP_NOTIF||a===rp.OP_VERIF||a===rp.OP_VERNOTIF?n++:a===rp.OP_ENDIF&&n--,a>0&&a<rp.OP_PUSHDATA1){let n=Math.min(i+a,r);t.push({data:rb.copyRange(e,i,n),op:a}),i=n}else if(a===rp.OP_PUSHDATA1){let n=i<r?e[i++]??0:0,s=Math.min(i+n,r);t.push({data:rb.copyRange(e,i,s),op:a}),i=s}else if(a===rp.OP_PUSHDATA2){let n=(e[i]??0)|(e[i+1]??0)<<8,s=Math.min((i=Math.min(i+2,r))+n,r);t.push({data:rb.copyRange(e,i,s),op:a}),i=s}else if(a===rp.OP_PUSHDATA4){let n=((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16|(e[i+3]??0)<<24)>>>0,s=Math.min((i=Math.min(i+4,r))+n,r);t.push({data:rb.copyRange(e,i,s),op:a}),i=s}else t.push({op:a})}return t}static copyRange(e,t,r){let i=Math.max(r-t,0),n=Array(i);for(let r=0;r<i;r++)n[r]=e[t+r]??0;return n}_chunkToString(e){let t=e.op,r="";if(void 0===e.data){let e=rp[t];r=`${r} ${e}`}else r=`${r} ${e0(e.data)}`;return r}}class ry extends rb{isLockingScript(){return!0}isUnlockingScript(){return!1}}class rm extends rb{isLockingScript(){return!1}isUnlockingScript(){return!0}}class rw extends Error{txid;outputIndex;context;programCounter;stackState;altStackState;ifStackState;stackMem;altStackMem;constructor(e){let t=e.stackState.map(e=>null!=e&&void 0!==e.length?e0(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),r=e.altStackState.map(e=>null!=e&&void 0!==e.length?e0(e):null==e?"null/undef":"INVALID_STACK_ITEM").join(", "),i=`Context: ${e.context}, PC: ${e.programCounter}`,n=`Stack: [${t}] (len: ${e.stackState.length}, mem: ${e.stackMem})`,a=`AltStack: [${r}] (len: ${e.altStackState.length}, mem: ${e.altStackMem})`;super(`Script evaluation error: ${e.message}
|
|
2
2
|
TXID: ${e.txid}, OutputIdx: ${e.outputIndex}
|
|
3
3
|
${i}
|
|
4
4
|
${n}
|
|
5
5
|
${a}
|
|
6
|
-
IfStack: [${e.ifStackState.join(", ")}]`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let rO=BigInt(0x7fffffff),rA=Object.freeze(new P(-1).toScriptNum()),r_=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new P(t).toScriptNum())));class rT{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;sigHashCache;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],r=e[3];if(2!==t||0===r||5+r>=e.length)return!1;let i=4+r,n=e[i],a=e[i+1];if(2!==n||0===a||(128&e[4])!=0||r>1&&0===e[4]&&(128&e[5])==0)return!1;let s=i+2;return(128&e[s])==0&&(!(a>1)||0!==e[s]||(128&e[s+1])!=0)&&r+a+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=ru.fromChecksigFormat(e);if(!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if((t.scope&ru.SIGHASH_FORKID)==0)return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{tX.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,r){return tj(new P(eo(ru.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:r,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache}))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],r=t.op;void 0===r&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>0x40000000&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);let i=!this.ifStack.includes(!1);if(i&&(r===rk.OP_2MUL||r===rk.OP_2DIV||r===rk.OP_VERIF||r===rk.OP_VERNOTIF||r===rk.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${rk[r]}, PC: ${this.programCounter})`),i&&r>=0&&r<=rk.OP_PUSHDATA4){let e,r;e=t.data,r=t.op,Array.isArray(e)&&(0===e.length?r!==rk.OP_0:1===e.length&&e[0]>=1&&e[0]<=16?r!==rk.OP_1+(e[0]-1):1===e.length&&129===e[0]?r!==rk.OP_1NEGATE:e.length<=75?r!==e.length:e.length<=255?r!==rk.OP_PUSHDATA1:e.length<=65535&&r!==rk.OP_PUSHDATA2)&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[])}else if(i||r>=rk.OP_IF&&r<=rk.OP_ENDIF){let e,t,n,a,s,o,c,l,h,u,d,f,p,g,b,y,m,w,v,I,k,S,x,E,N,O;switch(r){case rk.OP_1NEGATE:this.pushStackCopy(rA);break;case rk.OP_0:this.pushStackCopy(r_[0]);break;case rk.OP_1:case rk.OP_2:case rk.OP_3:case rk.OP_4:case rk.OP_5:case rk.OP_6:case rk.OP_7:case rk.OP_8:case rk.OP_9:case rk.OP_10:case rk.OP_11:case rk.OP_12:case rk.OP_13:case rk.OP_14:case rk.OP_15:case rk.OP_16:f=r-(rk.OP_1-1),this.pushStackCopy(r_[f]);break;case rk.OP_NOP:case rk.OP_NOP2:case rk.OP_NOP3:case rk.OP_NOP1:case rk.OP_NOP4:case rk.OP_NOP5:case rk.OP_NOP6:case rk.OP_NOP7:case rk.OP_NOP8:case rk.OP_NOP9:case rk.OP_NOP10:case rk.OP_NOP11:case rk.OP_NOP12:case rk.OP_NOP13:case rk.OP_NOP14:case rk.OP_NOP15:case rk.OP_NOP16:case rk.OP_NOP17:case rk.OP_NOP18:case rk.OP_NOP19:case rk.OP_NOP20:case rk.OP_NOP21:case rk.OP_NOP22:case rk.OP_NOP23:case rk.OP_NOP24:case rk.OP_NOP25:case rk.OP_NOP26:case rk.OP_NOP27:case rk.OP_NOP28:case rk.OP_NOP29:case rk.OP_NOP30:case rk.OP_NOP31:case rk.OP_NOP32:case rk.OP_NOP33:case rk.OP_NOP34:case rk.OP_NOP35:case rk.OP_NOP36:case rk.OP_NOP37:case rk.OP_NOP38:case rk.OP_NOP39:case rk.OP_NOP40:case rk.OP_NOP41:case rk.OP_NOP42:case rk.OP_NOP43:case rk.OP_NOP44:case rk.OP_NOP45:case rk.OP_NOP46:case rk.OP_NOP47:case rk.OP_NOP48:case rk.OP_NOP49:case rk.OP_NOP50:case rk.OP_NOP51:case rk.OP_NOP52:case rk.OP_NOP53:case rk.OP_NOP54:case rk.OP_NOP55:case rk.OP_NOP56:case rk.OP_NOP57:case rk.OP_NOP58:case rk.OP_NOP59:case rk.OP_NOP60:case rk.OP_NOP61:case rk.OP_NOP62:case rk.OP_NOP63:case rk.OP_NOP64:case rk.OP_NOP65:case rk.OP_NOP66:case rk.OP_NOP67:case rk.OP_NOP68:case rk.OP_NOP69:case rk.OP_NOP70:case rk.OP_NOP71:case rk.OP_NOP72:case rk.OP_NOP73:case rk.OP_NOP77:break;case rk.OP_IF:case rk.OP_NOTIF:g=!1,i&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),g=this.castToBool(e),r===rk.OP_NOTIF&&(g=!g)),this.ifStack.push(g);break;case rk.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case rk.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case rk.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case rk.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case rk.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case rk.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case rk.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case rk.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case rk.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),a=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(a);break;case rk.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case rk.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack(),n=this.popStack(),a=this.popStack();this.pushStack(i),this.pushStack(r),this.pushStack(t),this.pushStack(e),this.pushStack(a),this.pushStack(n);break}case rk.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(i),this.pushStack(r);break}case rk.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case rk.OP_DEPTH:this.pushStack(new P(this.stack.length).toScriptNum());break;case rk.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case rk.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case rk.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case rk.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case rk.OP_PICK:case rk.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items to be on the stack.`);let e=(l=P.fromScriptNum(this.popStack(),!0)).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${rk[r]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),i=this.stack[this.stack.length-1-t];r===rk.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=i.length,this.pushStack(i)):this.pushStackCopy(i);break}case rk.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(s);break;case rk.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(s);break;case rk.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case rk.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new P(this.stackTop().length).toScriptNum());break;case rk.OP_AND:case rk.OP_OR:case rk.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${rk[r]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let i=0;i<t.length;i++)r===rk.OP_AND?e[i]=t[i]&n[i]:r===rk.OP_OR?e[i]=t[i]|n[i]:e[i]=t[i]^n[i];this.pushStack(e);break}case rk.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let r=0;r<e.length;r++)t[r]=255&~e[r];this.pushStack(t);break}case rk.OP_LSHIFT:case rk.OP_RSHIFT:{this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items to be on the stack.`),u=P.fromScriptNum(this.popStack(),!0),t=this.popStack();let e=u.toBigInt();if(e<0n&&this.scriptEvaluationError(`${rk[r]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}h=new P(t);let i=(r===rk.OP_LSHIFT?h.ushln(e):h.ushrn(e)).toArray("be",t.length);this.pushStack(i);break}case rk.OP_EQUAL:case rk.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items to be on the stack.`),n=this.popStack(),g=function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(t=this.popStack(),n),this.pushStack(g?[1]:[]),r===rk.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case rk.OP_1ADD:case rk.OP_1SUB:case rk.OP_NEGATE:case rk.OP_ABS:case rk.OP_NOT:case rk.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${rk[r]} requires at least one item to be on the stack.`),l=P.fromScriptNum(this.popStack(),!0),r){case rk.OP_1ADD:l=l.add(new P(1));break;case rk.OP_1SUB:l=l.sub(new P(1));break;case rk.OP_NEGATE:l=l.neg();break;case rk.OP_ABS:l.isNeg()&&(l=l.neg());break;case rk.OP_NOT:l=new P(+(0===l.cmpn(0)));break;case rk.OP_0NOTEQUAL:l=new P(+(0!==l.cmpn(0)))}this.pushStack(l.toScriptNum());break;case rk.OP_ADD:case rk.OP_SUB:case rk.OP_MUL:case rk.OP_DIV:case rk.OP_MOD:case rk.OP_BOOLAND:case rk.OP_BOOLOR:case rk.OP_NUMEQUAL:case rk.OP_NUMEQUALVERIFY:case rk.OP_NUMNOTEQUAL:case rk.OP_LESSTHAN:case rk.OP_GREATERTHAN:case rk.OP_LESSTHANOREQUAL:case rk.OP_GREATERTHANOREQUAL:case rk.OP_MIN:case rk.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),u=P.fromScriptNum(n,!0),h=P.fromScriptNum(t,!0);let e=0;switch(r){case rk.OP_MUL:e=h.byteLength()+u.byteLength();break;case rk.OP_ADD:case rk.OP_SUB:e=Math.max(h.byteLength(),u.byteLength())+1;break;default:e=Math.max(h.byteLength(),u.byteLength())}this.ensureStackMem(e);let i=new P(0);switch(r){case rk.OP_ADD:i=h.add(u);break;case rk.OP_SUB:i=h.sub(u);break;case rk.OP_MUL:i=h.mul(u);break;case rk.OP_DIV:0===u.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),i=h.div(u);break;case rk.OP_MOD:0===u.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),i=h.mod(u);break;case rk.OP_BOOLAND:i=new P(+(0!==h.cmpn(0)&&0!==u.cmpn(0)));break;case rk.OP_BOOLOR:i=new P(+(0!==h.cmpn(0)||0!==u.cmpn(0)));break;case rk.OP_NUMEQUAL:case rk.OP_NUMEQUALVERIFY:i=new P(+(0===h.cmp(u)));break;case rk.OP_NUMNOTEQUAL:i=new P(+(0!==h.cmp(u)));break;case rk.OP_LESSTHAN:i=new P(+(0>h.cmp(u)));break;case rk.OP_GREATERTHAN:i=new P(+(h.cmp(u)>0));break;case rk.OP_LESSTHANOREQUAL:i=new P(+(0>=h.cmp(u)));break;case rk.OP_GREATERTHANOREQUAL:i=new P(+(h.cmp(u)>=0));break;case rk.OP_MIN:i=0>h.cmp(u)?h:u;break;case rk.OP_MAX:i=h.cmp(u)>0?h:u}this.pushStack(i.toScriptNum()),r===rk.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case rk.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),d=P.fromScriptNum(this.popStack(),!0),u=P.fromScriptNum(this.popStack(),!0),g=(h=P.fromScriptNum(this.popStack(),!0)).cmp(u)>=0&&0>h.cmp(d),this.pushStack(g?[1]:[]);break;case rk.OP_RIPEMD160:case rk.OP_SHA1:case rk.OP_SHA256:case rk.OP_HASH160:case rk.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${rk[r]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];r===rk.OP_RIPEMD160?t=ei(e):r===rk.OP_SHA1?t=en(e):r===rk.OP_SHA256?t=ea(e):r===rk.OP_HASH160?t=ec(e):r===rk.OP_HASH256&&(t=eo(e)),this.pushStack(t);break}case rk.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case rk.OP_CHECKSIG:case rk.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${rk[r]} requires at least two items to be on the stack.`),w=this.popStack(),m=this.popStack(),this.checkSignatureEncoding(m)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${rk[r]} requires correct encoding for the public key and signature.`),(y=new rx(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1))).findAndDelete(new rx().writeBin(m)),b=!1,m.length>0)try{v=ru.fromChecksigFormat(m),I=tX.fromDER(w),b=this.verifySignature(v,I,y)}catch(e){b=!1}this.pushStack(b?[1]:[]),r===rk.OP_CHECKSIGVERIFY&&(b||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case rk.OP_CHECKMULTISIG:case rk.OP_CHECKMULTISIGVERIFY:{k=1,this.stack.length<k&&this.scriptEvaluationError(`${rk[r]} requires at least 1 item for nKeys.`);let e=P.fromScriptNum(this.stackTop(-k),!0).toBigInt();(e<0n||e>rO)&&this.scriptEvaluationError(`${rk[r]} requires a key count between 0 and 2147483647.`);let t=E=Number(e);S=++k,k+=E,this.stack.length<k&&this.scriptEvaluationError(`${rk[r]} stack too small for nKeys and keys. Need ${k}, have ${this.stack.length}.`);let i=P.fromScriptNum(this.stackTop(-k),!0).toBigInt();(i<0n||i>BigInt(E))&&this.scriptEvaluationError(`${rk[r]} requires the number of signatures to be no greater than the number of keys.`);let n=N=Number(i);x=++k,k+=N,this.stack.length<k&&this.scriptEvaluationError(`${rk[r]} stack too small for N, keys, M, sigs, and dummy. Need ${k}, have ${this.stack.length}.`),y=new rx(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));for(let e=0;e<N;e++)m=this.stackTop(-x-e),y.findAndDelete(new rx().writeBin(m));for(b=!0;b&&N>0;){if(0===E){b=!1;break}if(m=this.stackTop(-x),w=this.stackTop(-S),this.checkSignatureEncoding(m)&&this.checkPublicKeyEncoding(w)||this.scriptEvaluationError(`${rk[r]} requires correct encoding for the public key and signature.`),O=!1,m.length>0)try{v=ru.fromChecksigFormat(m),I=tX.fromDER(w),O=this.verifySignature(v,I,y)}catch(e){O=!1}O&&(x++,N--),S++,N>--E&&(b=!1)}let a=1+t+1+n+1-1;for(;a>0;)this.popStack(),a--;this.stack.length<1&&this.scriptEvaluationError(`${rk[r]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${rk[r]} requires the extra stack item (dummy) to be empty.`),this.pushStack(b?[1]:[]),r===rk.OP_CHECKMULTISIGVERIFY&&(b||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case rk.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>0x40000000&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case rk.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=P.fromScriptNum(e,!0).toBigInt();(r<0n||r>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let i=Number(r);this.pushStack(t.slice(0,i)),this.pushStack(t.slice(i));break}case rk.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=P.fromScriptNum(this.popStack(),!0).toBigInt();(e>BigInt(0x40000000)||e<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),p=Number(e);let t=this.popStack();if((t=tf(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let r=Array(p).fill(0),i=0;t.length>0&&(i=128&t[t.length-1],t[t.length-1]&=127);for(let e=0;e<t.length;e++)r[e]=t[e];0!==i&&(r[p-1]|=128),this.pushStack(r);break}case rk.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=tf(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e[e.length-1])!=0||!(e.length<=1)&&(128&e[e.length-2])!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${r} (pc=${this.programCounter}).`)}}return this.programCounter++,!0}validate(){for(this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&("LockingScript"!==this.context||!(this.programCounter>=this.lockingScript.chunks.length)););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new rN({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class rC{lock(e){let t;if("string"==typeof e){let r=th(e);if(0!==r.prefix[0]&&111!==r.prefix[0])throw Error("only P2PKH is supported");t=r.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new rE([{op:rk.OP_DUP},{op:rk.OP_HASH160},{op:t.length,data:t},{op:rk.OP_EQUALVERIFY},{op:rk.OP_CHECKSIG}])}unlock(e,t="all",r=!1,i,n){return{sign:async(a,s)=>{let o=ru.SIGHASH_FORKID;"all"===t&&(o|=ru.SIGHASH_ALL),"none"===t&&(o|=ru.SIGHASH_NONE),"single"===t&&(o|=ru.SIGHASH_SINGLE),r&&(o|=ru.SIGHASH_ANYONECANPAY);let c=a.inputs[s],l=a.inputs.filter((e,t)=>t!==s),h=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==h||void 0===h||""===h)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(i||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis)||void 0===i)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let u=ru.format({sourceTXID:h,sourceOutputIndex:tb(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:i,transactionVersion:a.version,otherInputs:l,inputIndex:s,outputs:a.outputs,inputSequence:tb(c.sequence,"input.sequence must have value"),subscript:n,lockTime:a.lockTime,scope:o}),d=e.sign(ea(u)),f=new ru(d.r,d.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new rP([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class rR{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:rk.OP_OVER},{op:rk.OP_3},{op:rk.OP_SPLIT},{op:rk.OP_NIP},{op:rk.OP_1},{op:rk.OP_SPLIT},{op:rk.OP_SWAP},{op:rk.OP_SPLIT},{op:rk.OP_DROP}];return"raw"!==this.type&&t.push({op:rk["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:rk.OP_EQUALVERIFY}),t.push({op:rk.OP_CHECKSIG}),new rE(t)}unlock(e,t,r="all",i=!1){return{sign:async(n,a)=>{void 0===t&&(t=t1.fromRandom());let s=ru.SIGHASH_FORKID;"all"===r&&(s|=ru.SIGHASH_ALL),"none"===r&&(s|=ru.SIGHASH_NONE),"single"===r&&(s|=ru.SIGHASH_SINGLE),i&&(s|=ru.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[c]=o.splice(a,1);if("object"!=typeof c.sourceTransaction)throw Error("The source transaction is needed for transaction signing.");let l=ru.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:a,outputs:n.outputs,inputSequence:c.sequence??0xffffffff,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new rx,lockTime:n.lockTime,scope:s}),h=t.sign(ea(l),void 0,!0,e),u=new ru(h.r,h.s,s).toChecksigFormat(),d=t.toPublicKey().encode(!0);return new rP([{op:u.length,data:u},{op:d.length,data:d}])},estimateLength:async()=>108}}}let rB=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class rV{wallet;originator;static decode(e){let t=tX.fromString(e7(tb(e.chunks[0].data,"script.chunks[0].data must have value"))),r=[];for(let t=2;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,n=e.chunks[t].data??[];if(0===n.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?n=[e.chunks[t].op-80]:0===e.chunks[t].op?n=[0]:79===e.chunks[t].op&&(n=[129])),r.push(n),i===rk.OP_DROP||i===rk.OP_2DROP)break}return{fields:r,lockingPublicKey:t}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,r,i,n=!1,a=!0,s="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],l=[];if(c.push({op:o.length/2,data:e9(o,"hex")}),c.push({op:rk.OP_CHECKSIG}),a){let n=e.reduce((e,t)=>[...e,...t],[]),{signature:a}=await this.wallet.createSignature({data:n,protocolID:t,keyID:r,counterparty:i},this.originator);e.push(a)}for(let t of e)l.push(rB(t));let h=e.length;for(;h>1;)l.push({op:rk.OP_2DROP}),h-=2;return new rE((0!==h&&l.push({op:rk.OP_DROP}),"before"===s)?[...c,...l]:[...l,...c])}unlock(e,t,r,i="all",n=!1,a,s){return{sign:async(o,c)=>{let l=ru.SIGHASH_FORKID;"all"===i&&(l|=ru.SIGHASH_ALL),"none"===i&&(l|=ru.SIGHASH_NONE),"single"===i&&(l|=ru.SIGHASH_SINGLE),n&&(l|=ru.SIGHASH_ANYONECANPAY);let h=o.inputs[c],u=o.inputs.filter((e,t)=>t!==c),d=h.sourceTXID??h.sourceTransaction?.id("hex");if(null==d||void 0===d)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(a||=h.sourceTransaction?.outputs[h.sourceOutputIndex].satoshis)||void 0===a)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(s||=h.sourceTransaction?.outputs[h.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let f=ea(ru.format({sourceTXID:d,sourceOutputIndex:tb(h.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:a,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:h.sequence??0xffffffff,subscript:s,lockTime:o.lockTime,scope:l})),{signature:p}=await this.wallet.createSignature({data:f,protocolID:e,keyID:t,counterparty:r},this.originator),g=tF.fromDER([...p]),b=new ru(g.r,g.s,l).toChecksigFormat();return new rP([{op:b.length,data:b}])},estimateLength:async()=>73}}}class rD{value;constructor(e){this.value=e}async computeFee(e){let t,r=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+r(e.inputs.length);for(let i=0;i<e.inputs.length;i++){let n,a=e.inputs[i];if(t+=40,"object"==typeof a.unlockingScript)n=a.unlockingScript.toBinary().length;else if("object"==typeof a.unlockingScriptTemplate)n=await a.unlockingScriptTemplate.estimateLength(e,i);else throw Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=r(n),t+=n}for(let i of(t+=r(e.outputs.length),e.outputs)){t+=8;let e=i.lockingScript.toBinary().length;t+=r(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class rU extends rD{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return rU.instance||(rU.instance=new rU(e)),rU.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(rU.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.json();if(!r.policy?.miningFee||"number"!=typeof r.policy.miningFee.satoshis||"number"!=typeof r.policy.miningFee.bytes)throw Error("Invalid policy response format");let i=r.policy.miningFee.satoshis/r.policy.miningFee.bytes*1e3;return this.cachedRate=i,this.cacheTimestamp=e,i}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}class rF{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()})}}class rL{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},i=await this.fetch(e,r),n=i.headers.get("Content-Type"),a=n?.startsWith("application/json")?await i.json():await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:a}}}function rK(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rL(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rF(e)}catch(t){return e}}function rH(){return`ts-sdk-${e7(tJ(16))}`}class rq{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=rK(),this.deploymentId=rH(),this.callbackToken=void 0,this.callbackUrl=void 0;else{const{apiKey:e,deploymentId:r,httpClient:i,callbackToken:n,callbackUrl:a,headers:s}=t??{};this.apiKey=e,this.httpClient=i??rK(),this.deploymentId=r??rH(),this.callbackToken=n,this.callbackUrl=a,this.headers=s}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"===r.message)t=e.toHex();else throw r}let r={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(e.ok){let{txid:t,extraInfo:r,txStatus:i,competingTxs:n}=e.data,a={status:"success",txid:t,message:`${i} ${r}`};return null!=n&&(a.competingTxs=n),a}{let t=typeof e.status,r={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},i=e.data;if("string"==typeof i)try{i=JSON.parse(e.data)}catch{}return"object"==typeof i&&(null!==i&&(r.more=i),null!=i&&"string"==typeof i.txid&&(r.txid=i.txid),null!=i&&"detail"in i&&"string"==typeof i.detail&&(r.description=i.detail)),r}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),r={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(r){let t={status:"error",code:"500",description:"string"==typeof r.message?r.message:"Internal Server Error"};return e.map(()=>t)}}}function rM(e=!1,t={}){return new rq(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class r${network;apiKey;URL;httpClient;constructor(e="main",t={}){const{apiKey:r,httpClient:i}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=i??rK(),this.apiKey=r??""}async isValidRootForHeight(e,t){let r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${t}/header`,r);if(i.ok){let{merkleroot:t}=i.data;return t===e}if(404===i.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function rz(){return new r$}class rW{blockHeight;path;static fromHex(e){return rW.fromBinary(e9(e,"hex"))}static fromReader(e,t=!0){let r,i,n,a=e.readVarIntNum(),s=e.readUInt8(),o=Array(s).fill(null).map(()=>[]);for(let t=0;t<s;t++){for(n=e.readVarIntNum();n>0;){i=e.readVarIntNum(),r=e.readUInt8();let a={offset:i};(1&r)!=0?a.duplicate=!0:((2&r)!=0&&(a.txid=!0),a.hash=e7(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(a),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new rW(a,o,t)}static fromBinary(e){let t=new td(e);return rW.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new rW(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,r=!0){let i;this.blockHeight=e,this.path=t;const n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let i=new Set;e.forEach(e=>{if(i.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(i.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(r&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(i=this.computeRoot(e.hash)),i!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toBinary(){let e=new tu;e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let r=0;r<t;r++){let t=Object.keys(this.path[r]).length;for(let i of(e.writeVarIntNum(t),this.path[r])){e.writeVarIntNum(i.offset);let t=0;i?.duplicate===!0&&(t|=1),i?.txid!==void 0&&null!==i.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(e9(i.hash,"hex").reverse())}}return e.toArray()}toHex(){return e7(this.toBinary())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw Error("Transaction ID is undefined");let t=this.indexOf(e);if("number"!=typeof t)throw Error(`This proof does not contain the txid: ${e??"undefined"}`);let r=e=>e7(eo(e9(e,"hex").reverse()).reverse()),i=e;if(1===this.path.length&&1===this.path[0].length)return i;for(let e=0;e<this.path.length;e++){this.path[e];let n=t>>e^1,a=this.findOrComputeLeaf(e,n);if("object"!=typeof a)throw Error(`Missing hash for index ${t} at height ${e}`);i=r(!0===a.duplicate?(i??"")+(i??""):n%2!=0?(a.hash??"")+(i??""):(i??"")+(a.hash??""))}return i}findOrComputeLeaf(e,t){let r=e=>e7(eo(e9(e,"hex").reverse()).reverse()),i=this.path[e].find(e=>e.offset===t);if(null!=i)return i;if(0===e)return;let n=e-1,a=t<<1,s=this.findOrComputeLeaf(n,a);if(null==s||null==s.hash||""===s.hash)return;let o=this.findOrComputeLeaf(n,a+1);if(null!=o)return{offset:t,hash:r(!0===o.duplicate?s.hash+s.hash:(o.hash??"")+(s.hash??""))}}async verify(e,t){let r=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(r,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let r=0;r<this.path.length;r++){t.push([]);for(let e=0;e<this.path[r].length;e++)t[r].push(this.path[r][e]);for(let i=0;i<e.path[r].length;i++)if(void 0===t[r].find(t=>t.offset===e.path[r][i].offset))t[r].push(e.path[r][i]);else if(e.path[r][i]?.txid!==void 0&&e.path[r][i]?.txid!==null){let n=t[r].find(t=>t.offset===e.path[r][i].offset);null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.slice(-1)[0]!==e)&&t.push(e)},t=(e,t)=>{for(let r=e.length;r>=0;r--){let i=this.path[t].findIndex(t=>t.offset===e[r]);i>=0&&this.path[t].splice(i,1)}},r=t=>{let r=[];for(let i of t)e(i>>1,r);return r},i=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let r=this.path[0][t];if(!0===r.txid)e(r.offset>>1,i);else{let i=r.offset%2==1,a=this.path[0][t+(i?-1:1)];void 0!==a.txid&&null!==a.txid&&a.txid||e(a.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=i,i=r(i),t(n,e)}}class rj{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=e7(eo(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=r0.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(e,t){"string"==typeof e?this._txid=e:Array.isArray(e)?this._rawTx=e:this._tx=e,this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new rj(e,t)}static fromRawTx(e,t){return new rj(e,t)}static fromTxid(e,t){return new rj(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e={};for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&(e[t.sourceTXID]=!0);this.inputTxids=Object.keys(e)}}toWriter(e,t){let r=t=>{e.writeUInt8(t)},i=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(e9(this._txid,"hex"))},n=()=>{if(null!=this._rawTx)e.write(this._rawTx);else if(null!=this._tx)e.write(this._tx.toUint8Array());else throw Error("a valid serialized Transaction is expected")},a=()=>{void 0===this.bumpIndex?r(l.RAWTX):(r(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};t===rY?this.isTxidOnly?(r(l.TXID_ONLY),i()):(void 0!==this.bumpIndex?(r(l.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):r(l.RAWTX),n()):(n(),a())}static fromReader(e,t){let r,i,n;if(t===rY){let t=e.readUInt8();t===l.TXID_ONLY?n=rj.fromTxid(e7(e.readReverse(32))):(t===l.RAWTX_AND_BUMP_INDEX&&(i=e.readVarIntNum()),r=r0.fromReader(e),n=rj.fromTx(r,i))}else r=r0.fromReader(e),i=0!==e.readUInt8()?e.readVarIntNum():void 0,n=rj.fromTx(r,i);return n}}let rX="undefined"!=typeof globalThis?globalThis.Buffer:void 0,rG=0xefbe0001,rY=0xefbe0002,rJ=0x1010101;(a=l||(l={}))[a.RAWTX=0]="RAWTX",a[a.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",a[a.TXID_ONLY=2]="TXID_ONLY";class rZ{bumps=[];txs=[];version=rY;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=rY){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new tu;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let r=this.txs[t];return r.isTxidOnly?r:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),r=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tb(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null==t||null==t.tx)return;let r=(e,t)=>{let i=e.findBump(t.id("hex"));if(null!=i)t.merklePath=i;else for(let i of t.inputs){if(null==i.sourceTransaction){let t=e.findTxid(tb(i.sourceTXID,"sourceTXID must be valid"));null!=t&&(i.sourceTransaction=t.tx)}if(null!=i.sourceTransaction){let t=e.findBump(i.sourceTransaction.id("hex"));null!=t?i.sourceTransaction.merklePath=t:r(e,i.sourceTransaction)}}};return r(this,t.tx),t.tx}mergeBump(e){let t;this.markMutated(!1);for(let r=0;r<this.bumps.length;r++){let i=this.bumps[r];if(i===e)return r;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot()){i.combine(e),t=r;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));let r=this.bumps[t];for(let e of this.txs){let i=e.txid;if(null==e.bumpIndex){for(let n of r.path[0])if(n.hash===i){e.bumpIndex=t,n.txid=!0;break}}}return t}mergeRawTx(e,t){this.markMutated(!0);let r=new rj(e,t);return this.removeExistingTxid(r.txid),this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(e){let t;this.markMutated(!0);let r=e.id("hex");this.removeExistingTxid(r),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let i=new rj(e,t);if(this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),void 0===(t=i.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return i}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new rj(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=Array.isArray(e)?rZ.fromBinary(e):e;for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let r=this.verifyValid(t);if(!r.valid)return!1;for(let t of Object.keys(r.roots))if(!await e.isValidRootForHeight(r.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==e||r.withMissingInputs.length>0)return t;let i={};for(let r of this.txs)if(r.isTxidOnly){if(!0!==e)return t;i[r.txid]=!0}let n=(e,r)=>{let i=e.computeRoot(r);return(void 0===t.roots[e.blockHeight]||""===t.roots[e.blockHeight])&&(t.roots[e.blockHeight]=i),t.roots[e.blockHeight]===i};for(let e of this.bumps)for(let r of e.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(e,r.hash)))return t;for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return t;for(let e of this.txs){for(let r of e.inputTxids)if(!i[r])return t;i[e.txid]=!0}return t.valid=!0,t}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let r=this.txs[this.txs.length-1]===t?this:this.clone();if(r!==this){let t=this.txs.findIndex(t=>t.txid===e);r.txs.splice(t+1)}let i=new tu;return i.writeUInt32LE(rJ),i.writeReverse(e9(e,"hex")),r.toWriter(i),i.toArray()}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rX?rX.from(e).toString("hex"):e7(Array.from(e));return this.hexCache=t,t}static fromReader(e){let t,r=e.readUInt32LE();if(r===rJ&&(t=e7(e.readReverse(32)),r=e.readUInt32LE()),r!==rG&&r!==rY)throw Error(`Serialized BEEF must start with ${rG} or ${rY} but starts with ${r}`);let i=new rZ(r),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=rW.fromReader(e,!1);i.bumps.push(t)}let a=e.readVarIntNum();for(let t=0;t<a;t++){let t=rj.fromReader(e,r);i.txs.push(t)}return i.atomicTxid=t,i}static fromBinary(e){let t=new td(e);return rZ.fromReader(t)}static fromString(e,t="hex"){let r=new td(e9(e,t));return rZ.fromReader(r)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let r=0;r<this.bumps.length;r++){let i=this.bumps[r].path[0].findIndex(e=>e.hash===t);if(i>=0)return e.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){let e={},t={},r=[],i=[],n=[];for(let a of this.txs)t[a.txid]=a,a.isValid=a.hasProof,a.isValid?(e[a.txid]=!0,i.push(a)):a.isTxidOnly&&0===a.inputTxids.length?(e[a.txid]=!0,n.push(a)):r.push(a);let a={},s=[],o=r;for(let e of(r=[],o)){let i=!1;for(let r of e.inputTxids)void 0===t[r]&&(a[r]=!0,i=!0);i?s.push(e):r.push(e)}for(;r.length>0;){let t=r;for(let n of(r=[],t))n.inputTxids.every(t=>e[t])?(e[n.txid]=!0,i.push(n)):r.push(n);if(t.length===r.length)break}let c=r;return this.txs=s.concat(c).concat(n).concat(i),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:c.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:n.map(e=>e.txid)}}clone(){let e=new rZ;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e}trimKnownTxids(e){let t=!1;for(let r=0;r<this.txs.length;){let i=this.txs[r];i.isTxidOnly&&e.includes(i.txid)?(this.deleteFromIndex(i.txid),this.txs.splice(r,1),t=!0):r++}t&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
6
|
+
IfStack: [${e.ifStackState.join(", ")}]`),this.name=this.constructor.name,this.txid=e.txid,this.outputIndex=e.outputIndex,this.context=e.context,this.programCounter=e.programCounter,this.stackState=e.stackState.map(e=>e.slice()),this.altStackState=e.altStackState.map(e=>e.slice()),this.ifStackState=e.ifStackState.slice(),this.stackMem=e.stackMem,this.altStackMem=e.altStackMem}}let rv=BigInt(0x7fffffff),rI=Object.freeze(new m(-1).toScriptNum()),rk=Object.freeze(Array.from({length:17},(e,t)=>Object.freeze(new m(t).toScriptNum())));class rS{sourceTXID;sourceOutputIndex;sourceSatoshis;lockingScript;transactionVersion;otherInputs;outputs;inputIndex;unlockingScript;inputSequence;lockTime;context;programCounter;lastCodeSeparator;stack;altStack;ifStack;memoryLimit;stackMem;altStackMem;sigHashCache;constructor(e){this.sourceTXID=e.sourceTXID,this.sourceOutputIndex=e.sourceOutputIndex,this.sourceSatoshis=e.sourceSatoshis,this.lockingScript=e.lockingScript,this.transactionVersion=e.transactionVersion,this.otherInputs=e.otherInputs,this.outputs=e.outputs,this.inputIndex=e.inputIndex,this.unlockingScript=e.unlockingScript,this.inputSequence=e.inputSequence,this.lockTime=e.lockTime,this.memoryLimit=e.memoryLimit??32e6,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map},this.reset()}reset(){this.context="UnlockingScript",this.programCounter=0,this.lastCodeSeparator=null,this.stack=[],this.altStack=[],this.ifStack=[],this.stackMem=0,this.altStackMem=0,this.sigHashCache={hashOutputsSingle:new Map}}ensureStackMem(e){this.stackMem+e>this.memoryLimit&&this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}ensureAltStackMem(e){this.altStackMem+e>this.memoryLimit&&this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes")}pushStack(e){this.ensureStackMem(e.length),this.stack.push(e),this.stackMem+=e.length}pushStackCopy(e){this.ensureStackMem(e.length);let t=e.slice();this.stack.push(t),this.stackMem+=t.length}popStack(){0===this.stack.length&&this.scriptEvaluationError("Attempted to pop from an empty stack.");let e=this.stack.pop();return this.stackMem-=e.length,e}stackTop(e=-1){return(0===this.stack.length||this.stack.length<Math.abs(e)||e>=0&&e>=this.stack.length)&&this.scriptEvaluationError(`Stack underflow accessing element at index ${e}. Stack length is ${this.stack.length}.`),this.stack[this.stack.length+e]}pushAltStack(e){this.ensureAltStackMem(e.length),this.altStack.push(e),this.altStackMem+=e.length}popAltStack(){0===this.altStack.length&&this.scriptEvaluationError("Attempted to pop from an empty alt stack.");let e=this.altStack.pop();return this.altStackMem-=e.length,e}checkSignatureEncoding(e){if(0===e.length)return!0;if(!function(e){if(e.length<9||e.length>73||48!==e[0]||e[1]!==e.length-3)return!1;let t=e[2],r=e[3];if(2!==t||0===r||5+r>=e.length)return!1;let i=4+r,n=e[i],a=e[i+1];if(2!==n||0===a||(128&e[4])!=0||r>1&&0===e[4]&&(128&e[5])==0)return!1;let s=i+2;return(128&e[s])==0&&(!(a>1)||0!==e[s]||(128&e[s+1])!=0)&&r+a+7===e.length}(e))return this.scriptEvaluationError("The signature format is invalid."),!1;try{let t=ri.fromChecksigFormat(e);if(!t.hasLowS())return this.scriptEvaluationError("The signature must have a low S value."),!1;if((t.scope&ri.SIGHASH_FORKID)==0)return this.scriptEvaluationError("The signature must use SIGHASH_FORKID."),!1}catch(e){return this.scriptEvaluationError("The signature format is invalid."),!1}return!0}checkPublicKeyEncoding(e){if(0===e.length)return this.scriptEvaluationError("Public key is empty."),!1;if(e.length<33)return this.scriptEvaluationError("The public key is too short, it must be at least 33 bytes."),!1;if(4===e[0]){if(65!==e.length)return this.scriptEvaluationError("The non-compressed public key must be 65 bytes."),!1}else if(2!==e[0]&&3!==e[0])return this.scriptEvaluationError("The public key is in an unknown format."),!1;else if(33!==e.length)return this.scriptEvaluationError("The compressed public key must be 33 bytes."),!1;try{tL.fromDER(e)}catch(e){return this.scriptEvaluationError("The public key is in an unknown format."),!1}return!0}verifySignature(e,t,r){return tF(new m(Q(ri.formatBytes({sourceTXID:this.sourceTXID,sourceOutputIndex:this.sourceOutputIndex,sourceSatoshis:this.sourceSatoshis,transactionVersion:this.transactionVersion,otherInputs:this.otherInputs,outputs:this.outputs,inputIndex:this.inputIndex,subscript:r,inputSequence:this.inputSequence,lockTime:this.lockTime,scope:e.scope,cache:this.sigHashCache}))),e,t)}step(){if(this.stackMem>this.memoryLimit)return this.scriptEvaluationError("Stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;if(this.altStackMem>this.memoryLimit)return this.scriptEvaluationError("Alt stack memory usage has exceeded "+String(this.memoryLimit)+" bytes"),!1;"UnlockingScript"===this.context&&this.programCounter>=this.unlockingScript.chunks.length&&(this.context="LockingScript",this.programCounter=0);let e="UnlockingScript"===this.context?this.unlockingScript:this.lockingScript;if(this.programCounter>=e.chunks.length)return!1;let t=e.chunks[this.programCounter],r=t.op;void 0===r&&this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`),Array.isArray(t.data)&&t.data.length>0x40000000&&this.scriptEvaluationError(`Data push > 1073741824 bytes (pc=${this.programCounter}).`);let i=!this.ifStack.includes(!1);if(i&&(r===rp.OP_2MUL||r===rp.OP_2DIV||r===rp.OP_VERIF||r===rp.OP_VERNOTIF||r===rp.OP_VER)&&this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${rp[r]}, PC: ${this.programCounter})`),i&&r>=0&&r<=rp.OP_PUSHDATA4)!function(e){let t=e.data,r=e.op;return!Array.isArray(t)||(0===t.length?r===rp.OP_0:1===t.length&&t[0]>=1&&t[0]<=16?r===rp.OP_1+(t[0]-1):1===t.length&&129===t[0]?r===rp.OP_1NEGATE:t.length<=75?r===t.length:t.length<=255?r===rp.OP_PUSHDATA1:!(t.length<=65535)||r===rp.OP_PUSHDATA2)}(t)&&this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`),this.pushStack(Array.isArray(t.data)?t.data:[]);else if(i||r>=rp.OP_IF&&r<=rp.OP_ENDIF){let e,t,n,a,s,o,c,l,h,u,d,f,p,g,b,y,w,v,I,k,S,x,E,P,N,O;switch(r){case rp.OP_1NEGATE:this.pushStackCopy(rI);break;case rp.OP_0:this.pushStackCopy(rk[0]);break;case rp.OP_1:case rp.OP_2:case rp.OP_3:case rp.OP_4:case rp.OP_5:case rp.OP_6:case rp.OP_7:case rp.OP_8:case rp.OP_9:case rp.OP_10:case rp.OP_11:case rp.OP_12:case rp.OP_13:case rp.OP_14:case rp.OP_15:case rp.OP_16:f=r-(rp.OP_1-1),this.pushStackCopy(rk[f]);break;case rp.OP_NOP:case rp.OP_NOP2:case rp.OP_NOP3:case rp.OP_NOP1:case rp.OP_NOP4:case rp.OP_NOP5:case rp.OP_NOP6:case rp.OP_NOP7:case rp.OP_NOP8:case rp.OP_NOP9:case rp.OP_NOP10:case rp.OP_NOP11:case rp.OP_NOP12:case rp.OP_NOP13:case rp.OP_NOP14:case rp.OP_NOP15:case rp.OP_NOP16:case rp.OP_NOP17:case rp.OP_NOP18:case rp.OP_NOP19:case rp.OP_NOP20:case rp.OP_NOP21:case rp.OP_NOP22:case rp.OP_NOP23:case rp.OP_NOP24:case rp.OP_NOP25:case rp.OP_NOP26:case rp.OP_NOP27:case rp.OP_NOP28:case rp.OP_NOP29:case rp.OP_NOP30:case rp.OP_NOP31:case rp.OP_NOP32:case rp.OP_NOP33:case rp.OP_NOP34:case rp.OP_NOP35:case rp.OP_NOP36:case rp.OP_NOP37:case rp.OP_NOP38:case rp.OP_NOP39:case rp.OP_NOP40:case rp.OP_NOP41:case rp.OP_NOP42:case rp.OP_NOP43:case rp.OP_NOP44:case rp.OP_NOP45:case rp.OP_NOP46:case rp.OP_NOP47:case rp.OP_NOP48:case rp.OP_NOP49:case rp.OP_NOP50:case rp.OP_NOP51:case rp.OP_NOP52:case rp.OP_NOP53:case rp.OP_NOP54:case rp.OP_NOP55:case rp.OP_NOP56:case rp.OP_NOP57:case rp.OP_NOP58:case rp.OP_NOP59:case rp.OP_NOP60:case rp.OP_NOP61:case rp.OP_NOP62:case rp.OP_NOP63:case rp.OP_NOP64:case rp.OP_NOP65:case rp.OP_NOP66:case rp.OP_NOP67:case rp.OP_NOP68:case rp.OP_NOP69:case rp.OP_NOP70:case rp.OP_NOP71:case rp.OP_NOP72:case rp.OP_NOP73:case rp.OP_NOP77:break;case rp.OP_IF:case rp.OP_NOTIF:g=!1,i&&(this.stack.length<1&&this.scriptEvaluationError("OP_IF and OP_NOTIF require at least one item on the stack when they are used!"),e=this.popStack(),g=this.castToBool(e),r===rp.OP_NOTIF&&(g=!g)),this.ifStack.push(g);break;case rp.OP_ELSE:0===this.ifStack.length&&this.scriptEvaluationError("OP_ELSE requires a preceeding OP_IF."),this.ifStack[this.ifStack.length-1]=!this.ifStack[this.ifStack.length-1];break;case rp.OP_ENDIF:0===this.ifStack.length&&this.scriptEvaluationError("OP_ENDIF requires a preceeding OP_IF."),this.ifStack.pop();break;case rp.OP_VERIFY:this.stack.length<1&&this.scriptEvaluationError("OP_VERIFY requires at least one item to be on the stack."),t=this.stackTop(),(g=this.castToBool(t))||this.scriptEvaluationError("OP_VERIFY requires the top stack value to be truthy."),this.popStack();break;case rp.OP_RETURN:"UnlockingScript"===this.context?this.programCounter=this.unlockingScript.chunks.length:this.programCounter=this.lockingScript.chunks.length,this.ifStack=[],this.programCounter--;break;case rp.OP_TOALTSTACK:this.stack.length<1&&this.scriptEvaluationError("OP_TOALTSTACK requires at oeast one item to be on the stack."),this.pushAltStack(this.popStack());break;case rp.OP_FROMALTSTACK:this.altStack.length<1&&this.scriptEvaluationError("OP_FROMALTSTACK requires at least one item to be on the stack."),this.pushStack(this.popAltStack());break;case rp.OP_2DROP:this.stack.length<2&&this.scriptEvaluationError("OP_2DROP requires at least two items to be on the stack."),this.popStack(),this.popStack();break;case rp.OP_2DUP:this.stack.length<2&&this.scriptEvaluationError("OP_2DUP requires at least two items to be on the stack."),t=this.stackTop(-2),n=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n);break;case rp.OP_3DUP:this.stack.length<3&&this.scriptEvaluationError("OP_3DUP requires at least three items to be on the stack."),t=this.stackTop(-3),n=this.stackTop(-2),a=this.stackTop(-1),this.pushStackCopy(t),this.pushStackCopy(n),this.pushStackCopy(a);break;case rp.OP_2OVER:this.stack.length<4&&this.scriptEvaluationError("OP_2OVER requires at least four items to be on the stack."),t=this.stackTop(-4),n=this.stackTop(-3),this.pushStackCopy(t),this.pushStackCopy(n);break;case rp.OP_2ROT:{this.stack.length<6&&this.scriptEvaluationError("OP_2ROT requires at least six items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack(),n=this.popStack(),a=this.popStack();this.pushStack(i),this.pushStack(r),this.pushStack(t),this.pushStack(e),this.pushStack(a),this.pushStack(n);break}case rp.OP_2SWAP:{this.stack.length<4&&this.scriptEvaluationError("OP_2SWAP requires at least four items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=this.popStack(),i=this.popStack();this.pushStack(t),this.pushStack(e),this.pushStack(i),this.pushStack(r);break}case rp.OP_IFDUP:this.stack.length<1&&this.scriptEvaluationError("OP_IFDUP requires at least one item to be on the stack."),t=this.stackTop(),this.castToBool(t)&&this.pushStackCopy(t);break;case rp.OP_DEPTH:this.pushStack(new m(this.stack.length).toScriptNum());break;case rp.OP_DROP:this.stack.length<1&&this.scriptEvaluationError("OP_DROP requires at least one item to be on the stack."),this.popStack();break;case rp.OP_DUP:this.stack.length<1&&this.scriptEvaluationError("OP_DUP requires at least one item to be on the stack."),this.pushStackCopy(this.stackTop());break;case rp.OP_NIP:this.stack.length<2&&this.scriptEvaluationError("OP_NIP requires at least two items to be on the stack."),n=this.popStack(),this.popStack(),this.pushStack(n);break;case rp.OP_OVER:this.stack.length<2&&this.scriptEvaluationError("OP_OVER requires at least two items to be on the stack."),this.pushStackCopy(this.stackTop(-2));break;case rp.OP_PICK:case rp.OP_ROLL:{this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items to be on the stack.`);let e=(l=m.fromScriptNum(this.popStack(),!0)).toBigInt();(e<0n||e>=BigInt(this.stack.length))&&this.scriptEvaluationError(`${rp[r]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);let t=Number(e),i=this.stack[this.stack.length-1-t];r===rp.OP_ROLL?(this.stack.splice(this.stack.length-1-t,1),this.stackMem-=i.length,this.pushStack(i)):this.pushStackCopy(i);break}case rp.OP_ROT:this.stack.length<3&&this.scriptEvaluationError("OP_ROT requires at least three items to be on the stack."),c=this.popStack(),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(c),this.pushStack(s);break;case rp.OP_SWAP:this.stack.length<2&&this.scriptEvaluationError("OP_SWAP requires at least two items to be on the stack."),o=this.popStack(),s=this.popStack(),this.pushStack(o),this.pushStack(s);break;case rp.OP_TUCK:this.stack.length<2&&this.scriptEvaluationError("OP_TUCK requires at least two items to be on the stack."),t=this.stackTop(-1),this.ensureStackMem(t.length),this.stack.splice(this.stack.length-2,0,t.slice()),this.stackMem+=t.length;break;case rp.OP_SIZE:this.stack.length<1&&this.scriptEvaluationError("OP_SIZE requires at least one item to be on the stack."),this.pushStack(new m(this.stackTop().length).toScriptNum());break;case rp.OP_AND:case rp.OP_OR:case rp.OP_XOR:{this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items on the stack.`),n=this.popStack(),(t=this.popStack()).length!==n.length&&this.scriptEvaluationError(`${rp[r]} requires the top two stack items to be the same size.`);let e=Array(t.length);for(let i=0;i<t.length;i++)r===rp.OP_AND?e[i]=t[i]&n[i]:r===rp.OP_OR?e[i]=t[i]|n[i]:e[i]=t[i]^n[i];this.pushStack(e);break}case rp.OP_INVERT:{this.stack.length<1&&this.scriptEvaluationError("OP_INVERT requires at least one item to be on the stack.");let t=Array((e=this.popStack()).length);for(let r=0;r<e.length;r++)t[r]=255&~e[r];this.pushStack(t);break}case rp.OP_LSHIFT:case rp.OP_RSHIFT:{this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items to be on the stack.`),u=m.fromScriptNum(this.popStack(),!0),t=this.popStack();let e=u.toBigInt();if(e<0n&&this.scriptEvaluationError(`${rp[r]} requires the top item on the stack not to be negative.`),0===t.length){this.pushStack([]);break}h=new m(t);let i=(r===rp.OP_LSHIFT?h.ushln(e):h.ushrn(e)).toArray("be",t.length);this.pushStack(i);break}case rp.OP_EQUAL:case rp.OP_EQUALVERIFY:this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items to be on the stack.`),n=this.popStack(),g=function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}(t=this.popStack(),n),this.pushStack(g?[1]:[]),r===rp.OP_EQUALVERIFY&&(g||this.scriptEvaluationError("OP_EQUALVERIFY requires the top two stack items to be equal."),this.popStack());break;case rp.OP_1ADD:case rp.OP_1SUB:case rp.OP_NEGATE:case rp.OP_ABS:case rp.OP_NOT:case rp.OP_0NOTEQUAL:switch(this.stack.length<1&&this.scriptEvaluationError(`${rp[r]} requires at least one item to be on the stack.`),l=m.fromScriptNum(this.popStack(),!0),r){case rp.OP_1ADD:l=l.add(new m(1));break;case rp.OP_1SUB:l=l.sub(new m(1));break;case rp.OP_NEGATE:l=l.neg();break;case rp.OP_ABS:l.isNeg()&&(l=l.neg());break;case rp.OP_NOT:l=new m(+(0===l.cmpn(0)));break;case rp.OP_0NOTEQUAL:l=new m(+(0!==l.cmpn(0)))}this.pushStack(l.toScriptNum());break;case rp.OP_ADD:case rp.OP_SUB:case rp.OP_MUL:case rp.OP_DIV:case rp.OP_MOD:case rp.OP_BOOLAND:case rp.OP_BOOLOR:case rp.OP_NUMEQUAL:case rp.OP_NUMEQUALVERIFY:case rp.OP_NUMNOTEQUAL:case rp.OP_LESSTHAN:case rp.OP_GREATERTHAN:case rp.OP_LESSTHANOREQUAL:case rp.OP_GREATERTHANOREQUAL:case rp.OP_MIN:case rp.OP_MAX:{this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items to be on the stack.`),n=this.popStack(),t=this.popStack(),u=m.fromScriptNum(n,!0),h=m.fromScriptNum(t,!0);let e=0;switch(r){case rp.OP_MUL:e=h.byteLength()+u.byteLength();break;case rp.OP_ADD:case rp.OP_SUB:e=Math.max(h.byteLength(),u.byteLength())+1;break;default:e=Math.max(h.byteLength(),u.byteLength())}this.ensureStackMem(e);let i=new m(0);switch(r){case rp.OP_ADD:i=h.add(u);break;case rp.OP_SUB:i=h.sub(u);break;case rp.OP_MUL:i=h.mul(u);break;case rp.OP_DIV:0===u.cmpn(0)&&this.scriptEvaluationError("OP_DIV cannot divide by zero!"),i=h.div(u);break;case rp.OP_MOD:0===u.cmpn(0)&&this.scriptEvaluationError("OP_MOD cannot divide by zero!"),i=h.mod(u);break;case rp.OP_BOOLAND:i=new m(+(0!==h.cmpn(0)&&0!==u.cmpn(0)));break;case rp.OP_BOOLOR:i=new m(+(0!==h.cmpn(0)||0!==u.cmpn(0)));break;case rp.OP_NUMEQUAL:case rp.OP_NUMEQUALVERIFY:i=new m(+(0===h.cmp(u)));break;case rp.OP_NUMNOTEQUAL:i=new m(+(0!==h.cmp(u)));break;case rp.OP_LESSTHAN:i=new m(+(0>h.cmp(u)));break;case rp.OP_GREATERTHAN:i=new m(+(h.cmp(u)>0));break;case rp.OP_LESSTHANOREQUAL:i=new m(+(0>=h.cmp(u)));break;case rp.OP_GREATERTHANOREQUAL:i=new m(+(h.cmp(u)>=0));break;case rp.OP_MIN:i=0>h.cmp(u)?h:u;break;case rp.OP_MAX:i=h.cmp(u)>0?h:u}this.pushStack(i.toScriptNum()),r===rp.OP_NUMEQUALVERIFY&&(this.castToBool(this.stackTop())||this.scriptEvaluationError("OP_NUMEQUALVERIFY requires the top stack item to be truthy."),this.popStack());break}case rp.OP_WITHIN:this.stack.length<3&&this.scriptEvaluationError("OP_WITHIN requires at least three items to be on the stack."),d=m.fromScriptNum(this.popStack(),!0),u=m.fromScriptNum(this.popStack(),!0),g=(h=m.fromScriptNum(this.popStack(),!0)).cmp(u)>=0&&0>h.cmp(d),this.pushStack(g?[1]:[]);break;case rp.OP_RIPEMD160:case rp.OP_SHA1:case rp.OP_SHA256:case rp.OP_HASH160:case rp.OP_HASH256:{this.stack.length<1&&this.scriptEvaluationError(`${rp[r]} requires at least one item to be on the stack.`),e=this.popStack();let t=[];r===rp.OP_RIPEMD160?t=X(e):r===rp.OP_SHA1?t=J(e):r===rp.OP_SHA256?t=Y(e):r===rp.OP_HASH160?t=ee(e):r===rp.OP_HASH256&&(t=Q(e)),this.pushStack(t);break}case rp.OP_CODESEPARATOR:this.lastCodeSeparator=this.programCounter;break;case rp.OP_CHECKSIG:case rp.OP_CHECKSIGVERIFY:if(this.stack.length<2&&this.scriptEvaluationError(`${rp[r]} requires at least two items to be on the stack.`),v=this.popStack(),w=this.popStack(),this.checkSignatureEncoding(w)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${rp[r]} requires correct encoding for the public key and signature.`),(y=new rb(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1))).findAndDelete(new rb().writeBin(w)),b=!1,w.length>0)try{I=ri.fromChecksigFormat(w),k=tL.fromDER(v),b=this.verifySignature(I,k,y)}catch(e){b=!1}this.pushStack(b?[1]:[]),r===rp.OP_CHECKSIGVERIFY&&(b||this.scriptEvaluationError("OP_CHECKSIGVERIFY requires that a valid signature is provided."),this.popStack());break;case rp.OP_CHECKMULTISIG:case rp.OP_CHECKMULTISIGVERIFY:{S=1,this.stack.length<S&&this.scriptEvaluationError(`${rp[r]} requires at least 1 item for nKeys.`);let e=m.fromScriptNum(this.stackTop(-S),!0).toBigInt();(e<0n||e>rv)&&this.scriptEvaluationError(`${rp[r]} requires a key count between 0 and 2147483647.`);let t=P=Number(e);x=++S,S+=P,this.stack.length<S&&this.scriptEvaluationError(`${rp[r]} stack too small for nKeys and keys. Need ${S}, have ${this.stack.length}.`);let i=m.fromScriptNum(this.stackTop(-S),!0).toBigInt();(i<0n||i>BigInt(P))&&this.scriptEvaluationError(`${rp[r]} requires the number of signatures to be no greater than the number of keys.`);let n=N=Number(i);E=++S,S+=N,this.stack.length<S&&this.scriptEvaluationError(`${rp[r]} stack too small for N, keys, M, sigs, and dummy. Need ${S}, have ${this.stack.length}.`),y=new rb(("UnlockingScript"===this.context?this.unlockingScript:this.lockingScript).chunks.slice(null===this.lastCodeSeparator?0:this.lastCodeSeparator+1));for(let e=0;e<N;e++)w=this.stackTop(-E-e),y.findAndDelete(new rb().writeBin(w));for(b=!0;b&&N>0;){if(0===P){b=!1;break}if(w=this.stackTop(-E),v=this.stackTop(-x),this.checkSignatureEncoding(w)&&this.checkPublicKeyEncoding(v)||this.scriptEvaluationError(`${rp[r]} requires correct encoding for the public key and signature.`),O=!1,w.length>0)try{I=ri.fromChecksigFormat(w),k=tL.fromDER(v),O=this.verifySignature(I,k,y)}catch(e){O=!1}O&&(E++,N--),x++,N>--P&&(b=!1)}let a=1+t+1+n+1-1;for(;a>0;)this.popStack(),a--;this.stack.length<1&&this.scriptEvaluationError(`${rp[r]} requires an extra item (dummy) to be on the stack.`),this.popStack().length>0&&this.scriptEvaluationError(`${rp[r]} requires the extra stack item (dummy) to be empty.`),this.pushStack(b?[1]:[]),r===rp.OP_CHECKMULTISIGVERIFY&&(b||this.scriptEvaluationError("OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided."),this.popStack());break}case rp.OP_CAT:{this.stack.length<2&&this.scriptEvaluationError("OP_CAT requires at least two items to be on the stack."),n=this.popStack();let e=(t=this.popStack()).concat(n);e.length>0x40000000&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes."),this.pushStack(e);break}case rp.OP_SPLIT:{this.stack.length<2&&this.scriptEvaluationError("OP_SPLIT requires at least two items to be on the stack.");let e=this.popStack(),t=this.popStack(),r=m.fromScriptNum(e,!0).toBigInt();(r<0n||r>BigInt(t.length))&&this.scriptEvaluationError("OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.");let i=Number(r);this.pushStack(t.slice(0,i)),this.pushStack(t.slice(i));break}case rp.OP_NUM2BIN:{this.stack.length<2&&this.scriptEvaluationError("OP_NUM2BIN requires at least two items to be on the stack.");let e=m.fromScriptNum(this.popStack(),!0).toBigInt();(e>BigInt(0x40000000)||e<0n)&&this.scriptEvaluationError("It's not currently possible to push data larger than 1073741824 bytes or negative size."),p=Number(e);let t=this.popStack();if((t=ta(t)).length>p&&this.scriptEvaluationError("OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item."),t.length===p){this.pushStack(t);break}let r=Array(p).fill(0),i=0;t.length>0&&(i=128&t[t.length-1],t[t.length-1]&=127);for(let e=0;e<t.length;e++)r[e]=t[e];0!==i&&(r[p-1]|=128),this.pushStack(r);break}case rp.OP_BIN2NUM:{this.stack.length<1&&this.scriptEvaluationError("OP_BIN2NUM requires at least one item to be on the stack.");let e=ta(t=this.popStack());!function(e,t=Number.MAX_SAFE_INTEGER){return!(e.length>t)&&(!(e.length>0)||(127&e[e.length-1])!=0||!(e.length<=1)&&(128&e[e.length-2])!=0)}(e)&&this.scriptEvaluationError("OP_BIN2NUM requires that the resulting number is valid."),this.pushStack(e);break}default:this.scriptEvaluationError(`Invalid opcode ${r} (pc=${this.programCounter}).`)}}return this.programCounter++,!0}validate(){for(this.unlockingScript.isPushOnly()||this.scriptEvaluationError("Unlocking scripts can only contain push operations, and no other opcodes.");this.step()&&("LockingScript"!==this.context||!(this.programCounter>=this.lockingScript.chunks.length)););return this.ifStack.length>0&&this.scriptEvaluationError("Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script."),1!==this.stack.length&&this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`),0===this.stack.length?this.scriptEvaluationError("The top stack element must be truthy after script evaluation (stack is empty)."):this.castToBool(this.stackTop())||this.scriptEvaluationError("The top stack element must be truthy after script evaluation."),!0}castToBool(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(0!==e[t])return t!==e.length-1||128!==e[t];return!1}scriptEvaluationError(e){throw new rw({message:e,txid:this.sourceTXID,outputIndex:this.sourceOutputIndex,context:this.context,programCounter:this.programCounter,stackState:this.stack,altStackState:this.altStack,ifStackState:this.ifStack,stackMem:this.stackMem,altStackMem:this.altStackMem})}}class rx{lock(e){let t;if("string"==typeof e){let r=tr(e);if(0!==r.prefix[0]&&111!==r.prefix[0])throw Error("only P2PKH is supported");t=r.data}else t=e;if(20!==t.length)throw Error("P2PKH hash length must be 20 bytes");return new ry([{op:rp.OP_DUP},{op:rp.OP_HASH160},{op:t.length,data:t},{op:rp.OP_EQUALVERIFY},{op:rp.OP_CHECKSIG}])}unlock(e,t="all",r=!1,i,n){return{sign:async(a,s)=>{let o=ri.SIGHASH_FORKID;"all"===t&&(o|=ri.SIGHASH_ALL),"none"===t&&(o|=ri.SIGHASH_NONE),"single"===t&&(o|=ri.SIGHASH_SINGLE),r&&(o|=ri.SIGHASH_ANYONECANPAY);let c=a.inputs[s],l=a.inputs.filter((e,t)=>t!==s),h=c.sourceTXID??c.sourceTransaction?.id("hex");if(null==h||void 0===h||""===h)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(i||=c.sourceTransaction?.outputs[c.sourceOutputIndex].satoshis)||void 0===i)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(n||=c.sourceTransaction?.outputs[c.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let u=ri.format({sourceTXID:h,sourceOutputIndex:tc(c.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:i,transactionVersion:a.version,otherInputs:l,inputIndex:s,outputs:a.outputs,inputSequence:tc(c.sequence,"input.sequence must have value"),subscript:n,lockTime:a.lockTime,scope:o}),d=e.sign(Y(u)),f=new ri(d.r,d.s,o).toChecksigFormat(),p=e.toPublicKey().encode(!0);return new rm([{op:f.length,data:f},{op:p.length,data:p}])},estimateLength:async()=>108}}}class rE{type="raw";constructor(e="raw"){this.type=e}lock(e){let t=[{op:rp.OP_OVER},{op:rp.OP_3},{op:rp.OP_SPLIT},{op:rp.OP_NIP},{op:rp.OP_1},{op:rp.OP_SPLIT},{op:rp.OP_SWAP},{op:rp.OP_SPLIT},{op:rp.OP_DROP}];return"raw"!==this.type&&t.push({op:rp["OP_"+this.type]}),t.push({op:e.length,data:e}),t.push({op:rp.OP_EQUALVERIFY}),t.push({op:rp.OP_CHECKSIG}),new ry(t)}unlock(e,t,r="all",i=!1){return{sign:async(n,a)=>{void 0===t&&(t=tW.fromRandom());let s=ri.SIGHASH_FORKID;"all"===r&&(s|=ri.SIGHASH_ALL),"none"===r&&(s|=ri.SIGHASH_NONE),"single"===r&&(s|=ri.SIGHASH_SINGLE),i&&(s|=ri.SIGHASH_ANYONECANPAY);let o=[...n.inputs],[c]=o.splice(a,1);if("object"!=typeof c.sourceTransaction)throw Error("The source transaction is needed for transaction signing.");let l=ri.format({sourceTXID:c.sourceTransaction?.id("hex")??"",sourceOutputIndex:c.sourceOutputIndex??0,sourceSatoshis:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.satoshis??0,transactionVersion:n.version,otherInputs:o,inputIndex:a,outputs:n.outputs,inputSequence:c.sequence??0xffffffff,subscript:c.sourceTransaction?.outputs[c.sourceOutputIndex]?.lockingScript??new rb,lockTime:n.lockTime,scope:s}),h=t.sign(Y(l),void 0,!0,e),u=new ri(h.r,h.s,s).toChecksigFormat(),d=t.toPublicKey().encode(!0);return new rm([{op:u.length,data:u},{op:d.length,data:d}])},estimateLength:async()=>108}}}let rP=e=>0===e.length||1===e.length&&0===e[0]?{op:0}:1===e.length&&e[0]>0&&e[0]<=16?{op:80+e[0]}:1===e.length&&129===e[0]?{op:79}:e.length<=75?{op:e.length,data:e}:e.length<=255?{op:76,data:e}:e.length<=65535?{op:77,data:e}:{op:78,data:e};class rN{wallet;originator;static decode(e){let t=tL.fromString(e0(tc(e.chunks[0].data,"script.chunks[0].data must have value"))),r=[];for(let t=2;t<e.chunks.length;t++){let i=e.chunks[t+1]?.op,n=e.chunks[t].data??[];if(0===n.length&&(e.chunks[t].op>=80&&e.chunks[t].op<=95?n=[e.chunks[t].op-80]:0===e.chunks[t].op?n=[0]:79===e.chunks[t].op&&(n=[129])),r.push(n),i===rp.OP_DROP||i===rp.OP_2DROP)break}return{fields:r,lockingPublicKey:t}}constructor(e,t){this.wallet=e,this.originator=t}async lock(e,t,r,i,n=!1,a=!0,s="before"){let{publicKey:o}=await this.wallet.getPublicKey({protocolID:t,keyID:r,counterparty:i,forSelf:n},this.originator),c=[],l=[];if(c.push({op:o.length/2,data:e1(o,"hex")}),c.push({op:rp.OP_CHECKSIG}),a){let n=e.reduce((e,t)=>[...e,...t],[]),{signature:a}=await this.wallet.createSignature({data:n,protocolID:t,keyID:r,counterparty:i},this.originator);e.push(a)}for(let t of e)l.push(rP(t));let h=e.length;for(;h>1;)l.push({op:rp.OP_2DROP}),h-=2;return new ry((0!==h&&l.push({op:rp.OP_DROP}),"before"===s)?[...c,...l]:[...l,...c])}unlock(e,t,r,i="all",n=!1,a,s){return{sign:async(o,c)=>{let l=ri.SIGHASH_FORKID;"all"===i&&(l|=ri.SIGHASH_ALL),"none"===i&&(l|=ri.SIGHASH_NONE),"single"===i&&(l|=ri.SIGHASH_SINGLE),n&&(l|=ri.SIGHASH_ANYONECANPAY);let h=o.inputs[c],u=o.inputs.filter((e,t)=>t!==c),d=h.sourceTXID??h.sourceTransaction?.id("hex");if(null==d||void 0===d)throw Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(null==(a||=h.sourceTransaction?.outputs[h.sourceOutputIndex].satoshis)||void 0===a)throw Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(null==(s||=h.sourceTransaction?.outputs[h.sourceOutputIndex].lockingScript))throw Error("The lockingScript or input sourceTransaction is required for transaction signing.");let f=Y(ri.format({sourceTXID:d,sourceOutputIndex:tc(h.sourceOutputIndex,"input.sourceOutputIndex must have value"),sourceSatoshis:a,transactionVersion:o.version,otherInputs:u,inputIndex:c,outputs:o.outputs,inputSequence:h.sequence??0xffffffff,subscript:s,lockTime:o.lockTime,scope:l})),{signature:p}=await this.wallet.createSignature({data:f,protocolID:e,keyID:t,counterparty:r},this.originator),g=t_.fromDER([...p]),b=new ri(g.r,g.s,l).toChecksigFormat();return new rm([{op:b.length,data:b}])},estimateLength:async()=>73}}}class rO{value;constructor(e){this.value=e}async computeFee(e){let t,r=e=>e>0x100000000?9:e>65536?5:e>253?3:1;t=4+r(e.inputs.length);for(let i=0;i<e.inputs.length;i++){let n,a=e.inputs[i];if(t+=40,"object"==typeof a.unlockingScript)n=a.unlockingScript.toBinary().length;else if("object"==typeof a.unlockingScriptTemplate)n=await a.unlockingScriptTemplate.estimateLength(e,i);else throw Error("All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.");t+=r(n),t+=n}for(let i of(t+=r(e.outputs.length),e.outputs)){t+=8;let e=i.lockingScript.toBinary().length;t+=r(e),t+=e}return Math.ceil((t+=4)/1e3*this.value)}}class rA extends rO{static ARC_POLICY_URL="https://arc.gorillapool.io/v1/policy";static instance=null;cachedRate=null;cacheTimestamp=0;cacheValidityMs;constructor(e=3e5){super(100),this.cacheValidityMs=e}static getInstance(e=3e5){return rA.instance||(rA.instance=new rA(e)),rA.instance}async fetchFeeRate(){let e=Date.now();if(null!==this.cachedRate&&e-this.cacheTimestamp<this.cacheValidityMs)return this.cachedRate;try{let t=await fetch(rA.ARC_POLICY_URL);if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let r=await t.json();if(!r.policy?.miningFee||"number"!=typeof r.policy.miningFee.satoshis||"number"!=typeof r.policy.miningFee.bytes)throw Error("Invalid policy response format");let i=r.policy.miningFee.satoshis/r.policy.miningFee.bytes*1e3;return this.cachedRate=i,this.cacheTimestamp=e,i}catch(e){if(null!==this.cachedRate)return console.warn("Failed to fetch live fee rate, using cached value:",e),this.cachedRate;return console.warn("Failed to fetch live fee rate, using default 100 sat/kb:",e),100}}async computeFee(e){let t=await this.fetchFeeRate();return this.value=t,super.computeFee(e)}}class r_{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(JSON.stringify(t.data)),n.end()})}}class rT{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:JSON.stringify(t.data)},i=await this.fetch(e,r),n=i.headers.get("Content-Type"),a=n?.startsWith("application/json")?await i.json():await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:a}}}function rC(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rT(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new r_(e)}catch(t){return e}}function rR(){return`ts-sdk-${e0(tq(16))}`}class rB{URL;apiKey;deploymentId;callbackUrl;callbackToken;headers;httpClient;constructor(e,t){if(this.URL=e,"string"==typeof t)this.apiKey=t,this.httpClient=rC(),this.deploymentId=rR(),this.callbackToken=void 0,this.callbackUrl=void 0;else{let{apiKey:e,deploymentId:r,httpClient:i,callbackToken:n,callbackUrl:a,headers:s}=t??{};this.apiKey=e,this.httpClient=i??rC(),this.deploymentId=r??rR(),this.callbackToken=n,this.callbackUrl=a,this.headers=s}}requestHeaders(){let e={"Content-Type":"application/json","XDeployment-ID":this.deploymentId};if(null!=this.apiKey&&""!==this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),null!=this.callbackUrl&&""!==this.callbackUrl&&(e["X-CallbackUrl"]=this.callbackUrl),null!=this.callbackToken&&""!==this.callbackToken&&(e["X-CallbackToken"]=this.callbackToken),null!=this.headers)for(let t in this.headers)e[t]=this.headers[t];return e}async broadcast(e){let t;try{t=e.toHexEF()}catch(r){if("All inputs must have source transactions when serializing to EF format"===r.message)t=e.toHex();else throw r}let r={method:"POST",headers:this.requestHeaders(),data:{rawTx:t}};try{let e=await this.httpClient.request(`${this.URL}/v1/tx`,r);if(e.ok){let{txid:t,extraInfo:r,txStatus:i,competingTxs:n}=e.data,a={status:"success",txid:t,message:`${i} ${r}`};return null!=n&&(a.competingTxs=n),a}{let t=typeof e.status,r={status:"error",code:"number"===t||"string"===t?e.status.toString():"ERR_UNKNOWN",description:"Unknown error"},i=e.data;if("string"==typeof i)try{i=JSON.parse(e.data)}catch{}return"object"==typeof i&&(null!==i&&(r.more=i),null!=i&&"string"==typeof i.txid&&(r.txid=i.txid),null!=i&&"detail"in i&&"string"==typeof i.detail&&(r.description=i.detail)),r}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}async broadcastMany(e){let t=e.map(e=>{try{return{rawTx:e.toHexEF()}}catch(t){if("All inputs must have source transactions when serializing to EF format"===t.message)return{rawTx:e.toHex()};throw t}}),r={method:"POST",headers:this.requestHeaders(),data:t};try{return(await this.httpClient.request(`${this.URL}/v1/txs`,r)).data}catch(r){let t={status:"error",code:"500",description:"string"==typeof r.message?r.message:"Internal Server Error"};return e.map(()=>t)}}}function rV(e=!1,t={}){return new rB(e?"https://testnet.arc.gorillapool.io":"https://arc.gorillapool.io",t)}class rD{network;apiKey;URL;httpClient;constructor(e="main",t={}){let{apiKey:r,httpClient:i}=t;this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}`,this.httpClient=i??rC(),this.apiKey=r??""}async isValidRootForHeight(e,t){let r={method:"GET",headers:this.getHttpHeaders()},i=await this.httpClient.request(`${this.URL}/block/${t}/header`,r);if(i.ok){let{merkleroot:t}=i.data;return t===e}if(404===i.status)return!1;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(i.data)} `)}async currentHeight(){try{let e={method:"GET",headers:this.getHttpHeaders()},t=await this.httpClient.request(`${this.URL}/block/headers`,e);if(t.ok)return t.data[0].height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)} `)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}getHttpHeaders(){let e={Accept:"application/json"};return"string"==typeof this.apiKey&&""!==this.apiKey.trim()&&(e.Authorization=this.apiKey),e}}function rU(){return new rD}class rF{blockHeight;path;static fromHex(e){return rF.fromBinary(e1(e,"hex"))}static fromReader(e,t=!0){let r,i,n,a=e.readVarIntNum(),s=e.readUInt8(),o=Array(s).fill(null).map(()=>[]);for(let t=0;t<s;t++){for(n=e.readVarIntNum();n>0;){i=e.readVarIntNum(),r=e.readUInt8();let a={offset:i};(1&r)!=0?a.duplicate=!0:((2&r)!=0&&(a.txid=!0),a.hash=e0(e.read(32).reverse())),Array.isArray(o[t])&&0!==o[t].length||(o[t]=[]),o[t].push(a),n--}o[t].sort((e,t)=>e.offset-t.offset)}return new rF(a,o,t)}static fromBinary(e){let t=new tn(e);return rF.fromReader(t)}static fromCoinbaseTxidAndHeight(e,t){return new rF(t,[[{offset:0,hash:e,txid:!0}]])}constructor(e,t,r=!0){let i;this.blockHeight=e,this.path=t;let n=Array(this.path.length).fill(0).map(()=>new Set);this.path.forEach((e,t)=>{if(0===e.length&&0===t)throw Error(`Empty level at height: ${t}`);let i=new Set;e.forEach(e=>{if(i.has(e.offset))throw Error(`Duplicate offset: ${e.offset}, at height: ${t}`);if(i.add(e.offset),0===t){if(!0!==e.duplicate)for(let t=1;t<this.path.length;t++)n[t].add(e.offset>>t^1)}else if(r&&!n[t].has(e.offset))throw Error(`Invalid offset: ${e.offset}, at height: ${t}, with legal offsets: ${Array.from(n[t]).join(", ")}`)})}),this.path[0].forEach((e,t)=>{if(0===t&&(i=this.computeRoot(e.hash)),i!==this.computeRoot(e.hash))throw Error("Mismatched roots")})}toBinary(){let e=new ti;e.writeVarIntNum(this.blockHeight);let t=this.path.length;e.writeUInt8(t);for(let r=0;r<t;r++){let t=Object.keys(this.path[r]).length;for(let i of(e.writeVarIntNum(t),this.path[r])){e.writeVarIntNum(i.offset);let t=0;i?.duplicate===!0&&(t|=1),i?.txid!==void 0&&null!==i.txid&&(t|=2),e.writeUInt8(t),(1&t)==0&&e.write(e1(i.hash,"hex").reverse())}}return e.toArray()}toHex(){return e0(this.toBinary())}indexOf(e){let t=this.path[0].find(t=>t.hash===e);if(null==t)throw Error(`Transaction ID ${e} not found in the Merkle Path`);return t.offset}computeRoot(e){if("string"!=typeof e){let t=this.path[0].find(e=>!!e?.hash);if(null==t)throw Error("No valid leaf found in the Merkle Path");e=t.hash}if("string"!=typeof e)throw Error("Transaction ID is undefined");let t=this.indexOf(e);if("number"!=typeof t)throw Error(`This proof does not contain the txid: ${e??"undefined"}`);let r=e=>e0(Q(e1(e,"hex").reverse()).reverse()),i=e;if(1===this.path.length&&1===this.path[0].length)return i;for(let e=0;e<this.path.length;e++){this.path[e];let n=t>>e^1,a=this.findOrComputeLeaf(e,n);if("object"!=typeof a)throw Error(`Missing hash for index ${t} at height ${e}`);i=r(!0===a.duplicate?(i??"")+(i??""):n%2!=0?(a.hash??"")+(i??""):(i??"")+(a.hash??""))}return i}findOrComputeLeaf(e,t){let r=e=>e0(Q(e1(e,"hex").reverse()).reverse()),i=this.path[e].find(e=>e.offset===t);if(null!=i)return i;if(0===e)return;let n=e-1,a=t<<1,s=this.findOrComputeLeaf(n,a);if(null==s||null==s.hash||""===s.hash)return;let o=this.findOrComputeLeaf(n,a+1);if(null!=o)return{offset:t,hash:r(!0===o.duplicate?s.hash+s.hash:(o.hash??"")+(s.hash??""))}}async verify(e,t){let r=this.computeRoot(e);if(0===this.indexOf(e)){let e=await t.currentHeight();if(this.blockHeight+100<e)return!1}return await t.isValidRootForHeight(r,this.blockHeight)}combine(e){if(this.blockHeight!==e.blockHeight)throw Error("You cannot combine paths which do not have the same block height.");if(this.computeRoot()!==e.computeRoot())throw Error("You cannot combine paths which do not have the same root.");let t=[];for(let r=0;r<this.path.length;r++){t.push([]);for(let e=0;e<this.path[r].length;e++)t[r].push(this.path[r][e]);for(let i=0;i<e.path[r].length;i++)if(void 0===t[r].find(t=>t.offset===e.path[r][i].offset))t[r].push(e.path[r][i]);else if(e.path[r][i]?.txid!==void 0&&e.path[r][i]?.txid!==null){let n=t[r].find(t=>t.offset===e.path[r][i].offset);null!=n&&(n.txid=!0)}}this.path=t,this.trim()}trim(){let e=(e,t)=>{(0===t.length||t.slice(-1)[0]!==e)&&t.push(e)},t=(e,t)=>{for(let r=e.length;r>=0;r--){let i=this.path[t].findIndex(t=>t.offset===e[r]);i>=0&&this.path[t].splice(i,1)}},r=t=>{let r=[];for(let i of t)e(i>>1,r);return r},i=[],n=[];for(let e=0;e<this.path.length;e++)this.path[e].sort((e,t)=>e.offset-t.offset);for(let t=0;t<this.path[0].length;t++){let r=this.path[0][t];if(!0===r.txid)e(r.offset>>1,i);else{let i=r.offset%2==1,a=this.path[0][t+(i?-1:1)];void 0!==a.txid&&null!==a.txid&&a.txid||e(a.offset,n)}}t(n,0);for(let e=1;e<this.path.length;e++)n=i,i=r(i),t(n,e)}}class rL{_bumpIndex;_tx;_rawTx;_txid;inputTxids=[];isValid=void 0;get bumpIndex(){return this._bumpIndex}set bumpIndex(e){this._bumpIndex=e,this.updateInputTxids()}get hasProof(){return void 0!==this._bumpIndex}get isTxidOnly(){return void 0!==this._txid&&null!==this._txid&&null==this._rawTx&&null==this._tx}get txid(){if(void 0!==this._txid&&null!==this._txid&&""!==this._txid)return this._txid;if(null!=this._tx)return this._txid=this._tx.id("hex"),this._txid;if(null!=this._rawTx)return this._txid=e0(Q(this._rawTx)),this._txid;throw Error("Internal")}get tx(){return null!=this._tx?this._tx:null!=this._rawTx?(this._tx=rW.fromBinary(this._rawTx),this._tx):void 0}get rawTx(){return null!=this._rawTx?this._rawTx:null!=this._tx?(this._rawTx=this._tx.toBinary(),this._rawTx):void 0}constructor(e,t){"string"==typeof e?this._txid=e:Array.isArray(e)?this._rawTx=e:this._tx=e,this.bumpIndex=t,this.updateInputTxids()}static fromTx(e,t){return new rL(e,t)}static fromRawTx(e,t){return new rL(e,t)}static fromTxid(e,t){return new rL(e,t)}updateInputTxids(){if(this.hasProof||null==this.tx)this.inputTxids=[];else{let e={};for(let t of this.tx.inputs)void 0!==t.sourceTXID&&null!==t.sourceTXID&&""!==t.sourceTXID&&(e[t.sourceTXID]=!0);this.inputTxids=Object.keys(e)}}toWriter(e,r){let i=t=>{e.writeUInt8(t)},n=()=>{if(null==this._txid)throw Error("Transaction ID (_txid) is undefined");e.writeReverse(e1(this._txid,"hex"))},a=()=>{if(null!=this._rawTx)e.write(this._rawTx);else if(null!=this._tx)e.write(this._tx.toUint8Array());else throw Error("a valid serialized Transaction is expected")},s=()=>{void 0===this.bumpIndex?i(t.RAWTX):(i(t.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex))};r===rq?this.isTxidOnly?(i(t.TXID_ONLY),n()):(void 0!==this.bumpIndex?(i(t.RAWTX_AND_BUMP_INDEX),e.writeVarIntNum(this.bumpIndex)):i(t.RAWTX),a()):(a(),s())}static fromReader(e,r){let i,n,a;if(r===rq){let r=e.readUInt8();r===t.TXID_ONLY?a=rL.fromTxid(e0(e.readReverse(32))):(r===t.RAWTX_AND_BUMP_INDEX&&(n=e.readVarIntNum()),i=rW.fromReader(e),a=rL.fromTx(i,n))}else i=rW.fromReader(e),n=0!==e.readUInt8()?e.readVarIntNum():void 0,a=rL.fromTx(i,n);return a}}let rK="undefined"!=typeof globalThis?globalThis.Buffer:void 0,rH=0xefbe0001,rq=0xefbe0002,rM=0x1010101;!function(e){e[e.RAWTX=0]="RAWTX",e[e.RAWTX_AND_BUMP_INDEX=1]="RAWTX_AND_BUMP_INDEX",e[e.TXID_ONLY=2]="TXID_ONLY"}(t||(t={}));class r${bumps=[];txs=[];version=rq;atomicTxid=void 0;txidIndex=void 0;rawBytesCache;hexCache;needsSort=!0;constructor(e=rq){this.version=e}invalidateSerializationCaches(){this.rawBytesCache=void 0,this.hexCache=void 0}markMutated(e=!0){this.invalidateSerializationCaches(),e&&(this.needsSort=!0)}ensureSerializableState(){for(let e of this.txs)e.txid}ensureSortedForSerialization(){this.needsSort&&this.sortTxs()}getSerializedBytes(){if(this.ensureSerializableState(),null==this.rawBytesCache){this.ensureSortedForSerialization();let e=new ti;this.toWriter(e),this.rawBytesCache=e.toUint8Array()}return this.rawBytesCache}findTxid(e){return this.ensureTxidIndex().get(e)}ensureTxidIndex(){if(null==this.txidIndex)for(let e of(this.txidIndex=new Map,this.txs))this.txidIndex.set(e.txid,e);return this.txidIndex}deleteFromIndex(e){this.txidIndex?.delete(e)}addToIndex(e){this.txidIndex?.set(e.txid,e)}makeTxidOnly(e){let t=this.txs.findIndex(t=>t.txid===e);if(-1===t)return;let r=this.txs[t];return r.isTxidOnly?r:(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0),r=this.mergeTxidOnly(e))}findBump(e){return this.bumps.find(t=>t.path[0].some(t=>t.hash===e))}findTransactionForSigning(e){let t=this.findTxid(e);if(null!=t&&null!=t.tx){for(let e of t.tx.inputs)if(null==e.sourceTransaction){let t=this.findTxid(tc(e.sourceTXID,"sourceTXID must be valid"));null!=t&&(e.sourceTransaction=t.tx)}return t.tx}}findAtomicTransaction(e){let t=this.findTxid(e);if(null==t||null==t.tx)return;let r=(e,t)=>{let i=e.findBump(t.id("hex"));if(null!=i)t.merklePath=i;else for(let i of t.inputs){if(null==i.sourceTransaction){let t=e.findTxid(tc(i.sourceTXID,"sourceTXID must be valid"));null!=t&&(i.sourceTransaction=t.tx)}if(null!=i.sourceTransaction){let t=e.findBump(i.sourceTransaction.id("hex"));null!=t?i.sourceTransaction.merklePath=t:r(e,i.sourceTransaction)}}};return r(this,t.tx),t.tx}mergeBump(e){let t;this.markMutated(!1);for(let r=0;r<this.bumps.length;r++){let i=this.bumps[r];if(i===e)return r;if(i.blockHeight===e.blockHeight&&i.computeRoot()===e.computeRoot()){i.combine(e),t=r;break}}void 0===t&&(t=this.bumps.length,this.bumps.push(e));let r=this.bumps[t];for(let e of this.txs){let i=e.txid;if(null==e.bumpIndex){for(let n of r.path[0])if(n.hash===i){e.bumpIndex=t,n.txid=!0;break}}}return t}mergeRawTx(e,t){this.markMutated(!0);let r=new rL(e,t);return this.removeExistingTxid(r.txid),this.txs.push(r),this.addToIndex(r),this.tryToValidateBumpIndex(r),r}mergeTransaction(e){let t;this.markMutated(!0);let r=e.id("hex");this.removeExistingTxid(r),null!=e.merklePath&&(t=this.mergeBump(e.merklePath));let i=new rL(e,t);if(this.txs.push(i),this.addToIndex(i),this.tryToValidateBumpIndex(i),void 0===(t=i.bumpIndex))for(let t of e.inputs)null!=t.sourceTransaction&&this.mergeTransaction(t.sourceTransaction);return i}removeExistingTxid(e){let t=this.txs.findIndex(t=>t.txid===e);t>=0&&(this.deleteFromIndex(e),this.txs.splice(t,1),this.markMutated(!0))}mergeTxidOnly(e){let t=this.findTxid(e);return null==t&&(t=new rL(e),this.txs.push(t),this.addToIndex(t),this.tryToValidateBumpIndex(t),this.markMutated(!0)),t}mergeBeefTx(e){let t=this.findTxid(e.txid);if(e.isTxidOnly&&null==t?t=this.mergeTxidOnly(e.txid):null!=e._tx&&(null==t||t.isTxidOnly)?t=this.mergeTransaction(e._tx):null!=e._rawTx&&(null==t||t.isTxidOnly)&&(t=this.mergeRawTx(e._rawTx)),null==t)throw Error(`Failed to merge BeefTx for txid: ${e.txid}`);return t}mergeBeef(e){let t=Array.isArray(e)?r$.fromBinary(e):e;for(let e of t.bumps)this.mergeBump(e);for(let e of t.txs)this.mergeBeefTx(e)}isValid(e){return this.verifyValid(e).valid}async verify(e,t){let r=this.verifyValid(t);if(!r.valid)return!1;for(let t of Object.keys(r.roots))if(!await e.isValidRootForHeight(r.roots[t],Number(t)))return!1;return!0}verifyValid(e){let t={valid:!1,roots:{}},r=this.sortTxs();if(r.missingInputs.length>0||r.notValid.length>0||r.txidOnly.length>0&&!0!==e||r.withMissingInputs.length>0)return t;let i={};for(let r of this.txs)if(r.isTxidOnly){if(!0!==e)return t;i[r.txid]=!0}let n=(e,r)=>{let i=e.computeRoot(r);return(void 0===t.roots[e.blockHeight]||""===t.roots[e.blockHeight])&&(t.roots[e.blockHeight]=i),t.roots[e.blockHeight]===i};for(let e of this.bumps)for(let r of e.path[0])if(!0===r.txid&&"string"==typeof r.hash&&r.hash.length>0&&(i[r.hash]=!0,!n(e,r.hash)))return t;for(let e of this.txs)if(void 0!==e.bumpIndex&&null==this.bumps[e.bumpIndex].path[0].find(t=>t.hash===e.txid))return t;for(let e of this.txs){for(let r of e.inputTxids)if(!i[r])return t;i[e.txid]=!0}return t.valid=!0,t}toWriter(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.bumps.length),this.bumps))e.write(t.toBinary());for(let t of(e.writeVarIntNum(this.txs.length),this.txs))t.toWriter(e,this.version)}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toBinaryAtomic(e){this.needsSort&&this.sortTxs();let t=this.findTxid(e);if(null==t)throw Error(`${e} does not exist in this Beef`);let r=this.txs[this.txs.length-1]===t?this:this.clone();if(r!==this){let t=this.txs.findIndex(t=>t.txid===e);r.txs.splice(t+1)}let i=new ti;return i.writeUInt32LE(rM),i.writeReverse(e1(e,"hex")),r.toWriter(i),i.toArray()}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rK?rK.from(e).toString("hex"):e0(Array.from(e));return this.hexCache=t,t}static fromReader(e){let t,r=e.readUInt32LE();if(r===rM&&(t=e0(e.readReverse(32)),r=e.readUInt32LE()),r!==rH&&r!==rq)throw Error(`Serialized BEEF must start with ${rH} or ${rq} but starts with ${r}`);let i=new r$(r),n=e.readVarIntNum();for(let t=0;t<n;t++){let t=rF.fromReader(e,!1);i.bumps.push(t)}let a=e.readVarIntNum();for(let t=0;t<a;t++){let t=rL.fromReader(e,r);i.txs.push(t)}return i.atomicTxid=t,i}static fromBinary(e){let t=new tn(e);return r$.fromReader(t)}static fromString(e,t="hex"){let r=new tn(e1(e,t));return r$.fromReader(r)}tryToValidateBumpIndex(e){if(void 0!==e.bumpIndex)return!0;let t=e.txid;for(let r=0;r<this.bumps.length;r++){let i=this.bumps[r].path[0].findIndex(e=>e.hash===t);if(i>=0)return e.bumpIndex=r,this.bumps[r].path[0][i].txid=!0,!0}return!1}sortTxs(){let e={},t={},r=[],i=[],n=[];for(let a of this.txs)t[a.txid]=a,a.isValid=a.hasProof,a.isValid?(e[a.txid]=!0,i.push(a)):a.isTxidOnly&&0===a.inputTxids.length?(e[a.txid]=!0,n.push(a)):r.push(a);let a={},s=[],o=r;for(let e of(r=[],o)){let i=!1;for(let r of e.inputTxids)void 0===t[r]&&(a[r]=!0,i=!0);i?s.push(e):r.push(e)}for(;r.length>0;){let t=r;for(let n of(r=[],t))n.inputTxids.every(t=>e[t])?(e[n.txid]=!0,i.push(n)):r.push(n);if(t.length===r.length)break}let c=r;return this.txs=s.concat(c).concat(n).concat(i),this.needsSort=!1,this.invalidateSerializationCaches(),{missingInputs:Object.keys(a),notValid:c.map(e=>e.txid),valid:Object.keys(e),withMissingInputs:s.map(e=>e.txid),txidOnly:n.map(e=>e.txid)}}clone(){let e=new r$;return e.version=this.version,e.bumps=Array.from(this.bumps),e.txs=Array.from(this.txs),e.txidIndex=void 0,e.needsSort=this.needsSort,e}trimKnownTxids(e){let t=!1;for(let r=0;r<this.txs.length;){let i=this.txs[r];i.isTxidOnly&&e.includes(i.txid)?(this.deleteFromIndex(i.txid),this.txs.splice(r,1),t=!0):r++}t&&this.markMutated(!0)}getValidTxids(){return this.sortTxs().valid}toLogString(){let e="";e+=`BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}
|
|
7
7
|
`;let t=-1;for(let r of this.bumps)t++,e+=` BUMP ${t}
|
|
8
8
|
block: ${r.blockHeight}
|
|
9
9
|
txids: [
|
|
@@ -16,5 +16,5 @@ ${r.path[0].filter(e=>!0===e.txid).map(e=>` '${e.hash??""}'`).join(",\n")}
|
|
|
16
16
|
`,r.inputTxids.length>0&&(e+=` inputs: [
|
|
17
17
|
${r.inputTxids.map(e=>` '${e}'`).join(",\n")}
|
|
18
18
|
]
|
|
19
|
-
`);return e}addComputedLeaves(){let e=e=>e7(eo(e9(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let r=1;r<t.path.length;r++)for(let i of t.path[r-1])if("string"==typeof i.hash&&(1&i.offset)==0){let n=t.path[r-1].find(e=>e.offset===i.offset+1),a=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every(e=>e.offset!==a)&&t.path[r].push({offset:a,hash:e(n.hash+i.hash)})}}}let rQ="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class r0{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){let t=r[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let i of e.tx.inputs){if(void 0===i.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[i.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){let{tx:r}=r0.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=r0.fromAnyBeef(e);if(r!==i.atomicTxid)if(null!=i.atomicTxid)throw Error(`Transaction with TXID ${i.atomicTxid} not found in BEEF data.`);else throw Error("beef must conform to BRC-95 and must contain the subject txid.");return t}static fromAnyBeef(e,t){let r=rZ.fromBinary(e);if(r.txs.length<1)throw Error("beef must include at least one transaction.");let i=t??r.atomicTxid??r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)if(null!=t)throw Error(`Transaction with TXID ${i} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:r,txid:i}}static fromEF(e){let t=new td(e),r=t.readUInt32LE();if("0000000000ef"!==e7(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=e7(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=rP.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=rE.fromBinary(h),d=new r0(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:u},n.push({sourceTransaction:d,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=rE.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new r0(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new td(e),r=[],i=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=8;let r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){let t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){let t=e7(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=rP.fromBinary(a),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=rE.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new r0(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e9(e,"hex"),r=Uint8Array.from(t),i=new td(t),n=r0.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rQ?rQ.from(r).toString("hex"):e7(t),n}static fromHexEF(e){return r0.fromEF(e9(e,"hex"))}static fromHexBEEF(e,t){return r0.fromBEEF(e9(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===e.sequence&&(e.sequence=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let r=new rC().lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=rU.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let r=await e.computeFee(this),i=this.calculateChange(r);if(i<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(i,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let r of(t-=e,this.outputs))!0!==r.change&&void 0!==r.satoshis&&(t-=r.satoshis);return t}distributeChange(e,t){let r=0,i=this.outputs.filter(e=>e.change);if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e,n=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,i);n[e]=n[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return r}distributeEqualChange(e,t){let r=0,i=Math.floor(e/t.length);for(let e of t)r+=i,e.satoshis=i;return r}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(Math.floor(9*Math.random())+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rM()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(e9(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new tu;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toEF(){let e=new tu;for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(e9(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return e7(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rQ?rQ.from(e).toString("hex"):e7(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return e7(this.toBEEF())}toHexAtomicBEEF(){return e7(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=eo(this.getSerializedBytes())),"hex"===e)?e7(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?e7(t):t}async verify(e=rz(),t,r){let i=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await a.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=r0.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");i.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new rT({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(s)}return!0}toBEEF(e){let t=new tu;t.writeUInt32LE(rG);let r=[],i=new Map,n=new Map,a=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,u="object"==typeof h;if(u&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);if(void 0!==s)return r[s].combine(e),i.set(e,s),s;let o=r.length;return r.push(e),i.set(e,o),n.set(a,o),o})(h)),!u)for(let r=t.inputs.length-1;r>=0;r--){let i=t.inputs[r];if("object"==typeof i.sourceTransaction)o(i.sourceTransaction);else if(!1===e)throw Error("A required source transaction is missing!")}s.add(c),a.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(a.length),a))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}}function r1(e){return"success"===e.status}function r2(e){return"error"===e.status}let r8=class extends rZ{knownTo={};constructor(e){if(super(),null!=e)for(const t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let r=this.knownTo[e];for(let e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let r=Array.isArray(t)?rZ.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class r3{network;URL;httpClient;constructor(e="main",t=rK()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class r6{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class r4{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function r5(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new r4(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new r6(e)}catch(t){return e}}class r7{URL;httpClient;constructor(e,t=r5()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let r=await this.httpClient.request(this.URL,t);if(!r.ok)return{status:"error",code:r.status.toString()??"ERR_UNKNOWN",description:r.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class r9{baseUrl;httpClient;apiKey;constructor(e,t={}){const{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rK(),this.apiKey=i??""}async isValidRootForHeight(e,t){let r={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,r);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let ie="42423301",it=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tU,t=new t1(1),i=e.g.mul(t);r=new tX(i.x,i.y)}let n=tJ(32),a=ta(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e9(ie,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},ir=(e,t,r)=>{let i=new td(t),n=e7(i.read(4));if(n!==ie)throw Error(`Message version mismatch: Expected ${ie}, received ${n}`);let a=tX.fromString(e7(i.read(33))),[s]=i.read(1);if(0===s)r=new t1(1);else{let e=e7([s,...i.read(32)]);if("object"!=typeof r)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=r.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=ta(i.read(32)),c=e7(i.read(i.bin.length-i.pos)),l=tF.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},ii="42421033",ia=(e,t,r)=>{let i=tJ(32),n=ta(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new rl(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e9(ii,"hex"),...l,...r.encode(!0),...i,...c]},is=(e,t)=>{let r=new td(e),i=e7(r.read(4));if(i!==ii)throw Error(`Message version mismatch: Expected ${ii}, received ${i}`);let n=tX.fromString(e7(r.read(33))),a=e7(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=ta(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),u=t.deriveChild(n,l);return new rl(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},io="Bitcoin Signed Message:\n",ic=e=>{let t=new tu;return t.writeVarIntNum(io.length),t.write(e9(io,"utf8")),t.writeVarIntNum(e.length),t.write(e),eo(t.toArray())},il=(e,t,r="base64")=>{let i=ic(e),n=tW(new P(i),t,!0);if("raw"===r)return n;let a=new P(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},ih=(e,t,r)=>tj(new P(ic(e)),t,r);class iu{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tJ(32),this.privKey=t1.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=th(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=eh(e9("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new t1(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new td(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let r=t.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new t1(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tX.fromString(e7(r));else throw Error("Invalid key");return this}toString(){return tl(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),r=this;for(let[e,i]of t.entries()){if(0===e){if("m"!==i)throw Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw Error("invalid path");let t=i.length>1&&"'"===i[i.length-1],n=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=0x80000000),r=r.deriveChild(n)}return r}deriveChild(e){if("number"!=typeof e)throw Error("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let r=[...t],i=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=eh(this.chainCode,e),n=new P(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tU().n);(a=new iu).chainCode=s,a.privKey=new t1(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=eh(this.chainCode,e),i=new P(t.slice(0,32)),n=t.slice(32,64),s=new tU().g.mul(i),o=this.pubKey,c=s.add(o),l=new tX(c.x,c.y);(a=new iu).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ec(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new iu(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new tu().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new tu().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let id={value:["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],space:" "};class ip{mnemonic;seed;Wordlist;constructor(e,t,r=id){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new tu;if(""!==this.mnemonic){let t=e9(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}else e.writeVarIntNum(0);return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){let t=new td(e),r=t.readVarIntNum();r>0&&(this.mnemonic=tn(t.read(r),"utf8"));let i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=tJ(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=ea(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((r+=n=("00000000"+n).slice(-8).slice(0,i/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let a="";for(let e=0;e<r.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let r=0;r<e.length;r++){let i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let r=t.length/33,i=t.slice(-r),n=t.slice(0,t.length-r),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=ea(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,r))===i}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let r=e9(t,"utf8"),i=[...e9("mnemonic","utf8"),...e9(e,"utf8")];return this.seed=eQ(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new ip(e).isValid(t)}}function ig(e){let t,r,i,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],n=o;n<4*o+28;n++)t=r[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[n]=r[n-o]^t;for(let e=0;n>0;e++,n--)t=r[(3&e)!=0?n:n-4],n<=4||e<4?i[e]=t:i[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}ig.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,r,i,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],u=l[4],d=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(d[e]=e<<1^(e>>7)*283)^e]=e;for(t=r=0;0===h[t];t^=0!==i?i:1,r=0!==f[r]?f[r]:1)for(e=0,a=(a=r^r<<1^r<<2^r<<3^r<<4)>>8^255&a^99,h[t]=a,u[a]=t,o=0x1010101*d[n=d[i=d[t]]]^65537*n^257*i^0x1010100*t,s=257*d[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],u=s.length/4-2,d=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],b=p[1],y=p[2],m=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^y[l>>8&255]^m[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^y[h>>8&255]^m[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^y[o>>8&255]^m[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^y[c>>8&255]^m[255&l]^s[d+3],d+=4,o=r,c=i,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[d++],r=o,o=c,c=l,l=h,h=r;return f}};class ib{static encrypt(e,t){let r=ib.buf2Words(t),i=ib.buf2Words(e),n=new ig(r).encrypt(i);return ib.words2Buf(n)}static decrypt(e,t){let r=ib.buf2Words(e),i=new ig(ib.buf2Words(t)).decrypt(r);return ib.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let r=0;r<e.length/4;r++){let i=0x1000000*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){let t=Array(4*e.length);for(let r=0;r<e.length;r++){let i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class iy{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let a=e.slice(n*r,n*r+r);a.length<t&&(a=iy.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=iy.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=iy.buf2BlocksBuf(e,n);return iy.encryptBlocks(a,t,r,i).flat()}static decrypt(e,t,r,i){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=iy.decryptBlocks(a,t,r,i);return iy.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=iy.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return iy.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.encryptBlock(s,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=iy.decryptBlock(s,t,r,i);n.push(o),t=s}return n}static pkcs7Pad(e,t){let r=t/8-e.length,i=Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){let t=e[e.length-1],r=e.slice(e.length-t,e.length),i=Array(t);if(i.fill(t),e7(r)!==e7(i))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let r=Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class im{static encrypt(e,t,r,i=!0){r=r??tJ(16);let n=iy.encrypt(e,r,ib,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return iy.decrypt(e,r,ib,t);{r=e.slice(0,16);let i=e.slice(16);return iy.decrypt(i,r,ib,t)}}}class iw{static ivkEkM(e,t){let r=t.mul(e),i=es(new tX(r.x,r.y).encode(!0));return{iv:i.slice(0,16),kE:i.slice(16,32),kM:i.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let n,a=null;null==r&&(r=t1.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=iw.ivkEkM(r,t),l=im.encrypt(e,o,s,!1),h=e9("BIE1","utf8"),u=el(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==tn(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,n=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(n=e.slice(i,i+33),i+=33):4===t&&(n=e.slice(i,i+65),i+=65)}if(null!==n)null==r&&(r=tX.fromString(e7(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=iw.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=el(o,e.slice(0,e.length-32));if(e7(l)!==e7(h))throw Error("Invalid checksum");return im.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=t1.fromRandom()),null==i&&(i=tJ(16));let n=r,a=r.toPublicKey().encode(!0),s=es(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=im.encrypt(e,o,i),h=el(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tX.fromString(e7(e.slice(0,33))).mul(t);if(r.eq(new tD(0,0)))throw Error("P equals 0");let i=es(r.getX().toArray("be",32)),n=i.slice(0,32),a=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=el(a,s);if(e7(o)!==e7(c))throw Error("Invalid checksum");return[...im.decrypt(s,n)]}}function iv(e,t){let r=new r0(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:rE.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class iI{static generate(e,t){let r=this.withDefaultOptions(t);return ik(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){let i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;let n=this.getCounter(i.timestamp,i.period),a=[n];for(let e=1;e<=i.skew;e++)a.push(n+e),a.push(n-e);for(let r of a){let n=ik(e,r,i);if(ty(e9(t,"utf8"),e9(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function ik(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new et(e).update(t);case"SHA-256":return new ee(e).update(t);case"SHA-512":return new er(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new P(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new P(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}(s=h||(h={}))[s.Silent=0]="Silent",s[s.App=1]="App",s[s.Counterparty=2]="Counterparty";class iS{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new t1(1).toPublicKey(),"anyone"===e?this.rootKey=new t1(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return(r=this.normalizeCounterparty(r),i)?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,r){r="anyone"===r?this.anyone:this.normalizeCounterparty(r);let i=this.derivePublicKey(e,t,r),n=this.derivePrivateKey(e,t,r);return new rl(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,r){e=this.normalizeCounterparty(e);let i=this.rootKey.deriveSharedSecret(e),n=e9(this.computeInvoiceNumber(t,r),"utf8");return el(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new t1(1).toPublicKey():"string"==typeof e?tX.fromString(e):e}computeInvoiceNumber(e,t){let r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw Error("Protocol security level must be 0, 1, or 2");let i=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(i.length>400)if(i.startsWith("specific linkage revelation ")){if(i.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(i.length<5)throw Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${t}`}}class ix{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new t1(1):this.rootKey=e,this.keyDeriver=new iS(this.rootKey,(e,t,r)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,r)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,a),a}}derivePrivateKey(e,t,r){let i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(e,t,r){let i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){let i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tX||e instanceof t1?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class iE{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new ix(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=new rd().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tX.fromString(e.counterparty),tD.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=el(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),r=e.hmac,i=ty(e9(t),e9(r));if(!i){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:i}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??ea(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tW(new P(t),r,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??ea(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tj(new P(t),tF.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let iP=iE;class iN{CWI;constructor(){if("object"!=typeof window)throw Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class iO extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}(o=u||(u={}))[o.unknownError=1]="unknownError",o[o.unsupportedAction=2]="unsupportedAction",o[o.invalidHmac=3]="invalidHmac",o[o.invalidSignature=4]="invalidSignature",o[o.reviewActions=5]="reviewActions",o[o.invalidParameter=6]="invalidParameter",o[o.insufficientFunds=7]="insufficientFunds";let iA=iO;class i_{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw Error("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((r,i)=>{let n=ta(tJ(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?i(new iO(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",a),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class iT{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,a,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new tu,r=e9(this.type,"base64");t.write(r);let i=e9(this.serialNumber,"base64");t.write(i);let n=e9(this.subject,"hex");t.write(n);let a=e9(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e9(s,"hex");t.write(c),t.writeVarIntNum(Number(o));let l=Object.keys(this.fields).sort();for(let e of(t.writeVarIntNum(l.length),l)){let r=this.fields[e],i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e9(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new td(e),i=ta(r.read(32)),n=ta(r.read(32)),a=e7(r.read(33)),s=e7(r.read(33)),o=e7(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),u={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=tF.fromDER(e).toString("hex")}return new iT(i,n,a,s,l,u,t)}async verify(){let e=new iP("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e9(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=e7(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new iT(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}(c=d||(d={}))[c.createAction=1]="createAction",c[c.signAction=2]="signAction",c[c.abortAction=3]="abortAction",c[c.listActions=4]="listActions",c[c.internalizeAction=5]="internalizeAction",c[c.listOutputs=6]="listOutputs",c[c.relinquishOutput=7]="relinquishOutput",c[c.getPublicKey=8]="getPublicKey",c[c.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",c[c.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",c[c.encrypt=11]="encrypt",c[c.decrypt=12]="decrypt",c[c.createHmac=13]="createHmac",c[c.verifyHmac=14]="verifyHmac",c[c.createSignature=15]="createSignature",c[c.verifySignature=16]="verifySignature",c[c.acquireCertificate=17]="acquireCertificate",c[c.listCertificates=18]="listCertificates",c[c.proveCertificate=19]="proveCertificate",c[c.relinquishCertificate=20]="relinquishCertificate",c[c.discoverByIdentityKey=21]="discoverByIdentityKey",c[c.discoverByAttributes=22]="discoverByAttributes",c[c.isAuthenticated=23]="isAuthenticated",c[c.waitForAuthentication=24]="waitForAuthentication",c[c.getHeight=25]="getHeight",c[c.getHeaderForHeight=26]="getHeaderForHeight",c[c.getNetwork=27]="getNetwork",c[c.getVersion=28]="getVersion";let iC=d;class iR{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new tu;i.writeUInt8(iC[e]);let n=e9(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new td(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=ti(s.read(e)),r=s.readVarIntNum();throw new iO(t,o,ti(s.read(r)))}}async createAction(e,t){let r=new tu,i=e9(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs)for(let t of(r.writeVarIntNum(e.inputs.length),e.inputs)){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=e9(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e9(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(r.writeVarIntNum(e.outputs.length),e.outputs)){let e=e9(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e9(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e9(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e9(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags)for(let e of(r.writeVarIntNum(t.tags.length),t.tags)){let t=e9(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(+!!e.options.signAndProcess):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids)for(let t of(r.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=e9(t,"hex");r.write(e)}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.noSendChange)for(let t of(r.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))r.write(this.encodeOutpoint(t));else r.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=e9(t,"hex");r.write(e)}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(+!!e.options.randomizeOutputs):r.writeInt8(-1)}else r.writeInt8(0);let n=new td(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=e7(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),r=n.readVarIntNum();a.signableTransaction={tx:t,reference:ta(n.read(r))}}return a}async signAction(e,t){let r=new tu,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],n=e9(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e9(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=e9(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new td(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=e7(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=e7(a.read(32)),t=a.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),s.sendWithResults.push({txid:e,status:r})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,e9(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new tu;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}for(let t of("any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?r.writeInt8(+!!t):r.writeInt8(-1);"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=new td(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=e7(i.read(32)),r=i.readVarIntNum(),n=i.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:ti(i.read(o)),version:0,lockTime:0},l=i.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=i.readVarIntNum(),t=i.read(e);c.labels.push(ti(t))}}c.version=i.readVarIntNum(),c.lockTime=i.readVarIntNum();let h=i.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,r=this.readOutpoint(i),n=i.readVarIntNum(),a=i.readVarIntNum();a>=0&&(e=e7(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=e7(i.read(s)));let o=i.readVarIntNum(),l=ti(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let u=i.readVarIntNum();if(u>=0){c.outputs=[];for(let e=0;e<u;e++){let e,t,r,n=i.readVarIntNum(),a=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=e7(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=ti(i.read(l)),u=i.readVarIntNum();u>=0&&(t=ti(i.read(u)));let d=i.readVarIntNum(),f=[];if(d>=0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(ti(t))}let p=i.readVarIntNum();p>=0&&(r=ti(i.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let r=new tu;for(let t of(r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length),e.outputs))if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(e9(t.paymentRemittance.senderIdentityKey,"hex"));let e=e9(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e9(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e9(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e9(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(r.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=e9(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e9(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){let r,i=new tu,n=e9(e.basket,"utf8");if(i.writeVarIntNum(n.length),i.write(n),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=e9(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?i.writeInt8(+!!e.includeCustomInstructions):i.writeInt8(-1),"boolean"==typeof e.includeTags?i.writeInt8(+!!e.includeTags):i.writeInt8(-1),"boolean"==typeof e.includeLabels?i.writeInt8(+!!e.includeLabels):i.writeInt8(-1),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let a=new td(await this.transmit("listOutputs",t,i.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(r=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=e7(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=ti(a.read(r)));let i=a.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(ti(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new tu,i=e9(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let r=new tu;return r.writeUInt8(+!!e.identityKey),e.identityKey?r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(r.write(this.encodeKeyRelatedParams(e.protocolID??=[h.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1)),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:e7(await this.transmit("getPublicKey",t,r.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new tu;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e9(e.counterparty,"hex")),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readVarIntNum(),c=ti(i.read(o)),l=i.readVarIntNum(),h=i.read(l),u=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(u)}}async revealSpecificKeyLinkage(e,t){let r=new tu;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e9(e.verifier,"hex"));let i=new td(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=e7(i.read(33)),a=e7(i.read(33)),s=e7(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=ti(i.read(c)),h=i.readVarIntNum(),u=ti(i.read(h)),d=i.readVarIntNum(),f=i.read(d),p=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:u,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){let r=new tu;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,n){let a=new tu;a.writeUInt8(e[0]);let s=e9(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e9(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof r?a.writeUInt8(0):"self"===r?a.writeUInt8(11):"anyone"===r?a.writeUInt8(12):a.write(e9(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new tu;r.write(e9(e.type,"base64")),r.write(e9(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(e9(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e9(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e9(e.keyringRevealer,"hex"):[11];r.write(i);let n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let i=e9(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e9(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e9(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=iT.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new tu;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e9(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new tu;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e9(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e9(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let i=new td(await this.transmit("listCertificates",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=i.readVarIntNum(),r=i.read(t),n=iT.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=ti(i.read(e)),r=i.readVarIntNum();s[t]=ta(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=ti(i.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let r=new tu,i=e9(e.certificate.type,"base64");r.write(i);let n=e9(e.certificate.subject,"hex");r.write(n);let a=e9(e.certificate.serialNumber,"base64");r.write(a);let s=e9(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e9(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(r.writeVarIntNum(l.length),l)){let i=e9(e,"utf8"),n=e9(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=e9(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e9(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new td(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=ti(h.read(e)),r=h.readVarIntNum();d[t]=ta(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new tu,i=e9(e.type,"base64");r.write(i);let n=e9(e.serialNumber,"base64");r.write(n);let a=e9(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new td(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=iT.fromBinary(r),a=t.readVarIntNum(),s=ti(t.read(a)),o=t.readVarIntNum(),c=ti(t.read(o)),l=t.readVarIntNum(),h=ti(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();d[r]=t.read(i)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),r=ti(t.read(e)),i=t.readVarIntNum();p[r]=ti(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:u},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new tu;r.write(e9(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){let r=new tu,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e9(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e9(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new td(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new tu;return r.writeVarIntNum(e.height),{header:e7(await this.transmit("getHeaderForHeight",t,r.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:ti(await this.transmit("getVersion",t))}}}class iB{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){let t,r=new td(e),i=r.readUInt8(),n=iC[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=ti(r.read(a)));let s=r.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class iV extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let iD=iV;class iU extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let iF=iU,iL=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class iK{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;const i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!i&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;i||void 0!==n||console.error("Originator is required in Node.js environments");let a=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new iV(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new iU(s.parameter)).message=s.message;break;case 7:e=new iL(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class iH{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((r,i)=>{let n=ta(tJ(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?i(new iO(t.description,t.code)):r(t.result))};window.addEventListener("message",a),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}function iq(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function iM(e){return e??!1}function i$(e,t,r,i){if(void 0!==e)return iG(e,t,r,i)}function iz(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new iF(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new iF(t,`at least ${r} satoshis.`);return e}function iW(e,t,r,i){if(void 0!==e)return ij(e,t,void 0,r,i)}function ij(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new iF(t,"a valid integer")}if(!Number.isInteger(e))throw new iF(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new iF(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new iF(t,`no more than ${n} length.`);return e}function iX(e,t){return ij(e,t,0,0)}function iG(e,t,r,i){let n=e9(e,"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function iY(e){return iQ(e,"basket",1,300)}function iJ(e){return iQ(e,"label",1,300)}function iZ(e){return iQ(e,"tag",1,300)}function iQ(e,t,r,i){let n=e9(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new iF(t,`no more than ${i} length.`);return e}function i0(e,t,r,i){if(void 0!==e)return i1(e,t,r,i)}function i1(e,t,r,i){if(0===(e=e.trim()).length)throw new iF(t,"valid base64 string");let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if((!(i>=65)||!(i<=90))&&(!(i>=97)||!(i<=122))&&(!(i>=48)||!(i<=57))&&43!==i&&47!==i){if(61===i){if(r<e.length-2)throw new iF(t,"valid base64 string");n++;continue}throw new iF(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new iF(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new iF(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new iF(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new iF(t,`no more than ${i} bytes`);return e}function i2(e,t,r,i){if(void 0!==e)return i8(e,t,r,i)}function i8(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new iF(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new iF(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new iF(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new iF(t,`no more than ${i} length.`);return e}function i3(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function i6(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new iF("unlockingScript, unlockingScriptLength","at least one valid value.");let t=i2(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new iF("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iq(e.outpoint),inputDescription:iG(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function i4(e){return{lockingScript:i8(e.lockingScript,"lockingScript"),satoshis:iz(e.satoshis,"satoshis"),outputDescription:iG(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iY(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>iZ(e))}}function i5(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iq(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function i7(e,t){let r={description:iG(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>i6(e)),outputs:(e.outputs??[]).map(e=>i4(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>iJ(e))??[],options:i5(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return r.isTestWerrReviewActions=r.labels.includes(nv),r.isSendWith=r.options.sendWith.length>0,r.isRemixChange=!r.isSendWith&&0===r.inputs.length&&0===r.outputs.length,r.isNewTx=r.isRemixChange||r.inputs.length>0||r.outputs.length>0,r.isSignAction=r.isNewTx&&(!r.options.signAndProcess||r.inputs.some(e=>void 0===e.unlockingScript)),r.isDelayed=r.options.acceptDelayedBroadcast,r.isNoSend=r.options.noSend,r}function i9(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:iM(t.returnTXIDOnly),noSend:iM(t.noSend),sendWith:t.sendWith??[]}}function ne(e){let t={spends:e.spends,reference:e.reference,options:i9(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function nt(e){return{reference:i1(e.reference,"reference")}}function nr(e){if(void 0!==e)return{derivationPrefix:i1(e.derivationPrefix,"derivationPrefix"),derivationSuffix:i1(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:i8(e.senderIdentityKey,"senderIdentityKey")}}function ni(e){if(void 0!==e)return{basket:iY(e.basket),customInstructions:i$(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>iZ(e))}}function nn(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new iF("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iX(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:nr(e.paymentRemittance),insertionRemittance:ni(e.insertionRemittance)}}function na(e){if(void 0!==e){for(let t of(iG(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iG(t,"originator part",1,63);return e}}function ns(e){let t={tx:e.tx,outputs:e.outputs.map(e=>nn(e)),description:iG(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),seekPermission:e.seekPermission??!0};try{if(rZ.fromBinary(t.tx).txs.length<1)throw new iF("tx","at least one transaction to internalize an output from")}catch{throw new iF("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new iF("outputs","at least one output to internalize from the transaction");return t}function no(e,t){if(void 0!==e)return nc(e,t)}function nc(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new iF(t,"txid as hex string and numeric output index joined with '.'");let i=i8(r[0],`${t} txid`,void 0,64),n=iX(Number(r[1]),`${t} vout`);return`${i}.${n}`}function nl(e){return{basket:iY(e.basket),output:nc(e.output,"output")}}function nh(e){return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier")}}function nu(e){return{certifiers:e.certifiers.map(e=>i8(e.trim(),"certifiers"))??[],types:e.types.map(e=>i1(e.trim(),"types"))??[],limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nd(e){for(let t of Object.keys(e))iG(t,"field name",1,50);return e}function nf(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new iF("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),certifier:i8(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nd(e.fields),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function np(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new iF("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new iF("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new iF("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new iF("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new iF("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i1(e.type,"type"),serialNumber:i1(e.serialNumber,"serialNumber"),certifier:i8(e.certifier,"certifier"),revocationOutpoint:nc(e.revocationOutpoint,"revocationOutpoint"),fields:nd(e.fields),signature:i8(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:i8(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iG(r,`${t} field name`,1,50),i1(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ng(e){if(e.privileged&&!e.privilegedReason)throw new iF("privilegedReason","valid when 'privileged' is true ");return{type:i0(e.certificate.type,"certificate.type"),serialNumber:i0(e.certificate.serialNumber,"certificate.serialNumber"),certifier:i2(e.certificate.certifier,"certificate.certifier"),subject:i2(e.certificate.subject,"certificate.subject"),revocationOutpoint:no(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:i2(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iG(e,`fieldsToReveal ${e}`,1,50)),verifier:i8(e.verifier,"verifier"),privileged:iM(e.privileged),privilegedReason:i$(e.privilegedReason,"privilegedReason",5,50)}}function nb(e){return{identityKey:i8(e.identityKey,"identityKey",66,66),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function ny(e){return{attributes:function(e){for(let t of Object.keys(e))iG(t,`field name ${t}`,1,50);return e}(e.attributes),limit:ij(e.limit,"limit",10,1,1e4),offset:iX(e.offset??0,"offset"),seekPermission:iM(e.seekPermission)}}function nm(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new iF("tagQueryMode","undefined, 'any', or 'all'");return{basket:iG(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iG(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:iM(e.includeCustomInstructions),includeTags:iM(e.includeTags),includeLabels:iM(e.includeLabels),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nw(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new iF("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>iJ(e)),labelQueryMode:t,includeLabels:iM(e.includeLabels),includeInputs:iM(e.includeInputs),includeInputSourceLockingScripts:iM(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:iM(e.includeInputUnlockingScripts),includeOutputs:iM(e.includeOutputs),includeOutputLockingScripts:iM(e.includeOutputLockingScripts),limit:ij(e.limit,"limit",10,1,1e4),offset:ij(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nv="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nI{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iR(new iB(t))),"window.CWI"===e&&(e=new iN),"XDM"===e&&(e=new i_),"json-api"===e&&(e=new iK(t)),"react-native"===e&&(e=new iH(t)),"secure-json-api"===e&&(e=new iK(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let r,i=e();if(r="number"==typeof t?await Promise.race([i.getVersion({}),new Promise((e,r)=>setTimeout(()=>r(Error("Timed out.")),t))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)return{success:!1};return{success:!0,sub:i}}catch{return{success:!1}}},t=[e(()=>new iN),e(()=>new iK(this.originator,"https://localhost:2121")),e(()=>new iK(this.originator)),e(()=>new iH(this.originator)),e(()=>new iR(new iB(this.originator)))],r=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(r.length>0){this.substrate=r[0];return}let i=await e(()=>new i_,200);if(i.success&&void 0!==i.sub)this.substrate=i.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return i7(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return ne(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return nt(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nw(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return ns(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nm(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nl(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)np(e);else if("issuance"===e.acquisitionProtocol)nf(e);else throw new iU("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return nu(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return ng(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nh(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nb(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return ny(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class nk{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=e7(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new tu,[r,i]=e.split(".");return t.write(e9(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new td(e);try{let e=t.readUInt8(),r=iC[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=ti(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=ti(i);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let r=0;r<s;r++){let r={};r.outpoint=this.decodeOutpoint(t);let i=t.readVarIntNum();if(i>=0){let e=t.read(i);r.unlockingScript=e7(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=ti(a);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.inputs.push(r)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let r=0;r<o;r++){let r={},i=t.readVarIntNum(),n=t.read(i);r.lockingScript=e7(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=ti(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=ti(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=ti(e)}else r.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){r.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),i=t.read(e),n=ti(i);r.tags.push(n)}}else r.tags=void 0;e.outputs.push(r)}}else e.outputs=void 0;let c=t.readVarIntNum();c>=0?e.lockTime=c:e.lockTime=void 0;let l=t.readVarIntNum();l>=0?e.version=l:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let r=0;r<h;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i);e.labels.push(n)}}else e.labels=void 0;let u=t.readInt8();if(1===u){e.options={};let r=t.readInt8();-1===r?e.options.signAndProcess=void 0:e.options.signAndProcess=1===r;let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(r);e.options.knownTxids.push(i)}}else e.options.knownTxids=void 0;let s=t.readInt8();-1===s?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===s;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let c=t.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let r=0;r<c;r++){let r=this.decodeOutpoint(t);e.options.noSendChange.push(r)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let r=0;r<l;r++){let r=t.read(32),i=e7(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let d=await this.wallet.createAction(e,a),f=new tu;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e9(d.txid,"hex"))):f.writeInt8(0),null!=d.tx?(f.writeInt8(1),f.writeVarIntNum(d.tx.length),f.write(d.tx)):f.writeInt8(0),null!=d.noSendChange)for(let e of(f.writeVarIntNum(d.noSendChange.length),d.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=d.sendWithResults)for(let e of(f.writeVarIntNum(d.sendWithResults.length),d.sendWithResults)){let t;f.write(e9(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}else f.writeVarIntNum(-1);if(null!=d.signableTransaction){f.writeInt8(1),f.writeVarIntNum(d.signableTransaction.tx.length),f.write(d.signableTransaction.tx);let e=e9(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new tu;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},r=t.readVarIntNum();e.spends={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i={},n=t.readVarIntNum(),a=t.read(n);i.unlockingScript=e7(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),n=t.read(i);e.reference=ta(n);let s=t.readInt8();if(1===s){e.options={};let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let i=t.readInt8();-1===i?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===i;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let r=0;r<a;r++){let r=t.read(32),i=e7(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new tu;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e9(o.txid,"hex"))):c.writeInt8(0),null!=o.tx?(c.writeInt8(1),c.writeVarIntNum(o.tx.length),c.write(o.tx)):c.writeInt8(0),null!=o.sendWithResults)for(let e of(c.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;c.write(e9(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),c.writeInt8(t)}else c.writeVarIntNum(-1);let l=new tu;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=ta(e);await this.wallet.abortAction({reference:r},a);let i=new tu;return i.writeUInt8(0),i.toArray()}case"listActions":{let e={},r=t.readVarIntNum();e.labels=[];for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r);e.labels.push(ti(i))}let i=t.readInt8();for(let r of(-1===i?e.labelQueryMode=void 0:1===i?e.labelQueryMode="any":2===i&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let i=t.readInt8();-1===i?e[r]=void 0:e[r]=1===i}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new tu;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e9(e.txid,"hex")),l.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}l.writeInt8(t),l.writeInt8(+!!e.isOutgoing);let r=e9(e.description,"utf8");if(l.writeVarIntNum(r.length),l.write(r),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(l.writeVarIntNum(e.version),l.writeVarIntNum(e.lockTime),void 0!==e.inputs)for(let t of(l.writeVarIntNum(e.inputs.length),e.inputs)){if(l.write(this.encodeOutpoint(t.sourceOutpoint)),l.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){let e=e9(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e9(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e9(t.inputDescription,"utf8");l.writeVarIntNum(e.length),l.write(e),l.writeVarIntNum(t.sequenceNumber)}else l.writeVarIntNum(-1);if(void 0!==e.outputs)for(let t of(l.writeVarIntNum(e.outputs.length),e.outputs)){if(l.writeVarIntNum(t.outputIndex),l.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){let e=e9(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e9(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e9(t.basket,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.tags)for(let e of(l.writeVarIntNum(t.tags.length),t.tags)){let t=e9(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e9(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new tu;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},r=t.readVarIntNum();e.tx=t.read(r);let i=t.readVarIntNum();e.outputs=[];for(let r=0;r<i;r++){let r={};r.outputIndex=t.readVarIntNum();let i=t.readUInt8();if(1===i){r.protocol="wallet payment",r.paymentRemittance={};let e=t.read(33);r.paymentRemittance.senderIdentityKey=e7(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=ta(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=ta(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=ti(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=ti(e)}let a=t.readVarIntNum();if(a>0){r.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(ti(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let r=0;r<n;r++){let r=t.readVarIntNum();e.labels.push(ti(t.read(r)))}}let s=t.readVarIntNum();e.description=ti(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new tu;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(ti(i))}}else e.tags=void 0;let s=t.readInt8();1===s?e.tagQueryMode="all":2===s?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let c=t.readInt8();-1===c?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===c;let l=t.readInt8();-1===l?e.includeTags=void 0:e.includeTags=1===l;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let u=t.readVarIntNum();u>=0?e.limit=u:e.limit=void 0;let d=t.readVarIntNum();d>=0?e.offset=d:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new tu;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=e9(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e9(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=e9(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new tu;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=ti(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new tu;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},r=t.readUInt8();if(e.identityKey=1===r,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=ti(r)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}else{let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=ti(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new tu;s.writeUInt8(0);let o=e9(n.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.plaintext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.ciphertext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,a),s=new tu;return s.writeUInt8(0),s.write(n.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,a),s=new tu;return s.writeUInt8(0),s.write(n.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0,await this.wallet.verifyHmac(e,a);let n=new tu;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),r=t.readUInt8();if(1===r){let r=t.readVarIntNum();e.data=t.read(r)}else 2===r&&(e.hashToDirectlySign=t.read(32));let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,a),s=new tu;return s.writeUInt8(0),s.write(n.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),r=t.readInt8();-1===r?e.forSelf=void 0:e.forSelf=1===r;let i=t.readVarIntNum();e.signature=t.read(i);let n=t.readUInt8();if(1===n){let r=t.readVarIntNum();e.data=t.read(r)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new tu;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new tu;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new tu;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let r=await this.wallet.getHeaderForHeight(e,a),i=new tu;i.writeUInt8(0);let n=e9(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new tu;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new tu;t.writeUInt8(0);let r=e9(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1===i)e.privilegedReason=void 0;else{let r=t.read(i);e.privilegedReason=ti(r)}let n=t.read(33);e.counterparty=e7(n);let s=t.read(33);e.verifier=e7(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new tu;c.write(e9(o.prover,"hex")),c.write(e9(o.verifier,"hex")),c.write(e9(o.counterparty,"hex"));let l=e9(o.revelationTime,"utf8");c.writeVarIntNum(l.length),c.write(l),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);let h=new tu;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=e7(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new tu;n.write(e9(i.prover,"hex")),n.write(e9(i.verifier,"hex")),n.write(e9(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e9(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e9(i.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(i.encryptedLinkage.length),n.write(i.encryptedLinkage),n.writeVarIntNum(i.encryptedLinkageProof.length),n.write(i.encryptedLinkageProof),n.writeUInt8(i.proofType);let c=new tu;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(33);e.certifier=e7(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let r=t.read(o);e.privilegedReason=ti(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=ta(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=e7(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=e7(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ta(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=ti(i)}let l=await this.wallet.acquireCertificate(e,a),h=new iT(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new tu;return u.writeUInt8(0),u.write(h),u.toArray()}case"listCertificates":{let e={},r=t.readVarIntNum();e.certifiers=[];for(let i=0;i<r;i++){let r=t.read(33);e.certifiers.push(e7(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(ta(r))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let c=t.readInt8();if(-1===c)e.privilegedReason=void 0;else{let r=t.read(c);e.privilegedReason=ti(r)}let l=await this.wallet.listCertificates(e,a),h=new tu;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new iT(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,r]of(h.writeVarIntNum(t.length),t)){let t=e9(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e9(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e9(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new tu;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=ta(i);let n=t.read(33);r.subject=e7(n);let s=t.read(32);r.serialNumber=ta(s);let o=t.read(33);r.certifier=e7(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=e7(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);r.fields[n]=o}e.certificate=r;let u=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<u;r++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=e7(d);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let r=t.read(p);e.privilegedReason=ti(r)}let g=await this.wallet.proveCertificate(e,a),b=new tu,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(y.length),y)){let r=e9(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e9(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let m=new tu;return m.writeUInt8(0),m.write(b.toArray()),m.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=ta(r);let i=t.read(32);e.serialNumber=ta(i);let n=t.read(33);e.certifier=e7(n),await this.wallet.relinquishCertificate(e,a);let s=new tu;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=e7(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new tu;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},r=t.readVarIntNum();e.attributes={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r),n=ti(i),a=t.readVarIntNum(),s=t.read(a),o=ti(s);e.attributes[n]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new tu;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new tu;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e9("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e9("string"==typeof i.stack?i.stack:"","utf8");return e.writeVarIntNum(r.length),e.write(r),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),r=e.readVarIntNum();return[t,ti(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return ti(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?e7([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new tu;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new iT(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e9(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e9(r.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=e9(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e9(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=ti(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=ti(e.read(n)),t}}class nS extends iT{masterKeyring;constructor(e,t,r,i,n,a,s,o){for(const c of(super(e,t,r,i,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,r,i,n){let a={},s={};for(let[o,c]of Object.entries(r)){let r=rl.fromRandom(),l=r.encrypt(e9(c,"utf8"));a[o]=ta(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...iT.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=ta(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===i[h]||null===i[h]||""===i[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,a,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:u}=await e.encrypt({plaintext:n,...iT.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=ta(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"00".repeat(32),a){let s=a??ta(tJ(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new nS(i,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(r))s[o]=(await this.decryptField(e,t,o,r[o],i,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:e9(t[r],"base64"),...iT.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new rl(o).decrypt(e9(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:ti(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nx extends iT{keyring;decryptedFields;constructor(e,t,r,i,n,a,s,o,c){super(e,t,r,i,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nx(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,r,i){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:e9(this.keyring[a],"base64"),...iT.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new rl(s).decrypt(e9(this.fields[a],"base64"));n[a]=ti(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class nE extends iP{keyDeriver;constructor(e){if(super(e),e instanceof iS)this.keyDeriver=e;else if("string"==typeof e||e instanceof t1)this.keyDeriver=new ix(e);else throw Error("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nP{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){let t,r=this.sessionNonceToSession.get(e);if(null!=r)return r;let i=this.identityKeyToNonces.get(e);if(null!=i&&0!==i.size){for(let e of i){let r=this.sessionNonceToSession.get(e);null!=r&&(null==t?t=r:(r.lastUpdate??0)>(t.lastUpdate??0)&&(t=r))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nN(e,t,r="self",i){let n=e9(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:ti(a),counterparty:r},i);return o}async function nO(e,t="self",r){let i=tJ(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:ti(i),data:i,counterparty:t},r);return ta([...i,...n])}let nA=async(e,t,r,i)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:r},i);return new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},n_=async(e,t,r,i)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nx(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,i)}))},nT="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nC{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,r,i,n,a){this.wallet=e,this.originator=a,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=i?i:new nP,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:n,yourNonce:i.peerNonce,payload:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=ta(tJ(32)),{signature:a}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e,t){let r;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){let i=await this.initiateHandshake(e,t);if(null==(r=this.sessionManager.getSession(i))||!r.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e,t=1e4){let r=await nO(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{let n=this.listenForInitialResponse(e,e=>{clearTimeout(a),this.stopListeningForInitialResponses(n),r(e)}),a=setTimeout(()=>{this.stopListeningForInitialResponses(n),i(Error("Initial response timed out."))},t)})}listenForInitialResponse(e,t){let r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let r=t.details;null!=r&&"object"==typeof r?null==r.peerIdentityKey&&(r.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await nO(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:n}=await this.wallet.createSignature({data:nC.base64ToBytes(e.initialNonce+r),protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(a)}async processInitialResponse(e){if(!await nN(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let r=nC.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await n_(this.wallet,e,this.certificatesToRequest,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nN(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:nC.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nA(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let r=await this.getAuthenticatedSession(e),i=ta(tJ(32)),{signature:n}=await this.wallet.createSignature({data:nC.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(e){this.propagateTransportError(r.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nN(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:nC.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await n_(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await nN(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nT?Array.from(nT.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e9(e,"utf8")}static base64ToBytes(e){return null!=nT?Array.from(nT.from(e,"base64")):e9(e,"base64")}}let nR="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nB{onDataCallback;fetchClient;baseUrl;constructor(e,t=nR){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,r)=>{(async()=>{try{let r=`${this.baseUrl}/.well-known/auth`,i=(async()=>{try{return await this.fetchClient(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(r,e)}})();"initialRequest"!==e.messageType&&t();let n=await i;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(r,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t,r,i=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${i.urlPostfix}`;if("object"!=typeof i.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=e7(e.signature),i.headers["x-bsv-auth-request-id"]=i.requestId,null!=i.body){let e=i.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=ti(i.body):i.body=new Uint8Array(i.body)}try{t=await this.fetchClient(n,{method:i.method,headers:i.headers,body:i.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let r=t.headers.get(e);return null==r||0===r.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{r=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new tu;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e9(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&l.push([r,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=e9(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e9(l[e][1],"utf8");c.writeVarIntNum(r.length),c.write(r)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:r,payload:c.toArray(),signature:e9(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let r=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${r}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${r}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,r,i=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=i.length>0?`missing headers: ${i.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(r,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:i,bodyPreview:o},l}createMalformedHeaderError(e,t,r,i){let n=`Failed to parse ${t} returned by ${e}: ${r}`;if(i instanceof Error){let e=Error(`${n}. ${i.message}`);return e.stack=i.stack,e.cause=i,e}return Error(`${n}. ${String(i)}`)}getBodyPreview(e,t){let r;if(0===e.length)return;let i=e.length>1024,n=i?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{r=ti(n)}catch{r=this.formatBinaryPreview(n,i)}else r=this.formatBinaryPreview(n,i);return r.length>512&&(r=`${r.slice(0,512)}…`),i&&(r=`${r} (truncated)`),r}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let r=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${r}${t?"…":""}`}deserializeRequestPayload(e){let t,r=new td(e),i=ta(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=ti(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=ti(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=ti(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=ti(r.read(e)),i=r.readVarIntNum(),n=ti(r.read(i));h[t]=n}let d=r.readVarIntNum();return d>0&&(t=r.read(d)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:i}}}class nV{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new nP,this.originator=i}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let r=await new Promise(async(r,i)=>{try{let n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nB(l);n={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let r=await nA(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,r)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let i=await this.handleFetchAndValidate(e,t,this.peers[l]);r(i)}catch(e){i(e)}return}n=this.peers[l]}let h=tJ(32),u=ta(h),d=await this.serializeRequest(a,s,o,c,h);this.callbacks[u]={resolve:r,reject:i};let f=n.peer.listenForGeneralMessages((e,t)=>{let r,i=new td(t);if(ta(i.read(32))!==u)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=i.readVarIntNum(),s={},o=i.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=i.readVarIntNum(),t=i.read(e),r=ti(t),n=i.readVarIntNum(),a=i.read(n),o=ti(a);s[r]=o}s["x-bsv-auth-identity-key"]=e;let c=i.readVarIntNum();c>0&&(r=i.read(c));let h=new Response(r?new Uint8Array(r):null,{status:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[u].resolve(h),delete this.callbacks[u]});n.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===n.pendingCertificateRequests.length&&e()},100)}),await n.peer.toPeer(d.toArray(),n.identityKey).catch(async a=>{if(a.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let i=await this.fetch(e,t);r(i);return}if(a.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,n);r(i);return}catch(e){i(e)}else i(a)})}catch(e){i(e)}});return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){let r,i=new URL(e).origin;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{let e=new nB(i);r={peer:new nC(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let n=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(n),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){let a=new tu;if(a.write(n),a.writeVarIntNum(e.length),a.write(e9(e)),i.pathname.length>0){let e=e9(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e9(i.search);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);let s=[];for(let[e,r]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");s.push([e,r])}else if(e.startsWith("content-type"))r=r.split(";")[0].trim(),s.push([e,r]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");s.sort(([e],[t])=>e.localeCompare(t)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=e9(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e9(s[e][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){let e=s.find(([e])=>"content-type"===e);r=e&&e[1].includes("application/json")?"{}":""}if(r){let e=await this.normalizeBodyToNumberArray(r);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}async handleFetchAndValidate(e,t,r){let i=await fetch(e,t);if(i.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),i.ok)return r.supportsMutualAuth=!1,i;throw Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(e,t={},r){let i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);let n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=r.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=r.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let c=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let u=c.attempts+1,d=c.maxAttempts;c.attempts=u;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${u}/${d})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${u} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${u} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let i=this.getPaymentRetryDelay(c.attempts);return await this.wait(i),this.handlePaymentAndRetry(e,h,r)}}isPaymentContextCompatible(e,t,r,i){return e.satoshisRequired===t&&e.serverIdentityKey===r&&e.derivationPrefix===i}async createPaymentContext(e,t,r,i,n){let a=await nO(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:i},this.originator),o=new rC().lock(tX.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:r,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:i}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:r,transactionBase64:ta(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:i,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let r={...t.headers??{}},i="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:i,headers:r,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:e9(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("undefined"!=typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("undefined"!=typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:e9(e.toString(),"utf8").length};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:e9(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,r){let i="[AuthFetch][Payment]";"error"===e?console.error(`${i} ${t}`,r):"warn"===e?console.warn(`${i} ${t}`,r):"function"==typeof console.info?console.info(`${i} ${t}`,r):console.log(`${i} ${t}`,r)}createPaymentErrorEntry(e,t){let r={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(r.message=t.message,r.stack=t.stack??void 0):r.message=String(t),r}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,r){let i=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return i.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},r instanceof Error&&(i.cause=r),i}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return e9(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e9(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,r)=>{t.push([r,e.toString()])}),e9(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e9(e.toString(),"utf8");if(e instanceof ReadableStream)throw Error("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class nD{pushDrop;static decode(e){let t=rV.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=ti(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=e7(t.fields[1]);return{protocol:r,identityKey:i,domain:ti(t.fields[2]),topicOrService:ti(t.fields[3])}}constructor(e,t){this.pushDrop=new rV(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e9(e,"utf8"),e9(i,"hex"),e9(t,"utf8"),e9(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let nU="bsvsdk_overlay_host_reputation_v1";class nF{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let r=this.getOrCreate(e),i=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===r.avgLatencyMs?r.avgLatencyMs=n:r.avgLatencyMs=.75*r.avgLatencyMs+.25*n,r.lastLatencyMs=n,r.totalSuccesses+=1,r.consecutiveFailures=0,r.backoffUntil=0,r.lastUpdatedAt=i,r.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let r=this.getOrCreate(e),i=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let a=Math.max(r.consecutiveFailures-2,0);0===a?r.backoffUntil=0:r.backoffUntil=i+Math.min(6e4,1e3*Math.pow(2,a-1)),r.lastUpdatedAt=i,r.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let r=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(r.has(e)||r.set(e,t))});let i=Array.from(r.keys()).map(e=>{let i=this.getOrCreate(e);return{...i,score:this.computeScore(i,t),originalOrder:r.get(e)??0}});return i.sort((e,r)=>{let i=e.backoffUntil>t;return i!==r.backoffUntil>t?i?1:-1:e.score!==r.score?e.score-r.score:e.totalSuccesses!==r.totalSuccesses?r.totalSuccesses-e.totalSuccesses:e.originalOrder-r.originalOrder}),i.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,r)=>{try{e.setItem(t,r)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nU);if("string"!=typeof t||0===t.length)return;let r=JSON.parse(t);if("object"!=typeof r||null===r)return;for(let e of(this.stats.clear(),Object.keys(r))){let t=r[e];if(null!=t&&"object"==typeof t){let r={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(r.host,r)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,r]of this.stats.entries())t[e]=r;e.set(nU,JSON.stringify(t))}catch{}}computeScore(e,t){let r=e.avgLatencyMs??1500,i=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,r/2);return r+i+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nL=new nF,nK="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nH=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nq=["https://testnet-users.bapp.dev"];class nM{fetchClient;allowHTTP;constructor(e=nK,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i="undefined"!=typeof AbortController?new AbortController:void 0,n=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},n=await this.fetchClient(`${e}/lookup`,r);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new td([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=e7(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),i.push({txid:r,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:i.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:r0.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class n${facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nM(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nH:nq);const t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};const r=e.reputationStorage;"localStorage"===r?this.hostReputation=new nF:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new nF(r):this.hostReputation=nL,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let i=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(i.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await Promise.allSettled(i.map(async r=>await this.lookupHostWithTracking(r,e,t))),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n){if("fulfilled"!==e.status)continue;let t=e.value;if(t?.type==="output-list"&&Array.isArray(t.outputs))for(let e of t.outputs){let t=s(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:r0.fromBEEF(e.beef).id("hex"),expiresAt:i+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,r)}catch{continue}let n=`${r.txId}.${e.outputIndex}`;a.set(n,e)}}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),r=this.hostsCache.get(e);if("object"==typeof r&&r.expiresAt>t)return r.hosts.slice();if("object"==typeof r&&r.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),r.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw Error("Hosts is not defined.");return t.slice()}catch{}let i=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,i),(await i).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),r=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:r}),t}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},r=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");if(0===r.length)return[];let i=await Promise.allSettled(r.map(async e=>await this.lookupHostWithTracking(e,t,5e3))),n=new Set;for(let t of i){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=r0.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=nD.decode(i);if(a.topicOrService!==e||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&n.add(a.domain)}catch{continue}}return[...n]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let r=Date.now(),i=this.hostReputation.rankHosts(e,r),n=i.filter(e=>e.backoffUntil<=r).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...i.map(e=>e.backoffUntil))-r,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,r){let i=Date.now();try{let n=await this.facilitator.lookup(e,t,r),a=Date.now()-i;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nz{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let r;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){i["x-includes-off-chain-values"]="true";let e=new tu;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),r=new Uint8Array(e.toArray())}else r=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nW{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new nz(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new n$({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,r])=>{try{let i=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...r]});if(null==i||0===Object.keys(i).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:i}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),l=(await Promise.all(c)).filter(e=>e.success);if(0===l.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let h={};for(let e of l){let t=e.host,r=e.steak,i=new Set;for(let[e,t]of Object.entries(r)){let r=t.outputsToAdmit,n=t.coinsToRetain,a=t.coinsRemoved;(r?.length>0||n?.length>0||a?.length>0)&&i.add(e)}h[t]=i}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="any"):(r=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,i="all"),r.length>0&&!this.checkAcknowledgmentFromAllHosts(h,r,i))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(h,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,r){for(let i of Object.values(e))if("all"===r){for(let e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(let r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(let r of Object.values(e)){let e=!0;for(let i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(let r of Object.values(e))for(let e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[r,i]of Object.entries(t)){let t,n,a=e[r];if(null==a)return!1;if("all"===i||"any"===i)n=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let r of t)if(a.has(r)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let r of t.outputs)try{let t=r0.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=nD.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}async function nj(e,t,r=5){let i=0;for(;i<r;){i++;try{return await e()}catch(e){if(i<r&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=r0.fromBEEF(n.competingBeef,n.competingTxs[0]);await nj(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nX=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nG=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tl(e,e9("ce00","hex"))},nY=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new J;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nG(r.digest())},nJ=e=>{let{data:t,prefix:r}=th(e=nX(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==e7(r))throw Error("Bad prefix");return t},nZ=e=>{try{return nJ(e),!0}catch(e){return!1}};class nQ{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nV(e.wallet)}async getUploadInfo(e,t){let r=`${this.baseURL}/upload`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!i.ok)throw Error(`Upload info request failed: HTTP ${i.status}`);let n=await i.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nY(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=i.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,r);return await this.uploadFile(a,{data:i,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let r=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let i=await r.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return i.data}async listUploads(){let e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let r=await t.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){let r=`${this.baseURL}/renew`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!i.ok)throw Error(`renewFile request failed: HTTP ${i.status}`);let n=await i.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class n0{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new n$({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let r=[],i=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let n=r0.fromBEEF(t.outputs[e].beef),{fields:a}=rV.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new td(a[3]).readVarIntNum()<i||r.push(ti(a[2]))}return r}async download(e){if(!nZ(e))throw Error("Invalid parameter UHRP url");let t=e7(nJ(e)),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{let i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let n=i.body.getReader(),a=new J,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(e7(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let n1={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},n2={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},n8={identiCert:"z40BOInXkI8m7f/wBrv4MJ09bZfzZbTj2fJqCtONqCY=",discordCert:"2TgqRC35B1zehGmB21xveZNc7i5iqHc0uxMb+1NMPW4=",phoneCert:"mffUklUzxbHr65xLohn0hRL0Tq2GjW1GYF/OPfzqJ6A=",xCert:"vdDWvftf1H+5+ZprUw123kjHlywH+v20aPQTuXgMpNc=",registrant:"YoPsbfR6YQczjzPdHCoGC7nJsOdPQR50+SYqcWpJ0y0=",emailCert:"exOl3KM0dIJ04EW5pZgbZmPag6MdJXd3/a1enmUU/BA=",anyone:"mfkOMfLDQmrr3SBxBQ5WeE+6Hy3VJRFq6w4A5Ljtlis=",self:"Hkge6X5JRxt1cWXtHLCrSTg6dCVTxjQJJ48iOYd7n3g=",coolCert:"AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo="},n3=[2,"contact"];class n6{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class n4{wallet;cache=new n6;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nI,this.originator=t}async getContacts(e,t=!1,r=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t);return null!=e?r.filter(t=>t.identityKey===e):r}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let i=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);i.push(`identityKey ${e7(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=rV.decode(rE.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let r=JSON.parse(e.customInstructions).keyID,{plaintext:i}=await this.wallet.decrypt({ciphertext:t.fields[0],protocolID:n3,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(ti(i));a.push(n)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(a)),null!=e?a.filter(t=>t.identityKey===e):a}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?r[n]=a:r.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:n3,keyID:e.identityKey,counterparty:"self",data:e9(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${e7(s)}`],limit:100},this.originator),c=null,l=ta(tJ(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=r0.fromBEEF(o.BEEF,r),a=rV.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:n3,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(ti(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e9(JSON.stringify(h),"utf8"),protocolID:n3,keyID:l,counterparty:"self"},this.originator),d=await new rV(this.wallet,this.originator).lock([u],n3,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rV(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(n3,l,"self"),u=await h.sign(r0.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e7(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let r=[],{hmac:i}=await this.wallet.createHmac({protocolID:n3,keyID:e,counterparty:"self",data:e9(e,"utf8")},this.originator);r.push(`identityKey ${e7(i)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[r,i]=String(t.outpoint).split("."),a=r0.fromBEEF(n.BEEF,r),s=rV.decode(a.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:n3,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(ti(c)).identityKey===e){let e=`${r}.${i}`,t=new rV(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(n3,o,"self"),c=await s.sign(r0.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class n5{options;originator;wallet;contactsManager;constructor(e,t=n2,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new nI,this.contactsManager=new n4(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new iT(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new t1(1).toPublicKey().toString()},this.originator),i=await new rV(this.wallet,this.originator).lock([e9(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(r0.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){if(t){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t}let{certificates:r}=await this.wallet.discoverByIdentityKey(e,this.originator);return r.map(e=>n5.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[r,i]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),n=new Map(r.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>n.get(e.subject)??n5.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new n$({networkPreset:(await this.wallet.getNetwork({})).network}),r=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==r.type)throw Error("Failed to get lookup result");let i=new nW(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nj(async()=>{let e=r0.fromBEEF(r.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:r.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=r0.fromBEEF(n.tx),s=new rV(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await i.broadcast(r0.fromAtomicBEEF(c))},i)}async getContacts(e,t=!1,r=1e3){return await this.contactsManager.getContacts(e,t,r)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static parseIdentity(e){let t,r,i,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case n8.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case n8.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case n8.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case n8.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case n8.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case n8.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=n5.tryToParseGenericIdentity(s,o,c);t=e.name,r=e.avatarURL,i=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:i,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,r){let i=t.firstName,n=t.lastName,a=n5.hasValue(i)&&n5.hasValue(n)?`${i} ${n}`:n5.hasValue(i)?i:n5.hasValue(n)?n:void 0,s=n5.hasValue(t.name)?t.name:n5.hasValue(t.userName)?t.userName:a??(n5.hasValue(t.email)?t.email:n1.name),o=n5.hasValue(t.profilePhoto)?t.profilePhoto:n5.hasValue(t.avatar)?t.avatar:n5.hasValue(t.icon)?t.icon:n5.hasValue(t.photo)?t.photo:n1.avatarURL,c=n5.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:n1.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:n5.hasValue(r?.iconUrl)?r.iconUrl:n1.badgeIconURL,badgeClickURL:n1.badgeClickURL}}}class n7{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nI,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new n$}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),r=new rV(this.wallet,this.originator),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await r.lock(i,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(r0.fromAtomicBEEF(s))}async resolve(e,t){let r=this.mapDefinitionTypeToServiceName(e),i=await this.resolver.query({service:r,query:t});if("output-list"!==i.type)return[];let n=[];for(let t of i.outputs)try{let r=r0.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);n.push(i)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of r)if(t.spendable)try{let[r,a]=t.outpoint.split("."),s=r0.fromBEEF(i,r).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:r,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=r0.fromAtomicBEEF(n.tx),s=new rV(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(r0.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new rV(this.wallet,this.originator),a=this.buildPushDropFields(t,r),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=r0.fromAtomicBEEF(l.tx),u=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nW([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(r0.fromAtomicBEEF(f))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return r.push(t),r.map(e=>e9(e))}async parseLockingScript(e,t){let r,i,n=rV.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"basket",basketID:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;r=ti(c),i={definitionType:"protocol",protocolID:n9(ti(e)),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;r=ti(l);let h={};try{h=JSON.parse(ti(c))}catch{}i={definitionType:"certificate",type:ti(e),name:ti(t),iconURL:ti(a),description:ti(s),documentationURL:ti(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...i,registryOperator:r}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function n9(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[r,i]=t;if(![0,1,2].includes(r))throw Error("Invalid security level.");if("string"!=typeof i)throw Error("Invalid protocolID");return[r,i]}class ae{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nI,t="kvstore default",r=!0,i,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let r=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,r)}}getLockingScript(e,t){let[r,i]=e.outpoint.split("."),n=t.findTxid(r)?.tx;if(null==n)throw Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,n=await this.getOutputs(e,r),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,rZ.fromBinary(n.BEEF)),t=rV.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");i=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:i},this.originator);a.value=ti(t)}else a.value=ti(i);return a}getInputs(e){let t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){let n=this.getProtocol(e),a=r0.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(a,e);s[e]={unlockingScript:i.toHex()}}return s}async set(e,t){let r=await this.queueOperationOnKey(e);try{let r,i=await this.lookupValue(e,void 0,10);if(i.value===t){if(void 0===i.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return i.outpoint}let n=this.getProtocol(e),a=e9(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rV(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:i}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);r=`${i}.0`}}catch(t){throw Error(`There are ${c.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return r}finally{this.finishOperationOnKey(e,r)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(e);if(r.length>0){let a=new rV(this.wallet,this.originator);try{let n=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(r.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class at{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let r=e.id("hex"),i=this.ctxKeyFn(t);return`${this.interpreterVersion}|${r}|${i}`}async buildHistory(e,t){if(null!=this.historyCache){let r=this.historyKey(e,t);if(this.historyCache.has(r)){let e=this.historyCache.get(r);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",r),e.slice()}}let r=[],i=new Set,n=async e=>{let a=e.id("hex");if(i.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}i.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let i=0;i<e.outputs.length;i++)try{let n=await Promise.resolve(this.interpreter(e,i,t));void 0!==n&&(r.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${i}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=r.reverse();if(null!=this.historyCache){let r=this.historyKey(e,t);this.historyCache.set(r,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",r)}return a}}let ar={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},ai=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rV.decode(i.lockingScript),a=Object.keys(ar).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=ti(n.fields[ar.key]),c=ti(n.fields[ar.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return ti(n.fields[ar.value])}catch{return}}catch{return}},an={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class aa{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...an,...e},this.wallet=e.wallet??new nI,this.historian=new at(ai),this.lookupResolver=new n$({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nW(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let r=await this.queryOverlay(e,t);return r.length>0?r[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenSetDescription&&""!==r.tokenSetDescription?r.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=r.tokenUpdateDescription&&""!==r.tokenUpdateDescription?r.tokenUpdateDescription:`Update KVStore value for ${e}`,c=r.tokenAmount??this.config.tokenAmount,l=r.tags??[];try{let r=new rV(this.wallet,this.config.originator),n=[e9(JSON.stringify(a),"utf8"),e9(e,"utf8"),e9(t,"utf8"),e9(i,"hex")];l.length>0&&n.push(e9(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,ti(e9(e,"utf8")),"anyone",!0);return await nj(async()=>{let t=await this.queryOverlay({key:e,controller:i},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],i=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:i.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=r0.fromAtomicBEEF(a.tx),l=r.unlock(this.config.protocolID,e,"anyone"),u=await l.sign(s,0),{tx:d}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==d)throw Error("Unable to finalize update transaction");let f=r0.fromAtomicBEEF(d);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=r0.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenRemovalDescription&&""!==r.tokenRemovalDescription?r.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let r=new rV(this.wallet,this.config.originator);return await nj(async()=>{let n=await this.queryOverlay({key:e,controller:i},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=r0.fromAtomicBEEF(l.tx),u=r.unlock(a??this.config.protocolID,e,"anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=r0.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let r=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==r.type||0===r.outputs.length)return[];let i=[];for(let e of r.outputs)try{let r,n=r0.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rV.decode(a.lockingScript),o=Object.keys(ar).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new iE("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),keyID:ti(s.fields[ar.key])})}catch(e){continue}if(c&&null!=s.fields[ar.tags])try{r=JSON.parse(ti(s.fields[ar.tags]))}catch(e){r=void 0}let u={key:ti(s.fields[ar.key]),value:ti(s.fields[ar.value]),controller:e7(s.fields[ar.controller]),protocolID:JSON.parse(ti(s.fields[ar.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:rZ.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(u.history=await this.historian.buildHistory(n,{key:u.key,protocolID:u.protocolID})),i.push(u)}catch(e){continue}return i}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let as=aa;return p})());
|
|
19
|
+
`);return e}addComputedLeaves(){let e=e=>e0(Q(e1(e,"hex").reverse()).reverse());for(let t of this.bumps)for(let r=1;r<t.path.length;r++)for(let i of t.path[r-1])if("string"==typeof i.hash&&(1&i.offset)==0){let n=t.path[r-1].find(e=>e.offset===i.offset+1),a=i.offset>>1;void 0!==n&&"string"==typeof n.hash&&t.path[r].every(e=>e.offset!==a)&&t.path[r].push({offset:a,hash:e(n.hash+i.hash)})}}}let rz="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class rW{version;inputs;outputs;lockTime;metadata;merklePath;cachedHash;rawBytesCache;hexCache;static addPathOrInputs(e,t,r){if("number"==typeof e.pathIndex){let t=r[e.pathIndex];if("object"!=typeof t)throw Error("Invalid merkle path index found in BEEF!");e.tx.merklePath=t}else for(let i of e.tx.inputs){if(void 0===i.sourceTXID)throw Error("Input sourceTXID is undefined");let e=t[i.sourceTXID];if("object"!=typeof e)throw Error(`Reference to unknown TXID in BEEF: ${i.sourceTXID??"undefined"}`);i.sourceTransaction=e.tx,this.addPathOrInputs(e,t,r)}}static fromBEEF(e,t){let{tx:r}=rW.fromAnyBeef(e,t);return r}static fromAtomicBEEF(e){let{tx:t,txid:r,beef:i}=rW.fromAnyBeef(e);if(r!==i.atomicTxid)if(null!=i.atomicTxid)throw Error(`Transaction with TXID ${i.atomicTxid} not found in BEEF data.`);else throw Error("beef must conform to BRC-95 and must contain the subject txid.");return t}static fromAnyBeef(e,t){let r=r$.fromBinary(e);if(r.txs.length<1)throw Error("beef must include at least one transaction.");let i=t??r.atomicTxid??r.txs.slice(-1)[0].txid,n=r.findAtomicTransaction(i);if(null==n)if(null!=t)throw Error(`Transaction with TXID ${i} not found in BEEF data.`);else throw Error("beef does not contain transaction for atomic txid.");return{tx:n,beef:r,txid:i}}static fromEF(e){let t=new tn(e),r=t.readUInt32LE();if("0000000000ef"!==e0(t.read(6)))throw Error("Invalid EF marker");let i=t.readVarIntNum(),n=[];for(let e=0;e<i;e++){let e=e0(t.readReverse(32)),r=t.readUInt32LE(),i=t.readVarIntNum(),a=t.read(i),s=rm.fromBinary(a),o=t.readUInt32LE(),c=t.readUInt64LEBn().toNumber(),l=t.readVarIntNum(),h=t.read(l),u=ry.fromBinary(h),d=new rW(void 0,[],[],void 0);d.outputs=Array(r+1).fill(null),d.outputs[r]={satoshis:c,lockingScript:u},n.push({sourceTransaction:d,sourceTXID:e,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let a=t.readVarIntNum(),s=[];for(let e=0;e<a;e++){let e=t.readUInt64LEBn().toNumber(),r=t.readVarIntNum(),i=t.read(r),n=ry.fromBinary(i);s.push({satoshis:e,lockingScript:n})}return new rW(r,n,s,t.readUInt32LE())}static parseScriptOffsets(e){let t=new tn(e),r=[],i=[];t.pos+=4;let n=t.readVarIntNum();for(let e=0;e<n;e++){t.pos+=36;let i=t.readVarIntNum();r.push({vin:e,offset:t.pos,length:i}),t.pos+=i+4}let a=t.readVarIntNum();for(let e=0;e<a;e++){t.pos+=8;let r=t.readVarIntNum();i.push({vout:e,offset:t.pos,length:r}),t.pos+=r}return{inputs:r,outputs:i}}static fromReader(e){let t=e.readUInt32LE(),r=e.readVarIntNum(),i=[];for(let t=0;t<r;t++){let t=e0(e.readReverse(32)),r=e.readUInt32LE(),n=e.readVarIntNum(),a=e.read(n),s=rm.fromBinary(a),o=e.readUInt32LE();i.push({sourceTXID:t,sourceOutputIndex:r,unlockingScript:s,sequence:o})}let n=e.readVarIntNum(),a=[];for(let t=0;t<n;t++){let t=e.readUInt64LEBn().toNumber(),r=e.readVarIntNum(),i=e.read(r),n=ry.fromBinary(i);a.push({satoshis:t,lockingScript:n})}return new rW(t,i,a,e.readUInt32LE())}static fromBinary(e){let t=e.slice(),r=Uint8Array.from(t),i=new tn(t),n=rW.fromReader(i);return n.rawBytesCache=r,n}static fromHex(e){let t=e1(e,"hex"),r=Uint8Array.from(t),i=new tn(t),n=rW.fromReader(i);return n.rawBytesCache=r,n.hexCache=null!=rz?rz.from(r).toString("hex"):e0(t),n}static fromHexEF(e){return rW.fromEF(e1(e,"hex"))}static fromHexBEEF(e,t){return rW.fromBEEF(e1(e,"hex"),t)}constructor(e=1,t=[],r=[],i=0,n=new Map,a){this.version=e,this.inputs=t,this.outputs=r,this.lockTime=i,this.metadata=n,this.merklePath=a}invalidateSerializationCaches(){this.cachedHash=void 0,this.rawBytesCache=void 0,this.hexCache=void 0}addInput(e){if(void 0===e.sourceTXID&&void 0===e.sourceTransaction)throw Error("A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.");void 0===e.sequence&&(e.sequence=0xffffffff),this.invalidateSerializationCaches(),this.inputs.push(e)}addOutput(e){if(this.cachedHash=void 0,!0!==e.change){if(void 0===e.satoshis)throw Error("either satoshis must be defined or change must be set to true");if(e.satoshis<0)throw Error("satoshis must be a positive integer or zero")}if(null==e.lockingScript)throw Error("lockingScript must be defined");this.outputs.push(e)}addP2PKHOutput(e,t){let r=new rx().lock(e);if(void 0===t)return this.addOutput({lockingScript:r,change:!0});this.addOutput({lockingScript:r,satoshis:t})}updateMetadata(e){this.metadata={...this.metadata,...e}}async fee(e=rA.getInstance(),t="equal"){if(this.invalidateSerializationCaches(),"number"==typeof e){let t=e;e={computeFee:async()=>t}}let r=await e.computeFee(this),i=this.calculateChange(r);if(i<=0){this.outputs=this.outputs.filter(e=>!0!==e.change);return}this.distributeChange(i,t)}calculateChange(e){let t=0;for(let e of this.inputs){if("object"!=typeof e.sourceTransaction)throw Error("Source transactions are required for all inputs during fee computation");t+=e.sourceTransaction.outputs[e.sourceOutputIndex].satoshis??0}for(let r of(t-=e,this.outputs))!0!==r.change&&void 0!==r.satoshis&&(t-=r.satoshis);return t}distributeChange(e,t){let r=0,i=this.outputs.filter(e=>e.change);if("random"===t?r=this.distributeRandomChange(e,i):"equal"===t&&(r=this.distributeEqualChange(e,i)),r<e){let t=this.outputs[this.outputs.length-1];void 0!==t.satoshis?t.satoshis+=e-r:t.satoshis=e-r}}distributeRandomChange(e,t){let r=0,i=e,n=Array(t.length).fill(1);i-=t.length,r+=t.length;for(let e=0;e<t.length-1;e++){let t=this.benfordNumber(0,i);n[e]=n[e]+t,r+=t,i-=t}for(let e of this.outputs)!0===e.change&&(e.satoshis=n.shift());return r}distributeEqualChange(e,t){let r=0,i=Math.floor(e/t.length);for(let e of t)r+=i,e.satoshis=i;return r}benfordNumber(e,t){return Math.floor(e+(t-e)*Math.log10(1+1/(Math.floor(9*Math.random())+1))/Math.log10(10))}getFee(){let e=0;for(let t of this.inputs){if("object"!=typeof t.sourceTransaction)throw Error("Source transactions or sourceSatoshis are required for all inputs to calculate fee");e+=t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0}let t=0;for(let e of this.outputs)t+=e.satoshis??0;return e-t}async sign(){for(let e of(this.invalidateSerializationCaches(),this.outputs))if(void 0===e.satoshis)if(!0===e.change)throw Error("There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.");else throw Error("One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.");let e=await Promise.all(this.inputs.map(async(e,t)=>"object"==typeof this.inputs[t].unlockingScriptTemplate?await this.inputs[t]?.unlockingScriptTemplate?.sign(this,t):await Promise.resolve(void 0)));for(let t=0,r=this.inputs.length;t<r;t++)"object"==typeof this.inputs[t].unlockingScriptTemplate&&(this.inputs[t].unlockingScript=e[t])}async broadcast(e=rV()){return await e.broadcast(this)}writeTransactionBody(e){for(let t of(e.writeUInt32LE(this.version),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTXID)if(null!=t.sourceTransaction)e.write(t.sourceTransaction.hash());else throw Error("sourceTransaction is undefined");else e.writeReverse(e1(t.sourceTXID,"hex"));if(e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toUint8Array();e.writeVarIntNum(r.length),e.write(r)}e.writeUInt32LE(this.lockTime)}buildSerializedBytes(){let e=new ti;return this.writeTransactionBody(e),e.toUint8Array()}getSerializedBytes(){return null==this.rawBytesCache&&(this.rawBytesCache=this.buildSerializedBytes()),this.rawBytesCache}toBinary(){return Array.from(this.getSerializedBytes())}toUint8Array(){return this.getSerializedBytes()}toEF(){let e=new ti;for(let t of(e.writeUInt32LE(this.version),e.write([0,0,0,0,0,239]),e.writeVarIntNum(this.inputs.length),this.inputs)){if(void 0===t.sourceTransaction)throw Error("All inputs must have source transactions when serializing to EF format");if(void 0===t.sourceTXID?e.write(t.sourceTransaction.hash()):e.write(e1(t.sourceTXID,"hex").reverse()),e.writeUInt32LE(t.sourceOutputIndex),null==t.unlockingScript)throw Error("unlockingScript is undefined");let r=t.unlockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r),e.writeUInt32LE(t.sequence??0xffffffff),e.writeUInt64LE(t.sourceTransaction.outputs[t.sourceOutputIndex].satoshis??0);let i=t.sourceTransaction.outputs[t.sourceOutputIndex].lockingScript.toBinary();e.writeVarIntNum(i.length),e.write(i)}for(let t of(e.writeVarIntNum(this.outputs.length),this.outputs)){e.writeUInt64LE(t.satoshis??0);let r=t.lockingScript.toBinary();e.writeVarIntNum(r.length),e.write(r)}return e.writeUInt32LE(this.lockTime),e.toArray()}toHexEF(){return e0(this.toEF())}toHex(){if(null!=this.hexCache)return this.hexCache;let e=this.getSerializedBytes(),t=null!=rz?rz.from(e).toString("hex"):e0(Array.from(e));return this.hexCache=t,t}toHexBEEF(){return e0(this.toBEEF())}toHexAtomicBEEF(){return e0(this.toAtomicBEEF())}hash(e){return(null==this.cachedHash&&(this.cachedHash=Q(this.getSerializedBytes())),"hex"===e)?e0(this.cachedHash):this.cachedHash}id(e){let t=[...this.hash()];return(t.reverse(),"hex"===e)?e0(t):t}async verify(e=rU(),t,r){let i=new Set,n=[this];for(;n.length>0;){let a=n.shift(),s=a?.id("hex")??"";if(null!=s&&""!==s&&i.has(s))continue;if("object"==typeof a?.merklePath)if("scripts only"===e){null!=s&&i.add(s);continue}else{if(await a.merklePath.verify(s,e)){i.add(s);continue}throw Error(`Invalid merkle path for transaction ${s}`)}if(void 0!==t){if(void 0===a)throw Error("Transaction is undefined");let e=rW.fromEF(a.toEF());if(delete e.outputs[0].satoshis,e.outputs[0].change=!0,await e.fee(t),a.getFee()<e.getFee())throw Error(`Verification failed because the transaction ${s} has an insufficient fee and has not been mined.`)}let o=0;if(void 0===a)throw Error("Transaction is undefined");for(let e=0;e<a.inputs.length;e++){let t=a.inputs[e];if("object"!=typeof t.sourceTransaction)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated source transaction. This source transaction is required for transaction verification because there is no merkle proof for the transaction spending a UTXO it contains.`);if("object"!=typeof t.unlockingScript)throw Error(`Verification failed because the input at index ${e} of transaction ${s} is missing an associated unlocking script. This script is required for transaction verification because there is no merkle proof for the transaction spending the UTXO.`);let c=t.sourceTransaction.outputs[t.sourceOutputIndex];o+=c.satoshis??0;let l=t.sourceTransaction.id("hex");i.has(l)||n.push(t.sourceTransaction);let h=a.inputs.filter((t,r)=>r!==e);if(void 0===t.sourceTXID&&(t.sourceTXID=l),!new rS({sourceTXID:t.sourceTXID,sourceOutputIndex:t.sourceOutputIndex,lockingScript:c.lockingScript,sourceSatoshis:c.satoshis??0,transactionVersion:a.version,otherInputs:h,unlockingScript:t.unlockingScript,inputSequence:t.sequence??0xffffffff,inputIndex:e,outputs:a.outputs,lockTime:a.lockTime,memoryLimit:r}).validate())return!1}let c=0;for(let e of a.outputs){if("number"!=typeof e.satoshis)throw Error("Every output must have a defined amount during transaction verification.");c+=e.satoshis}if(c>o)return!1;i.add(s)}return!0}toBEEF(e){let t=new ti;t.writeUInt32LE(rH);let r=[],i=new Map,n=new Map,a=[],s=new Set,o=t=>{let c=t.id("hex");if(s.has(c))return;let l={tx:t},h=t.merklePath,u="object"==typeof h;if(u&&null!=h&&(l.pathIndex=(e=>{let t=i.get(e);if(void 0!==t)return t;let a=`${e.blockHeight}:${e.computeRoot()}`,s=n.get(a);if(void 0!==s)return r[s].combine(e),i.set(e,s),s;let o=r.length;return r.push(e),i.set(e,o),n.set(a,o),o})(h)),!u)for(let r=t.inputs.length-1;r>=0;r--){let i=t.inputs[r];if("object"==typeof i.sourceTransaction)o(i.sourceTransaction);else if(!1===e)throw Error("A required source transaction is missing!")}s.add(c),a.push(l)};for(let e of(o(this),t.writeVarIntNum(r.length),r))t.write(e.toBinary());for(let e of(t.writeVarIntNum(a.length),a))t.write(e.tx.toBinary()),"number"==typeof e.pathIndex?(t.writeUInt8(1),t.writeVarIntNum(e.pathIndex)):t.writeUInt8(0);return t.toArray()}toAtomicBEEF(e){return[1,1,1,1].concat(this.hash(),this.toBEEF(e))}}function rj(e){return"success"===e.status}function rG(e){return"error"===e.status}let rX=class extends r${knownTo={};constructor(e){if(super(),null!=e)for(let t of e)this.addParty(t)}isParty(e){return Object.keys(this.knownTo).includes(e)}addParty(e){if(this.isParty(e))throw Error(`Party ${e} already exists.`);this.knownTo[e]={}}getKnownTxidsForParty(e){let t=this.knownTo[e];if(void 0===t)throw Error(`Party ${e} is unknown.`);return Object.keys(t)}getTrimmedBeefForParty(e){let t=this.getKnownTxidsForParty(e),r=this.clone();return r.trimKnownTxids(t),r}addKnownTxidsForParty(e,t){this.isParty(e)||this.addParty(e);let r=this.knownTo[e];for(let e of t)r[e]=!0,this.mergeTxidOnly(e)}mergeBeefFromParty(e,t){let r=Array.isArray(t)?r$.fromBinary(t):t,i=r.getValidTxids();this.mergeBeef(r),this.addKnownTxidsForParty(e,i)}};class rJ{network;URL;httpClient;constructor(e="main",t=rC()){this.network=e,this.URL=`https://api.whatsonchain.com/v1/bsv/${e}/tx/raw`,this.httpClient=t}async broadcast(e){let t=e.toHex();try{let e=await this.httpClient.request(this.URL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/plain"},data:{txhex:t}});if(!e.ok)return{status:"error",code:e.status.toString()??"ERR_UNKNOWN",description:e.data??"Unknown error"};{let t=e.data;return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class rY{https;constructor(e){this.https=e}async request(e,t){return await new Promise((r,i)=>{let n=this.https.request(e,t,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{let i=e.statusCode>=200&&e.statusCode<=299,n=e.headers["content-type"],a=""!==t&&"string"==typeof n&&n.startsWith("application/json")?JSON.parse(t):t;r({status:e.statusCode,statusText:e.statusMessage,ok:i,data:a})})});n.on("error",e=>{i(e)}),null!==t.data&&void 0!==t.data&&n.write(Buffer.from(t.data)),n.end()})}}class rZ{fetch;constructor(e){this.fetch=e}async request(e,t){let r={method:t.method,headers:t.headers,body:t.data},i=await this.fetch(e,r),n=await i.text();return{ok:i.ok,status:i.status,statusText:i.statusText,data:n}}}function rQ(){let e={async request(){throw Error("No method available to perform HTTP request")}};if("undefined"!=typeof window&&"function"==typeof window.fetch)return new rZ(window.fetch.bind(window));if("undefined"==typeof require)return e;try{let e=require("https");return new rY(e)}catch(t){return e}}class r0{URL;httpClient;constructor(e,t=rQ()){this.URL=e,this.httpClient=t}async broadcast(e){let t={method:"POST",headers:{"Content-Type":"application/octet-stream"},data:new Blob([new Uint8Array(e.toEF())])};try{let r=await this.httpClient.request(this.URL,t);if(!r.ok)return{status:"error",code:r.status.toString()??"ERR_UNKNOWN",description:r.data??"Unknown error"};{let t=e.id("hex");return{status:"success",txid:t,message:"broadcast successful"}}}catch(e){return{status:"error",code:"500",description:"string"==typeof e.message?e.message:"Internal Server Error"}}}}class r1{baseUrl;httpClient;apiKey;constructor(e,t={}){let{httpClient:r,apiKey:i}=t;this.baseUrl=e,this.httpClient=r??rC(),this.apiKey=i??""}async isValidRootForHeight(e,t){let r={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.apiKey}`},data:[{blockHeight:t,merkleRoot:e}]};try{let e=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`,r);if(e.ok)return"CONFIRMED"===e.data.confirmationState;throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${JSON.stringify(e.data)}`)}catch(e){throw Error(`Failed to verify merkleroot for height ${t} because of an error: ${e instanceof Error?e.message:String(e)}`)}}async currentHeight(){let e={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`}};try{let t=await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`,e);if(t.ok&&t.data&&"number"==typeof t.data.height)return t.data.height;throw Error(`Failed to get current height because of an error: ${JSON.stringify(t.data)}`)}catch(e){throw Error(`Failed to get current height because of an error: ${e instanceof Error?e.message:String(e)}`)}}}let r2="42423301",r8=(e,t,r)=>{let i="object"!=typeof r;if(i){let e=new tA,t=new tW(1),i=e.g.mul(t);r=new tL(i.x,i.y)}let n=tq(32),a=e5(n),s=`2-message signing-${a}`,o=t.deriveChild(r,s).sign(e).toDER(),c=t.toPublicKey().encode(!0);return[...e1(r2,"hex"),...c,...i?[0]:r.encode(!0),...n,...o]},r3=(e,t,r)=>{let i=new tn(t),n=e0(i.read(4));if(n!==r2)throw Error(`Message version mismatch: Expected ${r2}, received ${n}`);let a=tL.fromString(e0(i.read(33))),[s]=i.read(1);if(0===s)r=new tW(1);else{let e=e0([s,...i.read(32)]);if("object"!=typeof r)throw Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${e}`);let t=r.toPublicKey().encode(!0,"hex");if(e!==t)throw Error(`The recipient public key is ${t} but the signature requres the recipient to have public key ${e}`)}let o=e5(i.read(32)),c=e0(i.read(i.bin.length-i.pos)),l=t_.fromDER(c,"hex"),h=`2-message signing-${o}`;return a.deriveChild(r,h).verify(e,l)},r4="42421033",r6=(e,t,r)=>{let i=tq(32),n=e5(i),a=`2-message encryption-${n}`,s=t.deriveChild(r,a),o=r.deriveChild(t,a),c=new rt(s.deriveSharedSecret(o).encode(!0).slice(1)).encrypt(e),l=t.toPublicKey().encode(!0);return[...e1(r4,"hex"),...l,...r.encode(!0),...i,...c]},r5=(e,t)=>{let r=new tn(e),i=e0(r.read(4));if(i!==r4)throw Error(`Message version mismatch: Expected ${r4}, received ${i}`);let n=tL.fromString(e0(r.read(33))),a=e0(r.read(33)),s=t.toPublicKey().encode(!0,"hex");if(a!==s)throw Error(`The encrypted message expects a recipient public key of ${a}, but the provided key is ${s}`);let o=e5(r.read(32)),c=r.read(r.bin.length-r.pos),l=`2-message encryption-${o}`,h=n.deriveChild(t,l),u=t.deriveChild(n,l);return new rt(h.deriveSharedSecret(u).encode(!0).slice(1)).decrypt(c)},r7="Bitcoin Signed Message:\n",r9=e=>{let t=new ti;return t.writeVarIntNum(r7.length),t.write(e1(r7,"utf8")),t.writeVarIntNum(e.length),t.write(e),Q(t.toArray())},ie=(e,t,r="base64")=>{let i=r9(e),n=tU(new m(i),t,!0);if("raw"===r)return n;let a=new m(i),s=n.CalculateRecoveryFactor(t.toPublicKey(),a);return n.toCompact(s,!0,"base64")},it=(e,t,r)=>tF(new m(r9(e)),t,r);class ir{versionBytesNum;depth;parentFingerPrint;childIndex;chainCode;privKey;pubKey;constants={pubKey:0x488b21e,privKey:0x488ade4};constructor(e,t,r,i,n,a,s){this.versionBytesNum=e,this.depth=t,this.parentFingerPrint=r,this.childIndex=i,this.chainCode=n,this.privKey=a,this.pubKey=s}fromRandom(){return this.versionBytesNum=this.constants.privKey,this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=tq(32),this.privKey=tW.fromRandom(),this.pubKey=this.privKey.toPublicKey(),this}static fromRandom(){return new this().fromRandom()}static fromString(e){return new this().fromString(e)}fromString(e){let t=tr(e);return this.fromBinary([...t.prefix,...t.data])}static fromSeed(e){return new this().fromSeed(e)}fromSeed(e){if(e.length<16)throw Error("Need more than 128 bits of entropy");if(e.length>64)throw Error("More than 512 bits of entropy is nonstandard");let t=er(e1("Bitcoin seed","utf8"),e);return this.depth=0,this.parentFingerPrint=[0,0,0,0],this.childIndex=0,this.chainCode=t.slice(32,64),this.versionBytesNum=this.constants.privKey,this.privKey=new tW(t.slice(0,32)),this.pubKey=this.privKey.toPublicKey(),this}static fromBinary(e){return new this().fromBinary(e)}fromBinary(e){if(78!==e.length)throw Error("incorrect bip32 data length");let t=new tn(e);this.versionBytesNum=t.readUInt32BE(),this.depth=t.readUInt8(),this.parentFingerPrint=t.read(4),this.childIndex=t.readUInt32BE(),this.chainCode=t.read(32);let r=t.read(33),i=this.versionBytesNum===this.constants.privKey,n=this.versionBytesNum===this.constants.pubKey;if(i&&0===r[0])this.privKey=new tW(r.slice(1,33)),this.pubKey=this.privKey.toPublicKey();else if(n&&(2===r[0]||3===r[0]))this.pubKey=tL.fromString(e0(r));else throw Error("Invalid key");return this}toString(){return tt(this.toBinary(),[])}derive(e){if("m"===e)return this;let t=e.split("/"),r=this;for(let[e,i]of t.entries()){if(0===e){if("m"!==i)throw Error("invalid path");continue}if(parseInt(i.replace("'",""),10).toString()!==i.replace("'",""))throw Error("invalid path");let t=i.length>1&&"'"===i[i.length-1],n=0x7fffffff&parseInt(t?i.slice(0,i.length-1):i,10);t&&(n+=0x80000000),r=r.deriveChild(n)}return r}deriveChild(e){if("number"!=typeof e)throw Error("i must be a number");let t=[];t.push(e>>24&255),t.push(e>>16&255),t.push(e>>8&255),t.push(255&e);let r=[...t],i=(0x80000000&e)!=0,n=this.versionBytesNum===this.constants.privKey;if(i&&(null===this.privKey||void 0===this.privKey||!n))throw Error("Cannot do private key derivation without private key");let a=null;if(null!==this.privKey&&void 0!==this.privKey){let e=null;e=i?[0,...this.privKey.toArray("be",32),...r]:[...this.pubKey.encode(!0),...r];let t=er(this.chainCode,e),n=new m(t.slice(0,32)),s=t.slice(32,64),o=n.add(this.privKey).mod(new tA().n);(a=new ir).chainCode=s,a.privKey=new tW(o.toArray()),a.pubKey=a.privKey.toPublicKey()}else{let e=[...this.pubKey.encode(!0),...r],t=er(this.chainCode,e),i=new m(t.slice(0,32)),n=t.slice(32,64),s=new tA().g.mul(i),o=this.pubKey,c=s.add(o),l=new tL(c.x,c.y);(a=new ir).chainCode=n,a.pubKey=l}a.childIndex=e;let s=ee(this.pubKey.encode(!0));return a.parentFingerPrint=s.slice(0,4),a.versionBytesNum=this.versionBytesNum,a.depth=this.depth+1,a}toPublic(){let e=new ir(this.versionBytesNum,this.depth,this.parentFingerPrint,this.childIndex,this.chainCode,this.privKey,this.pubKey);return e.versionBytesNum=this.constants.pubKey,e.privKey=void 0,e}toBinary(){let e=this.versionBytesNum===this.constants.privKey,t=this.versionBytesNum===this.constants.pubKey;if(e)return new ti().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).writeUInt8(0).write(this.privKey.toArray("be",32)).toArray();if(t)return new ti().writeUInt32BE(this.versionBytesNum).writeUInt8(this.depth).write(this.parentFingerPrint).writeUInt32BE(this.childIndex).write(this.chainCode).write(this.pubKey.encode(!0)).toArray();throw Error("bip32: invalid versionBytesNum byte")}isPrivate(){return this.versionBytesNum===this.constants.privKey}}let ii={value:["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],space:" "};class ia{mnemonic;seed;Wordlist;constructor(e,t,r=ii){this.mnemonic=e??"",this.seed=t??[],this.Wordlist=r}toBinary(){let e=new ti;if(""!==this.mnemonic){let t=e1(this.mnemonic,"utf8");e.writeVarIntNum(t.length),e.write(t)}else e.writeVarIntNum(0);return this.seed.length>0?(e.writeVarIntNum(this.seed.length),e.write(this.seed)):e.writeVarIntNum(0),e.toArray()}fromBinary(e){let t=new tn(e),r=t.readVarIntNum();r>0&&(this.mnemonic=e6(t.read(r),"utf8"));let i=t.readVarIntNum();return i>0&&(this.seed=t.read(i)),this}fromRandom(e){if((null==e||isNaN(e)||0===e)&&(e=128),e%32!=0)throw Error("bits must be multiple of 32");if(e<128)throw Error("bits must be at least 128");let t=tq(e/8);return this.entropy2Mnemonic(t),this.mnemonic2Seed(),this}static fromRandom(e){return new this().fromRandom(e)}fromEntropy(e){return this.entropy2Mnemonic(e),this}static fromEntropy(e){return new this().fromEntropy(e)}fromString(e){return this.mnemonic=e,this}static fromString(e){return new this().fromString(e)}toString(){return this.mnemonic}toSeed(e){return this.mnemonic2Seed(e),this.seed}entropy2Mnemonic(e){if(e.length<16)throw Error("Entropy is less than 128 bits. It must be 128 bits or more.");let t=Y(e),r="",i=8*e.length;for(let t=0;t<e.length;t++)r+=("00000000"+e[t].toString(2)).slice(-8);let n=t[0].toString(2);if((r+=n=("00000000"+n).slice(-8).slice(0,i/32)).length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+r.length.toString());let a="";for(let e=0;e<r.length/11;e++){""!==a&&(a+=this.Wordlist.space);let t=parseInt(r.slice(11*e,(e+1)*11),2);a+=this.Wordlist.value[t]}return this.mnemonic=a,this}check(){let e=this.mnemonic.split(this.Wordlist.space),t="";for(let r=0;r<e.length;r++){let i=this.Wordlist.value.indexOf(e[r]);if(i<0)return!1;t+=("00000000000"+i.toString(2)).slice(-11)}if(t.length%11!=0)throw Error("internal error - entropy not an even multiple of 11 bits - "+t.length.toString());let r=t.length/33,i=t.slice(-r),n=t.slice(0,t.length-r),a=[];for(let e=0;e<n.length/8;e++)a.push(parseInt(t.slice(8*e,(e+1)*8),2));let s=Y(a.slice(0,n.length/8))[0].toString(2);return(s=("00000000"+s).slice(-8).slice(0,r))===i}mnemonic2Seed(e=""){let t=this.mnemonic;if(!this.check())throw Error("Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?");if("string"!=typeof e)throw Error("passphrase must be a string or undefined");t=t.normalize("NFKD"),e=e.normalize("NFKD");let r=e1(t,"utf8"),i=[...e1("mnemonic","utf8"),...e1(e,"utf8")];return this.seed=ez(r,i,2048,64,"sha512"),this}isValid(e=""){let t;try{this.mnemonic2Seed(e),t=!0}catch{t=!1}return t}static isValid(e,t=""){return new ia(e).isValid(t)}}function is(e){let t,r,i,n;0===this._tables[0][0][0]&&this._precompute();let a=this._tables[0][4],s=this._tables[1],o=e.length,c=1;if(4!==o&&6!==o&&8!==o)throw Error("invalid aes key size");for(this._key=[r=e.slice(0),i=[]],n=o;n<4*o+28;n++)t=r[n-1],(n%o==0||8===o&&n%o==4)&&(t=a[t>>>24]<<24^a[t>>16&255]<<16^a[t>>8&255]<<8^a[255&t],n%o==0&&(t=t<<8^t>>>24^c<<24,c=c<<1^(c>>7)*283)),r[n]=r[n-o]^t;for(let e=0;n>0;e++,n--)t=r[(3&e)!=0?n:n-4],n<=4||e<4?i[e]=t:i[e]=s[0][a[t>>>24]]^s[1][a[t>>16&255]]^s[2][a[t>>8&255]]^s[3][a[255&t]]}is.prototype={encrypt:function(e){return this._crypt(e,0)},decrypt:function(e){return this._crypt(e,1)},_tables:[[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)]],_precompute:function(){let e,t,r,i,n,a,s,o,c=this._tables[0],l=this._tables[1],h=c[4],u=l[4],d=new Uint8Array(256),f=new Uint8Array(256);for(e=0;e<256;e++)f[(d[e]=e<<1^(e>>7)*283)^e]=e;for(t=r=0;0===h[t];t^=0!==i?i:1,r=0!==f[r]?f[r]:1)for(e=0,a=(a=r^r<<1^r<<2^r<<3^r<<4)>>8^255&a^99,h[t]=a,u[a]=t,o=0x1010101*d[n=d[i=d[t]]]^65537*n^257*i^0x1010100*t,s=257*d[a]^0x1010100*a;e<4;e++)c[e][t]=s=s<<24^s>>>8,l[e][a]=o=o<<24^o>>>8},_crypt:function(e,t){let r,i,n,a;if(4!==e.length)throw Error("invalid aes block size");let s=this._key[t],o=e[0]^s[0],c=e[1===t?3:1]^s[1],l=e[2]^s[2],h=e[1===t?1:3]^s[3],u=s.length/4-2,d=4,f=new Uint32Array(4),p=this._tables[t],g=p[0],b=p[1],y=p[2],m=p[3],w=p[4];for(a=0;a<u;a++)r=g[o>>>24]^b[c>>16&255]^y[l>>8&255]^m[255&h]^s[d],i=g[c>>>24]^b[l>>16&255]^y[h>>8&255]^m[255&o]^s[d+1],n=g[l>>>24]^b[h>>16&255]^y[o>>8&255]^m[255&c]^s[d+2],h=g[h>>>24]^b[o>>16&255]^y[c>>8&255]^m[255&l]^s[d+3],d+=4,o=r,c=i,l=n;for(a=0;a<4;a++)f[1===t?3&-a:a]=w[o>>>24]<<24^w[c>>16&255]<<16^w[l>>8&255]<<8^w[255&h]^s[d++],r=o,o=c,c=l,l=h,h=r;return f}};class io{static encrypt(e,t){let r=io.buf2Words(t),i=io.buf2Words(e),n=new is(r).encrypt(i);return io.words2Buf(n)}static decrypt(e,t){let r=io.buf2Words(e),i=new is(io.buf2Words(t)).decrypt(r);return io.words2Buf(i)}static buf2Words(e){if(e.length%4!=0)throw Error("buf length must be a multiple of 4");let t=[];for(let r=0;r<e.length/4;r++){let i=0x1000000*e[4*r]+(e[4*r+1]<<16|e[4*r+2]<<8|e[4*r+3]);t.push(i)}return t}static words2Buf(e){let t=Array(4*e.length);for(let r=0;r<e.length;r++){let i=e[r];t[4*r]=i>>>24&255,t[4*r+1]=i>>>16&255,t[4*r+2]=i>>>8&255,t[4*r+3]=255&i}return t}}class ic{static buf2BlocksBuf(e,t){let r=t/8,i=[];for(let n=0;n<=e.length/r;n++){let a=e.slice(n*r,n*r+r);a.length<t&&(a=ic.pkcs7Pad(a,t)),i.push(a)}return i}static blockBufs2Buf(e){let t=e[e.length-1];return t=ic.pkcs7Unpad(t),e[e.length-1]=t,e.flat()}static encrypt(e,t,r,i){let n=8*t.length,a=ic.buf2BlocksBuf(e,n);return ic.encryptBlocks(a,t,r,i).flat()}static decrypt(e,t,r,i){let n=t.length,a=[];for(let t=0;t<e.length/n;t++)a.push(e.slice(t*n,t*n+n));let s=ic.decryptBlocks(a,t,r,i);return ic.blockBufs2Buf(s)}static encryptBlock(e,t,r,i){let n=ic.xorBufs(e,t);return r.encrypt(n,i)}static decryptBlock(e,t,r,i){let n=r.decrypt(e,i);return ic.xorBufs(n,t)}static encryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=ic.encryptBlock(s,t,r,i);n.push(o),t=o}return n}static decryptBlocks(e,t,r,i){let n=[];for(let a=0;a<e.length;a++){let s=e[a],o=ic.decryptBlock(s,t,r,i);n.push(o),t=s}return n}static pkcs7Pad(e,t){let r=t/8-e.length,i=Array(r);return i.fill(r),[...e,...i]}static pkcs7Unpad(e){let t=e[e.length-1],r=e.slice(e.length-t,e.length),i=Array(t);if(i.fill(t),e0(r)!==e0(i))throw Error("invalid padding");return e.slice(0,e.length-t)}static xorBufs(e,t){if(e.length!==t.length)throw Error("bufs must have the same length");let r=Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}}class il{static encrypt(e,t,r,i=!0){r=r??tq(16);let n=ic.encrypt(e,r,io,t);return i?[...r,...n]:[...n]}static decrypt(e,t,r){if(null!=r)return ic.decrypt(e,r,io,t);{r=e.slice(0,16);let i=e.slice(16);return ic.decrypt(i,r,io,t)}}}class ih{static ivkEkM(e,t){let r=t.mul(e),i=Z(new tL(r.x,r.y).encode(!0));return{iv:i.slice(0,16),kE:i.slice(16,32),kM:i.slice(32,64)}}static electrumEncrypt(e,t,r,i=!1){let n,a=null;null==r&&(r=tW.fromRandom()),i||(a=r.toPublicKey().encode(!0));let{iv:s,kE:o,kM:c}=ih.ivkEkM(r,t),l=il.encrypt(e,o,s,!1),h=e1("BIE1","utf8"),u=et(c,n=null!=a&&a.length>0?[...h,...a,...l]:[...h,...l]);return[...n,...u]}static electrumDecrypt(e,t,r){if("BIE1"!==e6(e.slice(0,4),"utf8"))throw Error("Invalid Magic");let i=4,n=null;if(e.length-i-32>=33){let t=e[i];2===t||3===t?(n=e.slice(i,i+33),i+=33):4===t&&(n=e.slice(i,i+65),i+=65)}if(null!==n)null==r&&(r=tL.fromString(e0(n)));else if(null==r)throw Error("Sender public key is required");let{iv:a,kE:s,kM:o}=ih.ivkEkM(t,r),c=e.slice(i,e.length-32),l=e.slice(e.length-32,e.length),h=et(o,e.slice(0,e.length-32));if(e0(l)!==e0(h))throw Error("Invalid checksum");return il.decrypt(c,s,a)}static bitcoreEncrypt(e,t,r,i){null==r&&(r=tW.fromRandom()),null==i&&(i=tq(16));let n=r,a=r.toPublicKey().encode(!0),s=Z(t.mul(n).getX().toArray("be",32)),o=s.slice(0,32),c=s.slice(32,64),l=il.encrypt(e,o,i),h=et(c,[...l]);return[...a,...l,...h]}static bitcoreDecrypt(e,t){let r=tL.fromString(e0(e.slice(0,33))).mul(t);if(r.eq(new tO(0,0)))throw Error("P equals 0");let i=Z(r.getX().toArray("be",32)),n=i.slice(0,32),a=i.slice(32,64),s=e.slice(33,e.length-32),o=e.slice(e.length-32,e.length),c=et(a,s);if(e0(o)!==e0(c))throw Error("Invalid checksum");return[...il.decrypt(s,n)]}}function iu(e,t){let r=new rW(0,[],[],0);return r.outputs=Array(e.vout+1).fill(null),r.outputs[e.vout]={satoshis:e.satoshis,lockingScript:ry.fromHex(e.script)},{sourceTransaction:r,sourceTXID:e.txid,sourceOutputIndex:e.vout,unlockingScriptTemplate:t,sequence:0xffffffff}}class id{static generate(e,t){let r=this.withDefaultOptions(t);return ip(e,this.getCounter(r.timestamp,r.period),r)}static validate(e,t,r){let i=this.withDefaultValidateOptions(r);if((t=t.trim()).length!==i.digits)return!1;let n=this.getCounter(i.timestamp,i.period),a=[n];for(let e=1;e<=i.skew;e++)a.push(n+e),a.push(n-e);for(let r of a){let n=ip(e,r,i);if(tl(e1(t,"utf8"),e1(n,"utf8")))return!0}return!1}static getCounter(e,t){return Math.floor(Math.floor(e/1e3)/t)}static withDefaultOptions(e){return{digits:2,algorithm:"SHA-1",period:30,timestamp:Date.now(),...e}}static withDefaultValidateOptions(e){return{skew:1,...this.withDefaultOptions(e)}}}function ip(e,t,r){let i=(function(e,t,r){switch(r){case"SHA-1":return new j(e).update(t);case"SHA-256":return new W(e).update(t);case"SHA-512":return new G(e).update(t);default:throw Error("unsupported HMAC algorithm")}})(e,new m(t).toArray("be",8),r.algorithm).digest(),n=15&i[i.length-1];return(0x7fffffff&new m(i.slice(n,n+4)).toNumber()).toString().slice(-r.digits)}!function(e){e[e.Silent=0]="Silent",e[e.App=1]="App",e[e.Counterparty=2]="Counterparty"}(r||(r={}));class ig{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,r){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=r,this.anyone=new tW(1).toPublicKey(),"anyone"===e?this.rootKey=new tW(1):this.rootKey=e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,r,i=!1){return(r=this.normalizeCounterparty(r),i)?this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():r.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,r){return r=this.normalizeCounterparty(r),this.rootKey.deriveChild(r,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}deriveSymmetricKey(e,t,r){r="anyone"===r?this.anyone:this.normalizeCounterparty(r);let i=this.derivePublicKey(e,t,r),n=this.derivePrivateKey(e,t,r);return new rt(n.deriveSharedSecret(i)?.x?.toArray()??[])}revealCounterpartySecret(e){if("self"===e)throw Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);let t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,r){e=this.normalizeCounterparty(e);let i=this.rootKey.deriveSharedSecret(e),n=e1(this.computeInvoiceNumber(t,r),"utf8");return et(i.encode(!0),n)}normalizeCounterparty(e){if(null==e)throw Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new tW(1).toPublicKey():"string"==typeof e?tL.fromString(e):e}computeInvoiceNumber(e,t){let r=e[0];if(!Number.isInteger(r)||r<0||r>2)throw Error("Protocol security level must be 0, 1, or 2");let i=e[1].toLowerCase().trim();if(t.length>800)throw Error("Key IDs must be 800 characters or less");if(t.length<1)throw Error("Key IDs must be 1 character or more");if(i.length>400)if(i.startsWith("specific linkage revelation ")){if(i.length>430)throw Error("Specific linkage revelation protocol names must be 430 characters or less")}else throw Error("Protocol names must be 400 characters or less");if(i.length<5)throw Error("Protocol names must be 5 characters or more");if(i.includes(" "))throw Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(i))throw Error("Protocol names can only contain letters, numbers and spaces");if(i.endsWith(" protocol"))throw Error('No need to end your protocol name with " protocol"');return`${r}-${i}-${t}`}}class ib{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){"anyone"===e?this.rootKey=new tW(1):this.rootKey=e,this.keyDeriver=new ig(this.rootKey,(e,t,r)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,r)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;let r=t?.maxCacheSize;this.maxCacheSize=null!=r&&!isNaN(r)&&r>0?r:1e3}derivePublicKey(e,t,r,i=!1){let n=this.generateCacheKey("derivePublicKey",e,t,r,i);if(this.cache.has(n)){let e=this.cacheGet(n);if(void 0===e)throw Error("Cached value is undefined");return e}{let a=this.keyDeriver.derivePublicKey(e,t,r,i);return this.cacheSet(n,a),a}}derivePrivateKey(e,t,r){let i=this.generateCacheKey("derivePrivateKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.derivePrivateKey(e,t,r);return this.cacheSet(i,n),n}}deriveSymmetricKey(e,t,r){let i=this.generateCacheKey("deriveSymmetricKey",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.deriveSymmetricKey(e,t,r);return this.cacheSet(i,n),n}}revealCounterpartySecret(e){let t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){let e=this.cacheGet(t);if(void 0===e)throw Error("Cached value is undefined");return e}{let r=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,r),r}}revealSpecificSecret(e,t,r){let i=this.generateCacheKey("revealSpecificSecret",e,t,r);if(this.cache.has(i)){let e=this.cacheGet(i);if(void 0===e)throw Error("Cached value is undefined");return e}{let n=this.keyDeriver.revealSpecificSecret(e,t,r);return this.cacheSet(i,n),n}}generateCacheKey(e,...t){let r=t.map(e=>this.serializeArgument(e)).join("|");return`${e}|${r}`}serializeArgument(e){return e instanceof tL||e instanceof tW?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){let t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){let e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}class iy{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new ib(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf).toString()}}async revealCounterpartyKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealCounterpartySecret(e.counterparty),i=new rn().generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),tL.fromString(e.counterparty),tO.fromDER(r)),n=[...i.R.encode(!0),...i.SPrime.encode(!0),...i.z.toArray()],a=new Date().toISOString(),{ciphertext:s}=await this.encrypt({plaintext:r,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:a,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:a,encryptedLinkage:s,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){let{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let r=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:i}=await this.encrypt({plaintext:r,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:n}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:i,encryptedLinkageProof:n,proofType:0}}async encrypt(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{ciphertext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").encrypt(e.plaintext)}}async decrypt(e,t){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{plaintext:this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").decrypt(e.ciphertext)}}async createHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");return{hmac:et(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data)}}async verifyHmac(e){if(null==this.keyDeriver)throw Error("keyDeriver is undefined");let t=et(this.keyDeriver.deriveSymmetricKey(e.protocolID,e.keyID,e.counterparty??"self").toArray(),e.data),r=e.hmac,i=tl(e1(t),e1(r));if(!i){let e=Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:i}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw Error("args.data or args.hashToDirectlySign must be valid");let t=e.hashToDirectlySign??Y(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePrivateKey(e.protocolID,e.keyID,e.counterparty??"anyone");return{signature:tU(new m(t),r,!0).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw Error("args.data or args.hashToDirectlyVerify must be valid");let t=e.hashToDirectlyVerify??Y(e.data??[]),r=(this.keyDeriver??(()=>{throw Error("keyDeriver is undefined")})()).derivePublicKey(e.protocolID,e.keyID,e.counterparty??"self",e.forSelf),i=tF(new m(t),t_.fromDER(e.signature),r);if(!i){let e=Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:i}}}let im=iy;class iw{CWI;constructor(){if("object"!=typeof window)throw Error("The window.CWI substrate requires a global window object.");if("object"!=typeof window.CWI)throw Error("The window.CWI interface does not appear to be bound to the window object.");this.CWI=window.CWI}async createAction(e,t){return await this.CWI.createAction(e,t)}async signAction(e,t){return await this.CWI.signAction(e,t)}async abortAction(e,t){return await this.CWI.abortAction(e,t)}async listActions(e,t){return await this.CWI.listActions(e,t)}async internalizeAction(e,t){return await this.CWI.internalizeAction(e,t)}async listOutputs(e,t){return await this.CWI.listOutputs(e,t)}async relinquishOutput(e,t){return await this.CWI.relinquishOutput(e,t)}async getPublicKey(e,t){return await this.CWI.getPublicKey(e,t)}async revealCounterpartyKeyLinkage(e,t){return await this.CWI.revealCounterpartyKeyLinkage(e,t)}async revealSpecificKeyLinkage(e,t){return await this.CWI.revealSpecificKeyLinkage(e,t)}async encrypt(e,t){return await this.CWI.encrypt(e,t)}async decrypt(e,t){return await this.CWI.decrypt(e,t)}async createHmac(e,t){return await this.CWI.createHmac(e,t)}async verifyHmac(e,t){return await this.CWI.verifyHmac(e,t)}async createSignature(e,t){return await this.CWI.createSignature(e,t)}async verifySignature(e,t){return await this.CWI.verifySignature(e,t)}async acquireCertificate(e,t){return await this.CWI.acquireCertificate(e,t)}async listCertificates(e,t){return await this.CWI.listCertificates(e,t)}async proveCertificate(e,t){return await this.CWI.proveCertificate(e,t)}async relinquishCertificate(e,t){return await this.CWI.relinquishCertificate(e,t)}async discoverByIdentityKey(e,t){return await this.CWI.discoverByIdentityKey(e,t)}async discoverByAttributes(e,t){return await this.CWI.discoverByAttributes(e,t)}async isAuthenticated(e,t){return await this.CWI.isAuthenticated(e,t)}async waitForAuthentication(e,t){return await this.CWI.waitForAuthentication(e,t)}async getHeight(e,t){return await this.CWI.getHeight(e,t)}async getHeaderForHeight(e,t){return await this.CWI.getHeaderForHeight(e,t)}async getNetwork(e,t){return await this.CWI.getNetwork(e,t)}async getVersion(e,t){return await this.CWI.getVersion(e,t)}}class iv extends Error{code;isError=!0;constructor(e,t=1,r){super(e),this.code=t,this.name=this.constructor.name,null!=r&&""!==r?this.stack=r:Error.captureStackTrace(this,this.constructor)}static unknownToJson(e){let t;return!0===e.isError&&String(e.name).startsWith("WERR_")?"WERR_REVIEW_ACTIONS"===(t={name:e.name,message:e.message,isError:!0}).name?(t.reviewActionResults=e.reviewActionResults,t.sendWithResults=e.sendWithResults,t.txid=e.txid,t.tx=e.tx,t.noSendChange=e.noSendChange,t.code=5):"WERR_INVALID_PARAMETER"===t.name?(t.parameter=e.parameter,t.code=6):"WERR_INSUFFICIENT_FUNDS"===t.name&&(t.totalSatoshisNeeded=e.totalSatoshisNeeded,t.moreSatoshisNeeded=e.moreSatoshisNeeded,t.code=7):t=e instanceof Error?{name:e.constructor.name,message:e.message,isError:!0}:{name:"WERR_UNKNOWN",message:String(e),isError:!0},JSON.stringify(t)}}!function(e){e[e.unknownError=1]="unknownError",e[e.unsupportedAction=2]="unsupportedAction",e[e.invalidHmac=3]="invalidHmac",e[e.invalidSignature=4]="invalidSignature",e[e.reviewActions=5]="reviewActions",e[e.invalidParameter=6]="invalidParameter",e[e.insufficientFunds=7]="insufficientFunds"}(i||(i={}));let iI=iv;class ik{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if("function"!=typeof window.postMessage)throw Error("The window object does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((r,i)=>{let n=e5(tq(12)),a=e=>{"CWI"===e.data.type&&e.isTrusted&&e.data.id===n&&!0!==e.data.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===e.data.status?i(new iv(e.data.description,e.data.code)):r(e.data.result))};window.addEventListener("message",a),window.parent.postMessage({type:"CWI",isInvocation:!0,id:n,call:e,args:t},this.domain)})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}class iS{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,r,i,n,a,s){this.type=e,this.serialNumber=t,this.subject=r,this.certifier=i,this.revocationOutpoint=n,this.fields=a,this.signature=s}toBinary(e=!0){let t=new ti,r=e1(this.type,"base64");t.write(r);let i=e1(this.serialNumber,"base64");t.write(i);let n=e1(this.subject,"hex");t.write(n);let a=e1(this.certifier,"hex");t.write(a);let[s,o]=this.revocationOutpoint.split("."),c=e1(s,"hex");t.write(c),t.writeVarIntNum(Number(o));let l=Object.keys(this.fields).sort();for(let e of(t.writeVarIntNum(l.length),l)){let r=this.fields[e],i=e1(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e1(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}if(e&&(this.signature??"").length>0){let e=e1(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){let t,r=new tn(e),i=e5(r.read(32)),n=e5(r.read(32)),a=e0(r.read(33)),s=e0(r.read(33)),o=e0(r.read(32)),c=r.readVarIntNum(),l=`${o}.${c}`,h=r.readVarIntNum(),u={};for(let e=0;e<h;e++){let e=r.readVarIntNum(),t=e4(r.read(e)),i=r.readVarIntNum(),n=e4(r.read(i));u[t]=n}if(!r.eof()){let e=r.read();t=t_.fromDER(e).toString("hex")}return new iS(i,n,a,s,l,u,t)}async verify(){let e=new im("anyone"),t=this.toBinary(!1),r=this.signature??"",{valid:i}=await e.verifySignature({signature:e1(r,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return i}async sign(e){if(null!=this.signature&&this.signature.length>0)throw Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;let t=this.toBinary(!1),{signature:r}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=e0(r)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new iS(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}!function(e){e[e.createAction=1]="createAction",e[e.signAction=2]="signAction",e[e.abortAction=3]="abortAction",e[e.listActions=4]="listActions",e[e.internalizeAction=5]="internalizeAction",e[e.listOutputs=6]="listOutputs",e[e.relinquishOutput=7]="relinquishOutput",e[e.getPublicKey=8]="getPublicKey",e[e.revealCounterpartyKeyLinkage=9]="revealCounterpartyKeyLinkage",e[e.revealSpecificKeyLinkage=10]="revealSpecificKeyLinkage",e[e.encrypt=11]="encrypt",e[e.decrypt=12]="decrypt",e[e.createHmac=13]="createHmac",e[e.verifyHmac=14]="verifyHmac",e[e.createSignature=15]="createSignature",e[e.verifySignature=16]="verifySignature",e[e.acquireCertificate=17]="acquireCertificate",e[e.listCertificates=18]="listCertificates",e[e.proveCertificate=19]="proveCertificate",e[e.relinquishCertificate=20]="relinquishCertificate",e[e.discoverByIdentityKey=21]="discoverByIdentityKey",e[e.discoverByAttributes=22]="discoverByAttributes",e[e.isAuthenticated=23]="isAuthenticated",e[e.waitForAuthentication=24]="waitForAuthentication",e[e.getHeight=25]="getHeight",e[e.getHeaderForHeight=26]="getHeaderForHeight",e[e.getNetwork=27]="getNetwork",e[e.getVersion=28]="getVersion"}(n||(n={}));let ix=n;class iE{wire;constructor(e){this.wire=e}async transmit(e,t="",r=[]){let i=new ti;i.writeUInt8(ix[e]);let n=e1(t,"utf8");i.writeUInt8(n.length),i.write(n),r.length>0&&i.write(r);let a=i.toArray(),s=new tn(await this.wire.transmitToWallet(a)),o=s.readUInt8();if(0===o)return s.read();{let e=s.readVarIntNum(),t=e4(s.read(e)),r=s.readVarIntNum();throw new iv(t,o,e4(s.read(r)))}}async createAction(e,t){let r=new ti,i=e1(e.description,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=e.inputBEEF?(r.writeVarIntNum(e.inputBEEF.length),r.write(e.inputBEEF)):r.writeVarIntNum(-1),null!=e.inputs)for(let t of(r.writeVarIntNum(e.inputs.length),e.inputs)){if(r.write(this.encodeOutpoint(t.outpoint)),null!=t.unlockingScript&&""!==t.unlockingScript){let e=e1(t.unlockingScript,"hex");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1),r.writeVarIntNum(t.unlockingScriptLength??0);let e=e1(t.inputDescription,"utf8");r.writeVarIntNum(e.length),r.write(e),"number"==typeof t.sequenceNumber?r.writeVarIntNum(t.sequenceNumber):r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if(null!=e.outputs)for(let t of(r.writeVarIntNum(e.outputs.length),e.outputs)){let e=e1(t.lockingScript,"hex");r.writeVarIntNum(e.length),r.write(e),r.writeVarIntNum(t.satoshis);let i=e1(t.outputDescription,"utf8");if(r.writeVarIntNum(i.length),r.write(i),null!=t.basket&&""!==t.basket){let e=e1(t.basket,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.customInstructions&&""!==t.customInstructions){let e=e1(t.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=t.tags)for(let e of(r.writeVarIntNum(t.tags.length),t.tags)){let t=e1(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(-1)}else r.writeVarIntNum(-1);if("number"==typeof e.lockTime?r.writeVarIntNum(e.lockTime):r.writeVarIntNum(-1),"number"==typeof e.version?r.writeVarIntNum(e.version):r.writeVarIntNum(-1),null!=e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e1(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if(null!=e.options){if(r.writeInt8(1),"boolean"==typeof e.options.signAndProcess?r.writeInt8(+!!e.options.signAndProcess):r.writeInt8(-1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"known"===e.options.trustSelf?r.writeInt8(1):r.writeInt8(-1),null!=e.options.knownTxids)for(let t of(r.writeVarIntNum(e.options.knownTxids.length),e.options.knownTxids)){let e=e1(t,"hex");r.write(e)}else r.writeVarIntNum(-1);if("boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.noSendChange)for(let t of(r.writeVarIntNum(e.options.noSendChange.length),e.options.noSendChange))r.write(this.encodeOutpoint(t));else r.writeVarIntNum(-1);if(null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=e1(t,"hex");r.write(e)}else r.writeVarIntNum(-1);"boolean"==typeof e.options.randomizeOutputs?r.writeInt8(+!!e.options.randomizeOutputs):r.writeInt8(-1)}else r.writeInt8(0);let n=new tn(await this.transmit("createAction",t,r.toArray())),a={};if(1===n.readInt8()&&(a.txid=e0(n.read(32))),1===n.readInt8()){let e=n.readVarIntNum();a.tx=n.read(e)}let s=n.readVarIntNum();if(s>=0){a.noSendChange=[];for(let e=0;e<s;e++){let e=this.readOutpoint(n);a.noSendChange.push(e)}}let o=n.readVarIntNum();if(o>=0){a.sendWithResults=[];for(let e=0;e<o;e++){let e=e0(n.read(32)),t=n.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),a.sendWithResults.push({txid:e,status:r})}}if(1===n.readInt8()){let e=n.readVarIntNum(),t=n.read(e),r=n.readVarIntNum();a.signableTransaction={tx:t,reference:e5(n.read(r))}}return a}async signAction(e,t){let r=new ti,i=Object.keys(e.spends);for(let t of(r.writeVarIntNum(i.length),i)){r.writeVarIntNum(Number(t));let i=e.spends[Number(t)],n=e1(i.unlockingScript,"hex");r.writeVarIntNum(n.length),r.write(n),"number"==typeof i.sequenceNumber?r.writeVarIntNum(i.sequenceNumber):r.writeVarIntNum(-1)}let n=e1(e.reference,"base64");if(r.writeVarIntNum(n.length),r.write(n),null!=e.options)if(r.writeInt8(1),"boolean"==typeof e.options.acceptDelayedBroadcast?r.writeInt8(+!!e.options.acceptDelayedBroadcast):r.writeInt8(-1),"boolean"==typeof e.options.returnTXIDOnly?r.writeInt8(+!!e.options.returnTXIDOnly):r.writeInt8(-1),"boolean"==typeof e.options.noSend?r.writeInt8(+!!e.options.noSend):r.writeInt8(-1),null!=e.options.sendWith)for(let t of(r.writeVarIntNum(e.options.sendWith.length),e.options.sendWith)){let e=e1(t,"hex");r.write(e)}else r.writeVarIntNum(-1);else r.writeInt8(0);let a=new tn(await this.transmit("signAction",t,r.toArray())),s={};if(1===a.readInt8()&&(s.txid=e0(a.read(32))),1===a.readInt8()){let e=a.readVarIntNum();s.tx=a.read(e)}let o=a.readVarIntNum();if(o>=0){s.sendWithResults=[];for(let e=0;e<o;e++){let e=e0(a.read(32)),t=a.readInt8(),r="unproven";1===t?r="unproven":2===t?r="sending":3===t&&(r="failed"),s.sendWithResults.push({txid:e,status:r})}}return s}async abortAction(e,t){return await this.transmit("abortAction",t,e1(e.reference,"base64")),{aborted:!0}}async listActions(e,t){let r=new ti;for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e1(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}for(let t of("any"===e.labelQueryMode?r.writeInt8(1):"all"===e.labelQueryMode?r.writeInt8(2):r.writeInt8(-1),[e.includeLabels,e.includeInputs,e.includeInputSourceLockingScripts,e.includeInputUnlockingScripts,e.includeOutputs,e.includeOutputLockingScripts]))"boolean"==typeof t?r.writeInt8(+!!t):r.writeInt8(-1);"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=new tn(await this.transmit("listActions",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=e0(i.read(32)),r=i.readVarIntNum(),n=i.readInt8();switch(n){case 1:e="completed";break;case 2:e="unprocessed";break;case 3:e="sending";break;case 4:e="unproven";break;case 5:e="unsigned";break;case 6:e="nosend";break;case 7:e="nonfinal";break;case 8:e="failed";break;default:throw Error(`Unknown status code: ${n}`)}let s=1===i.readInt8(),o=i.readVarIntNum(),c={txid:t,satoshis:r,status:e,isOutgoing:s,description:e4(i.read(o)),version:0,lockTime:0},l=i.readVarIntNum();if(l>=0){c.labels=[];for(let e=0;e<l;e++){let e=i.readVarIntNum(),t=i.read(e);c.labels.push(e4(t))}}c.version=i.readVarIntNum(),c.lockTime=i.readVarIntNum();let h=i.readVarIntNum();if(h>=0){c.inputs=[];for(let e=0;e<h;e++){let e,t,r=this.readOutpoint(i),n=i.readVarIntNum(),a=i.readVarIntNum();a>=0&&(e=e0(i.read(a)));let s=i.readVarIntNum();s>=0&&(t=e0(i.read(s)));let o=i.readVarIntNum(),l=e4(i.read(o)),h=i.readVarIntNum();c.inputs.push({sourceOutpoint:r,sourceSatoshis:n,sourceLockingScript:e,unlockingScript:t,inputDescription:l,sequenceNumber:h})}}let u=i.readVarIntNum();if(u>=0){c.outputs=[];for(let e=0;e<u;e++){let e,t,r,n=i.readVarIntNum(),a=i.readVarIntNum(),s=i.readVarIntNum();s>=0&&(e=e0(i.read(s)));let o=1===i.readInt8(),l=i.readVarIntNum(),h=e4(i.read(l)),u=i.readVarIntNum();u>=0&&(t=e4(i.read(u)));let d=i.readVarIntNum(),f=[];if(d>=0)for(let e=0;e<d;e++){let e=i.readVarIntNum(),t=i.read(e);f.push(e4(t))}let p=i.readVarIntNum();p>=0&&(r=e4(i.read(p))),c.outputs.push({outputIndex:n,satoshis:a,lockingScript:e,spendable:o,outputDescription:h,basket:t,tags:f,customInstructions:r})}}a.push(c)}return{totalActions:n,actions:a}}async internalizeAction(e,t){let r=new ti;for(let t of(r.writeVarIntNum(e.tx.length),r.write(e.tx),r.writeVarIntNum(e.outputs.length),e.outputs))if(r.writeVarIntNum(t.outputIndex),"wallet payment"===t.protocol){if(null==t.paymentRemittance)throw Error("Payment remittance is required for wallet payment");r.writeUInt8(1),r.write(e1(t.paymentRemittance.senderIdentityKey,"hex"));let e=e1(t.paymentRemittance.derivationPrefix,"base64");r.writeVarIntNum(e.length),r.write(e);let i=e1(t.paymentRemittance.derivationSuffix,"base64");r.writeVarIntNum(i.length),r.write(i)}else{r.writeUInt8(2);let e=e1(t.insertionRemittance?.basket,"utf8");if(r.writeVarIntNum(e.length),r.write(e),"string"==typeof t.insertionRemittance?.customInstructions&&""!==t.insertionRemittance.customInstructions){let e=e1(t.insertionRemittance.customInstructions,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);if("object"==typeof t.insertionRemittance?.tags)for(let e of(r.writeVarIntNum(t.insertionRemittance.tags.length),t.insertionRemittance.tags)){let t=e1(e,"utf8");r.writeVarIntNum(t.length),r.write(t)}else r.writeVarIntNum(0)}if("object"==typeof e.labels)for(let t of(r.writeVarIntNum(e.labels.length),e.labels)){let e=e1(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}else r.writeVarIntNum(-1);let i=e1(e.description);return r.writeVarIntNum(i.length),r.write(i),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("internalizeAction",t,r.toArray()),{accepted:!0}}async listOutputs(e,t){let r,i=new ti,n=e1(e.basket,"utf8");if(i.writeVarIntNum(n.length),i.write(n),"object"==typeof e.tags)for(let t of(i.writeVarIntNum(e.tags.length),e.tags)){let e=e1(t,"utf8");i.writeVarIntNum(e.length),i.write(e)}else i.writeVarIntNum(0);"all"===e.tagQueryMode?i.writeInt8(1):"any"===e.tagQueryMode?i.writeInt8(2):i.writeInt8(-1),"locking scripts"===e.include?i.writeInt8(1):"entire transactions"===e.include?i.writeInt8(2):i.writeInt8(-1),"boolean"==typeof e.includeCustomInstructions?i.writeInt8(+!!e.includeCustomInstructions):i.writeInt8(-1),"boolean"==typeof e.includeTags?i.writeInt8(+!!e.includeTags):i.writeInt8(-1),"boolean"==typeof e.includeLabels?i.writeInt8(+!!e.includeLabels):i.writeInt8(-1),"number"==typeof e.limit?i.writeVarIntNum(e.limit):i.writeVarIntNum(-1),"number"==typeof e.offset?i.writeVarIntNum(e.offset):i.writeVarIntNum(-1),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let a=new tn(await this.transmit("listOutputs",t,i.toArray())),s=a.readVarIntNum(),o=a.readVarIntNum();o>=0&&(r=a.read(o));let c=[];for(let e=0;e<s;e++){let e={spendable:!0,outpoint:this.readOutpoint(a),satoshis:a.readVarIntNum()},t=a.readVarIntNum();t>=0&&(e.lockingScript=e0(a.read(t)));let r=a.readVarIntNum();r>=0&&(e.customInstructions=e4(a.read(r)));let i=a.readVarIntNum();if(-1!==i){let t=[];for(let e=0;e<i;e++){let e=a.readVarIntNum();t.push(e4(a.read(e)))}e.tags=t}let n=a.readVarIntNum();if(-1!==n){let t=[];for(let e=0;e<n;e++){let e=a.readVarIntNum();t.push(e4(a.read(e)))}e.labels=t}c.push(e)}return{totalOutputs:s,BEEF:r,outputs:c}}async relinquishOutput(e,t){let r=new ti,i=e1(e.basket,"utf8");return r.writeVarIntNum(i.length),r.write(i),r.write(this.encodeOutpoint(e.output)),await this.transmit("relinquishOutput",t,r.toArray()),{relinquished:!0}}encodeOutpoint(e){let t=new ti,[r,i]=e.split(".");return t.write(e1(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}readOutpoint(e){let t=e0(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}async getPublicKey(e,t){let i=new ti;return i.writeUInt8(+!!e.identityKey),e.identityKey?i.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)):(i.write(this.encodeKeyRelatedParams(e.protocolID??=[r.Silent,"default"],e.keyID??="",e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?i.writeInt8(+!!e.forSelf):i.writeInt8(-1)),i.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{publicKey:e0(await this.transmit("getPublicKey",t,i.toArray()))}}async revealCounterpartyKeyLinkage(e,t){let r=new ti;r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.write(e1(e.counterparty,"hex")),r.write(e1(e.verifier,"hex"));let i=new tn(await this.transmit("revealCounterpartyKeyLinkage",t,r.toArray())),n=e0(i.read(33)),a=e0(i.read(33)),s=e0(i.read(33)),o=i.readVarIntNum(),c=e4(i.read(o)),l=i.readVarIntNum(),h=i.read(l),u=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,revelationTime:c,encryptedLinkage:h,encryptedLinkageProof:i.read(u)}}async revealSpecificKeyLinkage(e,t){let r=new ti;r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e1(e.verifier,"hex"));let i=new tn(await this.transmit("revealSpecificKeyLinkage",t,r.toArray())),n=e0(i.read(33)),a=e0(i.read(33)),s=e0(i.read(33)),o=i.readUInt8(),c=i.readVarIntNum(),l=e4(i.read(c)),h=i.readVarIntNum(),u=e4(i.read(h)),d=i.readVarIntNum(),f=i.read(d),p=i.readVarIntNum();return{prover:n,verifier:a,counterparty:s,protocolID:[o,l],keyID:u,encryptedLinkage:f,encryptedLinkageProof:i.read(p),proofType:i.readUInt8()}}async encrypt(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.plaintext.length),r.write(e.plaintext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{ciphertext:await this.transmit("encrypt",t,r.toArray())}}async decrypt(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.ciphertext.length),r.write(e.ciphertext),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{plaintext:await this.transmit("decrypt",t,r.toArray())}}async createHmac(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{hmac:await this.transmit("createHmac",t,r.toArray())}}async verifyHmac(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),r.write(e.hmac),r.writeVarIntNum(e.data.length),r.write(e.data),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifyHmac",t,r.toArray()),{valid:!0}}async createSignature(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlySign??=[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),{signature:await this.transmit("createSignature",t,r.toArray())}}async verifySignature(e,t){let r=new ti;return r.write(this.encodeKeyRelatedParams(e.protocolID,e.keyID,e.counterparty,e.privileged,e.privilegedReason)),"boolean"==typeof e.forSelf?r.writeInt8(+!!e.forSelf):r.writeInt8(-1),r.writeVarIntNum(e.signature.length),r.write(e.signature),"object"==typeof e.data?(r.writeUInt8(1),r.writeVarIntNum(e.data.length),r.write(e.data)):(r.writeUInt8(2),r.write(e.hashToDirectlyVerify??[])),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1),await this.transmit("verifySignature",t,r.toArray()),{valid:!0}}encodeKeyRelatedParams(e,t,r,i,n){let a=new ti;a.writeUInt8(e[0]);let s=e1(e[1],"utf8");a.writeVarIntNum(s.length),a.write(s);let o=e1(t,"utf8");return a.writeVarIntNum(o.length),a.write(o),"string"!=typeof r?a.writeUInt8(0):"self"===r?a.writeUInt8(11):"anyone"===r?a.writeUInt8(12):a.write(e1(r,"hex")),a.write(this.encodePrivilegedParams(i,n)),a.toArray()}async acquireCertificate(e,t){let r=new ti;r.write(e1(e.type,"base64")),r.write(e1(e.certifier,"hex"));let i=Object.entries(e.fields);for(let[e,t]of(r.writeVarIntNum(i.length),i)){let i=e1(e,"utf8"),n=e1(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}if(r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason)),r.writeUInt8("direct"===e.acquisitionProtocol?1:2),"direct"===e.acquisitionProtocol){r.write(e1(e.serialNumber,"base64")),r.write(this.encodeOutpoint(e.revocationOutpoint??""));let t=e1(e.signature,"hex");r.writeVarIntNum(t.length),r.write(t);let i="certifier"!==e.keyringRevealer?e1(e.keyringRevealer,"hex"):[11];r.write(i);let n=Object.keys(e.keyringForSubject??{});r.writeVarIntNum(n.length);for(let t=0;t<n.length;t++){let i=e1(n[t],"utf8");r.writeVarIntNum(i.length),r.write(i);let a=e1(e.keyringForSubject?.[n[t]],"base64");r.writeVarIntNum(a.length),r.write(a)}}else{let t=e1(e.certifierUrl,"utf8");r.writeVarIntNum(t.length),r.write(t)}let n=await this.transmit("acquireCertificate",t,r.toArray()),a=iS.fromBinary(n);return{...a,signature:a.signature}}encodePrivilegedParams(e,t){let r=new ti;if("boolean"==typeof e?r.writeInt8(+!!e):r.writeInt8(-1),"string"==typeof t){let e=e1(t,"utf8");r.writeInt8(e.length),r.write(e)}else r.writeInt8(-1);return r.toArray()}async listCertificates(e,t){let r=new ti;r.writeVarIntNum(e.certifiers.length);for(let t=0;t<e.certifiers.length;t++)r.write(e1(e.certifiers[t],"hex"));r.writeVarIntNum(e.types.length);for(let t=0;t<e.types.length;t++)r.write(e1(e.types[t],"base64"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let i=new tn(await this.transmit("listCertificates",t,r.toArray())),n=i.readVarIntNum(),a=[];for(let e=0;e<n;e++){let e,t=i.readVarIntNum(),r=i.read(t),n=iS.fromBinary(r),s={};if(1===i.readInt8()){let e=i.readVarIntNum();for(let t=0;t<e;t++){let e=i.readVarIntNum(),t=e4(i.read(e)),r=i.readVarIntNum();s[t]=e5(i.read(r))}}let o=i.readVarIntNum();o>0&&(e=e4(i.read(o))),a.push({...n,signature:n.signature,keyring:s,verifier:e})}return{totalCertificates:n,certificates:a}}async proveCertificate(e,t){let r=new ti,i=e1(e.certificate.type,"base64");r.write(i);let n=e1(e.certificate.subject,"hex");r.write(n);let a=e1(e.certificate.serialNumber,"base64");r.write(a);let s=e1(e.certificate.certifier,"hex");r.write(s);let o=this.encodeOutpoint(e.certificate.revocationOutpoint??"");r.write(o);let c=e1(e.certificate.signature,"hex");r.writeVarIntNum(c.length),r.write(c);let l=Object.entries(e.certificate.fields??{});for(let[e,t]of(r.writeVarIntNum(l.length),l)){let i=e1(e,"utf8"),n=e1(t,"utf8");r.writeVarIntNum(i.length),r.write(i),r.writeVarIntNum(n.length),r.write(n)}for(let t of(r.writeVarIntNum(e.fieldsToReveal.length),e.fieldsToReveal)){let e=e1(t,"utf8");r.writeVarIntNum(e.length),r.write(e)}r.write(e1(e.verifier,"hex")),r.write(this.encodePrivilegedParams(e.privileged,e.privilegedReason));let h=new tn(await this.transmit("proveCertificate",t,r.toArray())),u=h.readVarIntNum(),d={};for(let e=0;e<u;e++){let e=h.readVarIntNum(),t=e4(h.read(e)),r=h.readVarIntNum();d[t]=e5(h.read(r))}return{keyringForVerifier:d}}async relinquishCertificate(e,t){let r=new ti,i=e1(e.type,"base64");r.write(i);let n=e1(e.serialNumber,"base64");r.write(n);let a=e1(e.certifier,"hex");return r.write(a),await this.transmit("relinquishCertificate",t,r.toArray()),{relinquished:!0}}parseDiscoveryResult(e){let t=new tn(e),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e=t.readVarIntNum(),r=t.read(e),n=iS.fromBinary(r),a=t.readVarIntNum(),s=e4(t.read(a)),o=t.readVarIntNum(),c=e4(t.read(o)),l=t.readVarIntNum(),h=e4(t.read(l)),u=t.readUInt8(),d={},f=t.readVarIntNum();for(let e=0;e<f;e++){let e=t.readVarIntNum(),r=e4(t.read(e)),i=t.readVarIntNum();d[r]=t.read(i)}let p={},g=t.readVarIntNum();for(let e=0;e<g;e++){let e=t.readVarIntNum(),r=e4(t.read(e)),i=t.readVarIntNum();p[r]=e4(t.read(i))}i.push({...n,signature:n.signature,certifierInfo:{iconUrl:c,name:s,description:h,trust:u},publiclyRevealedKeyring:d,decryptedFields:p})}return{totalCertificates:r,certificates:i}}async discoverByIdentityKey(e,t){let r=new ti;r.write(e1(e.identityKey,"hex")),"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let i=await this.transmit("discoverByIdentityKey",t,r.toArray());return this.parseDiscoveryResult(i)}async discoverByAttributes(e,t){let r=new ti,i=Object.keys(e.attributes);r.writeVarIntNum(i.length);for(let t=0;t<i.length;t++)r.writeVarIntNum(i[t].length),r.write(e1(i[t],"utf8")),r.writeVarIntNum(e.attributes[i[t]].length),r.write(e1(e.attributes[i[t]],"utf8"));"number"==typeof e.limit?r.writeVarIntNum(e.limit):r.writeVarIntNum(-1),"number"==typeof e.offset?r.writeVarIntNum(e.offset):r.writeVarIntNum(-1),r.writeInt8("boolean"==typeof e.seekPermission?+!!e.seekPermission:-1);let n=await this.transmit("discoverByAttributes",t,r.toArray());return this.parseDiscoveryResult(n)}async isAuthenticated(e,t){return{authenticated:1===(await this.transmit("isAuthenticated",t))[0]}}async waitForAuthentication(e,t){return await this.transmit("waitForAuthentication",t),{authenticated:!0}}async getHeight(e,t){return{height:new tn(await this.transmit("getHeight",t)).readVarIntNum()}}async getHeaderForHeight(e,t){let r=new ti;return r.writeVarIntNum(e.height),{header:e0(await this.transmit("getHeaderForHeight",t,r.toArray()))}}async getNetwork(e,t){return{network:0===(await this.transmit("getNetwork",t))[0]?"mainnet":"testnet"}}async getVersion(e,t){return{version:e4(await this.transmit("getVersion",t))}}}class iP{baseUrl;httpClient;originator;constructor(e,t="http://localhost:3301",r=fetch){this.baseUrl=t,this.httpClient=r,this.originator=e}async transmitToWallet(e){let t,r=new tn(e),i=r.readUInt8(),n=ix[i];if(void 0===n||""===n)throw Error(`Invalid call code: ${i}`);let a=r.readUInt8();a>0&&(t=e4(r.read(a)));let s=r.read(),o=await fetch(`${this.baseUrl}/${n}`,{method:"POST",headers:{"Content-Type":"application/octet-stream",Origin:t??""},body:new Uint8Array(s)});return Array.from(new Uint8Array(await o.arrayBuffer()))}}class iN extends Error{reviewActionResults;sendWithResults;txid;tx;noSendChange;code;isError=!0;constructor(e,t,r,i,n){super("Undelayed createAction or signAction results require review."),this.reviewActionResults=e,this.sendWithResults=t,this.txid=r,this.tx=i,this.noSendChange=n,this.code=5,this.name=this.constructor.name}}let iO=iN;class iA extends Error{parameter;code;isError=!0;constructor(e,t){super(`The ${e} parameter must be ${t??"valid."}`),this.parameter=e,this.code=6,this.name=this.constructor.name}}let i_=iA,iT=class extends Error{totalSatoshisNeeded;moreSatoshisNeeded;code;isError=!0;constructor(e,t){super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${t} more satoshis are needed, for a total of ${e}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`),this.totalSatoshisNeeded=e,this.moreSatoshisNeeded=t,this.code=7,this.name=this.constructor.name}};class iC{baseUrl;httpClient;originator;api;constructor(e,t="http://localhost:3321",r=fetch){this.baseUrl=t,this.originator=e,this.httpClient=r;let i="undefined"!=typeof window&&"undefined"!=typeof document&&window?.origin!=="file://";this.api=async(e,t)=>{let n=!i&&this.originator?function(e,t="http"){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{return new URL(e).origin}catch{}try{return new URL(`${t}://${e}`).origin}catch{throw Error(`Invalid originator value: ${e}`)}}(this.originator,"http"):void 0;i||void 0!==n||console.error("Originator is required in Node.js environments");let a=await await r(`${this.baseUrl}/${e}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...n?{Origin:n}:{},...n?{Originator:n}:{}},body:JSON.stringify(t)}),s=await a.json();if(!a.ok){if(400===a.status&&s.isError){let e;switch(s.code){case 5:e=new iN(s.reviewActionResults,s.sendWithResults,s.txid,s.tx,s.noSendChange);break;case 6:(e=new iA(s.parameter)).message=s.message;break;case 7:e=new iT(s.totalSatoshisNeeded,s.moreSatoshisNeeded)}if(e)throw e}throw Error(JSON.stringify({call:e,args:t,message:s.message??`HTTP Client error ${a.status}`}))}return s}}async createAction(e){return await this.api("createAction",e)}async signAction(e){return await this.api("signAction",e)}async abortAction(e){return await this.api("abortAction",e)}async listActions(e){return await this.api("listActions",e)}async internalizeAction(e){return await this.api("internalizeAction",e)}async listOutputs(e){return await this.api("listOutputs",e)}async relinquishOutput(e){return await this.api("relinquishOutput",e)}async getPublicKey(e){return await this.api("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.api("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.api("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.api("encrypt",e)}async decrypt(e){return await this.api("decrypt",e)}async createHmac(e){return await this.api("createHmac",e)}async verifyHmac(e){return await this.api("verifyHmac",e)}async createSignature(e){return await this.api("createSignature",e)}async verifySignature(e){return await this.api("verifySignature",e)}async acquireCertificate(e){return await this.api("acquireCertificate",e)}async listCertificates(e){return await this.api("listCertificates",e)}async proveCertificate(e){return await this.api("proveCertificate",e)}async relinquishCertificate(e){return await this.api("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.api("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.api("discoverByAttributes",e)}async isAuthenticated(e){return await this.api("isAuthenticated",e)}async waitForAuthentication(e){return await this.api("waitForAuthentication",e)}async getHeight(e){return await this.api("getHeight",e)}async getHeaderForHeight(e){return await this.api("getHeaderForHeight",e)}async getNetwork(e){return await this.api("getNetwork",e)}async getVersion(e){return await this.api("getVersion",e)}}class iR{domain;constructor(e="*"){if("object"!=typeof window)throw Error("The XDM substrate requires a global window object.");if(!window.hasOwnProperty("ReactNativeWebView"))throw Error("The window object does not have a ReactNativeWebView property.");if("function"!=typeof window.ReactNativeWebView.postMessage)throw Error("The window.ReactNativeWebView property does not seem to support postMessage calls.");this.domain=e}async invoke(e,t){return await new Promise((r,i)=>{let n=e5(tq(12)),a=e=>{let t=JSON.parse(e.data);"CWI"===t.type&&t.id===n&&!0!==t.isInvocation&&("function"==typeof window.removeEventListener&&window.removeEventListener("message",a),"error"===t.status?i(new iv(t.description,t.code)):r(t.result))};window.addEventListener("message",a),window.ReactNativeWebView.postMessage(JSON.stringify({type:"CWI",isInvocation:!0,id:n,call:e,args:t}))})}async createAction(e){return await this.invoke("createAction",e)}async signAction(e){return await this.invoke("signAction",e)}async abortAction(e){return await this.invoke("abortAction",e)}async listActions(e){return await this.invoke("listActions",e)}async internalizeAction(e){return await this.invoke("internalizeAction",e)}async listOutputs(e){return await this.invoke("listOutputs",e)}async relinquishOutput(e){return await this.invoke("relinquishOutput",e)}async getPublicKey(e){return await this.invoke("getPublicKey",e)}async revealCounterpartyKeyLinkage(e){return await this.invoke("revealCounterpartyKeyLinkage",e)}async revealSpecificKeyLinkage(e){return await this.invoke("revealSpecificKeyLinkage",e)}async encrypt(e){return await this.invoke("encrypt",e)}async decrypt(e){return await this.invoke("decrypt",e)}async createHmac(e){return await this.invoke("createHmac",e)}async verifyHmac(e){return await this.invoke("verifyHmac",e)}async createSignature(e){return await this.invoke("createSignature",e)}async verifySignature(e){return await this.invoke("verifySignature",e)}async acquireCertificate(e){return await this.invoke("acquireCertificate",e)}async listCertificates(e){return await this.invoke("listCertificates",e)}async proveCertificate(e){return await this.invoke("proveCertificate",e)}async relinquishCertificate(e){return await this.invoke("relinquishCertificate",e)}async discoverByIdentityKey(e){return await this.invoke("discoverByIdentityKey",e)}async discoverByAttributes(e){return await this.invoke("discoverByAttributes",e)}async isAuthenticated(e){return await this.invoke("isAuthenticated",e)}async waitForAuthentication(e){return await this.invoke("waitForAuthentication",e)}async getHeight(e){return await this.invoke("getHeight",e)}async getHeaderForHeight(e){return await this.invoke("getHeaderForHeight",e)}async getNetwork(e){return await this.invoke("getNetwork",e)}async getVersion(e){return await this.invoke("getVersion",e)}}function iB(e){let[t,r]=e.split(".");return{txid:t,vout:Number(r)}}function iV(e){return e??!1}function iD(e,t,r,i){if(void 0!==e)return iH(e,t,r,i)}function iU(e,t,r){if(void 0===e||!Number.isInteger(e)||e<0||e>21e14)throw new i_(t,"a valid number of satoshis");if(void 0!==r&&e<r)throw new i_(t,`at least ${r} satoshis.`);return e}function iF(e,t,r,i){if(void 0!==e)return iL(e,t,void 0,r,i)}function iL(e,t,r,i,n){if(void 0===e){if(void 0!==r)return r;throw new i_(t,"a valid integer")}if(!Number.isInteger(e))throw new i_(t,"an integer");if(e=Number(e),void 0!==i&&e<i)throw new i_(t,`at least ${i} length.`);if(void 0!==n&&e>n)throw new i_(t,`no more than ${n} length.`);return e}function iK(e,t){return iL(e,t,0,0)}function iH(e,t,r,i){let n=e1(e,"utf8").length;if(void 0!==r&&n<r)throw new i_(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new i_(t,`no more than ${i} length.`);return e}function iq(e){return iz(e,"basket",1,300)}function iM(e){return iz(e,"label",1,300)}function i$(e){return iz(e,"tag",1,300)}function iz(e,t,r,i){let n=e1(e=e.trim().toLowerCase(),"utf8").length;if(void 0!==r&&n<r)throw new i_(t,`at least ${r} length.`);if(void 0!==i&&n>i)throw new i_(t,`no more than ${i} length.`);return e}function iW(e,t,r,i){if(void 0!==e)return ij(e,t,r,i)}function ij(e,t,r,i){if(0===(e=e.trim()).length)throw new i_(t,"valid base64 string");let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if((!(i>=65)||!(i<=90))&&(!(i>=97)||!(i<=122))&&(!(i>=48)||!(i<=57))&&43!==i&&47!==i){if(61===i){if(r<e.length-2)throw new i_(t,"valid base64 string");n++;continue}throw new i_(t,"valid base64 string")}}if(n>2||n>0&&e.length%4!=0)throw new i_(t,"valid base64 string");let a=e.length%4;if(0!==a&&a!==4-n)throw new i_(t,"valid base64 string");let s=Math.floor(3*(e.length-n)/4);if(void 0!==r&&s<r)throw new i_(t,`at least ${r} bytes`);if(void 0!==i&&s>i)throw new i_(t,`no more than ${i} bytes`);return e}function iG(e,t,r,i){if(void 0!==e)return iX(e,t,r,i)}function iX(e,t,r,i){if((e=e.trim().toLowerCase()).length%2==1)throw new i_(t,`even length, not ${e.length}.`);if(!/^[0-9A-Fa-f]+$/.test(e))throw new i_(t,"hexadecimal string.");if(void 0!==r&&e.length<r)throw new i_(t,`at least ${r} length.`);if(void 0!==i&&e.length>i)throw new i_(t,`no more than ${i} length.`);return e}function iJ(e){return(e=e.trim()).length%2!=1&&!!/^[0-9A-Fa-f]+$/.test(e)}function iY(e){if(void 0===e.unlockingScript&&void 0===e.unlockingScriptLength)throw new i_("unlockingScript, unlockingScriptLength","at least one valid value.");let t=iG(e.unlockingScript,"unlockingScript"),r=e.unlockingScriptLength??(null!=t?t.length/2:0);if(t&&r!==t.length/2)throw new i_("unlockingScriptLength","length unlockingScript if both valid.");return{outpoint:iB(e.outpoint),inputDescription:iH(e.inputDescription,"inputDescription",5,2e3),unlockingScript:t,unlockingScriptLength:r,sequenceNumber:e.sequenceNumber??0xffffffff}}function iZ(e){return{lockingScript:iX(e.lockingScript,"lockingScript"),satoshis:iU(e.satoshis,"satoshis"),outputDescription:iH(e.outputDescription,"outputDescription",5,2e3),basket:function(e){if(void 0!==e)return iq(e)}(e.basket),customInstructions:e.customInstructions,tags:(e.tags??[]).map(e=>i$(e))}}function iQ(e){let t=null!=e?e:{};return{signAndProcess:t.signAndProcess??!0,acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,knownTxids:t.knownTxids??[],returnTXIDOnly:iV(t.returnTXIDOnly),noSend:iV(t.noSend),noSendChange:(t.noSendChange??[]).map(e=>iB(e)),sendWith:t.sendWith??[],randomizeOutputs:t.randomizeOutputs??!0}}function i0(e,t){let r={description:iH(e.description,"description",5,2e3),inputBEEF:e.inputBEEF,inputs:(e.inputs??[]).map(e=>iY(e)),outputs:(e.outputs??[]).map(e=>iZ(e)),lockTime:e.lockTime??0,version:e.version??1,labels:e.labels?.map(e=>iM(e))??[],options:iQ(e.options),logger:t,isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!1,isRemixChange:!1,isSignAction:!1,randomVals:void 0,includeAllSourceTransactions:!1,isTestWerrReviewActions:!1};return r.isTestWerrReviewActions=r.labels.includes(nd),r.isSendWith=r.options.sendWith.length>0,r.isRemixChange=!r.isSendWith&&0===r.inputs.length&&0===r.outputs.length,r.isNewTx=r.isRemixChange||r.inputs.length>0||r.outputs.length>0,r.isSignAction=r.isNewTx&&(!r.options.signAndProcess||r.inputs.some(e=>void 0===e.unlockingScript)),r.isDelayed=r.options.acceptDelayedBroadcast,r.isNoSend=r.options.noSend,r}function i1(e){let t=null!=e?e:{};return{acceptDelayedBroadcast:t.acceptDelayedBroadcast??!0,returnTXIDOnly:iV(t.returnTXIDOnly),noSend:iV(t.noSend),sendWith:t.sendWith??[]}}function i2(e){let t={spends:e.spends,reference:e.reference,options:i1(e.options),isSendWith:!1,isDelayed:!1,isNoSend:!1,isNewTx:!0,isRemixChange:!1,isTestWerrReviewActions:!1};return t.isSendWith=t.options.sendWith.length>0,t.isDelayed=t.options.acceptDelayedBroadcast,t.isNoSend=t.options.noSend,t}function i8(e){return{reference:ij(e.reference,"reference")}}function i3(e){if(void 0!==e)return{derivationPrefix:ij(e.derivationPrefix,"derivationPrefix"),derivationSuffix:ij(e.derivationSuffix,"derivationSuffix"),senderIdentityKey:iX(e.senderIdentityKey,"senderIdentityKey")}}function i4(e){if(void 0!==e)return{basket:iq(e.basket),customInstructions:iD(e.customInstructions,"customInstructions",0,1e3),tags:(e.tags??[]).map(e=>i$(e))}}function i6(e){if("basket insertion"!==e.protocol&&"wallet payment"!==e.protocol)throw new i_("protocol","'basket insertion' or 'wallet payment'");return{outputIndex:iK(e.outputIndex,"outputIndex"),protocol:e.protocol,paymentRemittance:i3(e.paymentRemittance),insertionRemittance:i4(e.insertionRemittance)}}function i5(e){if(void 0!==e){for(let t of(iH(e=e.trim().toLowerCase(),"originator",1,250),e.split(".")))iH(t,"originator part",1,63);return e}}function i7(e){let t={tx:e.tx,outputs:e.outputs.map(e=>i6(e)),description:iH(e.description,"description",5,2e3),labels:(null!=e.labels?e.labels:[]).map(e=>iM(e)),seekPermission:e.seekPermission??!0};try{if(r$.fromBinary(t.tx).txs.length<1)throw new i_("tx","at least one transaction to internalize an output from")}catch{throw new i_("tx","valid with at least one transaction to internalize an output from")}if(t.outputs.length<1)throw new i_("outputs","at least one output to internalize from the transaction");return t}function i9(e,t){if(void 0!==e)return ne(e,t)}function ne(e,t){let r=e.split(".");if(2!==r.length||!Number.isInteger(Number(r[1])))throw new i_(t,"txid as hex string and numeric output index joined with '.'");let i=iX(r[0],`${t} txid`,void 0,64),n=iK(Number(r[1]),`${t} vout`);return`${i}.${n}`}function nt(e){return{basket:iq(e.basket),output:ne(e.output,"output")}}function nr(e){return{type:ij(e.type,"type"),serialNumber:ij(e.serialNumber,"serialNumber"),certifier:iX(e.certifier,"certifier")}}function ni(e){return{certifiers:e.certifiers.map(e=>iX(e.trim(),"certifiers"))??[],types:e.types.map(e=>ij(e.trim(),"types"))??[],limit:iL(e.limit,"limit",10,1,1e4),offset:iK(e.offset??0,"offset"),privileged:iV(e.privileged),privilegedReason:iD(e.privilegedReason,"privilegedReason",5,50),partial:void 0}}function nn(e){for(let t of Object.keys(e))iH(t,"field name",1,50);return e}function na(e){if("issuance"!==e.acquisitionProtocol)throw Error("Only acquire certificate via issuance requests allowed here.");if(e.serialNumber)throw new i_("serialNumber",'valid when acquisitionProtocol is "direct"');if(e.signature)throw new i_("signature",'valid when acquisitionProtocol is "direct"');if(e.revocationOutpoint)throw new i_("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(e.keyringRevealer)throw new i_("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null!=e.keyringForSubject)throw new i_("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(!e.certifierUrl)throw new i_("certifierUrl",'valid when acquisitionProtocol is "issuance"');if(e.privileged&&!e.privilegedReason)throw new i_("privilegedReason","valid when 'privileged' is true ");return{type:ij(e.type,"type"),certifier:iX(e.certifier,"certifier"),certifierUrl:e.certifierUrl,fields:nn(e.fields),privileged:iV(e.privileged),privilegedReason:iD(e.privilegedReason,"privilegedReason",5,50),subject:""}}function ns(e){var t;if("direct"!==e.acquisitionProtocol)throw Error("Only acquire direct certificate requests allowed here.");if(!e.serialNumber)throw new i_("serialNumber",'valid when acquisitionProtocol is "direct"');if(!e.signature)throw new i_("signature",'valid when acquisitionProtocol is "direct"');if(!e.revocationOutpoint)throw new i_("revocationOutpoint",'valid when acquisitionProtocol is "direct"');if(!e.keyringRevealer)throw new i_("keyringRevealer",'valid when acquisitionProtocol is "direct"');if(null==e.keyringForSubject)throw new i_("keyringForSubject",'valid when acquisitionProtocol is "direct"');if(e.privileged&&!e.privilegedReason)throw new i_("privilegedReason","valid when 'privileged' is true ");return{type:ij(e.type,"type"),serialNumber:ij(e.serialNumber,"serialNumber"),certifier:iX(e.certifier,"certifier"),revocationOutpoint:ne(e.revocationOutpoint,"revocationOutpoint"),fields:nn(e.fields),signature:iX(e.signature,"signature"),keyringRevealer:(t=e.keyringRevealer,"certifier"===t?t:iX(t,"keyringRevealer")),keyringForSubject:function(e,t){for(let r of Object.keys(e))iH(r,`${t} field name`,1,50),ij(e[r],`${t} field value`);return e}(e.keyringForSubject,"keyringForSubject"),privileged:iV(e.privileged),privilegedReason:iD(e.privilegedReason,"privilegedReason",5,50),subject:""}}function no(e){if(e.privileged&&!e.privilegedReason)throw new i_("privilegedReason","valid when 'privileged' is true ");return{type:iW(e.certificate.type,"certificate.type"),serialNumber:iW(e.certificate.serialNumber,"certificate.serialNumber"),certifier:iG(e.certificate.certifier,"certificate.certifier"),subject:iG(e.certificate.subject,"certificate.subject"),revocationOutpoint:i9(e.certificate.revocationOutpoint,"certificate.revocationOutpoint"),signature:iG(e.certificate.signature,"certificate.signature"),fieldsToReveal:(e.fieldsToReveal??[]).map(e=>iH(e,`fieldsToReveal ${e}`,1,50)),verifier:iX(e.verifier,"verifier"),privileged:iV(e.privileged),privilegedReason:iD(e.privilegedReason,"privilegedReason",5,50)}}function nc(e){return{identityKey:iX(e.identityKey,"identityKey",66,66),limit:iL(e.limit,"limit",10,1,1e4),offset:iK(e.offset??0,"offset"),seekPermission:iV(e.seekPermission)}}function nl(e){return{attributes:function(e){for(let t of Object.keys(e))iH(t,`field name ${t}`,1,50);return e}(e.attributes),limit:iL(e.limit,"limit",10,1,1e4),offset:iK(e.offset??0,"offset"),seekPermission:iV(e.seekPermission)}}function nh(e){let t;if(void 0===e.tagQueryMode||"any"===e.tagQueryMode)t="any";else if("all"===e.tagQueryMode)t="all";else throw new i_("tagQueryMode","undefined, 'any', or 'all'");return{basket:iH(e.basket,"basket",1,300),tags:(null!=e.tags?e.tags:[]).map(e=>iH(e,"tag",1,300)),tagQueryMode:t,includeLockingScripts:"locking scripts"===e.include,includeTransactions:"entire transactions"===e.include,includeCustomInstructions:iV(e.includeCustomInstructions),includeTags:iV(e.includeTags),includeLabels:iV(e.includeLabels),limit:iL(e.limit,"limit",10,1,1e4),offset:iL(e.offset,"offset",0,void 0,void 0),seekPermission:e.seekPermission??!0,knownTxids:[]}}function nu(e){let t;if(void 0===e.labelQueryMode||"any"===e.labelQueryMode)t="any";else if("all"===e.labelQueryMode)t="all";else throw new i_("labelQueryMode","undefined, 'any', or 'all'");return{labels:(null!=e.labels?e.labels:[]).map(e=>iM(e)),labelQueryMode:t,includeLabels:iV(e.includeLabels),includeInputs:iV(e.includeInputs),includeInputSourceLockingScripts:iV(e.includeInputSourceLockingScripts),includeInputUnlockingScripts:iV(e.includeInputUnlockingScripts),includeOutputs:iV(e.includeOutputs),includeOutputLockingScripts:iV(e.includeOutputLockingScripts),limit:iL(e.limit,"limit",10,1,1e4),offset:iL(e.offset,"offset",0,0),seekPermission:e.seekPermission??!0}}let nd="a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a";class nf{substrate;originator;constructor(e="auto",t){"Cicada"===e&&(e=new iE(new iP(t))),"window.CWI"===e&&(e=new iw),"XDM"===e&&(e=new ik),"json-api"===e&&(e=new iC(t)),"react-native"===e&&(e=new iR(t)),"secure-json-api"===e&&(e=new iC(t,"https://localhost:2121")),this.substrate=e,this.originator=t}async connectToSubstrate(){if("object"==typeof this.substrate)return;let e=async(e,t)=>{try{let r,i=e();if(r="number"==typeof t?await Promise.race([i.getVersion({}),new Promise((e,r)=>setTimeout(()=>r(Error("Timed out.")),t))]):await i.getVersion({}),"object"!=typeof r||"string"!=typeof r.version)return{success:!1};return{success:!0,sub:i}}catch{return{success:!1}}},t=[e(()=>new iw),e(()=>new iC(this.originator,"https://localhost:2121")),e(()=>new iC(this.originator)),e(()=>new iR(this.originator)),e(()=>new iE(new iP(this.originator)))],r=(await Promise.allSettled(t)).filter(e=>"fulfilled"===e.status&&e.value.success&&void 0!==e.value.sub).map(e=>e.value.sub);if(r.length>0){this.substrate=r[0];return}let i=await e(()=>new ik,200);if(i.success&&void 0!==i.sub)this.substrate=i.sub;else throw Error("No wallet available over any communication substrate. Install a BSV wallet today!")}async createAction(e){return i0(e),await this.connectToSubstrate(),await this.substrate.createAction(e,this.originator)}async signAction(e){return i2(e),await this.connectToSubstrate(),await this.substrate.signAction(e,this.originator)}async abortAction(e){return i8(e),await this.connectToSubstrate(),await this.substrate.abortAction(e,this.originator)}async listActions(e){return nu(e),await this.connectToSubstrate(),await this.substrate.listActions(e,this.originator)}async internalizeAction(e){return i7(e),await this.connectToSubstrate(),await this.substrate.internalizeAction(e,this.originator)}async listOutputs(e){return nh(e),await this.connectToSubstrate(),await this.substrate.listOutputs(e,this.originator)}async relinquishOutput(e){return nt(e),await this.connectToSubstrate(),await this.substrate.relinquishOutput(e,this.originator)}async getPublicKey(e){return await this.connectToSubstrate(),await this.substrate.getPublicKey(e,this.originator)}async revealCounterpartyKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealCounterpartyKeyLinkage(e,this.originator)}async revealSpecificKeyLinkage(e){return await this.connectToSubstrate(),await this.substrate.revealSpecificKeyLinkage(e,this.originator)}async encrypt(e){return await this.connectToSubstrate(),await this.substrate.encrypt(e,this.originator)}async decrypt(e){return await this.connectToSubstrate(),await this.substrate.decrypt(e,this.originator)}async createHmac(e){return await this.connectToSubstrate(),await this.substrate.createHmac(e,this.originator)}async verifyHmac(e){return await this.connectToSubstrate(),await this.substrate.verifyHmac(e,this.originator)}async createSignature(e){return await this.connectToSubstrate(),await this.substrate.createSignature(e,this.originator)}async verifySignature(e){return await this.connectToSubstrate(),await this.substrate.verifySignature(e,this.originator)}async acquireCertificate(e){if("direct"===e.acquisitionProtocol)ns(e);else if("issuance"===e.acquisitionProtocol)na(e);else throw new iA("acquisitionProtocol",`valid. ${String(e.acquisitionProtocol)} is unrecognized.`);return await this.connectToSubstrate(),await this.substrate.acquireCertificate(e,this.originator)}async listCertificates(e){return ni(e),await this.connectToSubstrate(),await this.substrate.listCertificates(e,this.originator)}async proveCertificate(e){return no(e),await this.connectToSubstrate(),await this.substrate.proveCertificate(e,this.originator)}async relinquishCertificate(e){return nr(e),await this.connectToSubstrate(),await this.substrate.relinquishCertificate(e,this.originator)}async discoverByIdentityKey(e){return nc(e),await this.connectToSubstrate(),await this.substrate.discoverByIdentityKey(e,this.originator)}async discoverByAttributes(e){return nl(e),await this.connectToSubstrate(),await this.substrate.discoverByAttributes(e,this.originator)}async isAuthenticated(e={}){return await this.connectToSubstrate(),await this.substrate.isAuthenticated(e,this.originator)}async waitForAuthentication(e={}){return await this.connectToSubstrate(),await this.substrate.waitForAuthentication(e,this.originator)}async getHeight(e={}){return await this.connectToSubstrate(),await this.substrate.getHeight(e,this.originator)}async getHeaderForHeight(e){return await this.connectToSubstrate(),await this.substrate.getHeaderForHeight(e,this.originator)}async getNetwork(e={}){return await this.connectToSubstrate(),await this.substrate.getNetwork(e,this.originator)}async getVersion(e={}){return await this.connectToSubstrate(),await this.substrate.getVersion(e,this.originator)}}class np{wallet;constructor(e){this.wallet=e}decodeOutpoint(e){let t=e0(e.read(32)),r=e.readVarIntNum();return`${t}.${r}`}encodeOutpoint(e){let t=new ti,[r,i]=e.split(".");return t.write(e1(r,"hex")),t.writeVarIntNum(Number(i)),t.toArray()}async transmitToWallet(e){let t=new tn(e);try{let e=t.readUInt8(),r=ix[e];if(void 0===r||""===r)throw Error(`Invalid call code: ${e}`);let i=t.readUInt8(),n=t.read(i),a=e4(n);switch(r){case"createAction":{let e={},r=t.readVarIntNum(),i=t.read(r);e.description=e4(i);let n=t.readVarIntNum();n>=0?e.inputBEEF=t.read(n):e.inputBEEF=void 0;let s=t.readVarIntNum();if(s>=0){e.inputs=[];for(let r=0;r<s;r++){let r={};r.outpoint=this.decodeOutpoint(t);let i=t.readVarIntNum();if(i>=0){let e=t.read(i);r.unlockingScript=e0(e)}else r.unlockingScript=void 0,r.unlockingScriptLength=t.readVarIntNum();let n=t.readVarIntNum(),a=t.read(n);r.inputDescription=e4(a);let s=t.readVarIntNum();s>=0?r.sequenceNumber=s:r.sequenceNumber=void 0,e.inputs.push(r)}}else e.inputs=void 0;let o=t.readVarIntNum();if(o>=0){e.outputs=[];for(let r=0;r<o;r++){let r={},i=t.readVarIntNum(),n=t.read(i);r.lockingScript=e0(n),r.satoshis=t.readVarIntNum();let a=t.readVarIntNum(),s=t.read(a);r.outputDescription=e4(s);let o=t.readVarIntNum();if(o>=0){let e=t.read(o);r.basket=e4(e)}else r.basket=void 0;let c=t.readVarIntNum();if(c>=0){let e=t.read(c);r.customInstructions=e4(e)}else r.customInstructions=void 0;let l=t.readVarIntNum();if(l>=0){r.tags=[];for(let e=0;e<l;e++){let e=t.readVarIntNum(),i=t.read(e),n=e4(i);r.tags.push(n)}}else r.tags=void 0;e.outputs.push(r)}}else e.outputs=void 0;let c=t.readVarIntNum();c>=0?e.lockTime=c:e.lockTime=void 0;let l=t.readVarIntNum();l>=0?e.version=l:e.version=void 0;let h=t.readVarIntNum();if(h>=0){e.labels=[];for(let r=0;r<h;r++){let r=t.readVarIntNum(),i=t.read(r),n=e4(i);e.labels.push(n)}}else e.labels=void 0;let u=t.readInt8();if(1===u){e.options={};let r=t.readInt8();-1===r?e.options.signAndProcess=void 0:e.options.signAndProcess=1===r;let i=t.readInt8();-1===i?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===i;let n=t.readInt8();-1===n?e.options.trustSelf=void 0:1===n&&(e.options.trustSelf="known");let a=t.readVarIntNum();if(a>=0){e.options.knownTxids=[];for(let r=0;r<a;r++){let r=t.read(32),i=e0(r);e.options.knownTxids.push(i)}}else e.options.knownTxids=void 0;let s=t.readInt8();-1===s?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===s;let o=t.readInt8();-1===o?e.options.noSend=void 0:e.options.noSend=1===o;let c=t.readVarIntNum();if(c>=0){e.options.noSendChange=[];for(let r=0;r<c;r++){let r=this.decodeOutpoint(t);e.options.noSendChange.push(r)}}else e.options.noSendChange=void 0;let l=t.readVarIntNum();if(l>=0){e.options.sendWith=[];for(let r=0;r<l;r++){let r=t.read(32),i=e0(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0;let h=t.readInt8();-1===h?e.options.randomizeOutputs=void 0:e.options.randomizeOutputs=1===h}else e.options=void 0;let d=await this.wallet.createAction(e,a),f=new ti;if(null!=d.txid&&""!==d.txid?(f.writeInt8(1),f.write(e1(d.txid,"hex"))):f.writeInt8(0),null!=d.tx?(f.writeInt8(1),f.writeVarIntNum(d.tx.length),f.write(d.tx)):f.writeInt8(0),null!=d.noSendChange)for(let e of(f.writeVarIntNum(d.noSendChange.length),d.noSendChange))f.write(this.encodeOutpoint(e));else f.writeVarIntNum(-1);if(null!=d.sendWithResults)for(let e of(f.writeVarIntNum(d.sendWithResults.length),d.sendWithResults)){let t;f.write(e1(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),f.writeInt8(t)}else f.writeVarIntNum(-1);if(null!=d.signableTransaction){f.writeInt8(1),f.writeVarIntNum(d.signableTransaction.tx.length),f.write(d.signableTransaction.tx);let e=e1(d.signableTransaction.reference,"base64");f.writeVarIntNum(e.length),f.write(e)}else f.writeInt8(0);let p=new ti;return p.writeUInt8(0),p.write(f.toArray()),p.toArray()}case"signAction":{let e={},r=t.readVarIntNum();e.spends={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i={},n=t.readVarIntNum(),a=t.read(n);i.unlockingScript=e0(a);let s=t.readVarIntNum();s>=0?i.sequenceNumber=s:i.sequenceNumber=void 0,e.spends[r]=i}let i=t.readVarIntNum(),n=t.read(i);e.reference=e5(n);let s=t.readInt8();if(1===s){e.options={};let r=t.readInt8();-1===r?e.options.acceptDelayedBroadcast=void 0:e.options.acceptDelayedBroadcast=1===r;let i=t.readInt8();-1===i?e.options.returnTXIDOnly=void 0:e.options.returnTXIDOnly=1===i;let n=t.readInt8();-1===n?e.options.noSend=void 0:e.options.noSend=1===n;let a=t.readVarIntNum();if(a>=0){e.options.sendWith=[];for(let r=0;r<a;r++){let r=t.read(32),i=e0(r);e.options.sendWith.push(i)}}else e.options.sendWith=void 0}else e.options=void 0;let o=await this.wallet.signAction(e,a),c=new ti;if(null!=o.txid&&""!==o.txid?(c.writeInt8(1),c.write(e1(o.txid,"hex"))):c.writeInt8(0),null!=o.tx?(c.writeInt8(1),c.writeVarIntNum(o.tx.length),c.write(o.tx)):c.writeInt8(0),null!=o.sendWithResults)for(let e of(c.writeVarIntNum(o.sendWithResults.length),o.sendWithResults)){let t;c.write(e1(e.txid,"hex")),"unproven"===e.status?t=1:"sending"===e.status?t=2:"failed"===e.status&&(t=3),c.writeInt8(t)}else c.writeVarIntNum(-1);let l=new ti;return l.writeUInt8(0),l.write(c.toArray()),l.toArray()}case"abortAction":{let e=t.read(),r=e5(e);await this.wallet.abortAction({reference:r},a);let i=new ti;return i.writeUInt8(0),i.toArray()}case"listActions":{let e={},r=t.readVarIntNum();e.labels=[];for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r);e.labels.push(e4(i))}let i=t.readInt8();for(let r of(-1===i?e.labelQueryMode=void 0:1===i?e.labelQueryMode="any":2===i&&(e.labelQueryMode="all"),["includeLabels","includeInputs","includeInputSourceLockingScripts","includeInputUnlockingScripts","includeOutputs","includeOutputLockingScripts"])){let i=t.readInt8();-1===i?e[r]=void 0:e[r]=1===i}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0;let c=await this.wallet.listActions(e,a),l=new ti;for(let e of(l.writeVarIntNum(c.totalActions),c.actions)){let t;switch(l.write(e1(e.txid,"hex")),l.writeVarIntNum(e.satoshis),e.status){case"completed":t=1;break;case"unprocessed":t=2;break;case"sending":t=3;break;case"unproven":t=4;break;case"unsigned":t=5;break;case"nosend":t=6;break;case"nonfinal":t=7;break;case"failed":t=8;break;default:t=-1}l.writeInt8(t),l.writeInt8(+!!e.isOutgoing);let r=e1(e.description,"utf8");if(l.writeVarIntNum(r.length),l.write(r),void 0!==e.labels)for(let t of(l.writeVarIntNum(e.labels.length),e.labels)){let e=e1(t,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(l.writeVarIntNum(e.version),l.writeVarIntNum(e.lockTime),void 0!==e.inputs)for(let t of(l.writeVarIntNum(e.inputs.length),e.inputs)){if(l.write(this.encodeOutpoint(t.sourceOutpoint)),l.writeVarIntNum(t.sourceSatoshis),void 0!==t.sourceLockingScript){let e=e1(t.sourceLockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.unlockingScript){let e=e1(t.unlockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);let e=e1(t.inputDescription,"utf8");l.writeVarIntNum(e.length),l.write(e),l.writeVarIntNum(t.sequenceNumber)}else l.writeVarIntNum(-1);if(void 0!==e.outputs)for(let t of(l.writeVarIntNum(e.outputs.length),e.outputs)){if(l.writeVarIntNum(t.outputIndex),l.writeVarIntNum(t.satoshis),void 0!==t.lockingScript){let e=e1(t.lockingScript,"hex");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);l.writeInt8(+!!t.spendable);let e=e1(t.outputDescription,"utf8");if(l.writeVarIntNum(e.length),l.write(e),void 0!==t.basket){let e=e1(t.basket,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1);if(void 0!==t.tags)for(let e of(l.writeVarIntNum(t.tags.length),t.tags)){let t=e1(e,"utf8");l.writeVarIntNum(t.length),l.write(t)}else l.writeVarIntNum(-1);if(void 0!==t.customInstructions){let e=e1(t.customInstructions,"utf8");l.writeVarIntNum(e.length),l.write(e)}else l.writeVarIntNum(-1)}else l.writeVarIntNum(-1)}let h=new ti;return h.writeUInt8(0),h.write(l.toArray()),h.toArray()}case"internalizeAction":{let e={},r=t.readVarIntNum();e.tx=t.read(r);let i=t.readVarIntNum();e.outputs=[];for(let r=0;r<i;r++){let r={};r.outputIndex=t.readVarIntNum();let i=t.readUInt8();if(1===i){r.protocol="wallet payment",r.paymentRemittance={};let e=t.read(33);r.paymentRemittance.senderIdentityKey=e0(e);let i=t.readVarIntNum(),n=t.read(i);r.paymentRemittance.derivationPrefix=e5(n);let a=t.readVarIntNum(),s=t.read(a);r.paymentRemittance.derivationSuffix=e5(s)}else if(2===i){r.protocol="basket insertion",r.insertionRemittance={};let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.basket=e4(i);let n=t.readVarIntNum();if(n>=0){let e=t.read(n);r.insertionRemittance.customInstructions=e4(e)}let a=t.readVarIntNum();if(a>0){r.insertionRemittance.tags=[];for(let e=0;e<a;e++){let e=t.readVarIntNum(),i=t.read(e);r.insertionRemittance.tags.push(e4(i))}}else r.insertionRemittance.tags=[]}e.outputs.push(r)}let n=t.readVarIntNum();if(n>=0){e.labels=[];for(let r=0;r<n;r++){let r=t.readVarIntNum();e.labels.push(e4(t.read(r)))}}let s=t.readVarIntNum();e.description=e4(t.read(s));let o=t.readInt8();o>=0?e.seekPermission=1===o:e.seekPermission=void 0,await this.wallet.internalizeAction(e,a);let c=new ti;return c.writeUInt8(0),c.toArray()}case"listOutputs":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e4(i);let n=t.readVarIntNum();if(n>0){e.tags=[];for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r);e.tags.push(e4(i))}}else e.tags=void 0;let s=t.readInt8();1===s?e.tagQueryMode="all":2===s?e.tagQueryMode="any":e.tagQueryMode=void 0;let o=t.readInt8();1===o?e.include="locking scripts":2===o?e.include="entire transactions":e.include=void 0;let c=t.readInt8();-1===c?e.includeCustomInstructions=void 0:e.includeCustomInstructions=1===c;let l=t.readInt8();-1===l?e.includeTags=void 0:e.includeTags=1===l;let h=t.readInt8();-1===h?e.includeLabels=void 0:e.includeLabels=1===h;let u=t.readVarIntNum();u>=0?e.limit=u:e.limit=void 0;let d=t.readVarIntNum();d>=0?e.offset=d:e.offset=void 0;let f=t.readInt8();f>=0?e.seekPermission=1===f:e.seekPermission=void 0;let p=await this.wallet.listOutputs(e,a),g=new ti;for(let e of(g.writeVarIntNum(p.totalOutputs),null!=p.BEEF?(g.writeVarIntNum(p.BEEF.length),g.write(p.BEEF)):g.writeVarIntNum(-1),p.outputs)){if(g.write(this.encodeOutpoint(e.outpoint)),g.writeVarIntNum(e.satoshis),void 0!==e.lockingScript){let t=e1(e.lockingScript,"hex");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.customInstructions){let t=e1(e.customInstructions,"utf8");g.writeVarIntNum(t.length),g.write(t)}else g.writeVarIntNum(-1);if(void 0!==e.tags)for(let t of(g.writeVarIntNum(e.tags.length),e.tags)){let e=e1(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1);if(void 0!==e.labels)for(let t of(g.writeVarIntNum(e.labels.length),e.labels)){let e=e1(t,"utf8");g.writeVarIntNum(e.length),g.write(e)}else g.writeVarIntNum(-1)}let b=new ti;return b.writeUInt8(0),b.write(g.toArray()),b.toArray()}case"relinquishOutput":{let e={},r=t.readVarIntNum(),i=t.read(r);e.basket=e4(i),e.output=this.decodeOutpoint(t),await this.wallet.relinquishOutput(e,a);let n=new ti;return n.writeUInt8(0),n.toArray()}case"getPublicKey":{let e={},r=t.readUInt8();if(e.identityKey=1===r,!0!==e.identityKey){e.protocolID=this.decodeProtocolID(t),e.keyID=this.decodeString(t),e.counterparty=this.decodeCounterparty(t);let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e4(r)}else e.privilegedReason=void 0;let n=t.readInt8();-1===n?e.forSelf=void 0:e.forSelf=1===n}else{let r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1!==i){let r=t.read(i);e.privilegedReason=e4(r)}else e.privilegedReason=void 0}let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.getPublicKey(e,a),s=new ti;s.writeUInt8(0);let o=e1(n.publicKey,"hex");return s.write(o),s.toArray()}case"encrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.plaintext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.encrypt(e,a),s=new ti;return s.writeUInt8(0),s.write(n.ciphertext),s.toArray()}case"decrypt":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.ciphertext=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.decrypt(e,a),s=new ti;return s.writeUInt8(0),s.write(n.plaintext),s.toArray()}case"createHmac":{let e=this.decodeKeyRelatedParams(t),r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.createHmac(e,a),s=new ti;return s.writeUInt8(0),s.write(n.hmac),s.toArray()}case"verifyHmac":{let e=this.decodeKeyRelatedParams(t);e.hmac=t.read(32);let r=t.readVarIntNum();e.data=t.read(r);let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0,await this.wallet.verifyHmac(e,a);let n=new ti;return n.writeUInt8(0),n.toArray()}case"createSignature":{let e=this.decodeKeyRelatedParams(t),r=t.readUInt8();if(1===r){let r=t.readVarIntNum();e.data=t.read(r)}else 2===r&&(e.hashToDirectlySign=t.read(32));let i=t.readInt8();i>=0?e.seekPermission=1===i:e.seekPermission=void 0;let n=await this.wallet.createSignature(e,a),s=new ti;return s.writeUInt8(0),s.write(n.signature),s.toArray()}case"verifySignature":{let e=this.decodeKeyRelatedParams(t),r=t.readInt8();-1===r?e.forSelf=void 0:e.forSelf=1===r;let i=t.readVarIntNum();e.signature=t.read(i);let n=t.readUInt8();if(1===n){let r=t.readVarIntNum();e.data=t.read(r)}else 2===n&&(e.hashToDirectlyVerify=t.read(32));let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0,await this.wallet.verifySignature(e,a);let o=new ti;return o.writeUInt8(0),o.toArray()}case"isAuthenticated":{let e=await this.wallet.isAuthenticated({},a),t=new ti;return t.writeUInt8(0),t.writeUInt8(+!!e.authenticated),t.toArray()}case"waitForAuthentication":{await this.wallet.waitForAuthentication({},a);let e=new ti;return e.writeUInt8(0),e.toArray()}case"getHeight":{let e=await this.wallet.getHeight({},a),t=new ti;return t.writeUInt8(0),t.writeVarIntNum(e.height),t.toArray()}case"getHeaderForHeight":{let e={};e.height=t.readVarIntNum();let r=await this.wallet.getHeaderForHeight(e,a),i=new ti;i.writeUInt8(0);let n=e1(r.header,"hex");return i.write(n),i.toArray()}case"getNetwork":{let e=await this.wallet.getNetwork({},a),t=new ti;return t.writeUInt8(0),t.writeUInt8(+("mainnet"!==e.network)),t.toArray()}case"getVersion":{let e=await this.wallet.getVersion({},a),t=new ti;t.writeUInt8(0);let r=e1(e.version,"utf8");return t.write(r),t.toArray()}case"revealCounterpartyKeyLinkage":{let e={},r=t.readInt8();-1===r?e.privileged=void 0:e.privileged=1===r;let i=t.readInt8();if(-1===i)e.privilegedReason=void 0;else{let r=t.read(i);e.privilegedReason=e4(r)}let n=t.read(33);e.counterparty=e0(n);let s=t.read(33);e.verifier=e0(s);let o=await this.wallet.revealCounterpartyKeyLinkage(e,a),c=new ti;c.write(e1(o.prover,"hex")),c.write(e1(o.verifier,"hex")),c.write(e1(o.counterparty,"hex"));let l=e1(o.revelationTime,"utf8");c.writeVarIntNum(l.length),c.write(l),c.writeVarIntNum(o.encryptedLinkage.length),c.write(o.encryptedLinkage),c.writeVarIntNum(o.encryptedLinkageProof.length),c.write(o.encryptedLinkageProof);let h=new ti;return h.writeUInt8(0),h.write(c.toArray()),h.toArray()}case"revealSpecificKeyLinkage":{let e=this.decodeKeyRelatedParams(t),r=t.read(33);e.verifier=e0(r);let i=await this.wallet.revealSpecificKeyLinkage(e,a),n=new ti;n.write(e1(i.prover,"hex")),n.write(e1(i.verifier,"hex")),n.write(e1(i.counterparty,"hex")),n.writeUInt8(i.protocolID[0]);let s=e1(i.protocolID[1],"utf8");n.writeVarIntNum(s.length),n.write(s);let o=e1(i.keyID,"utf8");n.writeVarIntNum(o.length),n.write(o),n.writeVarIntNum(i.encryptedLinkage.length),n.write(i.encryptedLinkage),n.writeVarIntNum(i.encryptedLinkageProof.length),n.write(i.encryptedLinkageProof),n.writeUInt8(i.proofType);let c=new ti;return c.writeUInt8(0),c.write(n.toArray()),c.toArray()}case"acquireCertificate":{let e={},r=t.read(32);e.type=e5(r);let i=t.read(33);e.certifier=e0(i);let n=t.readVarIntNum();e.fields={};for(let r=0;r<n;r++){let r=t.readVarIntNum(),i=t.read(r),n=e4(i),a=t.readVarIntNum(),s=t.read(a),o=e4(s);e.fields[n]=o}let s=t.readInt8();-1===s?e.privileged=void 0:e.privileged=1===s;let o=t.readInt8();if(-1===o)e.privilegedReason=void 0;else{let r=t.read(o);e.privilegedReason=e4(r)}let c=t.readUInt8();if(e.acquisitionProtocol=1===c?"direct":"issuance","direct"===e.acquisitionProtocol){let r=t.read(32);e.serialNumber=e5(r),e.revocationOutpoint=this.decodeOutpoint(t);let i=t.readVarIntNum(),n=t.read(i);e.signature=e0(n);let a=t.readUInt8();if(11===a)e.keyringRevealer="certifier";else{let r=[a].concat(t.read(32));e.keyringRevealer=e0(r)}let s=t.readVarIntNum();e.keyringForSubject={};for(let r=0;r<s;r++){let r=t.readVarIntNum(),i=t.read(r),n=e4(i),a=t.readVarIntNum(),s=t.read(a),o=e5(s);e.keyringForSubject[n]=o}}else{let r=t.readVarIntNum(),i=t.read(r);e.certifierUrl=e4(i)}let l=await this.wallet.acquireCertificate(e,a),h=new iS(l.type,l.serialNumber,l.subject,l.certifier,l.revocationOutpoint,l.fields,l.signature).toBinary(),u=new ti;return u.writeUInt8(0),u.write(h),u.toArray()}case"listCertificates":{let e={},r=t.readVarIntNum();e.certifiers=[];for(let i=0;i<r;i++){let r=t.read(33);e.certifiers.push(e0(r))}let i=t.readVarIntNum();e.types=[];for(let r=0;r<i;r++){let r=t.read(32);e.types.push(e5(r))}let n=t.readVarIntNum();n>=0?e.limit=n:e.limit=void 0;let s=t.readVarIntNum();s>=0?e.offset=s:e.offset=void 0;let o=t.readInt8();-1===o?e.privileged=void 0:e.privileged=1===o;let c=t.readInt8();if(-1===c)e.privilegedReason=void 0;else{let r=t.read(c);e.privilegedReason=e4(r)}let l=await this.wallet.listCertificates(e,a),h=new ti;for(let e of(h.writeVarIntNum(l.totalCertificates),l.certificates)){let t=new iS(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature).toBinary();if(h.writeVarIntNum(t.length),h.write(t),e.keyring&&Object.keys(e.keyring).length>0){h.writeInt8(1);let t=Object.entries(e.keyring);for(let[e,r]of(h.writeVarIntNum(t.length),t)){let t=e1(e,"utf8");h.writeVarIntNum(t.length),h.write(t);let i=e1(r,"base64");h.writeVarIntNum(i.length),h.write(i)}}else h.writeInt8(0);let r=e1(e.verifier,"hex");h.writeVarIntNum(r.length),h.write(r)}let u=new ti;return u.writeUInt8(0),u.write(h.toArray()),u.toArray()}case"proveCertificate":{let e={},r={},i=t.read(32);r.type=e5(i);let n=t.read(33);r.subject=e0(n);let s=t.read(32);r.serialNumber=e5(s);let o=t.read(33);r.certifier=e0(o),r.revocationOutpoint=this.decodeOutpoint(t);let c=t.readVarIntNum(),l=t.read(c);r.signature=e0(l);let h=t.readVarIntNum();r.fields={};for(let e=0;e<h;e++){let e=t.readVarIntNum(),i=t.read(e),n=e4(i),a=t.readVarIntNum(),s=t.read(a),o=e4(s);r.fields[n]=o}e.certificate=r;let u=t.readVarIntNum();e.fieldsToReveal=[];for(let r=0;r<u;r++){let r=t.readVarIntNum(),i=t.read(r),n=e4(i);e.fieldsToReveal.push(n)}let d=t.read(33);e.verifier=e0(d);let f=t.readInt8();-1===f?e.privileged=void 0:e.privileged=1===f;let p=t.readInt8();if(-1===p)e.privilegedReason=void 0;else{let r=t.read(p);e.privilegedReason=e4(r)}let g=await this.wallet.proveCertificate(e,a),b=new ti,y=Object.entries(g.keyringForVerifier);for(let[e,t]of(b.writeVarIntNum(y.length),y)){let r=e1(e,"utf8");b.writeVarIntNum(r.length),b.write(r);let i=e1(t,"base64");b.writeVarIntNum(i.length),b.write(i)}let m=new ti;return m.writeUInt8(0),m.write(b.toArray()),m.toArray()}case"relinquishCertificate":{let e={},r=t.read(32);e.type=e5(r);let i=t.read(32);e.serialNumber=e5(i);let n=t.read(33);e.certifier=e0(n),await this.wallet.relinquishCertificate(e,a);let s=new ti;return s.writeUInt8(0),s.toArray()}case"discoverByIdentityKey":{let e={},r=t.read(33);e.identityKey=e0(r);let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByIdentityKey(e,a),c=this.serializeDiscoveryResult(o),l=new ti;return l.writeUInt8(0),l.write(c),l.toArray()}case"discoverByAttributes":{let e={},r=t.readVarIntNum();e.attributes={};for(let i=0;i<r;i++){let r=t.readVarIntNum(),i=t.read(r),n=e4(i),a=t.readVarIntNum(),s=t.read(a),o=e4(s);e.attributes[n]=o}let i=t.readVarIntNum();i>=0?e.limit=i:e.limit=void 0;let n=t.readVarIntNum();n>=0?e.offset=n:e.offset=void 0;let s=t.readInt8();s>=0?e.seekPermission=1===s:e.seekPermission=void 0;let o=await this.wallet.discoverByAttributes(e,a),c=this.serializeDiscoveryResult(o),l=new ti;return l.writeUInt8(0),l.write(c),l.toArray()}default:throw Error(`Method ${r} not implemented`)}}catch(i){let e=new ti;e.writeUInt8("number"==typeof i.code?i.code:1);let t=e1("string"==typeof i.message?i.message:"Unknown error","utf8");e.writeVarIntNum(t.length),e.write(t);let r=e1("string"==typeof i.stack?i.stack:"","utf8");return e.writeVarIntNum(r.length),e.write(r),e.toArray()}}decodeProtocolID(e){let t=e.readUInt8(),r=e.readVarIntNum();return[t,e4(e.read(r))]}decodeString(e){let t=e.readVarIntNum();return e4(e.read(t))}decodeCounterparty(e){let t=e.readUInt8();return 11===t?"self":12===t?"anyone":0!==t?e0([t,...e.read(32)]):void 0}serializeDiscoveryResult(e){let t=new ti;for(let r of(t.writeVarIntNum(e.totalCertificates),e.certificates)){let e=new iS(r.type,r.serialNumber,r.subject,r.certifier,r.revocationOutpoint,r.fields,r.signature).toBinary();t.writeVarIntNum(e.length),t.write(e);let i=e1(r.certifierInfo.name,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e1(r.certifierInfo.iconUrl,"utf8");t.writeVarIntNum(n.length),t.write(n);let a=e1(r.certifierInfo.description,"utf8");t.writeVarIntNum(a.length),t.write(a),t.writeUInt8(r.certifierInfo.trust);let s=Object.entries(r.publiclyRevealedKeyring);for(let[e,r]of(t.writeVarIntNum(s.length),s)){let i=e1(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e1(r,"base64");t.writeVarIntNum(n.length),t.write(n)}let o=Object.entries(r.decryptedFields);for(let[e,r]of(t.writeVarIntNum(o.length),o)){let i=e1(e,"utf8");t.writeVarIntNum(i.length),t.write(i);let n=e1(r,"utf8");t.writeVarIntNum(n.length),t.write(n)}}return t.toArray()}decodeKeyRelatedParams(e){let t={};t.protocolID=this.decodeProtocolID(e);let r=e.readVarIntNum();t.keyID=e4(e.read(r)),t.counterparty=this.decodeCounterparty(e);let i=e.readInt8();-1===i?t.privileged=void 0:t.privileged=1===i;let n=e.readInt8();return -1===n?t.privilegedReason=void 0:t.privilegedReason=e4(e.read(n)),t}}class ng extends iS{masterKeyring;constructor(e,t,r,i,n,a,s,o){for(let c of(super(e,t,r,i,n,a,o),Object.keys(a)))if(void 0===s[c]||""===s[c])throw Error(`Master keyring must contain a value for every field. Missing or empty key for field: "${c}".`);this.masterKeyring=s}static async createCertificateFields(e,t,r,i,n){let a={},s={};for(let[o,c]of Object.entries(r)){let r=rt.fromRandom(),l=r.encrypt(e1(c,"utf8"));a[o]=e5(l);let{ciphertext:h}=await e.encrypt({plaintext:r.toArray(),...iS.getCertificateFieldEncryptionDetails(o),counterparty:t,privileged:i,privilegedReason:n});s[o]=e5(h)}return{certificateFields:a,masterKeyring:s}}static async createKeyringForVerifier(e,t,r,i,n,a,s,o,c){if(!Array.isArray(n))throw Error("fieldsToReveal must be an array of strings");let l={};for(let h of n){if(void 0===i[h]||null===i[h]||""===i[h])throw Error(`Fields to reveal must be a subset of the certificate fields. Missing the "${h}" field.`);let n=(await this.decryptField(e,a,h,i[h],t,o,c)).fieldRevelationKey,{ciphertext:u}=await e.encrypt({plaintext:n,...iS.getCertificateFieldEncryptionDetails(h,s),counterparty:r,privileged:o,privilegedReason:c});l[h]=e5(u)}return l}static async issueCertificateForSubject(e,t,r,i,n=async e=>"00".repeat(32),a){let s=a??e5(tq(32)),{certificateFields:o,masterKeyring:c}=await this.createCertificateFields(e,t,r),l=await n(s),h=new ng(i,s,"self"===t?(await e.getPublicKey({identityKey:!0})).publicKey:t,(await e.getPublicKey({identityKey:!0})).publicKey,l,o,c);return await h.sign(e),h}static async decryptFields(e,t,r,i,n,a){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let s={};for(let o of Object.keys(r))s[o]=(await this.decryptField(e,t,o,r[o],i,n,a)).decryptedFieldValue;return s}catch{throw Error("Failed to decrypt all master certificate fields.")}}static async decryptField(e,t,r,i,n,a,s){if(null==t||0===Object.keys(t).length)throw Error("A MasterCertificate must have a valid masterKeyring!");try{let{plaintext:o}=await e.decrypt({ciphertext:e1(t[r],"base64"),...iS.getCertificateFieldEncryptionDetails(r),counterparty:n,privileged:a,privilegedReason:s}),c=new rt(o).decrypt(e1(i,"base64"));return{fieldRevelationKey:o,decryptedFieldValue:e4(c)}}catch{throw Error("Failed to decrypt certificate field!")}}}class nb extends iS{keyring;decryptedFields;constructor(e,t,r,i,n,a,s,o,c){super(e,t,r,i,n,a,o),this.keyring=s,this.decryptedFields=c}static fromCertificate(e,t){return new nb(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,r,i){if(null==this.keyring||0===Object.keys(this.keyring).length)throw Error("A keyring is required to decrypt certificate fields for the verifier.");try{let n={};for(let a in this.keyring){let{plaintext:s}=await e.decrypt({ciphertext:e1(this.keyring[a],"base64"),...iS.getCertificateFieldEncryptionDetails(a,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:r},i),o=new rt(s).decrypt(e1(this.fields[a],"base64"));n[a]=e4(o)}return n}catch(e){throw Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}class ny extends im{keyDeriver;constructor(e){if(super(e),e instanceof ig)this.keyDeriver=e;else if("string"==typeof e||e instanceof tW)this.keyDeriver=new ib(e);else throw Error("Invalid key deriver provided")}async isAuthenticated(){throw Error("not implemented")}async waitForAuthentication(){throw Error("not implemented")}async getNetwork(){throw Error("not implemented")}async getVersion(){throw Error("not implemented")}async getPublicKey(e){if(!0===e.privileged)throw Error("no privilege support");if(!0===e.identityKey){if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.rootKey.toPublicKey().toString()}}if(null==e.protocolID||"string"!=typeof e.keyID||""===e.keyID.trim())throw Error("protocolID and keyID are required if identityKey is false or undefined.");if(null===this.keyDeriver||void 0===this.keyDeriver)throw Error("keyDeriver is not initialized");return{publicKey:this.keyDeriver.derivePublicKey(e.protocolID,e.keyID,"string"==typeof e.counterparty&&""!==e.counterparty.trim()?e.counterparty:"self",!!e.forSelf).toString()}}async createAction(){throw Error("not implemented")}async signAction(){throw Error("not implemented")}async abortAction(){throw Error("not implemented")}async listActions(){throw Error("not implemented")}async internalizeAction(){throw Error("not implemented")}async listOutputs(){throw Error("not implemented")}async relinquishOutput(){throw Error("not implemented")}async acquireCertificate(){throw Error("not implemented")}async listCertificates(){throw Error("not implemented")}async proveCertificate(){throw Error("not implemented")}async relinquishCertificate(){throw Error("not implemented")}async discoverByIdentityKey(){throw Error("not implemented")}async discoverByAttributes(){throw Error("not implemented")}async getHeight(){throw Error("not implemented")}async getHeaderForHeight(){throw Error("not implemented")}}class nm{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw Error("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){let t,r=this.sessionNonceToSession.get(e);if(null!=r)return r;let i=this.identityKeyToNonces.get(e);if(null!=i&&0!==i.size){for(let e of i){let r=this.sessionNonceToSession.get(e);null!=r&&(null==t?t=r:(r.lastUpdate??0)>(t.lastUpdate??0)&&(t=r))}return t}}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;let t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}async function nw(e,t,r="self",i){let n=e1(e,"base64"),a=n.slice(0,16),s=n.slice(16),{valid:o}=await t.verifyHmac({data:a,hmac:s,protocolID:[2,"server hmac"],keyID:e4(a),counterparty:r},i);return o}async function nv(e,t="self",r){let i=tq(16),{hmac:n}=await e.createHmac({protocolID:[2,"server hmac"],keyID:e4(i),data:i,counterparty:t},r);return e5([...i,...n])}let nI=async(e,t,r,i)=>{let n=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},i);return await Promise.all(n.certificates.map(async n=>{let{keyringForVerifier:a}=await e.proveCertificate({certificate:n,fieldsToReveal:t.types[n.type],verifier:r},i);return new nb(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,a,n.signature)}))},nk=async(e,t,r,i)=>{if(null==t.certificates||0===t.certificates.length)throw Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async n=>{if(n.subject!==t.identityKey)throw Error(`The subject of one of your certificates ("${n.subject}") is not the same as the request sender ("${t.identityKey}").`);let a=new nb(n.type,n.serialNumber,n.subject,n.certifier,n.revocationOutpoint,n.fields,n.keyring,n.signature);if(!await a.verify())throw Error(`The signature for the certificate with serial number ${a.serialNumber} is invalid!`);if(null!=r){let{certifiers:e,types:t}=r;if(!e.includes(a.certifier))throw Error(`Certificate with serial number ${a.serialNumber} has an unrequested certifier: ${a.certifier}`);if(null==t[a.type])throw Error(`Certificate with type ${a.type} was not requested`)}await a.decryptFields(e,void 0,void 0,i)}))},nS="undefined"!=typeof globalThis?globalThis.Buffer:void 0;class nx{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;constructor(e,t,r,i,n,a){this.wallet=e,this.originator=a,this.transport=t,this.certificatesToRequest=r??{certifiers:[],types:{}},this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e=>{throw e}),this.sessionManager=null!=i?i:new nm,!1===n?this.autoPersistLastSession=!1:this.autoPersistLastSession=!0}async toPeer(e,t,r){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=e5(tq(32)),{signature:a}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:n,yourNonce:i.peerNonce,payload:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async requestCertificates(e,t,r=1e4){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);let i=await this.getAuthenticatedSession(t,r),n=e5(tq(32)),{signature:a}=await this.wallet.createSignature({data:nx.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${n} ${i.peerNonce??""}`,counterparty:i.peerIdentityKey},this.originator),s={version:"0.1",messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:n,initialNonce:i.sessionNonce,yourNonce:i.peerNonce,requestedCertificates:e,signature:a};i.lastUpdate=Date.now(),this.sessionManager.updateSession(i);try{await this.transport.send(s)}catch(e){this.propagateTransportError(i.peerIdentityKey,e)}}async getAuthenticatedSession(e,t){let r;if(void 0===this.transport)throw Error("Peer transport is not connected!");if("string"==typeof e&&(r=this.sessionManager.getSession(e)),null==r||!r.isAuthenticated){let i=await this.initiateHandshake(e,t);if(null==(r=this.sessionManager.getSession(i))||!r.isAuthenticated)throw Error("Unable to establish mutual authentication with peer!")}return r}listenForGeneralMessages(e){let t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){let t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){let t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e,t=1e4){let r=await nv(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:r,peerIdentityKey:e,lastUpdate:i});let n={version:"0.1",messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:r,requestedCertificates:this.certificatesToRequest};return await this.transport.send(n),await this.waitForInitialResponse(r,t)}async waitForInitialResponse(e,t=1e4){return await new Promise((r,i)=>{let n=this.listenForInitialResponse(e,e=>{clearTimeout(a),this.stopListeningForInitialResponses(n),r(e)}),a=setTimeout(()=>{this.stopListeningForInitialResponses(n),i(Error("Initial response timed out."))},t)})}listenForInitialResponse(e,t){let r=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(r,{callback:t,sessionNonce:e}),r}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){let r=t.details;null!=r&&"object"==typeof r?null==r.peerIdentityKey&&(r.peerIdentityKey=e):t.details={peerIdentityKey:e}}throw t}throw Error(`Failed to send message to peer ${e??"unknown"}: ${String(t)}`)}async handleIncomingMessage(e){if("string"!=typeof e.version||"0.1"!==e.version)throw Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: 0.1`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){let t;if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw Error("Missing required fields in initialRequest message.");let r=await nv(this.wallet,void 0,this.originator),i=Date.now();this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:r,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:i}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0&&(this.onCertificateRequestReceivedCallbacks.size>0?this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)}):t=await nI(this.wallet,e.requestedCertificates,e.identityKey,this.originator));let{signature:n}=await this.wallet.createSignature({data:[...nx.base64ToBytes(e.initialNonce),...nx.base64ToBytes(r)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${r}`,counterparty:e.identityKey},this.originator),a={version:"0.1",messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:r,yourNonce:e.initialNonce,certificates:t,requestedCertificates:this.certificatesToRequest,signature:n};void 0===this.lastInteractedWithPeer&&(this.lastInteractedWithPeer=e.identityKey),await this.transport.send(a)}async processInitialResponse(e){if(!await nw(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Peer session not found for peer: ${e.identityKey}`);let r=nx.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:i}=await this.wallet.verifySignature({data:r,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!i)throw Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);if(t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.certificatesToRequest?.certifiers?.length>0&&e.certificates?.length>0&&(await nk(this.wallet,e,this.certificatesToRequest,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>t(e.identityKey,e.certificates))),this.lastInteractedWithPeer=e.identityKey,this.onInitialResponseReceivedCallbacks.forEach(e=>{e.sessionNonce===t.sessionNonce&&e.callback(t.sessionNonce)}),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nI(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async processCertificateRequest(e){if(!await nw(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:nx.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)this.onCertificateRequestReceivedCallbacks.forEach(t=>{t(e.identityKey,e.requestedCertificates)});else{let t=await nI(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){let r=await this.getAuthenticatedSession(e),i=e5(tq(32)),{signature:n}=await this.wallet.createSignature({data:nx.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${i} ${r.peerNonce??""}`,counterparty:r.peerIdentityKey},this.originator),a={version:"0.1",messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:i,initialNonce:r.sessionNonce,yourNonce:r.peerNonce,certificates:t,signature:n};r.lastUpdate=Date.now(),this.sessionManager.updateSession(r);try{await this.transport.send(a)}catch(e){this.propagateTransportError(r.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await nw(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:nx.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);await nk(this.wallet,e,e.requestedCertificates,this.originator),this.onCertificatesReceivedCallbacks.forEach(t=>{t(e.identityKey,e.certificates??[])}),t.lastUpdate=Date.now(),this.sessionManager.updateSession(t)}async processGeneralMessage(e){if(!await nw(e.yourNonce,this.wallet,void 0,this.originator))throw Error(`Unable to verify nonce for general message from: ${e.identityKey}`);let t=this.sessionManager.getSession(e.yourNonce);if(null==t)throw Error(`Session not found for nonce: ${e.yourNonce}`);let{valid:r}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!r)throw Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey,this.onGeneralMessageReceivedCallbacks.forEach(t=>{t(e.identityKey,e.payload??[])})}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;let{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=nS?Array.from(nS.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from(new TextEncoder().encode(e)):e1(e,"utf8")}static base64ToBytes(e){return null!=nS?Array.from(nS.from(e,"base64")):e1(e,"base64")}}let nE="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch;class nP{onDataCallback;fetchClient;baseUrl;constructor(e,t=nE){if("function"!=typeof t)throw Error("SimplifiedFetchTransport requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=t,this.baseUrl=e}async send(e){if(null==this.onDataCallback)throw Error("Listen before you start speaking. God gave you two ears and one mouth for a reason.");if("general"!==e.messageType)return await new Promise((t,r)=>{(async()=>{try{let r=`${this.baseUrl}/.well-known/auth`,i=(async()=>{try{return await this.fetchClient(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){throw this.createNetworkError(r,e)}})();"initialRequest"!==e.messageType&&t();let n=await i;if(!n.ok){let e=Array.from(new Uint8Array(await n.arrayBuffer()));throw this.createUnauthenticatedResponseError(r,n,e)}if(null!=this.onDataCallback){let e=await n.json();this.onDataCallback(e)}"initialRequest"===e.messageType&&t()}catch(e){r(e)}})()});{let t,r,i=this.deserializeRequestPayload(e.payload),n=`${this.baseUrl}${i.urlPostfix}`;if("object"!=typeof i.headers&&(i.headers={}),i.headers["x-bsv-auth-version"]=e.version,i.headers["x-bsv-auth-identity-key"]=e.identityKey,i.headers["x-bsv-auth-nonce"]=e.nonce,i.headers["x-bsv-auth-your-nonce"]=e.yourNonce,i.headers["x-bsv-auth-signature"]=e0(e.signature),i.headers["x-bsv-auth-request-id"]=i.requestId,null!=i.body){let e=i.headers;if(null==e["content-type"])throw Error("Content-Type header is required for requests with a body.");let t=String(e["content-type"]??"");t.includes("application/json")||t.includes("application/x-www-form-urlencoded")||t.includes("text/plain")?i.body=e4(i.body):i.body=new Uint8Array(i.body)}try{t=await this.fetchClient(n,{method:i.method,headers:i.headers,body:i.body})}catch(e){throw this.createNetworkError(n,e)}let a=Array.from(new Uint8Array(await t.arrayBuffer())),s=["x-bsv-auth-version","x-bsv-auth-identity-key","x-bsv-auth-signature"].filter(e=>{let r=t.headers.get(e);return null==r||0===r.trim().length});if(s.length>0)throw this.createUnauthenticatedResponseError(n,t,a,s);let o=t.headers.get("x-bsv-auth-requested-certificates");if(null!=o)try{r=JSON.parse(o)}catch(e){throw this.createMalformedHeaderError(n,"x-bsv-auth-requested-certificates",o,e)}let c=new ti;null!=t.headers.get("x-bsv-auth-request-id")&&c.write(e1(t.headers.get("x-bsv-auth-request-id"),"base64")),c.writeVarIntNum(t.status);let l=[];t.headers.forEach((e,t)=>{let r=t.toLowerCase();(r.startsWith("x-bsv-")||"authorization"===r)&&!r.startsWith("x-bsv-auth")&&l.push([r,e])}),l.sort(([e],[t])=>e.localeCompare(t)),c.writeVarIntNum(l.length);for(let e=0;e<l.length;e++){let t=e1(l[e][0],"utf8");c.writeVarIntNum(t.length),c.write(t);let r=e1(l[e][1],"utf8");c.writeVarIntNum(r.length),c.write(r)}c.writeVarIntNum(a.length),a.length>0&&c.write(a);let h={version:t.headers.get("x-bsv-auth-version"),messageType:"certificateRequest"===t.headers.get("x-bsv-auth-message-type")?"certificateRequest":"general",identityKey:t.headers.get("x-bsv-auth-identity-key"),nonce:t.headers.get("x-bsv-auth-nonce")??void 0,yourNonce:t.headers.get("x-bsv-auth-your-nonce")??void 0,requestedCertificates:r,payload:c.toArray(),signature:e1(t.headers.get("x-bsv-auth-signature"),"hex")};if(null==h.version)throw this.createUnauthenticatedResponseError(n,t,a);this.onDataCallback(h)}}async onData(e){this.onDataCallback=t=>{e(t)}}createNetworkError(e,t){let r=`Network error while sending authenticated request to ${e}`;if(t instanceof Error){let e=Error(`${r}: ${t.message}`);return e.stack=t.stack,e.cause=t,e}return Error(`${r}: ${String(t)}`)}createUnauthenticatedResponseError(e,t,r,i=[]){let n=(t.statusText??"").trim(),a=n.length>0?`${t.status} ${n}`:`${t.status}`,s=i.length>0?`missing headers: ${i.join(", ")}`:"response lacked required BSV auth headers",o=this.getBodyPreview(r,t.headers.get("content-type")),c=[`Received HTTP ${a} from ${e} without valid BSV authentication (${s})`];null!=o&&c.push(`body preview: ${o}`);let l=Error(c.join(" - "));return l.details={url:e,status:t.status,statusText:t.statusText,missingHeaders:i,bodyPreview:o},l}createMalformedHeaderError(e,t,r,i){let n=`Failed to parse ${t} returned by ${e}: ${r}`;if(i instanceof Error){let e=Error(`${n}. ${i.message}`);return e.stack=i.stack,e.cause=i,e}return Error(`${n}. ${String(i)}`)}getBodyPreview(e,t){let r;if(0===e.length)return;let i=e.length>1024,n=i?e.slice(0,1024):e;if(this.isTextualContent(t,n))try{r=e4(n)}catch{r=this.formatBinaryPreview(n,i)}else r=this.formatBinaryPreview(n,i);return r.length>512&&(r=`${r.slice(0,512)}…`),i&&(r=`${r} (truncated)`),r}isTextualContent(e,t){if(0===t.length)return!1;if(null!=e){let t=e.toLowerCase();if(["application/json","application/problem+json","application/xml","application/xhtml+xml","application/javascript","application/ecmascript","application/x-www-form-urlencoded","text/"].some(e=>t.includes(e))||t.includes("charset="))return!0}return t.reduce((e,t)=>9===t||10===t||13===t||t>=32&&t<=126?e+1:e,0)/t.length>.8}formatBinaryPreview(e,t){let r=e.map(e=>e.toString(16).padStart(2,"0")).join("");return`0x${r}${t?"…":""}`}deserializeRequestPayload(e){let t,r=new tn(e),i=e5(r.read(32)),n=r.readVarIntNum(),a="GET";n>0&&(a=e4(r.read(n)));let s=r.readVarIntNum(),o="";s>0&&(o=e4(r.read(s)));let c=r.readVarIntNum(),l="";c>0&&(l=e4(r.read(c)));let h={},u=r.readVarIntNum();if(u>0)for(let e=0;e<u;e++){let e=r.readVarIntNum(),t=e4(r.read(e)),i=r.readVarIntNum(),n=e4(r.read(i));h[t]=n}let d=r.readVarIntNum();return d>0&&(t=r.read(d)),{urlPostfix:o+l,method:a,headers:h,body:t,requestId:i}}}class nN{sessionManager;wallet;callbacks={};certificatesReceived=[];requestedCertificates;originator;peers={};constructor(e,t,r,i){this.wallet=e,this.requestedCertificates=t,this.sessionManager=r??new nm,this.originator=i}async fetch(e,t={}){if("number"==typeof t.retryCounter){if(t.retryCounter<=0)throw Error("Request failed after maximum number of retries.");t.retryCounter--}let r=await new Promise(async(r,i)=>{try{let n,{method:a="GET",headers:s={},body:o}=t,c=new URL(e),l=c.origin;if(void 0===this.peers[l]){let e=new nP(l);n={peer:new nx(this.wallet,e,this.requestedCertificates,this.sessionManager,void 0,this.originator),pendingCertificateRequests:[]},this.peers[l]=n,this.peers[l].peer.listenForCertificatesReceived((e,t)=>{this.certificatesReceived.push(...t)}),this.peers[l].peer.listenForCertificatesRequested(async(e,t)=>{try{this.peers[l].pendingCertificateRequests.push(!0);let r=await nI(this.wallet,t,e,this.originator);await this.peers[l].peer.sendCertificateResponse(e,r)}finally{await new Promise(e=>setTimeout(e,500)),this.peers[l].pendingCertificateRequests.shift()}})}else{if(!1===this.peers[l].supportsMutualAuth){try{let i=await this.handleFetchAndValidate(e,t,this.peers[l]);r(i)}catch(e){i(e)}return}n=this.peers[l]}let h=tq(32),u=e5(h),d=await this.serializeRequest(a,s,o,c,h);this.callbacks[u]={resolve:r,reject:i};let f=n.peer.listenForGeneralMessages((e,t)=>{let r,i=new tn(t);if(e5(i.read(32))!==u)return;n.peer.stopListeningForGeneralMessages(f),this.peers[l].identityKey=e,this.peers[l].supportsMutualAuth=!0;let a=i.readVarIntNum(),s={},o=i.readVarIntNum();if(o>0)for(let e=0;e<o;e++){let e=i.readVarIntNum(),t=i.read(e),r=e4(t),n=i.readVarIntNum(),a=i.read(n),o=e4(a);s[r]=o}s["x-bsv-auth-identity-key"]=e;let c=i.readVarIntNum();c>0&&(r=i.read(c));let h=new Response(r?new Uint8Array(r):null,{status:a,statusText:`${a}`,headers:new Headers(s)});this.callbacks[u].resolve(h),delete this.callbacks[u]});n.pendingCertificateRequests.length>0&&await new Promise(e=>{setInterval(()=>{0===n.pendingCertificateRequests.length&&e()},100)}),await n.peer.toPeer(d.toArray(),n.identityKey).catch(async a=>{if(a.message.includes("Session not found for nonce")){delete this.peers[l],t.retryCounter??=3;let i=await this.fetch(e,t);r(i);return}if(a.message.includes("HTTP server failed to authenticate"))try{let i=await this.handleFetchAndValidate(e,t,n);r(i);return}catch(e){i(e)}else i(a)})}catch(e){i(e)}});return 402===r.status?await this.handlePaymentAndRetry(e,t,r):r}async sendCertificateRequest(e,t){let r,i=new URL(e).origin;if(void 0!==this.peers[i])r={peer:this.peers[i].peer};else{let e=new nP(i);r={peer:new nx(this.wallet,e,this.requestedCertificates,this.sessionManager,this.originator)},this.peers[i]=r}return await new Promise(async(e,i)=>{let n=r.peer.listenForCertificatesReceived((t,i)=>{r.peer.stopListeningForCertificatesReceived(n),this.certificatesReceived.push(...i),e(i)});try{await r.peer.requestCertificates(t,r.identityKey)}catch(e){r.peer.stopListeningForCertificatesReceived(n),i(e)}})}consumeReceivedCertificates(){return this.certificatesReceived.splice(0)}async serializeRequest(e,t,r,i,n){let a=new ti;if(a.write(n),a.writeVarIntNum(e.length),a.write(e1(e)),i.pathname.length>0){let e=e1(i.pathname);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);if(i.search.length>0){let e=e1(i.search);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);let s=[];for(let[e,r]of Object.entries(t))if((e=e.toLowerCase()).startsWith("x-bsv-")||"authorization"===e){if(e.startsWith("x-bsv-auth"))throw Error("No BSV auth headers allowed here!");s.push([e,r])}else if(e.startsWith("content-type"))r=r.split(";")[0].trim(),s.push([e,r]);else throw Error("Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.");s.sort(([e],[t])=>e.localeCompare(t)),a.writeVarIntNum(s.length);for(let e=0;e<s.length;e++){let t=e1(s[e][0],"utf8");a.writeVarIntNum(t.length),a.write(t);let r=e1(s[e][1],"utf8");a.writeVarIntNum(r.length),a.write(r)}if(["POST","PUT","PATCH","DELETE"].includes(e.toUpperCase())&&void 0===r){let e=s.find(([e])=>"content-type"===e);r=e&&e[1].includes("application/json")?"{}":""}if(r){let e=await this.normalizeBodyToNumberArray(r);a.writeVarIntNum(e.length),a.write(e)}else a.writeVarIntNum(-1);return a}async handleFetchAndValidate(e,t,r){let i=await fetch(e,t);if(i.headers.forEach(e=>{if(e.toLocaleLowerCase().startsWith("x-bsv"))throw Error("The server is trying to claim it has been authenticated when it has not!")}),i.ok)return r.supportsMutualAuth=!1,i;throw Error(`Request failed with status: ${i.status}`)}async handlePaymentAndRetry(e,t={},r){let i=r.headers.get("x-bsv-payment-version");if(!i||"1.0"!==i)throw Error(`Unsupported x-bsv-payment-version response header. Client version: 1.0, Server version: ${i}`);let n=r.headers.get("x-bsv-payment-satoshis-required");if(!n)throw Error("Missing x-bsv-payment-satoshis-required response header.");let a=parseInt(n);if(isNaN(a)||a<=0)throw Error("Invalid x-bsv-payment-satoshis-required response header value.");let s=r.headers.get("x-bsv-auth-identity-key");if("string"!=typeof s)throw Error("Missing x-bsv-auth-identity-key response header.");let o=r.headers.get("x-bsv-payment-derivation-prefix");if("string"!=typeof o||o.length<1)throw Error("Missing x-bsv-payment-derivation-prefix response header.");let c=t.paymentContext;if(null!=c?this.isPaymentContextCompatible(c,a,s,o)||(this.logPaymentAttempt("warn","Server adjusted payment requirements; regenerating transaction",this.composePaymentLogDetails(e,c)),c=await this.createPaymentContext(e,t,a,s,o)):c=await this.createPaymentContext(e,t,a,s,o),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,Error("Maximum payment attempts exceeded before retrying"));let l={...t.headers??{}};l["x-bsv-payment"]=JSON.stringify({derivationPrefix:c.derivationPrefix,derivationSuffix:c.derivationSuffix,transaction:c.transactionBase64});let h={...t,headers:l,paymentContext:c};"number"!=typeof h.retryCounter&&(h.retryCounter=3);let u=c.attempts+1,d=c.maxAttempts;c.attempts=u;let f=this.composePaymentLogDetails(e,c);this.logPaymentAttempt("warn",`Attempting paid request (${u}/${d})`,f);try{let t=await this.fetch(e,h);return this.logPaymentAttempt("info",`Paid request attempt ${u} succeeded`,f),t}catch(n){let t=this.createPaymentErrorEntry(c.attempts,n);if(c.errors.push(t),this.logPaymentAttempt("error",`Paid request attempt ${u} failed`,{...f,error:{message:t.message,stack:t.stack}}),c.attempts>=c.maxAttempts)throw this.buildPaymentFailureError(e,c,n);let i=this.getPaymentRetryDelay(c.attempts);return await this.wait(i),this.handlePaymentAndRetry(e,h,r)}}isPaymentContextCompatible(e,t,r,i){return e.satoshisRequired===t&&e.serverIdentityKey===r&&e.derivationPrefix===i}async createPaymentContext(e,t,r,i,n){let a=await nv(this.wallet,void 0,this.originator),{publicKey:s}=await this.wallet.getPublicKey({protocolID:[2,"3241645161d8"],keyID:`${n} ${a}`,counterparty:i},this.originator),o=new rx().lock(tL.fromString(s).toAddress()).toHex(),{tx:c}=await this.wallet.createAction({description:`Payment for request to ${new URL(e).origin}`,outputs:[{satoshis:r,lockingScript:o,customInstructions:JSON.stringify({derivationPrefix:n,derivationSuffix:a,payee:i}),outputDescription:"HTTP request payment"}],options:{randomizeOutputs:!1}},this.originator),{publicKey:l}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return{satoshisRequired:r,transactionBase64:e5(c),derivationPrefix:n,derivationSuffix:a,serverIdentityKey:i,clientIdentityKey:l,attempts:0,maxAttempts:this.getMaxPaymentAttempts(t),errors:[],requestSummary:this.buildPaymentRequestSummary(e,t)}}getMaxPaymentAttempts(e){let t="number"==typeof e.paymentRetryAttempts?e.paymentRetryAttempts:void 0;return"number"==typeof t&&t>0?Math.floor(t):3}buildPaymentRequestSummary(e,t){let r={...t.headers??{}},i="string"==typeof t.method?t.method.toUpperCase():"GET",n=this.describeRequestBodyForLogging(t.body);return{url:e,method:i,headers:r,bodyType:n.type,bodyByteLength:n.byteLength}}describeRequestBodyForLogging(e){if(null==e)return{type:"none",byteLength:0};if("string"==typeof e)return{type:"string",byteLength:e1(e,"utf8").length};if(Array.isArray(e))return e.every(e=>"number"==typeof e)?{type:"number[]",byteLength:e.length}:{type:"array",byteLength:e.length};if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer)return{type:"ArrayBuffer",byteLength:e.byteLength};if("undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e))return{type:null!=e.constructor?e.constructor.name:"TypedArray",byteLength:e.byteLength};if("undefined"!=typeof Blob&&e instanceof Blob)return{type:"Blob",byteLength:e.size};if("undefined"!=typeof FormData&&e instanceof FormData)return{type:"FormData",byteLength:0};if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return{type:"URLSearchParams",byteLength:e1(e.toString(),"utf8").length};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{type:"ReadableStream",byteLength:0};try{let t=JSON.stringify(e);if("string"==typeof t)return{type:"object",byteLength:e1(t,"utf8").length}}catch(e){}return{type:typeof e,byteLength:0}}composePaymentLogDetails(e,t){return{url:e,request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors}}logPaymentAttempt(e,t,r){let i="[AuthFetch][Payment]";"error"===e?console.error(`${i} ${t}`,r):"warn"===e?console.warn(`${i} ${t}`,r):"function"==typeof console.info?console.info(`${i} ${t}`,r):console.log(`${i} ${t}`,r)}createPaymentErrorEntry(e,t){let r={attempt:e,timestamp:new Date().toISOString(),message:"",stack:void 0};return t instanceof Error?(r.message=t.message,r.stack=t.stack??void 0):r.message=String(t),r}getPaymentRetryDelay(e){return 250*Math.min(e,5)}async wait(e){e<=0||await new Promise(t=>setTimeout(t,e))}buildPaymentFailureError(e,t,r){let i=Error(`Paid request to ${e} failed after ${t.attempts}/${t.maxAttempts} attempts. Sent ${t.satoshisRequired} satoshis to ${t.serverIdentityKey}.`);return i.details={request:t.requestSummary,payment:{satoshis:t.satoshisRequired,transactionBase64:t.transactionBase64,derivationPrefix:t.derivationPrefix,derivationSuffix:t.derivationSuffix,serverIdentityKey:t.serverIdentityKey,clientIdentityKey:t.clientIdentityKey},attempts:{used:t.attempts,max:t.maxAttempts},errors:t.errors},r instanceof Error&&(i.cause=r),i}async normalizeBodyToNumberArray(e){if(null==e)return[];if("object"==typeof e)return e1(JSON.stringify(e,"utf8"));if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if("string"==typeof e)return e1(e,"utf8");if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(new Uint8Array(e instanceof ArrayBuffer?e:e.buffer));if(e instanceof Blob)return Array.from(new Uint8Array(await e.arrayBuffer()));if(e instanceof FormData){let t=[];return e.forEach((e,r)=>{t.push([r,e.toString()])}),e1(new URLSearchParams(t).toString(),"utf8")}if(e instanceof URLSearchParams)return e1(e.toString(),"utf8");if(e instanceof ReadableStream)throw Error("ReadableStream cannot be directly converted to number[].");throw Error("Unsupported body type in this SimplifiedFetch implementation.")}}class nO{pushDrop;static decode(e){let t=rN.decode(e);if(t.fields.length<4)throw Error("Invalid SHIP/SLAP advertisement!");let r=e4(t.fields[0]);if("SHIP"!==r&&"SLAP"!==r)throw Error("Invalid protocol type!");let i=e0(t.fields[1]);return{protocol:r,identityKey:i,domain:e4(t.fields[2]),topicOrService:e4(t.fields[3])}}constructor(e,t){this.pushDrop=new rN(e,t)}async lock(e,t,r){let{publicKey:i}=await this.pushDrop.wallet.getPublicKey({identityKey:!0});return await this.pushDrop.lock([e1(e,"utf8"),e1(i,"hex"),e1(t,"utf8"),e1(r,"utf8")],[2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}unlock(e){return this.pushDrop.unlock([2,"SHIP"===e?"Service Host Interconnect":"Service Lookup Availability"],"1","self")}}let nA="bsvsdk_overlay_host_reputation_v1";class n_{stats;store;constructor(e){this.stats=new Map,this.store=e??this.getLocalStorageAdapter(),this.loadFromStorage()}reset(){this.stats.clear()}recordSuccess(e,t){let r=this.getOrCreate(e),i=Date.now(),n=Number.isFinite(t)&&t>=0?t:1500;null===r.avgLatencyMs?r.avgLatencyMs=n:r.avgLatencyMs=.75*r.avgLatencyMs+.25*n,r.lastLatencyMs=n,r.totalSuccesses+=1,r.consecutiveFailures=0,r.backoffUntil=0,r.lastUpdatedAt=i,r.lastError=void 0,this.saveToStorage()}recordFailure(e,t){let r=this.getOrCreate(e),i=Date.now();r.totalFailures+=1,r.consecutiveFailures+=1;let n="string"==typeof t?t:t instanceof Error?t.message:void 0;"string"==typeof n&&(n.includes("ERR_NAME_NOT_RESOLVED")||n.includes("ENOTFOUND")||n.includes("getaddrinfo")||n.includes("Failed to fetch"))&&r.consecutiveFailures<3&&(r.consecutiveFailures=3);let a=Math.max(r.consecutiveFailures-2,0);0===a?r.backoffUntil=0:r.backoffUntil=i+Math.min(6e4,1e3*Math.pow(2,a-1)),r.lastUpdatedAt=i,r.lastError="string"==typeof t?t:t instanceof Error?t.message:void 0,this.saveToStorage()}rankHosts(e,t=Date.now()){let r=new Map;e.forEach((e,t)=>{"string"==typeof e&&0!==e.length&&(r.has(e)||r.set(e,t))});let i=Array.from(r.keys()).map(e=>{let i=this.getOrCreate(e);return{...i,score:this.computeScore(i,t),originalOrder:r.get(e)??0}});return i.sort((e,r)=>{let i=e.backoffUntil>t;return i!==r.backoffUntil>t?i?1:-1:e.score!==r.score?e.score-r.score:e.totalSuccesses!==r.totalSuccesses?r.totalSuccesses-e.totalSuccesses:e.originalOrder-r.originalOrder}),i.map(({originalOrder:e,...t})=>t)}snapshot(e){let t=this.stats.get(e);return null!=t?{...t}:void 0}getStorage(){try{let e="object"==typeof globalThis?globalThis:void 0;if(null==e||null==e.localStorage)return;return e.localStorage}catch{return}}getLocalStorageAdapter(){let e=this.getStorage();if(null!=e)return{get:t=>{try{return e.getItem(t)}catch{return null}},set:(t,r)=>{try{e.setItem(t,r)}catch{}}}}loadFromStorage(){let e=this.store;if(null!=e)try{let t=e.get(nA);if("string"!=typeof t||0===t.length)return;let r=JSON.parse(t);if("object"!=typeof r||null===r)return;for(let e of(this.stats.clear(),Object.keys(r))){let t=r[e];if(null!=t&&"object"==typeof t){let r={host:String(t.host??e),totalSuccesses:Number(t.totalSuccesses??0),totalFailures:Number(t.totalFailures??0),consecutiveFailures:Number(t.consecutiveFailures??0),avgLatencyMs:null==t.avgLatencyMs?null:Number(t.avgLatencyMs),lastLatencyMs:null==t.lastLatencyMs?null:Number(t.lastLatencyMs),backoffUntil:Number(t.backoffUntil??0),lastUpdatedAt:Number(t.lastUpdatedAt??0),lastError:"string"==typeof t.lastError?t.lastError:void 0};this.stats.set(r.host,r)}}}catch{}}saveToStorage(){let e=this.store;if(null!=e)try{let t={};for(let[e,r]of this.stats.entries())t[e]=r;e.set(nA,JSON.stringify(t))}catch{}}computeScore(e,t){let r=e.avgLatencyMs??1500,i=400*e.consecutiveFailures,n=Math.min(30*e.totalSuccesses,r/2);return r+i+(e.backoffUntil>t?e.backoffUntil-t:0)-n}getOrCreate(e){let t=this.stats.get(e);return null==t&&(t={host:e,totalSuccesses:0,totalFailures:0,consecutiveFailures:0,avgLatencyMs:null,lastLatencyMs:null,backoffUntil:0,lastUpdatedAt:0},this.stats.set(e,t)),t}}let nT=new n_,nC="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,nR=["https://overlay-us-1.bsvb.tech","https://overlay-eu-1.bsvb.tech","https://overlay-ap-1.bsvb.tech","https://users.bapp.dev"],nB=["https://testnet-users.bapp.dev"];class nV{fetchClient;allowHTTP;constructor(e=nC,t=!1){if("function"!=typeof e)throw Error("HTTPSOverlayLookupFacilitator requires a fetch implementation. In environments without fetch, provide a polyfill or custom implementation.");this.fetchClient=e,this.allowHTTP=t}async lookup(e,t,r=5e3){if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i="undefined"!=typeof AbortController?new AbortController:void 0,n=setTimeout(()=>{try{i?.abort()}catch{}},r);try{let r={method:"POST",headers:{"Content-Type":"application/json","X-Aggregation":"yes"},body:JSON.stringify({service:t.service,query:t.query}),signal:i?.signal},n=await this.fetchClient(`${e}/lookup`,r);if(!n.ok)throw Error(`Failed to facilitate lookup (HTTP ${n.status})`);if("application/octet-stream"!==n.headers.get("content-type"))return await n.json();{let e=await n.arrayBuffer(),t=new tn([...new Uint8Array(e)]),r=t.readVarIntNum(),i=[];for(let e=0;e<r;e++){let e,r=e0(t.read(32)),n=t.readVarIntNum(),a=t.readVarIntNum();a>0&&(e=t.read(a)),i.push({txid:r,outputIndex:n,context:e})}let a=t.read();return{type:"output-list",outputs:i.map(e=>({outputIndex:e.outputIndex,context:e.context,beef:rW.fromBEEF(a,e.txid).toBEEF()}))}}}catch(e){if(e?.name==="AbortError")throw Error("Request timed out");throw e}finally{clearTimeout(n)}}}class nD{facilitator;slapTrackers;hostOverrides;additionalHosts;networkPreset;hostReputation;hostsCache;hostsInFlight;hostsTtlMs;hostsMaxEntries;txMemo;txMemoTtlMs;constructor(e={}){this.networkPreset=e.networkPreset??"mainnet",this.facilitator=e.facilitator??new nV(void 0,"local"===this.networkPreset),this.slapTrackers=e.slapTrackers??("mainnet"===this.networkPreset?nR:nB);let t=e.hostOverrides??{};this.assertValidOverrideServices(t),this.hostOverrides=t,this.additionalHosts=e.additionalHosts??{};let r=e.reputationStorage;"localStorage"===r?this.hostReputation=new n_:"object"==typeof r&&null!==r&&"function"==typeof r.get&&"function"==typeof r.set?this.hostReputation=new n_(r):this.hostReputation=nT,this.hostsTtlMs=e.cache?.hostsTtlMs??3e5,this.hostsMaxEntries=e.cache?.hostsMaxEntries??128,this.txMemoTtlMs=e.cache?.txMemoTtlMs??6e5,this.hostsCache=new Map,this.hostsInFlight=new Map,this.txMemo=new Map}async query(e,t){let r=[];if(r="ls_slap"===e.service?"local"===this.networkPreset?["http://localhost:8080"]:this.slapTrackers:null!=this.hostOverrides[e.service]?this.hostOverrides[e.service]:"local"===this.networkPreset?["http://localhost:8080"]:await this.getCompetentHostsCached(e.service),this.additionalHosts[e.service]?.length>0){let t=this.additionalHosts[e.service],i=new Set(r);for(let e of t)i.has(e)||r.push(e)}if(r.length<1)throw Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${e.service}`);let i=this.prepareHostsForQuery(r,`lookup service ${e.service}`);if(i.length<1)throw Error(`All competent hosts for ${e.service} are temporarily unavailable due to backoff.`);let n=await Promise.allSettled(i.map(async r=>await this.lookupHostWithTracking(r,e,t))),a=new Map,s=e=>"object"!=typeof e?"":e.join(",");for(let e of n){if("fulfilled"!==e.status)continue;let t=e.value;if(t?.type==="output-list"&&Array.isArray(t.outputs))for(let e of t.outputs){let t=s(e.beef),r=this.txMemo.get(t),i=Date.now();if("object"!=typeof r||null===r||r.expiresAt<=i)try{r={txId:rW.fromBEEF(e.beef).id("hex"),expiresAt:i+this.txMemoTtlMs},this.txMemo.size>4096&&this.evictOldest(this.txMemo),this.txMemo.set(t,r)}catch{continue}let n=`${r.txId}.${e.outputIndex}`;a.set(n,e)}}return{type:"output-list",outputs:Array.from(a.values())}}async getCompetentHostsCached(e){let t=Date.now(),r=this.hostsCache.get(e);if("object"==typeof r&&r.expiresAt>t)return r.hosts.slice();if("object"==typeof r&&r.expiresAt<=t)return this.hostsInFlight.has(e)||this.hostsInFlight.set(e,this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)})),r.hosts.slice();if(this.hostsInFlight.has(e))try{let t=await this.hostsInFlight.get(e);if("object"!=typeof t)throw Error("Hosts is not defined.");return t.slice()}catch{}let i=this.refreshHosts(e).finally(()=>{this.hostsInFlight.delete(e)});return this.hostsInFlight.set(e,i),(await i).slice()}async refreshHosts(e){let t=await this.findCompetentHosts(e),r=Date.now()+this.hostsTtlMs;if(!this.hostsCache.has(e)&&this.hostsCache.size>=this.hostsMaxEntries){let e=this.hostsCache.keys().next().value;void 0!==e&&this.hostsCache.delete(e)}return this.hostsCache.set(e,{hosts:t,expiresAt:r}),t}async findCompetentHosts(e){let t={service:"ls_slap",query:{service:e}},r=this.prepareHostsForQuery(this.slapTrackers,"SLAP trackers");if(0===r.length)return[];let i=await Promise.allSettled(r.map(async e=>await this.lookupHostWithTracking(e,t,5e3))),n=new Set;for(let t of i){if("fulfilled"!==t.status)continue;let r=t.value;if("output-list"===r.type)for(let t of r.outputs)try{let r=rW.fromBEEF(t.beef),i=r.outputs[t.outputIndex]?.lockingScript;if("object"!=typeof i||null===i)continue;let a=nO.decode(i);if(a.topicOrService!==e||"SLAP"!==a.protocol)continue;"string"==typeof a.domain&&a.domain.length>0&&n.add(a.domain)}catch{continue}}return[...n]}evictOldest(e){let t=e.keys().next().value;void 0!==t&&e.delete(t)}assertValidOverrideServices(e){for(let t of Object.keys(e))if(!t.startsWith("ls_"))throw Error(`Host override service names must start with "ls_": ${t}`)}prepareHostsForQuery(e,t){if(0===e.length)return[];let r=Date.now(),i=this.hostReputation.rankHosts(e,r),n=i.filter(e=>e.backoffUntil<=r).map(e=>e.host);if(n.length>0)return n;let a=Math.max(Math.min(...i.map(e=>e.backoffUntil))-r,0);throw Error(`All ${t} hosts are backing off for approximately ${a}ms due to repeated failures.`)}async lookupHostWithTracking(e,t,r){let i=Date.now();try{let n=await this.facilitator.lookup(e,t,r),a=Date.now()-i;return"object"==typeof n&&null!==n&&"output-list"===n.type&&Array.isArray(n.outputs)?this.hostReputation.recordSuccess(e,a):this.hostReputation.recordFailure(e,"Invalid lookup response"),n}catch(t){throw this.hostReputation.recordFailure(e,t),t}}}class nU{httpClient;allowHTTP;constructor(e=fetch,t=!1){this.httpClient=e,this.allowHTTP=t}async send(e,t){let r;if(!e.startsWith("https:")&&!this.allowHTTP)throw Error('HTTPS facilitator can only use URLs that start with "https:"');let i={"Content-Type":"application/octet-stream","X-Topics":JSON.stringify(t.topics)};if(Array.isArray(t.offChainValues)){i["x-includes-off-chain-values"]="true";let e=new ti;e.writeVarIntNum(t.beef.length),e.write(t.beef),e.write(t.offChainValues),r=new Uint8Array(e.toArray())}else r=new Uint8Array(t.beef);let n=await fetch(`${e}/submit`,{method:"POST",headers:i,body:r});if(n.ok)return await n.json();throw Error("Failed to facilitate broadcast")}}class nF{topics;facilitator;resolver;requireAcknowledgmentFromAllHostsForTopics;requireAcknowledgmentFromAnyHostForTopics;requireAcknowledgmentFromSpecificHostsForTopics;networkPreset;constructor(e,t={}){if(0===e.length)throw Error("At least one topic is required for broadcast.");if(e.some(e=>!e.startsWith("tm_")))throw Error('Every topic must start with "tm_".');this.topics=e,this.networkPreset=t.networkPreset??"mainnet",this.facilitator=t.facilitator??new nU(void 0,"local"===this.networkPreset),this.resolver=t.resolver??new nD({networkPreset:this.networkPreset}),this.requireAcknowledgmentFromAllHostsForTopics=t.requireAcknowledgmentFromAllHostsForTopics??[],this.requireAcknowledgmentFromAnyHostForTopics=t.requireAcknowledgmentFromAnyHostForTopics??"all",this.requireAcknowledgmentFromSpecificHostsForTopics=t.requireAcknowledgmentFromSpecificHostsForTopics??{}}async broadcast(e){let t,r,i,n,a,s=e.metadata.get("OffChainValues");try{t=e.toBEEF()}catch(e){throw Error("Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.")}let o=await this.findInterestedHosts();if(0===Object.keys(o).length)return{status:"error",code:"ERR_NO_HOSTS_INTERESTED",description:`No ${this.networkPreset} hosts are interested in receiving this transaction.`};let c=Object.entries(o).map(async([e,r])=>{try{let i=await this.facilitator.send(e,{beef:t,offChainValues:s,topics:[...r]});if(null==i||0===Object.keys(i).length)throw Error("Steak has no topics.");return{host:e,success:!0,steak:i}}catch(t){return console.error(t),{host:e,success:!1,error:t}}}),l=(await Promise.all(c)).filter(e=>e.success);if(0===l.length)return{status:"error",code:"ERR_ALL_HOSTS_REJECTED",description:`All ${this.networkPreset} topical hosts have rejected the transaction.`};let h={};for(let e of l){let t=e.host,r=e.steak,i=new Set;for(let[e,t]of Object.entries(r)){let r=t.outputsToAdmit,n=t.coinsToRetain,a=t.coinsRemoved;(r?.length>0||n?.length>0||a?.length>0)&&i.add(e)}h[t]=i}return("all"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="all"):"any"===this.requireAcknowledgmentFromAllHostsForTopics?(r=this.topics,i="any"):(r=Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)?this.requireAcknowledgmentFromAllHostsForTopics:this.topics,i="all"),r.length>0&&!this.checkAcknowledgmentFromAllHosts(h,r,i))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED",description:"Not all hosts acknowledged the required topics."}:("all"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="all"):"any"===this.requireAcknowledgmentFromAnyHostForTopics?(n=this.topics,a="any"):(n=Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)?this.requireAcknowledgmentFromAnyHostForTopics:[],a="all"),n.length>0&&!this.checkAcknowledgmentFromAnyHost(h,n,a))?{status:"error",code:"ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED",description:"No host acknowledged the required topics."}:Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length>0&&!this.checkAcknowledgmentFromSpecificHosts(h,this.requireAcknowledgmentFromSpecificHostsForTopics)?{status:"error",code:"ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED",description:"Specific hosts did not acknowledge the required topics."}:{status:"success",txid:e.id("hex"),message:`Sent to ${l.length} Overlay Services ${1===l.length?"host":"hosts"}.`}}checkAcknowledgmentFromAllHosts(e,t,r){for(let i of Object.values(e))if("all"===r){for(let e of t)if(!i.has(e))return!1}else if("any"===r){let e=!1;for(let r of t)if(i.has(r)){e=!0;break}if(!e)return!1}return!0}checkAcknowledgmentFromAnyHost(e,t,r){if("all"===r){for(let r of Object.values(e)){let e=!0;for(let i of t)if(!r.has(i)){e=!1;break}if(e)return!0}return!1}for(let r of Object.values(e))for(let e of t)if(r.has(e))return!0;return!1}checkAcknowledgmentFromSpecificHosts(e,t){for(let[r,i]of Object.entries(t)){let t,n,a=e[r];if(null==a)return!1;if("all"===i||"any"===i)n=i,t=this.topics;else{if(!Array.isArray(i))continue;t=i,n="all"}if("all"===n){for(let e of t)if(!a.has(e))return!1}else if("any"===n){let e=!1;for(let r of t)if(a.has(r)){e=!0;break}if(!e)return!1}}return!0}async findInterestedHosts(){if("local"===this.networkPreset){let e=new Set;for(let t=0;t<this.topics.length;t++)e.add(this.topics[t]);return{"http://localhost:8080":e}}let e={},t=await this.resolver.query({service:"ls_ship",query:{topics:this.topics}},5e3);if("output-list"!==t.type)throw Error("SHIP answer is not an output list.");for(let r of t.outputs)try{let t=rW.fromBEEF(r.beef).outputs[r.outputIndex].lockingScript,i=nO.decode(t);if(!this.topics.includes(i.topicOrService)||"SHIP"!==i.protocol)continue;void 0===e[i.domain]&&(e[i.domain]=new Set),e[i.domain].add(i.topicOrService)}catch(e){continue}return e}}async function nL(e,t,r=5){let i=0;for(;i<r;){i++;try{return await e()}catch(e){if(i<r&&"WERR_REVIEW_ACTIONS"===e.name){let n=e.reviewActionResults.find(e=>"doubleSpend"===e.status);if(n?.competingBeef!=null&&n?.competingTxs!=null&&n?.competingTxs.length>0){let e=rW.fromBEEF(n.competingBeef,n.competingTxs[0]);await nL(async()=>await t.broadcast(e),t,r-i);continue}}throw e}}throw Error("Unexpected end of retry loop")}let nK=e=>(e.toLowerCase().startsWith("uhrp:")&&(e=e.slice(5)),e.startsWith("//")&&(e=e.slice(2)),e),nH=e=>{if(32!==e.length)throw Error("Hash length must be 32 bytes (sha256)");return tt(e,e1("ce00","hex"))},nq=e=>{let t=e instanceof Uint8Array?e:Uint8Array.from(e),r=new M;for(let e=0;e<t.length;e+=1048576){let i=t.subarray(e,e+1048576);r.update(Array.from(i))}return nH(r.digest())},nM=e=>{let{data:t,prefix:r}=tr(e=nK(e),void 0,2);if(32!==t.length)throw Error("Invalid length!");if("ce00"!==e0(r))throw Error("Bad prefix");return t},n$=e=>{try{return nM(e),!0}catch(e){return!1}};class nz{authFetch;baseURL;constructor(e){this.baseURL=e.storageURL,this.authFetch=new nN(e.wallet)}async getUploadInfo(e,t){let r=`${this.baseURL}/upload`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileSize:e,retentionPeriod:t})});if(!i.ok)throw Error(`Upload info request failed: HTTP ${i.status}`);let n=await i.json();if("error"===n.status)throw Error("Upload route returned an error.");return{uploadURL:n.uploadURL,requiredHeaders:n.requiredHeaders,amount:n.amount}}async uploadFile(e,t,r){let i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=await fetch(e,{method:"PUT",body:i,headers:{"Content-Type":t.type,...r}});if(!n.ok)throw Error(`File upload failed: HTTP ${n.status}`);return{published:!0,uhrpURL:nq(i)}}async publishFile(e){let{file:t,retentionPeriod:r}=e,i=t.data instanceof Uint8Array?t.data:Uint8Array.from(t.data),n=i.byteLength,{uploadURL:a,requiredHeaders:s}=await this.getUploadInfo(n,r);return await this.uploadFile(a,{data:i,type:t.type},s)}async findFile(e){let t=new URL(`${this.baseURL}/find`);t.searchParams.set("uhrpUrl",e);let r=await this.authFetch.fetch(t.toString(),{method:"GET"});if(!r.ok)throw Error(`findFile request failed: HTTP ${r.status}`);let i=await r.json();if("error"===i.status){let e=i.code??"unknown-code",t=i.description??"no-description";throw Error(`findFile returned an error: ${e} - ${t}`)}return i.data}async listUploads(){let e=`${this.baseURL}/list`,t=await this.authFetch.fetch(e,{method:"GET"});if(!t.ok)throw Error(`listUploads request failed: HTTP ${t.status}`);let r=await t.json();if("error"===r.status){let e=r.code??"unknown-code",t=r.description??"no-description";throw Error(`listUploads returned an error: ${e} - ${t}`)}return r.uploads}async renewFile(e,t){let r=`${this.baseURL}/renew`,i=await this.authFetch.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uhrpUrl:e,additionalMinutes:t})});if(!i.ok)throw Error(`renewFile request failed: HTTP ${i.status}`);let n=await i.json();if("error"===n.status){let e=n.code??"unknown-code",t=n.description??"no-description";throw Error(`renewFile returned an error: ${e} - ${t}`)}return{status:n.status,prevExpiryTime:n.prevExpiryTime,newExpiryTime:n.newExpiryTime,amount:n.amount}}}class nW{networkPreset="mainnet";lookupResolver;constructor(e){this.networkPreset=e?.networkPreset??"mainnet",this.lookupResolver=new nD({networkPreset:this.networkPreset})}async resolve(e){let t=await this.lookupResolver.query({service:"ls_uhrp",query:{uhrpUrl:e}});if("output-list"!==t.type)throw Error("Lookup answer must be an output list");let r=[],i=Math.floor(Date.now()/1e3);for(let e=0;e<t.outputs.length;e++){let n=rW.fromBEEF(t.outputs[e].beef),{fields:a}=rN.decode(n.outputs[t.outputs[e].outputIndex].lockingScript);new tn(a[3]).readVarIntNum()<i||r.push(e4(a[2]))}return r}async download(e){if(!n$(e))throw Error("Invalid parameter UHRP url");let t=e0(nM(e)),r=await this.resolve(e);if(!Array.isArray(r)||0===r.length)throw Error("No one currently hosts this file!");for(let e=0;e<r.length;e++)try{let i=await fetch(r[e],{method:"GET"});if(!i.ok||i.status>=400||null==i.body)continue;let n=i.body.getReader(),a=new M,s=[],o=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;a.update(Array.from(t)),s.push(t),o+=t.length}if(e0(a.digest())!==t)throw Error("Data integrity error: value of content does not match hash of the url given");let c=new Uint8Array(o),l=0;for(let e of s)c.set(e,l),l+=e.length;return{data:c,mimeType:i.headers.get("Content-Type")}}catch(e){continue}throw Error(`Unable to download content from ${e}`)}}let nj={name:"Unknown Identity",avatarURL:"XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst",identityKey:"",abbreviatedKey:"",badgeIconURL:"XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",badgeLabel:"Not verified by anyone you trust.",badgeClickURL:"https://projectbabbage.com/docs/unknown-identity"},nG={protocolID:[1,"identity"],keyID:"1",tokenAmount:1,outputIndex:0},nX={identiCert:"z40BOInXkI8m7f/wBrv4MJ09bZfzZbTj2fJqCtONqCY=",discordCert:"2TgqRC35B1zehGmB21xveZNc7i5iqHc0uxMb+1NMPW4=",phoneCert:"mffUklUzxbHr65xLohn0hRL0Tq2GjW1GYF/OPfzqJ6A=",xCert:"vdDWvftf1H+5+ZprUw123kjHlywH+v20aPQTuXgMpNc=",registrant:"YoPsbfR6YQczjzPdHCoGC7nJsOdPQR50+SYqcWpJ0y0=",emailCert:"exOl3KM0dIJ04EW5pZgbZmPag6MdJXd3/a1enmUU/BA=",anyone:"mfkOMfLDQmrr3SBxBQ5WeE+6Hy3VJRFq6w4A5Ljtlis=",self:"Hkge6X5JRxt1cWXtHLCrSTg6dCVTxjQJJ48iOYd7n3g=",coolCert:"AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo="},nJ=[2,"contact"];class nY{cache=new Map;getItem(e){return this.cache.get(e)??null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}clear(){this.cache.clear()}}class nZ{wallet;cache=new nY;CONTACTS_CACHE_KEY="metanet-contacts";originator;constructor(e,t){this.wallet=e??new nf,this.originator=t}async getContacts(e,t=!1,r=1e3){if(!t){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t);return null!=e?r.filter(t=>t.identityKey===e):r}catch(e){console.warn("Invalid cached contacts JSON; will reload from chain",e)}}let i=[];if(null!=e){let{hmac:t}=await this.wallet.createHmac({protocolID:nJ,keyID:e,counterparty:"self",data:e1(e,"utf8")},this.originator);i.push(`identityKey ${e0(t)}`)}let n=await this.wallet.listOutputs({basket:"contacts",include:"locking scripts",includeCustomInstructions:!0,tags:i,limit:r},this.originator);if(null==n.outputs||0===n.outputs.length)return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify([])),[];let a=[];for(let e of n.outputs)try{if(null==e.lockingScript)continue;let t=rN.decode(ry.fromHex(e.lockingScript));if(null==e.customInstructions)continue;let r=JSON.parse(e.customInstructions).keyID,{plaintext:i}=await this.wallet.decrypt({ciphertext:t.fields[0],protocolID:nJ,keyID:r,counterparty:"self"},this.originator),n=JSON.parse(e4(i));a.push(n)}catch(e){console.warn("ContactsManager: Failed to decode contact output:",e)}return this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(a)),null!=e?a.filter(t=>t.identityKey===e):a}async saveContact(e,t){let r,i=this.cache.getItem(this.CONTACTS_CACHE_KEY),n=(r=null!=i&&""!==i?JSON.parse(i):await this.getContacts()).findIndex(t=>t.identityKey===e.identityKey),a={...e,metadata:t};n>=0?r[n]=a:r.push(a);let{hmac:s}=await this.wallet.createHmac({protocolID:nJ,keyID:e.identityKey,counterparty:"self",data:e1(e.identityKey,"utf8")},this.originator),o=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:[`identityKey ${e0(s)}`],limit:100},this.originator),c=null,l=e5(tq(32));if(null!=o.outputs)for(let t of o.outputs)try{let[r,i]=t.outpoint.split("."),n=rW.fromBEEF(o.BEEF,r),a=rN.decode(n.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;l=JSON.parse(t.customInstructions).keyID;let{plaintext:s}=await this.wallet.decrypt({ciphertext:a.fields[0],protocolID:nJ,keyID:l,counterparty:"self"},this.originator);if(JSON.parse(e4(s)).identityKey===e.identityKey){c=t;break}}catch(e){}let h={...e,metadata:t},{ciphertext:u}=await this.wallet.encrypt({plaintext:e1(JSON.stringify(h),"utf8"),protocolID:nJ,keyID:l,counterparty:"self"},this.originator),d=await new rN(this.wallet,this.originator).lock([u],nJ,l,"self");if(null!=c){let[t,r]=String(c.outpoint).split("."),i=`${t}.${r}`,n=new rN(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Update Contact",inputBEEF:o.BEEF,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:"Spend previous contact output"}],outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Updated Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e0(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to update contact");let h=n.unlock(nJ,l,"self"),u=await h.sign(rW.fromBEEF(a.tx),0),{tx:f}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}}},this.originator);if(null==f)throw Error("Failed to update contact output")}else{let{tx:t}=await this.wallet.createAction({description:"Add Contact",outputs:[{basket:"contacts",satoshis:1,lockingScript:d.toHex(),outputDescription:`Contact: ${e.name??e.identityKey.slice(0,10)}`,tags:[`identityKey ${e0(s)}`],customInstructions:JSON.stringify({keyID:l})}],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==t)throw Error("Failed to create contact output")}this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}async removeContact(e){let t=this.cache.getItem(this.CONTACTS_CACHE_KEY);if(null!=t&&""!==t)try{let r=JSON.parse(t).filter(t=>t.identityKey!==e);this.cache.setItem(this.CONTACTS_CACHE_KEY,JSON.stringify(r))}catch(e){console.warn("Failed to update cache after contact removal:",e)}let r=[],{hmac:i}=await this.wallet.createHmac({protocolID:nJ,keyID:e,counterparty:"self",data:e1(e,"utf8")},this.originator);r.push(`identityKey ${e0(i)}`);let n=await this.wallet.listOutputs({basket:"contacts",include:"entire transactions",includeCustomInstructions:!0,tags:r,limit:100},this.originator);if(null!=n.outputs)for(let t of n.outputs)try{let[r,i]=String(t.outpoint).split("."),a=rW.fromBEEF(n.BEEF,r),s=rN.decode(a.outputs[Number(i)].lockingScript);if(null==t.customInstructions)continue;let o=JSON.parse(t.customInstructions).keyID,{plaintext:c}=await this.wallet.decrypt({ciphertext:s.fields[0],protocolID:nJ,keyID:o,counterparty:"self"},this.originator);if(JSON.parse(e4(c)).identityKey===e){let e=`${r}.${i}`,t=new rN(this.wallet,this.originator),{signableTransaction:a}=await this.wallet.createAction({description:"Delete Contact",inputBEEF:n.BEEF,inputs:[{outpoint:e,unlockingScriptLength:74,inputDescription:"Spend contact output to delete"}],outputs:[],options:{acceptDelayedBroadcast:!1,randomizeOutputs:!1}},this.originator);if(null==a)throw Error("Unable to delete contact");let s=t.unlock(nJ,o,"self"),c=await s.sign(rW.fromBEEF(a.tx),0),{tx:l}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:c.toHex()}}},this.originator);if(null==l)throw Error("Failed to delete contact output");return}}catch(e){}}}class nQ{options;originator;wallet;contactsManager;constructor(e,t=nG,r){this.options=t,this.originator=r,this.originator=r,this.wallet=e??new nf,this.contactsManager=new nZ(this.wallet,this.originator)}async publiclyRevealAttributes(e,t){if(0===Object.keys(e.fields).length)throw Error("Public reveal failed: Certificate has no fields to reveal!");if(0===t.length)throw Error("Public reveal failed: You must reveal at least one field!");try{let t=new iS(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature);await t.verify()}catch(e){throw Error("Public reveal failed: Certificate verification failed!")}let{keyringForVerifier:r}=await this.wallet.proveCertificate({certificate:e,fieldsToReveal:t,verifier:new tW(1).toPublicKey().toString()},this.originator),i=await new rN(this.wallet,this.originator).lock([e1(JSON.stringify({...e,keyring:r}))],this.options.protocolID,this.options.keyID,"anyone",!0,!0),{tx:n}=await this.wallet.createAction({description:"Create a new Identity Token",outputs:[{satoshis:this.options.tokenAmount,lockingScript:i.toHex(),outputDescription:"Identity Token"}],options:{randomizeOutputs:!1}},this.originator);if(void 0!==n){let e=new nF(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network});return await e.broadcast(rW.fromAtomicBEEF(n))}throw Error("Public reveal failed: failed to create action!")}async resolveByIdentityKey(e,t=!0){if(t){let t=await this.contactsManager.getContacts(e.identityKey);if(t.length>0)return t}let{certificates:r}=await this.wallet.discoverByIdentityKey(e,this.originator);return r.map(e=>nQ.parseIdentity(e))}async resolveByAttributes(e,t=!0){let[r,i]=await Promise.all([t?this.contactsManager.getContacts():Promise.resolve([]),this.wallet.discoverByAttributes(e,this.originator)]),n=new Map(r.map(e=>[e.identityKey,e]));return(i?.certificates??[]).map(e=>n.get(e.subject)??nQ.parseIdentity(e))}async revokeCertificateRevelation(e){let t=new nD({networkPreset:(await this.wallet.getNetwork({})).network}),r=await t.query({service:"ls_identity",query:{serialNumber:e}});if("output-list"!==r.type)throw Error("Failed to get lookup result");let i=new nF(["tm_identity"],{networkPreset:(await this.wallet.getNetwork({})).network,requireAcknowledgmentFromAllHostsForTopics:[],requireAcknowledgmentFromAnyHostForTopics:[],requireAcknowledgmentFromSpecificHostsForTopics:{tm_identity:[]}});await nL(async()=>{let e=rW.fromBEEF(r.outputs[0].beef),t=`${e.id("hex")}.${this.options.outputIndex}`;if(void 0===e.outputs[this.options.outputIndex].lockingScript||void 0===t)throw Error("Failed to get locking script for revelation output!");let{signableTransaction:n}=await this.wallet.createAction({description:"Spend certificate revelation token",inputBEEF:r.outputs[0].beef,inputs:[{inputDescription:"Revelation token",outpoint:t,unlockingScriptLength:74}],options:{randomizeOutputs:!1,acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction");let a=rW.fromBEEF(n.tx),s=new rN(this.wallet,this.originator).unlock(this.options.protocolID,this.options.keyID,"anyone"),o=await s.sign(a,this.options.outputIndex),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{[this.options.outputIndex]:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:!1,noSend:!0}},this.originator);if(void 0===c)throw Error("Failed to sign transaction");await i.broadcast(rW.fromAtomicBEEF(c))},i)}async getContacts(e,t=!1,r=1e3){return await this.contactsManager.getContacts(e,t,r)}async saveContact(e,t){return await this.contactsManager.saveContact(e,t)}async removeContact(e){return await this.contactsManager.removeContact(e)}static parseIdentity(e){let t,r,i,n,a,{type:s,decryptedFields:o,certifierInfo:c}=e;switch(s){case nX.xCert:t=o.userName,r=o.profilePhoto,i=`X account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nX.discordCert:t=o.userName,r=o.profilePhoto,i=`Discord account certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nX.emailCert:t=o.email,r="XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu",i=`Email certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nX.phoneCert:t=o.phoneNumber,r="XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU",i=`Phone certified by ${c.name}`,n=c.iconUrl,a="https://socialcert.net";break;case nX.identiCert:t=`${o.firstName} ${o.lastName}`,r=o.profilePhoto,i=`Government ID certified by ${c.name}`,n=c.iconUrl,a="https://identicert.me";break;case nX.registrant:t=o.name,r=o.icon,i=`Entity certified by ${c.name}`,n=c.iconUrl,a="https://projectbabbage.com/docs/registrant";break;case nX.coolCert:t="true"===o.cool?"Cool Person!":"Not cool!";break;case nX.anyone:t="Anyone",r="XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR",i="Represents the ability for anyone to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/anyone-identity";break;case nX.self:t="You",r="XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR",i="Represents your ability to access this information.",n="XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG",a="https://projectbabbage.com/docs/self-identity";break;default:{let e=nQ.tryToParseGenericIdentity(s,o,c);t=e.name,r=e.avatarURL,i=e.badgeLabel,n=e.badgeIconURL,a=e.badgeClickURL}}return{name:t,avatarURL:r,abbreviatedKey:e.subject.length>0?`${e.subject.substring(0,10)}...`:"",identityKey:e.subject,badgeIconURL:n,badgeLabel:i,badgeClickURL:a}}static hasValue(e){return null!=e&&""!==e}static tryToParseGenericIdentity(e,t,r){let i=t.firstName,n=t.lastName,a=nQ.hasValue(i)&&nQ.hasValue(n)?`${i} ${n}`:nQ.hasValue(i)?i:nQ.hasValue(n)?n:void 0,s=nQ.hasValue(t.name)?t.name:nQ.hasValue(t.userName)?t.userName:a??(nQ.hasValue(t.email)?t.email:nj.name),o=nQ.hasValue(t.profilePhoto)?t.profilePhoto:nQ.hasValue(t.avatar)?t.avatar:nQ.hasValue(t.icon)?t.icon:nQ.hasValue(t.photo)?t.photo:nj.avatarURL,c=nQ.hasValue(r?.name)?`${e} certified by ${String(r.name)}`:nj.badgeLabel;return{name:s,avatarURL:o,badgeLabel:c,badgeIconURL:nQ.hasValue(r?.iconUrl)?r.iconUrl:nj.badgeIconURL,badgeClickURL:nj.badgeClickURL}}}class n0{wallet;originator;network;resolver;cachedIdentityKey;acceptDelayedBroadcast;constructor(e=new nf,t={},r){this.wallet=e,this.originator=r,this.acceptDelayedBroadcast=t.acceptDelayedBroadcast??!1,this.resolver=t.resolver??new nD}async getIdentityKey(){return void 0===this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0})).publicKey),this.cachedIdentityKey}async getNetwork(){return void 0===this.network&&(this.network=(await this.wallet.getNetwork({})).network),this.network}async registerDefinition(e){let t=await this.getIdentityKey(),r=new rN(this.wallet,this.originator),i=this.buildPushDropFields(e,t),n=this.mapDefinitionTypeToWalletProtocol(e.definitionType),a=await r.lock(i,n,"1","anyone",!0),{tx:s}=await this.wallet.createAction({description:`Register a new ${e.definitionType} item`,outputs:[{satoshis:1,lockingScript:a.toHex(),outputDescription:`New ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===s)throw Error(`Failed to create ${e.definitionType} registration transaction!`);let o=new nF([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await o.broadcast(rW.fromAtomicBEEF(s))}async resolve(e,t){let r=this.mapDefinitionTypeToServiceName(e),i=await this.resolver.query({service:r,query:t});if("output-list"!==i.type)return[];let n=[];for(let t of i.outputs)try{let r=rW.fromBEEF(t.beef).outputs[t.outputIndex].lockingScript,i=await this.parseLockingScript(e,r);n.push(i)}catch{}return n}async listOwnRegistryEntries(e){let t=this.mapDefinitionTypeToBasketName(e),{outputs:r,BEEF:i}=await this.wallet.listOutputs({basket:t,include:"entire transactions"}),n=[];for(let t of r)if(t.spendable)try{let[r,a]=t.outpoint.split("."),s=rW.fromBEEF(i,r).outputs[Number(a)].lockingScript,o=await this.parseLockingScript(e,s);n.push({...o,txid:r,outputIndex:Number(a),satoshis:t.satoshis,lockingScript:s.toHex(),beef:i})}catch{}return n}async removeDefinition(e){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");let t=await this.getIdentityKey();if(e.registryOperator!==t)throw Error("This registry token does not belong to the current wallet.");let r="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",i=`${e.txid}.${e.outputIndex}`,{signableTransaction:n}=await this.wallet.createAction({description:`Remove ${e.definitionType} item: ${r}`,inputBEEF:e.beef,inputs:[{outpoint:i,unlockingScriptLength:74,inputDescription:`Removing ${e.definitionType} token`}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===n)throw Error("Failed to create signable transaction.");let a=rW.fromAtomicBEEF(n.tx),s=new rN(this.wallet,this.originator).unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),o=await s.sign(a,0),{tx:c}=await this.wallet.signAction({reference:n.reference,spends:{0:{unlockingScript:o.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===c)throw Error("Failed to finalize the transaction signature.");let l=new nF([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await l.broadcast(rW.fromAtomicBEEF(c))}async updateDefinition(e,t){if(void 0===e.txid||void 0===e.outputIndex||void 0===e.lockingScript)throw Error("Invalid registry record. Missing txid, outputIndex, or lockingScript.");if(e.definitionType!==t.definitionType)throw Error(`Cannot change definition type from ${e.definitionType} to ${t.definitionType}`);let r=await this.getIdentityKey();if(e.registryOperator!==r)throw Error("This registry token does not belong to the current wallet.");let i="basket"===e.definitionType?e.basketID:"protocol"===e.definitionType?e.name:"certificate"===e.definitionType?void 0!==e.name?e.name:e.type:"unknown",n=new rN(this.wallet,this.originator),a=this.buildPushDropFields(t,r),s=this.mapDefinitionTypeToWalletProtocol(t.definitionType),o=await n.lock(a,s,"1","anyone",!0),c=`${e.txid}.${e.outputIndex}`,{signableTransaction:l}=await this.wallet.createAction({description:`Update ${e.definitionType} item: ${i}`,inputBEEF:e.beef,inputs:[{outpoint:c,unlockingScriptLength:74,inputDescription:`Updating ${e.definitionType} token`}],outputs:[{satoshis:1,lockingScript:o.toHex(),outputDescription:`Updated ${e.definitionType} registration token`,basket:this.mapDefinitionTypeToBasketName(e.definitionType)}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(void 0===l)throw Error("Failed to create signable transaction.");let h=rW.fromAtomicBEEF(l.tx),u=n.unlock(this.mapDefinitionTypeToWalletProtocol(e.definitionType),"1","anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if(void 0===f)throw Error("Failed to finalize the transaction signature.");let p=new nF([this.mapDefinitionTypeToTopic(e.definitionType)],{networkPreset:await this.getNetwork(),resolver:this.resolver});return await p.broadcast(rW.fromAtomicBEEF(f))}buildPushDropFields(e,t){let r;switch(e.definitionType){case"basket":r=[e.basketID,e.name,e.iconURL,e.description,e.documentationURL];break;case"protocol":r=[JSON.stringify(e.protocolID),e.name,e.iconURL,e.description,e.documentationURL];break;case"certificate":r=[e.type,e.name,e.iconURL,e.description,e.documentationURL,JSON.stringify(e.fields)];break;default:throw Error("Unsupported definition type")}return r.push(t),r.map(e=>e1(e))}async parseLockingScript(e,t){let r,i,n=rN.decode(t);if(0===n.fields.length)throw Error("Not a valid registry pushdrop script.");switch(e){case"basket":{if(7!==n.fields.length)throw Error("Unexpected field count for basket type.");let[e,t,a,s,o,c]=n.fields;r=e4(c),i={definitionType:"basket",basketID:e4(e),name:e4(t),iconURL:e4(a),description:e4(s),documentationURL:e4(o)};break}case"protocol":{if(7!==n.fields.length)throw Error("Unexpected field count for protocol type.");let[e,t,a,s,o,c]=n.fields;r=e4(c),i={definitionType:"protocol",protocolID:n1(e4(e)),name:e4(t),iconURL:e4(a),description:e4(s),documentationURL:e4(o)};break}case"certificate":{if(8!==n.fields.length)throw Error("Unexpected field count for certificate type.");let[e,t,a,s,o,c,l]=n.fields;r=e4(l);let h={};try{h=JSON.parse(e4(c))}catch{}i={definitionType:"certificate",type:e4(e),name:e4(t),iconURL:e4(a),description:e4(s),documentationURL:e4(o),fields:h};break}default:throw Error(`Unsupported definition type: ${e}`)}return{...i,registryOperator:r}}mapDefinitionTypeToWalletProtocol(e){switch(e){case"basket":return[1,"basketmap"];case"protocol":return[1,"protomap"];case"certificate":return[1,"certmap"];default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToBasketName(e){switch(e){case"basket":return"basketmap";case"protocol":return"protomap";case"certificate":return"certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToTopic(e){switch(e){case"basket":return"tm_basketmap";case"protocol":return"tm_protomap";case"certificate":return"tm_certmap";default:throw Error(`Unknown definition type: ${e}`)}}mapDefinitionTypeToServiceName(e){switch(e){case"basket":return"ls_basketmap";case"protocol":return"ls_protomap";case"certificate":return"ls_certmap";default:throw Error(`Unknown definition type: ${e}`)}}}function n1(e){let t=JSON.parse(e);if(!Array.isArray(t)||2!==t.length)throw Error("Invalid wallet protocol format.");let[r,i]=t;if(![0,1,2].includes(r))throw Error("Invalid security level.");if("string"!=typeof i)throw Error("Invalid protocolID");return[r,i]}class n2{wallet;context;encrypt;originator;acceptDelayedBroadcast=!1;keyLocks=new Map;constructor(e=new nf,t="kvstore default",r=!0,i,n=!1){if("string"!=typeof t||t.length<1)throw Error("A context in which to operate is required.");this.wallet=e,this.context=t,this.encrypt=r,this.originator=i,this.acceptDelayedBroadcast=n}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,t}finishOperationOnKey(e,t){t.shift(),t.length>0&&t[0]()}getProtocol(e){return{protocolID:[2,this.context],keyID:e}}async getOutputs(e,t){return await this.wallet.listOutputs({basket:this.context,tags:[e],tagQueryMode:"all",include:"entire transactions",limit:t},this.originator)}async get(e,t){let r=await this.queueOperationOnKey(e);try{return(await this.lookupValue(e,t,5)).value}finally{this.finishOperationOnKey(e,r)}}getLockingScript(e,t){let[r,i]=e.outpoint.split("."),n=t.findTxid(r)?.tx;if(null==n)throw Error(`beef must contain txid ${r}`);return n.outputs[Number(i)].lockingScript}async lookupValue(e,t,r){let i,n=await this.getOutputs(e,r),a={value:t,outpoint:void 0,lor:n},{outputs:s}=n;if(0===s.length)return a;let o=s.slice(-1)[0];a.outpoint=o.outpoint;try{if(void 0===n.BEEF)throw Error("entire transactions listOutputs option must return valid BEEF");let e=this.getLockingScript(o,r$.fromBinary(n.BEEF)),t=rN.decode(e);if(t.fields.length<1||t.fields.length>2)throw Error("Invalid token.");i=t.fields[0]}catch(e){throw Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${s[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${e instanceof Error?e.message:String(e)}`)}if(this.encrypt){let{plaintext:t}=await this.wallet.decrypt({...this.getProtocol(e),ciphertext:i},this.originator);a.value=e4(t)}else a.value=e4(i);return a}getInputs(e){let t=[];for(let r=0;r<e.length;r++)t.push({outpoint:e[r].outpoint,unlockingScriptLength:74,inputDescription:"Previous key-value token"});return t}async getSpends(e,t,r,i){let n=this.getProtocol(e),a=rW.fromAtomicBEEF(i),s={};for(let e=0;e<t.length;e++){let t=r.unlock(n.protocolID,n.keyID,"self"),i=await t.sign(a,e);s[e]={unlockingScript:i.toHex()}}return s}async set(e,t){let r=await this.queueOperationOnKey(e);try{let r,i=await this.lookupValue(e,void 0,10);if(i.value===t){if(void 0===i.outpoint)throw Error("outpoint must be valid when value is valid and unchanged");return i.outpoint}let n=this.getProtocol(e),a=e1(t,"utf8");if(this.encrypt){let{ciphertext:e}=await this.wallet.encrypt({...n,plaintext:a},this.originator);a=e}let s=new rN(this.wallet,this.originator),o=await s.lock([a],n.protocolID,n.keyID,"self"),{outputs:c,BEEF:l}=i.lor;try{let t=this.getInputs(c),{txid:i,signableTransaction:n}=await this.wallet.createAction({description:`Update ${e} in ${this.context}`,inputBEEF:l,inputs:t,outputs:[{basket:this.context,tags:[e],lockingScript:o.toHex(),satoshis:1,outputDescription:"Key-value token"}],options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast,randomizeOutputs:!1}},this.originator);if(c.length>0&&"object"!=typeof n)throw Error("Wallet did not return a signable transaction when expected.");if(null==n)r=`${i}.0`;else{let t=await this.getSpends(e,c,s,n.tx),{txid:i}=await this.wallet.signAction({reference:n.reference,spends:t},this.originator);r=`${i}.0`}}catch(t){throw Error(`There are ${c.length} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}return r}finally{this.finishOperationOnKey(e,r)}}async remove(e){let t=await this.queueOperationOnKey(e);try{let t=[];for(;;){let{outputs:r,BEEF:i,totalOutputs:n}=await this.getOutputs(e);if(r.length>0){let a=new rN(this.wallet,this.originator);try{let n=this.getInputs(r),{signableTransaction:s}=await this.wallet.createAction({description:`Remove ${e} in ${this.context}`,inputBEEF:i,inputs:n,options:{acceptDelayedBroadcast:this.acceptDelayedBroadcast}},this.originator);if("object"!=typeof s)throw Error("Wallet did not return a signable transaction when expected.");let o=await this.getSpends(e,r,a,s.tx),{txid:c}=await this.wallet.signAction({reference:s.reference,spends:o},this.originator);if(void 0===c)throw Error("signAction must return a valid txid");t.push(c)}catch(t){throw Error(`There are ${n} outputs with tag ${e} that cannot be unlocked. Original error: ${t instanceof Error?t.message:String(t)}`)}}if(r.length===n)break}return t}finally{this.finishOperationOnKey(e,t)}}}class n8{interpreter;debug;historyCache;interpreterVersion;ctxKeyFn;constructor(e,t){this.interpreter=e,this.debug=t?.debug??!1,this.historyCache=t?.historyCache,this.interpreterVersion=t?.interpreterVersion??"v1",this.ctxKeyFn=t?.ctxKeyFn??(e=>{try{return JSON.stringify(e??null)}catch{return""}})}historyKey(e,t){let r=e.id("hex"),i=this.ctxKeyFn(t);return`${this.interpreterVersion}|${r}|${i}`}async buildHistory(e,t){if(null!=this.historyCache){let r=this.historyKey(e,t);if(this.historyCache.has(r)){let e=this.historyCache.get(r);if(null!=e)return this.debug&&console.log("[Historian] History cache hit:",r),e.slice()}}let r=[],i=new Set,n=async e=>{let a=e.id("hex");if(i.has(a)){this.debug&&console.log(`[Historian] Skipping already visited transaction: ${a}`);return}i.add(a),this.debug&&console.log(`[Historian] Processing transaction: ${a}`);for(let i=0;i<e.outputs.length;i++)try{let n=await Promise.resolve(this.interpreter(e,i,t));void 0!==n&&(r.push(n),this.debug&&console.log("[Historian] Added value to history:",n))}catch(e){this.debug&&console.log(`[Historian] Failed to interpret output ${i}:`,e)}for(let t of e.inputs)null!=t.sourceTransaction?await n(t.sourceTransaction):this.debug&&console.log("[Historian] Input missing sourceTransaction, skipping")};await n(e);let a=r.reverse();if(null!=this.historyCache){let r=this.historyKey(e,t);this.historyCache.set(r,Object.freeze(a.slice())),this.debug&&console.log("[Historian] History cached:",r)}return a}}let n3={protocolID:0,key:1,value:2,controller:3,tags:4,signature:5},n4=async(e,t,r)=>{try{let i=e.outputs[t];if(null==i||null==i.lockingScript||null==r||null==r.key)return;let n=rN.decode(i.lockingScript),a=Object.keys(n3).length,s=n.fields.length===a;if(n.fields.length!==a-1&&!s)return;let o=e4(n.fields[n3.key]),c=e4(n.fields[n3.protocolID]);if(o!==r.key||c!==JSON.stringify(r.protocolID))return;try{return e4(n.fields[n3.value])}catch{return}}catch{return}},n6={protocolID:[1,"kvstore"],serviceName:"ls_kvstore",tokenAmount:1,topics:["tm_kvstore"],networkPreset:"mainnet",acceptDelayedBroadcast:!1,overlayBroadcast:!1,tokenSetDescription:"",tokenUpdateDescription:"",tokenRemovalDescription:""};class n5{wallet;config;historian;lookupResolver;topicBroadcaster;keyLocks=new Map;cachedIdentityKey=null;constructor(e={}){this.config={...n6,...e},this.wallet=e.wallet??new nf,this.historian=new n8(n4),this.lookupResolver=new nD({networkPreset:this.config.networkPreset}),this.topicBroadcaster=new nF(this.config.topics,{networkPreset:this.config.networkPreset})}async get(e,t={}){if(0===Object.keys(e).length)throw Error("Must specify either key, controller, or protocolID");if(null!=e.key&&null!=e.controller){let r=await this.queryOverlay(e,t);return r.length>0?r[0]:void 0}return await this.queryOverlay(e,t)}async set(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");if("string"!=typeof t)throw Error("Value must be a string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenSetDescription&&""!==r.tokenSetDescription?r.tokenSetDescription:`Create KVStore value for ${e}`,o=null!=r.tokenUpdateDescription&&""!==r.tokenUpdateDescription?r.tokenUpdateDescription:`Update KVStore value for ${e}`,c=r.tokenAmount??this.config.tokenAmount,l=r.tags??[];try{let r=new rN(this.wallet,this.config.originator),n=[e1(JSON.stringify(a),"utf8"),e1(e,"utf8"),e1(t,"utf8"),e1(i,"hex")];l.length>0&&n.push(e1(JSON.stringify(l),"utf8"));let h=await r.lock(n,a??this.config.protocolID,e4(e1(e,"utf8")),"anyone",!0);return await nL(async()=>{let t=await this.queryOverlay({key:e,controller:i},{includeToken:!0}),n=t.length>0?t[0].token:void 0;if(null!=n){let t=[{outpoint:`${n.txid}.${n.outputIndex}`,unlockingScriptLength:74,inputDescription:"Previous KVStore token"}],i=n.beef,{signableTransaction:a}=await this.wallet.createAction({description:o,inputBEEF:i.toBinary(),inputs:t,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==a)throw Error("Unable to create update transaction");let s=rW.fromAtomicBEEF(a.tx),l=r.unlock(this.config.protocolID,e,"anyone"),u=await l.sign(s,0),{tx:d}=await this.wallet.signAction({reference:a.reference,spends:{0:{unlockingScript:u.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==d)throw Error("Unable to finalize update transaction");let f=rW.fromAtomicBEEF(d);return await this.submitToOverlay(f),`${f.id("hex")}.0`}{let{tx:e}=await this.wallet.createAction({description:s,outputs:[{satoshis:c??this.config.tokenAmount,lockingScript:h.toHex(),outputDescription:"KVStore token"}],options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast,randomizeOutputs:!1}},this.config.originator);if(null==e)throw Error("Failed to create transaction");let t=rW.fromAtomicBEEF(e);return await this.submitToOverlay(t),`${t.id("hex")}.0`}},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async remove(e,t,r={}){if("string"!=typeof e||0===e.length)throw Error("Key must be a non-empty string.");let i=await this.getIdentityKey(),n=await this.queueOperationOnKey(e),a=r.protocolID??this.config.protocolID,s=null!=r.tokenRemovalDescription&&""!==r.tokenRemovalDescription?r.tokenRemovalDescription:`Remove KVStore value for ${e}`;try{let r=new rN(this.wallet,this.config.originator);return await nL(async()=>{let n=await this.queryOverlay({key:e,controller:i},{includeToken:!0});if(0===n.length||null==n[0].token)throw Error("The item did not exist, no item was deleted.");let o=n[0].token,c=[{outpoint:`${o.txid}.${o.outputIndex}`,unlockingScriptLength:74,inputDescription:"KVStore token to remove"}],{signableTransaction:l}=await this.wallet.createAction({description:s,inputBEEF:o.beef.toBinary(),inputs:c,outputs:t,options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,randomizeOutputs:!1,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==l)throw Error("Unable to create removal transaction");let h=rW.fromAtomicBEEF(l.tx),u=r.unlock(a??this.config.protocolID,e,"anyone"),d=await u.sign(h,0),{tx:f}=await this.wallet.signAction({reference:l.reference,spends:{0:{unlockingScript:d.toHex()}},options:{acceptDelayedBroadcast:this.config.acceptDelayedBroadcast,noSend:this.config.overlayBroadcast}},this.config.originator);if(null==f)throw Error("Unable to finalize removal transaction");let p=rW.fromAtomicBEEF(f);return await this.submitToOverlay(p),p.id("hex")},this.topicBroadcaster)}finally{n.length>0&&this.finishOperationOnKey(e,n)}}async queueOperationOnKey(e){let t=this.keyLocks.get(e);null==t&&(t=[],this.keyLocks.set(e,t));let r=()=>{},i=new Promise(e=>{r=e,null!=t&&t.push(e)});return 1===t.length&&r(),await i,t}finishOperationOnKey(e,t){t.shift(),t.length>0?t[0]():this.keyLocks.delete(e)}async getIdentityKey(){return null==this.cachedIdentityKey&&(this.cachedIdentityKey=(await this.wallet.getPublicKey({identityKey:!0},this.config.originator)).publicKey),this.cachedIdentityKey}async queryOverlay(e,t={}){let r=await this.lookupResolver.query({service:t.serviceName??this.config.serviceName,query:e});if("output-list"!==r.type||0===r.outputs.length)return[];let i=[];for(let e of r.outputs)try{let r,n=rW.fromBEEF(e.beef),a=n.outputs[e.outputIndex],s=rN.decode(a.lockingScript),o=Object.keys(n3).length,c=s.fields.length===o;if(s.fields.length!==o-1&&!c)continue;let l=new iy("anyone"),h=s.fields.pop();try{await l.verifySignature({data:s.fields.reduce((e,t)=>[...e,...t],[]),signature:h,counterparty:e0(s.fields[n3.controller]),protocolID:JSON.parse(e4(s.fields[n3.protocolID])),keyID:e4(s.fields[n3.key])})}catch(e){continue}if(c&&null!=s.fields[n3.tags])try{r=JSON.parse(e4(s.fields[n3.tags]))}catch(e){r=void 0}let u={key:e4(s.fields[n3.key]),value:e4(s.fields[n3.value]),controller:e0(s.fields[n3.controller]),protocolID:JSON.parse(e4(s.fields[n3.protocolID])),tags:r};!0===t.includeToken&&(u.token={txid:n.id("hex"),outputIndex:e.outputIndex,beef:r$.fromBinary(e.beef),satoshis:a.satoshis??1}),!0===t.history&&(u.history=await this.historian.buildHistory(n,{key:u.key,protocolID:u.protocolID})),i.push(u)}catch(e){continue}return i}async submitToOverlay(e){return await this.topicBroadcaster.broadcast(e)}}let n7=n5;return s})());
|
|
20
20
|
//# sourceMappingURL=bundle.js.map
|