@btc-vision/bitcoin 6.3.1 → 6.3.3

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 (374) hide show
  1. package/.babelrc +4 -0
  2. package/.gitattributes +2 -0
  3. package/.nyc_output/6368a5b2-daa5-4821-8ed0-b742d6fc7eab.json +1 -0
  4. package/.nyc_output/processinfo/6368a5b2-daa5-4821-8ed0-b742d6fc7eab.json +1 -0
  5. package/.nyc_output/processinfo/index.json +1 -0
  6. package/.prettierrc.json +12 -0
  7. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/.ready +0 -0
  8. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/.release-please-manifest.json +3 -0
  9. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/CHANGELOG.md +962 -0
  10. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/CONTRIBUTING.md +34 -0
  11. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/LICENSE +24 -0
  12. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/README.md +273 -0
  13. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/SECURITY.md +2 -0
  14. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/addon.gypi +204 -0
  15. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/bin/node-gyp.js +138 -0
  16. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/.release-please-manifest.json +3 -0
  17. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/LICENSE +28 -0
  18. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/data/ninja/build.ninja +4 -0
  19. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/data/win/large-pdb-shim.cc +12 -0
  20. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/GypVsCMake.md +116 -0
  21. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/Hacking.md +46 -0
  22. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/InputFormatReference.md +1080 -0
  23. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/LanguageSpecification.md +430 -0
  24. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/README.md +27 -0
  25. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/Testing.md +450 -0
  26. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/docs/UserDocumentation.md +965 -0
  27. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/gyp +8 -0
  28. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/gyp.bat +5 -0
  29. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  30. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +365 -0
  31. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  32. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1272 -0
  33. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  34. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  35. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  36. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  37. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  38. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +692 -0
  39. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/common.py +711 -0
  40. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +171 -0
  41. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +169 -0
  42. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +113 -0
  43. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  44. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  45. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +804 -0
  46. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  47. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1318 -0
  48. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +127 -0
  49. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  50. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +461 -0
  51. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  52. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +57 -0
  53. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2745 -0
  54. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3976 -0
  55. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  56. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2964 -0
  57. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +67 -0
  58. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1391 -0
  59. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  60. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/input.py +3115 -0
  61. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  62. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  63. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1260 -0
  64. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  65. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  66. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +373 -0
  67. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1938 -0
  68. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py +53 -0
  69. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  70. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3198 -0
  71. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  72. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/LICENSE +3 -0
  73. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/LICENSE.APACHE +177 -0
  74. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/LICENSE.BSD +23 -0
  75. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/__init__.py +15 -0
  76. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py +108 -0
  77. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_manylinux.py +252 -0
  78. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_musllinux.py +83 -0
  79. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_parser.py +359 -0
  80. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_structures.py +61 -0
  81. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/_tokenizer.py +192 -0
  82. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/markers.py +252 -0
  83. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/metadata.py +825 -0
  84. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/py.typed +0 -0
  85. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/requirements.py +90 -0
  86. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/specifiers.py +1030 -0
  87. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/tags.py +553 -0
  88. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/utils.py +172 -0
  89. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pylib/packaging/version.py +563 -0
  90. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/pyproject.toml +120 -0
  91. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/release-please-config.json +11 -0
  92. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  93. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/Find-VisualStudio.cs +250 -0
  94. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/build.js +227 -0
  95. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/clean.js +15 -0
  96. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/configure.js +328 -0
  97. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/create-config-gypi.js +150 -0
  98. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/download.js +39 -0
  99. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/find-node-directory.js +63 -0
  100. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/find-python.js +310 -0
  101. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/find-visualstudio.js +590 -0
  102. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/install.js +415 -0
  103. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/list.js +26 -0
  104. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/log.js +168 -0
  105. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/node-gyp.js +188 -0
  106. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/process-release.js +146 -0
  107. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/rebuild.js +12 -0
  108. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/remove.js +43 -0
  109. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/lib/util.js +81 -0
  110. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/macOS_Catalina_acid_test.sh +21 -0
  111. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/package.json +51 -0
  112. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/release-please-config.json +40 -0
  113. package/.yarn/unplugged/node-gyp-npm-10.2.0-cad1109948/node_modules/node-gyp/src/win_delay_load_hook.cc +39 -0
  114. package/CHANGELOG.md +403 -0
  115. package/CONTRIBUTING.md +83 -0
  116. package/browser/address.d.ts +16 -0
  117. package/{src → browser}/bip66.d.ts +6 -7
  118. package/{src → browser}/block.d.ts +29 -30
  119. package/{src → browser}/bufferutils.d.ts +34 -54
  120. package/browser/crypto/crypto.d.ts +1 -0
  121. package/{src → browser}/crypto.d.ts +13 -18
  122. package/browser/ecc_lib.d.ts +3 -0
  123. package/browser/hooks/AdvancedSignatureManager.d.ts +16 -0
  124. package/{src → browser}/hooks/HookedSigner.d.ts +4 -4
  125. package/browser/hooks/SignatureManager.d.ts +13 -0
  126. package/browser/index.d.ts +58 -0
  127. package/browser/index.js +2 -0
  128. package/browser/index.js.LICENSE.txt +14 -0
  129. package/browser/merkle.d.ts +1 -0
  130. package/browser/networks.d.ts +23 -0
  131. package/{src → browser}/ops.d.ts +126 -126
  132. package/browser/payments/bip341.d.ts +23 -0
  133. package/browser/payments/embed.d.ts +2 -0
  134. package/browser/payments/index.d.ts +43 -0
  135. package/{src → browser}/payments/lazy.d.ts +2 -2
  136. package/browser/payments/p2ms.d.ts +2 -0
  137. package/browser/payments/p2pk.d.ts +2 -0
  138. package/browser/payments/p2pkh.d.ts +2 -0
  139. package/browser/payments/p2sh.d.ts +2 -0
  140. package/browser/payments/p2tr.d.ts +2 -0
  141. package/browser/payments/p2wpkh.d.ts +2 -0
  142. package/browser/payments/p2wsh.d.ts +2 -0
  143. package/browser/psbt/bip371.d.ts +16 -0
  144. package/browser/psbt/psbtutils.d.ts +26 -0
  145. package/{src → browser}/psbt.d.ts +167 -238
  146. package/browser/push_data.d.ts +7 -0
  147. package/browser/script.d.ts +17 -0
  148. package/browser/script_number.d.ts +2 -0
  149. package/browser/script_signature.d.ts +7 -0
  150. package/{src → browser}/transaction.d.ts +48 -60
  151. package/{src → browser}/types.d.ts +37 -54
  152. package/build/address.d.ts +16 -0
  153. package/build/address.js +148 -0
  154. package/build/bip66.d.ts +6 -0
  155. package/build/bip66.js +99 -0
  156. package/build/block.d.ts +29 -0
  157. package/build/block.js +181 -0
  158. package/build/bufferutils.d.ts +34 -0
  159. package/build/bufferutils.js +141 -0
  160. package/build/crypto/crypto.d.ts +1 -0
  161. package/build/crypto/crypto.js +1 -0
  162. package/build/crypto.d.ts +13 -0
  163. package/build/crypto.js +87 -0
  164. package/build/ecc_lib.d.ts +3 -0
  165. package/build/ecc_lib.js +61 -0
  166. package/build/hooks/AdvancedSignatureManager.d.ts +16 -0
  167. package/build/hooks/AdvancedSignatureManager.js +52 -0
  168. package/build/hooks/HookedSigner.d.ts +4 -0
  169. package/build/hooks/HookedSigner.js +64 -0
  170. package/build/hooks/SignatureManager.d.ts +13 -0
  171. package/build/hooks/SignatureManager.js +45 -0
  172. package/build/index.d.ts +58 -0
  173. package/build/index.js +32 -0
  174. package/build/merkle.d.ts +1 -0
  175. package/build/merkle.js +19 -0
  176. package/build/networks.d.ts +23 -0
  177. package/build/networks.js +121 -0
  178. package/build/ops.d.ts +126 -0
  179. package/{src → build}/ops.js +127 -131
  180. package/build/payments/bip341.d.ts +23 -0
  181. package/build/payments/bip341.js +82 -0
  182. package/build/payments/embed.d.ts +2 -0
  183. package/build/payments/embed.js +39 -0
  184. package/build/payments/index.d.ts +43 -0
  185. package/build/payments/index.js +10 -0
  186. package/build/payments/lazy.d.ts +2 -0
  187. package/{src → build}/payments/lazy.js +28 -32
  188. package/build/payments/p2ms.d.ts +2 -0
  189. package/{src → build}/payments/p2ms.js +128 -158
  190. package/build/payments/p2pk.d.ts +2 -0
  191. package/build/payments/p2pk.js +68 -0
  192. package/build/payments/p2pkh.d.ts +2 -0
  193. package/build/payments/p2pkh.js +173 -0
  194. package/build/payments/p2sh.d.ts +2 -0
  195. package/build/payments/p2sh.js +176 -0
  196. package/build/payments/p2tr.d.ts +2 -0
  197. package/build/payments/p2tr.js +254 -0
  198. package/build/payments/p2wpkh.d.ts +2 -0
  199. package/build/payments/p2wpkh.js +130 -0
  200. package/build/payments/p2wsh.d.ts +2 -0
  201. package/build/payments/p2wsh.js +180 -0
  202. package/build/psbt/bip371.d.ts +16 -0
  203. package/build/psbt/bip371.js +246 -0
  204. package/build/psbt/psbtutils.d.ts +26 -0
  205. package/build/psbt/psbtutils.js +177 -0
  206. package/build/psbt.d.ts +167 -0
  207. package/build/psbt.js +1307 -0
  208. package/build/push_data.d.ts +7 -0
  209. package/build/push_data.js +57 -0
  210. package/build/script.d.ts +17 -0
  211. package/build/script.js +167 -0
  212. package/build/script_number.d.ts +2 -0
  213. package/build/script_number.js +49 -0
  214. package/build/script_signature.d.ts +7 -0
  215. package/build/script_signature.js +49 -0
  216. package/build/transaction.d.ts +48 -0
  217. package/build/transaction.js +445 -0
  218. package/build/types.d.ts +37 -0
  219. package/build/types.js +73 -0
  220. package/cjs/package.json +3 -0
  221. package/coverage/tmp/coverage-31752-1735543485354-0.json +1 -0
  222. package/coverage/tmp/coverage-59920-1735543484555-0.json +1 -0
  223. package/coverage/tmp/coverage-66252-1735543483919-0.json +1 -0
  224. package/coverage/tmp/coverage-68440-1735543485236-0.json +1 -0
  225. package/coverage/tmp/coverage-70588-1735543484426-0.json +1 -0
  226. package/coverage/tmp/coverage-79292-1735543485296-0.json +1 -0
  227. package/coverage/tmp/coverage-80212-1735543483980-0.json +1 -0
  228. package/eslint.config.js +56 -0
  229. package/gulpfile.js +42 -0
  230. package/package.json +105 -50
  231. package/src/{address.js → address.ts} +211 -191
  232. package/src/{bip66.js → bip66.ts} +23 -19
  233. package/src/{block.js → block.ts} +114 -105
  234. package/src/{bufferutils.js → bufferutils.ts} +65 -67
  235. package/src/crypto/crypto-browser.js +75 -0
  236. package/src/crypto/crypto.ts +1 -0
  237. package/src/crypto.ts +108 -0
  238. package/src/{ecc_lib.js → ecc_lib.ts} +25 -53
  239. package/src/hooks/{AdvancedSignatureManager.js → AdvancedSignatureManager.ts} +34 -18
  240. package/src/hooks/HookedSigner.ts +108 -0
  241. package/src/hooks/{SignatureManager.js → SignatureManager.ts} +26 -14
  242. package/src/index.ts +86 -0
  243. package/src/{merkle.js → merkle.ts} +8 -7
  244. package/src/{networks.js → networks.ts} +235 -220
  245. package/src/ops.ts +282 -0
  246. package/src/payments/bip341.ts +140 -0
  247. package/src/payments/embed.ts +55 -0
  248. package/src/payments/{index.d.ts → index.ts} +24 -10
  249. package/src/payments/lazy.ts +28 -0
  250. package/src/payments/p2ms.ts +150 -0
  251. package/src/payments/{p2pk.js → p2pk.ts} +85 -82
  252. package/src/payments/p2pkh.ts +206 -0
  253. package/src/payments/{p2sh.js → p2sh.ts} +206 -204
  254. package/src/payments/{p2tr.js → p2tr.ts} +114 -125
  255. package/src/payments/{p2wpkh.js → p2wpkh.ts} +51 -56
  256. package/src/payments/{p2wsh.js → p2wsh.ts} +69 -81
  257. package/src/psbt/{bip371.js → bip371.ts} +441 -424
  258. package/src/psbt/psbtutils.ts +301 -0
  259. package/src/{psbt.js → psbt.ts} +2187 -1828
  260. package/src/{push_data.js → push_data.ts} +35 -21
  261. package/src/{script.js → script.ts} +93 -77
  262. package/src/{script_number.js → script_number.ts} +15 -21
  263. package/src/{script_signature.js → script_signature.ts} +26 -14
  264. package/src/{transaction.js → transaction.ts} +247 -167
  265. package/src/types.ts +122 -0
  266. package/test/address.spec.js +124 -0
  267. package/test/address.spec.ts +177 -0
  268. package/test/bitcoin.core.spec.js +170 -0
  269. package/test/bitcoin.core.spec.ts +234 -0
  270. package/test/block.spec.js +141 -0
  271. package/test/block.spec.ts +194 -0
  272. package/test/bufferutils.spec.js +427 -0
  273. package/test/bufferutils.spec.ts +513 -0
  274. package/test/crypto.spec.js +41 -0
  275. package/test/crypto.spec.ts +55 -0
  276. package/test/fixtures/address.json +329 -0
  277. package/test/fixtures/block.json +148 -0
  278. package/test/fixtures/bufferutils.json +102 -0
  279. package/test/fixtures/core/README.md +26 -0
  280. package/test/fixtures/core/base58_encode_decode.json +50 -0
  281. package/test/fixtures/core/base58_keys_invalid.json +152 -0
  282. package/test/fixtures/core/base58_keys_valid.json +452 -0
  283. package/test/fixtures/core/blocks.json +27 -0
  284. package/test/fixtures/core/sig_canonical.json +7 -0
  285. package/test/fixtures/core/sig_noncanonical.json +33 -0
  286. package/test/fixtures/core/sighash.json +3505 -0
  287. package/test/fixtures/core/tx_valid.json +2023 -0
  288. package/test/fixtures/crypto.json +43 -0
  289. package/test/fixtures/ecdsa.json +217 -0
  290. package/test/fixtures/ecpair.json +141 -0
  291. package/test/fixtures/embed.json +108 -0
  292. package/test/fixtures/p2ms.json +434 -0
  293. package/test/fixtures/p2pk.json +179 -0
  294. package/test/fixtures/p2pkh.json +276 -0
  295. package/test/fixtures/p2sh.json +508 -0
  296. package/test/fixtures/p2tr.json +1198 -0
  297. package/test/fixtures/p2wpkh.json +290 -0
  298. package/test/fixtures/p2wsh.json +489 -0
  299. package/test/fixtures/psbt.json +924 -0
  300. package/test/fixtures/script.json +465 -0
  301. package/test/fixtures/script_number.json +225 -0
  302. package/test/fixtures/signature.json +140 -0
  303. package/test/fixtures/transaction.json +916 -0
  304. package/test/integration/_regtest.js +7 -0
  305. package/test/integration/_regtest.ts +6 -0
  306. package/test/integration/addresses.spec.js +116 -0
  307. package/test/integration/addresses.spec.ts +154 -0
  308. package/test/integration/bip32.spec.js +85 -0
  309. package/test/integration/bip32.spec.ts +151 -0
  310. package/test/integration/blocks.spec.js +26 -0
  311. package/test/integration/blocks.spec.ts +28 -0
  312. package/test/integration/cltv.spec.js +199 -0
  313. package/test/integration/cltv.spec.ts +283 -0
  314. package/test/integration/csv.spec.js +362 -0
  315. package/test/integration/csv.spec.ts +527 -0
  316. package/test/integration/payments.spec.js +98 -0
  317. package/test/integration/payments.spec.ts +135 -0
  318. package/test/integration/taproot.spec.js +532 -0
  319. package/test/integration/taproot.spec.ts +707 -0
  320. package/test/integration/transactions.spec.js +561 -0
  321. package/test/integration/transactions.spec.ts +769 -0
  322. package/test/payments.spec.js +97 -0
  323. package/test/payments.spec.ts +125 -0
  324. package/test/payments.utils.js +190 -0
  325. package/test/payments.utils.ts +208 -0
  326. package/test/psbt.spec.js +1044 -0
  327. package/test/psbt.spec.ts +1414 -0
  328. package/test/script.spec.js +151 -0
  329. package/test/script.spec.ts +210 -0
  330. package/test/script_number.spec.js +24 -0
  331. package/test/script_number.spec.ts +29 -0
  332. package/test/script_signature.spec.js +52 -0
  333. package/test/script_signature.spec.ts +66 -0
  334. package/test/transaction.spec.js +269 -0
  335. package/test/transaction.spec.ts +387 -0
  336. package/test/ts-node-register.js +5 -0
  337. package/test/tsconfig.json +45 -0
  338. package/test/types.spec.js +46 -0
  339. package/test/types.spec.ts +58 -0
  340. package/tsconfig.base.json +27 -0
  341. package/tsconfig.json +19 -0
  342. package/tsconfig.webpack.json +18 -0
  343. package/webpack.config.js +79 -0
  344. package/src/address.d.ts +0 -42
  345. package/src/crypto.js +0 -128
  346. package/src/ecc_lib.d.ts +0 -17
  347. package/src/hooks/AdvancedSignatureManager.d.ts +0 -44
  348. package/src/hooks/HookedSigner.js +0 -90
  349. package/src/hooks/SignatureManager.d.ts +0 -35
  350. package/src/index.d.ts +0 -42
  351. package/src/index.js +0 -87
  352. package/src/merkle.d.ts +0 -10
  353. package/src/networks.d.ts +0 -83
  354. package/src/payments/bip341.d.ts +0 -49
  355. package/src/payments/bip341.js +0 -124
  356. package/src/payments/embed.d.ts +0 -9
  357. package/src/payments/embed.js +0 -54
  358. package/src/payments/index.js +0 -69
  359. package/src/payments/p2ms.d.ts +0 -9
  360. package/src/payments/p2pk.d.ts +0 -10
  361. package/src/payments/p2pkh.d.ts +0 -10
  362. package/src/payments/p2pkh.js +0 -143
  363. package/src/payments/p2sh.d.ts +0 -10
  364. package/src/payments/p2tr.d.ts +0 -10
  365. package/src/payments/p2wpkh.d.ts +0 -10
  366. package/src/payments/p2wsh.d.ts +0 -10
  367. package/src/psbt/bip371.d.ts +0 -42
  368. package/src/psbt/psbtutils.d.ts +0 -64
  369. package/src/psbt/psbtutils.js +0 -191
  370. package/src/push_data.d.ts +0 -29
  371. package/src/script.d.ts +0 -42
  372. package/src/script_number.d.ts +0 -19
  373. package/src/script_signature.d.ts +0 -21
  374. package/src/types.js +0 -106
package/build/psbt.js ADDED
@@ -0,0 +1,1307 @@
1
+ import { Psbt as PsbtBase } from 'bip174';
2
+ import * as varuint from 'bip174/src/lib/converter/varint.js';
3
+ import { checkForInput, checkForOutput } from 'bip174/src/lib/utils.js';
4
+ import { fromOutputScript, toOutputScript } from './address.js';
5
+ import { cloneBuffer, reverseBuffer } from './bufferutils.js';
6
+ import { hookSigner } from './hooks/HookedSigner.js';
7
+ import { payments } from './index.js';
8
+ import { bitcoin as btcNetwork } from './networks.js';
9
+ import { tapleafHash } from './payments/bip341.js';
10
+ import { checkTaprootInputFields, checkTaprootInputForSigs, checkTaprootOutputFields, isTaprootInput, serializeTaprootSignature, tapScriptFinalizer, toXOnly, } from './psbt/bip371.js';
11
+ import { checkInputForSig, isP2MS, isP2PK, isP2PKH, isP2SHScript, isP2TR, isP2WPKH, isP2WSHScript, pubkeyInScript, witnessStackToScriptWitness, } from './psbt/psbtutils.js';
12
+ import * as bscript from './script.js';
13
+ import { Transaction } from './transaction.js';
14
+ const DEFAULT_OPTS = {
15
+ network: btcNetwork,
16
+ maximumFeeRate: 5000,
17
+ };
18
+ export class Psbt {
19
+ constructor(opts = {}, data = new PsbtBase(new PsbtTransaction())) {
20
+ this.data = data;
21
+ this.opts = Object.assign({}, DEFAULT_OPTS, opts);
22
+ this.__CACHE = {
23
+ __NON_WITNESS_UTXO_TX_CACHE: [],
24
+ __NON_WITNESS_UTXO_BUF_CACHE: [],
25
+ __TX_IN_CACHE: {},
26
+ __TX: this.data.globalMap.unsignedTx.tx,
27
+ __UNSAFE_SIGN_NONSEGWIT: false,
28
+ };
29
+ if (this.data.inputs.length === 0)
30
+ this.setVersion(2);
31
+ const dpew = (obj, attr, enumerable, writable) => {
32
+ Object.defineProperty(obj, attr, {
33
+ enumerable,
34
+ writable,
35
+ });
36
+ };
37
+ dpew(this, '__CACHE', false, true);
38
+ dpew(this, 'opts', false, true);
39
+ }
40
+ get inputCount() {
41
+ return this.data.inputs.length;
42
+ }
43
+ get version() {
44
+ return this.__CACHE.__TX.version;
45
+ }
46
+ set version(version) {
47
+ this.setVersion(version);
48
+ }
49
+ get locktime() {
50
+ return this.__CACHE.__TX.locktime;
51
+ }
52
+ set locktime(locktime) {
53
+ this.setLocktime(locktime);
54
+ }
55
+ get txInputs() {
56
+ return this.__CACHE.__TX.ins.map((input) => ({
57
+ hash: cloneBuffer(input.hash),
58
+ index: input.index,
59
+ sequence: input.sequence,
60
+ }));
61
+ }
62
+ get txOutputs() {
63
+ return this.__CACHE.__TX.outs.map((output) => {
64
+ let address;
65
+ try {
66
+ address = fromOutputScript(output.script, this.opts.network);
67
+ }
68
+ catch (_) { }
69
+ return {
70
+ script: cloneBuffer(output.script),
71
+ value: output.value,
72
+ address,
73
+ };
74
+ });
75
+ }
76
+ static fromBase64(data, opts = {}) {
77
+ const buffer = Buffer.from(data, 'base64');
78
+ return this.fromBuffer(buffer, opts);
79
+ }
80
+ static fromHex(data, opts = {}) {
81
+ const buffer = Buffer.from(data, 'hex');
82
+ return this.fromBuffer(buffer, opts);
83
+ }
84
+ static fromBuffer(buffer, opts = {}) {
85
+ const psbtBase = PsbtBase.fromBuffer(buffer, transactionFromBuffer);
86
+ const psbt = new Psbt(opts, psbtBase);
87
+ checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE);
88
+ return psbt;
89
+ }
90
+ combine(...those) {
91
+ this.data.combine(...those.map((o) => o.data));
92
+ return this;
93
+ }
94
+ clone() {
95
+ const res = Psbt.fromBuffer(this.data.toBuffer(), JSON.parse(JSON.stringify(this.opts)));
96
+ return res;
97
+ }
98
+ setMaximumFeeRate(satoshiPerByte) {
99
+ check32Bit(satoshiPerByte);
100
+ this.opts.maximumFeeRate = satoshiPerByte;
101
+ }
102
+ setVersion(version) {
103
+ check32Bit(version);
104
+ checkInputsForPartialSig(this.data.inputs, 'setVersion');
105
+ const c = this.__CACHE;
106
+ c.__TX.version = version;
107
+ c.__EXTRACTED_TX = undefined;
108
+ return this;
109
+ }
110
+ setLocktime(locktime) {
111
+ check32Bit(locktime);
112
+ checkInputsForPartialSig(this.data.inputs, 'setLocktime');
113
+ const c = this.__CACHE;
114
+ c.__TX.locktime = locktime;
115
+ c.__EXTRACTED_TX = undefined;
116
+ return this;
117
+ }
118
+ setInputSequence(inputIndex, sequence) {
119
+ check32Bit(sequence);
120
+ checkInputsForPartialSig(this.data.inputs, 'setInputSequence');
121
+ const c = this.__CACHE;
122
+ if (c.__TX.ins.length <= inputIndex) {
123
+ throw new Error('Input index too high');
124
+ }
125
+ c.__TX.ins[inputIndex].sequence = sequence;
126
+ c.__EXTRACTED_TX = undefined;
127
+ return this;
128
+ }
129
+ addInputs(inputDatas, checkPartialSigs = true) {
130
+ inputDatas.forEach((inputData) => this.addInput(inputData, checkPartialSigs));
131
+ return this;
132
+ }
133
+ addInput(inputData, checkPartialSigs = true) {
134
+ if (!inputData || inputData.hash === undefined || inputData.index === undefined) {
135
+ throw new Error(`Invalid arguments for Psbt.addInput. ` +
136
+ `Requires single object with at least [hash] and [index]`);
137
+ }
138
+ checkTaprootInputFields(inputData, inputData, 'addInput');
139
+ if (checkPartialSigs) {
140
+ checkInputsForPartialSig(this.data.inputs, 'addInput');
141
+ }
142
+ if (inputData.witnessScript)
143
+ checkInvalidP2WSH(inputData.witnessScript);
144
+ const c = this.__CACHE;
145
+ this.data.addInput(inputData);
146
+ const txIn = c.__TX.ins[c.__TX.ins.length - 1];
147
+ checkTxInputCache(c, txIn);
148
+ const inputIndex = this.data.inputs.length - 1;
149
+ const input = this.data.inputs[inputIndex];
150
+ if (input.nonWitnessUtxo) {
151
+ addNonWitnessTxCache(this.__CACHE, input, inputIndex);
152
+ }
153
+ c.__FEE = undefined;
154
+ c.__FEE_RATE = undefined;
155
+ c.__EXTRACTED_TX = undefined;
156
+ return this;
157
+ }
158
+ addOutputs(outputDatas) {
159
+ outputDatas.forEach((outputData) => this.addOutput(outputData));
160
+ return this;
161
+ }
162
+ addOutput(outputData) {
163
+ if (arguments.length > 1 ||
164
+ !outputData ||
165
+ outputData.value === undefined ||
166
+ (outputData.address === undefined && outputData.script === undefined)) {
167
+ throw new Error(`Invalid arguments for Psbt.addOutput. ` +
168
+ `Requires single object with at least [script or address] and [value]`);
169
+ }
170
+ checkInputsForPartialSig(this.data.inputs, 'addOutput');
171
+ const { address } = outputData;
172
+ if (typeof address === 'string') {
173
+ const { network } = this.opts;
174
+ const script = toOutputScript(address, network);
175
+ outputData = Object.assign({}, outputData, { script });
176
+ }
177
+ checkTaprootOutputFields(outputData, outputData, 'addOutput');
178
+ const c = this.__CACHE;
179
+ this.data.addOutput(outputData);
180
+ c.__FEE = undefined;
181
+ c.__FEE_RATE = undefined;
182
+ c.__EXTRACTED_TX = undefined;
183
+ return this;
184
+ }
185
+ extractTransaction(disableFeeCheck, disableOutputChecks) {
186
+ if (disableOutputChecks) {
187
+ this.data.inputs = this.data.inputs.filter((i) => !i.partialSig);
188
+ }
189
+ if (!this.data.inputs.every(isFinalized))
190
+ throw new Error('Not finalized');
191
+ const c = this.__CACHE;
192
+ if (!disableFeeCheck) {
193
+ checkFees(this, c, this.opts);
194
+ }
195
+ if (c.__EXTRACTED_TX)
196
+ return c.__EXTRACTED_TX;
197
+ const tx = c.__TX.clone();
198
+ inputFinalizeGetAmts(this.data.inputs, tx, c, true, disableOutputChecks);
199
+ return tx;
200
+ }
201
+ getFeeRate(disableOutputChecks = false) {
202
+ return getTxCacheValue('__FEE_RATE', 'fee rate', this.data.inputs, this.__CACHE, disableOutputChecks);
203
+ }
204
+ getFee(disableOutputChecks = false) {
205
+ return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE, disableOutputChecks);
206
+ }
207
+ finalizeAllInputs() {
208
+ checkForInput(this.data.inputs, 0);
209
+ range(this.data.inputs.length).forEach((idx) => this.finalizeInput(idx));
210
+ return this;
211
+ }
212
+ finalizeInput(inputIndex, finalScriptsFunc, canRunChecks) {
213
+ const input = checkForInput(this.data.inputs, inputIndex);
214
+ if (isTaprootInput(input)) {
215
+ return this._finalizeTaprootInput(inputIndex, input, undefined, finalScriptsFunc);
216
+ }
217
+ return this._finalizeInput(inputIndex, input, finalScriptsFunc, canRunChecks ?? true);
218
+ }
219
+ finalizeTaprootInput(inputIndex, tapLeafHashToFinalize, finalScriptsFunc = tapScriptFinalizer) {
220
+ const input = checkForInput(this.data.inputs, inputIndex);
221
+ if (isTaprootInput(input))
222
+ return this._finalizeTaprootInput(inputIndex, input, tapLeafHashToFinalize, finalScriptsFunc);
223
+ throw new Error(`Cannot finalize input #${inputIndex}. Not Taproot.`);
224
+ }
225
+ getInputType(inputIndex) {
226
+ const input = checkForInput(this.data.inputs, inputIndex);
227
+ const script = getScriptFromUtxo(inputIndex, input, this.__CACHE);
228
+ const result = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), input.witnessScript || redeemFromFinalWitnessScript(input.finalScriptWitness));
229
+ const type = result.type === 'raw' ? '' : result.type + '-';
230
+ const mainType = classifyScript(result.meaningfulScript);
231
+ return (type + mainType);
232
+ }
233
+ inputHasPubkey(inputIndex, pubkey) {
234
+ const input = checkForInput(this.data.inputs, inputIndex);
235
+ return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE);
236
+ }
237
+ inputHasHDKey(inputIndex, root) {
238
+ const input = checkForInput(this.data.inputs, inputIndex);
239
+ const derivationIsMine = bip32DerivationIsMine(root);
240
+ return !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine);
241
+ }
242
+ outputHasPubkey(outputIndex, pubkey) {
243
+ const output = checkForOutput(this.data.outputs, outputIndex);
244
+ return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE);
245
+ }
246
+ outputHasHDKey(outputIndex, root) {
247
+ const output = checkForOutput(this.data.outputs, outputIndex);
248
+ const derivationIsMine = bip32DerivationIsMine(root);
249
+ return !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine);
250
+ }
251
+ validateSignaturesOfAllInputs(validator) {
252
+ checkForInput(this.data.inputs, 0);
253
+ const results = range(this.data.inputs.length).map((idx) => this.validateSignaturesOfInput(idx, validator));
254
+ return results.reduce((final, res) => res === true && final, true);
255
+ }
256
+ validateSignaturesOfInput(inputIndex, validator, pubkey) {
257
+ const input = this.data.inputs[inputIndex];
258
+ if (isTaprootInput(input))
259
+ return this.validateSignaturesOfTaprootInput(inputIndex, validator, pubkey);
260
+ return this._validateSignaturesOfInput(inputIndex, validator, pubkey);
261
+ }
262
+ signAllInputsHD(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
263
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
264
+ throw new Error('Need HDSigner to sign input');
265
+ }
266
+ const results = [];
267
+ for (const i of range(this.data.inputs.length)) {
268
+ try {
269
+ this.signInputHD(i, hdKeyPair, sighashTypes);
270
+ results.push(true);
271
+ }
272
+ catch (err) {
273
+ results.push(false);
274
+ }
275
+ }
276
+ if (results.every((v) => v === false)) {
277
+ throw new Error('No inputs were signed');
278
+ }
279
+ return this;
280
+ }
281
+ signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
282
+ return new Promise((resolve, reject) => {
283
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
284
+ return reject(new Error('Need HDSigner to sign input'));
285
+ }
286
+ const results = [];
287
+ const promises = [];
288
+ for (const i of range(this.data.inputs.length)) {
289
+ promises.push(this.signInputHDAsync(i, hdKeyPair, sighashTypes).then(() => {
290
+ results.push(true);
291
+ }, () => {
292
+ results.push(false);
293
+ }));
294
+ }
295
+ return Promise.all(promises).then(() => {
296
+ if (results.every((v) => v === false)) {
297
+ return reject(new Error('No inputs were signed'));
298
+ }
299
+ resolve();
300
+ });
301
+ });
302
+ }
303
+ signInputHD(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
304
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
305
+ throw new Error('Need HDSigner to sign input');
306
+ }
307
+ const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
308
+ signers.forEach((signer) => this.signInput(inputIndex, signer, sighashTypes));
309
+ return this;
310
+ }
311
+ signInputHDAsync(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
312
+ return new Promise((resolve, reject) => {
313
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
314
+ return reject(new Error('Need HDSigner to sign input'));
315
+ }
316
+ const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
317
+ const promises = signers.map((signer) => this.signInputAsync(inputIndex, signer, sighashTypes));
318
+ return Promise.all(promises)
319
+ .then(() => {
320
+ resolve();
321
+ })
322
+ .catch(reject);
323
+ });
324
+ }
325
+ signAllInputs(keyPair, sighashTypes) {
326
+ if (!keyPair || !keyPair.publicKey)
327
+ throw new Error('Need Signer to sign input');
328
+ const results = [];
329
+ for (const i of range(this.data.inputs.length)) {
330
+ try {
331
+ this.signInput(i, keyPair, sighashTypes);
332
+ results.push(true);
333
+ }
334
+ catch (err) {
335
+ results.push(false);
336
+ }
337
+ }
338
+ if (results.every((v) => v === false)) {
339
+ throw new Error('No inputs were signed');
340
+ }
341
+ return this;
342
+ }
343
+ signAllInputsAsync(keyPair, sighashTypes) {
344
+ return new Promise((resolve, reject) => {
345
+ if (!keyPair || !keyPair.publicKey)
346
+ return reject(new Error('Need Signer to sign input'));
347
+ const results = [];
348
+ const promises = [];
349
+ for (const [i] of this.data.inputs.entries()) {
350
+ promises.push(this.signInputAsync(i, keyPair, sighashTypes).then(() => {
351
+ results.push(true);
352
+ }, () => {
353
+ results.push(false);
354
+ }));
355
+ }
356
+ return Promise.all(promises).then(() => {
357
+ if (results.every((v) => v === false)) {
358
+ return reject(new Error('No inputs were signed'));
359
+ }
360
+ resolve();
361
+ });
362
+ });
363
+ }
364
+ signInput(inputIndex, keyPair, sighashTypes) {
365
+ if (!keyPair || !keyPair.publicKey) {
366
+ throw new Error('Need Signer to sign input');
367
+ }
368
+ const input = checkForInput(this.data.inputs, inputIndex);
369
+ if (isTaprootInput(input)) {
370
+ return this._signTaprootInput(inputIndex, input, keyPair, undefined, sighashTypes);
371
+ }
372
+ return this._signInput(inputIndex, keyPair, sighashTypes);
373
+ }
374
+ signTaprootInput(inputIndex, keyPair, tapLeafHashToSign, sighashTypes) {
375
+ if (!keyPair || !keyPair.publicKey) {
376
+ throw new Error('Need Signer to sign input');
377
+ }
378
+ const input = checkForInput(this.data.inputs, inputIndex);
379
+ if (isTaprootInput(input)) {
380
+ return this._signTaprootInput(inputIndex, input, keyPair, tapLeafHashToSign, sighashTypes);
381
+ }
382
+ throw new Error(`Input #${inputIndex} is not of type Taproot.`);
383
+ }
384
+ signInputAsync(inputIndex, keyPair, sighashTypes) {
385
+ return Promise.resolve().then(() => {
386
+ if (!keyPair || !keyPair.publicKey)
387
+ throw new Error('Need Signer to sign input');
388
+ const input = checkForInput(this.data.inputs, inputIndex);
389
+ if (isTaprootInput(input))
390
+ return this._signTaprootInputAsync(inputIndex, input, keyPair, undefined, sighashTypes);
391
+ return this._signInputAsync(inputIndex, keyPair, sighashTypes);
392
+ });
393
+ }
394
+ signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) {
395
+ return Promise.resolve().then(() => {
396
+ if (!keyPair || !keyPair.publicKey)
397
+ throw new Error('Need Signer to sign input');
398
+ const input = checkForInput(this.data.inputs, inputIndex);
399
+ if (isTaprootInput(input))
400
+ return this._signTaprootInputAsync(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
401
+ throw new Error(`Input #${inputIndex} is not of type Taproot.`);
402
+ });
403
+ }
404
+ toBuffer() {
405
+ checkCache(this.__CACHE);
406
+ return this.data.toBuffer();
407
+ }
408
+ toHex() {
409
+ checkCache(this.__CACHE);
410
+ return this.data.toHex();
411
+ }
412
+ toBase64() {
413
+ checkCache(this.__CACHE);
414
+ return this.data.toBase64();
415
+ }
416
+ updateGlobal(updateData) {
417
+ this.data.updateGlobal(updateData);
418
+ return this;
419
+ }
420
+ updateInput(inputIndex, updateData) {
421
+ if (updateData.witnessScript)
422
+ checkInvalidP2WSH(updateData.witnessScript);
423
+ checkTaprootInputFields(this.data.inputs[inputIndex], updateData, 'updateInput');
424
+ this.data.updateInput(inputIndex, updateData);
425
+ if (updateData.nonWitnessUtxo) {
426
+ addNonWitnessTxCache(this.__CACHE, this.data.inputs[inputIndex], inputIndex);
427
+ }
428
+ return this;
429
+ }
430
+ updateOutput(outputIndex, updateData) {
431
+ const outputData = this.data.outputs[outputIndex];
432
+ checkTaprootOutputFields(outputData, updateData, 'updateOutput');
433
+ this.data.updateOutput(outputIndex, updateData);
434
+ return this;
435
+ }
436
+ addUnknownKeyValToGlobal(keyVal) {
437
+ this.data.addUnknownKeyValToGlobal(keyVal);
438
+ return this;
439
+ }
440
+ addUnknownKeyValToInput(inputIndex, keyVal) {
441
+ this.data.addUnknownKeyValToInput(inputIndex, keyVal);
442
+ return this;
443
+ }
444
+ addUnknownKeyValToOutput(outputIndex, keyVal) {
445
+ this.data.addUnknownKeyValToOutput(outputIndex, keyVal);
446
+ return this;
447
+ }
448
+ clearFinalizedInput(inputIndex) {
449
+ this.data.clearFinalizedInput(inputIndex);
450
+ return this;
451
+ }
452
+ checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHashToSign, allowedSighashTypes) {
453
+ if (typeof keyPair.signSchnorr !== 'function')
454
+ throw new Error(`Need Schnorr Signer to sign taproot input #${inputIndex}.`);
455
+ const hashesForSig = getTaprootHashesForSig(inputIndex, input, this.data.inputs, keyPair.publicKey, this.__CACHE, tapLeafHashToSign, allowedSighashTypes);
456
+ if (!hashesForSig || !hashesForSig.length)
457
+ throw new Error(`Can not sign for input #${inputIndex} with the key ${keyPair.publicKey.toString('hex')}`);
458
+ return hashesForSig;
459
+ }
460
+ _finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts, canRunChecks = true) {
461
+ const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput(inputIndex, input, this.__CACHE);
462
+ if (!script)
463
+ throw new Error(`No script found for input #${inputIndex}`);
464
+ checkPartialSigSighashes(input);
465
+ const { finalScriptSig, finalScriptWitness } = finalScriptsFunc(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks);
466
+ if (finalScriptSig)
467
+ this.data.updateInput(inputIndex, { finalScriptSig });
468
+ if (finalScriptWitness)
469
+ this.data.updateInput(inputIndex, { finalScriptWitness });
470
+ if (!finalScriptSig && !finalScriptWitness)
471
+ throw new Error(`Unknown error finalizing input #${inputIndex}`);
472
+ this.data.clearFinalizedInput(inputIndex);
473
+ return this;
474
+ }
475
+ _finalizeTaprootInput(inputIndex, input, tapLeafHashToFinalize, finalScriptsFunc = tapScriptFinalizer) {
476
+ if (!input.witnessUtxo)
477
+ throw new Error(`Cannot finalize input #${inputIndex}. Missing witness utxo.`);
478
+ if (input.tapKeySig) {
479
+ const payment = payments.p2tr({
480
+ output: input.witnessUtxo.script,
481
+ signature: input.tapKeySig,
482
+ });
483
+ const finalScriptWitness = witnessStackToScriptWitness(payment.witness);
484
+ this.data.updateInput(inputIndex, { finalScriptWitness });
485
+ }
486
+ else {
487
+ const { finalScriptWitness } = finalScriptsFunc(inputIndex, input, tapLeafHashToFinalize);
488
+ this.data.updateInput(inputIndex, { finalScriptWitness });
489
+ }
490
+ this.data.clearFinalizedInput(inputIndex);
491
+ return this;
492
+ }
493
+ _validateSignaturesOfInput(inputIndex, validator, pubkey) {
494
+ const input = this.data.inputs[inputIndex];
495
+ const partialSig = (input || {}).partialSig;
496
+ if (!input || !partialSig || partialSig.length < 1)
497
+ throw new Error('No signatures to validate');
498
+ if (typeof validator !== 'function')
499
+ throw new Error('Need validator function to validate signatures');
500
+ const mySigs = pubkey ? partialSig.filter((sig) => sig.pubkey.equals(pubkey)) : partialSig;
501
+ if (mySigs.length < 1)
502
+ throw new Error('No signatures for this pubkey');
503
+ const results = [];
504
+ let hashCache;
505
+ let scriptCache;
506
+ let sighashCache;
507
+ for (const pSig of mySigs) {
508
+ const sig = bscript.signature.decode(pSig.signature);
509
+ const { hash, script } = sighashCache !== sig.hashType
510
+ ? getHashForSig(inputIndex, Object.assign({}, input, {
511
+ sighashType: sig.hashType,
512
+ }), this.__CACHE, true)
513
+ : { hash: hashCache, script: scriptCache };
514
+ sighashCache = sig.hashType;
515
+ hashCache = hash;
516
+ scriptCache = script;
517
+ checkScriptForPubkey(pSig.pubkey, script, 'verify');
518
+ results.push(validator(pSig.pubkey, hash, sig.signature));
519
+ }
520
+ return results.every((res) => res === true);
521
+ }
522
+ validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) {
523
+ const input = this.data.inputs[inputIndex];
524
+ const tapKeySig = (input || {}).tapKeySig;
525
+ const tapScriptSig = (input || {}).tapScriptSig;
526
+ if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length))
527
+ throw new Error('No signatures to validate');
528
+ if (typeof validator !== 'function')
529
+ throw new Error('Need validator function to validate signatures');
530
+ pubkey = pubkey && toXOnly(pubkey);
531
+ const allHashses = pubkey
532
+ ? getTaprootHashesForSig(inputIndex, input, this.data.inputs, pubkey, this.__CACHE)
533
+ : getAllTaprootHashesForSig(inputIndex, input, this.data.inputs, this.__CACHE);
534
+ if (!allHashses.length)
535
+ throw new Error('No signatures for this pubkey');
536
+ const tapKeyHash = allHashses.find((h) => !h.leafHash);
537
+ let validationResultCount = 0;
538
+ if (tapKeySig && tapKeyHash) {
539
+ const isValidTapkeySig = validator(tapKeyHash.pubkey, tapKeyHash.hash, trimTaprootSig(tapKeySig));
540
+ if (!isValidTapkeySig)
541
+ return false;
542
+ validationResultCount++;
543
+ }
544
+ if (tapScriptSig) {
545
+ for (const tapSig of tapScriptSig) {
546
+ const tapSigHash = allHashses.find((h) => tapSig.pubkey.equals(h.pubkey));
547
+ if (tapSigHash) {
548
+ const isValidTapScriptSig = validator(tapSig.pubkey, tapSigHash.hash, trimTaprootSig(tapSig.signature));
549
+ if (!isValidTapScriptSig)
550
+ return false;
551
+ validationResultCount++;
552
+ }
553
+ }
554
+ }
555
+ return validationResultCount > 0;
556
+ }
557
+ _signInput(inputIndex, keyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
558
+ hookSigner(keyPair);
559
+ const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, keyPair.publicKey, this.__CACHE, sighashTypes);
560
+ const partialSig = [
561
+ {
562
+ pubkey: keyPair.publicKey,
563
+ signature: bscript.signature.encode(keyPair.sign(hash), sighashType),
564
+ },
565
+ ];
566
+ this.data.updateInput(inputIndex, { partialSig });
567
+ return this;
568
+ }
569
+ _signTaprootInput(inputIndex, input, keyPair, tapLeafHashToSign, allowedSighashTypes = [Transaction.SIGHASH_DEFAULT]) {
570
+ hookSigner(keyPair);
571
+ const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHashToSign, allowedSighashTypes);
572
+ const tapKeySig = hashesForSig
573
+ .filter((h) => !h.leafHash)
574
+ .map((h) => serializeTaprootSignature(keyPair.signSchnorr(h.hash), input.sighashType))[0];
575
+ const tapScriptSig = hashesForSig
576
+ .filter((h) => !!h.leafHash)
577
+ .map((h) => ({
578
+ pubkey: toXOnly(keyPair.publicKey),
579
+ signature: serializeTaprootSignature(keyPair.signSchnorr(h.hash), input.sighashType),
580
+ leafHash: h.leafHash,
581
+ }));
582
+ if (tapKeySig) {
583
+ this.data.updateInput(inputIndex, { tapKeySig });
584
+ }
585
+ if (tapScriptSig.length) {
586
+ this.data.updateInput(inputIndex, { tapScriptSig });
587
+ }
588
+ return this;
589
+ }
590
+ _signInputAsync(inputIndex, keyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
591
+ hookSigner(keyPair);
592
+ const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, keyPair.publicKey, this.__CACHE, sighashTypes);
593
+ return Promise.resolve(keyPair.sign(hash)).then((signature) => {
594
+ const partialSig = [
595
+ {
596
+ pubkey: keyPair.publicKey,
597
+ signature: bscript.signature.encode(signature, sighashType),
598
+ },
599
+ ];
600
+ this.data.updateInput(inputIndex, { partialSig });
601
+ });
602
+ }
603
+ async _signTaprootInputAsync(inputIndex, input, keyPair, tapLeafHash, sighashTypes = [Transaction.SIGHASH_DEFAULT]) {
604
+ hookSigner(keyPair);
605
+ const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
606
+ const signaturePromises = [];
607
+ const tapKeyHash = hashesForSig.filter((h) => !h.leafHash)[0];
608
+ if (tapKeyHash) {
609
+ const tapKeySigPromise = Promise.resolve(keyPair.signSchnorr(tapKeyHash.hash)).then((sig) => {
610
+ return {
611
+ tapKeySig: serializeTaprootSignature(sig, input.sighashType),
612
+ };
613
+ });
614
+ signaturePromises.push(tapKeySigPromise);
615
+ }
616
+ const tapScriptHashes = hashesForSig.filter((h) => !!h.leafHash);
617
+ if (tapScriptHashes.length) {
618
+ const tapScriptSigPromises = tapScriptHashes.map(async (tsh) => {
619
+ const signature = await keyPair.signSchnorr(tsh.hash);
620
+ const tapScriptSig = [
621
+ {
622
+ pubkey: toXOnly(keyPair.publicKey),
623
+ signature: serializeTaprootSignature(signature, input.sighashType),
624
+ leafHash: tsh.leafHash,
625
+ },
626
+ ];
627
+ return { tapScriptSig };
628
+ });
629
+ signaturePromises.push(...tapScriptSigPromises);
630
+ }
631
+ const results = await Promise.all(signaturePromises);
632
+ for (const v of results) {
633
+ this.data.updateInput(inputIndex, v);
634
+ }
635
+ }
636
+ }
637
+ const transactionFromBuffer = (buffer) => new PsbtTransaction(buffer);
638
+ class PsbtTransaction {
639
+ constructor(buffer = Buffer.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) {
640
+ this.tx = Transaction.fromBuffer(buffer);
641
+ checkTxEmpty(this.tx);
642
+ Object.defineProperty(this, 'tx', {
643
+ enumerable: false,
644
+ writable: true,
645
+ });
646
+ }
647
+ getInputOutputCounts() {
648
+ return {
649
+ inputCount: this.tx.ins.length,
650
+ outputCount: this.tx.outs.length,
651
+ };
652
+ }
653
+ addInput(input) {
654
+ if (input.hash === undefined ||
655
+ input.index === undefined ||
656
+ (!Buffer.isBuffer(input.hash) && typeof input.hash !== 'string') ||
657
+ typeof input.index !== 'number') {
658
+ throw new Error('Error adding input.');
659
+ }
660
+ const hash = typeof input.hash === 'string'
661
+ ? reverseBuffer(Buffer.from(input.hash, 'hex'))
662
+ : input.hash;
663
+ this.tx.addInput(hash, input.index, input.sequence);
664
+ }
665
+ addOutput(output) {
666
+ if (output.script === undefined ||
667
+ output.value === undefined ||
668
+ !Buffer.isBuffer(output.script) ||
669
+ typeof output.value !== 'number') {
670
+ throw new Error('Error adding output.');
671
+ }
672
+ this.tx.addOutput(output.script, output.value);
673
+ }
674
+ toBuffer() {
675
+ return this.tx.toBuffer();
676
+ }
677
+ }
678
+ function canFinalize(input, script, scriptType) {
679
+ switch (scriptType) {
680
+ case 'pubkey':
681
+ case 'pubkeyhash':
682
+ case 'witnesspubkeyhash':
683
+ return hasSigs(1, input.partialSig);
684
+ case 'multisig':
685
+ const p2ms = payments.p2ms({ output: script });
686
+ return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys);
687
+ default:
688
+ return false;
689
+ }
690
+ }
691
+ function checkCache(cache) {
692
+ if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) {
693
+ throw new Error('Not BIP174 compliant, can not export');
694
+ }
695
+ }
696
+ function hasSigs(neededSigs, partialSig, pubkeys) {
697
+ if (!partialSig)
698
+ return false;
699
+ let sigs;
700
+ if (pubkeys) {
701
+ sigs = pubkeys
702
+ .map((pkey) => {
703
+ const pubkey = compressPubkey(pkey);
704
+ return partialSig.find((pSig) => pSig.pubkey.equals(pubkey));
705
+ })
706
+ .filter((v) => !!v);
707
+ }
708
+ else {
709
+ sigs = partialSig;
710
+ }
711
+ if (sigs.length > neededSigs)
712
+ throw new Error('Too many signatures');
713
+ return sigs.length === neededSigs;
714
+ }
715
+ function isFinalized(input) {
716
+ return !!input.finalScriptSig || !!input.finalScriptWitness;
717
+ }
718
+ function bip32DerivationIsMine(root) {
719
+ return (d) => {
720
+ if (!d.masterFingerprint.equals(root.fingerprint))
721
+ return false;
722
+ if (!root.derivePath(d.path).publicKey.equals(d.pubkey))
723
+ return false;
724
+ return true;
725
+ };
726
+ }
727
+ function check32Bit(num) {
728
+ if (typeof num !== 'number' || num !== Math.floor(num) || num > 0xffffffff || num < 0) {
729
+ throw new Error('Invalid 32 bit integer');
730
+ }
731
+ }
732
+ function checkFees(psbt, cache, opts) {
733
+ const feeRate = cache.__FEE_RATE || psbt.getFeeRate();
734
+ const vsize = cache.__EXTRACTED_TX.virtualSize();
735
+ const satoshis = feeRate * vsize;
736
+ if (feeRate >= opts.maximumFeeRate) {
737
+ throw new Error(`Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` +
738
+ `fees, which is ${feeRate} satoshi per byte for a transaction ` +
739
+ `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` +
740
+ `byte). Use setMaximumFeeRate method to raise your threshold, or ` +
741
+ `pass true to the first arg of extractTransaction.`);
742
+ }
743
+ }
744
+ function checkInputsForPartialSig(inputs, action) {
745
+ inputs.forEach((input) => {
746
+ const throws = isTaprootInput(input)
747
+ ? checkTaprootInputForSigs(input, action)
748
+ : checkInputForSig(input, action);
749
+ if (throws)
750
+ throw new Error('Can not modify transaction, signatures exist.');
751
+ });
752
+ }
753
+ function checkPartialSigSighashes(input) {
754
+ if (!input.sighashType || !input.partialSig)
755
+ return;
756
+ const { partialSig, sighashType } = input;
757
+ partialSig.forEach((pSig) => {
758
+ const { hashType } = bscript.signature.decode(pSig.signature);
759
+ if (sighashType !== hashType) {
760
+ throw new Error('Signature sighash does not match input sighash type');
761
+ }
762
+ });
763
+ }
764
+ function checkScriptForPubkey(pubkey, script, action) {
765
+ if (!pubkeyInScript(pubkey, script)) {
766
+ throw new Error(`Can not ${action} for this input with the key ${pubkey.toString('hex')}`);
767
+ }
768
+ }
769
+ function checkTxEmpty(tx) {
770
+ const isEmpty = tx.ins.every((input) => input.script &&
771
+ input.script.length === 0 &&
772
+ input.witness &&
773
+ input.witness.length === 0);
774
+ if (!isEmpty) {
775
+ throw new Error('Format Error: Transaction ScriptSigs are not empty');
776
+ }
777
+ }
778
+ function checkTxForDupeIns(tx, cache) {
779
+ tx.ins.forEach((input) => {
780
+ checkTxInputCache(cache, input);
781
+ });
782
+ }
783
+ function checkTxInputCache(cache, input) {
784
+ const key = reverseBuffer(Buffer.from(input.hash)).toString('hex') + ':' + input.index;
785
+ if (cache.__TX_IN_CACHE[key])
786
+ throw new Error('Duplicate input detected.');
787
+ cache.__TX_IN_CACHE[key] = 1;
788
+ }
789
+ function scriptCheckerFactory(payment, paymentScriptName) {
790
+ return (inputIndex, scriptPubKey, redeemScript, ioType) => {
791
+ const redeemScriptOutput = payment({
792
+ redeem: { output: redeemScript },
793
+ }).output;
794
+ if (!scriptPubKey.equals(redeemScriptOutput)) {
795
+ throw new Error(`${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`);
796
+ }
797
+ };
798
+ }
799
+ const checkRedeemScript = scriptCheckerFactory(payments.p2sh, 'Redeem script');
800
+ const checkWitnessScript = scriptCheckerFactory(payments.p2wsh, 'Witness script');
801
+ function getTxCacheValue(key, name, inputs, c, disableOutputChecks = false) {
802
+ if (!inputs.every(isFinalized))
803
+ throw new Error(`PSBT must be finalized to calculate ${name}`);
804
+ if (key === '__FEE_RATE' && c.__FEE_RATE)
805
+ return c.__FEE_RATE;
806
+ if (key === '__FEE' && c.__FEE)
807
+ return c.__FEE;
808
+ let tx;
809
+ let mustFinalize = true;
810
+ if (c.__EXTRACTED_TX) {
811
+ tx = c.__EXTRACTED_TX;
812
+ mustFinalize = false;
813
+ }
814
+ else {
815
+ tx = c.__TX.clone();
816
+ }
817
+ inputFinalizeGetAmts(inputs, tx, c, mustFinalize, disableOutputChecks);
818
+ if (key === '__FEE_RATE')
819
+ return c.__FEE_RATE;
820
+ else if (key === '__FEE')
821
+ return c.__FEE;
822
+ }
823
+ export function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks = true) {
824
+ const scriptType = classifyScript(script);
825
+ if (!canFinalize(input, script, scriptType) && canRunChecks) {
826
+ throw new Error(`Can not finalize input #${inputIndex}`);
827
+ }
828
+ return prepareFinalScripts(script, scriptType, input.partialSig, isSegwit, isP2SH, isP2WSH);
829
+ }
830
+ export function prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH) {
831
+ let finalScriptSig;
832
+ let finalScriptWitness;
833
+ const payment = getPayment(script, scriptType, partialSig);
834
+ const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment });
835
+ const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment });
836
+ if (isSegwit) {
837
+ if (p2wsh) {
838
+ finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness);
839
+ }
840
+ else {
841
+ finalScriptWitness = witnessStackToScriptWitness(payment.witness);
842
+ }
843
+ if (p2sh) {
844
+ finalScriptSig = p2sh.input;
845
+ }
846
+ }
847
+ else {
848
+ if (p2sh) {
849
+ finalScriptSig = p2sh.input;
850
+ }
851
+ else {
852
+ finalScriptSig = payment.input;
853
+ }
854
+ }
855
+ return {
856
+ finalScriptSig,
857
+ finalScriptWitness,
858
+ };
859
+ }
860
+ function getHashAndSighashType(inputs, inputIndex, pubkey, cache, sighashTypes) {
861
+ const input = checkForInput(inputs, inputIndex);
862
+ const { hash, sighashType, script } = getHashForSig(inputIndex, input, cache, false, sighashTypes);
863
+ checkScriptForPubkey(pubkey, script, 'sign');
864
+ return {
865
+ hash,
866
+ sighashType,
867
+ };
868
+ }
869
+ function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) {
870
+ const unsignedTx = cache.__TX;
871
+ const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
872
+ checkSighashTypeAllowed(sighashType, sighashTypes);
873
+ let hash;
874
+ let prevout;
875
+ if (input.nonWitnessUtxo) {
876
+ const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
877
+ const prevoutHash = unsignedTx.ins[inputIndex].hash;
878
+ const utxoHash = nonWitnessUtxoTx.getHash();
879
+ if (!prevoutHash.equals(utxoHash)) {
880
+ throw new Error(`Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`);
881
+ }
882
+ const prevoutIndex = unsignedTx.ins[inputIndex].index;
883
+ prevout = nonWitnessUtxoTx.outs[prevoutIndex];
884
+ }
885
+ else if (input.witnessUtxo) {
886
+ prevout = input.witnessUtxo;
887
+ }
888
+ else {
889
+ throw new Error('Need a Utxo input item for signing');
890
+ }
891
+ const { meaningfulScript, type } = getMeaningfulScript(prevout.script, inputIndex, 'input', input.redeemScript, input.witnessScript);
892
+ if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) {
893
+ hash = unsignedTx.hashForWitnessV0(inputIndex, meaningfulScript, prevout.value, sighashType);
894
+ }
895
+ else if (isP2WPKH(meaningfulScript)) {
896
+ const signingScript = payments.p2pkh({
897
+ hash: meaningfulScript.slice(2),
898
+ }).output;
899
+ hash = unsignedTx.hashForWitnessV0(inputIndex, signingScript, prevout.value, sighashType);
900
+ }
901
+ else {
902
+ if (input.nonWitnessUtxo === undefined && cache.__UNSAFE_SIGN_NONSEGWIT === false)
903
+ throw new Error(`Input #${inputIndex} has witnessUtxo but non-segwit script: ` +
904
+ `${meaningfulScript.toString('hex')}`);
905
+ if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false)
906
+ console.warn('Warning: Signing non-segwit inputs without the full parent transaction ' +
907
+ 'means there is a chance that a miner could feed you incorrect information ' +
908
+ "to trick you into paying large fees. This behavior is the same as Psbt's predecessor " +
909
+ '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' +
910
+ 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' +
911
+ 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' +
912
+ '*********************');
913
+ hash = unsignedTx.hashForSignature(inputIndex, meaningfulScript, sighashType);
914
+ }
915
+ return {
916
+ script: meaningfulScript,
917
+ sighashType,
918
+ hash,
919
+ };
920
+ }
921
+ function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) {
922
+ const allPublicKeys = [];
923
+ if (input.tapInternalKey) {
924
+ const key = getPrevoutTaprootKey(inputIndex, input, cache);
925
+ if (key) {
926
+ allPublicKeys.push(key);
927
+ }
928
+ }
929
+ if (input.tapScriptSig) {
930
+ const tapScriptPubkeys = input.tapScriptSig.map((tss) => tss.pubkey);
931
+ allPublicKeys.push(...tapScriptPubkeys);
932
+ }
933
+ const allHashes = allPublicKeys.map((pubicKey) => getTaprootHashesForSig(inputIndex, input, inputs, pubicKey, cache));
934
+ return allHashes.flat();
935
+ }
936
+ function getPrevoutTaprootKey(inputIndex, input, cache) {
937
+ const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
938
+ return isP2TR(script) ? script.subarray(2, 34) : null;
939
+ }
940
+ function trimTaprootSig(signature) {
941
+ return signature.length === 64 ? signature : signature.subarray(0, 64);
942
+ }
943
+ function getTaprootHashesForSig(inputIndex, input, inputs, pubkey, cache, tapLeafHashToSign, allowedSighashTypes) {
944
+ const unsignedTx = cache.__TX;
945
+ const sighashType = input.sighashType || Transaction.SIGHASH_DEFAULT;
946
+ checkSighashTypeAllowed(sighashType, allowedSighashTypes);
947
+ const prevOuts = inputs.map((i, index) => getScriptAndAmountFromUtxo(index, i, cache));
948
+ const signingScripts = prevOuts.map((o) => o.script);
949
+ const values = prevOuts.map((o) => o.value);
950
+ const hashes = [];
951
+ if (input.tapInternalKey && !tapLeafHashToSign) {
952
+ const outputKey = getPrevoutTaprootKey(inputIndex, input, cache) || Buffer.from([]);
953
+ if (toXOnly(pubkey).equals(outputKey)) {
954
+ const tapKeyHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType);
955
+ hashes.push({ pubkey, hash: tapKeyHash });
956
+ }
957
+ }
958
+ const tapLeafHashes = (input.tapLeafScript || [])
959
+ .filter((tapLeaf) => pubkeyInScript(pubkey, tapLeaf.script))
960
+ .map((tapLeaf) => {
961
+ const hash = tapleafHash({
962
+ output: tapLeaf.script,
963
+ version: tapLeaf.leafVersion,
964
+ });
965
+ return Object.assign({ hash }, tapLeaf);
966
+ })
967
+ .filter((tapLeaf) => !tapLeafHashToSign || tapLeafHashToSign.equals(tapLeaf.hash))
968
+ .map((tapLeaf) => {
969
+ const tapScriptHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType, tapLeaf.hash);
970
+ return {
971
+ pubkey,
972
+ hash: tapScriptHash,
973
+ leafHash: tapLeaf.hash,
974
+ };
975
+ });
976
+ return hashes.concat(tapLeafHashes);
977
+ }
978
+ function checkSighashTypeAllowed(sighashType, sighashTypes) {
979
+ if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) {
980
+ const str = sighashTypeToString(sighashType);
981
+ throw new Error(`Sighash type is not allowed. Retry the sign method passing the ` +
982
+ `sighashTypes array of whitelisted types. Sighash type: ${str}`);
983
+ }
984
+ }
985
+ function getPayment(script, scriptType, partialSig) {
986
+ let payment;
987
+ switch (scriptType) {
988
+ case 'multisig':
989
+ const sigs = getSortedSigs(script, partialSig);
990
+ payment = payments.p2ms({
991
+ output: script,
992
+ signatures: sigs,
993
+ });
994
+ break;
995
+ case 'pubkey':
996
+ payment = payments.p2pk({
997
+ output: script,
998
+ signature: partialSig[0].signature,
999
+ });
1000
+ break;
1001
+ case 'pubkeyhash':
1002
+ payment = payments.p2pkh({
1003
+ output: script,
1004
+ pubkey: partialSig[0].pubkey,
1005
+ signature: partialSig[0].signature,
1006
+ });
1007
+ break;
1008
+ case 'witnesspubkeyhash':
1009
+ payment = payments.p2wpkh({
1010
+ output: script,
1011
+ pubkey: partialSig[0].pubkey,
1012
+ signature: partialSig[0].signature,
1013
+ });
1014
+ break;
1015
+ }
1016
+ return payment;
1017
+ }
1018
+ function getScriptFromInput(inputIndex, input, cache) {
1019
+ const unsignedTx = cache.__TX;
1020
+ const res = {
1021
+ script: null,
1022
+ isSegwit: false,
1023
+ isP2SH: false,
1024
+ isP2WSH: false,
1025
+ };
1026
+ res.isP2SH = !!input.redeemScript;
1027
+ res.isP2WSH = !!input.witnessScript;
1028
+ if (input.witnessScript) {
1029
+ res.script = input.witnessScript;
1030
+ }
1031
+ else if (input.redeemScript) {
1032
+ res.script = input.redeemScript;
1033
+ }
1034
+ else {
1035
+ if (input.nonWitnessUtxo) {
1036
+ const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
1037
+ const prevoutIndex = unsignedTx.ins[inputIndex].index;
1038
+ res.script = nonWitnessUtxoTx.outs[prevoutIndex].script;
1039
+ }
1040
+ else if (input.witnessUtxo) {
1041
+ res.script = input.witnessUtxo.script;
1042
+ }
1043
+ }
1044
+ if (input.witnessScript || isP2WPKH(res.script)) {
1045
+ res.isSegwit = true;
1046
+ }
1047
+ return res;
1048
+ }
1049
+ function getSignersFromHD(inputIndex, inputs, hdKeyPair) {
1050
+ const input = checkForInput(inputs, inputIndex);
1051
+ if (!input.bip32Derivation || input.bip32Derivation.length === 0) {
1052
+ throw new Error('Need bip32Derivation to sign with HD');
1053
+ }
1054
+ const myDerivations = input.bip32Derivation
1055
+ .map((bipDv) => {
1056
+ if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) {
1057
+ return bipDv;
1058
+ }
1059
+ else {
1060
+ return;
1061
+ }
1062
+ })
1063
+ .filter((v) => !!v);
1064
+ if (myDerivations.length === 0) {
1065
+ throw new Error('Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint');
1066
+ }
1067
+ return myDerivations.map((bipDv) => {
1068
+ const node = hdKeyPair.derivePath(bipDv.path);
1069
+ if (!bipDv.pubkey.equals(node.publicKey)) {
1070
+ throw new Error('pubkey did not match bip32Derivation');
1071
+ }
1072
+ return node;
1073
+ });
1074
+ }
1075
+ function getSortedSigs(script, partialSig) {
1076
+ const p2ms = payments.p2ms({ output: script });
1077
+ return p2ms
1078
+ .pubkeys.map((pk) => {
1079
+ return (partialSig.filter((ps) => {
1080
+ return ps.pubkey.equals(pk);
1081
+ })[0] || {}).signature;
1082
+ })
1083
+ .filter((v) => !!v);
1084
+ }
1085
+ function scriptWitnessToWitnessStack(buffer) {
1086
+ let offset = 0;
1087
+ function readSlice(n) {
1088
+ offset += n;
1089
+ return buffer.slice(offset - n, offset);
1090
+ }
1091
+ function readVarInt() {
1092
+ const vi = varuint.decode(buffer, offset);
1093
+ offset += varuint.decode.bytes;
1094
+ return vi;
1095
+ }
1096
+ function readVarSlice() {
1097
+ return readSlice(readVarInt());
1098
+ }
1099
+ function readVector() {
1100
+ const count = readVarInt();
1101
+ const vector = [];
1102
+ for (let i = 0; i < count; i++)
1103
+ vector.push(readVarSlice());
1104
+ return vector;
1105
+ }
1106
+ return readVector();
1107
+ }
1108
+ function sighashTypeToString(sighashType) {
1109
+ let text = sighashType & Transaction.SIGHASH_ANYONECANPAY ? 'SIGHASH_ANYONECANPAY | ' : '';
1110
+ const sigMod = sighashType & 0x1f;
1111
+ switch (sigMod) {
1112
+ case Transaction.SIGHASH_ALL:
1113
+ text += 'SIGHASH_ALL';
1114
+ break;
1115
+ case Transaction.SIGHASH_SINGLE:
1116
+ text += 'SIGHASH_SINGLE';
1117
+ break;
1118
+ case Transaction.SIGHASH_NONE:
1119
+ text += 'SIGHASH_NONE';
1120
+ break;
1121
+ }
1122
+ return text;
1123
+ }
1124
+ function addNonWitnessTxCache(cache, input, inputIndex) {
1125
+ cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo;
1126
+ cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = Transaction.fromBuffer(input.nonWitnessUtxo);
1127
+ const self = cache;
1128
+ const selfIndex = inputIndex;
1129
+ delete input.nonWitnessUtxo;
1130
+ Object.defineProperty(input, 'nonWitnessUtxo', {
1131
+ enumerable: true,
1132
+ get() {
1133
+ const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex];
1134
+ const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex];
1135
+ if (buf !== undefined) {
1136
+ return buf;
1137
+ }
1138
+ else {
1139
+ const newBuf = txCache.toBuffer();
1140
+ self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf;
1141
+ return newBuf;
1142
+ }
1143
+ },
1144
+ set(data) {
1145
+ self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data;
1146
+ },
1147
+ });
1148
+ }
1149
+ function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize, disableOutputChecks) {
1150
+ let inputAmount = 0;
1151
+ inputs.forEach((input, idx) => {
1152
+ if (mustFinalize && input.finalScriptSig)
1153
+ tx.ins[idx].script = input.finalScriptSig;
1154
+ if (mustFinalize && input.finalScriptWitness) {
1155
+ tx.ins[idx].witness = scriptWitnessToWitnessStack(input.finalScriptWitness);
1156
+ }
1157
+ if (input.witnessUtxo) {
1158
+ inputAmount += input.witnessUtxo.value;
1159
+ }
1160
+ else if (input.nonWitnessUtxo) {
1161
+ const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx);
1162
+ const vout = tx.ins[idx].index;
1163
+ const out = nwTx.outs[vout];
1164
+ inputAmount += out.value;
1165
+ }
1166
+ });
1167
+ const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0);
1168
+ const fee = inputAmount - outputAmount;
1169
+ if (!disableOutputChecks) {
1170
+ if (fee < 0) {
1171
+ throw new Error('Outputs are spending more than Inputs');
1172
+ }
1173
+ }
1174
+ const bytes = tx.virtualSize();
1175
+ cache.__FEE = fee;
1176
+ cache.__EXTRACTED_TX = tx;
1177
+ cache.__FEE_RATE = Math.floor(fee / bytes);
1178
+ }
1179
+ function nonWitnessUtxoTxFromCache(cache, input, inputIndex) {
1180
+ const c = cache.__NON_WITNESS_UTXO_TX_CACHE;
1181
+ if (!c[inputIndex]) {
1182
+ addNonWitnessTxCache(cache, input, inputIndex);
1183
+ }
1184
+ return c[inputIndex];
1185
+ }
1186
+ function getScriptFromUtxo(inputIndex, input, cache) {
1187
+ const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
1188
+ return script;
1189
+ }
1190
+ function getScriptAndAmountFromUtxo(inputIndex, input, cache) {
1191
+ if (input.witnessUtxo !== undefined) {
1192
+ return {
1193
+ script: input.witnessUtxo.script,
1194
+ value: input.witnessUtxo.value,
1195
+ };
1196
+ }
1197
+ else if (input.nonWitnessUtxo !== undefined) {
1198
+ const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
1199
+ const o = nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index];
1200
+ return { script: o.script, value: o.value };
1201
+ }
1202
+ else {
1203
+ throw new Error("Can't find pubkey in input without Utxo data");
1204
+ }
1205
+ }
1206
+ function pubkeyInInput(pubkey, input, inputIndex, cache) {
1207
+ const script = getScriptFromUtxo(inputIndex, input, cache);
1208
+ const { meaningfulScript } = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript, input.witnessScript);
1209
+ return pubkeyInScript(pubkey, meaningfulScript);
1210
+ }
1211
+ function pubkeyInOutput(pubkey, output, outputIndex, cache) {
1212
+ const script = cache.__TX.outs[outputIndex].script;
1213
+ const { meaningfulScript } = getMeaningfulScript(script, outputIndex, 'output', output.redeemScript, output.witnessScript);
1214
+ return pubkeyInScript(pubkey, meaningfulScript);
1215
+ }
1216
+ function redeemFromFinalScriptSig(finalScript) {
1217
+ if (!finalScript)
1218
+ return;
1219
+ const decomp = bscript.decompile(finalScript);
1220
+ if (!decomp)
1221
+ return;
1222
+ const lastItem = decomp[decomp.length - 1];
1223
+ if (!Buffer.isBuffer(lastItem) || isPubkeyLike(lastItem) || isSigLike(lastItem))
1224
+ return;
1225
+ const sDecomp = bscript.decompile(lastItem);
1226
+ if (!sDecomp)
1227
+ return;
1228
+ return lastItem;
1229
+ }
1230
+ function redeemFromFinalWitnessScript(finalScript) {
1231
+ if (!finalScript)
1232
+ return;
1233
+ const decomp = scriptWitnessToWitnessStack(finalScript);
1234
+ const lastItem = decomp[decomp.length - 1];
1235
+ if (isPubkeyLike(lastItem))
1236
+ return;
1237
+ const sDecomp = bscript.decompile(lastItem);
1238
+ if (!sDecomp)
1239
+ return;
1240
+ return lastItem;
1241
+ }
1242
+ function compressPubkey(pubkey) {
1243
+ if (pubkey.length === 65) {
1244
+ const parity = pubkey[64] & 1;
1245
+ const newKey = pubkey.slice(0, 33);
1246
+ newKey[0] = 2 | parity;
1247
+ return newKey;
1248
+ }
1249
+ return pubkey.slice();
1250
+ }
1251
+ function isPubkeyLike(buf) {
1252
+ return buf.length === 33 && bscript.isCanonicalPubKey(buf);
1253
+ }
1254
+ function isSigLike(buf) {
1255
+ return bscript.isCanonicalScriptSignature(buf);
1256
+ }
1257
+ function getMeaningfulScript(script, index, ioType, redeemScript, witnessScript) {
1258
+ const isP2SH = isP2SHScript(script);
1259
+ const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript);
1260
+ const isP2WSH = isP2WSHScript(script);
1261
+ if (isP2SH && redeemScript === undefined)
1262
+ throw new Error('scriptPubkey is P2SH but redeemScript missing');
1263
+ if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined)
1264
+ throw new Error('scriptPubkey or redeemScript is P2WSH but witnessScript missing');
1265
+ let meaningfulScript;
1266
+ if (isP2SHP2WSH) {
1267
+ meaningfulScript = witnessScript;
1268
+ checkRedeemScript(index, script, redeemScript, ioType);
1269
+ checkWitnessScript(index, redeemScript, witnessScript, ioType);
1270
+ checkInvalidP2WSH(meaningfulScript);
1271
+ }
1272
+ else if (isP2WSH) {
1273
+ meaningfulScript = witnessScript;
1274
+ checkWitnessScript(index, script, witnessScript, ioType);
1275
+ checkInvalidP2WSH(meaningfulScript);
1276
+ }
1277
+ else if (isP2SH) {
1278
+ meaningfulScript = redeemScript;
1279
+ checkRedeemScript(index, script, redeemScript, ioType);
1280
+ }
1281
+ else {
1282
+ meaningfulScript = script;
1283
+ }
1284
+ return {
1285
+ meaningfulScript,
1286
+ type: isP2SHP2WSH ? 'p2sh-p2wsh' : isP2SH ? 'p2sh' : isP2WSH ? 'p2wsh' : 'raw',
1287
+ };
1288
+ }
1289
+ function checkInvalidP2WSH(script) {
1290
+ if (isP2WPKH(script) || isP2SHScript(script)) {
1291
+ throw new Error('P2WPKH or P2SH can not be contained within P2WSH');
1292
+ }
1293
+ }
1294
+ function classifyScript(script) {
1295
+ if (isP2WPKH(script))
1296
+ return 'witnesspubkeyhash';
1297
+ if (isP2PKH(script))
1298
+ return 'pubkeyhash';
1299
+ if (isP2MS(script))
1300
+ return 'multisig';
1301
+ if (isP2PK(script))
1302
+ return 'pubkey';
1303
+ return 'nonstandard';
1304
+ }
1305
+ function range(n) {
1306
+ return [...Array(n).keys()];
1307
+ }