@bsv/wallet-toolbox 1.7.14 → 1.7.16

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.
Files changed (1194) hide show
  1. package/.github/workflows/push.yaml +136 -62
  2. package/CHANGELOG.md +5 -0
  3. package/docs/client.md +4 -2
  4. package/docs/storage.md +4 -2
  5. package/docs/wallet.md +4 -2
  6. package/mobile/node_modules/.package-lock.json +14 -0
  7. package/mobile/node_modules/@bsv/sdk/LICENSE.txt +28 -0
  8. package/mobile/node_modules/@bsv/sdk/README.md +133 -0
  9. package/mobile/node_modules/@bsv/sdk/dist/cjs/mod.js +36 -0
  10. package/mobile/node_modules/@bsv/sdk/dist/cjs/mod.js.map +1 -0
  11. package/mobile/node_modules/@bsv/sdk/dist/cjs/package.json +70 -0
  12. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/Peer.js +695 -0
  13. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/Peer.js.map +1 -0
  14. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/SessionManager.js +130 -0
  15. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/SessionManager.js.map +1 -0
  16. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/Certificate.js +236 -0
  17. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/Certificate.js.map +1 -0
  18. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/MasterCertificate.js +245 -0
  19. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/MasterCertificate.js.map +1 -0
  20. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/VerifiableCertificate.js +96 -0
  21. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/VerifiableCertificate.js.map +1 -0
  22. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/__tests/CompletedProtoWallet.js +111 -0
  23. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/__tests/CompletedProtoWallet.js.map +1 -0
  24. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/index.js +26 -0
  25. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/certificates/index.js.map +1 -0
  26. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/AuthFetch.js +734 -0
  27. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/AuthFetch.js.map +1 -0
  28. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/__tests__/AuthFetch.test.js +189 -0
  29. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/__tests__/AuthFetch.test.js.map +1 -0
  30. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/index.js +18 -0
  31. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/clients/index.js.map +1 -0
  32. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/index.js +24 -0
  33. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/index.js.map +1 -0
  34. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/SimplifiedFetchTransport.js +424 -0
  35. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/SimplifiedFetchTransport.js.map +1 -0
  36. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js +144 -0
  37. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js.map +1 -0
  38. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/index.js +18 -0
  39. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/transports/index.js.map +1 -0
  40. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/types.js +3 -0
  41. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/types.js.map +1 -0
  42. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/createNonce.js +62 -0
  43. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/createNonce.js.map +1 -0
  44. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/getVerifiableCertificates.js +31 -0
  45. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/getVerifiableCertificates.js.map +1 -0
  46. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/index.js +21 -0
  47. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/index.js.map +1 -0
  48. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/validateCertificates.js +45 -0
  49. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/validateCertificates.js.map +1 -0
  50. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/verifyNonce.js +61 -0
  51. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/auth/utils/verifyNonce.js.map +1 -0
  52. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/BSM.js +94 -0
  53. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/BSM.js.map +1 -0
  54. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/ECIES.js +590 -0
  55. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/ECIES.js.map +1 -0
  56. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/HD.js +354 -0
  57. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/HD.js.map +1 -0
  58. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/Mnemonic.js +314 -0
  59. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/Mnemonic.js.map +1 -0
  60. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/Utxo.js +51 -0
  61. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/Utxo.js.map +1 -0
  62. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/bip-39-wordlist-en.js +2057 -0
  63. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/bip-39-wordlist-en.js.map +1 -0
  64. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/index.js +49 -0
  65. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/compat/index.js.map +1 -0
  66. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/ContactsManager.js +338 -0
  67. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/ContactsManager.js.map +1 -0
  68. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/IdentityClient.js +367 -0
  69. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/IdentityClient.js.map +1 -0
  70. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/index.js +19 -0
  71. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/index.js.map +1 -0
  72. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/types/index.js +30 -0
  73. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/identity/types/index.js.map +1 -0
  74. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/GlobalKVStore.js +470 -0
  75. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/GlobalKVStore.js.map +1 -0
  76. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/LocalKVStore.js +343 -0
  77. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/LocalKVStore.js.map +1 -0
  78. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/index.js +11 -0
  79. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/index.js.map +1 -0
  80. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/kvStoreInterpreter.js +88 -0
  81. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/kvStoreInterpreter.js.map +1 -0
  82. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/types.js +12 -0
  83. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/kvstore/types.js.map +1 -0
  84. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/EncryptedMessage.js +71 -0
  85. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/EncryptedMessage.js.map +1 -0
  86. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/SignedMessage.js +86 -0
  87. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/SignedMessage.js.map +1 -0
  88. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/index.js +39 -0
  89. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/messages/index.js.map +1 -0
  90. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/Historian.js +153 -0
  91. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/Historian.js.map +1 -0
  92. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/HostReputationTracker.js +216 -0
  93. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/HostReputationTracker.js.map +1 -0
  94. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/LookupResolver.js +398 -0
  95. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/LookupResolver.js.map +1 -0
  96. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/OverlayAdminTokenTemplate.js +81 -0
  97. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/OverlayAdminTokenTemplate.js.map +1 -0
  98. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/SHIPBroadcaster.js +408 -0
  99. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/SHIPBroadcaster.js.map +1 -0
  100. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/index.js +36 -0
  101. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/index.js.map +1 -0
  102. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/withDoubleSpendRetry.js +54 -0
  103. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/overlay-tools/withDoubleSpendRetry.js.map +1 -0
  104. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/AESGCM.js +376 -0
  105. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/AESGCM.js.map +1 -0
  106. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/BasePoint.js +19 -0
  107. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/BasePoint.js.map +1 -0
  108. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/BigNumber.js +1367 -0
  109. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/BigNumber.js.map +1 -0
  110. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Curve.js +1149 -0
  111. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Curve.js.map +1 -0
  112. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/DRBG.js +109 -0
  113. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/DRBG.js.map +1 -0
  114. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/ECDSA.js +188 -0
  115. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/ECDSA.js.map +1 -0
  116. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Hash.js +1687 -0
  117. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Hash.js.map +1 -0
  118. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/JacobianPoint.js +427 -0
  119. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/JacobianPoint.js.map +1 -0
  120. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/K256.js +127 -0
  121. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/K256.js.map +1 -0
  122. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Mersenne.js +113 -0
  123. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Mersenne.js.map +1 -0
  124. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/MontgomoryMethod.js +150 -0
  125. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/MontgomoryMethod.js.map +1 -0
  126. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Point.js +1098 -0
  127. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Point.js.map +1 -0
  128. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Polynomial.js +83 -0
  129. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Polynomial.js.map +1 -0
  130. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/PrivateKey.js +519 -0
  131. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/PrivateKey.js.map +1 -0
  132. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/PublicKey.js +261 -0
  133. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/PublicKey.js.map +1 -0
  134. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Random.js +91 -0
  135. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Random.js.map +1 -0
  136. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/ReductionContext.js +490 -0
  137. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/ReductionContext.js.map +1 -0
  138. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Schnorr.js +98 -0
  139. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Schnorr.js.map +1 -0
  140. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Secp256r1.js +327 -0
  141. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Secp256r1.js.map +1 -0
  142. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Signature.js +358 -0
  143. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/Signature.js.map +1 -0
  144. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/SymmetricKey.js +96 -0
  145. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/SymmetricKey.js.map +1 -0
  146. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/TransactionSignature.js +235 -0
  147. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/TransactionSignature.js.map +1 -0
  148. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/hex.js +33 -0
  149. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/hex.js.map +1 -0
  150. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/index.js +69 -0
  151. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/index.js.map +1 -0
  152. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/utils.js +863 -0
  153. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/primitives/utils.js.map +1 -0
  154. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/RegistryClient.js +533 -0
  155. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/RegistryClient.js.map +1 -0
  156. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/index.js +19 -0
  157. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/index.js.map +1 -0
  158. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/types/index.js +3 -0
  159. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/registry/types/index.js.map +1 -0
  160. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/LockingScript.js +35 -0
  161. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/LockingScript.js.map +1 -0
  162. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/OP.js +207 -0
  163. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/OP.js.map +1 -0
  164. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/Script.js +567 -0
  165. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/Script.js.map +1 -0
  166. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptChunk.js +3 -0
  167. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptChunk.js.map +1 -0
  168. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptEvaluationError.js +27 -0
  169. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptEvaluationError.js.map +1 -0
  170. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptTemplate.js +3 -0
  171. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptTemplate.js.map +1 -0
  172. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptTemplateUnlock.js +3 -0
  173. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/ScriptTemplateUnlock.js.map +1 -0
  174. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/Spend.js +1208 -0
  175. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/Spend.js.map +1 -0
  176. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/UnlockingScript.js +35 -0
  177. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/UnlockingScript.js.map +1 -0
  178. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/index.js +34 -0
  179. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/index.js.map +1 -0
  180. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/P2PKH.js +129 -0
  181. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/P2PKH.js.map +1 -0
  182. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/PushDrop.js +219 -0
  183. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/PushDrop.js.map +1 -0
  184. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/RPuzzle.js +130 -0
  185. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/RPuzzle.js.map +1 -0
  186. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/index.js +13 -0
  187. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/script/templates/index.js.map +1 -0
  188. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageDownloader.js +100 -0
  189. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageDownloader.js.map +1 -0
  190. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageUploader.js +213 -0
  191. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageUploader.js.map +1 -0
  192. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageUtils.js +81 -0
  193. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/StorageUtils.js.map +1 -0
  194. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/index.js +42 -0
  195. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/storage/index.js.map +1 -0
  196. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/totp/index.js +18 -0
  197. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/totp/index.js.map +1 -0
  198. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/totp/totp.js +92 -0
  199. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/totp/totp.js.map +1 -0
  200. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Beef.js +840 -0
  201. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Beef.js.map +1 -0
  202. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/BeefParty.js +117 -0
  203. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/BeefParty.js.map +1 -0
  204. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/BeefTx.js +191 -0
  205. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/BeefTx.js.map +1 -0
  206. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Broadcaster.js +17 -0
  207. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Broadcaster.js.map +1 -0
  208. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/ChainTracker.js +3 -0
  209. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/ChainTracker.js.map +1 -0
  210. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/FeeModel.js +3 -0
  211. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/FeeModel.js.map +1 -0
  212. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/MerklePath.js +383 -0
  213. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/MerklePath.js.map +1 -0
  214. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Transaction.js +911 -0
  215. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/Transaction.js.map +1 -0
  216. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/TransactionInput.js +3 -0
  217. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/TransactionInput.js.map +1 -0
  218. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/TransactionOutput.js +3 -0
  219. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/TransactionOutput.js.map +1 -0
  220. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/ARC.js +181 -0
  221. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/ARC.js.map +1 -0
  222. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/DefaultBroadcaster.js +11 -0
  223. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/DefaultBroadcaster.js.map +1 -0
  224. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/Teranode.js +63 -0
  225. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/Teranode.js.map +1 -0
  226. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/WhatsOnChainBroadcaster.js +65 -0
  227. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/WhatsOnChainBroadcaster.js.map +1 -0
  228. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/index.js +15 -0
  229. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/broadcasters/index.js.map +1 -0
  230. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/BlockHeadersService.js +91 -0
  231. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -0
  232. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/DefaultChainTracker.js +11 -0
  233. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/DefaultChainTracker.js.map +1 -0
  234. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/WhatsOnChain.js +67 -0
  235. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/WhatsOnChain.js.map +1 -0
  236. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/index.js +13 -0
  237. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/chaintrackers/index.js.map +1 -0
  238. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/LivePolicy.js +90 -0
  239. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/LivePolicy.js.map +1 -0
  240. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/SatoshisPerKilobyte.js +69 -0
  241. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/SatoshisPerKilobyte.js.map +1 -0
  242. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/index.js +11 -0
  243. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/fee-models/index.js.map +1 -0
  244. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/BinaryFetchClient.js +94 -0
  245. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/BinaryFetchClient.js.map +1 -0
  246. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/DefaultHttpClient.js +37 -0
  247. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/DefaultHttpClient.js.map +1 -0
  248. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/FetchHttpClient.js +31 -0
  249. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/FetchHttpClient.js.map +1 -0
  250. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/HttpClient.js +3 -0
  251. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/HttpClient.js.map +1 -0
  252. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/NodejsHttpClient.js +43 -0
  253. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/NodejsHttpClient.js.map +1 -0
  254. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/index.js +12 -0
  255. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/http/index.js.map +1 -0
  256. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/index.js +33 -0
  257. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/transaction/index.js.map +1 -0
  258. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/CachedKeyDeriver.js +210 -0
  259. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/CachedKeyDeriver.js.map +1 -0
  260. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/KeyDeriver.js +191 -0
  261. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/KeyDeriver.js.map +1 -0
  262. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/ProtoWallet.js +188 -0
  263. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/ProtoWallet.js.map +1 -0
  264. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_INSUFFICIENT_FUNDS.js +26 -0
  265. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_INSUFFICIENT_FUNDS.js.map +1 -0
  266. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_INVALID_PARAMETER.js +20 -0
  267. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_INVALID_PARAMETER.js.map +1 -0
  268. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_REVIEW_ACTIONS.js +29 -0
  269. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WERR_REVIEW_ACTIONS.js.map +1 -0
  270. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/Wallet.interfaces.js +17 -0
  271. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/Wallet.interfaces.js.map +1 -0
  272. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletClient.js +222 -0
  273. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletClient.js.map +1 -0
  274. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletError.js +84 -0
  275. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletError.js.map +1 -0
  276. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletLoggerInterface.js +8 -0
  277. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/WalletLoggerInterface.js.map +1 -0
  278. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/index.js +64 -0
  279. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/index.js.map +1 -0
  280. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/HTTPWalletJSON.js +153 -0
  281. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/HTTPWalletJSON.js.map +1 -0
  282. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/HTTPWalletWire.js +78 -0
  283. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/HTTPWalletWire.js.map +1 -0
  284. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/ReactNativeWebView.js +175 -0
  285. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/ReactNativeWebView.js.map +1 -0
  286. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWire.js +3 -0
  287. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWire.js.map +1 -0
  288. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireCalls.js +36 -0
  289. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireCalls.js.map +1 -0
  290. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireProcessor.js +1854 -0
  291. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireProcessor.js.map +1 -0
  292. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireTransceiver.js +1411 -0
  293. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/WalletWireTransceiver.js.map +1 -0
  294. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/XDM.js +172 -0
  295. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/XDM.js.map +1 -0
  296. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/index.js +37 -0
  297. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/index.js.map +1 -0
  298. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js +20 -0
  299. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/utils/toOriginHeader.js.map +1 -0
  300. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/window.CWI.js +102 -0
  301. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/substrates/window.CWI.js.map +1 -0
  302. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/validationHelpers.js +931 -0
  303. package/mobile/node_modules/@bsv/sdk/dist/cjs/src/wallet/validationHelpers.js.map +1 -0
  304. package/mobile/node_modules/@bsv/sdk/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -0
  305. package/mobile/node_modules/@bsv/sdk/dist/esm/mod.js +20 -0
  306. package/mobile/node_modules/@bsv/sdk/dist/esm/mod.js.map +1 -0
  307. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/Peer.js +663 -0
  308. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/Peer.js.map +1 -0
  309. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/SessionManager.js +134 -0
  310. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/SessionManager.js.map +1 -0
  311. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/Certificate.js +225 -0
  312. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/Certificate.js.map +1 -0
  313. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/MasterCertificate.js +206 -0
  314. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/MasterCertificate.js.map +1 -0
  315. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/VerifiableCertificate.js +58 -0
  316. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/VerifiableCertificate.js.map +1 -0
  317. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/__tests/CompletedProtoWallet.js +105 -0
  318. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/__tests/CompletedProtoWallet.js.map +1 -0
  319. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/index.js +5 -0
  320. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/certificates/index.js.map +1 -0
  321. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/AuthFetch.js +698 -0
  322. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/AuthFetch.js.map +1 -0
  323. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/__tests__/AuthFetch.test.js +187 -0
  324. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/__tests__/AuthFetch.test.js.map +1 -0
  325. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/index.js +2 -0
  326. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/clients/index.js.map +1 -0
  327. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/index.js +8 -0
  328. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/index.js.map +1 -0
  329. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/SimplifiedFetchTransport.js +390 -0
  330. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/SimplifiedFetchTransport.js.map +1 -0
  331. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js +109 -0
  332. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/__tests__/SimplifiedFetchTransport.test.js.map +1 -0
  333. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/index.js +2 -0
  334. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/transports/index.js.map +1 -0
  335. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/types.js +2 -0
  336. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/types.js.map +1 -0
  337. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/createNonce.js +23 -0
  338. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/createNonce.js.map +1 -0
  339. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/getVerifiableCertificates.js +27 -0
  340. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/getVerifiableCertificates.js.map +1 -0
  341. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/index.js +5 -0
  342. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/index.js.map +1 -0
  343. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/validateCertificates.js +41 -0
  344. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/validateCertificates.js.map +1 -0
  345. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/verifyNonce.js +25 -0
  346. package/mobile/node_modules/@bsv/sdk/dist/esm/src/auth/utils/verifyNonce.js.map +1 -0
  347. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/BSM.js +52 -0
  348. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/BSM.js.map +1 -0
  349. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/ECIES.js +551 -0
  350. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/ECIES.js.map +1 -0
  351. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/HD.js +322 -0
  352. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/HD.js.map +1 -0
  353. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/Mnemonic.js +278 -0
  354. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/Mnemonic.js.map +1 -0
  355. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/Utxo.js +45 -0
  356. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/Utxo.js.map +1 -0
  357. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/bip-39-wordlist-en.js +2054 -0
  358. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/bip-39-wordlist-en.js.map +1 -0
  359. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/index.js +6 -0
  360. package/mobile/node_modules/@bsv/sdk/dist/esm/src/compat/index.js.map +1 -0
  361. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/ContactsManager.js +334 -0
  362. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/ContactsManager.js.map +1 -0
  363. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/IdentityClient.js +364 -0
  364. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/IdentityClient.js.map +1 -0
  365. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/index.js +3 -0
  366. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/index.js.map +1 -0
  367. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/types/index.js +27 -0
  368. package/mobile/node_modules/@bsv/sdk/dist/esm/src/identity/types/index.js.map +1 -0
  369. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/GlobalKVStore.js +456 -0
  370. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/GlobalKVStore.js.map +1 -0
  371. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/LocalKVStore.js +328 -0
  372. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/LocalKVStore.js.map +1 -0
  373. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/index.js +3 -0
  374. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/index.js.map +1 -0
  375. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/kvStoreInterpreter.js +51 -0
  376. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/kvStoreInterpreter.js.map +1 -0
  377. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/types.js +9 -0
  378. package/mobile/node_modules/@bsv/sdk/dist/esm/src/kvstore/types.js.map +1 -0
  379. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/EncryptedMessage.js +63 -0
  380. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/EncryptedMessage.js.map +1 -0
  381. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/SignedMessage.js +78 -0
  382. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/SignedMessage.js.map +1 -0
  383. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/index.js +3 -0
  384. package/mobile/node_modules/@bsv/sdk/dist/esm/src/messages/index.js.map +1 -0
  385. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/Historian.js +155 -0
  386. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/Historian.js.map +1 -0
  387. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/HostReputationTracker.js +213 -0
  388. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/HostReputationTracker.js.map +1 -0
  389. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/LookupResolver.js +372 -0
  390. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/LookupResolver.js.map +1 -0
  391. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/OverlayAdminTokenTemplate.js +76 -0
  392. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/OverlayAdminTokenTemplate.js.map +1 -0
  393. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/SHIPBroadcaster.js +376 -0
  394. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/SHIPBroadcaster.js.map +1 -0
  395. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/index.js +11 -0
  396. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/index.js.map +1 -0
  397. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/withDoubleSpendRetry.js +48 -0
  398. package/mobile/node_modules/@bsv/sdk/dist/esm/src/overlay-tools/withDoubleSpendRetry.js.map +1 -0
  399. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/AESGCM.js +363 -0
  400. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/AESGCM.js.map +1 -0
  401. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/BasePoint.js +16 -0
  402. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/BasePoint.js.map +1 -0
  403. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/BigNumber.js +1373 -0
  404. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/BigNumber.js.map +1 -0
  405. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Curve.js +1164 -0
  406. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Curve.js.map +1 -0
  407. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/DRBG.js +108 -0
  408. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/DRBG.js.map +1 -0
  409. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/ECDSA.js +180 -0
  410. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/ECDSA.js.map +1 -0
  411. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Hash.js +1693 -0
  412. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Hash.js.map +1 -0
  413. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/JacobianPoint.js +425 -0
  414. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/JacobianPoint.js.map +1 -0
  415. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/K256.js +121 -0
  416. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/K256.js.map +1 -0
  417. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Mersenne.js +112 -0
  418. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Mersenne.js.map +1 -0
  419. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/MontgomoryMethod.js +149 -0
  420. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/MontgomoryMethod.js.map +1 -0
  421. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Point.js +1078 -0
  422. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Point.js.map +1 -0
  423. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Polynomial.js +79 -0
  424. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Polynomial.js.map +1 -0
  425. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/PrivateKey.js +481 -0
  426. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/PrivateKey.js.map +1 -0
  427. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/PublicKey.js +255 -0
  428. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/PublicKey.js.map +1 -0
  429. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Random.js +90 -0
  430. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Random.js.map +1 -0
  431. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/ReductionContext.js +486 -0
  432. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/ReductionContext.js.map +1 -0
  433. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Schnorr.js +93 -0
  434. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Schnorr.js.map +1 -0
  435. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Secp256r1.js +319 -0
  436. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Secp256r1.js.map +1 -0
  437. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Signature.js +361 -0
  438. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/Signature.js.map +1 -0
  439. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/SymmetricKey.js +90 -0
  440. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/SymmetricKey.js.map +1 -0
  441. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/TransactionSignature.js +197 -0
  442. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/TransactionSignature.js.map +1 -0
  443. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/hex.js +29 -0
  444. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/hex.js.map +1 -0
  445. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/index.js +16 -0
  446. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/index.js.map +1 -0
  447. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/utils.js +847 -0
  448. package/mobile/node_modules/@bsv/sdk/dist/esm/src/primitives/utils.js.map +1 -0
  449. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/RegistryClient.js +534 -0
  450. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/RegistryClient.js.map +1 -0
  451. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/index.js +3 -0
  452. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/index.js.map +1 -0
  453. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/types/index.js +2 -0
  454. package/mobile/node_modules/@bsv/sdk/dist/esm/src/registry/types/index.js.map +1 -0
  455. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/LockingScript.js +29 -0
  456. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/LockingScript.js.map +1 -0
  457. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/OP.js +205 -0
  458. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/OP.js.map +1 -0
  459. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/Script.js +565 -0
  460. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/Script.js.map +1 -0
  461. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptChunk.js +2 -0
  462. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptChunk.js.map +1 -0
  463. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptEvaluationError.js +33 -0
  464. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptEvaluationError.js.map +1 -0
  465. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptTemplate.js +2 -0
  466. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptTemplate.js.map +1 -0
  467. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptTemplateUnlock.js +2 -0
  468. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/ScriptTemplateUnlock.js.map +1 -0
  469. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/Spend.js +1190 -0
  470. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/Spend.js.map +1 -0
  471. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/UnlockingScript.js +29 -0
  472. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/UnlockingScript.js.map +1 -0
  473. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/index.js +8 -0
  474. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/index.js.map +1 -0
  475. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/P2PKH.js +125 -0
  476. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/P2PKH.js.map +1 -0
  477. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/PushDrop.js +220 -0
  478. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/PushDrop.js.map +1 -0
  479. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/RPuzzle.js +124 -0
  480. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/RPuzzle.js.map +1 -0
  481. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/index.js +4 -0
  482. package/mobile/node_modules/@bsv/sdk/dist/esm/src/script/templates/index.js.map +1 -0
  483. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageDownloader.js +94 -0
  484. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageDownloader.js.map +1 -0
  485. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageUploader.js +178 -0
  486. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageUploader.js.map +1 -0
  487. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageUtils.js +73 -0
  488. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/StorageUtils.js.map +1 -0
  489. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/index.js +4 -0
  490. package/mobile/node_modules/@bsv/sdk/dist/esm/src/storage/index.js.map +1 -0
  491. package/mobile/node_modules/@bsv/sdk/dist/esm/src/totp/index.js +2 -0
  492. package/mobile/node_modules/@bsv/sdk/dist/esm/src/totp/index.js.map +1 -0
  493. package/mobile/node_modules/@bsv/sdk/dist/esm/src/totp/totp.js +85 -0
  494. package/mobile/node_modules/@bsv/sdk/dist/esm/src/totp/totp.js.map +1 -0
  495. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Beef.js +835 -0
  496. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Beef.js.map +1 -0
  497. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/BeefParty.js +113 -0
  498. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/BeefParty.js.map +1 -0
  499. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/BeefTx.js +189 -0
  500. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/BeefTx.js.map +1 -0
  501. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Broadcaster.js +13 -0
  502. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Broadcaster.js.map +1 -0
  503. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/ChainTracker.js +2 -0
  504. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/ChainTracker.js.map +1 -0
  505. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/FeeModel.js +2 -0
  506. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/FeeModel.js.map +1 -0
  507. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/MerklePath.js +382 -0
  508. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/MerklePath.js.map +1 -0
  509. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Transaction.js +914 -0
  510. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/Transaction.js.map +1 -0
  511. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/TransactionInput.js +2 -0
  512. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/TransactionInput.js.map +1 -0
  513. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/TransactionOutput.js +2 -0
  514. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/TransactionOutput.js.map +1 -0
  515. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/ARC.js +182 -0
  516. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/ARC.js.map +1 -0
  517. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/DefaultBroadcaster.js +5 -0
  518. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/DefaultBroadcaster.js.map +1 -0
  519. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/Teranode.js +62 -0
  520. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/Teranode.js.map +1 -0
  521. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/WhatsOnChainBroadcaster.js +65 -0
  522. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/WhatsOnChainBroadcaster.js.map +1 -0
  523. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/index.js +5 -0
  524. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/broadcasters/index.js.map +1 -0
  525. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/BlockHeadersService.js +90 -0
  526. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/BlockHeadersService.js.map +1 -0
  527. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/DefaultChainTracker.js +5 -0
  528. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/DefaultChainTracker.js.map +1 -0
  529. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/WhatsOnChain.js +68 -0
  530. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/WhatsOnChain.js.map +1 -0
  531. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/index.js +4 -0
  532. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/chaintrackers/index.js.map +1 -0
  533. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/LivePolicy.js +85 -0
  534. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/LivePolicy.js.map +1 -0
  535. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/SatoshisPerKilobyte.js +71 -0
  536. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/SatoshisPerKilobyte.js.map +1 -0
  537. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/index.js +3 -0
  538. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/fee-models/index.js.map +1 -0
  539. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/BinaryFetchClient.js +90 -0
  540. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/BinaryFetchClient.js.map +1 -0
  541. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/DefaultHttpClient.js +34 -0
  542. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/DefaultHttpClient.js.map +1 -0
  543. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/FetchHttpClient.js +28 -0
  544. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/FetchHttpClient.js.map +1 -0
  545. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/HttpClient.js +2 -0
  546. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/HttpClient.js.map +1 -0
  547. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/NodejsHttpClient.js +40 -0
  548. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/NodejsHttpClient.js.map +1 -0
  549. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/index.js +5 -0
  550. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/http/index.js.map +1 -0
  551. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/index.js +7 -0
  552. package/mobile/node_modules/@bsv/sdk/dist/esm/src/transaction/index.js.map +1 -0
  553. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/CachedKeyDeriver.js +218 -0
  554. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/CachedKeyDeriver.js.map +1 -0
  555. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/KeyDeriver.js +192 -0
  556. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/KeyDeriver.js.map +1 -0
  557. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/ProtoWallet.js +182 -0
  558. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/ProtoWallet.js.map +1 -0
  559. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_INSUFFICIENT_FUNDS.js +25 -0
  560. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_INSUFFICIENT_FUNDS.js.map +1 -0
  561. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_INVALID_PARAMETER.js +18 -0
  562. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_INVALID_PARAMETER.js.map +1 -0
  563. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_REVIEW_ACTIONS.js +31 -0
  564. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WERR_REVIEW_ACTIONS.js.map +1 -0
  565. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/Wallet.interfaces.js +14 -0
  566. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/Wallet.interfaces.js.map +1 -0
  567. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletClient.js +218 -0
  568. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletClient.js.map +1 -0
  569. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletError.js +81 -0
  570. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletError.js.map +1 -0
  571. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletLoggerInterface.js +7 -0
  572. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/WalletLoggerInterface.js.map +1 -0
  573. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/index.js +15 -0
  574. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/index.js.map +1 -0
  575. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/HTTPWalletJSON.js +151 -0
  576. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/HTTPWalletJSON.js.map +1 -0
  577. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/HTTPWalletWire.js +42 -0
  578. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/HTTPWalletWire.js.map +1 -0
  579. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/ReactNativeWebView.js +137 -0
  580. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/ReactNativeWebView.js.map +1 -0
  581. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWire.js +2 -0
  582. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWire.js.map +1 -0
  583. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireCalls.js +34 -0
  584. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireCalls.js.map +1 -0
  585. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireProcessor.js +1816 -0
  586. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireProcessor.js.map +1 -0
  587. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireTransceiver.js +1373 -0
  588. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/WalletWireTransceiver.js.map +1 -0
  589. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/XDM.js +134 -0
  590. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/XDM.js.map +1 -0
  591. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/index.js +10 -0
  592. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/index.js.map +1 -0
  593. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/utils/toOriginHeader.js +17 -0
  594. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/utils/toOriginHeader.js.map +1 -0
  595. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/window.CWI.js +100 -0
  596. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/substrates/window.CWI.js.map +1 -0
  597. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/validationHelpers.js +860 -0
  598. package/mobile/node_modules/@bsv/sdk/dist/esm/src/wallet/validationHelpers.js.map +1 -0
  599. package/mobile/node_modules/@bsv/sdk/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  600. package/mobile/node_modules/@bsv/sdk/dist/types/mod.d.ts +20 -0
  601. package/mobile/node_modules/@bsv/sdk/dist/types/mod.d.ts.map +1 -0
  602. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/Peer.d.ts +200 -0
  603. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/Peer.d.ts.map +1 -0
  604. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/SessionManager.d.ts +60 -0
  605. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/SessionManager.d.ts.map +1 -0
  606. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/Certificate.d.ts +112 -0
  607. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/Certificate.d.ts.map +1 -0
  608. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/MasterCertificate.d.ts +108 -0
  609. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/MasterCertificate.d.ts.map +1 -0
  610. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/VerifiableCertificate.d.ts +37 -0
  611. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/VerifiableCertificate.d.ts.map +1 -0
  612. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/__tests/CompletedProtoWallet.d.ts +29 -0
  613. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/__tests/CompletedProtoWallet.d.ts.map +1 -0
  614. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/index.d.ts +5 -0
  615. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/certificates/index.d.ts.map +1 -0
  616. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/AuthFetch.d.ts +126 -0
  617. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/AuthFetch.d.ts.map +1 -0
  618. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/__tests__/AuthFetch.test.d.ts +2 -0
  619. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/__tests__/AuthFetch.test.d.ts.map +1 -0
  620. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/index.d.ts +2 -0
  621. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/clients/index.d.ts.map +1 -0
  622. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/index.d.ts +8 -0
  623. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/index.d.ts.map +1 -0
  624. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/SimplifiedFetchTransport.d.ts +57 -0
  625. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/SimplifiedFetchTransport.d.ts.map +1 -0
  626. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/__tests__/SimplifiedFetchTransport.test.d.ts +2 -0
  627. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/__tests__/SimplifiedFetchTransport.test.d.ts.map +1 -0
  628. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/index.d.ts +2 -0
  629. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/transports/index.d.ts.map +1 -0
  630. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/types.d.ts +32 -0
  631. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/types.d.ts.map +1 -0
  632. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/createNonce.d.ts +9 -0
  633. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/createNonce.d.ts.map +1 -0
  634. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/getVerifiableCertificates.d.ts +13 -0
  635. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/getVerifiableCertificates.d.ts.map +1 -0
  636. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/index.d.ts +5 -0
  637. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/index.d.ts.map +1 -0
  638. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/validateCertificates.d.ts +12 -0
  639. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/validateCertificates.d.ts.map +1 -0
  640. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/verifyNonce.d.ts +10 -0
  641. package/mobile/node_modules/@bsv/sdk/dist/types/src/auth/utils/verifyNonce.d.ts.map +1 -0
  642. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/BSM.d.ts +29 -0
  643. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/BSM.d.ts.map +1 -0
  644. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/ECIES.d.ts +62 -0
  645. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/ECIES.d.ts.map +1 -0
  646. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/HD.d.ts +131 -0
  647. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/HD.d.ts.map +1 -0
  648. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/Mnemonic.d.ts +132 -0
  649. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/Mnemonic.d.ts.map +1 -0
  650. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/Utxo.d.ts +42 -0
  651. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/Utxo.d.ts.map +1 -0
  652. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/bip-39-wordlist-en.d.ts +5 -0
  653. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/bip-39-wordlist-en.d.ts.map +1 -0
  654. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/index.d.ts +6 -0
  655. package/mobile/node_modules/@bsv/sdk/dist/types/src/compat/index.d.ts.map +1 -0
  656. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/ContactsManager.d.ts +32 -0
  657. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/ContactsManager.d.ts.map +1 -0
  658. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/IdentityClient.d.ts +81 -0
  659. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/IdentityClient.d.ts.map +1 -0
  660. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/index.d.ts +3 -0
  661. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/index.d.ts.map +1 -0
  662. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/types/index.d.ts +30 -0
  663. package/mobile/node_modules/@bsv/sdk/dist/types/src/identity/types/index.d.ts.map +1 -0
  664. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/GlobalKVStore.d.ts +129 -0
  665. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/GlobalKVStore.d.ts.map +1 -0
  666. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/LocalKVStore.d.ts +95 -0
  667. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/LocalKVStore.d.ts.map +1 -0
  668. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/index.d.ts +3 -0
  669. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/index.d.ts.map +1 -0
  670. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/kvStoreInterpreter.d.ts +23 -0
  671. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/kvStoreInterpreter.d.ts.map +1 -0
  672. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/types.d.ts +118 -0
  673. package/mobile/node_modules/@bsv/sdk/dist/types/src/kvstore/types.d.ts.map +1 -0
  674. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/EncryptedMessage.d.ts +20 -0
  675. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/EncryptedMessage.d.ts.map +1 -0
  676. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/SignedMessage.d.ts +21 -0
  677. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/SignedMessage.d.ts.map +1 -0
  678. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/index.d.ts +3 -0
  679. package/mobile/node_modules/@bsv/sdk/dist/types/src/messages/index.d.ts.map +1 -0
  680. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/Historian.d.ts +92 -0
  681. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/Historian.d.ts.map +1 -0
  682. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/HostReputationTracker.d.ts +37 -0
  683. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/HostReputationTracker.d.ts.map +1 -0
  684. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/LookupResolver.d.ts +124 -0
  685. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/LookupResolver.d.ts.map +1 -0
  686. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/OverlayAdminTokenTemplate.d.ts +44 -0
  687. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/OverlayAdminTokenTemplate.d.ts.map +1 -0
  688. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/SHIPBroadcaster.d.ts +105 -0
  689. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/SHIPBroadcaster.d.ts.map +1 -0
  690. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/index.d.ts +9 -0
  691. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/index.d.ts.map +1 -0
  692. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/withDoubleSpendRetry.d.ts +14 -0
  693. package/mobile/node_modules/@bsv/sdk/dist/types/src/overlay-tools/withDoubleSpendRetry.d.ts.map +1 -0
  694. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/AESGCM.d.ts +14 -0
  695. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/AESGCM.d.ts.map +1 -0
  696. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/BasePoint.d.ts +22 -0
  697. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/BasePoint.d.ts.map +1 -0
  698. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/BigNumber.d.ts +438 -0
  699. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/BigNumber.d.ts.map +1 -0
  700. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Curve.d.ts +62 -0
  701. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Curve.d.ts.map +1 -0
  702. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/DRBG.d.ts +66 -0
  703. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/DRBG.d.ts.map +1 -0
  704. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/ECDSA.d.ts +39 -0
  705. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/ECDSA.d.ts.map +1 -0
  706. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Hash.d.ts +499 -0
  707. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Hash.d.ts.map +1 -0
  708. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/JacobianPoint.d.ts +164 -0
  709. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/JacobianPoint.d.ts.map +1 -0
  710. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/K256.d.ts +53 -0
  711. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/K256.d.ts.map +1 -0
  712. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Mersenne.d.ts +72 -0
  713. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Mersenne.d.ts.map +1 -0
  714. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/MontgomoryMethod.d.ts +96 -0
  715. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/MontgomoryMethod.d.ts.map +1 -0
  716. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Point.d.ts +362 -0
  717. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Point.d.ts.map +1 -0
  718. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Polynomial.d.ts +32 -0
  719. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Polynomial.d.ts.map +1 -0
  720. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/PrivateKey.d.ts +284 -0
  721. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/PrivateKey.d.ts.map +1 -0
  722. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/PublicKey.d.ts +155 -0
  723. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/PublicKey.d.ts.map +1 -0
  724. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Random.d.ts +14 -0
  725. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Random.d.ts.map +1 -0
  726. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/ReductionContext.d.ts +308 -0
  727. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/ReductionContext.d.ts.map +1 -0
  728. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Schnorr.d.ts +65 -0
  729. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Schnorr.d.ts.map +1 -0
  730. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Secp256r1.d.ts +91 -0
  731. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Secp256r1.d.ts.map +1 -0
  732. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Signature.d.ts +162 -0
  733. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/Signature.d.ts.map +1 -0
  734. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/SymmetricKey.d.ts +55 -0
  735. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/SymmetricKey.d.ts.map +1 -0
  736. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/TransactionSignature.d.ts +57 -0
  737. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/TransactionSignature.d.ts.map +1 -0
  738. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/hex.d.ts +3 -0
  739. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/hex.d.ts.map +1 -0
  740. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/index.d.ts +16 -0
  741. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/index.d.ts.map +1 -0
  742. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/utils.d.ts +140 -0
  743. package/mobile/node_modules/@bsv/sdk/dist/types/src/primitives/utils.d.ts.map +1 -0
  744. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/RegistryClient.d.ts +121 -0
  745. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/RegistryClient.d.ts.map +1 -0
  746. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/index.d.ts +3 -0
  747. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/index.d.ts.map +1 -0
  748. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/types/index.d.ts +113 -0
  749. package/mobile/node_modules/@bsv/sdk/dist/types/src/registry/types/index.d.ts.map +1 -0
  750. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/LockingScript.d.ts +25 -0
  751. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/LockingScript.d.ts.map +1 -0
  752. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/OP.d.ts +193 -0
  753. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/OP.d.ts.map +1 -0
  754. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/Script.d.ts +157 -0
  755. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/Script.d.ts.map +1 -0
  756. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptChunk.d.ts +8 -0
  757. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptChunk.d.ts.map +1 -0
  758. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptEvaluationError.d.ts +24 -0
  759. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptEvaluationError.d.ts.map +1 -0
  760. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptTemplate.d.ts +29 -0
  761. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptTemplate.d.ts.map +1 -0
  762. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptTemplateUnlock.d.ts +7 -0
  763. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/ScriptTemplateUnlock.d.ts.map +1 -0
  764. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/Spend.d.ts +120 -0
  765. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/Spend.d.ts.map +1 -0
  766. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/UnlockingScript.d.ts +25 -0
  767. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/UnlockingScript.d.ts.map +1 -0
  768. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/index.d.ts +11 -0
  769. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/index.d.ts.map +1 -0
  770. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/P2PKH.d.ts +40 -0
  771. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/P2PKH.d.ts.map +1 -0
  772. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/PushDrop.d.ts +56 -0
  773. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/PushDrop.d.ts.map +1 -0
  774. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/RPuzzle.d.ts +47 -0
  775. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/RPuzzle.d.ts.map +1 -0
  776. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/index.d.ts +4 -0
  777. package/mobile/node_modules/@bsv/sdk/dist/types/src/script/templates/index.d.ts.map +1 -0
  778. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageDownloader.d.ts +25 -0
  779. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageDownloader.d.ts.map +1 -0
  780. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageUploader.d.ts +103 -0
  781. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageUploader.d.ts.map +1 -0
  782. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageUtils.d.ts +32 -0
  783. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/StorageUtils.d.ts.map +1 -0
  784. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/index.d.ts +4 -0
  785. package/mobile/node_modules/@bsv/sdk/dist/types/src/storage/index.d.ts.map +1 -0
  786. package/mobile/node_modules/@bsv/sdk/dist/types/src/totp/index.d.ts +2 -0
  787. package/mobile/node_modules/@bsv/sdk/dist/types/src/totp/index.d.ts.map +1 -0
  788. package/mobile/node_modules/@bsv/sdk/dist/types/src/totp/totp.d.ts +42 -0
  789. package/mobile/node_modules/@bsv/sdk/dist/types/src/totp/totp.d.ts.map +1 -0
  790. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Beef.d.ts +248 -0
  791. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Beef.d.ts.map +1 -0
  792. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/BeefParty.d.ts +73 -0
  793. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/BeefParty.d.ts.map +1 -0
  794. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/BeefTx.d.ts +43 -0
  795. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/BeefTx.d.ts.map +1 -0
  796. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Broadcaster.d.ts +55 -0
  797. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Broadcaster.d.ts.map +1 -0
  798. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/ChainTracker.d.ts +29 -0
  799. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/ChainTracker.d.ts.map +1 -0
  800. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/FeeModel.d.ts +12 -0
  801. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/FeeModel.d.ts.map +1 -0
  802. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/MerklePath.d.ts +125 -0
  803. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/MerklePath.d.ts.map +1 -0
  804. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Transaction.d.ts +299 -0
  805. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/Transaction.d.ts.map +1 -0
  806. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/TransactionInput.d.ts +63 -0
  807. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/TransactionInput.d.ts.map +1 -0
  808. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/TransactionOutput.d.ts +36 -0
  809. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/TransactionOutput.d.ts.map +1 -0
  810. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/ARC.d.ts +64 -0
  811. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/ARC.d.ts.map +1 -0
  812. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/DefaultBroadcaster.d.ts +4 -0
  813. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/DefaultBroadcaster.d.ts.map +1 -0
  814. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/Teranode.d.ts +25 -0
  815. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/Teranode.d.ts.map +1 -0
  816. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/WhatsOnChainBroadcaster.d.ts +26 -0
  817. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/WhatsOnChainBroadcaster.d.ts.map +1 -0
  818. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/index.d.ts +6 -0
  819. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/broadcasters/index.d.ts.map +1 -0
  820. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/BlockHeadersService.d.ts +46 -0
  821. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/BlockHeadersService.d.ts.map +1 -0
  822. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/DefaultChainTracker.d.ts +3 -0
  823. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/DefaultChainTracker.d.ts.map +1 -0
  824. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/WhatsOnChain.d.ts +29 -0
  825. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/WhatsOnChain.d.ts.map +1 -0
  826. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/index.d.ts +5 -0
  827. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/chaintrackers/index.d.ts.map +1 -0
  828. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/LivePolicy.d.ts +41 -0
  829. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/LivePolicy.d.ts.map +1 -0
  830. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/SatoshisPerKilobyte.d.ts +26 -0
  831. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/SatoshisPerKilobyte.d.ts.map +1 -0
  832. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/index.d.ts +3 -0
  833. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/fee-models/index.d.ts.map +1 -0
  834. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/BinaryFetchClient.d.ts +48 -0
  835. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/BinaryFetchClient.d.ts.map +1 -0
  836. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/DefaultHttpClient.d.ts +8 -0
  837. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/DefaultHttpClient.d.ts.map +1 -0
  838. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/FetchHttpClient.d.ts +29 -0
  839. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/FetchHttpClient.d.ts.map +1 -0
  840. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/HttpClient.d.ts +45 -0
  841. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/HttpClient.d.ts.map +1 -0
  842. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/NodejsHttpClient.d.ts +20 -0
  843. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/NodejsHttpClient.d.ts.map +1 -0
  844. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/index.d.ts +8 -0
  845. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/http/index.d.ts.map +1 -0
  846. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/index.d.ts +11 -0
  847. package/mobile/node_modules/@bsv/sdk/dist/types/src/transaction/index.d.ts.map +1 -0
  848. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/CachedKeyDeriver.d.ts +102 -0
  849. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/CachedKeyDeriver.d.ts.map +1 -0
  850. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/KeyDeriver.d.ts +130 -0
  851. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/KeyDeriver.d.ts.map +1 -0
  852. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/ProtoWallet.d.ts +27 -0
  853. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/ProtoWallet.d.ts.map +1 -0
  854. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_INSUFFICIENT_FUNDS.d.ts +19 -0
  855. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_INSUFFICIENT_FUNDS.d.ts.map +1 -0
  856. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_INVALID_PARAMETER.d.ts +13 -0
  857. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_INVALID_PARAMETER.d.ts.map +1 -0
  858. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_REVIEW_ACTIONS.d.ts +23 -0
  859. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WERR_REVIEW_ACTIONS.d.ts.map +1 -0
  860. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/Wallet.interfaces.d.ts +1068 -0
  861. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/Wallet.interfaces.d.ts.map +1 -0
  862. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletClient.d.ts +180 -0
  863. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletClient.d.ts.map +1 -0
  864. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletError.d.ts +28 -0
  865. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletError.d.ts.map +1 -0
  866. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletLoggerInterface.d.ts +79 -0
  867. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/WalletLoggerInterface.d.ts.map +1 -0
  868. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/index.d.ts +14 -0
  869. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/index.d.ts.map +1 -0
  870. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/HTTPWalletJSON.d.ts +189 -0
  871. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/HTTPWalletJSON.d.ts.map +1 -0
  872. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/HTTPWalletWire.d.ts +9 -0
  873. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/HTTPWalletWire.d.ts.map +1 -0
  874. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/ReactNativeWebView.d.ts +412 -0
  875. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/ReactNativeWebView.d.ts.map +1 -0
  876. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWire.d.ts +7 -0
  877. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWire.d.ts.map +1 -0
  878. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireCalls.d.ts +33 -0
  879. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireCalls.d.ts.map +1 -0
  880. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireProcessor.d.ts +18 -0
  881. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireProcessor.d.ts.map +1 -0
  882. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireTransceiver.d.ts +196 -0
  883. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/WalletWireTransceiver.d.ts.map +1 -0
  884. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/XDM.d.ts +412 -0
  885. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/XDM.d.ts.map +1 -0
  886. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/index.d.ts +10 -0
  887. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/index.d.ts.map +1 -0
  888. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/utils/toOriginHeader.d.ts +2 -0
  889. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/utils/toOriginHeader.d.ts.map +1 -0
  890. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/window.CWI.d.ts +410 -0
  891. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/substrates/window.CWI.d.ts.map +1 -0
  892. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/validationHelpers.d.ts +514 -0
  893. package/mobile/node_modules/@bsv/sdk/dist/types/src/wallet/validationHelpers.d.ts.map +1 -0
  894. package/mobile/node_modules/@bsv/sdk/dist/types/tsconfig.types.tsbuildinfo +1 -0
  895. package/mobile/node_modules/@bsv/sdk/dist/umd/bundle.js +20 -0
  896. package/mobile/node_modules/@bsv/sdk/dist/umd/bundle.js.map +1 -0
  897. package/mobile/node_modules/@bsv/sdk/docs/fast-docs.png +0 -0
  898. package/mobile/node_modules/@bsv/sdk/docs/index.md +77 -0
  899. package/mobile/node_modules/@bsv/sdk/docs/performance.md +70 -0
  900. package/mobile/node_modules/@bsv/sdk/docs/reference/auth.md +1330 -0
  901. package/mobile/node_modules/@bsv/sdk/docs/reference/compat.md +2951 -0
  902. package/mobile/node_modules/@bsv/sdk/docs/reference/identity.md +383 -0
  903. package/mobile/node_modules/@bsv/sdk/docs/reference/kvstore.md +648 -0
  904. package/mobile/node_modules/@bsv/sdk/docs/reference/messages.md +158 -0
  905. package/mobile/node_modules/@bsv/sdk/docs/reference/overlay-tools.md +691 -0
  906. package/mobile/node_modules/@bsv/sdk/docs/reference/primitives.md +6262 -0
  907. package/mobile/node_modules/@bsv/sdk/docs/reference/registry.md +408 -0
  908. package/mobile/node_modules/@bsv/sdk/docs/reference/script.md +942 -0
  909. package/mobile/node_modules/@bsv/sdk/docs/reference/storage.md +411 -0
  910. package/mobile/node_modules/@bsv/sdk/docs/reference/totp.md +121 -0
  911. package/mobile/node_modules/@bsv/sdk/docs/reference/transaction.md +2332 -0
  912. package/mobile/node_modules/@bsv/sdk/docs/reference/wallet.md +6054 -0
  913. package/mobile/node_modules/@bsv/sdk/docs/requirements.txt +3 -0
  914. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/LICENSE +21 -0
  915. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/favicon-16x16.png +0 -0
  916. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/favicon-32x32.png +0 -0
  917. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/index.css +16 -0
  918. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/oauth2-redirect.html +79 -0
  919. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-initializer.js +20 -0
  920. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-bundle.js +2 -0
  921. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-bundle.js.map +1 -0
  922. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-es-bundle-core.js +3 -0
  923. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-es-bundle-core.js.map +1 -0
  924. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-es-bundle.js +2 -0
  925. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-es-bundle.js.map +1 -0
  926. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-standalone-preset.js +2 -0
  927. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui-standalone-preset.js.map +1 -0
  928. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui.css +3 -0
  929. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui.css.map +1 -0
  930. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui.js +2 -0
  931. package/mobile/node_modules/@bsv/sdk/docs/swagger/dist/swagger-ui.js.map +1 -0
  932. package/mobile/node_modules/@bsv/sdk/docs/swagger/index.html +19 -0
  933. package/mobile/node_modules/@bsv/sdk/docs/swagger/swagger-ui.version +1 -0
  934. package/mobile/node_modules/@bsv/sdk/docs/swagger/swagger.yaml +1960 -0
  935. package/mobile/node_modules/@bsv/sdk/docs/swagger.png +0 -0
  936. package/mobile/node_modules/@bsv/sdk/mod.ts +19 -0
  937. package/mobile/node_modules/@bsv/sdk/package.json +268 -0
  938. package/mobile/node_modules/@bsv/sdk/src/auth/Peer.ts +875 -0
  939. package/mobile/node_modules/@bsv/sdk/src/auth/SessionManager.ts +145 -0
  940. package/mobile/node_modules/@bsv/sdk/src/auth/__tests/Peer.test.ts +1059 -0
  941. package/mobile/node_modules/@bsv/sdk/src/auth/__tests/SessionManager.test.ts +136 -0
  942. package/mobile/node_modules/@bsv/sdk/src/auth/__tests/build.test.ts +11 -0
  943. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/Certificate.ts +311 -0
  944. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/MasterCertificate.ts +360 -0
  945. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/VerifiableCertificate.ts +125 -0
  946. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/__tests/Certificate.test.ts +386 -0
  947. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/__tests/CompletedProtoWallet.ts +202 -0
  948. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/__tests/MasterCertificate.test.ts +424 -0
  949. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/__tests/VerifiableCertificate.test.ts +179 -0
  950. package/mobile/node_modules/@bsv/sdk/src/auth/certificates/index.ts +4 -0
  951. package/mobile/node_modules/@bsv/sdk/src/auth/clients/AuthFetch.ts +881 -0
  952. package/mobile/node_modules/@bsv/sdk/src/auth/clients/__tests__/AuthFetch.test.ts +262 -0
  953. package/mobile/node_modules/@bsv/sdk/src/auth/clients/index.ts +1 -0
  954. package/mobile/node_modules/@bsv/sdk/src/auth/index.ts +7 -0
  955. package/mobile/node_modules/@bsv/sdk/src/auth/transports/SimplifiedFetchTransport.ts +446 -0
  956. package/mobile/node_modules/@bsv/sdk/src/auth/transports/__tests__/SimplifiedFetchTransport.test.ts +126 -0
  957. package/mobile/node_modules/@bsv/sdk/src/auth/transports/index.ts +1 -0
  958. package/mobile/node_modules/@bsv/sdk/src/auth/types.ts +42 -0
  959. package/mobile/node_modules/@bsv/sdk/src/auth/utils/__tests/cryptononce.test.ts +146 -0
  960. package/mobile/node_modules/@bsv/sdk/src/auth/utils/__tests/getVerifiableCertificates.test.ts +152 -0
  961. package/mobile/node_modules/@bsv/sdk/src/auth/utils/__tests/validateCertificates.test.ts +164 -0
  962. package/mobile/node_modules/@bsv/sdk/src/auth/utils/createNonce.ts +33 -0
  963. package/mobile/node_modules/@bsv/sdk/src/auth/utils/getVerifiableCertificates.ts +46 -0
  964. package/mobile/node_modules/@bsv/sdk/src/auth/utils/index.ts +4 -0
  965. package/mobile/node_modules/@bsv/sdk/src/auth/utils/validateCertificates.ts +73 -0
  966. package/mobile/node_modules/@bsv/sdk/src/auth/utils/verifyNonce.ts +34 -0
  967. package/mobile/node_modules/@bsv/sdk/src/compat/BSM.ts +66 -0
  968. package/mobile/node_modules/@bsv/sdk/src/compat/ECIES.ts +701 -0
  969. package/mobile/node_modules/@bsv/sdk/src/compat/HD.ts +386 -0
  970. package/mobile/node_modules/@bsv/sdk/src/compat/Mnemonic.ts +308 -0
  971. package/mobile/node_modules/@bsv/sdk/src/compat/Utxo.ts +59 -0
  972. package/mobile/node_modules/@bsv/sdk/src/compat/__tests/BSM.test.ts +80 -0
  973. package/mobile/node_modules/@bsv/sdk/src/compat/__tests/ECIES.test.ts +184 -0
  974. package/mobile/node_modules/@bsv/sdk/src/compat/__tests/HD.test.ts +417 -0
  975. package/mobile/node_modules/@bsv/sdk/src/compat/__tests/Mnemonic.test.ts +175 -0
  976. package/mobile/node_modules/@bsv/sdk/src/compat/__tests/Mnemonic.vectors.ts +227 -0
  977. package/mobile/node_modules/@bsv/sdk/src/compat/bip-39-wordlist-en.ts +2053 -0
  978. package/mobile/node_modules/@bsv/sdk/src/compat/index.ts +5 -0
  979. package/mobile/node_modules/@bsv/sdk/src/identity/ContactsManager.ts +376 -0
  980. package/mobile/node_modules/@bsv/sdk/src/identity/IdentityClient.ts +497 -0
  981. package/mobile/node_modules/@bsv/sdk/src/identity/README.md +92 -0
  982. package/mobile/node_modules/@bsv/sdk/src/identity/__tests/IdentityClient.test.ts +772 -0
  983. package/mobile/node_modules/@bsv/sdk/src/identity/index.ts +2 -0
  984. package/mobile/node_modules/@bsv/sdk/src/identity/types/index.ts +46 -0
  985. package/mobile/node_modules/@bsv/sdk/src/kvstore/GlobalKVStore.ts +523 -0
  986. package/mobile/node_modules/@bsv/sdk/src/kvstore/LocalKVStore.ts +357 -0
  987. package/mobile/node_modules/@bsv/sdk/src/kvstore/__tests/GlobalKVStore.test.ts +1104 -0
  988. package/mobile/node_modules/@bsv/sdk/src/kvstore/__tests/LocalKVStore.test.ts +686 -0
  989. package/mobile/node_modules/@bsv/sdk/src/kvstore/index.ts +2 -0
  990. package/mobile/node_modules/@bsv/sdk/src/kvstore/kvStoreInterpreter.ts +54 -0
  991. package/mobile/node_modules/@bsv/sdk/src/kvstore/types.ts +126 -0
  992. package/mobile/node_modules/@bsv/sdk/src/messages/EncryptedMessage.ts +74 -0
  993. package/mobile/node_modules/@bsv/sdk/src/messages/SignedMessage.ts +93 -0
  994. package/mobile/node_modules/@bsv/sdk/src/messages/__tests/EncryptedMessage.test.ts +61 -0
  995. package/mobile/node_modules/@bsv/sdk/src/messages/__tests/SignedMessage.test.ts +59 -0
  996. package/mobile/node_modules/@bsv/sdk/src/messages/index.ts +2 -0
  997. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/Historian.ts +195 -0
  998. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/HostReputationTracker.ts +232 -0
  999. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/LookupResolver.ts +499 -0
  1000. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/OverlayAdminTokenTemplate.ts +108 -0
  1001. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/SHIPBroadcaster.ts +504 -0
  1002. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/__tests/Historian.test.ts +690 -0
  1003. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/__tests/LookupResolver.test.ts +1805 -0
  1004. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/__tests/OverlayAdminTokenTemplate.test.ts +97 -0
  1005. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/__tests/SHIPBroadcaster.test.ts +1304 -0
  1006. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/index.ts +11 -0
  1007. package/mobile/node_modules/@bsv/sdk/src/overlay-tools/withDoubleSpendRetry.ts +71 -0
  1008. package/mobile/node_modules/@bsv/sdk/src/primitives/AESGCM.ts +457 -0
  1009. package/mobile/node_modules/@bsv/sdk/src/primitives/BasePoint.ts +21 -0
  1010. package/mobile/node_modules/@bsv/sdk/src/primitives/BigNumber.ts +1368 -0
  1011. package/mobile/node_modules/@bsv/sdk/src/primitives/Curve.ts +1234 -0
  1012. package/mobile/node_modules/@bsv/sdk/src/primitives/DRBG.ts +118 -0
  1013. package/mobile/node_modules/@bsv/sdk/src/primitives/ECDSA.ts +208 -0
  1014. package/mobile/node_modules/@bsv/sdk/src/primitives/Hash.ts +1924 -0
  1015. package/mobile/node_modules/@bsv/sdk/src/primitives/JacobianPoint.ts +475 -0
  1016. package/mobile/node_modules/@bsv/sdk/src/primitives/K256.ts +136 -0
  1017. package/mobile/node_modules/@bsv/sdk/src/primitives/Mersenne.ts +119 -0
  1018. package/mobile/node_modules/@bsv/sdk/src/primitives/MontgomoryMethod.ts +160 -0
  1019. package/mobile/node_modules/@bsv/sdk/src/primitives/Point.ts +1200 -0
  1020. package/mobile/node_modules/@bsv/sdk/src/primitives/Polynomial.ts +94 -0
  1021. package/mobile/node_modules/@bsv/sdk/src/primitives/PrivateKey.ts +524 -0
  1022. package/mobile/node_modules/@bsv/sdk/src/primitives/PublicKey.ts +282 -0
  1023. package/mobile/node_modules/@bsv/sdk/src/primitives/Random.ts +101 -0
  1024. package/mobile/node_modules/@bsv/sdk/src/primitives/ReductionContext.ts +528 -0
  1025. package/mobile/node_modules/@bsv/sdk/src/primitives/Schnorr.ts +117 -0
  1026. package/mobile/node_modules/@bsv/sdk/src/primitives/Secp256r1.ts +334 -0
  1027. package/mobile/node_modules/@bsv/sdk/src/primitives/Signature.ts +389 -0
  1028. package/mobile/node_modules/@bsv/sdk/src/primitives/SymmetricKey.ts +102 -0
  1029. package/mobile/node_modules/@bsv/sdk/src/primitives/TransactionSignature.ts +260 -0
  1030. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/AESGCM.test.ts +700 -0
  1031. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BRC42.private.vectors.ts +48 -0
  1032. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BRC42.public.vectors.ts +48 -0
  1033. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.arithmatic.test.ts +791 -0
  1034. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.binary.test.ts +284 -0
  1035. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.constructor.test.ts +216 -0
  1036. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.dhGroup.test.ts +22 -0
  1037. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.fixtures.ts +272 -0
  1038. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.serializers.test.ts +183 -0
  1039. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/BigNumber.utils.test.ts +437 -0
  1040. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Curve.unit.test.ts +277 -0
  1041. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/DRBG.test.ts +281 -0
  1042. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/DRBG.vectors.ts +137 -0
  1043. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/ECDH.test.ts +38 -0
  1044. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/ECDSA.test.ts +93 -0
  1045. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/HMAC.test.ts +76 -0
  1046. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Hash.test.ts +256 -0
  1047. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/PBKDF2.vectors.ts +132 -0
  1048. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/PrivateKey.split.test.ts +92 -0
  1049. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/PrivateKey.test.ts +98 -0
  1050. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/PublicKey.test.ts +96 -0
  1051. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Random.test.ts +35 -0
  1052. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Reader.test.ts +317 -0
  1053. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/ReductionContext.test.ts +321 -0
  1054. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Schnorr.test.ts +284 -0
  1055. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Secp256r1.test.ts +101 -0
  1056. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/SymmetricKey.test.ts +128 -0
  1057. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/SymmetricKey.vectors.ts +48 -0
  1058. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/SymmetricKeyCompatibility.test.ts +150 -0
  1059. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/Writer.test.ts +208 -0
  1060. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/bug-31.test.ts +27 -0
  1061. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/hex.test.ts +57 -0
  1062. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/sighash.vectors.ts +3503 -0
  1063. package/mobile/node_modules/@bsv/sdk/src/primitives/__tests/utils.test.ts +378 -0
  1064. package/mobile/node_modules/@bsv/sdk/src/primitives/hex.ts +35 -0
  1065. package/mobile/node_modules/@bsv/sdk/src/primitives/index.ts +15 -0
  1066. package/mobile/node_modules/@bsv/sdk/src/primitives/utils.ts +953 -0
  1067. package/mobile/node_modules/@bsv/sdk/src/registry/RegistryClient.ts +667 -0
  1068. package/mobile/node_modules/@bsv/sdk/src/registry/__tests/RegistryClient.test.ts +647 -0
  1069. package/mobile/node_modules/@bsv/sdk/src/registry/index.ts +2 -0
  1070. package/mobile/node_modules/@bsv/sdk/src/registry/types/index.ts +131 -0
  1071. package/mobile/node_modules/@bsv/sdk/src/script/LockingScript.ts +30 -0
  1072. package/mobile/node_modules/@bsv/sdk/src/script/OP.ts +218 -0
  1073. package/mobile/node_modules/@bsv/sdk/src/script/Script.ts +591 -0
  1074. package/mobile/node_modules/@bsv/sdk/src/script/ScriptChunk.ts +7 -0
  1075. package/mobile/node_modules/@bsv/sdk/src/script/ScriptEvaluationError.ts +44 -0
  1076. package/mobile/node_modules/@bsv/sdk/src/script/ScriptTemplate.ts +30 -0
  1077. package/mobile/node_modules/@bsv/sdk/src/script/ScriptTemplateUnlock.ts +7 -0
  1078. package/mobile/node_modules/@bsv/sdk/src/script/Spend.ts +1085 -0
  1079. package/mobile/node_modules/@bsv/sdk/src/script/UnlockingScript.ts +30 -0
  1080. package/mobile/node_modules/@bsv/sdk/src/script/__tests/Script.test.ts +429 -0
  1081. package/mobile/node_modules/@bsv/sdk/src/script/__tests/Spend.test.ts +555 -0
  1082. package/mobile/node_modules/@bsv/sdk/src/script/__tests/SpendComplex.test.ts +48 -0
  1083. package/mobile/node_modules/@bsv/sdk/src/script/__tests/script.invalid.vectors.ts +999 -0
  1084. package/mobile/node_modules/@bsv/sdk/src/script/__tests/script.valid.vectors.ts +1178 -0
  1085. package/mobile/node_modules/@bsv/sdk/src/script/__tests/spend.valid.vectors.ts +2295 -0
  1086. package/mobile/node_modules/@bsv/sdk/src/script/index.ts +10 -0
  1087. package/mobile/node_modules/@bsv/sdk/src/script/templates/P2PKH.ts +157 -0
  1088. package/mobile/node_modules/@bsv/sdk/src/script/templates/PushDrop.ts +281 -0
  1089. package/mobile/node_modules/@bsv/sdk/src/script/templates/RPuzzle.ts +161 -0
  1090. package/mobile/node_modules/@bsv/sdk/src/script/templates/__tests/PushDrop.test.ts +263 -0
  1091. package/mobile/node_modules/@bsv/sdk/src/script/templates/index.ts +3 -0
  1092. package/mobile/node_modules/@bsv/sdk/src/storage/StorageDownloader.ts +114 -0
  1093. package/mobile/node_modules/@bsv/sdk/src/storage/StorageUploader.ts +258 -0
  1094. package/mobile/node_modules/@bsv/sdk/src/storage/StorageUtils.ts +74 -0
  1095. package/mobile/node_modules/@bsv/sdk/src/storage/__tests/StorageDownloader.test.ts +236 -0
  1096. package/mobile/node_modules/@bsv/sdk/src/storage/__tests/StorageUploader.test.ts +219 -0
  1097. package/mobile/node_modules/@bsv/sdk/src/storage/__tests/StorageUtils.test.ts +86 -0
  1098. package/mobile/node_modules/@bsv/sdk/src/storage/index.ts +5 -0
  1099. package/mobile/node_modules/@bsv/sdk/src/totp/__tests/totp.test.ts +81 -0
  1100. package/mobile/node_modules/@bsv/sdk/src/totp/index.ts +1 -0
  1101. package/mobile/node_modules/@bsv/sdk/src/totp/totp.ts +138 -0
  1102. package/mobile/node_modules/@bsv/sdk/src/transaction/Beef.ts +935 -0
  1103. package/mobile/node_modules/@bsv/sdk/src/transaction/BeefParty.ts +123 -0
  1104. package/mobile/node_modules/@bsv/sdk/src/transaction/BeefTx.ts +194 -0
  1105. package/mobile/node_modules/@bsv/sdk/src/transaction/Broadcaster.ts +69 -0
  1106. package/mobile/node_modules/@bsv/sdk/src/transaction/ChainTracker.ts +28 -0
  1107. package/mobile/node_modules/@bsv/sdk/src/transaction/FeeModel.ts +12 -0
  1108. package/mobile/node_modules/@bsv/sdk/src/transaction/MerklePath.ts +455 -0
  1109. package/mobile/node_modules/@bsv/sdk/src/transaction/Transaction.ts +1055 -0
  1110. package/mobile/node_modules/@bsv/sdk/src/transaction/TransactionInput.ts +63 -0
  1111. package/mobile/node_modules/@bsv/sdk/src/transaction/TransactionOutput.ts +36 -0
  1112. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/Beef.test.ts +500 -0
  1113. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/MerklePath.test.ts +249 -0
  1114. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/Transaction.test.ts +1419 -0
  1115. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/bigtx.vectors.ts +5 -0
  1116. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/bump.invalid.vectors.ts +26 -0
  1117. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/bump.valid.vectors.ts +8 -0
  1118. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/tx.invalid.vectors.ts +977 -0
  1119. package/mobile/node_modules/@bsv/sdk/src/transaction/__tests/tx.valid.vectors.ts +1317 -0
  1120. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/ARC.ts +255 -0
  1121. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/DefaultBroadcaster.ts +12 -0
  1122. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/Teranode.ts +77 -0
  1123. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/WhatsOnChainBroadcaster.ts +83 -0
  1124. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/__tests/ARC.test.ts +323 -0
  1125. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/__tests/WhatsOnChainBroadcaster.test.ts +171 -0
  1126. package/mobile/node_modules/@bsv/sdk/src/transaction/broadcasters/index.ts +5 -0
  1127. package/mobile/node_modules/@bsv/sdk/src/transaction/chaintrackers/BlockHeadersService.ts +138 -0
  1128. package/mobile/node_modules/@bsv/sdk/src/transaction/chaintrackers/DefaultChainTracker.ts +6 -0
  1129. package/mobile/node_modules/@bsv/sdk/src/transaction/chaintrackers/WhatsOnChain.ts +102 -0
  1130. package/mobile/node_modules/@bsv/sdk/src/transaction/chaintrackers/__tests/WhatsOnChainChainTracker.test.ts +198 -0
  1131. package/mobile/node_modules/@bsv/sdk/src/transaction/chaintrackers/index.ts +4 -0
  1132. package/mobile/node_modules/@bsv/sdk/src/transaction/fee-models/LivePolicy.ts +97 -0
  1133. package/mobile/node_modules/@bsv/sdk/src/transaction/fee-models/SatoshisPerKilobyte.ts +75 -0
  1134. package/mobile/node_modules/@bsv/sdk/src/transaction/fee-models/__tests/LivePolicy.test.ts +148 -0
  1135. package/mobile/node_modules/@bsv/sdk/src/transaction/fee-models/index.ts +2 -0
  1136. package/mobile/node_modules/@bsv/sdk/src/transaction/http/BinaryFetchClient.ts +141 -0
  1137. package/mobile/node_modules/@bsv/sdk/src/transaction/http/DefaultHttpClient.ts +33 -0
  1138. package/mobile/node_modules/@bsv/sdk/src/transaction/http/FetchHttpClient.ts +57 -0
  1139. package/mobile/node_modules/@bsv/sdk/src/transaction/http/HttpClient.ts +51 -0
  1140. package/mobile/node_modules/@bsv/sdk/src/transaction/http/NodejsHttpClient.ts +67 -0
  1141. package/mobile/node_modules/@bsv/sdk/src/transaction/http/index.ts +11 -0
  1142. package/mobile/node_modules/@bsv/sdk/src/transaction/index.ts +14 -0
  1143. package/mobile/node_modules/@bsv/sdk/src/wallet/CachedKeyDeriver.ts +287 -0
  1144. package/mobile/node_modules/@bsv/sdk/src/wallet/KeyDeriver.ts +342 -0
  1145. package/mobile/node_modules/@bsv/sdk/src/wallet/ProtoWallet.ts +300 -0
  1146. package/mobile/node_modules/@bsv/sdk/src/wallet/WERR_INSUFFICIENT_FUNDS.ts +25 -0
  1147. package/mobile/node_modules/@bsv/sdk/src/wallet/WERR_INVALID_PARAMETER.ts +20 -0
  1148. package/mobile/node_modules/@bsv/sdk/src/wallet/WERR_REVIEW_ACTIONS.ts +30 -0
  1149. package/mobile/node_modules/@bsv/sdk/src/wallet/Wallet.interfaces.ts +1308 -0
  1150. package/mobile/node_modules/@bsv/sdk/src/wallet/WalletClient.ts +504 -0
  1151. package/mobile/node_modules/@bsv/sdk/src/wallet/WalletError.ts +81 -0
  1152. package/mobile/node_modules/@bsv/sdk/src/wallet/WalletLoggerInterface.ts +85 -0
  1153. package/mobile/node_modules/@bsv/sdk/src/wallet/__tests/CachedKeyDeriver.test.ts +381 -0
  1154. package/mobile/node_modules/@bsv/sdk/src/wallet/__tests/KeyDeriver.test.ts +221 -0
  1155. package/mobile/node_modules/@bsv/sdk/src/wallet/__tests/ProtoWallet.test.ts +592 -0
  1156. package/mobile/node_modules/@bsv/sdk/src/wallet/__tests/WalletClient.test.ts +31 -0
  1157. package/mobile/node_modules/@bsv/sdk/src/wallet/index.ts +14 -0
  1158. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/HTTPWalletJSON.ts +364 -0
  1159. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/HTTPWalletWire.ts +51 -0
  1160. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/ReactNativeWebView.ts +560 -0
  1161. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/WalletWire.ts +6 -0
  1162. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/WalletWireCalls.ts +34 -0
  1163. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/WalletWireProcessor.ts +2206 -0
  1164. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/WalletWireTransceiver.ts +2032 -0
  1165. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/XDM.ts +547 -0
  1166. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/__tests/WalletWire.integration.test.ts +2353 -0
  1167. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/__tests/XDM.test.ts +660 -0
  1168. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/__tests/toOriginHeader.test.ts +34 -0
  1169. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/index.ts +9 -0
  1170. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/utils/toOriginHeader.ts +15 -0
  1171. package/mobile/node_modules/@bsv/sdk/src/wallet/substrates/window.CWI.ts +593 -0
  1172. package/mobile/node_modules/@bsv/sdk/src/wallet/validationHelpers.ts +1215 -0
  1173. package/mobile/out/src/sdk/types.d.ts +1 -1
  1174. package/mobile/out/src/sdk/types.js +1 -1
  1175. package/mobile/out/src/storage/methods/ListOutputsSpecOp.d.ts.map +1 -1
  1176. package/mobile/out/src/storage/methods/ListOutputsSpecOp.js +2 -0
  1177. package/mobile/out/src/storage/methods/ListOutputsSpecOp.js.map +1 -1
  1178. package/mobile/package-lock.json +6 -6
  1179. package/mobile/package.json +2 -2
  1180. package/out/src/sdk/types.d.ts +1 -1
  1181. package/out/src/sdk/types.js +1 -1
  1182. package/out/src/storage/methods/ListOutputsSpecOp.d.ts.map +1 -1
  1183. package/out/src/storage/methods/ListOutputsSpecOp.js +2 -0
  1184. package/out/src/storage/methods/ListOutputsSpecOp.js.map +1 -1
  1185. package/out/test/Wallet/local/localWallet2.man.test.js +3 -2
  1186. package/out/test/Wallet/local/localWallet2.man.test.js.map +1 -1
  1187. package/out/test/Wallet/support/operations.man.test.js +11 -4
  1188. package/out/test/Wallet/support/operations.man.test.js.map +1 -1
  1189. package/out/tsconfig.all.tsbuildinfo +1 -1
  1190. package/package.json +2 -2
  1191. package/src/sdk/types.ts +1 -1
  1192. package/src/storage/methods/ListOutputsSpecOp.ts +1 -0
  1193. package/test/Wallet/local/localWallet2.man.test.ts +2 -2
  1194. package/test/Wallet/support/operations.man.test.ts +11 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.js","sources":["webpack://bsv/./dist/esm/src/primitives/Curve.js","webpack://bsv/./dist/esm/src/primitives/Hash.js","webpack://bsv/./dist/esm/src/transaction/Beef.js","webpack://bsv/./dist/esm/src/wallet/Wallet.interfaces.js","webpack://bsv/./dist/esm/src/wallet/WalletError.js","webpack://bsv/./dist/esm/src/wallet/substrates/WalletWireCalls.js","webpack://bsv/webpack/runtime/define_property_getters","webpack://bsv/webpack/runtime/has_own_property","webpack://bsv/webpack/runtime/make_namespace_object","webpack://bsv/./dist/esm/src/primitives/BigNumber.js","webpack://bsv/./dist/esm/src/primitives/Mersenne.js","webpack://bsv/./dist/esm/src/primitives/K256.js","webpack://bsv/./dist/esm/src/primitives/ReductionContext.js","webpack://bsv/./dist/esm/src/primitives/MontgomoryMethod.js","webpack://bsv/./dist/esm/src/primitives/BasePoint.js","webpack://bsv/./dist/esm/src/primitives/JacobianPoint.js","webpack://bsv/./dist/esm/src/primitives/hex.js","webpack://bsv/./dist/esm/src/primitives/utils.js","webpack://bsv/./dist/esm/src/primitives/Point.js","webpack://bsv/./dist/esm/src/primitives/Signature.js","webpack://bsv/./dist/esm/src/primitives/DRBG.js","webpack://bsv/./dist/esm/src/primitives/ECDSA.js","webpack://bsv/./dist/esm/src/primitives/PublicKey.js","webpack://bsv/./dist/esm/src/primitives/Random.js","webpack://bsv/./dist/esm/src/primitives/Polynomial.js","webpack://bsv/./dist/esm/src/primitives/PrivateKey.js","webpack://bsv/./dist/esm/src/primitives/AESGCM.js","webpack://bsv/./dist/esm/src/primitives/SymmetricKey.js","webpack://bsv/./dist/esm/src/primitives/TransactionSignature.js","webpack://bsv/./dist/esm/src/primitives/Schnorr.js","webpack://bsv/./dist/esm/src/primitives/Secp256r1.js","webpack://bsv/./dist/esm/src/script/OP.js","webpack://bsv/./dist/esm/src/script/Script.js","webpack://bsv/./dist/esm/src/script/LockingScript.js","webpack://bsv/./dist/esm/src/script/UnlockingScript.js","webpack://bsv/./dist/esm/src/script/ScriptEvaluationError.js","webpack://bsv/./dist/esm/src/script/Spend.js","webpack://bsv/./dist/esm/src/script/templates/P2PKH.js","webpack://bsv/./dist/esm/src/script/templates/RPuzzle.js","webpack://bsv/./dist/esm/src/script/templates/PushDrop.js","webpack://bsv/./dist/esm/src/transaction/fee-models/SatoshisPerKilobyte.js","webpack://bsv/./dist/esm/src/transaction/fee-models/LivePolicy.js","webpack://bsv/./dist/esm/src/transaction/http/NodejsHttpClient.js","webpack://bsv/./dist/esm/src/transaction/http/FetchHttpClient.js","webpack://bsv/./dist/esm/src/transaction/http/DefaultHttpClient.js","webpack://bsv/./dist/esm/src/transaction/broadcasters/ARC.js","webpack://bsv/./dist/esm/src/transaction/broadcasters/DefaultBroadcaster.js","webpack://bsv/./dist/esm/src/transaction/chaintrackers/WhatsOnChain.js","webpack://bsv/./dist/esm/src/transaction/chaintrackers/DefaultChainTracker.js","webpack://bsv/./dist/esm/src/transaction/MerklePath.js","webpack://bsv/./dist/esm/src/transaction/BeefTx.js","webpack://bsv/./dist/esm/src/transaction/Transaction.js","webpack://bsv/./dist/esm/src/transaction/Broadcaster.js","webpack://bsv/./dist/esm/src/transaction/BeefParty.js","webpack://bsv/./dist/esm/src/transaction/broadcasters/WhatsOnChainBroadcaster.js","webpack://bsv/./dist/esm/src/transaction/http/BinaryFetchClient.js","webpack://bsv/./dist/esm/src/transaction/broadcasters/Teranode.js","webpack://bsv/./dist/esm/src/transaction/chaintrackers/BlockHeadersService.js","webpack://bsv/./dist/esm/src/messages/SignedMessage.js","webpack://bsv/./dist/esm/src/messages/EncryptedMessage.js","webpack://bsv/./dist/esm/src/compat/BSM.js","webpack://bsv/./dist/esm/src/compat/HD.js","webpack://bsv/./dist/esm/src/compat/bip-39-wordlist-en.js","webpack://bsv/./dist/esm/src/compat/Mnemonic.js","webpack://bsv/./dist/esm/src/compat/ECIES.js","webpack://bsv/./dist/esm/src/compat/Utxo.js","webpack://bsv/./dist/esm/src/totp/totp.js","webpack://bsv/./dist/esm/src/wallet/KeyDeriver.js","webpack://bsv/./dist/esm/src/wallet/CachedKeyDeriver.js","webpack://bsv/./dist/esm/src/wallet/ProtoWallet.js","webpack://bsv/./dist/esm/src/wallet/substrates/window.CWI.js","webpack://bsv/./dist/esm/src/wallet/substrates/XDM.js","webpack://bsv/./dist/esm/src/auth/certificates/Certificate.js","webpack://bsv/./dist/esm/src/wallet/substrates/WalletWireTransceiver.js","webpack://bsv/./dist/esm/src/wallet/substrates/HTTPWalletWire.js","webpack://bsv/./dist/esm/src/wallet/WERR_REVIEW_ACTIONS.js","webpack://bsv/./dist/esm/src/wallet/WERR_INVALID_PARAMETER.js","webpack://bsv/./dist/esm/src/wallet/WERR_INSUFFICIENT_FUNDS.js","webpack://bsv/./dist/esm/src/wallet/substrates/HTTPWalletJSON.js","webpack://bsv/./dist/esm/src/wallet/substrates/utils/toOriginHeader.js","webpack://bsv/./dist/esm/src/wallet/substrates/ReactNativeWebView.js","webpack://bsv/./dist/esm/src/wallet/validationHelpers.js","webpack://bsv/./dist/esm/src/wallet/WalletClient.js","webpack://bsv/./dist/esm/src/wallet/substrates/WalletWireProcessor.js","webpack://bsv/./dist/esm/src/auth/certificates/MasterCertificate.js","webpack://bsv/./dist/esm/src/auth/certificates/VerifiableCertificate.js","webpack://bsv/./dist/esm/src/auth/certificates/__tests/CompletedProtoWallet.js","webpack://bsv/./dist/esm/src/auth/SessionManager.js","webpack://bsv/./dist/esm/src/auth/utils/verifyNonce.js","webpack://bsv/./dist/esm/src/auth/utils/createNonce.js","webpack://bsv/./dist/esm/src/auth/utils/getVerifiableCertificates.js","webpack://bsv/./dist/esm/src/auth/utils/validateCertificates.js","webpack://bsv/./dist/esm/src/auth/Peer.js","webpack://bsv/./dist/esm/src/auth/transports/SimplifiedFetchTransport.js","webpack://bsv/./dist/esm/src/auth/clients/AuthFetch.js","webpack://bsv/./dist/esm/src/overlay-tools/OverlayAdminTokenTemplate.js","webpack://bsv/./dist/esm/src/overlay-tools/HostReputationTracker.js","webpack://bsv/./dist/esm/src/overlay-tools/LookupResolver.js","webpack://bsv/./dist/esm/src/overlay-tools/SHIPBroadcaster.js","webpack://bsv/./dist/esm/src/overlay-tools/withDoubleSpendRetry.js","webpack://bsv/./dist/esm/src/storage/StorageUtils.js","webpack://bsv/./dist/esm/src/storage/StorageUploader.js","webpack://bsv/./dist/esm/src/storage/StorageDownloader.js","webpack://bsv/./dist/esm/src/identity/types/index.js","webpack://bsv/./dist/esm/src/identity/ContactsManager.js","webpack://bsv/./dist/esm/src/identity/IdentityClient.js","webpack://bsv/./dist/esm/src/registry/RegistryClient.js","webpack://bsv/./dist/esm/src/kvstore/LocalKVStore.js","webpack://bsv/./dist/esm/src/overlay-tools/Historian.js","webpack://bsv/./dist/esm/src/kvstore/types.js","webpack://bsv/./dist/esm/src/kvstore/kvStoreInterpreter.js","webpack://bsv/./dist/esm/src/kvstore/GlobalKVStore.js"],"sourcesContent":["import BigNumber from './BigNumber.js';\nimport ReductionContext from './ReductionContext.js';\nimport MontgomoryMethod from './MontgomoryMethod.js';\nimport Point from './Point.js';\nimport { toArray } from './utils.js';\n// This ensures that only one curve is ever created, enhancing performance.\n// This assumes there is never a need to have multiple distinct Curve instances.\n// So far, this assumption has proven to be valid.\nlet globalCurve;\nexport default class Curve {\n p;\n red;\n redN;\n zero;\n one;\n two;\n g;\n n;\n a;\n b;\n tinv;\n zeroA;\n threeA;\n endo; // beta, lambda, basis\n _endoWnafT1;\n _endoWnafT2;\n _wnafT1;\n _wnafT2;\n _wnafT3;\n _wnafT4;\n _bitLength;\n // Represent num in a w-NAF form\n static assert(expression, message = 'Elliptic curve assertion failed') {\n if (!expression) {\n throw new Error(message);\n }\n }\n getNAF(num, w, bits) {\n const naf = new Array(Math.max(num.bitLength(), bits) + 1);\n naf.fill(0);\n const ws = 1 << (w + 1);\n const k = num.clone();\n for (let i = 0; i < naf.length; i++) {\n let z;\n const mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1) {\n z = (ws >> 1) - mod;\n }\n else {\n z = mod;\n }\n k.isubn(z);\n }\n else {\n z = 0;\n }\n naf[i] = z;\n k.iushrn(1);\n }\n return naf;\n }\n // Represent k1, k2 in a Joint Sparse Form\n getJSF(k1, k2) {\n const jsf = [[], []];\n k1 = k1.clone();\n k2 = k2.clone();\n let d1 = 0;\n let d2 = 0;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n let m14 = (k1.andln(3) + d1) & 3;\n let m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3) {\n m14 = -1;\n }\n if (m24 === 3) {\n m24 = -1;\n }\n let u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n }\n else {\n const m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2) {\n u1 = -m14;\n }\n else {\n u1 = m14;\n }\n }\n jsf[0].push(u1);\n let u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n }\n else {\n const m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2) {\n u2 = -m24;\n }\n else {\n u2 = m24;\n }\n }\n jsf[1].push(u2);\n // Second phase\n if (2 * d1 === u1 + 1) {\n d1 = 1 - d1;\n }\n if (2 * d2 === u2 + 1) {\n d2 = 1 - d2;\n }\n k1.iushrn(1);\n k2.iushrn(1);\n }\n return jsf;\n }\n static cachedProperty(obj, name, computer) {\n const key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n const r = this[key] !== undefined ? this[key] : (this[key] = computer.call(this));\n return r;\n };\n }\n static parseBytes(bytes) {\n return typeof bytes === 'string' ? toArray(bytes, 'hex') : bytes;\n }\n static intFromLE(bytes) {\n return new BigNumber(bytes, 'hex', 'le');\n }\n constructor() {\n if (typeof globalCurve !== 'undefined') {\n return globalCurve;\n }\n else {\n /* eslint-disable @typescript-eslint/no-this-alias */\n globalCurve = this;\n }\n const precomputed = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'\n ]\n ]\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'\n ]\n ]\n }\n };\n const conf = {\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3'\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15'\n }\n ],\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n precomputed\n ]\n };\n this.p = new BigNumber(conf.p, 16);\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = new ReductionContext(conf.prime);\n // Useful for many curves\n this.zero = new BigNumber(0).toRed(this.red);\n this.one = new BigNumber(1).toRed(this.red);\n this.two = new BigNumber(2).toRed(this.red);\n // Curve configuration, optional\n this.n = new BigNumber(conf.n, 16);\n this.g = Point.fromJSON(conf.g, conf.gRed);\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n this._bitLength = this.n.bitLength();\n this.redN = this.n.toRed(this.red);\n this.a = new BigNumber(conf.a, 16).toRed(this.red);\n this.b = new BigNumber(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n }\n _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || this.p.modrn(3) !== 1) {\n return;\n }\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n let beta;\n let lambda;\n if (conf.beta !== undefined) {\n beta = new BigNumber(conf.beta, 16).toRed(this.red);\n }\n else {\n const betas = this._getEndoRoots(this.p);\n if (betas === null) {\n throw new Error('Failed to get endomorphism roots for beta.');\n }\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda !== undefined) {\n lambda = new BigNumber(conf.lambda, 16);\n }\n else {\n // Choose the lambda that matches selected beta\n const lambdas = this._getEndoRoots(this.n);\n if (lambdas === null) {\n throw new Error('Failed to get endomorphism roots for lambda.');\n }\n if (this.g == null) {\n throw new Error('Curve generator point (g) is not defined.');\n }\n const gMulX = this.g.mul(lambdas[0])?.x;\n const gXRedMulBeta = (this.g.x != null) ? this.g.x.redMul(beta) : undefined;\n if ((gMulX != null) && (gXRedMulBeta != null) && gMulX.cmp(gXRedMulBeta) === 0) {\n lambda = lambdas[0];\n }\n else {\n lambda = lambdas[1];\n if (this.g == null) {\n throw new Error('Curve generator point (g) is not defined.');\n }\n const gMulX = this.g.mul(lambda)?.x;\n const gXRedMulBeta = (this.g.x != null) ? this.g.x.redMul(beta) : undefined;\n if ((gMulX == null) || (gXRedMulBeta == null)) {\n throw new Error('Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.');\n }\n Curve.assert(gMulX.cmp(gXRedMulBeta) === 0, 'Lambda selection does not match computed beta.');\n }\n }\n // Get basis vectors, used for balanced length-two representation\n let basis;\n if (typeof conf.basis === 'object' && conf.basis !== null) {\n basis = conf.basis.map(function (vec) {\n return {\n a: new BigNumber(vec.a, 16),\n b: new BigNumber(vec.b, 16)\n };\n });\n }\n else {\n basis = this._getEndoBasis(lambda);\n }\n return {\n beta,\n lambda,\n basis\n };\n }\n _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n const red = num === this.p ? this.red : new MontgomoryMethod(num);\n const tinv = new BigNumber(2).toRed(red).redInvm();\n const ntinv = tinv.redNeg();\n const s = new BigNumber(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n const l1 = ntinv.redAdd(s).fromRed();\n const l2 = ntinv.redSub(s).fromRed();\n return [l1, l2];\n }\n _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n const aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n let u = lambda;\n let v = this.n.clone();\n let x1 = new BigNumber(1);\n let y1 = new BigNumber(0);\n let x2 = new BigNumber(0);\n let y2 = new BigNumber(1);\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n let a0;\n let b0;\n // First vector\n let a1;\n let b1;\n // Second vector\n let a2;\n let b2;\n let prevR = new BigNumber(0);\n let i = 0;\n let r = new BigNumber(0);\n let x = new BigNumber(0); // Ensure x is initialized\n while (u.cmpn(0) !== 0) {\n const q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1)); // Now TypeScript knows x is always assigned\n const y = y2.sub(q.mul(y1));\n if (a1 === undefined && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n }\n else if (a1 !== undefined && ++i === 2) {\n break;\n }\n prevR = r;\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n // Ensure a0 and b0 have been assigned\n if (a0 === undefined ||\n b0 === undefined ||\n a1 === undefined ||\n b1 === undefined) {\n throw new Error('Failed to compute Endo Basis values');\n }\n a2 = r.neg();\n b2 = x;\n const len1 = a1.sqr().add(b1.sqr());\n const len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n // Normalize signs\n if (a1.negative !== 0) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative !== 0) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 }\n ];\n }\n _endoSplit(k) {\n if (this.endo == null) {\n throw new Error('Endomorphism is not defined.');\n }\n const basis = this.endo.basis;\n const v1 = basis[0];\n const v2 = basis[1];\n const c1 = v2.b.mul(k).divRound(this.n);\n const c2 = v1.b.neg().mul(k).divRound(this.n);\n const p1 = c1.mul(v1.a);\n const p2 = c2.mul(v2.a);\n const q1 = c1.mul(v1.b);\n const q2 = c2.mul(v2.b);\n // Calculate answer\n const k1 = k.sub(p1).sub(p2);\n const k2 = q1.add(q2).neg();\n return { k1, k2 };\n }\n validate(point) {\n if (point.inf) {\n return true;\n }\n const x = point.x;\n const y = point.y;\n // Ensure x and y are not null before proceeding\n if (x === null || y === null) {\n throw new Error('Point coordinates cannot be null');\n }\n const ax = this.a.redMul(x);\n const rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n }\n}\n//# sourceMappingURL=Curve.js.map","// @ts-nocheck\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { assertValidHex, normalizeHex } from './hex.js';\nconst assert = (expression, message = 'Hash assertion failed') => {\n if (!expression) {\n throw new Error(message);\n }\n};\n/**\n * The BaseHash class is an abstract base class for cryptographic hash functions.\n * It provides a common structure and functionality for hash function classes.\n *\n * @class BaseHash\n *\n * @property pending - Stores partially processed message segments.\n * @property pendingTotal - The total number of characters that are being stored in `pending`\n * @property blockSize - The size of each block to processed.\n * @property outSize - The size of the final hash output.\n * @property endian - The endianness used during processing, can either be 'big' or 'little'.\n * @property _delta8 - The block size divided by 8, useful in various computations.\n * @property _delta32 - The block size divided by 32, useful in various computations.\n * @property padLength - The length of padding to be added to finalize the computation.\n * @property hmacStrength - The HMAC strength value.\n *\n * @param blockSize - The size of the block to be hashed.\n * @param outSize - The size of the resulting hash.\n * @param hmacStrength - The strength of the HMAC.\n * @param padLength - The length of the padding to be added.\n *\n * @example\n * Sub-classes would extend this base BaseHash class like:\n * class RIPEMD160 extends BaseHash {\n * constructor () {\n * super(512, 160, 192, 64);\n * // ...\n * }\n * // ...\n * }\n */\nclass BaseHash {\n pending;\n pendingTotal;\n blockSize;\n outSize;\n endian;\n _delta8;\n _delta32;\n padLength;\n hmacStrength;\n constructor(blockSize, outSize, hmacStrength, padLength) {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = blockSize;\n this.outSize = outSize;\n this.hmacStrength = hmacStrength;\n this.padLength = padLength / 8;\n this.endian = 'big';\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n }\n _update(msg, start) {\n throw new Error('Not implemented');\n }\n _digest() {\n throw new Error('Not implemented');\n }\n _digestHex() {\n throw new Error('Not implemented');\n }\n /**\n * Converts the input message into an array, pads it, and joins into 32bit blocks.\n * If there is enough data, it tries updating the hash computation.\n *\n * @method update\n * @param msg - The message segment to include in the hashing computation.\n * @param enc - The encoding of the message. If 'hex', the string will be treated as such, 'utf8' otherwise.\n *\n * @returns Returns the instance of the object for chaining.\n *\n * @example\n * sha256.update('Hello World', 'utf8');\n */\n update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = toArray(msg, enc);\n if (this.pending == null) {\n this.pending = msg;\n }\n else {\n this.pending = this.pending.concat(msg);\n }\n this.pendingTotal += msg.length;\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n // Process pending data in blocks\n const r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0) {\n this.pending = null;\n }\n msg = join32(msg, 0, msg.length - r, this.endian);\n for (let i = 0; i < msg.length; i += this._delta32) {\n this._update(msg, i);\n }\n }\n return this;\n }\n /**\n * Finalizes the hash computation and returns the hash value/result.\n *\n * @method digest\n *\n * @returns Returns the final hash value.\n *\n * @example\n * const hash = sha256.digest();\n */\n digest() {\n this.update(this._pad());\n assert(this.pending === null);\n return this._digest();\n }\n /**\n * Finalizes the hash computation and returns the hash value/result as a hex string.\n *\n * @method digest\n *\n * @returns Returns the final hash value as a hex string.\n *\n * @example\n * const hash = sha256.digestHex();\n */\n digestHex() {\n this.update(this._pad());\n assert(this.pending === null);\n return this._digestHex();\n }\n /**\n * [Private Method] Used internally to prepare the padding for the final stage of the hash computation.\n *\n * @method _pad\n * @private\n *\n * @returns Returns an array denoting the padding.\n */\n _pad() {\n const len = this.pendingTotal;\n if (!Number.isSafeInteger(len) || len < 0) {\n throw new Error('Message too long for this hash function');\n }\n const bytes = this._delta8;\n const k = bytes - ((len + this.padLength) % bytes);\n const res = new Array(k + this.padLength);\n res[0] = 0x80;\n let i;\n for (i = 1; i < k; i++) {\n res[i] = 0;\n }\n const lengthBytes = this.padLength;\n const maxBits = 1n << BigInt(lengthBytes * 8);\n let totalBits = BigInt(len) * 8n;\n if (totalBits >= maxBits) {\n throw new Error('Message too long for this hash function');\n }\n if (this.endian === 'big') {\n const lenArray = new Array(lengthBytes);\n for (let b = lengthBytes - 1; b >= 0; b--) {\n lenArray[b] = Number(totalBits & 0xffn);\n totalBits >>= 8n;\n }\n for (let b = 0; b < lengthBytes; b++) {\n res[i++] = lenArray[b];\n }\n }\n else {\n for (let b = 0; b < lengthBytes; b++) {\n res[i++] = Number(totalBits & 0xffn);\n totalBits >>= 8n;\n }\n }\n return res;\n }\n}\nfunction isSurrogatePair(msg, i) {\n if ((msg.charCodeAt(i) & 0xfc00) !== 0xd800) {\n return false;\n }\n if (i < 0 || i + 1 >= msg.length) {\n return false;\n }\n return (msg.charCodeAt(i + 1) & 0xfc00) === 0xdc00;\n}\n/**\n *\n * @param msg\n * @param enc Optional. Encoding to use if msg is string. Default is 'utf8'.\n * @returns array of byte values from msg. If msg is an array, a copy is returned.\n */\nexport function toArray(msg, enc) {\n if (Array.isArray(msg)) {\n return msg.slice();\n }\n if (!msg) {\n return [];\n }\n const res = [];\n if (typeof msg === 'string') {\n if (enc !== 'hex') {\n // Inspired by stringToUtf8ByteArray() in closure-library by Google\n // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt#L117-L143\n // Apache License 2.0\n // https://github.com/google/closure-library/blob/master/LICENSE\n let p = 0;\n for (let i = 0; i < msg.length; i++) {\n let c = msg.charCodeAt(i);\n if (c < 128) {\n res[p++] = c;\n }\n else if (c < 2048) {\n res[p++] = (c >> 6) | 192;\n res[p++] = (c & 63) | 128;\n }\n else if (isSurrogatePair(msg, i)) {\n c = 0x10000 + ((c & 0x03ff) << 10) + (msg.charCodeAt(++i) & 0x03ff);\n res[p++] = (c >> 18) | 240;\n res[p++] = ((c >> 12) & 63) | 128;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n }\n else {\n res[p++] = (c >> 12) | 224;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n }\n }\n }\n else {\n assertValidHex(msg);\n msg = normalizeHex(msg);\n for (let i = 0; i < msg.length; i += 2) {\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n }\n }\n else {\n msg = msg;\n for (let i = 0; i < msg.length; i++) {\n res[i] = msg[i] | 0;\n }\n }\n return res;\n}\n/**\n * @deprecated\n * This function behaves differently from the standard C `htonl()`.\n * It always performs an unconditional 32-bit byte swap.\n * Use `swapBytes32()` for explicit byte swapping, or `realHtonl()` for\n * standards-compliant host-to-network conversion.\n */\nexport function htonl(w) {\n return swapBytes32(w);\n}\nfunction toHex32(msg, endian) {\n let res = '';\n for (let i = 0; i < msg.length; i++) {\n let w = msg[i];\n if (endian === 'little') {\n w = htonl(w);\n }\n res += zero8(w.toString(16));\n }\n return res;\n}\nfunction zero8(word) {\n if (word.length === 7) {\n return '0' + word;\n }\n else if (word.length === 6) {\n return '00' + word;\n }\n else if (word.length === 5) {\n return '000' + word;\n }\n else if (word.length === 4) {\n return '0000' + word;\n }\n else if (word.length === 3) {\n return '00000' + word;\n }\n else if (word.length === 2) {\n return '000000' + word;\n }\n else if (word.length === 1) {\n return '0000000' + word;\n }\n else {\n return word;\n }\n}\nfunction bytesToHex(data) {\n let res = '';\n for (const b of data)\n res += b.toString(16).padStart(2, '0');\n return res;\n}\nfunction join32(msg, start, end, endian) {\n const len = end - start;\n assert(len % 4 === 0);\n const res = new Array(len / 4);\n for (let i = 0, k = start; i < res.length; i++, k += 4) {\n let w;\n if (endian === 'big') {\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n }\n else {\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n }\n res[i] = w >>> 0;\n }\n return res;\n}\nfunction split32(msg, endian) {\n const res = new Array(msg.length * 4);\n for (let i = 0, k = 0; i < msg.length; i++, k += 4) {\n const m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n }\n else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nfunction SUM32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nfunction SUM32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nfunction SUM32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nfunction FT_1(s, x, y, z) {\n if (s === 0) {\n return ch32(x, y, z);\n }\n if (s === 1 || s === 3) {\n return p32(x, y, z);\n }\n if (s === 2) {\n return maj32(x, y, z);\n }\n return 0;\n}\nfunction ch32(x, y, z) {\n return (x & y) ^ (~x & z);\n}\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nfunction S0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nfunction S1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nfunction G0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nfunction G1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nconst r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15,\n 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11,\n 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7,\n 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\nconst rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5,\n 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0,\n 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1,\n 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\nconst s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7,\n 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5,\n 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5,\n 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\nconst sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8,\n 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14,\n 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5,\n 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\nfunction f(j, x, y, z) {\n if (j <= 15) {\n return x ^ y ^ z;\n }\n else if (j <= 31) {\n return (x & y) | (~x & z);\n }\n else if (j <= 47) {\n return (x | ~y) ^ z;\n }\n else if (j <= 63) {\n return (x & z) | (y & ~z);\n }\n else {\n return x ^ (y | ~z);\n }\n}\nfunction K(j) {\n if (j <= 15) {\n return 0x00000000;\n }\n else if (j <= 31) {\n return 0x5a827999;\n }\n else if (j <= 47) {\n return 0x6ed9eba1;\n }\n else if (j <= 63) {\n return 0x8f1bbcdc;\n }\n else {\n return 0xa953fd4e;\n }\n}\nfunction Kh(j) {\n if (j <= 15) {\n return 0x50a28be6;\n }\n else if (j <= 31) {\n return 0x5c4dd124;\n }\n else if (j <= 47) {\n return 0x6d703ef3;\n }\n else if (j <= 63) {\n return 0x7a6d76e9;\n }\n else {\n return 0x00000000;\n }\n}\n/**\n * An implementation of RIPEMD160 cryptographic hash function. Extends the BaseHash class.\n * It provides a way to compute a 'digest' for any kind of input data; transforming the data\n * into a unique output of fixed size. The output is deterministic; it will always be\n * the same for the same input.\n *\n * @class RIPEMD160\n * @param None\n *\n * @constructor\n * Use the RIPEMD160 constructor to create an instance of RIPEMD160 hash function.\n *\n * @example\n * const ripemd160 = new RIPEMD160();\n *\n * @property h - Array that is updated iteratively as part of hashing computation.\n */\nexport class RIPEMD160 extends BaseHash {\n h;\n constructor() {\n super(512, 160, 192, 64);\n this.endian = 'little';\n this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n this.endian = 'little';\n }\n _update(msg, start) {\n let A = this.h[0];\n let B = this.h[1];\n let C = this.h[2];\n let D = this.h[3];\n let E = this.h[4];\n let Ah = A;\n let Bh = B;\n let Ch = C;\n let Dh = D;\n let Eh = E;\n let T;\n for (let j = 0; j < 80; j++) {\n T = sum32(rotl32(SUM32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(rotl32(SUM32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = SUM32_3(this.h[1], C, Dh);\n this.h[1] = SUM32_3(this.h[2], D, Eh);\n this.h[2] = SUM32_3(this.h[3], E, Ah);\n this.h[3] = SUM32_3(this.h[4], A, Bh);\n this.h[4] = SUM32_3(this.h[0], B, Ch);\n this.h[0] = T;\n }\n _digest() {\n return split32(this.h, 'little');\n }\n _digestHex() {\n return toHex32(this.h, 'little');\n }\n}\n/**\n * An implementation of SHA256 cryptographic hash function. Extends the BaseHash class.\n * It provides a way to compute a 'digest' for any kind of input data; transforming the data\n * into a unique output of fixed size. The output is deterministic; it will always be\n * the same for the same input.\n *\n * @class SHA256\n * @param None\n *\n * @constructor\n * Use the SHA256 constructor to create an instance of SHA256 hash function.\n *\n * @example\n * const sha256 = new SHA256();\n *\n * @property h - The initial hash constants\n * @property W - Provides a way to recycle usage of the array memory.\n * @property k - The round constants used for each round of SHA-256\n */\nexport class SHA256 {\n h;\n constructor() {\n this.h = new FastSHA256();\n }\n update(msg, enc) {\n const data = msg instanceof Uint8Array ? msg : Uint8Array.from(toArray(msg, enc));\n this.h.update(data);\n return this;\n }\n digest() {\n return Array.from(this.h.digest());\n }\n digestHex() {\n return bytesToHex(this.h.digest());\n }\n}\n/**\n * An implementation of SHA1 cryptographic hash function. Extends the BaseHash class.\n * It provides a way to compute a 'digest' for any kind of input data; transforming the data\n * into a unique output of fixed size. The output is deterministic; it will always be\n * the same for the same input.\n *\n * @class SHA1\n * @param None\n *\n * @constructor\n * Use the SHA1 constructor to create an instance of SHA1 hash function.\n *\n * @example\n * const sha1 = new SHA1();\n *\n * @property h - The initial hash constants.\n * @property W - Provides a way to recycle usage of the array memory.\n * @property k - The round constants used for each round of SHA-1.\n */\nexport class SHA1 extends BaseHash {\n h;\n W;\n k;\n constructor() {\n super(512, 160, 80, 64);\n this.k = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n this.W = new Array(80);\n }\n _update(msg, start) {\n const W = this.W;\n // Default start to 0\n if (start === undefined) {\n start = 0;\n }\n let i;\n for (i = 0; i < 16; i++) {\n W[i] = msg[start + i];\n }\n for (; i < W.length; i++) {\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n }\n let a = this.h[0];\n let b = this.h[1];\n let c = this.h[2];\n let d = this.h[3];\n let e = this.h[4];\n for (i = 0; i < W.length; i++) {\n const s = ~~(i / 20);\n const t = SUM32_5(rotl32(a, 5), FT_1(s, b, c, d), e, W[i], this.k[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n }\n _digest() {\n return split32(this.h, 'big');\n }\n _digestHex() {\n return toHex32(this.h, 'big');\n }\n}\n/**\n * An implementation of SHA512 cryptographic hash function. Extends the BaseHash class.\n * It provides a way to compute a 'digest' for any kind of input data; transforming the data\n * into a unique output of fixed size. The output is deterministic; it will always be\n * the same for the same input.\n *\n * @class SHA512\n * @param None\n *\n * @constructor\n * Use the SHA512 constructor to create an instance of SHA512 hash function.\n *\n * @example\n * const sha512 = new SHA512();\n *\n * @property h - The initial hash constants.\n * @property W - Provides a way to recycle usage of the array memory.\n * @property k - The round constants used for each round of SHA-512.\n */\nexport class SHA512 {\n h;\n constructor() {\n this.h = new FastSHA512();\n }\n update(msg, enc) {\n const data = Uint8Array.from(toArray(msg, enc));\n this.h.update(data);\n return this;\n }\n digest() {\n return Array.from(this.h.digest());\n }\n digestHex() {\n return bytesToHex(this.h.digest());\n }\n}\n/**\n * The `SHA256HMAC` class is used to create Hash-based Message Authentication Code (HMAC) using the SHA-256 cryptographic hash function.\n *\n * HMAC is a specific type of MAC involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and the authenticity of a message.\n *\n * This class also uses the SHA-256 cryptographic hash algorithm that produces a 256-bit (32-byte) hash value.\n *\n * @property inner - Represents the inner hash of SHA-256.\n * @property outer - Represents the outer hash of SHA-256.\n * @property blockSize - The block size for the SHA-256 hash function, in bytes. It's set to 64 bytes.\n * @property outSize - The output size of the SHA-256 hash function, in bytes. It's set to 32 bytes.\n */\nexport class SHA256HMAC {\n h;\n blockSize = 64;\n outSize = 32;\n /**\n * The constructor for the `SHA256HMAC` class.\n *\n * It initializes the `SHA256HMAC` object and sets up the inner and outer padded keys.\n * If the key size is larger than the blockSize, it is digested using SHA-256.\n * If the key size is less than the blockSize, it is padded with zeroes.\n *\n * @constructor\n * @param key - The key to use to create the HMAC. Can be a number array or a string in hexadecimal format.\n *\n * @example\n * const myHMAC = new SHA256HMAC('deadbeef');\n */\n constructor(key) {\n const k = key instanceof Uint8Array\n ? key\n : Uint8Array.from(toArray(key, typeof key === 'string' ? 'hex' : undefined));\n this.h = new HMAC(sha256Fast, k);\n }\n /**\n * Updates the `SHA256HMAC` object with part of the message to be hashed.\n *\n * @method update\n * @param msg - Part of the message to hash. Can be a number array or a string.\n * @param enc - If 'hex', then the input is encoded as hexadecimal. If undefined or not 'hex', then no encoding is performed.\n * @returns Returns the instance of `SHA256HMAC` for chaining calls.\n *\n * @example\n * myHMAC.update('deadbeef', 'hex');\n */\n update(msg, enc) {\n const data = msg instanceof Uint8Array ? msg : Uint8Array.from(toArray(msg, enc));\n this.h.update(data);\n return this;\n }\n /**\n * Finalizes the HMAC computation and returns the resultant hash.\n *\n * @method digest\n * @returns Returns the digest of the hashed data. Can be a number array or a string.\n *\n * @example\n * let hashedMessage = myHMAC.digest();\n */\n digest() {\n return Array.from(this.h.digest());\n }\n /**\n * Finalizes the HMAC computation and returns the resultant hash as a hex string.\n *\n * @method digest\n * @returns Returns the digest of the hashed data as a hex string\n *\n * @example\n * let hashedMessage = myHMAC.digestHex();\n */\n digestHex() {\n return bytesToHex(this.h.digest());\n }\n}\nexport class SHA1HMAC {\n inner;\n outer;\n blockSize = 64;\n constructor(key) {\n key = toArray(key, 'hex');\n // Shorten key, if needed\n if (key.length > this.blockSize) {\n key = new SHA1().update(key).digest();\n }\n // Keys shorter than block size are padded with zeros on the right\n let i;\n for (i = key.length; i < this.blockSize; i++) {\n key.push(0);\n }\n for (i = 0; i < key.length; i++) {\n key[i] ^= 0x36;\n }\n this.inner = new SHA1().update(key);\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++) {\n key[i] ^= 0x6a;\n }\n this.outer = new SHA1().update(key);\n }\n update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n }\n digest() {\n this.outer.update(this.inner.digest());\n return this.outer.digest();\n }\n digestHex() {\n this.outer.update(this.inner.digest());\n return this.outer.digestHex();\n }\n}\n/**\n * The `SHA512HMAC` class is used to create Hash-based Message Authentication Code (HMAC) using the SHA-512 cryptographic hash function.\n *\n * HMAC is a specific type of MAC involving a cryptographic hash function and a secret cryptographic key. It may be used to simultaneously verify both the data integrity and the authenticity of a message.\n *\n * This class also uses the SHA-512 cryptographic hash algorithm that produces a 512-bit (64-byte) hash value.\n *\n * @property inner - Represents the inner hash of SHA-512.\n * @property outer - Represents the outer hash of SHA-512.\n * @property blockSize - The block size for the SHA-512 hash function, in bytes. It's set to 128 bytes.\n * @property outSize - The output size of the SHA-512 hash function, in bytes. It's set to 64 bytes.\n */\nexport class SHA512HMAC {\n h;\n blockSize = 128;\n outSize = 32;\n /**\n * The constructor for the `SHA512HMAC` class.\n *\n * It initializes the `SHA512HMAC` object and sets up the inner and outer padded keys.\n * If the key size is larger than the blockSize, it is digested using SHA-512.\n * If the key size is less than the blockSize, it is padded with zeroes.\n *\n * @constructor\n * @param key - The key to use to create the HMAC. Can be a number array or a string in hexadecimal format.\n *\n * @example\n * const myHMAC = new SHA512HMAC('deadbeef');\n */\n constructor(key) {\n const k = key instanceof Uint8Array\n ? key\n : Uint8Array.from(toArray(key, typeof key === 'string' ? 'hex' : undefined));\n this.h = new HMAC(sha512Fast, k);\n }\n /**\n * Updates the `SHA512HMAC` object with part of the message to be hashed.\n *\n * @method update\n * @param msg - Part of the message to hash. Can be a number array or a string.\n * @param enc - If 'hex', then the input is encoded as hexadecimal. If undefined or not 'hex', then no encoding is performed.\n * @returns Returns the instance of `SHA512HMAC` for chaining calls.\n *\n * @example\n * myHMAC.update('deadbeef', 'hex');\n */\n update(msg, enc) {\n const data = msg instanceof Uint8Array ? msg : Uint8Array.from(toArray(msg, enc));\n this.h.update(data);\n return this;\n }\n /**\n * Finalizes the HMAC computation and returns the resultant hash.\n *\n * @method digest\n * @returns Returns the digest of the hashed data as a number array.\n *\n * @example\n * let hashedMessage = myHMAC.digest();\n */\n digest() {\n return Array.from(this.h.digest());\n }\n /**\n * Finalizes the HMAC computation and returns the resultant hash as a hex string.\n *\n * @method digest\n * @returns Returns the digest of the hashed data as a hex string\n *\n * @example\n * let hashedMessage = myHMAC.digestHex();\n */\n digestHex() {\n return bytesToHex(this.h.digest());\n }\n}\n/**\n * Computes RIPEMD160 hash of a given message.\n * @function ripemd160\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed RIPEMD160 hash of the message.\n *\n * @example\n * const digest = ripemd160('Hello, world!');\n */\nexport const ripemd160 = (msg, enc) => {\n return new RIPEMD160().update(msg, enc).digest();\n};\n/**\n * Computes SHA1 hash of a given message.\n * @function sha1\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed SHA1 hash of the message.\n *\n * @example\n * const digest = sha1('Hello, world!');\n */\nexport const sha1 = (msg, enc) => {\n return new SHA1().update(msg, enc).digest();\n};\n/**\n * Computes SHA256 hash of a given message.\n * @function sha256\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed SHA256 hash of the message.\n *\n * @example\n * const digest = sha256('Hello, world!');\n */\nexport const sha256 = (msg, enc) => {\n return new SHA256().update(msg, enc).digest();\n};\n/**\n * Computes SHA512 hash of a given message.\n * @function sha512\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed SHA512 hash of the message.\n *\n * @example\n * const digest = sha512('Hello, world!');\n */\nexport const sha512 = (msg, enc) => {\n return new SHA512().update(msg, enc).digest();\n};\n/**\n * Performs a 'double hash' using SHA256. This means the data is hashed twice\n * with SHA256. First, the SHA256 hash of the message is computed, then the\n * SHA256 hash of the resulting hash is computed.\n * @function hash256\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the double hashed SHA256 output.\n *\n * @example\n * const doubleHash = hash256('Hello, world!');\n */\nexport const hash256 = (msg, enc) => {\n const first = new SHA256().update(msg, enc).digest();\n return new SHA256().update(first).digest();\n};\n/**\n * Computes SHA256 hash of a given message and then computes a RIPEMD160 hash of the result.\n *\n * @function hash160\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the RIPEMD160 hash of the SHA256 hash of the input message.\n *\n * @example\n * const hash = hash160('Hello, world!');\n */\nexport const hash160 = (msg, enc) => {\n const first = new SHA256().update(msg, enc).digest();\n return new RIPEMD160().update(first).digest();\n};\n/**\n * Computes SHA256 HMAC of a given message with a given key.\n * @function sha256hmac\n * @param key - The key used to compute the HMAC\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed HMAC of the message.\n *\n * @example\n * const digest = sha256hmac('deadbeef', 'ffff001d');\n */\nexport const sha256hmac = (key, msg, enc) => {\n return new SHA256HMAC(key).update(msg, enc).digest();\n};\n/**\n * Computes SHA512 HMAC of a given message with a given key.\n * @function sha512hmac\n * @param key - The key used to compute the HMAC\n * @param msg - The message to compute the hash for.\n * @param enc - The encoding of msg if string. Default is 'utf8'.\n *\n * @returns the computed HMAC of the message.\n *\n * @example\n * const digest = sha512hmac('deadbeef', 'ffff001d');\n */\nexport const sha512hmac = (key, msg, enc) => {\n return new SHA512HMAC(key).update(msg, enc).digest();\n};\n// BEGIN fast-pbkdf2 helpers\n// Utils\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nfunction anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new Error(`positive integer expected, got ${n}`);\n }\n}\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length)) {\n const lens = lengths.join(',');\n throw new Error(`Uint8Array expected of length ${lens}, got length=${b.length}`);\n }\n}\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function') {\n throw new Error('Hash should be wrapped by utils.createHasher');\n }\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed === true)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished === true) {\n throw new Error('Hash#digest() has already been called');\n }\n}\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nfunction clean(...arrays) {\n for (let i = 0; i < arrays.length; i++)\n arrays[i].fill(0);\n}\nfunction createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str));\n}\nfunction kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\nclass Hash {\n}\nfunction createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n// u64 helpers\nconst U32_MASK64 = BigInt(2 ** 32 - 1);\nconst _32n = BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n const Ah = new Uint32Array(len);\n const Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n Ah[i] = h;\n Al[i] = l;\n }\n return [Ah, Al];\n}\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// _md helpers\nclass HashMD extends Hash {\n blockLen;\n outputLen;\n padOffset;\n isLE;\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n if (len % 4 !== 0)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen !== 0)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// sha256 fast constants\nconst SHA256_IV = Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\nconst K256 = Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\nconst SHA256_W = new Uint32Array(64);\nclass FastSHA256 extends HashMD {\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA256_W[i] = view.getUint32(offset);\n }\n for (let i = 16; i < 64; i++) {\n const w15 = SHA256_W[i - 15];\n const w2 = SHA256_W[i - 2];\n const s0 = G0_256(w15);\n const s1 = G1_256(w2);\n SHA256_W[i] = sum32(sum32(s0, SHA256_W[i - 7]), sum32(s1, SHA256_W[i - 16]));\n }\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const T1 = SUM32_5(H, S1_256(E), ch32(E, F, G), K256[i], SHA256_W[i]);\n const T2 = sum32(S0_256(A), maj32(A, B, C));\n H = G;\n G = F;\n F = E;\n E = sum32(D, T1);\n D = C;\n C = B;\n B = A;\n A = sum32(T1, T2);\n }\n this.A = sum32(this.A, A);\n this.B = sum32(this.B, B);\n this.C = sum32(this.C, C);\n this.D = sum32(this.D, D);\n this.E = sum32(this.E, E);\n this.F = sum32(this.F, F);\n this.G = sum32(this.G, G);\n this.H = sum32(this.H, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nconst sha256Fast = createHasher(() => new FastSHA256());\n// sha512\nconst SHA512_IV = Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179\n]);\nconst K512 = (() => split([\n '0x428a2f98d728ae22',\n '0x7137449123ef65cd',\n '0xb5c0fbcfec4d3b2f',\n '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538',\n '0x59f111f1b605d019',\n '0x923f82a4af194f9b',\n '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242',\n '0x12835b0145706fbe',\n '0x243185be4ee4b28c',\n '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f',\n '0x80deb1fe3b1696b1',\n '0x9bdc06a725c71235',\n '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2',\n '0xefbe4786384f25e3',\n '0x0fc19dc68b8cd5b5',\n '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275',\n '0x4a7484aa6ea6e483',\n '0x5cb0a9dcbd41fbd4',\n '0x76f988da831153b5',\n '0x983e5152ee66dfab',\n '0xa831c66d2db43210',\n '0xb00327c898fb213f',\n '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2',\n '0xd5a79147930aa725',\n '0x06ca6351e003826f',\n '0x142929670a0e6e70',\n '0x27b70a8546d22ffc',\n '0x2e1b21385c26c926',\n '0x4d2c6dfc5ac42aed',\n '0x53380d139d95b3df',\n '0x650a73548baf63de',\n '0x766a0abb3c77b2a8',\n '0x81c2c92e47edaee6',\n '0x92722c851482353b',\n '0xa2bfe8a14cf10364',\n '0xa81a664bbc423001',\n '0xc24b8b70d0f89791',\n '0xc76c51a30654be30',\n '0xd192e819d6ef5218',\n '0xd69906245565a910',\n '0xf40e35855771202a',\n '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8',\n '0x1e376c085141ab53',\n '0x2748774cdf8eeb99',\n '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63',\n '0x4ed8aa4ae3418acb',\n '0x5b9cca4f7763e373',\n '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc',\n '0x78a5636f43172f60',\n '0x84c87814a1f0ab72',\n '0x8cc702081a6439ec',\n '0x90befffa23631e28',\n '0xa4506cebde82bde9',\n '0xbef9a3f7b2c67915',\n '0xc67178f2e372532b',\n '0xca273eceea26619c',\n '0xd186b8c721c0c207',\n '0xeada7dd6cde0eb1e',\n '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba',\n '0x0a637dc5a2c898a6',\n '0x113f9804bef90dae',\n '0x1b710b35131c471b',\n '0x28db77f523047d84',\n '0x32caab7b40c72493',\n '0x3c9ebe0a15c9bebc',\n '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6',\n '0x597f299cfc657e2a',\n '0x5fcb6fab3ad6faec',\n '0x6c44198c4a475817'\n].map((n) => BigInt(n))))();\nconst SHA512_Kh = (() => K512[0])();\nconst SHA512_Kl = (() => K512[1])();\nconst SHA512_W_H = new Uint32Array(80);\nconst SHA512_W_L = new Uint32Array(80);\nclass FastSHA512 extends HashMD {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n }\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);\n const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);\n const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);\n const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n for (let i = 0; i < 80; i++) {\n const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);\n const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);\n const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const T2l = add3L(sigma0l, MAJl, T1l);\n Ah = add3H(T2l, sigma0h, MAJh, T1h);\n Al = T2l | 0;\n }\n ;\n ({ h: Ah, l: Al } = add(Ah, Al, this.Ah, this.Al));\n ({ h: Bh, l: Bl } = add(Bh, Bl, this.Bh, this.Bl));\n ({ h: Ch, l: Cl } = add(Ch, Cl, this.Ch, this.Cl));\n ({ h: Dh, l: Dl } = add(Dh, Dl, this.Dh, this.Dl));\n ({ h: Eh, l: El } = add(Eh, El, this.Eh, this.El));\n ({ h: Fh, l: Fl } = add(Fh, Fl, this.Fh, this.Fl));\n ({ h: Gh, l: Gl } = add(Gh, Gl, this.Gh, this.Gl));\n ({ h: Hh, l: Hl } = add(Hh, Hl, this.Hh, this.Hl));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nconst sha512Fast = createHasher(() => new FastSHA512());\nclass HMAC extends Hash {\n oHash;\n iHash;\n blockLen;\n outputLen;\n finished = false;\n destroyed = false;\n constructor(hash, _key) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function') {\n throw new Error('Expected instance of class which extends utils.Hash');\n }\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n this.oHash = hash.create();\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash ?? undefined);\n to.iHash = iHash._cloneInto(to.iHash ?? undefined);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nfunction pbkdf2Core(hash, password, salt, opts) {\n ahash(hash);\n const { c, dkLen } = Object.assign({ dkLen: 32 }, opts);\n anumber(c);\n anumber(dkLen);\n if (c < 1)\n throw new Error('iterations (c) should be >= 1');\n const pwd = kdfInputToBytes(password);\n const slt = kdfInputToBytes(salt);\n const DK = new Uint8Array(dkLen);\n const PRF = hmac.create(hash, pwd);\n const PRFSalt = PRF._cloneInto().update(slt);\n let prfW;\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW != null)\n prfW.destroy();\n clean(u);\n return DK;\n}\nconst hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\nfunction pbkdf2Fast(password, salt, iterations, keylen) {\n return pbkdf2Core(sha512Fast, password, salt, { c: iterations, dkLen: keylen });\n}\n// END fast-pbkdf2 helpers\n/**\n * Limited SHA-512-only PBKDF2 function for use in deprecated BIP39 code.\n * @function pbkdf2\n * @param password - The PBKDF2 password\n * @param salt - The PBKDF2 salt\n * @param iterations - The number of of iterations to run\n * @param keylen - The length of the key\n * @param digest - The digest (must be sha512 for this implementation)\n *\n * @returns The computed key\n */\nexport function pbkdf2(password, salt, iterations, keylen, digest = 'sha512') {\n if (digest !== 'sha512') {\n throw new Error('Only sha512 is supported in this PBKDF2 implementation');\n }\n // Attempt to use the native Node.js implementation if available as it is\n // considerably faster than the pure TypeScript fallback below. If the crypto\n // module isn't present (for example in a browser build) we'll silently fall\n // back to the original implementation.\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const nodeCrypto = require('crypto');\n if (typeof nodeCrypto.pbkdf2Sync === 'function') {\n const p = Buffer.from(password);\n const s = Buffer.from(salt);\n return [...nodeCrypto.pbkdf2Sync(p, s, iterations, keylen, digest)];\n }\n }\n catch {\n // ignore\n }\n const p = Uint8Array.from(password);\n const s = Uint8Array.from(salt);\n const out = pbkdf2Fast(p, s, iterations, keylen);\n return Array.from(out);\n}\n/**\n * Unconditionally swaps the byte order of a 32-bit unsigned integer.\n *\n * This function performs a strict 32-bit byte swap regardless of host\n * endianness. It is equivalent to the behavior commonly referred to as\n * `bswap32` in low-level libraries.\n *\n * This function is introduced as part of TOB-20 to provide a clearly-named\n * alternative to `htonl()`, which was previously implemented as an\n * unconditional byte swap and did not match the semantics of the traditional\n * C `htonl()` function.\n *\n * @param w - A 32-bit unsigned integer.\n * @returns The value with its byte order reversed.\n *\n * @example\n * swapBytes32(0x11223344) // → 0x44332211\n */\nexport function swapBytes32(w) {\n const res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\n// Detect the host machine's endianness at runtime.\n//\n// This is used by `realHtonl()` to determine whether the value must be\n// byte-swapped or returned unchanged. JavaScript engines on common platforms\n// are almost always little-endian, but this check is included for correctness.\nconst isLittleEndian = (() => {\n const b = new ArrayBuffer(4);\n const a = new Uint32Array(b);\n const c = new Uint8Array(b);\n a[0] = 0x01020304;\n return c[0] === 0x04;\n})();\n/**\n * Converts a 32-bit unsigned integer from host byte order to network byte order.\n *\n * Unlike the legacy `htonl()` implementation (which always swapped bytes),\n * this function behaves like the traditional C `htonl()`:\n *\n * - On **little-endian** machines → performs a byte swap.\n * - On **big-endian** machines → returns the value unchanged.\n *\n * This function is provided to resolve TOB-20, which identified that the\n * previous `htonl()` implementation had a misleading name and did not match\n * platform-dependent semantics.\n *\n * @param w - A 32-bit unsigned integer.\n * @returns The value converted to network byte order.\n *\n * @example\n * realHtonl(0x11223344) // → 0x44332211 on little-endian systems\n */\nexport function realHtonl(w) {\n return isLittleEndian ? swapBytes32(w) : (w >>> 0);\n}\n//# sourceMappingURL=Hash.js.map","import MerklePath from './MerklePath.js';\nimport BeefTx from './BeefTx.js';\nimport { Reader, Writer, toHex, toArray, verifyNotNull } from '../primitives/utils.js';\nimport { hash256 } from '../primitives/Hash.js';\nconst BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\nexport const BEEF_V1 = 4022206465; // 0100BEEF in LE order\nexport const BEEF_V2 = 4022206466; // 0200BEEF in LE order\nexport const ATOMIC_BEEF = 0x01010101; // 01010101\nexport var TX_DATA_FORMAT;\n(function (TX_DATA_FORMAT) {\n TX_DATA_FORMAT[TX_DATA_FORMAT[\"RAWTX\"] = 0] = \"RAWTX\";\n TX_DATA_FORMAT[TX_DATA_FORMAT[\"RAWTX_AND_BUMP_INDEX\"] = 1] = \"RAWTX_AND_BUMP_INDEX\";\n TX_DATA_FORMAT[TX_DATA_FORMAT[\"TXID_ONLY\"] = 2] = \"TXID_ONLY\";\n})(TX_DATA_FORMAT || (TX_DATA_FORMAT = {}));\n/*\n * BEEF standard: BRC-62: Background Evaluation Extended Format (BEEF) Transactions\n * https://github.com/bsv-blockchain/BRCs/blob/master/transactions/0062.md\n *\n * BUMP standard: BRC-74: BSV Unified Merkle Path (BUMP) Format\n * https://github.com/bsv-blockchain/BRCs/blob/master/transactions/0074.md\n *\n * BRC-95: Atomic BEEF Transactions\n * https://github.com/bsv-blockchain/BRCs/blob/master/transactions/0095.md\n *\n * The Atomic BEEF format is supported by the binary deserialization static method `fromBinary`.\n *\n * BRC-96: BEEF V2, Txid Only Extension\n * https://github.com/bsv-blockchain/BRCs/blob/master/transactions/0096.md\n *\n * A valid serialized BEEF is the cornerstone of Simplified Payment Validation (SPV)\n * where they are exchanged between two non-trusting parties to establish the\n * validity of a newly constructed bitcoin transaction and its inputs from prior\n * transactions.\n *\n * A `Beef` is fundamentally an list of `BUMP`s and a list of transactions.\n *\n * A `BUMP` is a partial merkle tree for a 'mined' bitcoin block.\n * It can therefore be used to prove the validity of transaction data\n * for each transaction txid whose merkle path is included in the tree.\n *\n * To be valid, the list of transactions must be sorted in dependency order:\n * oldest transaction first;\n * and each transaction must either\n * have a merkle path in one of the BUMPs, or\n * have all of its input transactions included in the list of transactions.\n *\n * The `Beef` class supports the construction of valid BEEFs by allowing BUMPs\n * (merkle paths) and transactions to be merged sequentially.\n *\n * The `Beef` class also extends the standard by supporting 'known' transactions.\n * A 'known' transaction is represented solely by its txid.\n * To become valid, all the 'known' transactions in a `Beef` must be replaced by full\n * transactions and merkle paths, if they are mined.\n *\n * The purpose of supporting 'known' transactions is that one or both parties\n * generating and exchanging BEEFs often possess partial knowledge of valid transactions\n * due to their history.\n *\n * A valid `Beef` is only required when sent to a party with no shared history,\n * such as a transaction processor.\n *\n * IMPORTANT NOTE:\n * It is fundamental to the BEEF value proposition that only valid transactions and valid\n * merkle path (BUMP) data be added to it. Merging invalid data breaks the `verify` and `isValid`\n * functions. There is no support for removing invalid data. A `Beef` that becomes invalid\n * must be discarded.\n */\nexport class Beef {\n bumps = [];\n txs = [];\n version = BEEF_V2;\n atomicTxid = undefined;\n txidIndex = undefined;\n rawBytesCache;\n hexCache;\n needsSort = true;\n constructor(version = BEEF_V2) {\n this.version = version;\n }\n invalidateSerializationCaches() {\n this.rawBytesCache = undefined;\n this.hexCache = undefined;\n }\n markMutated(requiresSort = true) {\n this.invalidateSerializationCaches();\n if (requiresSort) {\n this.needsSort = true;\n }\n }\n ensureSerializableState() {\n for (const tx of this.txs) {\n void tx.txid;\n }\n }\n ensureSortedForSerialization() {\n if (this.needsSort) {\n this.sortTxs();\n }\n }\n getSerializedBytes() {\n this.ensureSerializableState();\n if (this.rawBytesCache == null) {\n this.ensureSortedForSerialization();\n const writer = new Writer();\n this.toWriter(writer);\n this.rawBytesCache = writer.toUint8Array();\n }\n return this.rawBytesCache;\n }\n /**\n * @param txid of `beefTx` to find\n * @returns `BeefTx` in `txs` with `txid`.\n */\n findTxid(txid) {\n return this.ensureTxidIndex().get(txid);\n }\n ensureTxidIndex() {\n if (this.txidIndex == null) {\n this.txidIndex = new Map();\n for (const tx of this.txs) {\n this.txidIndex.set(tx.txid, tx);\n }\n }\n return this.txidIndex;\n }\n deleteFromIndex(txid) {\n this.txidIndex?.delete(txid);\n }\n addToIndex(tx) {\n this.txidIndex?.set(tx.txid, tx);\n }\n /**\n * Replaces `BeefTx` for this txid with txidOnly.\n *\n * Replacement is done so that a `clone()` can be\n * updated by this method without affecting the\n * original.\n *\n * @param txid\n * @returns undefined if txid is unknown.\n */\n makeTxidOnly(txid) {\n const i = this.txs.findIndex((tx) => tx.txid === txid);\n if (i === -1)\n return undefined;\n let btx = this.txs[i];\n if (btx.isTxidOnly) {\n return btx;\n }\n this.deleteFromIndex(txid);\n this.txs.splice(i, 1);\n this.markMutated(true);\n btx = this.mergeTxidOnly(txid);\n return btx;\n }\n /**\n * @returns `MerklePath` with level zero hash equal to txid or undefined.\n */\n findBump(txid) {\n return this.bumps.find((b) => b.path[0].some((leaf) => leaf.hash === txid) // ✅ Ensure boolean return with `.some()`\n );\n }\n /**\n * Finds a Transaction in this `Beef`\n * and adds any missing input SourceTransactions from this `Beef`.\n *\n * The result is suitable for signing.\n *\n * @param txid The id of the target transaction.\n * @returns Transaction with all available input `SourceTransaction`s from this Beef.\n */\n findTransactionForSigning(txid) {\n const beefTx = this.findTxid(txid);\n if ((beefTx == null) || (beefTx.tx == null))\n return undefined; // Ensure beefTx.tx exists before using it\n for (const i of beefTx.tx.inputs) {\n if (i.sourceTransaction == null) {\n const itx = this.findTxid(verifyNotNull(i.sourceTXID, 'sourceTXID must be valid'));\n if (itx != null) {\n i.sourceTransaction = itx.tx;\n }\n }\n }\n return beefTx.tx;\n }\n /**\n * Builds the proof tree rooted at a specific `Transaction`.\n *\n * To succeed, the Beef must contain all the required transaction and merkle path data.\n *\n * @param txid The id of the target transaction.\n * @returns Transaction with input `SourceTransaction` and `MerklePath` populated from this Beef.\n */\n findAtomicTransaction(txid) {\n const beefTx = this.findTxid(txid);\n if ((beefTx == null) || (beefTx.tx == null))\n return undefined; // Ensure beefTx.tx exists before using it\n const addInputProof = (beef, tx) => {\n const mp = beef.findBump(tx.id('hex'));\n if (mp != null) {\n tx.merklePath = mp;\n }\n else {\n for (const i of tx.inputs) {\n if (i.sourceTransaction == null) {\n const itx = beef.findTxid(verifyNotNull(i.sourceTXID, 'sourceTXID must be valid'));\n if (itx != null) {\n i.sourceTransaction = itx.tx;\n }\n }\n if (i.sourceTransaction != null) {\n const mp = beef.findBump(i.sourceTransaction.id('hex'));\n if (mp != null) {\n i.sourceTransaction.merklePath = mp;\n }\n else {\n addInputProof(beef, i.sourceTransaction);\n }\n }\n }\n }\n };\n addInputProof(this, beefTx.tx); // Safe because we checked that beefTx.tx exists\n return beefTx.tx;\n }\n /**\n * Merge a MerklePath that is assumed to be fully valid.\n * @param bump\n * @returns index of merged bump\n */\n mergeBump(bump) {\n this.markMutated(false);\n let bumpIndex;\n // If this proof is identical to another one previously added, we use that first. Otherwise, we try to merge it with proofs from the same block.\n for (let i = 0; i < this.bumps.length; i++) {\n const b = this.bumps[i];\n if (b === bump) {\n // Literally the same\n return i;\n }\n if (b.blockHeight === bump.blockHeight) {\n // Probably the same...\n const rootA = b.computeRoot();\n const rootB = bump.computeRoot();\n if (rootA === rootB) {\n // Definitely the same... combine them to save space\n b.combine(bump);\n bumpIndex = i;\n break;\n }\n }\n }\n // if the proof is not yet added, add a new path.\n if (bumpIndex === undefined) {\n bumpIndex = this.bumps.length;\n this.bumps.push(bump);\n }\n // Review if any transactions are proven by this bump\n const b = this.bumps[bumpIndex];\n for (const tx of this.txs) {\n const txid = tx.txid;\n if (tx.bumpIndex == null) { // ✅ Explicitly check for null or undefined\n for (const n of b.path[0]) {\n if (n.hash === txid) {\n tx.bumpIndex = bumpIndex;\n n.txid = true;\n break;\n }\n }\n }\n }\n return bumpIndex;\n }\n /**\n * Merge a serialized transaction.\n *\n * Checks that a transaction with the same txid hasn't already been merged.\n *\n * Replaces existing transaction with same txid.\n *\n * @param rawTx\n * @param bumpIndex Optional. If a number, must be valid index into bumps array.\n * @returns txid of rawTx\n */\n mergeRawTx(rawTx, bumpIndex) {\n this.markMutated(true);\n const newTx = new BeefTx(rawTx, bumpIndex);\n this.removeExistingTxid(newTx.txid);\n this.txs.push(newTx);\n this.addToIndex(newTx);\n this.tryToValidateBumpIndex(newTx);\n return newTx;\n }\n /**\n * Merge a `Transaction` and any referenced `merklePath` and `sourceTransaction`, recursifely.\n *\n * Replaces existing transaction with same txid.\n *\n * Attempts to match an existing bump to the new transaction.\n *\n * @param tx\n * @returns txid of tx\n */\n mergeTransaction(tx) {\n this.markMutated(true);\n const txid = tx.id('hex');\n this.removeExistingTxid(txid);\n let bumpIndex;\n if (tx.merklePath != null) {\n bumpIndex = this.mergeBump(tx.merklePath);\n }\n const newTx = new BeefTx(tx, bumpIndex);\n this.txs.push(newTx);\n this.addToIndex(newTx);\n this.tryToValidateBumpIndex(newTx);\n bumpIndex = newTx.bumpIndex;\n if (bumpIndex === undefined) {\n for (const input of tx.inputs) {\n if (input.sourceTransaction != null) {\n this.mergeTransaction(input.sourceTransaction);\n }\n }\n }\n return newTx;\n }\n /**\n * Removes an existing transaction from the BEEF, given its TXID\n * @param txid TXID of the transaction to remove\n */\n removeExistingTxid(txid) {\n const existingTxIndex = this.txs.findIndex((t) => t.txid === txid);\n if (existingTxIndex >= 0) {\n this.deleteFromIndex(txid);\n this.txs.splice(existingTxIndex, 1);\n this.markMutated(true);\n }\n }\n mergeTxidOnly(txid) {\n let tx = this.findTxid(txid);\n if (tx == null) {\n tx = new BeefTx(txid);\n this.txs.push(tx);\n this.addToIndex(tx);\n this.tryToValidateBumpIndex(tx);\n this.markMutated(true);\n }\n return tx;\n }\n mergeBeefTx(btx) {\n let beefTx = this.findTxid(btx.txid);\n if (btx.isTxidOnly && (beefTx == null)) {\n beefTx = this.mergeTxidOnly(btx.txid);\n }\n else if ((btx._tx != null) && ((beefTx == null) || beefTx.isTxidOnly)) {\n beefTx = this.mergeTransaction(btx._tx);\n }\n else if ((btx._rawTx != null) && ((beefTx == null) || beefTx.isTxidOnly)) {\n beefTx = this.mergeRawTx(btx._rawTx);\n }\n if (beefTx == null) {\n throw new Error(`Failed to merge BeefTx for txid: ${btx.txid}`);\n }\n return beefTx;\n }\n mergeBeef(beef) {\n const b = Array.isArray(beef) ? Beef.fromBinary(beef) : beef;\n for (const bump of b.bumps) {\n this.mergeBump(bump);\n }\n for (const tx of b.txs) {\n this.mergeBeefTx(tx);\n }\n }\n /**\n * Sorts `txs` and checks structural validity of beef.\n *\n * Does NOT verify merkle roots.\n *\n * Validity requirements:\n * 1. No 'known' txids, unless `allowTxidOnly` is true.\n * 2. All transactions have bumps or their inputs chain back to bumps (or are known).\n * 3. Order of transactions satisfies dependencies before dependents.\n * 4. No transactions with duplicate txids.\n *\n * @param allowTxidOnly optional. If true, transaction txid only is assumed valid\n */\n isValid(allowTxidOnly) {\n return this.verifyValid(allowTxidOnly).valid;\n }\n /**\n * Sorts `txs` and confirms validity of transaction data contained in beef\n * by validating structure of this beef and confirming computed merkle roots\n * using `chainTracker`.\n *\n * Validity requirements:\n * 1. No 'known' txids, unless `allowTxidOnly` is true.\n * 2. All transactions have bumps or their inputs chain back to bumps (or are known).\n * 3. Order of transactions satisfies dependencies before dependents.\n * 4. No transactions with duplicate txids.\n *\n * @param chainTracker Used to verify computed merkle path roots for all bump txids.\n * @param allowTxidOnly optional. If true, transaction txid is assumed valid\n */\n async verify(chainTracker, allowTxidOnly) {\n const r = this.verifyValid(allowTxidOnly);\n if (!r.valid)\n return false;\n for (const height of Object.keys(r.roots)) {\n const isValid = await chainTracker.isValidRootForHeight(r.roots[height], Number(height));\n if (!isValid) {\n return false;\n }\n }\n return true;\n }\n /**\n * Sorts `txs` and confirms validity of transaction data contained in beef\n * by validating structure of this beef.\n *\n * Returns block heights and merkle root values to be confirmed by a chaintracker.\n *\n * Validity requirements:\n * 1. No 'known' txids, unless `allowTxidOnly` is true.\n * 2. All transactions have bumps or their inputs chain back to bumps (or are known).\n * 3. Order of transactions satisfies dependencies before dependents.\n * 4. No transactions with duplicate txids.\n *\n * @param allowTxidOnly optional. If true, transaction txid is assumed valid\n * @returns {{valid: boolean, roots: Record<number, string>}}\n * `valid` is true iff this Beef is structuraly valid.\n * `roots` is a record where keys are block heights and values are the corresponding merkle roots to be validated.\n */\n verifyValid(allowTxidOnly) {\n const r = {\n valid: false,\n roots: {}\n };\n const sr = this.sortTxs();\n if (sr.missingInputs.length > 0 ||\n sr.notValid.length > 0 ||\n (sr.txidOnly.length > 0 && allowTxidOnly !== true) ||\n sr.withMissingInputs.length > 0) {\n return r;\n }\n // valid txids: only txids if allowed, bump txids, then txids with input's in txids\n const txids = {};\n for (const tx of this.txs) {\n if (tx.isTxidOnly) {\n if (allowTxidOnly !== true)\n return r; // ✅ Explicit check for `true`\n txids[tx.txid] = true;\n }\n }\n const confirmComputedRoot = (b, txid) => {\n const root = b.computeRoot(txid);\n if (r.roots[b.blockHeight] === undefined || r.roots[b.blockHeight] === '') {\n // accept the root as valid for this block and reuse for subsequent txids\n r.roots[b.blockHeight] = root;\n }\n if (r.roots[b.blockHeight] !== root) {\n return false;\n }\n return true;\n };\n for (const b of this.bumps) {\n for (const n of b.path[0]) {\n if (n.txid === true && typeof n.hash === 'string' && n.hash.length > 0) {\n txids[n.hash] = true;\n // All txid hashes in all bumps must agree on computed merkle path roots\n if (!confirmComputedRoot(b, n.hash)) {\n return r;\n }\n }\n }\n }\n // All txs with a bumpIndex have matching txid leaf at level zero of BUMP.\n for (const t of this.txs) {\n if (t.bumpIndex !== undefined) {\n const leaf = this.bumps[t.bumpIndex].path[0].find(l => l.hash === t.txid);\n if (leaf == null) {\n return r;\n }\n }\n }\n for (const t of this.txs) {\n // all input txids must be included before they are referenced\n for (const i of t.inputTxids) {\n if (!txids[i])\n return r;\n }\n txids[t.txid] = true;\n }\n r.valid = true;\n return r;\n }\n /**\n * Serializes this data to `writer`\n * @param writer\n */\n toWriter(writer) {\n writer.writeUInt32LE(this.version);\n writer.writeVarIntNum(this.bumps.length);\n for (const b of this.bumps) {\n writer.write(b.toBinary());\n }\n writer.writeVarIntNum(this.txs.length);\n for (const tx of this.txs) {\n tx.toWriter(writer, this.version);\n }\n }\n /**\n * Returns a binary array representing the serialized BEEF\n * @returns A binary array representing the BEEF\n */\n toBinary() {\n return Array.from(this.getSerializedBytes());\n }\n toUint8Array() {\n return this.getSerializedBytes();\n }\n /**\n * Serialize this Beef as AtomicBEEF.\n *\n * `txid` must exist\n *\n * after sorting, if txid is not last txid, creates a clone and removes newer txs\n *\n * @param txid\n * @returns serialized contents of this Beef with AtomicBEEF prefix.\n */\n toBinaryAtomic(txid) {\n if (this.needsSort) {\n this.sortTxs();\n }\n const tx = this.findTxid(txid);\n if (tx == null) {\n throw new Error(`${txid} does not exist in this Beef`);\n }\n // If the transaction is not the last one, clone and modify\n const beef = (this.txs[this.txs.length - 1] === tx) ? this : this.clone();\n if (beef !== this) {\n const i = this.txs.findIndex((t) => t.txid === txid);\n beef.txs.splice(i + 1);\n }\n const writer = new Writer();\n writer.writeUInt32LE(ATOMIC_BEEF);\n writer.writeReverse(toArray(txid, 'hex'));\n beef.toWriter(writer);\n return writer.toArray();\n }\n /**\n * Returns a hex string representing the serialized BEEF\n * @returns A hex string representing the BEEF\n */\n toHex() {\n if (this.hexCache != null) {\n return this.hexCache;\n }\n const bytes = this.getSerializedBytes();\n const hex = BufferCtor != null\n ? BufferCtor.from(bytes).toString('hex')\n : toHex(Array.from(bytes));\n this.hexCache = hex;\n return hex;\n }\n static fromReader(br) {\n let version = br.readUInt32LE();\n let atomicTxid;\n if (version === ATOMIC_BEEF) {\n // Skip the txid and re-read the BEEF version\n atomicTxid = toHex(br.readReverse(32));\n version = br.readUInt32LE();\n }\n if (version !== BEEF_V1 && version !== BEEF_V2) {\n throw new Error(`Serialized BEEF must start with ${BEEF_V1} or ${BEEF_V2} but starts with ${version}`);\n }\n const beef = new Beef(version);\n const bumpsLength = br.readVarIntNum();\n for (let i = 0; i < bumpsLength; i++) {\n const bump = MerklePath.fromReader(br, false);\n beef.bumps.push(bump);\n }\n const txsLength = br.readVarIntNum();\n for (let i = 0; i < txsLength; i++) {\n const beefTx = BeefTx.fromReader(br, version);\n beef.txs.push(beefTx);\n }\n beef.atomicTxid = atomicTxid;\n return beef;\n }\n /**\n * Constructs an instance of the Beef class based on the provided binary array\n * @param bin The binary array from which to construct BEEF\n * @returns An instance of the Beef class constructed from the binary data\n */\n static fromBinary(bin) {\n const br = new Reader(bin);\n return Beef.fromReader(br);\n }\n /**\n * Constructs an instance of the Beef class based on the provided string\n * @param s The string value from which to construct BEEF\n * @param enc The encoding of the string value from which BEEF should be constructed\n * @returns An instance of the Beef class constructed from the string\n */\n static fromString(s, enc = 'hex') {\n const bin = toArray(s, enc);\n const br = new Reader(bin);\n return Beef.fromReader(br);\n }\n /**\n * Try to validate newTx.bumpIndex by looking for an existing bump\n * that proves newTx.txid\n *\n * @param newTx A new `BeefTx` that has been added to this.txs\n * @returns true if a bump was found, false otherwise\n */\n tryToValidateBumpIndex(newTx) {\n if (newTx.bumpIndex !== undefined) {\n return true;\n }\n const txid = newTx.txid;\n for (let i = 0; i < this.bumps.length; i++) {\n const j = this.bumps[i].path[0].findIndex((b) => b.hash === txid);\n if (j >= 0) {\n newTx.bumpIndex = i;\n this.bumps[i].path[0][j].txid = true;\n return true;\n }\n }\n return false;\n }\n /**\n * Sort the `txs` by input txid dependency order:\n * - Oldest Tx Anchored by Path or txid only\n * - Newer Txs depending on Older parents\n * - Newest Tx\n *\n * with proof (MerklePath) last, longest chain of dependencies first\n *\n * @returns `{ missingInputs, notValid, valid, withMissingInputs }`\n */\n sortTxs() {\n // Hashtable of valid txids (with proof or all inputs chain to proof)\n const validTxids = {};\n // Hashtable of all transaction txids to transaction\n const txidToTx = {};\n // queue of unsorted transactions ...\n let queue = [];\n // sorted transactions: hasProof to with longest dependency chain\n const result = [];\n const txidOnly = [];\n for (const tx of this.txs) {\n txidToTx[tx.txid] = tx;\n tx.isValid = tx.hasProof;\n if (tx.isValid) {\n validTxids[tx.txid] = true;\n result.push(tx);\n }\n else if (tx.isTxidOnly && tx.inputTxids.length === 0) {\n validTxids[tx.txid] = true;\n txidOnly.push(tx);\n }\n else {\n queue.push(tx);\n }\n }\n // Hashtable of unknown input txids used to fund transactions without their own proof.\n const missingInputs = {};\n // transactions with one or more missing inputs\n const txsMissingInputs = [];\n const possiblyMissingInputs = queue;\n queue = [];\n // all tx are isValid false, hasProof false.\n // if isTxidOnly then has inputTxids\n for (const tx of possiblyMissingInputs) {\n let hasMissingInput = false;\n // For all the unproven transactions,\n // link their inputs that exist in this beef,\n // make a note of missing inputs.\n for (const inputTxid of tx.inputTxids) {\n if (txidToTx[inputTxid] === undefined) { // Explicitly check for undefined\n missingInputs[inputTxid] = true;\n hasMissingInput = true;\n }\n }\n if (hasMissingInput) {\n txsMissingInputs.push(tx);\n }\n else {\n queue.push(tx);\n }\n }\n // As long as we have unsorted transactions...\n while (queue.length > 0) {\n const oldQueue = queue;\n queue = [];\n // all tx are isValid false, hasProof false.\n // if isTxidOnly then has inputTxids\n for (const tx of oldQueue) {\n if (tx.inputTxids.every((txid) => validTxids[txid])) {\n validTxids[tx.txid] = true;\n result.push(tx);\n }\n else {\n queue.push(tx);\n }\n }\n if (oldQueue.length === queue.length) {\n break;\n }\n }\n // transactions that don't have proofs and don't chain to proofs\n const txsNotValid = queue;\n // New order of txs is unsortable (missing inputs or depends on missing inputs), txidOnly, sorted (so newest sorted is last)\n this.txs = txsMissingInputs\n .concat(txsNotValid)\n .concat(txidOnly)\n .concat(result);\n this.needsSort = false;\n this.invalidateSerializationCaches();\n return {\n missingInputs: Object.keys(missingInputs),\n notValid: txsNotValid.map((tx) => tx.txid),\n valid: Object.keys(validTxids),\n withMissingInputs: txsMissingInputs.map((tx) => tx.txid),\n txidOnly: txidOnly.map((tx) => tx.txid)\n };\n }\n /**\n * @returns a shallow copy of this beef\n */\n clone() {\n const c = new Beef();\n c.version = this.version;\n c.bumps = Array.from(this.bumps);\n c.txs = Array.from(this.txs);\n c.txidIndex = undefined;\n c.needsSort = this.needsSort;\n return c;\n }\n /**\n * Ensure that all the txids in `knownTxids` are txidOnly\n * @param knownTxids\n */\n trimKnownTxids(knownTxids) {\n let mutated = false;\n for (let i = 0; i < this.txs.length;) {\n const tx = this.txs[i];\n if (tx.isTxidOnly && knownTxids.includes(tx.txid)) {\n this.deleteFromIndex(tx.txid);\n this.txs.splice(i, 1);\n mutated = true;\n }\n else {\n i++;\n }\n }\n // TODO: bumps could be trimmed to eliminate unreferenced proofs.\n if (mutated) {\n this.markMutated(true);\n }\n }\n /**\n * @returns array of transaction txids that either have a proof or whose inputs chain back to a proven transaction.\n */\n getValidTxids() {\n const r = this.sortTxs();\n return r.valid;\n }\n /**\n * @returns Summary of `Beef` contents as multi-line string.\n */\n toLogString() {\n let log = '';\n log += `BEEF with ${this.bumps.length} BUMPS and ${this.txs.length} Transactions, isValid ${this.isValid().toString()}\\n`;\n let i = -1;\n for (const b of this.bumps) {\n i++;\n log += ` BUMP ${i}\\n block: ${b.blockHeight}\\n txids: [\\n${b.path[0]\n .filter((n) => n.txid === true) // ✅ Explicitly check if txid is `true`\n .map((n) => ` '${n.hash ?? ''}'`)\n .join(',\\n')}\\n ]\\n`;\n }\n i = -1;\n for (const t of this.txs) {\n i++;\n log += ` TX ${i}\\n txid: ${t.txid}\\n`;\n if (t.bumpIndex !== undefined) {\n log += ` bumpIndex: ${t.bumpIndex}\\n`;\n }\n if (t.isTxidOnly) {\n log += ' txidOnly\\n';\n }\n else {\n log += ` rawTx length=${t.rawTx?.length ?? 0}\\n`; // ✅ Fix applied here\n }\n if (t.inputTxids.length > 0) {\n log += ` inputs: [\\n${t.inputTxids\n .map((it) => ` '${it}'`)\n .join(',\\n')}\\n ]\\n`;\n }\n }\n return log;\n }\n /**\n * In some circumstances it may be helpful for the BUMP MerklePaths to include\n * leaves that can be computed from row zero.\n */\n addComputedLeaves() {\n const hash = (m) => toHex(hash256(toArray(m, 'hex').reverse()).reverse());\n for (const bump of this.bumps) { // ✅ Use `this` instead of `beef`\n for (let row = 1; row < bump.path.length; row++) {\n for (const leafL of bump.path[row - 1]) {\n if (typeof leafL.hash === 'string' && (leafL.offset & 1) === 0) {\n const leafR = bump.path[row - 1].find((l) => l.offset === leafL.offset + 1);\n const offsetOnRow = leafL.offset >> 1;\n if (leafR !== undefined &&\n typeof leafR.hash === 'string' &&\n bump.path[row].every((l) => l.offset !== offsetOnRow)) {\n // Computable leaf is missing... add it.\n bump.path[row].push({\n offset: offsetOnRow,\n // String concatenation puts the right leaf on the left of the left leaf hash\n hash: hash(leafR.hash + leafL.hash)\n });\n }\n }\n }\n }\n }\n }\n}\nexport default Beef;\n//# sourceMappingURL=Beef.js.map","/**\n * @enum {number} SecurityLevels\n *\n * Silent = 0 Silently grants the request with no user interation.\n * App = 1 Requires user approval for every application.\n * Counterparty = 2 Requires user approval per counterparty per application.\n */\nexport var SecurityLevels;\n(function (SecurityLevels) {\n SecurityLevels[SecurityLevels[\"Silent\"] = 0] = \"Silent\";\n SecurityLevels[SecurityLevels[\"App\"] = 1] = \"App\";\n SecurityLevels[SecurityLevels[\"Counterparty\"] = 2] = \"Counterparty\";\n})(SecurityLevels || (SecurityLevels = {}));\n//# sourceMappingURL=Wallet.interfaces.js.map","export class WalletError extends Error {\n code;\n isError = true;\n constructor(message, code = 1, stack) {\n super(message);\n this.code = code;\n this.name = this.constructor.name;\n if (stack !== undefined && stack !== null && stack !== '') {\n this.stack = stack;\n }\n else {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n /**\n * Safely serializes a WalletError (including special cases), Error or unknown error to JSON.\n *\n * Safely means avoiding deep, large, circular issues.\n *\n * Example deserialization can be found in HTTPWalletJSON.ts of bsv ts-sdk.\n *\n * @param error\n * @returns stringified JSON representation of the error such that it can be deserialized to a WalletError.\n */\n static unknownToJson(error) {\n let e;\n if (error.isError === true && String(error.name).startsWith('WERR_')) {\n e = {\n name: error.name,\n message: error.message,\n isError: true\n };\n if (e.name === 'WERR_REVIEW_ACTIONS') {\n e.reviewActionResults = error.reviewActionResults;\n e.sendWithResults = error.sendWithResults;\n e.txid = error.txid;\n e.tx = error.tx;\n e.noSendChange = error.noSendChange;\n e.code = 5;\n }\n else if (e.name === 'WERR_INVALID_PARAMETER') {\n e.parameter = error.parameter;\n e.code = 6;\n }\n else if (e.name === 'WERR_INSUFFICIENT_FUNDS') {\n e.totalSatoshisNeeded = error.totalSatoshisNeeded;\n e.moreSatoshisNeeded = error.moreSatoshisNeeded;\n e.code = 7;\n }\n }\n else if (error instanceof Error) {\n e = {\n name: error.constructor.name,\n message: error.message,\n isError: true\n };\n }\n else {\n e = {\n name: 'WERR_UNKNOWN',\n message: String(error),\n isError: true\n };\n }\n const json = JSON.stringify(e);\n return json;\n }\n}\n// NOTE: Enum values must not exceed the UInt8 range (0–255)\nexport var walletErrors;\n(function (walletErrors) {\n walletErrors[walletErrors[\"unknownError\"] = 1] = \"unknownError\";\n walletErrors[walletErrors[\"unsupportedAction\"] = 2] = \"unsupportedAction\";\n walletErrors[walletErrors[\"invalidHmac\"] = 3] = \"invalidHmac\";\n walletErrors[walletErrors[\"invalidSignature\"] = 4] = \"invalidSignature\";\n walletErrors[walletErrors[\"reviewActions\"] = 5] = \"reviewActions\";\n walletErrors[walletErrors[\"invalidParameter\"] = 6] = \"invalidParameter\";\n walletErrors[walletErrors[\"insufficientFunds\"] = 7] = \"insufficientFunds\";\n})(walletErrors || (walletErrors = {}));\nexport default WalletError;\n//# sourceMappingURL=WalletError.js.map","// NOTE: Enum values must not exceed the UInt8 range (0–255)\nvar calls;\n(function (calls) {\n calls[calls[\"createAction\"] = 1] = \"createAction\";\n calls[calls[\"signAction\"] = 2] = \"signAction\";\n calls[calls[\"abortAction\"] = 3] = \"abortAction\";\n calls[calls[\"listActions\"] = 4] = \"listActions\";\n calls[calls[\"internalizeAction\"] = 5] = \"internalizeAction\";\n calls[calls[\"listOutputs\"] = 6] = \"listOutputs\";\n calls[calls[\"relinquishOutput\"] = 7] = \"relinquishOutput\";\n calls[calls[\"getPublicKey\"] = 8] = \"getPublicKey\";\n calls[calls[\"revealCounterpartyKeyLinkage\"] = 9] = \"revealCounterpartyKeyLinkage\";\n calls[calls[\"revealSpecificKeyLinkage\"] = 10] = \"revealSpecificKeyLinkage\";\n calls[calls[\"encrypt\"] = 11] = \"encrypt\";\n calls[calls[\"decrypt\"] = 12] = \"decrypt\";\n calls[calls[\"createHmac\"] = 13] = \"createHmac\";\n calls[calls[\"verifyHmac\"] = 14] = \"verifyHmac\";\n calls[calls[\"createSignature\"] = 15] = \"createSignature\";\n calls[calls[\"verifySignature\"] = 16] = \"verifySignature\";\n calls[calls[\"acquireCertificate\"] = 17] = \"acquireCertificate\";\n calls[calls[\"listCertificates\"] = 18] = \"listCertificates\";\n calls[calls[\"proveCertificate\"] = 19] = \"proveCertificate\";\n calls[calls[\"relinquishCertificate\"] = 20] = \"relinquishCertificate\";\n calls[calls[\"discoverByIdentityKey\"] = 21] = \"discoverByIdentityKey\";\n calls[calls[\"discoverByAttributes\"] = 22] = \"discoverByAttributes\";\n calls[calls[\"isAuthenticated\"] = 23] = \"isAuthenticated\";\n calls[calls[\"waitForAuthentication\"] = 24] = \"waitForAuthentication\";\n calls[calls[\"getHeight\"] = 25] = \"getHeight\";\n calls[calls[\"getHeaderForHeight\"] = 26] = \"getHeaderForHeight\";\n calls[calls[\"getNetwork\"] = 27] = \"getNetwork\";\n calls[calls[\"getVersion\"] = 28] = \"getVersion\";\n})(calls || (calls = {}));\nexport default calls;\n//# sourceMappingURL=WalletWireCalls.js.map","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\nconst CAN_USE_BUFFER = BufferCtor != null && typeof BufferCtor.from === 'function';\nconst HEX_CHAR_TO_VALUE = new Int8Array(256).fill(-1);\nfor (let i = 0; i < 10; i++) {\n HEX_CHAR_TO_VALUE[48 + i] = i; // '0'-'9'\n}\nfor (let i = 0; i < 6; i++) {\n HEX_CHAR_TO_VALUE[65 + i] = 10 + i; // 'A'-'F'\n HEX_CHAR_TO_VALUE[97 + i] = 10 + i; // 'a'-'f'\n}\n/**\n * JavaScript numbers are only precise up to 53 bits. Since Bitcoin relies on\n * 256-bit cryptography, this BigNumber class enables operations on larger\n * numbers.\n *\n * @class BigNumber\n */\nexport default class BigNumber {\n /**\n * @privateinitializer\n */\n static zeros = [\n '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000',\n '000000000', '0000000000', '00000000000', '000000000000', '0000000000000',\n '00000000000000', '000000000000000', '0000000000000000', '00000000000000000',\n '000000000000000000', '0000000000000000000', '00000000000000000000',\n '000000000000000000000', '0000000000000000000000', '00000000000000000000000',\n '000000000000000000000000', '0000000000000000000000000'\n ];\n /**\n * @privateinitializer\n */\n static groupSizes = [\n 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5\n ];\n /**\n * @privateinitializer\n */\n static groupBases = [\n 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343,\n 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000,\n 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n /**\n * The word size of big number chunks.\n *\n * @property wordSize\n *\n * @example\n * console.log(BigNumber.wordSize); // output: 26\n */\n static wordSize = 26;\n static WORD_SIZE_BIGINT = BigInt(BigNumber.wordSize);\n static WORD_MASK = (1n << BigNumber.WORD_SIZE_BIGINT) - 1n;\n static MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);\n static MIN_SAFE_INTEGER_BIGINT = BigInt(Number.MIN_SAFE_INTEGER);\n static MAX_IMULN_ARG = 0x4000000 - 1;\n static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT = (1n << 53n) - 1n;\n _magnitude;\n _sign;\n _nominalWordLength;\n /**\n * Reduction context of the big number.\n *\n * @property red\n */\n red;\n /**\n * Negative flag. Indicates whether the big number is a negative number.\n * - If 0, the number is positive.\n * - If 1, the number is negative.\n *\n * @property negative\n */\n get negative() {\n return this._sign;\n }\n /**\n * Sets the negative flag. Only 0 (positive) or 1 (negative) are allowed.\n */\n set negative(val) {\n this.assert(val === 0 || val === 1, 'Negative property must be 0 or 1');\n const newSign = val === 1 ? 1 : 0;\n if (this._magnitude === 0n) {\n this._sign = 0;\n }\n else {\n this._sign = newSign;\n }\n }\n get _computedWordsArray() {\n if (this._magnitude === 0n)\n return [0];\n const arr = [];\n let temp = this._magnitude;\n while (temp > 0n) {\n arr.push(Number(temp & BigNumber.WORD_MASK));\n temp >>= BigNumber.WORD_SIZE_BIGINT;\n }\n return arr.length > 0 ? arr : [0];\n }\n /**\n * Array of numbers, where each number represents a part of the value of the big number.\n *\n * @property words\n */\n get words() {\n const computed = this._computedWordsArray;\n if (this._nominalWordLength <= computed.length) {\n return computed;\n }\n const paddedWords = new Array(this._nominalWordLength).fill(0);\n for (let i = 0; i < computed.length; i++) {\n paddedWords[i] = computed[i];\n }\n return paddedWords;\n }\n /**\n * Sets the words array representing the value of the big number.\n */\n set words(newWords) {\n const oldSign = this._sign;\n let newMagnitude = 0n;\n const len = newWords.length > 0 ? newWords.length : 1;\n for (let i = len - 1; i >= 0; i--) {\n const wordVal = newWords[i] === undefined ? 0 : newWords[i];\n newMagnitude = (newMagnitude << BigNumber.WORD_SIZE_BIGINT) | BigInt(wordVal & Number(BigNumber.WORD_MASK));\n }\n this._magnitude = newMagnitude;\n this._sign = oldSign;\n this._nominalWordLength = len;\n this.normSign();\n }\n /**\n * Length of the words array.\n *\n * @property length\n */\n get length() {\n return Math.max(1, this._nominalWordLength);\n }\n /**\n * Checks whether a value is an instance of BigNumber. Regular JS numbers fail this check.\n *\n * @method isBN\n * @param num - The value to be checked.\n * @returns - Returns a boolean value determining whether or not the checked num parameter is a BigNumber.\n */\n static isBN(num) {\n if (num instanceof BigNumber)\n return true;\n return (num !== null &&\n typeof num === 'object' &&\n num.constructor?.wordSize === BigNumber.wordSize &&\n Array.isArray(num.words));\n }\n /**\n * Returns the bigger value between two BigNumbers\n *\n * @method max\n * @param left - The first BigNumber to be compared.\n * @param right - The second BigNumber to be compared.\n * @returns - Returns the bigger BigNumber between left and right.\n */\n static max(left, right) { return left.cmp(right) > 0 ? left : right; }\n /**\n * Returns the smaller value between two BigNumbers\n *\n * @method min\n * @param left - The first BigNumber to be compared.\n * @param right - The second BigNumber to be compared.\n * @returns - Returns the smaller value between left and right.\n */\n static min(left, right) { return left.cmp(right) < 0 ? left : right; }\n /**\n * @constructor\n *\n * @param number - The number (various types accepted) to construct a BigNumber from. Default is 0.\n * @param base - The base of number provided. By default is 10.\n * @param endian - The endianness provided. By default is 'big endian'.\n */\n constructor(number = 0, base = 10, endian = 'be') {\n this._magnitude = 0n;\n this._sign = 0;\n this._nominalWordLength = 1;\n this.red = null;\n if (number === undefined)\n number = 0;\n if (number === null) {\n this._initializeState(0n, 0);\n return;\n }\n if (typeof number === 'bigint') {\n this._initializeState(number < 0n ? -number : number, number < 0n ? 1 : 0);\n this.normSign();\n return;\n }\n let effectiveBase = base;\n let effectiveEndian = endian;\n if (base === 'le' || base === 'be') {\n effectiveEndian = base;\n effectiveBase = 10;\n }\n if (typeof number === 'number') {\n this.initNumber(number, effectiveEndian);\n return;\n }\n if (Array.isArray(number)) {\n this.initArray(number, effectiveEndian);\n return;\n }\n if (typeof number === 'string') {\n if (effectiveBase === 'hex')\n effectiveBase = 16;\n this.assert(typeof effectiveBase === 'number' && effectiveBase === (effectiveBase | 0) && effectiveBase >= 2 && effectiveBase <= 36, 'Base must be an integer between 2 and 36');\n const originalNumberStr = number.toString().replace(/\\s+/g, '');\n let start = 0;\n let sign = 0;\n if (originalNumberStr.startsWith('-')) {\n start++;\n sign = 1;\n }\n else if (originalNumberStr.startsWith('+')) {\n start++;\n }\n const numStr = originalNumberStr.substring(start);\n if (numStr.length === 0) {\n this._initializeState(0n, (sign === 1 && originalNumberStr.startsWith('-')) ? 1 : 0);\n this.normSign();\n return;\n }\n if (effectiveBase === 16) {\n let tempMagnitude;\n if (effectiveEndian === 'le') {\n const bytes = [];\n let hexStr = numStr;\n if (hexStr.length % 2 !== 0)\n hexStr = '0' + hexStr;\n for (let i = 0; i < hexStr.length; i += 2) {\n const byteHex = hexStr.substring(i, i + 2);\n const byteVal = parseInt(byteHex, 16);\n if (isNaN(byteVal))\n throw new Error('Invalid character in ' + hexStr);\n bytes.push(byteVal);\n }\n this.initArray(bytes, 'le');\n this._sign = sign;\n this.normSign();\n return;\n }\n else {\n try {\n tempMagnitude = BigInt('0x' + numStr);\n }\n catch (e) {\n throw new Error('Invalid character in ' + numStr);\n }\n }\n this._initializeState(tempMagnitude, sign);\n this.normSign();\n }\n else {\n try {\n this._parseBaseString(numStr, effectiveBase);\n this._sign = sign;\n this.normSign();\n if (effectiveEndian === 'le') {\n const currentSign = this._sign;\n this.initArray(this.toArray('be'), 'le');\n this._sign = currentSign;\n this.normSign();\n }\n }\n catch (err) {\n const error = err;\n if (error.message.includes('Invalid character in string') ||\n error.message.includes('Invalid digit for base') ||\n error.message.startsWith('Invalid character:')) {\n throw new Error('Invalid character');\n }\n throw error;\n }\n }\n }\n else if (number !== 0) {\n this.assert(false, 'Unsupported input type for BigNumber constructor');\n }\n else {\n this._initializeState(0n, 0);\n }\n }\n _bigIntToStringInBase(num, base) {\n if (num === 0n)\n return '0';\n if (base < 2 || base > 36)\n throw new Error('Base must be between 2 and 36');\n const digits = '0123456789abcdefghijklmnopqrstuvwxyz';\n let result = '';\n let currentNum = num > 0n ? num : -num;\n const bigBase = BigInt(base);\n while (currentNum > 0n) {\n result = digits[Number(currentNum % bigBase)] + result;\n currentNum /= bigBase;\n }\n return result;\n }\n _parseBaseString(numberStr, base) {\n if (numberStr.length === 0) {\n this._magnitude = 0n;\n this._finishInitialization();\n return;\n }\n this._magnitude = 0n;\n const bigBase = BigInt(base);\n let groupSize = BigNumber.groupSizes[base];\n let groupBaseBigInt = BigInt(BigNumber.groupBases[base]);\n if (groupSize === 0 || groupBaseBigInt === 0n) {\n groupSize = Math.floor(Math.log(0x3ffffff) / Math.log(base));\n if (groupSize === 0)\n groupSize = 1;\n groupBaseBigInt = bigBase ** BigInt(groupSize);\n }\n let currentPos = 0;\n const totalLen = numberStr.length;\n let firstChunkLen = totalLen % groupSize;\n if (firstChunkLen === 0 && totalLen > 0)\n firstChunkLen = groupSize;\n if (firstChunkLen > 0) {\n const chunkStr = numberStr.substring(currentPos, currentPos + firstChunkLen);\n this._magnitude = BigInt(this._parseBaseWord(chunkStr, base));\n currentPos += firstChunkLen;\n }\n while (currentPos < totalLen) {\n const chunkStr = numberStr.substring(currentPos, currentPos + groupSize);\n const wordVal = BigInt(this._parseBaseWord(chunkStr, base));\n this._magnitude = this._magnitude * groupBaseBigInt + wordVal;\n currentPos += groupSize;\n }\n this._finishInitialization();\n }\n _parseBaseWord(str, base) {\n let r = 0;\n for (let i = 0; i < str.length; i++) {\n const charCode = str.charCodeAt(i);\n let digitVal;\n if (charCode >= 48 && charCode <= 57)\n digitVal = charCode - 48;\n else if (charCode >= 65 && charCode <= 90)\n digitVal = charCode - 65 + 10;\n else if (charCode >= 97 && charCode <= 122)\n digitVal = charCode - 97 + 10;\n else\n throw new Error('Invalid character: ' + str[i]);\n if (digitVal >= base)\n throw new Error('Invalid character');\n r = r * base + digitVal;\n }\n return r;\n }\n _initializeState(magnitude, sign) {\n this._magnitude = magnitude;\n this._sign = (magnitude === 0n) ? 0 : sign;\n this._finishInitialization();\n }\n _finishInitialization() {\n if (this._magnitude === 0n) {\n this._nominalWordLength = 1;\n this._sign = 0;\n }\n else {\n const bitLen = this._magnitude.toString(2).length;\n this._nominalWordLength = Math.max(1, Math.ceil(bitLen / BigNumber.wordSize));\n }\n }\n assert(val, msg = 'Assertion failed') { if (!val)\n throw new Error(msg); }\n initNumber(number, endian = 'be') {\n this.assert(BigInt(Math.abs(number)) <= BigNumber.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT, 'The number is larger than 2 ^ 53 (unsafe)');\n this.assert(number % 1 === 0, 'Number must be an integer for BigNumber conversion');\n this._initializeState(BigInt(Math.abs(number)), number < 0 ? 1 : 0);\n if (endian === 'le') {\n const currentSign = this._sign;\n const beBytes = this.toArray('be');\n this.initArray(beBytes, 'le');\n this._sign = currentSign;\n this.normSign();\n }\n return this;\n }\n initArray(bytes, endian) {\n if (bytes.length === 0) {\n this._initializeState(0n, 0);\n return this;\n }\n let magnitude = 0n;\n if (endian === 'be') {\n for (let i = 0; i < bytes.length; i++)\n magnitude = (magnitude << 8n) | BigInt(bytes[i] & 0xff);\n }\n else {\n for (let i = bytes.length - 1; i >= 0; i--)\n magnitude = (magnitude << 8n) | BigInt(bytes[i] & 0xff);\n }\n this._initializeState(magnitude, 0);\n return this;\n }\n copy(dest) { dest._magnitude = this._magnitude; dest._sign = this._sign; dest._nominalWordLength = this._nominalWordLength; dest.red = this.red; }\n static move(dest, src) { dest._magnitude = src._magnitude; dest._sign = src._sign; dest._nominalWordLength = src._nominalWordLength; dest.red = src.red; }\n clone() { const r = new BigNumber(0n); this.copy(r); return r; }\n expand(size) {\n this.assert(size >= 0, 'Expand size must be non-negative');\n this._nominalWordLength = Math.max(this._nominalWordLength, size, 1);\n return this;\n }\n strip() { this._finishInitialization(); return this.normSign(); }\n normSign() { if (this._magnitude === 0n)\n this._sign = 0; return this; }\n inspect() { return (this.red !== null ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>'; }\n _getMinimalHex() {\n if (this._magnitude === 0n)\n return '0';\n return this._magnitude.toString(16);\n }\n /**\n * Converts the BigNumber instance to a string representation.\n *\n * @method toString\n * @param base - The base for representing number. Default is 10. Other accepted values are 16 and 'hex'.\n * @param padding - Represents the minimum number of digits to represent the BigNumber as a string. Default is 1.\n * @returns The string representation of the BigNumber instance\n */\n toString(base = 10, padding = 1) {\n if (base === 16 || base === 'hex') {\n // For toString('hex', N), N is the 'multiple-of-N characters' rule from bn.js tests\n // For toString(16, P) where P=1 (default) or P=0, it means minimal hex.\n let hexStr = this._getMinimalHex(); // e.g., \"f\", \"123\", \"0\"\n if (padding > 1) { // N-multiple rule for characters\n // Ensure hexStr is even length if not \"0\" to represent full bytes before applying multiple rule\n if (hexStr !== '0' && hexStr.length % 2 !== 0) {\n hexStr = '0' + hexStr;\n }\n while (hexStr.length % padding !== 0) {\n hexStr = '0' + hexStr;\n }\n }\n // If padding is 0 or 1, hexStr (minimal) is used as is.\n // \"0\" is always \"0\" unless toHex(\"\") specific case.\n // Single digit hex like \"f\" is not \"0f\" by default from toString(16).\n return (this.isNeg() ? '-' : '') + hexStr;\n }\n if (typeof base !== 'number' || base < 2 || base > 36 || base % 1 !== 0)\n throw new Error('Base should be an integer between 2 and 36');\n return this.toBaseString(base, padding);\n }\n toBaseString(base, padding) {\n if (this._magnitude === 0n) {\n let out = '0';\n if (padding > 1) {\n while (out.length < padding)\n out = '0' + out;\n }\n return out;\n }\n let groupSize = BigNumber.groupSizes[base];\n let groupBaseBigInt = BigInt(BigNumber.groupBases[base]);\n if (groupSize === 0 || groupBaseBigInt === 0n) {\n groupSize = Math.floor(Math.log(Number.MAX_SAFE_INTEGER) / Math.log(base));\n if (groupSize === 0)\n groupSize = 1;\n groupBaseBigInt = BigInt(base) ** BigInt(groupSize);\n }\n let out = '';\n let tempMag = this._magnitude;\n while (tempMag > 0n) {\n const remainder = tempMag % groupBaseBigInt;\n tempMag /= groupBaseBigInt;\n const chunkStr = this._bigIntToStringInBase(remainder, base);\n if (tempMag > 0n) {\n const zerosToPrepend = groupSize - chunkStr.length;\n if (zerosToPrepend > 0 && zerosToPrepend < BigNumber.zeros.length) {\n out = BigNumber.zeros[zerosToPrepend] + chunkStr + out;\n }\n else if (zerosToPrepend > 0) {\n out = '0'.repeat(zerosToPrepend) + chunkStr + out;\n }\n else {\n out = chunkStr + out;\n }\n }\n else {\n out = chunkStr + out;\n }\n }\n if (padding > 0) {\n while (out.length < padding)\n out = '0' + out;\n }\n return (this._sign === 1 ? '-' : '') + out;\n }\n /**\n * Converts the BigNumber instance to a JavaScript number.\n * Please note that JavaScript numbers are only precise up to 53 bits.\n *\n * @method toNumber\n * @throws If the BigNumber instance cannot be safely stored in a JavaScript number\n * @returns The JavaScript number representation of the BigNumber instance.\n */\n toNumber() {\n const val = this._getSignedValue();\n if (val > BigNumber.MAX_SAFE_INTEGER_BIGINT || val < BigNumber.MIN_SAFE_INTEGER_BIGINT)\n throw new Error('Number can only safely store up to 53 bits');\n return Number(val);\n }\n /**\n * Returns the signed BigInt representation of this BigNumber without any safety checks.\n *\n * @method toBigInt\n * @returns bigint value for this BigNumber.\n */\n toBigInt() {\n return this._getSignedValue();\n }\n /**\n * Converts the BigNumber instance to a JSON-formatted string.\n *\n * @method toJSON\n * @returns The JSON string representation of the BigNumber instance.\n */\n toJSON() {\n const hex = this._getMinimalHex();\n return (this.isNeg() ? '-' : '') + hex;\n }\n toArrayLikeGeneric(res, isLE) {\n let tempMag = this._magnitude;\n let position = isLE ? 0 : res.length - 1;\n const increment = isLE ? 1 : -1;\n for (let k = 0; k < res.length; ++k) {\n if (tempMag === 0n && position >= 0 && position < res.length) {\n res[position] = 0;\n }\n else if (position >= 0 && position < res.length) {\n res[position] = Number(tempMag & 0xffn);\n }\n else {\n break;\n }\n tempMag >>= 8n;\n position += increment;\n }\n }\n /**\n * Converts the BigNumber instance to an array of bytes.\n *\n * @method toArray\n * @param endian - Endianness of the output array, defaults to 'be'.\n * @param length - Optional length of the output array.\n * @returns Array of bytes representing the BigNumber.\n */\n toArray(endian = 'be', length) {\n this.strip();\n const actualByteLength = this.byteLength();\n const reqLength = length ?? Math.max(1, actualByteLength);\n this.assert(actualByteLength <= reqLength, 'byte array longer than desired length');\n this.assert(reqLength > 0, 'Requested array length <= 0');\n const res = new Array(reqLength).fill(0);\n if (this._magnitude === 0n && reqLength > 0)\n return res;\n if (this._magnitude === 0n && reqLength === 0)\n return [];\n this.toArrayLikeGeneric(res, endian === 'le');\n return res;\n }\n /**\n * Calculates the number of bits required to represent the BigNumber.\n *\n * @method bitLength\n * @returns The bit length of the BigNumber.\n */\n bitLength() { if (this._magnitude === 0n)\n return 0; return this._magnitude.toString(2).length; }\n /**\n * Converts a BigNumber to an array of bits.\n *\n * @method toBitArray\n * @param num - The BigNumber to convert.\n * @returns An array of bits.\n */\n static toBitArray(num) {\n const len = num.bitLength();\n if (len === 0)\n return [];\n const w = new Array(len);\n const mag = num._magnitude;\n for (let bit = 0; bit < len; bit++) {\n w[bit] = ((mag >> BigInt(bit)) & 1n) !== 0n ? 1 : 0;\n }\n return w;\n }\n /**\n * Instance version of {@link toBitArray}.\n */\n toBitArray() { return BigNumber.toBitArray(this); }\n /**\n * Returns the number of trailing zero bits in the big number.\n *\n * @method zeroBits\n * @returns Returns the number of trailing zero bits\n * in the binary representation of the big number.\n *\n * @example\n * const bn = new BigNumber('8'); // binary: 1000\n * const zeroBits = bn.zeroBits(); // 3\n */\n zeroBits() {\n if (this._magnitude === 0n)\n return 0;\n let c = 0;\n let t = this._magnitude;\n while ((t & 1n) === 0n && t !== 0n) {\n c++;\n t >>= 1n;\n }\n return c;\n }\n /**\n * Calculates the number of bytes required to represent the BigNumber.\n *\n * @method byteLength\n * @returns The byte length of the BigNumber.\n */\n byteLength() { if (this._magnitude === 0n)\n return 0; return Math.ceil(this.bitLength() / 8); }\n _getSignedValue() { return this._sign === 1 ? -this._magnitude : this._magnitude; }\n _setValueFromSigned(sVal) {\n if (sVal < 0n) {\n this._magnitude = -sVal;\n this._sign = 1;\n }\n else {\n this._magnitude = sVal;\n this._sign = 0;\n }\n this._finishInitialization();\n this.normSign();\n }\n toTwos(width) {\n this.assert(width >= 0);\n const Bw = BigInt(width);\n let v = this._getSignedValue();\n if (this._sign === 1 && this._magnitude !== 0n)\n v = (1n << Bw) + v;\n const m = (1n << Bw) - 1n;\n v &= m;\n const r = new BigNumber(0n);\n r._initializeState(v, 0);\n return r;\n }\n fromTwos(width) {\n this.assert(width >= 0);\n const Bw = BigInt(width);\n const m = this._magnitude;\n if (width > 0 && ((m >> (Bw - 1n)) & 1n) !== 0n && this._sign === 0) {\n const sVal = m - (1n << Bw);\n const r = new BigNumber(0n);\n r._setValueFromSigned(sVal);\n return r;\n }\n return this.clone();\n }\n isNeg() { return this._sign === 1 && this._magnitude !== 0n; }\n neg() { return this.clone().ineg(); }\n ineg() { if (this._magnitude !== 0n)\n this._sign = this._sign === 1 ? 0 : 1; return this; }\n _iuop(num, op) {\n const newMag = op(this._magnitude, num._magnitude);\n const isXor = op === ((a, b) => a ^ b);\n let targetNominalLength = this._nominalWordLength;\n if (isXor)\n targetNominalLength = Math.max(this.length, num.length);\n this._magnitude = newMag;\n this._finishInitialization();\n if (isXor)\n this._nominalWordLength = Math.max(this._nominalWordLength, targetNominalLength);\n return this.strip();\n }\n iuor(num) { return this._iuop(num, (a, b) => a | b); }\n iuand(num) { return this._iuop(num, (a, b) => a & b); }\n iuxor(num) { return this._iuop(num, (a, b) => a ^ b); }\n _iop(num, op) { this.assert(this._sign === 0 && num._sign === 0); return this._iuop(num, op); }\n ior(num) { return this._iop(num, (a, b) => a | b); }\n iand(num) { return this._iop(num, (a, b) => a & b); }\n ixor(num) { return this._iop(num, (a, b) => a ^ b); }\n _uop_new(num, opName) { if (this.length >= num.length)\n return this.clone()[opName](num); return num.clone()[opName](this); }\n or(num) { this.assert(this._sign === 0 && num._sign === 0); return this._uop_new(num, 'iuor'); }\n uor(num) { return this._uop_new(num, 'iuor'); }\n and(num) { this.assert(this._sign === 0 && num._sign === 0); return this._uop_new(num, 'iuand'); }\n uand(num) { return this._uop_new(num, 'iuand'); }\n xor(num) { this.assert(this._sign === 0 && num._sign === 0); return this._uop_new(num, 'iuxor'); }\n uxor(num) { return this._uop_new(num, 'iuxor'); }\n inotn(width) {\n this.assert(typeof width === 'number' && width >= 0);\n const Bw = BigInt(width);\n const m = (1n << Bw) - 1n;\n this._magnitude = (~this._magnitude) & m;\n const wfw = width === 0 ? 1 : Math.ceil(width / BigNumber.wordSize);\n this._nominalWordLength = Math.max(1, wfw);\n this.strip();\n this._nominalWordLength = Math.max(this._nominalWordLength, Math.max(1, wfw));\n return this;\n }\n notn(width) { return this.clone().inotn(width); }\n setn(bit, val) { this.assert(typeof bit === 'number' && bit >= 0); const Bb = BigInt(bit); if (val === 1 || val === true)\n this._magnitude |= (1n << Bb);\n else\n this._magnitude &= ~(1n << Bb); const wnb = Math.floor(bit / BigNumber.wordSize) + 1; this._nominalWordLength = Math.max(this._nominalWordLength, wnb); this._finishInitialization(); return this.strip(); }\n iadd(num) { this._setValueFromSigned(this._getSignedValue() + num._getSignedValue()); return this; }\n add(num) { const r = new BigNumber(0n); r._setValueFromSigned(this._getSignedValue() + num._getSignedValue()); return r; }\n isub(num) { this._setValueFromSigned(this._getSignedValue() - num._getSignedValue()); return this; }\n sub(num) { const r = new BigNumber(0n); r._setValueFromSigned(this._getSignedValue() - num._getSignedValue()); return r; }\n mul(num) {\n const r = new BigNumber(0n);\n r._magnitude = this._magnitude * num._magnitude;\n r._sign = r._magnitude === 0n ? 0 : (this._sign ^ num._sign);\n r._nominalWordLength = this.length + num.length;\n r.red = null;\n return r.normSign();\n }\n imul(num) {\n this._magnitude *= num._magnitude;\n this._sign = this._magnitude === 0n ? 0 : (this._sign ^ num._sign);\n this._nominalWordLength = this.length + num.length;\n this.red = null;\n return this.normSign();\n }\n imuln(num) { this.assert(typeof num === 'number', 'Assertion failed'); this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, 'Assertion failed'); this._setValueFromSigned(this._getSignedValue() * BigInt(num)); return this; }\n muln(num) { return this.clone().imuln(num); }\n sqr() {\n const r = new BigNumber(0n);\n r._magnitude = this._magnitude * this._magnitude;\n r._sign = 0;\n r._nominalWordLength = this.length * 2;\n r.red = null;\n return r;\n }\n isqr() {\n this._magnitude *= this._magnitude;\n this._sign = 0;\n this._nominalWordLength = this.length * 2;\n this.red = null;\n return this;\n }\n pow(num) {\n this.assert(num._sign === 0, 'Exponent for pow must be non-negative');\n if (num.isZero())\n return new BigNumber(1n);\n const res = new BigNumber(1n);\n const currentBase = this.clone();\n const exp = num.clone();\n const baseIsNegative = currentBase.isNeg();\n const expIsOdd = exp.isOdd();\n if (baseIsNegative)\n currentBase.ineg();\n while (!exp.isZero()) {\n if (exp.isOdd()) {\n res.imul(currentBase);\n }\n currentBase.isqr();\n exp.iushrn(1);\n }\n if (baseIsNegative && expIsOdd) {\n res.ineg();\n }\n return res;\n }\n static normalizeNonNegativeBigInt(value, label) {\n if (typeof value === 'number') {\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0)\n throw new Error(`${label} must be a non-negative integer`);\n return BigInt(value);\n }\n if (value < 0n)\n throw new Error(`${label} must be a non-negative integer`);\n return value;\n }\n iushln(bits) {\n const normalizedBits = BigNumber.normalizeNonNegativeBigInt(bits, 'Shift bits');\n if (normalizedBits === 0n)\n return this;\n this._magnitude <<= normalizedBits;\n this._finishInitialization();\n return this.strip();\n }\n ishln(bits) {\n this.assert(this._sign === 0, 'ishln requires positive number');\n return this.iushln(bits);\n }\n iushrn(bits, hint, extended) {\n const normalizedBits = BigNumber.normalizeNonNegativeBigInt(bits, 'Shift bits');\n if (normalizedBits === 0n) {\n if (extended != null)\n extended._initializeState(0n, 0);\n return this;\n }\n if (extended != null) {\n const m = (1n << normalizedBits) - 1n;\n const sOut = this._magnitude & m;\n extended._initializeState(sOut, 0);\n }\n this._magnitude >>= normalizedBits;\n this._finishInitialization();\n return this.strip();\n }\n ishrn(bits, hint, extended) {\n this.assert(this._sign === 0, 'ishrn requires positive number');\n return this.iushrn(bits, hint, extended);\n }\n shln(bits) { return this.clone().ishln(bits); }\n ushln(bits) { return this.clone().iushln(bits); }\n shrn(bits) { return this.clone().ishrn(bits); }\n ushrn(bits) { return this.clone().iushrn(bits); }\n testn(bit) {\n this.assert(typeof bit === 'number' && bit >= 0);\n return ((this._magnitude >> BigInt(bit)) & 1n) !== 0n;\n }\n imaskn(bits) {\n this.assert(typeof bits === 'number' && bits >= 0);\n this.assert(this._sign === 0, 'imaskn works only with positive numbers');\n const Bb = BigInt(bits);\n const m = Bb === 0n ? 0n : (1n << Bb) - 1n;\n this._magnitude &= m;\n const wfm = bits === 0 ? 1 : Math.max(1, Math.ceil(bits / BigNumber.wordSize));\n this._nominalWordLength = wfm;\n this._finishInitialization();\n this._nominalWordLength = Math.max(this._nominalWordLength, wfm);\n return this.strip();\n }\n maskn(bits) { return this.clone().imaskn(bits); }\n iaddn(num) { this.assert(typeof num === 'number'); this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, 'num is too large'); this._setValueFromSigned(this._getSignedValue() + BigInt(num)); return this; }\n _iaddn(num) { return this.iaddn(num); }\n isubn(num) { this.assert(typeof num === 'number'); this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, 'Assertion failed'); this._setValueFromSigned(this._getSignedValue() - BigInt(num)); return this; }\n addn(num) { return this.clone().iaddn(num); }\n subn(num) { return this.clone().isubn(num); }\n iabs() { this._sign = 0; return this; }\n abs() { return this.clone().iabs(); }\n divmod(num, mode, positive) {\n this.assert(!num.isZero(), 'Division by zero');\n if (this.isZero()) {\n const z = new BigNumber(0n);\n return { div: mode !== 'mod' ? z : null, mod: mode !== 'div' ? z : null };\n }\n const tV = this._getSignedValue();\n const nV = num._getSignedValue();\n let dV = null;\n let mV = null;\n if (mode !== 'mod')\n dV = tV / nV;\n if (mode !== 'div') {\n mV = tV % nV;\n if (positive === true && mV < 0n)\n mV += nV < 0n ? -nV : nV;\n }\n const rd = dV !== null ? new BigNumber(0n) : null;\n if (rd !== null && dV !== null)\n rd._setValueFromSigned(dV);\n const rm = mV !== null ? new BigNumber(0n) : null;\n if (rm !== null && mV !== null)\n rm._setValueFromSigned(mV);\n return { div: rd, mod: rm };\n }\n div(num) {\n return this.divmod(num, 'div', false).div;\n }\n mod(num) {\n return this.divmod(num, 'mod', false).mod;\n }\n umod(num) {\n return this.divmod(num, 'mod', true).mod;\n }\n divRound(num) {\n this.assert(!num.isZero());\n const tV = this._getSignedValue();\n const nV = num._getSignedValue();\n let d = tV / nV;\n const m = tV % nV;\n if (m === 0n) {\n const r = new BigNumber(0n);\n r._setValueFromSigned(d);\n return r;\n }\n const absM = m < 0n ? -m : m;\n const absNV = nV < 0n ? -nV : nV;\n if (absM * 2n >= absNV) {\n if ((tV > 0n && nV > 0n) || (tV < 0n && nV < 0n)) {\n d += 1n;\n }\n else {\n d -= 1n;\n }\n }\n const r = new BigNumber(0n);\n r._setValueFromSigned(d);\n return r;\n }\n modrn(numArg) {\n this.assert(numArg !== 0, 'Division by zero in modrn');\n const absDivisor = BigInt(Math.abs(numArg));\n if (absDivisor === 0n)\n throw new Error('Division by zero in modrn');\n const remainderMag = this._magnitude % absDivisor;\n return numArg < 0 ? Number(-remainderMag) : Number(remainderMag);\n }\n idivn(num) {\n this.assert(num !== 0);\n this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, 'num is too large');\n this._setValueFromSigned(this._getSignedValue() / BigInt(num));\n return this;\n }\n divn(num) { return this.clone().idivn(num); }\n egcd(p) {\n this.assert(p._sign === 0, 'p must not be negative');\n this.assert(!p.isZero(), 'p must not be zero');\n let uV = this._getSignedValue();\n let vV = p._magnitude;\n let a = 1n;\n let pa = 0n;\n let b = 0n;\n let pb = 1n;\n while (vV !== 0n) {\n const q = uV / vV;\n let t = vV;\n vV = uV % vV;\n uV = t;\n t = pa;\n pa = a - q * pa;\n a = t;\n t = pb;\n pb = b - q * pb;\n b = t;\n }\n const ra = new BigNumber(0n);\n ra._setValueFromSigned(a);\n const rb = new BigNumber(0n);\n rb._setValueFromSigned(b);\n const rg = new BigNumber(0n);\n rg._initializeState(uV < 0n ? -uV : uV, 0);\n return { a: ra, b: rb, gcd: rg };\n }\n gcd(num) {\n let u = this._magnitude;\n let v = num._magnitude;\n if (u === 0n) {\n const r = new BigNumber(0n);\n r._setValueFromSigned(v);\n return r.iabs();\n }\n if (v === 0n) {\n const r = new BigNumber(0n);\n r._setValueFromSigned(u);\n return r.iabs();\n }\n while (v !== 0n) {\n const t = u % v;\n u = v;\n v = t;\n }\n const res = new BigNumber(0n);\n res._initializeState(u, 0);\n return res;\n }\n invm(num) {\n this.assert(!num.isZero() && num._sign === 0, 'Modulus for invm must be positive and non-zero');\n const eg = this.egcd(num);\n if (!eg.gcd.eqn(1)) {\n throw new Error('Inverse does not exist (numbers are not coprime).');\n }\n return eg.a.umod(num);\n }\n isEven() { return this._magnitude % 2n === 0n; }\n isOdd() { return this._magnitude % 2n === 1n; }\n andln(num) { this.assert(num >= 0); return Number(this._magnitude & BigInt(num)); }\n bincn(bit) { this.assert(typeof bit === 'number' && bit >= 0); const BVal = 1n << BigInt(bit); this._setValueFromSigned(this._getSignedValue() + BVal); return this; }\n isZero() { return this._magnitude === 0n; }\n cmpn(num) { this.assert(Math.abs(num) <= BigNumber.MAX_IMULN_ARG, 'Number is too big'); const tV = this._getSignedValue(); const nV = BigInt(num); if (tV < nV)\n return -1; if (tV > nV)\n return 1; return 0; }\n cmp(num) { const tV = this._getSignedValue(); const nV = num._getSignedValue(); if (tV < nV)\n return -1; if (tV > nV)\n return 1; return 0; }\n ucmp(num) { if (this._magnitude < num._magnitude)\n return -1; if (this._magnitude > num._magnitude)\n return 1; return 0; }\n gtn(num) { return this.cmpn(num) === 1; }\n gt(num) { return this.cmp(num) === 1; }\n gten(num) { return this.cmpn(num) >= 0; }\n gte(num) { return this.cmp(num) >= 0; }\n ltn(num) { return this.cmpn(num) === -1; }\n lt(num) { return this.cmp(num) === -1; }\n lten(num) { return this.cmpn(num) <= 0; }\n lte(num) { return this.cmp(num) <= 0; }\n eqn(num) { return this.cmpn(num) === 0; }\n eq(num) { return this.cmp(num) === 0; }\n toRed(ctx) { this.assert(this.red == null, 'Already a number in reduction context'); this.assert(this._sign === 0, 'toRed works only with positives'); return ctx.convertTo(this).forceRed(ctx); }\n fromRed() { this.assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }\n forceRed(ctx) { this.red = ctx; return this; }\n redAdd(num) { this.assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }\n redIAdd(num) { this.assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }\n redSub(num) { this.assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }\n redISub(num) { this.assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }\n redShl(num) { this.assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }\n redMul(num) { this.assert(this.red, 'redMul works only with red numbers'); this.red.verify2(this, num); return this.red.mul(this, num); }\n redIMul(num) { this.assert(this.red, 'redIMul works only with red numbers'); this.red.verify2(this, num); return this.red.imul(this, num); }\n redSqr() { this.assert(this.red, 'redSqr works only with red numbers'); this.red.verify1(this); return this.red.sqr(this); }\n redISqr() { this.assert(this.red, 'redISqr works only with red numbers'); this.red.verify1(this); return this.red.isqr(this); }\n redSqrt() { this.assert(this.red, 'redSqrt works only with red numbers'); this.red.verify1(this); return this.red.sqrt(this); }\n redInvm() { this.assert(this.red, 'redInvm works only with red numbers'); this.red.verify1(this); return this.red.invm(this); }\n redNeg() { this.assert(this.red, 'redNeg works only with red numbers'); this.red.verify1(this); return this.red.neg(this); }\n redPow(num) { this.assert(this.red != null && num.red == null, 'redPow(normalNum)'); this.red.verify1(this); return this.red.pow(this, num); }\n /**\n * Creates a BigNumber from a hexadecimal string.\n *\n * @static\n * @method fromHex\n * @param hex - The hexadecimal string to create a BigNumber from.\n * @param endian - Optional endianness for parsing the hex string.\n * @returns Returns a BigNumber created from the hexadecimal input string.\n *\n * @example\n * const exampleHex = 'a1b2c3';\n * const bigNumber = BigNumber.fromHex(exampleHex);\n */\n static fromHex(hex, endian) {\n let eE = 'be';\n if (endian === 'little' || endian === 'le')\n eE = 'le';\n return new BigNumber(hex, 16, eE);\n }\n /**\n * Converts this BigNumber to a hexadecimal string.\n *\n * @method toHex\n * @param length - The minimum length of the hex string\n * @returns Returns a string representing the hexadecimal value of this BigNumber.\n *\n * @example\n * const bigNumber = new BigNumber(255)\n * const hex = bigNumber.toHex()\n */\n toHex(byteLength = 0) {\n if (this.isZero() && byteLength === 0)\n return '';\n let hexStr = this._getMinimalHex(); // Raw hex: \"0\", \"f\", \"10\", \"123\"\n // Ensure even length for non-zero values (byte alignment)\n if (hexStr !== '0' && hexStr.length % 2 !== 0) {\n hexStr = '0' + hexStr;\n }\n // Pad to minimum character length (byteLength * 2)\n const minChars = byteLength * 2;\n while (hexStr.length < minChars) {\n hexStr = '0' + hexStr;\n }\n return (this.isNeg() ? '-' : '') + hexStr;\n }\n /**\n * Creates a BigNumber from a JSON-serialized string.\n *\n * @static\n * @method fromJSON\n * @param str - The JSON-serialized string to create a BigNumber from.\n * @returns Returns a BigNumber created from the JSON input string.\n */\n static fromJSON(str) { return new BigNumber(str, 16); }\n /**\n * Creates a BigNumber from a number.\n *\n * @static\n * @method fromNumber\n * @param n - The number to create a BigNumber from.\n * @returns Returns a BigNumber equivalent to the input number.\n */\n static fromNumber(n) { return new BigNumber(n); }\n /**\n * Creates a BigNumber from a string, considering an optional base.\n *\n * @static\n * @method fromString\n * @param str - The string to create a BigNumber from.\n * @param base - The base used for conversion. If not provided, base 10 is assumed.\n * @returns Returns a BigNumber equivalent to the string after conversion from the specified base.\n */\n static fromString(str, base) { return new BigNumber(str, base); }\n /**\n * Creates a BigNumber from a signed magnitude number.\n *\n * @static\n * @method fromSm\n * @param bytes - The signed magnitude number to convert to a BigNumber.\n * @param endian - Defines endianess. If not provided, big endian is assumed.\n * @returns Returns a BigNumber equivalent to the signed magnitude number interpreted with specified endianess.\n */\n static fromSm(bytes, endian = 'big') {\n if (bytes.length === 0)\n return new BigNumber(0n);\n const beBytes = bytes.slice();\n if (endian === 'little') {\n beBytes.reverse();\n }\n let sign = 0;\n if (beBytes.length > 0 && (beBytes[0] & 0x80) !== 0) {\n sign = 1;\n beBytes[0] &= 0x7f;\n }\n let magnitude = 0n;\n if (CAN_USE_BUFFER) {\n const hex = BufferCtor.from(beBytes).toString('hex');\n magnitude = hex.length === 0 ? 0n : BigInt('0x' + hex);\n }\n else {\n let hex = '';\n for (const byte of beBytes) {\n hex += byte < 16 ? '0' + byte.toString(16) : byte.toString(16);\n }\n magnitude = hex.length === 0 ? 0n : BigInt('0x' + hex);\n }\n const r = new BigNumber(0n);\n r._initializeState(magnitude, sign);\n return r;\n }\n /**\n * Converts this BigNumber to a signed magnitude number.\n *\n * @method toSm\n * @param endian - Defines endianess. If not provided, big endian is assumed.\n * @returns Returns an array equivalent to this BigNumber interpreted as a signed magnitude with specified endianess.\n */\n toSm(endian = 'big') {\n if (this._magnitude === 0n) {\n return this._sign === 1 ? [0x80] : [];\n }\n let hex = this._getMinimalHex();\n if (hex.length % 2 !== 0)\n hex = '0' + hex;\n const byteLen = hex.length / 2;\n const bytes = new Array(byteLen);\n for (let i = 0, j = 0; i < hex.length; i += 2) {\n const high = HEX_CHAR_TO_VALUE[hex.charCodeAt(i)];\n const low = HEX_CHAR_TO_VALUE[hex.charCodeAt(i + 1)];\n bytes[j++] = ((high & 0xf) << 4) | (low & 0xf);\n }\n let result;\n if (this._sign === 1) {\n if ((bytes[0] & 0x80) !== 0) {\n result = [0x80, ...bytes];\n }\n else {\n result = bytes.slice();\n result[0] |= 0x80;\n }\n }\n else if ((bytes[0] & 0x80) !== 0) {\n result = [0x00, ...bytes];\n }\n else {\n result = bytes.slice();\n }\n return endian === 'little' ? result.reverse() : result;\n }\n /**\n * Creates a BigNumber from a number representing the \"bits\" value in a block header.\n *\n * @static\n * @method fromBits\n * @param bits - The number representing the bits value in a block header.\n * @param strict - If true, an error is thrown if the number has negative bit set.\n * @returns Returns a BigNumber equivalent to the \"bits\" value in a block header.\n * @throws Will throw an error if `strict` is `true` and the number has negative bit set.\n */\n static fromBits(bits, strict = false) {\n const nSize = bits >>> 24;\n const nWordCompact = bits & 0x007fffff;\n const isNegativeFromBit = (bits & 0x00800000) !== 0;\n if (strict && isNegativeFromBit) {\n throw new Error('negative bit set');\n }\n if (nSize === 0 && nWordCompact === 0) {\n if (isNegativeFromBit && strict)\n throw new Error('negative bit set for zero value');\n return new BigNumber(0n);\n }\n const bn = new BigNumber(nWordCompact);\n // This logic comes from original bn.js `fromCompact`\n if (nSize <= 3) {\n bn.iushrn((3 - nSize) * 8);\n }\n else {\n bn.iushln((nSize - 3) * 8);\n }\n if (isNegativeFromBit) {\n bn.ineg();\n }\n return bn;\n }\n /**\n * Converts this BigNumber to a number representing the \"bits\" value in a block header.\n *\n * @method toBits\n * @returns Returns a number equivalent to the \"bits\" value in a block header.\n */\n toBits() {\n this.strip();\n if (this.isZero() && !this.isNeg())\n return 0;\n const isActualNegative = this.isNeg();\n const bnAbs = this.abs(); // Work with absolute value for magnitude\n // Get byte array of absolute value\n let mB = bnAbs.toArray('be'); // Minimal byte array\n // Remove leading zeros from byte array, if any (toArray('be') might already do this if no length specified)\n let firstNonZeroIdx = 0;\n while (firstNonZeroIdx < mB.length - 1 && mB[firstNonZeroIdx] === 0) { // Keep last byte if it's [0]\n firstNonZeroIdx++;\n }\n mB = mB.slice(firstNonZeroIdx);\n let nSize = mB.length;\n if (nSize === 0 && !bnAbs.isZero()) { // Should not happen if bnAbs is truly non-zero and toArray is correct\n mB = [0]; // Should not be needed if toArray works for small numbers\n nSize = 1;\n }\n if (bnAbs.isZero()) { // if original was, e.g., -0, bnAbs is 0.\n nSize = 0; // Size for 0 is 0, unless it's negative 0 to be encoded\n mB = [];\n }\n let nWordNum;\n if (nSize === 0) {\n nWordNum = 0;\n }\n else if (nSize <= 3) {\n nWordNum = 0;\n for (let i = 0; i < nSize; i++) {\n nWordNum = (nWordNum << 8) | mB[i];\n }\n }\n else { // nSize > 3\n nWordNum = (mB[0] << 16) | (mB[1] << 8) | mB[2];\n }\n if ((nWordNum & 0x00800000) !== 0 && nSize <= 0xff) { // MSB of 3-byte mantissa is set\n nWordNum >>>= 8; // Shift mantissa over by one byte\n nSize++; // Increase size component by one\n }\n let b = (nSize << 24) | nWordNum;\n if (isActualNegative)\n b |= 0x00800000;\n return b >>> 0;\n }\n /**\n * Creates a BigNumber from the format used in Bitcoin scripts.\n *\n * @static\n * @method fromScriptNum\n * @param num - The number in the format used in Bitcoin scripts.\n * @param requireMinimal - If true, non-minimally encoded values will throw an error.\n * @param maxNumSize - The maximum allowed size for the number.\n * @returns Returns a BigNumber equivalent to the number used in a Bitcoin script.\n */\n static fromScriptNum(num, requireMinimal = false, maxNumSize) {\n if (maxNumSize !== undefined && num.length > maxNumSize)\n throw new Error('script number overflow');\n if (num.length === 0)\n return new BigNumber(0n);\n if (requireMinimal) {\n if ((num[num.length - 1] & 0x7f) === 0) {\n if (num.length <= 1 || (num[num.length - 2] & 0x80) === 0) {\n throw new Error('non-minimally encoded script number');\n }\n }\n }\n return BigNumber.fromSm(num, 'little');\n }\n /**\n * Converts this BigNumber to a number in the format used in Bitcoin scripts.\n *\n * @method toScriptNum\n * @returns Returns the equivalent to this BigNumber as a Bitcoin script number.\n */\n toScriptNum() { return this.toSm('little'); }\n /**\n * Compute the multiplicative inverse of the current BigNumber in the modulus field specified by `p`.\n * The multiplicative inverse is a number which when multiplied with the current BigNumber gives '1' in the modulus field.\n *\n * @method _invmp\n * @param p - The `BigNumber` specifying the modulus field.\n * @returns The multiplicative inverse `BigNumber` in the modulus field specified by `p`.\n */\n _invmp(p) {\n this.assert(p._sign === 0, 'p must not be negative for _invmp');\n this.assert(!p.isZero(), 'p must not be zero for _invmp');\n const aBN = this.umod(p);\n let aVal = aBN._magnitude;\n let bVal = p._magnitude;\n let x1Val = 1n;\n let x2Val = 0n;\n const modulus = p._magnitude;\n while (aVal > 1n && bVal > 1n) {\n let i = 0;\n while (((aVal >> BigInt(i)) & 1n) === 0n)\n i++;\n if (i > 0) {\n aVal >>= BigInt(i);\n for (let k = 0; k < i; ++k) {\n if ((x1Val & 1n) !== 0n)\n x1Val += modulus;\n x1Val >>= 1n;\n }\n }\n let j = 0;\n while (((bVal >> BigInt(j)) & 1n) === 0n)\n j++;\n if (j > 0) {\n bVal >>= BigInt(j);\n for (let k = 0; k < j; ++k) {\n if ((x2Val & 1n) !== 0n)\n x2Val += modulus;\n x2Val >>= 1n;\n }\n }\n if (aVal >= bVal) {\n aVal -= bVal;\n x1Val -= x2Val;\n }\n else {\n bVal -= aVal;\n x2Val -= x1Val;\n }\n }\n let resultVal;\n if (aVal === 1n)\n resultVal = x1Val;\n else if (bVal === 1n)\n resultVal = x2Val;\n else if (aVal === 0n && bVal === 1n)\n resultVal = x2Val;\n else if (bVal === 0n && aVal === 1n)\n resultVal = x1Val;\n else\n throw new Error('_invmp: GCD is not 1, inverse does not exist. aVal=' + aVal + ', bVal=' + bVal);\n resultVal %= modulus;\n if (resultVal < 0n)\n resultVal += modulus;\n const resultBN = new BigNumber(0n);\n resultBN._initializeState(resultVal, 0);\n return resultBN;\n }\n /**\n * Performs multiplication between the BigNumber instance and a given BigNumber.\n * It chooses the multiplication method based on the lengths of the numbers to optimize execution time.\n *\n * @method mulTo\n * @param num - The BigNumber multiply with.\n * @param out - The BigNumber where to store the result.\n * @returns The BigNumber resulting from the multiplication operation.\n */\n mulTo(num, out) {\n out._magnitude = this._magnitude * num._magnitude;\n out._sign = out._magnitude === 0n ? 0 : (this._sign ^ num._sign);\n out._nominalWordLength = this.length + num.length;\n out.red = null;\n out.normSign();\n return out;\n }\n}\n//# sourceMappingURL=BigNumber.js.map","import BigNumber from './BigNumber.js';\n/**\n * A representation of a pseudo-Mersenne prime.\n * A pseudo-Mersenne prime has the general form 2^n - k, where n and k are integers.\n *\n * @class Mersenne\n *\n * @property name - The identifier for the Mersenne instance.\n * @property p - BigNumber equivalent to 2^n - k.\n * @property k - The constant subtracted from 2^n to derive a pseudo-Mersenne prime.\n * @property n - The exponent which determines the magnitude of the prime.\n */\nexport default class Mersenne {\n name;\n p;\n k;\n n;\n tmp;\n /**\n * @constructor\n * @param name - An identifier for the Mersenne instance.\n * @param p - A string representation of the pseudo-Mersenne prime, expressed in hexadecimal.\n *\n * @example\n * const mersenne = new Mersenne('M31', '7FFFFFFF');\n */\n constructor(name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BigNumber(p, 16);\n this.n = this.p.bitLength();\n this.k = new BigNumber(BigInt(1)).iushln(this.n).isub(this.p); // Use 1n for BigInt compatibility\n this.tmp = this._tmp();\n }\n /**\n * Creates a temporary BigNumber structure for computations,\n * ensuring the appropriate number of words are initially allocated.\n *\n * @method _tmp\n * @returns A BigNumber with scaled size depending on prime magnitude.\n */\n _tmp() {\n const tmp = new BigNumber(BigInt(0)); // Initialize with BigInt 0\n const requiredWords = Math.ceil(this.n / BigNumber.wordSize);\n tmp.expand(Math.max(1, requiredWords)); // Expand sets _nominalWordLength\n return tmp;\n }\n /**\n * Reduces an input BigNumber in place, under the assumption that\n * it is less than the square of the pseudo-Mersenne prime.\n *\n * @method ireduce\n * @param num - The BigNumber to be reduced.\n * @returns The reduced BigNumber.\n *\n * @example\n * const reduced = mersenne.ireduce(new BigNumber('2345', 16));\n */\n ireduce(num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n const r = num; // num is directly modified\n let rlen;\n do {\n this.split(r, this.tmp); // r is modified (becomes HI), this.tmp becomes LO\n this.imulK(r); // r becomes HI * K\n r.iadd(this.tmp); // r becomes HI * K + LO\n rlen = r.bitLength();\n } while (rlen > this.n);\n const cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words = [0]; // Set to zero using the words setter\n }\n else if (cmp > 0) {\n r.isub(this.p);\n }\n // No explicit strip needed here if operations maintain correctness and setter handles it.\n // However, ensuring it's stripped to minimal form after reduction is good.\n r.strip();\n return r;\n }\n /**\n * Shifts bits of the input BigNumber to the right, in place,\n * to meet the magnitude of the pseudo-Mersenne prime.\n *\n * @method split\n * @param input - The BigNumber to be shifted (will contain HI part).\n * @param out - The BigNumber to hold the shifted result (LO part).\n *\n * @example\n * mersenne.split(new BigNumber('2345', 16), new BigNumber());\n */\n split(input, out) {\n // out gets the LO bits (shifted out part)\n // input gets modified to be the HI bits (remaining part after shift)\n input.iushrn(this.n, 0, out);\n }\n /**\n * Performs an in-place multiplication of the parameter by constant k.\n *\n * @method imulK\n * @param num - The BigNumber to multiply with k.\n * @returns The result of the multiplication, in BigNumber format.\n *\n * @example\n * const multiplied = mersenne.imulK(new BigNumber('2345', 16));\n */\n imulK(num) {\n return num.imul(this.k);\n }\n}\n//# sourceMappingURL=Mersenne.js.map","import Mersenne from './Mersenne.js';\n/**\n * A class representing K-256, a prime number with optimizations, specifically used in the secp256k1 curve.\n * It extends the functionalities of the Mersenne class.\n * K-256 prime is represented as 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'\n *\n * @class K256\n * @extends {Mersenne}\n *\n * @example\n * const k256 = new K256();\n */\nexport default class K256 extends Mersenne {\n /**\n * Constructor for the K256 class.\n * Creates an instance of K256 using the super constructor from Mersenne.\n *\n * @constructor\n *\n * @example\n * const k256 = new K256();\n */\n constructor() {\n super('k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n /**\n * Splits a BigNumber into a new BigNumber based on specific computation\n * rules. This method modifies the input and output big numbers.\n *\n * @method split\n * @param input - The BigNumber to be split.\n * @param output - The BigNumber that results from the split.\n *\n * @example\n * const input = new BigNumber(3456);\n * const output = new BigNumber(0);\n * k256.split(input, output);\n */\n split(input, output) {\n const mask = 0x3fffff; // 22 bits\n const inputWords = input.words; // Access via getter\n const inputNominalLength = input.length; // Access via getter, respects _nominalWordLength\n const outLen = Math.min(inputNominalLength, 9);\n const tempOutputWords = new Array(outLen + (inputNominalLength > 9 ? 1 : 0)).fill(0);\n for (let i = 0; i < outLen; i++) {\n tempOutputWords[i] = inputWords[i];\n }\n let currentOutputWordCount = outLen;\n if (inputNominalLength <= 9) {\n const finalOutputWords = new Array(currentOutputWordCount);\n for (let i = 0; i < currentOutputWordCount; ++i)\n finalOutputWords[i] = tempOutputWords[i];\n output.words = finalOutputWords; // Use setter\n input.words = [0]; // Use setter to set to 0\n return;\n }\n // Shift by 9 limbs\n let prev = inputWords[9];\n tempOutputWords[currentOutputWordCount++] = prev & mask;\n const finalOutputWords = new Array(currentOutputWordCount);\n for (let i = 0; i < currentOutputWordCount; ++i)\n finalOutputWords[i] = tempOutputWords[i];\n output.words = finalOutputWords; // Use setter for output\n // For input modification\n const tempInputNewWords = new Array(Math.max(1, inputNominalLength - 9)).fill(0);\n let currentInputNewWordCount = 0;\n for (let i = 10; i < inputNominalLength; i++) {\n const next = inputWords[i] | 0;\n if (currentInputNewWordCount < tempInputNewWords.length) { // Boundary check\n tempInputNewWords[currentInputNewWordCount++] = ((next & mask) << 4) | (prev >>> 22);\n }\n prev = next;\n }\n prev >>>= 22;\n if (currentInputNewWordCount < tempInputNewWords.length) { // Boundary check\n tempInputNewWords[currentInputNewWordCount++] = prev;\n }\n else if (prev !== 0 && tempInputNewWords.length > 0) { // If prev is non-zero but no space, this is an issue.\n // This case implies original logic might have relied on array auto-expansion or specific length handling\n // For safety, if there's still a carry and no space, the array should have been bigger.\n // However, the original logic `input.length -= 9` suggests truncation.\n }\n const finalInputNewWords = new Array(currentInputNewWordCount);\n for (let i = 0; i < currentInputNewWordCount; ++i)\n finalInputNewWords[i] = tempInputNewWords[i];\n input.words = finalInputNewWords; // Use setter, which will strip and set magnitude\n }\n /**\n * Multiplies a BigNumber ('num') with the constant 'K' in-place and returns the result.\n * 'K' is equal to 0x1000003d1 or in decimal representation: [ 64, 977 ].\n *\n * @method imulK\n * @param num - The BigNumber to multiply with K.\n * @returns Returns the mutated BigNumber after multiplication.\n *\n * @example\n * const number = new BigNumber(12345);\n * const result = k256.imulK(number);\n */\n imulK(num) {\n const currentWords = num.words; // Get current words based on _magnitude and _nominalWordLength\n const originalNominalLength = num.length; // Getter\n const newNominalLength = originalNominalLength + 2;\n const tempWords = new Array(newNominalLength).fill(0);\n for (let i = 0; i < originalNominalLength; i++) {\n tempWords[i] = currentWords[i];\n }\n // tempWords is now effectively num.words expanded with zeroes\n let lo = 0;\n for (let i = 0; i < newNominalLength; i++) { // Iterate up to new expanded length\n const w = tempWords[i] | 0;\n lo += w * 0x3d1; // 0x3d1 = 977\n tempWords[i] = lo & 0x3ffffff; // 26-bit mask\n lo = w * 0x40 + ((lo / 0x4000000) | 0); // 0x40 = 64. 0x4000000 = 2^26\n }\n num.words = tempWords; // Use setter to re-initialize from tempWords\n // The setter will handle _magnitude, _sign, _nominalWordLength, and strip.\n return num;\n }\n}\n//# sourceMappingURL=K256.js.map","import BigNumber from './BigNumber.js';\nimport K256 from './K256.js';\n/**\n * A base reduction engine that provides several arithmetic operations over\n * big numbers under a modulus context. It's particularly suitable for\n * calculations required in cryptography algorithms and encoding schemas.\n *\n * @class ReductionContext\n *\n * @property prime - The prime number utilised in the reduction context, typically an instance of Mersenne class.\n * @property m - The modulus used for reduction operations.\n */\nexport default class ReductionContext {\n prime;\n m;\n /**\n * Constructs a new ReductionContext.\n *\n * @constructor\n * @param m - A BigNumber representing the modulus, or 'k256' to create a context for Koblitz curve.\n *\n * @example\n * new ReductionContext(new BigNumber(11));\n * new ReductionContext('k256');\n */\n constructor(m) {\n if (m === 'k256') {\n const prime = new K256();\n this.m = prime.p;\n this.prime = prime;\n }\n else {\n this.assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n /**\n * Asserts that given value is truthy. Throws an Error with a provided message\n * if the value is falsy.\n *\n * @private\n * @param val - The value to be checked.\n * @param msg - The error message to be thrown if the value is falsy.\n *\n * @example\n * this.assert(1 < 2, '1 is not less than 2');\n * this.assert(2 < 1, '2 is less than 1'); // throws an Error with message '2 is less than 1'\n */\n assert(val, msg = 'Assertion failed') {\n if (!val)\n throw new Error(msg);\n }\n /**\n * Verifies that a BigNumber is positive and red. Throws an error if these\n * conditions are not met.\n *\n * @param a - The BigNumber to be verified.\n *\n * @example\n * this.verify1(new BigNumber(10).toRed());\n * this.verify1(new BigNumber(-10).toRed()); //throws an Error\n * this.verify1(new BigNumber(10)); //throws an Error\n */\n verify1(a) {\n this.assert(a.negative === 0, 'red works only with positives');\n this.assert(a.red, 'red works only with red numbers');\n }\n /**\n * Verifies that two BigNumbers are both positive and red. Also checks\n * that they have the same reduction context. Throws an error if these\n * conditions are not met.\n *\n * @param a - The first BigNumber to be verified.\n * @param b - The second BigNumber to be verified.\n *\n * @example\n * this.verify2(new BigNumber(10).toRed(this), new BigNumber(20).toRed(this));\n * this.verify2(new BigNumber(-10).toRed(this), new BigNumber(20).toRed(this)); //throws an Error\n * this.verify2(new BigNumber(10).toRed(this), new BigNumber(20)); //throws an Error\n */\n verify2(a, b) {\n this.assert((a.negative | b.negative) === 0, 'red works only with positives');\n this.assert(a.red != null && a.red === b.red, 'red works only with red numbers');\n }\n /**\n * Performs an in-place reduction of the given BigNumber by the modulus of the reduction context, 'm'.\n *\n * @method imod\n *\n * @param a - BigNumber to be reduced.\n *\n * @returns Returns the reduced result.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.imod(new BigNumber(19)); // Returns 5\n */\n imod(a) {\n if (this.prime != null)\n return this.prime.ireduce(a).forceRed(this);\n BigNumber.move(a, a.umod(this.m).forceRed(this));\n return a;\n }\n /**\n * Negates a BigNumber in the context of the modulus.\n *\n * @method neg\n *\n * @param a - BigNumber to negate.\n *\n * @returns Returns the negation of 'a' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.neg(new BigNumber(3)); // Returns 4\n */\n neg(a) {\n if (a.isZero()) {\n return a.clone();\n }\n return this.m.sub(a).forceRed(this);\n }\n /**\n * Performs the addition operation on two BigNumbers in the reduction context.\n *\n * @method add\n *\n * @param a - First BigNumber to add.\n * @param b - Second BigNumber to add.\n *\n * @returns Returns the result of 'a + b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(5));\n * context.add(new BigNumber(2), new BigNumber(4)); // Returns 1\n */\n add(a, b) {\n this.verify2(a, b);\n const res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res.forceRed(this);\n }\n /**\n * Performs an in-place addition operation on two BigNumbers in the reduction context\n * in order to avoid creating a new BigNumber, it modifies the first one with the result.\n *\n * @method iadd\n *\n * @param a - First BigNumber to add.\n * @param b - Second BigNumber to add.\n *\n * @returns Returns the modified 'a' after addition with 'b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(5));\n * const a = new BigNumber(2);\n * context.iadd(a, new BigNumber(4)); // Modifies 'a' to be 1\n */\n iadd(a, b) {\n this.verify2(a, b);\n const res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n }\n /**\n * Subtracts one BigNumber from another BigNumber in the reduction context.\n *\n * @method sub\n *\n * @param a - BigNumber to be subtracted from.\n * @param b - BigNumber to subtract.\n *\n * @returns Returns the result of 'a - b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.sub(new BigNumber(3), new BigNumber(2)); // Returns 1\n */\n sub(a, b) {\n this.verify2(a, b);\n const res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res.forceRed(this);\n }\n /**\n * Performs in-place subtraction of one BigNumber from another in the reduction context,\n * it modifies the first BigNumber with the result.\n *\n * @method isub\n *\n * @param a - BigNumber to be subtracted from.\n * @param b - BigNumber to subtract.\n *\n * @returns Returns the modified 'a' after subtraction of 'b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(5));\n * const a = new BigNumber(4);\n * context.isub(a, new BigNumber(2)); // Modifies 'a' to be 2\n */\n isub(a, b) {\n this.verify2(a, b);\n const res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n }\n /**\n * Performs bitwise shift left operation on a BigNumber in the reduction context.\n *\n * @method shl\n *\n * @param a - BigNumber to perform shift on.\n * @param num - The number of positions to shift.\n *\n * @returns Returns the result of shifting 'a' left by 'num' positions in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(32));\n * context.shl(new BigNumber(4), 2); // Returns 16\n */\n shl(a, num) {\n this.verify1(a);\n return this.imod(a.ushln(num));\n }\n /**\n * Performs in-place multiplication of two BigNumbers in the reduction context,\n * modifying the first BigNumber with the result.\n *\n * @method imul\n *\n * @param a - First BigNumber to multiply.\n * @param b - Second BigNumber to multiply.\n *\n * @returns Returns the modified 'a' after multiplication with 'b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * const a = new BigNumber(3);\n * context.imul(a, new BigNumber(2)); // Modifies 'a' to be 6\n */\n imul(a, b) {\n this.verify2(a, b);\n return this.imod(a.imul(b));\n }\n /**\n * Multiplies two BigNumbers in the reduction context.\n *\n * @method mul\n *\n * @param a - First BigNumber to multiply.\n * @param b - Second BigNumber to multiply.\n *\n * @returns Returns the result of 'a * b' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.mul(new BigNumber(3), new BigNumber(2)); // Returns 6\n */\n mul(a, b) {\n this.verify2(a, b);\n return this.imod(a.mul(b));\n }\n /**\n * Calculates the square of a BigNumber in the reduction context,\n * modifying the original BigNumber with the result.\n *\n * @method isqr\n *\n * @param a - BigNumber to be squared.\n *\n * @returns Returns the squared 'a' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * const a = new BigNumber(3);\n * context.isqr(a); // Modifies 'a' to be 2 (9 % 7 = 2)\n */\n isqr(a) {\n return this.imul(a, a.clone());\n }\n /**\n * Calculates the square of a BigNumber in the reduction context.\n *\n * @method sqr\n *\n * @param a - BigNumber to be squared.\n *\n * @returns Returns the result of 'a^2' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.sqr(new BigNumber(3)); // Returns 2 (9 % 7 = 2)\n */\n sqr(a) {\n return this.mul(a, a);\n }\n /**\n * Calculates the square root of a BigNumber in the reduction context.\n *\n * @method sqrt\n *\n * @param a - The BigNumber to calculate the square root of.\n *\n * @returns Returns the square root of 'a' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(9));\n * context.sqrt(new BigNumber(4)); // Returns 2\n */\n sqrt(a) {\n if (a.isZero())\n return a.clone();\n const mod3 = this.m.andln(3);\n this.assert(mod3 % 2 === 1);\n // Fast case\n if (mod3 === 3) {\n const pow = this.m.add(new BigNumber(1)).iushrn(2);\n return this.pow(a, pow);\n }\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n const q = this.m.subn(1);\n let s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n this.assert(!q.isZero());\n const one = new BigNumber(1).toRed(this);\n const nOne = one.redNeg();\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n const lpow = this.m.subn(1).iushrn(1);\n const zl = this.m.bitLength();\n const z = new BigNumber(2 * zl * zl).toRed(this);\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n let c = this.pow(z, q);\n let r = this.pow(a, q.addn(1).iushrn(1));\n let t = this.pow(a, q);\n let m = s;\n while (t.cmp(one) !== 0) {\n let tmp = t;\n let i = 0;\n for (; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n this.assert(i < m);\n const b = this.pow(c, new BigNumber(1).iushln(m - i - 1));\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n return r;\n }\n /**\n * Calculates the multiplicative inverse of a BigNumber in the reduction context.\n *\n * @method invm\n *\n * @param a - The BigNumber to find the multiplicative inverse of.\n *\n * @returns Returns the multiplicative inverse of 'a' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(11));\n * context.invm(new BigNumber(3)); // Returns 4 (3*4 mod 11 = 1)\n */\n invm(a) {\n const inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n }\n else {\n return this.imod(inv);\n }\n }\n /**\n * Raises a BigNumber to a power in the reduction context.\n *\n * @method pow\n *\n * @param a - The BigNumber to be raised to a power.\n * @param num - The power to raise the BigNumber to.\n *\n * @returns Returns the result of 'a' raised to the power of 'num' in the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.pow(new BigNumber(3), new BigNumber(2)); // Returns 2 (3^2 % 7)\n */\n pow(a, num) {\n if (num.isZero())\n return new BigNumber(1).toRed(this);\n if (num.cmpn(1) === 0)\n return a.clone();\n const windowSize = 4;\n const wnd = new Array(1 << windowSize);\n wnd[0] = new BigNumber(1).toRed(this);\n wnd[1] = a;\n let i = 2;\n for (; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n let res = wnd[0];\n let current = 0;\n let currentLen = 0;\n let start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n for (i = num.length - 1; i >= 0; i--) {\n const word = num.words[i];\n for (let j = start - 1; j >= 0; j--) {\n const bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0))\n continue;\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n return res;\n }\n /**\n * Converts a BigNumber to its equivalent in the reduction context.\n *\n * @method convertTo\n *\n * @param num - The BigNumber to convert to the reduction context.\n *\n * @returns Returns the converted BigNumber compatible with the reduction context.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * context.convertTo(new BigNumber(8)); // Returns 1 (8 % 7)\n */\n convertTo(num) {\n const r = num.umod(this.m);\n return r === num ? r.clone() : r;\n }\n /**\n * Converts a BigNumber from reduction context to its regular form.\n *\n * @method convertFrom\n *\n * @param num - The BigNumber to convert from the reduction context.\n *\n * @returns Returns the converted BigNumber in its regular form.\n *\n * @example\n * const context = new ReductionContext(new BigNumber(7));\n * const a = context.convertTo(new BigNumber(8)); // 'a' is now 1 in the reduction context\n * context.convertFrom(a); // Returns 1\n */\n convertFrom(num) {\n const res = num.clone();\n res.red = null;\n return res;\n }\n}\n//# sourceMappingURL=ReductionContext.js.map","import ReductionContext from './ReductionContext.js';\nimport BigNumber from './BigNumber.js';\n/**\n * Represents a Montgomery reduction context, which is a mathematical method\n * for performing modular multiplication without division.\n *\n * Montgomery reduction is an algorithm used mainly in cryptography which can\n * help to speed up calculations in contexts where there are many repeated\n * computations.\n *\n * This class extends the `ReductionContext` class.\n *\n * @class MontgomoryMethod\n * @extends {ReductionContext}\n *\n * @property shift - The number of bits in the modulus.\n * @property r - The 2^shift, shifted left by the bit length of modulus `m`.\n * @property r2 - The square of `r` modulo `m`.\n * @property rinv - The modular multiplicative inverse of `r` mod `m`.\n * @property minv - The modular multiplicative inverse of `m` mod `r`.\n */\nexport default class MontgomoryMethod extends ReductionContext {\n shift;\n r;\n r2;\n rinv;\n minv;\n /**\n * @constructor\n * @param m - The modulus to be used for the Montgomery method reductions.\n */\n constructor(m) {\n super(m);\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n this.r = new BigNumber(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n /**\n * Converts a number into the Montgomery domain.\n *\n * @method convertTo\n * @param num - The number to be converted into the Montgomery domain.\n * @returns The result of the conversion into the Montgomery domain.\n *\n * @example\n * const montMethod = new MontgomoryMethod(m);\n * const convertedNum = montMethod.convertTo(num);\n */\n convertTo(num) {\n return this.imod(num.ushln(this.shift));\n }\n /**\n * Converts a number from the Montgomery domain back to the original domain.\n *\n * @method convertFrom\n * @param num - The number to be converted from the Montgomery domain.\n * @returns The result of the conversion from the Montgomery domain.\n *\n * @example\n * const montMethod = new MontgomoryMethod(m);\n * const convertedNum = montMethod.convertFrom(num);\n */\n convertFrom(num) {\n const r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n }\n /**\n * Performs an in-place multiplication of two numbers in the Montgomery domain.\n *\n * @method imul\n * @param a - The first number to multiply.\n * @param b - The second number to multiply.\n * @returns The result of the in-place multiplication.\n *\n * @example\n * const montMethod = new MontgomoryMethod(m);\n * const product = montMethod.imul(a, b);\n */\n imul(a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n const t = a.imul(b);\n const c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n const u = t.isub(c).iushrn(this.shift);\n let res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n }\n else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n return res.forceRed(this);\n }\n /**\n * Performs the multiplication of two numbers in the Montgomery domain.\n *\n * @method mul\n * @param a - The first number to multiply.\n * @param b - The second number to multiply.\n * @returns The result of the multiplication.\n *\n * @example\n * const montMethod = new MontgomoryMethod(m);\n * const product = montMethod.mul(a, b);\n */\n mul(a, b) {\n if (a.isZero() || b.isZero())\n return new BigNumber(0).forceRed(this);\n const t = a.mul(b);\n const c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n const u = t.isub(c).iushrn(this.shift);\n let res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n }\n else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n return res.forceRed(this);\n }\n /**\n * Calculates the modular multiplicative inverse of a number in the Montgomery domain.\n *\n * @method invm\n * @param a - The number to compute the modular multiplicative inverse of.\n * @returns The modular multiplicative inverse of 'a'.\n *\n * @example\n * const montMethod = new MontgomoryMethod(m);\n * const inverse = montMethod.invm(a);\n */\n invm(a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n const res = this.imod(a._invmp(this.m).mul(this.r2));\n return res.forceRed(this);\n }\n}\n//# sourceMappingURL=MontgomoryMethod.js.map","import Curve from './Curve.js';\n/**\n * Base class for Point (affine coordinates) and JacobianPoint classes,\n * defining their curve and type.\n */\nexport default class BasePoint {\n curve;\n type;\n precomputed;\n constructor(type) {\n this.curve = new Curve(); // Always initialized, so never null\n this.type = type;\n this.precomputed = null;\n }\n}\n//# sourceMappingURL=BasePoint.js.map","import BasePoint from './BasePoint.js';\nimport BigNumber from './BigNumber.js';\nimport Point from './Point.js';\n/**\n * The `JacobianPoint` class extends the `BasePoint` class for handling Jacobian coordinates on an Elliptic Curve.\n * This class defines the properties and the methods needed to work with points in Jacobian coordinates.\n *\n * The Jacobian coordinates represent a point (x, y, z) on an Elliptic Curve such that the usual (x, y) coordinates are given by (x/z^2, y/z^3).\n *\n * @property x - The `x` coordinate of the point in the Jacobian form.\n * @property y - The `y` coordinate of the point in the Jacobian form.\n * @property z - The `z` coordinate of the point in the Jacobian form.\n * @property zOne - Flag that indicates if the `z` coordinate is one.\n *\n * @example\n * const pointJ = new JacobianPoint('3', '4', '1');\n */\nexport default class JacobianPoint extends BasePoint {\n x;\n y;\n z;\n zOne;\n /**\n * Constructs a new `JacobianPoint` instance.\n *\n * @param x - If `null`, the x-coordinate will default to the curve's defined 'one' constant.\n * If `x` is not a BigNumber, `x` will be converted to a `BigNumber` assuming it is a hex string.\n *\n * @param y - If `null`, the y-coordinate will default to the curve's defined 'one' constant.\n * If `y` is not a BigNumber, `y` will be converted to a `BigNumber` assuming it is a hex string.\n *\n * @param z - If `null`, the z-coordinate will default to 0.\n * If `z` is not a BigNumber, `z` will be converted to a `BigNumber` assuming it is a hex string.\n *\n * @example\n * const pointJ1 = new JacobianPoint(null, null, null); // creates point at infinity\n * const pointJ2 = new JacobianPoint('3', '4', '1'); // creates point (3, 4, 1)\n */\n constructor(x, y, z) {\n super('jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BigNumber(0);\n }\n else {\n if (!BigNumber.isBN(x)) {\n x = new BigNumber(x, 16);\n }\n this.x = x;\n if (!BigNumber.isBN(y)) {\n y = new BigNumber(y, 16);\n }\n this.y = y;\n if (!BigNumber.isBN(z)) {\n z = new BigNumber(z, 16);\n }\n this.z = z;\n }\n if (this.x.red == null) {\n this.x = this.x.toRed(this.curve.red);\n }\n if (this.y.red == null) {\n this.y = this.y.toRed(this.curve.red);\n }\n if (this.z.red == null) {\n this.z = this.z.toRed(this.curve.red);\n }\n this.zOne = this.z === this.curve.one;\n // --- Canonicalize point at infinity ---\n if (this.isInfinity()) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BigNumber(0).toRed(this.curve.red);\n this.zOne = false;\n }\n }\n /**\n * Converts the `JacobianPoint` object instance to standard affine `Point` format and returns `Point` type.\n *\n * @returns The `Point`(affine) object representing the same point as the original `JacobianPoint`.\n *\n * If the initial `JacobianPoint` represents point at infinity, an instance of `Point` at infinity is returned.\n *\n * @example\n * const pointJ = new JacobianPoint('3', '4', '1');\n * const pointP = pointJ.toP(); // The point in affine coordinates.\n */\n toP() {\n if (this.isInfinity()) {\n return new Point(null, null);\n }\n const zinv = this.z.redInvm();\n const zinv2 = zinv.redSqr();\n const ax = this.x.redMul(zinv2);\n const ay = this.y.redMul(zinv2).redMul(zinv);\n return new Point(ax, ay);\n }\n /**\n * Negation operation. It returns the additive inverse of the Jacobian point.\n *\n * @method neg\n * @returns Returns a new Jacobian point as the result of the negation.\n *\n * @example\n * const jp = new JacobianPoint(x, y, z)\n * const result = jp.neg()\n */\n neg() {\n return new JacobianPoint(this.x, this.y.redNeg(), this.z);\n }\n /**\n * Addition operation in the Jacobian coordinates. It takes a Jacobian point as an argument\n * and returns a new Jacobian point as a result of the addition. In the special cases,\n * when either one of the points is the point at infinity, it will return the other point.\n *\n * @method add\n * @param p - The Jacobian point to be added.\n * @returns Returns a new Jacobian point as the result of the addition.\n *\n * @example\n * const p1 = new JacobianPoint(x1, y1, z1)\n * const p2 = new JacobianPoint(x2, y2, z2)\n * const result = p1.add(p2)\n */\n add(p) {\n // O + P = P\n if (this.isInfinity()) {\n return p;\n }\n // P + O = P\n if (p.isInfinity()) {\n return this;\n }\n // 12M + 4S + 7A\n const pz2 = p.z.redSqr();\n const z2 = this.z.redSqr();\n const u1 = this.x.redMul(pz2);\n const u2 = p.x.redMul(z2);\n const s1 = this.y.redMul(pz2.redMul(p.z));\n const s2 = p.y.redMul(z2.redMul(this.z));\n const h = u1.redSub(u2);\n const r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0) {\n return new JacobianPoint(null, null, null);\n }\n else {\n return this.dbl();\n }\n }\n const h2 = h.redSqr();\n const h3 = h2.redMul(h);\n const v = u1.redMul(h2);\n const nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n const ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n const nz = this.z.redMul(p.z).redMul(h);\n return new JacobianPoint(nx, ny, nz);\n }\n /**\n * Mixed addition operation. This function combines the standard point addition with\n * the transformation from the affine to Jacobian coordinates. It first converts\n * the affine point to Jacobian, and then preforms the addition.\n *\n * @method mixedAdd\n * @param p - The affine point to be added.\n * @returns Returns the result of the mixed addition as a new Jacobian point.\n *\n * @example\n * const jp = new JacobianPoint(x1, y1, z1)\n * const ap = new Point(x2, y2)\n * const result = jp.mixedAdd(ap)\n */\n mixedAdd(p) {\n // O + P = P\n if (this.isInfinity()) {\n return p.toJ();\n }\n // P + O = P\n if (p.isInfinity()) {\n return this;\n }\n // Ensure x and y are not null\n if (p.x === null || p.y === null) {\n throw new Error('Point coordinates cannot be null');\n }\n // 8M + 3S + 7A\n const z2 = this.z.redSqr();\n const u1 = this.x;\n const u2 = p.x.redMul(z2);\n const s1 = this.y;\n const s2 = p.y.redMul(z2).redMul(this.z);\n const h = u1.redSub(u2);\n const r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0) {\n return new JacobianPoint(null, null, null);\n }\n else {\n return this.dbl();\n }\n }\n const h2 = h.redSqr();\n const h3 = h2.redMul(h);\n const v = u1.redMul(h2);\n const nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n const ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n const nz = this.z.redMul(h);\n return new JacobianPoint(nx, ny, nz);\n }\n /**\n * Multiple doubling operation. It doubles the Jacobian point as many times as the pow parameter specifies. If pow is 0 or the point is the point at infinity, it will return the point itself.\n *\n * @method dblp\n * @param pow - The number of times the point should be doubled.\n * @returns Returns a new Jacobian point as the result of multiple doublings.\n *\n * @example\n * const jp = new JacobianPoint(x, y, z)\n * const result = jp.dblp(3)\n */\n dblp(pow) {\n if (pow === 0) {\n return this;\n }\n if (this.isInfinity()) {\n return this;\n }\n if (typeof pow === 'undefined') {\n return this.dbl();\n }\n /* eslint-disable @typescript-eslint/no-this-alias */\n let r = this;\n for (let i = 0; i < pow; i++) {\n r = r.dbl();\n }\n return r;\n }\n /**\n * Point doubling operation in the Jacobian coordinates. A special case is when the point is the point at infinity, in this case, this function will return the point itself.\n *\n * @method dbl\n * @returns Returns a new Jacobian point as the result of the doubling.\n *\n * @example\n * const jp = new JacobianPoint(x, y, z)\n * const result = jp.dbl()\n */\n dbl() {\n if (this.isInfinity()) {\n return this;\n }\n let nx;\n let ny;\n let nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n // XX = X1^2\n const xx = this.x.redSqr();\n // YY = Y1^2\n const yy = this.y.redSqr();\n // YYYY = YY^2\n const yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n let s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n const m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n const t = m.redSqr().redISub(s).redISub(s);\n // 8 * YYYY\n let yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n }\n else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n // A = X1^2\n const a = this.x.redSqr();\n // B = Y1^2\n const b = this.y.redSqr();\n // C = B^2\n const c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n let d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n const e = a.redAdd(a).redIAdd(a);\n // F = E^2\n const f = e.redSqr();\n // 8 * C\n let c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n return new JacobianPoint(nx, ny, nz);\n }\n /**\n * Equality check operation. It checks whether the affine or Jacobian point is equal to this Jacobian point.\n *\n * @method eq\n * @param p - The affine or Jacobian point to compare with.\n * @returns Returns true if the points are equal, otherwise returns false.\n *\n * @example\n * const jp1 = new JacobianPoint(x1, y1, z1)\n * const jp2 = new JacobianPoint(x2, y2, z2)\n * const areEqual = jp1.eq(jp2)\n */\n eq(p) {\n if (p.type === 'affine') {\n return this.eq(p.toJ());\n }\n if (this === p) {\n return true;\n }\n p = p;\n // --- Infinity handling ---\n if (this.isInfinity() && p.isInfinity()) {\n return true;\n }\n if (this.isInfinity() !== p.isInfinity()) {\n return false;\n }\n // x1 * z2^2 == x2 * z1^2\n const z2 = this.z.redSqr();\n const pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) {\n return false;\n }\n // y1 * z2^3 == y2 * z1^3\n const z3 = z2.redMul(this.z);\n const pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n }\n /**\n * Equality check operation in relation to an x coordinate of a point in projective coordinates.\n * It checks whether the x coordinate of the Jacobian point is equal to the provided x coordinate\n * of a point in projective coordinates.\n *\n * @method eqXToP\n * @param x - The x coordinate of a point in projective coordinates.\n * @returns Returns true if the x coordinates are equal, otherwise returns false.\n *\n * @example\n * const jp = new JacobianPoint(x1, y1, z1)\n * const isXEqual = jp.eqXToP(x2)\n */\n eqXToP(x) {\n const zs = this.z.redSqr();\n const rx = x.toRed(this.curve?.red).redMul(zs);\n if (this.x.cmp(rx) === 0) {\n return true;\n }\n const xc = x.clone();\n if (this.curve === null || (this.curve.redN == null)) {\n throw new Error('Curve or redN is not initialized.');\n }\n const t = this.curve.redN.redMul(zs);\n while (xc.cmp(this.curve.p) < 0) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0) {\n return false;\n }\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0) {\n return true;\n }\n }\n // ✅ Ensure function always returns a boolean\n return false;\n }\n /**\n * Returns the string representation of the JacobianPoint instance.\n * @method inspect\n * @returns Returns the string description of the JacobianPoint. If the JacobianPoint represents a point at infinity, the return value of this function is '<EC JPoint Infinity>'. For a normal point, it returns the string description format as '<EC JPoint x: x-coordinate y: y-coordinate z: z-coordinate>'.\n *\n * @example\n * const point = new JacobianPoint('5', '6', '1');\n * console.log(point.inspect()); // Output: '<EC JPoint x: 5 y: 6 z: 1>'\n */\n inspect() {\n if (this.isInfinity()) {\n return '<EC JPoint Infinity>';\n }\n return ('<EC JPoint x: ' +\n this.x.toString(16, 2) +\n ' y: ' +\n this.y.toString(16, 2) +\n ' z: ' +\n this.z.toString(16, 2) +\n '>');\n }\n /**\n * Checks whether the JacobianPoint instance represents a point at infinity.\n * @method isInfinity\n * @returns Returns true if the JacobianPoint's z-coordinate equals to zero (which represents the point at infinity in Jacobian coordinates). Returns false otherwise.\n *\n * @example\n * const point = new JacobianPoint('5', '6', '0');\n * console.log(point.isInfinity()); // Output: true\n */\n isInfinity() {\n return this.z.cmpn(0) === 0;\n }\n}\n//# sourceMappingURL=JacobianPoint.js.map","// src/primitives/hex.ts\n// Accepts empty string because empty byte arrays are valid in Bitcoin.\nconst PURE_HEX_REGEX = /^[0-9a-fA-F]*$/;\nexport function assertValidHex(msg) {\n if (typeof msg !== 'string') {\n console.error('assertValidHex FAIL (non-string):', msg);\n throw new Error('Invalid hex string');\n }\n // allow empty\n if (msg.length === 0)\n return;\n if (!PURE_HEX_REGEX.test(msg)) {\n console.error('assertValidHex FAIL (bad hex):', msg);\n throw new Error('Invalid hex string');\n }\n}\nexport function normalizeHex(msg) {\n assertValidHex(msg);\n // If empty, return empty — never force to \"00\"\n if (msg.length === 0)\n return '';\n let normalized = msg.toLowerCase();\n // Pad odd-length hex\n if (normalized.length % 2 !== 0) {\n normalized = '0' + normalized;\n }\n return normalized;\n}\n//# sourceMappingURL=hex.js.map","import BigNumber from './BigNumber.js';\nimport { hash256 } from './Hash.js';\nimport { assertValidHex } from './hex.js';\nconst BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\nconst CAN_USE_BUFFER = BufferCtor != null && typeof BufferCtor.from === 'function';\n/**\n * Prepends a '0' to an odd character length word to ensure it has an even number of characters.\n * @param {string} word - The input word.\n * @returns {string} - The word with a leading '0' if it's an odd character length; otherwise, the original word.\n */\nexport const zero2 = (word) => {\n if (word.length % 2 === 1) {\n return '0' + word;\n }\n else {\n return word;\n }\n};\n/**\n * Converts an array of numbers to a hexadecimal string representation.\n * @param {number[]} msg - The input array of numbers.\n * @returns {string} - The hexadecimal string representation of the input array.\n */\nconst HEX_DIGITS = '0123456789abcdef';\nconst HEX_BYTE_STRINGS = new Array(256);\nfor (let i = 0; i < 256; i++) {\n HEX_BYTE_STRINGS[i] =\n HEX_DIGITS[(i >> 4) & 0xf] + HEX_DIGITS[i & 0xf];\n}\nexport const toHex = (msg) => {\n if (CAN_USE_BUFFER) {\n return BufferCtor.from(msg).toString('hex');\n }\n if (msg.length === 0)\n return '';\n const out = new Array(msg.length);\n for (let i = 0; i < msg.length; i++) {\n out[i] = HEX_BYTE_STRINGS[msg[i] & 0xff];\n }\n return out.join('');\n};\n/**\n * Converts various message formats into an array of numbers.\n * Supports arrays, hexadecimal strings, base64 strings, and UTF-8 strings.\n *\n * @param {any} msg - The input message (array or string).\n * @param {('hex' | 'utf8' | 'base64')} enc - Specifies the string encoding, if applicable.\n * @returns {any[]} - Array representation of the input.\n */\nexport const toArray = (msg, enc) => {\n if (Array.isArray(msg))\n return msg.slice();\n if (msg === undefined)\n return [];\n if (typeof msg !== 'string') {\n return Array.from(msg, (item) => item | 0);\n }\n switch (enc) {\n case 'hex':\n return hexToArray(msg);\n case 'base64':\n return base64ToArray(msg);\n default:\n return utf8ToArray(msg);\n }\n};\nconst HEX_CHAR_TO_VALUE = new Int8Array(256).fill(-1);\nfor (let i = 0; i < 10; i++) {\n HEX_CHAR_TO_VALUE[48 + i] = i; // '0'-'9'\n}\nfor (let i = 0; i < 6; i++) {\n HEX_CHAR_TO_VALUE[65 + i] = 10 + i; // 'A'-'F'\n HEX_CHAR_TO_VALUE[97 + i] = 10 + i; // 'a'-'f'\n}\nconst hexToArray = (msg) => {\n assertValidHex(msg);\n const normalized = msg.length % 2 === 0 ? msg : '0' + msg;\n if (CAN_USE_BUFFER) {\n return Array.from(BufferCtor.from(normalized, 'hex'));\n }\n const out = new Array(normalized.length / 2);\n let o = 0;\n for (let i = 0; i < normalized.length; i += 2) {\n const hi = HEX_CHAR_TO_VALUE[normalized.charCodeAt(i)];\n const lo = HEX_CHAR_TO_VALUE[normalized.charCodeAt(i + 1)];\n out[o++] = (hi << 4) | lo;\n }\n return out;\n};\nexport function base64ToArray(msg) {\n if (typeof msg !== 'string') {\n throw new TypeError('msg must be a string');\n }\n // cleanse string\n let s = msg.trim().replace(/[\\r\\n\\t\\f\\v ]+/g, '');\n s = s.replace(/-/g, '+').replace(/_/g, '/');\n // ensure padding is correct\n const padIndex = s.indexOf('=');\n if (padIndex !== -1) {\n const pad = s.slice(padIndex);\n if (!/^={1,2}$/.test(pad)) {\n throw new Error('Invalid base64 padding');\n }\n if (s.slice(0, padIndex).includes('=')) {\n throw new Error('Invalid base64 padding');\n }\n s = s.slice(0, padIndex);\n }\n // if (s.length % 4 === 1)\n // {\n // throw new Error(\"Invalid base64 length\")\n // }\n const result = [];\n let bitBuffer = 0;\n let bitCount = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n // using ascii map values rather than indexOf\n let v = -1;\n if (c >= 65 && c <= 90) {\n v = c - 65; // A-Z\n }\n else if (c >= 97 && c <= 122) {\n v = c - 97 + 26; // a-z\n }\n else if (c >= 48 && c <= 57) {\n v = c - 48 + 52; // 0-9\n }\n else if (c === 43) {\n v = 62; // +\n }\n else if (c === 47) {\n v = 63; // /\n }\n else {\n throw new Error(`Invalid base64 character at index ${i}`);\n }\n bitBuffer = (bitBuffer << 6) | v;\n bitCount += 6;\n while (bitCount >= 8) {\n bitCount -= 8;\n result.push((bitBuffer >> bitCount) & 0xff);\n bitBuffer &= (1 << bitCount) - 1;\n }\n }\n // check for valid padding bits\n // if (bitCount !== 0 && bitBuffer !== 0) {\n // throw new Error(\"Invalid base64: non-zero padding bits\")\n // }\n return result;\n}\n/**\n * Encodes a string into an array of bytes representing its UTF-8 encoding.\n * Any lone surrogates are replaced with the Unicode replacement character (U+FFFD).\n *\n * @param str - The string to encode.\n * @returns An array of numbers, each representing a byte in the UTF-8 encoded string.\n */\nfunction utf8ToArray(str) {\n const result = [];\n for (let i = 0; i < str.length; i++) {\n const cp = str.codePointAt(i);\n if (cp === undefined) {\n // Should never be out of range.\n throw new Error(`Index out of range: ${i}`);\n }\n let codePoint = cp;\n if (codePoint > 0xFFFF) {\n // Valid surrogate pair => skip the next code unit because codePointAt\n // has already combined them into a single code point.\n i++;\n }\n else {\n // Check if codePoint is a lone (unpaired) high surrogate or low surrogate.\n if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {\n // Replace with the replacement character (U+FFFD).\n codePoint = 0xFFFD;\n }\n }\n // Encode according to the UTF-8 standard\n if (codePoint <= 0x7F) {\n result.push(codePoint);\n }\n else if (codePoint <= 0x7FF) {\n result.push(0xC0 | (codePoint >> 6), 0x80 | (codePoint & 0x3F));\n }\n else if (codePoint <= 0xFFFF) {\n result.push(0xE0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3F), 0x80 | (codePoint & 0x3F));\n }\n else {\n result.push(0xF0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3F), 0x80 | ((codePoint >> 6) & 0x3F), 0x80 | (codePoint & 0x3F));\n }\n }\n return result;\n}\n/**\n * Converts an array of numbers to a UTF-8 encoded string.\n * @param {number[]} arr - The input array of numbers.\n * @returns {string} - The UTF-8 encoded string.\n */\nexport const toUTF8 = (arr) => {\n let result = '';\n const replacementChar = '\\uFFFD';\n for (let i = 0; i < arr.length; i++) {\n const byte1 = arr[i];\n if (byte1 <= 0x7f) {\n result += String.fromCharCode(byte1);\n continue;\n }\n const emitReplacement = () => {\n result += replacementChar;\n };\n if (byte1 >= 0xc0 && byte1 <= 0xdf) {\n if (i + 1 >= arr.length) {\n emitReplacement();\n continue;\n }\n const byte2 = arr[i + 1];\n if ((byte2 & 0xc0) !== 0x80) {\n emitReplacement();\n i += 1;\n continue;\n }\n const codePoint = ((byte1 & 0x1f) << 6) | (byte2 & 0x3f);\n result += String.fromCharCode(codePoint);\n i += 1;\n continue;\n }\n if (byte1 >= 0xe0 && byte1 <= 0xef) {\n if (i + 2 >= arr.length) {\n emitReplacement();\n continue;\n }\n const byte2 = arr[i + 1];\n const byte3 = arr[i + 2];\n if ((byte2 & 0xc0) !== 0x80 || (byte3 & 0xc0) !== 0x80) {\n emitReplacement();\n i += 2;\n continue;\n }\n const codePoint = ((byte1 & 0x0f) << 12) |\n ((byte2 & 0x3f) << 6) |\n (byte3 & 0x3f);\n result += String.fromCharCode(codePoint);\n i += 2;\n continue;\n }\n if (byte1 >= 0xf0 && byte1 <= 0xf7) {\n if (i + 3 >= arr.length) {\n emitReplacement();\n continue;\n }\n const byte2 = arr[i + 1];\n const byte3 = arr[i + 2];\n const byte4 = arr[i + 3];\n if ((byte2 & 0xc0) !== 0x80 ||\n (byte3 & 0xc0) !== 0x80 ||\n (byte4 & 0xc0) !== 0x80) {\n emitReplacement();\n i += 3;\n continue;\n }\n const codePoint = ((byte1 & 0x07) << 18) |\n ((byte2 & 0x3f) << 12) |\n ((byte3 & 0x3f) << 6) |\n (byte4 & 0x3f);\n const offset = codePoint - 0x10000;\n const highSurrogate = 0xd800 + (offset >> 10);\n const lowSurrogate = 0xdc00 + (offset & 0x3ff);\n result += String.fromCharCode(highSurrogate, lowSurrogate);\n i += 3;\n continue;\n }\n emitReplacement();\n }\n return result;\n};\n/**\n * Encodes an array of numbers into a specified encoding ('hex' or 'utf8'). If no encoding is provided, returns the original array.\n * @param {number[]} arr - The input array of numbers.\n * @param {('hex' | 'utf8')} enc - The desired encoding.\n * @returns {string | number[]} - The encoded message as a string (for 'hex' and 'utf8') or the original array.\n */\nexport const encode = (arr, enc) => {\n switch (enc) {\n case 'hex':\n return toHex(arr);\n case 'utf8':\n return toUTF8(arr);\n // If no encoding is provided, return the original array\n default:\n return arr;\n }\n};\n/**\n * Converts an array of bytes (each between 0 and 255) into a base64 encoded string.\n *\n * @param {number[]} byteArray - An array of numbers where each number is a byte (0-255).\n * @returns {string} The base64 encoded string.\n *\n * @example\n * const bytes = [72, 101, 108, 108, 111]; // Represents the string \"Hello\"\n * console.log(toBase64(bytes)); // Outputs: SGVsbG8=\n */\nexport function toBase64(byteArray) {\n const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n let result = '';\n let i;\n for (i = 0; i < byteArray.length; i += 3) {\n const byte1 = byteArray[i];\n const byte2 = i + 1 < byteArray.length ? byteArray[i + 1] : 0;\n const byte3 = i + 2 < byteArray.length ? byteArray[i + 2] : 0;\n const encoded1 = byte1 >> 2;\n const encoded2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n const encoded3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n const encoded4 = byte3 & 0x3f;\n result += base64Chars.charAt(encoded1) + base64Chars.charAt(encoded2);\n result += i + 1 < byteArray.length ? base64Chars.charAt(encoded3) : '=';\n result += i + 2 < byteArray.length ? base64Chars.charAt(encoded4) : '=';\n }\n return result;\n}\nconst base58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n/**\n * Converts a string from base58 to a binary array\n * @param str - The string representation\n * @returns The binary representation\n */\nexport const fromBase58 = (str) => {\n if (str === '' || typeof str !== 'string') {\n throw new Error(`Expected base58 string but got “${str}”`);\n }\n const match = str.match(/[IOl0]/gmu);\n if (match !== null) {\n throw new Error(`Invalid base58 character “${match.join('')}”`);\n }\n const lz = str.match(/^1+/gmu);\n const psz = (lz !== null) ? lz[0].length : 0;\n const size = ((str.length - psz) * (Math.log(58) / Math.log(256)) + 1) >>> 0;\n const uint8 = new Uint8Array([\n ...new Uint8Array(psz),\n ...(str.match(/./gmu) ?? [] // ✅ Safe Fix: If null, use []\n )\n .map((i) => base58chars.indexOf(i))\n .reduce((acc, i) => {\n acc = acc.map((j) => {\n const x = j * 58 + i;\n i = x >> 8;\n return x;\n });\n return acc;\n }, new Uint8Array(size))\n .reverse()\n .filter(((lastValue) => (value) => \n // @ts-expect-error\n (lastValue = lastValue || value))(false))\n ]);\n return [...uint8];\n};\n/**\n * Converts a binary array into a base58 string\n * @param bin - The binary array to convert to base58\n * @returns The base58 string representation\n */\nexport const toBase58 = (bin) => {\n const base58Map = Array(256).fill(-1);\n for (let i = 0; i < base58chars.length; ++i) {\n base58Map[base58chars.charCodeAt(i)] = i;\n }\n const result = [];\n for (const byte of bin) {\n let carry = byte;\n for (let j = 0; j < result.length; ++j) {\n const x = (base58Map[result[j]] << 8) + carry;\n result[j] = base58chars.charCodeAt(x % 58);\n carry = (x / 58) | 0;\n }\n while (carry !== 0) {\n result.push(base58chars.charCodeAt(carry % 58));\n carry = (carry / 58) | 0;\n }\n }\n for (const byte of bin) {\n if (byte !== 0)\n break;\n else\n result.push('1'.charCodeAt(0));\n }\n result.reverse();\n return String.fromCharCode(...result);\n};\n/**\n * Converts a binary array into a base58check string with a checksum\n * @param bin - The binary array to convert to base58check\n * @returns The base58check string representation\n */\nexport const toBase58Check = (bin, prefix = [0]) => {\n let hash = hash256([...prefix, ...bin]);\n hash = [...prefix, ...bin, ...hash.slice(0, 4)];\n return toBase58(hash);\n};\n/**\n * Converts a base58check string into a binary array after validating the checksum\n * @param str - The base58check string to convert to binary\n * @param enc - If hex, the return values will be hex strings, arrays of numbers otherwise\n * @param prefixLength - The length of the prefix. Optional, defaults to 1.\n * @returns The binary array representation\n */\nexport const fromBase58Check = (str, enc, prefixLength = 1) => {\n const bin = fromBase58(str);\n let prefix = bin.slice(0, prefixLength);\n let data = bin.slice(prefixLength, -4);\n let hash = [...prefix, ...data];\n hash = hash256(hash);\n bin.slice(-4).forEach((check, index) => {\n if (check !== hash[index]) {\n throw new Error('Invalid checksum');\n }\n });\n if (enc === 'hex') {\n prefix = toHex(prefix);\n data = toHex(data);\n }\n return { prefix, data };\n};\nexport class Writer {\n bufs;\n length;\n constructor(bufs) {\n this.bufs = bufs !== undefined ? bufs : [];\n this.length = 0;\n for (const b of this.bufs)\n this.length += b.length;\n }\n getLength() {\n return this.length;\n }\n toUint8Array() {\n const out = new Uint8Array(this.length);\n let offset = 0;\n for (const buf of this.bufs) {\n out.set(buf, offset);\n offset += buf.length;\n }\n return out;\n }\n toArray() {\n const totalLength = this.length;\n const ret = new Array(totalLength);\n let offset = 0;\n for (const buf of this.bufs) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n ret[offset++] = buf[i];\n }\n }\n else {\n const arr = buf;\n for (let i = 0; i < arr.length; i++) {\n ret[offset++] = arr[i];\n }\n }\n }\n return ret;\n }\n write(buf) {\n this.bufs.push(buf);\n this.length += buf.length;\n return this;\n }\n writeReverse(buf) {\n const buf2 = new Array(buf.length);\n for (let i = 0; i < buf2.length; i++) {\n buf2[i] = buf[buf.length - 1 - i];\n }\n return this.write(buf2);\n }\n writeUInt8(n) {\n const buf = new Array(1);\n buf[0] = n & 0xff;\n this.write(buf);\n return this;\n }\n writeInt8(n) {\n const buf = new Array(1);\n buf[0] = n & 0xff;\n this.write(buf);\n return this;\n }\n writeUInt16BE(n) {\n const buf = [\n (n >> 8) & 0xff, // shift right 8 bits to get the high byte\n n & 0xff // low byte is just the last 8 bits\n ];\n return this.write(buf);\n }\n writeInt16BE(n) {\n return this.writeUInt16BE(n & 0xffff); // Mask with 0xFFFF to get the lower 16 bits\n }\n writeUInt16LE(n) {\n const buf = [\n n & 0xff, // low byte is just the last 8 bits\n (n >> 8) & 0xff // shift right 8 bits to get the high byte\n ];\n return this.write(buf);\n }\n writeInt16LE(n) {\n return this.writeUInt16LE(n & 0xffff); // Mask with 0xFFFF to get the lower 16 bits\n }\n writeUInt32BE(n) {\n const buf = [\n (n >> 24) & 0xff, // highest byte\n (n >> 16) & 0xff,\n (n >> 8) & 0xff,\n n & 0xff // lowest byte\n ];\n return this.write(buf);\n }\n writeInt32BE(n) {\n return this.writeUInt32BE(n >>> 0); // Using unsigned right shift to handle negative numbers\n }\n writeUInt32LE(n) {\n const buf = [\n n & 0xff, // lowest byte\n (n >> 8) & 0xff,\n (n >> 16) & 0xff,\n (n >> 24) & 0xff // highest byte\n ];\n return this.write(buf);\n }\n writeInt32LE(n) {\n return this.writeUInt32LE(n >>> 0); // Using unsigned right shift to handle negative numbers\n }\n writeUInt64BEBn(bn) {\n const buf = bn.toArray('be', 8);\n this.write(buf);\n return this;\n }\n writeUInt64LEBn(bn) {\n const buf = bn.toArray('be', 8);\n this.writeReverse(buf);\n return this;\n }\n writeUInt64LE(n) {\n const buf = new BigNumber(n).toArray('be', 8);\n this.writeReverse(buf);\n return this;\n }\n writeVarIntNum(n) {\n const buf = Writer.varIntNum(n);\n this.write(buf);\n return this;\n }\n writeVarIntBn(bn) {\n const buf = Writer.varIntBn(bn);\n this.write(buf);\n return this;\n }\n static varIntNum(n) {\n let buf;\n if (n < 0) {\n return this.varIntBn(new BigNumber(n));\n }\n if (n < 253) {\n buf = [n]; // 1 byte\n }\n else if (n < 0x10000) {\n // 253 followed by the number in little-endian format\n buf = [\n 253, // 0xfd\n n & 0xff, // low byte\n (n >> 8) & 0xff // high byte\n ];\n }\n else if (n < 0x100000000) {\n // 254 followed by the number in little-endian format\n buf = [\n 254, // 0xfe\n n & 0xff,\n (n >> 8) & 0xff,\n (n >> 16) & 0xff,\n (n >> 24) & 0xff\n ];\n }\n else {\n // 255 followed by the number in little-endian format\n // Since JavaScript bitwise operations work on 32 bits, we need to handle 64-bit numbers in two parts\n const low = n & 0xffffffff;\n const high = Math.floor(n / 0x100000000) & 0xffffffff;\n buf = [\n 255, // 0xff\n low & 0xff,\n (low >> 8) & 0xff,\n (low >> 16) & 0xff,\n (low >> 24) & 0xff,\n high & 0xff,\n (high >> 8) & 0xff,\n (high >> 16) & 0xff,\n (high >> 24) & 0xff\n ];\n }\n return buf;\n }\n static varIntBn(bn) {\n let buf;\n if (bn.isNeg()) {\n bn = bn.add(OverflowUint64); // Adjust for negative numbers\n }\n if (bn.ltn(253)) {\n const n = bn.toNumber();\n // No need for bitwise operation as the value is within a byte's range\n buf = [n];\n }\n else if (bn.ltn(0x10000)) {\n const n = bn.toNumber();\n // Value fits in a uint16\n buf = [253, n & 0xff, (n >> 8) & 0xff];\n }\n else if (bn.lt(new BigNumber(0x100000000))) {\n const n = bn.toNumber();\n // Value fits in a uint32\n buf = [\n 254,\n n & 0xff,\n (n >> 8) & 0xff,\n (n >> 16) & 0xff,\n (n >> 24) & 0xff\n ];\n }\n else {\n const bw = new Writer();\n bw.writeUInt8(255);\n bw.writeUInt64LEBn(bn);\n buf = bw.toArray();\n }\n return buf;\n }\n}\nexport class Reader {\n bin;\n pos;\n length;\n constructor(bin = [], pos = 0) {\n this.bin = bin;\n this.pos = pos;\n this.length = bin.length;\n }\n eof() {\n return this.pos >= this.length;\n }\n read(len = this.length) {\n const start = this.pos;\n const end = this.pos + len;\n this.pos = end;\n return this.bin.slice(start, end);\n }\n readReverse(len = this.length) {\n const buf2 = new Array(len);\n for (let i = 0; i < len; i++) {\n buf2[i] = this.bin[this.pos + len - 1 - i];\n }\n this.pos += len;\n return buf2;\n }\n readUInt8() {\n const val = this.bin[this.pos];\n this.pos += 1;\n return val;\n }\n readInt8() {\n const val = this.bin[this.pos];\n this.pos += 1;\n // If the sign bit is set, convert to negative value\n return (val & 0x80) !== 0 ? val - 0x100 : val;\n }\n readUInt16BE() {\n const val = (this.bin[this.pos] << 8) | this.bin[this.pos + 1];\n this.pos += 2;\n return val;\n }\n readInt16BE() {\n const val = this.readUInt16BE();\n // If the sign bit is set, convert to negative value\n return (val & 0x8000) !== 0 ? val - 0x10000 : val;\n }\n readUInt16LE() {\n const val = this.bin[this.pos] | (this.bin[this.pos + 1] << 8);\n this.pos += 2;\n return val;\n }\n readInt16LE() {\n const val = this.readUInt16LE();\n // If the sign bit is set, convert to negative value\n const x = (val & 0x8000) !== 0 ? val - 0x10000 : val;\n return x;\n }\n readUInt32BE() {\n const val = this.bin[this.pos] * 0x1000000 + // Shift the first byte by 24 bits\n ((this.bin[this.pos + 1] << 16) | // Shift the second byte by 16 bits\n (this.bin[this.pos + 2] << 8) | // Shift the third byte by 8 bits\n this.bin[this.pos + 3]); // The fourth byte\n this.pos += 4;\n return val;\n }\n readInt32BE() {\n const val = this.readUInt32BE();\n // If the sign bit is set, convert to negative value\n return (val & 0x80000000) !== 0 ? val - 0x100000000 : val;\n }\n readUInt32LE() {\n const val = (this.bin[this.pos] |\n (this.bin[this.pos + 1] << 8) |\n (this.bin[this.pos + 2] << 16) |\n (this.bin[this.pos + 3] << 24)) >>>\n 0;\n this.pos += 4;\n return val;\n }\n readInt32LE() {\n const val = this.readUInt32LE();\n // Explicitly check if the sign bit is set and then convert to a negative value\n return (val & 0x80000000) !== 0 ? val - 0x100000000 : val;\n }\n readUInt64BEBn() {\n const bin = this.bin.slice(this.pos, this.pos + 8);\n const bn = new BigNumber(bin);\n this.pos = this.pos + 8;\n return bn;\n }\n readUInt64LEBn() {\n const bin = this.readReverse(8);\n const bn = new BigNumber(bin);\n return bn;\n }\n readInt64LEBn() {\n const bin = this.readReverse(8);\n let bn = new BigNumber(bin);\n if (bn.gte(OverflowInt64)) {\n bn = bn.sub(OverflowUint64); // Adjust for negative numbers\n }\n return bn;\n }\n readVarIntNum(signed = true) {\n const first = this.readUInt8();\n let bn;\n switch (first) {\n case 0xfd:\n return this.readUInt16LE();\n case 0xfe:\n return this.readUInt32LE();\n case 0xff:\n bn = signed ? this.readInt64LEBn() : this.readUInt64LEBn();\n if (bn.lte(new BigNumber(2).pow(new BigNumber(53)))) {\n return bn.toNumber();\n }\n else {\n throw new Error('number too large to retain precision - use readVarIntBn');\n }\n default:\n return first;\n }\n }\n readVarInt() {\n const first = this.bin[this.pos];\n switch (first) {\n case 0xfd:\n return this.read(1 + 2);\n case 0xfe:\n return this.read(1 + 4);\n case 0xff:\n return this.read(1 + 8);\n default:\n return this.read(1);\n }\n }\n readVarIntBn() {\n const first = this.readUInt8();\n switch (first) {\n case 0xfd:\n return new BigNumber(this.readUInt16LE());\n case 0xfe:\n return new BigNumber(this.readUInt32LE());\n case 0xff:\n return this.readUInt64LEBn();\n default:\n return new BigNumber(first);\n }\n }\n}\nexport const minimallyEncode = (buf) => {\n if (buf.length === 0) {\n return buf;\n }\n // If the last byte is not 0x00 or 0x80, we are minimally encoded.\n const last = buf[buf.length - 1];\n if ((last & 0x7f) !== 0) {\n return buf;\n }\n // If the script is one byte long, then we have a zero, which encodes as an\n // empty array.\n if (buf.length === 1) {\n return [];\n }\n // If the next byte has it sign bit set, then we are minimaly encoded.\n if ((buf[buf.length - 2] & 0x80) !== 0) {\n return buf;\n }\n // We are not minimally encoded, we need to figure out how much to trim.\n for (let i = buf.length - 1; i > 0; i--) {\n // We found a non zero byte, time to encode.\n if (buf[i - 1] !== 0) {\n if ((buf[i - 1] & 0x80) !== 0) {\n // We found a byte with it sign bit set so we need one more\n // byte.\n buf[i] = last;\n return buf.slice(0, i + 1);\n }\n else {\n // the sign bit is clear, we can use it.\n buf[i - 1] |= last;\n return buf.slice(0, i);\n }\n }\n }\n // If we found the whole thing is zeros, then we have a zero.\n return [];\n};\nconst OverflowInt64 = new BigNumber(2).pow(new BigNumber(63));\nconst OverflowUint64 = new BigNumber(2).pow(new BigNumber(64));\n/**\n * Verifies that a value is not null or undefined, throwing an error if it is.\n *\n * @template T - The type of the value being verified\n * @param {T | undefined | null} value - The value to verify\n * @param {string} errorMessage - The error message to throw if the value is null or undefined\n * @returns {T} - The verified value\n * @throws {Error} - If the value is null or undefined\n *\n * @example\n * const myValue = verifyNotNull(someValue, 'someValue must be defined')\n */\nexport function verifyNotNull(value, errorMessage = 'Expected a valid value, but got undefined or null.') {\n if (value == null)\n throw new Error(errorMessage);\n return value;\n}\n//# sourceMappingURL=utils.js.map","import BasePoint from './BasePoint.js';\nimport JPoint from './JacobianPoint.js';\nimport BigNumber from './BigNumber.js';\nimport { toArray, toHex } from './utils.js';\n// -----------------------------------------------------------------------------\n// BigInt helpers & constants (secp256k1) – hoisted so we don't recreate them on\n// every Point.mul() call.\n// -----------------------------------------------------------------------------\nexport const BI_ZERO = 0n;\nexport const BI_ONE = 1n;\nexport const BI_TWO = 2n;\nexport const BI_THREE = 3n;\nexport const BI_FOUR = 4n;\nexport const BI_EIGHT = 8n;\nexport const P_BIGINT = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\nexport const N_BIGINT = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;\nexport const MASK_256 = (1n << 256n) - 1n; // 0xffff…ffff (256 sones)\nexport function red(x) {\n // first fold\n let hi = x >> 256n;\n x = (x & MASK_256) + (hi << 32n) + hi * 977n;\n // second fold (hi ≤ 2³² + 977 here, so one more pass is enough)\n hi = x >> 256n;\n x = (x & MASK_256) + (hi << 32n) + hi * 977n;\n // final conditional subtraction\n if (x >= P_BIGINT)\n x -= P_BIGINT;\n return x;\n}\nexport const biMod = (a) => red((a % P_BIGINT + P_BIGINT) % P_BIGINT);\nexport const biModSub = (a, b) => (a >= b ? a - b : P_BIGINT - (b - a));\nexport const biModMul = (a, b) => red(a * b);\nexport const biModAdd = (a, b) => red(a + b);\nexport const biModInv = (a) => {\n let lm = BI_ONE;\n let hm = BI_ZERO;\n let low = biMod(a);\n let high = P_BIGINT;\n while (low > BI_ONE) {\n const r = high / low;\n [lm, hm] = [hm - lm * r, lm];\n [low, high] = [high - low * r, low];\n }\n return biMod(lm);\n};\nexport const biModSqr = (a) => biModMul(a, a);\nexport const biModPow = (base, exp) => {\n let result = BI_ONE;\n base = biMod(base);\n let e = exp;\n while (e > BI_ZERO) {\n if ((e & BI_ONE) === BI_ONE)\n result = biModMul(result, base);\n base = biModMul(base, base);\n e >>= BI_ONE;\n }\n return result;\n};\nexport const P_PLUS1_DIV4 = (P_BIGINT + 1n) >> 2n;\nexport const biModSqrt = (a) => {\n const r = biModPow(a, P_PLUS1_DIV4);\n return biModMul(r, r) === biMod(a) ? r : null;\n};\nconst toBigInt = (x) => {\n if (BigNumber.isBN(x))\n return BigInt('0x' + x.toString(16));\n if (typeof x === 'string')\n return BigInt('0x' + x);\n if (Array.isArray(x))\n return BigInt('0x' + toHex(x));\n return BigInt(x);\n};\n// Generator point coordinates as bigint constants\nexport const GX_BIGINT = BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798');\nexport const GY_BIGINT = BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8');\n// Cache for precomputed windowed tables keyed by 'window:x:y'\nconst WNAF_TABLE_CACHE = new Map();\nexport const jpDouble = (P) => {\n const { X: X1, Y: Y1, Z: Z1 } = P;\n if (Y1 === BI_ZERO)\n return { X: BI_ZERO, Y: BI_ONE, Z: BI_ZERO };\n const Y1sq = biModMul(Y1, Y1);\n const S = biModMul(BI_FOUR, biModMul(X1, Y1sq));\n const M = biModMul(BI_THREE, biModMul(X1, X1));\n const X3 = biModSub(biModMul(M, M), biModMul(BI_TWO, S));\n const Y3 = biModSub(biModMul(M, biModSub(S, X3)), biModMul(BI_EIGHT, biModMul(Y1sq, Y1sq)));\n const Z3 = biModMul(BI_TWO, biModMul(Y1, Z1));\n return { X: X3, Y: Y3, Z: Z3 };\n};\nexport const jpAdd = (P, Q) => {\n if (P.Z === BI_ZERO)\n return Q;\n if (Q.Z === BI_ZERO)\n return P;\n const Z1Z1 = biModMul(P.Z, P.Z);\n const Z2Z2 = biModMul(Q.Z, Q.Z);\n const U1 = biModMul(P.X, Z2Z2);\n const U2 = biModMul(Q.X, Z1Z1);\n const S1 = biModMul(P.Y, biModMul(Z2Z2, Q.Z));\n const S2 = biModMul(Q.Y, biModMul(Z1Z1, P.Z));\n const H = biModSub(U2, U1);\n const r = biModSub(S2, S1);\n if (H === BI_ZERO) {\n if (r === BI_ZERO)\n return jpDouble(P);\n return { X: BI_ZERO, Y: BI_ONE, Z: BI_ZERO }; // Infinity\n }\n const HH = biModMul(H, H);\n const HHH = biModMul(H, HH);\n const V = biModMul(U1, HH);\n const X3 = biModSub(biModSub(biModMul(r, r), HHH), biModMul(BI_TWO, V));\n const Y3 = biModSub(biModMul(r, biModSub(V, X3)), biModMul(S1, HHH));\n const Z3 = biModMul(H, biModMul(P.Z, Q.Z));\n return { X: X3, Y: Y3, Z: Z3 };\n};\nexport const jpNeg = (P) => {\n if (P.Z === BI_ZERO)\n return P;\n return { X: P.X, Y: P_BIGINT - P.Y, Z: P.Z };\n};\n// Fast windowed-NAF scalar multiplication (default window = 5) in Jacobian\n// coordinates. Returns Q = k * P0 as a JacobianPoint.\nexport const scalarMultiplyWNAF = (k, P0, window = 5) => {\n const key = `${window}:${P0.x.toString(16)}:${P0.y.toString(16)}`;\n let tbl = WNAF_TABLE_CACHE.get(key);\n let P;\n if (tbl === undefined) {\n // Convert affine to Jacobian and pre-compute odd multiples\n const tblSize = 1 << (window - 1); // e.g. w=5 → 16 entries\n tbl = new Array(tblSize);\n P = { X: P0.x, Y: P0.y, Z: BI_ONE };\n tbl[0] = P;\n const twoP = jpDouble(P);\n for (let i = 1; i < tblSize; i++) {\n tbl[i] = jpAdd(tbl[i - 1], twoP);\n }\n WNAF_TABLE_CACHE.set(key, tbl);\n }\n else {\n P = tbl[0];\n }\n // Build wNAF representation of k\n const wnaf = [];\n const wBig = 1n << BigInt(window);\n const wHalf = wBig >> 1n;\n let kTmp = k;\n while (kTmp > 0n) {\n if ((kTmp & BI_ONE) === BI_ZERO) {\n wnaf.push(0);\n kTmp >>= BI_ONE;\n }\n else {\n let z = kTmp & (wBig - 1n); // kTmp mod 2^w\n if (z > wHalf)\n z -= wBig; // make it odd & within (-2^{w-1}, 2^{w-1})\n wnaf.push(Number(z));\n kTmp -= z;\n kTmp >>= BI_ONE;\n }\n }\n // Accumulate from MSB to LSB\n let Q = { X: BI_ZERO, Y: BI_ONE, Z: BI_ZERO }; // infinity\n for (let i = wnaf.length - 1; i >= 0; i--) {\n Q = jpDouble(Q);\n const di = wnaf[i];\n if (di !== 0) {\n const idx = Math.abs(di) >> 1; // (|di|-1)/2 because di is odd\n const addend = di > 0 ? tbl[idx] : jpNeg(tbl[idx]);\n Q = jpAdd(Q, addend);\n }\n }\n return Q;\n};\nexport const modN = (a) => {\n let r = a % N_BIGINT;\n if (r < 0n)\n r += N_BIGINT;\n return r;\n};\nexport const modMulN = (a, b) => modN(a * b);\n/** modular inverse modulo n with plain extended‑gcd (not constant‑time) */\nexport const modInvN = (a) => {\n let lm = 1n;\n let hm = 0n;\n let low = modN(a);\n let high = N_BIGINT;\n while (low > 1n) {\n const q = high / low;\n [lm, hm] = [hm - lm * q, lm];\n [low, high] = [high - low * q, low];\n }\n return modN(lm);\n};\n/**\n * `Point` class is a representation of an elliptic curve point with affine coordinates.\n * It extends the functionality of BasePoint and carries x, y coordinates of point on the curve.\n * It also introduces new methods for handling Point operations in elliptic curve.\n *\n * @class Point\n * @extends {BasePoint}\n *\n * @property x - The x-coordinate of the point.\n * @property y - The y-coordinate of the point.\n * @property inf - Flag to record if the point is at infinity in the Elliptic Curve.\n */\nexport default class Point extends BasePoint {\n x;\n y;\n inf;\n /**\n * Creates a point object from a given Array. These numbers can represent coordinates in hex format, or points\n * in multiple established formats.\n * The function verifies the integrity of the provided data and throws errors if inconsistencies are found.\n *\n * @method fromDER\n * @static\n * @param bytes - The point representation number array.\n * @returns Returns a new point representing the given string.\n * @throws `Error` If the point number[] value has a wrong length.\n * @throws `Error` If the point format is unknown.\n *\n * @example\n * const derPoint = [ 2, 18, 123, 108, 125, 83, 1, 251, 164, 214, 16, 119, 200, 216, 210, 193, 251, 193, 129, 67, 97, 146, 210, 216, 77, 254, 18, 6, 150, 190, 99, 198, 128 ];\n * const point = Point.fromDER(derPoint);\n */\n static fromDER(bytes) {\n const len = 32;\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06) {\n if (bytes[bytes.length - 1] % 2 !== 0) {\n throw new Error('Point string value is wrong length');\n }\n }\n else if (bytes[0] === 0x07) {\n if (bytes[bytes.length - 1] % 2 !== 1) {\n throw new Error('Point string value is wrong length');\n }\n }\n const res = new Point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len));\n return res;\n }\n else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return Point.fromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n }\n /**\n * Creates a point object from a given string. This string can represent coordinates in hex format, or points\n * in multiple established formats.\n * The function verifies the integrity of the provided data and throws errors if inconsistencies are found.\n *\n * @method fromString\n * @static\n *\n * @param str The point representation string.\n * @returns Returns a new point representing the given string.\n * @throws `Error` If the point string value has a wrong length.\n * @throws `Error` If the point format is unknown.\n *\n * @example\n * const pointStr = 'abcdef';\n * const point = Point.fromString(pointStr);\n */\n static fromString(str) {\n const bytes = toArray(str, 'hex');\n return Point.fromDER(bytes);\n }\n /**\n * Generates a point from an x coordinate and a boolean indicating whether the corresponding\n * y coordinate is odd.\n *\n * @method fromX\n * @static\n * @param x - The x coordinate of the point.\n * @param odd - Boolean indicating whether the corresponding y coordinate is odd or not.\n * @returns Returns the new point.\n * @throws `Error` If the point is invalid.\n *\n * @example\n * const xCoordinate = new BigNumber('10');\n * const point = Point.fromX(xCoordinate, true);\n */\n static fromX(x, odd) {\n let xBigInt = toBigInt(x);\n xBigInt = biMod(xBigInt);\n const y2 = biModAdd(biModMul(biModSqr(xBigInt), xBigInt), 7n);\n const y = biModSqrt(y2);\n if (y === null)\n throw new Error('Invalid point');\n let yBig = y;\n if ((yBig & BI_ONE) !== (odd ? BI_ONE : BI_ZERO)) {\n yBig = biModSub(P_BIGINT, yBig);\n }\n const xBN = new BigNumber(xBigInt.toString(16), 16);\n const yBN = new BigNumber(yBig.toString(16), 16);\n return new Point(xBN, yBN);\n }\n /**\n * Generates a point from a serialized JSON object. The function accounts for different options in the JSON object,\n * including precomputed values for optimization of EC operations, and calls another helper function to turn nested\n * JSON points into proper Point objects.\n *\n * @method fromJSON\n * @static\n * @param obj - An object or array that holds the data for the point.\n * @param isRed - A boolean to direct how the Point is constructed from the JSON object.\n * @returns Returns a new point based on the deserialized JSON object.\n *\n * @example\n * const serializedPoint = '{\"x\":52,\"y\":15}';\n * const point = Point.fromJSON(serializedPoint, true);\n */\n static fromJSON(obj, isRed) {\n if (typeof obj === 'string') {\n obj = JSON.parse(obj);\n }\n const res = new Point(obj[0], obj[1], isRed);\n if (typeof obj[2] !== 'object') {\n return res;\n }\n const obj2point = (obj) => {\n return new Point(obj[0], obj[1], isRed);\n };\n const pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: typeof pre.doubles === 'object' && pre.doubles !== null\n ? {\n step: pre.doubles.step,\n points: [res].concat(pre.doubles.points.map(obj2point))\n }\n : undefined,\n naf: typeof pre.naf === 'object' && pre.naf !== null\n ? {\n wnd: pre.naf.wnd,\n points: [res].concat(pre.naf.points.map(obj2point))\n }\n : undefined\n };\n return res;\n }\n /**\n * @constructor\n * @param x - The x-coordinate of the point. May be a number, a BigNumber, a string (which will be interpreted as hex), a number array, or null. If null, an \"Infinity\" point is constructed.\n * @param y - The y-coordinate of the point, similar to x.\n * @param isRed - A boolean indicating if the point is a member of the field of integers modulo the k256 prime. Default is true.\n *\n * @example\n * new Point('abc123', 'def456');\n * new Point(null, null); // Generates Infinity point.\n */\n constructor(x, y, isRed = true) {\n super('affine');\n this.precomputed = null;\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n }\n else {\n if (!BigNumber.isBN(x)) {\n x = new BigNumber(x, 16);\n }\n this.x = x;\n if (!BigNumber.isBN(y)) {\n y = new BigNumber(y, 16);\n }\n this.y = y;\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (this.x.red === null) {\n this.x = this.x.toRed(this.curve.red);\n }\n if (this.y.red === null) {\n this.y = this.y.toRed(this.curve.red);\n }\n this.inf = false;\n }\n }\n /**\n * Validates if a point belongs to the curve. Follows the short Weierstrass\n * equation for elliptic curves: y^2 = x^3 + ax + b.\n *\n * @method validate\n * @returns {boolean} true if the point is on the curve, false otherwise.\n *\n * @example\n * const aPoint = new Point(x, y);\n * const isValid = aPoint.validate();\n */\n validate() {\n return this.curve.validate(this);\n }\n /**\n * Encodes the coordinates of a point into an array or a hexadecimal string.\n * The details of encoding are determined by the optional compact and enc parameters.\n *\n * @method encode\n * @param compact - If true, an additional prefix byte 0x02 or 0x03 based on the 'y' coordinate being even or odd respectively is used. If false, byte 0x04 is used.\n * @param enc - Expects the string 'hex' if hexadecimal string encoding is required instead of an array of numbers.\n * @throws Will throw an error if the specified encoding method is not recognized. Expects 'hex'.\n * @returns If enc is undefined, a byte array representation of the point will be returned. if enc is 'hex', a hexadecimal string representation of the point will be returned.\n *\n * @example\n * const aPoint = new Point(x, y);\n * const encodedPointArray = aPoint.encode();\n * const encodedPointHex = aPoint.encode(true, 'hex');\n */\n encode(compact = true, enc) {\n if (this.inf) {\n if (enc === 'hex')\n return '00';\n return [0x00];\n }\n const len = this.curve.p.byteLength();\n const x = this.getX().toArray('be', len);\n let res;\n if (compact) {\n res = [this.getY().isEven() ? 0x02 : 0x03].concat(x);\n }\n else {\n res = [0x04].concat(x, this.getY().toArray('be', len));\n }\n if (enc !== 'hex') {\n return res;\n }\n else {\n return toHex(res);\n }\n }\n /**\n * Converts the point coordinates to a hexadecimal string. A wrapper method\n * for encode. Byte 0x02 or 0x03 is used as prefix based on the 'y' coordinate being even or odd respectively.\n *\n * @method toString\n * @returns {string} A hexadecimal string representation of the point coordinates.\n *\n * @example\n * const aPoint = new Point(x, y);\n * const stringPoint = aPoint.toString();\n */\n toString() {\n return this.encode(true, 'hex');\n }\n /**\n * Exports the x and y coordinates of the point, and the precomputed doubles and non-adjacent form (NAF) for optimization. The output is an array.\n *\n * @method toJSON\n * @returns An Array where first two elements are the coordinates of the point and optional third element is an object with doubles and NAF points.\n *\n * @example\n * const aPoint = new Point(x, y);\n * const jsonPoint = aPoint.toJSON();\n */\n toJSON() {\n if (this.precomputed == null) {\n return [this.x, this.y];\n }\n return [\n this.x,\n this.y,\n typeof this.precomputed === 'object' && this.precomputed !== null\n ? {\n doubles: this.precomputed.doubles != null\n ? {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1)\n }\n : undefined,\n naf: this.precomputed.naf != null\n ? {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1)\n }\n : undefined\n }\n : undefined\n ];\n }\n /**\n * Provides the point coordinates in a human-readable string format for debugging purposes.\n *\n * @method inspect\n * @returns String of the format '<EC Point x: x-coordinate y: y-coordinate>', or '<EC Point Infinity>' if the point is at infinity.\n *\n * @example\n * const aPoint = new Point(x, y);\n * console.log(aPoint.inspect());\n */\n inspect() {\n if (this.isInfinity()) {\n return '<EC Point Infinity>';\n }\n return ('<EC Point x: ' +\n (this.x?.fromRed()?.toString(16, 2) ?? 'undefined') +\n ' y: ' +\n (this.y?.fromRed()?.toString(16, 2) ?? 'undefined') +\n '>');\n }\n /**\n * Checks if the point is at infinity.\n * @method isInfinity\n * @returns Returns whether or not the point is at infinity.\n *\n * @example\n * const p = new Point(null, null);\n * console.log(p.isInfinity()); // outputs: true\n */\n isInfinity() {\n return this.inf;\n }\n /**\n * Adds another Point to this Point, returning a new Point.\n *\n * @method add\n * @param p - The Point to add to this one.\n * @returns A new Point that results from the addition.\n *\n * @example\n * const p1 = new Point(1, 2);\n * const p2 = new Point(2, 3);\n * const result = p1.add(p2);\n */\n add(p) {\n // O + P = P\n if (this.inf) {\n return p;\n }\n // P + O = P\n if (p.inf) {\n return this;\n }\n // P + P = 2P\n if (this.eq(p)) {\n return this.dbl();\n }\n // P + (-P) = O\n if (this.neg().eq(p)) {\n return new Point(null, null);\n }\n // P + Q = O\n if (this.x?.cmp(p.x ?? new BigNumber(0)) === 0) {\n return new Point(null, null);\n }\n const P1 = {\n X: BigInt('0x' + this.x.fromRed().toString(16)),\n Y: BigInt('0x' + this.y.fromRed().toString(16)),\n Z: BI_ONE\n };\n const Q1 = {\n X: BigInt('0x' + p.x.fromRed().toString(16)),\n Y: BigInt('0x' + p.y.fromRed().toString(16)),\n Z: BI_ONE\n };\n const R = jpAdd(P1, Q1);\n if (R.Z === BI_ZERO)\n return new Point(null, null);\n const zInv = biModInv(R.Z);\n const zInv2 = biModMul(zInv, zInv);\n const xRes = biModMul(R.X, zInv2);\n const yRes = biModMul(R.Y, biModMul(zInv2, zInv));\n return new Point(xRes.toString(16), yRes.toString(16));\n }\n /**\n * Doubles the current point.\n *\n * @method dbl\n *\n * @example\n * const P = new Point('123', '456');\n * const result = P.dbl();\n * */\n dbl() {\n if (this.inf)\n return this;\n if (this.x === null || this.y === null) {\n throw new Error('Point coordinates cannot be null');\n }\n const X = BigInt('0x' + this.x.fromRed().toString(16));\n const Y = BigInt('0x' + this.y.fromRed().toString(16));\n if (Y === BI_ZERO)\n return new Point(null, null);\n const R = jpDouble({ X, Y, Z: BI_ONE });\n const zInv = biModInv(R.Z);\n const zInv2 = biModMul(zInv, zInv);\n const xRes = biModMul(R.X, zInv2);\n const yRes = biModMul(R.Y, biModMul(zInv2, zInv));\n return new Point(xRes.toString(16), yRes.toString(16));\n }\n /**\n * Returns X coordinate of point\n *\n * @example\n * const P = new Point('123', '456');\n * const x = P.getX();\n */\n getX() {\n return (this.x ?? new BigNumber(0)).fromRed();\n }\n /**\n * Returns X coordinate of point\n *\n * @example\n * const P = new Point('123', '456');\n * const x = P.getX();\n */\n getY() {\n return (this.y ?? new BigNumber(0)).fromRed();\n }\n /**\n * Multiplies this Point by a scalar value, returning a new Point.\n *\n * @method mul\n * @param k - The scalar value to multiply this Point by.\n * @returns A new Point that results from the multiplication.\n *\n * @example\n * const p = new Point(1, 2);\n * const result = p.mul(2); // this doubles the Point\n */\n mul(k) {\n if (!BigNumber.isBN(k)) {\n k = new BigNumber(k, 16);\n }\n k = k;\n if (this.inf) {\n return this;\n }\n let kBig = BigInt('0x' + k.toString(16));\n const isNeg = kBig < BI_ZERO;\n if (isNeg)\n kBig = -kBig;\n kBig = biMod(kBig);\n if (kBig === BI_ZERO) {\n return new Point(null, null);\n }\n if (this.x === null || this.y === null) {\n throw new Error('Point coordinates cannot be null');\n }\n let Px;\n let Py;\n if (this === this.curve.g) {\n Px = GX_BIGINT;\n Py = GY_BIGINT;\n }\n else {\n Px = BigInt('0x' + this.x.fromRed().toString(16));\n Py = BigInt('0x' + this.y.fromRed().toString(16));\n }\n const R = scalarMultiplyWNAF(kBig, { x: Px, y: Py });\n if (R.Z === BI_ZERO) {\n return new Point(null, null);\n }\n const zInv = biModInv(R.Z);\n const zInv2 = biModMul(zInv, zInv);\n const xRes = biModMul(R.X, zInv2);\n const yRes = biModMul(R.Y, biModMul(zInv2, zInv));\n const xBN = new BigNumber(xRes.toString(16), 16);\n const yBN = new BigNumber(yRes.toString(16), 16);\n const result = new Point(xBN, yBN);\n if (isNeg) {\n return result.neg();\n }\n return result;\n }\n /**\n * Performs a multiplication and addition operation in a single step.\n * Multiplies this Point by k1, adds the resulting Point to the result of p2 multiplied by k2.\n *\n * @method mulAdd\n * @param k1 - The scalar value to multiply this Point by.\n * @param p2 - The other Point to be involved in the operation.\n * @param k2 - The scalar value to multiply the Point p2 by.\n * @returns A Point that results from the combined multiplication and addition operations.\n *\n * @example\n * const p1 = new Point(1, 2);\n * const p2 = new Point(2, 3);\n * const result = p1.mulAdd(2, p2, 3);\n */\n mulAdd(k1, p2, k2) {\n const points = [this, p2];\n const coeffs = [k1, k2];\n return this._endoWnafMulAdd(points, coeffs);\n }\n /**\n * Performs the Jacobian multiplication and addition operation in a single\n * step. Instead of returning a regular Point, the result is a JacobianPoint.\n *\n * @method jmulAdd\n * @param k1 - The scalar value to multiply this Point by.\n * @param p2 - The other Point to be involved in the operation\n * @param k2 - The scalar value to multiply the Point p2 by.\n * @returns A JacobianPoint that results from the combined multiplication and addition operation.\n *\n * @example\n * const p1 = new Point(1, 2);\n * const p2 = new Point(2, 3);\n * const result = p1.jmulAdd(2, p2, 3);\n */\n jmulAdd(k1, p2, k2) {\n const points = [this, p2];\n const coeffs = [k1, k2];\n return this._endoWnafMulAdd(points, coeffs, true);\n }\n /**\n * Checks if the Point instance is equal to another given Point.\n *\n * @method eq\n * @param p - The Point to be checked if equal to the current instance.\n *\n * @returns Whether the two Point instances are equal. Both the 'x' and 'y' coordinates have to match, and both points have to either be valid or at infinity for equality. If both conditions are true, it returns true, else it returns false.\n *\n * @example\n * const p1 = new Point(5, 20);\n * const p2 = new Point(5, 20);\n * const areEqual = p1.eq(p2); // returns true\n */\n eq(p) {\n return (this === p ||\n (this.inf === p.inf &&\n (this.inf || ((this.x ?? new BigNumber(0)).cmp(p.x ?? new BigNumber(0)) === 0 && (this.y ?? new BigNumber(0)).cmp(p.y ?? new BigNumber(0)) === 0))));\n }\n /**\n * Negate a point. The negation of a point P is the mirror of P about x-axis.\n *\n * @method neg\n *\n * @example\n * const P = new Point('123', '456');\n * const result = P.neg();\n */\n neg(_precompute) {\n if (this.inf) {\n return this;\n }\n const res = new Point(this.x, (this.y ?? new BigNumber(0)).redNeg());\n if (_precompute === true && this.precomputed != null) {\n const pre = this.precomputed;\n const negate = (p) => p.neg();\n res.precomputed = {\n naf: pre.naf != null\n ? {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate)\n }\n : undefined,\n doubles: pre.doubles != null\n ? {\n step: pre.doubles.step,\n points: pre.doubles.points.map((p) => p.neg())\n }\n : undefined,\n beta: undefined\n };\n }\n return res;\n }\n /**\n * Performs the \"doubling\" operation on the Point a given number of times.\n * This is used in elliptic curve operations to perform multiplication by 2, multiple times.\n * If the point is at infinity, it simply returns the point because doubling\n * a point at infinity is still infinity.\n *\n * @method dblp\n * @param k - The number of times the \"doubling\" operation is to be performed on the Point.\n * @returns The Point after 'k' \"doubling\" operations have been performed.\n *\n * @example\n * const p = new Point(5, 20);\n * const doubledPoint = p.dblp(10); // returns the point after \"doubled\" 10 times\n */\n dblp(k) {\n /* eslint-disable @typescript-eslint/no-this-alias */\n let r = this;\n for (let i = 0; i < k; i++) {\n r = r.dbl();\n }\n return r;\n }\n /**\n * Converts the point to a Jacobian point. If the point is at infinity, the corresponding Jacobian point\n * will also be at infinity.\n *\n * @method toJ\n * @returns Returns a new Jacobian point based on the current point.\n *\n * @example\n * const point = new Point(xCoordinate, yCoordinate);\n * const jacobianPoint = point.toJ();\n */\n toJ() {\n if (this.inf) {\n return new JPoint(null, null, null);\n }\n const res = new JPoint(this.x, this.y, this.curve.one);\n return res;\n }\n _getBeta() {\n if (typeof this.curve.endo !== 'object') {\n return;\n }\n const pre = this.precomputed;\n if (typeof pre === 'object' &&\n pre !== null &&\n typeof pre.beta === 'object' &&\n pre.beta !== null) {\n return pre.beta;\n }\n const beta = new Point((this.x ?? new BigNumber(0)).redMul(this.curve.endo.beta), this.y);\n if (pre != null) {\n const curve = this.curve;\n const endoMul = (p) => {\n if (p.x === null) {\n throw new Error('p.x is null');\n }\n if (curve.endo === undefined || curve.endo === null) {\n throw new Error('curve.endo is undefined');\n }\n return new Point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf != null\n ? {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul)\n }\n : undefined,\n doubles: pre.doubles != null\n ? {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul)\n }\n : undefined\n };\n }\n return beta;\n }\n _fixedNafMul(k) {\n if (typeof this.precomputed !== 'object' || this.precomputed === null) {\n throw new Error('_fixedNafMul requires precomputed values for the point');\n }\n const doubles = this._getDoubles();\n const naf = this.curve.getNAF(k, 1, this.curve._bitLength);\n let I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n // Translate into more windowed form\n const repr = [];\n for (let j = 0; j < naf.length; j += doubles.step) {\n let nafW = 0;\n for (let k = j + doubles.step - 1; k >= j; k--) {\n nafW = (nafW << 1) + naf[k];\n }\n repr.push(nafW);\n }\n let a = new JPoint(null, null, null);\n let b = new JPoint(null, null, null);\n for (let i = I; i > 0; i--) {\n for (let j = 0; j < repr.length; j++) {\n const nafW = repr[j];\n if (nafW === i) {\n b = b.mixedAdd(doubles.points[j]);\n }\n else if (nafW === -i) {\n b = b.mixedAdd(doubles.points[j].neg());\n }\n }\n a = a.add(b);\n }\n return a.toP();\n }\n _wnafMulAdd(defW, points, coeffs, len, jacobianResult) {\n const wndWidth = this.curve._wnafT1.map(num => num.toNumber()); // Convert BigNumber to number\n const wnd = this.curve._wnafT2.map(() => []); // Initialize as empty Point[][] array\n const naf = this.curve._wnafT3.map(() => []); // Initialize as empty number[][] array\n // Fill all arrays\n let max = 0;\n for (let i = 0; i < len; i++) {\n const p = points[i];\n const nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd; // Ensure correct type\n wnd[i] = nafPoints.points; // Ensure correct type\n }\n // Comb small window NAFs\n for (let i = len - 1; i >= 1; i -= 2) {\n const a = i - 1;\n const b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = this.curve.getNAF(coeffs[a], wndWidth[a], this.curve._bitLength);\n naf[b] = this.curve.getNAF(coeffs[b], wndWidth[b], this.curve._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n const comb = [\n points[a] /* 1 */,\n null /* 3 */,\n null /* 5 */,\n points[b] /* 7 */\n ];\n // Try to avoid Projective points, if possible\n if ((points[a].y ?? new BigNumber(0)).cmp(points[b].y ?? new BigNumber(0)) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n else if ((points[a].y ?? new BigNumber(0)).cmp((points[b].y ?? new BigNumber(0)).redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n }\n else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n const index = [\n -3 /* -1 -1 */, -1 /* -1 0 */, -5 /* -1 1 */, -7 /* 0 -1 */,\n 0 /* 0 0 */, 7 /* 0 1 */, 5 /* 1 -1 */, 1 /* 1 0 */, 3 /* 1 1 */\n ];\n const jsf = this.curve.getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (let j = 0; j < max; j++) {\n const ja = jsf[0][j] | 0;\n const jb = jsf[1][j] | 0;\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n let acc = new JPoint(null, null, null);\n const tmp = this.curve._wnafT4;\n for (let i = max; i >= 0; i--) {\n let k = 0;\n while (i >= 0) {\n let zero = true;\n for (let j = 0; j < len; j++) {\n tmp[j] = new BigNumber(typeof naf[j][i] === 'number' ? naf[j][i] : 0); // Ensure type consistency\n if (!tmp[j].isZero()) { // Use BigNumber's built-in comparison\n zero = false;\n }\n }\n if (!zero) {\n break;\n }\n k++;\n i--;\n }\n if (i >= 0) {\n k++;\n }\n acc = acc.dblp(k);\n if (i < 0) {\n break;\n }\n const one = new BigNumber(1);\n const two = new BigNumber(2);\n for (let j = 0; j < len; j++) {\n const z = tmp[j];\n let p;\n if (z.cmpn(0) === 0) { // Check if z is 0\n continue;\n }\n else if (!z.isNeg()) { // If z is positive\n p = wnd[j][z.sub(one).div(two).toNumber()];\n }\n else { // If z is negative\n p = wnd[j][z.neg().sub(one).div(two).toNumber()].neg();\n }\n if (p.type === 'affine') {\n acc = acc.mixedAdd(p);\n }\n else {\n acc = acc.add(p);\n }\n }\n }\n // Zeroify references\n for (let i = 0; i < len; i++) {\n wnd[i] = [];\n }\n if (jacobianResult === true) {\n return acc;\n }\n else {\n return acc.toP();\n }\n }\n _endoWnafMulAdd(points, coeffs, // Explicitly type coeffs\n jacobianResult) {\n const npoints = new Array(points.length * 2);\n const ncoeffs = new Array(points.length * 2);\n let i;\n for (i = 0; i < points.length; i++) {\n const split = this.curve._endoSplit(coeffs[i]);\n let p = points[i];\n let beta = p._getBeta() ?? new Point(null, null);\n if (split.k1.negative !== 0) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative !== 0) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n const res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n // Clean-up references to points and coefficients\n for (let j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n }\n _hasDoubles(k) {\n if (this.precomputed == null) {\n return false;\n }\n const doubles = this.precomputed.doubles;\n if (typeof doubles !== 'object') {\n return false;\n }\n return (doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step));\n }\n _getDoubles(step, power) {\n if (typeof this.precomputed === 'object' &&\n this.precomputed !== null &&\n typeof this.precomputed.doubles === 'object' &&\n this.precomputed.doubles !== null) {\n return this.precomputed.doubles;\n }\n const doubles = [this];\n /* eslint-disable @typescript-eslint/no-this-alias */\n let acc = this;\n for (let i = 0; i < (power ?? 0); i += (step ?? 1)) {\n for (let j = 0; j < (step ?? 1); j++) {\n acc = acc.dbl();\n }\n doubles.push(acc);\n }\n return {\n step: step ?? 1,\n points: doubles\n };\n }\n _getNAFPoints(wnd) {\n if (typeof this.precomputed === 'object' &&\n this.precomputed !== null &&\n typeof this.precomputed.naf === 'object' &&\n this.precomputed.naf !== null) {\n return this.precomputed.naf;\n }\n const res = [this];\n const max = (1 << wnd) - 1;\n const dbl = max === 1 ? null : this.dbl();\n for (let i = 1; i < max; i++) {\n if (dbl !== null) {\n res[i] = res[i - 1].add(dbl);\n }\n }\n return {\n wnd,\n points: res\n };\n }\n}\n//# sourceMappingURL=Point.js.map","import BigNumber from './BigNumber.js';\nimport PublicKey from './PublicKey.js';\nimport { verify } from './ECDSA.js';\nimport { sha256 } from './Hash.js';\nimport { toArray, toHex, toBase64 } from './utils.js';\nimport Point from './Point.js';\nimport Curve from './Curve.js';\n/**\n * Represents a digital signature.\n *\n * A digital signature is a mathematical scheme for verifying the authenticity of\n * digital messages or documents. In many scenarios, it is equivalent to a handwritten signature or stamped seal.\n * The signature pair (R, S) corresponds to the raw ECDSA ([Elliptic Curve Digital Signature Algorithm](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm)) signature.\n * Signatures are often serialized into a format known as '[DER encoding](https://en.wikipedia.org/wiki/X.690#DER_encoding)' for transmission.\n *\n * @class Signature\n */\nexport default class Signature {\n /**\n * @property Represents the \"r\" component of the digital signature\n */\n r;\n /**\n * @property Represents the \"s\" component of the digital signature\n */\n s;\n /**\n * Takes an array of numbers or a string and returns a new Signature instance.\n * This method will throw an error if the DER encoding is invalid.\n * If a string is provided, it is assumed to represent a hexadecimal sequence.\n *\n * @static\n * @method fromDER\n * @param data - The sequence to decode from DER encoding.\n * @param enc - The encoding of the data string.\n * @returns The decoded data in the form of Signature instance.\n *\n * @example\n * const signature = Signature.fromDER('30440220018c1f5502f8...', 'hex');\n */\n static fromDER(data, enc) {\n const getLength = (buf, p) => {\n const initial = buf[p.place++];\n if ((initial & 0x80) === 0) {\n return initial;\n }\n else {\n throw new Error('Invalid DER entity length');\n }\n };\n class Position {\n place;\n constructor() {\n this.place = 0;\n }\n }\n data = toArray(data, enc);\n const p = new Position();\n if (data[p.place++] !== 0x30) {\n throw new Error('Signature DER must start with 0x30');\n }\n const len = getLength(data, p);\n if (len + p.place !== data.length) {\n throw new Error('Signature DER invalid');\n }\n if (data[p.place++] !== 0x02) {\n throw new Error('Signature DER invalid');\n }\n const rlen = getLength(data, p);\n let r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n throw new Error('Signature DER invalid');\n }\n const slen = getLength(data, p);\n if (data.length !== slen + p.place) {\n throw new Error('Invalid R-length in signature DER');\n }\n let s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if ((r[1] & 0x80) !== 0) {\n r = r.slice(1);\n }\n else {\n throw new Error('Invalid R-value in signature DER');\n }\n }\n if (s[0] === 0) {\n if ((s[1] & 0x80) !== 0) {\n s = s.slice(1);\n }\n else {\n throw new Error('Invalid S-value in signature DER');\n }\n }\n return new Signature(new BigNumber(r), new BigNumber(s));\n }\n /**\n * Takes an array of numbers or a string and returns a new Signature instance.\n * This method will throw an error if the Compact encoding is invalid.\n * If a string is provided, it is assumed to represent a hexadecimal sequence.\n * compactByte value 27-30 means uncompressed public key.\n * 31-34 means compressed public key.\n * The range represents the recovery param which can be 0,1,2,3.\n * We could support recovery functions in future if there's demand.\n *\n * @static\n * @method fromCompact\n * @param data - The sequence to decode from Compact encoding.\n * @param enc - The encoding of the data string.\n * @returns The decoded data in the form of Signature instance.\n *\n * @example\n * const signature = Signature.fromCompact('1b18c1f5502f8...', 'hex');\n */\n static fromCompact(data, enc) {\n data = toArray(data, enc);\n if (data.length !== 65) {\n throw new Error('Invalid Compact Signature');\n }\n const compactByte = data[0];\n if (compactByte < 27 || compactByte >= 35) {\n throw new Error('Invalid Compact Byte');\n }\n return new Signature(new BigNumber(data.slice(1, 33)), new BigNumber(data.slice(33, 65)));\n }\n /**\n * Creates an instance of the Signature class.\n *\n * @constructor\n * @param r - The R component of the signature.\n * @param s - The S component of the signature.\n *\n * @example\n * const r = new BigNumber('208755674028...');\n * const s = new BigNumber('564745627577...');\n * const signature = new Signature(r, s);\n */\n constructor(r, s) {\n this.r = r;\n this.s = s;\n }\n /**\n * Verifies a digital signature.\n *\n * This method will return true if the signature, key, and message hash match.\n * If the data or key do not match the signature, the function returns false.\n *\n * @method verify\n * @param msg - The message to verify.\n * @param key - The public key used to sign the original message.\n * @param enc - The encoding of the msg string.\n * @returns A boolean representing whether the signature is valid.\n *\n * @example\n * const msg = 'The quick brown fox jumps over the lazy dog';\n * const publicKey = PublicKey.fromString('04188ca1050...');\n * const isVerified = signature.verify(msg, publicKey);\n */\n verify(msg, key, enc) {\n const msgHash = new BigNumber(sha256(msg, enc), 16);\n return verify(msgHash, this, key);\n }\n /**\n * Converts an instance of Signature into DER encoding.\n * An alias for the toDER method.\n *\n * If the encoding parameter is set to 'hex', the function will return a hex string.\n * If 'base64', it will return a base64 string.\n * Otherwise, it will return an array of numbers.\n *\n * @method toDER\n * @param enc - The encoding to use for the output.\n * @returns The current instance in DER encoding.\n *\n * @example\n * const der = signature.toString('base64');\n */\n toString(enc) {\n return this.toDER(enc);\n }\n /**\n * Converts an instance of Signature into DER encoding.\n *\n * If the encoding parameter is set to 'hex', the function will return a hex string.\n * If 'base64', it will return a base64 string.\n * Otherwise, it will return an array of numbers.\n *\n * @method toDER\n * @param enc - The encoding to use for the output.\n * @returns The current instance in DER encoding.\n *\n * @example\n * const der = signature.toDER('hex');\n */\n toDER(enc) {\n const constructLength = (arr, len) => {\n if (len < 0x80) {\n arr.push(len);\n }\n else {\n throw new Error('len must be < 0x80');\n }\n };\n const rmPadding = (buf) => {\n let i = 0;\n const len = buf.length - 1;\n while (buf[i] === 0 && (buf[i + 1] & 0x80) === 0 && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n };\n let r = this.r.toArray();\n let s = this.s.toArray();\n // Pad values\n if ((r[0] & 0x80) !== 0) {\n r = [0].concat(r);\n }\n // Pad values\n if ((s[0] & 0x80) !== 0) {\n s = [0].concat(s);\n }\n r = rmPadding(r);\n s = rmPadding(s);\n while (s[0] === 0 && (s[1] & 0x80) === 0) {\n s = s.slice(1);\n }\n let arr = [0x02];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n const backHalf = arr.concat(s);\n let res = [0x30];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n if (enc === 'hex') {\n return toHex(res);\n }\n else if (enc === 'base64') {\n return toBase64(res);\n }\n else {\n return res;\n }\n }\n /**\n * Converts an instance of Signature into Compact encoding.\n *\n * If the encoding parameter is set to 'hex', the function will return a hex string.\n * If 'base64', it will return a base64 string.\n * Otherwise, it will return an array of numbers.\n *\n * @method toCompact\n * @param enc - The encoding to use for the output.\n * @returns The current instance in DER encoding.\n *\n * @example\n * const compact = signature.toCompact(3, true, 'base64');\n */\n toCompact(recovery, compressed, enc) {\n if (recovery < 0 || recovery > 3)\n throw new Error('Invalid recovery param');\n if (typeof compressed !== 'boolean') {\n throw new Error('Invalid compressed param');\n }\n let compactByte = 27 + recovery;\n if (compressed) {\n compactByte += 4;\n }\n let arr = [compactByte];\n arr = arr.concat(this.r.toArray('be', 32));\n arr = arr.concat(this.s.toArray('be', 32));\n if (enc === 'hex') {\n return toHex(arr);\n }\n else if (enc === 'base64') {\n return toBase64(arr);\n }\n else {\n return arr;\n }\n }\n /**\n * Recovers the public key from a signature.\n * This method will return the public key if it finds a valid public key.\n * If it does not find a valid public key, it will throw an error.\n * The recovery factor is a number between 0 and 3.\n * @method RecoverPublicKey\n * @param recovery - The recovery factor.\n * @param e - The message hash.\n * @returns The public key associated with the signature.\n *\n * @example\n * const publicKey = signature.RecoverPublicKey(0, msgHash);\n */\n RecoverPublicKey(recovery, e) {\n const r = this.r;\n const s = this.s;\n // A set LSB signifies that the y-coordinate is odd\n const isYOdd = (recovery & 1) !== 0;\n // The more significant bit specifies whether we should use the\n // first or second candidate key.\n const isSecondKey = recovery >> 1;\n const curve = new Curve();\n const n = curve.n;\n const G = curve.g;\n // 1.1 LEt x = r + jn\n const x = isSecondKey !== 0 ? r.add(n) : r;\n const R = Point.fromX(x, isYOdd);\n // 1.4 Check that nR is at infinity\n const nR = R.mul(n);\n if (!nR.isInfinity()) {\n throw new Error('nR is not at infinity');\n }\n // Compute -e from e\n const eNeg = e.neg().umod(n);\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n const rInv = r.invm(n);\n // const Q = R.multiplyTwo(s, G, eNeg).mul(rInv)\n const srInv = rInv.mul(s).umod(n);\n const eInvrInv = rInv.mul(eNeg).umod(n);\n const Q = G.mul(eInvrInv).add(R.mul(srInv));\n const pubKey = new PublicKey(Q);\n pubKey.validate();\n return pubKey;\n }\n /**\n * Calculates the recovery factor which will work for a particular public key and message hash.\n * This method will return the recovery factor if it finds a valid recovery factor.\n * If it does not find a valid recovery factor, it will throw an error.\n * The recovery factor is a number between 0 and 3.\n *\n * @method CalculateRecoveryFactor\n * @param msgHash - The message hash.\n * @returns the recovery factor: number\n * /\n * @example\n * const recovery = signature.CalculateRecoveryFactor(publicKey, msgHash);\n */\n CalculateRecoveryFactor(pubkey, msgHash) {\n for (let recovery = 0; recovery < 4; recovery++) {\n let Qprime;\n try {\n Qprime = this.RecoverPublicKey(recovery, msgHash);\n }\n catch {\n continue;\n }\n if (pubkey.eq(Qprime)) {\n return recovery;\n }\n }\n throw new Error('Unable to find valid recovery factor');\n }\n}\n//# sourceMappingURL=Signature.js.map","import { SHA256HMAC } from './Hash.js';\nimport { toHex, toArray } from './utils.js';\n/**\n * HMAC-DRBG used **only** for deterministic ECDSA nonce generation.\n *\n * This implementation follows the RFC 6979-style HMAC-DRBG construction for secp256k1\n * and is wired internally into the ECDSA signing code. It is **not forward-secure**\n * and MUST NOT be used as a general-purpose DRBG, key generator, or randomness source.\n *\n * Security note:\n * - Intended scope: internal ECDSA nonce generation with fixed-size inputs.\n * - Out-of-scope: generic randomness, long-lived session keys, or any context\n * where forward secrecy is required.\n * - API stability: this class is internal.\n *\n * @class DRBG\n *\n * @constructor\n * @param entropy - Initial entropy either in number array or hexadecimal string.\n * @param nonce - Initial nonce either in number array or hexadecimal string.\n *\n * @throws Throws an error message 'Not enough entropy. Minimum is 256 bits' when entropy's length is less than 32.\n * @throws Thrown an error message 'Nonce must be exactly 32 bytes (256 bits)' when nonce's length is less than 32.\n *\n * @example\n * const drbg = new DRBG('af12de...', '123ef...');\n */\nexport default class DRBG {\n K;\n V;\n constructor(entropy, nonce) {\n const entropyBytes = toArray(entropy, 'hex');\n const nonceBytes = toArray(nonce, 'hex');\n // RFC 6979 for secp256k1 assumes 256-bit x and h1.\n if (entropyBytes.length !== 32) {\n throw new Error('Entropy must be exactly 32 bytes (256 bits)');\n }\n if (nonceBytes.length !== 32) {\n throw new Error('Nonce must be exactly 32 bytes (256 bits)');\n }\n const seedMaterial = entropyBytes.concat(nonceBytes);\n this.K = new Array(32);\n this.V = new Array(32);\n for (let i = 0; i < 32; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n this.update(seedMaterial);\n }\n /**\n * Generates HMAC using the K value of the instance. This method is used internally for operations.\n *\n * @method hmac\n * @returns The SHA256HMAC object created with K value.\n *\n * @example\n * const hmac = drbg.hmac();\n */\n hmac() {\n return new SHA256HMAC(this.K);\n }\n /**\n * Updates the `K` and `V` values of the instance based on the seed.\n * The seed if not provided uses `V` as seed.\n *\n * @method update\n * @param seed - an optional value that used to update `K` and `V`. Default is `undefined`.\n * @returns Nothing, but updates the internal state `K` and `V` value.\n *\n * @example\n * drbg.update('e13af...');\n */\n update(seed) {\n let kmac = this.hmac().update(this.V).update([0x00]);\n if (seed !== undefined) {\n kmac = kmac.update(seed);\n }\n this.K = kmac.digest();\n this.V = this.hmac().update(this.V).digest();\n if (seed === undefined) {\n return;\n }\n this.K = this.hmac().update(this.V).update([0x01]).update(seed).digest();\n this.V = this.hmac().update(this.V).digest();\n }\n /**\n * Generates deterministic random hexadecimal string of given length.\n * In every generation process, it also updates the internal state `K` and `V`.\n *\n * @method generate\n * @param len - The length of required random number.\n * @returns The required deterministic random hexadecimal string.\n *\n * @example\n * const randomHex = drbg.generate(256);\n */\n generate(len) {\n let temp = [];\n while (temp.length < len) {\n this.V = this.hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n const res = temp.slice(0, len);\n this.update();\n return toHex(res);\n }\n}\n//# sourceMappingURL=DRBG.js.map","import BigNumber from './BigNumber.js';\nimport Signature from './Signature.js';\nimport Curve from './Curve.js';\nimport { scalarMultiplyWNAF, biModInv, BI_ZERO, biModMul, GX_BIGINT, GY_BIGINT, jpAdd, N_BIGINT, modInvN, modMulN, modN } from './Point.js';\nimport DRBG from './DRBG.js';\n/**\n * Truncates a BigNumber message to the length of the curve order n, in the context of the Elliptic Curve Digital Signature Algorithm (ECDSA).\n * This method is used as part of ECDSA signing and verification.\n *\n * The method calculates `delta`, which is a difference obtained by subtracting the bit length of the curve order `n` from the byte length of the message in bits.\n * If `delta` is greater than zero, logical shifts msg to the right by `delta`, retaining the sign.\n *\n * Another condition is tested, but only if `truncOnly` is false. This condition compares the value of msg to curve order `n`.\n * If msg is greater or equal to `n`, it is decreased by `n` and returned.\n *\n * @method truncateToN\n * @param msg - The BigNumber message to be truncated.\n * @param truncOnly - An optional boolean parameter that if set to true, the method will only perform truncation of the BigNumber without doing the additional subtraction from the curve order.\n * @returns Returns the truncated BigNumber value, potentially subtracted by the curve order n.\n *\n * @example\n * let msg = new BigNumber('1234567890abcdef', 16);\n * let truncatedMsg = truncateToN(msg);\n */\nfunction truncateToN(msg, truncOnly, curve = new Curve()) {\n const delta = msg.byteLength() * 8 - curve.n.bitLength();\n if (delta > 0) {\n msg.iushrn(delta);\n }\n if (truncOnly === null && msg.cmp(curve.n) >= 0) {\n return msg.sub(curve.n);\n }\n else {\n return msg;\n }\n}\nconst curve = new Curve();\nconst bytes = curve.n.byteLength();\nconst ns1 = curve.n.subn(1);\nconst halfN = N_BIGINT >> 1n;\n/**\n * Generates a digital signature for a given message.\n *\n * @function sign\n * @param msg - The BigNumber message for which the signature has to be computed.\n * @param key - Private key in BigNumber.\n * @param forceLowS - Optional boolean flag if True forces \"s\" to be the lower of two possible values.\n * @param customK - Optional specification for k value, which can be a function or BigNumber.\n * @returns Returns the elliptic curve digital signature of the message.\n *\n * @example\n * const msg = new BigNumber('2664878')\n * const key = new BigNumber('123456')\n * const signature = sign(msg, key)\n */\nexport const sign = (msg, key, forceLowS = false, customK) => {\n // —— prepare inputs ────────────────────────────────────────────────────────\n msg = truncateToN(msg);\n const msgBig = BigInt('0x' + msg.toString(16));\n const keyBig = BigInt('0x' + key.toString(16));\n // DRBG seeding identical to previous implementation\n const bkey = key.toArray('be', bytes);\n const nonce = msg.toArray('be', bytes);\n const drbg = new DRBG(bkey, nonce);\n for (let iter = 0;; iter++) {\n // —— k generation & basic validity checks ───────────────────────────────\n let kBN = typeof customK === 'function'\n ? customK(iter)\n : BigNumber.isBN(customK)\n ? customK\n : new BigNumber(drbg.generate(bytes), 16);\n if (kBN == null)\n throw new Error('k is undefined');\n kBN = truncateToN(kBN, true);\n if (kBN.cmpn(1) < 0 || kBN.cmp(ns1) > 0) {\n if (BigNumber.isBN(customK)) {\n throw new Error('Invalid fixed custom K value (must be >1 and <N‑1)');\n }\n continue;\n }\n const kBig = BigInt('0x' + kBN.toString(16));\n // —— R = k·G (Jacobian, window‑NAF) ──────────────────────────────────────\n const R = scalarMultiplyWNAF(kBig, { x: GX_BIGINT, y: GY_BIGINT });\n if (R.Z === 0n) { // point at infinity – should never happen for valid k\n if (BigNumber.isBN(customK)) {\n throw new Error('Invalid fixed custom K value (k·G at infinity)');\n }\n continue;\n }\n // affine X coordinate of R\n const zInv = biModInv(R.Z);\n const zInv2 = biModMul(zInv, zInv);\n const xAff = biModMul(R.X, zInv2);\n const rBig = modN(xAff);\n if (rBig === 0n) {\n if (BigNumber.isBN(customK)) {\n throw new Error('Invalid fixed custom K value (r == 0)');\n }\n continue;\n }\n // —— s = k⁻¹ · (msg + r·key) mod n ─────────────────────────────────────\n const kInv = modInvN(kBig);\n const rTimesKey = modMulN(rBig, keyBig);\n const sum = modN(msgBig + rTimesKey);\n let sBig = modMulN(kInv, sum);\n if (sBig === 0n) {\n if (BigNumber.isBN(customK)) {\n throw new Error('Invalid fixed custom K value (s == 0)');\n }\n continue;\n }\n // low‑S mitigation (BIP‑62/BIP‑340 style)\n if (forceLowS && sBig > halfN) {\n sBig = N_BIGINT - sBig;\n }\n // —— convert back to BigNumber & return ─────────────────────────────────\n const r = new BigNumber(rBig.toString(16), 16);\n const s = new BigNumber(sBig.toString(16), 16);\n return new Signature(r, s);\n }\n};\n/**\n * Verifies a digital signature of a given message.\n *\n * Message and key used during the signature generation process, and the previously computed signature\n * are used to validate the authenticity of the digital signature.\n *\n * @function verify\n * @param msg - The BigNumber message for which the signature has to be verified.\n * @param sig - Signature object consisting of parameters 'r' and 's'.\n * @param key - Public key in Point.\n * @returns Returns true if the signature is valid and false otherwise.\n *\n * @example\n * const msg = new BigNumber('2664878', 16)\n * const key = new Point(new BigNumber(10), new BigNumber(20)\n * const signature = sign(msg, new BigNumber('123456'))\n * const isVerified = verify(msg, sig, key)\n */\nexport const verify = (msg, sig, key) => {\n // Convert inputs to BigInt\n const hash = BigInt('0x' + msg.toString(16));\n if ((key.x == null) || (key.y == null)) {\n throw new Error('Invalid public key: missing coordinates.');\n }\n const publicKey = {\n x: BigInt('0x' + key.x.toString(16)),\n y: BigInt('0x' + key.y.toString(16))\n };\n const signature = {\n r: BigInt('0x' + sig.r.toString(16)),\n s: BigInt('0x' + sig.s.toString(16))\n };\n const { r, s } = signature;\n const z = hash;\n // Check r and s are in [1, n - 1]\n if (r <= BI_ZERO || r >= N_BIGINT || s <= BI_ZERO || s >= N_BIGINT) {\n return false;\n }\n // ── compute u₁ = z·s⁻¹ mod n and u₂ = r·s⁻¹ mod n ───────────────────────\n const w = modInvN(s); // s⁻¹ mod n\n if (w === 0n)\n return false; // should never happen\n const u1 = modMulN(z, w);\n const u2 = modMulN(r, w);\n // ── R = u₁·G + u₂·Q (Jacobian, window‑NAF) ──────────────────────────────\n const RG = scalarMultiplyWNAF(u1, { x: GX_BIGINT, y: GY_BIGINT });\n const RQ = scalarMultiplyWNAF(u2, publicKey);\n const R = jpAdd(RG, RQ);\n if (R.Z === 0n)\n return false; // point at infinity\n // ── affine x‑coordinate of R (mod p) ─────────────────────────────────────\n const zInv = biModInv(R.Z); // (Z⁻¹ mod p)\n const zInv2 = biModMul(zInv, zInv); // Z⁻²\n const xAff = biModMul(R.X, zInv2); // X / Z² mod p\n // ── v = xAff mod n and final check ───────────────────────────────────────\n const v = modN(xAff);\n return v === r;\n};\n//# sourceMappingURL=ECDSA.js.map","import Point from './Point.js';\nimport Curve from './Curve.js';\nimport { verify } from './ECDSA.js';\nimport BigNumber from './BigNumber.js';\nimport { sha256, sha256hmac, hash160 } from './Hash.js';\nimport Signature from './Signature.js';\nimport { toArray, toBase58Check, toHex } from './utils.js';\n/**\n * The PublicKey class extends the Point class. It is used in public-key cryptography to derive shared secret, verify message signatures, and encode the public key in the DER format.\n * The class comes with static methods to generate PublicKey instances from private keys or from strings.\n *\n * @extends {Point}\n * @see {@link Point} for more information on Point.\n */\nexport default class PublicKey extends Point {\n /**\n * Static factory method to derive a public key from a private key.\n * It multiplies the generator point 'g' on the elliptic curve by the private key.\n *\n * @static\n * @method fromPrivateKey\n *\n * @param key - The private key from which to derive the public key.\n *\n * @returns Returns the PublicKey derived from the given PrivateKey.\n *\n * @example\n * const myPrivKey = new PrivateKey(...)\n * const myPubKey = PublicKey.fromPrivateKey(myPrivKey)\n */\n static fromPrivateKey(key) {\n const c = new Curve();\n const p = c.g.mul(key);\n return new PublicKey(p.x, p.y);\n }\n /**\n * Static factory method to create a PublicKey instance from a string.\n *\n * @param str - A string representing a public key.\n *\n * @returns Returns the PublicKey created from the string.\n *\n * @example\n * const myPubKey = PublicKey.fromString(\"03....\")\n */\n static fromString(str) {\n const p = Point.fromString(str);\n return new PublicKey(p.x, p.y);\n }\n /**\n * Static factory method to create a PublicKey instance from a number array.\n *\n * @param bytes - A number array representing a public key.\n *\n * @returns Returns the PublicKey created from the number array.\n *\n * @example\n * const myPubKey = PublicKey.fromString(\"03....\")\n */\n static fromDER(bytes) {\n const p = Point.fromDER(bytes);\n return new PublicKey(p.x, p.y);\n }\n /**\n * @constructor\n * @param x - A point or the x-coordinate of the point. May be a number, a BigNumber, a string (which will be interpreted as hex), a number array, or null. If null, an \"Infinity\" point is constructed.\n * @param y - If x is not a point, the y-coordinate of the point, similar to x.\n * @param isRed - A boolean indicating if the point is a member of the field of integers modulo the k256 prime. Default is true.\n *\n * @example\n * new PublicKey(point1);\n * new PublicKey('abc123', 'def456');\n */\n constructor(x, y = null, isRed = true) {\n if (x instanceof Point) {\n super(x.getX(), x.getY());\n }\n else {\n // Common gotcha: constructing PublicKey with a DER value when you should use .fromString()\n if (y === null && isRed && typeof x === 'string') {\n if (x.length === 66 || x.length === 130) {\n throw new Error('You are using the \"new PublicKey()\" constructor with a DER hex string. You need to use \"PublicKey.fromString()\" instead.');\n }\n }\n super(x, y, isRed);\n }\n }\n /**\n * Derive a shared secret from a public key and a private key for use in symmetric encryption.\n * This method multiplies the public key (an instance of Point) with a private key.\n *\n * @param priv - The private key to use in deriving the shared secret.\n *\n * @returns Returns the Point representing the shared secret.\n *\n * @throws Will throw an error if the public key is not valid for ECDH secret derivation.\n *\n * @example\n * const myPrivKey = new PrivateKey(...)\n * const sharedSecret = myPubKey.deriveSharedSecret(myPrivKey)\n */\n deriveSharedSecret(priv) {\n if (!this.validate()) {\n throw new Error('Public key not valid for ECDH secret derivation');\n }\n return this.mul(priv);\n }\n /**\n * Verify a signature of a message using this public key.\n *\n * @param msg - The message to verify. It can be a string or an array of numbers.\n * @param sig - The Signature of the message that needs verification.\n * @param enc - The encoding of the message. It defaults to 'utf8'.\n *\n * @returns Returns true if the signature is verified successfully, otherwise false.\n *\n * @example\n * const myMessage = \"Hello, world!\"\n * const mySignature = new Signature(...)\n * const isVerified = myPubKey.verify(myMessage, mySignature)\n */\n verify(msg, sig, enc) {\n const msgHash = new BigNumber(sha256(msg, enc), 16);\n return verify(msgHash, sig, this);\n }\n /**\n * Encode the public key to DER (Distinguished Encoding Rules) format.\n *\n * @returns Returns the DER-encoded public key in number array or string.\n *\n * @param enc - The encoding of the DER string. undefined = number array, 'hex' = hex string.\n *\n * @example\n * const derPublicKey = myPubKey.toDER()\n */\n toDER(enc) {\n if (enc === 'hex')\n return this.encode(true, enc);\n return this.encode(true);\n }\n /**\n * Hash sha256 and ripemd160 of the public key.\n *\n * @returns Returns the hash of the public key.\n *\n * @example\n * const publicKeyHash = pubkey.toHash()\n */\n toHash(enc) {\n const pkh = hash160(this.encode(true));\n if (enc === 'hex') {\n return toHex(pkh);\n }\n return pkh;\n }\n /**\n * Base58Check encodes the hash of the public key with a prefix to indicate locking script type.\n * Defaults to P2PKH for mainnet, otherwise known as a \"Bitcoin Address\".\n *\n * @param prefix defaults to [0x00] for mainnet, set to [0x6f] for testnet or use the strings 'mainnet' or 'testnet'\n *\n * @returns Returns the address encoding associated with the hash of the public key.\n *\n * @example\n * const address = pubkey.toAddress()\n * const address = pubkey.toAddress('mainnet')\n * const testnetAddress = pubkey.toAddress([0x6f])\n * const testnetAddress = pubkey.toAddress('testnet')\n */\n toAddress(prefix = [0x00]) {\n if (typeof prefix === 'string') {\n if (prefix === 'testnet' || prefix === 'test') {\n prefix = [0x6f];\n }\n else if (prefix === 'mainnet' || prefix === 'main') {\n prefix = [0x00];\n }\n else {\n throw new Error(`Invalid prefix ${prefix}`);\n }\n }\n return toBase58Check(this.toHash(), prefix);\n }\n /**\n * Derives a child key with BRC-42.\n * @param privateKey The private key of the other party\n * @param invoiceNumber The invoice number used to derive the child key\n * @param cacheSharedSecret Optional function to cache shared secrets\n * @param retrieveCachedSharedSecret Optional function to retrieve shared secrets from the cache\n * @returns The derived child key.\n */\n deriveChild(privateKey, invoiceNumber, cacheSharedSecret, retrieveCachedSharedSecret) {\n let sharedSecret;\n if (typeof retrieveCachedSharedSecret === 'function') {\n const retrieved = retrieveCachedSharedSecret(privateKey, this);\n if (typeof retrieved !== 'undefined') {\n sharedSecret = retrieved;\n }\n else {\n sharedSecret = this.deriveSharedSecret(privateKey);\n if (typeof cacheSharedSecret === 'function') {\n cacheSharedSecret(privateKey, this, sharedSecret);\n }\n }\n }\n else {\n sharedSecret = this.deriveSharedSecret(privateKey);\n }\n const invoiceNumberBin = toArray(invoiceNumber, 'utf8');\n const hmac = sha256hmac(sharedSecret.encode(true), invoiceNumberBin);\n const curve = new Curve();\n const point = curve.g.mul(new BigNumber(hmac));\n const finalPoint = this.add(point);\n return new PublicKey(finalPoint.x, finalPoint.y);\n }\n /**\n * Takes an array of numbers or a string and returns a new PublicKey instance.\n * This method will throw an error if the Compact encoding is invalid.\n * If a string is provided, it is assumed to represent a hexadecimal sequence.\n * compactByte value 27-30 means uncompressed public key.\n * 31-34 means compressed public key.\n * The range represents the recovery param which can be 0,1,2,3.\n *\n * @static\n * @method fromMsgHashAndCompactSignature\n * @param msgHash - The message hash which was signed.\n * @param signature - The signature in compact format.\n * @param enc - The encoding of the signature string.\n * @returns A PublicKey instance derived from the message hash and compact signature.\n * @example\n * const publicKey = Signature.fromMsgHashAndCompactSignature(msgHash, 'IMOl2mVKfDgsSsHT4uIYBNN4e...', 'base64');\n */\n static fromMsgHashAndCompactSignature(msgHash, signature, enc) {\n const data = toArray(signature, enc);\n if (data.length !== 65) {\n throw new Error('Invalid Compact Signature');\n }\n const compactByte = data[0];\n if (compactByte < 27 || compactByte >= 35) {\n throw new Error('Invalid Compact Byte');\n }\n let r = data[0] - 27;\n // NOTE: We don't use uncompressed pubkeys in this library,\n // but whether the key is compressed is captured in the recovery param.\n // Code below is commented out for reference of how you could capture this.\n // let compressed = false\n if (r > 3) {\n // compressed = true\n r -= 4;\n }\n const s = new Signature(new BigNumber(data.slice(1, 33)), new BigNumber(data.slice(33, 65)));\n return s.RecoverPublicKey(r, msgHash);\n }\n}\n//# sourceMappingURL=PublicKey.js.map","/**\n * Random number generator that works across modern JavaScript environments.\n *\n * This implementation uses the Web Crypto API which is available in:\n * - Node.js 6+ via require('crypto').randomBytes()\n * - Node.js 18+ via globalThis.crypto\n * - Modern browsers via globalThis.crypto, self.crypto, or window.crypto\n * - Web Workers and Service Workers via self.crypto\n * - Deno and Bun via globalThis.crypto\n *\n * @throws {Error} If no secure random number generator is available\n */\nclass Rand {\n _rand; // ✅ Explicit function type\n getRandomValues(obj, n) {\n const arr = new Uint8Array(n);\n obj.crypto.getRandomValues(arr);\n return Array.from(arr);\n }\n constructor() {\n const noRand = () => {\n throw new Error('No secure random number generator is available in this environment.');\n };\n this._rand = noRand; // Assign the function\n // Try globalThis.crypto (works in Node.js 18+, modern browsers, and Deno)\n if (typeof globalThis !== 'undefined' && typeof globalThis.crypto?.getRandomValues === 'function') {\n this._rand = (n) => {\n /* eslint-disable-next-line */\n return this.getRandomValues(globalThis, n);\n };\n return;\n }\n // Node.js fallback for versions < 18\n if (typeof process !== 'undefined' && process.release?.name === 'node') {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const crypto = require('crypto');\n if (typeof crypto.randomBytes === 'function') {\n this._rand = (n) => {\n return Array.from(crypto.randomBytes(n));\n };\n return;\n }\n }\n catch (e) {\n // crypto module not available, continue to other checks\n }\n }\n // Try self.crypto (Web Workers and Service Workers)\n if (typeof self !== 'undefined' && typeof self.crypto?.getRandomValues === 'function') {\n this._rand = (n) => {\n /* eslint-disable-next-line */\n return this.getRandomValues(self, n);\n };\n return;\n }\n // Try window.crypto (browsers)\n if (typeof window !== 'undefined' && typeof window.crypto?.getRandomValues === 'function') {\n this._rand = (n) => {\n /* eslint-disable-next-line */\n return this.getRandomValues(window, n);\n };\n return;\n }\n // No crypto available\n this._rand = noRand;\n }\n generate(len) {\n return this._rand(len);\n }\n}\nlet ayn = null;\n/**\n * Generates a sequence of pseudo-random bytes with the given length.\n *\n * @param len - The number of bytes to generate\n *\n * @returns The generated bytes\n *\n * @example\n * import Random from '@bsv/sdk/primitives/Random'\n * const bytes = Random(32) // Produces 32 random bytes\n */\nexport default (len) => {\n if (ayn == null) {\n ayn = new Rand();\n }\n return ayn.generate(len);\n};\n//# sourceMappingURL=Random.js.map","import BigNumber from './BigNumber.js';\nimport Curve from './Curve.js';\nimport Random from './Random.js';\nimport { fromBase58, toBase58 } from './utils.js';\nexport class PointInFiniteField {\n x;\n y;\n constructor(x, y) {\n const P = new Curve().p; // arithmetic is mod P\n this.x = x.umod(P);\n this.y = y.umod(P);\n }\n toString() {\n return toBase58(this.x.toArray()) + '.' + toBase58(this.y.toArray());\n }\n static fromString(str) {\n const [x, y] = str.split('.');\n return new PointInFiniteField(new BigNumber(fromBase58(x)), new BigNumber(fromBase58(y)));\n }\n}\n/**\n * Polynomial class\n *\n * This class is used to create a polynomial with a given threshold and a private key.\n * The polynomial is used to create shares of the private key.\n *\n * @param key - The private key to split\n * @param threshold - The number of shares required to recombine the private key\n *\n * @example\n * const key = new PrivateKey()\n * const threshold = 2\n * const polynomial = new Polynomial(key, threshold)\n *\n */\nexport default class Polynomial {\n points;\n threshold;\n constructor(points, threshold) {\n this.points = points;\n this.threshold = threshold ?? points.length; // ✅ Handles undefined safely\n }\n static fromPrivateKey(key, threshold) {\n const P = new Curve().p; // arithmetic is mod P\n // The key is the y-intercept of the polynomial where x=0.\n const points = [\n new PointInFiniteField(new BigNumber(0), new BigNumber(key.toArray()))\n ];\n // The other values are random\n for (let i = 1; i < threshold; i++) {\n const randomX = new BigNumber(Random(32)).umod(P);\n const randomY = new BigNumber(Random(32)).umod(P);\n points.push(new PointInFiniteField(randomX, randomY));\n }\n return new Polynomial(points);\n }\n // Evaluate the polynomial at x by using Lagrange interpolation\n valueAt(x) {\n const P = new Curve().p; // arithmetic is mod P\n let y = new BigNumber(0);\n for (let i = 0; i < this.threshold; i++) {\n let term = this.points[i].y;\n for (let j = 0; j < this.threshold; j++) {\n if (i !== j) {\n const xj = this.points[j].x;\n const xi = this.points[i].x;\n const numerator = x.sub(xj).umod(P);\n const denominator = xi.sub(xj).umod(P);\n const denominatorInverse = denominator.invm(P);\n const fraction = numerator.mul(denominatorInverse).umod(P);\n term = term.mul(fraction).umod(P);\n }\n }\n y = y.add(term).umod(P);\n }\n return y;\n }\n}\n//# sourceMappingURL=Polynomial.js.map","import BigNumber from './BigNumber.js';\nimport PublicKey from './PublicKey.js';\nimport Curve from './Curve.js';\nimport { sign, verify } from './ECDSA.js';\nimport { sha256, sha256hmac, sha512hmac } from './Hash.js';\nimport Random from './Random.js';\nimport { fromBase58Check, toArray, toBase58Check } from './utils.js';\nimport Polynomial, { PointInFiniteField } from './Polynomial.js';\n/**\n * @class KeyShares\n *\n * This class is used to store the shares of a private key.\n *\n * @param shares - An array of shares\n * @param threshold - The number of shares required to recombine the private key\n *\n * @returns KeyShares\n *\n * @example\n * const key = PrivateKey.fromShares(shares)\n *\n */\nexport class KeyShares {\n points;\n threshold;\n integrity;\n constructor(points, threshold, integrity) {\n this.points = points;\n this.threshold = threshold;\n this.integrity = integrity;\n }\n static fromBackupFormat(shares) {\n let threshold = 0;\n let integrity = '';\n const points = shares.map((share, idx) => {\n const shareParts = share.split('.');\n if (shareParts.length !== 4) {\n throw new Error('Invalid share format in share ' +\n idx.toString() +\n '. Expected format: \"x.y.t.i\" - received ' +\n share);\n }\n const [x, y, t, i] = shareParts;\n if (t === undefined)\n throw new Error('Threshold not found in share ' + idx.toString());\n if (i === undefined)\n throw new Error('Integrity not found in share ' + idx.toString());\n const tInt = parseInt(t);\n if (idx !== 0 && threshold !== tInt) {\n throw new Error('Threshold mismatch in share ' + idx.toString());\n }\n if (idx !== 0 && integrity !== i) {\n throw new Error('Integrity mismatch in share ' + idx.toString());\n }\n threshold = tInt;\n integrity = i;\n return PointInFiniteField.fromString([x, y].join('.'));\n });\n return new KeyShares(points, threshold, integrity);\n }\n toBackupFormat() {\n return this.points.map((share) => share.toString() + '.' + this.threshold.toString() + '.' + this.integrity);\n }\n}\n/**\n * Represents a Private Key, which is a secret that can be used to generate signatures in a cryptographic system.\n *\n * The `PrivateKey` class extends from the `BigNumber` class. It offers methods to create signatures, verify them,\n * create a corresponding public key and derive a shared secret from a public key.\n *\n * @extends {BigNumber}\n * @see {@link BigNumber} for more information on BigNumber.\n */\nexport default class PrivateKey extends BigNumber {\n /**\n * Generates a private key randomly.\n *\n * @method fromRandom\n * @static\n * @returns The newly generated Private Key.\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n */\n static fromRandom() {\n return new PrivateKey(Random(32));\n }\n /**\n * Generates a private key from a string.\n *\n * @method fromString\n * @static\n * @param str - The string to generate the private key from.\n * @param base - The base of the string.\n * @returns The generated Private Key.\n * @throws Will throw an error if the string is not valid.\n **/\n static fromString(str, base = 'hex') {\n return new PrivateKey(super.fromString(str, base).toArray());\n }\n /**\n * Generates a private key from a hexadecimal string.\n *\n * @method fromHex\n * @static\n * @param {string} str - The hexadecimal string representing the private key. The string must represent a valid private key in big-endian format.\n * @returns {PrivateKey} The generated Private Key instance.\n * @throws {Error} If the string is not a valid hexadecimal or represents an invalid private key.\n **/\n static fromHex(str) {\n return new PrivateKey(super.fromHex(str, 'big'));\n }\n /**\n * Generates a private key from a WIF (Wallet Import Format) string.\n *\n * @method fromWif\n * @static\n * @param wif - The WIF string to generate the private key from.\n * @param base - The base of the string.\n * @returns The generated Private Key.\n * @throws Will throw an error if the string is not a valid WIF.\n **/\n static fromWif(wif, prefixLength = 1) {\n const decoded = fromBase58Check(wif, undefined, prefixLength);\n if (decoded.data.length !== 33) {\n throw new Error('Invalid WIF length');\n }\n if (decoded.data[32] !== 1) {\n throw new Error('Invalid WIF padding');\n }\n return new PrivateKey(decoded.data.slice(0, 32));\n }\n /**\n * @constructor\n *\n * @param number - The number (various types accepted) to construct a BigNumber from. Default is 0.\n *\n * @param base - The base of number provided. By default is 10. Ignored if number is BigNumber.\n *\n * @param endian - The endianness provided. By default is 'big endian'. Ignored if number is BigNumber.\n *\n * @param modN - Optional. Default 'apply. If 'apply', apply modN to input to guarantee a valid PrivateKey. If 'error', if input is out of field throw new Error('Input is out of field'). If 'nocheck', assumes input is in field.\n *\n * @example\n * import PrivateKey from './PrivateKey';\n * import BigNumber from './BigNumber';\n * const privKey = new PrivateKey(new BigNumber('123456', 10, 'be'));\n */\n constructor(number = 0, base = 10, endian = 'be', modN = 'apply') {\n if (number instanceof BigNumber) {\n super();\n number.copy(this);\n }\n else {\n super(number, base, endian);\n }\n if (modN !== 'nocheck') {\n const check = this.checkInField();\n if (!check.inField) {\n if (modN === 'error') {\n throw new Error('Input is out of field');\n }\n // Force the PrivateKey BigNumber value to lie in the field limited by curve.n\n BigNumber.move(this, check.modN);\n }\n }\n }\n /**\n * A utility function to check that the value of this PrivateKey lies in the field limited by curve.n\n * @returns { inField, modN } where modN is this PrivateKey's current BigNumber value mod curve.n, and inField is true only if modN equals current BigNumber value.\n */\n checkInField() {\n const curve = new Curve();\n const modN = this.mod(curve.n);\n const inField = this.cmp(modN) === 0;\n return { inField, modN };\n }\n /**\n * @returns true if the PrivateKey's current BigNumber value lies in the field limited by curve.n\n */\n isValid() {\n return this.checkInField().inField;\n }\n /**\n * Signs a message using the private key.\n *\n * @method sign\n * @param msg - The message (array of numbers or string) to be signed.\n * @param enc - If 'hex' the string will be treated as hex, utf8 otherwise.\n * @param forceLowS - If true (the default), the signature will be forced to have a low S value.\n * @param customK — If provided, uses a custom K-value for the signature. Provie a function that returns a BigNumber, or the BigNumber itself.\n * @returns A digital signature generated from the hash of the message and the private key.\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n * const signature = privateKey.sign('Hello, World!');\n */\n sign(msg, enc, forceLowS = true, customK) {\n const msgHash = new BigNumber(sha256(msg, enc), 16);\n return sign(msgHash, this, forceLowS, customK);\n }\n /**\n * Verifies a message's signature using the public key associated with this private key.\n *\n * @method verify\n * @param msg - The original message which has been signed.\n * @param sig - The signature to be verified.\n * @param enc - The data encoding method.\n * @returns Whether or not the signature is valid.\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n * const signature = privateKey.sign('Hello, World!');\n * const isSignatureValid = privateKey.verify('Hello, World!', signature);\n */\n verify(msg, sig, enc) {\n const msgHash = new BigNumber(sha256(msg, enc), 16);\n return verify(msgHash, sig, this.toPublicKey());\n }\n /**\n * Converts the private key to its corresponding public key.\n *\n * The public key is generated by multiplying the base point G of the curve and the private key.\n *\n * @method toPublicKey\n * @returns The generated PublicKey.\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n * const publicKey = privateKey.toPublicKey();\n */\n toPublicKey() {\n const c = new Curve();\n const p = c.g.mul(this);\n return new PublicKey(p.x, p.y);\n }\n /**\n * Converts the private key to a Wallet Import Format (WIF) string.\n *\n * Base58Check encoding is used for encoding the private key.\n * The prefix\n *\n * @method toWif\n * @returns The WIF string.\n *\n * @param prefix defaults to [0x80] for mainnet, set it to [0xef] for testnet.\n *\n * @throws Error('Value is out of field') if current BigNumber value is out of field limited by curve.n\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n * const wif = privateKey.toWif();\n * const testnetWif = privateKey.toWif([0xef]);\n */\n toWif(prefix = [0x80]) {\n if (!this.isValid()) {\n throw new Error('Value is out of field');\n }\n return toBase58Check([...this.toArray('be', 32), 1], prefix);\n }\n /**\n * Base58Check encodes the hash of the public key associated with this private key with a prefix to indicate locking script type.\n * Defaults to P2PKH for mainnet, otherwise known as a \"Bitcoin Address\".\n *\n * @param prefix defaults to [0x00] for mainnet, set to [0x6f] for testnet or use the strings 'testnet' or 'mainnet'\n *\n * @returns Returns the address encoding associated with the hash of the public key associated with this private key.\n *\n * @example\n * const address = privkey.toAddress()\n * const address = privkey.toAddress('mainnet')\n * const testnetAddress = privkey.toAddress([0x6f])\n * const testnetAddress = privkey.toAddress('testnet')\n */\n toAddress(prefix = [0x00]) {\n return this.toPublicKey().toAddress(prefix);\n }\n /**\n * Converts this PrivateKey to a hexadecimal string.\n *\n * @method toHex\n * @param length - The minimum length of the hex string\n * @returns Returns a string representing the hexadecimal value of this BigNumber.\n *\n * @example\n * const bigNumber = new BigNumber(255);\n * const hex = bigNumber.toHex();\n */\n toHex() {\n return super.toHex(32);\n }\n /**\n * Converts this PrivateKey to a string representation.\n *\n * @method toString\n * @param {number | 'hex'} [base='hex'] - The base for representing the number. Default is hexadecimal ('hex').\n * @param {number} [padding=64] - The minimum number of digits for the output string. Default is 64, ensuring a 256-bit representation in hexadecimal.\n * @returns {string} A string representation of the PrivateKey in the specified base, padded to the specified length.\n *\n **/\n toString(base = 'hex', padding = 64) {\n return super.toString(base, padding);\n }\n /**\n * Derives a shared secret from the public key.\n *\n * @method deriveSharedSecret\n * @param key - The public key to derive the shared secret from.\n * @returns The derived shared secret (a point on the curve).\n * @throws Will throw an error if the public key is not valid.\n *\n * @example\n * const privateKey = PrivateKey.fromRandom();\n * const publicKey = privateKey.toPublicKey();\n * const sharedSecret = privateKey.deriveSharedSecret(publicKey);\n */\n deriveSharedSecret(key) {\n if (!key.validate()) {\n throw new Error('Public key not valid for ECDH secret derivation');\n }\n return key.mul(this);\n }\n /**\n * Derives a child key with BRC-42.\n * @param publicKey The public key of the other party\n * @param invoiceNumber The invoice number used to derive the child key\n * @param cacheSharedSecret Optional function to cache shared secrets\n * @param retrieveCachedSharedSecret Optional function to retrieve shared secrets from the cache\n * @returns The derived child key.\n */\n deriveChild(publicKey, invoiceNumber, cacheSharedSecret, retrieveCachedSharedSecret) {\n let sharedSecret;\n if (typeof retrieveCachedSharedSecret === 'function') {\n const retrieved = retrieveCachedSharedSecret(this, publicKey);\n if (typeof retrieved !== 'undefined') {\n sharedSecret = retrieved;\n }\n else {\n sharedSecret = this.deriveSharedSecret(publicKey);\n if (typeof cacheSharedSecret === 'function') {\n cacheSharedSecret(this, publicKey, sharedSecret);\n }\n }\n }\n else {\n sharedSecret = this.deriveSharedSecret(publicKey);\n }\n const invoiceNumberBin = toArray(invoiceNumber, 'utf8');\n const hmac = sha256hmac(sharedSecret.encode(true), invoiceNumberBin);\n const curve = new Curve();\n return new PrivateKey(this.add(new BigNumber(hmac)).mod(curve.n).toArray());\n }\n /**\n * Splits the private key into shares using Shamir's Secret Sharing Scheme.\n *\n * @param threshold The minimum number of shares required to reconstruct the private key.\n * @param totalShares The total number of shares to generate.\n * @param prime The prime number to be used in Shamir's Secret Sharing Scheme.\n * @returns An array of shares.\n *\n * @example\n * const key = PrivateKey.fromRandom()\n * const shares = key.toKeyShares(2, 5)\n */\n toKeyShares(threshold, totalShares) {\n if (typeof threshold !== 'number' || typeof totalShares !== 'number') {\n throw new Error('threshold and totalShares must be numbers');\n }\n if (threshold < 2)\n throw new Error('threshold must be at least 2');\n if (totalShares < 2)\n throw new Error('totalShares must be at least 2');\n if (threshold > totalShares) {\n throw new Error('threshold should be less than or equal to totalShares');\n }\n const poly = Polynomial.fromPrivateKey(this, threshold);\n const points = [];\n const usedXCoordinates = new Set();\n const curve = new Curve();\n /**\n * Cryptographically secure x-coordinate generation for Shamir's Secret Sharing (toKeyShares)\n *\n * - Each x-coordinate is derived using a master seed (Random(64)) as the HMAC key and a per-attempt counter array as the message.\n * - The counter array includes the share index, the attempt number (to handle rare collisions), and 32 bytes of fresh randomness for each attempt.\n * - This ensures:\n * 1. **Non-determinism**: Each split is unique, even for the same key and parameters, due to the per-attempt randomness.\n * 2. **Uniqueness**: x-coordinates are checked for zero and duplication; retry logic ensures no repeats or invalid values.\n * 3. **Cryptographic strength**: HMAC-SHA-512 is robust, and combining deterministic and random values protects against RNG compromise or bias.\n * 4. **Defensive programming**: Attempts are capped (5 per share) to prevent infinite loops in pathological cases.\n *\n * This approach is robust against all practical attacks and is suitable for high-security environments where deterministic splits are not desired.\n */\n const seed = Random(64);\n for (let i = 0; i < totalShares; i++) {\n let x;\n let attempts = 0;\n do {\n // To ensure no two points are ever the same, even if the system RNG is compromised,\n // we'll use a different counter value for each point and use SHA-512 HMAC.\n const counter = [i, attempts, ...Random(32)];\n const h = sha512hmac(seed, counter);\n x = new BigNumber(h).umod(curve.p);\n // repeat generation if x is zero or has already been used (insanely unlikely)\n attempts++;\n if (attempts > 5) {\n throw new Error('Failed to generate unique x coordinate after 5 attempts');\n }\n } while (x.isZero() || usedXCoordinates.has(x.toString()));\n usedXCoordinates.add(x.toString());\n const y = poly.valueAt(x);\n points.push(new PointInFiniteField(x, y));\n }\n const integrity = this.toPublicKey().toHash('hex').slice(0, 8);\n return new KeyShares(points, threshold, integrity);\n }\n /**\n * @method toBackupShares\n *\n * Creates a backup of the private key by splitting it into shares.\n *\n *\n * @param threshold The number of shares which will be required to reconstruct the private key.\n * @param totalShares The number of shares to generate for distribution.\n * @returns\n */\n toBackupShares(threshold, totalShares) {\n return this.toKeyShares(threshold, totalShares).toBackupFormat();\n }\n /**\n *\n * @method fromBackupShares\n *\n * Creates a private key from backup shares.\n *\n * @param shares\n * @returns PrivateKey\n *\n * @example\n *\n * const share1 = '3znuzt7DZp8HzZTfTh5MF9YQKNX3oSxTbSYmSRGrH2ev.2Nm17qoocmoAhBTCs8TEBxNXCskV9N41rB2PckcgYeqV.2.35449bb9'\n * const share2 = 'Cm5fuUc39X5xgdedao8Pr1kvCSm8Gk7Cfenc7xUKcfLX.2juyK9BxCWn2DiY5JUAgj9NsQ77cc9bWksFyW45haXZm.2.35449bb9'\n *\n * const recoveredKey = PrivateKey.fromBackupShares([share1, share2])\n */\n static fromBackupShares(shares) {\n return PrivateKey.fromKeyShares(KeyShares.fromBackupFormat(shares));\n }\n /**\n * Combines shares to reconstruct the private key.\n *\n * @param shares An array of points (shares) to be used to reconstruct the private key.\n * @param threshold The minimum number of shares required to reconstruct the private key.\n *\n * @returns The reconstructed private key.\n *\n **/\n static fromKeyShares(keyShares) {\n const { points, threshold, integrity } = keyShares;\n if (threshold < 2)\n throw new Error('threshold must be at least 2');\n if (points.length < threshold) {\n throw new Error(`At least ${threshold} shares are required to reconstruct the private key`);\n }\n // check to see if two points have the same x value\n for (let i = 0; i < threshold; i++) {\n for (let j = i + 1; j < threshold; j++) {\n if (points[i].x.eq(points[j].x)) {\n throw new Error('Duplicate share detected, each must be unique.');\n }\n }\n }\n const poly = new Polynomial(points, threshold);\n const privateKey = new PrivateKey(poly.valueAt(new BigNumber(0)).toArray());\n const integrityHash = privateKey.toPublicKey().toHash('hex').slice(0, 8);\n if (integrityHash !== integrity) {\n throw new Error('Integrity hash mismatch');\n }\n return privateKey;\n }\n}\n//# sourceMappingURL=PrivateKey.js.map","// @ts-nocheck\nconst SBox = new Uint8Array([\n 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,\n 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,\n 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,\n 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,\n 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,\n 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,\n 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,\n 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,\n 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,\n 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,\n 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,\n 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,\n 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,\n 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,\n 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,\n 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16\n]);\nconst Rcon = [\n [0x00, 0x00, 0x00, 0x00], [0x01, 0x00, 0x00, 0x00], [0x02, 0x00, 0x00, 0x00], [0x04, 0x00, 0x00, 0x00],\n [0x08, 0x00, 0x00, 0x00], [0x10, 0x00, 0x00, 0x00], [0x20, 0x00, 0x00, 0x00], [0x40, 0x00, 0x00, 0x00],\n [0x80, 0x00, 0x00, 0x00], [0x1b, 0x00, 0x00, 0x00], [0x36, 0x00, 0x00, 0x00]\n].map(v => new Uint8Array(v));\nconst mul2 = new Uint8Array(256);\nconst mul3 = new Uint8Array(256);\nfor (let i = 0; i < 256; i++) {\n const m2 = ((i << 1) ^ ((i & 0x80) !== 0 ? 0x1b : 0)) & 0xff;\n mul2[i] = m2;\n mul3[i] = m2 ^ i;\n}\nfunction addRoundKey(state, roundKeyArray, offset) {\n for (let c = 0; c < 4; c++) {\n const keyCol = roundKeyArray[offset + c];\n for (let r = 0; r < 4; r++) {\n state[r][c] ^= keyCol[r];\n }\n }\n}\nfunction subBytes(state) {\n for (let r = 0; r < 4; r++) {\n for (let c = 0; c < 4; c++) {\n state[r][c] = SBox[state[r][c]];\n }\n }\n}\nfunction subWord(value) {\n for (let i = 0; i < 4; i++) {\n value[i] = SBox[value[i]];\n }\n}\nfunction rotWord(value) {\n const temp = value[0];\n value[0] = value[1];\n value[1] = value[2];\n value[2] = value[3];\n value[3] = temp;\n}\nfunction shiftRows(state) {\n let tmp = state[1][0];\n state[1][0] = state[1][1];\n state[1][1] = state[1][2];\n state[1][2] = state[1][3];\n state[1][3] = tmp;\n tmp = state[2][0];\n const tmp2 = state[2][1];\n state[2][0] = state[2][2];\n state[2][1] = state[2][3];\n state[2][2] = tmp;\n state[2][3] = tmp2;\n tmp = state[3][3];\n state[3][3] = state[3][2];\n state[3][2] = state[3][1];\n state[3][1] = state[3][0];\n state[3][0] = tmp;\n}\nfunction mixColumns(state) {\n for (let c = 0; c < 4; c++) {\n const s0 = state[0][c];\n const s1 = state[1][c];\n const s2 = state[2][c];\n const s3 = state[3][c];\n state[0][c] = mul2[s0] ^ mul3[s1] ^ s2 ^ s3;\n state[1][c] = s0 ^ mul2[s1] ^ mul3[s2] ^ s3;\n state[2][c] = s0 ^ s1 ^ mul2[s2] ^ mul3[s3];\n state[3][c] = mul3[s0] ^ s1 ^ s2 ^ mul2[s3];\n }\n}\nfunction keyExpansion(roundLimit, key) {\n const nK = key.length / 4;\n const result = [];\n for (let i = 0; i < key.length; i++) {\n if (i % 4 === 0)\n result.push([]);\n result[i >> 2].push(key[i]);\n }\n for (let i = nK; i < 4 * roundLimit; i++) {\n result[i] = [];\n const temp = result[i - 1].slice();\n if (i % nK === 0) {\n rotWord(temp);\n subWord(temp);\n const r = Rcon[i / nK];\n for (let j = 0; j < 4; j++) {\n temp[j] ^= r[j];\n }\n }\n else if (nK > 6 && (i % nK) === 4) {\n subWord(temp);\n }\n for (let j = 0; j < 4; j++) {\n result[i][j] = result[i - nK][j] ^ temp[j];\n }\n }\n return result;\n}\nexport function AES(input, key) {\n let i;\n let j;\n let round;\n let roundLimit;\n const state = [[], [], [], []];\n const output = [];\n const ekey = Array.from(key);\n if (ekey.length === 16) {\n roundLimit = 11;\n }\n else if (ekey.length === 24) {\n roundLimit = 13;\n }\n else if (ekey.length === 32) {\n roundLimit = 15;\n }\n else {\n throw new Error('Illegal key length: ' + String(ekey.length));\n }\n const w = keyExpansion(roundLimit, ekey);\n for (let c = 0; c < 4; c++) {\n state[0][c] = input[c * 4];\n state[1][c] = input[c * 4 + 1];\n state[2][c] = input[c * 4 + 2];\n state[3][c] = input[c * 4 + 3];\n }\n addRoundKey(state, w, 0);\n for (round = 1; round < roundLimit; round++) {\n subBytes(state);\n shiftRows(state);\n if (round + 1 < roundLimit) {\n mixColumns(state);\n }\n addRoundKey(state, w, round * 4);\n }\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 4; j++) {\n output.push(state[j][i]);\n }\n }\n return output;\n}\nexport const checkBit = function (byteArray, byteIndex, bitIndex) {\n return (byteArray[byteIndex] & (0x01 << bitIndex)) !== 0 ? 1 : 0;\n};\nexport const getBytes = function (numericValue) {\n return [\n (numericValue & 0xFF000000) >>> 24,\n (numericValue & 0x00FF0000) >> 16,\n (numericValue & 0x0000FF00) >> 8,\n numericValue & 0x000000FF\n ];\n};\nconst createZeroBlock = function (length) {\n return new Array(length).fill(0);\n};\nconst R = [0xe1].concat(createZeroBlock(15));\nexport const exclusiveOR = function (block0, block1) {\n const len = block0.length;\n const result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = block0[i] ^ block1[i];\n }\n return result;\n};\nconst xorInto = function (target, block) {\n for (let i = 0; i < target.length; i++) {\n target[i] ^= block[i];\n }\n};\nexport const rightShift = function (block) {\n let i;\n let carry = 0;\n let oldCarry = 0;\n for (i = 0; i < block.length; i++) {\n oldCarry = carry;\n carry = block[i] & 0x01;\n block[i] = block[i] >> 1;\n if (oldCarry !== 0) {\n block[i] = block[i] | 0x80;\n }\n }\n return block;\n};\nexport const multiply = function (block0, block1) {\n const v = block1.slice();\n const z = createZeroBlock(16);\n for (let i = 0; i < 16; i++) {\n for (let j = 7; j >= 0; j--) {\n if ((block0[i] & (1 << j)) !== 0) {\n xorInto(z, v);\n }\n if ((v[15] & 1) !== 0) {\n rightShift(v);\n xorInto(v, R);\n }\n else {\n rightShift(v);\n }\n }\n }\n return z;\n};\nexport const incrementLeastSignificantThirtyTwoBits = function (block) {\n let i;\n const result = block.slice();\n for (i = 15; i !== 11; i--) {\n result[i] = result[i] + 1;\n if (result[i] === 256) {\n result[i] = 0;\n }\n else {\n break;\n }\n }\n return result;\n};\nexport function ghash(input, hashSubKey) {\n let result = createZeroBlock(16);\n for (let i = 0; i < input.length; i += 16) {\n const block = result.slice();\n for (let j = 0; j < 16; j++) {\n block[j] ^= input[i + j] ?? 0;\n }\n result = multiply(block, hashSubKey);\n }\n return result;\n}\nfunction gctr(input, initialCounterBlock, key) {\n if (input.length === 0)\n return [];\n const output = new Array(input.length);\n let counterBlock = initialCounterBlock;\n let pos = 0;\n const n = Math.ceil(input.length / 16);\n for (let i = 0; i < n; i++) {\n const counter = AES(counterBlock, key);\n const chunk = Math.min(16, input.length - pos);\n for (let j = 0; j < chunk; j++) {\n output[pos] = input[pos] ^ counter[j];\n pos++;\n }\n if (i + 1 < n) {\n counterBlock = incrementLeastSignificantThirtyTwoBits(counterBlock);\n }\n }\n return output;\n}\nexport function AESGCM(plainText, additionalAuthenticatedData, initializationVector, key) {\n if (initializationVector.length === 0) {\n throw new Error('Initialization vector must not be empty');\n }\n if (key.length === 0) {\n throw new Error('Key must not be empty');\n }\n let preCounterBlock;\n let plainTag;\n const hashSubKey = AES(createZeroBlock(16), key);\n preCounterBlock = [...initializationVector];\n if (initializationVector.length === 12) {\n preCounterBlock = preCounterBlock.concat(createZeroBlock(3)).concat([0x01]);\n }\n else {\n if (initializationVector.length % 16 !== 0) {\n preCounterBlock = preCounterBlock.concat(createZeroBlock(16 - (initializationVector.length % 16)));\n }\n preCounterBlock = preCounterBlock.concat(createZeroBlock(8));\n preCounterBlock = ghash(preCounterBlock.concat(createZeroBlock(4))\n .concat(getBytes(initializationVector.length * 8)), hashSubKey);\n }\n const cipherText = gctr(plainText, incrementLeastSignificantThirtyTwoBits(preCounterBlock), key);\n plainTag = additionalAuthenticatedData.slice();\n if (additionalAuthenticatedData.length === 0) {\n plainTag = plainTag.concat(createZeroBlock(16));\n }\n else if (additionalAuthenticatedData.length % 16 !== 0) {\n plainTag = plainTag.concat(createZeroBlock(16 - (additionalAuthenticatedData.length % 16)));\n }\n plainTag = plainTag.concat(cipherText);\n if (cipherText.length === 0) {\n plainTag = plainTag.concat(createZeroBlock(16));\n }\n else if (cipherText.length % 16 !== 0) {\n plainTag = plainTag.concat(createZeroBlock(16 - (cipherText.length % 16)));\n }\n plainTag = plainTag.concat(createZeroBlock(4))\n .concat(getBytes(additionalAuthenticatedData.length * 8))\n .concat(createZeroBlock(4)).concat(getBytes(cipherText.length * 8));\n return {\n result: cipherText,\n authenticationTag: gctr(ghash(plainTag, hashSubKey), preCounterBlock, key)\n };\n}\nexport function AESGCMDecrypt(cipherText, additionalAuthenticatedData, initializationVector, authenticationTag, key) {\n if (cipherText.length === 0) {\n throw new Error('Cipher text must not be empty');\n }\n if (initializationVector.length === 0) {\n throw new Error('Initialization vector must not be empty');\n }\n if (key.length === 0) {\n throw new Error('Key must not be empty');\n }\n let preCounterBlock;\n let compareTag;\n // Generate the hash subkey\n const hashSubKey = AES(createZeroBlock(16), key);\n preCounterBlock = [...initializationVector];\n if (initializationVector.length === 12) {\n preCounterBlock = preCounterBlock.concat(createZeroBlock(3)).concat([0x01]);\n }\n else {\n if (initializationVector.length % 16 !== 0) {\n preCounterBlock = preCounterBlock.concat(createZeroBlock(16 - (initializationVector.length % 16)));\n }\n preCounterBlock = preCounterBlock.concat(createZeroBlock(8));\n preCounterBlock = ghash(preCounterBlock.concat(createZeroBlock(4)).concat(getBytes(initializationVector.length * 8)), hashSubKey);\n }\n // Decrypt to obtain the plain text\n const plainText = gctr(cipherText, incrementLeastSignificantThirtyTwoBits(preCounterBlock), key);\n compareTag = additionalAuthenticatedData.slice();\n if (additionalAuthenticatedData.length === 0) {\n compareTag = compareTag.concat(createZeroBlock(16));\n }\n else if (additionalAuthenticatedData.length % 16 !== 0) {\n compareTag = compareTag.concat(createZeroBlock(16 - (additionalAuthenticatedData.length % 16)));\n }\n compareTag = compareTag.concat(cipherText);\n if (cipherText.length === 0) {\n compareTag = compareTag.concat(createZeroBlock(16));\n }\n else if (cipherText.length % 16 !== 0) {\n compareTag = compareTag.concat(createZeroBlock(16 - (cipherText.length % 16)));\n }\n compareTag = compareTag.concat(createZeroBlock(4))\n .concat(getBytes(additionalAuthenticatedData.length * 8))\n .concat(createZeroBlock(4)).concat(getBytes(cipherText.length * 8));\n // Generate the authentication tag\n const calculatedTag = gctr(ghash(compareTag, hashSubKey), preCounterBlock, key);\n // If the calculated tag does not match the provided tag, return null - the decryption failed.\n if (calculatedTag.join() !== authenticationTag.join()) {\n return null;\n }\n return plainText;\n}\n//# sourceMappingURL=AESGCM.js.map","import BigNumber from './BigNumber.js';\nimport { AESGCM, AESGCMDecrypt } from './AESGCM.js';\nimport Random from './Random.js';\nimport { toArray, encode } from './utils.js';\n/**\n * `SymmetricKey` is a class that extends the `BigNumber` class and implements symmetric encryption and decryption methods.\n * Symmetric-Key encryption is a form of encryption where the same key is used to encrypt and decrypt the message.\n * It leverages the Advanced Encryption Standard Galois/Counter Mode (AES-GCM) for encryption and decryption of messages.\n *\n * @class SymmetricKey\n * @extends {BigNumber}\n */\nexport default class SymmetricKey extends BigNumber {\n /**\n * Generates a symmetric key randomly.\n *\n * @method fromRandom\n * @static\n * @returns The newly generated Symmetric Key.\n *\n * @example\n * const symmetricKey = SymmetricKey.fromRandom();\n */\n static fromRandom() {\n return new SymmetricKey(Random(32));\n }\n /**\n * Encrypts a given message using AES-GCM encryption.\n * The generated Initialization Vector (IV) is attached to the encrypted message for decryption purposes.\n * The OpenSSL format of |IV|encryptedContent|authTag| is used.\n *\n * @method encrypt\n * @param msg - The message to be encrypted. It can be a string or an array of numbers.\n * @param enc - optional. The encoding of the message. If hex, the string is assumed to be hex, UTF-8 otherwise.\n * @returns Returns the encrypted message as a string or an array of numbers, depending on `enc` argument.\n *\n * @example\n * const key = new SymmetricKey(1234);\n * const encryptedMessage = key.encrypt('plainText', 'utf8');\n */\n encrypt(msg, enc) {\n const iv = Random(32);\n msg = toArray(msg, enc);\n const keyBytes = this.toArray('be', 32);\n const { result, authenticationTag } = AESGCM(msg, [], iv, keyBytes);\n const totalLength = iv.length + result.length + authenticationTag.length;\n const combined = new Array(totalLength);\n let offset = 0;\n for (const chunk of [iv, result, authenticationTag]) {\n for (let i = 0; i < chunk.length; i++) {\n combined[offset++] = chunk[i];\n }\n }\n return encode(combined, enc);\n }\n /**\n * Decrypts a given AES-GCM encrypted message using the same key that was used for encryption.\n * The method extracts the IV and the authentication tag from the encrypted message, then attempts to decrypt it.\n * If the decryption fails (e.g., due to message tampering), an error is thrown.\n *\n * @method decrypt\n * @param msg - The encrypted message to be decrypted. It can be a string or an array of numbers.\n * @param enc - optional. The encoding of the message (if no encoding is provided, uses utf8 for strings, unless specified as hex).\n * @returns Returns the decrypted message as a string or an array of numbers, depending on `enc` argument. If absent, an array of numbers is returned.\n *\n * @example\n * const key = new SymmetricKey(1234);\n * const decryptedMessage = key.decrypt(encryptedMessage, 'utf8');\n *\n * @throws {Error} Will throw an error if the decryption fails, likely due to message tampering or incorrect decryption key.\n */\n decrypt(msg, enc) {\n msg = toArray(msg, enc);\n const ivLength = 32;\n const tagLength = 16;\n if (msg.length < ivLength + tagLength) {\n throw new Error('Ciphertext too short');\n }\n const iv = msg.slice(0, ivLength);\n const tagStart = msg.length - tagLength;\n const ciphertext = msg.slice(ivLength, tagStart);\n const messageTag = msg.slice(tagStart);\n const result = AESGCMDecrypt(ciphertext, [], iv, messageTag, this.toArray('be', 32));\n if (result === null) {\n throw new Error('Decryption failed!');\n }\n return encode(result, enc);\n }\n}\n//# sourceMappingURL=SymmetricKey.js.map","import Signature from './Signature.js';\nimport BigNumber from './BigNumber.js';\nimport * as Hash from './Hash.js';\nimport { toArray, Writer } from './utils.js';\nconst EMPTY_SCRIPT = new Uint8Array(0);\nexport default class TransactionSignature extends Signature {\n static SIGHASH_ALL = 0x00000001;\n static SIGHASH_NONE = 0x00000002;\n static SIGHASH_SINGLE = 0x00000003;\n static SIGHASH_FORKID = 0x00000040;\n static SIGHASH_ANYONECANPAY = 0x00000080;\n scope;\n /**\n * Formats the SIGHASH preimage for the targeted input, optionally using a cache to skip recomputing shared hash prefixes.\n * @param params - Context for the signing input plus transaction metadata.\n * @param params.cache - Optional cache storing previously computed `hashPrevouts`, `hashSequence`, or `hashOutputs*` values; it will be populated if present.\n */\n static format(params) {\n return Array.from(this.formatBytes(params));\n }\n /**\n * Formats the same SIGHASH preimage bytes as `format`, supporting the optional cache for hash reuse.\n * @param params - Context for the signing operation.\n * @param params.cache - Optional `SignatureHashCache` that may already contain hashed prefixes and is populated during formatting.\n * @returns Bytes for signing.\n */\n static formatBytes(params) {\n const cache = params.cache;\n const currentInput = {\n sourceTXID: params.sourceTXID,\n sourceOutputIndex: params.sourceOutputIndex,\n sequence: params.inputSequence\n };\n const inputs = [...params.otherInputs];\n inputs.splice(params.inputIndex, 0, currentInput);\n const getPrevoutHash = () => {\n const writer = new Writer();\n for (const input of inputs) {\n if (typeof input.sourceTXID === 'undefined') {\n if (input.sourceTransaction == null) {\n throw new Error('Missing sourceTransaction for input');\n }\n writer.write(input.sourceTransaction.hash());\n }\n else {\n writer.writeReverse(toArray(input.sourceTXID, 'hex'));\n }\n writer.writeUInt32LE(input.sourceOutputIndex);\n }\n return Hash.hash256(writer.toUint8Array());\n };\n const getSequenceHash = () => {\n const writer = new Writer();\n for (const input of inputs) {\n const sequence = input.sequence ?? 0xffffffff; // Default to max sequence number\n writer.writeUInt32LE(sequence);\n }\n return Hash.hash256(writer.toUint8Array());\n };\n function getOutputsHash(outputIndex) {\n const writer = new Writer();\n if (typeof outputIndex === 'undefined') {\n for (const output of params.outputs) {\n const satoshis = output.satoshis ?? 0; // Default to 0 if undefined\n writer.writeUInt64LE(satoshis);\n const script = output.lockingScript?.toUint8Array() ?? EMPTY_SCRIPT;\n writer.writeVarIntNum(script.length);\n writer.write(script);\n }\n }\n else {\n const output = params.outputs[outputIndex];\n if (output === undefined) { // ✅ Explicitly check for undefined\n throw new Error(`Output at index ${outputIndex} does not exist`);\n }\n const satoshis = output.satoshis ?? 0; // Default to 0 if undefined\n writer.writeUInt64LE(satoshis);\n const script = output.lockingScript?.toUint8Array() ?? EMPTY_SCRIPT;\n writer.writeVarIntNum(script.length);\n writer.write(script);\n }\n return Hash.hash256(writer.toUint8Array());\n }\n let hashPrevouts = new Array(32).fill(0);\n let hashSequence = new Array(32).fill(0);\n let hashOutputs = new Array(32).fill(0);\n if ((params.scope & TransactionSignature.SIGHASH_ANYONECANPAY) === 0) {\n if (cache?.hashPrevouts != null) {\n hashPrevouts = cache.hashPrevouts;\n }\n else {\n hashPrevouts = getPrevoutHash();\n if (cache != null)\n cache.hashPrevouts = hashPrevouts;\n }\n }\n if ((params.scope & TransactionSignature.SIGHASH_ANYONECANPAY) === 0 &&\n (params.scope & 31) !== TransactionSignature.SIGHASH_SINGLE &&\n (params.scope & 31) !== TransactionSignature.SIGHASH_NONE) {\n if (cache?.hashSequence != null) {\n hashSequence = cache.hashSequence;\n }\n else {\n hashSequence = getSequenceHash();\n if (cache != null)\n cache.hashSequence = hashSequence;\n }\n }\n if ((params.scope & 31) !== TransactionSignature.SIGHASH_SINGLE &&\n (params.scope & 31) !== TransactionSignature.SIGHASH_NONE) {\n if (cache?.hashOutputsAll != null) {\n hashOutputs = cache.hashOutputsAll;\n }\n else {\n hashOutputs = getOutputsHash();\n if (cache != null)\n cache.hashOutputsAll = hashOutputs;\n }\n }\n else if ((params.scope & 31) === TransactionSignature.SIGHASH_SINGLE &&\n params.inputIndex < params.outputs.length) {\n const key = params.inputIndex;\n const cachedSingle = cache?.hashOutputsSingle?.get(key);\n if (cachedSingle != null) {\n hashOutputs = cachedSingle;\n }\n else {\n hashOutputs = getOutputsHash(key);\n if (cache != null) {\n if (cache.hashOutputsSingle == null)\n cache.hashOutputsSingle = new Map();\n cache.hashOutputsSingle.set(key, hashOutputs);\n }\n }\n }\n const writer = new Writer();\n // Version\n writer.writeInt32LE(params.transactionVersion);\n // Input prevouts/nSequence (none/all, depending on flags)\n writer.write(hashPrevouts);\n writer.write(hashSequence);\n // outpoint (32-byte hash + 4-byte little endian)\n writer.writeReverse(toArray(params.sourceTXID, 'hex'));\n writer.writeUInt32LE(params.sourceOutputIndex);\n // scriptCode of the input (serialized as scripts inside CTxOuts)\n const subscriptBin = params.subscript.toUint8Array();\n writer.writeVarIntNum(subscriptBin.length);\n writer.write(subscriptBin);\n // value of the output spent by this input (8-byte little endian)\n writer.writeUInt64LE(params.sourceSatoshis);\n // nSequence of the input (4-byte little endian)\n const sequenceNumber = currentInput.sequence;\n writer.writeUInt32LE(sequenceNumber);\n // Outputs (none/one/all, depending on flags)\n writer.write(hashOutputs);\n // Locktime\n writer.writeUInt32LE(params.lockTime);\n // sighashType\n writer.writeUInt32LE(params.scope >>> 0);\n return writer.toUint8Array();\n }\n // The format used in a tx\n static fromChecksigFormat(buf) {\n if (buf.length === 0) {\n // allow setting a \"blank\" signature\n const r = new BigNumber(1);\n const s = new BigNumber(1);\n const scope = 1;\n return new TransactionSignature(r, s, scope);\n }\n const scope = buf[buf.length - 1];\n const derbuf = buf.slice(0, buf.length - 1);\n const tempSig = Signature.fromDER(derbuf);\n return new TransactionSignature(tempSig.r, tempSig.s, scope);\n }\n constructor(r, s, scope) {\n super(r, s);\n this.scope = scope;\n }\n /**\n * Compares to bitcoind's IsLowDERSignature\n * See also Ecdsa signature algorithm which enforces this.\n * See also Bip 62, \"low S values in signatures\"\n */\n hasLowS() {\n if (this.s.ltn(1) ||\n this.s.gt(new BigNumber('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0', 'hex'))) {\n return false;\n }\n return true;\n }\n toChecksigFormat() {\n const derbuf = this.toDER();\n return [...derbuf, this.scope];\n }\n}\n//# sourceMappingURL=TransactionSignature.js.map","import BigNumber from './BigNumber.js';\nimport Curve from './Curve.js';\nimport { sha256 } from './Hash.js';\nimport { PrivateKey } from './index.js';\n/**\n * Class representing the Schnorr Zero-Knowledge Proof (ZKP) protocol.\n *\n * This class provides methods to generate and verify proofs that demonstrate knowledge of a secret without revealing it.\n * Specifically, it allows one party to prove to another that they know the private key corresponding to a public key\n * and have correctly computed a shared secret, without disclosing the private key itself.\n *\n * The protocol involves two main methods:\n * - `generateProof`: Generates a proof linking a public key `A` and a shared secret `S`, proving knowledge of the corresponding private key `a`.\n * - `verifyProof`: Verifies the provided proof, ensuring its validity without revealing any secret information.\n *\n * The class utilizes elliptic curve cryptography (ECC) and the SHA-256 hash function to compute challenges within the proof.\n *\n * @example\n * ```typescript\n * const schnorr = new Schnorr();\n * const a = PrivateKey.fromRandom(); // Prover's private key\n * const A = a.toPublicKey(); // Prover's public key\n * const b = PrivateKey.fromRandom(); // Other party's private key\n * const B = b.toPublicKey(); // Other party's public key\n * const S = B.mul(a); // Shared secret\n *\n * // Prover generates the proof\n * const proof = schnorr.generateProof(a, A, B, S);\n *\n * // Verifier verifies the proof\n * const isValid = schnorr.verifyProof(A.point, B.point, S.point, proof);\n * console.log(`Proof is valid: ${isValid}`);\n * ```\n */\nexport default class Schnorr {\n curve;\n constructor() {\n this.curve = new Curve();\n }\n /**\n * Generates a proof that demonstrates the link between public key A and shared secret S\n * @param a Private key corresponding to public key A\n * @param A Public key\n * @param B Other party's public key\n * @param S Shared secret\n * @returns Proof (R, S', z)\n */\n generateProof(aArg, AArg, BArg, S) {\n const r = PrivateKey.fromRandom();\n const R = r.toPublicKey();\n const SPrime = BArg.mul(r);\n const e = this.computeChallenge(AArg, BArg, S, SPrime, R);\n const z = r.add(e.mul(aArg)).umod(this.curve.n);\n return { R, SPrime, z };\n }\n /**\n * Verifies the proof of the link between public key A and shared secret S\n * @param A Public key\n * @param B Other party's public key\n * @param S Shared secret\n * @param proof Proof (R, S', z)\n * @returns True if the proof is valid, false otherwise\n */\n verifyProof(A, B, S, proof) {\n const { R, SPrime, z } = proof;\n const e = this.computeChallenge(A, B, S, SPrime, R);\n // Check zG = R + eA\n const zG = this.curve.g.mul(z);\n const RpluseA = R.add(A.mul(e));\n if (!zG.eq(RpluseA)) {\n return false;\n }\n // Check zB = S' + eS\n const zB = B.mul(z);\n const SprimeeS = SPrime.add(S.mul(e));\n if (!zB.eq(SprimeeS)) {\n return false;\n }\n return true;\n }\n computeChallenge(A, B, S, SPrime, R) {\n const message = [\n ...A.encode(true),\n ...B.encode(true),\n ...S.encode(true),\n ...SPrime.encode(true),\n ...R.encode(true)\n ];\n const hash = sha256(message);\n return new BigNumber(hash).umod(this.curve.n);\n }\n}\n//# sourceMappingURL=Schnorr.js.map","import Random from './Random.js';\nimport { sha256, sha256hmac } from './Hash.js';\nimport { toArray, toHex } from './utils.js';\nconst HEX_REGEX = /^[0-9a-fA-F]+$/;\nconst P = BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff');\nconst N = BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551');\nconst A = P - 3n; // a = -3 mod p\nconst B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\nconst GX = BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296');\nconst GY = BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5');\nconst G = { x: GX, y: GY };\nconst HALF_N = N >> 1n;\nconst COMPRESSED_EVEN = '02';\nconst COMPRESSED_ODD = '03';\nconst UNCOMPRESSED = '04';\n/**\n * Pure BigInt implementation of the NIST P-256 (secp256r1) curve with ECDSA sign/verify.\n *\n * This class is standalone (no dependency on the existing secp256k1 primitives) and exposes\n * key generation, point encoding/decoding, scalar multiplication, and SHA-256 based ECDSA.\n */\nexport default class Secp256r1 {\n p = P;\n n = N;\n a = A;\n b = B;\n g = G;\n mod(x, m = this.p) {\n const v = x % m;\n return v >= 0n ? v : v + m;\n }\n modInv(x, m) {\n if (x === 0n || m <= 0n)\n throw new Error('Invalid mod inverse input');\n let [a, b] = [this.mod(x, m), m];\n let [u, v] = [1n, 0n];\n while (b !== 0n) {\n const q = a / b;\n [a, b] = [b, a - q * b];\n [u, v] = [v, u - q * v];\n }\n if (a !== 1n)\n throw new Error('Inverse does not exist');\n return this.mod(u, m);\n }\n modPow(base, exponent, modulus) {\n if (modulus === 1n)\n return 0n;\n let result = 1n;\n let b = this.mod(base, modulus);\n let e = exponent;\n while (e > 0n) {\n if ((e & 1n) === 1n)\n result = this.mod(result * b, modulus);\n e >>= 1n;\n b = this.mod(b * b, modulus);\n }\n return result;\n }\n isInfinity(p) {\n return p === null;\n }\n assertOnCurve(p) {\n if (this.isInfinity(p))\n return;\n const { x, y } = p;\n const left = this.mod(y * y);\n const right = this.mod(this.mod(x * x * x + this.a * x) + this.b);\n if (left !== right) {\n throw new Error('Point is not on secp256r1');\n }\n }\n pointFromAffine(x, y) {\n const point = { x: this.mod(x), y: this.mod(y) };\n this.assertOnCurve(point);\n return point;\n }\n /**\n * Decode a point from compressed or uncompressed hex.\n */\n pointFromHex(hex) {\n if (hex.startsWith(UNCOMPRESSED)) {\n const x = BigInt('0x' + hex.slice(2, 66));\n const y = BigInt('0x' + hex.slice(66));\n return this.pointFromAffine(x, y);\n }\n if (hex.startsWith(COMPRESSED_EVEN) || hex.startsWith(COMPRESSED_ODD)) {\n const x = BigInt('0x' + hex.slice(2));\n const ySq = this.mod(this.mod(x * x * x + this.a * x) + this.b);\n const y = this.modPow(ySq, (this.p + 1n) >> 2n, this.p);\n const isOdd = (y & 1n) === 1n;\n const shouldBeOdd = hex.startsWith(COMPRESSED_ODD);\n const yFinal = (isOdd === shouldBeOdd) ? y : this.p - y;\n return this.pointFromAffine(x, yFinal);\n }\n throw new Error('Invalid point encoding');\n }\n /**\n * Encode a point to compressed or uncompressed hex. Infinity is encoded as `00`.\n */\n pointToHex(p, compressed = false) {\n if (this.isInfinity(p))\n return '00';\n const xHex = this.to32BytesHex(p.x);\n const yHex = this.to32BytesHex(p.y);\n if (!compressed)\n return UNCOMPRESSED + xHex + yHex;\n const prefix = (p.y & 1n) === 0n ? COMPRESSED_EVEN : COMPRESSED_ODD;\n return prefix + xHex;\n }\n /**\n * Add two affine points (handles infinity).\n */\n addPoints(p1, p2) {\n if (this.isInfinity(p1))\n return p2;\n if (this.isInfinity(p2))\n return p1;\n const { x: x1, y: y1 } = p1;\n const { x: x2, y: y2 } = p2;\n if (x1 === x2) {\n if (y1 === y2) {\n return this.doublePoint(p1);\n }\n return null;\n }\n const m = this.mod((y2 - y1) * this.modInv(x2 - x1, this.p));\n const x3 = this.mod(m * m - x1 - x2);\n const y3 = this.mod(m * (x1 - x3) - y1);\n return { x: x3, y: y3 };\n }\n doublePoint(p) {\n if (this.isInfinity(p))\n return p;\n if (p.y === 0n)\n return null;\n const m = this.mod((3n * p.x * p.x + this.a) * this.modInv(2n * p.y, this.p));\n const x3 = this.mod(m * m - 2n * p.x);\n const y3 = this.mod(m * (p.x - x3) - p.y);\n return { x: x3, y: y3 };\n }\n /**\n * Add two points (handles infinity).\n */\n add(p1, p2) {\n return this.addPoints(p1, p2);\n }\n /**\n * Scalar multiply an arbitrary point using double-and-add.\n */\n multiply(point, scalar) {\n if (scalar === 0n || this.isInfinity(point))\n return null;\n let k = this.mod(scalar, this.n);\n let result = null;\n let addend = point;\n while (k > 0n) {\n if ((k & 1n) === 1n) {\n result = this.addPoints(result, addend);\n }\n addend = this.doublePoint(addend);\n k >>= 1n;\n }\n return result;\n }\n /**\n * Scalar multiply the base point.\n */\n multiplyBase(scalar) {\n return this.multiply(this.g, scalar);\n }\n /**\n * Check if a point lies on the curve (including infinity).\n */\n isOnCurve(p) {\n try {\n this.assertOnCurve(p);\n return true;\n }\n catch (err) {\n return false;\n }\n }\n /**\n * Generate a new random private key as 32-byte hex.\n */\n generatePrivateKeyHex() {\n return this.to32BytesHex(this.randomScalar());\n }\n randomScalar() {\n while (true) {\n const bytes = Random(32);\n const k = BigInt('0x' + toHex(bytes));\n if (k > 0n && k < this.n)\n return k;\n }\n }\n normalizePrivateKey(d) {\n const key = this.mod(d, this.n);\n if (key === 0n)\n throw new Error('Invalid private key');\n return key;\n }\n toScalar(input) {\n if (typeof input === 'bigint')\n return this.normalizePrivateKey(input);\n const hex = input.startsWith('0x') ? input.slice(2) : input;\n if (!HEX_REGEX.test(hex) || hex.length === 0 || hex.length > 64) {\n throw new Error('Private key must be a hex string <= 32 bytes');\n }\n const value = BigInt('0x' + hex.padStart(64, '0'));\n return this.normalizePrivateKey(value);\n }\n publicKeyFromPrivate(privateKey) {\n const d = this.toScalar(privateKey);\n return this.multiplyBase(d);\n }\n /**\n * Create an ECDSA signature over a message. Uses SHA-256 unless `prehashed` is true.\n * Returns low-s normalized signature hex parts.\n */\n sign(message, privateKey, opts = {}) {\n const { prehashed = false, nonce } = opts;\n const d = this.toScalar(privateKey);\n const digest = this.normalizeMessage(message, prehashed);\n const z = this.bytesToScalar(digest);\n let k = nonce ?? this.deterministicNonce(d, digest);\n while (true) {\n const p = this.multiplyBase(k);\n if (this.isInfinity(p)) {\n k = nonce ?? this.deterministicNonce(d, digest);\n continue;\n }\n const r = this.mod(p.x, this.n);\n if (r === 0n) {\n k = nonce ?? this.deterministicNonce(d, digest);\n continue;\n }\n const kinv = this.modInv(k, this.n);\n let s = this.mod(kinv * (z + r * d), this.n);\n if (s === 0n) {\n k = nonce ?? this.deterministicNonce(d, digest);\n continue;\n }\n if (s > HALF_N)\n s = this.n - s; // enforce low-s\n return { r: this.to32BytesHex(r), s: this.to32BytesHex(s) };\n }\n }\n /**\n * Verify an ECDSA signature against a message and public key.\n */\n verify(message, signature, publicKey, opts = {}) {\n const { prehashed = false } = opts;\n let q;\n try {\n q = typeof publicKey === 'string' ? this.pointFromHex(publicKey) : publicKey;\n }\n catch {\n return false;\n }\n if ((q == null) || !this.isOnCurve(q))\n return false;\n const r = typeof signature.r === 'bigint' ? signature.r : BigInt('0x' + signature.r);\n const s = typeof signature.s === 'bigint' ? signature.s : BigInt('0x' + signature.s);\n if (r <= 0n || r >= this.n || s <= 0n || s >= this.n)\n return false;\n const z = this.bytesToScalar(this.normalizeMessage(message, prehashed));\n const w = this.modInv(s, this.n);\n const u1 = this.mod(z * w, this.n);\n const u2 = this.mod(r * w, this.n);\n const p = this.addPoints(this.multiplyBase(u1), this.multiply(q, u2));\n if (this.isInfinity(p))\n return false;\n const v = this.mod(p.x, this.n);\n return v === r;\n }\n normalizeMessage(message, prehashed) {\n const bytes = this.toBytes(message);\n if (prehashed)\n return bytes;\n return new Uint8Array(sha256(bytes));\n }\n bytesToScalar(bytes) {\n const hex = toHex(Array.from(bytes));\n return BigInt('0x' + hex) % this.n;\n }\n deterministicNonce(priv, msgDigest) {\n const keyBytes = toArray(this.to32BytesHex(priv), 'hex');\n let counter = 0;\n while (counter < 1024) { // safety bound\n const data = counter === 0\n ? Array.from(msgDigest)\n : Array.from(msgDigest).concat([counter & 0xff]);\n const hmac = sha256hmac(keyBytes, data);\n const k = BigInt('0x' + toHex(hmac)) % this.n;\n if (k > 0n)\n return k;\n counter++;\n }\n throw new Error('Failed to derive deterministic nonce');\n }\n toBytes(data) {\n if (typeof data === 'string') {\n const isHex = HEX_REGEX.test(data) && data.length % 2 === 0;\n return Uint8Array.from(toArray(data, isHex ? 'hex' : 'utf8'));\n }\n if (data instanceof Uint8Array)\n return data;\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new Error('Unsupported message format');\n }\n to32BytesHex(num) {\n return num.toString(16).padStart(64, '0');\n }\n}\n//# sourceMappingURL=Secp256r1.js.map","/**\n * An object mapping opcode names (such as OP_DUP) to their corresponding numbers (such as 0x76), and vice versa.\n */\nconst OP = {\n // push value\n OP_FALSE: 0x00,\n OP_0: 0x00,\n OP_PUSHDATA1: 0x4c,\n OP_PUSHDATA2: 0x4d,\n OP_PUSHDATA4: 0x4e,\n OP_1NEGATE: 0x4f,\n OP_RESERVED: 0x50,\n OP_TRUE: 0x51,\n OP_1: 0x51,\n OP_2: 0x52,\n OP_3: 0x53,\n OP_4: 0x54,\n OP_5: 0x55,\n OP_6: 0x56,\n OP_7: 0x57,\n OP_8: 0x58,\n OP_9: 0x59,\n OP_10: 0x5a,\n OP_11: 0x5b,\n OP_12: 0x5c,\n OP_13: 0x5d,\n OP_14: 0x5e,\n OP_15: 0x5f,\n OP_16: 0x60,\n // control\n OP_NOP: 0x61,\n OP_VER: 0x62,\n OP_IF: 0x63,\n OP_NOTIF: 0x64,\n OP_VERIF: 0x65,\n OP_VERNOTIF: 0x66,\n OP_ELSE: 0x67,\n OP_ENDIF: 0x68,\n OP_VERIFY: 0x69,\n OP_RETURN: 0x6a,\n // stack ops\n OP_TOALTSTACK: 0x6b,\n OP_FROMALTSTACK: 0x6c,\n OP_2DROP: 0x6d,\n OP_2DUP: 0x6e,\n OP_3DUP: 0x6f,\n OP_2OVER: 0x70,\n OP_2ROT: 0x71,\n OP_2SWAP: 0x72,\n OP_IFDUP: 0x73,\n OP_DEPTH: 0x74,\n OP_DROP: 0x75,\n OP_DUP: 0x76,\n OP_NIP: 0x77,\n OP_OVER: 0x78,\n OP_PICK: 0x79,\n OP_ROLL: 0x7a,\n OP_ROT: 0x7b,\n OP_SWAP: 0x7c,\n OP_TUCK: 0x7d,\n // data manipulation ops\n OP_CAT: 0x7e,\n OP_SUBSTR: 0x7f, // Replaced in BSV\n OP_SPLIT: 0x7f,\n OP_LEFT: 0x80, // Replaced in BSV\n OP_NUM2BIN: 0x80,\n OP_RIGHT: 0x81, // Replaced in BSV\n OP_BIN2NUM: 0x81,\n OP_SIZE: 0x82,\n // bit logic\n OP_INVERT: 0x83,\n OP_AND: 0x84,\n OP_OR: 0x85,\n OP_XOR: 0x86,\n OP_EQUAL: 0x87,\n OP_EQUALVERIFY: 0x88,\n OP_RESERVED1: 0x89,\n OP_RESERVED2: 0x8a,\n // numeric\n OP_1ADD: 0x8b,\n OP_1SUB: 0x8c,\n OP_2MUL: 0x8d,\n OP_2DIV: 0x8e,\n OP_NEGATE: 0x8f,\n OP_ABS: 0x90,\n OP_NOT: 0x91,\n OP_0NOTEQUAL: 0x92,\n OP_ADD: 0x93,\n OP_SUB: 0x94,\n OP_MUL: 0x95,\n OP_DIV: 0x96,\n OP_MOD: 0x97,\n OP_LSHIFT: 0x98,\n OP_RSHIFT: 0x99,\n OP_BOOLAND: 0x9a,\n OP_BOOLOR: 0x9b,\n OP_NUMEQUAL: 0x9c,\n OP_NUMEQUALVERIFY: 0x9d,\n OP_NUMNOTEQUAL: 0x9e,\n OP_LESSTHAN: 0x9f,\n OP_GREATERTHAN: 0xa0,\n OP_LESSTHANOREQUAL: 0xa1,\n OP_GREATERTHANOREQUAL: 0xa2,\n OP_MIN: 0xa3,\n OP_MAX: 0xa4,\n OP_WITHIN: 0xa5,\n // crypto\n OP_RIPEMD160: 0xa6,\n OP_SHA1: 0xa7,\n OP_SHA256: 0xa8,\n OP_HASH160: 0xa9,\n OP_HASH256: 0xaa,\n OP_CODESEPARATOR: 0xab,\n OP_CHECKSIG: 0xac,\n OP_CHECKSIGVERIFY: 0xad,\n OP_CHECKMULTISIG: 0xae,\n OP_CHECKMULTISIGVERIFY: 0xaf,\n // expansion\n OP_NOP1: 0xb0,\n OP_NOP2: 0xb1,\n OP_NOP3: 0xb2,\n OP_NOP4: 0xb3,\n OP_NOP5: 0xb4,\n OP_NOP6: 0xb5,\n OP_NOP7: 0xb6,\n OP_NOP8: 0xb7,\n OP_NOP9: 0xb8,\n OP_NOP10: 0xb9,\n OP_NOP11: 0xba,\n OP_NOP12: 0xbb,\n OP_NOP13: 0xbc,\n OP_NOP14: 0xbd,\n OP_NOP15: 0xbe,\n OP_NOP16: 0xbf,\n OP_NOP17: 0xc0,\n OP_NOP18: 0xc1,\n OP_NOP19: 0xc2,\n OP_NOP20: 0xc3,\n OP_NOP21: 0xc4,\n OP_NOP22: 0xc5,\n OP_NOP23: 0xc6,\n OP_NOP24: 0xc7,\n OP_NOP25: 0xc8,\n OP_NOP26: 0xc9,\n OP_NOP27: 0xca,\n OP_NOP28: 0xcb,\n OP_NOP29: 0xcc,\n OP_NOP30: 0xcd,\n OP_NOP31: 0xce,\n OP_NOP32: 0xcf,\n OP_NOP33: 0xd0,\n OP_NOP34: 0xd1,\n OP_NOP35: 0xd2,\n OP_NOP36: 0xd3,\n OP_NOP37: 0xd4,\n OP_NOP38: 0xd5,\n OP_NOP39: 0xd6,\n OP_NOP40: 0xd7,\n OP_NOP41: 0xd8,\n OP_NOP42: 0xd9,\n OP_NOP43: 0xda,\n OP_NOP44: 0xdb,\n OP_NOP45: 0xdc,\n OP_NOP46: 0xdd,\n OP_NOP47: 0xde,\n OP_NOP48: 0xdf,\n OP_NOP49: 0xe0,\n OP_NOP50: 0xe1,\n OP_NOP51: 0xe2,\n OP_NOP52: 0xe3,\n OP_NOP53: 0xe4,\n OP_NOP54: 0xe5,\n OP_NOP55: 0xe6,\n OP_NOP56: 0xe7,\n OP_NOP57: 0xe8,\n OP_NOP58: 0xe9,\n OP_NOP59: 0xea,\n OP_NOP60: 0xeb,\n OP_NOP61: 0xec,\n OP_NOP62: 0xed,\n OP_NOP63: 0xee,\n OP_NOP64: 0xef,\n OP_NOP65: 0xf0,\n OP_NOP66: 0xf1,\n OP_NOP67: 0xf2,\n OP_NOP68: 0xf3,\n OP_NOP69: 0xf4,\n OP_NOP70: 0xf5,\n OP_NOP71: 0xf6,\n OP_NOP72: 0xf7,\n OP_NOP73: 0xf8,\n OP_NOP77: 0xfc,\n // template matching params\n OP_SMALLDATA: 0xf9,\n OP_SMALLINTEGER: 0xfa,\n OP_PUBKEYS: 0xfb,\n OP_PUBKEYHASH: 0xfd,\n OP_PUBKEY: 0xfe,\n OP_INVALIDOPCODE: 0xff\n};\nfor (const name in OP) {\n OP[OP[name]] = name;\n}\nexport default OP;\n//# sourceMappingURL=OP.js.map","import OP from './OP.js';\nimport { encode, toHex, toArray } from '../primitives/utils.js';\nimport BigNumber from '../primitives/BigNumber.js';\n/**\n * The Script class represents a script in a Bitcoin SV transaction,\n * encapsulating the functionality to construct, parse, and serialize\n * scripts used in both locking (output) and unlocking (input) scripts.\n *\n * @property {ScriptChunk[]} chunks - An array of script chunks that make up the script.\n */\nconst BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\nexport default class Script {\n _chunks;\n parsed;\n rawBytesCache;\n hexCache;\n /**\n * @method fromASM\n * Static method to construct a Script instance from an ASM (Assembly) formatted string.\n * @param asm - The script in ASM string format.\n * @returns A new Script instance.\n * @example\n * const script = Script.fromASM(\"OP_DUP OP_HASH160 abcd... OP_EQUALVERIFY OP_CHECKSIG\")\n */\n static fromASM(asm) {\n const chunks = [];\n const tokens = asm.split(' ');\n let i = 0;\n while (i < tokens.length) {\n const token = tokens[i];\n let opCode;\n let opCodeNum = 0;\n if (token.startsWith('OP_') && typeof OP[token] !== 'undefined') {\n opCode = token;\n opCodeNum = OP[token];\n }\n // we start with two special cases, 0 and -1, which are handled specially in\n // toASM. see _chunkToString.\n if (token === '0') {\n opCodeNum = 0;\n chunks.push({\n op: opCodeNum\n });\n i = i + 1;\n }\n else if (token === '-1') {\n opCodeNum = OP.OP_1NEGATE;\n chunks.push({\n op: opCodeNum\n });\n i = i + 1;\n }\n else if (opCode === undefined) {\n let hex = tokens[i];\n if (hex.length % 2 !== 0) {\n hex = '0' + hex;\n }\n const arr = toArray(hex, 'hex');\n if (encode(arr, 'hex') !== hex) {\n throw new Error('invalid hex string in script');\n }\n const len = arr.length;\n if (len >= 0 && len < OP.OP_PUSHDATA1) {\n opCodeNum = len;\n }\n else if (len < Math.pow(2, 8)) {\n opCodeNum = OP.OP_PUSHDATA1;\n }\n else if (len < Math.pow(2, 16)) {\n opCodeNum = OP.OP_PUSHDATA2;\n }\n else if (len < Math.pow(2, 32)) {\n opCodeNum = OP.OP_PUSHDATA4;\n }\n chunks.push({\n data: arr,\n op: opCodeNum\n });\n i = i + 1;\n }\n else if (opCodeNum === OP.OP_PUSHDATA1 ||\n opCodeNum === OP.OP_PUSHDATA2 ||\n opCodeNum === OP.OP_PUSHDATA4) {\n chunks.push({\n data: toArray(tokens[i + 2], 'hex'),\n op: opCodeNum\n });\n i = i + 3;\n }\n else {\n chunks.push({\n op: opCodeNum\n });\n i = i + 1;\n }\n }\n return new Script(chunks);\n }\n /**\n * @method fromHex\n * Static method to construct a Script instance from a hexadecimal string.\n * @param hex - The script in hexadecimal format.\n * @returns A new Script instance.\n * @example\n * const script = Script.fromHex(\"76a9...\");\n */\n static fromHex(hex) {\n if (hex.length === 0)\n return Script.fromBinary([]);\n if (hex.length % 2 !== 0) {\n throw new Error('There is an uneven number of characters in the string which suggests it is not hex encoded.');\n }\n if (!/^[0-9a-fA-F]+$/.test(hex)) {\n throw new Error('Some elements in this string are not hex encoded.');\n }\n const bin = toArray(hex, 'hex');\n const rawBytes = Uint8Array.from(bin);\n return new Script([], rawBytes, hex.toLowerCase(), false);\n }\n /**\n * @method fromBinary\n * Static method to construct a Script instance from a binary array.\n * @param bin - The script in binary array format.\n * @returns A new Script instance.\n * @example\n * const script = Script.fromBinary([0x76, 0xa9, ...])\n */\n static fromBinary(bin) {\n const rawBytes = Uint8Array.from(bin);\n return new Script([], rawBytes, undefined, false);\n }\n /**\n * @constructor\n * Constructs a new Script object.\n * @param chunks=[] - An array of script chunks to directly initialize the script.\n * @param rawBytesCache - Optional serialized bytes that can be reused instead of reserializing `chunks`.\n * @param hexCache - Optional lowercase hex string that matches the serialized bytes, used to satisfy `toHex` quickly.\n * @param parsed - When false the script defers parsing `rawBytesCache` until `chunks` is accessed; defaults to true.\n */\n constructor(chunks = [], rawBytesCache, hexCache, parsed = true) {\n this._chunks = chunks;\n this.parsed = parsed;\n this.rawBytesCache = rawBytesCache;\n this.hexCache = hexCache;\n }\n get chunks() {\n this.ensureParsed();\n return this._chunks;\n }\n set chunks(value) {\n this._chunks = value;\n this.parsed = true;\n this.invalidateSerializationCaches();\n }\n ensureParsed() {\n if (this.parsed)\n return;\n if (this.rawBytesCache != null) {\n this._chunks = Script.parseChunks(this.rawBytesCache);\n }\n else {\n this._chunks = [];\n }\n this.parsed = true;\n }\n /**\n * @method toASM\n * Serializes the script to an ASM formatted string.\n * @returns The script in ASM string format.\n */\n toASM() {\n let str = '';\n for (let i = 0; i < this.chunks.length; i++) {\n const chunk = this.chunks[i];\n str += this._chunkToString(chunk);\n }\n return str.slice(1);\n }\n /**\n * @method toHex\n * Serializes the script to a hexadecimal string.\n * @returns The script in hexadecimal format.\n */\n toHex() {\n if (this.hexCache != null) {\n return this.hexCache;\n }\n if (this.rawBytesCache == null) {\n this.rawBytesCache = this.serializeChunksToBytes();\n }\n const hex = BufferCtor != null\n ? BufferCtor.from(this.rawBytesCache).toString('hex')\n : encode(Array.from(this.rawBytesCache), 'hex');\n this.hexCache = hex;\n return hex;\n }\n /**\n * @method toBinary\n * Serializes the script to a binary array.\n * @returns The script in binary array format.\n */\n toBinary() {\n return Array.from(this.toUint8Array());\n }\n toUint8Array() {\n if (this.rawBytesCache == null) {\n this.rawBytesCache = this.serializeChunksToBytes();\n }\n return this.rawBytesCache;\n }\n /**\n * @method writeScript\n * Appends another script to this script.\n * @param script - The script to append.\n * @returns This script instance for chaining.\n */\n writeScript(script) {\n this.invalidateSerializationCaches();\n this.chunks = this.chunks.concat(script.chunks);\n return this;\n }\n /**\n * @method writeOpCode\n * Appends an opcode to the script.\n * @param op - The opcode to append.\n * @returns This script instance for chaining.\n */\n writeOpCode(op) {\n this.invalidateSerializationCaches();\n this.chunks.push({ op });\n return this;\n }\n /**\n * @method setChunkOpCode\n * Sets the opcode of a specific chunk in the script.\n * @param i - The index of the chunk.\n * @param op - The opcode to set.\n * @returns This script instance for chaining.\n */\n setChunkOpCode(i, op) {\n this.invalidateSerializationCaches();\n this.chunks[i] = { op };\n return this;\n }\n /**\n * @method writeBn\n * Appends a BigNumber to the script as an opcode.\n * @param bn - The BigNumber to append.\n * @returns This script instance for chaining.\n */\n writeBn(bn) {\n this.invalidateSerializationCaches();\n if (bn.cmpn(0) === OP.OP_0) {\n this.chunks.push({\n op: OP.OP_0\n });\n }\n else if (bn.cmpn(-1) === 0) {\n this.chunks.push({\n op: OP.OP_1NEGATE\n });\n }\n else if (bn.cmpn(1) >= 0 && bn.cmpn(16) <= 0) {\n // see OP_1 - OP_16\n this.chunks.push({\n op: bn.toNumber() + OP.OP_1 - 1\n });\n }\n else {\n const buf = bn.toSm('little');\n this.writeBin(buf);\n }\n return this;\n }\n /**\n * @method writeBin\n * Appends binary data to the script, determining the appropriate opcode based on length.\n * @param bin - The binary data to append.\n * @returns This script instance for chaining.\n * @throws {Error} Throws an error if the data is too large to be pushed.\n */\n writeBin(bin) {\n this.invalidateSerializationCaches();\n let op;\n const data = bin.length > 0 ? bin : undefined;\n if (bin.length > 0 && bin.length < OP.OP_PUSHDATA1) {\n op = bin.length;\n }\n else if (bin.length === 0) {\n op = OP.OP_0;\n }\n else if (bin.length < Math.pow(2, 8)) {\n op = OP.OP_PUSHDATA1;\n }\n else if (bin.length < Math.pow(2, 16)) {\n op = OP.OP_PUSHDATA2;\n }\n else if (bin.length < Math.pow(2, 32)) {\n op = OP.OP_PUSHDATA4;\n }\n else {\n throw new Error(\"You can't push that much data\");\n }\n this.chunks.push({\n data,\n op\n });\n return this;\n }\n /**\n * @method writeNumber\n * Appends a number to the script.\n * @param num - The number to append.\n * @returns This script instance for chaining.\n */\n writeNumber(num) {\n this.invalidateSerializationCaches();\n this.writeBn(new BigNumber(num));\n return this;\n }\n /**\n * @method removeCodeseparators\n * Removes all OP_CODESEPARATOR opcodes from the script.\n * @returns This script instance for chaining.\n */\n removeCodeseparators() {\n this.invalidateSerializationCaches();\n const chunks = [];\n for (let i = 0; i < this.chunks.length; i++) {\n if (this.chunks[i].op !== OP.OP_CODESEPARATOR) {\n chunks.push(this.chunks[i]);\n }\n }\n this.chunks = chunks;\n return this;\n }\n /**\n * Deletes the given item wherever it appears in the current script.\n *\n * @param script - The script containing the item to delete from the current script.\n *\n * @returns This script instance for chaining.\n */\n findAndDelete(script) {\n this.invalidateSerializationCaches();\n const buf = script.toHex();\n for (let i = 0; i < this.chunks.length; i++) {\n const script2 = new Script([this.chunks[i]]);\n const buf2 = script2.toHex();\n if (buf === buf2) {\n this.chunks.splice(i, 1);\n }\n }\n return this;\n }\n /**\n * @method isPushOnly\n * Checks if the script contains only push data operations.\n * @returns True if the script is push-only, otherwise false.\n */\n isPushOnly() {\n for (let i = 0; i < this.chunks.length; i++) {\n const chunk = this.chunks[i];\n const opCodeNum = chunk.op;\n if (opCodeNum > OP.OP_16) {\n return false;\n }\n }\n return true;\n }\n /**\n * @method isLockingScript\n * Determines if the script is a locking script.\n * @returns True if the script is a locking script, otherwise false.\n */\n isLockingScript() {\n throw new Error('Not implemented');\n }\n /**\n * @method isUnlockingScript\n * Determines if the script is an unlocking script.\n * @returns True if the script is an unlocking script, otherwise false.\n */\n isUnlockingScript() {\n throw new Error('Not implemented');\n }\n /**\n * @private\n * @method _chunkToString\n * Converts a script chunk to its string representation.\n * @param chunk - The script chunk.\n * @returns The string representation of the chunk.\n */\n static computeSerializedLength(chunks) {\n let total = 0;\n for (const chunk of chunks) {\n total += 1;\n if (chunk.data == null)\n continue;\n const len = chunk.data.length;\n if (chunk.op === OP.OP_RETURN) {\n total += len;\n break;\n }\n if (chunk.op < OP.OP_PUSHDATA1) {\n total += len;\n }\n else if (chunk.op === OP.OP_PUSHDATA1) {\n total += 1 + len;\n }\n else if (chunk.op === OP.OP_PUSHDATA2) {\n total += 2 + len;\n }\n else if (chunk.op === OP.OP_PUSHDATA4) {\n total += 4 + len;\n }\n }\n return total;\n }\n serializeChunksToBytes() {\n const chunks = this.chunks;\n const totalLength = Script.computeSerializedLength(chunks);\n const bytes = new Uint8Array(totalLength);\n let offset = 0;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n bytes[offset++] = chunk.op;\n if (chunk.data == null)\n continue;\n if (chunk.op === OP.OP_RETURN) {\n bytes.set(chunk.data, offset);\n offset += chunk.data.length;\n break;\n }\n offset = Script.writeChunkData(bytes, offset, chunk.op, chunk.data);\n }\n return bytes;\n }\n invalidateSerializationCaches() {\n this.rawBytesCache = undefined;\n this.hexCache = undefined;\n }\n static writeChunkData(target, offset, op, data) {\n const len = data.length;\n if (op < OP.OP_PUSHDATA1) {\n target.set(data, offset);\n return offset + len;\n }\n else if (op === OP.OP_PUSHDATA1) {\n target[offset++] = len & 0xff;\n target.set(data, offset);\n return offset + len;\n }\n else if (op === OP.OP_PUSHDATA2) {\n target[offset++] = len & 0xff;\n target[offset++] = (len >> 8) & 0xff;\n target.set(data, offset);\n return offset + len;\n }\n else if (op === OP.OP_PUSHDATA4) {\n const size = len >>> 0;\n target[offset++] = size & 0xff;\n target[offset++] = (size >> 8) & 0xff;\n target[offset++] = (size >> 16) & 0xff;\n target[offset++] = (size >> 24) & 0xff;\n target.set(data, offset);\n return offset + len;\n }\n return offset;\n }\n static parseChunks(bytes) {\n const chunks = [];\n const length = bytes.length;\n let pos = 0;\n let inConditionalBlock = 0;\n while (pos < length) {\n const op = bytes[pos++] ?? 0;\n if (op === OP.OP_RETURN && inConditionalBlock === 0) {\n chunks.push({\n op,\n data: Script.copyRange(bytes, pos, length)\n });\n break;\n }\n if (op === OP.OP_IF ||\n op === OP.OP_NOTIF ||\n op === OP.OP_VERIF ||\n op === OP.OP_VERNOTIF) {\n inConditionalBlock++;\n }\n else if (op === OP.OP_ENDIF) {\n inConditionalBlock--;\n }\n if (op > 0 && op < OP.OP_PUSHDATA1) {\n const len = op;\n const end = Math.min(pos + len, length);\n chunks.push({\n data: Script.copyRange(bytes, pos, end),\n op\n });\n pos = end;\n }\n else if (op === OP.OP_PUSHDATA1) {\n const len = pos < length ? bytes[pos++] ?? 0 : 0;\n const end = Math.min(pos + len, length);\n chunks.push({\n data: Script.copyRange(bytes, pos, end),\n op\n });\n pos = end;\n }\n else if (op === OP.OP_PUSHDATA2) {\n const b0 = bytes[pos] ?? 0;\n const b1 = bytes[pos + 1] ?? 0;\n const len = b0 | (b1 << 8);\n pos = Math.min(pos + 2, length);\n const end = Math.min(pos + len, length);\n chunks.push({\n data: Script.copyRange(bytes, pos, end),\n op\n });\n pos = end;\n }\n else if (op === OP.OP_PUSHDATA4) {\n const len = ((bytes[pos] ?? 0) |\n ((bytes[pos + 1] ?? 0) << 8) |\n ((bytes[pos + 2] ?? 0) << 16) |\n ((bytes[pos + 3] ?? 0) << 24)) >>>\n 0;\n pos = Math.min(pos + 4, length);\n const end = Math.min(pos + len, length);\n chunks.push({\n data: Script.copyRange(bytes, pos, end),\n op\n });\n pos = end;\n }\n else {\n chunks.push({ op });\n }\n }\n return chunks;\n }\n static copyRange(bytes, start, end) {\n const size = Math.max(end - start, 0);\n const data = new Array(size);\n for (let i = 0; i < size; i++) {\n data[i] = bytes[start + i] ?? 0;\n }\n return data;\n }\n _chunkToString(chunk) {\n const op = chunk.op;\n let str = '';\n if (typeof chunk.data === 'undefined') {\n const val = OP[op];\n str = `${str} ${val}`;\n }\n else {\n str = `${str} ${toHex(chunk.data)}`;\n }\n return str;\n }\n}\n//# sourceMappingURL=Script.js.map","import Script from './Script.js';\n/**\n * The LockingScript class represents a locking script in a Bitcoin SV transaction.\n * It extends the Script class and is used specifically for output scripts that lock funds.\n *\n * Inherits all properties and methods from the Script class.\n *\n * @extends {Script}\n * @see {@link Script} for more information on Script.\n */\nexport default class LockingScript extends Script {\n /**\n * @method isLockingScript\n * Determines if the script is a locking script.\n * @returns {boolean} Always returns true for a LockingScript instance.\n */\n isLockingScript() {\n return true;\n }\n /**\n * @method isUnlockingScript\n * Determines if the script is an unlocking script.\n * @returns {boolean} Always returns false for a LockingScript instance.\n */\n isUnlockingScript() {\n return false;\n }\n}\n//# sourceMappingURL=LockingScript.js.map","import Script from './Script.js';\n/**\n * The UnlockingScript class represents an unlocking script in a Bitcoin SV transaction.\n * It extends the Script class and is used specifically for input scripts that unlock funds.\n *\n * Inherits all properties and methods from the Script class.\n *\n * @extends {Script}\n * @see {@link Script} for more information on Script.\n */\nexport default class UnlockingScript extends Script {\n /**\n * @method isLockingScript\n * Determines if the script is a locking script.\n * @returns {boolean} Always returns false for an UnlockingScript instance.\n */\n isLockingScript() {\n return false;\n }\n /**\n * @method isUnlockingScript\n * Determines if the script is an unlocking script.\n * @returns {boolean} Always returns true for an UnlockingScript instance.\n */\n isUnlockingScript() {\n return true;\n }\n}\n//# sourceMappingURL=UnlockingScript.js.map","import { toHex } from '../primitives/utils.js';\nexport default class ScriptEvaluationError extends Error {\n txid;\n outputIndex;\n context;\n programCounter;\n stackState;\n altStackState;\n ifStackState;\n stackMem;\n altStackMem;\n constructor(params) {\n const stackHex = params.stackState.map(s => s != null && typeof s.length !== 'undefined' ? toHex(s) : (s === null || s === undefined ? 'null/undef' : 'INVALID_STACK_ITEM')).join(', ');\n const altStackHex = params.altStackState.map(s => s != null && typeof s.length !== 'undefined' ? toHex(s) : (s === null || s === undefined ? 'null/undef' : 'INVALID_STACK_ITEM')).join(', ');\n const pcInfo = `Context: ${params.context}, PC: ${params.programCounter}`;\n const stackInfo = `Stack: [${stackHex}] (len: ${params.stackState.length}, mem: ${params.stackMem})`;\n const altStackInfo = `AltStack: [${altStackHex}] (len: ${params.altStackState.length}, mem: ${params.altStackMem})`;\n const ifStackInfo = `IfStack: [${params.ifStackState.join(', ')}]`;\n const fullMessage = `Script evaluation error: ${params.message}\\nTXID: ${params.txid}, OutputIdx: ${params.outputIndex}\\n${pcInfo}\\n${stackInfo}\\n${altStackInfo}\\n${ifStackInfo}`;\n super(fullMessage);\n this.name = this.constructor.name;\n this.txid = params.txid;\n this.outputIndex = params.outputIndex;\n this.context = params.context;\n this.programCounter = params.programCounter;\n this.stackState = params.stackState.map(s => s.slice());\n this.altStackState = params.altStackState.map(s => s.slice());\n this.ifStackState = params.ifStackState.slice();\n this.stackMem = params.stackMem;\n this.altStackMem = params.altStackMem;\n }\n}\n//# sourceMappingURL=ScriptEvaluationError.js.map","import Script from './Script.js';\nimport BigNumber from '../primitives/BigNumber.js';\nimport OP from './OP.js';\nimport { minimallyEncode } from '../primitives/utils.js';\nimport ScriptEvaluationError from './ScriptEvaluationError.js';\nimport * as Hash from '../primitives/Hash.js';\nimport TransactionSignature from '../primitives/TransactionSignature.js';\nimport PublicKey from '../primitives/PublicKey.js';\nimport { verify } from '../primitives/ECDSA.js';\n// These constants control the current behavior of the interpreter.\nconst maxScriptElementSize = 1024 * 1024 * 1024;\nconst maxMultisigKeyCount = Math.pow(2, 31) - 1;\nconst maxMultisigKeyCountBigInt = BigInt(maxMultisigKeyCount);\nconst requireMinimalPush = true;\nconst requirePushOnlyUnlockingScripts = true;\nconst requireLowSSignatures = true;\nconst requireCleanStack = true;\n// --- Optimization: Pre-computed script numbers ---\nconst SCRIPTNUM_NEG_1 = Object.freeze(new BigNumber(-1).toScriptNum());\nconst SCRIPTNUMS_0_TO_16 = Object.freeze(Array.from({ length: 17 }, (_, i) => Object.freeze(new BigNumber(i).toScriptNum())));\n// --- Helper functions ---\nfunction compareNumberArrays(a, b) {\n if (a.length !== b.length)\n return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i])\n return false;\n }\n return true;\n}\nfunction isMinimallyEncodedHelper(buf, maxNumSize = Number.MAX_SAFE_INTEGER) {\n if (buf.length > maxNumSize) {\n return false;\n }\n if (buf.length > 0) {\n if ((buf[buf.length - 1] & 0x7f) === 0) {\n if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) === 0) {\n return false;\n }\n }\n }\n return true;\n}\nfunction isChecksigFormatHelper(buf) {\n // This is a simplified check. The full DER check is more complex and typically\n // done by TransactionSignature.fromChecksigFormat which can throw.\n // This helper is mostly for early bailout or non-throwing checks if needed.\n if (buf.length < 9 || buf.length > 73)\n return false;\n if (buf[0] !== 0x30)\n return false; // DER SEQUENCE\n if (buf[1] !== buf.length - 3)\n return false; // Total length (excluding type and length byte for sequence, and hash type)\n const rMarker = buf[2];\n const rLen = buf[3];\n if (rMarker !== 0x02)\n return false; // DER INTEGER\n if (rLen === 0)\n return false; // R length is zero\n if (5 + rLen >= buf.length)\n return false; // S length misplaced or R too long\n const sMarkerOffset = 4 + rLen;\n const sMarker = buf[sMarkerOffset];\n const sLen = buf[sMarkerOffset + 1];\n if (sMarker !== 0x02)\n return false; // DER INTEGER\n if (sLen === 0)\n return false; // S length is zero\n // Check R value negative or excessively padded\n if ((buf[4] & 0x80) !== 0)\n return false; // R value negative\n if (rLen > 1 && buf[4] === 0x00 && (buf[5] & 0x80) === 0)\n return false; // R value excessively padded\n // Check S value negative or excessively padded\n const sValueOffset = sMarkerOffset + 2;\n if ((buf[sValueOffset] & 0x80) !== 0)\n return false; // S value negative\n if (sLen > 1 && buf[sValueOffset] === 0x00 && (buf[sValueOffset + 1] & 0x80) === 0)\n return false; // S value excessively padded\n if (rLen + sLen + 7 !== buf.length)\n return false; // Final length check including hash type\n return true;\n}\nfunction isOpcodeDisabledHelper(op) {\n return (op === OP.OP_2MUL ||\n op === OP.OP_2DIV ||\n op === OP.OP_VERIF ||\n op === OP.OP_VERNOTIF ||\n op === OP.OP_VER);\n}\nfunction isChunkMinimalPushHelper(chunk) {\n const data = chunk.data;\n const op = chunk.op;\n if (!Array.isArray(data))\n return true;\n if (data.length === 0)\n return op === OP.OP_0;\n if (data.length === 1 && data[0] >= 1 && data[0] <= 16)\n return op === OP.OP_1 + (data[0] - 1);\n if (data.length === 1 && data[0] === 0x81)\n return op === OP.OP_1NEGATE;\n if (data.length <= 75)\n return op === data.length;\n if (data.length <= 255)\n return op === OP.OP_PUSHDATA1;\n if (data.length <= 65535)\n return op === OP.OP_PUSHDATA2;\n return true;\n}\n/**\n * The Spend class represents a spend action within a Bitcoin SV transaction.\n * It encapsulates all the necessary data required for spending a UTXO (Unspent Transaction Output)\n * and includes details about the source transaction, output, and the spending transaction itself.\n *\n * @property {string} sourceTXID - The transaction ID of the source UTXO.\n * @property {number} sourceOutputIndex - The index of the output in the source transaction.\n * @property {BigNumber} sourceSatoshis - The amount of satoshis in the source UTXO.\n * @property {LockingScript} lockingScript - The locking script associated with the UTXO.\n * @property {number} transactionVersion - The version of the current transaction.\n * @property {Array<{ sourceTXID: string, sourceOutputIndex: number, sequence: number }>} otherInputs -\n * An array of other inputs in the transaction, each with a txid, outputIndex, and sequence number.\n * @property {Array<{ satoshis: BigNumber, lockingScript: LockingScript }>} outputs -\n * An array of outputs of the current transaction, including the satoshi value and locking script for each.\n * @property {number} inputIndex - The index of this input in the current transaction.\n * @property {UnlockingScript} unlockingScript - The unlocking script that unlocks the UTXO for spending.\n * @property {number} inputSequence - The sequence number of this input.\n * @property {number} lockTime - The lock time of the transaction.\n */\nexport default class Spend {\n sourceTXID;\n sourceOutputIndex;\n sourceSatoshis;\n lockingScript;\n transactionVersion;\n otherInputs;\n outputs;\n inputIndex;\n unlockingScript;\n inputSequence;\n lockTime;\n context;\n programCounter;\n lastCodeSeparator;\n stack;\n altStack;\n ifStack;\n memoryLimit;\n stackMem;\n altStackMem;\n sigHashCache;\n /**\n * @constructor\n * Constructs the Spend object with necessary transaction details.\n * @param {string} params.sourceTXID - The transaction ID of the source UTXO.\n * @param {number} params.sourceOutputIndex - The index of the output in the source transaction.\n * @param {BigNumber} params.sourceSatoshis - The amount of satoshis in the source UTXO.\n * @param {LockingScript} params.lockingScript - The locking script associated with the UTXO.\n * @param {number} params.transactionVersion - The version of the current transaction.\n * @param {Array<{ sourceTXID: string, sourceOutputIndex: number, sequence: number }>} params.otherInputs -\n * An array of other inputs in the transaction.\n * @param {Array<{ satoshis: BigNumber, lockingScript: LockingScript }>} params.outputs -\n * The outputs of the current transaction.\n * @param {number} params.inputIndex - The index of this input in the current transaction.\n * @param {UnlockingScript} params.unlockingScript - The unlocking script for this spend.\n * @param {number} params.inputSequence - The sequence number of this input.\n * @param {number} params.lockTime - The lock time of the transaction.\n *\n * @example\n * const spend = new Spend({\n * sourceTXID: \"abcd1234\", // sourceTXID\n * sourceOutputIndex: 0, // sourceOutputIndex\n * sourceSatoshis: new BigNumber(1000), // sourceSatoshis\n * lockingScript: LockingScript.fromASM(\"OP_DUP OP_HASH160 abcd1234... OP_EQUALVERIFY OP_CHECKSIG\"),\n * transactionVersion: 1, // transactionVersion\n * otherInputs: [{ sourceTXID: \"abcd1234\", sourceOutputIndex: 1, sequence: 0xffffffff }], // otherInputs\n * outputs: [{ satoshis: new BigNumber(500), lockingScript: LockingScript.fromASM(\"OP_DUP...\") }], // outputs\n * inputIndex: 0, // inputIndex\n * unlockingScript: UnlockingScript.fromASM(\"3045... 02ab...\"),\n * inputSequence: 0xffffffff // inputSequence\n * memoryLimit: 100000 // memoryLimit\n * });\n */\n constructor(params) {\n this.sourceTXID = params.sourceTXID;\n this.sourceOutputIndex = params.sourceOutputIndex;\n this.sourceSatoshis = params.sourceSatoshis;\n this.lockingScript = params.lockingScript;\n this.transactionVersion = params.transactionVersion;\n this.otherInputs = params.otherInputs;\n this.outputs = params.outputs;\n this.inputIndex = params.inputIndex;\n this.unlockingScript = params.unlockingScript;\n this.inputSequence = params.inputSequence;\n this.lockTime = params.lockTime;\n this.memoryLimit = params.memoryLimit ?? 32000000;\n this.stack = [];\n this.altStack = [];\n this.ifStack = [];\n this.stackMem = 0;\n this.altStackMem = 0;\n this.sigHashCache = { hashOutputsSingle: new Map() };\n this.reset();\n }\n reset() {\n this.context = 'UnlockingScript';\n this.programCounter = 0;\n this.lastCodeSeparator = null;\n this.stack = [];\n this.altStack = [];\n this.ifStack = [];\n this.stackMem = 0;\n this.altStackMem = 0;\n this.sigHashCache = { hashOutputsSingle: new Map() };\n }\n ensureStackMem(additional) {\n if (this.stackMem + additional > this.memoryLimit) {\n this.scriptEvaluationError('Stack memory usage has exceeded ' + String(this.memoryLimit) + ' bytes');\n }\n }\n ensureAltStackMem(additional) {\n if (this.altStackMem + additional > this.memoryLimit) {\n this.scriptEvaluationError('Alt stack memory usage has exceeded ' + String(this.memoryLimit) + ' bytes');\n }\n }\n pushStack(item) {\n this.ensureStackMem(item.length);\n this.stack.push(item);\n this.stackMem += item.length;\n }\n pushStackCopy(item) {\n this.ensureStackMem(item.length);\n const copy = item.slice();\n this.stack.push(copy);\n this.stackMem += copy.length;\n }\n popStack() {\n if (this.stack.length === 0) {\n this.scriptEvaluationError('Attempted to pop from an empty stack.');\n }\n const item = this.stack.pop();\n this.stackMem -= item.length;\n return item;\n }\n stackTop(index = -1) {\n // index = -1 for top, -2 for second top, etc.\n // stack.length + index provides 0-based index from start\n if (this.stack.length === 0 || this.stack.length < Math.abs(index) || (index >= 0 && index >= this.stack.length)) {\n this.scriptEvaluationError(`Stack underflow accessing element at index ${index}. Stack length is ${this.stack.length}.`);\n }\n return this.stack[this.stack.length + index];\n }\n pushAltStack(item) {\n this.ensureAltStackMem(item.length);\n this.altStack.push(item);\n this.altStackMem += item.length;\n }\n popAltStack() {\n if (this.altStack.length === 0) {\n this.scriptEvaluationError('Attempted to pop from an empty alt stack.');\n }\n const item = this.altStack.pop();\n this.altStackMem -= item.length;\n return item;\n }\n checkSignatureEncoding(buf) {\n if (buf.length === 0)\n return true;\n if (!isChecksigFormatHelper(buf)) {\n this.scriptEvaluationError('The signature format is invalid.'); // Generic message like original\n return false;\n }\n try {\n const sig = TransactionSignature.fromChecksigFormat(buf); // This can throw for stricter DER rules\n if (requireLowSSignatures && !sig.hasLowS()) {\n this.scriptEvaluationError('The signature must have a low S value.');\n return false;\n }\n if ((sig.scope & TransactionSignature.SIGHASH_FORKID) === 0) {\n this.scriptEvaluationError('The signature must use SIGHASH_FORKID.');\n return false;\n }\n }\n catch (e) {\n this.scriptEvaluationError('The signature format is invalid.');\n return false;\n }\n return true;\n }\n checkPublicKeyEncoding(buf) {\n if (buf.length === 0) {\n this.scriptEvaluationError('Public key is empty.');\n return false;\n }\n if (buf.length < 33) {\n this.scriptEvaluationError('The public key is too short, it must be at least 33 bytes.');\n return false;\n }\n if (buf[0] === 0x04) {\n if (buf.length !== 65) {\n this.scriptEvaluationError('The non-compressed public key must be 65 bytes.');\n return false;\n }\n }\n else if (buf[0] === 0x02 || buf[0] === 0x03) {\n if (buf.length !== 33) {\n this.scriptEvaluationError('The compressed public key must be 33 bytes.');\n return false;\n }\n }\n else {\n this.scriptEvaluationError('The public key is in an unknown format.');\n return false;\n }\n try {\n PublicKey.fromDER(buf); // This can throw for stricter DER rules\n }\n catch (e) {\n this.scriptEvaluationError('The public key is in an unknown format.');\n return false;\n }\n return true;\n }\n verifySignature(sig, pubkey, subscript) {\n const preimage = TransactionSignature.formatBytes({\n sourceTXID: this.sourceTXID,\n sourceOutputIndex: this.sourceOutputIndex,\n sourceSatoshis: this.sourceSatoshis,\n transactionVersion: this.transactionVersion,\n otherInputs: this.otherInputs,\n outputs: this.outputs,\n inputIndex: this.inputIndex,\n subscript,\n inputSequence: this.inputSequence,\n lockTime: this.lockTime,\n scope: sig.scope,\n cache: this.sigHashCache\n });\n const hash = new BigNumber(Hash.hash256(preimage));\n return verify(hash, sig, pubkey);\n }\n step() {\n if (this.stackMem > this.memoryLimit) {\n this.scriptEvaluationError('Stack memory usage has exceeded ' + String(this.memoryLimit) + ' bytes');\n return false; // Error thrown\n }\n if (this.altStackMem > this.memoryLimit) {\n this.scriptEvaluationError('Alt stack memory usage has exceeded ' + String(this.memoryLimit) + ' bytes');\n return false; // Error thrown\n }\n if (this.context === 'UnlockingScript' &&\n this.programCounter >= this.unlockingScript.chunks.length) {\n this.context = 'LockingScript';\n this.programCounter = 0;\n }\n const currentScript = this.context === 'UnlockingScript' ? this.unlockingScript : this.lockingScript;\n if (this.programCounter >= currentScript.chunks.length) {\n return false;\n }\n const operation = currentScript.chunks[this.programCounter];\n const currentOpcode = operation.op;\n if (typeof currentOpcode === 'undefined') {\n this.scriptEvaluationError(`Missing opcode in ${this.context} at pc=${this.programCounter}.`); // Error thrown\n }\n if (Array.isArray(operation.data) && operation.data.length > maxScriptElementSize) {\n this.scriptEvaluationError(`Data push > ${maxScriptElementSize} bytes (pc=${this.programCounter}).`); // Error thrown\n }\n const isScriptExecuting = !this.ifStack.includes(false);\n if (isScriptExecuting && isOpcodeDisabledHelper(currentOpcode)) {\n this.scriptEvaluationError(`This opcode is currently disabled. (Opcode: ${OP[currentOpcode]}, PC: ${this.programCounter})`); // Error thrown\n }\n if (isScriptExecuting && currentOpcode >= 0 && currentOpcode <= OP.OP_PUSHDATA4) {\n if (requireMinimalPush && !isChunkMinimalPushHelper(operation)) {\n this.scriptEvaluationError(`This data is not minimally-encoded. (PC: ${this.programCounter})`); // Error thrown\n }\n this.pushStack(Array.isArray(operation.data) ? operation.data : []);\n }\n else if (isScriptExecuting || (currentOpcode >= OP.OP_IF && currentOpcode <= OP.OP_ENDIF)) {\n let buf, buf1, buf2, buf3;\n let x1, x2, x3;\n let bn, bn1, bn2, bn3;\n let n, size, fValue, fSuccess, subscript;\n let bufSig, bufPubkey;\n let sig, pubkey;\n let i, ikey, isig, nKeysCount, nSigsCount, fOk;\n switch (currentOpcode) {\n case OP.OP_1NEGATE:\n this.pushStackCopy(SCRIPTNUM_NEG_1);\n break;\n case OP.OP_0:\n this.pushStackCopy(SCRIPTNUMS_0_TO_16[0]);\n break;\n case OP.OP_1:\n case OP.OP_2:\n case OP.OP_3:\n case OP.OP_4:\n case OP.OP_5:\n case OP.OP_6:\n case OP.OP_7:\n case OP.OP_8:\n case OP.OP_9:\n case OP.OP_10:\n case OP.OP_11:\n case OP.OP_12:\n case OP.OP_13:\n case OP.OP_14:\n case OP.OP_15:\n case OP.OP_16:\n n = currentOpcode - (OP.OP_1 - 1);\n this.pushStackCopy(SCRIPTNUMS_0_TO_16[n]);\n break;\n case OP.OP_NOP:\n case OP.OP_NOP2: // Formerly CHECKLOCKTIMEVERIFY\n case OP.OP_NOP3: // Formerly CHECKSEQUENCEVERIFY\n case OP.OP_NOP1:\n case OP.OP_NOP4:\n case OP.OP_NOP5:\n case OP.OP_NOP6:\n case OP.OP_NOP7:\n case OP.OP_NOP8:\n case OP.OP_NOP9:\n case OP.OP_NOP10:\n /* falls through */\n // eslint-disable-next-line no-fallthrough\n // eslint-disable-next-line no-fallthrough\n case OP.OP_NOP11:\n case OP.OP_NOP12:\n case OP.OP_NOP13:\n case OP.OP_NOP14:\n case OP.OP_NOP15:\n case OP.OP_NOP16:\n case OP.OP_NOP17:\n case OP.OP_NOP18:\n case OP.OP_NOP19:\n case OP.OP_NOP20:\n case OP.OP_NOP21:\n case OP.OP_NOP22:\n case OP.OP_NOP23:\n case OP.OP_NOP24:\n case OP.OP_NOP25:\n case OP.OP_NOP26:\n case OP.OP_NOP27:\n case OP.OP_NOP28:\n case OP.OP_NOP29:\n case OP.OP_NOP30:\n case OP.OP_NOP31:\n case OP.OP_NOP32:\n case OP.OP_NOP33:\n case OP.OP_NOP34:\n case OP.OP_NOP35:\n case OP.OP_NOP36:\n case OP.OP_NOP37:\n case OP.OP_NOP38:\n case OP.OP_NOP39:\n case OP.OP_NOP40:\n case OP.OP_NOP41:\n case OP.OP_NOP42:\n case OP.OP_NOP43:\n case OP.OP_NOP44:\n case OP.OP_NOP45:\n case OP.OP_NOP46:\n case OP.OP_NOP47:\n case OP.OP_NOP48:\n case OP.OP_NOP49:\n case OP.OP_NOP50:\n case OP.OP_NOP51:\n case OP.OP_NOP52:\n case OP.OP_NOP53:\n case OP.OP_NOP54:\n case OP.OP_NOP55:\n case OP.OP_NOP56:\n case OP.OP_NOP57:\n case OP.OP_NOP58:\n case OP.OP_NOP59:\n case OP.OP_NOP60:\n case OP.OP_NOP61:\n case OP.OP_NOP62:\n case OP.OP_NOP63:\n case OP.OP_NOP64:\n case OP.OP_NOP65:\n case OP.OP_NOP66:\n case OP.OP_NOP67:\n case OP.OP_NOP68:\n case OP.OP_NOP69:\n case OP.OP_NOP70:\n case OP.OP_NOP71:\n case OP.OP_NOP72:\n case OP.OP_NOP73:\n case OP.OP_NOP77:\n break;\n case OP.OP_IF:\n case OP.OP_NOTIF:\n fValue = false;\n if (isScriptExecuting) {\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_IF and OP_NOTIF require at least one item on the stack when they are used!');\n buf = this.popStack();\n fValue = this.castToBool(buf);\n if (currentOpcode === OP.OP_NOTIF)\n fValue = !fValue;\n }\n this.ifStack.push(fValue);\n break;\n case OP.OP_ELSE:\n if (this.ifStack.length === 0)\n this.scriptEvaluationError('OP_ELSE requires a preceeding OP_IF.');\n this.ifStack[this.ifStack.length - 1] = !this.ifStack[this.ifStack.length - 1];\n break;\n case OP.OP_ENDIF:\n if (this.ifStack.length === 0)\n this.scriptEvaluationError('OP_ENDIF requires a preceeding OP_IF.');\n this.ifStack.pop();\n break;\n case OP.OP_VERIFY:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_VERIFY requires at least one item to be on the stack.');\n buf1 = this.stackTop();\n fValue = this.castToBool(buf1);\n if (!fValue)\n this.scriptEvaluationError('OP_VERIFY requires the top stack value to be truthy.');\n this.popStack();\n break;\n case OP.OP_RETURN:\n if (this.context === 'UnlockingScript')\n this.programCounter = this.unlockingScript.chunks.length;\n else\n this.programCounter = this.lockingScript.chunks.length;\n this.ifStack = [];\n this.programCounter--; // To counteract the final increment and ensure loop termination\n break;\n case OP.OP_TOALTSTACK:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_TOALTSTACK requires at oeast one item to be on the stack.');\n this.pushAltStack(this.popStack());\n break;\n case OP.OP_FROMALTSTACK:\n if (this.altStack.length < 1)\n this.scriptEvaluationError('OP_FROMALTSTACK requires at least one item to be on the stack.'); // \"stack\" here means altstack\n this.pushStack(this.popAltStack());\n break;\n case OP.OP_2DROP:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_2DROP requires at least two items to be on the stack.');\n this.popStack();\n this.popStack();\n break;\n case OP.OP_2DUP:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_2DUP requires at least two items to be on the stack.');\n buf1 = this.stackTop(-2);\n buf2 = this.stackTop(-1);\n this.pushStackCopy(buf1);\n this.pushStackCopy(buf2);\n break;\n case OP.OP_3DUP:\n if (this.stack.length < 3)\n this.scriptEvaluationError('OP_3DUP requires at least three items to be on the stack.');\n buf1 = this.stackTop(-3);\n buf2 = this.stackTop(-2);\n buf3 = this.stackTop(-1);\n this.pushStackCopy(buf1);\n this.pushStackCopy(buf2);\n this.pushStackCopy(buf3);\n break;\n case OP.OP_2OVER:\n if (this.stack.length < 4)\n this.scriptEvaluationError('OP_2OVER requires at least four items to be on the stack.');\n buf1 = this.stackTop(-4);\n buf2 = this.stackTop(-3);\n this.pushStackCopy(buf1);\n this.pushStackCopy(buf2);\n break;\n case OP.OP_2ROT: {\n if (this.stack.length < 6)\n this.scriptEvaluationError('OP_2ROT requires at least six items to be on the stack.');\n const rot6 = this.popStack();\n const rot5 = this.popStack();\n const rot4 = this.popStack();\n const rot3 = this.popStack();\n const rot2 = this.popStack();\n const rot1 = this.popStack();\n this.pushStack(rot3);\n this.pushStack(rot4);\n this.pushStack(rot5);\n this.pushStack(rot6);\n this.pushStack(rot1);\n this.pushStack(rot2);\n break;\n }\n case OP.OP_2SWAP: {\n if (this.stack.length < 4)\n this.scriptEvaluationError('OP_2SWAP requires at least four items to be on the stack.');\n const swap4 = this.popStack();\n const swap3 = this.popStack();\n const swap2 = this.popStack();\n const swap1 = this.popStack();\n this.pushStack(swap3);\n this.pushStack(swap4);\n this.pushStack(swap1);\n this.pushStack(swap2);\n break;\n }\n case OP.OP_IFDUP:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_IFDUP requires at least one item to be on the stack.');\n buf1 = this.stackTop();\n if (this.castToBool(buf1)) {\n this.pushStackCopy(buf1);\n }\n break;\n case OP.OP_DEPTH:\n this.pushStack(new BigNumber(this.stack.length).toScriptNum());\n break;\n case OP.OP_DROP:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_DROP requires at least one item to be on the stack.');\n this.popStack();\n break;\n case OP.OP_DUP:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_DUP requires at least one item to be on the stack.');\n this.pushStackCopy(this.stackTop());\n break;\n case OP.OP_NIP:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_NIP requires at least two items to be on the stack.');\n buf2 = this.popStack();\n this.popStack();\n this.pushStack(buf2);\n break;\n case OP.OP_OVER:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_OVER requires at least two items to be on the stack.');\n this.pushStackCopy(this.stackTop(-2));\n break;\n case OP.OP_PICK:\n case OP.OP_ROLL: {\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items to be on the stack.`);\n bn = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush);\n const nBigInt = bn.toBigInt();\n if (nBigInt < 0n || nBigInt >= BigInt(this.stack.length)) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires the top stack element to be 0 or a positive number less than the current size of the stack.`);\n }\n const nIndex = Number(nBigInt);\n const itemToMoveOrCopy = this.stack[this.stack.length - 1 - nIndex];\n if (currentOpcode === OP.OP_ROLL) {\n this.stack.splice(this.stack.length - 1 - nIndex, 1);\n this.stackMem -= itemToMoveOrCopy.length;\n this.pushStack(itemToMoveOrCopy);\n }\n else { // OP_PICK\n this.pushStackCopy(itemToMoveOrCopy);\n }\n break;\n }\n case OP.OP_ROT:\n if (this.stack.length < 3)\n this.scriptEvaluationError('OP_ROT requires at least three items to be on the stack.');\n x3 = this.popStack();\n x2 = this.popStack();\n x1 = this.popStack();\n this.pushStack(x2);\n this.pushStack(x3);\n this.pushStack(x1);\n break;\n case OP.OP_SWAP:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_SWAP requires at least two items to be on the stack.');\n x2 = this.popStack();\n x1 = this.popStack();\n this.pushStack(x2);\n this.pushStack(x1);\n break;\n case OP.OP_TUCK:\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_TUCK requires at least two items to be on the stack.');\n buf1 = this.stackTop(-1); // Top element (x2)\n // stack is [... rest, x1, x2]\n // We want [... rest, x2_copy, x1, x2]\n this.ensureStackMem(buf1.length);\n this.stack.splice(this.stack.length - 2, 0, buf1.slice()); // Insert copy of x2 before x1\n this.stackMem += buf1.length; // Account for the new copy\n break;\n case OP.OP_SIZE:\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_SIZE requires at least one item to be on the stack.');\n this.pushStack(new BigNumber(this.stackTop().length).toScriptNum());\n break;\n case OP.OP_AND:\n case OP.OP_OR:\n case OP.OP_XOR: {\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items on the stack.`);\n buf2 = this.popStack();\n buf1 = this.popStack();\n if (buf1.length !== buf2.length)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires the top two stack items to be the same size.`);\n const resultBufBitwiseOp = new Array(buf1.length);\n for (let k = 0; k < buf1.length; k++) {\n if (currentOpcode === OP.OP_AND)\n resultBufBitwiseOp[k] = buf1[k] & buf2[k];\n else if (currentOpcode === OP.OP_OR)\n resultBufBitwiseOp[k] = buf1[k] | buf2[k];\n else\n resultBufBitwiseOp[k] = buf1[k] ^ buf2[k];\n }\n this.pushStack(resultBufBitwiseOp);\n break;\n }\n case OP.OP_INVERT: {\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_INVERT requires at least one item to be on the stack.');\n buf = this.popStack();\n const invertedBufOp = new Array(buf.length);\n for (let k = 0; k < buf.length; k++) {\n invertedBufOp[k] = (~buf[k]) & 0xff;\n }\n this.pushStack(invertedBufOp);\n break;\n }\n case OP.OP_LSHIFT:\n case OP.OP_RSHIFT: {\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items to be on the stack.`);\n bn2 = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush); // n (shift amount)\n buf1 = this.popStack(); // value to shift\n const shiftBits = bn2.toBigInt();\n if (shiftBits < 0n)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires the top item on the stack not to be negative.`);\n if (buf1.length === 0) {\n this.pushStack([]);\n break;\n }\n bn1 = new BigNumber(buf1);\n let shiftedBn;\n if (currentOpcode === OP.OP_LSHIFT)\n shiftedBn = bn1.ushln(shiftBits);\n else\n shiftedBn = bn1.ushrn(shiftBits);\n const shiftedArr = shiftedBn.toArray('be', buf1.length);\n this.pushStack(shiftedArr);\n break;\n }\n case OP.OP_EQUAL:\n case OP.OP_EQUALVERIFY:\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items to be on the stack.`);\n buf2 = this.popStack();\n buf1 = this.popStack();\n fValue = compareNumberArrays(buf1, buf2);\n this.pushStack(fValue ? [1] : []);\n if (currentOpcode === OP.OP_EQUALVERIFY) {\n if (!fValue)\n this.scriptEvaluationError('OP_EQUALVERIFY requires the top two stack items to be equal.');\n this.popStack();\n }\n break;\n case OP.OP_1ADD:\n case OP.OP_1SUB:\n case OP.OP_NEGATE:\n case OP.OP_ABS:\n case OP.OP_NOT:\n case OP.OP_0NOTEQUAL:\n if (this.stack.length < 1)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least one item to be on the stack.`);\n bn = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush);\n switch (currentOpcode) {\n case OP.OP_1ADD:\n bn = bn.add(new BigNumber(1));\n break;\n case OP.OP_1SUB:\n bn = bn.sub(new BigNumber(1));\n break;\n case OP.OP_NEGATE:\n bn = bn.neg();\n break;\n case OP.OP_ABS:\n if (bn.isNeg())\n bn = bn.neg();\n break;\n case OP.OP_NOT:\n bn = new BigNumber(bn.cmpn(0) === 0 ? 1 : 0);\n break;\n case OP.OP_0NOTEQUAL:\n bn = new BigNumber(bn.cmpn(0) !== 0 ? 1 : 0);\n break;\n }\n this.pushStack(bn.toScriptNum());\n break;\n case OP.OP_ADD:\n case OP.OP_SUB:\n case OP.OP_MUL:\n case OP.OP_DIV:\n case OP.OP_MOD:\n case OP.OP_BOOLAND:\n case OP.OP_BOOLOR:\n case OP.OP_NUMEQUAL:\n case OP.OP_NUMEQUALVERIFY:\n case OP.OP_NUMNOTEQUAL:\n case OP.OP_LESSTHAN:\n case OP.OP_GREATERTHAN:\n case OP.OP_LESSTHANOREQUAL:\n case OP.OP_GREATERTHANOREQUAL:\n case OP.OP_MIN:\n case OP.OP_MAX: {\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items to be on the stack.`);\n buf2 = this.popStack();\n buf1 = this.popStack();\n bn2 = BigNumber.fromScriptNum(buf2, requireMinimalPush);\n bn1 = BigNumber.fromScriptNum(buf1, requireMinimalPush);\n let predictedLen = 0;\n switch (currentOpcode) {\n case OP.OP_MUL:\n predictedLen = bn1.byteLength() + bn2.byteLength();\n break;\n case OP.OP_ADD:\n case OP.OP_SUB:\n predictedLen = Math.max(bn1.byteLength(), bn2.byteLength()) + 1;\n break;\n default:\n predictedLen = Math.max(bn1.byteLength(), bn2.byteLength());\n }\n this.ensureStackMem(predictedLen);\n let resultBnArithmetic = new BigNumber(0);\n switch (currentOpcode) {\n case OP.OP_ADD:\n resultBnArithmetic = bn1.add(bn2);\n break;\n case OP.OP_SUB:\n resultBnArithmetic = bn1.sub(bn2);\n break;\n case OP.OP_MUL:\n resultBnArithmetic = bn1.mul(bn2);\n break;\n case OP.OP_DIV:\n if (bn2.cmpn(0) === 0)\n this.scriptEvaluationError('OP_DIV cannot divide by zero!');\n resultBnArithmetic = bn1.div(bn2);\n break;\n case OP.OP_MOD:\n if (bn2.cmpn(0) === 0)\n this.scriptEvaluationError('OP_MOD cannot divide by zero!');\n resultBnArithmetic = bn1.mod(bn2);\n break;\n case OP.OP_BOOLAND:\n resultBnArithmetic = new BigNumber((bn1.cmpn(0) !== 0 && bn2.cmpn(0) !== 0) ? 1 : 0);\n break;\n case OP.OP_BOOLOR:\n resultBnArithmetic = new BigNumber((bn1.cmpn(0) !== 0 || bn2.cmpn(0) !== 0) ? 1 : 0);\n break;\n case OP.OP_NUMEQUAL:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) === 0 ? 1 : 0);\n break;\n case OP.OP_NUMEQUALVERIFY:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) === 0 ? 1 : 0);\n break;\n case OP.OP_NUMNOTEQUAL:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) !== 0 ? 1 : 0);\n break;\n case OP.OP_LESSTHAN:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) < 0 ? 1 : 0);\n break;\n case OP.OP_GREATERTHAN:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) > 0 ? 1 : 0);\n break;\n case OP.OP_LESSTHANOREQUAL:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) <= 0 ? 1 : 0);\n break;\n case OP.OP_GREATERTHANOREQUAL:\n resultBnArithmetic = new BigNumber(bn1.cmp(bn2) >= 0 ? 1 : 0);\n break;\n case OP.OP_MIN:\n resultBnArithmetic = bn1.cmp(bn2) < 0 ? bn1 : bn2;\n break;\n case OP.OP_MAX:\n resultBnArithmetic = bn1.cmp(bn2) > 0 ? bn1 : bn2;\n break;\n }\n this.pushStack(resultBnArithmetic.toScriptNum());\n if (currentOpcode === OP.OP_NUMEQUALVERIFY) {\n if (!this.castToBool(this.stackTop()))\n this.scriptEvaluationError('OP_NUMEQUALVERIFY requires the top stack item to be truthy.');\n this.popStack();\n }\n break;\n }\n case OP.OP_WITHIN:\n if (this.stack.length < 3)\n this.scriptEvaluationError('OP_WITHIN requires at least three items to be on the stack.');\n bn3 = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush); // max\n bn2 = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush); // min\n bn1 = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush); // x\n fValue = bn1.cmp(bn2) >= 0 && bn1.cmp(bn3) < 0;\n this.pushStack(fValue ? [1] : []);\n break;\n case OP.OP_RIPEMD160:\n case OP.OP_SHA1:\n case OP.OP_SHA256:\n case OP.OP_HASH160:\n case OP.OP_HASH256: {\n if (this.stack.length < 1)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least one item to be on the stack.`);\n buf = this.popStack();\n let hashResult = []; // Initialize to empty, to satisfy TS compiler\n if (currentOpcode === OP.OP_RIPEMD160)\n hashResult = Hash.ripemd160(buf);\n else if (currentOpcode === OP.OP_SHA1)\n hashResult = Hash.sha1(buf);\n else if (currentOpcode === OP.OP_SHA256)\n hashResult = Hash.sha256(buf);\n else if (currentOpcode === OP.OP_HASH160)\n hashResult = Hash.hash160(buf);\n else if (currentOpcode === OP.OP_HASH256)\n hashResult = Hash.hash256(buf);\n this.pushStack(hashResult);\n break;\n }\n case OP.OP_CODESEPARATOR:\n this.lastCodeSeparator = this.programCounter;\n break;\n case OP.OP_CHECKSIG:\n case OP.OP_CHECKSIGVERIFY: {\n if (this.stack.length < 2)\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least two items to be on the stack.`);\n bufPubkey = this.popStack();\n bufSig = this.popStack();\n if (!this.checkSignatureEncoding(bufSig) || !this.checkPublicKeyEncoding(bufPubkey)) {\n // Error already thrown by helpers\n this.scriptEvaluationError(`${OP[currentOpcode]} requires correct encoding for the public key and signature.`); // Fallback, should be unreachable\n }\n const scriptForChecksig = this.context === 'UnlockingScript' ? this.unlockingScript : this.lockingScript;\n const scriptCodeChunks = scriptForChecksig.chunks.slice(this.lastCodeSeparator === null ? 0 : this.lastCodeSeparator + 1);\n subscript = new Script(scriptCodeChunks);\n subscript.findAndDelete(new Script().writeBin(bufSig));\n fSuccess = false;\n if (bufSig.length > 0) {\n try {\n sig = TransactionSignature.fromChecksigFormat(bufSig);\n pubkey = PublicKey.fromDER(bufPubkey);\n fSuccess = this.verifySignature(sig, pubkey, subscript);\n }\n catch (e) {\n fSuccess = false;\n }\n }\n this.pushStack(fSuccess ? [1] : []);\n if (currentOpcode === OP.OP_CHECKSIGVERIFY) {\n if (!fSuccess)\n this.scriptEvaluationError('OP_CHECKSIGVERIFY requires that a valid signature is provided.');\n this.popStack();\n }\n break;\n }\n case OP.OP_CHECKMULTISIG:\n case OP.OP_CHECKMULTISIGVERIFY: {\n i = 1;\n if (this.stack.length < i) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires at least 1 item for nKeys.`);\n }\n const nKeysCountBN = BigNumber.fromScriptNum(this.stackTop(-i), requireMinimalPush);\n const nKeysCountBigInt = nKeysCountBN.toBigInt();\n if (nKeysCountBigInt < 0n || nKeysCountBigInt > maxMultisigKeyCountBigInt) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires a key count between 0 and ${maxMultisigKeyCount}.`);\n }\n nKeysCount = Number(nKeysCountBigInt);\n const declaredKeyCount = nKeysCount;\n ikey = ++i;\n i += nKeysCount;\n if (this.stack.length < i) {\n this.scriptEvaluationError(`${OP[currentOpcode]} stack too small for nKeys and keys. Need ${i}, have ${this.stack.length}.`);\n }\n const nSigsCountBN = BigNumber.fromScriptNum(this.stackTop(-i), requireMinimalPush);\n const nSigsCountBigInt = nSigsCountBN.toBigInt();\n if (nSigsCountBigInt < 0n || nSigsCountBigInt > BigInt(nKeysCount)) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires the number of signatures to be no greater than the number of keys.`);\n }\n nSigsCount = Number(nSigsCountBigInt);\n const declaredSigCount = nSigsCount;\n isig = ++i;\n i += nSigsCount;\n if (this.stack.length < i) {\n this.scriptEvaluationError(`${OP[currentOpcode]} stack too small for N, keys, M, sigs, and dummy. Need ${i}, have ${this.stack.length}.`);\n }\n const baseScriptCMS = this.context === 'UnlockingScript' ? this.unlockingScript : this.lockingScript;\n const subscriptChunksCMS = baseScriptCMS.chunks.slice(this.lastCodeSeparator === null ? 0 : this.lastCodeSeparator + 1);\n subscript = new Script(subscriptChunksCMS);\n for (let k = 0; k < nSigsCount; k++) {\n bufSig = this.stackTop(-isig - k); // Sigs are closer to top than keys\n subscript.findAndDelete(new Script().writeBin(bufSig));\n }\n fSuccess = true;\n while (fSuccess && nSigsCount > 0) {\n if (nKeysCount === 0) { // No more keys to check against but still sigs left\n fSuccess = false;\n break;\n }\n bufSig = this.stackTop(-isig);\n bufPubkey = this.stackTop(-ikey);\n if (!this.checkSignatureEncoding(bufSig) || !this.checkPublicKeyEncoding(bufPubkey)) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires correct encoding for the public key and signature.`);\n }\n fOk = false;\n if (bufSig.length > 0) {\n try {\n sig = TransactionSignature.fromChecksigFormat(bufSig);\n pubkey = PublicKey.fromDER(bufPubkey);\n fOk = this.verifySignature(sig, pubkey, subscript);\n }\n catch (e) {\n fOk = false;\n }\n }\n if (fOk) {\n isig++;\n nSigsCount--;\n }\n ikey++;\n nKeysCount--;\n if (nSigsCount > nKeysCount) {\n fSuccess = false;\n }\n }\n // Correct total items consumed by op (N_val, keys, M_val, sigs, dummy)\n const itemsConsumedByOp = 1 + // N_val\n declaredKeyCount + // keys\n 1 + // M_val\n declaredSigCount + // sigs\n 1; // dummy\n let popCount = itemsConsumedByOp - 1; // Pop all except dummy\n while (popCount > 0) {\n this.popStack();\n popCount--;\n }\n // Check and pop dummy\n if (this.stack.length < 1) {\n this.scriptEvaluationError(`${OP[currentOpcode]} requires an extra item (dummy) to be on the stack.`);\n }\n const dummyBuf = this.popStack();\n if (dummyBuf.length > 0) { // SCRIPT_VERIFY_NULLDUMMY\n this.scriptEvaluationError(`${OP[currentOpcode]} requires the extra stack item (dummy) to be empty.`);\n }\n this.pushStack(fSuccess ? [1] : []);\n if (currentOpcode === OP.OP_CHECKMULTISIGVERIFY) {\n if (!fSuccess)\n this.scriptEvaluationError('OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided.');\n this.popStack();\n }\n break;\n }\n case OP.OP_CAT: {\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_CAT requires at least two items to be on the stack.');\n buf2 = this.popStack();\n buf1 = this.popStack();\n const catResult = (buf1).concat(buf2);\n if (catResult.length > maxScriptElementSize)\n this.scriptEvaluationError(`It's not currently possible to push data larger than ${maxScriptElementSize} bytes.`);\n this.pushStack(catResult);\n break;\n }\n case OP.OP_SPLIT: {\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_SPLIT requires at least two items to be on the stack.');\n const posBuf = this.popStack();\n const dataToSplit = this.popStack();\n const splitIndexBigInt = BigNumber.fromScriptNum(posBuf, requireMinimalPush).toBigInt();\n if (splitIndexBigInt < 0n || splitIndexBigInt > BigInt(dataToSplit.length)) {\n 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.');\n }\n const splitIndex = Number(splitIndexBigInt);\n this.pushStack(dataToSplit.slice(0, splitIndex));\n this.pushStack(dataToSplit.slice(splitIndex));\n break;\n }\n case OP.OP_NUM2BIN: {\n if (this.stack.length < 2)\n this.scriptEvaluationError('OP_NUM2BIN requires at least two items to be on the stack.');\n const sizeBigInt = BigNumber.fromScriptNum(this.popStack(), requireMinimalPush).toBigInt();\n if (sizeBigInt > BigInt(maxScriptElementSize) || sizeBigInt < 0n) { // size can be 0\n this.scriptEvaluationError(`It's not currently possible to push data larger than ${maxScriptElementSize} bytes or negative size.`);\n }\n size = Number(sizeBigInt);\n let rawnum = this.popStack(); // This is the number to convert\n rawnum = minimallyEncode(rawnum); // Get its minimal scriptnum form\n if (rawnum.length > size) {\n 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.');\n }\n if (rawnum.length === size) {\n this.pushStack(rawnum);\n break;\n }\n const resultN2B = new Array(size).fill(0x00);\n let signbit = 0x00;\n if (rawnum.length > 0) {\n signbit = rawnum[rawnum.length - 1] & 0x80; // Store sign bit\n rawnum[rawnum.length - 1] &= 0x7f; // Remove sign bit for padding\n }\n // Copy rawnum (now positive magnitude) into the result\n for (let k = 0; k < rawnum.length; k++) {\n resultN2B[k] = rawnum[k];\n }\n // If the original number was negative, the sign bit must be set on the new MSB\n if (signbit !== 0) {\n resultN2B[size - 1] |= 0x80;\n }\n this.pushStack(resultN2B);\n break;\n }\n case OP.OP_BIN2NUM: {\n if (this.stack.length < 1)\n this.scriptEvaluationError('OP_BIN2NUM requires at least one item to be on the stack.');\n buf1 = this.popStack();\n const b2nResult = minimallyEncode(buf1);\n if (!isMinimallyEncodedHelper(b2nResult)) {\n this.scriptEvaluationError('OP_BIN2NUM requires that the resulting number is valid.');\n }\n this.pushStack(b2nResult);\n break;\n }\n default:\n this.scriptEvaluationError(`Invalid opcode ${currentOpcode} (pc=${this.programCounter}).`);\n }\n }\n this.programCounter++;\n return true;\n }\n /**\n * @method validate\n * Validates the spend action by interpreting the locking and unlocking scripts.\n * @returns {boolean} Returns true if the scripts are valid and the spend is legitimate, otherwise false.\n * @example\n * if (spend.validate()) {\n * console.log(\"Spend is valid!\");\n * } else {\n * console.log(\"Invalid spend!\");\n * }\n */\n validate() {\n if (requirePushOnlyUnlockingScripts && !this.unlockingScript.isPushOnly()) {\n this.scriptEvaluationError('Unlocking scripts can only contain push operations, and no other opcodes.');\n }\n while (this.step()) {\n if (this.context === 'LockingScript' &&\n this.programCounter >= this.lockingScript.chunks.length) {\n break;\n }\n }\n if (this.ifStack.length > 0) {\n this.scriptEvaluationError('Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script.');\n }\n if (requireCleanStack) {\n if (this.stack.length !== 1) {\n this.scriptEvaluationError(`The clean stack rule requires exactly one item to be on the stack after script execution, found ${this.stack.length}.`);\n }\n }\n if (this.stack.length === 0) {\n this.scriptEvaluationError('The top stack element must be truthy after script evaluation (stack is empty).');\n }\n else if (!this.castToBool(this.stackTop())) {\n this.scriptEvaluationError('The top stack element must be truthy after script evaluation.');\n }\n return true;\n }\n castToBool(val) {\n if (val.length === 0)\n return false;\n for (let i = 0; i < val.length; i++) {\n if (val[i] !== 0) {\n return !(i === val.length - 1 && val[i] === 0x80);\n }\n }\n return false;\n }\n scriptEvaluationError(str) {\n throw new ScriptEvaluationError({\n message: str,\n txid: this.sourceTXID,\n outputIndex: this.sourceOutputIndex,\n context: this.context,\n programCounter: this.programCounter,\n stackState: this.stack,\n altStackState: this.altStack,\n ifStackState: this.ifStack,\n stackMem: this.stackMem,\n altStackMem: this.altStackMem\n });\n }\n}\n//# sourceMappingURL=Spend.js.map","import OP from '../OP.js';\nimport { fromBase58Check, verifyNotNull } from '../../primitives/utils.js';\nimport LockingScript from '../LockingScript.js';\nimport UnlockingScript from '../UnlockingScript.js';\nimport TransactionSignature from '../../primitives/TransactionSignature.js';\nimport { sha256 } from '../../primitives/Hash.js';\n/**\n * P2PKH (Pay To Public Key Hash) class implementing ScriptTemplate.\n *\n * This class provides methods to create Pay To Public Key Hash locking and unlocking scripts, including the unlocking of P2PKH UTXOs with the private key.\n */\nexport default class P2PKH {\n /**\n * Creates a P2PKH locking script for a given public key hash or address string\n *\n * @param {number[] | string} pubkeyhash or address - An array or address representing the public key hash.\n * @returns {LockingScript} - A P2PKH locking script.\n */\n lock(pubkeyhash) {\n let data;\n if (typeof pubkeyhash === 'string') {\n const hash = fromBase58Check(pubkeyhash);\n if (hash.prefix[0] !== 0x00 && hash.prefix[0] !== 0x6f) {\n throw new Error('only P2PKH is supported');\n }\n data = hash.data;\n }\n else {\n data = pubkeyhash;\n }\n if (data.length !== 20) {\n throw new Error('P2PKH hash length must be 20 bytes');\n }\n return new LockingScript([\n { op: OP.OP_DUP },\n { op: OP.OP_HASH160 },\n { op: data.length, data },\n { op: OP.OP_EQUALVERIFY },\n { op: OP.OP_CHECKSIG }\n ]);\n }\n /**\n * Creates a function that generates a P2PKH unlocking script along with its signature and length estimation.\n *\n * The returned object contains:\n * 1. `sign` - A function that, when invoked with a transaction and an input index,\n * produces an unlocking script suitable for a P2PKH locked output.\n * 2. `estimateLength` - A function that returns the estimated length of the unlocking script in bytes.\n *\n * @param {PrivateKey} privateKey - The private key used for signing the transaction.\n * @param {'all'|'none'|'single'} signOutputs - The signature scope for outputs.\n * @param {boolean} anyoneCanPay - Flag indicating if the signature allows for other inputs to be added later.\n * @param {number} sourceSatoshis - Optional. The amount being unlocked. Otherwise the input.sourceTransaction is required.\n * @param {Script} lockingScript - Optional. The lockinScript. Otherwise the input.sourceTransaction is required.\n * @returns {Object} - An object containing the `sign` and `estimateLength` functions.\n */\n unlock(privateKey, signOutputs = 'all', anyoneCanPay = false, sourceSatoshis, lockingScript) {\n return {\n sign: async (tx, inputIndex) => {\n let signatureScope = TransactionSignature.SIGHASH_FORKID;\n if (signOutputs === 'all') {\n signatureScope |= TransactionSignature.SIGHASH_ALL;\n }\n if (signOutputs === 'none') {\n signatureScope |= TransactionSignature.SIGHASH_NONE;\n }\n if (signOutputs === 'single') {\n signatureScope |= TransactionSignature.SIGHASH_SINGLE;\n }\n if (anyoneCanPay) {\n signatureScope |= TransactionSignature.SIGHASH_ANYONECANPAY;\n }\n const input = tx.inputs[inputIndex];\n const otherInputs = tx.inputs.filter((_, index) => index !== inputIndex);\n const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex');\n if (sourceTXID == null || sourceTXID === undefined) {\n throw new Error('The input sourceTXID or sourceTransaction is required for transaction signing.');\n }\n if (sourceTXID === '') {\n throw new Error('The input sourceTXID or sourceTransaction is required for transaction signing.');\n }\n sourceSatoshis ||=\n input.sourceTransaction?.outputs[input.sourceOutputIndex].satoshis;\n if (sourceSatoshis == null || sourceSatoshis === undefined) {\n throw new Error('The sourceSatoshis or input sourceTransaction is required for transaction signing.');\n }\n lockingScript ||=\n input.sourceTransaction?.outputs[input.sourceOutputIndex]\n .lockingScript;\n if (lockingScript == null) {\n throw new Error('The lockingScript or input sourceTransaction is required for transaction signing.');\n }\n const preimage = TransactionSignature.format({\n sourceTXID,\n sourceOutputIndex: verifyNotNull(input.sourceOutputIndex, 'input.sourceOutputIndex must have value'),\n sourceSatoshis,\n transactionVersion: tx.version,\n otherInputs,\n inputIndex,\n outputs: tx.outputs,\n inputSequence: verifyNotNull(input.sequence, 'input.sequence must have value'),\n subscript: lockingScript,\n lockTime: tx.lockTime,\n scope: signatureScope\n });\n const rawSignature = privateKey.sign(sha256(preimage));\n const sig = new TransactionSignature(rawSignature.r, rawSignature.s, signatureScope);\n const sigForScript = sig.toChecksigFormat();\n const pubkeyForScript = privateKey\n .toPublicKey()\n .encode(true);\n return new UnlockingScript([\n { op: sigForScript.length, data: sigForScript },\n { op: pubkeyForScript.length, data: pubkeyForScript }\n ]);\n },\n estimateLength: async () => {\n // public key (1+33) + signature (1+73)\n // Note: We add 1 to each element's length because of the associated OP_PUSH\n return 108;\n }\n };\n }\n}\n//# sourceMappingURL=P2PKH.js.map","import OP from '../OP.js';\nimport LockingScript from '../LockingScript.js';\nimport UnlockingScript from '../UnlockingScript.js';\nimport PrivateKey from '../../primitives/PrivateKey.js';\nimport TransactionSignature from '../../primitives/TransactionSignature.js';\nimport { sha256 } from '../../primitives/Hash.js';\nimport Script from '../Script.js';\n/**\n * RPuzzle class implementing ScriptTemplate.\n *\n * This class provides methods to create R Puzzle and R Puzzle Hash locking and unlocking scripts, including the unlocking of UTXOs with the correct K value.\n */\nexport default class RPuzzle {\n type = 'raw';\n /**\n * @constructor\n * Constructs an R Puzzle template instance for a given puzzle type\n *\n * @param {'raw'|'SHA1'|'SHA256'|'HASH256'|'RIPEMD160'|'HASH160'} type Denotes the type of puzzle to create\n */\n constructor(type = 'raw') {\n this.type = type;\n }\n /**\n * Creates an R puzzle locking script for a given R value or R value hash.\n *\n * @param {number[]} value - An array representing the R value or its hash.\n * @returns {LockingScript} - An R puzzle locking script.\n */\n lock(value) {\n const chunks = [\n { op: OP.OP_OVER },\n { op: OP.OP_3 },\n { op: OP.OP_SPLIT },\n { op: OP.OP_NIP },\n { op: OP.OP_1 },\n { op: OP.OP_SPLIT },\n { op: OP.OP_SWAP },\n { op: OP.OP_SPLIT },\n { op: OP.OP_DROP }\n ];\n if (this.type !== 'raw') {\n chunks.push({\n op: OP['OP_' + this.type]\n });\n }\n chunks.push({ op: value.length, data: value });\n chunks.push({ op: OP.OP_EQUALVERIFY });\n chunks.push({ op: OP.OP_CHECKSIG });\n return new LockingScript(chunks);\n }\n /**\n * Creates a function that generates an R puzzle unlocking script along with its signature and length estimation.\n *\n * The returned object contains:\n * 1. `sign` - A function that, when invoked with a transaction and an input index,\n * produces an unlocking script suitable for an R puzzle locked output.\n * 2. `estimateLength` - A function that returns the estimated length of the unlocking script in bytes.\n *\n * @param {BigNumber} k — The K-value used to unlock the R-puzzle.\n * @param {PrivateKey} privateKey - The private key used for signing the transaction. If not provided, a random key will be generated.\n * @param {'all'|'none'|'single'} signOutputs - The signature scope for outputs.\n * @param {boolean} anyoneCanPay - Flag indicating if the signature allows for other inputs to be added later.\n * @returns {Object} - An object containing the `sign` and `estimateLength` functions.\n */\n unlock(k, privateKey, signOutputs = 'all', anyoneCanPay = false) {\n return {\n sign: async (tx, inputIndex) => {\n if (typeof privateKey === 'undefined') {\n privateKey = PrivateKey.fromRandom();\n }\n let signatureScope = TransactionSignature.SIGHASH_FORKID;\n if (signOutputs === 'all') {\n signatureScope |= TransactionSignature.SIGHASH_ALL;\n }\n if (signOutputs === 'none') {\n signatureScope |= TransactionSignature.SIGHASH_NONE;\n }\n if (signOutputs === 'single') {\n signatureScope |= TransactionSignature.SIGHASH_SINGLE;\n }\n if (anyoneCanPay) {\n signatureScope |= TransactionSignature.SIGHASH_ANYONECANPAY;\n }\n const otherInputs = [...tx.inputs];\n const [input] = otherInputs.splice(inputIndex, 1);\n if (typeof input.sourceTransaction !== 'object') {\n throw new Error('The source transaction is needed for transaction signing.');\n }\n const preimage = TransactionSignature.format({\n sourceTXID: input.sourceTransaction?.id('hex') ?? '',\n sourceOutputIndex: input.sourceOutputIndex ?? 0,\n sourceSatoshis: input.sourceTransaction?.outputs[input.sourceOutputIndex]\n ?.satoshis ?? 0,\n transactionVersion: tx.version,\n otherInputs,\n inputIndex,\n outputs: tx.outputs,\n inputSequence: input.sequence ?? 0xffffffff,\n subscript: input.sourceTransaction?.outputs[input.sourceOutputIndex]\n ?.lockingScript ?? new Script(),\n lockTime: tx.lockTime,\n scope: signatureScope\n });\n const rawSignature = privateKey.sign(sha256(preimage), undefined, true, k);\n const sig = new TransactionSignature(rawSignature.r, rawSignature.s, signatureScope);\n const sigForScript = sig.toChecksigFormat();\n const pubkeyForScript = privateKey\n .toPublicKey()\n .encode(true);\n return new UnlockingScript([\n { op: sigForScript.length, data: sigForScript },\n { op: pubkeyForScript.length, data: pubkeyForScript }\n ]);\n },\n estimateLength: async () => {\n // public key (1+33) + signature (1+73)\n // Note: We add 1 to each element's length because of the associated OP_PUSH\n return 108;\n }\n };\n }\n}\n//# sourceMappingURL=RPuzzle.js.map","import { LockingScript, UnlockingScript, OP } from '../index.js';\nimport { Utils, Hash, TransactionSignature, Signature, PublicKey } from '../../primitives/index.js';\nimport { verifyNotNull } from '../../primitives/utils.js';\n/**\n * For a given piece of data to push onto the stack in script, creates the correct minimally-encoded script chunk,\n * including the correct push operation.\n *\n * TODO: This should be made into a TS-SDK util (distinct from the `minimallyEncode` util)\n */\nconst createMinimallyEncodedScriptChunk = (data) => {\n if (data.length === 0) {\n // Could have used OP_0.\n return { op: 0 };\n }\n if (data.length === 1 && data[0] === 0) {\n // Could have used OP_0.\n return { op: 0 };\n }\n if (data.length === 1 && data[0] > 0 && data[0] <= 16) {\n // Could have used OP_0 .. OP_16.\n return { op: 0x50 + data[0] };\n }\n if (data.length === 1 && data[0] === 0x81) {\n // Could have used OP_1NEGATE.\n return { op: 0x4f };\n }\n if (data.length <= 75) {\n // Could have used a direct push (opcode indicating number of bytes\n // pushed + those bytes).\n return { op: data.length, data };\n }\n if (data.length <= 255) {\n // Could have used OP_PUSHDATA.\n return { op: 0x4c, data };\n }\n if (data.length <= 65535) {\n // Could have used OP_PUSHDATA2.\n return { op: 0x4d, data };\n }\n return { op: 0x4e, data };\n};\nexport default class PushDrop {\n wallet;\n originator;\n /**\n * Decodes a PushDrop script back into its token fields and the locking public key. If a signature was present, it will be the last field returned.\n * Warning: Only works with a P2PK lock at the beginning of the script.\n * @param script PushDrop script to decode back into token fields\n * @returns An object containing PushDrop token fields and the locking public key. If a signature was included, it will be the last field.\n */\n static decode(script) {\n const lockingPublicKey = PublicKey.fromString(Utils.toHex(verifyNotNull(script.chunks[0].data, 'script.chunks[0].data must have value')));\n const fields = [];\n for (let i = 2; i < script.chunks.length; i++) {\n const nextOpcode = script.chunks[i + 1]?.op; // ✅ Prevent accessing `op` from `undefined`\n let chunk = script.chunks[i].data ?? []; // ✅ Ensure `chunk` is always `number[]`\n if (chunk.length === 0) {\n // ✅ Only modify `chunk` if it was empty\n if (script.chunks[i].op >= 80 && script.chunks[i].op <= 95) {\n chunk = [script.chunks[i].op - 80];\n }\n else if (script.chunks[i].op === 0) {\n chunk = [0];\n }\n else if (script.chunks[i].op === 0x4f) {\n chunk = [0x81];\n }\n }\n fields.push(chunk);\n // If the next value is DROP or 2DROP then this is the final field\n if (nextOpcode === OP.OP_DROP || nextOpcode === OP.OP_2DROP) {\n break;\n }\n }\n return {\n fields,\n lockingPublicKey\n };\n }\n /**\n * Constructs a new instance of the PushDrop class.\n *\n * @param {WalletInterface} wallet - The wallet interface used for creating signatures and accessing public keys.\n * @param {string} originator — The originator to use with Wallet requests\n */\n constructor(wallet, originator) {\n this.wallet = wallet;\n this.originator = originator;\n }\n /**\n * Creates a PushDrop locking script with arbitrary data fields and a public key lock.\n *\n * @param {number[][]} fields - The token fields to include in the locking script.\n * @param {WalletProtocol} protocolID - The protocol ID to use.\n * @param {string} keyID - The key ID to use.\n * @param {string} counterparty - The counterparty involved in the transaction, \"self\" or \"anyone\".\n * @param {boolean} [forSelf=false] - Flag indicating if the lock is for the creator (default no).\n * @param {boolean} [includeSignature=true] - Flag indicating if a signature should be included in the script (default yes).\n * @returns {Promise<LockingScript>} The generated PushDrop locking script.\n */\n async lock(fields, protocolID, keyID, counterparty, forSelf = false, includeSignature = true, lockPosition = 'before') {\n const { publicKey } = await this.wallet.getPublicKey({\n protocolID,\n keyID,\n counterparty,\n forSelf\n }, this.originator);\n const lockChunks = [];\n const pushDropChunks = [];\n lockChunks.push({\n op: publicKey.length / 2,\n data: Utils.toArray(publicKey, 'hex')\n });\n lockChunks.push({ op: OP.OP_CHECKSIG });\n if (includeSignature) {\n const dataToSign = fields.reduce((a, e) => [...a, ...e], []);\n const { signature } = await this.wallet.createSignature({\n data: dataToSign,\n protocolID,\n keyID,\n counterparty\n }, this.originator);\n fields.push(signature);\n }\n for (const field of fields) {\n pushDropChunks.push(createMinimallyEncodedScriptChunk(field));\n }\n let notYetDropped = fields.length;\n while (notYetDropped > 1) {\n pushDropChunks.push({ op: OP.OP_2DROP });\n notYetDropped -= 2;\n }\n if (notYetDropped !== 0) {\n pushDropChunks.push({ op: OP.OP_DROP });\n }\n if (lockPosition === 'before') {\n return new LockingScript([...lockChunks, ...pushDropChunks]);\n }\n else {\n return new LockingScript([...pushDropChunks, ...lockChunks]);\n }\n }\n /**\n * Creates an unlocking script for spending a PushDrop token output.\n *\n * @param {WalletProtocol} protocolID - The protocol ID to use.\n * @param {string} keyID - The key ID to use.\n * @param {string} counterparty - The counterparty involved in the transaction, \"self\" or \"anyone\".\n * @param {string} [sourceTXID] - The TXID of the source transaction.\n * @param {number} [sourceSatoshis] - The number of satoshis in the source output.\n * @param {LockingScript} [lockingScript] - The locking script of the source output.\n * @param {'all' | 'none' | 'single'} [signOutputs='all'] - Specifies which outputs to sign.\n * @param {boolean} [anyoneCanPay=false] - Specifies if the anyone-can-pay flag is set.\n * @returns {Object} An object containing functions to sign the transaction and estimate the script length.\n */\n unlock(protocolID, keyID, counterparty, signOutputs = 'all', anyoneCanPay = false, sourceSatoshis, lockingScript) {\n return {\n sign: async (tx, inputIndex) => {\n let signatureScope = TransactionSignature.SIGHASH_FORKID;\n if (signOutputs === 'all') {\n signatureScope |= TransactionSignature.SIGHASH_ALL;\n }\n if (signOutputs === 'none') {\n signatureScope |= TransactionSignature.SIGHASH_NONE;\n }\n if (signOutputs === 'single') {\n signatureScope |= TransactionSignature.SIGHASH_SINGLE;\n }\n if (anyoneCanPay) {\n signatureScope |= TransactionSignature.SIGHASH_ANYONECANPAY;\n }\n const input = tx.inputs[inputIndex];\n const otherInputs = tx.inputs.filter((_, index) => index !== inputIndex);\n const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex');\n if (sourceTXID == null || sourceTXID === undefined) {\n throw new Error('The input sourceTXID or sourceTransaction is required for transaction signing.');\n }\n sourceSatoshis ||=\n input.sourceTransaction?.outputs[input.sourceOutputIndex].satoshis;\n if (sourceSatoshis == null || sourceSatoshis === undefined) {\n throw new Error('The sourceSatoshis or input sourceTransaction is required for transaction signing.');\n }\n lockingScript ||=\n input.sourceTransaction?.outputs[input.sourceOutputIndex]\n .lockingScript;\n if (lockingScript == null) {\n throw new Error('The lockingScript or input sourceTransaction is required for transaction signing.');\n }\n const preimage = TransactionSignature.format({\n sourceTXID,\n sourceOutputIndex: verifyNotNull(input.sourceOutputIndex, 'input.sourceOutputIndex must have value'),\n sourceSatoshis,\n transactionVersion: tx.version,\n otherInputs,\n inputIndex,\n outputs: tx.outputs,\n inputSequence: input.sequence ?? 0xffffffff,\n subscript: lockingScript,\n lockTime: tx.lockTime,\n scope: signatureScope\n });\n const preimageHash = Hash.sha256(preimage);\n const { signature: bareSignature } = await this.wallet.createSignature({\n data: preimageHash,\n protocolID,\n keyID,\n counterparty\n }, this.originator);\n const signature = Signature.fromDER([...bareSignature]);\n const txSignature = new TransactionSignature(signature.r, signature.s, signatureScope);\n const sigForScript = txSignature.toChecksigFormat();\n return new UnlockingScript([\n { op: sigForScript.length, data: sigForScript }\n ]);\n },\n estimateLength: async () => 73\n };\n }\n}\n//# sourceMappingURL=PushDrop.js.map","/**\n * Represents the \"satoshis per kilobyte\" transaction fee model.\n */\nexport default class SatoshisPerKilobyte {\n /**\n * @property\n * Denotes the number of satoshis paid per kilobyte of transaction size.\n */\n value;\n /**\n * Constructs an instance of the sat/kb fee model.\n *\n * @param {number} value - The number of satoshis per kilobyte to charge as a fee.\n */\n constructor(value) {\n this.value = value;\n }\n /**\n * Computes the fee for a given transaction.\n *\n * @param tx The transaction for which a fee is to be computed.\n * @returns The fee in satoshis for the transaction, as a BigNumber.\n */\n async computeFee(tx) {\n const getVarIntSize = (i) => {\n if (i > 2 ** 32) {\n return 9;\n }\n else if (i > 2 ** 16) {\n return 5;\n }\n else if (i > 253) {\n return 3;\n }\n else {\n return 1;\n }\n };\n // Compute the (potentially estimated) size of the transaction\n let size = 4; // version\n size += getVarIntSize(tx.inputs.length); // number of inputs\n for (let i = 0; i < tx.inputs.length; i++) {\n const input = tx.inputs[i];\n size += 40; // txid, output index, sequence number\n let scriptLength;\n if (typeof input.unlockingScript === 'object') {\n scriptLength = input.unlockingScript.toBinary().length;\n }\n else if (typeof input.unlockingScriptTemplate === 'object') {\n scriptLength = await input.unlockingScriptTemplate.estimateLength(tx, i);\n }\n else {\n throw new Error('All inputs must have an unlocking script or an unlocking script template for sat/kb fee computation.');\n }\n size += getVarIntSize(scriptLength); // unlocking script length\n size += scriptLength; // unlocking script\n }\n size += getVarIntSize(tx.outputs.length); // number of outputs\n for (const out of tx.outputs) {\n size += 8; // satoshis\n const length = out.lockingScript.toBinary().length;\n size += getVarIntSize(length); // script length\n size += length; // script\n }\n size += 4; // lock time\n // We'll use Math.ceil to ensure the miners get the extra satoshi.\n const fee = Math.ceil((size / 1000) * this.value);\n return fee;\n }\n}\n//# sourceMappingURL=SatoshisPerKilobyte.js.map","import SatoshisPerKilobyte from './SatoshisPerKilobyte.js';\n/**\n * Represents a live fee policy that fetches current rates from ARC GorillaPool.\n * Extends SatoshisPerKilobyte to reuse transaction size calculation logic.\n */\nexport default class LivePolicy extends SatoshisPerKilobyte {\n static ARC_POLICY_URL = 'https://arc.gorillapool.io/v1/policy';\n static instance = null;\n cachedRate = null;\n cacheTimestamp = 0;\n cacheValidityMs;\n /**\n * Constructs an instance of the live policy fee model.\n *\n * @param {number} cacheValidityMs - How long to cache the fee rate in milliseconds (default: 5 minutes)\n */\n constructor(cacheValidityMs = 5 * 60 * 1000) {\n super(100); // Initialize with dummy value, will be overridden by fetchFeeRate\n this.cacheValidityMs = cacheValidityMs;\n }\n /**\n * Gets the singleton instance of LivePolicy to ensure cache sharing across the application.\n *\n * @param {number} cacheValidityMs - How long to cache the fee rate in milliseconds (default: 5 minutes)\n * @returns The singleton LivePolicy instance\n */\n static getInstance(cacheValidityMs = 5 * 60 * 1000) {\n if (!LivePolicy.instance) {\n LivePolicy.instance = new LivePolicy(cacheValidityMs);\n }\n return LivePolicy.instance;\n }\n /**\n * Fetches the current fee rate from ARC GorillaPool API.\n *\n * @returns The current satoshis per kilobyte rate\n */\n async fetchFeeRate() {\n const now = Date.now();\n // Return cached rate if still valid\n if (this.cachedRate !== null && (now - this.cacheTimestamp) < this.cacheValidityMs) {\n return this.cachedRate;\n }\n try {\n const response = await fetch(LivePolicy.ARC_POLICY_URL);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n const response_data = await response.json();\n if (!response_data.policy?.miningFee || typeof response_data.policy.miningFee.satoshis !== 'number' || typeof response_data.policy.miningFee.bytes !== 'number') {\n throw new Error('Invalid policy response format');\n }\n // Convert to satoshis per kilobyte\n const rate = (response_data.policy.miningFee.satoshis / response_data.policy.miningFee.bytes) * 1000;\n // Cache the result\n this.cachedRate = rate;\n this.cacheTimestamp = now;\n return rate;\n }\n catch (error) {\n // If we have a cached rate, use it as fallback\n if (this.cachedRate !== null) {\n console.warn('Failed to fetch live fee rate, using cached value:', error);\n return this.cachedRate;\n }\n // Otherwise, use a reasonable default (100 sat/kb)\n console.warn('Failed to fetch live fee rate, using default 100 sat/kb:', error);\n return 100;\n }\n }\n /**\n * Computes the fee for a given transaction using the current live rate.\n * Overrides the parent method to use dynamic rate fetching.\n *\n * @param tx The transaction for which a fee is to be computed.\n * @returns The fee in satoshis for the transaction.\n */\n async computeFee(tx) {\n const rate = await this.fetchFeeRate();\n // Update the value property so parent's computeFee uses the live rate\n this.value = rate;\n return super.computeFee(tx);\n }\n}\n//# sourceMappingURL=LivePolicy.js.map","/**\n * Adapter for Node Https module to be used as HttpClient\n */\nexport class NodejsHttpClient {\n https;\n constructor(https) {\n this.https = https;\n }\n async request(url, requestOptions) {\n return await new Promise((resolve, reject) => {\n const req = this.https.request(url, requestOptions, (res) => {\n let body = '';\n res.on('data', (chunk) => {\n body += chunk;\n });\n res.on('end', () => {\n const ok = res.statusCode >= 200 && res.statusCode <= 299;\n const mediaType = res.headers['content-type'];\n const data = body !== '' && typeof mediaType === 'string' && mediaType.startsWith('application/json')\n ? JSON.parse(body)\n : body;\n resolve({\n status: res.statusCode,\n statusText: res.statusMessage,\n ok,\n data\n });\n });\n });\n req.on('error', (error) => {\n reject(error);\n });\n if (requestOptions.data !== null && requestOptions.data !== undefined) {\n req.write(JSON.stringify(requestOptions.data));\n }\n req.end();\n });\n }\n}\n//# sourceMappingURL=NodejsHttpClient.js.map","/**\n * Adapter for Node Https module to be used as HttpClient\n */\nexport class FetchHttpClient {\n fetch;\n constructor(fetch) {\n this.fetch = fetch;\n }\n async request(url, options) {\n const fetchOptions = {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.data)\n };\n const res = await this.fetch(url, fetchOptions);\n const mediaType = res.headers.get('Content-Type');\n const data = mediaType?.startsWith('application/json') ?? false\n ? await res.json()\n : await res.text();\n return {\n ok: res.ok,\n status: res.status,\n statusText: res.statusText,\n data: data\n };\n }\n}\n//# sourceMappingURL=FetchHttpClient.js.map","import { NodejsHttpClient } from './NodejsHttpClient.js';\nimport { FetchHttpClient } from './FetchHttpClient.js';\n/**\n * Returns a default HttpClient implementation based on the environment that it is run on.\n * This method will attempt to use `window.fetch` if available (in browser environments).\n * If running in a Node environment, it falls back to using the Node `https` module\n */\nexport function defaultHttpClient() {\n const noHttpClient = {\n async request(..._) {\n throw new Error('No method available to perform HTTP request');\n }\n };\n if (typeof window !== 'undefined' && typeof window.fetch === 'function') {\n // Use fetch in a browser environment\n return new FetchHttpClient(window.fetch.bind(window));\n }\n else if (typeof require !== 'undefined') {\n // Use Node https module\n // eslint-disable-next-line\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const https = require('https');\n return new NodejsHttpClient(https);\n }\n catch (e) {\n return noHttpClient;\n }\n }\n else {\n return noHttpClient;\n }\n}\n//# sourceMappingURL=DefaultHttpClient.js.map","import { defaultHttpClient } from '../http/DefaultHttpClient.js';\nimport Random from '../../primitives/Random.js';\nimport { toHex } from '../../primitives/utils.js';\nfunction defaultDeploymentId() {\n return `ts-sdk-${toHex(Random(16))}`;\n}\n/**\n * Represents an ARC transaction broadcaster.\n */\nexport default class ARC {\n URL;\n apiKey;\n deploymentId;\n callbackUrl;\n callbackToken;\n headers;\n httpClient;\n constructor(URL, config) {\n this.URL = URL;\n if (typeof config === 'string') {\n this.apiKey = config;\n this.httpClient = defaultHttpClient();\n this.deploymentId = defaultDeploymentId();\n this.callbackToken = undefined;\n this.callbackUrl = undefined;\n }\n else {\n const configObj = config ?? {};\n const { apiKey, deploymentId, httpClient, callbackToken, callbackUrl, headers } = configObj;\n this.apiKey = apiKey;\n this.httpClient = httpClient ?? defaultHttpClient();\n this.deploymentId = deploymentId ?? defaultDeploymentId();\n this.callbackToken = callbackToken;\n this.callbackUrl = callbackUrl;\n this.headers = headers;\n }\n }\n /**\n * Constructs a dictionary of the default & supplied request headers.\n */\n requestHeaders() {\n const headers = {\n 'Content-Type': 'application/json',\n 'XDeployment-ID': this.deploymentId\n };\n if (this.apiKey != null && this.apiKey !== '') {\n headers.Authorization = `Bearer ${this.apiKey}`;\n }\n if (this.callbackUrl != null && this.callbackUrl !== '') {\n headers['X-CallbackUrl'] = this.callbackUrl;\n }\n if (this.callbackToken != null && this.callbackToken !== '') {\n headers['X-CallbackToken'] = this.callbackToken;\n }\n if (this.headers != null) {\n for (const key in this.headers) {\n headers[key] = this.headers[key];\n }\n }\n return headers;\n }\n /**\n * Broadcasts a transaction via ARC.\n *\n * @param {Transaction} tx - The transaction to be broadcasted.\n * @returns {Promise<BroadcastResponse | BroadcastFailure>} A promise that resolves to either a success or failure response.\n */\n async broadcast(tx) {\n let rawTx;\n try {\n rawTx = tx.toHexEF();\n }\n catch (error) {\n if (error.message ===\n 'All inputs must have source transactions when serializing to EF format') {\n rawTx = tx.toHex();\n }\n else {\n throw error;\n }\n }\n const requestOptions = {\n method: 'POST',\n headers: this.requestHeaders(),\n data: { rawTx }\n };\n try {\n const response = await this.httpClient.request(`${this.URL}/v1/tx`, requestOptions);\n if (response.ok) {\n const { txid, extraInfo, txStatus, competingTxs } = response.data;\n const broadcastRes = {\n status: 'success',\n txid,\n message: `${txStatus} ${extraInfo}`\n };\n if (competingTxs != null) {\n broadcastRes.competingTxs = competingTxs;\n }\n return broadcastRes;\n }\n else {\n const st = typeof response.status;\n const r = {\n status: 'error',\n code: st === 'number' || st === 'string'\n ? response.status.toString()\n : 'ERR_UNKNOWN',\n description: 'Unknown error'\n };\n let d = response.data;\n if (typeof d === 'string') {\n try {\n d = JSON.parse(response.data);\n }\n catch {\n // Intentionally left empty\n }\n }\n if (typeof d === 'object') {\n if (d !== null) {\n r.more = d;\n }\n if ((d != null) && typeof d.txid === 'string') {\n r.txid = d.txid;\n }\n if ((d != null) && 'detail' in d && typeof d.detail === 'string') {\n r.description = d.detail;\n }\n }\n return r;\n }\n }\n catch (error) {\n return {\n status: 'error',\n code: '500',\n description: typeof error.message === 'string'\n ? error.message\n : 'Internal Server Error'\n };\n }\n }\n /**\n * Broadcasts multiple transactions via ARC.\n * Handles mixed responses where some transactions succeed and others fail.\n *\n * @param {Transaction[]} txs - Array of transactions to be broadcasted.\n * @returns {Promise<Array<object>>} A promise that resolves to an array of objects.\n */\n async broadcastMany(txs) {\n const rawTxs = txs.map((tx) => {\n try {\n return { rawTx: tx.toHexEF() };\n }\n catch (error) {\n if (error.message ===\n 'All inputs must have source transactions when serializing to EF format') {\n return { rawTx: tx.toHex() };\n }\n throw error;\n }\n });\n const requestOptions = {\n method: 'POST',\n headers: this.requestHeaders(),\n data: rawTxs\n };\n try {\n const response = await this.httpClient.request(`${this.URL}/v1/txs`, requestOptions);\n return response.data;\n }\n catch (error) {\n const errorResponse = {\n status: 'error',\n code: '500',\n description: typeof error.message === 'string' ? error.message : 'Internal Server Error'\n };\n return txs.map(() => errorResponse);\n }\n }\n}\n//# sourceMappingURL=ARC.js.map","import ARC from './ARC.js';\nexport function defaultBroadcaster(isTestnet = false, config = {}) {\n return new ARC(isTestnet ? 'https://testnet.arc.gorillapool.io' : 'https://arc.gorillapool.io', config);\n}\n//# sourceMappingURL=DefaultBroadcaster.js.map","import { defaultHttpClient } from '../http/DefaultHttpClient.js';\n/**\n * Represents a chain tracker based on What's On Chain .\n */\nexport default class WhatsOnChain {\n network;\n apiKey;\n URL;\n httpClient;\n /**\n * Constructs an instance of the WhatsOnChain ChainTracker.\n *\n * @param {'main' | 'test' | 'stn'} network - The BSV network to use when calling the WhatsOnChain API.\n * @param {WhatsOnChainConfig} config - Configuration options for the WhatsOnChain ChainTracker.\n */\n constructor(network = 'main', config = {}) {\n const { apiKey, httpClient } = config;\n this.network = network;\n this.URL = `https://api.whatsonchain.com/v1/bsv/${network}`;\n this.httpClient = httpClient ?? defaultHttpClient();\n this.apiKey = apiKey ?? '';\n }\n async isValidRootForHeight(root, height) {\n const requestOptions = {\n method: 'GET',\n headers: this.getHttpHeaders()\n };\n const response = await this.httpClient.request(`${this.URL}/block/${height}/header`, requestOptions);\n if (response.ok) {\n const { merkleroot } = response.data;\n return merkleroot === root;\n }\n else if (response.status === 404) {\n return false;\n }\n else {\n throw new Error(`Failed to verify merkleroot for height ${height} because of an error: ${JSON.stringify(response.data)} `);\n }\n }\n async currentHeight() {\n try {\n const requestOptions = {\n method: 'GET',\n headers: this.getHttpHeaders()\n };\n const response = await this.httpClient.request(`${this.URL}/block/headers`, requestOptions);\n if (response.ok) {\n return response.data[0].height;\n }\n else {\n throw new Error(`Failed to get current height because of an error: ${JSON.stringify(response.data)} `);\n }\n }\n catch (error) {\n throw new Error(`Failed to get current height because of an error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n getHttpHeaders() {\n const headers = {\n Accept: 'application/json'\n };\n if (typeof this.apiKey === 'string' && this.apiKey.trim() !== '') {\n headers.Authorization = this.apiKey;\n }\n return headers;\n }\n}\n//# sourceMappingURL=WhatsOnChain.js.map","import WhatsOnChain from './WhatsOnChain.js';\nexport function defaultChainTracker() {\n return new WhatsOnChain();\n}\n//# sourceMappingURL=DefaultChainTracker.js.map","import { Reader, Writer, toHex, toArray } from '../primitives/utils.js';\nimport { hash256 } from '../primitives/Hash.js';\n/**\n * Represents a Merkle Path, which is used to provide a compact proof of inclusion for a\n * transaction in a block. This class encapsulates all the details required for creating\n * and verifying Merkle Proofs.\n *\n * @class MerklePath\n * @property {number} blockHeight - The height of the block in which the transaction is included.\n * @property {Array<Array<{offset: number, hash?: string, txid?: boolean, duplicate?: boolean}>>} path -\n * A tree structure representing the Merkle Path, with each level containing information\n * about the nodes involved in constructing the proof.\n *\n * @example\n * // Creating and verifying a Merkle Path\n * const merklePath = MerklePath.fromHex('...');\n * const isValid = merklePath.verify(txid, chainTracker);\n *\n * @description\n * The MerklePath class is useful for verifying transactions in a lightweight and efficient manner without\n * needing the entire block data. This class offers functionalities for creating, converting,\n * and verifying these proofs.\n */\nexport default class MerklePath {\n blockHeight;\n path;\n /**\n * Creates a MerklePath instance from a hexadecimal string.\n *\n * @static\n * @param {string} hex - The hexadecimal string representation of the Merkle Path.\n * @returns {MerklePath} - A new MerklePath instance.\n */\n static fromHex(hex) {\n return MerklePath.fromBinary(toArray(hex, 'hex'));\n }\n static fromReader(reader, legalOffsetsOnly = true) {\n const blockHeight = reader.readVarIntNum();\n const treeHeight = reader.readUInt8();\n // Explicitly define the type of path as an array of arrays of leaf objects\n const path = Array(treeHeight)\n .fill(null)\n .map(() => []);\n let flags, offset, nLeavesAtThisHeight;\n for (let level = 0; level < treeHeight; level++) {\n nLeavesAtThisHeight = reader.readVarIntNum();\n while (nLeavesAtThisHeight > 0) {\n offset = reader.readVarIntNum();\n flags = reader.readUInt8();\n const leaf = { offset };\n if ((flags & 1) !== 0) {\n leaf.duplicate = true;\n }\n else {\n if ((flags & 2) !== 0) {\n leaf.txid = true;\n }\n leaf.hash = toHex(reader.read(32).reverse());\n }\n // Ensure path[level] exists before pushing\n if (!Array.isArray(path[level]) || path[level].length === 0) {\n path[level] = [];\n }\n path[level].push(leaf);\n nLeavesAtThisHeight--;\n }\n // Sort the array based on the offset property\n path[level].sort((a, b) => a.offset - b.offset);\n }\n return new MerklePath(blockHeight, path, legalOffsetsOnly);\n }\n /**\n * Creates a MerklePath instance from a binary array.\n *\n * @static\n * @param {number[]} bump - The binary array representation of the Merkle Path.\n * @returns {MerklePath} - A new MerklePath instance.\n */\n static fromBinary(bump) {\n const reader = new Reader(bump);\n return MerklePath.fromReader(reader);\n }\n /**\n *\n * @static fromCoinbaseTxid\n *\n * Creates a MerklePath instance for a coinbase transaction in an empty block.\n * This edge case is difficult to retrieve from standard APIs.\n *\n * @param {string} txid - The coinbase txid.\n * @param {number} height - The height of the block.\n * @returns {MerklePath} - A new MerklePath instance which assumes the tx is in a block with no other transactions.\n */\n static fromCoinbaseTxidAndHeight(txid, height) {\n return new MerklePath(height, [[{ offset: 0, hash: txid, txid: true }]]);\n }\n constructor(blockHeight, path, legalOffsetsOnly = true) {\n this.blockHeight = blockHeight;\n this.path = path;\n // store all of the legal offsets which we expect given the txid indices.\n const legalOffsets = Array(this.path.length)\n .fill(0)\n .map(() => new Set());\n this.path.forEach((leaves, height) => {\n if (leaves.length === 0 && height === 0) {\n throw new Error(`Empty level at height: ${height}`);\n }\n const offsetsAtThisHeight = new Set();\n leaves.forEach((leaf) => {\n if (offsetsAtThisHeight.has(leaf.offset)) {\n throw new Error(`Duplicate offset: ${leaf.offset}, at height: ${height}`);\n }\n offsetsAtThisHeight.add(leaf.offset);\n if (height === 0) {\n if (leaf.duplicate !== true) {\n for (let h = 1; h < this.path.length; h++) {\n legalOffsets[h].add((leaf.offset >> h) ^ 1);\n }\n }\n }\n else {\n if (legalOffsetsOnly && !legalOffsets[height].has(leaf.offset)) {\n throw new Error(`Invalid offset: ${leaf.offset}, at height: ${height}, with legal offsets: ${Array.from(legalOffsets[height]).join(', ')}`);\n }\n }\n });\n });\n // every txid must calculate to the same root.\n let root;\n this.path[0].forEach((leaf, idx) => {\n if (idx === 0)\n root = this.computeRoot(leaf.hash);\n if (root !== this.computeRoot(leaf.hash)) {\n throw new Error('Mismatched roots');\n }\n });\n }\n /**\n * Converts the MerklePath to a binary array format.\n *\n * @returns {number[]} - The binary array representation of the Merkle Path.\n */\n toBinary() {\n const writer = new Writer();\n writer.writeVarIntNum(this.blockHeight);\n const treeHeight = this.path.length;\n writer.writeUInt8(treeHeight);\n for (let level = 0; level < treeHeight; level++) {\n const nLeaves = Object.keys(this.path[level]).length;\n writer.writeVarIntNum(nLeaves);\n for (const leaf of this.path[level]) {\n writer.writeVarIntNum(leaf.offset);\n let flags = 0;\n if (leaf?.duplicate === true) {\n flags |= 1;\n }\n if (leaf?.txid !== undefined && leaf.txid !== null) {\n flags |= 2;\n }\n writer.writeUInt8(flags);\n if ((flags & 1) === 0) {\n writer.write(toArray(leaf.hash, 'hex').reverse());\n }\n }\n }\n return writer.toArray();\n }\n /**\n * Converts the MerklePath to a hexadecimal string format.\n *\n * @returns {string} - The hexadecimal string representation of the Merkle Path.\n */\n toHex() {\n return toHex(this.toBinary());\n }\n //\n indexOf(txid) {\n const leaf = this.path[0].find((l) => l.hash === txid);\n if (leaf === null || leaf === undefined) {\n throw new Error(`Transaction ID ${txid} not found in the Merkle Path`);\n }\n return leaf.offset;\n }\n /**\n * Computes the Merkle root from the provided transaction ID.\n *\n * @param {string} txid - The transaction ID to compute the Merkle root for. If not provided, the root will be computed from an unspecified branch, and not all branches will be validated!\n * @returns {string} - The computed Merkle root as a hexadecimal string.\n * @throws {Error} - If the transaction ID is not part of the Merkle Path.\n */\n computeRoot(txid) {\n if (typeof txid !== 'string') {\n const foundLeaf = this.path[0].find((leaf) => Boolean(leaf?.hash));\n if (foundLeaf === null || foundLeaf === undefined) {\n throw new Error('No valid leaf found in the Merkle Path');\n }\n txid = foundLeaf.hash;\n }\n // Find the index of the txid at the lowest level of the Merkle tree\n if (typeof txid !== 'string') {\n throw new Error('Transaction ID is undefined');\n }\n const index = this.indexOf(txid);\n if (typeof index !== 'number') {\n throw new Error(`This proof does not contain the txid: ${txid ?? 'undefined'}`);\n }\n // Calculate the root using the index as a way to determine which direction to concatenate.\n const hash = (m) => toHex(hash256(toArray(m, 'hex').reverse()).reverse());\n let workingHash = txid;\n // special case for blocks with only one transaction\n if (this.path.length === 1 && this.path[0].length === 1)\n return workingHash;\n for (let height = 0; height < this.path.length; height++) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const leaves = this.path[height];\n const offset = (index >> height) ^ 1;\n const leaf = this.findOrComputeLeaf(height, offset);\n if (typeof leaf !== 'object') {\n throw new Error(`Missing hash for index ${index} at height ${height}`);\n }\n if (leaf.duplicate === true) {\n workingHash = hash((workingHash ?? '') + (workingHash ?? ''));\n }\n else if (offset % 2 !== 0) {\n workingHash = hash((leaf.hash ?? '') + (workingHash ?? ''));\n }\n else {\n workingHash = hash((workingHash ?? '') + (leaf.hash ?? ''));\n }\n }\n return workingHash;\n }\n /**\n * Find leaf with `offset` at `height` or compute from level below, recursively.\n *\n * Does not add computed leaves to path.\n *\n * @param height\n * @param offset\n */\n findOrComputeLeaf(height, offset) {\n const hash = (m) => toHex(hash256(toArray(m, 'hex').reverse()).reverse());\n let leaf = this.path[height].find((l) => l.offset === offset);\n if (leaf != null)\n return leaf;\n if (height === 0)\n return undefined;\n const h = height - 1;\n const l = offset << 1;\n const leaf0 = this.findOrComputeLeaf(h, l);\n if (leaf0 == null || leaf0.hash == null || leaf0.hash === '')\n return undefined;\n const leaf1 = this.findOrComputeLeaf(h, l + 1);\n if (leaf1 == null)\n return undefined;\n let workinghash;\n if (leaf1.duplicate === true) {\n workinghash = hash(leaf0.hash + leaf0.hash);\n }\n else {\n workinghash = hash((leaf1.hash ?? '') + (leaf0.hash ?? ''));\n }\n leaf = {\n offset,\n hash: workinghash\n };\n return leaf;\n }\n /**\n * Verifies if the given transaction ID is part of the Merkle tree at the specified block height.\n *\n * @param {string} txid - The transaction ID to verify.\n * @param {ChainTracker} chainTracker - The ChainTracker instance used to verify the Merkle root.\n * @returns {boolean} - True if the transaction ID is valid within the Merkle Path at the specified block height.\n */\n async verify(txid, chainTracker) {\n const root = this.computeRoot(txid);\n if (this.indexOf(txid) === 0) {\n // Coinbase transaction outputs can only be spent once they're 100 blocks deep.\n const height = await chainTracker.currentHeight();\n if (this.blockHeight + 100 < height) {\n return false;\n }\n }\n // Use the chain tracker to determine whether this is a valid merkle root at the given block height\n return await chainTracker.isValidRootForHeight(root, this.blockHeight);\n }\n /**\n * Combines this MerklePath with another to create a compound proof.\n *\n * @param {MerklePath} other - Another MerklePath to combine with this path.\n * @throws {Error} - If the paths have different block heights or roots.\n */\n combine(other) {\n if (this.blockHeight !== other.blockHeight) {\n throw new Error('You cannot combine paths which do not have the same block height.');\n }\n const root1 = this.computeRoot();\n const root2 = other.computeRoot();\n if (root1 !== root2) {\n throw new Error('You cannot combine paths which do not have the same root.');\n }\n const combinedPath = [];\n for (let h = 0; h < this.path.length; h++) {\n combinedPath.push([]);\n for (let l = 0; l < this.path[h].length; l++) {\n combinedPath[h].push(this.path[h][l]);\n }\n for (let l = 0; l < other.path[h].length; l++) {\n if (combinedPath[h].find((leaf) => leaf.offset === other.path[h][l].offset) === undefined) {\n combinedPath[h].push(other.path[h][l]);\n }\n else {\n // Ensure that any elements which appear in both are not downgraded to a non txid.\n if (other.path[h][l]?.txid !== undefined && other.path[h][l]?.txid !== null) {\n const target = combinedPath[h].find((leaf) => leaf.offset === other.path[h][l].offset);\n if (target !== null && target !== undefined) {\n target.txid = true;\n }\n }\n }\n }\n }\n this.path = combinedPath;\n this.trim();\n }\n /**\n * Remove all internal nodes that are not required by level zero txid nodes.\n * Assumes that at least all required nodes are present.\n * Leaves all levels sorted by increasing offset.\n */\n trim() {\n const pushIfNew = (v, a) => {\n if (a.length === 0 || a.slice(-1)[0] !== v) {\n a.push(v);\n }\n };\n const dropOffsetsFromLevel = (dropOffsets, level) => {\n for (let i = dropOffsets.length; i >= 0; i--) {\n const l = this.path[level].findIndex((n) => n.offset === dropOffsets[i]);\n if (l >= 0) {\n this.path[level].splice(l, 1);\n }\n }\n };\n const nextComputedOffsets = (cos) => {\n const ncos = [];\n for (const o of cos) {\n pushIfNew(o >> 1, ncos);\n }\n return ncos;\n };\n let computedOffsets = []; // in next level\n let dropOffsets = [];\n for (let h = 0; h < this.path.length; h++) {\n // Sort each level by increasing offset order\n this.path[h].sort((a, b) => a.offset - b.offset);\n }\n for (let l = 0; l < this.path[0].length; l++) {\n const n = this.path[0][l];\n if (n.txid === true) {\n // level 0 must enable computing level 1 for txid nodes\n pushIfNew(n.offset >> 1, computedOffsets);\n }\n else {\n const isOdd = n.offset % 2 === 1;\n const peer = this.path[0][l + (isOdd ? -1 : 1)];\n if (peer.txid === undefined || peer.txid === null || !peer.txid) {\n // drop non-txid level 0 nodes without a txid peer\n pushIfNew(peer.offset, dropOffsets);\n }\n }\n }\n dropOffsetsFromLevel(dropOffsets, 0);\n for (let h = 1; h < this.path.length; h++) {\n dropOffsets = computedOffsets;\n computedOffsets = nextComputedOffsets(computedOffsets);\n dropOffsetsFromLevel(dropOffsets, h);\n }\n }\n}\n//# sourceMappingURL=MerklePath.js.map","import { hash256 } from '../primitives/Hash.js';\nimport { toHex, toArray } from '../primitives/utils.js';\nimport Transaction from './Transaction.js';\nimport { BEEF_V2, TX_DATA_FORMAT } from './Beef.js';\n/**\n * A single bitcoin transaction associated with a `Beef` validity proof set.\n *\n * Simple case is transaction data included directly, either as raw bytes or fully parsed data, or both.\n *\n * Supports 'known' transactions which are represented by just their txid.\n * It is assumed that intended consumer of this beef already has validity proof for such a transaction,\n * which they can merge if necessary to create a valid beef.\n */\nexport default class BeefTx {\n _bumpIndex;\n _tx;\n _rawTx;\n _txid;\n inputTxids = [];\n /**\n * true if `hasProof` or all inputs chain to `hasProof`.\n *\n * Typically set by sorting transactions by proven dependency chains.\n */\n isValid = undefined;\n get bumpIndex() {\n return this._bumpIndex;\n }\n set bumpIndex(v) {\n this._bumpIndex = v;\n this.updateInputTxids();\n }\n get hasProof() {\n return this._bumpIndex !== undefined;\n }\n get isTxidOnly() {\n return this._txid !== undefined && this._txid !== null && (this._rawTx == null) && (this._tx == null);\n }\n get txid() {\n if (this._txid !== undefined && this._txid !== null && this._txid !== '')\n return this._txid;\n if (this._tx != null) {\n this._txid = this._tx.id('hex');\n return this._txid;\n }\n if (this._rawTx != null) {\n this._txid = toHex(hash256(this._rawTx));\n return this._txid;\n }\n throw new Error('Internal');\n }\n get tx() {\n if (this._tx != null)\n return this._tx;\n if (this._rawTx != null) {\n this._tx = Transaction.fromBinary(this._rawTx);\n return this._tx;\n }\n return undefined;\n }\n get rawTx() {\n if (this._rawTx != null)\n return this._rawTx;\n if (this._tx != null) {\n this._rawTx = this._tx.toBinary();\n return this._rawTx;\n }\n return undefined;\n }\n /**\n * @param tx If string, must be a valid txid. If `number[]` must be a valid serialized transaction.\n * @param bumpIndex If transaction already has a proof in the beef to which it will be added.\n */\n constructor(tx, bumpIndex) {\n if (typeof tx === 'string') {\n this._txid = tx;\n }\n else if (Array.isArray(tx)) {\n this._rawTx = tx;\n }\n else {\n this._tx = tx;\n }\n this.bumpIndex = bumpIndex;\n this.updateInputTxids();\n }\n static fromTx(tx, bumpIndex) {\n return new BeefTx(tx, bumpIndex);\n }\n static fromRawTx(rawTx, bumpIndex) {\n return new BeefTx(rawTx, bumpIndex);\n }\n static fromTxid(txid, bumpIndex) {\n return new BeefTx(txid, bumpIndex);\n }\n updateInputTxids() {\n if (this.hasProof || (this.tx == null)) {\n // If we have a proof, or don't have a parsed transaction\n this.inputTxids = [];\n }\n else {\n const inputTxids = {}; // ✅ Explicit object type\n for (const input of this.tx.inputs) {\n if (input.sourceTXID !== undefined && input.sourceTXID !== null && input.sourceTXID !== '') {\n // ✅ Ensure sourceTXID is defined\n inputTxids[input.sourceTXID] = true;\n }\n }\n this.inputTxids = Object.keys(inputTxids);\n }\n }\n toWriter(writer, version) {\n const writeByte = (bb) => {\n writer.writeUInt8(bb);\n };\n const writeTxid = () => {\n if (this._txid == null) {\n throw new Error('Transaction ID (_txid) is undefined');\n }\n writer.writeReverse(toArray(this._txid, 'hex'));\n };\n const writeTx = () => {\n if (this._rawTx != null) {\n writer.write(this._rawTx);\n }\n else if (this._tx != null) {\n writer.write(this._tx.toUint8Array());\n }\n else {\n throw new Error('a valid serialized Transaction is expected');\n }\n };\n const writeBumpIndex = () => {\n if (this.bumpIndex === undefined) {\n writeByte(TX_DATA_FORMAT.RAWTX); // 0\n }\n else {\n writeByte(TX_DATA_FORMAT.RAWTX_AND_BUMP_INDEX); // 1\n writer.writeVarIntNum(this.bumpIndex); // the index of the associated bump\n }\n };\n if (version === BEEF_V2) {\n if (this.isTxidOnly) {\n writeByte(TX_DATA_FORMAT.TXID_ONLY);\n writeTxid();\n }\n else if (this.bumpIndex !== undefined) {\n writeByte(TX_DATA_FORMAT.RAWTX_AND_BUMP_INDEX);\n writer.writeVarIntNum(this.bumpIndex);\n writeTx();\n }\n else {\n writeByte(TX_DATA_FORMAT.RAWTX);\n writeTx();\n }\n }\n else {\n writeTx();\n writeBumpIndex();\n }\n }\n static fromReader(br, version) {\n let data;\n let bumpIndex;\n let beefTx;\n if (version === BEEF_V2) {\n // V2\n const format = br.readUInt8();\n if (format === TX_DATA_FORMAT.TXID_ONLY) {\n beefTx = BeefTx.fromTxid(toHex(br.readReverse(32)));\n }\n else {\n if (format === TX_DATA_FORMAT.RAWTX_AND_BUMP_INDEX) {\n bumpIndex = br.readVarIntNum();\n }\n data = Transaction.fromReader(br);\n beefTx = BeefTx.fromTx(data, bumpIndex);\n }\n }\n else {\n // V1\n data = Transaction.fromReader(br);\n bumpIndex = br.readUInt8() !== 0 ? br.readVarIntNum() : undefined;\n beefTx = BeefTx.fromTx(data, bumpIndex);\n }\n return beefTx;\n }\n}\n//# sourceMappingURL=BeefTx.js.map","import UnlockingScript from '../script/UnlockingScript.js';\nimport LockingScript from '../script/LockingScript.js';\nimport { Reader, Writer, toHex, toArray } from '../primitives/utils.js';\nimport { hash256 } from '../primitives/Hash.js';\nimport LivePolicy from './fee-models/LivePolicy.js';\nimport Spend from '../script/Spend.js';\nimport { defaultBroadcaster } from './broadcasters/DefaultBroadcaster.js';\nimport { defaultChainTracker } from './chaintrackers/DefaultChainTracker.js';\nimport { Beef, BEEF_V1 } from './Beef.js';\nimport P2PKH from '../script/templates/P2PKH.js';\nconst BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\n/**\n * Represents a complete Bitcoin transaction. This class encapsulates all the details\n * required for creating, signing, and processing a Bitcoin transaction, including\n * inputs, outputs, and various transaction-related methods.\n *\n * @class Transaction\n * @property {number} version - The version number of the transaction. Used to specify\n * which set of rules this transaction follows.\n * @property {TransactionInput[]} inputs - An array of TransactionInput objects, representing\n * the inputs for the transaction. Each input references a previous transaction's output.\n * @property {TransactionOutput[]} outputs - An array of TransactionOutput objects, representing\n * the outputs for the transaction. Each output specifies the amount of satoshis to be\n * transferred and the conditions under which they can be spent.\n * @property {number} lockTime - The lock time of the transaction. If non-zero, it specifies the\n * earliest time or block height at which the transaction can be added to the block chain.\n * @property {Record<string, any>} metadata - A key-value store for attaching additional data to\n * the transaction object, not included in the transaction itself. Useful for adding descriptions, internal reference numbers, or other information.\n * @property {MerkleProof} [merklePath] - Optional. A merkle proof demonstrating the transaction's\n * inclusion in a block. Useful for transaction verification using SPV.\n *\n * @example\n * // Creating a new transaction\n * let tx = new Transaction();\n * tx.addInput(...);\n * tx.addOutput(...);\n * await tx.fee();\n * await tx.sign();\n * await tx.broadcast();\n *\n * @description\n * The Transaction class provides comprehensive\n * functionality to handle various aspects of transaction creation, including\n * adding inputs and outputs, computing fees, signing the transaction, and\n * generating its binary or hexadecimal representation.\n */\nexport default class Transaction {\n version;\n inputs;\n outputs;\n lockTime;\n metadata;\n merklePath;\n cachedHash;\n rawBytesCache;\n hexCache;\n // Recursive function for adding merkle proofs or input transactions\n static addPathOrInputs(obj, transactions, BUMPs) {\n if (typeof obj.pathIndex === 'number') {\n const path = BUMPs[obj.pathIndex];\n if (typeof path !== 'object') {\n throw new Error('Invalid merkle path index found in BEEF!');\n }\n obj.tx.merklePath = path;\n }\n else {\n for (const input of obj.tx.inputs) {\n if (input.sourceTXID === undefined) {\n throw new Error('Input sourceTXID is undefined');\n }\n const sourceObj = transactions[input.sourceTXID];\n if (typeof sourceObj !== 'object') {\n throw new Error(`Reference to unknown TXID in BEEF: ${input.sourceTXID ?? 'undefined'}`);\n }\n input.sourceTransaction = sourceObj.tx;\n this.addPathOrInputs(sourceObj, transactions, BUMPs);\n }\n }\n }\n /**\n * Creates a new transaction, linked to its inputs and their associated merkle paths, from a BEEF V1, V2 or Atomic.\n * Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data.\n * If the TXID is provided but not found in the BEEF data, an error will be thrown.\n * If no TXID is provided, the last transaction in the BEEF data is returned, or the atomic txid.\n * @param beef A binary representation of transactions in BEEF format.\n * @param txid Optional TXID of the transaction to retrieve from the BEEF data.\n * @returns An anchored transaction, linked to its associated inputs populated with merkle paths.\n */\n static fromBEEF(beef, txid) {\n const { tx } = Transaction.fromAnyBeef(beef, txid);\n return tx;\n }\n /**\n * Creates a new transaction from an Atomic BEEF (BRC-95) structure.\n * Extracts the subject transaction and supporting merkle path and source transactions contained in the BEEF data\n *\n * @param beef A binary representation of an Atomic BEEF structure.\n * @returns The subject transaction, linked to its associated inputs populated with merkle paths.\n */\n static fromAtomicBEEF(beef) {\n const { tx, txid, beef: b } = Transaction.fromAnyBeef(beef);\n if (txid !== b.atomicTxid) {\n if (b.atomicTxid != null) {\n throw new Error(`Transaction with TXID ${b.atomicTxid} not found in BEEF data.`);\n }\n else {\n throw new Error('beef must conform to BRC-95 and must contain the subject txid.');\n }\n }\n return tx;\n }\n static fromAnyBeef(beef, txid) {\n const b = Beef.fromBinary(beef);\n if (b.txs.length < 1) {\n throw new Error('beef must include at least one transaction.');\n }\n const target = txid ?? b.atomicTxid ?? b.txs.slice(-1)[0].txid;\n const tx = b.findAtomicTransaction(target);\n if (tx == null) {\n if (txid != null) {\n throw new Error(`Transaction with TXID ${target} not found in BEEF data.`);\n }\n else {\n throw new Error('beef does not contain transaction for atomic txid.');\n }\n }\n return { tx, beef: b, txid: target };\n }\n /**\n * Creates a new transaction, linked to its inputs and their associated merkle paths, from a EF (BRC-30) structure.\n * @param ef A binary representation of a transaction in EF format.\n * @returns An extended transaction, linked to its associated inputs by locking script and satoshis amounts only.\n */\n static fromEF(ef) {\n const br = new Reader(ef);\n const version = br.readUInt32LE();\n if (toHex(br.read(6)) !== '0000000000ef') {\n throw new Error('Invalid EF marker');\n }\n const inputsLength = br.readVarIntNum();\n const inputs = [];\n for (let i = 0; i < inputsLength; i++) {\n const sourceTXID = toHex(br.readReverse(32));\n const sourceOutputIndex = br.readUInt32LE();\n const scriptLength = br.readVarIntNum();\n const scriptBin = br.read(scriptLength);\n const unlockingScript = UnlockingScript.fromBinary(scriptBin);\n const sequence = br.readUInt32LE();\n const satoshis = br.readUInt64LEBn().toNumber();\n const lockingScriptLength = br.readVarIntNum();\n const lockingScriptBin = br.read(lockingScriptLength);\n const lockingScript = LockingScript.fromBinary(lockingScriptBin);\n const sourceTransaction = new Transaction(undefined, [], [], undefined);\n sourceTransaction.outputs = Array(sourceOutputIndex + 1).fill(null);\n sourceTransaction.outputs[sourceOutputIndex] = {\n satoshis,\n lockingScript\n };\n inputs.push({\n sourceTransaction,\n sourceTXID,\n sourceOutputIndex,\n unlockingScript,\n sequence\n });\n }\n const outputsLength = br.readVarIntNum();\n const outputs = [];\n for (let i = 0; i < outputsLength; i++) {\n const satoshis = br.readUInt64LEBn().toNumber();\n const scriptLength = br.readVarIntNum();\n const scriptBin = br.read(scriptLength);\n const lockingScript = LockingScript.fromBinary(scriptBin);\n outputs.push({\n satoshis,\n lockingScript\n });\n }\n const lockTime = br.readUInt32LE();\n return new Transaction(version, inputs, outputs, lockTime);\n }\n /**\n * Since the validation of blockchain data is atomically transaction data validation,\n * any application seeking to validate data in output scripts must store the entire transaction as well.\n * Since the transaction data includes the output script data, saving a second copy of potentially\n * large scripts can bloat application storage requirements.\n *\n * This function efficiently parses binary transaction data to determine the offsets and lengths of each script.\n * This supports the efficient retreival of script data from transaction data.\n *\n * @param bin binary transaction data\n * @returns {\n * inputs: { vin: number, offset: number, length: number }[]\n * outputs: { vout: number, offset: number, length: number }[]\n * }\n */\n static parseScriptOffsets(bin) {\n const br = new Reader(bin);\n const inputs = [];\n const outputs = [];\n br.pos += 4; // version\n const inputsLength = br.readVarIntNum();\n for (let i = 0; i < inputsLength; i++) {\n br.pos += 36; // txid and vout\n const scriptLength = br.readVarIntNum();\n inputs.push({ vin: i, offset: br.pos, length: scriptLength });\n br.pos += scriptLength + 4; // script and sequence\n }\n const outputsLength = br.readVarIntNum();\n for (let i = 0; i < outputsLength; i++) {\n br.pos += 8; // satoshis\n const scriptLength = br.readVarIntNum();\n outputs.push({ vout: i, offset: br.pos, length: scriptLength });\n br.pos += scriptLength;\n }\n return { inputs, outputs };\n }\n static fromReader(br) {\n const version = br.readUInt32LE();\n const inputsLength = br.readVarIntNum();\n const inputs = [];\n for (let i = 0; i < inputsLength; i++) {\n const sourceTXID = toHex(br.readReverse(32));\n const sourceOutputIndex = br.readUInt32LE();\n const scriptLength = br.readVarIntNum();\n const scriptBin = br.read(scriptLength);\n const unlockingScript = UnlockingScript.fromBinary(scriptBin);\n const sequence = br.readUInt32LE();\n inputs.push({\n sourceTXID,\n sourceOutputIndex,\n unlockingScript,\n sequence\n });\n }\n const outputsLength = br.readVarIntNum();\n const outputs = [];\n for (let i = 0; i < outputsLength; i++) {\n const satoshis = br.readUInt64LEBn().toNumber();\n const scriptLength = br.readVarIntNum();\n const scriptBin = br.read(scriptLength);\n const lockingScript = LockingScript.fromBinary(scriptBin);\n outputs.push({\n satoshis,\n lockingScript\n });\n }\n const lockTime = br.readUInt32LE();\n return new Transaction(version, inputs, outputs, lockTime);\n }\n /**\n * Creates a Transaction instance from a binary array.\n *\n * @static\n * @param {number[]} bin - The binary array representation of the transaction.\n * @returns {Transaction} - A new Transaction instance.\n */\n static fromBinary(bin) {\n const copy = bin.slice();\n const rawBytes = Uint8Array.from(copy);\n const br = new Reader(copy);\n const tx = Transaction.fromReader(br);\n tx.rawBytesCache = rawBytes;\n return tx;\n }\n /**\n * Creates a Transaction instance from a hexadecimal string.\n *\n * @static\n * @param {string} hex - The hexadecimal string representation of the transaction.\n * @returns {Transaction} - A new Transaction instance.\n */\n static fromHex(hex) {\n const bin = toArray(hex, 'hex');\n const rawBytes = Uint8Array.from(bin);\n const br = new Reader(bin);\n const tx = Transaction.fromReader(br);\n tx.rawBytesCache = rawBytes;\n tx.hexCache =\n BufferCtor != null\n ? BufferCtor.from(rawBytes).toString('hex')\n : toHex(bin);\n return tx;\n }\n /**\n * Creates a Transaction instance from a hexadecimal string encoded EF.\n *\n * @static\n * @param {string} hex - The hexadecimal string representation of the transaction EF.\n * @returns {Transaction} - A new Transaction instance.\n */\n static fromHexEF(hex) {\n return Transaction.fromEF(toArray(hex, 'hex'));\n }\n /**\n * Creates a Transaction instance from a hexadecimal string encoded BEEF.\n * Optionally, you can provide a specific TXID to retrieve a particular transaction from the BEEF data.\n * If the TXID is provided but not found in the BEEF data, an error will be thrown.\n * If no TXID is provided, the last transaction in the BEEF data is returned.\n *\n * @static\n * @param {string} hex - The hexadecimal string representation of the transaction BEEF.\n * @param {string} [txid] - Optional TXID of the transaction to retrieve from the BEEF data.\n * @returns {Transaction} - A new Transaction instance.\n */\n static fromHexBEEF(hex, txid) {\n return Transaction.fromBEEF(toArray(hex, 'hex'), txid);\n }\n constructor(version = 1, inputs = [], outputs = [], lockTime = 0, metadata = new Map(), merklePath) {\n this.version = version;\n this.inputs = inputs;\n this.outputs = outputs;\n this.lockTime = lockTime;\n this.metadata = metadata;\n this.merklePath = merklePath;\n }\n invalidateSerializationCaches() {\n this.cachedHash = undefined;\n this.rawBytesCache = undefined;\n this.hexCache = undefined;\n }\n /**\n * Adds a new input to the transaction.\n *\n * @param {TransactionInput} input - The TransactionInput object to add to the transaction.\n * @throws {Error} - If the input does not have a sourceTXID or sourceTransaction defined.\n */\n addInput(input) {\n if (typeof input.sourceTXID === 'undefined' &&\n typeof input.sourceTransaction === 'undefined') {\n throw new Error('A reference to an an input transaction is required. If the input transaction itself cannot be referenced, its TXID must still be provided.');\n }\n // If the input sequence number hasn't been set, the expectation is that it is final.\n if (typeof input.sequence === 'undefined') {\n input.sequence = 0xffffffff;\n }\n this.invalidateSerializationCaches();\n this.inputs.push(input);\n }\n /**\n * Adds a new output to the transaction.\n *\n * @param {TransactionOutput} output - The TransactionOutput object to add to the transaction.\n */\n addOutput(output) {\n this.cachedHash = undefined;\n if (output.change !== true) {\n if (typeof output.satoshis === 'undefined') {\n throw new Error('either satoshis must be defined or change must be set to true');\n }\n if (output.satoshis < 0) {\n throw new Error('satoshis must be a positive integer or zero');\n }\n }\n if (output.lockingScript == null)\n throw new Error('lockingScript must be defined');\n this.outputs.push(output);\n }\n /**\n * Adds a new P2PKH output to the transaction.\n *\n * @param {number[] | string} address - The P2PKH address of the output.\n * @param {number} [satoshis] - The number of satoshis to send to the address - if not provided, the output is considered a change output.\n *\n */\n addP2PKHOutput(address, satoshis) {\n const lockingScript = new P2PKH().lock(address);\n if (typeof satoshis === 'undefined') {\n return this.addOutput({ lockingScript, change: true });\n }\n this.addOutput({\n lockingScript,\n satoshis\n });\n }\n /**\n * Updates the transaction's metadata.\n *\n * @param {Record<string, any>} metadata - The metadata object to merge into the existing metadata.\n */\n updateMetadata(metadata) {\n this.metadata = {\n ...this.metadata,\n ...metadata\n };\n }\n /**\n * Computes fees prior to signing.\n * If no fee model is provided, uses a LivePolicy fee model that fetches current rates from ARC.\n * If fee is a number, the transaction uses that value as fee.\n *\n * @param modelOrFee - The initialized fee model to use or fixed fee for the transaction\n * @param changeDistribution - Specifies how the change should be distributed\n * amongst the change outputs\n *\n */\n async fee(modelOrFee = LivePolicy.getInstance(), changeDistribution = 'equal') {\n this.invalidateSerializationCaches();\n if (typeof modelOrFee === 'number') {\n const sats = modelOrFee;\n modelOrFee = {\n computeFee: async () => sats\n };\n }\n const fee = await modelOrFee.computeFee(this);\n const change = this.calculateChange(fee);\n if (change <= 0) {\n this.outputs = this.outputs.filter((output) => output.change !== true);\n return;\n }\n this.distributeChange(change, changeDistribution);\n }\n calculateChange(fee) {\n let change = 0;\n for (const input of this.inputs) {\n if (typeof input.sourceTransaction !== 'object') {\n throw new Error('Source transactions are required for all inputs during fee computation');\n }\n change +=\n input.sourceTransaction.outputs[input.sourceOutputIndex].satoshis ?? 0;\n }\n change -= fee;\n for (const out of this.outputs) {\n if (out.change !== true) {\n if (out.satoshis !== undefined) {\n change -= out.satoshis;\n }\n }\n }\n return change;\n }\n distributeChange(change, changeDistribution) {\n let distributedChange = 0;\n const changeOutputs = this.outputs.filter((out) => out.change);\n if (changeDistribution === 'random') {\n distributedChange = this.distributeRandomChange(change, changeOutputs);\n }\n else if (changeDistribution === 'equal') {\n distributedChange = this.distributeEqualChange(change, changeOutputs);\n }\n if (distributedChange < change) {\n const lastOutput = this.outputs[this.outputs.length - 1];\n if (lastOutput.satoshis !== undefined) {\n lastOutput.satoshis += change - distributedChange;\n }\n else {\n lastOutput.satoshis = change - distributedChange;\n }\n }\n }\n distributeRandomChange(change, changeOutputs) {\n let distributedChange = 0;\n let changeToUse = change;\n const benfordNumbers = Array(changeOutputs.length).fill(1);\n changeToUse -= changeOutputs.length;\n distributedChange += changeOutputs.length;\n for (let i = 0; i < changeOutputs.length - 1; i++) {\n const portion = this.benfordNumber(0, changeToUse);\n benfordNumbers[i] = benfordNumbers[i] + portion;\n distributedChange += portion;\n changeToUse -= portion;\n }\n for (const output of this.outputs) {\n if (output.change === true)\n output.satoshis = benfordNumbers.shift();\n }\n return distributedChange;\n }\n distributeEqualChange(change, changeOutputs) {\n let distributedChange = 0;\n const perOutput = Math.floor(change / changeOutputs.length);\n for (const out of changeOutputs) {\n distributedChange += perOutput;\n out.satoshis = perOutput;\n }\n return distributedChange;\n }\n benfordNumber(min, max) {\n const d = Math.floor(Math.random() * 9) + 1;\n return Math.floor(min + ((max - min) * Math.log10(1 + 1 / d)) / Math.log10(10));\n }\n /**\n * Utility method that returns the current fee based on inputs and outputs\n *\n * @returns The current transaction fee\n */\n getFee() {\n let totalIn = 0;\n for (const input of this.inputs) {\n if (typeof input.sourceTransaction !== 'object') {\n throw new Error('Source transactions or sourceSatoshis are required for all inputs to calculate fee');\n }\n totalIn +=\n input.sourceTransaction.outputs[input.sourceOutputIndex].satoshis ?? 0;\n }\n let totalOut = 0;\n for (const output of this.outputs) {\n totalOut += output.satoshis ?? 0;\n }\n return totalIn - totalOut;\n }\n /**\n * Signs a transaction, hydrating all its unlocking scripts based on the provided script templates where they are available.\n */\n async sign() {\n this.invalidateSerializationCaches();\n for (const out of this.outputs) {\n if (typeof out.satoshis === 'undefined') {\n if (out.change === true) {\n throw new Error('There are still change outputs with uncomputed amounts. Use the fee() method to compute the change amounts and transaction fees prior to signing.');\n }\n else {\n throw new Error('One or more transaction outputs is missing an amount. Ensure all output amounts are provided before signing.');\n }\n }\n }\n const unlockingScripts = await Promise.all(this.inputs.map(async (x, i) => {\n if (typeof this.inputs[i].unlockingScriptTemplate === 'object') {\n return await this.inputs[i]?.unlockingScriptTemplate?.sign(this, i);\n }\n else {\n return await Promise.resolve(undefined);\n }\n }));\n for (let i = 0, l = this.inputs.length; i < l; i++) {\n if (typeof this.inputs[i].unlockingScriptTemplate === 'object') {\n this.inputs[i].unlockingScript = unlockingScripts[i];\n }\n }\n }\n /**\n * Broadcasts a transaction.\n *\n * @param broadcaster The Broadcaster instance wwhere the transaction will be sent\n * @returns A BroadcastResponse or BroadcastFailure from the Broadcaster\n */\n async broadcast(broadcaster = defaultBroadcaster()) {\n return await broadcaster.broadcast(this);\n }\n writeTransactionBody(writer) {\n writer.writeUInt32LE(this.version);\n writer.writeVarIntNum(this.inputs.length);\n for (const i of this.inputs) {\n if (typeof i.sourceTXID === 'undefined') {\n if (i.sourceTransaction != null) {\n writer.write(i.sourceTransaction.hash());\n }\n else {\n throw new Error('sourceTransaction is undefined');\n }\n }\n else {\n writer.writeReverse(toArray(i.sourceTXID, 'hex'));\n }\n writer.writeUInt32LE(i.sourceOutputIndex);\n if (i.unlockingScript == null) {\n throw new Error('unlockingScript is undefined');\n }\n const scriptBin = i.unlockingScript.toUint8Array();\n writer.writeVarIntNum(scriptBin.length);\n writer.write(scriptBin);\n writer.writeUInt32LE(i.sequence ?? 0xffffffff);\n }\n writer.writeVarIntNum(this.outputs.length);\n for (const o of this.outputs) {\n writer.writeUInt64LE(o.satoshis ?? 0);\n const scriptBin = o.lockingScript.toUint8Array();\n writer.writeVarIntNum(scriptBin.length);\n writer.write(scriptBin);\n }\n writer.writeUInt32LE(this.lockTime);\n }\n buildSerializedBytes() {\n const writer = new Writer();\n this.writeTransactionBody(writer);\n return writer.toUint8Array();\n }\n getSerializedBytes() {\n if (this.rawBytesCache == null) {\n this.rawBytesCache = this.buildSerializedBytes();\n }\n return this.rawBytesCache;\n }\n /**\n * Converts the transaction to a binary array format.\n *\n * @returns {number[]} - The binary array representation of the transaction.\n */\n toBinary() {\n return Array.from(this.getSerializedBytes());\n }\n toUint8Array() {\n return this.getSerializedBytes();\n }\n /**\n * Converts the transaction to a BRC-30 EF format.\n *\n * @returns {number[]} - The BRC-30 EF representation of the transaction.\n */\n toEF() {\n const writer = new Writer();\n writer.writeUInt32LE(this.version);\n writer.write([0, 0, 0, 0, 0, 0xef]);\n writer.writeVarIntNum(this.inputs.length);\n for (const i of this.inputs) {\n if (typeof i.sourceTransaction === 'undefined') {\n throw new Error('All inputs must have source transactions when serializing to EF format');\n }\n if (typeof i.sourceTXID === 'undefined') {\n writer.write(i.sourceTransaction.hash());\n }\n else {\n writer.write(toArray(i.sourceTXID, 'hex').reverse());\n }\n writer.writeUInt32LE(i.sourceOutputIndex);\n if (i.unlockingScript == null) {\n throw new Error('unlockingScript is undefined');\n }\n const scriptBin = i.unlockingScript.toBinary();\n writer.writeVarIntNum(scriptBin.length);\n writer.write(scriptBin);\n writer.writeUInt32LE(i.sequence ?? 0xffffffff); // default to max sequence\n writer.writeUInt64LE(i.sourceTransaction.outputs[i.sourceOutputIndex].satoshis ?? 0);\n const lockingScriptBin = i.sourceTransaction.outputs[i.sourceOutputIndex].lockingScript.toBinary();\n writer.writeVarIntNum(lockingScriptBin.length);\n writer.write(lockingScriptBin);\n }\n writer.writeVarIntNum(this.outputs.length);\n for (const o of this.outputs) {\n writer.writeUInt64LE(o.satoshis ?? 0);\n const scriptBin = o.lockingScript.toBinary();\n writer.writeVarIntNum(scriptBin.length);\n writer.write(scriptBin);\n }\n writer.writeUInt32LE(this.lockTime);\n return writer.toArray();\n }\n /**\n * Converts the transaction to a hexadecimal string EF.\n *\n * @returns {string} - The hexadecimal string representation of the transaction EF.\n */\n toHexEF() {\n return toHex(this.toEF());\n }\n /**\n * Converts the transaction to a hexadecimal string format.\n *\n * @returns {string} - The hexadecimal string representation of the transaction.\n */\n toHex() {\n if (this.hexCache != null) {\n return this.hexCache;\n }\n const bytes = this.getSerializedBytes();\n const hex = BufferCtor != null\n ? BufferCtor.from(bytes).toString('hex')\n : toHex(Array.from(bytes));\n this.hexCache = hex;\n return hex;\n }\n /**\n * Converts the transaction to a hexadecimal string BEEF.\n *\n * @returns {string} - The hexadecimal string representation of the transaction BEEF.\n */\n toHexBEEF() {\n return toHex(this.toBEEF());\n }\n /**\n * Converts the transaction to a hexadecimal string Atomic BEEF.\n *\n * @returns {string} - The hexadecimal string representation of the transaction Atomic BEEF.\n */\n toHexAtomicBEEF() {\n return toHex(this.toAtomicBEEF());\n }\n /**\n * Calculates the transaction's hash.\n *\n * @param {'hex' | undefined} enc - The encoding to use for the hash. If 'hex', returns a hexadecimal string; otherwise returns a binary array.\n * @returns {string | number[]} - The hash of the transaction in the specified format.\n */\n hash(enc) {\n if (this.cachedHash == null) {\n this.cachedHash = hash256(this.getSerializedBytes());\n }\n if (enc === 'hex') {\n return toHex(this.cachedHash);\n }\n return this.cachedHash;\n }\n /**\n * Calculates the transaction's ID.\n *\n * @param {'hex' | undefined} enc - The encoding to use for the ID. If 'hex', returns a hexadecimal string; otherwise returns a binary array.\n * @returns {string | number[]} - The ID of the transaction in the specified format.\n */\n id(enc) {\n const id = [...this.hash()];\n id.reverse();\n if (enc === 'hex') {\n return toHex(id);\n }\n return id;\n }\n /**\n * Verifies the legitimacy of the Bitcoin transaction according to the rules of SPV by ensuring all the input transactions link back to valid block headers, the chain of spends for all inputs are valid, and the sum of inputs is not less than the sum of outputs.\n *\n * @param chainTracker - An instance of ChainTracker, a Bitcoin block header tracker. If the value is set to 'scripts only', headers will not be verified. If not provided then the default chain tracker will be used.\n * @param feeModel - An instance of FeeModel, a fee model to use for fee calculation. If not provided then the default fee model will be used.\n * @param memoryLimit - The maximum memory in bytes usage allowed for script evaluation. If not provided then the default memory limit will be used.\n *\n * @returns Whether the transaction is valid according to the rules of SPV.\n *\n * @example tx.verify(new WhatsOnChain(), LivePolicy.getInstance())\n */\n async verify(chainTracker = defaultChainTracker(), feeModel, memoryLimit) {\n const verifiedTxids = new Set();\n const txQueue = [this];\n while (txQueue.length > 0) {\n const tx = txQueue.shift();\n const txid = tx?.id('hex') ?? '';\n if (txid != null && txid !== '' && verifiedTxids.has(txid)) {\n continue;\n }\n // If the transaction has a valid merkle path, verification is complete.\n if (typeof tx?.merklePath === 'object') {\n if (chainTracker === 'scripts only') {\n if (txid != null) {\n verifiedTxids.add(txid);\n }\n continue;\n }\n else {\n const proofValid = await tx.merklePath.verify(txid, chainTracker);\n // If the proof is valid, no need to verify inputs.\n if (proofValid) {\n verifiedTxids.add(txid);\n continue;\n }\n else {\n throw new Error(`Invalid merkle path for transaction ${txid}`);\n }\n }\n }\n // Verify fee if feeModel is provided\n if (typeof feeModel !== 'undefined') {\n if (tx === undefined) {\n throw new Error('Transaction is undefined');\n }\n const cpTx = Transaction.fromEF(tx.toEF());\n delete cpTx.outputs[0].satoshis;\n cpTx.outputs[0].change = true;\n await cpTx.fee(feeModel);\n if (tx.getFee() < cpTx.getFee()) {\n throw new Error(`Verification failed because the transaction ${txid} has an insufficient fee and has not been mined.`);\n }\n }\n // Verify each input transaction and evaluate the spend events.\n // Also, keep a total of the input amounts for later.\n let inputTotal = 0;\n if (tx === undefined) {\n throw new Error('Transaction is undefined');\n }\n for (let i = 0; i < tx.inputs.length; i++) {\n const input = tx.inputs[i];\n if (typeof input.sourceTransaction !== 'object') {\n throw new Error(`Verification failed because the input at index ${i} of transaction ${txid} 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.`);\n }\n if (typeof input.unlockingScript !== 'object') {\n throw new Error(`Verification failed because the input at index ${i} of transaction ${txid} 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.`);\n }\n const sourceOutput = input.sourceTransaction.outputs[input.sourceOutputIndex];\n inputTotal += sourceOutput.satoshis ?? 0;\n const sourceTxid = input.sourceTransaction.id('hex');\n if (!verifiedTxids.has(sourceTxid)) {\n txQueue.push(input.sourceTransaction);\n }\n const otherInputs = tx.inputs.filter((_, idx) => idx !== i);\n if (typeof input.sourceTXID === 'undefined') {\n input.sourceTXID = sourceTxid;\n }\n const spend = new Spend({\n sourceTXID: input.sourceTXID,\n sourceOutputIndex: input.sourceOutputIndex,\n lockingScript: sourceOutput.lockingScript,\n sourceSatoshis: sourceOutput.satoshis ?? 0,\n transactionVersion: tx.version,\n otherInputs,\n unlockingScript: input.unlockingScript,\n inputSequence: input.sequence ?? 0xffffffff, // default to max sequence\n inputIndex: i,\n outputs: tx.outputs,\n lockTime: tx.lockTime,\n memoryLimit\n });\n const spendValid = spend.validate();\n if (!spendValid) {\n return false;\n }\n }\n // Total the outputs to ensure they don't amount to more than the inputs\n let outputTotal = 0;\n for (const out of tx.outputs) {\n if (typeof out.satoshis !== 'number') {\n throw new Error('Every output must have a defined amount during transaction verification.');\n }\n outputTotal += out.satoshis;\n }\n if (outputTotal > inputTotal) {\n return false;\n }\n verifiedTxids.add(txid);\n }\n return true;\n }\n /**\n * Serializes this transaction, together with its inputs and the respective merkle proofs, into the BEEF (BRC-62) format. This enables efficient verification of its compliance with the rules of SPV.\n *\n * @param allowPartial If true, error will not be thrown if there are any missing sourceTransactions.\n *\n * @returns The serialized BEEF structure\n * @throws Error if there are any missing sourceTransactions unless `allowPartial` is true.\n */\n toBEEF(allowPartial) {\n const writer = new Writer();\n writer.writeUInt32LE(BEEF_V1);\n const BUMPs = [];\n const bumpIndexByInstance = new Map();\n const bumpIndexByRoot = new Map();\n const txs = [];\n const seenTxids = new Set();\n const getBumpIndex = (merklePath) => {\n const existingByInstance = bumpIndexByInstance.get(merklePath);\n if (existingByInstance !== undefined) {\n return existingByInstance;\n }\n const key = `${merklePath.blockHeight}:${merklePath.computeRoot()}`;\n const existingByRoot = bumpIndexByRoot.get(key);\n if (existingByRoot !== undefined) {\n BUMPs[existingByRoot].combine(merklePath);\n bumpIndexByInstance.set(merklePath, existingByRoot);\n return existingByRoot;\n }\n const newIndex = BUMPs.length;\n BUMPs.push(merklePath);\n bumpIndexByInstance.set(merklePath, newIndex);\n bumpIndexByRoot.set(key, newIndex);\n return newIndex;\n };\n // Recursive function to add paths and input transactions for a TX\n const addPathsAndInputs = (tx) => {\n const txid = tx.id('hex');\n if (seenTxids.has(txid)) {\n return;\n }\n const obj = { tx };\n const merklePath = tx.merklePath;\n const hasProof = typeof merklePath === 'object';\n if (hasProof && merklePath != null) {\n obj.pathIndex = getBumpIndex(merklePath);\n }\n if (!hasProof) {\n for (let i = tx.inputs.length - 1; i >= 0; i--) {\n const input = tx.inputs[i];\n if (typeof input.sourceTransaction === 'object') {\n addPathsAndInputs(input.sourceTransaction);\n }\n else if (allowPartial === false) {\n throw new Error('A required source transaction is missing!');\n }\n }\n }\n seenTxids.add(txid);\n txs.push(obj);\n };\n addPathsAndInputs(this);\n writer.writeVarIntNum(BUMPs.length);\n for (const b of BUMPs) {\n writer.write(b.toBinary());\n }\n writer.writeVarIntNum(txs.length);\n for (const t of txs) {\n writer.write(t.tx.toBinary());\n if (typeof t.pathIndex === 'number') {\n writer.writeUInt8(1);\n writer.writeVarIntNum(t.pathIndex);\n }\n else {\n writer.writeUInt8(0);\n }\n }\n return writer.toArray();\n }\n /**\n * Serializes this transaction and its inputs into the Atomic BEEF (BRC-95) format.\n * The Atomic BEEF format starts with a 4-byte prefix `0x01010101`, followed by the TXID of the subject transaction,\n * and then the BEEF data containing only the subject transaction and its dependencies.\n * This format ensures that the BEEF structure is atomic and contains no unrelated transactions.\n *\n * @param allowPartial If true, error will not be thrown if there are any missing sourceTransactions.\n *\n * @returns {number[]} - The serialized Atomic BEEF structure.\n * @throws Error if there are any missing sourceTransactions unless `allowPartial` is true.\n */\n toAtomicBEEF(allowPartial) {\n const prefix = [1, 1, 1, 1];\n const txHash = this.hash();\n const beefData = this.toBEEF(allowPartial);\n return prefix.concat(txHash, beefData);\n }\n}\n//# sourceMappingURL=Transaction.js.map","/**\n * Convenience type guard for response from `Broadcaster.broadcast`\n */\nexport function isBroadcastResponse(r) {\n return r.status === 'success';\n}\n/**\n * Convenience type guard for response from `Broadcaster.broadcast`\n */\nexport function isBroadcastFailure(r) {\n return r.status === 'error';\n}\n//# sourceMappingURL=Broadcaster.js.map","import { Beef } from './Beef.js';\n/**\n * Extends `Beef` that is used to exchange transaction validity data with more than one external party.\n *\n * Use `addKnownTxidsForParty` to keep track of who knows what to reduce re-transmission of potentially large transactions.\n *\n * Use `getTrimmedBeefForParty` to obtain a `Beef` trimmed of transaction validity data known to a specific party.\n *\n * Typical usage scenario:\n *\n * 1. Query a wallet storage provider for spendable outputs.\n * 2. The provider replies with a Beef validating the returned outputs.\n * 3. Construct a new transaction using some of the queried outputs as inputs, including Beef validating all the inputs.\n * 4. Receive new valid raw transaction after processing and Beef validating change outputs added to original inputs.\n * 5. Return to step 1, continuing to build on old and new spendable outputs.\n *\n * By default, each Beef is required to be complete and valid: All transactions appear as full serialized bitcoin transactions and\n * each transaction either has a merkle path proof (it has been mined) or all of its input transactions are included.\n *\n * The size and redundancy of these Beefs becomes a problem when chained transaction creation out-paces the block mining rate.\n *\n */\nexport class BeefParty extends Beef {\n /**\n * keys are party identifiers.\n * values are records of txids with truthy value for which the party already has validity proof.\n */\n knownTo = {};\n /**\n *\n * @param parties Optional array of initial unique party identifiers.\n */\n constructor(parties) {\n super();\n if (parties != null) {\n for (const party of parties) {\n this.addParty(party);\n }\n }\n }\n /**\n * @param party\n * @returns `true` if `party` has already been added to this `BeefParty`.\n */\n isParty(party) {\n const r = Object.keys(this.knownTo).includes(party);\n return r;\n }\n /**\n * Adds a new unique party identifier to this `BeefParty`.\n * @param party\n */\n addParty(party) {\n if (this.isParty(party)) {\n throw new Error(`Party ${party} already exists.`);\n }\n this.knownTo[party] = {};\n }\n /**\n * @param party\n * @returns Array of txids \"known\" to `party`.\n */\n getKnownTxidsForParty(party) {\n const knownTxids = this.knownTo[party];\n if (knownTxids === undefined) { // ✅ Explicitly check for undefined\n throw new Error(`Party ${party} is unknown.`);\n }\n return Object.keys(knownTxids);\n }\n /**\n * @param party\n * @returns trimmed beef of unknown transactions and proofs for `party`\n */\n getTrimmedBeefForParty(party) {\n const knownTxids = this.getKnownTxidsForParty(party);\n const prunedBeef = this.clone();\n prunedBeef.trimKnownTxids(knownTxids);\n return prunedBeef;\n }\n /**\n * Make note of additional txids \"known\" to `party`.\n * @param party unique identifier, added if new.\n * @param knownTxids\n */\n addKnownTxidsForParty(party, knownTxids) {\n if (!this.isParty(party)) {\n this.addParty(party);\n }\n const kts = this.knownTo[party];\n for (const txid of knownTxids) {\n kts[txid] = true;\n this.mergeTxidOnly(txid);\n }\n }\n /**\n * Merge a `beef` received from a specific `party`.\n *\n * Updates this `BeefParty` to track all the txids\n * corresponding to transactions for which `party`\n * has raw transaction and validity proof data.\n *\n * @param party\n * @param beef\n */\n mergeBeefFromParty(party, beef) {\n const b = Array.isArray(beef) ? Beef.fromBinary(beef) : beef;\n const knownTxids = b.getValidTxids();\n this.mergeBeef(b);\n this.addKnownTxidsForParty(party, knownTxids);\n }\n}\nexport default BeefParty;\n//# sourceMappingURL=BeefParty.js.map","import { defaultHttpClient } from '../http/DefaultHttpClient.js';\n/**\n * Represents an WhatsOnChain transaction broadcaster.\n */\nexport default class WhatsOnChainBroadcaster {\n network;\n URL;\n httpClient;\n /**\n * Constructs an instance of the WhatsOnChain broadcaster.\n *\n * @param {'main' | 'test' | 'stn'} network - The BSV network to use when calling the WhatsOnChain API.\n * @param {HttpClient} httpClient - The HTTP client used to make requests to the API.\n */\n constructor(network = 'main', httpClient = defaultHttpClient()) {\n this.network = network;\n this.URL = `https://api.whatsonchain.com/v1/bsv/${network}/tx/raw`;\n this.httpClient = httpClient;\n }\n /**\n * Broadcasts a transaction via WhatsOnChain.\n *\n * @param {Transaction} tx - The transaction to be broadcasted.\n * @returns {Promise<BroadcastResponse | BroadcastFailure>} A promise that resolves to either a success or failure response.\n */\n async broadcast(tx) {\n const rawTx = tx.toHex();\n const requestOptions = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/plain'\n },\n data: { txhex: rawTx }\n };\n try {\n const response = await this.httpClient.request(this.URL, requestOptions);\n if (response.ok) {\n const txid = response.data;\n return {\n status: 'success',\n txid,\n message: 'broadcast successful'\n };\n }\n else {\n return {\n status: 'error',\n code: response.status.toString() ?? 'ERR_UNKNOWN',\n description: response.data ?? 'Unknown error'\n };\n }\n }\n catch (error) {\n return {\n status: 'error',\n code: '500',\n description: typeof error.message === 'string'\n ? error.message\n : 'Internal Server Error'\n };\n }\n }\n}\n//# sourceMappingURL=WhatsOnChainBroadcaster.js.map","/**\n * Adapter for Node Https module to be used as HttpClient\n */\nexport class BinaryNodejsHttpClient {\n https;\n constructor(https) {\n this.https = https;\n }\n async request(url, requestOptions) {\n return await new Promise((resolve, reject) => {\n const req = this.https.request(url, requestOptions, (res) => {\n let body = '';\n res.on('data', (chunk) => {\n body += chunk;\n });\n res.on('end', () => {\n const ok = res.statusCode >= 200 && res.statusCode <= 299;\n const mediaType = res.headers['content-type'];\n const data = body !== '' && typeof mediaType === 'string' && mediaType.startsWith('application/json')\n ? JSON.parse(body)\n : body;\n resolve({\n status: res.statusCode,\n statusText: res.statusMessage,\n ok,\n data\n });\n });\n });\n req.on('error', (error) => {\n reject(error);\n });\n if (requestOptions.data !== null && requestOptions.data !== undefined) {\n req.write(Buffer.from(requestOptions.data));\n }\n req.end();\n });\n }\n}\n/**\n * Adapter for Node Https module to be used as HttpClient\n */\nexport class BinaryFetchClient {\n fetch;\n constructor(fetch) {\n this.fetch = fetch;\n }\n async request(url, options) {\n const fetchOptions = {\n method: options.method,\n headers: options.headers,\n body: options.data\n };\n const res = await this.fetch(url, fetchOptions);\n const data = await res.text();\n return {\n ok: res.ok,\n status: res.status,\n statusText: res.statusText,\n data: data\n };\n }\n}\nexport function binaryHttpClient() {\n const noHttpClient = {\n async request(..._) {\n throw new Error('No method available to perform HTTP request');\n }\n };\n if (typeof window !== 'undefined' && typeof window.fetch === 'function') {\n // Use fetch in a browser environment\n return new BinaryFetchClient(window.fetch.bind(window));\n }\n else if (typeof require !== 'undefined') {\n // Use Node https module\n // eslint-disable-next-line\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const https = require('https');\n return new BinaryNodejsHttpClient(https);\n }\n catch (e) {\n return noHttpClient;\n }\n }\n else {\n return noHttpClient;\n }\n}\n//# sourceMappingURL=BinaryFetchClient.js.map","import { binaryHttpClient } from '../http/index.js';\n/**\n * Represents an Teranode transaction broadcaster.\n */\nexport default class Teranode {\n URL;\n httpClient;\n /**\n * Constructs an instance of the Teranode broadcaster.\n *\n * @param {string} URL - The URL endpoint for the Teranode API.\n * @param {HttpClient} httpClient - The HTTP client used to make requests to the API, binaryHttpClient by default.\n */\n constructor(URL, httpClient = binaryHttpClient()) {\n this.URL = URL;\n this.httpClient = httpClient;\n }\n /**\n * Broadcasts a transaction via Teranode.\n *\n * @param {Transaction} tx - The transaction to be broadcasted.\n * @returns {Promise<BroadcastResponse | BroadcastFailure>} A promise that resolves to either a success or failure response.\n */\n async broadcast(tx) {\n const rawTx = tx.toEF();\n const requestOptions = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream'\n },\n data: new Blob([new Uint8Array(rawTx)])\n };\n try {\n const response = await this.httpClient.request(this.URL, requestOptions);\n if (response.ok) {\n const txid = tx.id('hex');\n return {\n status: 'success',\n txid,\n message: 'broadcast successful'\n };\n }\n else {\n return {\n status: 'error',\n code: response.status.toString() ?? 'ERR_UNKNOWN',\n description: response.data ?? 'Unknown error'\n };\n }\n }\n catch (error) {\n return {\n status: 'error',\n code: '500',\n description: typeof error.message === 'string'\n ? error.message\n : 'Internal Server Error'\n };\n }\n }\n}\n//# sourceMappingURL=Teranode.js.map","import { defaultHttpClient } from '../http/DefaultHttpClient.js';\n/**\n * Represents a chain tracker based on a BlockHeadersService API.\n *\n * @example\n * ```typescript\n * const chainTracker = new BlockHeadersService('https://headers.spv.money', {\n * apiKey: '17JxRHcJerGBEbusx56W8o1m8Js73TFGo'\n * })\n * ```\n */\nexport class BlockHeadersService {\n baseUrl;\n httpClient;\n apiKey;\n /**\n * Constructs an instance of the BlockHeadersService ChainTracker.\n *\n * @param {string} baseUrl - The base URL for the BlockHeadersService API (e.g. https://headers.spv.money)\n * @param {BlockHeadersServiceConfig} config - Configuration options for the BlockHeadersService ChainTracker.\n */\n constructor(baseUrl, config = {}) {\n const { httpClient, apiKey } = config;\n this.baseUrl = baseUrl;\n this.httpClient = httpClient ?? defaultHttpClient();\n this.apiKey = apiKey ?? '';\n }\n /**\n * Verifies if a given merkle root is valid for a specific block height.\n *\n * @param {string} root - The merkle root to verify.\n * @param {number} height - The block height to check against.\n * @returns {Promise<boolean>} - A promise that resolves to true if the merkle root is valid for the specified block height, false otherwise.\n */\n async isValidRootForHeight(root, height) {\n const requestOptions = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`\n },\n data: [\n {\n blockHeight: height,\n merkleRoot: root\n }\n ]\n };\n try {\n const response = await this.httpClient.request(`${this.baseUrl}/api/v1/chain/merkleroot/verify`, requestOptions);\n if (response.ok) {\n return response.data.confirmationState === 'CONFIRMED';\n }\n else {\n throw new Error(`Failed to verify merkleroot for height ${height} because of an error: ${JSON.stringify(response.data)}`);\n }\n }\n catch (error) {\n throw new Error(`Failed to verify merkleroot for height ${height} because of an error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n /**\n * Gets the current block height from the BlockHeadersService API.\n *\n * @returns {Promise<number>} - A promise that resolves to the current block height.\n */\n async currentHeight() {\n const requestOptions = {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`\n }\n };\n try {\n const response = await this.httpClient.request(`${this.baseUrl}/api/v1/chain/tip/longest`, requestOptions);\n if (response.ok && response.data && typeof response.data.height === 'number') {\n return response.data.height;\n }\n else {\n throw new Error(`Failed to get current height because of an error: ${JSON.stringify(response.data)}`);\n }\n }\n catch (error) {\n throw new Error(`Failed to get current height because of an error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n}\n//# sourceMappingURL=BlockHeadersService.js.map","// @ts-nocheck\nimport PublicKey from '../primitives/PublicKey.js';\nimport PrivateKey from '../primitives/PrivateKey.js';\nimport Signature from '../primitives/Signature.js';\nimport Curve from '../primitives/Curve.js';\nimport Random from '../primitives/Random.js';\nimport { toBase64, toArray, Reader, toHex } from '../primitives/utils.js';\nconst VERSION = '42423301';\n/**\n * Signs a message from one party to be verified by another, or for verification by anyone, using the BRC-77 message signing protocol.\n * @param message The message to sign\n * @param signer The private key of the message signer\n * @param [verifier] The public key of the person who can verify the message. If not provided, anyone will be able to verify the message signature.\n *\n * @returns The message signature.\n */\nexport const sign = (message, signer, verifier) => {\n const recipientAnyone = typeof verifier !== 'object';\n if (recipientAnyone) {\n const curve = new Curve();\n const anyone = new PrivateKey(1);\n const anyonePoint = curve.g.mul(anyone);\n verifier = new PublicKey(anyonePoint.x, anyonePoint.y);\n }\n const keyID = Random(32);\n const keyIDBase64 = toBase64(keyID);\n const invoiceNumber = `2-message signing-${keyIDBase64}`;\n const signingKey = signer.deriveChild(verifier, invoiceNumber);\n const signature = signingKey.sign(message).toDER();\n const senderPublicKey = signer.toPublicKey().encode(true);\n const version = toArray(VERSION, 'hex');\n return [\n ...version,\n ...senderPublicKey,\n ...(recipientAnyone ? [0] : verifier.encode(true)),\n ...keyID,\n ...signature\n ];\n};\n/**\n * Verifies a message using the BRC-77 message signing protocol.\n * @param message The message to verify.\n * @param sig The message signature to be verified.\n * @param [recipient] The private key of the message verifier. This can be omitted if the message is verifiable by anyone.\n *\n * @returns True if the message is verified.\n */\nexport const verify = (message, sig, recipient) => {\n const reader = new Reader(sig);\n const messageVersion = toHex(reader.read(4));\n if (messageVersion !== VERSION) {\n throw new Error(`Message version mismatch: Expected ${VERSION}, received ${messageVersion}`);\n }\n const signer = PublicKey.fromString(toHex(reader.read(33)));\n const [verifierFirst] = reader.read(1);\n if (verifierFirst === 0) {\n recipient = new PrivateKey(1);\n }\n else {\n const verifierRest = reader.read(32);\n const verifierDER = toHex([verifierFirst, ...verifierRest]);\n if (typeof recipient !== 'object') {\n throw new Error(`This signature can only be verified with knowledge of a specific private key. The associated public key is: ${verifierDER}`);\n }\n const recipientDER = recipient.toPublicKey().encode(true, 'hex');\n if (verifierDER !== recipientDER) {\n throw new Error(`The recipient public key is ${recipientDER} but the signature requres the recipient to have public key ${verifierDER}`);\n }\n }\n const keyID = toBase64(reader.read(32));\n const signatureDER = toHex(reader.read(reader.bin.length - reader.pos));\n const signature = Signature.fromDER(signatureDER, 'hex');\n const invoiceNumber = `2-message signing-${keyID}`;\n const signingKey = signer.deriveChild(recipient, invoiceNumber);\n const verified = signingKey.verify(message, signature);\n return verified;\n};\n//# sourceMappingURL=SignedMessage.js.map","import PublicKey from '../primitives/PublicKey.js';\nimport SymmetricKey from '../primitives/SymmetricKey.js';\nimport Random from '../primitives/Random.js';\nimport { toBase64, toArray, Reader, toHex } from '../primitives/utils.js';\nconst VERSION = '42421033';\n/**\n * Encrypts a message from one party to another using the BRC-78 message encryption protocol.\n * @param message The message to encrypt\n * @param sender The private key of the sender\n * @param recipient The public key of the recipient\n *\n * @returns The encrypted message\n */\nexport const encrypt = (message, sender, recipient) => {\n const keyID = Random(32);\n const keyIDBase64 = toBase64(keyID);\n const invoiceNumber = `2-message encryption-${keyIDBase64}`;\n const signingPriv = sender.deriveChild(recipient, invoiceNumber);\n const recipientPub = recipient.deriveChild(sender, invoiceNumber);\n const sharedSecret = signingPriv.deriveSharedSecret(recipientPub);\n const symmetricKey = new SymmetricKey(sharedSecret.encode(true).slice(1));\n const encrypted = symmetricKey.encrypt(message);\n const senderPublicKey = sender.toPublicKey().encode(true);\n const version = toArray(VERSION, 'hex');\n return [\n ...version,\n ...senderPublicKey,\n ...recipient.encode(true),\n ...keyID,\n ...encrypted\n ];\n};\n/**\n * Decrypts a message from one party to another using the BRC-78 message encryption protocol.\n * @param message The message to decrypt\n * @param sender The private key of the recipient\n *\n * @returns The decrypted message\n */\nexport const decrypt = (message, recipient) => {\n const reader = new Reader(message);\n const messageVersion = toHex(reader.read(4));\n if (messageVersion !== VERSION) {\n throw new Error(`Message version mismatch: Expected ${VERSION}, received ${messageVersion}`);\n }\n const sender = PublicKey.fromString(toHex(reader.read(33)));\n const expectedRecipientDER = toHex(reader.read(33));\n const actualRecipientDER = recipient\n .toPublicKey()\n .encode(true, 'hex');\n if (expectedRecipientDER !== actualRecipientDER) {\n throw new Error(`The encrypted message expects a recipient public key of ${expectedRecipientDER}, but the provided key is ${actualRecipientDER}`);\n }\n const keyID = toBase64(reader.read(32));\n const encrypted = reader.read(reader.bin.length - reader.pos);\n const invoiceNumber = `2-message encryption-${keyID}`;\n const signingPriv = sender.deriveChild(recipient, invoiceNumber);\n const recipientPub = recipient.deriveChild(sender, invoiceNumber);\n const sharedSecret = signingPriv.deriveSharedSecret(recipientPub);\n const symmetricKey = new SymmetricKey(sharedSecret.encode(true).slice(1));\n return symmetricKey.decrypt(encrypted);\n};\n//# sourceMappingURL=EncryptedMessage.js.map","import BigNumber from '../primitives/BigNumber.js';\nimport { Writer, toArray } from '../primitives/utils.js';\nimport * as ECDSA from '../primitives/ECDSA.js';\nimport * as Hash from '../primitives/Hash.js';\nconst prefix = 'Bitcoin Signed Message:\\n';\n/**\n * Generates a SHA256 double-hash of the prefixed message.\n * @deprecated Replaced by BRC-77 which uses a more secure and private method for message signing.\n * @param messageBuf The message buffer to be hashed.\n * @returns The double-hash of the prefixed message as a number array.\n */\nexport const magicHash = (messageBuf) => {\n const bw = new Writer();\n bw.writeVarIntNum(prefix.length);\n bw.write(toArray(prefix, 'utf8'));\n bw.writeVarIntNum(messageBuf.length);\n bw.write(messageBuf);\n const buf = bw.toArray();\n const hashBuf = Hash.hash256(buf);\n return hashBuf;\n};\n/**\n * Signs a BSM message using the given private key.\n * @deprecated Replaced by BRC-77 which employs BRC-42 key derivation and BRC-43 invoice numbers for enhanced security and privacy.\n * @param message The message to be signed as a number array.\n * @param privateKey The private key used for signing the message.\n * @param mode The mode of operation. When \"base64\", the BSM format signature is returned. When \"raw\", a Signature object is returned. Default: \"base64\".\n * @returns The signature object when in raw mode, or the BSM base64 string when in base64 mode.\n */\nexport const sign = (message, privateKey, mode = 'base64') => {\n const hashBuf = magicHash(message);\n const sig = ECDSA.sign(new BigNumber(hashBuf), privateKey, true);\n if (mode === 'raw') {\n return sig;\n }\n const h = new BigNumber(hashBuf);\n const r = sig.CalculateRecoveryFactor(privateKey.toPublicKey(), h);\n return sig.toCompact(r, true, 'base64');\n};\n/**\n * Verifies a BSM signed message using the given public key.\n * @deprecated Replaced by BRC-77 which provides privately-verifiable signatures and avoids key reuse.\n * @param message The message to be verified as a number array.\n * @param sig The signature object.\n * @param pubKey The public key for verification.\n * @returns True if the signature is valid, false otherwise.\n */\nexport const verify = (message, sig, pubKey) => {\n const hashBuf = magicHash(message);\n return ECDSA.verify(new BigNumber(hashBuf), sig, pubKey);\n};\n//# sourceMappingURL=BSM.js.map","// @ts-nocheck\nimport { fromBase58Check, toBase58Check, Writer, Reader, toArray, toHex } from '../primitives/utils.js';\nimport * as Hash from '../primitives/Hash.js';\nimport Curve from '../primitives/Curve.js';\nimport PrivateKey from '../primitives/PrivateKey.js';\nimport PublicKey from '../primitives/PublicKey.js';\nimport Random from '../primitives/Random.js';\nimport BigNumber from '../primitives/BigNumber.js';\n/**\n * @deprecated\n * The HD class implements the Bitcoin Improvement Proposal 32 (BIP32) hierarchical deterministic wallets.\n * It allows the generation of child keys from a master key, ensuring a tree-like structure of keys and addresses.\n * This class is deprecated due to the introduction of BRC-42, which offers an enhanced key derivation scheme.\n * BRC-42 uses invoice numbers for key derivation, improving privacy and scalability compared to BIP32.\n *\n * @class HD\n * @deprecated Replaced by BRC-42 which uses invoice numbers and supports private derivation.\n */\nexport default class HD {\n versionBytesNum;\n depth;\n parentFingerPrint;\n childIndex;\n chainCode;\n privKey;\n pubKey;\n constants = {\n pubKey: 0x0488b21e,\n privKey: 0x0488ade4\n };\n /**\n * Constructor for the BIP32 HD wallet.\n * Initializes an HD wallet with optional parameters for version bytes, depth, parent fingerprint, child index, chain code, private key, and public key.\n * @param versionBytesNum - Version bytes number for the wallet.\n * @param depth - Depth of the key in the hierarchy.\n * @param parentFingerPrint - Fingerprint of the parent key.\n * @param childIndex - Index of the child key.\n * @param chainCode - Chain code for key derivation.\n * @param privKey - Private key of the wallet.\n * @param pubKey - Public key of the wallet.\n */\n constructor(versionBytesNum, depth, parentFingerPrint, childIndex, chainCode, privKey, pubKey) {\n this.versionBytesNum = versionBytesNum;\n this.depth = depth;\n this.parentFingerPrint = parentFingerPrint;\n this.childIndex = childIndex;\n this.chainCode = chainCode;\n this.privKey = privKey;\n this.pubKey = pubKey;\n }\n /**\n * Generates a new HD wallet with random keys.\n * This method creates a root HD wallet with randomly generated private and public keys.\n * @returns {HD} The current HD instance with generated keys.\n */\n fromRandom() {\n this.versionBytesNum = this.constants.privKey;\n this.depth = 0x00;\n this.parentFingerPrint = [0, 0, 0, 0];\n this.childIndex = 0;\n this.chainCode = Random(32);\n this.privKey = PrivateKey.fromRandom();\n this.pubKey = this.privKey.toPublicKey();\n return this;\n }\n /**\n * Generates a new HD wallet with random keys.\n * This method creates a root HD wallet with randomly generated private and public keys.\n * @returns {HD} A new HD instance with generated keys.\n * @static\n */\n static fromRandom() {\n return new this().fromRandom();\n }\n /**\n * Initializes the HD wallet from a given base58 encoded string.\n * This method decodes a provided string to set up the HD wallet's properties.\n * @param str - A base58 encoded string representing the wallet.\n * @returns {HD} The new instance with properties set from the string.\n */\n static fromString(str) {\n return new this().fromString(str);\n }\n /**\n * Initializes the HD wallet from a given base58 encoded string.\n * This method decodes a provided string to set up the HD wallet's properties.\n * @param str - A base58 encoded string representing the wallet.\n * @returns {HD} The current instance with properties set from the string.\n */\n fromString(str) {\n const decoded = fromBase58Check(str);\n return this.fromBinary([...decoded.prefix, ...decoded.data]);\n }\n /**\n * Initializes the HD wallet from a seed.\n * This method generates keys and other properties from a given seed, conforming to the BIP32 specification.\n * @param bytes - An array of bytes representing the seed.\n * @returns {HD} The current instance with properties set from the seed.\n */\n static fromSeed(bytes) {\n return new this().fromSeed(bytes);\n }\n /**\n * Initializes the HD wallet from a seed.\n * This method generates keys and other properties from a given seed, conforming to the BIP32 specification.\n * @param bytes - An array of bytes representing the seed.\n * @returns {HD} The current instance with properties set from the seed.\n */\n fromSeed(bytes) {\n if (bytes.length < 128 / 8) {\n throw new Error('Need more than 128 bits of entropy');\n }\n if (bytes.length > 512 / 8) {\n throw new Error('More than 512 bits of entropy is nonstandard');\n }\n const hash = Hash.sha512hmac(toArray('Bitcoin seed', 'utf8'), bytes);\n this.depth = 0x00;\n this.parentFingerPrint = [0, 0, 0, 0];\n this.childIndex = 0;\n this.chainCode = hash.slice(32, 64);\n this.versionBytesNum = this.constants.privKey;\n this.privKey = new PrivateKey(hash.slice(0, 32));\n this.pubKey = this.privKey.toPublicKey();\n return this;\n }\n /**\n * Initializes the HD wallet from a binary buffer.\n * Parses a binary buffer to set up the wallet's properties.\n * @param buf - A buffer containing the wallet data.\n * @returns {HD} The new instance with properties set from the buffer.\n */\n static fromBinary(buf) {\n return new this().fromBinary(buf);\n }\n /**\n * Initializes the HD wallet from a binary buffer.\n * Parses a binary buffer to set up the wallet's properties.\n * @param buf - A buffer containing the wallet data.\n * @returns {HD} The current instance with properties set from the buffer.\n */\n fromBinary(buf) {\n // Both pub and private extended keys are 78 buf\n if (buf.length !== 78) {\n throw new Error('incorrect bip32 data length');\n }\n const reader = new Reader(buf);\n this.versionBytesNum = reader.readUInt32BE();\n this.depth = reader.readUInt8();\n this.parentFingerPrint = reader.read(4);\n this.childIndex = reader.readUInt32BE();\n this.chainCode = reader.read(32);\n const keyBytes = reader.read(33);\n const isPrivate = this.versionBytesNum === this.constants.privKey;\n const isPublic = this.versionBytesNum === this.constants.pubKey;\n if (isPrivate && keyBytes[0] === 0) {\n this.privKey = new PrivateKey(keyBytes.slice(1, 33));\n this.pubKey = this.privKey.toPublicKey();\n }\n else if (isPublic && (keyBytes[0] === 0x02 || keyBytes[0] === 0x03)) {\n this.pubKey = PublicKey.fromString(toHex(keyBytes));\n }\n else {\n throw new Error('Invalid key');\n }\n return this;\n }\n /**\n * Converts the HD wallet to a base58 encoded string.\n * This method provides a string representation of the HD wallet's current state.\n * @returns {string} A base58 encoded string of the HD wallet.\n */\n toString() {\n const bin = this.toBinary();\n return toBase58Check(bin, []);\n }\n /**\n * Derives a child HD wallet based on a given path.\n * The path specifies the hierarchy of the child key to be derived.\n * @param path - A string representing the derivation path (e.g., 'm/0'/1).\n * @returns {HD} A new HD instance representing the derived child wallet.\n */\n derive(path) {\n if (path === 'm') {\n return this;\n }\n const e = path.split('/');\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let bip32 = this;\n for (const [i, c] of e.entries()) {\n if (i === 0) { // Since `i` is now a number, compare it to 0\n if (c !== 'm') {\n throw new Error('invalid path');\n }\n continue;\n }\n if (parseInt(c.replace(\"'\", ''), 10).toString() !== c.replace(\"'\", '')) {\n throw new Error('invalid path');\n }\n const usePrivate = c.length > 1 && c[c.length - 1] === \"'\";\n let childIndex = parseInt(usePrivate ? c.slice(0, c.length - 1) : c, 10) & 0x7fffffff;\n if (usePrivate) {\n childIndex += 0x80000000;\n }\n bip32 = bip32.deriveChild(childIndex);\n }\n return bip32;\n }\n /**\n * Derives a child HD wallet from the current wallet based on an index.\n * This method generates either a private or public child key depending on the current wallet's state.\n * @param i - The index of the child key to derive.\n * @returns {HD} A new HD instance representing the derived child wallet.\n */\n deriveChild(i) {\n if (typeof i !== 'number') {\n throw new Error('i must be a number');\n }\n const ibc = [];\n ibc.push((i >> 24) & 0xff);\n ibc.push((i >> 16) & 0xff);\n ibc.push((i >> 8) & 0xff);\n ibc.push(i & 0xff);\n const ib = [...ibc];\n const usePrivate = (i & 0x80000000) !== 0;\n const isPrivate = this.versionBytesNum === this.constants.privKey;\n if (usePrivate && (this.privKey === null || this.privKey === undefined || !isPrivate)) {\n throw new Error('Cannot do private key derivation without private key');\n }\n let ret = null;\n if (this.privKey !== null && this.privKey !== undefined) {\n let data = null;\n if (usePrivate) {\n data = [0, ...this.privKey.toArray('be', 32), ...ib];\n }\n else {\n data = [...this.pubKey.encode(true), ...ib];\n }\n const hash = Hash.sha512hmac(this.chainCode, data);\n const il = new BigNumber(hash.slice(0, 32));\n const ir = hash.slice(32, 64);\n // ki = IL + kpar (mod n).\n const k = il.add(this.privKey).mod(new Curve().n);\n ret = new HD();\n ret.chainCode = ir;\n ret.privKey = new PrivateKey(k.toArray());\n ret.pubKey = ret.privKey.toPublicKey();\n }\n else {\n const data = [...this.pubKey.encode(true), ...ib];\n const hash = Hash.sha512hmac(this.chainCode, data);\n const il = new BigNumber(hash.slice(0, 32));\n const ir = hash.slice(32, 64);\n // Ki = (IL + kpar)*G = IL*G + Kpar\n const ilG = new Curve().g.mul(il);\n const Kpar = this.pubKey;\n const Ki = ilG.add(Kpar);\n const newpub = new PublicKey(Ki.x, Ki.y);\n ret = new HD();\n ret.chainCode = ir;\n ret.pubKey = newpub;\n }\n ret.childIndex = i;\n const pubKeyhash = Hash.hash160(this.pubKey.encode(true));\n ret.parentFingerPrint = pubKeyhash.slice(0, 4);\n ret.versionBytesNum = this.versionBytesNum;\n ret.depth = this.depth + 1;\n return ret;\n }\n /**\n * Converts the current HD wallet to a public-only wallet.\n * This method strips away the private key information, leaving only the public part.\n * @returns {HD} A new HD instance representing the public-only wallet.\n */\n toPublic() {\n const bip32 = new HD(this.versionBytesNum, this.depth, this.parentFingerPrint, this.childIndex, this.chainCode, this.privKey, this.pubKey);\n bip32.versionBytesNum = this.constants.pubKey;\n bip32.privKey = undefined;\n return bip32;\n }\n /**\n * Converts the HD wallet into a binary representation.\n * This method serializes the wallet's properties into a binary format.\n * @returns {number[]} An array of numbers representing the binary data of the wallet.\n */\n toBinary() {\n const isPrivate = this.versionBytesNum === this.constants.privKey;\n const isPublic = this.versionBytesNum === this.constants.pubKey;\n if (isPrivate) {\n return new Writer()\n .writeUInt32BE(this.versionBytesNum)\n .writeUInt8(this.depth)\n .write(this.parentFingerPrint)\n .writeUInt32BE(this.childIndex)\n .write(this.chainCode)\n .writeUInt8(0)\n .write(this.privKey.toArray('be', 32))\n .toArray();\n }\n else if (isPublic) {\n return new Writer()\n .writeUInt32BE(this.versionBytesNum)\n .writeUInt8(this.depth)\n .write(this.parentFingerPrint)\n .writeUInt32BE(this.childIndex)\n .write(this.chainCode)\n .write(this.pubKey.encode(true))\n .toArray();\n }\n else {\n throw new Error('bip32: invalid versionBytesNum byte');\n }\n }\n /**\n * Checks if the HD wallet contains a private key.\n * This method determines whether the wallet is a private key wallet or a public key only wallet.\n * @returns {boolean} A boolean value indicating whether the wallet has a private key (true) or not (false).\n */\n isPrivate() {\n return this.versionBytesNum === this.constants.privKey;\n }\n}\n//# sourceMappingURL=HD.js.map","export const wordList = {\n value: [\n 'abandon',\n 'ability',\n 'able',\n 'about',\n 'above',\n 'absent',\n 'absorb',\n 'abstract',\n 'absurd',\n 'abuse',\n 'access',\n 'accident',\n 'account',\n 'accuse',\n 'achieve',\n 'acid',\n 'acoustic',\n 'acquire',\n 'across',\n 'act',\n 'action',\n 'actor',\n 'actress',\n 'actual',\n 'adapt',\n 'add',\n 'addict',\n 'address',\n 'adjust',\n 'admit',\n 'adult',\n 'advance',\n 'advice',\n 'aerobic',\n 'affair',\n 'afford',\n 'afraid',\n 'again',\n 'age',\n 'agent',\n 'agree',\n 'ahead',\n 'aim',\n 'air',\n 'airport',\n 'aisle',\n 'alarm',\n 'album',\n 'alcohol',\n 'alert',\n 'alien',\n 'all',\n 'alley',\n 'allow',\n 'almost',\n 'alone',\n 'alpha',\n 'already',\n 'also',\n 'alter',\n 'always',\n 'amateur',\n 'amazing',\n 'among',\n 'amount',\n 'amused',\n 'analyst',\n 'anchor',\n 'ancient',\n 'anger',\n 'angle',\n 'angry',\n 'animal',\n 'ankle',\n 'announce',\n 'annual',\n 'another',\n 'answer',\n 'antenna',\n 'antique',\n 'anxiety',\n 'any',\n 'apart',\n 'apology',\n 'appear',\n 'apple',\n 'approve',\n 'april',\n 'arch',\n 'arctic',\n 'area',\n 'arena',\n 'argue',\n 'arm',\n 'armed',\n 'armor',\n 'army',\n 'around',\n 'arrange',\n 'arrest',\n 'arrive',\n 'arrow',\n 'art',\n 'artefact',\n 'artist',\n 'artwork',\n 'ask',\n 'aspect',\n 'assault',\n 'asset',\n 'assist',\n 'assume',\n 'asthma',\n 'athlete',\n 'atom',\n 'attack',\n 'attend',\n 'attitude',\n 'attract',\n 'auction',\n 'audit',\n 'august',\n 'aunt',\n 'author',\n 'auto',\n 'autumn',\n 'average',\n 'avocado',\n 'avoid',\n 'awake',\n 'aware',\n 'away',\n 'awesome',\n 'awful',\n 'awkward',\n 'axis',\n 'baby',\n 'bachelor',\n 'bacon',\n 'badge',\n 'bag',\n 'balance',\n 'balcony',\n 'ball',\n 'bamboo',\n 'banana',\n 'banner',\n 'bar',\n 'barely',\n 'bargain',\n 'barrel',\n 'base',\n 'basic',\n 'basket',\n 'battle',\n 'beach',\n 'bean',\n 'beauty',\n 'because',\n 'become',\n 'beef',\n 'before',\n 'begin',\n 'behave',\n 'behind',\n 'believe',\n 'below',\n 'belt',\n 'bench',\n 'benefit',\n 'best',\n 'betray',\n 'better',\n 'between',\n 'beyond',\n 'bicycle',\n 'bid',\n 'bike',\n 'bind',\n 'biology',\n 'bird',\n 'birth',\n 'bitter',\n 'black',\n 'blade',\n 'blame',\n 'blanket',\n 'blast',\n 'bleak',\n 'bless',\n 'blind',\n 'blood',\n 'blossom',\n 'blouse',\n 'blue',\n 'blur',\n 'blush',\n 'board',\n 'boat',\n 'body',\n 'boil',\n 'bomb',\n 'bone',\n 'bonus',\n 'book',\n 'boost',\n 'border',\n 'boring',\n 'borrow',\n 'boss',\n 'bottom',\n 'bounce',\n 'box',\n 'boy',\n 'bracket',\n 'brain',\n 'brand',\n 'brass',\n 'brave',\n 'bread',\n 'breeze',\n 'brick',\n 'bridge',\n 'brief',\n 'bright',\n 'bring',\n 'brisk',\n 'broccoli',\n 'broken',\n 'bronze',\n 'broom',\n 'brother',\n 'brown',\n 'brush',\n 'bubble',\n 'buddy',\n 'budget',\n 'buffalo',\n 'build',\n 'bulb',\n 'bulk',\n 'bullet',\n 'bundle',\n 'bunker',\n 'burden',\n 'burger',\n 'burst',\n 'bus',\n 'business',\n 'busy',\n 'butter',\n 'buyer',\n 'buzz',\n 'cabbage',\n 'cabin',\n 'cable',\n 'cactus',\n 'cage',\n 'cake',\n 'call',\n 'calm',\n 'camera',\n 'camp',\n 'can',\n 'canal',\n 'cancel',\n 'candy',\n 'cannon',\n 'canoe',\n 'canvas',\n 'canyon',\n 'capable',\n 'capital',\n 'captain',\n 'car',\n 'carbon',\n 'card',\n 'cargo',\n 'carpet',\n 'carry',\n 'cart',\n 'case',\n 'cash',\n 'casino',\n 'castle',\n 'casual',\n 'cat',\n 'catalog',\n 'catch',\n 'category',\n 'cattle',\n 'caught',\n 'cause',\n 'caution',\n 'cave',\n 'ceiling',\n 'celery',\n 'cement',\n 'census',\n 'century',\n 'cereal',\n 'certain',\n 'chair',\n 'chalk',\n 'champion',\n 'change',\n 'chaos',\n 'chapter',\n 'charge',\n 'chase',\n 'chat',\n 'cheap',\n 'check',\n 'cheese',\n 'chef',\n 'cherry',\n 'chest',\n 'chicken',\n 'chief',\n 'child',\n 'chimney',\n 'choice',\n 'choose',\n 'chronic',\n 'chuckle',\n 'chunk',\n 'churn',\n 'cigar',\n 'cinnamon',\n 'circle',\n 'citizen',\n 'city',\n 'civil',\n 'claim',\n 'clap',\n 'clarify',\n 'claw',\n 'clay',\n 'clean',\n 'clerk',\n 'clever',\n 'click',\n 'client',\n 'cliff',\n 'climb',\n 'clinic',\n 'clip',\n 'clock',\n 'clog',\n 'close',\n 'cloth',\n 'cloud',\n 'clown',\n 'club',\n 'clump',\n 'cluster',\n 'clutch',\n 'coach',\n 'coast',\n 'coconut',\n 'code',\n 'coffee',\n 'coil',\n 'coin',\n 'collect',\n 'color',\n 'column',\n 'combine',\n 'come',\n 'comfort',\n 'comic',\n 'common',\n 'company',\n 'concert',\n 'conduct',\n 'confirm',\n 'congress',\n 'connect',\n 'consider',\n 'control',\n 'convince',\n 'cook',\n 'cool',\n 'copper',\n 'copy',\n 'coral',\n 'core',\n 'corn',\n 'correct',\n 'cost',\n 'cotton',\n 'couch',\n 'country',\n 'couple',\n 'course',\n 'cousin',\n 'cover',\n 'coyote',\n 'crack',\n 'cradle',\n 'craft',\n 'cram',\n 'crane',\n 'crash',\n 'crater',\n 'crawl',\n 'crazy',\n 'cream',\n 'credit',\n 'creek',\n 'crew',\n 'cricket',\n 'crime',\n 'crisp',\n 'critic',\n 'crop',\n 'cross',\n 'crouch',\n 'crowd',\n 'crucial',\n 'cruel',\n 'cruise',\n 'crumble',\n 'crunch',\n 'crush',\n 'cry',\n 'crystal',\n 'cube',\n 'culture',\n 'cup',\n 'cupboard',\n 'curious',\n 'current',\n 'curtain',\n 'curve',\n 'cushion',\n 'custom',\n 'cute',\n 'cycle',\n 'dad',\n 'damage',\n 'damp',\n 'dance',\n 'danger',\n 'daring',\n 'dash',\n 'daughter',\n 'dawn',\n 'day',\n 'deal',\n 'debate',\n 'debris',\n 'decade',\n 'december',\n 'decide',\n 'decline',\n 'decorate',\n 'decrease',\n 'deer',\n 'defense',\n 'define',\n 'defy',\n 'degree',\n 'delay',\n 'deliver',\n 'demand',\n 'demise',\n 'denial',\n 'dentist',\n 'deny',\n 'depart',\n 'depend',\n 'deposit',\n 'depth',\n 'deputy',\n 'derive',\n 'describe',\n 'desert',\n 'design',\n 'desk',\n 'despair',\n 'destroy',\n 'detail',\n 'detect',\n 'develop',\n 'device',\n 'devote',\n 'diagram',\n 'dial',\n 'diamond',\n 'diary',\n 'dice',\n 'diesel',\n 'diet',\n 'differ',\n 'digital',\n 'dignity',\n 'dilemma',\n 'dinner',\n 'dinosaur',\n 'direct',\n 'dirt',\n 'disagree',\n 'discover',\n 'disease',\n 'dish',\n 'dismiss',\n 'disorder',\n 'display',\n 'distance',\n 'divert',\n 'divide',\n 'divorce',\n 'dizzy',\n 'doctor',\n 'document',\n 'dog',\n 'doll',\n 'dolphin',\n 'domain',\n 'donate',\n 'donkey',\n 'donor',\n 'door',\n 'dose',\n 'double',\n 'dove',\n 'draft',\n 'dragon',\n 'drama',\n 'drastic',\n 'draw',\n 'dream',\n 'dress',\n 'drift',\n 'drill',\n 'drink',\n 'drip',\n 'drive',\n 'drop',\n 'drum',\n 'dry',\n 'duck',\n 'dumb',\n 'dune',\n 'during',\n 'dust',\n 'dutch',\n 'duty',\n 'dwarf',\n 'dynamic',\n 'eager',\n 'eagle',\n 'early',\n 'earn',\n 'earth',\n 'easily',\n 'east',\n 'easy',\n 'echo',\n 'ecology',\n 'economy',\n 'edge',\n 'edit',\n 'educate',\n 'effort',\n 'egg',\n 'eight',\n 'either',\n 'elbow',\n 'elder',\n 'electric',\n 'elegant',\n 'element',\n 'elephant',\n 'elevator',\n 'elite',\n 'else',\n 'embark',\n 'embody',\n 'embrace',\n 'emerge',\n 'emotion',\n 'employ',\n 'empower',\n 'empty',\n 'enable',\n 'enact',\n 'end',\n 'endless',\n 'endorse',\n 'enemy',\n 'energy',\n 'enforce',\n 'engage',\n 'engine',\n 'enhance',\n 'enjoy',\n 'enlist',\n 'enough',\n 'enrich',\n 'enroll',\n 'ensure',\n 'enter',\n 'entire',\n 'entry',\n 'envelope',\n 'episode',\n 'equal',\n 'equip',\n 'era',\n 'erase',\n 'erode',\n 'erosion',\n 'error',\n 'erupt',\n 'escape',\n 'essay',\n 'essence',\n 'estate',\n 'eternal',\n 'ethics',\n 'evidence',\n 'evil',\n 'evoke',\n 'evolve',\n 'exact',\n 'example',\n 'excess',\n 'exchange',\n 'excite',\n 'exclude',\n 'excuse',\n 'execute',\n 'exercise',\n 'exhaust',\n 'exhibit',\n 'exile',\n 'exist',\n 'exit',\n 'exotic',\n 'expand',\n 'expect',\n 'expire',\n 'explain',\n 'expose',\n 'express',\n 'extend',\n 'extra',\n 'eye',\n 'eyebrow',\n 'fabric',\n 'face',\n 'faculty',\n 'fade',\n 'faint',\n 'faith',\n 'fall',\n 'false',\n 'fame',\n 'family',\n 'famous',\n 'fan',\n 'fancy',\n 'fantasy',\n 'farm',\n 'fashion',\n 'fat',\n 'fatal',\n 'father',\n 'fatigue',\n 'fault',\n 'favorite',\n 'feature',\n 'february',\n 'federal',\n 'fee',\n 'feed',\n 'feel',\n 'female',\n 'fence',\n 'festival',\n 'fetch',\n 'fever',\n 'few',\n 'fiber',\n 'fiction',\n 'field',\n 'figure',\n 'file',\n 'film',\n 'filter',\n 'final',\n 'find',\n 'fine',\n 'finger',\n 'finish',\n 'fire',\n 'firm',\n 'first',\n 'fiscal',\n 'fish',\n 'fit',\n 'fitness',\n 'fix',\n 'flag',\n 'flame',\n 'flash',\n 'flat',\n 'flavor',\n 'flee',\n 'flight',\n 'flip',\n 'float',\n 'flock',\n 'floor',\n 'flower',\n 'fluid',\n 'flush',\n 'fly',\n 'foam',\n 'focus',\n 'fog',\n 'foil',\n 'fold',\n 'follow',\n 'food',\n 'foot',\n 'force',\n 'forest',\n 'forget',\n 'fork',\n 'fortune',\n 'forum',\n 'forward',\n 'fossil',\n 'foster',\n 'found',\n 'fox',\n 'fragile',\n 'frame',\n 'frequent',\n 'fresh',\n 'friend',\n 'fringe',\n 'frog',\n 'front',\n 'frost',\n 'frown',\n 'frozen',\n 'fruit',\n 'fuel',\n 'fun',\n 'funny',\n 'furnace',\n 'fury',\n 'future',\n 'gadget',\n 'gain',\n 'galaxy',\n 'gallery',\n 'game',\n 'gap',\n 'garage',\n 'garbage',\n 'garden',\n 'garlic',\n 'garment',\n 'gas',\n 'gasp',\n 'gate',\n 'gather',\n 'gauge',\n 'gaze',\n 'general',\n 'genius',\n 'genre',\n 'gentle',\n 'genuine',\n 'gesture',\n 'ghost',\n 'giant',\n 'gift',\n 'giggle',\n 'ginger',\n 'giraffe',\n 'girl',\n 'give',\n 'glad',\n 'glance',\n 'glare',\n 'glass',\n 'glide',\n 'glimpse',\n 'globe',\n 'gloom',\n 'glory',\n 'glove',\n 'glow',\n 'glue',\n 'goat',\n 'goddess',\n 'gold',\n 'good',\n 'goose',\n 'gorilla',\n 'gospel',\n 'gossip',\n 'govern',\n 'gown',\n 'grab',\n 'grace',\n 'grain',\n 'grant',\n 'grape',\n 'grass',\n 'gravity',\n 'great',\n 'green',\n 'grid',\n 'grief',\n 'grit',\n 'grocery',\n 'group',\n 'grow',\n 'grunt',\n 'guard',\n 'guess',\n 'guide',\n 'guilt',\n 'guitar',\n 'gun',\n 'gym',\n 'habit',\n 'hair',\n 'half',\n 'hammer',\n 'hamster',\n 'hand',\n 'happy',\n 'harbor',\n 'hard',\n 'harsh',\n 'harvest',\n 'hat',\n 'have',\n 'hawk',\n 'hazard',\n 'head',\n 'health',\n 'heart',\n 'heavy',\n 'hedgehog',\n 'height',\n 'hello',\n 'helmet',\n 'help',\n 'hen',\n 'hero',\n 'hidden',\n 'high',\n 'hill',\n 'hint',\n 'hip',\n 'hire',\n 'history',\n 'hobby',\n 'hockey',\n 'hold',\n 'hole',\n 'holiday',\n 'hollow',\n 'home',\n 'honey',\n 'hood',\n 'hope',\n 'horn',\n 'horror',\n 'horse',\n 'hospital',\n 'host',\n 'hotel',\n 'hour',\n 'hover',\n 'hub',\n 'huge',\n 'human',\n 'humble',\n 'humor',\n 'hundred',\n 'hungry',\n 'hunt',\n 'hurdle',\n 'hurry',\n 'hurt',\n 'husband',\n 'hybrid',\n 'ice',\n 'icon',\n 'idea',\n 'identify',\n 'idle',\n 'ignore',\n 'ill',\n 'illegal',\n 'illness',\n 'image',\n 'imitate',\n 'immense',\n 'immune',\n 'impact',\n 'impose',\n 'improve',\n 'impulse',\n 'inch',\n 'include',\n 'income',\n 'increase',\n 'index',\n 'indicate',\n 'indoor',\n 'industry',\n 'infant',\n 'inflict',\n 'inform',\n 'inhale',\n 'inherit',\n 'initial',\n 'inject',\n 'injury',\n 'inmate',\n 'inner',\n 'innocent',\n 'input',\n 'inquiry',\n 'insane',\n 'insect',\n 'inside',\n 'inspire',\n 'install',\n 'intact',\n 'interest',\n 'into',\n 'invest',\n 'invite',\n 'involve',\n 'iron',\n 'island',\n 'isolate',\n 'issue',\n 'item',\n 'ivory',\n 'jacket',\n 'jaguar',\n 'jar',\n 'jazz',\n 'jealous',\n 'jeans',\n 'jelly',\n 'jewel',\n 'job',\n 'join',\n 'joke',\n 'journey',\n 'joy',\n 'judge',\n 'juice',\n 'jump',\n 'jungle',\n 'junior',\n 'junk',\n 'just',\n 'kangaroo',\n 'keen',\n 'keep',\n 'ketchup',\n 'key',\n 'kick',\n 'kid',\n 'kidney',\n 'kind',\n 'kingdom',\n 'kiss',\n 'kit',\n 'kitchen',\n 'kite',\n 'kitten',\n 'kiwi',\n 'knee',\n 'knife',\n 'knock',\n 'know',\n 'lab',\n 'label',\n 'labor',\n 'ladder',\n 'lady',\n 'lake',\n 'lamp',\n 'language',\n 'laptop',\n 'large',\n 'later',\n 'latin',\n 'laugh',\n 'laundry',\n 'lava',\n 'law',\n 'lawn',\n 'lawsuit',\n 'layer',\n 'lazy',\n 'leader',\n 'leaf',\n 'learn',\n 'leave',\n 'lecture',\n 'left',\n 'leg',\n 'legal',\n 'legend',\n 'leisure',\n 'lemon',\n 'lend',\n 'length',\n 'lens',\n 'leopard',\n 'lesson',\n 'letter',\n 'level',\n 'liar',\n 'liberty',\n 'library',\n 'license',\n 'life',\n 'lift',\n 'light',\n 'like',\n 'limb',\n 'limit',\n 'link',\n 'lion',\n 'liquid',\n 'list',\n 'little',\n 'live',\n 'lizard',\n 'load',\n 'loan',\n 'lobster',\n 'local',\n 'lock',\n 'logic',\n 'lonely',\n 'long',\n 'loop',\n 'lottery',\n 'loud',\n 'lounge',\n 'love',\n 'loyal',\n 'lucky',\n 'luggage',\n 'lumber',\n 'lunar',\n 'lunch',\n 'luxury',\n 'lyrics',\n 'machine',\n 'mad',\n 'magic',\n 'magnet',\n 'maid',\n 'mail',\n 'main',\n 'major',\n 'make',\n 'mammal',\n 'man',\n 'manage',\n 'mandate',\n 'mango',\n 'mansion',\n 'manual',\n 'maple',\n 'marble',\n 'march',\n 'margin',\n 'marine',\n 'market',\n 'marriage',\n 'mask',\n 'mass',\n 'master',\n 'match',\n 'material',\n 'math',\n 'matrix',\n 'matter',\n 'maximum',\n 'maze',\n 'meadow',\n 'mean',\n 'measure',\n 'meat',\n 'mechanic',\n 'medal',\n 'media',\n 'melody',\n 'melt',\n 'member',\n 'memory',\n 'mention',\n 'menu',\n 'mercy',\n 'merge',\n 'merit',\n 'merry',\n 'mesh',\n 'message',\n 'metal',\n 'method',\n 'middle',\n 'midnight',\n 'milk',\n 'million',\n 'mimic',\n 'mind',\n 'minimum',\n 'minor',\n 'minute',\n 'miracle',\n 'mirror',\n 'misery',\n 'miss',\n 'mistake',\n 'mix',\n 'mixed',\n 'mixture',\n 'mobile',\n 'model',\n 'modify',\n 'mom',\n 'moment',\n 'monitor',\n 'monkey',\n 'monster',\n 'month',\n 'moon',\n 'moral',\n 'more',\n 'morning',\n 'mosquito',\n 'mother',\n 'motion',\n 'motor',\n 'mountain',\n 'mouse',\n 'move',\n 'movie',\n 'much',\n 'muffin',\n 'mule',\n 'multiply',\n 'muscle',\n 'museum',\n 'mushroom',\n 'music',\n 'must',\n 'mutual',\n 'myself',\n 'mystery',\n 'myth',\n 'naive',\n 'name',\n 'napkin',\n 'narrow',\n 'nasty',\n 'nation',\n 'nature',\n 'near',\n 'neck',\n 'need',\n 'negative',\n 'neglect',\n 'neither',\n 'nephew',\n 'nerve',\n 'nest',\n 'net',\n 'network',\n 'neutral',\n 'never',\n 'news',\n 'next',\n 'nice',\n 'night',\n 'noble',\n 'noise',\n 'nominee',\n 'noodle',\n 'normal',\n 'north',\n 'nose',\n 'notable',\n 'note',\n 'nothing',\n 'notice',\n 'novel',\n 'now',\n 'nuclear',\n 'number',\n 'nurse',\n 'nut',\n 'oak',\n 'obey',\n 'object',\n 'oblige',\n 'obscure',\n 'observe',\n 'obtain',\n 'obvious',\n 'occur',\n 'ocean',\n 'october',\n 'odor',\n 'off',\n 'offer',\n 'office',\n 'often',\n 'oil',\n 'okay',\n 'old',\n 'olive',\n 'olympic',\n 'omit',\n 'once',\n 'one',\n 'onion',\n 'online',\n 'only',\n 'open',\n 'opera',\n 'opinion',\n 'oppose',\n 'option',\n 'orange',\n 'orbit',\n 'orchard',\n 'order',\n 'ordinary',\n 'organ',\n 'orient',\n 'original',\n 'orphan',\n 'ostrich',\n 'other',\n 'outdoor',\n 'outer',\n 'output',\n 'outside',\n 'oval',\n 'oven',\n 'over',\n 'own',\n 'owner',\n 'oxygen',\n 'oyster',\n 'ozone',\n 'pact',\n 'paddle',\n 'page',\n 'pair',\n 'palace',\n 'palm',\n 'panda',\n 'panel',\n 'panic',\n 'panther',\n 'paper',\n 'parade',\n 'parent',\n 'park',\n 'parrot',\n 'party',\n 'pass',\n 'patch',\n 'path',\n 'patient',\n 'patrol',\n 'pattern',\n 'pause',\n 'pave',\n 'payment',\n 'peace',\n 'peanut',\n 'pear',\n 'peasant',\n 'pelican',\n 'pen',\n 'penalty',\n 'pencil',\n 'people',\n 'pepper',\n 'perfect',\n 'permit',\n 'person',\n 'pet',\n 'phone',\n 'photo',\n 'phrase',\n 'physical',\n 'piano',\n 'picnic',\n 'picture',\n 'piece',\n 'pig',\n 'pigeon',\n 'pill',\n 'pilot',\n 'pink',\n 'pioneer',\n 'pipe',\n 'pistol',\n 'pitch',\n 'pizza',\n 'place',\n 'planet',\n 'plastic',\n 'plate',\n 'play',\n 'please',\n 'pledge',\n 'pluck',\n 'plug',\n 'plunge',\n 'poem',\n 'poet',\n 'point',\n 'polar',\n 'pole',\n 'police',\n 'pond',\n 'pony',\n 'pool',\n 'popular',\n 'portion',\n 'position',\n 'possible',\n 'post',\n 'potato',\n 'pottery',\n 'poverty',\n 'powder',\n 'power',\n 'practice',\n 'praise',\n 'predict',\n 'prefer',\n 'prepare',\n 'present',\n 'pretty',\n 'prevent',\n 'price',\n 'pride',\n 'primary',\n 'print',\n 'priority',\n 'prison',\n 'private',\n 'prize',\n 'problem',\n 'process',\n 'produce',\n 'profit',\n 'program',\n 'project',\n 'promote',\n 'proof',\n 'property',\n 'prosper',\n 'protect',\n 'proud',\n 'provide',\n 'public',\n 'pudding',\n 'pull',\n 'pulp',\n 'pulse',\n 'pumpkin',\n 'punch',\n 'pupil',\n 'puppy',\n 'purchase',\n 'purity',\n 'purpose',\n 'purse',\n 'push',\n 'put',\n 'puzzle',\n 'pyramid',\n 'quality',\n 'quantum',\n 'quarter',\n 'question',\n 'quick',\n 'quit',\n 'quiz',\n 'quote',\n 'rabbit',\n 'raccoon',\n 'race',\n 'rack',\n 'radar',\n 'radio',\n 'rail',\n 'rain',\n 'raise',\n 'rally',\n 'ramp',\n 'ranch',\n 'random',\n 'range',\n 'rapid',\n 'rare',\n 'rate',\n 'rather',\n 'raven',\n 'raw',\n 'razor',\n 'ready',\n 'real',\n 'reason',\n 'rebel',\n 'rebuild',\n 'recall',\n 'receive',\n 'recipe',\n 'record',\n 'recycle',\n 'reduce',\n 'reflect',\n 'reform',\n 'refuse',\n 'region',\n 'regret',\n 'regular',\n 'reject',\n 'relax',\n 'release',\n 'relief',\n 'rely',\n 'remain',\n 'remember',\n 'remind',\n 'remove',\n 'render',\n 'renew',\n 'rent',\n 'reopen',\n 'repair',\n 'repeat',\n 'replace',\n 'report',\n 'require',\n 'rescue',\n 'resemble',\n 'resist',\n 'resource',\n 'response',\n 'result',\n 'retire',\n 'retreat',\n 'return',\n 'reunion',\n 'reveal',\n 'review',\n 'reward',\n 'rhythm',\n 'rib',\n 'ribbon',\n 'rice',\n 'rich',\n 'ride',\n 'ridge',\n 'rifle',\n 'right',\n 'rigid',\n 'ring',\n 'riot',\n 'ripple',\n 'risk',\n 'ritual',\n 'rival',\n 'river',\n 'road',\n 'roast',\n 'robot',\n 'robust',\n 'rocket',\n 'romance',\n 'roof',\n 'rookie',\n 'room',\n 'rose',\n 'rotate',\n 'rough',\n 'round',\n 'route',\n 'royal',\n 'rubber',\n 'rude',\n 'rug',\n 'rule',\n 'run',\n 'runway',\n 'rural',\n 'sad',\n 'saddle',\n 'sadness',\n 'safe',\n 'sail',\n 'salad',\n 'salmon',\n 'salon',\n 'salt',\n 'salute',\n 'same',\n 'sample',\n 'sand',\n 'satisfy',\n 'satoshi',\n 'sauce',\n 'sausage',\n 'save',\n 'say',\n 'scale',\n 'scan',\n 'scare',\n 'scatter',\n 'scene',\n 'scheme',\n 'school',\n 'science',\n 'scissors',\n 'scorpion',\n 'scout',\n 'scrap',\n 'screen',\n 'script',\n 'scrub',\n 'sea',\n 'search',\n 'season',\n 'seat',\n 'second',\n 'secret',\n 'section',\n 'security',\n 'seed',\n 'seek',\n 'segment',\n 'select',\n 'sell',\n 'seminar',\n 'senior',\n 'sense',\n 'sentence',\n 'series',\n 'service',\n 'session',\n 'settle',\n 'setup',\n 'seven',\n 'shadow',\n 'shaft',\n 'shallow',\n 'share',\n 'shed',\n 'shell',\n 'sheriff',\n 'shield',\n 'shift',\n 'shine',\n 'ship',\n 'shiver',\n 'shock',\n 'shoe',\n 'shoot',\n 'shop',\n 'short',\n 'shoulder',\n 'shove',\n 'shrimp',\n 'shrug',\n 'shuffle',\n 'shy',\n 'sibling',\n 'sick',\n 'side',\n 'siege',\n 'sight',\n 'sign',\n 'silent',\n 'silk',\n 'silly',\n 'silver',\n 'similar',\n 'simple',\n 'since',\n 'sing',\n 'siren',\n 'sister',\n 'situate',\n 'six',\n 'size',\n 'skate',\n 'sketch',\n 'ski',\n 'skill',\n 'skin',\n 'skirt',\n 'skull',\n 'slab',\n 'slam',\n 'sleep',\n 'slender',\n 'slice',\n 'slide',\n 'slight',\n 'slim',\n 'slogan',\n 'slot',\n 'slow',\n 'slush',\n 'small',\n 'smart',\n 'smile',\n 'smoke',\n 'smooth',\n 'snack',\n 'snake',\n 'snap',\n 'sniff',\n 'snow',\n 'soap',\n 'soccer',\n 'social',\n 'sock',\n 'soda',\n 'soft',\n 'solar',\n 'soldier',\n 'solid',\n 'solution',\n 'solve',\n 'someone',\n 'song',\n 'soon',\n 'sorry',\n 'sort',\n 'soul',\n 'sound',\n 'soup',\n 'source',\n 'south',\n 'space',\n 'spare',\n 'spatial',\n 'spawn',\n 'speak',\n 'special',\n 'speed',\n 'spell',\n 'spend',\n 'sphere',\n 'spice',\n 'spider',\n 'spike',\n 'spin',\n 'spirit',\n 'split',\n 'spoil',\n 'sponsor',\n 'spoon',\n 'sport',\n 'spot',\n 'spray',\n 'spread',\n 'spring',\n 'spy',\n 'square',\n 'squeeze',\n 'squirrel',\n 'stable',\n 'stadium',\n 'staff',\n 'stage',\n 'stairs',\n 'stamp',\n 'stand',\n 'start',\n 'state',\n 'stay',\n 'steak',\n 'steel',\n 'stem',\n 'step',\n 'stereo',\n 'stick',\n 'still',\n 'sting',\n 'stock',\n 'stomach',\n 'stone',\n 'stool',\n 'story',\n 'stove',\n 'strategy',\n 'street',\n 'strike',\n 'strong',\n 'struggle',\n 'student',\n 'stuff',\n 'stumble',\n 'style',\n 'subject',\n 'submit',\n 'subway',\n 'success',\n 'such',\n 'sudden',\n 'suffer',\n 'sugar',\n 'suggest',\n 'suit',\n 'summer',\n 'sun',\n 'sunny',\n 'sunset',\n 'super',\n 'supply',\n 'supreme',\n 'sure',\n 'surface',\n 'surge',\n 'surprise',\n 'surround',\n 'survey',\n 'suspect',\n 'sustain',\n 'swallow',\n 'swamp',\n 'swap',\n 'swarm',\n 'swear',\n 'sweet',\n 'swift',\n 'swim',\n 'swing',\n 'switch',\n 'sword',\n 'symbol',\n 'symptom',\n 'syrup',\n 'system',\n 'table',\n 'tackle',\n 'tag',\n 'tail',\n 'talent',\n 'talk',\n 'tank',\n 'tape',\n 'target',\n 'task',\n 'taste',\n 'tattoo',\n 'taxi',\n 'teach',\n 'team',\n 'tell',\n 'ten',\n 'tenant',\n 'tennis',\n 'tent',\n 'term',\n 'test',\n 'text',\n 'thank',\n 'that',\n 'theme',\n 'then',\n 'theory',\n 'there',\n 'they',\n 'thing',\n 'this',\n 'thought',\n 'three',\n 'thrive',\n 'throw',\n 'thumb',\n 'thunder',\n 'ticket',\n 'tide',\n 'tiger',\n 'tilt',\n 'timber',\n 'time',\n 'tiny',\n 'tip',\n 'tired',\n 'tissue',\n 'title',\n 'toast',\n 'tobacco',\n 'today',\n 'toddler',\n 'toe',\n 'together',\n 'toilet',\n 'token',\n 'tomato',\n 'tomorrow',\n 'tone',\n 'tongue',\n 'tonight',\n 'tool',\n 'tooth',\n 'top',\n 'topic',\n 'topple',\n 'torch',\n 'tornado',\n 'tortoise',\n 'toss',\n 'total',\n 'tourist',\n 'toward',\n 'tower',\n 'town',\n 'toy',\n 'track',\n 'trade',\n 'traffic',\n 'tragic',\n 'train',\n 'transfer',\n 'trap',\n 'trash',\n 'travel',\n 'tray',\n 'treat',\n 'tree',\n 'trend',\n 'trial',\n 'tribe',\n 'trick',\n 'trigger',\n 'trim',\n 'trip',\n 'trophy',\n 'trouble',\n 'truck',\n 'true',\n 'truly',\n 'trumpet',\n 'trust',\n 'truth',\n 'try',\n 'tube',\n 'tuition',\n 'tumble',\n 'tuna',\n 'tunnel',\n 'turkey',\n 'turn',\n 'turtle',\n 'twelve',\n 'twenty',\n 'twice',\n 'twin',\n 'twist',\n 'two',\n 'type',\n 'typical',\n 'ugly',\n 'umbrella',\n 'unable',\n 'unaware',\n 'uncle',\n 'uncover',\n 'under',\n 'undo',\n 'unfair',\n 'unfold',\n 'unhappy',\n 'uniform',\n 'unique',\n 'unit',\n 'universe',\n 'unknown',\n 'unlock',\n 'until',\n 'unusual',\n 'unveil',\n 'update',\n 'upgrade',\n 'uphold',\n 'upon',\n 'upper',\n 'upset',\n 'urban',\n 'urge',\n 'usage',\n 'use',\n 'used',\n 'useful',\n 'useless',\n 'usual',\n 'utility',\n 'vacant',\n 'vacuum',\n 'vague',\n 'valid',\n 'valley',\n 'valve',\n 'van',\n 'vanish',\n 'vapor',\n 'various',\n 'vast',\n 'vault',\n 'vehicle',\n 'velvet',\n 'vendor',\n 'venture',\n 'venue',\n 'verb',\n 'verify',\n 'version',\n 'very',\n 'vessel',\n 'veteran',\n 'viable',\n 'vibrant',\n 'vicious',\n 'victory',\n 'video',\n 'view',\n 'village',\n 'vintage',\n 'violin',\n 'virtual',\n 'virus',\n 'visa',\n 'visit',\n 'visual',\n 'vital',\n 'vivid',\n 'vocal',\n 'voice',\n 'void',\n 'volcano',\n 'volume',\n 'vote',\n 'voyage',\n 'wage',\n 'wagon',\n 'wait',\n 'walk',\n 'wall',\n 'walnut',\n 'want',\n 'warfare',\n 'warm',\n 'warrior',\n 'wash',\n 'wasp',\n 'waste',\n 'water',\n 'wave',\n 'way',\n 'wealth',\n 'weapon',\n 'wear',\n 'weasel',\n 'weather',\n 'web',\n 'wedding',\n 'weekend',\n 'weird',\n 'welcome',\n 'west',\n 'wet',\n 'whale',\n 'what',\n 'wheat',\n 'wheel',\n 'when',\n 'where',\n 'whip',\n 'whisper',\n 'wide',\n 'width',\n 'wife',\n 'wild',\n 'will',\n 'win',\n 'window',\n 'wine',\n 'wing',\n 'wink',\n 'winner',\n 'winter',\n 'wire',\n 'wisdom',\n 'wise',\n 'wish',\n 'witness',\n 'wolf',\n 'woman',\n 'wonder',\n 'wood',\n 'wool',\n 'word',\n 'work',\n 'world',\n 'worry',\n 'worth',\n 'wrap',\n 'wreck',\n 'wrestle',\n 'wrist',\n 'write',\n 'wrong',\n 'yard',\n 'year',\n 'yellow',\n 'you',\n 'young',\n 'youth',\n 'zebra',\n 'zero',\n 'zone',\n 'zoo'\n ],\n space: ' '\n};\n//# sourceMappingURL=bip-39-wordlist-en.js.map","import { wordList } from './bip-39-wordlist-en.js';\nimport { encode, toArray, Reader, Writer } from '../primitives/utils.js';\nimport * as Hash from '../primitives/Hash.js';\nimport Random from '../primitives/Random.js';\n/**\n * @class Mnemonic\n *\n * @description\n * Class representing Mnemonic functionality.\n * This class provides methods for generating, converting, and validating mnemonic phrases\n * according to the BIP39 standard. It supports creating mnemonics from random entropy,\n * converting mnemonics to seeds, and validating mnemonic phrases.\n */\nexport default class Mnemonic {\n mnemonic;\n seed;\n Wordlist;\n /**\n * Constructs a Mnemonic object.\n * @param {string} [mnemonic] - An optional mnemonic phrase.\n * @param {number[]} [seed] - An optional seed derived from the mnemonic.\n * @param {object} [wordlist=wordList] - An object containing a list of words and space character used in the mnemonic.\n */\n constructor(mnemonic, seed, wordlist = wordList) {\n this.mnemonic = mnemonic ?? ''; // Default to empty string if undefined\n this.seed = seed ?? []; // Default to empty array if undefined\n this.Wordlist = wordlist;\n }\n /**\n * Converts the mnemonic and seed into a binary representation.\n * @returns {number[]} The binary representation of the mnemonic and seed.\n */\n toBinary() {\n const bw = new Writer();\n if (this.mnemonic !== '') {\n const buf = toArray(this.mnemonic, 'utf8');\n bw.writeVarIntNum(buf.length);\n bw.write(buf);\n }\n else {\n bw.writeVarIntNum(0);\n }\n if (this.seed.length > 0) {\n bw.writeVarIntNum(this.seed.length);\n bw.write(this.seed);\n }\n else {\n bw.writeVarIntNum(0);\n }\n return bw.toArray();\n }\n /**\n * Loads a mnemonic and seed from a binary representation.\n * @param {number[]} bin - The binary representation of a mnemonic and seed.\n * @returns {this} The Mnemonic instance with loaded mnemonic and seed.\n */\n fromBinary(bin) {\n const br = new Reader(bin);\n const mnemoniclen = br.readVarIntNum();\n if (mnemoniclen > 0) {\n this.mnemonic = encode(br.read(mnemoniclen), 'utf8');\n }\n const seedlen = br.readVarIntNum();\n if (seedlen > 0) {\n this.seed = br.read(seedlen);\n }\n return this;\n }\n /**\n * Generates a random mnemonic from a given bit length.\n * @param {number} [bits=128] - The bit length for the random mnemonic (must be a multiple of 32 and at least 128).\n * @returns {this} The Mnemonic instance with the new random mnemonic.\n * @throws {Error} If the bit length is not a multiple of 32 or is less than 128.\n */\n fromRandom(bits) {\n if (bits === undefined || bits === null || isNaN(bits) || bits === 0) {\n bits = 128;\n }\n if (bits % 32 !== 0) {\n throw new Error('bits must be multiple of 32');\n }\n if (bits < 128) {\n throw new Error('bits must be at least 128');\n }\n const buf = Random(bits / 8);\n this.entropy2Mnemonic(buf);\n this.mnemonic2Seed();\n return this;\n }\n /**\n * Static method to generate a Mnemonic instance with a random mnemonic.\n * @param {number} [bits=128] - The bit length for the random mnemonic.\n * @returns {Mnemonic} A new Mnemonic instance.\n */\n static fromRandom(bits) {\n return new this().fromRandom(bits);\n }\n /**\n * Converts given entropy into a mnemonic phrase.\n * This method is used to generate a mnemonic from a specific entropy source.\n * @param {number[]} buf - The entropy buffer, must be at least 128 bits.\n * @returns {this} The Mnemonic instance with the mnemonic set from the given entropy.\n * @throws {Error} If the entropy is less than 128 bits.\n */\n fromEntropy(buf) {\n this.entropy2Mnemonic(buf);\n return this;\n }\n /**\n * Static method to create a Mnemonic instance from a given entropy.\n * @param {number[]} buf - The entropy buffer.\n * @returns {Mnemonic} A new Mnemonic instance.\n */\n static fromEntropy(buf) {\n return new this().fromEntropy(buf);\n }\n /**\n * Sets the mnemonic for the instance from a string.\n * @param {string} mnemonic - The mnemonic phrase as a string.\n * @returns {this} The Mnemonic instance with the set mnemonic.\n */\n fromString(mnemonic) {\n this.mnemonic = mnemonic;\n return this;\n }\n /**\n * Static method to create a Mnemonic instance from a mnemonic string.\n * @param {string} str - The mnemonic phrase.\n * @returns {Mnemonic} A new Mnemonic instance.\n */\n static fromString(str) {\n return new this().fromString(str);\n }\n /**\n * Converts the instance's mnemonic to a string representation.\n * @returns {string} The mnemonic phrase as a string.\n */\n toString() {\n return this.mnemonic;\n }\n /**\n * Converts the mnemonic to a seed.\n * The mnemonic must pass the validity check before conversion.\n * @param {string} [passphrase=''] - An optional passphrase for additional security.\n * @returns {number[]} The generated seed.\n * @throws {Error} If the mnemonic is invalid.\n */\n toSeed(passphrase) {\n this.mnemonic2Seed(passphrase);\n return this.seed;\n }\n /**\n * Converts entropy to a mnemonic phrase.\n * This method takes a buffer of entropy and converts it into a corresponding\n * mnemonic phrase based on the Mnemonic wordlist. The entropy should be at least 128 bits.\n * The method applies a checksum and maps the entropy to words in the wordlist.\n * @param {number[]} buf - The entropy buffer to convert. Must be at least 128 bits.\n * @returns {this} The Mnemonic instance with the mnemonic set from the entropy.\n * @throws {Error} If the entropy is less than 128 bits or if it's not an even multiple of 11 bits.\n */\n entropy2Mnemonic(buf) {\n if (buf.length < 128 / 8) {\n throw new Error('Entropy is less than 128 bits. It must be 128 bits or more.');\n }\n const hash = Hash.sha256(buf);\n let bin = '';\n const bits = buf.length * 8;\n for (let i = 0; i < buf.length; i++) {\n bin = bin + ('00000000' + buf[i].toString(2)).slice(-8);\n }\n let hashbits = hash[0].toString(2);\n hashbits = ('00000000' + hashbits).slice(-8).slice(0, bits / 32);\n bin = bin + hashbits;\n if (bin.length % 11 !== 0) {\n throw new Error('internal error - entropy not an even multiple of 11 bits - ' +\n bin.length.toString());\n }\n let mnemonic = '';\n for (let i = 0; i < bin.length / 11; i++) {\n if (mnemonic !== '') {\n mnemonic = mnemonic + this.Wordlist.space;\n }\n const wi = parseInt(bin.slice(i * 11, (i + 1) * 11), 2);\n mnemonic = mnemonic + this.Wordlist.value[wi];\n }\n this.mnemonic = mnemonic;\n return this;\n }\n /**\n * Validates the mnemonic phrase.\n * Checks for correct length, absence of invalid words, and proper checksum.\n * @returns {boolean} True if the mnemonic is valid, false otherwise.\n * @throws {Error} If the mnemonic is not an even multiple of 11 bits.\n */\n check() {\n const mnemonic = this.mnemonic;\n // confirm no invalid words\n const words = mnemonic.split(this.Wordlist.space);\n let bin = '';\n for (let i = 0; i < words.length; i++) {\n const ind = this.Wordlist.value.indexOf(words[i]);\n if (ind < 0) {\n return false;\n }\n bin = bin + ('00000000000' + ind.toString(2)).slice(-11);\n }\n if (bin.length % 11 !== 0) {\n throw new Error('internal error - entropy not an even multiple of 11 bits - ' +\n bin.length.toString());\n }\n // confirm checksum\n const cs = bin.length / 33;\n const hashBits = bin.slice(-cs);\n const nonhashBits = bin.slice(0, bin.length - cs);\n const buf = [];\n for (let i = 0; i < nonhashBits.length / 8; i++) {\n buf.push(parseInt(bin.slice(i * 8, (i + 1) * 8), 2));\n }\n const hash = Hash.sha256(buf.slice(0, nonhashBits.length / 8));\n let expectedHashBits = hash[0].toString(2);\n expectedHashBits = ('00000000' + expectedHashBits).slice(-8).slice(0, cs);\n return expectedHashBits === hashBits;\n }\n /**\n * Converts a mnemonic to a seed.\n * This method takes the instance's mnemonic phrase, combines it with a passphrase (if provided),\n * and uses PBKDF2 to generate a seed. It also validates the mnemonic before conversion.\n * This seed can then be used for generating deterministic keys.\n * @param {string} [passphrase=''] - An optional passphrase for added security.\n * @returns {this} The Mnemonic instance with the seed generated from the mnemonic.\n * @throws {Error} If the mnemonic does not pass validation or if the passphrase is not a string.\n */\n mnemonic2Seed(passphrase = '') {\n let mnemonic = this.mnemonic;\n if (!this.check()) {\n throw new Error('Mnemonic does not pass the check - was the mnemonic typed incorrectly? Are there extra spaces?');\n }\n if (typeof passphrase !== 'string') {\n throw new Error('passphrase must be a string or undefined');\n }\n mnemonic = mnemonic.normalize('NFKD');\n passphrase = passphrase.normalize('NFKD');\n const mbuf = toArray(mnemonic, 'utf8');\n const pbuf = [\n ...toArray('mnemonic', 'utf8'),\n ...toArray(passphrase, 'utf8')\n ];\n this.seed = Hash.pbkdf2(mbuf, pbuf, 2048, 64, 'sha512');\n return this;\n }\n /**\n * Determines the validity of a given passphrase with the mnemonic.\n * This method is useful for checking if a passphrase matches with the mnemonic.\n * @param {string} [passphrase=''] - The passphrase to validate.\n * @returns {boolean} True if the mnemonic and passphrase combination is valid, false otherwise.\n */\n isValid(passphrase = '') {\n let isValid;\n try {\n this.mnemonic2Seed(passphrase);\n isValid = true;\n }\n catch {\n isValid = false;\n }\n return isValid;\n }\n /**\n * Static method to check the validity of a given mnemonic and passphrase combination.\n * @param {string} mnemonic - The mnemonic phrase.\n * @param {string} [passphrase=''] - The passphrase to validate.\n * @returns {boolean} True if the combination is valid, false otherwise.\n */\n static isValid(mnemonic, passphrase = '') {\n return new Mnemonic(mnemonic).isValid(passphrase);\n }\n}\n//# sourceMappingURL=Mnemonic.js.map","// import { AESWrappercbc } from './aescbc'\nimport Random from '../primitives/Random.js';\nimport PrivateKey from '../primitives/PrivateKey.js';\nimport PublicKey from '../primitives/PublicKey.js';\nimport Point from '../primitives/Point.js';\nimport * as Hash from '../primitives/Hash.js';\nimport { toArray, toHex, encode } from '../primitives/utils.js';\nfunction AES(key) {\n if (this._tables[0][0][0] === 0)\n this._precompute();\n let tmp, encKey, decKey;\n const sbox = this._tables[0][4];\n const decTable = this._tables[1];\n const keyLen = key.length;\n let rcon = 1;\n if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {\n throw new Error('invalid aes key size');\n }\n this._key = [(encKey = key.slice(0)), (decKey = [])];\n // schedule encryption keys\n let i;\n for (i = keyLen; i < 4 * keyLen + 28; i++) {\n tmp = encKey[i - 1];\n // apply sbox\n if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {\n tmp =\n (sbox[tmp >>> 24] << 24) ^\n (sbox[(tmp >> 16) & 255] << 16) ^\n (sbox[(tmp >> 8) & 255] << 8) ^\n sbox[tmp & 255];\n // shift rows and add rcon\n if (i % keyLen === 0) {\n tmp = (tmp << 8) ^ (tmp >>> 24) ^ (rcon << 24);\n rcon = (rcon << 1) ^ ((rcon >> 7) * 283);\n }\n }\n encKey[i] = encKey[i - keyLen] ^ tmp;\n }\n // schedule decryption keys\n for (let j = 0; i > 0; j++, i--) {\n tmp = encKey[(j & 3) !== 0 ? i : i - 4];\n if (i <= 4 || j < 4) {\n decKey[j] = tmp;\n }\n else {\n decKey[j] =\n decTable[0][sbox[tmp >>> 24]] ^\n decTable[1][sbox[(tmp >> 16) & 255]] ^\n decTable[2][sbox[(tmp >> 8) & 255]] ^\n decTable[3][sbox[tmp & 255]];\n }\n }\n}\nAES.prototype = {\n /**\n * Encrypt an array of 4 big-endian words.\n * @param {Array} data The plaintext.\n * @return {Array} The ciphertext.\n */\n encrypt: function (data) {\n return this._crypt(data, 0);\n },\n /**\n * Decrypt an array of 4 big-endian words.\n * @param {Array} data The ciphertext.\n * @return {Array} The plaintext.\n */\n decrypt: function (data) {\n return this._crypt(data, 1);\n },\n /**\n * The expanded S-box and inverse S-box tables. These will be computed\n * on the client so that we don't have to send them down the wire.\n *\n * There are two tables, _tables[0] is for encryption and\n * _tables[1] is for decryption.\n *\n * The first 4 sub-tables are the expanded S-box with MixColumns. The\n * last (_tables[01][4]) is the S-box itself.\n *\n * @private\n */\n _tables: [\n [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256)\n ],\n [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256)\n ]\n ],\n // Expand the S-box tables.\n _precompute: function () {\n const encTable = this._tables[0];\n const decTable = this._tables[1];\n const sbox = encTable[4];\n const sboxInv = decTable[4];\n let i;\n let x;\n let xInv;\n const d = new Uint8Array(256);\n const th = new Uint8Array(256);\n let x2;\n let x4;\n let x8;\n let s;\n let tEnc;\n let tDec;\n // Compute double and third tables\n for (i = 0; i < 256; i++) {\n th[(d[i] = (i << 1) ^ ((i >> 7) * 283)) ^ i] = i;\n }\n for (x = xInv = 0; sbox[x] === 0; x ^= (x2 !== 0 ? x2 : 1), xInv = th[xInv] !== 0 ? th[xInv] : 1) {\n // Compute sbox\n s = xInv ^ (xInv << 1) ^ (xInv << 2) ^ (xInv << 3) ^ (xInv << 4);\n s = (s >> 8) ^ (s & 255) ^ 99;\n sbox[x] = s;\n sboxInv[s] = x;\n // Compute MixColumns\n x8 = d[(x4 = d[(x2 = d[x])])];\n tDec = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n tEnc = (d[s] * 0x101) ^ (s * 0x1010100);\n for (i = 0; i < 4; i++) {\n encTable[i][x] = tEnc = (tEnc << 24) ^ (tEnc >>> 8);\n decTable[i][s] = tDec = (tDec << 24) ^ (tDec >>> 8);\n }\n }\n },\n /**\n * Encryption and decryption core.\n * @param {Array} input Four words to be encrypted or decrypted.\n * @param dir The direction, 0 for encrypt and 1 for decrypt.\n * @return {Array} The four encrypted or decrypted words.\n * @private\n */\n _crypt: function (input, dir) {\n if (input.length !== 4) {\n throw new Error('invalid aes block size');\n }\n const key = this._key[dir];\n // state variables a,b,c,d are loaded with pre-whitened data\n let a = input[0] ^ key[0];\n let b = input[dir === 1 ? 3 : 1] ^ key[1];\n let c = input[2] ^ key[2];\n let d = input[dir === 1 ? 1 : 3] ^ key[3];\n let a2;\n let b2;\n let c2;\n const nInnerRounds = key.length / 4 - 2;\n let i;\n let kIndex = 4;\n const out = new Uint32Array(4);\n const // <--- this is slower in Node, about the same in Chrome */\n table = this._tables[dir];\n // load up the tables\n const t0 = table[0];\n const t1 = table[1];\n const t2 = table[2];\n const t3 = table[3];\n const sbox = table[4];\n // Inner rounds. Cribbed from OpenSSL.\n for (i = 0; i < nInnerRounds; i++) {\n a2 =\n t0[a >>> 24] ^\n t1[(b >> 16) & 255] ^\n t2[(c >> 8) & 255] ^\n t3[d & 255] ^\n key[kIndex];\n b2 =\n t0[b >>> 24] ^\n t1[(c >> 16) & 255] ^\n t2[(d >> 8) & 255] ^\n t3[a & 255] ^\n key[kIndex + 1];\n c2 =\n t0[c >>> 24] ^\n t1[(d >> 16) & 255] ^\n t2[(a >> 8) & 255] ^\n t3[b & 255] ^\n key[kIndex + 2];\n d =\n t0[d >>> 24] ^\n t1[(a >> 16) & 255] ^\n t2[(b >> 8) & 255] ^\n t3[c & 255] ^\n key[kIndex + 3];\n kIndex += 4;\n a = a2;\n b = b2;\n c = c2;\n }\n // Last round.\n for (i = 0; i < 4; i++) {\n out[dir === 1 ? 3 & -i : i] =\n (sbox[a >>> 24] << 24) ^\n (sbox[(b >> 16) & 255] << 16) ^\n (sbox[(c >> 8) & 255] << 8) ^\n sbox[d & 255] ^\n key[kIndex++];\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n }\n};\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass AESWrapper {\n static encrypt(messageBuf, keyBuf) {\n const key = AESWrapper.buf2Words(keyBuf);\n const message = AESWrapper.buf2Words(messageBuf);\n const a = new AES(key);\n const enc = a.encrypt(message);\n const encBuf = AESWrapper.words2Buf(enc);\n return encBuf;\n }\n static decrypt(encBuf, keyBuf) {\n const enc = AESWrapper.buf2Words(encBuf);\n const key = AESWrapper.buf2Words(keyBuf);\n const a = new AES(key);\n const message = a.decrypt(enc);\n const messageBuf = AESWrapper.words2Buf(message);\n return messageBuf;\n }\n static buf2Words(buf) {\n if (buf.length % 4 !== 0) {\n throw new Error('buf length must be a multiple of 4');\n }\n const words = [];\n for (let i = 0; i < buf.length / 4; i++) {\n const val = buf[i * 4] * 0x1000000 + // Shift the first byte by 24 bits\n ((buf[i * 4 + 1] << 16) | // Shift the second byte by 16 bits\n (buf[i * 4 + 2] << 8) | // Shift the third byte by 8 bits\n buf[i * 4 + 3]); // The fourth byte\n words.push(val);\n }\n return words;\n }\n static words2Buf(words) {\n const buf = new Array(words.length * 4);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n buf[i * 4] = (word >>> 24) & 0xff;\n buf[i * 4 + 1] = (word >>> 16) & 0xff;\n buf[i * 4 + 2] = (word >>> 8) & 0xff;\n buf[i * 4 + 3] = word & 0xff;\n }\n return buf;\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass CBC {\n static buf2BlocksBuf(buf, blockSize) {\n const bytesize = blockSize / 8;\n const blockBufs = [];\n for (let i = 0; i <= buf.length / bytesize; i++) {\n let blockBuf = buf.slice(i * bytesize, i * bytesize + bytesize);\n if (blockBuf.length < blockSize) {\n blockBuf = CBC.pkcs7Pad(blockBuf, blockSize);\n }\n blockBufs.push(blockBuf);\n }\n return blockBufs;\n }\n static blockBufs2Buf(blockBufs) {\n let last = blockBufs[blockBufs.length - 1];\n last = CBC.pkcs7Unpad(last);\n blockBufs[blockBufs.length - 1] = last;\n const buf = blockBufs.flat();\n return buf;\n }\n static encrypt(messageBuf, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const blockSize = ivBuf.length * 8;\n const blockBufs = CBC.buf2BlocksBuf(messageBuf, blockSize);\n const encBufs = CBC.encryptBlocks(blockBufs, ivBuf, blockCipher, cipherKeyBuf);\n const encBuf = encBufs.flat();\n return encBuf;\n }\n static decrypt(encBuf, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const bytesize = ivBuf.length;\n const encBufs = [];\n for (let i = 0; i < encBuf.length / bytesize; i++) {\n encBufs.push(encBuf.slice(i * bytesize, i * bytesize + bytesize));\n }\n const blockBufs = CBC.decryptBlocks(encBufs, ivBuf, blockCipher, cipherKeyBuf);\n const buf = CBC.blockBufs2Buf(blockBufs);\n return buf;\n }\n static encryptBlock(blockBuf, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const xorbuf = CBC.xorBufs(blockBuf, ivBuf);\n const encBuf = blockCipher.encrypt(xorbuf, cipherKeyBuf);\n return encBuf;\n }\n static decryptBlock(encBuf, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const xorbuf = blockCipher.decrypt(encBuf, cipherKeyBuf);\n const blockBuf = CBC.xorBufs(xorbuf, ivBuf);\n return blockBuf;\n }\n static encryptBlocks(blockBufs, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const encBufs = [];\n for (let i = 0; i < blockBufs.length; i++) {\n const blockBuf = blockBufs[i];\n const encBuf = CBC.encryptBlock(blockBuf, ivBuf, blockCipher, cipherKeyBuf);\n encBufs.push(encBuf);\n ivBuf = encBuf;\n }\n return encBufs;\n }\n static decryptBlocks(encBufs, ivBuf, blockCipher /* TODO: type */, cipherKeyBuf) {\n const blockBufs = [];\n for (let i = 0; i < encBufs.length; i++) {\n const encBuf = encBufs[i];\n const blockBuf = CBC.decryptBlock(encBuf, ivBuf, blockCipher, cipherKeyBuf);\n blockBufs.push(blockBuf);\n ivBuf = encBuf;\n }\n return blockBufs;\n }\n static pkcs7Pad(buf, blockSize) {\n const bytesize = blockSize / 8;\n const padbytesize = bytesize - buf.length;\n const pad = new Array(padbytesize);\n pad.fill(padbytesize);\n const paddedbuf = [...buf, ...pad];\n return paddedbuf;\n }\n static pkcs7Unpad(paddedbuf) {\n const padlength = paddedbuf[paddedbuf.length - 1];\n const padbuf = paddedbuf.slice(paddedbuf.length - padlength, paddedbuf.length);\n const padbuf2 = new Array(padlength);\n padbuf2.fill(padlength);\n if (toHex(padbuf) !== toHex(padbuf2)) {\n throw new Error('invalid padding');\n }\n return paddedbuf.slice(0, paddedbuf.length - padlength);\n }\n static xorBufs(buf1, buf2) {\n if (buf1.length !== buf2.length) {\n throw new Error('bufs must have the same length');\n }\n const buf = new Array(buf1.length);\n for (let i = 0; i < buf1.length; i++) {\n buf[i] = buf1[i] ^ buf2[i];\n }\n return buf;\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass AESCBC {\n static encrypt(messageBuf, cipherKeyBuf, ivBuf, concatIvBuf = true) {\n ivBuf = ivBuf ?? Random(128 / 8);\n const ctBuf = CBC.encrypt(messageBuf, ivBuf, AESWrapper, cipherKeyBuf);\n if (concatIvBuf) {\n return [...ivBuf, ...ctBuf];\n }\n else {\n return [...ctBuf];\n }\n }\n static decrypt(encBuf, cipherKeyBuf, ivBuf) {\n if (ivBuf == null) {\n ivBuf = encBuf.slice(0, 128 / 8);\n const ctBuf = encBuf.slice(128 / 8);\n return CBC.decrypt(ctBuf, ivBuf, AESWrapper, cipherKeyBuf);\n }\n else {\n const ctBuf = encBuf;\n return CBC.decrypt(ctBuf, ivBuf, AESWrapper, cipherKeyBuf);\n }\n }\n}\n/**\n * @class ECIES\n * Implements the Electrum ECIES protocol for encrypted communication.\n *\n * @prprecated This class is deprecated in favor of the BRC-78 standard for portable encrypted messages,\n * which provides a more comprehensive and secure solution by integrating with BRC-42 and BRC-43 standards.\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport default class ECIES {\n /**\n * Generates the initialization vector (iv), encryption key (kE), and MAC key (kM)\n * using the sender's private key and receiver's public key.\n *\n * @param {PrivateKey} privKey - The sender's private key.\n * @param {PublicKey} pubKey - The receiver's public key.\n * @returns {Object} An object containing the iv, kE, and kM as number arrays.\n */\n static ivkEkM(privKey, pubKey) {\n const r = privKey;\n const KB = pubKey;\n const P = KB.mul(r);\n const S = new PublicKey(P.x, P.y);\n const Sbuf = S.encode(true);\n const hash = Hash.sha512(Sbuf);\n return {\n iv: hash.slice(0, 16),\n kE: hash.slice(16, 32),\n kM: hash.slice(32, 64)\n };\n }\n /**\n * Encrypts a given message using the Electrum ECIES method.\n *\n * @param {number[]} messageBuf - The message to be encrypted, in number array format.\n * @param {PublicKey} toPublicKey - The public key of the recipient.\n * @param {PrivateKey} [fromPrivateKey] - The private key of the sender. If not provided, a random private key is used.\n * @param {boolean} [noKey=false] - If true, does not include the sender's public key in the encrypted message.\n * @returns {number[]} The encrypted message as a number array.\n */\n static electrumEncrypt(messageBuf, toPublicKey, fromPrivateKey, noKey = false) {\n let Rbuf = null;\n if (fromPrivateKey == null) {\n fromPrivateKey = PrivateKey.fromRandom();\n }\n if (!noKey) {\n Rbuf = fromPrivateKey.toPublicKey().encode(true);\n }\n const { iv, kE, kM } = ECIES.ivkEkM(fromPrivateKey, toPublicKey);\n const ciphertext = AESCBC.encrypt(messageBuf, kE, iv, false);\n const BIE1 = toArray('BIE1', 'utf8');\n let encBuf;\n if (Rbuf !== undefined && Rbuf !== null && Rbuf.length > 0) {\n encBuf = [...BIE1, ...Rbuf, ...ciphertext];\n }\n else {\n encBuf = [...BIE1, ...ciphertext];\n }\n const hmac = Hash.sha256hmac(kM, encBuf);\n return [...encBuf, ...hmac];\n }\n /**\n * Decrypts a message encrypted using the Electrum ECIES method.\n *\n * @param {number[]} encBuf - The encrypted message buffer.\n * @param {PrivateKey} toPrivateKey - The private key of the recipient.\n * @param {PublicKey} [fromPublicKey=null] - The public key of the sender. If not provided, it is extracted from the message.\n * @returns {number[]} The decrypted message as a number array.\n */\n static electrumDecrypt(encBuf, toPrivateKey, fromPublicKey) {\n const tagLength = 32;\n const magic = encBuf.slice(0, 4);\n if (encode(magic, 'utf8') !== 'BIE1') {\n throw new Error('Invalid Magic');\n }\n let offset = 4;\n // Determine if the sender's public key is included in encBuf\n let Rbuf = null;\n if (encBuf.length - offset - tagLength >= 33) {\n const firstByte = encBuf[offset];\n if (firstByte === 0x02 || firstByte === 0x03) {\n // Compressed public key\n Rbuf = encBuf.slice(offset, offset + 33);\n offset += 33;\n }\n else if (firstByte === 0x04) {\n // Uncompressed public key\n Rbuf = encBuf.slice(offset, offset + 65);\n offset += 65;\n }\n }\n if (Rbuf !== null) {\n if (fromPublicKey == null) {\n fromPublicKey = PublicKey.fromString(toHex(Rbuf));\n }\n }\n else {\n if (fromPublicKey == null) {\n throw new Error('Sender public key is required');\n }\n }\n const { iv, kE, kM } = ECIES.ivkEkM(toPrivateKey, fromPublicKey);\n const ciphertext = encBuf.slice(offset, encBuf.length - tagLength);\n const hmac = encBuf.slice(encBuf.length - tagLength, encBuf.length);\n const hmac2 = Hash.sha256hmac(kM, encBuf.slice(0, encBuf.length - tagLength));\n if (toHex(hmac) !== toHex(hmac2)) {\n throw new Error('Invalid checksum');\n }\n return AESCBC.decrypt(ciphertext, kE, iv);\n }\n /**\n * Encrypts a given message using the Bitcore variant of ECIES.\n *\n * @param {number[]} messageBuf - The message to be encrypted, in number array format.\n * @param {PublicKey} toPublicKey - The public key of the recipient.\n * @param {PrivateKey} [fromPrivateKey] - The private key of the sender. If not provided, a random private key is used.\n * @param {number[]} [ivBuf] - The initialization vector for encryption. If not provided, a random IV is used.\n * @returns {number[]} The encrypted message as a number array.\n */\n static bitcoreEncrypt(messageBuf, toPublicKey, fromPrivateKey, ivBuf) {\n if (fromPrivateKey == null) {\n fromPrivateKey = PrivateKey.fromRandom();\n }\n if (ivBuf == null) {\n ivBuf = Random(16);\n }\n const r = fromPrivateKey;\n const RPublicKey = fromPrivateKey.toPublicKey();\n const RBuf = RPublicKey.encode(true);\n const KB = toPublicKey;\n const P = KB.mul(r);\n const S = P.getX();\n const Sbuf = S.toArray('be', 32);\n const kEkM = Hash.sha512(Sbuf);\n const kE = kEkM.slice(0, 32);\n const kM = kEkM.slice(32, 64);\n const c = AESCBC.encrypt(messageBuf, kE, ivBuf);\n const d = Hash.sha256hmac(kM, [...c]);\n const encBuf = [...RBuf, ...c, ...d];\n return encBuf;\n }\n /**\n * Decrypts a message encrypted using the Bitcore variant of ECIES.\n *\n * @param {number[]} encBuf - The encrypted message buffer.\n * @param {PrivateKey} toPrivateKey - The private key of the recipient.\n * @returns {number[]} The decrypted message as a number array.\n */\n static bitcoreDecrypt(encBuf, toPrivateKey) {\n const kB = toPrivateKey;\n const fromPublicKey = PublicKey.fromString(toHex(encBuf.slice(0, 33)));\n const R = fromPublicKey;\n const P = R.mul(kB);\n if (P.eq(new Point(0, 0))) {\n throw new Error('P equals 0');\n }\n const S = P.getX();\n const Sbuf = S.toArray('be', 32);\n const kEkM = Hash.sha512(Sbuf);\n const kE = kEkM.slice(0, 32);\n const kM = kEkM.slice(32, 64);\n const c = encBuf.slice(33, encBuf.length - 32);\n const d = encBuf.slice(encBuf.length - 32, encBuf.length);\n const d2 = Hash.sha256hmac(kM, c);\n if (toHex(d) !== toHex(d2)) {\n throw new Error('Invalid checksum');\n }\n const messageBuf = AESCBC.decrypt(c, kE);\n return [...messageBuf];\n }\n}\n//# sourceMappingURL=ECIES.js.map","import Transaction from '../transaction/Transaction.js';\nimport LockingScript from '../script/LockingScript.js';\n/**\n * @method fromUtxo\n *\n * @description\n * This function creates a transaction input from a utxo json object\n * The idea being old code that uses utxos rather than sourceTranactions can convert using this.\n *\n * @deprecated\n * This approach is made available for compatibility only. It is deprecated in favor of using sourceTransactions\n * directly. It's recommended that wallets general keep transactions which store unspent outputs in their entirety,\n * along with corresonding Merkle paths. The reason you would keep the whole transaction is such that you can prove\n * the txid, and therefore its inclusion within a specific block.\n *\n * @example\n * const i = fromUtxo({\n * txid: '434555433eaca96dff6e71a4d02febd0dd3832e5ca4e5734623ca914522e17d5',\n * vout: 0,\n * script: '51',\n * satoshis: 1234\n * }, new P2PKH().unlock(p))\n *\n * tx.addInput(i)\n *\n * @param utxo: jsonUtxo\n * @param unlockingScriptTemplate: { sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>, estimateLength: (tx: Transaction, inputIndex: number) => Promise<number> }\n * @returns\n */\nexport default function fromUtxo(utxo, unlockingScriptTemplate) {\n const sourceTransaction = new Transaction(0, [], [], 0);\n sourceTransaction.outputs = Array(utxo.vout + 1).fill(null);\n sourceTransaction.outputs[utxo.vout] = {\n satoshis: utxo.satoshis,\n lockingScript: LockingScript.fromHex(utxo.script)\n };\n return {\n sourceTransaction,\n sourceTXID: utxo.txid,\n sourceOutputIndex: utxo.vout,\n unlockingScriptTemplate,\n sequence: 0xffffffff\n };\n}\n//# sourceMappingURL=Utxo.js.map","import { SHA1HMAC, SHA256HMAC, SHA512HMAC } from '../primitives/Hash.js';\nimport BigNumber from '../primitives/BigNumber.js';\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport class TOTP {\n /**\n * Generates a Time-based One-Time Password (TOTP).\n * @param {number[]} secret - The secret key for TOTP.\n * @param {TOTPOptions} options - Optional parameters for TOTP.\n * @returns {string} The generated TOTP.\n */\n static generate(secret, options) {\n const _options = this.withDefaultOptions(options);\n const counter = this.getCounter(_options.timestamp, _options.period);\n const otp = generateHOTP(secret, counter, _options);\n return otp;\n }\n /**\n * Validates a Time-based One-Time Password (TOTP).\n * @param {number[]} secret - The secret key for TOTP.\n * @param {string} passcode - The passcode to validate.\n * @param {TOTPValidateOptions} options - Optional parameters for TOTP validation.\n * @returns {boolean} A boolean indicating whether the passcode is valid.\n */\n static validate(secret, passcode, options) {\n const _options = this.withDefaultValidateOptions(options);\n passcode = passcode.trim();\n if (passcode.length !== _options.digits) {\n return false;\n }\n const counter = this.getCounter(_options.timestamp, _options.period);\n const counters = [counter];\n for (let i = 1; i <= _options.skew; i++) {\n counters.push(counter + i);\n counters.push(counter - i);\n }\n for (const c of counters) {\n if (passcode === generateHOTP(secret, c, _options)) {\n return true;\n }\n }\n return false;\n }\n static getCounter(timestamp, period) {\n const epochSeconds = Math.floor(timestamp / 1000);\n const counter = Math.floor(epochSeconds / period);\n return counter;\n }\n static withDefaultOptions(options) {\n return {\n digits: 2,\n algorithm: 'SHA-1',\n period: 30,\n timestamp: Date.now(),\n ...options\n };\n }\n static withDefaultValidateOptions(options) {\n return { skew: 1, ...this.withDefaultOptions(options) };\n }\n}\nfunction generateHOTP(secret, counter, options) {\n const timePad = new BigNumber(counter).toArray('be', 8);\n const hmac = calcHMAC(secret, timePad, options.algorithm);\n const signature = hmac.digest();\n // RFC 4226 https://datatracker.ietf.org/doc/html/rfc4226#section-5.4\n const offset = signature[signature.length - 1] & 0x0f; // offset is the last byte in the hmac\n const fourBytesRange = signature.slice(offset, offset + 4); // starting from offset, get 4 bytes\n const mask = 0x7fffffff; // 32-bit number with a leading 0 followed by 31 ones [0111 (...) 1111]\n const masked = new BigNumber(fourBytesRange).toNumber() & mask;\n const otp = masked.toString().slice(-options.digits);\n return otp;\n}\nfunction calcHMAC(secret, timePad, algorithm) {\n switch (algorithm) {\n case 'SHA-1':\n return new SHA1HMAC(secret).update(timePad);\n case 'SHA-256':\n return new SHA256HMAC(secret).update(timePad);\n case 'SHA-512':\n return new SHA512HMAC(secret).update(timePad);\n default:\n throw new Error('unsupported HMAC algorithm');\n }\n}\n//# sourceMappingURL=totp.js.map","import { PrivateKey, PublicKey, SymmetricKey, Hash, Utils } from '../primitives/index.js';\n/**\n * Class responsible for deriving various types of keys using a root private key.\n * It supports deriving public and private keys, symmetric keys, and revealing key linkages.\n */\nexport class KeyDeriver {\n cacheSharedSecret;\n retrieveCachedSharedSecret;\n rootKey;\n identityKey;\n anyone;\n /**\n * Initializes the KeyDeriver instance with a root private key.\n * @param {PrivateKey | 'anyone'} rootKey - The root private key or the string 'anyone'.\n */\n constructor(rootKey, cacheSharedSecret, retrieveCachedSharedSecret) {\n this.cacheSharedSecret = cacheSharedSecret;\n this.retrieveCachedSharedSecret = retrieveCachedSharedSecret;\n this.anyone = new PrivateKey(1).toPublicKey();\n if (rootKey === 'anyone') {\n this.rootKey = new PrivateKey(1);\n }\n else {\n this.rootKey = rootKey;\n }\n this.identityKey = this.rootKey.toPublicKey().toString();\n }\n /**\n * Derives a public key based on protocol ID, key ID, and counterparty.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @param {boolean} [forSelf=false] - Whether deriving for self.\n * @returns {PublicKey} - The derived public key.\n */\n derivePublicKey(protocolID, keyID, counterparty, forSelf = false) {\n counterparty = this.normalizeCounterparty(counterparty);\n if (forSelf) {\n return this.rootKey\n .deriveChild(counterparty, this.computeInvoiceNumber(protocolID, keyID), this.cacheSharedSecret, this.retrieveCachedSharedSecret)\n .toPublicKey();\n }\n else {\n return counterparty.deriveChild(this.rootKey, this.computeInvoiceNumber(protocolID, keyID), this.cacheSharedSecret, this.retrieveCachedSharedSecret);\n }\n }\n /**\n * Derives a private key based on protocol ID, key ID, and counterparty.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {PrivateKey} - The derived private key.\n */\n derivePrivateKey(protocolID, keyID, counterparty) {\n counterparty = this.normalizeCounterparty(counterparty);\n return this.rootKey.deriveChild(counterparty, this.computeInvoiceNumber(protocolID, keyID), this.cacheSharedSecret, this.retrieveCachedSharedSecret);\n }\n /**\n * Derives a symmetric key based on protocol ID, key ID, and counterparty.\n * Note: Symmetric keys should not be derivable by everyone due to security risks.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {SymmetricKey} - The derived symmetric key.\n */\n deriveSymmetricKey(protocolID, keyID, counterparty) {\n // If counterparty is 'anyone', we use 1*G as the public key.\n // This is a publicly derivable key and should only be used in scenarios where public disclosure is intended.\n if (counterparty === 'anyone') {\n counterparty = this.anyone;\n }\n else {\n counterparty = this.normalizeCounterparty(counterparty);\n }\n const derivedPublicKey = this.derivePublicKey(protocolID, keyID, counterparty);\n const derivedPrivateKey = this.derivePrivateKey(protocolID, keyID, counterparty);\n return new SymmetricKey(derivedPrivateKey.deriveSharedSecret(derivedPublicKey)?.x?.toArray() ?? []);\n }\n /**\n * Reveals the shared secret between the root key and the counterparty.\n * Note: This should not be used for 'self'.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {number[]} - The shared secret as a number array.\n * @throws {Error} - Throws an error if attempting to reveal a shared secret for 'self'.\n */\n revealCounterpartySecret(counterparty) {\n if (counterparty === 'self') {\n throw new Error('Counterparty secrets cannot be revealed for counterparty=self.');\n }\n counterparty = this.normalizeCounterparty(counterparty);\n // Double-check to ensure not revealing the secret for 'self'\n const self = this.rootKey.toPublicKey();\n const keyDerivedBySelf = this.rootKey.deriveChild(self, 'test').toHex();\n const keyDerivedByCounterparty = this.rootKey\n .deriveChild(counterparty, 'test')\n .toHex();\n if (keyDerivedBySelf === keyDerivedByCounterparty) {\n throw new Error('Counterparty secrets cannot be revealed for counterparty=self.');\n }\n return this.rootKey\n .deriveSharedSecret(counterparty)\n .encode(true);\n }\n /**\n * Reveals the specific key association for a given protocol ID, key ID, and counterparty.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @returns {number[]} - The specific key association as a number array.\n */\n revealSpecificSecret(counterparty, protocolID, keyID) {\n counterparty = this.normalizeCounterparty(counterparty);\n const sharedSecret = this.rootKey.deriveSharedSecret(counterparty);\n const invoiceNumberBin = Utils.toArray(this.computeInvoiceNumber(protocolID, keyID), 'utf8');\n return Hash.sha256hmac(sharedSecret.encode(true), invoiceNumberBin);\n }\n /**\n * Normalizes the counterparty to a public key.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {PublicKey} - The normalized counterparty public key.\n * @throws {Error} - Throws an error if the counterparty is invalid.\n */\n normalizeCounterparty(counterparty) {\n if (counterparty === null || counterparty === undefined) {\n throw new Error('counterparty must be self, anyone or a public key!');\n }\n else if (counterparty === 'self') {\n return this.rootKey.toPublicKey();\n }\n else if (counterparty === 'anyone') {\n return new PrivateKey(1).toPublicKey();\n }\n else if (typeof counterparty === 'string') {\n return PublicKey.fromString(counterparty);\n }\n else {\n return counterparty;\n }\n }\n /**\n * Computes the invoice number based on the protocol ID and key ID.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @returns {string} - The computed invoice number.\n * @throws {Error} - Throws an error if protocol ID or key ID are invalid.\n */\n computeInvoiceNumber(protocolID, keyID) {\n const securityLevel = protocolID[0];\n if (!Number.isInteger(securityLevel) ||\n securityLevel < 0 ||\n securityLevel > 2) {\n throw new Error('Protocol security level must be 0, 1, or 2');\n }\n const protocolName = protocolID[1].toLowerCase().trim();\n if (keyID.length > 800) {\n throw new Error('Key IDs must be 800 characters or less');\n }\n if (keyID.length < 1) {\n throw new Error('Key IDs must be 1 character or more');\n }\n if (protocolName.length > 400) {\n // Specific linkage revelation is the only protocol ID that can contain another protocol ID.\n // Therefore, we allow it to be long enough to encapsulate the target protocol\n if (protocolName.startsWith('specific linkage revelation ')) {\n // The format is: 'specific linkage revelation x YYYYY'\n // Where: x is the security level and YYYYY is the target protocol\n // Thus, the max acceptable length is 30 + 400 = 430 bytes\n if (protocolName.length > 430) {\n throw new Error('Specific linkage revelation protocol names must be 430 characters or less');\n }\n }\n else {\n throw new Error('Protocol names must be 400 characters or less');\n }\n }\n if (protocolName.length < 5) {\n throw new Error('Protocol names must be 5 characters or more');\n }\n if (protocolName.includes(' ')) {\n throw new Error('Protocol names cannot contain multiple consecutive spaces (\" \")');\n }\n if (!/^[a-z0-9 ]+$/g.test(protocolName)) {\n throw new Error('Protocol names can only contain letters, numbers and spaces');\n }\n if (protocolName.endsWith(' protocol')) {\n throw new Error('No need to end your protocol name with \" protocol\"');\n }\n return `${securityLevel}-${protocolName}-${keyID}`;\n }\n}\nexport default KeyDeriver;\n//# sourceMappingURL=KeyDeriver.js.map","import { PrivateKey, PublicKey } from '../primitives/index.js';\nimport { KeyDeriver } from './KeyDeriver.js';\n/**\n * A cached version of KeyDeriver that caches the results of key derivation methods.\n * This is useful for optimizing performance when the same keys are derived multiple times.\n * It supports configurable cache size with sane defaults and maintains cache entries using LRU (Least Recently Used) eviction policy.\n */\nexport default class CachedKeyDeriver {\n keyDeriver;\n cache;\n maxCacheSize;\n /**\n * The root key from which all other keys are derived.\n */\n rootKey;\n /**\n * The identity of this key deriver which is normally the public key associated with the `rootKey`\n */\n identityKey;\n /**\n * Initializes the CachedKeyDeriver instance with a root private key and optional cache settings.\n * @param {PrivateKey | 'anyone'} rootKey - The root private key or the string 'anyone'.\n * @param {Object} [options] - Optional settings for the cache.\n * @param {number} [options.maxCacheSize=1000] - The maximum number of entries to store in the cache.\n */\n constructor(rootKey, options) {\n if (rootKey === 'anyone') {\n this.rootKey = new PrivateKey(1);\n }\n else {\n this.rootKey = rootKey;\n }\n this.keyDeriver = new KeyDeriver(this.rootKey, (priv, pub, point) => {\n this.cacheSet(`${priv.toString()}-${pub.toString()}`, point);\n }, (priv, pub) => {\n return this.cacheGet(`${priv.toString()}-${pub.toString()}`);\n });\n this.identityKey = this.rootKey.toPublicKey().toString();\n this.cache = new Map();\n const maxCacheSize = options?.maxCacheSize;\n this.maxCacheSize = (maxCacheSize != null && !isNaN(maxCacheSize) && maxCacheSize > 0) ? maxCacheSize : 1000;\n }\n /**\n * Derives a public key based on protocol ID, key ID, and counterparty.\n * Caches the result for future calls with the same parameters.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @param {boolean} [forSelf=false] - Whether deriving for self.\n * @returns {PublicKey} - The derived public key.\n */\n derivePublicKey(protocolID, keyID, counterparty, forSelf = false) {\n const cacheKey = this.generateCacheKey('derivePublicKey', protocolID, keyID, counterparty, forSelf);\n if (this.cache.has(cacheKey)) {\n const cachedValue = this.cacheGet(cacheKey);\n if (cachedValue === undefined) {\n throw new Error('Cached value is undefined');\n }\n return cachedValue;\n }\n else {\n const result = this.keyDeriver.derivePublicKey(protocolID, keyID, counterparty, forSelf);\n this.cacheSet(cacheKey, result);\n return result;\n }\n }\n /**\n * Derives a private key based on protocol ID, key ID, and counterparty.\n * Caches the result for future calls with the same parameters.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {PrivateKey} - The derived private key.\n */\n derivePrivateKey(protocolID, keyID, counterparty) {\n const cacheKey = this.generateCacheKey('derivePrivateKey', protocolID, keyID, counterparty);\n if (this.cache.has(cacheKey)) {\n const cachedValue = this.cacheGet(cacheKey);\n if (cachedValue === undefined) {\n throw new Error('Cached value is undefined');\n }\n return cachedValue;\n }\n else {\n const result = this.keyDeriver.derivePrivateKey(protocolID, keyID, counterparty);\n this.cacheSet(cacheKey, result);\n return result;\n }\n }\n /**\n * Derives a symmetric key based on protocol ID, key ID, and counterparty.\n * Caches the result for future calls with the same parameters.\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {SymmetricKey} - The derived symmetric key.\n * @throws {Error} - Throws an error if attempting to derive a symmetric key for 'anyone'.\n */\n deriveSymmetricKey(protocolID, keyID, counterparty) {\n const cacheKey = this.generateCacheKey('deriveSymmetricKey', protocolID, keyID, counterparty);\n if (this.cache.has(cacheKey)) {\n const cachedValue = this.cacheGet(cacheKey);\n if (cachedValue === undefined) {\n throw new Error('Cached value is undefined');\n }\n return cachedValue;\n }\n else {\n const result = this.keyDeriver.deriveSymmetricKey(protocolID, keyID, counterparty);\n this.cacheSet(cacheKey, result);\n return result;\n }\n }\n /**\n * Reveals the shared secret between the root key and the counterparty.\n * Caches the result for future calls with the same parameters.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @returns {number[]} - The shared secret as a number array.\n * @throws {Error} - Throws an error if attempting to reveal a shared secret for 'self'.\n */\n revealCounterpartySecret(counterparty) {\n const cacheKey = this.generateCacheKey('revealCounterpartySecret', counterparty);\n if (this.cache.has(cacheKey)) {\n const cachedValue = this.cacheGet(cacheKey);\n if (cachedValue === undefined) {\n throw new Error('Cached value is undefined');\n }\n return cachedValue;\n }\n else {\n const result = this.keyDeriver.revealCounterpartySecret(counterparty);\n this.cacheSet(cacheKey, result);\n return result;\n }\n }\n /**\n * Reveals the specific key association for a given protocol ID, key ID, and counterparty.\n * Caches the result for future calls with the same parameters.\n * @param {Counterparty} counterparty - The counterparty's public key or a predefined value ('self' or 'anyone').\n * @param {WalletProtocol} protocolID - The protocol ID including a security level and protocol name.\n * @param {string} keyID - The key identifier.\n * @returns {number[]} - The specific key association as a number array.\n */\n revealSpecificSecret(counterparty, protocolID, keyID) {\n const cacheKey = this.generateCacheKey('revealSpecificSecret', counterparty, protocolID, keyID);\n if (this.cache.has(cacheKey)) {\n const cachedValue = this.cacheGet(cacheKey);\n if (cachedValue === undefined) {\n throw new Error('Cached value is undefined');\n }\n return cachedValue;\n }\n else {\n const result = this.keyDeriver.revealSpecificSecret(counterparty, protocolID, keyID);\n this.cacheSet(cacheKey, result);\n return result;\n }\n }\n /**\n * Generates a unique cache key based on the method name and input parameters.\n * @param {string} methodName - The name of the method.\n * @param {...any} args - The arguments passed to the method.\n * @returns {string} - The generated cache key.\n */\n generateCacheKey(methodName, ...args) {\n const serializedArgs = args\n .map((arg) => this.serializeArgument(arg))\n .join('|');\n return `${methodName}|${serializedArgs}`;\n }\n /**\n * Serializes an argument to a string for use in a cache key.\n * @param {any} arg - The argument to serialize.\n * @returns {string} - The serialized argument.\n */\n serializeArgument(arg) {\n if (arg instanceof PublicKey || arg instanceof PrivateKey) {\n return arg.toString();\n }\n else if (Array.isArray(arg)) {\n return arg.map((item) => this.serializeArgument(item)).join(',');\n }\n else if (typeof arg === 'object' && arg !== null) {\n return JSON.stringify(arg);\n }\n else {\n return String(arg);\n }\n }\n /**\n * Retrieves an item from the cache and updates its position to reflect recent use.\n * @param {string} cacheKey - The key of the cached item.\n * @returns {any} - The cached value.\n */\n cacheGet(cacheKey) {\n const value = this.cache.get(cacheKey);\n // Update the entry to reflect recent use\n this.cache.delete(cacheKey);\n if (value !== undefined) {\n this.cache.set(cacheKey, value);\n }\n return value;\n }\n /**\n * Adds an item to the cache and evicts the least recently used item if necessary.\n * @param {string} cacheKey - The key of the item to cache.\n * @param {any} value - The value to cache.\n */\n cacheSet(cacheKey, value) {\n if (this.cache.size >= this.maxCacheSize) {\n // Evict the least recently used item (first item in Map)\n const firstKey = this.cache.keys().next().value;\n this.cache.delete(firstKey);\n }\n this.cache.set(cacheKey, value);\n }\n}\n//# sourceMappingURL=CachedKeyDeriver.js.map","import CachedKeyDeriver from './CachedKeyDeriver.js';\nimport { Hash, ECDSA, BigNumber, Signature, Schnorr, PublicKey, Point } from '../primitives/index.js';\n/**\n * A ProtoWallet is precursor to a full wallet, capable of performing all foundational cryptographic operations.\n * It can derive keys, create signatures, facilitate encryption and HMAC operations, and reveal key linkages.\n *\n * However, ProtoWallet does not create transactions, manage outputs, interact with the blockchain,\n * enable the management of identity certificates, or store any data. It is also not concerned with privileged keys.\n */\nexport class ProtoWallet {\n keyDeriver;\n constructor(rootKeyOrKeyDeriver) {\n if (typeof rootKeyOrKeyDeriver.identityKey !== 'string') {\n rootKeyOrKeyDeriver = new CachedKeyDeriver(rootKeyOrKeyDeriver);\n }\n this.keyDeriver = rootKeyOrKeyDeriver;\n }\n async getPublicKey(args) {\n if (args.identityKey) {\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n return { publicKey: this.keyDeriver.rootKey.toPublicKey().toString() };\n }\n else {\n if (args.protocolID == null || args.keyID == null || args.keyID === '') {\n throw new Error('protocolID and keyID are required if identityKey is false or undefined.');\n }\n const keyDeriver = this.keyDeriver ??\n (() => {\n throw new Error('keyDeriver is undefined');\n })();\n return {\n publicKey: keyDeriver\n .derivePublicKey(args.protocolID, args.keyID, args.counterparty ?? 'self', args.forSelf)\n .toString()\n };\n }\n }\n async revealCounterpartyKeyLinkage(args) {\n const { publicKey: identityKey } = await this.getPublicKey({\n identityKey: true\n });\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const linkage = this.keyDeriver.revealCounterpartySecret(args.counterparty);\n const linkageProof = new Schnorr().generateProof(this.keyDeriver.rootKey, this.keyDeriver.rootKey.toPublicKey(), PublicKey.fromString(args.counterparty), Point.fromDER(linkage));\n const linkageProofBin = [\n ...linkageProof.R.encode(true),\n ...linkageProof.SPrime.encode(true),\n ...linkageProof.z.toArray()\n ];\n const revelationTime = new Date().toISOString();\n const { ciphertext: encryptedLinkage } = await this.encrypt({\n plaintext: linkage,\n protocolID: [2, 'counterparty linkage revelation'],\n keyID: revelationTime,\n counterparty: args.verifier\n });\n const { ciphertext: encryptedLinkageProof } = await this.encrypt({\n plaintext: linkageProofBin,\n protocolID: [2, 'counterparty linkage revelation'],\n keyID: revelationTime,\n counterparty: args.verifier\n });\n return {\n prover: identityKey,\n verifier: args.verifier,\n counterparty: args.counterparty,\n revelationTime,\n encryptedLinkage,\n encryptedLinkageProof\n };\n }\n async revealSpecificKeyLinkage(args) {\n const { publicKey: identityKey } = await this.getPublicKey({\n identityKey: true\n });\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const linkage = this.keyDeriver.revealSpecificSecret(args.counterparty, args.protocolID, args.keyID);\n const { ciphertext: encryptedLinkage } = await this.encrypt({\n plaintext: linkage,\n protocolID: [\n 2,\n `specific linkage revelation ${args.protocolID[0]} ${args.protocolID[1]}`\n ],\n keyID: args.keyID,\n counterparty: args.verifier\n });\n const { ciphertext: encryptedLinkageProof } = await this.encrypt({\n plaintext: [0], // Proof type 0, no proof provided\n protocolID: [\n 2,\n `specific linkage revelation ${args.protocolID[0]} ${args.protocolID[1]}`\n ],\n keyID: args.keyID,\n counterparty: args.verifier\n });\n return {\n prover: identityKey,\n verifier: args.verifier,\n counterparty: args.counterparty,\n protocolID: args.protocolID,\n keyID: args.keyID,\n encryptedLinkage,\n encryptedLinkageProof,\n proofType: 0\n };\n }\n async encrypt(args) {\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const key = this.keyDeriver.deriveSymmetricKey(args.protocolID, args.keyID, args.counterparty ?? 'self');\n return { ciphertext: key.encrypt(args.plaintext) };\n }\n async decrypt(args, originator) {\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const key = this.keyDeriver.deriveSymmetricKey(args.protocolID, args.keyID, args.counterparty ?? 'self');\n return { plaintext: key.decrypt(args.ciphertext) };\n }\n async createHmac(args) {\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const key = this.keyDeriver.deriveSymmetricKey(args.protocolID, args.keyID, args.counterparty ?? 'self');\n return { hmac: Hash.sha256hmac(key.toArray(), args.data) };\n }\n async verifyHmac(args) {\n if (this.keyDeriver == null) {\n throw new Error('keyDeriver is undefined');\n }\n const key = this.keyDeriver.deriveSymmetricKey(args.protocolID, args.keyID, args.counterparty ?? 'self');\n const valid = Hash.sha256hmac(key.toArray(), args.data).toString() ===\n args.hmac.toString();\n if (!valid) {\n const e = new Error('HMAC is not valid');\n e.code = 'ERR_INVALID_HMAC';\n throw e;\n }\n return { valid };\n }\n async createSignature(args) {\n if ((args.hashToDirectlySign == null) && (args.data == null)) {\n throw new Error('args.data or args.hashToDirectlySign must be valid');\n }\n const hash = args.hashToDirectlySign ?? Hash.sha256(args.data ?? []);\n const keyDeriver = this.keyDeriver ??\n (() => {\n throw new Error('keyDeriver is undefined');\n })();\n const key = keyDeriver.derivePrivateKey(args.protocolID, args.keyID, args.counterparty ?? 'anyone');\n return {\n signature: ECDSA.sign(new BigNumber(hash), key, true).toDER()\n };\n }\n async verifySignature(args) {\n if ((args.hashToDirectlyVerify == null) && (args.data == null)) {\n throw new Error('args.data or args.hashToDirectlyVerify must be valid');\n }\n const hash = args.hashToDirectlyVerify ?? Hash.sha256(args.data ?? []);\n const keyDeriver = this.keyDeriver ??\n (() => {\n throw new Error('keyDeriver is undefined');\n })();\n const key = keyDeriver.derivePublicKey(args.protocolID, args.keyID, args.counterparty ?? 'self', args.forSelf);\n const valid = ECDSA.verify(new BigNumber(hash), Signature.fromDER(args.signature), key);\n if (!valid) {\n const e = new Error('Signature is not valid');\n e.code = 'ERR_INVALID_SIGNATURE';\n throw e;\n }\n return { valid };\n }\n}\nexport default ProtoWallet;\n//# sourceMappingURL=ProtoWallet.js.map","/**\n * Facilitates wallet operations over the window.CWI interface.\n */\nexport default class WindowCWISubstrate {\n CWI;\n constructor() {\n if (typeof window !== 'object') {\n throw new Error('The window.CWI substrate requires a global window object.');\n }\n if (typeof window.CWI !== 'object') {\n throw new Error('The window.CWI interface does not appear to be bound to the window object.');\n }\n this.CWI = window.CWI; // Binding CWI to prevent changes\n }\n async createAction(args, originator) {\n return await this.CWI.createAction(args, originator);\n }\n async signAction(args, originator) {\n return await this.CWI.signAction(args, originator);\n }\n async abortAction(args, originator) {\n return await this.CWI.abortAction(args, originator);\n }\n async listActions(args, originator) {\n return await this.CWI.listActions(args, originator);\n }\n async internalizeAction(args, originator) {\n return await this.CWI.internalizeAction(args, originator);\n }\n async listOutputs(args, originator) {\n return await this.CWI.listOutputs(args, originator);\n }\n async relinquishOutput(args, originator) {\n return await this.CWI.relinquishOutput(args, originator);\n }\n async getPublicKey(args, originator) {\n return await this.CWI.getPublicKey(args, originator);\n }\n async revealCounterpartyKeyLinkage(args, originator) {\n return await this.CWI.revealCounterpartyKeyLinkage(args, originator);\n }\n async revealSpecificKeyLinkage(args, originator) {\n return await this.CWI.revealSpecificKeyLinkage(args, originator);\n }\n async encrypt(args, originator) {\n return await this.CWI.encrypt(args, originator);\n }\n async decrypt(args, originator) {\n return await this.CWI.decrypt(args, originator);\n }\n async createHmac(args, originator) {\n return await this.CWI.createHmac(args, originator);\n }\n async verifyHmac(args, originator) {\n return await this.CWI.verifyHmac(args, originator);\n }\n async createSignature(args, originator) {\n return await this.CWI.createSignature(args, originator);\n }\n async verifySignature(args, originator) {\n return await this.CWI.verifySignature(args, originator);\n }\n async acquireCertificate(args, originator) {\n return await this.CWI.acquireCertificate(args, originator);\n }\n async listCertificates(args, originator) {\n return await this.CWI.listCertificates(args, originator);\n }\n async proveCertificate(args, originator) {\n return await this.CWI.proveCertificate(args, originator);\n }\n async relinquishCertificate(args, originator) {\n return await this.CWI.relinquishCertificate(args, originator);\n }\n async discoverByIdentityKey(args, originator) {\n return await this.CWI.discoverByIdentityKey(args, originator);\n }\n async discoverByAttributes(args, originator) {\n return await this.CWI.discoverByAttributes(args, originator);\n }\n async isAuthenticated(args, originator) {\n return await this.CWI.isAuthenticated(args, originator);\n }\n async waitForAuthentication(args, originator) {\n return await this.CWI.waitForAuthentication(args, originator);\n }\n async getHeight(args, originator) {\n return await this.CWI.getHeight(args, originator);\n }\n async getHeaderForHeight(args, originator) {\n return await this.CWI.getHeaderForHeight(args, originator);\n }\n async getNetwork(args, originator) {\n return await this.CWI.getNetwork(args, originator);\n }\n async getVersion(args, originator) {\n return await this.CWI.getVersion(args, originator);\n }\n}\n//# sourceMappingURL=window.CWI.js.map","import Random from '../../primitives/Random.js';\nimport * as Utils from '../../primitives/utils.js';\nimport { WalletError } from '../WalletError.js';\n/**\n * Facilitates wallet operations over cross-document messaging.\n */\nexport default class XDMSubstrate {\n domain;\n constructor(domain = '*') {\n if (typeof window !== 'object') {\n throw new Error('The XDM substrate requires a global window object.');\n }\n if (typeof window.postMessage !== 'function') {\n throw new Error('The window object does not seem to support postMessage calls.');\n }\n this.domain = domain;\n }\n async invoke(call, args) {\n return await new Promise((resolve, reject) => {\n const id = Utils.toBase64(Random(12));\n const listener = (e) => {\n if (e.data.type !== 'CWI' ||\n !e.isTrusted ||\n e.data.id !== id ||\n e.data.isInvocation === true) {\n return;\n }\n if (typeof window.removeEventListener === 'function') {\n window.removeEventListener('message', listener);\n }\n if (e.data.status === 'error') {\n const err = new WalletError(e.data.description, e.data.code);\n reject(err);\n }\n else {\n resolve(e.data.result);\n }\n };\n window.addEventListener('message', listener);\n window.parent.postMessage({\n type: 'CWI',\n isInvocation: true,\n id,\n call,\n args\n }, this.domain);\n });\n }\n async createAction(args) {\n return await this.invoke('createAction', args);\n }\n async signAction(args) {\n return await this.invoke('signAction', args);\n }\n async abortAction(args) {\n return await this.invoke('abortAction', args);\n }\n async listActions(args) {\n return await this.invoke('listActions', args);\n }\n async internalizeAction(args) {\n return await this.invoke('internalizeAction', args);\n }\n async listOutputs(args) {\n return await this.invoke('listOutputs', args);\n }\n async relinquishOutput(args) {\n return await this.invoke('relinquishOutput', args);\n }\n async getPublicKey(args) {\n return await this.invoke('getPublicKey', args);\n }\n async revealCounterpartyKeyLinkage(args) {\n return await this.invoke('revealCounterpartyKeyLinkage', args);\n }\n async revealSpecificKeyLinkage(args) {\n return await this.invoke('revealSpecificKeyLinkage', args);\n }\n async encrypt(args) {\n return await this.invoke('encrypt', args);\n }\n async decrypt(args) {\n return await this.invoke('decrypt', args);\n }\n async createHmac(args) {\n return await this.invoke('createHmac', args);\n }\n async verifyHmac(args) {\n return await this.invoke('verifyHmac', args);\n }\n async createSignature(args) {\n return await this.invoke('createSignature', args);\n }\n async verifySignature(args) {\n return await this.invoke('verifySignature', args);\n }\n async acquireCertificate(args) {\n return await this.invoke('acquireCertificate', args);\n }\n async listCertificates(args) {\n return await this.invoke('listCertificates', args);\n }\n async proveCertificate(args) {\n return await this.invoke('proveCertificate', args);\n }\n async relinquishCertificate(args) {\n return await this.invoke('relinquishCertificate', args);\n }\n async discoverByIdentityKey(args) {\n return await this.invoke('discoverByIdentityKey', args);\n }\n async discoverByAttributes(args) {\n return await this.invoke('discoverByAttributes', args);\n }\n async isAuthenticated(args) {\n return await this.invoke('isAuthenticated', args);\n }\n async waitForAuthentication(args) {\n return await this.invoke('waitForAuthentication', args);\n }\n async getHeight(args) {\n return await this.invoke('getHeight', args);\n }\n async getHeaderForHeight(args) {\n return await this.invoke('getHeaderForHeight', args);\n }\n async getNetwork(args) {\n return await this.invoke('getNetwork', args);\n }\n async getVersion(args) {\n return await this.invoke('getVersion', args);\n }\n}\n//# sourceMappingURL=XDM.js.map","import * as Utils from '../../primitives/utils.js';\nimport ProtoWallet from '../../wallet/ProtoWallet.js';\nimport Signature from '../../primitives/Signature.js';\n/**\n * Represents an Identity Certificate as per the Wallet interface specifications.\n *\n * This class provides methods to serialize and deserialize certificates, as well as signing and verifying the certificate's signature.\n */\nexport default class Certificate {\n /**\n * Type identifier for the certificate, base64 encoded string, 32 bytes.\n */\n type;\n /**\n * Unique serial number of the certificate, base64 encoded string, 32 bytes.\n */\n serialNumber;\n /**\n * The public key belonging to the certificate's subject, compressed public key hex string.\n */\n subject;\n /**\n * Public key of the certifier who issued the certificate, compressed public key hex string.\n */\n certifier;\n /**\n * The outpoint used to confirm that the certificate has not been revoked (TXID.OutputIndex), as a string.\n */\n revocationOutpoint;\n /**\n * All the fields present in the certificate, with field names as keys and encrypted field values as Base64 strings.\n */\n fields;\n /**\n * Certificate signature by the certifier's private key, DER encoded hex string.\n */\n signature;\n /**\n * Constructs a new Certificate.\n *\n * @param {Base64String} type - Type identifier for the certificate, base64 encoded string, 32 bytes.\n * @param {Base64String} serialNumber - Unique serial number of the certificate, base64 encoded string, 32 bytes.\n * @param {PubKeyHex} subject - The public key belonging to the certificate's subject, compressed public key hex string.\n * @param {PubKeyHex} certifier - Public key of the certifier who issued the certificate, compressed public key hex string.\n * @param {OutpointString} revocationOutpoint - The outpoint used to confirm that the certificate has not been revoked (TXID.OutputIndex), as a string.\n * @param {Record<CertificateFieldNameUnder50Bytes, string>} fields - All the fields present in the certificate.\n * @param {HexString} signature - Certificate signature by the certifier's private key, DER encoded hex string.\n */\n constructor(type, serialNumber, subject, certifier, revocationOutpoint, fields, signature) {\n this.type = type;\n this.serialNumber = serialNumber;\n this.subject = subject;\n this.certifier = certifier;\n this.revocationOutpoint = revocationOutpoint;\n this.fields = fields;\n this.signature = signature;\n }\n /**\n * Serializes the certificate into binary format, with or without a signature.\n *\n * @param {boolean} [includeSignature=true] - Whether to include the signature in the serialization.\n * @returns {number[]} - The serialized certificate in binary format.\n */\n toBinary(includeSignature = true) {\n const writer = new Utils.Writer();\n // Write type (Base64String, 32 bytes)\n const typeBytes = Utils.toArray(this.type, 'base64');\n writer.write(typeBytes);\n // Write serialNumber (Base64String, 32 bytes)\n const serialNumberBytes = Utils.toArray(this.serialNumber, 'base64');\n writer.write(serialNumberBytes);\n // Write subject (33 bytes compressed PubKeyHex)\n const subjectBytes = Utils.toArray(this.subject, 'hex');\n writer.write(subjectBytes);\n // Write certifier (33 bytes compressed PubKeyHex)\n const certifierBytes = Utils.toArray(this.certifier, 'hex');\n writer.write(certifierBytes);\n // Write revocationOutpoint (TXID + OutputIndex)\n const [txid, outputIndex] = this.revocationOutpoint.split('.');\n const txidBytes = Utils.toArray(txid, 'hex');\n writer.write(txidBytes);\n writer.writeVarIntNum(Number(outputIndex));\n // Write fields\n // Sort field names lexicographically\n const fieldNames = Object.keys(this.fields).sort();\n writer.writeVarIntNum(fieldNames.length);\n for (const fieldName of fieldNames) {\n const fieldValue = this.fields[fieldName];\n // Field name\n const fieldNameBytes = Utils.toArray(fieldName, 'utf8');\n writer.writeVarIntNum(fieldNameBytes.length);\n writer.write(fieldNameBytes);\n // Field value\n const fieldValueBytes = Utils.toArray(fieldValue, 'utf8');\n writer.writeVarIntNum(fieldValueBytes.length);\n writer.write(fieldValueBytes);\n }\n // Write signature if included\n if (includeSignature && (this.signature ?? '').length > 0) { // ✅ Explicitly handle nullish signature\n const signatureBytes = Utils.toArray(this.signature, 'hex'); // ✅ Type assertion ensures it's a string\n writer.write(signatureBytes);\n }\n return writer.toArray();\n }\n /**\n * Deserializes a certificate from binary format.\n *\n * @param {number[]} bin - The binary data representing the certificate.\n * @returns {Certificate} - The deserialized Certificate object.\n */\n static fromBinary(bin) {\n const reader = new Utils.Reader(bin);\n // Read type\n const typeBytes = reader.read(32);\n const type = Utils.toBase64(typeBytes);\n // Read serialNumber\n const serialNumberBytes = reader.read(32);\n const serialNumber = Utils.toBase64(serialNumberBytes);\n // Read subject (33 bytes)\n const subjectBytes = reader.read(33);\n const subject = Utils.toHex(subjectBytes);\n // Read certifier (33 bytes)\n const certifierBytes = reader.read(33);\n const certifier = Utils.toHex(certifierBytes);\n // Read revocationOutpoint\n const txidBytes = reader.read(32);\n const txid = Utils.toHex(txidBytes);\n const outputIndex = reader.readVarIntNum();\n const revocationOutpoint = `${txid}.${outputIndex}`;\n // Read fields\n const numFields = reader.readVarIntNum();\n const fields = {};\n for (let i = 0; i < numFields; i++) {\n // Field name\n const fieldNameLength = reader.readVarIntNum();\n const fieldNameBytes = reader.read(fieldNameLength);\n const fieldName = Utils.toUTF8(fieldNameBytes);\n // Field value\n const fieldValueLength = reader.readVarIntNum();\n const fieldValueBytes = reader.read(fieldValueLength);\n const fieldValue = Utils.toUTF8(fieldValueBytes);\n fields[fieldName] = fieldValue;\n }\n // Read signature if present\n let signature;\n if (!reader.eof()) {\n const signatureBytes = reader.read();\n const sig = Signature.fromDER(signatureBytes);\n signature = sig.toString('hex');\n }\n return new Certificate(type, serialNumber, subject, certifier, revocationOutpoint, fields, signature);\n }\n /**\n * Verifies the certificate's signature.\n *\n * @returns {Promise<boolean>} - A promise that resolves to true if the signature is valid.\n */\n async verify() {\n // A verifier can be any wallet capable of verifying signatures\n const verifier = new ProtoWallet('anyone');\n const verificationData = this.toBinary(false); // Exclude the signature from the verification data\n const signatureHex = this.signature ?? ''; // Provide a fallback value (empty string)\n const { valid } = await verifier.verifySignature({\n signature: Utils.toArray(signatureHex, 'hex'), // Now it is always a string\n data: verificationData,\n protocolID: [2, 'certificate signature'],\n keyID: `${this.type} ${this.serialNumber}`,\n counterparty: this.certifier // The certifier is the one who signed the certificate\n });\n return valid;\n }\n /**\n * Signs the certificate using the provided certifier wallet.\n *\n * @param {Wallet} certifierWallet - The wallet representing the certifier.\n * @returns {Promise<void>}\n */\n async sign(certifierWallet) {\n if (this.signature != null && this.signature.length > 0) { // ✅ Explicitly checking for null/undefined\n throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);\n }\n // Ensure the certifier declared is the one actually signing\n this.certifier = (await certifierWallet.getPublicKey({ identityKey: true })).publicKey;\n const preimage = this.toBinary(false); // Exclude the signature when signing\n const { signature } = await certifierWallet.createSignature({\n data: preimage,\n protocolID: [2, 'certificate signature'],\n keyID: `${this.type} ${this.serialNumber}`\n });\n this.signature = Utils.toHex(signature);\n }\n /**\n * Helper function which retrieves the protocol ID and key ID for certificate field encryption.\n *\n * For master certificate creation, no serial number is provided because entropy is required\n * from both the client and the certifier. In this case, the `keyID` is simply the `fieldName`.\n *\n * For VerifiableCertificates verifier keyring creation, both the serial number and field name are available,\n * so the `keyID` is formed by concatenating the `serialNumber` and `fieldName`.\n *\n * @param fieldName - The name of the field within the certificate to be encrypted.\n * @param serialNumber - (Optional) The serial number of the certificate.\n * @returns An object containing:\n * - `protocolID` (WalletProtocol): The protocol ID for certificate field encryption.\n * - `keyID` (string): A unique key identifier. It is the `fieldName` if `serialNumber` is undefined,\n * otherwise it is a combination of `serialNumber` and `fieldName`.\n */\n static getCertificateFieldEncryptionDetails(fieldName, serialNumber) {\n return {\n protocolID: [2, 'certificate field encryption'],\n keyID: serialNumber ? `${serialNumber} ${fieldName}` : fieldName\n };\n }\n /**\n * Creates a Certificate instance from a plain object representation.\n *\n * @param obj - The object containing certificate data.\n * @returns A new Certificate instance.\n */\n static fromObject(obj) {\n const cert = new Certificate(obj.type, obj.serialNumber, obj.subject, obj.certifier, obj.revocationOutpoint, obj.fields, obj.signature);\n return cert;\n }\n}\n//# sourceMappingURL=Certificate.js.map","import { SecurityLevels } from '../Wallet.interfaces.js';\nimport Certificate from '../../auth/certificates/Certificate.js';\nimport * as Utils from '../../primitives/utils.js';\nimport calls from './WalletWireCalls.js';\nimport { WalletError } from '../WalletError.js';\n/**\n * A way to make remote calls to a wallet over a wallet wire.\n */\nexport default class WalletWireTransceiver {\n wire;\n constructor(wire) {\n this.wire = wire;\n }\n async transmit(call, originator = '', params = []) {\n const frameWriter = new Utils.Writer();\n frameWriter.writeUInt8(calls[call]);\n const originatorArray = Utils.toArray(originator, 'utf8');\n frameWriter.writeUInt8(originatorArray.length);\n frameWriter.write(originatorArray);\n if (params.length > 0) {\n frameWriter.write(params);\n }\n const frame = frameWriter.toArray();\n const result = await this.wire.transmitToWallet(frame);\n const resultReader = new Utils.Reader(result);\n const errorByte = resultReader.readUInt8();\n if (errorByte === 0) {\n const resultFrame = resultReader.read();\n return resultFrame;\n }\n else {\n // Deserialize the error message length\n const errorMessageLength = resultReader.readVarIntNum();\n const errorMessageBytes = resultReader.read(errorMessageLength);\n const errorMessage = Utils.toUTF8(errorMessageBytes);\n // Deserialize the stack trace length\n const stackTraceLength = resultReader.readVarIntNum();\n const stackTraceBytes = resultReader.read(stackTraceLength);\n const stackTrace = Utils.toUTF8(stackTraceBytes);\n // Construct a custom wallet error\n const e = new WalletError(errorMessage, errorByte, stackTrace);\n throw e;\n }\n }\n async createAction(args, originator) {\n const paramWriter = new Utils.Writer();\n // Serialize description\n const descriptionBytes = Utils.toArray(args.description, 'utf8');\n paramWriter.writeVarIntNum(descriptionBytes.length);\n paramWriter.write(descriptionBytes);\n // input BEEF\n if (args.inputBEEF != null) {\n paramWriter.writeVarIntNum(args.inputBEEF.length);\n paramWriter.write(args.inputBEEF);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize inputs\n if (args.inputs != null) {\n paramWriter.writeVarIntNum(args.inputs.length);\n for (const input of args.inputs) {\n // outpoint\n paramWriter.write(this.encodeOutpoint(input.outpoint));\n // unlockingScript / unlockingScriptLength\n if (input.unlockingScript != null && input.unlockingScript !== '') {\n const unlockingScriptBytes = Utils.toArray(input.unlockingScript, 'hex');\n paramWriter.writeVarIntNum(unlockingScriptBytes.length);\n paramWriter.write(unlockingScriptBytes);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n paramWriter.writeVarIntNum(input.unlockingScriptLength ?? 0);\n }\n // inputDescription\n const inputDescriptionBytes = Utils.toArray(input.inputDescription, 'utf8');\n paramWriter.writeVarIntNum(inputDescriptionBytes.length);\n paramWriter.write(inputDescriptionBytes);\n // sequenceNumber\n if (typeof input.sequenceNumber === 'number') {\n paramWriter.writeVarIntNum(input.sequenceNumber);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize outputs\n if (args.outputs != null) {\n paramWriter.writeVarIntNum(args.outputs.length);\n for (const output of args.outputs) {\n // lockingScript\n const lockingScriptBytes = Utils.toArray(output.lockingScript, 'hex');\n paramWriter.writeVarIntNum(lockingScriptBytes.length);\n paramWriter.write(lockingScriptBytes);\n // satoshis\n paramWriter.writeVarIntNum(output.satoshis);\n // outputDescription\n const outputDescriptionBytes = Utils.toArray(output.outputDescription, 'utf8');\n paramWriter.writeVarIntNum(outputDescriptionBytes.length);\n paramWriter.write(outputDescriptionBytes);\n // basket\n if (output.basket != null && output.basket !== '') {\n const basketBytes = Utils.toArray(output.basket, 'utf8');\n paramWriter.writeVarIntNum(basketBytes.length);\n paramWriter.write(basketBytes);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // customInstructions\n if (output.customInstructions != null && output.customInstructions !== '') {\n const customInstructionsBytes = Utils.toArray(output.customInstructions, 'utf8');\n paramWriter.writeVarIntNum(customInstructionsBytes.length);\n paramWriter.write(customInstructionsBytes);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // tags\n if (output.tags != null) {\n paramWriter.writeVarIntNum(output.tags.length);\n for (const tag of output.tags) {\n const tagBytes = Utils.toArray(tag, 'utf8');\n paramWriter.writeVarIntNum(tagBytes.length);\n paramWriter.write(tagBytes);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize lockTime\n if (typeof args.lockTime === 'number') {\n paramWriter.writeVarIntNum(args.lockTime);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize version\n if (typeof args.version === 'number') {\n paramWriter.writeVarIntNum(args.version);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize labels\n if (args.labels != null) {\n paramWriter.writeVarIntNum(args.labels.length);\n for (const label of args.labels) {\n const labelBytes = Utils.toArray(label, 'utf8');\n paramWriter.writeVarIntNum(labelBytes.length);\n paramWriter.write(labelBytes);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize options\n if (args.options != null) {\n paramWriter.writeInt8(1); // options present\n // signAndProcess\n if (typeof args.options.signAndProcess === 'boolean') {\n paramWriter.writeInt8(args.options.signAndProcess ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // acceptDelayedBroadcast\n if (typeof args.options.acceptDelayedBroadcast === 'boolean') {\n paramWriter.writeInt8(args.options.acceptDelayedBroadcast ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // trustSelf\n if (args.options.trustSelf === 'known') {\n paramWriter.writeInt8(1);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // knownTxids\n if (args.options.knownTxids != null) {\n paramWriter.writeVarIntNum(args.options.knownTxids.length);\n for (const txid of args.options.knownTxids) {\n const txidBytes = Utils.toArray(txid, 'hex');\n paramWriter.write(txidBytes);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // returnTXIDOnly\n if (typeof args.options.returnTXIDOnly === 'boolean') {\n paramWriter.writeInt8(args.options.returnTXIDOnly ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // noSend\n if (typeof args.options.noSend === 'boolean') {\n paramWriter.writeInt8(args.options.noSend ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // noSendChange\n if (args.options.noSendChange != null) {\n paramWriter.writeVarIntNum(args.options.noSendChange.length);\n for (const outpoint of args.options.noSendChange) {\n paramWriter.write(this.encodeOutpoint(outpoint));\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // sendWith\n if (args.options.sendWith != null) {\n paramWriter.writeVarIntNum(args.options.sendWith.length);\n for (const txid of args.options.sendWith) {\n const txidBytes = Utils.toArray(txid, 'hex');\n paramWriter.write(txidBytes);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // randomizeOutputs\n if (typeof args.options.randomizeOutputs === 'boolean') {\n paramWriter.writeInt8(args.options.randomizeOutputs ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n }\n else {\n paramWriter.writeInt8(0); // options not present\n }\n // Transmit and parse response\n const result = await this.transmit('createAction', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const response = {};\n // Parse txid\n const txidFlag = resultReader.readInt8();\n if (txidFlag === 1) {\n const txidBytes = resultReader.read(32);\n response.txid = Utils.toHex(txidBytes);\n }\n // Parse tx\n const txFlag = resultReader.readInt8();\n if (txFlag === 1) {\n const txLength = resultReader.readVarIntNum();\n response.tx = resultReader.read(txLength);\n }\n // Parse noSendChange\n const noSendChangeLength = resultReader.readVarIntNum();\n if (noSendChangeLength >= 0) {\n response.noSendChange = [];\n for (let i = 0; i < noSendChangeLength; i++) {\n const outpoint = this.readOutpoint(resultReader);\n response.noSendChange.push(outpoint);\n }\n }\n // Parse sendWithResults\n const sendWithResultsLength = resultReader.readVarIntNum();\n if (sendWithResultsLength >= 0) {\n response.sendWithResults = [];\n for (let i = 0; i < sendWithResultsLength; i++) {\n const txidBytes = resultReader.read(32);\n const txid = Utils.toHex(txidBytes);\n const statusCode = resultReader.readInt8();\n let status = 'unproven';\n if (statusCode === 1)\n status = 'unproven';\n else if (statusCode === 2)\n status = 'sending';\n else if (statusCode === 3)\n status = 'failed';\n response.sendWithResults.push({ txid, status });\n }\n }\n // Parse signableTransaction\n const signableTransactionFlag = resultReader.readInt8();\n if (signableTransactionFlag === 1) {\n const txLength = resultReader.readVarIntNum();\n const tx = resultReader.read(txLength);\n const referenceLength = resultReader.readVarIntNum();\n const referenceBytes = resultReader.read(referenceLength);\n response.signableTransaction = {\n tx,\n reference: Utils.toBase64(referenceBytes)\n };\n }\n return response;\n }\n async signAction(args, originator) {\n const paramWriter = new Utils.Writer();\n // Serialize spends\n const spendIndexes = Object.keys(args.spends);\n paramWriter.writeVarIntNum(spendIndexes.length);\n for (const index of spendIndexes) {\n paramWriter.writeVarIntNum(Number(index));\n const spend = args.spends[Number(index)];\n // unlockingScript\n const unlockingScriptBytes = Utils.toArray(spend.unlockingScript, 'hex');\n paramWriter.writeVarIntNum(unlockingScriptBytes.length);\n paramWriter.write(unlockingScriptBytes);\n // sequenceNumber\n if (typeof spend.sequenceNumber === 'number') {\n paramWriter.writeVarIntNum(spend.sequenceNumber);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n }\n // Serialize reference\n const referenceBytes = Utils.toArray(args.reference, 'base64');\n paramWriter.writeVarIntNum(referenceBytes.length);\n paramWriter.write(referenceBytes);\n // Serialize options\n if (args.options != null) {\n paramWriter.writeInt8(1); // options present\n // acceptDelayedBroadcast\n if (typeof args.options.acceptDelayedBroadcast === 'boolean') {\n paramWriter.writeInt8(args.options.acceptDelayedBroadcast ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // returnTXIDOnly\n if (typeof args.options.returnTXIDOnly === 'boolean') {\n paramWriter.writeInt8(args.options.returnTXIDOnly ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // noSend\n if (typeof args.options.noSend === 'boolean') {\n paramWriter.writeInt8(args.options.noSend ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // sendWith\n if (args.options.sendWith != null) {\n paramWriter.writeVarIntNum(args.options.sendWith.length);\n for (const txid of args.options.sendWith) {\n const txidBytes = Utils.toArray(txid, 'hex');\n paramWriter.write(txidBytes);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n }\n else {\n paramWriter.writeInt8(0); // options not present\n }\n // Transmit and parse response\n const result = await this.transmit('signAction', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const response = {};\n // Parse txid\n const txidFlag = resultReader.readInt8();\n if (txidFlag === 1) {\n const txidBytes = resultReader.read(32);\n response.txid = Utils.toHex(txidBytes);\n }\n // Parse tx\n const txFlag = resultReader.readInt8();\n if (txFlag === 1) {\n const txLength = resultReader.readVarIntNum();\n response.tx = resultReader.read(txLength);\n }\n // Parse sendWithResults\n const sendWithResultsLength = resultReader.readVarIntNum();\n if (sendWithResultsLength >= 0) {\n response.sendWithResults = [];\n for (let i = 0; i < sendWithResultsLength; i++) {\n const txidBytes = resultReader.read(32);\n const txid = Utils.toHex(txidBytes);\n const statusCode = resultReader.readInt8();\n let status = 'unproven';\n if (statusCode === 1)\n status = 'unproven';\n else if (statusCode === 2)\n status = 'sending';\n else if (statusCode === 3)\n status = 'failed';\n response.sendWithResults.push({ txid, status });\n }\n }\n return response;\n }\n async abortAction(args, originator) {\n await this.transmit('abortAction', originator, Utils.toArray(args.reference, 'base64'));\n return { aborted: true };\n }\n async listActions(args, originator) {\n const paramWriter = new Utils.Writer();\n // Serialize labels\n paramWriter.writeVarIntNum(args.labels.length);\n for (const label of args.labels) {\n const labelBytes = Utils.toArray(label, 'utf8');\n paramWriter.writeVarIntNum(labelBytes.length);\n paramWriter.write(labelBytes);\n }\n // Serialize labelQueryMode\n if (args.labelQueryMode === 'any') {\n paramWriter.writeInt8(1);\n }\n else if (args.labelQueryMode === 'all') {\n paramWriter.writeInt8(2);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n // Serialize include options\n const includeOptions = [\n args.includeLabels,\n args.includeInputs,\n args.includeInputSourceLockingScripts,\n args.includeInputUnlockingScripts,\n args.includeOutputs,\n args.includeOutputLockingScripts\n ];\n for (const option of includeOptions) {\n if (typeof option === 'boolean') {\n paramWriter.writeInt8(option ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n }\n // Serialize limit and offset\n if (typeof args.limit === 'number') {\n paramWriter.writeVarIntNum(args.limit);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof args.offset === 'number') {\n paramWriter.writeVarIntNum(args.offset);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n // Transmit and parse response\n const result = await this.transmit('listActions', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const totalActions = resultReader.readVarIntNum();\n const actions = [];\n for (let i = 0; i < totalActions; i++) {\n // Parse action fields\n const txidBytes = resultReader.read(32);\n const txid = Utils.toHex(txidBytes);\n const satoshis = resultReader.readVarIntNum();\n const statusCode = resultReader.readInt8();\n let status;\n switch (statusCode) {\n case 1:\n status = 'completed';\n break;\n case 2:\n status = 'unprocessed';\n break;\n case 3:\n status = 'sending';\n break;\n case 4:\n status = 'unproven';\n break;\n case 5:\n status = 'unsigned';\n break;\n case 6:\n status = 'nosend';\n break;\n case 7:\n status = 'nonfinal';\n break;\n case 8:\n status = 'failed';\n break;\n default:\n throw new Error(`Unknown status code: ${statusCode}`);\n }\n const isOutgoing = resultReader.readInt8() === 1;\n const descriptionLength = resultReader.readVarIntNum();\n const descriptionBytes = resultReader.read(descriptionLength);\n const description = Utils.toUTF8(descriptionBytes);\n const action = {\n txid,\n satoshis,\n status,\n isOutgoing,\n description,\n version: 0,\n lockTime: 0\n };\n // Parse labels\n const labelsLength = resultReader.readVarIntNum();\n if (labelsLength >= 0) {\n action.labels = [];\n for (let j = 0; j < labelsLength; j++) {\n const labelLength = resultReader.readVarIntNum();\n const labelBytes = resultReader.read(labelLength);\n action.labels.push(Utils.toUTF8(labelBytes));\n }\n }\n // Parse version and lockTime\n action.version = resultReader.readVarIntNum();\n action.lockTime = resultReader.readVarIntNum();\n // Parse inputs\n const inputsLength = resultReader.readVarIntNum();\n if (inputsLength >= 0) {\n action.inputs = [];\n for (let k = 0; k < inputsLength; k++) {\n const sourceOutpoint = this.readOutpoint(resultReader);\n const sourceSatoshis = resultReader.readVarIntNum();\n // sourceLockingScript\n const sourceLockingScriptLength = resultReader.readVarIntNum();\n let sourceLockingScript;\n if (sourceLockingScriptLength >= 0) {\n const sourceLockingScriptBytes = resultReader.read(sourceLockingScriptLength);\n sourceLockingScript = Utils.toHex(sourceLockingScriptBytes);\n }\n // unlockingScript\n const unlockingScriptLength = resultReader.readVarIntNum();\n let unlockingScript;\n if (unlockingScriptLength >= 0) {\n const unlockingScriptBytes = resultReader.read(unlockingScriptLength);\n unlockingScript = Utils.toHex(unlockingScriptBytes);\n }\n // inputDescription\n const inputDescriptionLength = resultReader.readVarIntNum();\n const inputDescriptionBytes = resultReader.read(inputDescriptionLength);\n const inputDescription = Utils.toUTF8(inputDescriptionBytes);\n // sequenceNumber\n const sequenceNumber = resultReader.readVarIntNum();\n action.inputs.push({\n sourceOutpoint,\n sourceSatoshis,\n sourceLockingScript,\n unlockingScript,\n inputDescription,\n sequenceNumber\n });\n }\n }\n // Parse outputs\n const outputsLength = resultReader.readVarIntNum();\n if (outputsLength >= 0) {\n action.outputs = [];\n for (let l = 0; l < outputsLength; l++) {\n const outputIndex = resultReader.readVarIntNum();\n const satoshis = resultReader.readVarIntNum();\n // lockingScript\n const lockingScriptLength = resultReader.readVarIntNum();\n let lockingScript;\n if (lockingScriptLength >= 0) {\n const lockingScriptBytes = resultReader.read(lockingScriptLength);\n lockingScript = Utils.toHex(lockingScriptBytes);\n }\n const spendable = resultReader.readInt8() === 1;\n // outputDescription\n const outputDescriptionLength = resultReader.readVarIntNum();\n const outputDescriptionBytes = resultReader.read(outputDescriptionLength);\n const outputDescription = Utils.toUTF8(outputDescriptionBytes);\n // basket\n const basketLength = resultReader.readVarIntNum();\n let basket;\n if (basketLength >= 0) {\n const basketBytes = resultReader.read(basketLength);\n basket = Utils.toUTF8(basketBytes);\n }\n // tags\n const tagsLength = resultReader.readVarIntNum();\n const tags = [];\n if (tagsLength >= 0) {\n for (let m = 0; m < tagsLength; m++) {\n const tagLength = resultReader.readVarIntNum();\n const tagBytes = resultReader.read(tagLength);\n tags.push(Utils.toUTF8(tagBytes));\n }\n }\n // customInstructions\n const customInstructionsLength = resultReader.readVarIntNum();\n let customInstructions;\n if (customInstructionsLength >= 0) {\n const customInstructionsBytes = resultReader.read(customInstructionsLength);\n customInstructions = Utils.toUTF8(customInstructionsBytes);\n }\n action.outputs.push({\n outputIndex,\n satoshis,\n lockingScript,\n spendable,\n outputDescription,\n basket,\n tags,\n customInstructions\n });\n }\n }\n actions.push(action);\n }\n return {\n totalActions,\n actions\n };\n }\n async internalizeAction(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.writeVarIntNum(args.tx.length);\n paramWriter.write(args.tx);\n paramWriter.writeVarIntNum(args.outputs.length);\n for (const out of args.outputs) {\n paramWriter.writeVarIntNum(out.outputIndex);\n if (out.protocol === 'wallet payment') {\n if (out.paymentRemittance == null) {\n throw new Error('Payment remittance is required for wallet payment');\n }\n paramWriter.writeUInt8(1);\n paramWriter.write(Utils.toArray(out.paymentRemittance.senderIdentityKey, 'hex'));\n const derivationPrefixAsArray = Utils.toArray(out.paymentRemittance.derivationPrefix, 'base64');\n paramWriter.writeVarIntNum(derivationPrefixAsArray.length);\n paramWriter.write(derivationPrefixAsArray);\n const derivationSuffixAsArray = Utils.toArray(out.paymentRemittance.derivationSuffix, 'base64');\n paramWriter.writeVarIntNum(derivationSuffixAsArray.length);\n paramWriter.write(derivationSuffixAsArray);\n }\n else {\n paramWriter.writeUInt8(2);\n const basketAsArray = Utils.toArray(out.insertionRemittance?.basket, 'utf8');\n paramWriter.writeVarIntNum(basketAsArray.length);\n paramWriter.write(basketAsArray);\n if (typeof out.insertionRemittance?.customInstructions === 'string' && out.insertionRemittance.customInstructions !== '') {\n const customInstructionsAsArray = Utils.toArray(out.insertionRemittance.customInstructions, 'utf8');\n paramWriter.writeVarIntNum(customInstructionsAsArray.length);\n paramWriter.write(customInstructionsAsArray);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof out.insertionRemittance?.tags === 'object') {\n paramWriter.writeVarIntNum(out.insertionRemittance.tags.length);\n for (const tag of out.insertionRemittance.tags) {\n const tagAsArray = Utils.toArray(tag, 'utf8');\n paramWriter.writeVarIntNum(tagAsArray.length);\n paramWriter.write(tagAsArray);\n }\n }\n else {\n paramWriter.writeVarIntNum(0);\n }\n }\n }\n if (typeof args.labels === 'object') {\n paramWriter.writeVarIntNum(args.labels.length);\n for (const l of args.labels) {\n const labelAsArray = Utils.toArray(l, 'utf8');\n paramWriter.writeVarIntNum(labelAsArray.length);\n paramWriter.write(labelAsArray);\n }\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n const descriptionAsArray = Utils.toArray(args.description);\n paramWriter.writeVarIntNum(descriptionAsArray.length);\n paramWriter.write(descriptionAsArray);\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n await this.transmit('internalizeAction', originator, paramWriter.toArray());\n return { accepted: true };\n }\n async listOutputs(args, originator) {\n const paramWriter = new Utils.Writer();\n const basketAsArray = Utils.toArray(args.basket, 'utf8');\n paramWriter.writeVarIntNum(basketAsArray.length);\n paramWriter.write(basketAsArray);\n if (typeof args.tags === 'object') {\n paramWriter.writeVarIntNum(args.tags.length);\n for (const tag of args.tags) {\n const tagAsArray = Utils.toArray(tag, 'utf8');\n paramWriter.writeVarIntNum(tagAsArray.length);\n paramWriter.write(tagAsArray);\n }\n }\n else {\n paramWriter.writeVarIntNum(0);\n }\n if (args.tagQueryMode === 'all') {\n paramWriter.writeInt8(1);\n }\n else if (args.tagQueryMode === 'any') {\n paramWriter.writeInt8(2);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (args.include === 'locking scripts') {\n paramWriter.writeInt8(1);\n }\n else if (args.include === 'entire transactions') {\n paramWriter.writeInt8(2);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (typeof args.includeCustomInstructions === 'boolean') {\n paramWriter.writeInt8(args.includeCustomInstructions ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (typeof args.includeTags === 'boolean') {\n paramWriter.writeInt8(args.includeTags ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (typeof args.includeLabels === 'boolean') {\n paramWriter.writeInt8(args.includeLabels ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (typeof args.limit === 'number') {\n paramWriter.writeVarIntNum(args.limit);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof args.offset === 'number') {\n paramWriter.writeVarIntNum(args.offset);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n const result = await this.transmit('listOutputs', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const totalOutputs = resultReader.readVarIntNum();\n const beefLength = resultReader.readVarIntNum();\n let BEEF;\n if (beefLength >= 0) {\n BEEF = resultReader.read(beefLength);\n }\n const outputs = [];\n for (let i = 0; i < totalOutputs; i++) {\n const outpoint = this.readOutpoint(resultReader);\n const satoshis = resultReader.readVarIntNum();\n const output = {\n spendable: true,\n outpoint,\n satoshis\n };\n const scriptLength = resultReader.readVarIntNum();\n if (scriptLength >= 0) {\n output.lockingScript = Utils.toHex(resultReader.read(scriptLength));\n }\n const customInstructionsLength = resultReader.readVarIntNum();\n if (customInstructionsLength >= 0) {\n output.customInstructions = Utils.toUTF8(resultReader.read(customInstructionsLength));\n }\n const tagsLength = resultReader.readVarIntNum();\n if (tagsLength !== -1) {\n const tags = [];\n for (let i = 0; i < tagsLength; i++) {\n const tagLength = resultReader.readVarIntNum();\n tags.push(Utils.toUTF8(resultReader.read(tagLength)));\n }\n output.tags = tags;\n }\n const labelsLength = resultReader.readVarIntNum();\n if (labelsLength !== -1) {\n const labels = [];\n for (let i = 0; i < labelsLength; i++) {\n const labelLength = resultReader.readVarIntNum();\n labels.push(Utils.toUTF8(resultReader.read(labelLength)));\n }\n output.labels = labels;\n }\n outputs.push(output);\n }\n return {\n totalOutputs,\n BEEF,\n outputs\n };\n }\n async relinquishOutput(args, originator) {\n const paramWriter = new Utils.Writer();\n const basketAsArray = Utils.toArray(args.basket, 'utf8');\n paramWriter.writeVarIntNum(basketAsArray.length);\n paramWriter.write(basketAsArray);\n paramWriter.write(this.encodeOutpoint(args.output));\n await this.transmit('relinquishOutput', originator, paramWriter.toArray());\n return { relinquished: true };\n }\n encodeOutpoint(outpoint) {\n const writer = new Utils.Writer();\n const [txid, index] = outpoint.split('.');\n writer.write(Utils.toArray(txid, 'hex'));\n writer.writeVarIntNum(Number(index));\n return writer.toArray();\n }\n readOutpoint(reader) {\n const txid = Utils.toHex(reader.read(32));\n const index = reader.readVarIntNum();\n return `${txid}.${index}`;\n }\n async getPublicKey(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.writeUInt8(args.identityKey ? 1 : 0);\n if (!args.identityKey) {\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID ??= [SecurityLevels.Silent, 'default'], args.keyID ??= '', args.counterparty, args.privileged, args.privilegedReason));\n if (typeof args.forSelf === 'boolean') {\n paramWriter.writeInt8(args.forSelf ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n }\n else {\n paramWriter.write(this.encodePrivilegedParams(args.privileged, args.privilegedReason));\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n const result = await this.transmit('getPublicKey', originator, paramWriter.toArray());\n return {\n publicKey: Utils.toHex(result)\n };\n }\n async revealCounterpartyKeyLinkage(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodePrivilegedParams(args.privileged, args.privilegedReason));\n paramWriter.write(Utils.toArray(args.counterparty, 'hex'));\n paramWriter.write(Utils.toArray(args.verifier, 'hex'));\n const result = await this.transmit('revealCounterpartyKeyLinkage', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const prover = Utils.toHex(resultReader.read(33));\n const verifier = Utils.toHex(resultReader.read(33));\n const counterparty = Utils.toHex(resultReader.read(33));\n const revelationTimeLength = resultReader.readVarIntNum();\n const revelationTime = Utils.toUTF8(resultReader.read(revelationTimeLength));\n const encryptedLinkageLength = resultReader.readVarIntNum();\n const encryptedLinkage = resultReader.read(encryptedLinkageLength);\n const encryptedLinkageProofLength = resultReader.readVarIntNum();\n const encryptedLinkageProof = resultReader.read(encryptedLinkageProofLength);\n return {\n prover,\n verifier,\n counterparty,\n revelationTime,\n encryptedLinkage,\n encryptedLinkageProof\n };\n }\n async revealSpecificKeyLinkage(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n paramWriter.write(Utils.toArray(args.verifier, 'hex'));\n const result = await this.transmit('revealSpecificKeyLinkage', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const prover = Utils.toHex(resultReader.read(33));\n const verifier = Utils.toHex(resultReader.read(33));\n const counterparty = Utils.toHex(resultReader.read(33));\n const securityLevel = resultReader.readUInt8();\n const protocolLength = resultReader.readVarIntNum();\n const protocol = Utils.toUTF8(resultReader.read(protocolLength));\n const keyIDLength = resultReader.readVarIntNum();\n const keyID = Utils.toUTF8(resultReader.read(keyIDLength));\n const encryptedLinkageLength = resultReader.readVarIntNum();\n const encryptedLinkage = resultReader.read(encryptedLinkageLength);\n const encryptedLinkageProofLength = resultReader.readVarIntNum();\n const encryptedLinkageProof = resultReader.read(encryptedLinkageProofLength);\n const proofType = resultReader.readUInt8();\n return {\n prover,\n verifier,\n counterparty,\n protocolID: [securityLevel, protocol],\n keyID,\n encryptedLinkage,\n encryptedLinkageProof,\n proofType\n };\n }\n async encrypt(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n paramWriter.writeVarIntNum(args.plaintext.length);\n paramWriter.write(args.plaintext);\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n return {\n ciphertext: await this.transmit('encrypt', originator, paramWriter.toArray())\n };\n }\n async decrypt(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n paramWriter.writeVarIntNum(args.ciphertext.length);\n paramWriter.write(args.ciphertext);\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n return {\n plaintext: await this.transmit('decrypt', originator, paramWriter.toArray())\n };\n }\n async createHmac(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n paramWriter.writeVarIntNum(args.data.length);\n paramWriter.write(args.data);\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n return {\n hmac: await this.transmit('createHmac', originator, paramWriter.toArray())\n };\n }\n async verifyHmac(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n paramWriter.write(args.hmac);\n paramWriter.writeVarIntNum(args.data.length);\n paramWriter.write(args.data);\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n await this.transmit('verifyHmac', originator, paramWriter.toArray());\n return { valid: true };\n }\n async createSignature(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n if (typeof args.data === 'object') {\n paramWriter.writeUInt8(1);\n paramWriter.writeVarIntNum(args.data.length);\n paramWriter.write(args.data);\n }\n else {\n paramWriter.writeUInt8(2);\n paramWriter.write(args.hashToDirectlySign ??= []);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n return {\n signature: await this.transmit('createSignature', originator, paramWriter.toArray())\n };\n }\n async verifySignature(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(this.encodeKeyRelatedParams(args.protocolID, args.keyID, args.counterparty, args.privileged, args.privilegedReason));\n if (typeof args.forSelf === 'boolean') {\n paramWriter.writeInt8(args.forSelf ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n paramWriter.writeVarIntNum(args.signature.length);\n paramWriter.write(args.signature);\n if (typeof args.data === 'object') {\n paramWriter.writeUInt8(1);\n paramWriter.writeVarIntNum(args.data.length);\n paramWriter.write(args.data);\n }\n else {\n paramWriter.writeUInt8(2);\n paramWriter.write(args.hashToDirectlyVerify ?? []);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n await this.transmit('verifySignature', originator, paramWriter.toArray());\n return { valid: true };\n }\n encodeKeyRelatedParams(protocolID, keyID, counterparty, privileged, privilegedReason) {\n const paramWriter = new Utils.Writer();\n paramWriter.writeUInt8(protocolID[0]);\n const protocolAsArray = Utils.toArray(protocolID[1], 'utf8');\n paramWriter.writeVarIntNum(protocolAsArray.length);\n paramWriter.write(protocolAsArray);\n const keyIDAsArray = Utils.toArray(keyID, 'utf8');\n paramWriter.writeVarIntNum(keyIDAsArray.length);\n paramWriter.write(keyIDAsArray);\n if (typeof counterparty !== 'string') {\n paramWriter.writeUInt8(0);\n }\n else if (counterparty === 'self') {\n paramWriter.writeUInt8(11);\n }\n else if (counterparty === 'anyone') {\n paramWriter.writeUInt8(12);\n }\n else {\n paramWriter.write(Utils.toArray(counterparty, 'hex'));\n }\n paramWriter.write(this.encodePrivilegedParams(privileged, privilegedReason));\n return paramWriter.toArray();\n }\n async acquireCertificate(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(Utils.toArray(args.type, 'base64'));\n paramWriter.write(Utils.toArray(args.certifier, 'hex'));\n const fieldEntries = Object.entries(args.fields);\n paramWriter.writeVarIntNum(fieldEntries.length);\n for (const [key, value] of fieldEntries) {\n const keyAsArray = Utils.toArray(key, 'utf8');\n const valueAsArray = Utils.toArray(value, 'utf8');\n paramWriter.writeVarIntNum(keyAsArray.length);\n paramWriter.write(keyAsArray);\n paramWriter.writeVarIntNum(valueAsArray.length);\n paramWriter.write(valueAsArray);\n }\n paramWriter.write(this.encodePrivilegedParams(args.privileged, args.privilegedReason));\n paramWriter.writeUInt8(args.acquisitionProtocol === 'direct' ? 1 : 2);\n if (args.acquisitionProtocol === 'direct') {\n paramWriter.write(Utils.toArray(args.serialNumber, 'base64'));\n paramWriter.write(this.encodeOutpoint(args.revocationOutpoint ?? ''));\n const signatureAsArray = Utils.toArray(args.signature, 'hex');\n paramWriter.writeVarIntNum(signatureAsArray.length);\n paramWriter.write(signatureAsArray);\n const keyringRevealerAsArray = args.keyringRevealer !== 'certifier'\n ? Utils.toArray(args.keyringRevealer, 'hex')\n : [11];\n paramWriter.write(keyringRevealerAsArray);\n const keyringKeys = Object.keys(args.keyringForSubject ?? {});\n paramWriter.writeVarIntNum(keyringKeys.length);\n for (let i = 0; i < keyringKeys.length; i++) {\n const keyringKeysAsArray = Utils.toArray(keyringKeys[i], 'utf8');\n paramWriter.writeVarIntNum(keyringKeysAsArray.length);\n paramWriter.write(keyringKeysAsArray);\n const keyringForSubjectAsArray = Utils.toArray(args.keyringForSubject?.[keyringKeys[i]], 'base64');\n paramWriter.writeVarIntNum(keyringForSubjectAsArray.length);\n paramWriter.write(keyringForSubjectAsArray);\n }\n }\n else {\n const certifierUrlAsArray = Utils.toArray(args.certifierUrl, 'utf8');\n paramWriter.writeVarIntNum(certifierUrlAsArray.length);\n paramWriter.write(certifierUrlAsArray);\n }\n const result = await this.transmit('acquireCertificate', originator, paramWriter.toArray());\n const cert = Certificate.fromBinary(result);\n return {\n ...cert,\n signature: cert.signature\n };\n }\n encodePrivilegedParams(privileged, privilegedReason) {\n const paramWriter = new Utils.Writer();\n if (typeof privileged === 'boolean') {\n paramWriter.writeInt8(privileged ? 1 : 0);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n if (typeof privilegedReason === 'string') {\n const privilegedReasonAsArray = Utils.toArray(privilegedReason, 'utf8');\n paramWriter.writeInt8(privilegedReasonAsArray.length);\n paramWriter.write(privilegedReasonAsArray);\n }\n else {\n paramWriter.writeInt8(-1);\n }\n return paramWriter.toArray();\n }\n async listCertificates(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.writeVarIntNum(args.certifiers.length);\n for (let i = 0; i < args.certifiers.length; i++) {\n paramWriter.write(Utils.toArray(args.certifiers[i], 'hex'));\n }\n paramWriter.writeVarIntNum(args.types.length);\n for (let i = 0; i < args.types.length; i++) {\n paramWriter.write(Utils.toArray(args.types[i], 'base64'));\n }\n if (typeof args.limit === 'number') {\n paramWriter.writeVarIntNum(args.limit);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof args.offset === 'number') {\n paramWriter.writeVarIntNum(args.offset);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n paramWriter.write(this.encodePrivilegedParams(args.privileged, args.privilegedReason));\n const result = await this.transmit('listCertificates', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const totalCertificates = resultReader.readVarIntNum();\n const certificates = [];\n for (let i = 0; i < totalCertificates; i++) {\n const certificateLength = resultReader.readVarIntNum();\n const certificateBin = resultReader.read(certificateLength);\n const cert = Certificate.fromBinary(certificateBin);\n const keyringForVerifier = {};\n if (resultReader.readInt8() === 1) {\n const numFields = resultReader.readVarIntNum();\n for (let i = 0; i < numFields; i++) {\n const fieldKeyLength = resultReader.readVarIntNum();\n const fieldKey = Utils.toUTF8(resultReader.read(fieldKeyLength));\n const fieldValueLength = resultReader.readVarIntNum();\n keyringForVerifier[fieldKey] = Utils.toBase64(resultReader.read(fieldValueLength));\n }\n }\n const verifierLength = resultReader.readVarIntNum();\n let verifier = undefined;\n if (verifierLength > 0) {\n verifier = Utils.toUTF8(resultReader.read(verifierLength));\n }\n certificates.push({\n ...cert,\n signature: cert.signature,\n keyring: keyringForVerifier,\n verifier,\n });\n }\n return {\n totalCertificates,\n certificates\n };\n }\n async proveCertificate(args, originator) {\n const paramWriter = new Utils.Writer();\n const typeAsArray = Utils.toArray(args.certificate.type, 'base64');\n paramWriter.write(typeAsArray);\n const subjectAsArray = Utils.toArray(args.certificate.subject, 'hex');\n paramWriter.write(subjectAsArray);\n const serialNumberAsArray = Utils.toArray(args.certificate.serialNumber, 'base64');\n paramWriter.write(serialNumberAsArray);\n const certifierAsArray = Utils.toArray(args.certificate.certifier, 'hex');\n paramWriter.write(certifierAsArray);\n const revocationOutpointAsArray = this.encodeOutpoint(args.certificate.revocationOutpoint ?? '');\n paramWriter.write(revocationOutpointAsArray);\n const signatureAsArray = Utils.toArray(args.certificate.signature, 'hex');\n paramWriter.writeVarIntNum(signatureAsArray.length);\n paramWriter.write(signatureAsArray);\n const fieldEntries = Object.entries(args.certificate.fields ?? {});\n paramWriter.writeVarIntNum(fieldEntries.length);\n for (const [key, value] of fieldEntries) {\n const keyAsArray = Utils.toArray(key, 'utf8');\n const valueAsArray = Utils.toArray(value, 'utf8');\n paramWriter.writeVarIntNum(keyAsArray.length);\n paramWriter.write(keyAsArray);\n paramWriter.writeVarIntNum(valueAsArray.length);\n paramWriter.write(valueAsArray);\n }\n paramWriter.writeVarIntNum(args.fieldsToReveal.length);\n for (const field of args.fieldsToReveal) {\n const fieldAsArray = Utils.toArray(field, 'utf8');\n paramWriter.writeVarIntNum(fieldAsArray.length);\n paramWriter.write(fieldAsArray);\n }\n paramWriter.write(Utils.toArray(args.verifier, 'hex'));\n paramWriter.write(this.encodePrivilegedParams(args.privileged, args.privilegedReason));\n const result = await this.transmit('proveCertificate', originator, paramWriter.toArray());\n const resultReader = new Utils.Reader(result);\n const numFields = resultReader.readVarIntNum();\n const keyringForVerifier = {};\n for (let i = 0; i < numFields; i++) {\n const fieldKeyLength = resultReader.readVarIntNum();\n const fieldKey = Utils.toUTF8(resultReader.read(fieldKeyLength));\n const fieldValueLength = resultReader.readVarIntNum();\n keyringForVerifier[fieldKey] = Utils.toBase64(resultReader.read(fieldValueLength));\n }\n return {\n keyringForVerifier\n };\n }\n async relinquishCertificate(args, originator) {\n const paramWriter = new Utils.Writer();\n const typeAsArray = Utils.toArray(args.type, 'base64');\n paramWriter.write(typeAsArray);\n const serialNumberAsArray = Utils.toArray(args.serialNumber, 'base64');\n paramWriter.write(serialNumberAsArray);\n const certifierAsArray = Utils.toArray(args.certifier, 'hex');\n paramWriter.write(certifierAsArray);\n await this.transmit('relinquishCertificate', originator, paramWriter.toArray());\n return { relinquished: true };\n }\n parseDiscoveryResult(result) {\n const resultReader = new Utils.Reader(result);\n const totalCertificates = resultReader.readVarIntNum();\n const certificates = [];\n for (let i = 0; i < totalCertificates; i++) {\n const certBinLen = resultReader.readVarIntNum();\n const certBin = resultReader.read(certBinLen);\n const cert = Certificate.fromBinary(certBin);\n const nameLength = resultReader.readVarIntNum();\n const name = Utils.toUTF8(resultReader.read(nameLength));\n const iconUrlLength = resultReader.readVarIntNum();\n const iconUrl = Utils.toUTF8(resultReader.read(iconUrlLength));\n const descriptionLength = resultReader.readVarIntNum();\n const description = Utils.toUTF8(resultReader.read(descriptionLength));\n const trust = resultReader.readUInt8();\n const publiclyRevealedKeyring = {};\n const numPublicKeyringEntries = resultReader.readVarIntNum();\n for (let j = 0; j < numPublicKeyringEntries; j++) {\n const fieldKeyLen = resultReader.readVarIntNum();\n const fieldKey = Utils.toUTF8(resultReader.read(fieldKeyLen));\n const fieldValueLen = resultReader.readVarIntNum();\n publiclyRevealedKeyring[fieldKey] = resultReader.read(fieldValueLen);\n }\n const decryptedFields = {};\n const numDecryptedFields = resultReader.readVarIntNum();\n for (let k = 0; k < numDecryptedFields; k++) {\n const fieldKeyLen = resultReader.readVarIntNum();\n const fieldKey = Utils.toUTF8(resultReader.read(fieldKeyLen));\n const fieldValueLen = resultReader.readVarIntNum();\n decryptedFields[fieldKey] = Utils.toUTF8(resultReader.read(fieldValueLen));\n }\n certificates.push({\n ...cert,\n signature: cert.signature,\n certifierInfo: { iconUrl, name, description, trust },\n publiclyRevealedKeyring,\n decryptedFields\n });\n }\n return {\n totalCertificates,\n certificates\n };\n }\n async discoverByIdentityKey(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.write(Utils.toArray(args.identityKey, 'hex'));\n if (typeof args.limit === 'number') {\n paramWriter.writeVarIntNum(args.limit);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof args.offset === 'number') {\n paramWriter.writeVarIntNum(args.offset);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n const result = await this.transmit('discoverByIdentityKey', originator, paramWriter.toArray());\n return this.parseDiscoveryResult(result);\n }\n async discoverByAttributes(args, originator) {\n const paramWriter = new Utils.Writer();\n const attributeKeys = Object.keys(args.attributes);\n paramWriter.writeVarIntNum(attributeKeys.length);\n for (let i = 0; i < attributeKeys.length; i++) {\n paramWriter.writeVarIntNum(attributeKeys[i].length);\n paramWriter.write(Utils.toArray(attributeKeys[i], 'utf8'));\n paramWriter.writeVarIntNum(args.attributes[attributeKeys[i]].length);\n paramWriter.write(Utils.toArray(args.attributes[attributeKeys[i]], 'utf8'));\n }\n if (typeof args.limit === 'number') {\n paramWriter.writeVarIntNum(args.limit);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n if (typeof args.offset === 'number') {\n paramWriter.writeVarIntNum(args.offset);\n }\n else {\n paramWriter.writeVarIntNum(-1);\n }\n // Serialize seekPermission\n paramWriter.writeInt8(typeof args.seekPermission === 'boolean'\n ? args.seekPermission\n ? 1\n : 0\n : -1);\n const result = await this.transmit('discoverByAttributes', originator, paramWriter.toArray());\n return this.parseDiscoveryResult(result);\n }\n async isAuthenticated(args, originator) {\n const result = await this.transmit('isAuthenticated', originator);\n // @ts-expect-error\n return { authenticated: result[0] === 1 };\n }\n async waitForAuthentication(args, originator) {\n await this.transmit('waitForAuthentication', originator);\n return { authenticated: true };\n }\n async getHeight(args, originator) {\n const result = await this.transmit('getHeight', originator);\n const resultReader = new Utils.Reader(result);\n return {\n height: resultReader.readVarIntNum()\n };\n }\n async getHeaderForHeight(args, originator) {\n const paramWriter = new Utils.Writer();\n paramWriter.writeVarIntNum(args.height);\n const header = await this.transmit('getHeaderForHeight', originator, paramWriter.toArray());\n return {\n header: Utils.toHex(header)\n };\n }\n async getNetwork(args, originator) {\n const net = await this.transmit('getNetwork', originator);\n return {\n network: net[0] === 0 ? 'mainnet' : 'testnet'\n };\n }\n async getVersion(args, originator) {\n const version = await this.transmit('getVersion', originator);\n return {\n version: Utils.toUTF8(version)\n };\n }\n}\n//# sourceMappingURL=WalletWireTransceiver.js.map","import WalletWireCalls from './WalletWireCalls.js';\nimport * as Utils from '../../primitives/utils.js';\nexport default class HTTPWalletWire {\n baseUrl;\n httpClient;\n originator;\n constructor(originator, baseUrl = 'http://localhost:3301', httpClient = fetch) {\n this.baseUrl = baseUrl;\n this.httpClient = httpClient;\n this.originator = originator;\n }\n async transmitToWallet(message) {\n const messageReader = new Utils.Reader(message);\n // Read call code\n const callCode = messageReader.readUInt8();\n // Map call code to call name\n const callName = WalletWireCalls[callCode]; // calls is enum\n if (callName === undefined || callName === '') {\n // Invalid call code\n throw new Error(`Invalid call code: ${callCode}`);\n }\n // Read originator length\n const originatorLength = messageReader.readUInt8();\n let originator;\n if (originatorLength > 0) {\n const originatorBytes = messageReader.read(originatorLength);\n originator = Utils.toUTF8(originatorBytes);\n }\n const payload = messageReader.read();\n const response = await fetch(`${this.baseUrl}/${callName}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream',\n Origin: originator ?? '' // ✅ Explicitly handle null/undefined cases\n },\n body: new Uint8Array(payload)\n });\n const responseBuffer = await response.arrayBuffer();\n return Array.from(new Uint8Array(responseBuffer));\n }\n}\n//# sourceMappingURL=HTTPWalletWire.js.map","/**\n * When a `createAction` or `signAction` is completed in undelayed mode (`acceptDelayedBroadcast`: false),\n * any unsucccessful result will return the results by way of this exception to ensure attention is\n * paid to processing errors.\n */\nexport class WERR_REVIEW_ACTIONS extends Error {\n reviewActionResults;\n sendWithResults;\n txid;\n tx;\n noSendChange;\n code;\n isError = true;\n /**\n * All parameters correspond to their comparable `createAction` or `signSction` results\n * with the exception of `reviewActionResults`;\n * which contains more details, particularly for double spend results.\n */\n constructor(reviewActionResults, sendWithResults, txid, tx, noSendChange) {\n super('Undelayed createAction or signAction results require review.');\n this.reviewActionResults = reviewActionResults;\n this.sendWithResults = sendWithResults;\n this.txid = txid;\n this.tx = tx;\n this.noSendChange = noSendChange;\n this.code = 5;\n this.name = this.constructor.name;\n }\n}\nexport default WERR_REVIEW_ACTIONS;\n//# sourceMappingURL=WERR_REVIEW_ACTIONS.js.map","/**\n * The ${parameter} parameter is invalid.\n *\n * This is an example of an error object with a custom property `parameter` and templated `message`.\n */\nexport class WERR_INVALID_PARAMETER extends Error {\n parameter;\n code;\n isError = true;\n constructor(parameter, mustBe) {\n super(`The ${parameter} parameter must be ${mustBe ?? 'valid.'}`);\n this.parameter = parameter;\n this.code = 6;\n this.name = this.constructor.name;\n }\n}\nexport default WERR_INVALID_PARAMETER;\n//# sourceMappingURL=WERR_INVALID_PARAMETER.js.map","/**\n * Insufficient funds in the available inputs to cover the cost of the required outputs\n * and the transaction fee (${moreSatoshisNeeded} more satoshis are needed,\n * for a total of ${totalSatoshisNeeded}), plus whatever would be required in order\n * to pay the fee to unlock and spend the outputs used to provide the additional satoshis.\n */\nexport class WERR_INSUFFICIENT_FUNDS extends Error {\n totalSatoshisNeeded;\n moreSatoshisNeeded;\n code;\n isError = true;\n /**\n * @param totalSatoshisNeeded Total satoshis required to fund transactions after net of required inputs and outputs.\n * @param moreSatoshisNeeded Shortfall on total satoshis required to fund transactions after net of required inputs and outputs.\n */\n constructor(totalSatoshisNeeded, moreSatoshisNeeded) {\n super(`Insufficient funds in the available inputs to cover the cost of the required outputs and the transaction fee (${moreSatoshisNeeded} more satoshis are needed, for a total of ${totalSatoshisNeeded}), plus whatever would be required in order to pay the fee to unlock and spend the outputs used to provide the additional satoshis.`);\n this.totalSatoshisNeeded = totalSatoshisNeeded;\n this.moreSatoshisNeeded = moreSatoshisNeeded;\n this.code = 7;\n this.name = this.constructor.name;\n }\n}\nexport default WERR_INSUFFICIENT_FUNDS;\n//# sourceMappingURL=WERR_INSUFFICIENT_FUNDS.js.map","import { WERR_REVIEW_ACTIONS } from '../WERR_REVIEW_ACTIONS.js';\nimport { WERR_INVALID_PARAMETER } from '../WERR_INVALID_PARAMETER.js';\nimport { toOriginHeader } from './utils/toOriginHeader.js';\nimport WERR_INSUFFICIENT_FUNDS from '../WERR_INSUFFICIENT_FUNDS.js';\nexport default class HTTPWalletJSON {\n baseUrl;\n httpClient;\n originator;\n api; // Fixed `any` types\n constructor(originator, baseUrl = 'http://localhost:3321', httpClient = fetch) {\n this.baseUrl = baseUrl;\n this.originator = originator;\n this.httpClient = httpClient;\n // Detect if we're in a browser environment\n const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window?.origin !== 'file://';\n this.api = async (call, args) => {\n // In browser environments, let the browser handle Origin header automatically\n // In Node.js environments, we need to set it manually if originator is provided\n const origin = !isBrowser && this.originator\n ? toOriginHeader(this.originator, 'http')\n : undefined;\n if (!isBrowser && origin === undefined) {\n console.error('Originator is required in Node.js environments');\n }\n const res = await (await httpClient(`${this.baseUrl}/${call}`, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n ...(origin ? { Origin: origin } : {}),\n ...(origin ? { Originator: origin } : {}),\n },\n body: JSON.stringify(args)\n }));\n const data = await res.json();\n // Check the HTTP status on the original response\n if (!res.ok) {\n if (res.status === 400 && data.isError) {\n let err;\n switch (data.code) {\n case 5:\n err = new WERR_REVIEW_ACTIONS(data.reviewActionResults, data.sendWithResults, data.txid, data.tx, data.noSendChange);\n break;\n case 6:\n err = new WERR_INVALID_PARAMETER(data.parameter);\n err.message = data.message;\n break;\n case 7:\n err = new WERR_INSUFFICIENT_FUNDS(data.totalSatoshisNeeded, data.moreSatoshisNeeded);\n break;\n default: break;\n }\n if (err)\n throw err;\n }\n const err = {\n call,\n args,\n message: data.message ?? `HTTP Client error ${res.status}`\n };\n throw new Error(JSON.stringify(err));\n }\n return data;\n };\n }\n async createAction(args) {\n return await this.api('createAction', args);\n }\n async signAction(args) {\n return await this.api('signAction', args);\n }\n async abortAction(args) {\n return await this.api('abortAction', args);\n }\n async listActions(args) {\n return await this.api('listActions', args);\n }\n async internalizeAction(args) {\n return await this.api('internalizeAction', args);\n }\n async listOutputs(args) {\n return await this.api('listOutputs', args);\n }\n async relinquishOutput(args) {\n return await this.api('relinquishOutput', args);\n }\n async getPublicKey(args) {\n return await this.api('getPublicKey', args);\n }\n async revealCounterpartyKeyLinkage(args) {\n return await this.api('revealCounterpartyKeyLinkage', args);\n }\n async revealSpecificKeyLinkage(args) {\n return await this.api('revealSpecificKeyLinkage', args);\n }\n async encrypt(args) {\n return await this.api('encrypt', args);\n }\n async decrypt(args) {\n return await this.api('decrypt', args);\n }\n async createHmac(args) {\n return await this.api('createHmac', args);\n }\n async verifyHmac(args) {\n return await this.api('verifyHmac', args);\n }\n async createSignature(args) {\n return await this.api('createSignature', args);\n }\n async verifySignature(args) {\n return await this.api('verifySignature', args);\n }\n async acquireCertificate(args) {\n return await this.api('acquireCertificate', args);\n }\n async listCertificates(args) {\n return await this.api('listCertificates', args);\n }\n async proveCertificate(args) {\n return await this.api('proveCertificate', args);\n }\n async relinquishCertificate(args) {\n return await this.api('relinquishCertificate', args);\n }\n async discoverByIdentityKey(args) {\n return await this.api('discoverByIdentityKey', args);\n }\n async discoverByAttributes(args) {\n return await this.api('discoverByAttributes', args);\n }\n async isAuthenticated(args) {\n return await this.api('isAuthenticated', args);\n }\n async waitForAuthentication(args) {\n return await this.api('waitForAuthentication', args);\n }\n async getHeight(args) {\n return await this.api('getHeight', args);\n }\n async getHeaderForHeight(args) {\n return await this.api('getHeaderForHeight', args);\n }\n async getNetwork(args) {\n return await this.api('getNetwork', args);\n }\n async getVersion(args) {\n return await this.api('getVersion', args);\n }\n}\n//# sourceMappingURL=HTTPWalletJSON.js.map","export function toOriginHeader(originator, fallbackScheme = 'http') {\n // If the caller already gave us a scheme, assume it’s fine\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(originator)) {\n try {\n return new URL(originator).origin; // trims any path/query\n }\n catch { /* fall through to fix-up */ }\n }\n // Otherwise, prepend the fallback scheme and validate\n try {\n return new URL(`${fallbackScheme}://${originator}`).origin;\n }\n catch {\n throw new Error(`Invalid originator value: ${originator}`);\n }\n}\n//# sourceMappingURL=toOriginHeader.js.map","import Random from '../../primitives/Random.js';\nimport * as Utils from '../../primitives/utils.js';\nimport { WalletError } from '../WalletError.js';\n/**\n * Facilitates wallet operations over cross-document messaging.\n */\nexport default class ReactNativeWebView {\n domain;\n constructor(domain = '*') {\n if (typeof window !== 'object') {\n throw new Error('The XDM substrate requires a global window object.');\n }\n if (!window.hasOwnProperty(\"ReactNativeWebView\")) {\n throw new Error('The window object does not have a ReactNativeWebView property.');\n }\n if (typeof window.ReactNativeWebView.postMessage !== 'function') {\n throw new Error('The window.ReactNativeWebView property does not seem to support postMessage calls.');\n }\n this.domain = domain;\n }\n async invoke(call, args) {\n return await new Promise((resolve, reject) => {\n const id = Utils.toBase64(Random(12));\n const listener = (e) => {\n const data = JSON.parse(e.data);\n if (data.type !== 'CWI' ||\n data.id !== id ||\n data.isInvocation === true) {\n return;\n }\n if (typeof window.removeEventListener === 'function') {\n window.removeEventListener('message', listener);\n }\n if (data.status === 'error') {\n const err = new WalletError(data.description, data.code);\n reject(err);\n }\n else {\n resolve(data.result);\n }\n };\n window.addEventListener('message', listener);\n window.ReactNativeWebView.postMessage(JSON.stringify({\n type: 'CWI',\n isInvocation: true,\n id,\n call,\n args\n }));\n });\n }\n async createAction(args) {\n return await this.invoke('createAction', args);\n }\n async signAction(args) {\n return await this.invoke('signAction', args);\n }\n async abortAction(args) {\n return await this.invoke('abortAction', args);\n }\n async listActions(args) {\n return await this.invoke('listActions', args);\n }\n async internalizeAction(args) {\n return await this.invoke('internalizeAction', args);\n }\n async listOutputs(args) {\n return await this.invoke('listOutputs', args);\n }\n async relinquishOutput(args) {\n return await this.invoke('relinquishOutput', args);\n }\n async getPublicKey(args) {\n return await this.invoke('getPublicKey', args);\n }\n async revealCounterpartyKeyLinkage(args) {\n return await this.invoke('revealCounterpartyKeyLinkage', args);\n }\n async revealSpecificKeyLinkage(args) {\n return await this.invoke('revealSpecificKeyLinkage', args);\n }\n async encrypt(args) {\n return await this.invoke('encrypt', args);\n }\n async decrypt(args) {\n return await this.invoke('decrypt', args);\n }\n async createHmac(args) {\n return await this.invoke('createHmac', args);\n }\n async verifyHmac(args) {\n return await this.invoke('verifyHmac', args);\n }\n async createSignature(args) {\n return await this.invoke('createSignature', args);\n }\n async verifySignature(args) {\n return await this.invoke('verifySignature', args);\n }\n async acquireCertificate(args) {\n return await this.invoke('acquireCertificate', args);\n }\n async listCertificates(args) {\n return await this.invoke('listCertificates', args);\n }\n async proveCertificate(args) {\n return await this.invoke('proveCertificate', args);\n }\n async relinquishCertificate(args) {\n return await this.invoke('relinquishCertificate', args);\n }\n async discoverByIdentityKey(args) {\n return await this.invoke('discoverByIdentityKey', args);\n }\n async discoverByAttributes(args) {\n return await this.invoke('discoverByAttributes', args);\n }\n async isAuthenticated(args) {\n return await this.invoke('isAuthenticated', args);\n }\n async waitForAuthentication(args) {\n return await this.invoke('waitForAuthentication', args);\n }\n async getHeight(args) {\n return await this.invoke('getHeight', args);\n }\n async getHeaderForHeight(args) {\n return await this.invoke('getHeaderForHeight', args);\n }\n async getNetwork(args) {\n return await this.invoke('getNetwork', args);\n }\n async getVersion(args) {\n return await this.invoke('getVersion', args);\n }\n}\n//# sourceMappingURL=ReactNativeWebView.js.map","import * as Utils from '../primitives/utils.js';\nimport WERR_INVALID_PARAMETER from './WERR_INVALID_PARAMETER.js';\nimport Beef from '../transaction/Beef.js';\nexport function parseWalletOutpoint(outpoint) {\n const [txid, vout] = outpoint.split('.');\n return { txid, vout: Number(vout) };\n}\nfunction defaultTrue(v) {\n return v ?? true;\n}\nfunction defaultFalse(v) {\n return v ?? false;\n}\nfunction defaultZero(v) {\n return v ?? 0;\n}\nfunction default0xffffffff(v) {\n return v ?? 0xffffffff;\n}\nfunction defaultOne(v) {\n return v ?? 1;\n}\nfunction defaultEmpty(v) {\n return v ?? [];\n}\nfunction validateOptionalStringLength(s, name, min, max) {\n if (s === undefined)\n return undefined;\n return validateStringLength(s, name, min, max);\n}\n/**\n * Validate a satoshi amount.\n *\n * @param v - value to validate (integer number of satoshis)\n * @param name - parameter name used in error messages\n * @param min - optional minimum allowed satoshi value\n * @returns validated satoshi number\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateSatoshis(v, name, min) {\n if (v === undefined || !Number.isInteger(v) || v < 0 || v > 21e14) {\n throw new WERR_INVALID_PARAMETER(name, 'a valid number of satoshis');\n }\n if (min !== undefined && v < min)\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} satoshis.`);\n return v;\n}\n/**\n * Validate an optional integer. Returns undefined or the validated integer.\n *\n * @param v - value to validate (may be undefined)\n * @param name - parameter name used in error messages\n * @param min - optional minimum value\n * @param max - optional maximum value\n * @returns validated integer or undefined\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateOptionalInteger(v, name, min, max) {\n if (v === undefined)\n return undefined;\n return validateInteger(v, name, undefined, min, max);\n}\n/**\n * Validate an integer, applying an optional default.\n *\n * @param v - value to validate (may be undefined)\n * @param name - parameter name used in error messages\n * @param defaultValue - value to return when v is undefined\n * @param min - optional minimum allowed value\n * @param max - optional maximum allowed value\n * @returns validated integer\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateInteger(v, name, defaultValue, min, max) {\n if (v === undefined) {\n if (defaultValue !== undefined)\n return defaultValue;\n throw new WERR_INVALID_PARAMETER(name, 'a valid integer');\n }\n if (!Number.isInteger(v))\n throw new WERR_INVALID_PARAMETER(name, 'an integer');\n v = Number(v);\n if (min !== undefined && v < min)\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} length.`);\n if (max !== undefined && v > max)\n throw new WERR_INVALID_PARAMETER(name, `no more than ${max} length.`);\n return v;\n}\n/**\n * Validate a non-negative integer (zero allowed).\n *\n * @param v - value to validate\n * @param name - parameter name used in error messages\n * @returns validated integer\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validatePositiveIntegerOrZero(v, name) {\n return validateInteger(v, name, 0, 0);\n}\n/**\n * Validate string length in bytes for UTF-8 encoded string.\n *\n * @param s - string to validate\n * @param name - parameter name used in error messages\n * @param min - optional minimum byte length\n * @param max - optional maximum byte length\n * @returns the original string when valid\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateStringLength(s, name, min, max) {\n const bytes = Utils.toArray(s, 'utf8').length;\n if (min !== undefined && bytes < min)\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} length.`);\n if (max !== undefined && bytes > max)\n throw new WERR_INVALID_PARAMETER(name, `no more than ${max} length.`);\n return s;\n}\n/**\n * Validate an optional basket string (1..300 bytes).\n *\n * @param s - basket string or undefined\n * @returns validated basket string or undefined\n */\nfunction validateOptionalBasket(s) {\n if (s === undefined)\n return undefined;\n return validateBasket(s);\n}\n/**\n * Validate basket identifier (1..300 bytes).\n *\n * @param s - basket string\n * @returns validated basket string\n */\nfunction validateBasket(s) {\n return validateIdentifier(s, 'basket', 1, 300);\n}\n/**\n * Validate label identifier (1..300 bytes).\n *\n * @param s - label string\n * @returns validated label string\n */\nfunction validateLabel(s) {\n return validateIdentifier(s, 'label', 1, 300);\n}\n/**\n * Validate tag identifier (1..300 bytes).\n *\n * @param s - tag string\n * @returns validated tag string\n */\nfunction validateTag(s) {\n return validateIdentifier(s, 'tag', 1, 300);\n}\n/**\n * Normalize and validate an identifier (trim, lowercase, byte length).\n *\n * @param s - input string\n * @param name - name used in errors\n * @param min - optional minimum byte length\n * @param max - optional maximum byte length\n * @returns normalized identifier\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nfunction validateIdentifier(s, name, min, max) {\n s = s.trim().toLowerCase();\n const bytes = Utils.toArray(s, 'utf8').length;\n if (min !== undefined && bytes < min)\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} length.`);\n if (max !== undefined && bytes > max)\n throw new WERR_INVALID_PARAMETER(name, `no more than ${max} length.`);\n return s;\n}\n/**\n * Validate an optional Base64 encoded string.\n *\n * @param s - base64 string or undefined\n * @param name - parameter name used in error messages\n * @param min - optional minimum decoded byte length\n * @param max - optional maximum decoded byte length\n * @returns validated base64 string or undefined\n */\nfunction validateOptionalBase64String(s, name, min, max) {\n if (s === undefined)\n return undefined;\n return validateBase64String(s, name, min, max);\n}\n/**\n * Validate a Base64 string (structure and decoded size).\n *\n * @param s - base64 string\n * @param name - parameter name used in error messages\n * @param min - optional minimum decoded byte length\n * @param max - optional maximum decoded byte length\n * @returns validated base64 string\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateBase64String(s, name, min, max) {\n s = s.trim();\n if (s.length === 0) {\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n let paddingCount = 0;\n for (let i = 0; i < s.length; i++) {\n const char = s.charCodeAt(i);\n if (char >= 65 && char <= 90)\n continue; // A-Z\n if (char >= 97 && char <= 122)\n continue; // a-z\n if (char >= 48 && char <= 57)\n continue; // 0-9\n if (char === 43)\n continue; // +\n if (char === 47)\n continue; // /\n if (char === 61) { // =\n if (i < s.length - 2) {\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n paddingCount++;\n continue;\n }\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n // Padding rules\n if (paddingCount > 2) {\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n if (paddingCount > 0 && s.length % 4 !== 0) {\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n // Length must be multiple of 4 if no padding, or valid with padding\n const mod = s.length % 4;\n if (mod !== 0 && mod !== (4 - paddingCount)) {\n throw new WERR_INVALID_PARAMETER(name, 'valid base64 string');\n }\n // Calculate decoded byte length: (valid chars * 6) / 8\n const encodedLength = s.length - paddingCount;\n const bytes = Math.floor(encodedLength * 3 / 4);\n if (min !== undefined && bytes < min) {\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} bytes`);\n }\n if (max !== undefined && bytes > max) {\n throw new WERR_INVALID_PARAMETER(name, `no more than ${max} bytes`);\n }\n return s;\n}\nfunction validateOptionalHexString(s, name, min, max) {\n if (s === undefined)\n return undefined;\n return validateHexString(s, name, min, max);\n}\n/**\n * Validate a hex string (even length, hex chars) and optional length bounds (character count).\n *\n * @param s - hex string\n * @param name - parameter name used in error messages\n * @param min if valid, string length minimum (not bytes)\n * @param max if valid, string length maximum (not bytes)\n * @returns\n */\nfunction validateHexString(s, name, min, max) {\n s = s.trim().toLowerCase();\n if (s.length % 2 === 1)\n throw new WERR_INVALID_PARAMETER(name, `even length, not ${s.length}.`);\n const hexRegex = /^[0-9A-Fa-f]+$/;\n if (!hexRegex.test(s))\n throw new WERR_INVALID_PARAMETER(name, 'hexadecimal string.');\n if (min !== undefined && s.length < min)\n throw new WERR_INVALID_PARAMETER(name, `at least ${min} length.`);\n if (max !== undefined && s.length > max)\n throw new WERR_INVALID_PARAMETER(name, `no more than ${max} length.`);\n return s;\n}\n/**\n * Check whether a string is a valid hex string (even length and hex characters).\n *\n * @param s - input string\n * @returns true when s is a valid hex string\n */\nexport function isHexString(s) {\n s = s.trim();\n if (s.length % 2 === 1)\n return false;\n const hexRegex = /^[0-9A-Fa-f]+$/;\n if (!hexRegex.test(s))\n return false;\n return true;\n}\n/**\n * Validate a CreateActionInput structure.\n *\n * Ensures either unlockingScript or unlockingScriptLength is provided and consistent,\n * validates outpoint, description length, and sequence number.\n *\n * @param i - CreateActionInput to validate\n * @returns ValidCreateActionInput\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateCreateActionInput(i) {\n if (i.unlockingScript === undefined && i.unlockingScriptLength === undefined) {\n throw new WERR_INVALID_PARAMETER('unlockingScript, unlockingScriptLength', 'at least one valid value.');\n }\n const unlockingScript = validateOptionalHexString(i.unlockingScript, 'unlockingScript');\n const unlockingScriptLength = i.unlockingScriptLength ?? (unlockingScript != null ? unlockingScript.length / 2 : 0);\n if (unlockingScript && unlockingScriptLength !== unlockingScript.length / 2) {\n throw new WERR_INVALID_PARAMETER('unlockingScriptLength', 'length unlockingScript if both valid.');\n }\n const vi = {\n outpoint: parseWalletOutpoint(i.outpoint),\n inputDescription: validateStringLength(i.inputDescription, 'inputDescription', 5, 2000),\n unlockingScript,\n unlockingScriptLength,\n sequenceNumber: default0xffffffff(i.sequenceNumber)\n };\n return vi;\n}\n/**\n * Validate CreateActionOutput fields: locking script, satoshis, description, basket, tags.\n *\n * @param o - CreateActionOutput to validate\n * @returns ValidCreateActionOutput\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateCreateActionOutput(o) {\n const vo = {\n lockingScript: validateHexString(o.lockingScript, 'lockingScript'),\n satoshis: validateSatoshis(o.satoshis, 'satoshis'),\n outputDescription: validateStringLength(o.outputDescription, 'outputDescription', 5, 2000),\n basket: validateOptionalBasket(o.basket),\n customInstructions: o.customInstructions,\n tags: defaultEmpty(o.tags).map(t => validateTag(t))\n };\n return vo;\n}\n/**\n * Normalize and validate CreateActionOptions, applying defaults for booleans/numbers/arrays.\n *\n * @param options - CreateActionOptions or undefined\n * @returns ValidCreateActionOptions with defaults applied\n */\nexport function validateCreateActionOptions(options) {\n const o = options != null ? options : {};\n const vo = {\n signAndProcess: defaultTrue(o.signAndProcess),\n acceptDelayedBroadcast: defaultTrue(o.acceptDelayedBroadcast),\n knownTxids: defaultEmpty(o.knownTxids),\n returnTXIDOnly: defaultFalse(o.returnTXIDOnly),\n noSend: defaultFalse(o.noSend),\n noSendChange: defaultEmpty(o.noSendChange).map(nsc => parseWalletOutpoint(nsc)),\n sendWith: defaultEmpty(o.sendWith),\n randomizeOutputs: defaultTrue(o.randomizeOutputs)\n };\n return vo;\n}\n/**\n * Validate the arguments for creating a new action.\n *\n * @param args\n * @returns validated arguments\n * @throws primarily WERR_INVALID_PARAMETER if args are invalid.\n */\nexport function validateCreateActionArgs(args, logger) {\n const vargs = {\n description: validateStringLength(args.description, 'description', 5, 2000),\n inputBEEF: args.inputBEEF,\n inputs: defaultEmpty(args.inputs).map(i => validateCreateActionInput(i)),\n outputs: defaultEmpty(args.outputs).map(o => validateCreateActionOutput(o)),\n lockTime: defaultZero(args.lockTime),\n version: defaultOne(args.version),\n labels: defaultEmpty(args.labels?.map(l => validateLabel(l))),\n options: validateCreateActionOptions(args.options),\n logger,\n isSendWith: false,\n isDelayed: false,\n isNoSend: false,\n isNewTx: false,\n isRemixChange: false,\n isSignAction: false,\n randomVals: undefined,\n includeAllSourceTransactions: false,\n isTestWerrReviewActions: false\n };\n vargs.isTestWerrReviewActions = vargs.labels.includes(specOpThrowReviewActions);\n vargs.isSendWith = vargs.options.sendWith.length > 0;\n vargs.isRemixChange = !vargs.isSendWith && vargs.inputs.length === 0 && vargs.outputs.length === 0;\n vargs.isNewTx = vargs.isRemixChange || vargs.inputs.length > 0 || vargs.outputs.length > 0;\n vargs.isSignAction =\n vargs.isNewTx && (!vargs.options.signAndProcess || vargs.inputs.some(i => i.unlockingScript === undefined));\n vargs.isDelayed = vargs.options.acceptDelayedBroadcast;\n vargs.isNoSend = vargs.options.noSend;\n return vargs;\n}\n/**\n * Set all default true/false booleans to true or false if undefined.\n * Set all possibly undefined numbers to their default values.\n * Set all possibly undefined arrays to empty arrays.\n * Convert string outpoints to `{ txid: string, vout: number }`\n */\nexport function validateSignActionOptions(options) {\n const o = options != null ? options : {};\n const vo = {\n acceptDelayedBroadcast: defaultTrue(o.acceptDelayedBroadcast),\n returnTXIDOnly: defaultFalse(o.returnTXIDOnly),\n noSend: defaultFalse(o.noSend),\n sendWith: defaultEmpty(o.sendWith)\n };\n return vo;\n}\n/**\n * Validate SignActionArgs and apply defaults/flags.\n *\n * @param args - SignActionArgs to validate\n * @returns ValidSignActionArgs\n */\nexport function validateSignActionArgs(args) {\n const vargs = {\n spends: args.spends,\n reference: args.reference,\n options: validateSignActionOptions(args.options),\n isSendWith: false,\n isDelayed: false,\n isNoSend: false,\n isNewTx: true,\n isRemixChange: false,\n isTestWerrReviewActions: false\n };\n vargs.isSendWith = vargs.options.sendWith.length > 0;\n vargs.isDelayed = vargs.options.acceptDelayedBroadcast;\n vargs.isNoSend = vargs.options.noSend;\n return vargs;\n}\n/**\n * Validate AbortActionArgs (ensures reference is a valid base64 string).\n *\n * @param args - AbortActionArgs\n * @returns ValidAbortActionArgs\n */\nexport function validateAbortActionArgs(args) {\n const vargs = {\n reference: validateBase64String(args.reference, 'reference')\n };\n return vargs;\n}\n/**\n * Validate wallet payment remittance structure.\n *\n * @param args - WalletPayment or undefined\n * @returns ValidWalletPayment or undefined\n */\nexport function validateWalletPayment(args) {\n if (args === undefined)\n return undefined;\n const v = {\n derivationPrefix: validateBase64String(args.derivationPrefix, 'derivationPrefix'),\n derivationSuffix: validateBase64String(args.derivationSuffix, 'derivationSuffix'),\n senderIdentityKey: validateHexString(args.senderIdentityKey, 'senderIdentityKey')\n };\n return v;\n}\n/**\n * Validate a BasketInsertion structure (basket, custom instructions, tags).\n *\n * @param args - BasketInsertion or undefined\n * @returns ValidBasketInsertion or undefined\n */\nexport function validateBasketInsertion(args) {\n if (args === undefined)\n return undefined;\n const v = {\n basket: validateBasket(args.basket),\n customInstructions: validateOptionalStringLength(args.customInstructions, 'customInstructions', 0, 1000), // TODO: real max??\n tags: defaultEmpty(args.tags).map(t => validateTag(t))\n };\n return v;\n}\n/**\n * Validate an InternalizeOutput entry.\n *\n * @param args - InternalizeOutput to validate\n * @returns ValidInternalizeOutput\n */\nexport function validateInternalizeOutput(args) {\n if (args.protocol !== 'basket insertion' && args.protocol !== 'wallet payment') {\n throw new WERR_INVALID_PARAMETER('protocol', '\\'basket insertion\\' or \\'wallet payment\\'');\n }\n const v = {\n outputIndex: validatePositiveIntegerOrZero(args.outputIndex, 'outputIndex'),\n protocol: args.protocol,\n paymentRemittance: validateWalletPayment(args.paymentRemittance),\n insertionRemittance: validateBasketInsertion(args.insertionRemittance)\n };\n return v;\n}\n/**\n * Validate originator string (trim/lowercase and part length checks).\n *\n * @param s - originator string or undefined\n * @returns normalized originator or undefined\n */\nexport function validateOriginator(s) {\n if (s === undefined)\n return undefined;\n s = s.trim().toLowerCase();\n validateStringLength(s, 'originator', 1, 250);\n const sps = s.split('.');\n for (const sp of sps) {\n validateStringLength(sp, 'originator part', 1, 63);\n }\n return s;\n}\n/**\n * Validate InternalizeActionArgs: tx, outputs, description, labels, permission flag.\n *\n * @param args - InternalizeActionArgs to validate\n * @returns ValidInternalizeActionArgs\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateInternalizeActionArgs(args) {\n const vargs = {\n tx: args.tx,\n outputs: args.outputs.map(o => validateInternalizeOutput(o)),\n description: validateStringLength(args.description, 'description', 5, 2000),\n labels: (args.labels != null ? args.labels : []).map(t => validateLabel(t)),\n seekPermission: defaultTrue(args.seekPermission)\n };\n try {\n const beef = Beef.fromBinary(vargs.tx);\n if (beef.txs.length < 1) {\n throw new WERR_INVALID_PARAMETER('tx', 'at least one transaction to internalize an output from');\n }\n }\n catch {\n throw new WERR_INVALID_PARAMETER('tx', 'valid with at least one transaction to internalize an output from');\n }\n if (vargs.outputs.length < 1) {\n throw new WERR_INVALID_PARAMETER('outputs', 'at least one output to internalize from the transaction');\n }\n return vargs;\n}\n/**\n * Validate an optional outpoint string (txid.vout).\n *\n * @param outpoint - outpoint string or undefined\n * @param name - parameter name used in error messages\n * @returns validated outpoint string or undefined\n */\nexport function validateOptionalOutpointString(outpoint, name) {\n if (outpoint === undefined)\n return undefined;\n return validateOutpointString(outpoint, name);\n}\n/**\n * Validate an outpoint string of the form txid.vout.\n *\n * @param outpoint - outpoint string\n * @param name - parameter name used in error messages\n * @returns normalized outpoint string (validated txid and vout)\n * @throws WERR_INVALID_PARAMETER when invalid\n */\nexport function validateOutpointString(outpoint, name) {\n const s = outpoint.split('.');\n if (s.length !== 2 || !Number.isInteger(Number(s[1]))) {\n throw new WERR_INVALID_PARAMETER(name, 'txid as hex string and numeric output index joined with \\'.\\'');\n }\n const txid = validateHexString(s[0], `${name} txid`, undefined, 64);\n const vout = validatePositiveIntegerOrZero(Number(s[1]), `${name} vout`);\n return `${txid}.${vout}`;\n}\n/**\n * Validate RelinquishOutputArgs (basket and output).\n *\n * @param args - RelinquishOutputArgs\n * @returns ValidRelinquishOutputArgs\n */\nexport function validateRelinquishOutputArgs(args) {\n const vargs = {\n basket: validateBasket(args.basket),\n output: validateOutpointString(args.output, 'output')\n };\n return vargs;\n}\n/**\n * Validate RelinquishCertificateArgs (type, serialNumber, certifier).\n *\n * @param args - RelinquishCertificateArgs\n * @returns ValidRelinquishCertificateArgs\n */\nexport function validateRelinquishCertificateArgs(args) {\n const vargs = {\n type: validateBase64String(args.type, 'type'),\n serialNumber: validateBase64String(args.serialNumber, 'serialNumber'),\n certifier: validateHexString(args.certifier, 'certifier')\n };\n return vargs;\n}\n/**\n * Validate ListCertificatesArgs: certifiers, types, paging, and optional privileged reason.\n *\n * @param args - ListCertificatesArgs\n * @returns ValidListCertificatesArgs\n */\nexport function validateListCertificatesArgs(args) {\n const vargs = {\n certifiers: defaultEmpty(args.certifiers.map(c => validateHexString(c.trim(), 'certifiers'))),\n types: defaultEmpty(args.types.map(t => validateBase64String(t.trim(), 'types'))),\n limit: validateInteger(args.limit, 'limit', 10, 1, 10000),\n offset: validatePositiveIntegerOrZero(defaultZero(args.offset), 'offset'),\n privileged: defaultFalse(args.privileged),\n privilegedReason: validateOptionalStringLength(args.privilegedReason, 'privilegedReason', 5, 50),\n partial: undefined\n };\n return vargs;\n}\nfunction validateCertificateFields(fields) {\n for (const fieldName of Object.keys(fields)) {\n validateStringLength(fieldName, 'field name', 1, 50);\n }\n return fields;\n}\nfunction validateKeyringRevealer(kr, name) {\n if (kr === 'certifier')\n return kr;\n return validateHexString(kr, name);\n}\nfunction validateKeyringForSubject(kr, name) {\n for (const fn of Object.keys(kr)) {\n validateStringLength(fn, `${name} field name`, 1, 50);\n validateBase64String(kr[fn], `${name} field value`);\n }\n return kr;\n}\n/**\n * Validate issuance-specific acquire certificate args.\n *\n * @param args - AcquireCertificateArgs with acquisitionProtocol === 'issuance'\n * @returns ValidAcquireIssuanceCertificateArgs\n * @throws when args contain fields invalid for issuance\n */\nexport function validateAcquireIssuanceCertificateArgs(args) {\n if (args.acquisitionProtocol !== 'issuance') {\n throw new Error('Only acquire certificate via issuance requests allowed here.');\n }\n if (args.serialNumber)\n throw new WERR_INVALID_PARAMETER('serialNumber', 'valid when acquisitionProtocol is \"direct\"');\n if (args.signature)\n throw new WERR_INVALID_PARAMETER('signature', 'valid when acquisitionProtocol is \"direct\"');\n if (args.revocationOutpoint) {\n throw new WERR_INVALID_PARAMETER('revocationOutpoint', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (args.keyringRevealer) {\n throw new WERR_INVALID_PARAMETER('keyringRevealer', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (args.keyringForSubject != null) {\n throw new WERR_INVALID_PARAMETER('keyringForSubject', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (!args.certifierUrl) {\n throw new WERR_INVALID_PARAMETER('certifierUrl', 'valid when acquisitionProtocol is \"issuance\"');\n }\n if (args.privileged && !args.privilegedReason) {\n throw new WERR_INVALID_PARAMETER('privilegedReason', 'valid when \\'privileged\\' is true ');\n }\n const vargs = {\n type: validateBase64String(args.type, 'type'),\n certifier: validateHexString(args.certifier, 'certifier'),\n certifierUrl: args.certifierUrl,\n fields: validateCertificateFields(args.fields),\n privileged: defaultFalse(args.privileged),\n privilegedReason: validateOptionalStringLength(args.privilegedReason, 'privilegedReason', 5, 50),\n subject: ''\n };\n return vargs;\n}\n/**\n * Validate direct-acquisition-specific acquire certificate args.\n *\n * @param args - AcquireCertificateArgs with acquisitionProtocol === 'direct'\n * @returns ValidAcquireDirectCertificateArgs\n * @throws when args contain fields invalid for direct acquisition\n */\nexport function validateAcquireDirectCertificateArgs(args) {\n if (args.acquisitionProtocol !== 'direct') {\n throw new Error('Only acquire direct certificate requests allowed here.');\n }\n if (!args.serialNumber)\n throw new WERR_INVALID_PARAMETER('serialNumber', 'valid when acquisitionProtocol is \"direct\"');\n if (!args.signature)\n throw new WERR_INVALID_PARAMETER('signature', 'valid when acquisitionProtocol is \"direct\"');\n if (!args.revocationOutpoint) {\n throw new WERR_INVALID_PARAMETER('revocationOutpoint', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (!args.keyringRevealer) {\n throw new WERR_INVALID_PARAMETER('keyringRevealer', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (args.keyringForSubject == null) {\n throw new WERR_INVALID_PARAMETER('keyringForSubject', 'valid when acquisitionProtocol is \"direct\"');\n }\n if (args.privileged && !args.privilegedReason) {\n throw new WERR_INVALID_PARAMETER('privilegedReason', 'valid when \\'privileged\\' is true ');\n }\n const vargs = {\n type: validateBase64String(args.type, 'type'),\n serialNumber: validateBase64String(args.serialNumber, 'serialNumber'),\n certifier: validateHexString(args.certifier, 'certifier'),\n revocationOutpoint: validateOutpointString(args.revocationOutpoint, 'revocationOutpoint'),\n fields: validateCertificateFields(args.fields),\n signature: validateHexString(args.signature, 'signature'),\n keyringRevealer: validateKeyringRevealer(args.keyringRevealer, 'keyringRevealer'),\n keyringForSubject: validateKeyringForSubject(args.keyringForSubject, 'keyringForSubject'),\n privileged: defaultFalse(args.privileged),\n privilegedReason: validateOptionalStringLength(args.privilegedReason, 'privilegedReason', 5, 50),\n subject: ''\n };\n return vargs;\n}\n/**\n * Validate ProveCertificateArgs including optional certificate fields and reveal list.\n *\n * @param args - ProveCertificateArgs\n * @returns ValidProveCertificateArgs\n */\nexport function validateProveCertificateArgs(args) {\n if (args.privileged && !args.privilegedReason) {\n throw new WERR_INVALID_PARAMETER('privilegedReason', 'valid when \\'privileged\\' is true ');\n }\n const vargs = {\n type: validateOptionalBase64String(args.certificate.type, 'certificate.type'),\n serialNumber: validateOptionalBase64String(args.certificate.serialNumber, 'certificate.serialNumber'),\n certifier: validateOptionalHexString(args.certificate.certifier, 'certificate.certifier'),\n subject: validateOptionalHexString(args.certificate.subject, 'certificate.subject'),\n revocationOutpoint: validateOptionalOutpointString(args.certificate.revocationOutpoint, 'certificate.revocationOutpoint'),\n signature: validateOptionalHexString(args.certificate.signature, 'certificate.signature'),\n fieldsToReveal: defaultEmpty(args.fieldsToReveal).map(fieldName => validateStringLength(fieldName, `fieldsToReveal ${fieldName}`, 1, 50)),\n verifier: validateHexString(args.verifier, 'verifier'),\n privileged: defaultFalse(args.privileged),\n privilegedReason: validateOptionalStringLength(args.privilegedReason, 'privilegedReason', 5, 50)\n };\n return vargs;\n}\n/**\n * Validate DiscoverByIdentityKeyArgs, enforcing identity key length and defaults.\n *\n * @param args - DiscoverByIdentityKeyArgs\n * @returns ValidDiscoverByIdentityKeyArgs\n */\nexport function validateDiscoverByIdentityKeyArgs(args) {\n const vargs = {\n identityKey: validateHexString(args.identityKey, 'identityKey', 66, 66),\n limit: validateInteger(args.limit, 'limit', 10, 1, 10000),\n offset: validatePositiveIntegerOrZero(defaultZero(args.offset), 'offset'),\n seekPermission: defaultFalse(args.seekPermission)\n };\n return vargs;\n}\nfunction validateAttributes(attributes) {\n for (const fieldName of Object.keys(attributes)) {\n validateStringLength(fieldName, `field name ${fieldName}`, 1, 50);\n }\n return attributes;\n}\n/**\n * Validate DiscoverByAttributesArgs: attributes, limit, offset, and permission flag.\n *\n * @param args - DiscoverByAttributesArgs\n * @returns ValidDiscoverByAttributesArgs\n */\nexport function validateDiscoverByAttributesArgs(args) {\n const vargs = {\n attributes: validateAttributes(args.attributes),\n limit: validateInteger(args.limit, 'limit', 10, 1, 10000),\n offset: validatePositiveIntegerOrZero(defaultZero(args.offset), 'offset'),\n seekPermission: defaultFalse(args.seekPermission)\n };\n return vargs;\n}\n/**\n * @param {BasketStringUnder300Bytes} args.basket - Required. The associated basket name whose outputs should be listed.\n * @param {OutputTagStringUnder300Bytes[]} [args.tags] - Optional. Filter outputs based on these tags.\n * @param {'all' | 'any'} [args.tagQueryMode] - Optional. Filter mode, defining whether all or any of the tags must match. By default, any tag can match.\n * @param {'locking scripts' | 'entire transactions'} [args.include] - Optional. Whether to include locking scripts (with each output) or entire transactions (as aggregated BEEF, at the top level) in the result. By default, unless specified, neither are returned.\n * @param {BooleanDefaultFalse} [args.includeEntireTransactions] - Optional. Whether to include the entire transaction(s) in the result.\n * @param {BooleanDefaultFalse} [args.includeCustomInstructions] - Optional. Whether custom instructions should be returned in the result.\n * @param {BooleanDefaultFalse} [args.includeTags] - Optional. Whether the tags associated with the output should be returned.\n * @param {BooleanDefaultFalse} [args.includeLabels] - Optional. Whether the labels associated with the transaction containing the output should be returned.\n * @param {PositiveIntegerDefault10Max10000} [args.limit] - Optional limit on the number of outputs to return.\n * @param {number} [args.offset] - If positive or zero: Number of outputs to skip before starting to return results, oldest first.\n * If negative: Outputs are returned newest first and offset of -1 is the newest output.\n * When using negative offsets, caution is required as new outputs may be added between calls,\n * potentially causing outputs to be duplicated across calls.\n * @param {BooleanDefaultTrue} [args.seekPermission] — Optional. Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.\n */\nexport function validateListOutputsArgs(args) {\n let tagQueryMode;\n if (args.tagQueryMode === undefined || args.tagQueryMode === 'any')\n tagQueryMode = 'any';\n else if (args.tagQueryMode === 'all')\n tagQueryMode = 'all';\n else\n throw new WERR_INVALID_PARAMETER('tagQueryMode', 'undefined, \\'any\\', or \\'all\\'');\n const vargs = {\n basket: validateStringLength(args.basket, 'basket', 1, 300),\n tags: (args.tags != null ? args.tags : []).map(t => validateStringLength(t, 'tag', 1, 300)),\n tagQueryMode,\n includeLockingScripts: args.include === 'locking scripts',\n includeTransactions: args.include === 'entire transactions',\n includeCustomInstructions: defaultFalse(args.includeCustomInstructions),\n includeTags: defaultFalse(args.includeTags),\n includeLabels: defaultFalse(args.includeLabels),\n limit: validateInteger(args.limit, 'limit', 10, 1, 10000),\n offset: validateInteger(args.offset, 'offset', 0, undefined, undefined),\n seekPermission: defaultTrue(args.seekPermission),\n knownTxids: []\n };\n return vargs;\n}\n/**\n * @param {LabelStringUnder300Bytes[]} args.labels - An array of labels used to filter actions.\n * @param {'any' | 'all'} [args.labelQueryMode] - Optional. Specifies how to match labels (default is any which matches any of the labels).\n * @param {BooleanDefaultFalse} [args.includeLabels] - Optional. Whether to include transaction labels in the result set.\n * @param {BooleanDefaultFalse} [args.includeInputs] - Optional. Whether to include input details in the result set.\n * @param {BooleanDefaultFalse} [args.includeInputSourceLockingScripts] - Optional. Whether to include input source locking scripts in the result set.\n * @param {BooleanDefaultFalse} [args.includeInputUnlockingScripts] - Optional. Whether to include input unlocking scripts in the result set.\n * @param {BooleanDefaultFalse} [args.includeOutputs] - Optional. Whether to include output details in the result set.\n * @param {BooleanDefaultFalse} [args.includeOutputLockingScripts] - Optional. Whether to include output locking scripts in the result set.\n * @param {PositiveIntegerDefault10Max10000} [args.limit] - Optional. The maximum number of transactions to retrieve.\n * @param {PositiveIntegerOrZero} [args.offset] - Optional. Number of transactions to skip before starting to return the results.\n * @param {BooleanDefaultTrue} [args.seekPermission] — Optional. Whether to seek permission from the user for this operation if required. Default true, will return an error rather than proceed if set to false.\n */\nexport function validateListActionsArgs(args) {\n let labelQueryMode;\n if (args.labelQueryMode === undefined || args.labelQueryMode === 'any')\n labelQueryMode = 'any';\n else if (args.labelQueryMode === 'all')\n labelQueryMode = 'all';\n else\n throw new WERR_INVALID_PARAMETER('labelQueryMode', 'undefined, \\'any\\', or \\'all\\'');\n const vargs = {\n labels: (args.labels != null ? args.labels : []).map(t => validateLabel(t)),\n labelQueryMode,\n includeLabels: defaultFalse(args.includeLabels),\n includeInputs: defaultFalse(args.includeInputs),\n includeInputSourceLockingScripts: defaultFalse(args.includeInputSourceLockingScripts),\n includeInputUnlockingScripts: defaultFalse(args.includeInputUnlockingScripts),\n includeOutputs: defaultFalse(args.includeOutputs),\n includeOutputLockingScripts: defaultFalse(args.includeOutputLockingScripts),\n limit: validateInteger(args.limit, 'limit', 10, 1, 10000),\n offset: validateInteger(args.offset, 'offset', 0, 0),\n seekPermission: defaultTrue(args.seekPermission)\n };\n return vargs;\n}\n/**\n * `createAction` special operation label name value.\n *\n * Causes WERR_REVIEW_ACTIONS throw with dummy properties.\n *\n */\nexport const specOpThrowReviewActions = 'a496e747fc3ad5fabdd4ae8f91184e71f87539bd3d962aa2548942faaaf0047a';\n//# sourceMappingURL=validationHelpers.js.map","import WindowCWISubstrate from './substrates/window.CWI.js';\nimport XDMSubstrate from './substrates/XDM.js';\nimport WalletWireTransceiver from './substrates/WalletWireTransceiver.js';\nimport HTTPWalletWire from './substrates/HTTPWalletWire.js';\nimport HTTPWalletJSON from './substrates/HTTPWalletJSON.js';\nimport ReactNativeWebView from './substrates/ReactNativeWebView.js';\nimport { validateAbortActionArgs, validateAcquireDirectCertificateArgs, validateAcquireIssuanceCertificateArgs, validateCreateActionArgs, validateDiscoverByAttributesArgs, validateDiscoverByIdentityKeyArgs, validateInternalizeActionArgs, validateListActionsArgs, validateListCertificatesArgs, validateListOutputsArgs, validateProveCertificateArgs, validateRelinquishCertificateArgs, validateRelinquishOutputArgs, validateSignActionArgs } from './validationHelpers.js';\nimport { WERR_INVALID_PARAMETER } from './WERR_INVALID_PARAMETER.js';\nconst MAX_XDM_RESPONSE_WAIT = 200;\n/**\n * The SDK is how applications communicate with wallets over a communications substrate.\n */\nexport default class WalletClient {\n substrate;\n originator;\n constructor(substrate = 'auto', originator) {\n if (substrate === 'Cicada') {\n substrate = new WalletWireTransceiver(new HTTPWalletWire(originator));\n }\n if (substrate === 'window.CWI')\n substrate = new WindowCWISubstrate();\n if (substrate === 'XDM')\n substrate = new XDMSubstrate();\n if (substrate === 'json-api')\n substrate = new HTTPWalletJSON(originator);\n if (substrate === 'react-native')\n substrate = new ReactNativeWebView(originator);\n if (substrate === 'secure-json-api')\n substrate = new HTTPWalletJSON(originator, 'https://localhost:2121');\n this.substrate = substrate;\n this.originator = originator;\n }\n async connectToSubstrate() {\n if (typeof this.substrate === 'object') {\n return; // substrate is already connected\n }\n const attemptSubstrate = async (factory, timeout) => {\n try {\n const sub = factory();\n let result;\n if (typeof timeout === 'number') {\n result = await Promise.race([\n sub.getVersion({}),\n new Promise((_resolve, reject) => setTimeout(() => reject(new Error('Timed out.')), timeout))\n ]);\n }\n else {\n result = await sub.getVersion({});\n }\n if (typeof result !== 'object' || typeof result.version !== 'string') {\n return { success: false };\n }\n return { success: true, sub };\n }\n catch {\n return { success: false };\n }\n };\n // Try fast substrates first\n const fastAttempts = [\n attemptSubstrate(() => new WindowCWISubstrate()),\n attemptSubstrate(() => new HTTPWalletJSON(this.originator, 'https://localhost:2121')),\n attemptSubstrate(() => new HTTPWalletJSON(this.originator)),\n attemptSubstrate(() => new ReactNativeWebView(this.originator)),\n attemptSubstrate(() => new WalletWireTransceiver(new HTTPWalletWire(this.originator)))\n ];\n const fastResults = await Promise.allSettled(fastAttempts);\n const fastSuccessful = fastResults\n .filter((r) => r.status === 'fulfilled' && r.value.success && r.value.sub !== undefined)\n .map(r => r.value.sub);\n if (fastSuccessful.length > 0) {\n this.substrate = fastSuccessful[0];\n return;\n }\n // Fall back to slower XDM substrate\n const xdmResult = await attemptSubstrate(() => new XDMSubstrate(), MAX_XDM_RESPONSE_WAIT);\n if (xdmResult.success && xdmResult.sub !== undefined) {\n this.substrate = xdmResult.sub;\n }\n else {\n throw new Error('No wallet available over any communication substrate. Install a BSV wallet today!');\n }\n }\n async createAction(args) {\n validateCreateActionArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.createAction(args, this.originator);\n }\n async signAction(args) {\n validateSignActionArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.signAction(args, this.originator);\n }\n async abortAction(args) {\n validateAbortActionArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.abortAction(args, this.originator);\n }\n async listActions(args) {\n validateListActionsArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.listActions(args, this.originator);\n }\n async internalizeAction(args) {\n validateInternalizeActionArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.internalizeAction(args, this.originator);\n }\n async listOutputs(args) {\n validateListOutputsArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.listOutputs(args, this.originator);\n }\n async relinquishOutput(args) {\n validateRelinquishOutputArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.relinquishOutput(args, this.originator);\n }\n async getPublicKey(args) {\n await this.connectToSubstrate();\n return await this.substrate.getPublicKey(args, this.originator);\n }\n async revealCounterpartyKeyLinkage(args) {\n await this.connectToSubstrate();\n return await this.substrate.revealCounterpartyKeyLinkage(args, this.originator);\n }\n async revealSpecificKeyLinkage(args) {\n await this.connectToSubstrate();\n return await this.substrate.revealSpecificKeyLinkage(args, this.originator);\n }\n async encrypt(args) {\n await this.connectToSubstrate();\n return await this.substrate.encrypt(args, this.originator);\n }\n async decrypt(args) {\n await this.connectToSubstrate();\n return await this.substrate.decrypt(args, this.originator);\n }\n async createHmac(args) {\n await this.connectToSubstrate();\n return await this.substrate.createHmac(args, this.originator);\n }\n async verifyHmac(args) {\n await this.connectToSubstrate();\n return await this.substrate.verifyHmac(args, this.originator);\n }\n async createSignature(args) {\n await this.connectToSubstrate();\n return await this.substrate.createSignature(args, this.originator);\n }\n async verifySignature(args) {\n await this.connectToSubstrate();\n return await this.substrate.verifySignature(args, this.originator);\n }\n async acquireCertificate(args) {\n if (args.acquisitionProtocol === 'direct') {\n validateAcquireDirectCertificateArgs(args);\n }\n else if (args.acquisitionProtocol === 'issuance') {\n validateAcquireIssuanceCertificateArgs(args);\n }\n else {\n throw new WERR_INVALID_PARAMETER('acquisitionProtocol', `valid. ${String(args.acquisitionProtocol)} is unrecognized.`);\n }\n await this.connectToSubstrate();\n return await this.substrate.acquireCertificate(args, this.originator);\n }\n async listCertificates(args) {\n validateListCertificatesArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.listCertificates(args, this.originator);\n }\n async proveCertificate(args) {\n validateProveCertificateArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.proveCertificate(args, this.originator);\n }\n async relinquishCertificate(args) {\n validateRelinquishCertificateArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.relinquishCertificate(args, this.originator);\n }\n async discoverByIdentityKey(args) {\n validateDiscoverByIdentityKeyArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.discoverByIdentityKey(args, this.originator);\n }\n async discoverByAttributes(args) {\n validateDiscoverByAttributesArgs(args);\n await this.connectToSubstrate();\n return await this.substrate.discoverByAttributes(args, this.originator);\n }\n async isAuthenticated(args = {}) {\n await this.connectToSubstrate();\n return await this.substrate.isAuthenticated(args, this.originator);\n }\n async waitForAuthentication(args = {}) {\n await this.connectToSubstrate();\n return await this.substrate.waitForAuthentication(args, this.originator);\n }\n async getHeight(args = {}) {\n await this.connectToSubstrate();\n return await this.substrate.getHeight(args, this.originator);\n }\n async getHeaderForHeight(args) {\n await this.connectToSubstrate();\n return await this.substrate.getHeaderForHeight(args, this.originator);\n }\n async getNetwork(args = {}) {\n await this.connectToSubstrate();\n return await this.substrate.getNetwork(args, this.originator);\n }\n async getVersion(args = {}) {\n await this.connectToSubstrate();\n return await this.substrate.getVersion(args, this.originator);\n }\n}\n//# sourceMappingURL=WalletClient.js.map","import * as Utils from '../../primitives/utils.js';\nimport calls from './WalletWireCalls.js';\nimport Certificate from '../../auth/certificates/Certificate.js';\n/**\n * Processes incoming wallet calls received over a wallet wire, with a given wallet.\n */\nexport default class WalletWireProcessor {\n wallet;\n constructor(wallet) {\n this.wallet = wallet;\n }\n decodeOutpoint(reader) {\n const txidBytes = reader.read(32);\n const txid = Utils.toHex(txidBytes);\n const index = reader.readVarIntNum();\n return `${txid}.${index}`;\n }\n encodeOutpoint(outpoint) {\n const writer = new Utils.Writer();\n const [txid, index] = outpoint.split('.');\n writer.write(Utils.toArray(txid, 'hex'));\n writer.writeVarIntNum(Number(index));\n return writer.toArray();\n }\n async transmitToWallet(message) {\n const messageReader = new Utils.Reader(message);\n try {\n // Read call code\n const callCode = messageReader.readUInt8();\n // Map call code to call name\n const callName = calls[callCode]; // calls is enum\n if (callName === undefined || callName === '') {\n // Invalid call code\n throw new Error(`Invalid call code: ${callCode}`);\n }\n // Read originator length\n const originatorLength = messageReader.readUInt8();\n const originatorBytes = messageReader.read(originatorLength);\n const originator = Utils.toUTF8(originatorBytes);\n // Read parameters\n const paramsReader = messageReader; // Remaining bytes\n switch (callName) {\n case 'createAction': {\n // Deserialize parameters from paramsReader\n const args = {};\n // Read description\n const descriptionLength = paramsReader.readVarIntNum();\n const descriptionBytes = paramsReader.read(descriptionLength);\n args.description = Utils.toUTF8(descriptionBytes);\n // tx\n const inputBeefLength = paramsReader.readVarIntNum();\n if (inputBeefLength >= 0) {\n args.inputBEEF = paramsReader.read(inputBeefLength); // BEEF (Byte[])\n }\n else {\n args.inputBEEF = undefined;\n }\n // Read inputs\n const inputsLength = paramsReader.readVarIntNum();\n if (inputsLength >= 0) {\n args.inputs = [];\n for (let i = 0; i < inputsLength; i++) {\n const input = {};\n // outpoint\n input.outpoint = this.decodeOutpoint(paramsReader);\n // unlockingScript / unlockingScriptLength\n const unlockingScriptLength = paramsReader.readVarIntNum();\n if (unlockingScriptLength >= 0) {\n const unlockingScriptBytes = paramsReader.read(unlockingScriptLength);\n input.unlockingScript = Utils.toHex(unlockingScriptBytes);\n }\n else {\n input.unlockingScript = undefined;\n const unlockingScriptLengthValue = paramsReader.readVarIntNum();\n input.unlockingScriptLength = unlockingScriptLengthValue;\n }\n // inputDescription\n const inputDescriptionLength = paramsReader.readVarIntNum();\n const inputDescriptionBytes = paramsReader.read(inputDescriptionLength);\n input.inputDescription = Utils.toUTF8(inputDescriptionBytes);\n // sequenceNumber\n const sequenceNumber = paramsReader.readVarIntNum();\n if (sequenceNumber >= 0) {\n input.sequenceNumber = sequenceNumber;\n }\n else {\n input.sequenceNumber = undefined;\n }\n args.inputs.push(input);\n }\n }\n else {\n args.inputs = undefined;\n }\n // Read outputs\n const outputsLength = paramsReader.readVarIntNum();\n if (outputsLength >= 0) {\n args.outputs = [];\n for (let i = 0; i < outputsLength; i++) {\n const output = {};\n // lockingScript\n const lockingScriptLength = paramsReader.readVarIntNum();\n const lockingScriptBytes = paramsReader.read(lockingScriptLength);\n output.lockingScript = Utils.toHex(lockingScriptBytes);\n // satoshis\n output.satoshis = paramsReader.readVarIntNum();\n // outputDescription\n const outputDescriptionLength = paramsReader.readVarIntNum();\n const outputDescriptionBytes = paramsReader.read(outputDescriptionLength);\n output.outputDescription = Utils.toUTF8(outputDescriptionBytes);\n // basket\n const basketLength = paramsReader.readVarIntNum();\n if (basketLength >= 0) {\n const basketBytes = paramsReader.read(basketLength);\n output.basket = Utils.toUTF8(basketBytes);\n }\n else {\n output.basket = undefined;\n }\n // customInstructions\n const customInstructionsLength = paramsReader.readVarIntNum();\n if (customInstructionsLength >= 0) {\n const customInstructionsBytes = paramsReader.read(customInstructionsLength);\n output.customInstructions = Utils.toUTF8(customInstructionsBytes);\n }\n else {\n output.customInstructions = undefined;\n }\n // tags\n const tagsLength = paramsReader.readVarIntNum();\n if (tagsLength >= 0) {\n output.tags = [];\n for (let j = 0; j < tagsLength; j++) {\n const tagLength = paramsReader.readVarIntNum();\n const tagBytes = paramsReader.read(tagLength);\n const tag = Utils.toUTF8(tagBytes);\n output.tags.push(tag);\n }\n }\n else {\n output.tags = undefined;\n }\n args.outputs.push(output);\n }\n }\n else {\n args.outputs = undefined;\n }\n // lockTime\n const lockTime = paramsReader.readVarIntNum();\n if (lockTime >= 0) {\n args.lockTime = lockTime;\n }\n else {\n args.lockTime = undefined;\n }\n // version\n const version = paramsReader.readVarIntNum();\n if (version >= 0) {\n args.version = version;\n }\n else {\n args.version = undefined;\n }\n // labels\n const labelsLength = paramsReader.readVarIntNum();\n if (labelsLength >= 0) {\n args.labels = [];\n for (let i = 0; i < labelsLength; i++) {\n const labelLength = paramsReader.readVarIntNum();\n const labelBytes = paramsReader.read(labelLength);\n const label = Utils.toUTF8(labelBytes);\n args.labels.push(label);\n }\n }\n else {\n args.labels = undefined;\n }\n // options\n const optionsPresent = paramsReader.readInt8();\n if (optionsPresent === 1) {\n args.options = {};\n // signAndProcess\n const signAndProcessFlag = paramsReader.readInt8();\n if (signAndProcessFlag === -1) {\n args.options.signAndProcess = undefined;\n }\n else {\n args.options.signAndProcess = signAndProcessFlag === 1;\n }\n // acceptDelayedBroadcast\n const acceptDelayedBroadcastFlag = paramsReader.readInt8();\n if (acceptDelayedBroadcastFlag === -1) {\n args.options.acceptDelayedBroadcast = undefined;\n }\n else {\n args.options.acceptDelayedBroadcast =\n acceptDelayedBroadcastFlag === 1;\n }\n // trustSelf\n const trustSelfFlag = paramsReader.readInt8();\n if (trustSelfFlag === -1) {\n args.options.trustSelf = undefined;\n }\n else if (trustSelfFlag === 1) {\n args.options.trustSelf = 'known';\n }\n // knownTxids\n const knownTxidsLength = paramsReader.readVarIntNum();\n if (knownTxidsLength >= 0) {\n args.options.knownTxids = [];\n for (let i = 0; i < knownTxidsLength; i++) {\n const txidBytes = paramsReader.read(32);\n const txid = Utils.toHex(txidBytes);\n args.options.knownTxids.push(txid);\n }\n }\n else {\n args.options.knownTxids = undefined;\n }\n // returnTXIDOnly\n const returnTXIDOnlyFlag = paramsReader.readInt8();\n if (returnTXIDOnlyFlag === -1) {\n args.options.returnTXIDOnly = undefined;\n }\n else {\n args.options.returnTXIDOnly = returnTXIDOnlyFlag === 1;\n }\n // noSend\n const noSendFlag = paramsReader.readInt8();\n if (noSendFlag === -1) {\n args.options.noSend = undefined;\n }\n else {\n args.options.noSend = noSendFlag === 1;\n }\n // noSendChange\n const noSendChangeLength = paramsReader.readVarIntNum();\n if (noSendChangeLength >= 0) {\n args.options.noSendChange = [];\n for (let i = 0; i < noSendChangeLength; i++) {\n const outpoint = this.decodeOutpoint(paramsReader);\n args.options.noSendChange.push(outpoint);\n }\n }\n else {\n args.options.noSendChange = undefined;\n }\n // sendWith\n const sendWithLength = paramsReader.readVarIntNum();\n if (sendWithLength >= 0) {\n args.options.sendWith = [];\n for (let i = 0; i < sendWithLength; i++) {\n const txidBytes = paramsReader.read(32);\n const txid = Utils.toHex(txidBytes);\n args.options.sendWith.push(txid);\n }\n }\n else {\n args.options.sendWith = undefined;\n }\n // randomizeOutputs\n const randomizeOutputsFlag = paramsReader.readInt8();\n if (randomizeOutputsFlag === -1) {\n args.options.randomizeOutputs = undefined;\n }\n else {\n args.options.randomizeOutputs = randomizeOutputsFlag === 1;\n }\n }\n else {\n args.options = undefined;\n }\n // Call the method\n const createActionResult = await this.wallet.createAction(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // txid\n if (createActionResult.txid != null && createActionResult.txid !== '') {\n resultWriter.writeInt8(1);\n resultWriter.write(Utils.toArray(createActionResult.txid, 'hex'));\n }\n else {\n resultWriter.writeInt8(0);\n }\n // tx\n if (createActionResult.tx != null) {\n resultWriter.writeInt8(1);\n resultWriter.writeVarIntNum(createActionResult.tx.length);\n resultWriter.write(createActionResult.tx);\n }\n else {\n resultWriter.writeInt8(0);\n }\n // noSendChange\n if (createActionResult.noSendChange != null) {\n resultWriter.writeVarIntNum(createActionResult.noSendChange.length);\n for (const outpoint of createActionResult.noSendChange) {\n resultWriter.write(this.encodeOutpoint(outpoint));\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // sendWithResults\n if (createActionResult.sendWithResults != null) {\n resultWriter.writeVarIntNum(createActionResult.sendWithResults.length);\n for (const result of createActionResult.sendWithResults) {\n resultWriter.write(Utils.toArray(result.txid, 'hex'));\n let statusCode;\n if (result.status === 'unproven')\n statusCode = 1;\n else if (result.status === 'sending')\n statusCode = 2;\n else if (result.status === 'failed')\n statusCode = 3;\n resultWriter.writeInt8(statusCode);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // signableTransaction\n if (createActionResult.signableTransaction != null) {\n resultWriter.writeInt8(1);\n resultWriter.writeVarIntNum(createActionResult.signableTransaction.tx.length);\n resultWriter.write(createActionResult.signableTransaction.tx);\n const referenceBytes = Utils.toArray(createActionResult.signableTransaction.reference, 'base64');\n resultWriter.writeVarIntNum(referenceBytes.length);\n resultWriter.write(referenceBytes);\n }\n else {\n resultWriter.writeInt8(0);\n }\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'signAction': {\n const args = {};\n // Deserialize spends\n const spendCount = paramsReader.readVarIntNum();\n args.spends = {};\n for (let i = 0; i < spendCount; i++) {\n const inputIndex = paramsReader.readVarIntNum();\n const spend = {};\n // unlockingScript\n const unlockingScriptLength = paramsReader.readVarIntNum();\n const unlockingScriptBytes = paramsReader.read(unlockingScriptLength);\n spend.unlockingScript = Utils.toHex(unlockingScriptBytes);\n // sequenceNumber\n const sequenceNumber = paramsReader.readVarIntNum();\n if (sequenceNumber >= 0) {\n spend.sequenceNumber = sequenceNumber;\n }\n else {\n spend.sequenceNumber = undefined;\n }\n args.spends[inputIndex] = spend;\n }\n // Deserialize reference\n const referenceLength = paramsReader.readVarIntNum();\n const referenceBytes = paramsReader.read(referenceLength);\n args.reference = Utils.toBase64(referenceBytes);\n // Deserialize options\n const optionsPresent = paramsReader.readInt8();\n if (optionsPresent === 1) {\n args.options = {};\n // acceptDelayedBroadcast\n const acceptDelayedBroadcastFlag = paramsReader.readInt8();\n if (acceptDelayedBroadcastFlag === -1) {\n args.options.acceptDelayedBroadcast = undefined;\n }\n else {\n args.options.acceptDelayedBroadcast =\n acceptDelayedBroadcastFlag === 1;\n }\n // returnTXIDOnly\n const returnTXIDOnlyFlag = paramsReader.readInt8();\n if (returnTXIDOnlyFlag === -1) {\n args.options.returnTXIDOnly = undefined;\n }\n else {\n args.options.returnTXIDOnly = returnTXIDOnlyFlag === 1;\n }\n // noSend\n const noSendFlag = paramsReader.readInt8();\n if (noSendFlag === -1) {\n args.options.noSend = undefined;\n }\n else {\n args.options.noSend = noSendFlag === 1;\n }\n // sendWith\n const sendWithLength = paramsReader.readVarIntNum();\n if (sendWithLength >= 0) {\n args.options.sendWith = [];\n for (let i = 0; i < sendWithLength; i++) {\n const txidBytes = paramsReader.read(32);\n const txid = Utils.toHex(txidBytes);\n args.options.sendWith.push(txid);\n }\n }\n else {\n args.options.sendWith = undefined;\n }\n }\n else {\n args.options = undefined;\n }\n // Call the method\n const signActionResult = await this.wallet.signAction(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // txid\n if (signActionResult.txid != null && signActionResult.txid !== '') {\n resultWriter.writeInt8(1);\n resultWriter.write(Utils.toArray(signActionResult.txid, 'hex'));\n }\n else {\n resultWriter.writeInt8(0);\n }\n // tx\n if (signActionResult.tx != null) {\n resultWriter.writeInt8(1);\n resultWriter.writeVarIntNum(signActionResult.tx.length);\n resultWriter.write(signActionResult.tx);\n }\n else {\n resultWriter.writeInt8(0);\n }\n // sendWithResults\n if (signActionResult.sendWithResults != null) {\n resultWriter.writeVarIntNum(signActionResult.sendWithResults.length);\n for (const result of signActionResult.sendWithResults) {\n resultWriter.write(Utils.toArray(result.txid, 'hex'));\n let statusCode;\n if (result.status === 'unproven')\n statusCode = 1;\n else if (result.status === 'sending')\n statusCode = 2;\n else if (result.status === 'failed')\n statusCode = 3;\n resultWriter.writeInt8(statusCode);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'abortAction': {\n // Deserialize reference\n const referenceBytes = paramsReader.read();\n const reference = Utils.toBase64(referenceBytes);\n // Call the method\n await this.wallet.abortAction({ reference }, originator);\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'listActions': {\n const args = {};\n // Deserialize labels\n const labelsLength = paramsReader.readVarIntNum();\n args.labels = [];\n for (let i = 0; i < labelsLength; i++) {\n const labelLength = paramsReader.readVarIntNum();\n const labelBytes = paramsReader.read(labelLength);\n args.labels.push(Utils.toUTF8(labelBytes));\n }\n // Deserialize labelQueryMode\n const labelQueryModeFlag = paramsReader.readInt8();\n if (labelQueryModeFlag === -1) {\n args.labelQueryMode = undefined;\n }\n else if (labelQueryModeFlag === 1) {\n args.labelQueryMode = 'any';\n }\n else if (labelQueryModeFlag === 2) {\n args.labelQueryMode = 'all';\n }\n // Deserialize include options\n const includeOptionsNames = [\n 'includeLabels',\n 'includeInputs',\n 'includeInputSourceLockingScripts',\n 'includeInputUnlockingScripts',\n 'includeOutputs',\n 'includeOutputLockingScripts'\n ];\n for (const optionName of includeOptionsNames) {\n const optionFlag = paramsReader.readInt8();\n if (optionFlag === -1) {\n args[optionName] = undefined;\n }\n else {\n args[optionName] = optionFlag === 1;\n }\n }\n // Deserialize limit\n const limit = paramsReader.readVarIntNum();\n if (limit >= 0) {\n args.limit = limit;\n }\n else {\n args.limit = undefined;\n }\n // Deserialize offset\n const offset = paramsReader.readVarIntNum();\n if (offset >= 0) {\n args.offset = offset;\n }\n else {\n args.offset = undefined;\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const listActionsResult = await this.wallet.listActions(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // totalActions\n resultWriter.writeVarIntNum(listActionsResult.totalActions);\n // actions\n for (const action of listActionsResult.actions) {\n // txid\n resultWriter.write(Utils.toArray(action.txid, 'hex'));\n // satoshis\n resultWriter.writeVarIntNum(action.satoshis);\n // status\n let statusCode;\n switch (action.status) {\n case 'completed':\n statusCode = 1;\n break;\n case 'unprocessed':\n statusCode = 2;\n break;\n case 'sending':\n statusCode = 3;\n break;\n case 'unproven':\n statusCode = 4;\n break;\n case 'unsigned':\n statusCode = 5;\n break;\n case 'nosend':\n statusCode = 6;\n break;\n case 'nonfinal':\n statusCode = 7;\n break;\n case 'failed':\n statusCode = 8;\n break;\n default:\n statusCode = -1;\n break;\n }\n resultWriter.writeInt8(statusCode);\n // isOutgoing\n resultWriter.writeInt8(action.isOutgoing ? 1 : 0);\n // description\n const descriptionBytes = Utils.toArray(action.description, 'utf8');\n resultWriter.writeVarIntNum(descriptionBytes.length);\n resultWriter.write(descriptionBytes);\n // labels\n if (action.labels !== undefined) {\n resultWriter.writeVarIntNum(action.labels.length);\n for (const label of action.labels) {\n const labelBytes = Utils.toArray(label, 'utf8');\n resultWriter.writeVarIntNum(labelBytes.length);\n resultWriter.write(labelBytes);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // version\n resultWriter.writeVarIntNum(action.version);\n // lockTime\n resultWriter.writeVarIntNum(action.lockTime);\n // inputs\n if (action.inputs !== undefined) {\n resultWriter.writeVarIntNum(action.inputs.length);\n for (const input of action.inputs) {\n // sourceOutpoint\n resultWriter.write(this.encodeOutpoint(input.sourceOutpoint));\n // sourceSatoshis\n resultWriter.writeVarIntNum(input.sourceSatoshis);\n // sourceLockingScript\n if (input.sourceLockingScript !== undefined) {\n const sourceLockingScriptBytes = Utils.toArray(input.sourceLockingScript, 'hex');\n resultWriter.writeVarIntNum(sourceLockingScriptBytes.length);\n resultWriter.write(sourceLockingScriptBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // unlockingScript\n if (input.unlockingScript !== undefined) {\n const unlockingScriptBytes = Utils.toArray(input.unlockingScript, 'hex');\n resultWriter.writeVarIntNum(unlockingScriptBytes.length);\n resultWriter.write(unlockingScriptBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // inputDescription\n const inputDescriptionBytes = Utils.toArray(input.inputDescription, 'utf8');\n resultWriter.writeVarIntNum(inputDescriptionBytes.length);\n resultWriter.write(inputDescriptionBytes);\n // sequenceNumber\n resultWriter.writeVarIntNum(input.sequenceNumber);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // outputs\n if (action.outputs !== undefined) {\n resultWriter.writeVarIntNum(action.outputs.length);\n for (const output of action.outputs) {\n // outputIndex\n resultWriter.writeVarIntNum(output.outputIndex);\n // satoshis\n resultWriter.writeVarIntNum(output.satoshis);\n // lockingScript\n if (output.lockingScript !== undefined) {\n const lockingScriptBytes = Utils.toArray(output.lockingScript, 'hex');\n resultWriter.writeVarIntNum(lockingScriptBytes.length);\n resultWriter.write(lockingScriptBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // spendable\n resultWriter.writeInt8(output.spendable ? 1 : 0);\n // outputDescription\n const outputDescriptionBytes = Utils.toArray(output.outputDescription, 'utf8');\n resultWriter.writeVarIntNum(outputDescriptionBytes.length);\n resultWriter.write(outputDescriptionBytes);\n // basket\n if (output.basket !== undefined) {\n const basketBytes = Utils.toArray(output.basket, 'utf8');\n resultWriter.writeVarIntNum(basketBytes.length);\n resultWriter.write(basketBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // tags\n if (output.tags !== undefined) {\n resultWriter.writeVarIntNum(output.tags.length);\n for (const tag of output.tags) {\n const tagBytes = Utils.toArray(tag, 'utf8');\n resultWriter.writeVarIntNum(tagBytes.length);\n resultWriter.write(tagBytes);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // customInstructions\n if (output.customInstructions !== undefined) {\n const customInstructionsBytes = Utils.toArray(output.customInstructions, 'utf8');\n resultWriter.writeVarIntNum(customInstructionsBytes.length);\n resultWriter.write(customInstructionsBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n }\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'internalizeAction': {\n const args = {};\n // Read tx\n const txLength = paramsReader.readVarIntNum();\n args.tx = paramsReader.read(txLength);\n // Read outputs\n const outputsLength = paramsReader.readVarIntNum();\n args.outputs = [];\n for (let i = 0; i < outputsLength; i++) {\n const output = {};\n // outputIndex\n output.outputIndex = paramsReader.readVarIntNum();\n // protocol\n const protocolFlag = paramsReader.readUInt8();\n if (protocolFlag === 1) {\n output.protocol = 'wallet payment';\n output.paymentRemittance = {};\n // senderIdentityKey\n const senderIdentityKeyBytes = paramsReader.read(33);\n output.paymentRemittance.senderIdentityKey = Utils.toHex(senderIdentityKeyBytes);\n // derivationPrefix\n const derivationPrefixLength = paramsReader.readVarIntNum();\n const derivationPrefixBytes = paramsReader.read(derivationPrefixLength);\n output.paymentRemittance.derivationPrefix = Utils.toBase64(derivationPrefixBytes);\n // derivationSuffix\n const derivationSuffixLength = paramsReader.readVarIntNum();\n const derivationSuffixBytes = paramsReader.read(derivationSuffixLength);\n output.paymentRemittance.derivationSuffix = Utils.toBase64(derivationSuffixBytes);\n }\n else if (protocolFlag === 2) {\n output.protocol = 'basket insertion';\n output.insertionRemittance = {};\n // basket\n const basketLength = paramsReader.readVarIntNum();\n const basketBytes = paramsReader.read(basketLength);\n output.insertionRemittance.basket = Utils.toUTF8(basketBytes);\n // customInstructions\n const customInstructionsLength = paramsReader.readVarIntNum();\n if (customInstructionsLength >= 0) {\n const customInstructionsBytes = paramsReader.read(customInstructionsLength);\n output.insertionRemittance.customInstructions = Utils.toUTF8(customInstructionsBytes);\n }\n // tags\n const tagsLength = paramsReader.readVarIntNum();\n if (tagsLength > 0) {\n output.insertionRemittance.tags = [];\n for (let j = 0; j < tagsLength; j++) {\n const tagLength = paramsReader.readVarIntNum();\n const tagBytes = paramsReader.read(tagLength);\n output.insertionRemittance.tags.push(Utils.toUTF8(tagBytes));\n }\n }\n else {\n output.insertionRemittance.tags = [];\n }\n }\n args.outputs.push(output);\n }\n const numberOfLabels = paramsReader.readVarIntNum();\n if (numberOfLabels >= 0) {\n args.labels = [];\n for (let i = 0; i < numberOfLabels; i++) {\n const labelLength = paramsReader.readVarIntNum();\n args.labels.push(Utils.toUTF8(paramsReader.read(labelLength)));\n }\n }\n const descriptionLength = paramsReader.readVarIntNum();\n args.description = Utils.toUTF8(paramsReader.read(descriptionLength));\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n await this.wallet.internalizeAction(args, originator);\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'listOutputs': {\n const args = {};\n // Deserialize basket\n const basketLength = paramsReader.readVarIntNum();\n const basketBytes = paramsReader.read(basketLength);\n args.basket = Utils.toUTF8(basketBytes);\n // Deserialize tags\n const tagsLength = paramsReader.readVarIntNum();\n if (tagsLength > 0) {\n args.tags = [];\n for (let i = 0; i < tagsLength; i++) {\n const tagLength = paramsReader.readVarIntNum();\n const tagBytes = paramsReader.read(tagLength);\n args.tags.push(Utils.toUTF8(tagBytes));\n }\n }\n else {\n args.tags = undefined;\n }\n // Deserialize tagQueryMode\n const tagQueryModeFlag = paramsReader.readInt8();\n if (tagQueryModeFlag === 1) {\n args.tagQueryMode = 'all';\n }\n else if (tagQueryModeFlag === 2) {\n args.tagQueryMode = 'any';\n }\n else {\n args.tagQueryMode = undefined;\n }\n // Deserialize include\n const includeFlag = paramsReader.readInt8();\n if (includeFlag === 1) {\n args.include = 'locking scripts';\n }\n else if (includeFlag === 2) {\n args.include = 'entire transactions';\n }\n else {\n args.include = undefined;\n }\n // Deserialize includeCustomInstructions\n const includeCustomInstructionsFlag = paramsReader.readInt8();\n if (includeCustomInstructionsFlag === -1) {\n args.includeCustomInstructions = undefined;\n }\n else {\n args.includeCustomInstructions =\n includeCustomInstructionsFlag === 1;\n }\n // Deserialize includeTags\n const includeTagsFlag = paramsReader.readInt8();\n if (includeTagsFlag === -1) {\n args.includeTags = undefined;\n }\n else {\n args.includeTags = includeTagsFlag === 1;\n }\n // Deserialize includeLabels\n const includeLabelsFlag = paramsReader.readInt8();\n if (includeLabelsFlag === -1) {\n args.includeLabels = undefined;\n }\n else {\n args.includeLabels = includeLabelsFlag === 1;\n }\n // Deserialize limit\n const limit = paramsReader.readVarIntNum();\n if (limit >= 0) {\n args.limit = limit;\n }\n else {\n args.limit = undefined;\n }\n // Deserialize offset\n const offset = paramsReader.readVarIntNum();\n if (offset >= 0) {\n args.offset = offset;\n }\n else {\n args.offset = undefined;\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const listOutputsResult = await this.wallet.listOutputs(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // totalOutputs\n resultWriter.writeVarIntNum(listOutputsResult.totalOutputs);\n // BEEF length and BEEF or -1\n if (listOutputsResult.BEEF != null) {\n resultWriter.writeVarIntNum(listOutputsResult.BEEF.length);\n resultWriter.write(listOutputsResult.BEEF);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // outputs\n for (const output of listOutputsResult.outputs) {\n // outpoint\n resultWriter.write(this.encodeOutpoint(output.outpoint));\n // satoshis\n resultWriter.writeVarIntNum(output.satoshis);\n // lockingScript\n if (output.lockingScript !== undefined) {\n const lockingScriptBytes = Utils.toArray(output.lockingScript, 'hex');\n resultWriter.writeVarIntNum(lockingScriptBytes.length);\n resultWriter.write(lockingScriptBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // customInstructions\n if (output.customInstructions !== undefined) {\n const customInstructionsBytes = Utils.toArray(output.customInstructions, 'utf8');\n resultWriter.writeVarIntNum(customInstructionsBytes.length);\n resultWriter.write(customInstructionsBytes);\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // tags\n if (output.tags !== undefined) {\n resultWriter.writeVarIntNum(output.tags.length);\n for (const tag of output.tags) {\n const tagBytes = Utils.toArray(tag, 'utf8');\n resultWriter.writeVarIntNum(tagBytes.length);\n resultWriter.write(tagBytes);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n // labels\n if (output.labels !== undefined) {\n resultWriter.writeVarIntNum(output.labels.length);\n for (const label of output.labels) {\n const labelBytes = Utils.toArray(label, 'utf8');\n resultWriter.writeVarIntNum(labelBytes.length);\n resultWriter.write(labelBytes);\n }\n }\n else {\n resultWriter.writeVarIntNum(-1);\n }\n }\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'relinquishOutput': {\n const args = {};\n // Deserialize basket\n const basketLength = paramsReader.readVarIntNum();\n const basketBytes = paramsReader.read(basketLength);\n args.basket = Utils.toUTF8(basketBytes);\n // Deserialize outpoint\n args.output = this.decodeOutpoint(paramsReader);\n // Call the method\n await this.wallet.relinquishOutput(args, originator);\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'getPublicKey': {\n const args = {};\n // Deserialize identityKey flag\n const identityKeyFlag = paramsReader.readUInt8();\n args.identityKey = identityKeyFlag === 1;\n if (args.identityKey !== true) {\n // Deserialize protocolID\n args.protocolID = this.decodeProtocolID(paramsReader);\n // Deserialize keyID\n args.keyID = this.decodeString(paramsReader);\n // Deserialize counterparty\n args.counterparty = this.decodeCounterparty(paramsReader);\n // Deserialize privilege parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength !== -1) {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n else {\n args.privilegedReason = undefined;\n }\n // Deserialize forSelf\n const forSelfFlag = paramsReader.readInt8();\n if (forSelfFlag === -1) {\n args.forSelf = undefined;\n }\n else {\n args.forSelf = forSelfFlag === 1;\n }\n }\n else {\n // Deserialize privilege parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength !== -1) {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n else {\n args.privilegedReason = undefined;\n }\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const getPublicKeyResult = await this.wallet.getPublicKey(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n const publicKeyBytes = Utils.toArray(getPublicKeyResult.publicKey, 'hex');\n responseWriter.write(publicKeyBytes);\n return responseWriter.toArray();\n }\n case 'encrypt': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize plaintext\n const plaintextLength = paramsReader.readVarIntNum();\n args.plaintext = paramsReader.read(plaintextLength);\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const encryptResult = await this.wallet.encrypt(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(encryptResult.ciphertext);\n return responseWriter.toArray();\n }\n case 'decrypt': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize ciphertext\n const ciphertextLength = paramsReader.readVarIntNum();\n args.ciphertext = paramsReader.read(ciphertextLength);\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const decryptResult = await this.wallet.decrypt(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(decryptResult.plaintext);\n return responseWriter.toArray();\n }\n case 'createHmac': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize data\n const dataLength = paramsReader.readVarIntNum();\n args.data = paramsReader.read(dataLength);\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const createHmacResult = await this.wallet.createHmac(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(createHmacResult.hmac);\n return responseWriter.toArray();\n }\n case 'verifyHmac': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize hmac\n args.hmac = paramsReader.read(32);\n // Deserialize data\n const dataLength = paramsReader.readVarIntNum();\n args.data = paramsReader.read(dataLength);\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n await this.wallet.verifyHmac(args, originator);\n // Serialize the result (no data to return)\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'createSignature': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize data or hashToDirectlySign\n const dataTypeFlag = paramsReader.readUInt8();\n if (dataTypeFlag === 1) {\n const dataLength = paramsReader.readVarIntNum();\n args.data = paramsReader.read(dataLength);\n }\n else if (dataTypeFlag === 2) {\n args.hashToDirectlySign = paramsReader.read(32);\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const createSignatureResult = await this.wallet.createSignature(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(createSignatureResult.signature);\n return responseWriter.toArray();\n }\n case 'verifySignature': {\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Deserialize forSelf\n const forSelfFlag = paramsReader.readInt8();\n if (forSelfFlag === -1) {\n args.forSelf = undefined;\n }\n else {\n args.forSelf = forSelfFlag === 1;\n }\n // Deserialize signature\n const signatureLength = paramsReader.readVarIntNum();\n args.signature = paramsReader.read(signatureLength);\n // Deserialize data or hashToDirectlyVerify\n const dataTypeFlag = paramsReader.readUInt8();\n if (dataTypeFlag === 1) {\n const dataLength = paramsReader.readVarIntNum();\n args.data = paramsReader.read(dataLength);\n }\n else if (dataTypeFlag === 2) {\n args.hashToDirectlyVerify = paramsReader.read(32);\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n await this.wallet.verifySignature(args, originator);\n // Serialize the result (no data to return)\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'isAuthenticated': {\n // No parameters to deserialize\n // Call the method\n const isAuthenticatedResult = await this.wallet.isAuthenticated({}, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.writeUInt8(isAuthenticatedResult.authenticated ? 1 : 0);\n return responseWriter.toArray();\n }\n case 'waitForAuthentication': {\n // No parameters to deserialize\n // Call the method\n await this.wallet.waitForAuthentication({}, originator);\n // Serialize the result (authenticated is always true)\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'getHeight': {\n // No parameters to deserialize\n // Call the method\n const getHeightResult = await this.wallet.getHeight({}, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.writeVarIntNum(getHeightResult.height);\n return responseWriter.toArray();\n }\n case 'getHeaderForHeight': {\n const args = {};\n // Deserialize height\n args.height = paramsReader.readVarIntNum();\n // Call the method\n const getHeaderResult = await this.wallet.getHeaderForHeight(args, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n const headerBytes = Utils.toArray(getHeaderResult.header, 'hex');\n responseWriter.write(headerBytes);\n return responseWriter.toArray();\n }\n case 'getNetwork': {\n // No parameters to deserialize\n // Call the method\n const getNetworkResult = await this.wallet.getNetwork({}, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.writeUInt8(getNetworkResult.network === 'mainnet' ? 0 : 1);\n return responseWriter.toArray();\n }\n case 'getVersion': {\n // No parameters to deserialize\n // Call the method\n const getVersionResult = await this.wallet.getVersion({}, originator);\n // Serialize the result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n const versionBytes = Utils.toArray(getVersionResult.version, 'utf8');\n responseWriter.write(versionBytes);\n return responseWriter.toArray();\n }\n case 'revealCounterpartyKeyLinkage': {\n const args = {};\n // Read privileged parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength === -1) {\n args.privilegedReason = undefined;\n }\n else {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n // Read counterparty public key\n const counterpartyBytes = paramsReader.read(33);\n args.counterparty = Utils.toHex(counterpartyBytes);\n // Read verifier public key\n const verifierBytes = paramsReader.read(33);\n args.verifier = Utils.toHex(verifierBytes);\n // Call the method\n const revealResult = await this.wallet.revealCounterpartyKeyLinkage(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // Write prover\n resultWriter.write(Utils.toArray(revealResult.prover, 'hex'));\n // Write verifier\n resultWriter.write(Utils.toArray(revealResult.verifier, 'hex'));\n // Write counterparty\n resultWriter.write(Utils.toArray(revealResult.counterparty, 'hex'));\n // Write revelationTime\n const revelationTimeBytes = Utils.toArray(revealResult.revelationTime, 'utf8');\n resultWriter.writeVarIntNum(revelationTimeBytes.length);\n resultWriter.write(revelationTimeBytes);\n // Write encryptedLinkage\n resultWriter.writeVarIntNum(revealResult.encryptedLinkage.length);\n resultWriter.write(revealResult.encryptedLinkage);\n // Write encryptedLinkageProof\n resultWriter.writeVarIntNum(revealResult.encryptedLinkageProof.length);\n resultWriter.write(revealResult.encryptedLinkageProof);\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'revealSpecificKeyLinkage': {\n // Deserialize key-related parameters and privileged parameters\n const args = this.decodeKeyRelatedParams(paramsReader);\n // Read verifier public key\n const verifierBytes = paramsReader.read(33);\n args.verifier = Utils.toHex(verifierBytes);\n // Call the method\n const revealResult = await this.wallet.revealSpecificKeyLinkage(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // Write prover\n resultWriter.write(Utils.toArray(revealResult.prover, 'hex'));\n // Write verifier\n resultWriter.write(Utils.toArray(revealResult.verifier, 'hex'));\n // Write counterparty\n resultWriter.write(Utils.toArray(revealResult.counterparty, 'hex'));\n // Write securityLevel\n resultWriter.writeUInt8(revealResult.protocolID[0]);\n // Write protocol string\n const protocolBytesOut = Utils.toArray(revealResult.protocolID[1], 'utf8');\n resultWriter.writeVarIntNum(protocolBytesOut.length);\n resultWriter.write(protocolBytesOut);\n // Write keyID\n const keyIDBytesOut = Utils.toArray(revealResult.keyID, 'utf8');\n resultWriter.writeVarIntNum(keyIDBytesOut.length);\n resultWriter.write(keyIDBytesOut);\n // Write encryptedLinkage\n resultWriter.writeVarIntNum(revealResult.encryptedLinkage.length);\n resultWriter.write(revealResult.encryptedLinkage);\n // Write encryptedLinkageProof\n resultWriter.writeVarIntNum(revealResult.encryptedLinkageProof.length);\n resultWriter.write(revealResult.encryptedLinkageProof);\n // Write proofType\n resultWriter.writeUInt8(revealResult.proofType);\n // Return success code and result\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'acquireCertificate': {\n const args = {};\n // Read args.type\n const typeBytes = paramsReader.read(32);\n args.type = Utils.toBase64(typeBytes);\n // args.certifier\n const certifierBytes = paramsReader.read(33);\n args.certifier = Utils.toHex(certifierBytes);\n // Read fields\n const fieldsLength = paramsReader.readVarIntNum();\n args.fields = {};\n for (let i = 0; i < fieldsLength; i++) {\n const fieldNameLength = paramsReader.readVarIntNum();\n const fieldNameBytes = paramsReader.read(fieldNameLength);\n const fieldName = Utils.toUTF8(fieldNameBytes);\n const fieldValueLength = paramsReader.readVarIntNum();\n const fieldValueBytes = paramsReader.read(fieldValueLength);\n const fieldValue = Utils.toUTF8(fieldValueBytes);\n args.fields[fieldName] = fieldValue;\n }\n // Read privileged parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength === -1) {\n args.privilegedReason = undefined;\n }\n else {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n // Read acquisitionProtocol\n const acquisitionProtocolFlag = paramsReader.readUInt8();\n args.acquisitionProtocol =\n acquisitionProtocolFlag === 1 ? 'direct' : 'issuance';\n if (args.acquisitionProtocol === 'direct') {\n // args.serialNumber\n const serialNumberBytes = paramsReader.read(32);\n args.serialNumber = Utils.toBase64(serialNumberBytes);\n // args.revocationOutpoint\n args.revocationOutpoint = this.decodeOutpoint(paramsReader);\n // args.signature\n const signatureLength = paramsReader.readVarIntNum();\n const signatureBytes = paramsReader.read(signatureLength);\n args.signature = Utils.toHex(signatureBytes);\n // args.keyringRevealer\n const keyringRevealerIdentifier = paramsReader.readUInt8();\n if (keyringRevealerIdentifier === 11) {\n args.keyringRevealer = 'certifier';\n }\n else {\n const keyringRevealerBytes = [keyringRevealerIdentifier].concat(paramsReader.read(32));\n args.keyringRevealer = Utils.toHex(keyringRevealerBytes);\n }\n // args.keyringForSubject\n const keyringEntriesLength = paramsReader.readVarIntNum();\n args.keyringForSubject = {};\n for (let i = 0; i < keyringEntriesLength; i++) {\n const fieldKeyLength = paramsReader.readVarIntNum();\n const fieldKeyBytes = paramsReader.read(fieldKeyLength);\n const fieldKey = Utils.toUTF8(fieldKeyBytes);\n const fieldValueLength = paramsReader.readVarIntNum();\n const fieldValueBytes = paramsReader.read(fieldValueLength);\n const fieldValue = Utils.toBase64(fieldValueBytes);\n args.keyringForSubject[fieldKey] = fieldValue;\n }\n }\n else {\n // args.certifierUrl\n const certifierUrlLength = paramsReader.readVarIntNum();\n const certifierUrlBytes = paramsReader.read(certifierUrlLength);\n args.certifierUrl = Utils.toUTF8(certifierUrlBytes);\n }\n // Call the method\n const acquireResult = await this.wallet.acquireCertificate(args, originator);\n // Serialize the certificate (assuming Certificate class is available)\n const cert = new Certificate(acquireResult.type, acquireResult.serialNumber, acquireResult.subject, acquireResult.certifier, acquireResult.revocationOutpoint, acquireResult.fields, acquireResult.signature);\n const certBin = cert.toBinary();\n // Return success code and certificate binary\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(certBin);\n return responseWriter.toArray();\n }\n case 'listCertificates': {\n const args = {};\n // Read certifiers\n const certifiersLength = paramsReader.readVarIntNum();\n args.certifiers = [];\n for (let i = 0; i < certifiersLength; i++) {\n const certifierBytes = paramsReader.read(33);\n args.certifiers.push(Utils.toHex(certifierBytes));\n }\n // Read types\n const typesLength = paramsReader.readVarIntNum();\n args.types = [];\n for (let i = 0; i < typesLength; i++) {\n const typeBytes = paramsReader.read(32);\n args.types.push(Utils.toBase64(typeBytes));\n }\n // Read limit and offset\n const limit = paramsReader.readVarIntNum();\n if (limit >= 0) {\n args.limit = limit;\n }\n else {\n args.limit = undefined;\n }\n const offset = paramsReader.readVarIntNum();\n if (offset >= 0) {\n args.offset = offset;\n }\n else {\n args.offset = undefined;\n }\n // Read privileged parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength === -1) {\n args.privilegedReason = undefined;\n }\n else {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n // Call the method\n const listResult = await this.wallet.listCertificates(args, originator);\n // Serialize the result\n const resultWriter = new Utils.Writer();\n // totalCertificates\n resultWriter.writeVarIntNum(listResult.totalCertificates);\n // certificates\n for (const cert of listResult.certificates) {\n const certificate = new Certificate(cert.type, cert.serialNumber, cert.subject, cert.certifier, cert.revocationOutpoint, cert.fields, cert.signature);\n const certBin = certificate.toBinary();\n // Write certificate binary length and data\n resultWriter.writeVarIntNum(certBin.length);\n resultWriter.write(certBin);\n if (cert.keyring && Object.keys(cert.keyring).length > 0) {\n resultWriter.writeInt8(1); // Flag indicating keyring is present\n const keyringEntries = Object.entries(cert.keyring);\n resultWriter.writeVarIntNum(keyringEntries.length);\n for (const [fieldName, fieldValue] of keyringEntries) {\n const fieldNameBytes = Utils.toArray(fieldName, 'utf8');\n resultWriter.writeVarIntNum(fieldNameBytes.length);\n resultWriter.write(fieldNameBytes);\n const fieldValueBytes = Utils.toArray(fieldValue, 'base64');\n resultWriter.writeVarIntNum(fieldValueBytes.length);\n resultWriter.write(fieldValueBytes);\n }\n }\n else {\n resultWriter.writeInt8(0); // Flag indicating no keyring\n }\n const verifierBytes = Utils.toArray(cert.verifier, 'hex');\n resultWriter.writeVarIntNum(verifierBytes.length);\n resultWriter.write(verifierBytes);\n }\n // Return the response\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'proveCertificate': {\n const args = {};\n // Read certificate\n const cert = {};\n // Read type\n const typeBytes = paramsReader.read(32);\n cert.type = Utils.toBase64(typeBytes);\n // Read subject\n const subjectBytes = paramsReader.read(33);\n cert.subject = Utils.toHex(subjectBytes);\n // Read serialNumber\n const serialNumberBytes = paramsReader.read(32);\n cert.serialNumber = Utils.toBase64(serialNumberBytes);\n // Read certifier\n const certifierBytes = paramsReader.read(33);\n cert.certifier = Utils.toHex(certifierBytes);\n // Read revocationOutpoint\n cert.revocationOutpoint = this.decodeOutpoint(paramsReader);\n // Read signature\n const signatureLength = paramsReader.readVarIntNum();\n const signatureBytes = paramsReader.read(signatureLength);\n cert.signature = Utils.toHex(signatureBytes);\n // Read fields\n const fieldsLength = paramsReader.readVarIntNum();\n cert.fields = {};\n for (let i = 0; i < fieldsLength; i++) {\n const fieldNameLength = paramsReader.readVarIntNum();\n const fieldNameBytes = paramsReader.read(fieldNameLength);\n const fieldName = Utils.toUTF8(fieldNameBytes);\n const fieldValueLength = paramsReader.readVarIntNum();\n const fieldValueBytes = paramsReader.read(fieldValueLength);\n const fieldValue = Utils.toUTF8(fieldValueBytes);\n cert.fields[fieldName] = fieldValue;\n }\n args.certificate = cert;\n // Read fields to reveal\n const fieldsToRevealLength = paramsReader.readVarIntNum();\n args.fieldsToReveal = [];\n for (let i = 0; i < fieldsToRevealLength; i++) {\n const fieldNameLength = paramsReader.readVarIntNum();\n const fieldNameBytes = paramsReader.read(fieldNameLength);\n const fieldName = Utils.toUTF8(fieldNameBytes);\n args.fieldsToReveal.push(fieldName);\n }\n // Read verifier\n const verifierBytes = paramsReader.read(33);\n args.verifier = Utils.toHex(verifierBytes);\n // Read privileged parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength === -1) {\n args.privilegedReason = undefined;\n }\n else {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n // Call the method\n const proveResult = await this.wallet.proveCertificate(args, originator);\n // Serialize keyringForVerifier\n const resultWriter = new Utils.Writer();\n const keyringEntries = Object.entries(proveResult.keyringForVerifier);\n resultWriter.writeVarIntNum(keyringEntries.length);\n for (const [fieldName, fieldValue] of keyringEntries) {\n const fieldNameBytes = Utils.toArray(fieldName, 'utf8');\n resultWriter.writeVarIntNum(fieldNameBytes.length);\n resultWriter.write(fieldNameBytes);\n const fieldValueBytes = Utils.toArray(fieldValue, 'base64');\n resultWriter.writeVarIntNum(fieldValueBytes.length);\n resultWriter.write(fieldValueBytes);\n }\n // Return the response\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(resultWriter.toArray());\n return responseWriter.toArray();\n }\n case 'relinquishCertificate': {\n const args = {};\n // Read type\n const typeBytes = paramsReader.read(32);\n args.type = Utils.toBase64(typeBytes);\n // Read serialNumber\n const serialNumberBytes = paramsReader.read(32);\n args.serialNumber = Utils.toBase64(serialNumberBytes);\n // Read certifier\n const certifierBytes = paramsReader.read(33);\n args.certifier = Utils.toHex(certifierBytes);\n // Call the method\n await this.wallet.relinquishCertificate(args, originator);\n // Return success code\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n return responseWriter.toArray();\n }\n case 'discoverByIdentityKey': {\n const args = {};\n // Read identityKey\n const identityKeyBytes = paramsReader.read(33);\n args.identityKey = Utils.toHex(identityKeyBytes);\n // Read limit and offset\n const limit = paramsReader.readVarIntNum();\n if (limit >= 0) {\n args.limit = limit;\n }\n else {\n args.limit = undefined;\n }\n const offset = paramsReader.readVarIntNum();\n if (offset >= 0) {\n args.offset = offset;\n }\n else {\n args.offset = undefined;\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const discoverResult = await this.wallet.discoverByIdentityKey(args, originator);\n // Serialize the result\n const result = this.serializeDiscoveryResult(discoverResult);\n // Return the response\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(result);\n return responseWriter.toArray();\n }\n case 'discoverByAttributes': {\n const args = {};\n // Read attributes\n const attributesLength = paramsReader.readVarIntNum();\n args.attributes = {};\n for (let i = 0; i < attributesLength; i++) {\n const fieldKeyLength = paramsReader.readVarIntNum();\n const fieldKeyBytes = paramsReader.read(fieldKeyLength);\n const fieldKey = Utils.toUTF8(fieldKeyBytes);\n const fieldValueLength = paramsReader.readVarIntNum();\n const fieldValueBytes = paramsReader.read(fieldValueLength);\n const fieldValue = Utils.toUTF8(fieldValueBytes);\n args.attributes[fieldKey] = fieldValue;\n }\n // Read limit and offset\n const limit = paramsReader.readVarIntNum();\n if (limit >= 0) {\n args.limit = limit;\n }\n else {\n args.limit = undefined;\n }\n const offset = paramsReader.readVarIntNum();\n if (offset >= 0) {\n args.offset = offset;\n }\n else {\n args.offset = undefined;\n }\n // Deserialize seekPermission\n const seekPermission = paramsReader.readInt8();\n if (seekPermission >= 0) {\n args.seekPermission = seekPermission === 1;\n }\n else {\n args.seekPermission = undefined;\n }\n // Call the method\n const discoverResult = await this.wallet.discoverByAttributes(args, originator);\n // Serialize the result\n const result = this.serializeDiscoveryResult(discoverResult);\n // Return the response\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(0); // errorByte = 0\n responseWriter.write(result);\n return responseWriter.toArray();\n }\n default:\n throw new Error(`Method ${callName} not implemented`);\n }\n }\n catch (err) {\n const responseWriter = new Utils.Writer();\n responseWriter.writeUInt8(typeof err.code === 'number' ? err.code : 1); // errorCode = 1 (generic error)\n // Serialize the error message\n const errorMessage = typeof err.message === 'string' ? err.message : 'Unknown error';\n const errorMessageBytes = Utils.toArray(errorMessage, 'utf8');\n responseWriter.writeVarIntNum(errorMessageBytes.length);\n responseWriter.write(errorMessageBytes);\n // Serialize the stack trace\n const stackTrace = typeof err.stack === 'string' ? err.stack : '';\n const stackTraceBytes = Utils.toArray(stackTrace, 'utf8');\n responseWriter.writeVarIntNum(stackTraceBytes.length);\n responseWriter.write(stackTraceBytes);\n return responseWriter.toArray();\n }\n }\n decodeProtocolID(reader) {\n const securityLevel = reader.readUInt8();\n const protocolLength = reader.readVarIntNum();\n const protocolBytes = reader.read(protocolLength);\n const protocolString = Utils.toUTF8(protocolBytes);\n return [securityLevel, protocolString];\n }\n decodeString(reader) {\n const length = reader.readVarIntNum();\n const bytes = reader.read(length);\n return Utils.toUTF8(bytes);\n }\n decodeCounterparty(reader) {\n const counterpartyFlag = reader.readUInt8();\n if (counterpartyFlag === 11) {\n return 'self';\n }\n else if (counterpartyFlag === 12) {\n return 'anyone';\n }\n else if (counterpartyFlag === 0) {\n return undefined;\n }\n else {\n const counterpartyRemainingBytes = reader.read(32);\n return Utils.toHex([counterpartyFlag, ...counterpartyRemainingBytes]);\n }\n }\n serializeDiscoveryResult(discoverResult) {\n const resultWriter = new Utils.Writer();\n // totalCertificates\n resultWriter.writeVarIntNum(discoverResult.totalCertificates);\n // certificates\n for (const cert of discoverResult.certificates) {\n // Serialize certificate binary\n const certificate = new Certificate(cert.type, cert.serialNumber, cert.subject, cert.certifier, cert.revocationOutpoint, cert.fields, cert.signature);\n const certBin = certificate.toBinary();\n // Write certificate binary length and data\n resultWriter.writeVarIntNum(certBin.length);\n resultWriter.write(certBin);\n // Serialize certifierInfo\n const nameBytes = Utils.toArray(cert.certifierInfo.name, 'utf8');\n resultWriter.writeVarIntNum(nameBytes.length);\n resultWriter.write(nameBytes);\n const iconUrlBytes = Utils.toArray(cert.certifierInfo.iconUrl, 'utf8');\n resultWriter.writeVarIntNum(iconUrlBytes.length);\n resultWriter.write(iconUrlBytes);\n const descriptionBytes = Utils.toArray(cert.certifierInfo.description, 'utf8');\n resultWriter.writeVarIntNum(descriptionBytes.length);\n resultWriter.write(descriptionBytes);\n resultWriter.writeUInt8(cert.certifierInfo.trust);\n // Serialize publiclyRevealedKeyring\n const publicKeyringEntries = Object.entries(cert.publiclyRevealedKeyring);\n resultWriter.writeVarIntNum(publicKeyringEntries.length);\n for (const [fieldName, fieldValue] of publicKeyringEntries) {\n const fieldNameBytes = Utils.toArray(fieldName, 'utf8');\n resultWriter.writeVarIntNum(fieldNameBytes.length);\n resultWriter.write(fieldNameBytes);\n const fieldValueBytes = Utils.toArray(fieldValue, 'base64');\n resultWriter.writeVarIntNum(fieldValueBytes.length);\n resultWriter.write(fieldValueBytes);\n }\n // Serialize decryptedFields\n const decryptedFieldEntries = Object.entries(cert.decryptedFields);\n resultWriter.writeVarIntNum(decryptedFieldEntries.length);\n for (const [fieldName, fieldValue] of decryptedFieldEntries) {\n const fieldNameBytes = Utils.toArray(fieldName, 'utf8');\n resultWriter.writeVarIntNum(fieldNameBytes.length);\n resultWriter.write(fieldNameBytes);\n const fieldValueBytes = Utils.toArray(fieldValue, 'utf8');\n resultWriter.writeVarIntNum(fieldValueBytes.length);\n resultWriter.write(fieldValueBytes);\n }\n }\n return resultWriter.toArray();\n }\n decodeKeyRelatedParams(paramsReader) {\n const args = {};\n // Read protocolID\n args.protocolID = this.decodeProtocolID(paramsReader);\n // Read keyID\n const keyIDLength = paramsReader.readVarIntNum();\n const keyIDBytes = paramsReader.read(keyIDLength);\n args.keyID = Utils.toUTF8(keyIDBytes);\n // Read counterparty\n args.counterparty = this.decodeCounterparty(paramsReader);\n // Read privileged parameters\n const privilegedFlag = paramsReader.readInt8();\n if (privilegedFlag === -1) {\n args.privileged = undefined;\n }\n else {\n args.privileged = privilegedFlag === 1;\n }\n const privilegedReasonLength = paramsReader.readInt8();\n if (privilegedReasonLength === -1) {\n args.privilegedReason = undefined;\n }\n else {\n const privilegedReasonBytes = paramsReader.read(privilegedReasonLength);\n args.privilegedReason = Utils.toUTF8(privilegedReasonBytes);\n }\n return args;\n }\n}\n//# sourceMappingURL=WalletWireProcessor.js.map","import Certificate from './Certificate.js';\nimport * as Utils from '../../primitives/utils.js';\nimport SymmetricKey from '../../primitives/SymmetricKey.js';\nimport Random from '../../primitives/Random.js';\n/**\n * MasterCertificate extends the base Certificate class to manage a master keyring, enabling the creation of verifiable certificates.\n *\n * It allows for the selective disclosure of certificate fields by creating a `VerifiableCertificate` for a specific verifier.\n * The `MasterCertificate` can securely decrypt each master key and re-encrypt it for a verifier, creating a customized\n * keyring containing only the keys necessary for the verifier to access designated fields.\n *\n */\nexport class MasterCertificate extends Certificate {\n masterKeyring;\n constructor(type, serialNumber, subject, certifier, revocationOutpoint, fields, masterKeyring, signature) {\n super(type, serialNumber, subject, certifier, revocationOutpoint, fields, signature);\n // Ensure every field in `fields` is a string and has a corresponding key in `masterKeyring`\n for (const fieldName of Object.keys(fields)) {\n if (masterKeyring[fieldName] === undefined || masterKeyring[fieldName] === '') {\n throw new Error(`Master keyring must contain a value for every field. Missing or empty key for field: \"${fieldName}\".`);\n }\n }\n this.masterKeyring = masterKeyring;\n }\n /**\n * Encrypts certificate fields for a subject and generates a master keyring.\n * This method returns a master keyring tied to a specific certifier or subject who will validate\n * and sign off on the fields, along with the encrypted certificate fields.\n *\n * @param {ProtoWallet} creatorWallet - The wallet of the creator responsible for encrypting the fields.\n * @param {WalletCounterparty} certifierOrSubject - The certifier or subject who will validate the certificate fields.\n * @param {Record<CertificateFieldNameUnder50Bytes, string>} fields - A record of certificate field names (under 50 bytes) mapped to their values.\n * @param {BooleanDefaultFalse} [privileged] - Whether this is a privileged request.\n * @param {DescriptionString5to50Bytes} [privilegedReason] - Reason provided for privileged access, required if this is a privileged operation. *\n * @returns {Promise<CreateCertificateFieldsResult>} A promise resolving to an object containing:\n * - `certificateFields` {Record<CertificateFieldNameUnder50Bytes, Base64String>}:\n * The encrypted certificate fields.\n * - `masterKeyring` {Record<CertificateFieldNameUnder50Bytes, Base64String>}:\n * The master keyring containing encrypted revelation keys for each field.\n */\n static async createCertificateFields(creatorWallet, certifierOrSubject, fields, privileged, privilegedReason) {\n const certificateFields = {};\n const masterKeyring = {};\n for (const [fieldName, fieldValue] of Object.entries(fields)) {\n const fieldSymmetricKey = SymmetricKey.fromRandom();\n const encryptedFieldValue = fieldSymmetricKey.encrypt(Utils.toArray(fieldValue, 'utf8'));\n certificateFields[fieldName] = Utils.toBase64(encryptedFieldValue);\n const { ciphertext: encryptedFieldRevelationKey } = await creatorWallet.encrypt({\n plaintext: fieldSymmetricKey.toArray(),\n ...Certificate.getCertificateFieldEncryptionDetails(fieldName), // Only fieldName used on MasterCertificate\n counterparty: certifierOrSubject,\n privileged,\n privilegedReason\n });\n masterKeyring[fieldName] = Utils.toBase64(encryptedFieldRevelationKey);\n }\n return {\n certificateFields,\n masterKeyring\n };\n }\n /**\n * Creates a keyring for a verifier, enabling them to decrypt specific certificate fields.\n * This method decrypts the master field keys for the specified fields and re-encrypts them\n * for the verifier's identity key. The result is a keyring containing the keys necessary\n * for the verifier to access the designated fields.\n *\n * @param {ProtoWallet} subjectWallet - The wallet instance of the subject, used to decrypt and re-encrypt field keys.\n * @param {WalletCounterparty} verifier - The verifier who will receive access to the selectively revealed fields. Can be an identity key as hex, 'anyone', or 'self'.\n * @param {string[]} fieldsToReveal - An array of field names to be revealed to the verifier. Must be a subset of the certificate's fields.\n * @param {string} [originator] - Optional originator identifier, used if additional context is needed for decryption and encryption operations.\n * @returns {Promise<Record<CertificateFieldNameUnder50Bytes, string>>} - A keyring mapping field names to encrypted field revelation keys, allowing the verifier to decrypt specified fields.\n * @param {BooleanDefaultFalse} [privileged] - Whether this is a privileged request.\n * @param {DescriptionString5to50Bytes} [privilegedReason] - Reason provided for privileged access, required if this is a privileged operation. *\n * @throws {Error} Throws an error if:\n * - fieldsToReveal is not an array of strings.\n * - A field in `fieldsToReveal` does not exist in the certificate.\n * - The decrypted master field key fails to decrypt the corresponding field (indicating an invalid key).\n */\n static async createKeyringForVerifier(subjectWallet, certifier, verifier, fields, fieldsToReveal, masterKeyring, serialNumber, privileged, privilegedReason) {\n if (!Array.isArray(fieldsToReveal)) {\n throw new Error('fieldsToReveal must be an array of strings');\n }\n const fieldRevelationKeyring = {};\n for (const fieldName of fieldsToReveal) {\n // Make sure that fields to reveal is a subset of the certificate fields\n if (fields[fieldName] === undefined || fields[fieldName] === null || fields[fieldName] === '') {\n throw new Error(`Fields to reveal must be a subset of the certificate fields. Missing the \"${fieldName}\" field.`);\n }\n // Decrypt the master field key and verify that derived key actually decrypts requested field\n const masterFieldKey = (await this.decryptField(subjectWallet, masterKeyring, fieldName, fields[fieldName], certifier, privileged, privilegedReason)).fieldRevelationKey;\n // Encrypt derived fieldRevelationKey for verifier\n const { ciphertext: encryptedFieldRevelationKey } = await subjectWallet.encrypt({\n plaintext: masterFieldKey,\n ...Certificate.getCertificateFieldEncryptionDetails(fieldName, serialNumber),\n counterparty: verifier,\n privileged,\n privilegedReason\n });\n // Add encryptedFieldRevelationKey to fieldRevelationKeyring\n fieldRevelationKeyring[fieldName] = Utils.toBase64(encryptedFieldRevelationKey);\n }\n // Return the field revelation keyring which can be used to create a verifiable certificate for a verifier.\n return fieldRevelationKeyring;\n }\n /**\n * Issues a new MasterCertificate for a specified subject.\n *\n * This method generates a certificate containing encrypted fields and a keyring\n * for the subject to decrypt all fields. Each field is encrypted with a randomly\n * generated symmetric key, which is then encrypted for the subject. The certificate\n * can also includes a revocation outpoint to manage potential revocation.\n *\n * @param {ProtoWallet} certifierWallet - The wallet of the certifier, used to sign the certificate and encrypt field keys.\n * @param {WalletCounterparty} subject - The subject for whom the certificate is issued.\n * @param {Record<CertificateFieldNameUnder50Bytes, string>} fields - Unencrypted certificate fields to include, with their names and values.\n * @param {string} certificateType - The type of certificate being issued.\n * @param {function(string, Record<CertificateFieldNameUnder50Bytes, string>?): Promise<string>} getRevocationOutpoint -\n * Optional function to obtain a revocation outpoint for the certificate. Defaults to a placeholder.\n * @param {function(string): Promise<void>} updateProgress - Optional callback for reporting progress updates during the operation. Defaults to a no-op.\n * @returns {Promise<MasterCertificate>} - A signed MasterCertificate instance containing the encrypted fields and subject specific keyring.\n *\n * @throws {Error} Throws an error if any operation (e.g., encryption, signing) fails during certificate issuance.\n */\n static async issueCertificateForSubject(certifierWallet, subject, fields, certificateType, getRevocationOutpoint = async (_serial) => {\n void _serial; // Explicitly acknowledge unused parameter\n return '00'.repeat(32);\n }, serialNumber) {\n // 1. Generate a random serialNumber if not provided\n const finalSerialNumber = serialNumber ?? Utils.toBase64(Random(32));\n // 2. Create encrypted certificate fields and associated master keyring\n const { certificateFields, masterKeyring } = await this.createCertificateFields(certifierWallet, subject, fields);\n // 3. Obtain a revocation outpoint\n const revocationOutpoint = await getRevocationOutpoint(finalSerialNumber);\n let subjectIdentityKey;\n if (subject === 'self') {\n subjectIdentityKey = (await certifierWallet.getPublicKey({ identityKey: true })).publicKey;\n }\n else {\n subjectIdentityKey = subject;\n }\n // 4. Create new MasterCertificate instance\n const certificate = new MasterCertificate(certificateType, finalSerialNumber, subjectIdentityKey, (await certifierWallet.getPublicKey({ identityKey: true })).publicKey, revocationOutpoint, certificateFields, masterKeyring);\n // 5. Sign and return the new MasterCertificate certifying the subject.\n await certificate.sign(certifierWallet);\n return certificate;\n }\n /**\n * Decrypts all fields in the MasterCertificate using the subject's or certifier's wallet.\n *\n * This method allows the subject or certifier to decrypt the `masterKeyring` and retrieve\n * the encryption keys for each field, which are then used to decrypt the corresponding field values.\n * The counterparty used for decryption depends on how the certificate fields were created:\n * - If the certificate is self-signed, the counterparty should be set to 'self'.\n * - Otherwise, the counterparty should always be the other party involved in the certificate issuance process (the subject or certifier).\n *\n * @param {ProtoWallet} subjectOrCertifierWallet - The wallet of the subject or certifier, used to decrypt the master keyring and field values.\n * @param {Record<CertificateFieldNameUnder50Bytes, Base64String>} masterKeyring - A record containing encrypted keys for each field.\n * @param {Record<CertificateFieldNameUnder50Bytes, Base64String>} fields - A record of encrypted field names and their values.\n * @param {WalletCounterparty} counterparty - The counterparty responsible for creating or signing the certificate. For self-signed certificates, use 'self'.\n * @param {BooleanDefaultFalse} [privileged] - Whether this is a privileged request.\n * @param {DescriptionString5to50Bytes} [privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.\n * @returns {Promise<Record<CertificateFieldNameUnder50Bytes, string>>} A promise resolving to a record of field names and their decrypted values in plaintext.\n *\n * @throws {Error} Throws an error if the `masterKeyring` is invalid or if decryption fails for any field.\n */\n static async decryptFields(subjectOrCertifierWallet, masterKeyring, fields, counterparty, privileged, privilegedReason) {\n if (masterKeyring == null || Object.keys(masterKeyring).length === 0) {\n throw new Error('A MasterCertificate must have a valid masterKeyring!');\n }\n try {\n const decryptedFields = {};\n // Note: we want to iterate through all fields, not just masterKeyring keys/value pairs.\n for (const fieldName of Object.keys(fields)) {\n decryptedFields[fieldName] = (await this.decryptField(subjectOrCertifierWallet, masterKeyring, fieldName, fields[fieldName], counterparty, privileged, privilegedReason)).decryptedFieldValue;\n }\n return decryptedFields;\n }\n catch {\n throw new Error('Failed to decrypt all master certificate fields.');\n }\n }\n static async decryptField(subjectOrCertifierWallet, masterKeyring, fieldName, fieldValue, counterparty, privileged, privilegedReason) {\n if (masterKeyring == null || Object.keys(masterKeyring).length === 0) {\n throw new Error('A MasterCertificate must have a valid masterKeyring!');\n }\n try {\n const { plaintext: fieldRevelationKey } = await subjectOrCertifierWallet.decrypt({\n ciphertext: Utils.toArray(masterKeyring[fieldName], 'base64'),\n ...Certificate.getCertificateFieldEncryptionDetails(fieldName), // Only fieldName used on MasterCertificate\n counterparty,\n privileged,\n privilegedReason\n });\n const decryptedFieldValue = new SymmetricKey(fieldRevelationKey).decrypt(Utils.toArray(fieldValue, 'base64'));\n return {\n fieldRevelationKey,\n decryptedFieldValue: Utils.toUTF8(decryptedFieldValue)\n };\n }\n catch {\n throw new Error('Failed to decrypt certificate field!');\n }\n }\n}\n//# sourceMappingURL=MasterCertificate.js.map","import SymmetricKey from '../../primitives/SymmetricKey.js';\nimport * as Utils from '../../primitives/utils.js';\nimport Certificate from './Certificate.js';\n/**\n * VerifiableCertificate extends the Certificate class, adding functionality to manage a verifier-specific keyring.\n * This keyring allows selective decryption of certificate fields for authorized verifiers.\n */\nexport class VerifiableCertificate extends Certificate {\n keyring;\n decryptedFields;\n constructor(type, serialNumber, subject, certifier, revocationOutpoint, fields, keyring, signature, decryptedFields) {\n super(type, serialNumber, subject, certifier, revocationOutpoint, fields, signature);\n this.keyring = keyring;\n this.decryptedFields = decryptedFields;\n }\n /**\n *\n * @param {WalletCertificate} certificate – The source certificate that was issued and signed by the certifier.\n * @param {Record<CertificateFieldNameUnder50Bytes, string>} keyring – A allows the verifier to decrypt selected certificate fields.\n * @returns {VerifiableCertificate} – A fully-formed instance containing the\n * original certificate data plus the supplied keyring.\n */\n static fromCertificate(certificate, keyring) {\n return new VerifiableCertificate(certificate.type, certificate.serialNumber, certificate.subject, certificate.certifier, certificate.revocationOutpoint, certificate.fields, keyring, certificate.signature);\n }\n /**\n * Decrypts selectively revealed certificate fields using the provided keyring and verifier wallet\n * @param {ProtoWallet} verifierWallet - The wallet instance of the certificate's verifier, used to decrypt field keys.\n * @returns {Promise<Record<CertificateFieldNameUnder50Bytes, string>>} - A promise that resolves to an object where each key is a field name and each value is the decrypted field value as a string.\n * @param {BooleanDefaultFalse} [privileged] - Whether this is a privileged request.\n * @param {DescriptionString5to50Bytes} [privilegedReason] - Reason provided for privileged access, required if this is a privileged operation.\n * @throws {Error} Throws an error if any of the decryption operations fail, with a message indicating the failure context.\n */\n async decryptFields(verifierWallet, privileged, privilegedReason, originator) {\n if (this.keyring == null || Object.keys(this.keyring).length === 0) {\n throw new Error('A keyring is required to decrypt certificate fields for the verifier.');\n }\n try {\n const decryptedFields = {};\n for (const fieldName in this.keyring) {\n const { plaintext: fieldRevelationKey } = await verifierWallet.decrypt({\n ciphertext: Utils.toArray(this.keyring[fieldName], 'base64'),\n ...Certificate.getCertificateFieldEncryptionDetails(fieldName, this.serialNumber),\n counterparty: this.subject,\n privileged,\n privilegedReason\n }, originator);\n const fieldValue = new SymmetricKey(fieldRevelationKey).decrypt(Utils.toArray(this.fields[fieldName], 'base64'));\n decryptedFields[fieldName] = Utils.toUTF8(fieldValue);\n }\n return decryptedFields;\n }\n catch (error) {\n throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(error instanceof Error ? error.message : error)}`);\n }\n }\n}\n//# sourceMappingURL=VerifiableCertificate.js.map","//@ts-nocheck\nimport PrivateKey from '../../../primitives/PrivateKey.js';\nimport { ProtoWallet, KeyDeriver, CachedKeyDeriver } from '../../../wallet/index.js';\n// Test Mock wallet which extends ProtoWallet but still implements Wallet interface\n// Unsupported methods throw\nexport class CompletedProtoWallet extends ProtoWallet {\n keyDeriver;\n constructor(rootKeyOrKeyDeriver) {\n super(rootKeyOrKeyDeriver);\n if (rootKeyOrKeyDeriver instanceof KeyDeriver) {\n this.keyDeriver = rootKeyOrKeyDeriver;\n }\n else if (typeof rootKeyOrKeyDeriver === 'string' ||\n rootKeyOrKeyDeriver instanceof PrivateKey) {\n this.keyDeriver = new CachedKeyDeriver(rootKeyOrKeyDeriver);\n }\n else {\n throw new Error('Invalid key deriver provided');\n }\n }\n async isAuthenticated() {\n throw new Error('not implemented');\n }\n async waitForAuthentication() {\n throw new Error('not implemented');\n }\n async getNetwork() {\n throw new Error('not implemented');\n }\n async getVersion() {\n throw new Error('not implemented');\n }\n async getPublicKey(args) {\n if (args.privileged === true) {\n throw new Error('no privilege support');\n }\n if (args.identityKey === true) {\n if (this.keyDeriver === null || this.keyDeriver === undefined) {\n throw new Error('keyDeriver is not initialized');\n }\n return { publicKey: this.keyDeriver.rootKey.toPublicKey().toString() };\n }\n else {\n if (args.protocolID == null || typeof args.keyID !== 'string' || args.keyID.trim() === '') {\n throw new Error('protocolID and keyID are required if identityKey is false or undefined.');\n }\n if (this.keyDeriver === null || this.keyDeriver === undefined) {\n throw new Error('keyDeriver is not initialized');\n }\n return {\n publicKey: this.keyDeriver\n .derivePublicKey(args.protocolID, args.keyID, typeof args.counterparty === 'string' && args.counterparty.trim() !== ''\n ? args.counterparty\n : 'self', Boolean(args.forSelf))\n .toString()\n };\n }\n }\n async createAction() {\n throw new Error('not implemented');\n }\n async signAction() {\n throw new Error('not implemented');\n }\n async abortAction() {\n throw new Error('not implemented');\n }\n async listActions() {\n throw new Error('not implemented');\n }\n async internalizeAction() {\n throw new Error('not implemented');\n }\n async listOutputs() {\n throw new Error('not implemented');\n }\n async relinquishOutput() {\n throw new Error('not implemented');\n }\n async acquireCertificate() {\n throw new Error('not implemented');\n }\n async listCertificates() {\n throw new Error('not implemented');\n }\n async proveCertificate() {\n throw new Error('not implemented');\n }\n async relinquishCertificate() {\n throw new Error('not implemented');\n }\n async discoverByIdentityKey() {\n throw new Error('not implemented');\n }\n async discoverByAttributes() {\n throw new Error('not implemented');\n }\n async getHeight() {\n throw new Error('not implemented');\n }\n async getHeaderForHeight() {\n throw new Error('not implemented');\n }\n}\n//# sourceMappingURL=CompletedProtoWallet.js.map","/**\n * Manages sessions for peers, allowing multiple concurrent sessions\n * per identity key. Primary lookup is always by `sessionNonce`.\n */\nexport class SessionManager {\n /**\n * Maps sessionNonce -> PeerSession\n */\n sessionNonceToSession;\n /**\n * Maps identityKey -> Set of sessionNonces\n */\n identityKeyToNonces;\n constructor() {\n this.sessionNonceToSession = new Map();\n this.identityKeyToNonces = new Map();\n }\n /**\n * Adds a session to the manager, associating it with its sessionNonce,\n * and also with its peerIdentityKey (if any).\n *\n * This does NOT overwrite existing sessions for the same peerIdentityKey,\n * allowing multiple concurrent sessions for the same peer.\n *\n * @param {PeerSession} session - The peer session to add.\n */\n addSession(session) {\n if (typeof session.sessionNonce !== 'string') {\n throw new Error('Invalid session: sessionNonce is required to add a session.');\n }\n // Use the sessionNonce as the primary key\n this.sessionNonceToSession.set(session.sessionNonce, session);\n // Also track it by identity key if present\n if (typeof session.peerIdentityKey === 'string') {\n let nonces = this.identityKeyToNonces.get(session.peerIdentityKey);\n if (nonces == null) {\n nonces = new Set();\n this.identityKeyToNonces.set(session.peerIdentityKey, nonces);\n }\n nonces.add(session.sessionNonce);\n }\n }\n /**\n * Updates a session in the manager (primarily by re-adding it),\n * ensuring we record the latest data (e.g., isAuthenticated, lastUpdate, etc.).\n *\n * @param {PeerSession} session - The peer session to update.\n */\n updateSession(session) {\n // Remove the old references (if any) and re-add\n this.removeSession(session);\n this.addSession(session);\n }\n /**\n * Retrieves a session based on a given identifier, which can be:\n * - A sessionNonce, or\n * - A peerIdentityKey.\n *\n * If it is a `sessionNonce`, returns that exact session.\n * If it is a `peerIdentityKey`, returns the \"best\" (e.g. most recently updated,\n * authenticated) session associated with that peer, if any.\n *\n * @param {string} identifier - The identifier for the session (sessionNonce or peerIdentityKey).\n * @returns {PeerSession | undefined} - The matching peer session, or undefined if not found.\n */\n getSession(identifier) {\n // Check if this identifier is directly a sessionNonce\n const direct = this.sessionNonceToSession.get(identifier);\n if (direct != null) {\n return direct;\n }\n // Otherwise, interpret the identifier as an identity key\n const nonces = this.identityKeyToNonces.get(identifier);\n if ((nonces == null) || nonces.size === 0) {\n return undefined;\n }\n // Pick the \"best\" session. One sensible approach:\n // - Choose an authenticated session if available\n // - Among them, pick the most recently updated\n let best;\n for (const nonce of nonces) {\n const s = this.sessionNonceToSession.get(nonce);\n if (s == null)\n continue;\n // We can prefer authenticated sessions\n if (best == null) {\n best = s;\n }\n else {\n // If we want the \"most recently updated\" AND isAuthenticated\n if ((s.lastUpdate ?? 0) > (best.lastUpdate ?? 0)) {\n best = s;\n }\n }\n }\n // Optionally, you could also filter out isAuthenticated===false if you only want\n // an authenticated session. But for our usage, let's return the latest any session.\n return best;\n }\n /**\n * Removes a session from the manager by clearing all associated identifiers.\n *\n * @param {PeerSession} session - The peer session to remove.\n */\n removeSession(session) {\n if (typeof session.sessionNonce === 'string') {\n this.sessionNonceToSession.delete(session.sessionNonce);\n }\n if (typeof session.peerIdentityKey === 'string') {\n const nonces = this.identityKeyToNonces.get(session.peerIdentityKey);\n if (nonces != null) {\n nonces.delete(session.sessionNonce ?? '');\n if (nonces.size === 0) {\n this.identityKeyToNonces.delete(session.peerIdentityKey);\n }\n }\n }\n }\n /**\n * Checks if a session exists for a given identifier (either sessionNonce or identityKey).\n *\n * @param {string} identifier - The identifier to check.\n * @returns {boolean} - True if the session exists, false otherwise.\n */\n hasSession(identifier) {\n const direct = this.sessionNonceToSession.has(identifier);\n if (direct)\n return true;\n // if not directly a nonce, interpret as identityKey\n const nonces = this.identityKeyToNonces.get(identifier);\n return !(nonces == null) && nonces.size > 0;\n }\n}\n//# sourceMappingURL=SessionManager.js.map","import * as Utils from '../../primitives/utils.js';\n/**\n * Verifies a nonce derived from a wallet\n * @param nonce - A nonce to verify as a base64 string.\n * @param wallet\n * @param counterparty - The counterparty to the nonce creation. Defaults to 'self'.\n * @returns The status of the validation\n */\nexport async function verifyNonce(nonce, wallet, counterparty = 'self', originator) {\n // Convert nonce from base64 string to Uint8Array\n const buffer = Utils.toArray(nonce, 'base64');\n // Split the nonce buffer\n const data = buffer.slice(0, 16);\n const hmac = buffer.slice(16);\n // Calculate the HMAC\n const { valid } = await wallet.verifyHmac({\n data,\n hmac,\n protocolID: [2, 'server hmac'],\n keyID: Utils.toUTF8(data),\n counterparty\n }, originator);\n return valid;\n}\n//# sourceMappingURL=verifyNonce.js.map","import * as Utils from '../../primitives/utils.js';\nimport Random from '../../primitives/Random.js';\n/**\n * Creates a nonce derived from a wallet\n * @param wallet\n * @param counterparty - The counterparty to the nonce creation. Defaults to 'self'.\n * @returns A random nonce derived with a wallet\n */\nexport async function createNonce(wallet, counterparty = 'self', originator) {\n // Generate 16 random bytes for the first half of the data\n const firstHalf = Random(16);\n // Create an sha256 HMAC\n const { hmac } = await wallet.createHmac({\n protocolID: [2, 'server hmac'],\n keyID: Utils.toUTF8(firstHalf),\n data: firstHalf,\n counterparty\n }, originator);\n // Concatenate firstHalf and secondHalf as the nonce bytes\n const nonceBytes = [...firstHalf, ...hmac];\n return Utils.toBase64(nonceBytes);\n}\n//# sourceMappingURL=createNonce.js.map","import { VerifiableCertificate } from '../certificates/VerifiableCertificate.js';\n/**\n * Retrieves an array of verifiable certificates based on the request.\n *\n * @private\n * @param {RequestedCertificateSet} requestedCertificates - The set of certificates requested by the peer.\n * @param {string} verifierIdentityKey - The public key of the verifier requesting the certificates.\n * @returns {Promise<VerifiableCertificate[]>} An array of verifiable certificates.\n */\nexport const getVerifiableCertificates = async (wallet, requestedCertificates, verifierIdentityKey, originator) => {\n // Find matching certificates we have\n // Note: This may return multiple certificates that match the correct type.\n const matchingCertificates = await wallet.listCertificates({\n certifiers: requestedCertificates.certifiers,\n types: Object.keys(requestedCertificates.types)\n }, originator);\n // For each certificate requested, create a verifiable cert with selectively revealed fields\n return await Promise.all(matchingCertificates.certificates.map(async (certificate) => {\n const { keyringForVerifier } = await wallet.proveCertificate({\n certificate,\n fieldsToReveal: requestedCertificates.types[certificate.type],\n verifier: verifierIdentityKey\n }, originator);\n return new VerifiableCertificate(certificate.type, certificate.serialNumber, certificate.subject, certificate.certifier, certificate.revocationOutpoint, certificate.fields, keyringForVerifier, certificate.signature);\n }));\n};\n//# sourceMappingURL=getVerifiableCertificates.js.map","import { VerifiableCertificate } from '../certificates/VerifiableCertificate.js';\n/**\n * Validates and processes the certificates received from a peer.\n *\n * @private\n * @param {AuthMessage} message - The message containing the certificates to validate.\n * @returns {Promise<void>}\n * @throws Will throw an error if certificate validation or field decryption fails.\n */\nexport const validateCertificates = async (verifierWallet, message, certificatesRequested, originator) => {\n if ((message.certificates == null) || message.certificates.length === 0) {\n throw new Error('No certificates were provided in the AuthMessage.');\n }\n await Promise.all(message.certificates.map(async (incomingCert) => {\n if (incomingCert.subject !== message.identityKey) {\n throw new Error(`The subject of one of your certificates (\"${incomingCert.subject}\") is not the same as the request sender (\"${message.identityKey}\").`);\n }\n // Verify Certificate structure and signature\n const certToVerify = new VerifiableCertificate(incomingCert.type, incomingCert.serialNumber, incomingCert.subject, incomingCert.certifier, incomingCert.revocationOutpoint, incomingCert.fields, incomingCert.keyring, incomingCert.signature);\n const isValidCert = await certToVerify.verify();\n if (!isValidCert) {\n throw new Error(`The signature for the certificate with serial number ${certToVerify.serialNumber} is invalid!`);\n }\n // Check if the certificate matches requested certifiers, types, and fields\n if (certificatesRequested != null) {\n const { certifiers, types } = certificatesRequested;\n // Check certifier matches\n if (!certifiers.includes(certToVerify.certifier)) {\n throw new Error(`Certificate with serial number ${certToVerify.serialNumber} has an unrequested certifier: ${certToVerify.certifier}`);\n }\n // Check type and fields match requested\n const requestedFields = types[certToVerify.type];\n if (requestedFields == null) {\n throw new Error(`Certificate with type ${certToVerify.type} was not requested`);\n }\n }\n // Attempt to decrypt fields\n await certToVerify.decryptFields(verifierWallet, undefined, undefined, originator);\n }));\n};\n//# sourceMappingURL=validateCertificates.js.map","import { SessionManager } from './SessionManager.js';\nimport { createNonce, verifyNonce, getVerifiableCertificates, validateCertificates } from './utils/index.js';\nimport Random from '../primitives/Random.js';\nimport * as Utils from '../primitives/utils.js';\nconst AUTH_VERSION = '0.1';\nconst BufferCtor = typeof globalThis !== 'undefined' ? globalThis.Buffer : undefined;\n/**\n * Represents a peer capable of performing mutual authentication.\n * Manages sessions, handles authentication handshakes, certificate requests and responses,\n * and sending and receiving general messages over a transport layer.\n *\n * This version supports multiple concurrent sessions per peer identityKey.\n */\nexport class Peer {\n sessionManager;\n transport;\n wallet;\n certificatesToRequest;\n onGeneralMessageReceivedCallbacks = new Map();\n onCertificatesReceivedCallbacks = new Map();\n onCertificateRequestReceivedCallbacks = new Map();\n onInitialResponseReceivedCallbacks = new Map();\n // Single shared counter for all callback types\n callbackIdCounter = 0;\n // Whether to auto-persist the session with the last-interacted-with peer\n autoPersistLastSession = true;\n // Last-interacted-with peer identity key (if the user calls toPeer with no identityKey)\n lastInteractedWithPeer;\n originator;\n identityPublicKey;\n /**\n * Creates a new Peer instance\n *\n * @param {WalletInterface} wallet - The wallet instance used for cryptographic operations.\n * @param {Transport} transport - The transport mechanism used for sending and receiving messages.\n * @param {RequestedCertificateSet} [certificatesToRequest] - Optional set of certificates to request from a peer during the initial handshake.\n * @param {SessionManager} [sessionManager] - Optional SessionManager to be used for managing peer sessions.\n * @param {boolean} [autoPersistLastSession] - Whether to auto-persist the session with the last-interacted-with peer. Defaults to true.\n */\n constructor(wallet, transport, certificatesToRequest, sessionManager, autoPersistLastSession, originator) {\n this.wallet = wallet;\n this.originator = originator;\n this.transport = transport;\n this.certificatesToRequest = certificatesToRequest ?? {\n certifiers: [],\n types: {}\n };\n this.transport.onData(this.handleIncomingMessage.bind(this)).catch(e => {\n throw e;\n });\n this.sessionManager =\n sessionManager != null ? sessionManager : new SessionManager();\n if (autoPersistLastSession === false) {\n this.autoPersistLastSession = false;\n }\n else {\n this.autoPersistLastSession = true;\n }\n }\n /**\n * Sends a general message to a peer, and initiates a handshake if necessary.\n *\n * @param {number[]} message - The message payload to send.\n * @param {string} [identityKey] - The identity public key of the peer. If not provided, uses lastInteractedWithPeer (if any).\n * @param {number} [maxWaitTime] - optional max wait time in ms\n * @returns {Promise<void>}\n * @throws Will throw an error if the message fails to send.\n */\n async toPeer(message, identityKey, maxWaitTime) {\n if (this.autoPersistLastSession &&\n typeof this.lastInteractedWithPeer === 'string' &&\n typeof identityKey !== 'string') {\n identityKey = this.lastInteractedWithPeer;\n }\n const peerSession = await this.getAuthenticatedSession(identityKey, maxWaitTime);\n // Prepare the general message\n const requestNonce = Utils.toBase64(Random(32));\n const { signature } = await this.wallet.createSignature({\n data: message,\n protocolID: [2, 'auth message signature'],\n keyID: `${requestNonce} ${peerSession.peerNonce ?? ''}`,\n counterparty: peerSession.peerIdentityKey\n }, this.originator);\n const generalMessage = {\n version: AUTH_VERSION,\n messageType: 'general',\n identityKey: await this.getIdentityPublicKey(),\n nonce: requestNonce,\n yourNonce: peerSession.peerNonce,\n payload: message,\n signature\n };\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n try {\n await this.transport.send(generalMessage);\n }\n catch (error) {\n this.propagateTransportError(peerSession.peerIdentityKey, error);\n }\n }\n /**\n * Sends a request for certificates to a peer.\n * This method allows a peer to dynamically request specific certificates after\n * an initial handshake or message has been exchanged.\n *\n * @param {RequestedCertificateSet} certificatesToRequest - Specifies the certifiers and types of certificates required from the peer.\n * @param {string} [identityKey] - The identity public key of the peer. If not provided, the current or last session identity is used.\n * @param {number} [maxWaitTime=10000] - Maximum time in milliseconds to wait for the peer session to be authenticated.\n * @returns {Promise<void>} Resolves if the certificate request message is successfully sent.\n * @throws Will throw an error if the peer session is not authenticated or if sending the request fails.\n */\n async requestCertificates(certificatesToRequest, identityKey, maxWaitTime = 10000) {\n if (this.autoPersistLastSession &&\n typeof this.lastInteractedWithPeer === 'string' &&\n typeof identityKey !== 'string') {\n identityKey = this.lastInteractedWithPeer;\n }\n const peerSession = await this.getAuthenticatedSession(identityKey, maxWaitTime);\n // Prepare the message\n const requestNonce = Utils.toBase64(Random(32));\n const { signature } = await this.wallet.createSignature({\n data: Peer.utf8ToBytes(JSON.stringify(certificatesToRequest)),\n protocolID: [2, 'auth message signature'],\n keyID: `${requestNonce} ${peerSession.peerNonce ?? ''}`,\n counterparty: peerSession.peerIdentityKey\n }, this.originator);\n const certRequestMessage = {\n version: AUTH_VERSION,\n messageType: 'certificateRequest',\n identityKey: await this.getIdentityPublicKey(),\n nonce: requestNonce,\n initialNonce: peerSession.sessionNonce,\n yourNonce: peerSession.peerNonce,\n requestedCertificates: certificatesToRequest,\n signature\n };\n // Update last-used timestamp\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n try {\n await this.transport.send(certRequestMessage);\n }\n catch (error) {\n this.propagateTransportError(peerSession.peerIdentityKey, error);\n }\n }\n /**\n * Retrieves an authenticated session for a given peer identity. If no session exists\n * or the session is not authenticated, initiates a handshake to create or authenticate the session.\n *\n * - If `identityKey` is provided, we look up any existing session for that identity key.\n * - If none is found or not authenticated, we do a new handshake.\n * - If `identityKey` is not provided, but we have a `lastInteractedWithPeer`, we try that key.\n *\n * @param {string} [identityKey] - The identity public key of the peer.\n * @param {number} [maxWaitTime] - The maximum time in milliseconds to wait for the handshake.\n * @returns {Promise<PeerSession>} - A promise that resolves with an authenticated `PeerSession`.\n */\n async getAuthenticatedSession(identityKey, maxWaitTime) {\n if (this.transport === undefined) {\n throw new Error('Peer transport is not connected!');\n }\n let peerSession;\n if (typeof identityKey === 'string') {\n peerSession = this.sessionManager.getSession(identityKey);\n }\n // If that session doesn't exist or isn't authenticated, initiate handshake\n if ((peerSession == null) || !peerSession.isAuthenticated) {\n // This will create a brand-new session\n const sessionNonce = await this.initiateHandshake(identityKey, maxWaitTime);\n // Now retrieve it by the sessionNonce\n peerSession = this.sessionManager.getSession(sessionNonce);\n if ((peerSession == null) || !peerSession.isAuthenticated) {\n throw new Error('Unable to establish mutual authentication with peer!');\n }\n }\n return peerSession;\n }\n /**\n * Registers a callback to listen for general messages from peers.\n *\n * @param {(senderPublicKey: string, payload: number[]) => void} callback - The function to call when a general message is received.\n * @returns {number} The ID of the callback listener.\n */\n listenForGeneralMessages(callback) {\n const callbackID = this.callbackIdCounter++;\n this.onGeneralMessageReceivedCallbacks.set(callbackID, callback);\n return callbackID;\n }\n /**\n * Removes a general message listener.\n *\n * @param {number} callbackID - The ID of the callback to remove.\n */\n stopListeningForGeneralMessages(callbackID) {\n this.onGeneralMessageReceivedCallbacks.delete(callbackID);\n }\n /**\n * Registers a callback to listen for certificates received from peers.\n *\n * @param {(senderPublicKey: string, certs: VerifiableCertificate[]) => void} callback - The function to call when certificates are received.\n * @returns {number} The ID of the callback listener.\n */\n listenForCertificatesReceived(callback) {\n const callbackID = this.callbackIdCounter++;\n this.onCertificatesReceivedCallbacks.set(callbackID, callback);\n return callbackID;\n }\n /**\n * Cancels and unsubscribes a certificatesReceived listener.\n *\n * @param {number} callbackID - The ID of the certificates received callback to cancel.\n */\n stopListeningForCertificatesReceived(callbackID) {\n this.onCertificatesReceivedCallbacks.delete(callbackID);\n }\n /**\n * Registers a callback to listen for certificates requested from peers.\n *\n * @param {(requestedCertificates: RequestedCertificateSet) => void} callback - The function to call when a certificate request is received\n * @returns {number} The ID of the callback listener.\n */\n listenForCertificatesRequested(callback) {\n const callbackID = this.callbackIdCounter++;\n this.onCertificateRequestReceivedCallbacks.set(callbackID, callback);\n return callbackID;\n }\n /**\n * Cancels and unsubscribes a certificatesRequested listener.\n *\n * @param {number} callbackID - The ID of the requested certificates callback to cancel.\n */\n stopListeningForCertificatesRequested(callbackID) {\n this.onCertificateRequestReceivedCallbacks.delete(callbackID);\n }\n /**\n * Initiates the mutual authentication handshake with a peer.\n *\n * @private\n * @param {string} [identityKey] - The identity public key of the peer.\n * @param {number} [maxWaitTime=10000] - how long to wait for handshake\n * @returns {Promise<string>} A promise that resolves to the session nonce.\n */\n async initiateHandshake(identityKey, maxWaitTime = 10000) {\n const sessionNonce = await createNonce(this.wallet, undefined, this.originator); // Initial request nonce\n // Create the preliminary session (not yet authenticated)\n const now = Date.now();\n this.sessionManager.addSession({\n isAuthenticated: false,\n sessionNonce,\n peerIdentityKey: identityKey,\n lastUpdate: now\n });\n const initialRequest = {\n version: AUTH_VERSION,\n messageType: 'initialRequest',\n identityKey: await this.getIdentityPublicKey(),\n initialNonce: sessionNonce,\n requestedCertificates: this.certificatesToRequest\n };\n await this.transport.send(initialRequest);\n return await this.waitForInitialResponse(sessionNonce, maxWaitTime);\n }\n /**\n * Waits for the initial response from the peer after sending an initial handshake request message.\n *\n * @param {string} sessionNonce - The session nonce created in the initial request.\n * @returns {Promise<string>} A promise that resolves with the session nonce when the initial response is received.\n */\n async waitForInitialResponse(sessionNonce, maxWaitTime = 10000) {\n return await new Promise((resolve, reject) => {\n const callbackID = this.listenForInitialResponse(sessionNonce, nonce => {\n clearTimeout(timeoutHandle);\n this.stopListeningForInitialResponses(callbackID);\n resolve(nonce);\n });\n const timeoutHandle = setTimeout(() => {\n this.stopListeningForInitialResponses(callbackID);\n reject(new Error('Initial response timed out.'));\n }, maxWaitTime);\n });\n }\n /**\n * Adds a listener for an initial response message matching a specific initial nonce.\n *\n * @private\n * @param {string} sessionNonce - The session nonce to match.\n * @param {(sessionNonce: string) => void} callback - The callback to invoke when the initial response is received.\n * @returns {number} The ID of the callback listener.\n */\n listenForInitialResponse(sessionNonce, callback) {\n const callbackID = this.callbackIdCounter++;\n this.onInitialResponseReceivedCallbacks.set(callbackID, {\n callback,\n sessionNonce\n });\n return callbackID;\n }\n /**\n * Removes a listener for initial responses.\n *\n * @private\n * @param {number} callbackID - The ID of the callback to remove.\n */\n stopListeningForInitialResponses(callbackID) {\n this.onInitialResponseReceivedCallbacks.delete(callbackID);\n }\n propagateTransportError(peerIdentityKey, error) {\n if (error instanceof Error) {\n if (peerIdentityKey != null) {\n const existingDetails = error.details;\n if (existingDetails != null && typeof existingDetails === 'object') {\n if (existingDetails.peerIdentityKey == null) {\n existingDetails.peerIdentityKey = peerIdentityKey;\n }\n }\n else {\n error.details = { peerIdentityKey };\n }\n }\n throw error;\n }\n const message = `Failed to send message to peer ${peerIdentityKey ?? 'unknown'}: ${String(error)}`;\n throw new Error(message);\n }\n /**\n * Handles incoming messages from the transport.\n *\n * @param {AuthMessage} message - The incoming message to process.\n * @returns {Promise<void>}\n */\n async handleIncomingMessage(message) {\n if (typeof message.version !== 'string' || message.version !== AUTH_VERSION) {\n throw new Error(`Invalid or unsupported message auth version! Received: ${message.version}, expected: ${AUTH_VERSION}`);\n }\n switch (message.messageType) {\n case 'initialRequest':\n await this.processInitialRequest(message);\n break;\n case 'initialResponse':\n await this.processInitialResponse(message);\n break;\n case 'certificateRequest':\n await this.processCertificateRequest(message);\n break;\n case 'certificateResponse':\n await this.processCertificateResponse(message);\n break;\n case 'general':\n await this.processGeneralMessage(message);\n break;\n default:\n throw new Error(`Unknown message type of ${String(message.messageType)} from ${String(message.identityKey)}`);\n }\n }\n /**\n * Processes an initial request message from a peer.\n *\n * @param {AuthMessage} message - The incoming initial request message.\n */\n async processInitialRequest(message) {\n if (typeof message.identityKey !== 'string' ||\n typeof message.initialNonce !== 'string' ||\n message.initialNonce === '') {\n throw new Error('Missing required fields in initialRequest message.');\n }\n // Create a new sessionNonce for our side\n const sessionNonce = await createNonce(this.wallet, undefined, this.originator);\n const now = Date.now();\n // We'll treat this as fully authenticated from *our* perspective (the responding side).\n this.sessionManager.addSession({\n isAuthenticated: true,\n sessionNonce,\n peerNonce: message.initialNonce,\n peerIdentityKey: message.identityKey,\n lastUpdate: now\n });\n // Possibly handle the peer's requested certs\n let certificatesToInclude;\n if ((message.requestedCertificates != null) &&\n Array.isArray(message.requestedCertificates.certifiers) &&\n message.requestedCertificates.certifiers.length > 0) {\n if (this.onCertificateRequestReceivedCallbacks.size > 0) {\n // Let the application handle it\n this.onCertificateRequestReceivedCallbacks.forEach(cb => {\n cb(message.identityKey, message.requestedCertificates);\n });\n }\n else {\n // Attempt to find automatically\n certificatesToInclude = await getVerifiableCertificates(this.wallet, message.requestedCertificates, message.identityKey, this.originator);\n }\n }\n // Create signature\n const { signature } = await this.wallet.createSignature({\n data: Peer.base64ToBytes(message.initialNonce + sessionNonce),\n protocolID: [2, 'auth message signature'],\n keyID: `${message.initialNonce} ${sessionNonce}`,\n counterparty: message.identityKey\n }, this.originator);\n const initialResponseMessage = {\n version: AUTH_VERSION,\n messageType: 'initialResponse',\n identityKey: await this.getIdentityPublicKey(),\n initialNonce: sessionNonce,\n yourNonce: message.initialNonce,\n certificates: certificatesToInclude,\n requestedCertificates: this.certificatesToRequest,\n signature\n };\n // If we haven't interacted with a peer yet, store this identity as \"lastInteracted\"\n if (this.lastInteractedWithPeer === undefined) {\n this.lastInteractedWithPeer = message.identityKey;\n }\n // Send the response\n await this.transport.send(initialResponseMessage);\n }\n /**\n * Processes an initial response message from a peer.\n *\n * @private\n * @param {AuthMessage} message - The incoming initial response message.\n * @throws Will throw an error if nonce or signature verification fails.\n */\n async processInitialResponse(message) {\n const validNonce = await verifyNonce(message.yourNonce, this.wallet, undefined, this.originator);\n if (!validNonce) {\n throw new Error(`Initial response nonce verification failed from peer: ${message.identityKey}`);\n }\n // This is the session we previously created by calling initiateHandshake\n const peerSession = this.sessionManager.getSession(message.yourNonce);\n if (peerSession == null) {\n throw new Error(`Peer session not found for peer: ${message.identityKey}`);\n }\n // Validate message signature\n const dataToVerify = Peer.base64ToBytes((peerSession.sessionNonce ?? '') + (message.initialNonce ?? ''));\n const { valid } = await this.wallet.verifySignature({\n data: dataToVerify,\n signature: message.signature,\n protocolID: [2, 'auth message signature'],\n keyID: `${peerSession.sessionNonce ?? ''} ${message.initialNonce ?? ''}`,\n counterparty: message.identityKey\n }, this.originator);\n if (!valid) {\n throw new Error(`Unable to verify initial response signature for peer: ${message.identityKey}`);\n }\n // Now mark the session as authenticated\n peerSession.peerNonce = message.initialNonce;\n peerSession.peerIdentityKey = message.identityKey;\n peerSession.isAuthenticated = true;\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n // If the handshake had requested certificates, validate them\n if (this.certificatesToRequest?.certifiers?.length > 0 &&\n message.certificates?.length > 0) {\n await validateCertificates(this.wallet, message, this.certificatesToRequest, this.originator);\n // Notify listeners\n this.onCertificatesReceivedCallbacks.forEach(cb => cb(message.identityKey, message.certificates));\n }\n // Update lastInteractedWithPeer\n this.lastInteractedWithPeer = message.identityKey;\n // Let the handshake wait-latch know we got our response\n this.onInitialResponseReceivedCallbacks.forEach(entry => {\n if (entry.sessionNonce === peerSession.sessionNonce) {\n entry.callback(peerSession.sessionNonce);\n }\n });\n // The peer might also request certificates from us\n if ((message.requestedCertificates != null) &&\n Array.isArray(message.requestedCertificates.certifiers) &&\n message.requestedCertificates.certifiers.length > 0) {\n if (this.onCertificateRequestReceivedCallbacks.size > 0) {\n // Let the application handle it\n this.onCertificateRequestReceivedCallbacks.forEach(cb => {\n cb(message.identityKey, message.requestedCertificates);\n });\n }\n else {\n // Attempt auto\n const verifiableCertificates = await getVerifiableCertificates(this.wallet, message.requestedCertificates, message.identityKey, this.originator);\n await this.sendCertificateResponse(message.identityKey, verifiableCertificates);\n }\n }\n }\n /**\n * Processes an incoming certificate request message from a peer.\n * Verifies nonce/signature and then possibly sends a certificateResponse.\n *\n * @param {AuthMessage} message - The certificate request message received from the peer.\n * @throws {Error} if nonce or signature is invalid.\n */\n async processCertificateRequest(message) {\n const validNonce = await verifyNonce(message.yourNonce, this.wallet, undefined, this.originator);\n if (!validNonce) {\n throw new Error(`Unable to verify nonce for certificate request message from: ${message.identityKey}`);\n }\n const peerSession = this.sessionManager.getSession(message.yourNonce);\n if (peerSession == null) {\n throw new Error(`Session not found for nonce: ${message.yourNonce}`);\n }\n const { valid } = await this.wallet.verifySignature({\n data: Peer.utf8ToBytes(JSON.stringify(message.requestedCertificates)),\n signature: message.signature,\n protocolID: [2, 'auth message signature'],\n keyID: `${message.nonce ?? ''} ${peerSession.sessionNonce ?? ''}`,\n counterparty: peerSession.peerIdentityKey\n }, this.originator);\n if (!valid) {\n throw new Error(`Invalid signature in certificate request message from ${peerSession.peerIdentityKey}`);\n }\n // Update usage\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n if ((message.requestedCertificates != null) &&\n Array.isArray(message.requestedCertificates.certifiers) &&\n message.requestedCertificates.certifiers.length > 0) {\n if (this.onCertificateRequestReceivedCallbacks.size > 0) {\n // Let the application handle it\n this.onCertificateRequestReceivedCallbacks.forEach(cb => {\n cb(message.identityKey, message.requestedCertificates);\n });\n }\n else {\n // Attempt auto\n const verifiableCertificates = await getVerifiableCertificates(this.wallet, message.requestedCertificates, message.identityKey, this.originator);\n await this.sendCertificateResponse(message.identityKey, verifiableCertificates);\n }\n }\n }\n /**\n * Sends a certificate response message containing the specified certificates to a peer.\n *\n * @param {string} verifierIdentityKey - The identity key of the peer requesting the certificates.\n * @param {VerifiableCertificate[]} certificates - The list of certificates to include in the response.\n * @throws Will throw an error if the transport fails to send the message.\n */\n async sendCertificateResponse(verifierIdentityKey, certificates) {\n const peerSession = await this.getAuthenticatedSession(verifierIdentityKey);\n const requestNonce = Utils.toBase64(Random(32));\n const { signature } = await this.wallet.createSignature({\n data: Peer.utf8ToBytes(JSON.stringify(certificates)),\n protocolID: [2, 'auth message signature'],\n keyID: `${requestNonce} ${peerSession.peerNonce ?? ''}`,\n counterparty: peerSession.peerIdentityKey\n }, this.originator);\n const certificateResponse = {\n version: AUTH_VERSION,\n messageType: 'certificateResponse',\n identityKey: await this.getIdentityPublicKey(),\n nonce: requestNonce,\n initialNonce: peerSession.sessionNonce,\n yourNonce: peerSession.peerNonce,\n certificates,\n signature\n };\n // Update usage\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n try {\n await this.transport.send(certificateResponse);\n }\n catch (error) {\n this.propagateTransportError(peerSession.peerIdentityKey, error);\n }\n }\n /**\n * Processes a certificate response message from a peer.\n *\n * @private\n * @param {AuthMessage} message - The incoming certificate response message.\n * @throws Will throw an error if nonce verification or signature verification fails.\n */\n async processCertificateResponse(message) {\n const validNonce = await verifyNonce(message.yourNonce, this.wallet, undefined, this.originator);\n if (!validNonce) {\n throw new Error(`Unable to verify nonce for certificate response from: ${message.identityKey}`);\n }\n const peerSession = this.sessionManager.getSession(message.yourNonce);\n if (peerSession == null) {\n throw new Error(`Session not found for nonce: ${message.yourNonce}`);\n }\n // Validate message signature\n const { valid } = await this.wallet.verifySignature({\n data: Peer.utf8ToBytes(JSON.stringify(message.certificates)),\n signature: message.signature,\n protocolID: [2, 'auth message signature'],\n keyID: `${message.nonce ?? ''} ${peerSession.sessionNonce ?? ''}`,\n counterparty: message.identityKey\n }, this.originator);\n if (!valid) {\n throw new Error(`Unable to verify certificate response signature for peer: ${message.identityKey}`);\n }\n // We also handle optional validation if there's a requestedCertificates field\n await validateCertificates(this.wallet, message, message.requestedCertificates, this.originator);\n // Notify any listeners\n this.onCertificatesReceivedCallbacks.forEach(cb => {\n cb(message.identityKey, message.certificates ?? []);\n });\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n }\n /**\n * Processes a general message from a peer.\n *\n * @private\n * @param {AuthMessage} message - The incoming general message.\n * @throws Will throw an error if nonce or signature verification fails.\n */\n async processGeneralMessage(message) {\n const validNonce = await verifyNonce(message.yourNonce, this.wallet, undefined, this.originator);\n if (!validNonce) {\n throw new Error(`Unable to verify nonce for general message from: ${message.identityKey}`);\n }\n const peerSession = this.sessionManager.getSession(message.yourNonce);\n if (peerSession == null) {\n throw new Error(`Session not found for nonce: ${message.yourNonce}`);\n }\n const { valid } = await this.wallet.verifySignature({\n data: message.payload,\n signature: message.signature,\n protocolID: [2, 'auth message signature'],\n keyID: `${message.nonce ?? ''} ${peerSession.sessionNonce ?? ''}`,\n counterparty: peerSession.peerIdentityKey\n }, this.originator);\n if (!valid) {\n throw new Error(`Invalid signature in generalMessage from ${peerSession.peerIdentityKey}`);\n }\n // Mark last usage\n peerSession.lastUpdate = Date.now();\n this.sessionManager.updateSession(peerSession);\n // Update lastInteractedWithPeer\n this.lastInteractedWithPeer = message.identityKey;\n // Dispatch callbacks\n this.onGeneralMessageReceivedCallbacks.forEach(cb => {\n cb(message.identityKey, message.payload ?? []);\n });\n }\n async getIdentityPublicKey() {\n if (this.identityPublicKey != null) {\n return this.identityPublicKey;\n }\n const { publicKey } = await this.wallet.getPublicKey({ identityKey: true }, this.originator);\n this.identityPublicKey = publicKey;\n return publicKey;\n }\n static utf8ToBytes(data) {\n if (BufferCtor != null) {\n return Array.from(BufferCtor.from(data, 'utf8'));\n }\n if (typeof TextEncoder !== 'undefined') {\n return Array.from(new TextEncoder().encode(data));\n }\n return Utils.toArray(data, 'utf8');\n }\n static base64ToBytes(data) {\n if (BufferCtor != null) {\n return Array.from(BufferCtor.from(data, 'base64'));\n }\n return Utils.toArray(data, 'base64');\n }\n}\n//# sourceMappingURL=Peer.js.map","import * as Utils from '../../primitives/utils.js';\nconst defaultFetch = typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function'\n ? globalThis.fetch.bind(globalThis)\n : fetch;\n/**\n * Implements an HTTP-specific transport for handling Peer mutual authentication messages.\n * This class integrates with fetch to send and receive authenticated messages between peers.\n */\nexport class SimplifiedFetchTransport {\n onDataCallback;\n fetchClient;\n baseUrl;\n /**\n * Constructs a new instance of SimplifiedFetchTransport.\n * @param baseUrl - The base URL for all HTTP requests made by this transport.\n * @param fetchClient - A fetch implementation to use for HTTP requests (default: global fetch).\n */\n constructor(baseUrl, fetchClient = defaultFetch) {\n if (typeof fetchClient !== 'function') {\n throw new Error('SimplifiedFetchTransport requires a fetch implementation. ' +\n 'In environments without fetch, provide a polyfill or custom implementation.');\n }\n this.fetchClient = fetchClient;\n this.baseUrl = baseUrl;\n }\n /**\n * Sends a message to an HTTP server using the transport mechanism.\n * Handles both general and authenticated message types. For general messages,\n * the payload is deserialized and sent as an HTTP request. For other message types,\n * the message is sent as a POST request to the `/auth` endpoint.\n *\n * @param message - The AuthMessage to send.\n * @returns A promise that resolves when the message is successfully sent.\n *\n * @throws Will throw an error if no listener has been registered via `onData`.\n */\n async send(message) {\n if (this.onDataCallback == null) {\n throw new Error('Listen before you start speaking. God gave you two ears and one mouth for a reason.');\n }\n if (message.messageType !== 'general') {\n return await new Promise((resolve, reject) => {\n void (async () => {\n try {\n const authUrl = `${this.baseUrl}/.well-known/auth`;\n const responsePromise = (async () => {\n try {\n return await this.fetchClient(authUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(message)\n });\n }\n catch (error) {\n throw this.createNetworkError(authUrl, error);\n }\n })();\n // For initialRequest message, mark connection as established and start pool.\n if (message.messageType !== 'initialRequest') {\n resolve();\n }\n const response = await responsePromise;\n if (!response.ok) {\n const responseBodyArray = Array.from(new Uint8Array(await response.arrayBuffer()));\n throw this.createUnauthenticatedResponseError(authUrl, response, responseBodyArray);\n }\n if (this.onDataCallback != null) {\n const responseMessage = await response.json();\n this.onDataCallback(responseMessage);\n }\n if (message.messageType === 'initialRequest') {\n resolve();\n }\n }\n catch (e) {\n reject(e);\n }\n })();\n });\n }\n else {\n // Parse message payload\n const httpRequest = this.deserializeRequestPayload(message.payload);\n // Send the byte array as the HTTP payload\n const url = `${this.baseUrl}${httpRequest.urlPostfix}`;\n const httpRequestWithAuthHeaders = httpRequest;\n if (typeof httpRequest.headers !== 'object') {\n httpRequestWithAuthHeaders.headers = {};\n }\n // Append auth headers in request to server\n httpRequestWithAuthHeaders.headers['x-bsv-auth-version'] = message.version;\n httpRequestWithAuthHeaders.headers['x-bsv-auth-identity-key'] = message.identityKey;\n httpRequestWithAuthHeaders.headers['x-bsv-auth-nonce'] = message.nonce;\n httpRequestWithAuthHeaders.headers['x-bsv-auth-your-nonce'] = message.yourNonce;\n httpRequestWithAuthHeaders.headers['x-bsv-auth-signature'] = Utils.toHex(message.signature);\n httpRequestWithAuthHeaders.headers['x-bsv-auth-request-id'] = httpRequest.requestId;\n // Ensure Content-Type is set for requests with a body\n if (httpRequestWithAuthHeaders.body != null) {\n const headers = httpRequestWithAuthHeaders.headers;\n if (headers['content-type'] == null) {\n throw new Error('Content-Type header is required for requests with a body.');\n }\n const contentType = String(headers['content-type'] ?? '');\n // Transform body based on Content-Type\n if (contentType.includes('application/json')) {\n // Convert byte array to JSON string\n httpRequestWithAuthHeaders.body = Utils.toUTF8(httpRequestWithAuthHeaders.body);\n }\n else if (contentType.includes('application/x-www-form-urlencoded')) {\n // Convert byte array to URL-encoded string\n httpRequestWithAuthHeaders.body = Utils.toUTF8(httpRequestWithAuthHeaders.body);\n }\n else if (contentType.includes('text/plain')) {\n // Convert byte array to plain UTF-8 string\n httpRequestWithAuthHeaders.body = Utils.toUTF8(httpRequestWithAuthHeaders.body);\n }\n else {\n // For all other content types, treat as binary data\n httpRequestWithAuthHeaders.body = new Uint8Array(httpRequestWithAuthHeaders.body);\n }\n }\n // Send the actual fetch request to the server\n let response;\n try {\n response = await this.fetchClient(url, {\n method: httpRequestWithAuthHeaders.method,\n headers: httpRequestWithAuthHeaders.headers,\n body: httpRequestWithAuthHeaders.body\n });\n }\n catch (error) {\n throw this.createNetworkError(url, error);\n }\n const responseBodyBuffer = await response.arrayBuffer();\n const responseBodyArray = Array.from(new Uint8Array(responseBodyBuffer));\n const missingAuthHeaders = ['x-bsv-auth-version', 'x-bsv-auth-identity-key', 'x-bsv-auth-signature']\n .filter(headerName => {\n const headerValue = response.headers.get(headerName);\n return headerValue == null || headerValue.trim().length === 0;\n });\n if (missingAuthHeaders.length > 0) {\n throw this.createUnauthenticatedResponseError(url, response, responseBodyArray, missingAuthHeaders);\n }\n const requestedCertificatesHeader = response.headers.get('x-bsv-auth-requested-certificates');\n let requestedCertificates;\n if (requestedCertificatesHeader != null) {\n try {\n requestedCertificates = JSON.parse(requestedCertificatesHeader);\n }\n catch (error) {\n throw this.createMalformedHeaderError(url, 'x-bsv-auth-requested-certificates', requestedCertificatesHeader, error);\n }\n }\n const payloadWriter = new Utils.Writer();\n if (response.headers.get('x-bsv-auth-request-id') != null) {\n payloadWriter.write(Utils.toArray(response.headers.get('x-bsv-auth-request-id'), 'base64'));\n }\n payloadWriter.writeVarIntNum(response.status);\n // PARSE RESPONSE HEADERS FROM SERVER --------------------------------\n // Parse response headers from the server and include only the signed headers:\n // - Include custom headers prefixed with x-bsv (excluding those starting with x-bsv-auth)\n // - Include the authorization header\n const includedHeaders = [];\n response.headers.forEach((value, key) => {\n const lowerKey = key.toLowerCase();\n if ((lowerKey.startsWith('x-bsv-') || lowerKey === 'authorization') && !lowerKey.startsWith('x-bsv-auth')) {\n includedHeaders.push([lowerKey, value]);\n }\n });\n // Sort the headers by key to ensure a consistent order for signing and verification.\n includedHeaders.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));\n // nHeaders\n payloadWriter.writeVarIntNum(includedHeaders.length);\n for (let i = 0; i < includedHeaders.length; i++) {\n // headerKeyLength\n const headerKeyAsArray = Utils.toArray(includedHeaders[i][0], 'utf8');\n payloadWriter.writeVarIntNum(headerKeyAsArray.length);\n // headerKey\n payloadWriter.write(headerKeyAsArray);\n // headerValueLength\n const headerValueAsArray = Utils.toArray(includedHeaders[i][1], 'utf8');\n payloadWriter.writeVarIntNum(headerValueAsArray.length);\n // headerValue\n payloadWriter.write(headerValueAsArray);\n }\n // Handle body\n payloadWriter.writeVarIntNum(responseBodyArray.length);\n if (responseBodyArray.length > 0) {\n payloadWriter.write(responseBodyArray);\n }\n // Build the correct AuthMessage for the response\n const responseMessage = {\n version: response.headers.get('x-bsv-auth-version'),\n messageType: response.headers.get('x-bsv-auth-message-type') === 'certificateRequest' ? 'certificateRequest' : 'general',\n identityKey: response.headers.get('x-bsv-auth-identity-key'),\n nonce: response.headers.get('x-bsv-auth-nonce') ?? undefined,\n yourNonce: response.headers.get('x-bsv-auth-your-nonce') ?? undefined,\n requestedCertificates,\n payload: payloadWriter.toArray(),\n signature: Utils.toArray(response.headers.get('x-bsv-auth-signature'), 'hex')\n };\n // If the server didn't provide the correct authentication headers, throw an error\n if (responseMessage.version == null) {\n throw this.createUnauthenticatedResponseError(url, response, responseBodyArray);\n }\n // Handle the response if data is received and callback is set\n this.onDataCallback(responseMessage);\n }\n }\n /**\n * Registers a callback to handle incoming messages.\n * This must be called before sending any messages to ensure responses can be processed.\n *\n * @param callback - A function to invoke when an incoming AuthMessage is received.\n * @returns A promise that resolves once the callback is set.\n */\n async onData(callback) {\n this.onDataCallback = (m) => {\n void callback(m);\n };\n }\n createNetworkError(url, originalError) {\n const baseMessage = `Network error while sending authenticated request to ${url}`;\n if (originalError instanceof Error) {\n const error = new Error(`${baseMessage}: ${originalError.message}`);\n error.stack = originalError.stack;\n error.cause = originalError;\n return error;\n }\n return new Error(`${baseMessage}: ${String(originalError)}`);\n }\n createUnauthenticatedResponseError(url, response, bodyBytes, missingHeaders = []) {\n const statusText = (response.statusText ?? '').trim();\n const statusDescription = statusText.length > 0\n ? `${response.status} ${statusText}`\n : `${response.status}`;\n const headerMessage = missingHeaders.length > 0\n ? `missing headers: ${missingHeaders.join(', ')}`\n : 'response lacked required BSV auth headers';\n const bodyPreview = this.getBodyPreview(bodyBytes, response.headers.get('content-type'));\n const parts = [`Received HTTP ${statusDescription} from ${url} without valid BSV authentication (${headerMessage})`];\n if (bodyPreview != null) {\n parts.push(`body preview: ${bodyPreview}`);\n }\n const error = new Error(parts.join(' - '));\n error.details = {\n url,\n status: response.status,\n statusText: response.statusText,\n missingHeaders,\n bodyPreview\n };\n return error;\n }\n createMalformedHeaderError(url, headerName, headerValue, cause) {\n const errorMessage = `Failed to parse ${headerName} returned by ${url}: ${headerValue}`;\n if (cause instanceof Error) {\n const error = new Error(`${errorMessage}. ${cause.message}`);\n error.stack = cause.stack;\n error.cause = cause;\n return error;\n }\n return new Error(`${errorMessage}. ${String(cause)}`);\n }\n getBodyPreview(bodyBytes, contentType) {\n if (bodyBytes.length === 0) {\n return undefined;\n }\n const maxBytesForPreview = 1024;\n const truncated = bodyBytes.length > maxBytesForPreview;\n const slice = truncated ? bodyBytes.slice(0, maxBytesForPreview) : bodyBytes;\n const isText = this.isTextualContent(contentType, slice);\n let preview;\n if (isText) {\n try {\n preview = Utils.toUTF8(slice);\n }\n catch {\n preview = this.formatBinaryPreview(slice, truncated);\n }\n }\n else {\n preview = this.formatBinaryPreview(slice, truncated);\n }\n if (preview.length > 512) {\n preview = `${preview.slice(0, 512)}…`;\n }\n if (truncated) {\n preview = `${preview} (truncated)`;\n }\n return preview;\n }\n isTextualContent(contentType, sample) {\n if (sample.length === 0) {\n return false;\n }\n if (contentType != null) {\n const lowered = contentType.toLowerCase();\n const textualTokens = [\n 'application/json',\n 'application/problem+json',\n 'application/xml',\n 'application/xhtml+xml',\n 'application/javascript',\n 'application/ecmascript',\n 'application/x-www-form-urlencoded',\n 'text/'\n ];\n if (textualTokens.some(token => lowered.includes(token)) || lowered.includes('charset=')) {\n return true;\n }\n }\n const printableCount = sample.reduce((count, byte) => {\n if (byte === 9 || byte === 10 || byte === 13) {\n return count + 1;\n }\n if (byte >= 32 && byte <= 126) {\n return count + 1;\n }\n return count;\n }, 0);\n return (printableCount / sample.length) > 0.8;\n }\n formatBinaryPreview(bytes, truncated) {\n const hex = bytes.map(byte => byte.toString(16).padStart(2, '0')).join('');\n return `0x${hex}${truncated ? '…' : ''}`;\n }\n /**\n * Deserializes a request payload from a byte array into an HTTP request-like structure.\n *\n * @param payload - The serialized payload to deserialize.\n * @returns An object representing the deserialized request, including the method,\n * URL postfix (path and query string), headers, body, and request ID.\n */\n deserializeRequestPayload(payload) {\n // Create a reader\n const requestReader = new Utils.Reader(payload);\n // The first 32 bytes is the requestId\n const requestId = Utils.toBase64(requestReader.read(32));\n // Method\n const methodLength = requestReader.readVarIntNum();\n let method = 'GET';\n if (methodLength > 0) {\n method = Utils.toUTF8(requestReader.read(methodLength));\n }\n // Path\n const pathLength = requestReader.readVarIntNum();\n let path = '';\n if (pathLength > 0) {\n path = Utils.toUTF8(requestReader.read(pathLength));\n }\n // Search\n const searchLength = requestReader.readVarIntNum();\n let search = '';\n if (searchLength > 0) {\n search = Utils.toUTF8(requestReader.read(searchLength));\n }\n // Read headers\n const requestHeaders = {};\n const nHeaders = requestReader.readVarIntNum();\n if (nHeaders > 0) {\n for (let i = 0; i < nHeaders; i++) {\n const nHeaderKeyBytes = requestReader.readVarIntNum();\n const headerKeyBytes = requestReader.read(nHeaderKeyBytes);\n const headerKey = Utils.toUTF8(headerKeyBytes);\n const nHeaderValueBytes = requestReader.readVarIntNum();\n const headerValueBytes = requestReader.read(nHeaderValueBytes);\n const headerValue = Utils.toUTF8(headerValueBytes);\n requestHeaders[headerKey] = headerValue;\n }\n }\n // Read body\n let requestBody;\n const requestBodyBytes = requestReader.readVarIntNum();\n if (requestBodyBytes > 0) {\n requestBody = requestReader.read(requestBodyBytes);\n }\n // Return the deserialized RequestInit\n return {\n urlPostfix: path + search,\n method,\n headers: requestHeaders,\n body: requestBody,\n requestId\n };\n }\n}\n//# sourceMappingURL=SimplifiedFetchTransport.js.map","// @ts-nocheck\nimport * as Utils from '../../primitives/utils.js';\nimport Random from '../../primitives/Random.js';\nimport P2PKH from '../../script/templates/P2PKH.js';\nimport PublicKey from '../../primitives/PublicKey.js';\nimport { createNonce } from '../utils/createNonce.js';\nimport { Peer } from '../Peer.js';\nimport { SimplifiedFetchTransport } from '../transports/SimplifiedFetchTransport.js';\nimport { SessionManager } from '../SessionManager.js';\nimport { getVerifiableCertificates } from '../utils/index.js';\nconst PAYMENT_VERSION = '1.0';\n/**\n * AuthFetch provides a lightweight fetch client for interacting with servers\n * over a simplified HTTP transport mechanism. It integrates session management, peer communication,\n * and certificate handling to enable secure and mutually-authenticated requests.\n *\n * Additionally, it automatically handles 402 Payment Required responses by creating\n * and sending BSV payment transactions when necessary.\n */\nexport class AuthFetch {\n sessionManager;\n wallet;\n callbacks = {};\n certificatesReceived = [];\n requestedCertificates;\n originator;\n peers = {};\n /**\n * Constructs a new AuthFetch instance.\n * @param wallet - The wallet instance for signing and authentication.\n * @param requestedCertificates - Optional set of certificates to request from peers.\n */\n constructor(wallet, requestedCertificates, sessionManager, originator) {\n this.wallet = wallet;\n this.requestedCertificates = requestedCertificates;\n this.sessionManager = sessionManager ?? new SessionManager();\n this.originator = originator;\n }\n /**\n * Mutually authenticates and sends a HTTP request to a server.\n *\n * 1) Attempt the request.\n * 2) If 402 Payment Required, automatically create and send payment.\n * 3) Return the final response.\n *\n * @param url - The URL to send the request to.\n * @param config - Configuration options for the request, including method, headers, and body.\n * @returns A promise that resolves with the server's response, structured as a Response-like object.\n *\n * @throws Will throw an error if unsupported headers are used or other validation fails.\n */\n async fetch(url, config = {}) {\n if (typeof config.retryCounter === 'number') {\n if (config.retryCounter <= 0) {\n throw new Error('Request failed after maximum number of retries.');\n }\n config.retryCounter--;\n }\n const response = await new Promise((async (resolve, reject) => {\n try {\n // Apply defaults\n const { method = 'GET', headers = {}, body } = config;\n // Extract a base url\n const parsedUrl = new URL(url);\n const baseURL = parsedUrl.origin;\n // Create a new transport for this base url if needed\n let peerToUse;\n if (typeof this.peers[baseURL] === 'undefined') {\n // Create a peer for the request\n const newTransport = new SimplifiedFetchTransport(baseURL);\n peerToUse = {\n peer: new Peer(this.wallet, newTransport, this.requestedCertificates, this.sessionManager, undefined, this.originator),\n pendingCertificateRequests: []\n };\n this.peers[baseURL] = peerToUse;\n this.peers[baseURL].peer.listenForCertificatesReceived((senderPublicKey, certs) => {\n this.certificatesReceived.push(...certs);\n });\n this.peers[baseURL].peer.listenForCertificatesRequested((async (verifier, requestedCertificates) => {\n try {\n this.peers[baseURL].pendingCertificateRequests.push(true);\n const certificatesToInclude = await getVerifiableCertificates(this.wallet, requestedCertificates, verifier, this.originator);\n await this.peers[baseURL].peer.sendCertificateResponse(verifier, certificatesToInclude);\n }\n finally {\n // Give the backend 500 ms to process the certificates we just sent, before releasing the queue entry\n await new Promise(resolve => setTimeout(resolve, 500));\n this.peers[baseURL].pendingCertificateRequests.shift();\n }\n }));\n }\n else {\n // Check if there's a session associated with this baseURL\n if (this.peers[baseURL].supportsMutualAuth === false) {\n // Use standard fetch if mutual authentication is not supported\n try {\n const response = await this.handleFetchAndValidate(url, config, this.peers[baseURL]);\n resolve(response);\n }\n catch (error) {\n reject(error);\n }\n return;\n }\n peerToUse = this.peers[baseURL];\n }\n // Serialize the simplified fetch request.\n const requestNonce = Random(32);\n const requestNonceAsBase64 = Utils.toBase64(requestNonce);\n const writer = await this.serializeRequest(method, headers, body, parsedUrl, requestNonce);\n // Setup general message listener to resolve requests once a response is received\n this.callbacks[requestNonceAsBase64] = { resolve, reject };\n const listenerId = peerToUse.peer.listenForGeneralMessages((senderPublicKey, payload) => {\n // Create a reader\n const responseReader = new Utils.Reader(payload);\n // Deserialize first 32 bytes of payload\n const responseNonceAsBase64 = Utils.toBase64(responseReader.read(32));\n if (responseNonceAsBase64 !== requestNonceAsBase64) {\n return;\n }\n peerToUse.peer.stopListeningForGeneralMessages(listenerId);\n // Save the identity key for the peer for future requests, since we have it here.\n this.peers[baseURL].identityKey = senderPublicKey;\n this.peers[baseURL].supportsMutualAuth = true;\n // Status code\n const statusCode = responseReader.readVarIntNum();\n // Headers\n const responseHeaders = {};\n const nHeaders = responseReader.readVarIntNum();\n if (nHeaders > 0) {\n for (let i = 0; i < nHeaders; i++) {\n const nHeaderKeyBytes = responseReader.readVarIntNum();\n const headerKeyBytes = responseReader.read(nHeaderKeyBytes);\n const headerKey = Utils.toUTF8(headerKeyBytes);\n const nHeaderValueBytes = responseReader.readVarIntNum();\n const headerValueBytes = responseReader.read(nHeaderValueBytes);\n const headerValue = Utils.toUTF8(headerValueBytes);\n responseHeaders[headerKey] = headerValue;\n }\n }\n // Add back the server identity key header\n responseHeaders['x-bsv-auth-identity-key'] = senderPublicKey;\n // Body\n let responseBody;\n const responseBodyBytes = responseReader.readVarIntNum();\n if (responseBodyBytes > 0) {\n responseBody = responseReader.read(responseBodyBytes);\n }\n // Create the Response object\n const responseValue = new Response(responseBody ? new Uint8Array(responseBody) : null, {\n status: statusCode,\n statusText: `${statusCode}`,\n headers: new Headers(responseHeaders)\n });\n // Resolve or reject the correct request with the response data\n this.callbacks[requestNonceAsBase64].resolve(responseValue);\n // Clean up\n delete this.callbacks[requestNonceAsBase64];\n });\n // Before sending general messages to the peer, ensure that no certificate requests are pending.\n // This way, the user would need to choose to either allow or reject the certificate request first.\n // If the server has a resource that requires certificates to be sent before access would be granted,\n // this makes sure the user has a chance to send the certificates before the resource is requested.\n if (peerToUse.pendingCertificateRequests.length > 0) {\n await new Promise(resolve => {\n setInterval(() => {\n if (peerToUse.pendingCertificateRequests.length === 0) {\n resolve();\n }\n }, 100); // Check every 100 ms for the user to finish responding\n });\n }\n // Send the request, now that all listeners are set up\n await peerToUse.peer.toPeer(writer.toArray(), peerToUse.identityKey).catch(async (error) => {\n if (error.message.includes('Session not found for nonce')) {\n delete this.peers[baseURL];\n config.retryCounter ??= 3;\n const response = await this.fetch(url, config);\n resolve(response);\n return;\n }\n if (error.message.includes('HTTP server failed to authenticate')) {\n try {\n const response = await this.handleFetchAndValidate(url, config, peerToUse);\n resolve(response);\n return;\n }\n catch (fetchError) {\n reject(fetchError);\n }\n }\n else {\n reject(error);\n }\n });\n }\n catch (e) {\n reject(e);\n }\n }));\n // Check if server requires payment to access the requested route\n if (response.status === 402) {\n // Create and attach a payment, then retry\n return await this.handlePaymentAndRetry(url, config, response);\n }\n return response;\n }\n /**\n * Request Certificates from a Peer\n * @param baseUrl\n * @param certificatesToRequest\n */\n async sendCertificateRequest(baseUrl, certificatesToRequest) {\n const parsedUrl = new URL(baseUrl);\n const baseURL = parsedUrl.origin;\n let peerToUse;\n if (typeof this.peers[baseURL] !== 'undefined') {\n peerToUse = { peer: this.peers[baseURL].peer };\n }\n else {\n const newTransport = new SimplifiedFetchTransport(baseURL);\n peerToUse = {\n peer: new Peer(this.wallet, newTransport, this.requestedCertificates, this.sessionManager, this.originator)\n };\n this.peers[baseURL] = peerToUse;\n }\n // Return a promise that resolves when certificates are received\n return await new Promise((async (resolve, reject) => {\n // Set up the listener before making the request\n const callbackId = peerToUse.peer.listenForCertificatesReceived((_senderPublicKey, certs) => {\n peerToUse.peer.stopListeningForCertificatesReceived(callbackId);\n this.certificatesReceived.push(...certs);\n resolve(certs);\n });\n try {\n // Initiate the certificate request\n await peerToUse.peer.requestCertificates(certificatesToRequest, peerToUse.identityKey);\n }\n catch (err) {\n peerToUse.peer.stopListeningForCertificatesReceived(callbackId);\n reject(err);\n }\n }));\n }\n /**\n * Return any certificates we've collected thus far, then clear them out.\n */\n consumeReceivedCertificates() {\n return this.certificatesReceived.splice(0);\n }\n /**\n * Serializes the HTTP request to be sent over the Transport.\n *\n * @param method - The HTTP method (e.g., 'GET', 'POST') for the request.\n * @param headers - A record of HTTP headers to include in the request.\n * @param body - The body of the request, if applicable (e.g., for POST/PUT requests).\n * @param parsedUrl - The parsed URL object containing the full request URL.\n * @param requestNonce - A unique random nonce to ensure request integrity.\n * @returns A promise that resolves to a `Writer` containing the serialized request.\n *\n * @throws Will throw an error if unsupported headers are used or serialization fails.\n */\n async serializeRequest(method, headers, body, parsedUrl, requestNonce) {\n const writer = new Utils.Writer();\n // Write request nonce\n writer.write(requestNonce);\n // Method length\n writer.writeVarIntNum(method.length);\n // Method\n writer.write(Utils.toArray(method));\n // Handle pathname (e.g. /path/to/resource)\n if (parsedUrl.pathname.length > 0) {\n // Pathname length\n const pathnameAsArray = Utils.toArray(parsedUrl.pathname);\n writer.writeVarIntNum(pathnameAsArray.length);\n // Pathname\n writer.write(pathnameAsArray);\n }\n else {\n writer.writeVarIntNum(-1);\n }\n // Handle search params (e.g. ?q=hello)\n if (parsedUrl.search.length > 0) {\n // search length\n const searchAsArray = Utils.toArray(parsedUrl.search);\n writer.writeVarIntNum(searchAsArray.length);\n // search\n writer.write(searchAsArray);\n }\n else {\n writer.writeVarIntNum(-1);\n }\n // Construct headers to send / sign:\n // Ensures clients only provided supported HTTP request headers\n // - Include custom headers prefixed with x-bsv (excluding those starting with x-bsv-auth)\n // - Include a normalized version of the content-type header\n // - Include the authorization header\n const includedHeaders = [];\n for (let [k, v] of Object.entries(headers)) {\n k = k.toLowerCase(); // We will always sign lower-case header keys\n if (k.startsWith('x-bsv-') || k === 'authorization') {\n if (k.startsWith('x-bsv-auth')) {\n throw new Error('No BSV auth headers allowed here!');\n }\n includedHeaders.push([k, v]);\n }\n else if (k.startsWith('content-type')) {\n // Normalize the Content-Type header by removing any parameters (e.g., \"; charset=utf-8\")\n v = v.split(';')[0].trim();\n includedHeaders.push([k, v]);\n }\n else {\n throw new Error('Unsupported header in the simplified fetch implementation. Only content-type, authorization, and x-bsv-* headers are supported.');\n }\n }\n // Sort the headers by key to ensure a consistent order for signing and verification.\n includedHeaders.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));\n // nHeaders\n writer.writeVarIntNum(includedHeaders.length);\n for (let i = 0; i < includedHeaders.length; i++) {\n // headerKeyLength\n const headerKeyAsArray = Utils.toArray(includedHeaders[i][0], 'utf8');\n writer.writeVarIntNum(headerKeyAsArray.length);\n // headerKey\n writer.write(headerKeyAsArray);\n // headerValueLength\n const headerValueAsArray = Utils.toArray(includedHeaders[i][1], 'utf8');\n writer.writeVarIntNum(headerValueAsArray.length);\n // headerValue\n writer.write(headerValueAsArray);\n }\n // If method typically carries a body and body is undefined, default it\n // This prevents signature verification errors due to mismatch default body types with express\n const methodsThatTypicallyHaveBody = ['POST', 'PUT', 'PATCH', 'DELETE'];\n if (methodsThatTypicallyHaveBody.includes(method.toUpperCase()) && body === undefined) {\n // Check if content-type is application/json\n const contentTypeHeader = includedHeaders.find(([k]) => k === 'content-type');\n if (contentTypeHeader && contentTypeHeader[1].includes('application/json')) {\n body = '{}';\n }\n else {\n body = '';\n }\n }\n // Handle body\n if (body) {\n const reqBody = await this.normalizeBodyToNumberArray(body); // Use the utility function\n writer.writeVarIntNum(reqBody.length);\n writer.write(reqBody);\n }\n else {\n writer.writeVarIntNum(-1); // No body\n }\n return writer;\n }\n /**\n * Handles a non-authenticated fetch requests and validates that the server is not claiming to be authenticated.\n */\n async handleFetchAndValidate(url, config, peerToUse) {\n const response = await fetch(url, config);\n response.headers.forEach(header => {\n if (header.toLocaleLowerCase().startsWith('x-bsv')) {\n throw new Error('The server is trying to claim it has been authenticated when it has not!');\n }\n });\n if (response.ok) {\n peerToUse.supportsMutualAuth = false;\n return response;\n }\n else {\n throw new Error(`Request failed with status: ${response.status}`);\n }\n }\n /**\n * If we get 402 Payment Required, we build a transaction via wallet.createAction()\n * and re-attempt the request with an x-bsv-payment header.\n */\n async handlePaymentAndRetry(url, config = {}, originalResponse) {\n const paymentVersion = originalResponse.headers.get('x-bsv-payment-version');\n if (!paymentVersion || paymentVersion !== PAYMENT_VERSION) {\n throw new Error(`Unsupported x-bsv-payment-version response header. Client version: ${PAYMENT_VERSION}, Server version: ${paymentVersion}`);\n }\n const satoshisRequiredHeader = originalResponse.headers.get('x-bsv-payment-satoshis-required');\n if (!satoshisRequiredHeader) {\n throw new Error('Missing x-bsv-payment-satoshis-required response header.');\n }\n const satoshisRequired = parseInt(satoshisRequiredHeader);\n if (isNaN(satoshisRequired) || satoshisRequired <= 0) {\n throw new Error('Invalid x-bsv-payment-satoshis-required response header value.');\n }\n const serverIdentityKey = originalResponse.headers.get('x-bsv-auth-identity-key');\n if (typeof serverIdentityKey !== 'string') {\n throw new Error('Missing x-bsv-auth-identity-key response header.');\n }\n const derivationPrefix = originalResponse.headers.get('x-bsv-payment-derivation-prefix');\n if (typeof derivationPrefix !== 'string' || derivationPrefix.length < 1) {\n throw new Error('Missing x-bsv-payment-derivation-prefix response header.');\n }\n let paymentContext = config.paymentContext;\n if (paymentContext != null) {\n const requirementsChanged = !this.isPaymentContextCompatible(paymentContext, satoshisRequired, serverIdentityKey, derivationPrefix);\n if (requirementsChanged) {\n this.logPaymentAttempt('warn', 'Server adjusted payment requirements; regenerating transaction', this.composePaymentLogDetails(url, paymentContext));\n paymentContext = await this.createPaymentContext(url, config, satoshisRequired, serverIdentityKey, derivationPrefix);\n }\n }\n else {\n paymentContext = await this.createPaymentContext(url, config, satoshisRequired, serverIdentityKey, derivationPrefix);\n }\n if (paymentContext.attempts >= paymentContext.maxAttempts) {\n throw this.buildPaymentFailureError(url, paymentContext, new Error('Maximum payment attempts exceeded before retrying'));\n }\n const headersWithPayment = {\n ...(config.headers ?? {})\n };\n headersWithPayment['x-bsv-payment'] = JSON.stringify({\n derivationPrefix: paymentContext.derivationPrefix,\n derivationSuffix: paymentContext.derivationSuffix,\n transaction: paymentContext.transactionBase64\n });\n const nextConfig = {\n ...config,\n headers: headersWithPayment,\n paymentContext\n };\n if (typeof nextConfig.retryCounter !== 'number') {\n nextConfig.retryCounter = 3;\n }\n const attemptNumber = paymentContext.attempts + 1;\n const maxAttempts = paymentContext.maxAttempts;\n paymentContext.attempts = attemptNumber;\n const attemptDetails = this.composePaymentLogDetails(url, paymentContext);\n this.logPaymentAttempt('warn', `Attempting paid request (${attemptNumber}/${maxAttempts})`, attemptDetails);\n try {\n const response = await this.fetch(url, nextConfig);\n this.logPaymentAttempt('info', `Paid request attempt ${attemptNumber} succeeded`, attemptDetails);\n return response;\n }\n catch (error) {\n const errorEntry = this.createPaymentErrorEntry(paymentContext.attempts, error);\n paymentContext.errors.push(errorEntry);\n this.logPaymentAttempt('error', `Paid request attempt ${attemptNumber} failed`, {\n ...attemptDetails,\n error: {\n message: errorEntry.message,\n stack: errorEntry.stack\n }\n });\n if (paymentContext.attempts >= paymentContext.maxAttempts) {\n throw this.buildPaymentFailureError(url, paymentContext, error);\n }\n const delayMs = this.getPaymentRetryDelay(paymentContext.attempts);\n await this.wait(delayMs);\n return this.handlePaymentAndRetry(url, nextConfig, originalResponse);\n }\n }\n isPaymentContextCompatible(context, satoshisRequired, serverIdentityKey, derivationPrefix) {\n return (context.satoshisRequired === satoshisRequired &&\n context.serverIdentityKey === serverIdentityKey &&\n context.derivationPrefix === derivationPrefix);\n }\n async createPaymentContext(url, config, satoshisRequired, serverIdentityKey, derivationPrefix) {\n const derivationSuffix = await createNonce(this.wallet, undefined, this.originator);\n const { publicKey: derivedPublicKey } = await this.wallet.getPublicKey({\n protocolID: [2, '3241645161d8'],\n keyID: `${derivationPrefix} ${derivationSuffix}`,\n counterparty: serverIdentityKey\n }, this.originator);\n const lockingScript = new P2PKH().lock(PublicKey.fromString(derivedPublicKey).toAddress()).toHex();\n const { tx } = await this.wallet.createAction({\n description: `Payment for request to ${new URL(url).origin}`,\n outputs: [{\n satoshis: satoshisRequired,\n lockingScript,\n customInstructions: JSON.stringify({ derivationPrefix, derivationSuffix, payee: serverIdentityKey }),\n outputDescription: 'HTTP request payment'\n }],\n options: {\n randomizeOutputs: false\n }\n }, this.originator);\n const { publicKey: clientIdentityKey } = await this.wallet.getPublicKey({ identityKey: true }, this.originator);\n return {\n satoshisRequired,\n transactionBase64: Utils.toBase64(tx),\n derivationPrefix,\n derivationSuffix,\n serverIdentityKey,\n clientIdentityKey,\n attempts: 0,\n maxAttempts: this.getMaxPaymentAttempts(config),\n errors: [],\n requestSummary: this.buildPaymentRequestSummary(url, config)\n };\n }\n getMaxPaymentAttempts(config) {\n const attempts = typeof config.paymentRetryAttempts === 'number' ? config.paymentRetryAttempts : undefined;\n if (typeof attempts === 'number' && attempts > 0) {\n return Math.floor(attempts);\n }\n return 3;\n }\n buildPaymentRequestSummary(url, config) {\n const headers = { ...(config.headers ?? {}) };\n const method = typeof config.method === 'string' ? config.method.toUpperCase() : 'GET';\n const bodySummary = this.describeRequestBodyForLogging(config.body);\n return {\n url,\n method,\n headers,\n bodyType: bodySummary.type,\n bodyByteLength: bodySummary.byteLength\n };\n }\n describeRequestBodyForLogging(body) {\n if (body == null) {\n return { type: 'none', byteLength: 0 };\n }\n if (typeof body === 'string') {\n return { type: 'string', byteLength: Utils.toArray(body, 'utf8').length };\n }\n if (Array.isArray(body)) {\n if (body.every((item) => typeof item === 'number')) {\n return { type: 'number[]', byteLength: body.length };\n }\n return { type: 'array', byteLength: body.length };\n }\n if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {\n return { type: 'ArrayBuffer', byteLength: body.byteLength };\n }\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(body)) {\n return {\n type: body.constructor != null ? body.constructor.name : 'TypedArray',\n byteLength: body.byteLength\n };\n }\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n return { type: 'Blob', byteLength: body.size };\n }\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\n return { type: 'FormData', byteLength: 0 };\n }\n if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {\n const serialized = body.toString();\n return { type: 'URLSearchParams', byteLength: Utils.toArray(serialized, 'utf8').length };\n }\n if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {\n return { type: 'ReadableStream', byteLength: 0 };\n }\n try {\n const serialized = JSON.stringify(body);\n if (typeof serialized === 'string') {\n return { type: 'object', byteLength: Utils.toArray(serialized, 'utf8').length };\n }\n }\n catch (_) {\n // Ignore JSON serialization issues for logging purposes.\n }\n return { type: typeof body, byteLength: 0 };\n }\n composePaymentLogDetails(url, context) {\n return {\n url,\n request: context.requestSummary,\n payment: {\n satoshis: context.satoshisRequired,\n transactionBase64: context.transactionBase64,\n derivationPrefix: context.derivationPrefix,\n derivationSuffix: context.derivationSuffix,\n serverIdentityKey: context.serverIdentityKey,\n clientIdentityKey: context.clientIdentityKey\n },\n attempts: {\n used: context.attempts,\n max: context.maxAttempts\n },\n errors: context.errors\n };\n }\n logPaymentAttempt(level, message, details) {\n const prefix = '[AuthFetch][Payment]';\n if (level === 'error') {\n console.error(`${prefix} ${message}`, details);\n }\n else if (level === 'warn') {\n console.warn(`${prefix} ${message}`, details);\n }\n else {\n if (typeof console.info === 'function') {\n console.info(`${prefix} ${message}`, details);\n }\n else {\n console.log(`${prefix} ${message}`, details);\n }\n }\n }\n createPaymentErrorEntry(attempt, error) {\n const entry = {\n attempt,\n timestamp: new Date().toISOString(),\n message: '',\n stack: undefined\n };\n if (error instanceof Error) {\n entry.message = error.message;\n entry.stack = error.stack ?? undefined;\n }\n else {\n entry.message = String(error);\n }\n return entry;\n }\n getPaymentRetryDelay(attempt) {\n const baseDelay = 250;\n const multiplier = Math.min(attempt, 5);\n return baseDelay * multiplier;\n }\n async wait(ms) {\n if (ms <= 0) {\n return;\n }\n await new Promise(resolve => setTimeout(resolve, ms));\n }\n buildPaymentFailureError(url, context, lastError) {\n const message = `Paid request to ${url} failed after ${context.attempts}/${context.maxAttempts} attempts. Sent ${context.satoshisRequired} satoshis to ${context.serverIdentityKey}.`;\n const error = new Error(message);\n const failureDetails = {\n request: context.requestSummary,\n payment: {\n satoshis: context.satoshisRequired,\n transactionBase64: context.transactionBase64,\n derivationPrefix: context.derivationPrefix,\n derivationSuffix: context.derivationSuffix,\n serverIdentityKey: context.serverIdentityKey,\n clientIdentityKey: context.clientIdentityKey\n },\n attempts: {\n used: context.attempts,\n max: context.maxAttempts\n },\n errors: context.errors\n };\n error.details = failureDetails;\n if (lastError instanceof Error) {\n ;\n error.cause = lastError;\n }\n return error;\n }\n async normalizeBodyToNumberArray(body) {\n // 0. Null / undefined\n if (body == null) {\n return [];\n }\n // 1. object\n if (typeof body === 'object') {\n return Utils.toArray(JSON.stringify(body, 'utf8'));\n }\n // 2. number[]\n if (Array.isArray(body) && body.every((item) => typeof item === 'number')) {\n return body; // Return the array as is\n }\n // 3. string\n if (typeof body === 'string') {\n return Utils.toArray(body, 'utf8');\n }\n // 4. ArrayBuffer / TypedArrays\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n const typedArray = body instanceof ArrayBuffer ? new Uint8Array(body) : new Uint8Array(body.buffer);\n return Array.from(typedArray);\n }\n // 5. Blob\n if (body instanceof Blob) {\n const arrayBuffer = await body.arrayBuffer();\n return Array.from(new Uint8Array(arrayBuffer));\n }\n // 6. FormData\n if (body instanceof FormData) {\n const entries = [];\n body.forEach((value, key) => {\n entries.push([key, value.toString()]);\n });\n const urlEncoded = new URLSearchParams(entries).toString();\n return Utils.toArray(urlEncoded, 'utf8');\n }\n // 7. URLSearchParams\n if (body instanceof URLSearchParams) {\n return Utils.toArray(body.toString(), 'utf8');\n }\n // 8. ReadableStream\n if (body instanceof ReadableStream) {\n throw new Error('ReadableStream cannot be directly converted to number[].');\n }\n // 9. Fallback\n throw new Error('Unsupported body type in this SimplifiedFetch implementation.');\n }\n}\n//# sourceMappingURL=AuthFetch.js.map","import PushDrop from '../script/templates/PushDrop.js';\nimport { Utils } from '../primitives/index.js';\n/**\n * Script template enabling the creation, unlocking, and decoding of SHIP and SLAP advertisements.\n */\nexport default class OverlayAdminTokenTemplate {\n pushDrop;\n /**\n * Decodes a SHIP or SLAP advertisement from a given locking script.\n * @param script Locking script comprising a SHIP or SLAP token to decode\n * @returns Decoded SHIP or SLAP advertisement\n */\n static decode(script) {\n const result = PushDrop.decode(script);\n if (result.fields.length < 4) {\n throw new Error('Invalid SHIP/SLAP advertisement!');\n }\n const protocol = Utils.toUTF8(result.fields[0]);\n if (protocol !== 'SHIP' && protocol !== 'SLAP') {\n throw new Error('Invalid protocol type!');\n }\n const identityKey = Utils.toHex(result.fields[1]);\n const domain = Utils.toUTF8(result.fields[2]);\n const topicOrService = Utils.toUTF8(result.fields[3]);\n return {\n protocol,\n identityKey,\n domain,\n topicOrService\n };\n }\n /**\n * Constructs a new Overlay Admin template instance\n * @param wallet Wallet to use for locking and unlocking\n */\n constructor(wallet, originator) {\n this.pushDrop = new PushDrop(wallet, originator);\n }\n /**\n * Creates a new advertisement locking script\n * @param protocol SHIP or SLAP\n * @param domain Domain where the topic or service is available\n * @param topicOrService Topic or service to advertise\n * @returns Locking script comprising the advertisement token\n */\n async lock(protocol, domain, topicOrService) {\n const { publicKey: identityKey } = await this.pushDrop.wallet.getPublicKey({\n identityKey: true\n });\n return await this.pushDrop.lock([\n Utils.toArray(protocol, 'utf8'),\n Utils.toArray(identityKey, 'hex'),\n Utils.toArray(domain, 'utf8'),\n Utils.toArray(topicOrService, 'utf8')\n ], [\n 2,\n protocol === 'SHIP'\n ? 'Service Host Interconnect'\n : 'Service Lookup Availability'\n ], '1', 'self');\n }\n /**\n * Unlocks an advertisement token as part of a transaction.\n * @param protocol SHIP or SLAP, depending on the token to unlock\n * @returns Script unlocker capable of unlocking the advertisement token\n */\n unlock(protocol) {\n return this.pushDrop.unlock([\n 2,\n protocol === 'SHIP'\n ? 'Service Host Interconnect'\n : 'Service Lookup Availability'\n ], '1', 'self');\n }\n}\n//# sourceMappingURL=OverlayAdminTokenTemplate.js.map","const DEFAULT_LATENCY_MS = 1500;\nconst LATENCY_SMOOTHING_FACTOR = 0.25;\nconst BASE_BACKOFF_MS = 1000;\nconst MAX_BACKOFF_MS = 60_000;\nconst FAILURE_PENALTY_MS = 400;\nconst SUCCESS_BONUS_MS = 30;\nconst FAILURE_BACKOFF_GRACE = 2;\nconst STORAGE_KEY = 'bsvsdk_overlay_host_reputation_v1';\nexport class HostReputationTracker {\n stats;\n store;\n constructor(store) {\n this.stats = new Map();\n this.store = store ?? this.getLocalStorageAdapter();\n this.loadFromStorage();\n }\n reset() {\n this.stats.clear();\n }\n recordSuccess(host, latencyMs) {\n const entry = this.getOrCreate(host);\n const now = Date.now();\n const safeLatency = Number.isFinite(latencyMs) && latencyMs >= 0 ? latencyMs : DEFAULT_LATENCY_MS;\n if (entry.avgLatencyMs === null) {\n entry.avgLatencyMs = safeLatency;\n }\n else {\n entry.avgLatencyMs =\n (1 - LATENCY_SMOOTHING_FACTOR) * entry.avgLatencyMs +\n LATENCY_SMOOTHING_FACTOR * safeLatency;\n }\n entry.lastLatencyMs = safeLatency;\n entry.totalSuccesses += 1;\n entry.consecutiveFailures = 0;\n entry.backoffUntil = 0;\n entry.lastUpdatedAt = now;\n entry.lastError = undefined;\n this.saveToStorage();\n }\n recordFailure(host, reason) {\n const entry = this.getOrCreate(host);\n const now = Date.now();\n entry.totalFailures += 1;\n entry.consecutiveFailures += 1;\n const msg = typeof reason === 'string'\n ? reason\n : reason instanceof Error\n ? reason.message\n : undefined;\n const immediate = typeof msg === 'string' &&\n (msg.includes('ERR_NAME_NOT_RESOLVED') ||\n msg.includes('ENOTFOUND') ||\n msg.includes('getaddrinfo') ||\n msg.includes('Failed to fetch'));\n if (immediate && entry.consecutiveFailures < FAILURE_BACKOFF_GRACE + 1) {\n entry.consecutiveFailures = FAILURE_BACKOFF_GRACE + 1;\n }\n const penaltyLevel = Math.max(entry.consecutiveFailures - FAILURE_BACKOFF_GRACE, 0);\n if (penaltyLevel === 0) {\n entry.backoffUntil = 0;\n }\n else {\n const backoffDuration = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * Math.pow(2, penaltyLevel - 1));\n entry.backoffUntil = now + backoffDuration;\n }\n entry.lastUpdatedAt = now;\n entry.lastError =\n typeof reason === 'string'\n ? reason\n : reason instanceof Error\n ? reason.message\n : undefined;\n this.saveToStorage();\n }\n rankHosts(hosts, now = Date.now()) {\n const seen = new Map();\n hosts.forEach((host, idx) => {\n if (typeof host !== 'string' || host.length === 0)\n return;\n if (!seen.has(host))\n seen.set(host, idx);\n });\n const orderedHosts = Array.from(seen.keys());\n const ranked = orderedHosts.map((host) => {\n const entry = this.getOrCreate(host);\n return {\n ...entry,\n score: this.computeScore(entry, now),\n originalOrder: seen.get(host) ?? 0\n };\n });\n ranked.sort((a, b) => {\n const aInBackoff = a.backoffUntil > now;\n const bInBackoff = b.backoffUntil > now;\n if (aInBackoff !== bInBackoff)\n return aInBackoff ? 1 : -1;\n if (a.score !== b.score)\n return a.score - b.score;\n if (a.totalSuccesses !== b.totalSuccesses)\n return b.totalSuccesses - a.totalSuccesses;\n return a.originalOrder - b.originalOrder;\n });\n return ranked.map(({ originalOrder, ...rest }) => rest);\n }\n snapshot(host) {\n const entry = this.stats.get(host);\n return entry != null ? { ...entry } : undefined;\n }\n getStorage() {\n try {\n const g = typeof globalThis === 'object' ? globalThis : undefined;\n if (g == null || g.localStorage == null)\n return undefined;\n return g.localStorage;\n }\n catch {\n return undefined;\n }\n }\n getLocalStorageAdapter() {\n const s = this.getStorage();\n if (s == null)\n return undefined;\n return {\n get: (key) => {\n try {\n return s.getItem(key);\n }\n catch {\n return null;\n }\n },\n set: (key, value) => {\n try {\n s.setItem(key, value);\n }\n catch { }\n }\n };\n }\n loadFromStorage() {\n const s = this.store;\n if (s == null)\n return;\n try {\n const raw = s.get(STORAGE_KEY);\n if (typeof raw !== 'string' || raw.length === 0)\n return;\n const data = JSON.parse(raw);\n if (typeof data !== 'object' || data === null)\n return;\n this.stats.clear();\n for (const k of Object.keys(data)) {\n const v = (data)[k];\n if (v != null && typeof v === 'object') {\n const entry = {\n host: String(v.host ?? k),\n totalSuccesses: Number(v.totalSuccesses ?? 0),\n totalFailures: Number(v.totalFailures ?? 0),\n consecutiveFailures: Number(v.consecutiveFailures ?? 0),\n avgLatencyMs: v.avgLatencyMs == null ? null : Number(v.avgLatencyMs),\n lastLatencyMs: v.lastLatencyMs == null ? null : Number(v.lastLatencyMs),\n backoffUntil: Number(v.backoffUntil ?? 0),\n lastUpdatedAt: Number(v.lastUpdatedAt ?? 0),\n lastError: typeof v.lastError === 'string' ? v.lastError : undefined\n };\n this.stats.set(entry.host, entry);\n }\n }\n }\n catch { }\n }\n saveToStorage() {\n const s = this.store;\n if (s == null)\n return;\n try {\n const obj = {};\n for (const [host, entry] of this.stats.entries()) {\n obj[host] = entry;\n }\n s.set(STORAGE_KEY, JSON.stringify(obj));\n }\n catch { }\n }\n computeScore(entry, now) {\n const latency = entry.avgLatencyMs ?? DEFAULT_LATENCY_MS;\n const failurePenalty = entry.consecutiveFailures * FAILURE_PENALTY_MS;\n const successBonus = Math.min(entry.totalSuccesses * SUCCESS_BONUS_MS, latency / 2);\n const backoffPenalty = entry.backoffUntil > now ? entry.backoffUntil - now : 0;\n return latency + failurePenalty + backoffPenalty - successBonus;\n }\n getOrCreate(host) {\n let entry = this.stats.get(host);\n if (entry == null) {\n entry = {\n host,\n totalSuccesses: 0,\n totalFailures: 0,\n consecutiveFailures: 0,\n avgLatencyMs: null,\n lastLatencyMs: null,\n backoffUntil: 0,\n lastUpdatedAt: 0\n };\n this.stats.set(host, entry);\n }\n return entry;\n }\n}\nconst globalTracker = new HostReputationTracker();\nexport const getOverlayHostReputationTracker = () => globalTracker;\n//# sourceMappingURL=HostReputationTracker.js.map","import { Transaction } from '../transaction/index.js';\nimport OverlayAdminTokenTemplate from './OverlayAdminTokenTemplate.js';\nimport * as Utils from '../primitives/utils.js';\nimport { getOverlayHostReputationTracker, HostReputationTracker } from './HostReputationTracker.js';\nconst defaultFetch = typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function'\n ? globalThis.fetch.bind(globalThis)\n : fetch;\n/** Default SLAP trackers */\nexport const DEFAULT_SLAP_TRACKERS = [\n // BSVA clusters\n 'https://overlay-us-1.bsvb.tech',\n 'https://overlay-eu-1.bsvb.tech',\n 'https://overlay-ap-1.bsvb.tech',\n // Babbage primary overlay service\n 'https://users.bapp.dev'\n // NOTE: Other entities may submit pull requests to the library if they maintain SLAP overlay services.\n // Additional trackers run by different entities contribute to greater network resiliency.\n // It also generally doesn't hurt to have more trackers in this list.\n // DISCLAIMER:\n // Trackers known to host invalid or illegal records will be removed at the discretion of the BSV Association.\n];\n/** Default testnet SLAP trackers */\nexport const DEFAULT_TESTNET_SLAP_TRACKERS = [\n // Babbage primary testnet overlay service\n 'https://testnet-users.bapp.dev'\n];\nconst MAX_TRACKER_WAIT_TIME = 5000;\nexport class HTTPSOverlayLookupFacilitator {\n fetchClient;\n allowHTTP;\n constructor(httpClient = defaultFetch, allowHTTP = false) {\n if (typeof httpClient !== 'function') {\n throw new Error('HTTPSOverlayLookupFacilitator requires a fetch implementation. ' +\n 'In environments without fetch, provide a polyfill or custom implementation.');\n }\n this.fetchClient = httpClient;\n this.allowHTTP = allowHTTP;\n }\n async lookup(url, question, timeout = 5000) {\n if (!url.startsWith('https:') && !this.allowHTTP) {\n throw new Error('HTTPS facilitator can only use URLs that start with \"https:\"');\n }\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;\n const timer = setTimeout(() => {\n try {\n controller?.abort();\n }\n catch { /* noop */ }\n }, timeout);\n try {\n const fco = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Aggregation': 'yes'\n },\n body: JSON.stringify({ service: question.service, query: question.query }),\n signal: controller?.signal\n };\n const response = await this.fetchClient(`${url}/lookup`, fco);\n if (!response.ok)\n throw new Error(`Failed to facilitate lookup (HTTP ${response.status})`);\n if (response.headers.get('content-type') === 'application/octet-stream') {\n const payload = await response.arrayBuffer();\n const r = new Utils.Reader([...new Uint8Array(payload)]);\n const nOutpoints = r.readVarIntNum();\n const outpoints = [];\n for (let i = 0; i < nOutpoints; i++) {\n const txid = Utils.toHex(r.read(32));\n const outputIndex = r.readVarIntNum();\n const contextLength = r.readVarIntNum();\n let context;\n if (contextLength > 0) {\n context = r.read(contextLength);\n }\n outpoints.push({\n txid,\n outputIndex,\n context\n });\n }\n const beef = r.read();\n return {\n type: 'output-list',\n outputs: outpoints.map(x => ({\n outputIndex: x.outputIndex,\n context: x.context,\n beef: Transaction.fromBEEF(beef, x.txid).toBEEF()\n }))\n };\n }\n else {\n return await response.json();\n }\n }\n catch (e) {\n // Normalize timeouts to a consistent error message\n if (e?.name === 'AbortError')\n throw new Error('Request timed out');\n throw e;\n }\n finally {\n clearTimeout(timer);\n }\n }\n}\n/**\n * Represents a Lookup Resolver.\n */\nexport default class LookupResolver {\n facilitator;\n slapTrackers;\n hostOverrides;\n additionalHosts;\n networkPreset;\n hostReputation;\n // ---- Caches / memoization ----\n hostsCache;\n hostsInFlight;\n hostsTtlMs;\n hostsMaxEntries;\n txMemo;\n txMemoTtlMs;\n constructor(config = {}) {\n this.networkPreset = config.networkPreset ?? 'mainnet';\n this.facilitator = config.facilitator ?? new HTTPSOverlayLookupFacilitator(undefined, this.networkPreset === 'local');\n this.slapTrackers = config.slapTrackers ?? (this.networkPreset === 'mainnet' ? DEFAULT_SLAP_TRACKERS : DEFAULT_TESTNET_SLAP_TRACKERS);\n const hostOverrides = config.hostOverrides ?? {};\n this.assertValidOverrideServices(hostOverrides);\n this.hostOverrides = hostOverrides;\n this.additionalHosts = config.additionalHosts ?? {};\n const rs = config.reputationStorage;\n if (rs === 'localStorage') {\n this.hostReputation = new HostReputationTracker();\n }\n else if (typeof rs === 'object' && rs !== null && typeof rs.get === 'function' && typeof rs.set === 'function') {\n this.hostReputation = new HostReputationTracker(rs);\n }\n else {\n this.hostReputation = getOverlayHostReputationTracker();\n }\n // cache tuning\n this.hostsTtlMs = config.cache?.hostsTtlMs ?? 5 * 60 * 1000; // 5 min\n this.hostsMaxEntries = config.cache?.hostsMaxEntries ?? 128;\n this.txMemoTtlMs = config.cache?.txMemoTtlMs ?? 10 * 60 * 1000; // 10 min\n this.hostsCache = new Map();\n this.hostsInFlight = new Map();\n this.txMemo = new Map();\n }\n /**\n * Given a LookupQuestion, returns a LookupAnswer. Aggregates across multiple services and supports resiliency.\n */\n async query(question, timeout) {\n let competentHosts = [];\n if (question.service === 'ls_slap') {\n competentHosts = this.networkPreset === 'local' ? ['http://localhost:8080'] : this.slapTrackers;\n }\n else if (this.hostOverrides[question.service] != null) {\n competentHosts = this.hostOverrides[question.service];\n }\n else if (this.networkPreset === 'local') {\n competentHosts = ['http://localhost:8080'];\n }\n else {\n competentHosts = await this.getCompetentHostsCached(question.service);\n }\n if (this.additionalHosts[question.service]?.length > 0) {\n // preserve order: resolved hosts first, then additional (unique)\n const extra = this.additionalHosts[question.service];\n const seen = new Set(competentHosts);\n for (const h of extra)\n if (!seen.has(h))\n competentHosts.push(h);\n }\n if (competentHosts.length < 1) {\n throw new Error(`No competent ${this.networkPreset} hosts found by the SLAP trackers for lookup service: ${question.service}`);\n }\n const rankedHosts = this.prepareHostsForQuery(competentHosts, `lookup service ${question.service}`);\n if (rankedHosts.length < 1) {\n throw new Error(`All competent hosts for ${question.service} are temporarily unavailable due to backoff.`);\n }\n // Fire all hosts with per-host timeout, harvest successful output-list responses\n const hostResponses = await Promise.allSettled(rankedHosts.map(async (host) => {\n return await this.lookupHostWithTracking(host, question, timeout);\n }));\n const outputsMap = new Map();\n // Memo key helper for tx parsing\n const beefKey = (beef) => {\n if (typeof beef !== 'object')\n return ''; // The invalid BEEF has an empty key.\n // A fast and deterministic key for memoization; avoids large JSON strings\n // since beef is an array of integers, join is safe and compact.\n return beef.join(',');\n };\n for (const result of hostResponses) {\n if (result.status !== 'fulfilled')\n continue;\n const response = result.value;\n if (response?.type !== 'output-list' || !Array.isArray(response.outputs))\n continue;\n for (const output of response.outputs) {\n const keyForBeef = beefKey(output.beef);\n let memo = this.txMemo.get(keyForBeef);\n const now = Date.now();\n if (typeof memo !== 'object' || memo === null || memo.expiresAt <= now) {\n try {\n const txId = Transaction.fromBEEF(output.beef).id('hex');\n memo = { txId, expiresAt: now + this.txMemoTtlMs };\n // prune opportunistically if the map gets too large (cheap heuristic)\n if (this.txMemo.size > 4096)\n this.evictOldest(this.txMemo);\n this.txMemo.set(keyForBeef, memo);\n }\n catch {\n continue;\n }\n }\n const uniqKey = `${memo.txId}.${output.outputIndex}`;\n // last-writer wins is fine here; outputs are identical if uniqKey matches\n outputsMap.set(uniqKey, output);\n }\n }\n return {\n type: 'output-list',\n outputs: Array.from(outputsMap.values())\n };\n }\n /**\n * Cached wrapper for competent host discovery with stale-while-revalidate.\n */\n async getCompetentHostsCached(service) {\n const now = Date.now();\n const cached = this.hostsCache.get(service);\n // if fresh, return immediately\n if (typeof cached === 'object' && cached.expiresAt > now) {\n return cached.hosts.slice();\n }\n // if stale but present, kick off a refresh if not already in-flight and return stale\n if (typeof cached === 'object' && cached.expiresAt <= now) {\n if (!this.hostsInFlight.has(service)) {\n this.hostsInFlight.set(service, this.refreshHosts(service).finally(() => {\n this.hostsInFlight.delete(service);\n }));\n }\n return cached.hosts.slice();\n }\n // no cache: coalesce concurrent requests\n if (this.hostsInFlight.has(service)) {\n try {\n const hosts = await this.hostsInFlight.get(service);\n if (typeof hosts !== 'object') {\n throw new Error('Hosts is not defined.');\n }\n return hosts.slice();\n }\n catch {\n // fall through to a fresh attempt below\n }\n }\n const promise = this.refreshHosts(service).finally(() => {\n this.hostsInFlight.delete(service);\n });\n this.hostsInFlight.set(service, promise);\n const hosts = await promise;\n return hosts.slice();\n }\n /**\n * Actually resolves competent hosts from SLAP trackers and updates cache.\n */\n async refreshHosts(service) {\n const hosts = await this.findCompetentHosts(service);\n const expiresAt = Date.now() + this.hostsTtlMs;\n // bounded cache with simple FIFO eviction\n if (!this.hostsCache.has(service) && this.hostsCache.size >= this.hostsMaxEntries) {\n const oldestKey = this.hostsCache.keys().next().value;\n if (oldestKey !== undefined)\n this.hostsCache.delete(oldestKey);\n }\n this.hostsCache.set(service, { hosts, expiresAt });\n return hosts;\n }\n /**\n * Returns a list of competent hosts for a given lookup service.\n * @param service Service for which competent hosts are to be returned\n * @returns Array of hosts competent for resolving queries\n */\n async findCompetentHosts(service) {\n const query = {\n service: 'ls_slap',\n query: { service }\n };\n // Query all SLAP trackers; tolerate failures.\n const trackerHosts = this.prepareHostsForQuery(this.slapTrackers, 'SLAP trackers');\n if (trackerHosts.length === 0)\n return [];\n const trackerResponses = await Promise.allSettled(trackerHosts.map(async (tracker) => await this.lookupHostWithTracking(tracker, query, MAX_TRACKER_WAIT_TIME)));\n const hosts = new Set();\n for (const result of trackerResponses) {\n if (result.status !== 'fulfilled')\n continue;\n const answer = result.value;\n if (answer.type !== 'output-list')\n continue;\n for (const output of answer.outputs) {\n try {\n const tx = Transaction.fromBEEF(output.beef);\n const script = tx.outputs[output.outputIndex]?.lockingScript;\n if (typeof script !== 'object' || script === null)\n continue;\n const parsed = OverlayAdminTokenTemplate.decode(script);\n if (parsed.topicOrService !== service || parsed.protocol !== 'SLAP')\n continue;\n if (typeof parsed.domain === 'string' && parsed.domain.length > 0) {\n hosts.add(parsed.domain);\n }\n }\n catch {\n continue;\n }\n }\n }\n return [...hosts];\n }\n /** Evict an arbitrary “oldest” entry from a Map (iteration order). */\n evictOldest(m) {\n const firstKey = m.keys().next().value;\n if (firstKey !== undefined)\n m.delete(firstKey);\n }\n assertValidOverrideServices(overrides) {\n for (const service of Object.keys(overrides)) {\n if (!service.startsWith('ls_')) {\n throw new Error(`Host override service names must start with \"ls_\": ${service}`);\n }\n }\n }\n prepareHostsForQuery(hosts, context) {\n if (hosts.length === 0)\n return [];\n const now = Date.now();\n const ranked = this.hostReputation.rankHosts(hosts, now);\n const available = ranked.filter((h) => h.backoffUntil <= now).map((h) => h.host);\n if (available.length > 0)\n return available;\n const soonest = Math.min(...ranked.map((h) => h.backoffUntil));\n const waitMs = Math.max(soonest - now, 0);\n throw new Error(`All ${context} hosts are backing off for approximately ${waitMs}ms due to repeated failures.`);\n }\n async lookupHostWithTracking(host, question, timeout) {\n const startedAt = Date.now();\n try {\n const answer = await this.facilitator.lookup(host, question, timeout);\n const latency = Date.now() - startedAt;\n const isValid = typeof answer === 'object' &&\n answer !== null &&\n answer.type === 'output-list' &&\n Array.isArray((answer).outputs);\n if (isValid) {\n this.hostReputation.recordSuccess(host, latency);\n }\n else {\n this.hostReputation.recordFailure(host, 'Invalid lookup response');\n }\n return answer;\n }\n catch (err) {\n this.hostReputation.recordFailure(host, err);\n throw err;\n }\n }\n}\n//# sourceMappingURL=LookupResolver.js.map","import { Transaction } from '../transaction/index.js';\nimport * as Utils from '../primitives/utils.js';\nimport LookupResolver from './LookupResolver.js';\nimport OverlayAdminTokenTemplate from './OverlayAdminTokenTemplate.js';\nconst MAX_SHIP_QUERY_TIMEOUT = 5000;\nexport class HTTPSOverlayBroadcastFacilitator {\n httpClient;\n allowHTTP;\n constructor(httpClient = fetch, allowHTTP = false) {\n this.httpClient = httpClient;\n this.allowHTTP = allowHTTP;\n }\n async send(url, taggedBEEF) {\n if (!url.startsWith('https:') && !this.allowHTTP) {\n throw new Error('HTTPS facilitator can only use URLs that start with \"https:\"');\n }\n const headers = {\n 'Content-Type': 'application/octet-stream',\n 'X-Topics': JSON.stringify(taggedBEEF.topics)\n };\n let body;\n if (Array.isArray(taggedBEEF.offChainValues)) {\n headers['x-includes-off-chain-values'] = 'true';\n const w = new Utils.Writer();\n w.writeVarIntNum(taggedBEEF.beef.length);\n w.write(taggedBEEF.beef);\n w.write(taggedBEEF.offChainValues);\n body = new Uint8Array(w.toArray());\n }\n else {\n body = new Uint8Array(taggedBEEF.beef);\n }\n const response = await fetch(`${url}/submit`, {\n method: 'POST',\n headers,\n body\n });\n if (response.ok) {\n return await response.json();\n }\n else {\n throw new Error('Failed to facilitate broadcast');\n }\n }\n}\n/**\n * Broadcasts transactions to one or more overlay topics.\n */\nexport default class TopicBroadcaster {\n topics;\n facilitator;\n resolver;\n requireAcknowledgmentFromAllHostsForTopics;\n requireAcknowledgmentFromAnyHostForTopics;\n requireAcknowledgmentFromSpecificHostsForTopics;\n networkPreset;\n /**\n * Constructs an instance of the SHIP broadcaster.\n *\n * @param {string[]} topics - The list of SHIP topic names where transactions are to be sent.\n * @param {SHIPBroadcasterConfig} config - Configuration options for the SHIP broadcaster.\n */\n constructor(topics, config = {}) {\n if (topics.length === 0) {\n throw new Error('At least one topic is required for broadcast.');\n }\n if (topics.some((x) => !x.startsWith('tm_'))) {\n throw new Error('Every topic must start with \"tm_\".');\n }\n this.topics = topics;\n this.networkPreset = config.networkPreset ?? 'mainnet';\n this.facilitator = config.facilitator ?? new HTTPSOverlayBroadcastFacilitator(undefined, this.networkPreset === 'local');\n this.resolver = config.resolver ?? new LookupResolver({ networkPreset: this.networkPreset });\n this.requireAcknowledgmentFromAllHostsForTopics =\n config.requireAcknowledgmentFromAllHostsForTopics ?? [];\n this.requireAcknowledgmentFromAnyHostForTopics =\n config.requireAcknowledgmentFromAnyHostForTopics ?? 'all';\n this.requireAcknowledgmentFromSpecificHostsForTopics =\n config.requireAcknowledgmentFromSpecificHostsForTopics ?? {};\n }\n /**\n * Broadcasts a transaction to Overlay Services via SHIP.\n *\n * @param {Transaction} tx - The transaction to be sent.\n * @returns {Promise<BroadcastResponse | BroadcastFailure>} A promise that resolves to either a success or failure response.\n */\n async broadcast(tx) {\n let beef;\n const offChainValues = tx.metadata.get('OffChainValues');\n try {\n beef = tx.toBEEF();\n }\n catch (error) {\n throw new Error('Transactions sent via SHIP to Overlay Services must be serializable to BEEF format.');\n }\n const interestedHosts = await this.findInterestedHosts();\n if (Object.keys(interestedHosts).length === 0) {\n return {\n status: 'error',\n code: 'ERR_NO_HOSTS_INTERESTED',\n description: `No ${this.networkPreset} hosts are interested in receiving this transaction.`\n };\n }\n const hostPromises = Object.entries(interestedHosts).map(async ([host, topics]) => {\n try {\n const steak = await this.facilitator.send(host, {\n beef,\n offChainValues,\n topics: [...topics]\n });\n if (steak == null || Object.keys(steak).length === 0) {\n throw new Error('Steak has no topics.');\n }\n return { host, success: true, steak };\n }\n catch (error) {\n console.error(error);\n // Log error if needed\n return { host, success: false, error };\n }\n });\n const results = await Promise.all(hostPromises);\n const successfulHosts = results.filter((result) => result.success);\n if (successfulHosts.length === 0) {\n return {\n status: 'error',\n code: 'ERR_ALL_HOSTS_REJECTED',\n description: `All ${this.networkPreset} topical hosts have rejected the transaction.`\n };\n }\n // Collect host acknowledgments\n const hostAcknowledgments = {};\n for (const result of successfulHosts) {\n const host = result.host;\n const steak = result.steak;\n const acknowledgedTopics = new Set();\n for (const [topic, instructions] of Object.entries(steak)) {\n const outputsToAdmit = instructions.outputsToAdmit;\n const coinsToRetain = instructions.coinsToRetain;\n const coinsRemoved = instructions.coinsRemoved;\n if (outputsToAdmit?.length > 0 ||\n coinsToRetain?.length > 0 ||\n coinsRemoved?.length > 0) {\n acknowledgedTopics.add(topic);\n }\n }\n hostAcknowledgments[host] = acknowledgedTopics;\n }\n // Now, perform the checks\n // Check requireAcknowledgmentFromAllHostsForTopics\n let requiredTopicsAllHosts;\n let requireAllHosts;\n if (this.requireAcknowledgmentFromAllHostsForTopics === 'all') {\n requiredTopicsAllHosts = this.topics;\n requireAllHosts = 'all';\n }\n else if (this.requireAcknowledgmentFromAllHostsForTopics === 'any') {\n requiredTopicsAllHosts = this.topics;\n requireAllHosts = 'any';\n }\n else if (Array.isArray(this.requireAcknowledgmentFromAllHostsForTopics)) {\n requiredTopicsAllHosts = this.requireAcknowledgmentFromAllHostsForTopics;\n requireAllHosts = 'all';\n }\n else {\n // Default to 'all' and 'all'\n requiredTopicsAllHosts = this.topics;\n requireAllHosts = 'all';\n }\n if (requiredTopicsAllHosts.length > 0) {\n const allHostsAcknowledged = this.checkAcknowledgmentFromAllHosts(hostAcknowledgments, requiredTopicsAllHosts, requireAllHosts);\n if (!allHostsAcknowledged) {\n return {\n status: 'error',\n code: 'ERR_REQUIRE_ACK_FROM_ALL_HOSTS_FAILED',\n description: 'Not all hosts acknowledged the required topics.'\n };\n }\n }\n // Check requireAcknowledgmentFromAnyHostForTopics\n let requiredTopicsAnyHost;\n let requireAnyHost;\n if (this.requireAcknowledgmentFromAnyHostForTopics === 'all') {\n requiredTopicsAnyHost = this.topics;\n requireAnyHost = 'all';\n }\n else if (this.requireAcknowledgmentFromAnyHostForTopics === 'any') {\n requiredTopicsAnyHost = this.topics;\n requireAnyHost = 'any';\n }\n else if (Array.isArray(this.requireAcknowledgmentFromAnyHostForTopics)) {\n requiredTopicsAnyHost = this.requireAcknowledgmentFromAnyHostForTopics;\n requireAnyHost = 'all';\n }\n else {\n // No requirement\n requiredTopicsAnyHost = [];\n requireAnyHost = 'all';\n }\n if (requiredTopicsAnyHost.length > 0) {\n const anyHostAcknowledged = this.checkAcknowledgmentFromAnyHost(hostAcknowledgments, requiredTopicsAnyHost, requireAnyHost);\n if (!anyHostAcknowledged) {\n return {\n status: 'error',\n code: 'ERR_REQUIRE_ACK_FROM_ANY_HOST_FAILED',\n description: 'No host acknowledged the required topics.'\n };\n }\n }\n // Check requireAcknowledgmentFromSpecificHostsForTopics\n if (Object.keys(this.requireAcknowledgmentFromSpecificHostsForTopics).length >\n 0) {\n const specificHostsAcknowledged = this.checkAcknowledgmentFromSpecificHosts(hostAcknowledgments, this.requireAcknowledgmentFromSpecificHostsForTopics);\n if (!specificHostsAcknowledged) {\n return {\n status: 'error',\n code: 'ERR_REQUIRE_ACK_FROM_SPECIFIC_HOSTS_FAILED',\n description: 'Specific hosts did not acknowledge the required topics.'\n };\n }\n }\n // If all checks pass, return success\n return {\n status: 'success',\n txid: tx.id('hex'),\n message: `Sent to ${successfulHosts.length} Overlay Services ${successfulHosts.length === 1 ? 'host' : 'hosts'}.`\n };\n }\n checkAcknowledgmentFromAllHosts(hostAcknowledgments, requiredTopics, require) {\n for (const acknowledgedTopics of Object.values(hostAcknowledgments)) {\n if (require === 'all') {\n for (const topic of requiredTopics) {\n if (!acknowledgedTopics.has(topic)) {\n return false;\n }\n }\n }\n else if (require === 'any') {\n let anyAcknowledged = false;\n for (const topic of requiredTopics) {\n if (acknowledgedTopics.has(topic)) {\n anyAcknowledged = true;\n break;\n }\n }\n if (!anyAcknowledged) {\n return false;\n }\n }\n }\n return true;\n }\n checkAcknowledgmentFromAnyHost(hostAcknowledgments, requiredTopics, require) {\n if (require === 'all') {\n // All required topics must be acknowledged by at least one host\n for (const acknowledgedTopics of Object.values(hostAcknowledgments)) {\n let acknowledgesAllRequiredTopics = true;\n for (const topic of requiredTopics) {\n if (!acknowledgedTopics.has(topic)) {\n acknowledgesAllRequiredTopics = false;\n break;\n }\n }\n if (acknowledgesAllRequiredTopics) {\n return true;\n }\n }\n return false;\n }\n else {\n // At least one required topic must be acknowledged by at least one host\n for (const acknowledgedTopics of Object.values(hostAcknowledgments)) {\n for (const topic of requiredTopics) {\n if (acknowledgedTopics.has(topic)) {\n return true;\n }\n }\n }\n return false;\n }\n }\n checkAcknowledgmentFromSpecificHosts(hostAcknowledgments, requirements) {\n for (const [host, requiredTopicsOrAllAny] of Object.entries(requirements)) {\n const acknowledgedTopics = hostAcknowledgments[host];\n if (acknowledgedTopics == null) {\n // Host did not respond successfully\n return false;\n }\n let requiredTopics;\n let require;\n if (requiredTopicsOrAllAny === 'all' ||\n requiredTopicsOrAllAny === 'any') {\n require = requiredTopicsOrAllAny;\n requiredTopics = this.topics;\n }\n else if (Array.isArray(requiredTopicsOrAllAny)) {\n requiredTopics = requiredTopicsOrAllAny;\n require = 'all';\n }\n else {\n // Invalid configuration\n continue;\n }\n if (require === 'all') {\n for (const topic of requiredTopics) {\n if (!acknowledgedTopics.has(topic)) {\n return false;\n }\n }\n }\n else if (require === 'any') {\n let anyAcknowledged = false;\n for (const topic of requiredTopics) {\n if (acknowledgedTopics.has(topic)) {\n anyAcknowledged = true;\n break;\n }\n }\n if (!anyAcknowledged) {\n return false;\n }\n }\n }\n return true;\n }\n /**\n * Finds which hosts are interested in transactions tagged with the given set of topics.\n *\n * @returns A mapping of URLs for hosts interested in this transaction. Keys are URLs, values are which of our topics the specific host cares about.\n */\n async findInterestedHosts() {\n // Handle the local network preset\n if (this.networkPreset === 'local') {\n const resultSet = new Set();\n for (let i = 0; i < this.topics.length; i++) {\n resultSet.add(this.topics[i]);\n }\n return { 'http://localhost:8080': resultSet };\n }\n // TODO: cache the list of interested hosts to avoid spamming SHIP trackers.\n // TODO: Monetize the operation of the SHIP tracker system.\n // TODO: Cache ship/slap lookup with expiry (every 5min)\n // Find all SHIP advertisements for the topics we care about\n const results = {};\n const answer = await this.resolver.query({\n service: 'ls_ship',\n query: {\n topics: this.topics\n }\n }, MAX_SHIP_QUERY_TIMEOUT);\n if (answer.type !== 'output-list') {\n throw new Error('SHIP answer is not an output list.');\n }\n for (const output of answer.outputs) {\n try {\n const tx = Transaction.fromBEEF(output.beef);\n const script = tx.outputs[output.outputIndex].lockingScript;\n const parsed = OverlayAdminTokenTemplate.decode(script);\n if (!this.topics.includes(parsed.topicOrService) ||\n parsed.protocol !== 'SHIP') {\n // This should make us think a LOT less highly of this SHIP tracker if it ever happens...\n continue;\n }\n if (results[parsed.domain] === undefined) {\n results[parsed.domain] = new Set();\n }\n results[parsed.domain].add(parsed.topicOrService);\n }\n catch (e) {\n continue;\n }\n }\n return results;\n }\n}\n//# sourceMappingURL=SHIPBroadcaster.js.map","import Transaction from '../transaction/Transaction.js';\n/**\n * Maximum number of retry attempts for double-spend resolution\n */\nconst MAX_DOUBLE_SPEND_RETRIES = 5;\n/**\n * Executes an operation with automatic retry logic for double-spend errors.\n * When a double-spend is detected, broadcasts the competing transaction to\n * update the overlay with missing state, then retries the operation.\n *\n * @param operation - The async operation to execute (e.g., createAction + signAction)\n * @param broadcaster - The TopicBroadcaster to use for syncing missing state\n * @param maxRetries - Maximum number of retry attempts (default: MAX_DOUBLE_SPEND_RETRIES)\n * @returns The result of the successful operation\n * @throws If max retries exceeded or non-double-spend error occurs\n */\nexport async function withDoubleSpendRetry(operation, broadcaster, maxRetries = MAX_DOUBLE_SPEND_RETRIES) {\n let attempts = 0;\n while (attempts < maxRetries) {\n attempts++;\n try {\n return await operation();\n }\n catch (error) {\n // Only handle double-spend errors on non-final attempts\n if (attempts < maxRetries && error.name === 'WERR_REVIEW_ACTIONS') {\n const reviewError = error;\n // Check if any action in the batch has a double-spend\n const doubleSpendResult = reviewError.reviewActionResults.find((result) => result.status === 'doubleSpend');\n if (doubleSpendResult?.competingBeef != null &&\n doubleSpendResult?.competingTxs != null &&\n doubleSpendResult?.competingTxs.length > 0) {\n const competingTx = Transaction.fromBEEF(doubleSpendResult.competingBeef, doubleSpendResult.competingTxs[0]);\n // Recursively handle double-spend errors during broadcast\n // The broadcast itself might fail if the competing tx depends on another missing tx\n await withDoubleSpendRetry(async () => await broadcaster.broadcast(competingTx), broadcaster, maxRetries - attempts // Reduce max retries based on attempts already used\n );\n continue;\n }\n }\n // Non-double-spend error or max retries exceeded - rethrow\n throw error;\n }\n }\n // This should never be reached, but TypeScript requires it\n throw new Error('Unexpected end of retry loop');\n}\n//# sourceMappingURL=withDoubleSpendRetry.js.map","import { toHex, fromBase58Check, toBase58Check, toArray } from '../primitives/utils.js';\nimport { Hash } from '../primitives/index.js';\n/**\n * Takes a UHRP URL and removes any prefixes.\n * @param {string} URL - The UHRP URL.\n * @returns {string} - Normalized URL.\n */\nexport const normalizeURL = (URL) => {\n if (URL.toLowerCase().startsWith('uhrp:'))\n URL = URL.slice(5);\n if (URL.startsWith('//'))\n URL = URL.slice(2);\n return URL;\n};\n/**\n * Generates a UHRP URL from a given SHA-256 hash.\n * @param {number[]} hash - 32-byte SHA-256 hash.\n * @returns {string} - Base58Check encoded URL.\n */\nexport const getURLForHash = (hash) => {\n if (hash.length !== 32) {\n throw new Error('Hash length must be 32 bytes (sha256)');\n }\n return toBase58Check(hash, toArray('ce00', 'hex'));\n};\n/**\n * Generates a UHRP URL for a given file.\n * Uses a streaming hash to avoid excessive memory usage with large files.\n * @param {Uint8Array | number[]} file - File content as a typed array or number array.\n * @returns {string} - Base58Check encoded URL.\n */\nexport const getURLForFile = (file) => {\n const data = file instanceof Uint8Array ? file : Uint8Array.from(file);\n const hasher = new Hash.SHA256();\n const chunkSize = 1024 * 1024;\n for (let i = 0; i < data.length; i += chunkSize) {\n const chunk = data.subarray(i, i + chunkSize);\n hasher.update(Array.from(chunk));\n }\n const hash = hasher.digest();\n return getURLForHash(hash);\n};\n/**\n * Extracts the hash from a UHRP URL.\n * @param {string} URL - UHRP URL.\n * @returns {number[]} - Extracted SHA-256 hash.\n */\nexport const getHashFromURL = (URL) => {\n URL = normalizeURL(URL);\n const { data, prefix } = fromBase58Check(URL, undefined, 2);\n if (data.length !== 32) {\n throw new Error('Invalid length!');\n }\n if (toHex(prefix) !== 'ce00') {\n throw new Error('Bad prefix');\n }\n return data;\n};\n/**\n * Checks if a URL is a valid UHRP URL.\n * @param {string} URL - The URL to validate.\n * @returns {boolean} - True if valid, false otherwise.\n */\nexport const isValidURL = (URL) => {\n try {\n getHashFromURL(URL);\n return true;\n }\n catch (e) {\n return false;\n }\n};\n//# sourceMappingURL=StorageUtils.js.map","import { AuthFetch } from '../auth/clients/AuthFetch.js';\nimport * as StorageUtils from './StorageUtils.js';\n/**\n * The StorageUploader class provides client-side methods for:\n * - Uploading files with a specified retention period\n * - Finding file metadata by UHRP URL\n * - Listing all user uploads\n * - Renewing an existing advertisement's expiry time\n */\nexport class StorageUploader {\n authFetch;\n baseURL;\n /**\n * Creates a new StorageUploader instance.\n * @param {UploaderConfig} config - An object containing the storage server's URL and a wallet interface\n */\n constructor(config) {\n this.baseURL = config.storageURL;\n this.authFetch = new AuthFetch(config.wallet);\n }\n /**\n * Requests information from the server to upload a file (including presigned URL and headers).\n * @private\n * @param {number} fileSize - The size of the file, in bytes\n * @param {number} retentionPeriod - The desired hosting time, in minutes\n * @returns {Promise<{ uploadURL: string; requiredHeaders: Record<string, string>; amount?: number }>}\n * @throws {Error} If the server returns a non-OK response or an error status\n */\n async getUploadInfo(fileSize, retentionPeriod) {\n const url = `${this.baseURL}/upload`;\n const body = { fileSize, retentionPeriod };\n const response = await this.authFetch.fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body)\n });\n if (!response.ok) {\n throw new Error(`Upload info request failed: HTTP ${response.status}`);\n }\n const data = await response.json();\n if (data.status === 'error') {\n throw new Error('Upload route returned an error.');\n }\n return {\n uploadURL: data.uploadURL,\n requiredHeaders: data.requiredHeaders,\n amount: data.amount\n };\n }\n /**\n * Performs the actual file upload (HTTP PUT) to the presigned URL returned by the server.\n * @private\n * @param {string} uploadURL - The presigned URL where the file is to be uploaded\n * @param {UploadableFile} file - The file to upload, including its raw data and MIME type\n * @param {Record<string, string>} requiredHeaders - Additional headers required by the server (e.g. content-length)\n * @returns {Promise<UploadFileResult>} An object indicating whether publishing was successful and the resulting UHRP URL\n * @throws {Error} If the server returns a non-OK response\n */\n async uploadFile(uploadURL, file, requiredHeaders) {\n const body = file.data instanceof Uint8Array ? file.data : Uint8Array.from(file.data);\n const response = await fetch(uploadURL, {\n method: 'PUT',\n body: body,\n headers: {\n 'Content-Type': file.type,\n ...requiredHeaders\n }\n });\n if (!response.ok) {\n throw new Error(`File upload failed: HTTP ${response.status}`);\n }\n const uhrpURL = StorageUtils.getURLForFile(body);\n return {\n published: true,\n uhrpURL\n };\n }\n /**\n * Publishes a file to the storage server with the specified retention period.\n *\n * This will:\n * 1. Request an upload URL from the server.\n * 2. Perform an HTTP PUT to upload the file’s raw bytes.\n * 3. Return a UHRP URL referencing the file once published.\n *\n * @param {Object} params\n * @param {UploadableFile} params.file - The file data + type\n * @param {number} params.retentionPeriod - Number of minutes to host the file\n * @returns {Promise<UploadFileResult>} An object with the file's UHRP URL\n * @throws {Error} If the server or upload step returns a non-OK response\n */\n async publishFile(params) {\n const { file, retentionPeriod } = params;\n const data = file.data instanceof Uint8Array ? file.data : Uint8Array.from(file.data);\n const fileSize = data.byteLength;\n const { uploadURL, requiredHeaders } = await this.getUploadInfo(fileSize, retentionPeriod);\n return await this.uploadFile(uploadURL, { data, type: file.type }, requiredHeaders);\n }\n /**\n * Retrieves metadata for a file matching the given UHRP URL from the `/find` route.\n * @param {string} uhrpUrl - The UHRP URL, e.g. \"uhrp://abcd...\"\n * @returns {Promise<FindFileData>} An object with file name, size, MIME type, and expiry time\n * @throws {Error} If the server or the route returns an error\n */\n async findFile(uhrpUrl) {\n const url = new URL(`${this.baseURL}/find`);\n url.searchParams.set('uhrpUrl', uhrpUrl);\n const response = await this.authFetch.fetch(url.toString(), {\n method: 'GET'\n });\n if (!response.ok) {\n throw new Error(`findFile request failed: HTTP ${response.status}`);\n }\n const data = await response.json();\n if (data.status === 'error') {\n const errCode = data.code ?? 'unknown-code';\n const errDesc = data.description ?? 'no-description';\n throw new Error(`findFile returned an error: ${errCode} - ${errDesc}`);\n }\n return data.data;\n }\n /**\n * Lists all advertisements belonging to the user from the `/list` route.\n * @returns {Promise<any>} The array of uploads returned by the server\n * @throws {Error} If the server or the route returns an error\n */\n async listUploads() {\n const url = `${this.baseURL}/list`;\n const response = await this.authFetch.fetch(url, {\n method: 'GET'\n });\n if (!response.ok) {\n throw new Error(`listUploads request failed: HTTP ${response.status}`);\n }\n const data = await response.json();\n if (data.status === 'error') {\n const errCode = data.code ?? 'unknown-code';\n const errDesc = data.description ?? 'no-description';\n throw new Error(`listUploads returned an error: ${errCode} - ${errDesc}`);\n }\n return data.uploads;\n }\n /**\n * Renews the hosting time for an existing file advertisement identified by uhrpUrl.\n * Calls the `/renew` route to add `additionalMinutes` to the GCS customTime\n * and re-mint the advertisement token on-chain.\n *\n * @param {string} uhrpUrl - The UHRP URL of the file (e.g., \"uhrp://abcd1234...\")\n * @param {number} additionalMinutes - The number of minutes to extend\n * @returns {Promise<RenewFileResult>} An object with the new and previous expiry times, plus any cost\n * @throws {Error} If the request fails or the server returns an error\n */\n async renewFile(uhrpUrl, additionalMinutes) {\n const url = `${this.baseURL}/renew`;\n const body = { uhrpUrl, additionalMinutes };\n const response = await this.authFetch.fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body)\n });\n if (!response.ok) {\n throw new Error(`renewFile request failed: HTTP ${response.status}`);\n }\n const data = await response.json();\n if (data.status === 'error') {\n const errCode = data.code ?? 'unknown-code';\n const errDesc = data.description ?? 'no-description';\n throw new Error(`renewFile returned an error: ${errCode} - ${errDesc}`);\n }\n return {\n status: data.status,\n prevExpiryTime: data.prevExpiryTime,\n newExpiryTime: data.newExpiryTime,\n amount: data.amount\n };\n }\n}\n//# sourceMappingURL=StorageUploader.js.map","import { LookupResolver } from '../overlay-tools/index.js';\nimport { StorageUtils } from './index.js';\nimport PushDrop from '../script/templates/PushDrop.js';\nimport Transaction from '../transaction/Transaction.js';\nimport { Hash, Utils } from '../primitives/index.js';\nexport class StorageDownloader {\n networkPreset = 'mainnet';\n lookupResolver;\n constructor(config) {\n this.networkPreset = config?.networkPreset ?? 'mainnet';\n this.lookupResolver = new LookupResolver({ networkPreset: this.networkPreset });\n }\n /**\n * Resolves the UHRP URL to a list of HTTP URLs where content can be downloaded.\n * @param uhrpUrl The UHRP URL to resolve.\n * @returns A promise that resolves to an array of HTTP URLs.\n */\n async resolve(uhrpUrl) {\n // Use UHRP lookup service\n const response = await this.lookupResolver.query({ service: 'ls_uhrp', query: { uhrpUrl } });\n if (response.type !== 'output-list') {\n throw new Error('Lookup answer must be an output list');\n }\n const decodedResults = [];\n const currentTime = Math.floor(Date.now() / 1000);\n for (let i = 0; i < response.outputs.length; i++) {\n const tx = Transaction.fromBEEF(response.outputs[i].beef);\n const { fields } = PushDrop.decode(tx.outputs[response.outputs[i].outputIndex].lockingScript);\n const expiryTime = new Utils.Reader(fields[3]).readVarIntNum();\n if (expiryTime < currentTime) {\n continue;\n }\n decodedResults.push(Utils.toUTF8(fields[2]));\n }\n return decodedResults;\n }\n /**\n * Downloads the content from the UHRP URL after validating the hash for integrity.\n * @param uhrpUrl The UHRP URL to download.\n * @returns A promise that resolves to the downloaded content.\n */\n async download(uhrpUrl) {\n if (!StorageUtils.isValidURL(uhrpUrl)) {\n throw new Error('Invalid parameter UHRP url');\n }\n const hash = StorageUtils.getHashFromURL(uhrpUrl);\n const expected = Utils.toHex(hash);\n const downloadURLs = await this.resolve(uhrpUrl);\n if (!Array.isArray(downloadURLs) || downloadURLs.length === 0) {\n throw new Error('No one currently hosts this file!');\n }\n for (let i = 0; i < downloadURLs.length; i++) {\n try {\n // The url is fetched\n const result = await fetch(downloadURLs[i], { method: 'GET' });\n // If the request fails, continue to the next url\n if (!result.ok || result.status >= 400 || result.body == null) {\n continue;\n }\n const reader = result.body.getReader();\n const hashStream = new Hash.SHA256();\n const chunks = [];\n let totalLength = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n hashStream.update(Array.from(value));\n chunks.push(value);\n totalLength += value.length;\n }\n const digest = Utils.toHex(hashStream.digest());\n if (digest !== expected) {\n throw new Error('Data integrity error: value of content does not match hash of the url given');\n }\n const data = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n data.set(chunk, offset);\n offset += chunk.length;\n }\n return {\n data,\n mimeType: result.headers.get('Content-Type')\n };\n }\n catch (error) {\n continue;\n }\n }\n throw new Error(`Unable to download content from ${uhrpUrl}`);\n }\n}\n//# sourceMappingURL=StorageDownloader.js.map","export const defaultIdentity = {\n name: 'Unknown Identity',\n avatarURL: 'XUUB8bbn9fEthk15Ge3zTQXypUShfC94vFjp65v7u5CQ8qkpxzst',\n identityKey: '',\n abbreviatedKey: '',\n badgeIconURL: 'XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG',\n badgeLabel: 'Not verified by anyone you trust.',\n badgeClickURL: 'https://projectbabbage.com/docs/unknown-identity'\n};\nexport const DEFAULT_IDENTITY_CLIENT_OPTIONS = {\n protocolID: [1, 'identity'],\n keyID: '1',\n tokenAmount: 1,\n outputIndex: 0\n};\nexport const KNOWN_IDENTITY_TYPES = {\n identiCert: 'z40BOInXkI8m7f/wBrv4MJ09bZfzZbTj2fJqCtONqCY=',\n discordCert: '2TgqRC35B1zehGmB21xveZNc7i5iqHc0uxMb+1NMPW4=',\n phoneCert: 'mffUklUzxbHr65xLohn0hRL0Tq2GjW1GYF/OPfzqJ6A=',\n xCert: 'vdDWvftf1H+5+ZprUw123kjHlywH+v20aPQTuXgMpNc=',\n registrant: 'YoPsbfR6YQczjzPdHCoGC7nJsOdPQR50+SYqcWpJ0y0=',\n emailCert: 'exOl3KM0dIJ04EW5pZgbZmPag6MdJXd3/a1enmUU/BA=',\n anyone: 'mfkOMfLDQmrr3SBxBQ5WeE+6Hy3VJRFq6w4A5Ljtlis=',\n self: 'Hkge6X5JRxt1cWXtHLCrSTg6dCVTxjQJJ48iOYd7n3g=',\n coolCert: 'AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo='\n};\n//# sourceMappingURL=index.js.map","import { WalletClient } from '../wallet/index.js';\nimport { Utils, Random } from '../primitives/index.js';\nimport { LockingScript, PushDrop } from '../script/index.js';\nimport { Transaction } from '../transaction/index.js';\nconst CONTACT_PROTOCOL_ID = [2, 'contact'];\n// In-memory cache for cross-platform compatibility\nclass MemoryCache {\n cache = new Map();\n getItem(key) {\n return this.cache.get(key) ?? null;\n }\n setItem(key, value) {\n this.cache.set(key, value);\n }\n removeItem(key) {\n this.cache.delete(key);\n }\n clear() {\n this.cache.clear();\n }\n}\nexport class ContactsManager {\n wallet;\n cache = new MemoryCache();\n CONTACTS_CACHE_KEY = 'metanet-contacts';\n originator;\n constructor(wallet, originator) {\n this.wallet = wallet ?? new WalletClient();\n this.originator = originator;\n }\n /**\n * Load all records from the contacts basket\n * @param identityKey Optional specific identity key to fetch\n * @param forceRefresh Whether to force a check for new contact data\n * @param limit Maximum number of contacts to return\n * @returns A promise that resolves with an array of contacts\n */\n async getContacts(identityKey, forceRefresh = false, limit = 1000) {\n // Check in-memory cache first unless forcing refresh\n if (!forceRefresh) {\n const cached = this.cache.getItem(this.CONTACTS_CACHE_KEY);\n if (cached != null && cached !== '') {\n try {\n const cachedContacts = JSON.parse(cached);\n return identityKey != null\n ? cachedContacts.filter(c => c.identityKey === identityKey)\n : cachedContacts;\n }\n catch (e) {\n console.warn('Invalid cached contacts JSON; will reload from chain', e);\n }\n }\n }\n const tags = [];\n if (identityKey != null) {\n // Hash the identity key to use as a tag for quick lookup\n const { hmac: hashedIdentityKey } = await this.wallet.createHmac({\n protocolID: CONTACT_PROTOCOL_ID,\n keyID: identityKey,\n counterparty: 'self',\n data: Utils.toArray(identityKey, 'utf8')\n }, this.originator);\n tags.push(`identityKey ${Utils.toHex(hashedIdentityKey)}`);\n }\n // Get all contact outputs from the contacts basket\n const outputs = await this.wallet.listOutputs({\n basket: 'contacts',\n include: 'locking scripts',\n includeCustomInstructions: true,\n tags,\n limit\n }, this.originator);\n if (outputs.outputs == null || outputs.outputs.length === 0) {\n this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify([]));\n return [];\n }\n const contacts = [];\n // Process each contact output\n for (const output of outputs.outputs) {\n try {\n if (output.lockingScript == null)\n continue;\n // Decode the PushDrop data\n const decoded = PushDrop.decode(LockingScript.fromHex(output.lockingScript));\n if (output.customInstructions == null)\n continue;\n const keyID = JSON.parse(output.customInstructions).keyID;\n // Decrypt the contact data\n const { plaintext } = await this.wallet.decrypt({\n ciphertext: decoded.fields[0],\n protocolID: CONTACT_PROTOCOL_ID,\n keyID,\n counterparty: 'self'\n }, this.originator);\n // Parse the contact data\n const contactData = JSON.parse(Utils.toUTF8(plaintext));\n contacts.push(contactData);\n }\n catch (error) {\n console.warn('ContactsManager: Failed to decode contact output:', error);\n // Skip this contact and continue with others\n }\n }\n // Cache the loaded contacts\n this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(contacts));\n const filteredContacts = identityKey != null\n ? contacts.filter(c => c.identityKey === identityKey)\n : contacts;\n return filteredContacts;\n }\n /**\n * Save or update a Metanet contact\n * @param contact The displayable identity information for the contact\n * @param metadata Optional metadata to store with the contact (ex. notes, aliases, etc)\n */\n async saveContact(contact, metadata) {\n // Get current contacts from cache or blockchain\n const cached = this.cache.getItem(this.CONTACTS_CACHE_KEY);\n let contacts;\n if (cached != null && cached !== '') {\n contacts = JSON.parse(cached);\n }\n else {\n // If cache is empty, get current data from blockchain\n contacts = await this.getContacts();\n }\n const existingIndex = contacts.findIndex(c => c.identityKey === contact.identityKey);\n const contactToStore = {\n ...contact,\n metadata\n };\n if (existingIndex >= 0) {\n contacts[existingIndex] = contactToStore;\n }\n else {\n contacts.push(contactToStore);\n }\n const { hmac: hashedIdentityKey } = await this.wallet.createHmac({\n protocolID: CONTACT_PROTOCOL_ID,\n keyID: contact.identityKey,\n counterparty: 'self',\n data: Utils.toArray(contact.identityKey, 'utf8')\n }, this.originator);\n // Check if this contact already exists (to update it)\n const outputs = await this.wallet.listOutputs({\n basket: 'contacts',\n include: 'entire transactions',\n includeCustomInstructions: true,\n tags: [`identityKey ${Utils.toHex(hashedIdentityKey)}`],\n limit: 100 // Should only be one contact!\n }, this.originator);\n let existingOutput = null;\n let keyID = Utils.toBase64(Random(32));\n if (outputs.outputs != null) {\n // Find output by trying to decrypt and checking identityKey in payload\n for (const output of outputs.outputs) {\n try {\n const [txid, outputIndex] = output.outpoint.split('.');\n const tx = Transaction.fromBEEF(outputs.BEEF, txid);\n const decoded = PushDrop.decode(tx.outputs[Number(outputIndex)].lockingScript);\n if (output.customInstructions == null)\n continue;\n keyID = JSON.parse(output.customInstructions).keyID;\n const { plaintext } = await this.wallet.decrypt({\n ciphertext: decoded.fields[0],\n protocolID: CONTACT_PROTOCOL_ID,\n keyID,\n counterparty: 'self'\n }, this.originator);\n const storedContact = JSON.parse(Utils.toUTF8(plaintext));\n if (storedContact.identityKey === contact.identityKey) {\n // Found the right output\n existingOutput = output;\n break;\n }\n }\n catch (e) {\n // Skip malformed or undecryptable outputs\n }\n }\n }\n // Encrypt the contact data directly\n const contactWithMetadata = {\n ...contact,\n metadata\n };\n const { ciphertext } = await this.wallet.encrypt({\n plaintext: Utils.toArray(JSON.stringify(contactWithMetadata), 'utf8'),\n protocolID: CONTACT_PROTOCOL_ID,\n keyID,\n counterparty: 'self'\n }, this.originator);\n // Create locking script for the new contact token\n const lockingScript = await new PushDrop(this.wallet, this.originator).lock([ciphertext], CONTACT_PROTOCOL_ID, keyID, 'self');\n if (existingOutput != null) {\n // Update existing contact by spending its output\n const [txid, outputIndex] = String(existingOutput.outpoint).split('.');\n const prevOutpoint = `${txid}.${outputIndex}`;\n const pushdrop = new PushDrop(this.wallet, this.originator);\n const { signableTransaction } = await this.wallet.createAction({\n description: 'Update Contact',\n inputBEEF: outputs.BEEF,\n inputs: [{\n outpoint: prevOutpoint,\n unlockingScriptLength: 74,\n inputDescription: 'Spend previous contact output'\n }],\n outputs: [{\n basket: 'contacts',\n satoshis: 1,\n lockingScript: lockingScript.toHex(),\n outputDescription: `Updated Contact: ${contact.name ?? contact.identityKey.slice(0, 10)}`,\n tags: [`identityKey ${Utils.toHex(hashedIdentityKey)}`],\n customInstructions: JSON.stringify({ keyID })\n }],\n options: { acceptDelayedBroadcast: false, randomizeOutputs: false } // TODO: Support custom config as needed.\n }, this.originator);\n if (signableTransaction == null)\n throw new Error('Unable to update contact');\n const unlocker = pushdrop.unlock(CONTACT_PROTOCOL_ID, keyID, 'self');\n const unlockingScript = await unlocker.sign(Transaction.fromBEEF(signableTransaction.tx), 0);\n const { tx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: { 0: { unlockingScript: unlockingScript.toHex() } }\n }, this.originator);\n if (tx == null)\n throw new Error('Failed to update contact output');\n }\n else {\n // Create new contact output\n const { tx } = await this.wallet.createAction({\n description: 'Add Contact',\n outputs: [{\n basket: 'contacts',\n satoshis: 1,\n lockingScript: lockingScript.toHex(),\n outputDescription: `Contact: ${contact.name ?? contact.identityKey.slice(0, 10)}`,\n tags: [`identityKey ${Utils.toHex(hashedIdentityKey)}`],\n customInstructions: JSON.stringify({ keyID })\n }],\n options: { acceptDelayedBroadcast: false, randomizeOutputs: false } // TODO: Support custom config as needed.\n }, this.originator);\n if (tx == null)\n throw new Error('Failed to create contact output');\n }\n this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(contacts));\n }\n /**\n * Remove a contact from the contacts basket\n * @param identityKey The identity key of the contact to remove\n */\n async removeContact(identityKey) {\n // Update in-memory cache\n const cached = this.cache.getItem(this.CONTACTS_CACHE_KEY);\n if (cached != null && cached !== '') {\n try {\n const contacts = JSON.parse(cached);\n const filteredContacts = contacts.filter(c => c.identityKey !== identityKey);\n this.cache.setItem(this.CONTACTS_CACHE_KEY, JSON.stringify(filteredContacts));\n }\n catch (e) {\n console.warn('Failed to update cache after contact removal:', e);\n }\n }\n // Hash the identity key to use as a tag for quick lookup\n const tags = [];\n const { hmac: hashedIdentityKey } = await this.wallet.createHmac({\n protocolID: CONTACT_PROTOCOL_ID,\n keyID: identityKey,\n counterparty: 'self',\n data: Utils.toArray(identityKey, 'utf8')\n }, this.originator);\n tags.push(`identityKey ${Utils.toHex(hashedIdentityKey)}`);\n // Find and spend the contact's output\n const outputs = await this.wallet.listOutputs({\n basket: 'contacts',\n include: 'entire transactions',\n includeCustomInstructions: true,\n tags,\n limit: 100 // Should only be one contact!\n }, this.originator);\n if (outputs.outputs == null)\n return;\n // Find the output for this specific contact by decrypting and checking identityKey\n for (const output of outputs.outputs) {\n try {\n const [txid, outputIndex] = String(output.outpoint).split('.');\n const tx = Transaction.fromBEEF(outputs.BEEF, txid);\n const decoded = PushDrop.decode(tx.outputs[Number(outputIndex)].lockingScript);\n if (output.customInstructions == null)\n continue;\n const keyID = JSON.parse(output.customInstructions).keyID;\n const { plaintext } = await this.wallet.decrypt({\n ciphertext: decoded.fields[0],\n protocolID: CONTACT_PROTOCOL_ID,\n keyID,\n counterparty: 'self'\n }, this.originator);\n const storedContact = JSON.parse(Utils.toUTF8(plaintext));\n if (storedContact.identityKey === identityKey) {\n // Found the contact's output, spend it without creating a new one\n const prevOutpoint = `${txid}.${outputIndex}`;\n const pushdrop = new PushDrop(this.wallet, this.originator);\n const { signableTransaction } = await this.wallet.createAction({\n description: 'Delete Contact',\n inputBEEF: outputs.BEEF,\n inputs: [{\n outpoint: prevOutpoint,\n unlockingScriptLength: 74,\n inputDescription: 'Spend contact output to delete'\n }],\n outputs: [], // No outputs = deletion\n options: { acceptDelayedBroadcast: false, randomizeOutputs: false } // TODO: Support custom config as needed.\n }, this.originator);\n if (signableTransaction == null)\n throw new Error('Unable to delete contact');\n const unlocker = pushdrop.unlock(CONTACT_PROTOCOL_ID, keyID, 'self');\n const unlockingScript = await unlocker.sign(Transaction.fromBEEF(signableTransaction.tx), 0);\n const { tx: deleteTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: { 0: { unlockingScript: unlockingScript.toHex() } }\n }, this.originator);\n if (deleteTx == null)\n throw new Error('Failed to delete contact output');\n return;\n }\n }\n catch (e) {\n // Skip malformed or undecryptable outputs\n }\n }\n }\n}\n//# sourceMappingURL=ContactsManager.js.map","import { DEFAULT_IDENTITY_CLIENT_OPTIONS, defaultIdentity, KNOWN_IDENTITY_TYPES } from './types/index.js';\nimport { WalletClient } from '../wallet/index.js';\nimport { Transaction } from '../transaction/index.js';\nimport Certificate from '../auth/certificates/Certificate.js';\nimport { PushDrop } from '../script/index.js';\nimport { PrivateKey, Utils } from '../primitives/index.js';\nimport { LookupResolver, SHIPBroadcaster, TopicBroadcaster, withDoubleSpendRetry } from '../overlay-tools/index.js';\nimport { ContactsManager } from './ContactsManager.js';\n/**\n * IdentityClient lets you discover who others are, and let the world know who you are.\n */\nexport class IdentityClient {\n options;\n originator;\n wallet;\n contactsManager;\n constructor(wallet, options = DEFAULT_IDENTITY_CLIENT_OPTIONS, originator) {\n this.options = options;\n this.originator = originator;\n this.originator = originator;\n this.wallet = wallet ?? new WalletClient();\n this.contactsManager = new ContactsManager(this.wallet, this.originator);\n }\n /**\n * Publicly reveals selected fields from a given certificate by creating a publicly verifiable certificate.\n * The publicly revealed certificate is included in a blockchain transaction and broadcast to a federated overlay node.\n *\n * @param {Certificate} certificate - The master certificate to selectively reveal.\n * @param {CertificateFieldNameUnder50Bytes[]} fieldsToReveal - An array of certificate field names to reveal. Only these fields will be included in the public certificate.\n *\n * @returns {Promise<object>} A promise that resolves with the broadcast result from the overlay network.\n * @throws {Error} Throws an error if the certificate is invalid, the fields cannot be revealed, or if the broadcast fails.\n */\n async publiclyRevealAttributes(certificate, fieldsToReveal) {\n if (Object.keys(certificate.fields).length === 0) {\n throw new Error('Public reveal failed: Certificate has no fields to reveal!');\n }\n if (fieldsToReveal.length === 0) {\n throw new Error('Public reveal failed: You must reveal at least one field!');\n }\n try {\n const masterCert = new Certificate(certificate.type, certificate.serialNumber, certificate.subject, certificate.certifier, certificate.revocationOutpoint, certificate.fields, certificate.signature);\n await masterCert.verify();\n }\n catch (error) {\n throw new Error('Public reveal failed: Certificate verification failed!');\n }\n // Given we already have a master certificate from a certifier,\n // create an anyone verifiable certificate with selectively revealed fields\n const { keyringForVerifier } = await this.wallet.proveCertificate({\n certificate,\n fieldsToReveal,\n verifier: new PrivateKey(1).toPublicKey().toString()\n }, this.originator);\n // Build the lockingScript with pushdrop.create() and the transaction with createAction()\n const lockingScript = await new PushDrop(this.wallet, this.originator).lock([\n Utils.toArray(JSON.stringify({ ...certificate, keyring: keyringForVerifier }))\n ], this.options.protocolID, this.options.keyID, 'anyone', true, true);\n // TODO: Consider verification and if this is necessary\n // counterpartyCanVerifyMyOwnership: true\n const { tx } = await this.wallet.createAction({\n description: 'Create a new Identity Token',\n outputs: [\n {\n satoshis: this.options.tokenAmount,\n lockingScript: lockingScript.toHex(),\n outputDescription: 'Identity Token'\n }\n ],\n options: {\n randomizeOutputs: false\n }\n }, this.originator);\n if (tx !== undefined) {\n // Submit the transaction to an overlay\n const broadcaster = new TopicBroadcaster(['tm_identity'], {\n networkPreset: (await this.wallet.getNetwork({})).network\n });\n return await broadcaster.broadcast(Transaction.fromAtomicBEEF(tx));\n }\n throw new Error('Public reveal failed: failed to create action!');\n }\n /**\n * Resolves displayable identity certificates, issued to a given identity key by a trusted certifier.\n *\n * @param {DiscoverByIdentityKeyArgs} args - Arguments for requesting the discovery based on the identity key.\n * @param {boolean} [overrideWithContacts=true] - Whether to override the results with personal contacts if available.\n * @returns {Promise<DisplayableIdentity[]>} The promise resolves to displayable identities.\n */\n async resolveByIdentityKey(args, overrideWithContacts = true) {\n if (overrideWithContacts) {\n // Override results with personal contacts if available\n const contacts = await this.contactsManager.getContacts(args.identityKey);\n if (contacts.length > 0) {\n return contacts;\n }\n }\n const { certificates } = await this.wallet.discoverByIdentityKey(args, this.originator);\n return certificates.map((cert) => {\n return IdentityClient.parseIdentity(cert);\n });\n }\n /**\n * Resolves displayable identity certificates by specific identity attributes, issued by a trusted entity.\n *\n * @param {DiscoverByAttributesArgs} args - Attributes and optional parameters used to discover certificates.\n * @param {boolean} [overrideWithContacts=true] - Whether to override the results with personal contacts if available.\n * @returns {Promise<DisplayableIdentity[]>} The promise resolves to displayable identities.\n */\n async resolveByAttributes(args, overrideWithContacts = true) {\n // Run both queries in parallel for better performance\n const [contacts, certificatesResult] = await Promise.all([\n overrideWithContacts\n ? this.contactsManager.getContacts()\n : Promise.resolve([]),\n this.wallet.discoverByAttributes(args, this.originator)\n ]);\n // Fast lookup by identityKey\n const contactByKey = new Map(contacts.map((contact) => [contact.identityKey, contact]));\n // Guard if certificates might be absent\n const certs = certificatesResult?.certificates ?? [];\n // Parse certificates and substitute with contacts where available\n return certs.map((cert) => contactByKey.get(cert.subject) ?? IdentityClient.parseIdentity(cert));\n }\n /**\n * Remove public certificate revelation from overlay services by spending the identity token\n * @param serialNumber - Unique serial number of the certificate to revoke revelation\n */\n async revokeCertificateRevelation(serialNumber) {\n // 1. Find existing UTXO\n const lookupResolver = new LookupResolver({\n networkPreset: (await this.wallet.getNetwork({})).network\n });\n const result = await lookupResolver.query({\n service: 'ls_identity',\n query: {\n serialNumber\n }\n });\n if (result.type !== 'output-list') {\n throw new Error('Failed to get lookup result');\n }\n const topicBroadcaster = new SHIPBroadcaster(['tm_identity'], {\n networkPreset: (await this.wallet.getNetwork({})).network,\n requireAcknowledgmentFromAllHostsForTopics: [],\n requireAcknowledgmentFromAnyHostForTopics: [],\n requireAcknowledgmentFromSpecificHostsForTopics: { tm_identity: [] }\n });\n await withDoubleSpendRetry(async () => {\n const tx = Transaction.fromBEEF(result.outputs[0].beef);\n const outpoint = `${tx.id('hex')}.${this.options.outputIndex}`;\n const lockingScript = tx.outputs[this.options.outputIndex].lockingScript;\n if (lockingScript === undefined || outpoint === undefined) {\n throw new Error('Failed to get locking script for revelation output!');\n }\n // 2. Parse results\n const { signableTransaction } = await this.wallet.createAction({\n description: 'Spend certificate revelation token',\n inputBEEF: result.outputs[0].beef,\n inputs: [\n {\n inputDescription: 'Revelation token',\n outpoint,\n unlockingScriptLength: 74\n }\n ],\n options: {\n randomizeOutputs: false,\n acceptDelayedBroadcast: false,\n noSend: true\n }\n }, this.originator);\n if (signableTransaction === undefined) {\n throw new Error('Failed to create signable transaction');\n }\n const partialTx = Transaction.fromBEEF(signableTransaction.tx);\n const unlocker = new PushDrop(this.wallet, this.originator).unlock(this.options.protocolID, this.options.keyID, 'anyone');\n const unlockingScript = await unlocker.sign(partialTx, this.options.outputIndex);\n const { tx: signedTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: {\n [this.options.outputIndex]: {\n unlockingScript: unlockingScript.toHex()\n }\n },\n options: {\n acceptDelayedBroadcast: false,\n noSend: true\n }\n }, this.originator);\n if (signedTx === undefined) {\n throw new Error('Failed to sign transaction');\n }\n await topicBroadcaster.broadcast(Transaction.fromAtomicBEEF(signedTx));\n }, topicBroadcaster);\n }\n /**\n * Load all records from the contacts basket\n * @param identityKey Optional specific identity key to fetch\n * @param forceRefresh Whether to force a check for new contact data\n * @param limit Optional limit on number of contacts to fetch\n * @returns A promise that resolves with an array of contacts\n */\n async getContacts(identityKey, forceRefresh = false, limit = 1000) {\n return await this.contactsManager.getContacts(identityKey, forceRefresh, limit);\n }\n /**\n * Save or update a Metanet contact\n * @param contact The displayable identity information for the contact\n * @param metadata Optional metadata to store with the contact (ex. notes, aliases, etc)\n */\n async saveContact(contact, metadata) {\n return await this.contactsManager.saveContact(contact, metadata);\n }\n /**\n * Remove a contact from the contacts basket\n * @param identityKey The identity key of the contact to remove\n */\n async removeContact(identityKey) {\n return await this.contactsManager.removeContact(identityKey);\n }\n /**\n * Parse out identity and certifier attributes to display from an IdentityCertificate\n * @param identityToParse - The Identity Certificate to parse\n * @returns - IdentityToDisplay\n */\n static parseIdentity(identityToParse) {\n const { type, decryptedFields, certifierInfo } = identityToParse;\n let name, avatarURL, badgeLabel, badgeIconURL, badgeClickURL;\n // Parse out the name to display based on the specific certificate type which has clearly defined fields.\n switch (type) {\n case KNOWN_IDENTITY_TYPES.xCert:\n name = decryptedFields.userName;\n avatarURL = decryptedFields.profilePhoto;\n badgeLabel = `X account certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://socialcert.net'; // TODO Make a specific page for this.\n break;\n case KNOWN_IDENTITY_TYPES.discordCert:\n name = decryptedFields.userName;\n avatarURL = decryptedFields.profilePhoto;\n badgeLabel = `Discord account certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://socialcert.net'; // TODO Make a specific page for this.\n break;\n case KNOWN_IDENTITY_TYPES.emailCert:\n name = decryptedFields.email;\n avatarURL = 'XUTZxep7BBghAJbSBwTjNfmcsDdRFs5EaGEgkESGSgjJVYgMEizu';\n badgeLabel = `Email certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://socialcert.net'; // TODO Make a specific page for this.\n break;\n case KNOWN_IDENTITY_TYPES.phoneCert:\n name = decryptedFields.phoneNumber;\n avatarURL = 'XUTLxtX3ELNUwRhLwL7kWNGbdnFM8WG2eSLv84J7654oH8HaJWrU';\n badgeLabel = `Phone certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://socialcert.net'; // TODO Make a specific page for this.\n break;\n case KNOWN_IDENTITY_TYPES.identiCert:\n name = `${decryptedFields.firstName} ${decryptedFields.lastName}`;\n avatarURL = decryptedFields.profilePhoto;\n badgeLabel = `Government ID certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://identicert.me'; // TODO Make a specific page for this.\n break;\n case KNOWN_IDENTITY_TYPES.registrant:\n name = decryptedFields.name;\n avatarURL = decryptedFields.icon;\n badgeLabel = `Entity certified by ${certifierInfo.name}`;\n badgeIconURL = certifierInfo.iconUrl;\n badgeClickURL = 'https://projectbabbage.com/docs/registrant'; // TODO: Make this doc page exist\n break;\n case KNOWN_IDENTITY_TYPES.coolCert:\n name = decryptedFields.cool === 'true' ? 'Cool Person!' : 'Not cool!';\n break;\n case KNOWN_IDENTITY_TYPES.anyone:\n name = 'Anyone';\n avatarURL = 'XUT4bpQ6cpBaXi1oMzZsXfpkWGbtp2JTUYAoN7PzhStFJ6wLfoeR';\n badgeLabel =\n 'Represents the ability for anyone to access this information.';\n badgeIconURL = 'XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG';\n badgeClickURL = 'https://projectbabbage.com/docs/anyone-identity'; // TODO: Make this doc page exist\n break;\n case KNOWN_IDENTITY_TYPES.self:\n name = 'You';\n avatarURL = 'XUT9jHGk2qace148jeCX5rDsMftkSGYKmigLwU2PLLBc7Hm63VYR';\n badgeLabel = 'Represents your ability to access this information.';\n badgeIconURL = 'XUUV39HVPkpmMzYNTx7rpKzJvXfeiVyQWg2vfSpjBAuhunTCA9uG';\n badgeClickURL = 'https://projectbabbage.com/docs/self-identity'; // TODO: Make this doc page exist\n break;\n default: {\n const parsed = IdentityClient.tryToParseGenericIdentity(type, decryptedFields, certifierInfo);\n name = parsed.name;\n avatarURL = parsed.avatarURL;\n badgeLabel = parsed.badgeLabel;\n badgeIconURL = parsed.badgeIconURL;\n badgeClickURL = parsed.badgeClickURL;\n break;\n }\n }\n return {\n name,\n avatarURL,\n abbreviatedKey: identityToParse.subject.length > 0\n ? `${identityToParse.subject.substring(0, 10)}...`\n : '',\n identityKey: identityToParse.subject,\n badgeIconURL,\n badgeLabel,\n badgeClickURL\n };\n }\n /**\n * Helper to check if a value is a non-empty string\n */\n static hasValue(value) {\n return value !== undefined && value !== null && value !== '';\n }\n /**\n * Try to parse identity information from unknown certificate types\n * by checking common field names\n */\n static tryToParseGenericIdentity(type, decryptedFields, certifierInfo) {\n // Try to construct a name from common field patterns\n const firstName = decryptedFields.firstName;\n const lastName = decryptedFields.lastName;\n const fullName = IdentityClient.hasValue(firstName) && IdentityClient.hasValue(lastName)\n ? `${firstName} ${lastName}`\n : IdentityClient.hasValue(firstName)\n ? firstName\n : IdentityClient.hasValue(lastName)\n ? lastName\n : undefined;\n const name = IdentityClient.hasValue(decryptedFields.name)\n ? decryptedFields.name\n : IdentityClient.hasValue(decryptedFields.userName)\n ? decryptedFields.userName\n : (fullName ??\n (IdentityClient.hasValue(decryptedFields.email)\n ? decryptedFields.email\n : defaultIdentity.name));\n // Try to find an avatar/photo from common field names\n const avatarURL = IdentityClient.hasValue(decryptedFields.profilePhoto)\n ? decryptedFields.profilePhoto\n : IdentityClient.hasValue(decryptedFields.avatar)\n ? decryptedFields.avatar\n : IdentityClient.hasValue(decryptedFields.icon)\n ? decryptedFields.icon\n : IdentityClient.hasValue(decryptedFields.photo)\n ? decryptedFields.photo\n : defaultIdentity.avatarURL;\n // Generate badge information\n const badgeLabel = IdentityClient.hasValue(certifierInfo?.name)\n ? `${type} certified by ${String(certifierInfo.name)}`\n : defaultIdentity.badgeLabel;\n const badgeIconURL = IdentityClient.hasValue(certifierInfo?.iconUrl)\n ? certifierInfo.iconUrl\n : defaultIdentity.badgeIconURL;\n const badgeClickURL = defaultIdentity.badgeClickURL;\n return { name, avatarURL, badgeLabel, badgeIconURL, badgeClickURL };\n }\n}\n//# sourceMappingURL=IdentityClient.js.map","import { WalletClient } from '../wallet/index.js';\nimport { Utils } from '../primitives/index.js';\nimport { Transaction } from '../transaction/index.js';\nimport { LookupResolver, TopicBroadcaster } from '../overlay-tools/index.js';\nimport { PushDrop } from '../script/index.js';\nconst REGISTRANT_TOKEN_AMOUNT = 1;\nconst REGISTRANT_KEY_ID = '1';\n/**\n * RegistryClient manages on-chain registry definitions for three types:\n * - basket (basket-based items)\n * - protocol (protocol-based items)\n * - certificate (certificate-based items)\n *\n * It provides methods to:\n * - Register new definitions using pushdrop-based UTXOs.\n * - Resolve existing definitions using a lookup service.\n * - List registry entries associated with the operator's wallet.\n * - Remove existing registry entries by spending their UTXOs.\n * - Update existing registry entries.\n *\n * Registry operators use this client to establish and manage\n * canonical references for baskets, protocols, and certificate types.\n */\nexport class RegistryClient {\n wallet;\n originator;\n network;\n resolver;\n cachedIdentityKey;\n acceptDelayedBroadcast;\n constructor(wallet = new WalletClient(), options = {}, originator) {\n this.wallet = wallet;\n this.originator = originator;\n this.acceptDelayedBroadcast = options.acceptDelayedBroadcast ?? false;\n this.resolver = options.resolver ?? new LookupResolver();\n }\n /**\n * Gets the wallet's identity key, caching it after the first call.\n * @returns The public identity key as a hex string.\n */\n async getIdentityKey() {\n if (this.cachedIdentityKey === undefined) {\n this.cachedIdentityKey = (await this.wallet.getPublicKey({ identityKey: true })).publicKey;\n }\n return this.cachedIdentityKey;\n }\n /**\n * Gets the network, initializing and caching it on first call.\n * @returns The network type ('mainnet' or 'testnet').\n */\n async getNetwork() {\n if (this.network === undefined) {\n this.network = (await this.wallet.getNetwork({})).network;\n }\n return this.network;\n }\n /**\n * Publishes a new on-chain definition for baskets, protocols, or certificates.\n * The definition data is encoded in a pushdrop-based UTXO.\n *\n * Registry operators (i.e., identity key owners) can create these definitions\n * to establish canonical references for basket IDs, protocol specs, or certificate schemas.\n *\n * @param data - Structured information about a 'basket', 'protocol', or 'certificate'.\n * @returns A promise with the broadcast result or failure.\n */\n async registerDefinition(data) {\n const registryOperator = await this.getIdentityKey();\n const pushdrop = new PushDrop(this.wallet, this.originator);\n // Convert definition data into PushDrop fields\n const fields = this.buildPushDropFields(data, registryOperator);\n // Convert the user-friendly definitionType to the actual wallet protocol\n const protocol = this.mapDefinitionTypeToWalletProtocol(data.definitionType);\n // Lock the fields into a pushdrop-based UTXO\n const lockingScript = await pushdrop.lock(fields, protocol, REGISTRANT_KEY_ID, 'anyone', true);\n // Create a transaction\n const { tx } = await this.wallet.createAction({\n description: `Register a new ${data.definitionType} item`,\n outputs: [\n {\n satoshis: REGISTRANT_TOKEN_AMOUNT,\n lockingScript: lockingScript.toHex(),\n outputDescription: `New ${data.definitionType} registration token`,\n basket: this.mapDefinitionTypeToBasketName(data.definitionType)\n }\n ],\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast,\n randomizeOutputs: false\n }\n }, this.originator);\n if (tx === undefined) {\n throw new Error(`Failed to create ${data.definitionType} registration transaction!`);\n }\n // Broadcast to the relevant topic\n const broadcaster = new TopicBroadcaster([this.mapDefinitionTypeToTopic(data.definitionType)], {\n networkPreset: await this.getNetwork(),\n resolver: this.resolver\n });\n const result = await broadcaster.broadcast(Transaction.fromAtomicBEEF(tx));\n return result;\n }\n /**\n * Resolves registrant tokens of a particular type using a lookup service.\n *\n * The query object shape depends on the registry type:\n * - For \"basket\", the query is of type BasketMapQuery:\n * { basketID?: string; name?: string; registryOperators?: string[]; }\n * - For \"protocol\", the query is of type ProtoMapQuery:\n * { name?: string; registryOperators?: string[]; protocolID?: WalletProtocol; }\n * - For \"certificate\", the query is of type CertMapQuery:\n * { type?: string; name?: string; registryOperators?: string[]; }\n *\n * @param definitionType - The registry type, which can be 'basket', 'protocol', or 'certificate'.\n * @param query - The query object used to filter registry records, whose shape is determined by the registry type.\n * @returns A promise that resolves to an array of matching registry records.\n */\n async resolve(definitionType, query) {\n const serviceName = this.mapDefinitionTypeToServiceName(definitionType);\n // Make the lookup query\n const result = await this.resolver.query({ service: serviceName, query });\n if (result.type !== 'output-list') {\n return [];\n }\n const parsedRegistryRecords = [];\n for (const output of result.outputs) {\n try {\n const parsedTx = Transaction.fromBEEF(output.beef);\n const lockingScript = parsedTx.outputs[output.outputIndex].lockingScript;\n const record = await this.parseLockingScript(definitionType, lockingScript);\n parsedRegistryRecords.push(record);\n }\n catch {\n // Skip invalid or non-pushdrop outputs\n }\n }\n return parsedRegistryRecords;\n }\n /**\n * Lists the registry operator's published definitions for the given type.\n *\n * Returns parsed registry records including transaction details such as txid, outputIndex, satoshis, and the locking script.\n *\n * @param definitionType - The type of registry definition to list ('basket', 'protocol', or 'certificate').\n * @returns A promise that resolves to an array of RegistryRecord objects.\n */\n async listOwnRegistryEntries(definitionType) {\n const relevantBasketName = this.mapDefinitionTypeToBasketName(definitionType);\n const { outputs, BEEF } = await this.wallet.listOutputs({\n basket: relevantBasketName,\n include: 'entire transactions'\n });\n const results = [];\n for (const output of outputs) {\n if (!output.spendable) {\n continue;\n }\n try {\n const [txid, outputIndex] = output.outpoint.split('.');\n const tx = Transaction.fromBEEF(BEEF, txid);\n const lockingScript = tx.outputs[Number(outputIndex)].lockingScript;\n const record = await this.parseLockingScript(definitionType, lockingScript);\n results.push({\n ...record,\n txid,\n outputIndex: Number(outputIndex),\n satoshis: output.satoshis,\n lockingScript: lockingScript.toHex(),\n beef: BEEF\n });\n }\n catch {\n // Ignore parse errors\n }\n }\n return results;\n }\n /**\n * Removes a registry definition by spending its associated UTXO.\n *\n * @param registryRecord - The registry record to remove (must have valid txid, outputIndex, and lockingScript).\n * @returns Broadcast success/failure.\n */\n async removeDefinition(registryRecord) {\n if (registryRecord.txid === undefined || typeof registryRecord.outputIndex === 'undefined' || registryRecord.lockingScript === undefined) {\n throw new Error('Invalid registry record. Missing txid, outputIndex, or lockingScript.');\n }\n // Check if the registry record belongs to the current user\n const currentIdentityKey = await this.getIdentityKey();\n if (registryRecord.registryOperator !== currentIdentityKey) {\n throw new Error('This registry token does not belong to the current wallet.');\n }\n // Create a descriptive label for the item we're removing\n const itemIdentifier = registryRecord.definitionType === 'basket'\n ? registryRecord.basketID\n : registryRecord.definitionType === 'protocol'\n ? registryRecord.name\n : registryRecord.definitionType === 'certificate'\n ? (registryRecord.name !== undefined ? registryRecord.name : registryRecord.type)\n : 'unknown';\n const outpoint = `${registryRecord.txid}.${registryRecord.outputIndex}`;\n const { signableTransaction } = await this.wallet.createAction({\n description: `Remove ${registryRecord.definitionType} item: ${itemIdentifier}`,\n inputBEEF: registryRecord.beef,\n inputs: [\n {\n outpoint,\n unlockingScriptLength: 74,\n inputDescription: `Removing ${registryRecord.definitionType} token`\n }\n ],\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast,\n randomizeOutputs: false\n }\n }, this.originator);\n if (signableTransaction === undefined) {\n throw new Error('Failed to create signable transaction.');\n }\n const partialTx = Transaction.fromAtomicBEEF(signableTransaction.tx);\n // Prepare the unlocker\n const pushdrop = new PushDrop(this.wallet, this.originator);\n const unlocker = pushdrop.unlock(this.mapDefinitionTypeToWalletProtocol(registryRecord.definitionType), REGISTRANT_KEY_ID, 'anyone');\n // Convert to Transaction, apply signature\n const finalUnlockScript = await unlocker.sign(partialTx, 0);\n // Complete signing with the final unlock script\n const { tx: signedTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: {\n 0: {\n unlockingScript: finalUnlockScript.toHex()\n }\n },\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast\n }\n }, this.originator);\n if (signedTx === undefined) {\n throw new Error('Failed to finalize the transaction signature.');\n }\n // Broadcast\n const broadcaster = new TopicBroadcaster([this.mapDefinitionTypeToTopic(registryRecord.definitionType)], {\n networkPreset: await this.getNetwork(),\n resolver: this.resolver\n });\n const result = await broadcaster.broadcast(Transaction.fromAtomicBEEF(signedTx));\n return result;\n }\n /**\n * Updates an existing registry record by spending its UTXO and creating a new one with updated data.\n *\n * @param registryRecord - The existing registry record to update (must have valid txid, outputIndex, and lockingScript).\n * @param updatedData - The new definition data to replace the old record.\n * @returns Broadcast success/failure.\n */\n async updateDefinition(registryRecord, updatedData) {\n if (registryRecord.txid === undefined || typeof registryRecord.outputIndex === 'undefined' || registryRecord.lockingScript === undefined) {\n throw new Error('Invalid registry record. Missing txid, outputIndex, or lockingScript.');\n }\n // Verify the updated data matches the record type\n if (registryRecord.definitionType !== updatedData.definitionType) {\n throw new Error(`Cannot change definition type from ${registryRecord.definitionType} to ${updatedData.definitionType}`);\n }\n // Check if the registry record belongs to the current user\n const currentIdentityKey = await this.getIdentityKey();\n if (registryRecord.registryOperator !== currentIdentityKey) {\n throw new Error('This registry token does not belong to the current wallet.');\n }\n // Create a descriptive label for the item we're updating\n const itemIdentifier = registryRecord.definitionType === 'basket'\n ? registryRecord.basketID\n : registryRecord.definitionType === 'protocol'\n ? registryRecord.name\n : registryRecord.definitionType === 'certificate'\n ? (registryRecord.name !== undefined ? registryRecord.name : registryRecord.type)\n : 'unknown';\n const pushdrop = new PushDrop(this.wallet, this.originator);\n // Build the new locking script with updated data\n const fields = this.buildPushDropFields(updatedData, currentIdentityKey);\n const protocol = this.mapDefinitionTypeToWalletProtocol(updatedData.definitionType);\n const newLockingScript = await pushdrop.lock(fields, protocol, REGISTRANT_KEY_ID, 'anyone', true);\n const outpoint = `${registryRecord.txid}.${registryRecord.outputIndex}`;\n const { signableTransaction } = await this.wallet.createAction({\n description: `Update ${registryRecord.definitionType} item: ${itemIdentifier}`,\n inputBEEF: registryRecord.beef,\n inputs: [\n {\n outpoint,\n unlockingScriptLength: 74,\n inputDescription: `Updating ${registryRecord.definitionType} token`\n }\n ],\n outputs: [\n {\n satoshis: REGISTRANT_TOKEN_AMOUNT,\n lockingScript: newLockingScript.toHex(),\n outputDescription: `Updated ${registryRecord.definitionType} registration token`,\n basket: this.mapDefinitionTypeToBasketName(registryRecord.definitionType)\n }\n ],\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast,\n randomizeOutputs: false\n }\n }, this.originator);\n if (signableTransaction === undefined) {\n throw new Error('Failed to create signable transaction.');\n }\n const partialTx = Transaction.fromAtomicBEEF(signableTransaction.tx);\n // Prepare the unlocker for the input\n const unlocker = pushdrop.unlock(this.mapDefinitionTypeToWalletProtocol(registryRecord.definitionType), REGISTRANT_KEY_ID, 'anyone');\n // Sign the input\n const finalUnlockScript = await unlocker.sign(partialTx, 0);\n // Complete signing with the final unlock script\n const { tx: signedTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: {\n 0: {\n unlockingScript: finalUnlockScript.toHex()\n }\n },\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast\n }\n }, this.originator);\n if (signedTx === undefined) {\n throw new Error('Failed to finalize the transaction signature.');\n }\n // Broadcast\n const broadcaster = new TopicBroadcaster([this.mapDefinitionTypeToTopic(registryRecord.definitionType)], {\n networkPreset: await this.getNetwork(),\n resolver: this.resolver\n });\n return await broadcaster.broadcast(Transaction.fromAtomicBEEF(signedTx));\n }\n // --------------------------------------------------------------------------\n // INTERNAL UTILITY METHODS\n // --------------------------------------------------------------------------\n /**\n * Convert definition data into an array of pushdrop fields (strings).\n * Each definition type has a slightly different shape.\n */\n buildPushDropFields(data, registryOperator) {\n let fields;\n switch (data.definitionType) {\n case 'basket':\n fields = [\n data.basketID,\n data.name,\n data.iconURL,\n data.description,\n data.documentationURL\n ];\n break;\n case 'protocol':\n fields = [\n JSON.stringify(data.protocolID),\n data.name,\n data.iconURL,\n data.description,\n data.documentationURL\n ];\n break;\n case 'certificate':\n fields = [\n data.type,\n data.name,\n data.iconURL,\n data.description,\n data.documentationURL,\n JSON.stringify(data.fields)\n ];\n break;\n default:\n throw new Error('Unsupported definition type');\n }\n // Append the operator's public identity key last\n fields.push(registryOperator);\n return fields.map(field => Utils.toArray(field));\n }\n /**\n * Decodes a pushdrop locking script for a given definition type,\n * returning a typed record with the appropriate fields.\n */\n async parseLockingScript(definitionType, lockingScript) {\n const decoded = PushDrop.decode(lockingScript);\n if (decoded.fields.length === 0) {\n throw new Error('Not a valid registry pushdrop script.');\n }\n let registryOperator;\n let parsedData;\n switch (definitionType) {\n case 'basket': {\n if (decoded.fields.length !== 7) {\n throw new Error('Unexpected field count for basket type.');\n }\n const [basketID, name, iconURL, description, docURL, operator] = decoded.fields;\n registryOperator = Utils.toUTF8(operator);\n parsedData = {\n definitionType: 'basket',\n basketID: Utils.toUTF8(basketID),\n name: Utils.toUTF8(name),\n iconURL: Utils.toUTF8(iconURL),\n description: Utils.toUTF8(description),\n documentationURL: Utils.toUTF8(docURL)\n };\n break;\n }\n case 'protocol': {\n if (decoded.fields.length !== 7) {\n throw new Error('Unexpected field count for protocol type.');\n }\n const [protocolID, name, iconURL, description, docURL, operator] = decoded.fields;\n registryOperator = Utils.toUTF8(operator);\n parsedData = {\n definitionType: 'protocol',\n protocolID: deserializeWalletProtocol(Utils.toUTF8(protocolID)),\n name: Utils.toUTF8(name),\n iconURL: Utils.toUTF8(iconURL),\n description: Utils.toUTF8(description),\n documentationURL: Utils.toUTF8(docURL)\n };\n break;\n }\n case 'certificate': {\n if (decoded.fields.length !== 8) {\n throw new Error('Unexpected field count for certificate type.');\n }\n const [certType, name, iconURL, description, docURL, fieldsJSON, operator] = decoded.fields;\n registryOperator = Utils.toUTF8(operator);\n let parsedFields = {};\n try {\n parsedFields = JSON.parse(Utils.toUTF8(fieldsJSON));\n }\n catch {\n // If there's a JSON parse error, assume empty\n }\n parsedData = {\n definitionType: 'certificate',\n type: Utils.toUTF8(certType),\n name: Utils.toUTF8(name),\n iconURL: Utils.toUTF8(iconURL),\n description: Utils.toUTF8(description),\n documentationURL: Utils.toUTF8(docURL),\n fields: parsedFields\n };\n break;\n }\n default:\n throw new Error(`Unsupported definition type: ${definitionType}`);\n }\n // Return the typed data plus the operator key\n return { ...parsedData, registryOperator };\n }\n /**\n * Convert our definitionType to the wallet protocol format ([protocolID, keyID]).\n */\n mapDefinitionTypeToWalletProtocol(definitionType) {\n switch (definitionType) {\n case 'basket':\n return [1, 'basketmap'];\n case 'protocol':\n return [1, 'protomap'];\n case 'certificate':\n return [1, 'certmap'];\n default:\n throw new Error(`Unknown definition type: ${definitionType}`);\n }\n }\n /**\n * Convert 'basket'|'protocol'|'certificate' to the basket name used by the wallet.\n */\n mapDefinitionTypeToBasketName(definitionType) {\n switch (definitionType) {\n case 'basket':\n return 'basketmap';\n case 'protocol':\n return 'protomap';\n case 'certificate':\n return 'certmap';\n default:\n throw new Error(`Unknown definition type: ${definitionType}`);\n }\n }\n /**\n * Convert 'basket'|'protocol'|'certificate' to the broadcast topic name.\n */\n mapDefinitionTypeToTopic(definitionType) {\n switch (definitionType) {\n case 'basket':\n return 'tm_basketmap';\n case 'protocol':\n return 'tm_protomap';\n case 'certificate':\n return 'tm_certmap';\n default:\n throw new Error(`Unknown definition type: ${definitionType}`);\n }\n }\n /**\n * Convert 'basket'|'protocol'|'certificate' to the lookup service name.\n */\n mapDefinitionTypeToServiceName(definitionType) {\n switch (definitionType) {\n case 'basket':\n return 'ls_basketmap';\n case 'protocol':\n return 'ls_protomap';\n case 'certificate':\n return 'ls_certmap';\n default:\n throw new Error(`Unknown definition type: ${definitionType}`);\n }\n }\n}\nexport function deserializeWalletProtocol(str) {\n // Parse the JSON string back into a JavaScript value.\n const parsed = JSON.parse(str);\n // Validate that the parsed value is an array with exactly two elements.\n if (!Array.isArray(parsed) || parsed.length !== 2) {\n throw new Error('Invalid wallet protocol format.');\n }\n const [security, protocolString] = parsed;\n // Validate that the security level is one of the allowed numbers.\n if (![0, 1, 2].includes(security)) {\n throw new Error('Invalid security level.');\n }\n // Validate that the protocol string is a string and its length is within the allowed bounds.\n if (typeof protocolString !== 'string') {\n throw new Error('Invalid protocolID');\n }\n return [security, protocolString];\n}\n//# sourceMappingURL=RegistryClient.js.map","import PushDrop from '../script/templates/PushDrop.js';\nimport * as Utils from '../primitives/utils.js';\nimport WalletClient from '../wallet/WalletClient.js';\nimport Transaction from '../transaction/Transaction.js';\nimport { Beef } from '../transaction/Beef.js';\n/**\n * Implements a key-value storage system backed by transaction outputs managed by a wallet.\n * Each key-value pair is represented by a PushDrop token output in a specific context (basket).\n * Allows setting, getting, and removing key-value pairs, with optional encryption.\n */\nexport default class LocalKVStore {\n /**\n * The wallet interface used to manage outputs and perform cryptographic operations.\n * @private\n * @readonly\n */\n wallet;\n /**\n * The context (basket name) used to namespace the key-value pairs within the wallet.\n * @private\n * @readonly\n */\n context;\n /**\n * Flag indicating whether values should be encrypted before storing.\n * @private\n * @readonly\n */\n encrypt;\n /**\n * An originator to use with PushDrop and the wallet.\n * @private\n * @readonly\n */\n originator;\n acceptDelayedBroadcast = false;\n /**\n * A map to store locks for each key to ensure atomic updates.\n * @private\n */\n keyLocks = new Map();\n /**\n * Creates an instance of the localKVStore.\n *\n * @param {WalletInterface} [wallet=new WalletClient()] - The wallet interface to use. Defaults to a new WalletClient instance.\n * @param {string} [context='kvstoredefault'] - The context (basket) for namespacing keys. Defaults to 'kvstore default'.\n * @param {boolean} [encrypt=true] - Whether to encrypt values. Defaults to true.\n * @param {string} [originator] — An originator to use with PushDrop and the wallet, if provided.\n * @throws {Error} If the context is missing or empty.\n */\n constructor(wallet = new WalletClient(), context = 'kvstore default', encrypt = true, originator, acceptDelayedBroadcast = false) {\n if (typeof context !== 'string' || context.length < 1) {\n throw new Error('A context in which to operate is required.');\n }\n this.wallet = wallet;\n this.context = context;\n this.encrypt = encrypt;\n this.originator = originator;\n this.acceptDelayedBroadcast = acceptDelayedBroadcast;\n }\n async queueOperationOnKey(key) {\n // Check if a lock exists for this key and wait for it to resolve\n let lockQueue = this.keyLocks.get(key);\n if (lockQueue == null) {\n lockQueue = [];\n this.keyLocks.set(key, lockQueue);\n }\n let resolveNewLock = () => { };\n const newLock = new Promise((resolve) => {\n resolveNewLock = resolve;\n if (lockQueue != null) {\n lockQueue.push(resolve);\n }\n });\n // If we are the only request, resolve the lock immediately, queue remains at 1 item until request ends.\n if (lockQueue.length === 1) {\n resolveNewLock();\n }\n await newLock;\n return lockQueue;\n }\n finishOperationOnKey(key, lockQueue) {\n lockQueue.shift(); // Remove the current lock from the queue\n if (lockQueue.length > 0) {\n // If there are more locks waiting, resolve the next one\n lockQueue[0]();\n }\n }\n getProtocol(key) {\n return { protocolID: [2, this.context], keyID: key };\n }\n async getOutputs(key, limit) {\n const results = await this.wallet.listOutputs({\n basket: this.context,\n tags: [key],\n tagQueryMode: 'all',\n include: 'entire transactions',\n limit\n }, this.originator);\n return results;\n }\n /**\n * Retrieves the value associated with a given key.\n *\n * @param {string} key - The key to retrieve the value for.\n * @param {string | undefined} [defaultValue=undefined] - The value to return if the key is not found.\n * @returns {Promise<string | undefined>} A promise that resolves to the value as a string,\n * the defaultValue if the key is not found, or undefined if no defaultValue is provided.\n * @throws {Error} If too many outputs are found for the key (ambiguous state).\n * @throws {Error} If the found output's locking script cannot be decoded or represents an invalid token format.\n */\n async get(key, defaultValue = undefined) {\n const lockQueue = await this.queueOperationOnKey(key);\n try {\n const r = await this.lookupValue(key, defaultValue, 5);\n return r.value;\n }\n finally {\n this.finishOperationOnKey(key, lockQueue);\n }\n }\n getLockingScript(output, beef) {\n const [txid, vout] = output.outpoint.split('.');\n const tx = beef.findTxid(txid)?.tx;\n if (tx == null) {\n throw new Error(`beef must contain txid ${txid}`);\n }\n const lockingScript = tx.outputs[Number(vout)].lockingScript;\n return lockingScript;\n }\n async lookupValue(key, defaultValue, limit) {\n const lor = await this.getOutputs(key, limit);\n const r = { value: defaultValue, outpoint: undefined, lor };\n const { outputs } = lor;\n if (outputs.length === 0) {\n return r;\n }\n const output = outputs.slice(-1)[0];\n r.outpoint = output.outpoint;\n let field;\n try {\n if (lor.BEEF === undefined) {\n throw new Error('entire transactions listOutputs option must return valid BEEF');\n }\n const lockingScript = this.getLockingScript(output, Beef.fromBinary(lor.BEEF));\n const decoded = PushDrop.decode(lockingScript);\n if (decoded.fields.length < 1 || decoded.fields.length > 2) {\n throw new Error('Invalid token.');\n }\n field = decoded.fields[0];\n }\n catch (error) {\n throw new Error(`Invalid value found. You need to call set to collapse the corrupted state (or relinquish the corrupted ${outputs[0].outpoint} output from the ${this.context} basket) before you can get this value again. Original error: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!this.encrypt) {\n r.value = Utils.toUTF8(field);\n }\n else {\n const { plaintext } = await this.wallet.decrypt({\n ...this.getProtocol(key),\n ciphertext: field\n }, this.originator);\n r.value = Utils.toUTF8(plaintext);\n }\n return r;\n }\n getInputs(outputs) {\n const inputs = [];\n for (let i = 0; i < outputs.length; i++) {\n inputs.push({\n outpoint: outputs[i].outpoint,\n unlockingScriptLength: 74,\n inputDescription: 'Previous key-value token'\n });\n }\n return inputs;\n }\n async getSpends(key, outputs, pushdrop, atomicBEEF) {\n const p = this.getProtocol(key);\n const tx = Transaction.fromAtomicBEEF(atomicBEEF);\n const spends = {};\n for (let i = 0; i < outputs.length; i++) {\n const unlocker = pushdrop.unlock(p.protocolID, p.keyID, 'self');\n const unlockingScript = await unlocker.sign(tx, i);\n spends[i] = {\n unlockingScript: unlockingScript.toHex()\n };\n }\n return spends;\n }\n /**\n * Sets or updates the value associated with a given key atomically.\n * If the key already exists (one or more outputs found), it spends the existing output(s)\n * and creates a new one with the updated value. If multiple outputs exist for the key,\n * they are collapsed into a single new output.\n * If the key does not exist, it creates a new output.\n * Handles encryption if enabled.\n * If signing the update/collapse transaction fails, it relinquishes the original outputs and starts over with a new chain.\n * Ensures atomicity by locking the key during the operation, preventing concurrent updates\n * to the same key from missing earlier changes.\n *\n * @param {string} key - The key to set or update.\n * @param {string} value - The value to associate with the key.\n * @returns {Promise<OutpointString>} A promise that resolves to the outpoint string (txid.vout) of the new or updated token output.\n */\n async set(key, value) {\n const lockQueue = await this.queueOperationOnKey(key);\n try {\n const current = await this.lookupValue(key, undefined, 10);\n if (current.value === value) {\n if (current.outpoint === undefined) {\n throw new Error('outpoint must be valid when value is valid and unchanged');\n }\n // Don't create a new transaction if the value doesn't need to change\n return current.outpoint;\n }\n const protocol = this.getProtocol(key);\n let valueAsArray = Utils.toArray(value, 'utf8');\n if (this.encrypt) {\n const { ciphertext } = await this.wallet.encrypt({\n ...protocol,\n plaintext: valueAsArray\n }, this.originator);\n valueAsArray = ciphertext;\n }\n const pushdrop = new PushDrop(this.wallet, this.originator);\n const lockingScript = await pushdrop.lock([valueAsArray], protocol.protocolID, protocol.keyID, 'self');\n const { outputs, BEEF: inputBEEF } = current.lor;\n let outpoint;\n try {\n const inputs = this.getInputs(outputs);\n const { txid, signableTransaction } = await this.wallet.createAction({\n description: `Update ${key} in ${this.context}`,\n inputBEEF,\n inputs,\n outputs: [{\n basket: this.context,\n tags: [key],\n lockingScript: lockingScript.toHex(),\n satoshis: 1,\n outputDescription: 'Key-value token'\n }],\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast,\n randomizeOutputs: false\n }\n }, this.originator);\n if (outputs.length > 0 && typeof signableTransaction !== 'object') {\n throw new Error('Wallet did not return a signable transaction when expected.');\n }\n if (signableTransaction == null) {\n outpoint = `${txid}.0`;\n }\n else {\n const spends = await this.getSpends(key, outputs, pushdrop, signableTransaction.tx);\n const { txid } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends\n }, this.originator);\n outpoint = `${txid}.0`;\n }\n }\n catch (error) {\n throw new Error(`There are ${outputs.length} outputs with tag ${key} that cannot be unlocked. Original error: ${error instanceof Error ? error.message : String(error)}`);\n }\n return outpoint;\n }\n finally {\n this.finishOperationOnKey(key, lockQueue);\n }\n }\n /**\n * Removes the key-value pair associated with the given key.\n * It finds the existing output(s) for the key and spends them without creating a new output.\n * If multiple outputs exist, they are all spent in the same transaction.\n * If the key does not exist, it does nothing.\n * If signing the removal transaction fails, it relinquishes the original outputs instead of spending.\n *\n * @param {string} key - The key to remove.\n * @returns {Promise<string[]>} A promise that resolves to the txids of the removal transactions if successful.\n */\n async remove(key) {\n const lockQueue = await this.queueOperationOnKey(key);\n try {\n const txids = [];\n for (;;) {\n const { outputs, BEEF: inputBEEF, totalOutputs } = await this.getOutputs(key);\n if (outputs.length > 0) {\n const pushdrop = new PushDrop(this.wallet, this.originator);\n try {\n const inputs = this.getInputs(outputs);\n const { signableTransaction } = await this.wallet.createAction({\n description: `Remove ${key} in ${this.context}`,\n inputBEEF,\n inputs,\n options: {\n acceptDelayedBroadcast: this.acceptDelayedBroadcast\n }\n }, this.originator);\n if (typeof signableTransaction !== 'object') {\n throw new Error('Wallet did not return a signable transaction when expected.');\n }\n const spends = await this.getSpends(key, outputs, pushdrop, signableTransaction.tx);\n const { txid } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends\n }, this.originator);\n if (txid === undefined) {\n throw new Error('signAction must return a valid txid');\n }\n txids.push(txid);\n }\n catch (error) {\n throw new Error(`There are ${totalOutputs} outputs with tag ${key} that cannot be unlocked. Original error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n if (outputs.length === totalOutputs) {\n break;\n }\n }\n return txids;\n }\n finally {\n this.finishOperationOnKey(key, lockQueue);\n }\n }\n}\n//# sourceMappingURL=LocalKVStore.js.map","/**\n * Historian builds a chronological history (oldest → newest) of typed values by traversing\n * a transaction's input ancestry and interpreting each output with a provided interpreter.\n *\n * Core ideas:\n * - You provide an interpreter `(tx, outputIndex) => T | undefined` that decodes one output\n * into your domain value (e.g., kvstore entries). If it returns `undefined`, that output\n * contributes nothing to history.\n * - Traversal follows `Transaction.inputs[].sourceTransaction` recursively, so callers must\n * supply transactions whose inputs have `sourceTransaction` populated (e.g., via overlay\n * history reconstruction).\n * - The traversal visits each transaction once (cycle-safe) and collects interpreted values\n * in reverse-chronological order, then returns them as chronological (oldest-first).\n * - Optional caching support: provide a `historyCache` Map to cache complete history results\n * and avoid re-traversing identical transaction chains with the same context.\n *\n * Usage:\n * - Construct with an interpreter (and optional cache)\n * - Call historian.buildHistory(tx, context) to get an array of values representing the history of a token over time.\n *\n * Example:\n * const cache = new Map() // Optional: for caching repeated queries\n * const historian = new Historian(interpreter, { historyCache: cache })\n * const history = await historian.buildHistory(tipTransaction, context)\n * // history: T[] (e.g., prior values for a protected kvstore key)\n *\n * Caching:\n * - Cache keys are generated from `interpreterVersion|txid|contextKey`\n * - Cached results are immutable snapshots to prevent external mutation\n * - Bump `interpreterVersion` when interpreter semantics change to invalidate old cache entries\n */\nexport class Historian {\n interpreter;\n debug;\n // --- minimal cache support ---\n historyCache;\n interpreterVersion;\n ctxKeyFn;\n /**\n * Create a new Historian instance\n *\n * @param interpreter - Function to interpret transaction outputs into typed values\n * @param options - Configuration options\n * @param options.debug - Enable debug logging (default: false)\n * @param options.historyCache - Optional external cache for complete history results\n * @param options.interpreterVersion - Version identifier for cache invalidation (default: 'v1')\n * @param options.ctxKeyFn - Custom function to serialize context for cache keys (default: JSON.stringify)\n */\n constructor(interpreter, options) {\n this.interpreter = interpreter;\n this.debug = options?.debug ?? false;\n // Configure caching (all optional)\n this.historyCache = options?.historyCache;\n this.interpreterVersion = options?.interpreterVersion ?? 'v1';\n this.ctxKeyFn = options?.ctxKeyFn ?? ((ctx) => {\n try {\n return JSON.stringify(ctx ?? null);\n }\n catch {\n return '';\n }\n });\n }\n historyKey(startTransaction, context) {\n const txid = startTransaction.id('hex');\n const ctxKey = this.ctxKeyFn(context);\n return `${this.interpreterVersion}|${txid}|${ctxKey}`;\n }\n /**\n * Build history by traversing input chain from a starting transaction\n * Returns values in chronological order (oldest first)\n *\n * If caching is enabled, will first check for cached results matching the\n * startTransaction and context. On cache miss, performs full traversal and\n * stores the result for future queries.\n *\n * @param startTransaction - The transaction to start traversal from\n * @param context - The context to pass to the interpreter\n * @returns Array of interpreted values in chronological order\n */\n async buildHistory(startTransaction, context) {\n // --- minimal cache fast path ---\n if (this.historyCache != null) {\n const cacheKey = this.historyKey(startTransaction, context);\n if (this.historyCache.has(cacheKey)) {\n const cached = this.historyCache.get(cacheKey);\n if (cached != null) {\n if (this.debug)\n console.log('[Historian] History cache hit:', cacheKey);\n // Return a shallow copy to avoid external mutation of the cached array\n return cached.slice();\n }\n }\n }\n const history = [];\n const visited = new Set();\n // Recursively traverse input transactions to build history\n const traverseHistory = async (transaction) => {\n const txid = transaction.id('hex');\n // Prevent infinite loops\n if (visited.has(txid)) {\n if (this.debug) {\n console.log(`[Historian] Skipping already visited transaction: ${txid}`);\n }\n return;\n }\n visited.add(txid);\n if (this.debug) {\n console.log(`[Historian] Processing transaction: ${txid}`);\n }\n // Check all outputs in this transaction for interpretable values\n for (let outputIndex = 0; outputIndex < transaction.outputs.length; outputIndex++) {\n try {\n // Try to interpret this output\n const interpretedValue = await Promise.resolve(this.interpreter(transaction, outputIndex, context));\n if (interpretedValue !== undefined) {\n history.push(interpretedValue);\n if (this.debug) {\n console.log('[Historian] Added value to history:', interpretedValue);\n }\n }\n }\n catch (error) {\n if (this.debug) {\n console.log(`[Historian] Failed to interpret output ${outputIndex}:`, error);\n }\n // Skip outputs that can't be interpreted\n }\n }\n // Recursively traverse input transactions\n for (const input of transaction.inputs) {\n if (input.sourceTransaction != null) {\n await traverseHistory(input.sourceTransaction);\n }\n else if (this.debug) {\n console.log('[Historian] Input missing sourceTransaction, skipping');\n }\n }\n };\n // Start traversal from the provided transaction\n await traverseHistory(startTransaction);\n // History is built in reverse chronological order during traversal,\n // so we reverse it to return oldest-first\n const chronological = history.reverse();\n if (this.historyCache != null) {\n const cacheKey = this.historyKey(startTransaction, context);\n // Store an immutable snapshot to avoid accidental external mutation\n this.historyCache.set(cacheKey, Object.freeze(chronological.slice()));\n if (this.debug)\n console.log('[Historian] History cached:', cacheKey);\n }\n return chronological;\n }\n}\n//# sourceMappingURL=Historian.js.map","export const kvProtocol = {\n protocolID: 0,\n key: 1,\n value: 2,\n controller: 3,\n tags: 4,\n signature: 5 // Note: signature moves to position 5 when tags are present\n};\n//# sourceMappingURL=types.js.map","import { PushDrop } from '../script/index.js';\nimport * as Utils from '../primitives/utils.js';\nimport { kvProtocol } from './types.js';\n/**\n * KVStore interpreter used by Historian.\n *\n * Validates the KVStore PushDrop tokens: [protocolID, key, value, controller, signature] (old format)\n * or [protocolID, key, value, controller, tags, signature] (new format).\n * Filters outputs by the provided key in the interpreter context.\n * Produces the plaintext value for matching outputs; returns undefined otherwise.\n *\n * @param transaction - The transaction to inspect.\n * @param outputIndex - The index of the output within transaction.outputs.\n * @param ctx - { key: string, protocolID: WalletProtocol } — per-call context specifying which key to match.\n *\n * @returns string | undefined — the decoded KV value if the output is a valid KVStore token for the\n * given key; otherwise undefined.\n */\nexport const kvStoreInterpreter = async (transaction, outputIndex, ctx) => {\n try {\n const output = transaction.outputs[outputIndex];\n if (output == null || output.lockingScript == null)\n return undefined;\n if (ctx == null || ctx.key == null)\n return undefined;\n // Decode the KVStore token\n const decoded = PushDrop.decode(output.lockingScript);\n // Support backwards compatibility: old format without tags, new format with tags\n const expectedFieldCount = Object.keys(kvProtocol).length;\n const hasTagsField = decoded.fields.length === expectedFieldCount;\n const isOldFormat = decoded.fields.length === expectedFieldCount - 1;\n if (!isOldFormat && !hasTagsField)\n return undefined;\n // Only return values for the given key and protocolID\n const key = Utils.toUTF8(decoded.fields[kvProtocol.key]);\n const protocolID = Utils.toUTF8(decoded.fields[kvProtocol.protocolID]);\n if (key !== ctx.key || protocolID !== JSON.stringify(ctx.protocolID))\n return undefined;\n try {\n return Utils.toUTF8(decoded.fields[kvProtocol.value]);\n }\n catch {\n return undefined;\n }\n }\n catch {\n // Skip non-KVStore outputs or malformed tokens\n return undefined;\n }\n};\n//# sourceMappingURL=kvStoreInterpreter.js.map","import Transaction from '../transaction/Transaction.js';\nimport * as Utils from '../primitives/utils.js';\nimport { TopicBroadcaster, LookupResolver, withDoubleSpendRetry } from '../overlay-tools/index.js';\nimport { PushDrop } from '../script/index.js';\nimport WalletClient from '../wallet/WalletClient.js';\nimport { Beef } from '../transaction/Beef.js';\nimport { Historian } from '../overlay-tools/Historian.js';\nimport { kvStoreInterpreter } from './kvStoreInterpreter.js';\nimport { ProtoWallet } from '../wallet/ProtoWallet.js';\nimport { kvProtocol } from './types.js';\n/**\n * Default configuration values for GlobalKVStore operations.\n * Provides sensible defaults for overlay connection and protocol settings.\n */\nconst DEFAULT_CONFIG = {\n protocolID: [1, 'kvstore'],\n serviceName: 'ls_kvstore',\n tokenAmount: 1,\n topics: ['tm_kvstore'],\n networkPreset: 'mainnet',\n acceptDelayedBroadcast: false,\n overlayBroadcast: false, // Use overlay broadcasting to prevent UTXO spending on broadcast rejection.\n tokenSetDescription: '', // Will be set dynamically\n tokenUpdateDescription: '', // Will be set dynamically\n tokenRemovalDescription: '' // Will be set dynamically\n};\n/**\n * Implements a global key-value storage system which uses an overlay service to track key-value pairs.\n * Each key-value pair is represented by a PushDrop token output.\n * Allows getting, setting, and removing key-value pairs with optional fetching by protocolID and history tracking.\n */\nexport class GlobalKVStore {\n /**\n * The wallet interface used to create transactions and perform cryptographic operations.\n * @readonly\n */\n wallet;\n /**\n * Configuration for the KVStore instance containing all runtime options.\n * @private\n * @readonly\n */\n config;\n /**\n * Historian instance used to extract history from transaction outputs.\n * @private\n */\n historian;\n /**\n * Lookup resolver used to query the overlay for transaction outputs.\n * @private\n */\n lookupResolver;\n /**\n * Topic broadcaster used to broadcast transactions to the overlay.\n * @private\n */\n topicBroadcaster;\n /**\n * A map to store locks for each key to ensure atomic updates.\n * @private\n */\n keyLocks = new Map();\n /**\n * Cached user identity key\n * @private\n */\n cachedIdentityKey = null;\n /**\n * Creates an instance of the GlobalKVStore.\n *\n * @param {KVStoreConfig} [config={}] - Configuration options for the KVStore. Defaults to empty object.\n * @param {WalletInterface} [config.wallet] - Wallet to use for operations. Defaults to WalletClient.\n * @throws {Error} If the configuration contains invalid parameters.\n */\n constructor(config = {}) {\n // Merge with defaults to create a fully resolved config\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.wallet = config.wallet ?? new WalletClient();\n this.historian = new Historian(kvStoreInterpreter);\n this.lookupResolver = new LookupResolver({\n networkPreset: this.config.networkPreset\n });\n this.topicBroadcaster = new TopicBroadcaster(this.config.topics, {\n networkPreset: this.config.networkPreset\n });\n }\n /**\n * Retrieves data from the KVStore.\n * Can query by key+controller (single result), protocolID, controller, or key (multiple results).\n *\n * @param {KVStoreQuery} query - Query parameters sent to overlay\n * @param {KVStoreGetOptions} [options={}] - Configuration options for the get operation\n * @returns {Promise<KVStoreEntry | KVStoreEntry[] | undefined>} Single entry for key+controller queries, array for all other queries\n */\n async get(query, options = {}) {\n if (Object.keys(query).length === 0) {\n throw new Error('Must specify either key, controller, or protocolID');\n }\n if (query.key != null && query.controller != null) {\n // Specific key+controller query - return single entry\n const entries = await this.queryOverlay(query, options);\n return entries.length > 0 ? entries[0] : undefined;\n }\n return await this.queryOverlay(query, options);\n }\n /**\n * Sets a key-value pair. The current user (wallet identity) becomes the controller.\n *\n * @param {string} key - The key to set (user computes this however they want)\n * @param {string} value - The value to store\n * @param {KVStoreSetOptions} [options={}] - Configuration options for the set operation\n * @returns {Promise<OutpointString>} The outpoint of the created token\n */\n async set(key, value, options = {}) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error('Key must be a non-empty string.');\n }\n if (typeof value !== 'string') {\n throw new Error('Value must be a string.');\n }\n const controller = await this.getIdentityKey();\n const lockQueue = await this.queueOperationOnKey(key);\n const protocolID = options.protocolID ?? this.config.protocolID;\n const tokenSetDescription = (options.tokenSetDescription != null && options.tokenSetDescription !== '') ? options.tokenSetDescription : `Create KVStore value for ${key}`;\n const tokenUpdateDescription = (options.tokenUpdateDescription != null && options.tokenUpdateDescription !== '') ? options.tokenUpdateDescription : `Update KVStore value for ${key}`;\n const tokenAmount = options.tokenAmount ?? this.config.tokenAmount;\n const tags = options.tags ?? [];\n try {\n // Create PushDrop locking script (reusable across retries)\n const pushdrop = new PushDrop(this.wallet, this.config.originator);\n const lockingScriptFields = [\n Utils.toArray(JSON.stringify(protocolID), 'utf8'),\n Utils.toArray(key, 'utf8'),\n Utils.toArray(value, 'utf8'),\n Utils.toArray(controller, 'hex')\n ];\n // Add tags as optional 5th field for backwards compatibility\n if (tags.length > 0) {\n lockingScriptFields.push(Utils.toArray(JSON.stringify(tags), 'utf8'));\n }\n const lockingScript = await pushdrop.lock(lockingScriptFields, protocolID ?? this.config.protocolID, Utils.toUTF8(Utils.toArray(key, 'utf8')), 'anyone', true);\n // Wrap entire operation in double-spend retry, including overlay query\n const outpoint = await withDoubleSpendRetry(async () => {\n // Re-query overlay on each attempt to get fresh token state\n const existingEntries = await this.queryOverlay({ key, controller }, { includeToken: true });\n const existingToken = existingEntries.length > 0 ? existingEntries[0].token : undefined;\n if (existingToken != null) {\n // Update existing token\n const inputs = [{\n outpoint: `${existingToken.txid}.${existingToken.outputIndex}`,\n unlockingScriptLength: 74,\n inputDescription: 'Previous KVStore token'\n }];\n const inputBEEF = existingToken.beef;\n const { signableTransaction } = await this.wallet.createAction({\n description: tokenUpdateDescription,\n inputBEEF: inputBEEF.toBinary(),\n inputs,\n outputs: [{\n satoshis: tokenAmount ?? this.config.tokenAmount,\n lockingScript: lockingScript.toHex(),\n outputDescription: 'KVStore token'\n }],\n options: {\n acceptDelayedBroadcast: this.config.acceptDelayedBroadcast,\n noSend: this.config.overlayBroadcast,\n randomizeOutputs: false\n }\n }, this.config.originator);\n if (signableTransaction == null) {\n throw new Error('Unable to create update transaction');\n }\n const tx = Transaction.fromAtomicBEEF(signableTransaction.tx);\n const unlocker = pushdrop.unlock(this.config.protocolID, key, 'anyone');\n const unlockingScript = await unlocker.sign(tx, 0);\n const { tx: finalTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: { 0: { unlockingScript: unlockingScript.toHex() } },\n options: {\n acceptDelayedBroadcast: this.config.acceptDelayedBroadcast,\n noSend: this.config.overlayBroadcast\n }\n }, this.config.originator);\n if (finalTx == null) {\n throw new Error('Unable to finalize update transaction');\n }\n const transaction = Transaction.fromAtomicBEEF(finalTx);\n await this.submitToOverlay(transaction);\n return `${transaction.id('hex')}.0`;\n }\n else {\n // Create new token\n const { tx } = await this.wallet.createAction({\n description: tokenSetDescription,\n outputs: [{\n satoshis: tokenAmount ?? this.config.tokenAmount,\n lockingScript: lockingScript.toHex(),\n outputDescription: 'KVStore token'\n }],\n options: {\n acceptDelayedBroadcast: this.config.acceptDelayedBroadcast,\n noSend: this.config.overlayBroadcast,\n randomizeOutputs: false\n }\n }, this.config.originator);\n if (tx == null) {\n throw new Error('Failed to create transaction');\n }\n const transaction = Transaction.fromAtomicBEEF(tx);\n await this.submitToOverlay(transaction);\n return `${transaction.id('hex')}.0`;\n }\n }, this.topicBroadcaster);\n return outpoint;\n }\n finally {\n if (lockQueue.length > 0) {\n this.finishOperationOnKey(key, lockQueue);\n }\n }\n }\n /**\n * Removes the key-value pair associated with the given key from the overlay service.\n *\n * @param {string} key - The key to remove.\n * @param {CreateActionOutput[] | undefined} [outputs=undefined] - Additional outputs to include in the removal transaction.\n * @param {KVStoreRemoveOptions} [options=undefined] - Optional parameters for the removal operation.\n * @returns {Promise<HexString>} A promise that resolves to the txid of the removal transaction if successful.\n * @throws {Error} If the key is invalid.\n * @throws {Error} If the key does not exist in the store.\n * @throws {Error} If the overlay service is unreachable or the transaction fails.\n * @throws {Error} If there are existing tokens that cannot be unlocked.\n */\n async remove(key, outputs, options = {}) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error('Key must be a non-empty string.');\n }\n const controller = await this.getIdentityKey();\n const lockQueue = await this.queueOperationOnKey(key);\n const protocolID = options.protocolID ?? this.config.protocolID;\n const tokenRemovalDescription = (options.tokenRemovalDescription != null && options.tokenRemovalDescription !== '') ? options.tokenRemovalDescription : `Remove KVStore value for ${key}`;\n try {\n const pushdrop = new PushDrop(this.wallet, this.config.originator);\n // Remove token with double-spend retry\n const txid = await withDoubleSpendRetry(async () => {\n // Re-query overlay on each attempt to get fresh token state\n const existingEntries = await this.queryOverlay({ key, controller }, { includeToken: true });\n if (existingEntries.length === 0 || existingEntries[0].token == null) {\n throw new Error('The item did not exist, no item was deleted.');\n }\n const existingToken = existingEntries[0].token;\n const inputs = [{\n outpoint: `${existingToken.txid}.${existingToken.outputIndex}`,\n unlockingScriptLength: 74,\n inputDescription: 'KVStore token to remove'\n }];\n const { signableTransaction } = await this.wallet.createAction({\n description: tokenRemovalDescription,\n inputBEEF: existingToken.beef.toBinary(),\n inputs,\n outputs,\n options: {\n acceptDelayedBroadcast: this.config.acceptDelayedBroadcast,\n randomizeOutputs: false,\n noSend: this.config.overlayBroadcast\n }\n }, this.config.originator);\n if (signableTransaction == null) {\n throw new Error('Unable to create removal transaction');\n }\n const tx = Transaction.fromAtomicBEEF(signableTransaction.tx);\n const unlocker = pushdrop.unlock(protocolID ?? this.config.protocolID, key, 'anyone');\n const unlockingScript = await unlocker.sign(tx, 0);\n const { tx: finalTx } = await this.wallet.signAction({\n reference: signableTransaction.reference,\n spends: { 0: { unlockingScript: unlockingScript.toHex() } },\n options: {\n acceptDelayedBroadcast: this.config.acceptDelayedBroadcast,\n noSend: this.config.overlayBroadcast\n }\n }, this.config.originator);\n if (finalTx == null) {\n throw new Error('Unable to finalize removal transaction');\n }\n const transaction = Transaction.fromAtomicBEEF(finalTx);\n await this.submitToOverlay(transaction);\n return transaction.id('hex');\n }, this.topicBroadcaster);\n return txid;\n }\n finally {\n if (lockQueue.length > 0) {\n this.finishOperationOnKey(key, lockQueue);\n }\n }\n }\n /**\n * Queues an operation on a specific key to ensure atomic updates.\n * Prevents concurrent operations on the same key from interfering with each other.\n *\n * @param {string} key - The key to queue an operation for.\n * @returns {Promise<Array<(value: void | PromiseLike<void>) => void>>} The lock queue for cleanup.\n * @private\n */\n async queueOperationOnKey(key) {\n // Check if a lock exists for this key and wait for it to resolve\n let lockQueue = this.keyLocks.get(key);\n if (lockQueue == null) {\n lockQueue = [];\n this.keyLocks.set(key, lockQueue);\n }\n let resolveNewLock = () => { };\n const newLock = new Promise((resolve) => {\n resolveNewLock = resolve;\n if (lockQueue != null) {\n lockQueue.push(resolve);\n }\n });\n // If we are the only request, resolve the lock immediately, queue remains at 1 item until request ends.\n if (lockQueue.length === 1) {\n resolveNewLock();\n }\n await newLock;\n return lockQueue;\n }\n /**\n * Finishes an operation on a key and resolves the next waiting operation.\n *\n * @param {string} key - The key to finish the operation for.\n * @param {Array<(value: void | PromiseLike<void>) => void>} lockQueue - The lock queue from queueOperationOnKey.\n * @private\n */\n finishOperationOnKey(key, lockQueue) {\n lockQueue.shift(); // Remove the current lock from the queue\n if (lockQueue.length > 0) {\n // If there are more locks waiting, resolve the next one\n lockQueue[0]();\n }\n else {\n // Clean up empty queue to prevent memory leak\n this.keyLocks.delete(key);\n }\n }\n /**\n * Helper function to fetch and cache user identity key\n *\n * @returns {Promise<PubKeyHex>} The identity key of the current user\n * @private\n */\n async getIdentityKey() {\n if (this.cachedIdentityKey == null) {\n this.cachedIdentityKey = (await this.wallet.getPublicKey({ identityKey: true }, this.config.originator)).publicKey;\n }\n return this.cachedIdentityKey;\n }\n /**\n * Queries the overlay service for KV entries.\n *\n * @param {KVStoreQuery} query - Query parameters sent to overlay\n * @param {KVStoreGetOptions} options - Configuration options for the query\n * @returns {Promise<KVStoreEntry[]>} Array of matching KV entries\n * @private\n */\n async queryOverlay(query, options = {}) {\n const answer = await this.lookupResolver.query({\n service: options.serviceName ?? this.config.serviceName,\n query\n });\n if (answer.type !== 'output-list' || answer.outputs.length === 0) {\n return [];\n }\n const entries = [];\n for (const result of answer.outputs) {\n try {\n const tx = Transaction.fromBEEF(result.beef);\n const output = tx.outputs[result.outputIndex];\n const decoded = PushDrop.decode(output.lockingScript);\n // Support backwards compatibility: old format without tags, new format with tags\n const expectedFieldCount = Object.keys(kvProtocol).length;\n const hasTagsField = decoded.fields.length === expectedFieldCount;\n const isOldFormat = decoded.fields.length === expectedFieldCount - 1;\n if (!isOldFormat && !hasTagsField) {\n continue;\n }\n // Verify signature\n const anyoneWallet = new ProtoWallet('anyone');\n const signature = decoded.fields.pop();\n try {\n await anyoneWallet.verifySignature({\n data: decoded.fields.reduce((a, e) => [...a, ...e], []),\n signature,\n counterparty: Utils.toHex(decoded.fields[kvProtocol.controller]),\n protocolID: JSON.parse(Utils.toUTF8(decoded.fields[kvProtocol.protocolID])),\n keyID: Utils.toUTF8(decoded.fields[kvProtocol.key])\n });\n }\n catch (error) {\n // Skip all outputs that fail signature verification\n continue;\n }\n // Extract tags if present (backwards compatible)\n let tags;\n if (hasTagsField && decoded.fields[kvProtocol.tags] != null) {\n try {\n tags = JSON.parse(Utils.toUTF8(decoded.fields[kvProtocol.tags]));\n }\n catch (e) {\n // If tags parsing fails, continue without tags\n tags = undefined;\n }\n }\n const entry = {\n key: Utils.toUTF8(decoded.fields[kvProtocol.key]),\n value: Utils.toUTF8(decoded.fields[kvProtocol.value]),\n controller: Utils.toHex(decoded.fields[kvProtocol.controller]),\n protocolID: JSON.parse(Utils.toUTF8(decoded.fields[kvProtocol.protocolID])),\n tags\n };\n if (options.includeToken === true) {\n entry.token = {\n txid: tx.id('hex'),\n outputIndex: result.outputIndex,\n beef: Beef.fromBinary(result.beef),\n satoshis: output.satoshis ?? 1\n };\n }\n if (options.history === true) {\n entry.history = await this.historian.buildHistory(tx, {\n key: entry.key,\n protocolID: entry.protocolID\n });\n }\n entries.push(entry);\n }\n catch (error) {\n continue;\n }\n }\n return entries;\n }\n /**\n * Submits a transaction to an overlay service using TopicBroadcaster.\n * Broadcasts the transaction to the configured topics for network propagation.\n *\n * @param {Transaction} transaction - The transaction to broadcast.\n * @returns {Promise<BroadcastResponse | BroadcastFailure>} The broadcast result.\n * @throws {Error} If the broadcast fails or the network is unreachable.\n * @private\n */\n async submitToOverlay(transaction) {\n return await this.topicBroadcaster.broadcast(transaction);\n }\n}\nexport default GlobalKVStore;\n//# sourceMappingURL=GlobalKVStore.js.map"],"names":["e","Object","Symbol","globalThis","Int8Array","BigInt","Number","t","Array","Math","parseInt","isNaN","Error","r","i","n","s","h","console","B","Uint8Array","ArrayBuffer","DataView","TextEncoder","l","o","Uint32Array","require","Buffer","TypeError","String","to","Map","JSON","a","p","process","self","window","Set","c","u","Date","fetch","Promise","Blob","d","document","URL","setTimeout","clearTimeout","Response","Headers","setInterval","FormData","URLSearchParams","ReadableStream","AbortController","f"],"mappings":"2NAQI,ECwnDM,EACA,EACA,E,ICznDC,ECDA,EC8DA,ECpEA,EHMA,ECDA,EC8DA,ECpEP,E,ICDJ,GAAoB,CAAC,CAAG,CAACA,EAAS,KACjC,IAAI,IAAI,KAAO,EACL,EAAoB,CAAC,CAAC,EAAY,IAAQ,CAAC,EAAoB,CAAC,CAACA,EAAS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T,MAAO,OACP,EAAG,0EACH,EAAG,IACH,EAAG,IACH,EAAG,0EACH,EAAG,IAEH,KAAM,mEACN,OAAQ,mEACR,MAAO,CACH,CACI,EAAG,mCACH,EAAG,mCACP,EACA,CACI,EAAG,oCACH,EAAG,kCACP,EACH,CACD,KAAM,GACN,EAAG,CACC,mEACA,mEAnyBY,CAChB,QAAS,CACL,KAAM,EACN,OAAQ,CACJ,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,iEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACJ,AACL,EACA,IAAK,CACD,IAAK,EACL,OAAQ,CACJ,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,iEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,kEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,kEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACD,CACI,mEACA,mEACH,CACJ,AACL,CACJ,EA0BK,AACL,CACA,KAAI,CAAC,CAAC,CAAG,IAAI,EAAU,EAAK,CAAC,CAAE,IAE/B,IAAI,CAAC,GAAG,CAAG,IAAI,EAAiB,EAAK,KAAK,EAE1C,IAAI,CAAC,IAAI,CAAG,IAAI,EAAU,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAC3C,IAAI,CAAC,GAAG,CAAG,IAAI,EAAU,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAC1C,IAAI,CAAC,GAAG,CAAG,IAAI,EAAU,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAE1C,IAAI,CAAC,CAAC,CAAG,IAAI,EAAU,EAAK,CAAC,CAAE,IAC/B,IAAI,CAAC,CAAC,CA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AC,UAAU,EAC7B,KAAK,CAAC,IAAI,CAAC,SAAS,EACpB,UAAU,CAAC,GACX,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAM,KACjC,OAAO,GAEX,GAAI,EACL,OAAO,IAAI,KACN,aAAa,CAAC,IAAI,CAAC,eAAe,EAClC,UAAU,CAAC,IAAI,CAAC,KAAK,EACrB,KAAK,CAAC,IAAI,CAAC,iBAAiB,EAC5B,aAAa,CAAC,IAAI,CAAC,UAAU,EAC7B,KAAK,CAAC,IAAI,CAAC,SAAS,EACpB,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KACzB,OAAO,EAGZ,OAAM,AAAIF,MAAM,sCAExB,CAMA,WAAY,CACR,OAAO,IAAI,CAAC,eAAe,GAAK,IAAI,CAAC,SAAS,CAAC,OAAO,AAC1D,CACJ,CChUO,IAAM,GAAW,CACpB,MAAO,CACH,UACA,UACA,OACA,QACA,QACA,SACA,SACA,WACA,SACA,QACA,SACA,WACA,UACA,SACA,UACA,OACA,WACA,UACA,SACA,MACA,SACA,QACA,UACA,SACA,QACA,MACA,SACA,UACA,SACA,QACA,QACA,UACA,SACA,UACA,SACA,SACA,SACA,QACA,MACA,QACA,QACA,QACA,MACA,MACA,UACA,QACA,QACA,QACA,UACA,QACA,QACA,MACA,QACA,QACA,SACA,QACA,QACA,UACA,OACA,QACA,SACA,UACA,UACA,QACA,SACA,SACA,UACA,SACA,UACA,QACA,QACA,QACA,SACA,QACA,WACA,SACA,UACA,SACA,UACA,UACA,UACA,MACA,QACA,UACA,SACA,QACA,UACA,QACA,OACA,SACA,OACA,QACA,QACA,MACA,QACA,QACA,OACA,SACA,UACA,SACA,SACA,QACA,MACA,WACA,SACA,UACA,MACA,SACA,UACA,QACA,SACA,SACA,SACA,UACA,OACA,SACA,SACA,WACA,UACA,UACA,QACA,SACA,OACA,SACA,OACA,SACA,UACA,UACA,QACA,QACA,QACA,OACA,UACA,QACA,UACA,OACA,OACA,WACA,QACA,QACA,MACA,UACA,UACA,OACA,SACA,SACA,SACA,MACA,SACA,UACA,SACA,OACA,QACA,SACA,SACA,QACA,OACA,SACA,UACA,SACA,OACA,SACA,QACA,SACA,SACA,UACA,QACA,OACA,QACA,UACA,OACA,SACA,SACA,UACA,SACA,UACA,MACA,OACA,OACA,UACA,OACA,QACA,SACA,QACA,QACA,QACA,UACA,QACA,QACA,QACA,QACA,QACA,UACA,SACA,OACA,OACA,QACA,QACA,OACA,OACA,OACA,OACA,OACA,QACA,OACA,QACA,SACA,SACA,SACA,OACA,SACA,SACA,MACA,MACA,UACA,QACA,QACA,QACA,QACA,QACA,SACA,QACA,SACA,QACA,SACA,QACA,QACA,WACA,SACA,SACA,QACA,UACA,QACA,QACA,SACA,QACA,SACA,UACA,QACA,OACA,OACA,SACA,SACA,SACA,SACA,SACA,QACA,MACA,WACA,OACA,SACA,QACA,OACA,UACA,QACA,QACA,SACA,OACA,OACA,OACA,OACA,SACA,OACA,MACA,QACA,SACA,QACA,SACA,QACA,SACA,SACA,UACA,UACA,UACA,MACA,SACA,OACA,QACA,SACA,QACA,OACA,OACA,OACA,SACA,SACA,SACA,MACA,UACA,QACA,WACA,SACA,SACA,QACA,UACA,OACA,UACA,SACA,SACA,SACA,UACA,SACA,UACA,QACA,QACA,WACA,SACA,QACA,UACA,SACA,QACA,OACA,QACA,QACA,SACA,OACA,SACA,QACA,UACA,QACA,QACA,UACA,SACA,SACA,UACA,UACA,QACA,QACA,QACA,WACA,SACA,UACA,OACA,QACA,QACA,OACA,UACA,OACA,OACA,QACA,QACA,SACA,QACA,SACA,QACA,QACA,SACA,OACA,QACA,OACA,QACA,QACA,QACA,QACA,OACA,QACA,UACA,SACA,QACA,QACA,UACA,OACA,SACA,OACA,OACA,UACA,QACA,SACA,UACA,OACA,UACA,QACA,SACA,UACA,UACA,UACA,UACA,WACA,UACA,WACA,UACA,WACA,OACA,OACA,SACA,OACA,QACA,OACA,OACA,UACA,OACA,SACA,QACA,UACA,SACA,SACA,SACA,QACA,SACA,QACA,SACA,QACA,OACA,QACA,QACA,SACA,QACA,QACA,QACA,SACA,QACA,OACA,UACA,QACA,QACA,SACA,OACA,QACA,SACA,QACA,UACA,QACA,SACA,UACA,SACA,QACA,MACA,UACA,OACA,UACA,MACA,WACA,UACA,UACA,UACA,QACA,UACA,SACA,OACA,QACA,MACA,SACA,OACA,QACA,SACA,SACA,OACA,WACA,OACA,MACA,OACA,SACA,SACA,SACA,WACA,SACA,UACA,WACA,WACA,OACA,UACA,SACA,OACA,SACA,QACA,UACA,SACA,SACA,SACA,UACA,OACA,SACA,SACA,UACA,QACA,SACA,SACA,WACA,SACA,SACA,OACA,UACA,UACA,SACA,SACA,UACA,SACA,SACA,UACA,OACA,UACA,QACA,OACA,SACA,OACA,SACA,UACA,UACA,UACA,SACA,WACA,SACA,OACA,WACA,WACA,UACA,OACA,UACA,WACA,UACA,WACA,SACA,SACA,UACA,QACA,SACA,WACA,MACA,OACA,UACA,SACA,SACA,SACA,QACA,OACA,OACA,SACA,OACA,QACA,SACA,QACA,UACA,OACA,QACA,QACA,QACA,QACA,QACA,OACA,QACA,OACA,OACA,MACA,OACA,OACA,OACA,SACA,OACA,QACA,OACA,QACA,UACA,QACA,QACA,QACA,OACA,QACA,SACA,OACA,OACA,OACA,UACA,UACA,OACA,OACA,UACA,SACA,MACA,QACA,SACA,QACA,QACA,WACA,UACA,UACA,WACA,WACA,QACA,OACA,SACA,SACA,UACA,SACA,UACA,SACA,UACA,QACA,SACA,QACA,MACA,UACA,UACA,QACA,SACA,UACA,SACA,SACA,UACA,QACA,SACA,SACA,SACA,SACA,SACA,QACA,SACA,QACA,WACA,UACA,QACA,QACA,MACA,QACA,QACA,UACA,QACA,QACA,SACA,QACA,UACA,SACA,UACA,SACA,WACA,OACA,QACA,SACA,QACA,UACA,SACA,WACA,SACA,UACA,SACA,UACA,WACA,UACA,UACA,QACA,QACA,OACA,SACA,SACA,SACA,SACA,UACA,SACA,UACA,SACA,QACA,MACA,UACA,SACA,OACA,UACA,OACA,QACA,QACA,OACA,QACA,OACA,SACA,SACA,MACA,QACA,UACA,OACA,UACA,MACA,QACA,SACA,UACA,QACA,WACA,UACA,WACA,UACA,MACA,OACA,OACA,SACA,QACA,WACA,QACA,QACA,MACA,QACA,UACA,QACA,SACA,OACA,OACA,SACA,QACA,OACA,OACA,SACA,SACA,OACA,OACA,QACA,SACA,OACA,MACA,UACA,MACA,OACA,QACA,QACA,OACA,SACA,OACA,SACA,OACA,QACA,QACA,QACA,SACA,QACA,QACA,MACA,OACA,QACA,MACA,OACA,OACA,SACA,OACA,OACA,QACA,SACA,SACA,OACA,UACA,QACA,UACA,SACA,SACA,QACA,MACA,UACA,QACA,WACA,QACA,SACA,SACA,OACA,QACA,QACA,QACA,SACA,QACA,OACA,MACA,QACA,UACA,OACA,SACA,SACA,OACA,SACA,UACA,OACA,MACA,SACA,UACA,SACA,SACA,UACA,MACA,OACA,OACA,SACA,QACA,OACA,UACA,SACA,QACA,SACA,UACA,UACA,QACA,QACA,OACA,SACA,SACA,UACA,OACA,OACA,OACA,SACA,QACA,QACA,QACA,UACA,QACA,QACA,QACA,QACA,OACA,OACA,OACA,UACA,OACA,OACA,QACA,UACA,SACA,SACA,SACA,OACA,OACA,QACA,QACA,QACA,QACA,QACA,UACA,QACA,QACA,OACA,QACA,OACA,UACA,QACA,OACA,QACA,QACA,QACA,QACA,QACA,SACA,MACA,MACA,QACA,OACA,OACA,SACA,UACA,OACA,QACA,SACA,OACA,QACA,UACA,MACA,OACA,OACA,SACA,OACA,SACA,QACA,QACA,WACA,SACA,QACA,SACA,OACA,MACA,OACA,SACA,OACA,OACA,OACA,MACA,OACA,UACA,QACA,SACA,OACA,OACA,UACA,SACA,OACA,QACA,OACA,OACA,OACA,SACA,QACA,WACA,OACA,QACA,OACA,QACA,MACA,OACA,QACA,SACA,QACA,UACA,SACA,OACA,SACA,QACA,OACA,UACA,SACA,MACA,OACA,OACA,WACA,OACA,SACA,MACA,UACA,UACA,QACA,UACA,UACA,SACA,SACA,SACA,UACA,UACA,OACA,UACA,SACA,WACA,QACA,WACA,SACA,WACA,SACA,UACA,SACA,SACA,UACA,UACA,SACA,SACA,SACA,QACA,WACA,QACA,UACA,SACA,SACA,SACA,UACA,UACA,SACA,WACA,OACA,SACA,SACA,UACA,OACA,SACA,UACA,QACA,OACA,QACA,SACA,SACA,MACA,OACA,UACA,QACA,QACA,QACA,MACA,OACA,OACA,UACA,MACA,QACA,QACA,OACA,SACA,SACA,OACA,OACA,WACA,OACA,OACA,UACA,MACA,OACA,MACA,SACA,OACA,UACA,OACA,MACA,UACA,OACA,SACA,OACA,OACA,QACA,QACA,OACA,MACA,QACA,QACA,SACA,OACA,OACA,OACA,WACA,SACA,QACA,QACA,QACA,QACA,UACA,OACA,MACA,OACA,UACA,QACA,OACA,SACA,OACA,QACA,QACA,UACA,OACA,MACA,QACA,SACA,UACA,QACA,OACA,SACA,OACA,UACA,SACA,SACA,QACA,OACA,UACA,UACA,UACA,OACA,OACA,QACA,OACA,OACA,QACA,OACA,OACA,SACA,OACA,SACA,OACA,SACA,OACA,OACA,UACA,QACA,OACA,QACA,SACA,OACA,OACA,UACA,OACA,SACA,OACA,QACA,QACA,UACA,SACA,QACA,QACA,SACA,SACA,UACA,MACA,QACA,SACA,OACA,OACA,OACA,QACA,OACA,SACA,MACA,SACA,UACA,QACA,UACA,SACA,QACA,SACA,QACA,SACA,SACA,SACA,WACA,OACA,OACA,SACA,QACA,WACA,OACA,SACA,SACA,UACA,OACA,SACA,OACA,UACA,OACA,WACA,QACA,QACA,SACA,OACA,SACA,SACA,UACA,OACA,QACA,QACA,QACA,QACA,OACA,UACA,QACA,SACA,SACA,WACA,OACA,UACA,QACA,OACA,UACA,QACA,SACA,UACA,SACA,SACA,OACA,UACA,MACA,QACA,UACA,SACA,QACA,SACA,MACA,SACA,UACA,SACA,UACA,QACA,OACA,QACA,OACA,UACA,WACA,SACA,SACA,QACA,WACA,QACA,OACA,QACA,OACA,SACA,OACA,WACA,SACA,SACA,WACA,QACA,OACA,SACA,SACA,UACA,OACA,QACA,OACA,SACA,SACA,QACA,SACA,SACA,OACA,OACA,OACA,WACA,UACA,UACA,SACA,QACA,OACA,MACA,UACA,UACA,QACA,OACA,OACA,OACA,QACA,QACA,QACA,UACA,SACA,SACA,QACA,OACA,UACA,OACA,UACA,SACA,QACA,MACA,UACA,SACA,QACA,MACA,MACA,OACA,SACA,SACA,UACA,UACA,SACA,UACA,QACA,QACA,UACA,OACA,MACA,QACA,SACA,QACA,MACA,OACA,MACA,QACA,UACA,OACA,OACA,MACA,QACA,SACA,OACA,OACA,QACA,UACA,SACA,SACA,SACA,QACA,UACA,QACA,WACA,QACA,SACA,WACA,SACA,UACA,QACA,UACA,QACA,SACA,UACA,OACA,OACA,OACA,MACA,QACA,SACA,SACA,QACA,OACA,SACA,OACA,OACA,SACA,OACA,QACA,QACA,QACA,UACA,QACA,SACA,SACA,OACA,SACA,QACA,OACA,QACA,OACA,UACA,SACA,UACA,QACA,OACA,UACA,QACA,SACA,OACA,UACA,UACA,MACA,UACA,SACA,SACA,SACA,UACA,SACA,SACA,MACA,QACA,QACA,SACA,WACA,QACA,SACA,UACA,QACA,MACA,SACA,OACA,QACA,OACA,UACA,OACA,SACA,QACA,QACA,QACA,SACA,UACA,QACA,OACA,SACA,SACA,QACA,OACA,SACA,OACA,OACA,QACA,QACA,OACA,SACA,OACA,OACA,OACA,UACA,UACA,WACA,WACA,OACA,SACA,UACA,UACA,SACA,QACA,WACA,SACA,UACA,SACA,UACA,UACA,SACA,UACA,QACA,QACA,UACA,QACA,WACA,SACA,UACA,QACA,UACA,UACA,UACA,SACA,UACA,UACA,UACA,QACA,WACA,UACA,UACA,QACA,UACA,SACA,UACA,OACA,OACA,QACA,UACA,QACA,QACA,QACA,WACA,SACA,UACA,QACA,OACA,MACA,SACA,UACA,UACA,UACA,UACA,WACA,QACA,OACA,OACA,QACA,SACA,UACA,OACA,OACA,QACA,QACA,OACA,OACA,QACA,QACA,OACA,QACA,SACA,QACA,QACA,OACA,OACA,SACA,QACA,MACA,QACA,QACA,OACA,SACA,QACA,UACA,SACA,UACA,SACA,SACA,UACA,SACA,UACA,SACA,SACA,SACA,SACA,UACA,SACA,QACA,UACA,SACA,OACA,SACA,WACA,SACA,SACA,SACA,QACA,OACA,SACA,SACA,SACA,UACA,SACA,UACA,SACA,WACA,SACA,WACA,WACA,SACA,SACA,UACA,SACA,UACA,SACA,SACA,SACA,SACA,MACA,SACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,OACA,OACA,SACA,OACA,SACA,QACA,QACA,OACA,QACA,QACA,SACA,SACA,UACA,OACA,SACA,OACA,OACA,SACA,QACA,QACA,QACA,QACA,SACA,OACA,MACA,OACA,MACA,SACA,QACA,MACA,SACA,UACA,OACA,OACA,QACA,SACA,QACA,OACA,SACA,OACA,SACA,OACA,UACA,UACA,QACA,UACA,OACA,MACA,QACA,OACA,QACA,UACA,QACA,SACA,SACA,UACA,WACA,WACA,QACA,QACA,SACA,SACA,QACA,MACA,SACA,SACA,OACA,SACA,SACA,UACA,WACA,OACA,OACA,UACA,SACA,OACA,UACA,SACA,QACA,WACA,SACA,UACA,UACA,SACA,QACA,QACA,SACA,QACA,UACA,QACA,OACA,QACA,UACA,SACA,QACA,QACA,OACA,SACA,QACA,OACA,QACA,OACA,QACA,WACA,QACA,SACA,QACA,UACA,MACA,UACA,OACA,OACA,QACA,QACA,OACA,SACA,OACA,QACA,SACA,UACA,SACA,QACA,OACA,QACA,SACA,UACA,MACA,OACA,QACA,SACA,MACA,QACA,OACA,QACA,QACA,OACA,OACA,QACA,UACA,QACA,QACA,SACA,OACA,SACA,OACA,OACA,QACA,QACA,QACA,QACA,QACA,SACA,QACA,QACA,OACA,QACA,OACA,OACA,SACA,SACA,OACA,OACA,OACA,QACA,UACA,QACA,WACA,QACA,UACA,OACA,OACA,QACA,OACA,OACA,QACA,OACA,SACA,QACA,QACA,QACA,UACA,QACA,QACA,UACA,QACA,QACA,QACA,SACA,QACA,SACA,QACA,OACA,SACA,QACA,QACA,UACA,QACA,QACA,OACA,QACA,SACA,SACA,MACA,SACA,UACA,WACA,SACA,UACA,QACA,QACA,SACA,QACA,QACA,QACA,QACA,OACA,QACA,QACA,OACA,OACA,SACA,QACA,QACA,QACA,QACA,UACA,QACA,QACA,QACA,QACA,WACA,SACA,SACA,SACA,WACA,UACA,QACA,UACA,QACA,UACA,SACA,SACA,UACA,OACA,SACA,SACA,QACA,UACA,OACA,SACA,MACA,QACA,SACA,QACA,SACA,UACA,OACA,UACA,QACA,WACA,WACA,SACA,UACA,UACA,UACA,QACA,OACA,QACA,QACA,QACA,QACA,OACA,QACA,SACA,QACA,SACA,UACA,QACA,SACA,QACA,SACA,MACA,OACA,SACA,OACA,OACA,OACA,SACA,OACA,QACA,SACA,OACA,QACA,OACA,OACA,MACA,SACA,SACA,OACA,OACA,OACA,OACA,QACA,OACA,QACA,OACA,SACA,QACA,OACA,QACA,OACA,UACA,QACA,SACA,QACA,QACA,UACA,SACA,OACA,QACA,OACA,SACA,OACA,OACA,MACA,QACA,SACA,QACA,QACA,UACA,QACA,UACA,MACA,WACA,SACA,QACA,SACA,WACA,OACA,SACA,UACA,OACA,QACA,MACA,QACA,SACA,QACA,UACA,WACA,OACA,QACA,UACA,SACA,QACA,OACA,MACA,QACA,QACA,UACA,SACA,QACA,WACA,OACA,QACA,SACA,OACA,QACA,OACA,QACA,QACA,QACA,QACA,UACA,OACA,OACA,SACA,UACA,QACA,OACA,QACA,UACA,QACA,QACA,MACA,OACA,UACA,SACA,OACA,SACA,SACA,OACA,SACA,SACA,SACA,QACA,OACA,QACA,MACA,OACA,UACA,OACA,WACA,SACA,UACA,QACA,UACA,QACA,OACA,SACA,SACA,UACA,UACA,SACA,OACA,WACA,UACA,SACA,QACA,UACA,SACA,SACA,UACA,SACA,OACA,QACA,QACA,QACA,OACA,QACA,MACA,OACA,SACA,UACA,QACA,UACA,SACA,SACA,QACA,QACA,SACA,QACA,MACA,SACA,QACA,UACA,OACA,QACA,UACA,SACA,SACA,UACA,QACA,OACA,SACA,UACA,OACA,SACA,UACA,SACA,UACA,UACA,UACA,QACA,OACA,UACA,UACA,SACA,UACA,QACA,OACA,QACA,SACA,QACA,QACA,QACA,QACA,OACA,UACA,SACA,OACA,SACA,OACA,QACA,OACA,OACA,OACA,SACA,OACA,UACA,OACA,UACA,OACA,OACA,QACA,QACA,OACA,MACA,SACA,SACA,OACA,SACA,UACA,MACA,UACA,UACA,QACA,UACA,OACA,MACA,QACA,OACA,QACA,QACA,OACA,QACA,OACA,UACA,OACA,QACA,OACA,OACA,OACA,MACA,SACA,OACA,OACA,OACA,SACA,SACA,OACA,SACA,OACA,OACA,UACA,OACA,QACA,SACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,OACA,QACA,UACA,QACA,QACA,QACA,OACA,OACA,SACA,MACA,QACA,QACA,QACA,OACA,OACA,MACH,CACD,MAAO,GACX,CCv/De,OAAM,GACjB,QAAS,AACT,KAAK,AACL,SAAS,AAOT,aAAY,CAAQ,CAAE,CAAI,CAAE,EAAW,EAAQ,CAAE,CAC7C,IAAI,CAAC,QAAQ,CAAG,GAAY,GAC5B,IAAI,CAAC,IAAI,CAAG,GAAQ,EAAE,CACtB,IAAI,CAAC,QAAQ,CAAG,CACpB,CAKA,UAAW,CACP,IAAM,EAAK,IAAI,GACf,GAAI,AAAkB,KAAlB,IAAI,CAAC,QAAQ,CAAS,CACtB,IAAM,EAAM,GAAQ,IAAI,CAAC,QAAQ,CAAE,QACnC,EAAG,cAAc,CAAC,EAAI,MAAM,EAC5B,EAAG,KAAK,CAAC,EACb,MAEI,EAAG,cAAc,CAAC,GAStB,OAPI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAG,GACnB,EAAG,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAClC,EAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAGlB,EAAG,cAAc,CAAC,GAEf,EAAG,OAAO,EACrB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