edge-currency-plugins 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -0
  3. package/lib/bch.js +15 -0
  4. package/lib/bsv.js +15 -0
  5. package/lib/btc.js +15 -0
  6. package/lib/common/constants.js +11 -0
  7. package/lib/common/fees/calcMinerFeePerByte.js +62 -0
  8. package/lib/common/fees/makeFees.js +182 -0
  9. package/lib/common/fees/processInfoServerFees.js +30 -0
  10. package/lib/common/fees/processMempoolSpaceFees.js +38 -0
  11. package/lib/common/plugin/makeCurrencyPlugin.js +66 -0
  12. package/lib/common/plugin/makeCurrencyTools.js +211 -0
  13. package/lib/common/plugin/makeEngineEmitter.js +102 -0
  14. package/lib/common/plugin/makeMetadata.js +99 -0
  15. package/lib/common/plugin/pluginState.js +253 -0
  16. package/lib/common/plugin/serverScores.js +328 -0
  17. package/lib/common/plugin/types.js +173 -0
  18. package/lib/common/plugin/utils.js +18 -0
  19. package/lib/common/utxobased/db/Models/ProcessorTransaction.js +122 -0
  20. package/lib/common/utxobased/db/Models/baselet.js +81 -0
  21. package/lib/common/utxobased/db/makeBaselets.js +123 -0
  22. package/lib/common/utxobased/db/makeMutex.js +17 -0
  23. package/lib/common/utxobased/db/makeProcessor.js +554 -0
  24. package/lib/common/utxobased/db/types.js +67 -0
  25. package/lib/common/utxobased/engine/await-lock.js +65 -0
  26. package/lib/common/utxobased/engine/constants.js +7 -0
  27. package/lib/common/utxobased/engine/makeServerStates.js +394 -0
  28. package/lib/common/utxobased/engine/makeUtxoEngine.js +690 -0
  29. package/lib/common/utxobased/engine/makeUtxoEngineState.js +1443 -0
  30. package/lib/common/utxobased/engine/makeUtxoWalletTools.js +216 -0
  31. package/lib/common/utxobased/engine/paymentRequest.js +102 -0
  32. package/lib/common/utxobased/engine/types.js +21 -0
  33. package/lib/common/utxobased/engine/util/defaultValidateConfirmations.js +19 -0
  34. package/lib/common/utxobased/engine/util/getOwnUtxosFromTx.js +54 -0
  35. package/lib/common/utxobased/engine/utils.js +239 -0
  36. package/lib/common/utxobased/info/all.js +67 -0
  37. package/lib/common/utxobased/info/badcoin.js +73 -0
  38. package/lib/common/utxobased/info/bitcoin.js +91 -0
  39. package/lib/common/utxobased/info/bitcoincash.js +93 -0
  40. package/lib/common/utxobased/info/bitcoincashtestnet.js +72 -0
  41. package/lib/common/utxobased/info/bitcoingold.js +85 -0
  42. package/lib/common/utxobased/info/bitcoingoldtestnet.js +71 -0
  43. package/lib/common/utxobased/info/bitcoinsv.js +76 -0
  44. package/lib/common/utxobased/info/bitcointestnet.js +81 -0
  45. package/lib/common/utxobased/info/dash.js +76 -0
  46. package/lib/common/utxobased/info/digibyte.js +76 -0
  47. package/lib/common/utxobased/info/dogecoin.js +76 -0
  48. package/lib/common/utxobased/info/eboost.js +70 -0
  49. package/lib/common/utxobased/info/feathercoin.js +76 -0
  50. package/lib/common/utxobased/info/groestlcoin.js +88 -0
  51. package/lib/common/utxobased/info/litecoin.js +82 -0
  52. package/lib/common/utxobased/info/qtum.js +67 -0
  53. package/lib/common/utxobased/info/ravencoin.js +70 -0
  54. package/lib/common/utxobased/info/scriptTemplates/bitcoincashScriptTemplates.js +56 -0
  55. package/lib/common/utxobased/info/scriptTemplates/types.js +14 -0
  56. package/lib/common/utxobased/info/smartcash.js +78 -0
  57. package/lib/common/utxobased/info/ufo.js +75 -0
  58. package/lib/common/utxobased/info/utxoPickers/dogeUtxoPicker.js +34 -0
  59. package/lib/common/utxobased/info/vertcoin.js +82 -0
  60. package/lib/common/utxobased/info/zcoin.js +72 -0
  61. package/lib/common/utxobased/keymanager/base.js +60 -0
  62. package/lib/common/utxobased/keymanager/bip69.js +31 -0
  63. package/lib/common/utxobased/keymanager/bitcoincashUtils/base32.js +88 -0
  64. package/lib/common/utxobased/keymanager/bitcoincashUtils/bn.js +210 -0
  65. package/lib/common/utxobased/keymanager/bitcoincashUtils/cashAddress.js +282 -0
  66. package/lib/common/utxobased/keymanager/cleaners.js +198 -0
  67. package/lib/common/utxobased/keymanager/coinmapper.js +12 -0
  68. package/lib/common/utxobased/keymanager/declarations/base58grscheck.d.js +1 -0
  69. package/lib/common/utxobased/keymanager/declarations/blake-hash.d.js +1 -0
  70. package/lib/common/utxobased/keymanager/declarations/bn.d.js +1 -0
  71. package/lib/common/utxobased/keymanager/declarations/bs58smartcheck.d.js +1 -0
  72. package/lib/common/utxobased/keymanager/declarations/wif-smart.d.js +1 -0
  73. package/lib/common/utxobased/keymanager/declarations/wifgrs.d.js +1 -0
  74. package/lib/common/utxobased/keymanager/keymanager.js +1214 -0
  75. package/lib/common/utxobased/keymanager/utxopicker/accumulative.js +52 -0
  76. package/lib/common/utxobased/keymanager/utxopicker/forceUseUtxo.js +59 -0
  77. package/lib/common/utxobased/keymanager/utxopicker/subtractFee.js +17 -0
  78. package/lib/common/utxobased/keymanager/utxopicker/types.js +42 -0
  79. package/lib/common/utxobased/keymanager/utxopicker/utils.js +159 -0
  80. package/lib/common/utxobased/keymanager/utxopicker.js +17 -0
  81. package/lib/common/utxobased/network/BlockBook.js +200 -0
  82. package/lib/common/utxobased/network/BlockBookAPI.js +335 -0
  83. package/lib/common/utxobased/network/Deferred.js +29 -0
  84. package/lib/common/utxobased/network/MakeSocketEmitter.js +35 -0
  85. package/lib/common/utxobased/network/Socket.js +362 -0
  86. package/lib/common/utxobased/network/nodejsWS.js +59 -0
  87. package/lib/common/utxobased/network/socketQueue.js +60 -0
  88. package/lib/common/utxobased/network/types.js +19 -0
  89. package/lib/common/utxobased/network/windowWS.js +54 -0
  90. package/lib/firo.js +15 -0
  91. package/lib/ftc.js +15 -0
  92. package/lib/index.js +19 -0
  93. package/lib/ltc.js +15 -0
  94. package/lib/src/bch.d.ts +3 -0
  95. package/lib/src/bsv.d.ts +3 -0
  96. package/lib/src/btc.d.ts +3 -0
  97. package/lib/src/common/constants.d.ts +9 -0
  98. package/lib/src/common/fees/calcMinerFeePerByte.d.ts +13 -0
  99. package/lib/src/common/fees/makeFees.d.ts +20 -0
  100. package/lib/src/common/fees/processInfoServerFees.d.ts +7 -0
  101. package/lib/src/common/fees/processMempoolSpaceFees.d.ts +13 -0
  102. package/lib/src/common/plugin/makeCurrencyPlugin.d.ts +3 -0
  103. package/lib/src/common/plugin/makeCurrencyTools.d.ts +8 -0
  104. package/lib/src/common/plugin/makeEngineEmitter.d.ts +23 -0
  105. package/lib/src/common/plugin/makeMetadata.d.ts +14 -0
  106. package/lib/src/common/plugin/pluginState.d.ts +34 -0
  107. package/lib/src/common/plugin/serverScores.d.ts +61 -0
  108. package/lib/src/common/plugin/types.d.ts +135 -0
  109. package/lib/src/common/plugin/utils.d.ts +6 -0
  110. package/lib/src/common/utxobased/db/Models/ProcessorTransaction.d.ts +16 -0
  111. package/lib/src/common/utxobased/db/Models/baselet.d.ts +28 -0
  112. package/lib/src/common/utxobased/db/makeBaselets.d.ts +33 -0
  113. package/lib/src/common/utxobased/db/makeMutex.d.ts +3 -0
  114. package/lib/src/common/utxobased/db/makeProcessor.d.ts +42 -0
  115. package/lib/src/common/utxobased/db/types.d.ts +47 -0
  116. package/lib/src/common/utxobased/engine/await-lock.d.ts +29 -0
  117. package/lib/src/common/utxobased/engine/constants.d.ts +4 -0
  118. package/lib/src/common/utxobased/engine/makeServerStates.d.ts +37 -0
  119. package/lib/src/common/utxobased/engine/makeUtxoEngine.d.ts +3 -0
  120. package/lib/src/common/utxobased/engine/makeUtxoEngineState.d.ts +108 -0
  121. package/lib/src/common/utxobased/engine/makeUtxoWalletTools.d.ts +52 -0
  122. package/lib/src/common/utxobased/engine/paymentRequest.d.ts +18 -0
  123. package/lib/src/common/utxobased/engine/types.d.ts +19 -0
  124. package/lib/src/common/utxobased/engine/util/defaultValidateConfirmations.d.ts +3 -0
  125. package/lib/src/common/utxobased/engine/util/getOwnUtxosFromTx.d.ts +4 -0
  126. package/lib/src/common/utxobased/engine/utils.d.ts +43 -0
  127. package/lib/src/common/utxobased/info/all.d.ts +22 -0
  128. package/lib/src/common/utxobased/info/badcoin.d.ts +3 -0
  129. package/lib/src/common/utxobased/info/bitcoin.d.ts +3 -0
  130. package/lib/src/common/utxobased/info/bitcoincash.d.ts +3 -0
  131. package/lib/src/common/utxobased/info/bitcoincashtestnet.d.ts +3 -0
  132. package/lib/src/common/utxobased/info/bitcoingold.d.ts +3 -0
  133. package/lib/src/common/utxobased/info/bitcoingoldtestnet.d.ts +3 -0
  134. package/lib/src/common/utxobased/info/bitcoinsv.d.ts +3 -0
  135. package/lib/src/common/utxobased/info/bitcointestnet.d.ts +6 -0
  136. package/lib/src/common/utxobased/info/dash.d.ts +3 -0
  137. package/lib/src/common/utxobased/info/digibyte.d.ts +3 -0
  138. package/lib/src/common/utxobased/info/dogecoin.d.ts +3 -0
  139. package/lib/src/common/utxobased/info/eboost.d.ts +3 -0
  140. package/lib/src/common/utxobased/info/feathercoin.d.ts +6 -0
  141. package/lib/src/common/utxobased/info/groestlcoin.d.ts +3 -0
  142. package/lib/src/common/utxobased/info/litecoin.d.ts +6 -0
  143. package/lib/src/common/utxobased/info/qtum.d.ts +3 -0
  144. package/lib/src/common/utxobased/info/ravencoin.d.ts +3 -0
  145. package/lib/src/common/utxobased/info/scriptTemplates/bitcoincashScriptTemplates.d.ts +2 -0
  146. package/lib/src/common/utxobased/info/scriptTemplates/types.d.ts +9 -0
  147. package/lib/src/common/utxobased/info/smartcash.d.ts +3 -0
  148. package/lib/src/common/utxobased/info/ufo.d.ts +3 -0
  149. package/lib/src/common/utxobased/info/utxoPickers/dogeUtxoPicker.d.ts +2 -0
  150. package/lib/src/common/utxobased/info/vertcoin.d.ts +3 -0
  151. package/lib/src/common/utxobased/info/zcoin.d.ts +6 -0
  152. package/lib/src/common/utxobased/keymanager/base.d.ts +9 -0
  153. package/lib/src/common/utxobased/keymanager/bip69.d.ts +19 -0
  154. package/lib/src/common/utxobased/keymanager/bitcoincashUtils/base32.d.ts +19 -0
  155. package/lib/src/common/utxobased/keymanager/bitcoincashUtils/bn.d.ts +2 -0
  156. package/lib/src/common/utxobased/keymanager/bitcoincashUtils/cashAddress.d.ts +12 -0
  157. package/lib/src/common/utxobased/keymanager/cleaners.d.ts +55 -0
  158. package/lib/src/common/utxobased/keymanager/coinmapper.d.ts +2 -0
  159. package/lib/src/common/utxobased/keymanager/keymanager.d.ts +198 -0
  160. package/lib/src/common/utxobased/keymanager/utxopicker/accumulative.d.ts +2 -0
  161. package/lib/src/common/utxobased/keymanager/utxopicker/forceUseUtxo.d.ts +2 -0
  162. package/lib/src/common/utxobased/keymanager/utxopicker/subtractFee.d.ts +2 -0
  163. package/lib/src/common/utxobased/keymanager/utxopicker/types.d.ts +36 -0
  164. package/lib/src/common/utxobased/keymanager/utxopicker/utils.d.ts +15 -0
  165. package/lib/src/common/utxobased/keymanager/utxopicker.d.ts +8 -0
  166. package/lib/src/common/utxobased/network/BlockBook.d.ts +33 -0
  167. package/lib/src/common/utxobased/network/BlockBookAPI.d.ts +163 -0
  168. package/lib/src/common/utxobased/network/Deferred.d.ts +8 -0
  169. package/lib/src/common/utxobased/network/MakeSocketEmitter.d.ts +13 -0
  170. package/lib/src/common/utxobased/network/Socket.d.ts +41 -0
  171. package/lib/src/common/utxobased/network/nodejsWS.d.ts +2 -0
  172. package/lib/src/common/utxobased/network/socketQueue.d.ts +8 -0
  173. package/lib/src/common/utxobased/network/types.d.ts +17 -0
  174. package/lib/src/common/utxobased/network/windowWS.d.ts +2 -0
  175. package/lib/src/firo.d.ts +3 -0
  176. package/lib/src/ftc.d.ts +3 -0
  177. package/lib/src/index.d.ts +4 -0
  178. package/lib/src/ltc.d.ts +3 -0
  179. package/lib/src/tbch.d.ts +3 -0
  180. package/lib/src/tbtc.d.ts +3 -0
  181. package/lib/src/tbtg.d.ts +3 -0
  182. package/lib/src/types.d.ts +6 -0
  183. package/lib/src/util/delay.d.ts +1 -0
  184. package/lib/src/util/filterUndefined.d.ts +1 -0
  185. package/lib/src/util/indexAtProtected.d.ts +5 -0
  186. package/lib/src/util/typeUtil.d.ts +8 -0
  187. package/lib/src/util/undefinedIfEmptyString.d.ts +1 -0
  188. package/lib/src/util/unixTime.d.ts +1 -0
  189. package/lib/tbch.js +15 -0
  190. package/lib/tbtc.js +15 -0
  191. package/lib/tbtg.js +15 -0
  192. package/lib/test/common/fees/calcMinerFeePerByte.spec.d.ts +1 -0
  193. package/lib/test/common/fees/fees.spec.d.ts +1 -0
  194. package/lib/test/common/plugin/currencyPlugin.fixtures/common.d.ts +29 -0
  195. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/bitcoin.d.ts +2 -0
  196. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/bitcoincash.d.ts +2 -0
  197. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/bitcoinsv.d.ts +2 -0
  198. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/digibyte.d.ts +2 -0
  199. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/feathercoin.d.ts +2 -0
  200. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/groestlcoin.d.ts +2 -0
  201. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/litecoin.d.ts +2 -0
  202. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/smartcash.d.ts +2 -0
  203. package/lib/test/common/plugin/currencyPlugin.fixtures/currencies/zcoin.d.ts +2 -0
  204. package/lib/test/common/plugin/currencyPlugin.fixtures/index.d.ts +2 -0
  205. package/lib/test/common/plugin/currencyPlugin.spec.d.ts +1 -0
  206. package/lib/test/common/plugin/makeMetadata.spec.d.ts +1 -0
  207. package/lib/test/common/plugin/serverScores.spec.d.ts +1 -0
  208. package/lib/test/common/utxobased/addressFormat/addressFormatIndex/addressFormat.spec.d.ts +1 -0
  209. package/lib/test/common/utxobased/db/Processor.spec.d.ts +1 -0
  210. package/lib/test/common/utxobased/engine/PaymentRequest.spec.d.ts +1 -0
  211. package/lib/test/common/utxobased/engine/UtxoWalletTools.spec.d.ts +1 -0
  212. package/lib/test/common/utxobased/engine/engine.fixtures/bitcoinTestnet/tests.d.ts +70 -0
  213. package/lib/test/common/utxobased/engine/engine.fixtures/index.d.ts +65 -0
  214. package/lib/test/common/utxobased/engine/engine.spec.d.ts +1 -0
  215. package/lib/test/common/utxobased/keymanager/coins/altcointestfixtures.d.ts +54 -0
  216. package/lib/test/common/utxobased/keymanager/coins/bitcoincashtransactiontest.spec.d.ts +1 -0
  217. package/lib/test/common/utxobased/keymanager/coins/bitcointransactiontest.spec.d.ts +1 -0
  218. package/lib/test/common/utxobased/keymanager/coins/cashaddr.spec.d.ts +1 -0
  219. package/lib/test/common/utxobased/keymanager/coins/checkdatasig.spec.d.ts +1 -0
  220. package/lib/test/common/utxobased/keymanager/coins/groestlcointransactiontest.spec.d.ts +1 -0
  221. package/lib/test/common/utxobased/keymanager/coins/keymanagertest.spec.d.ts +1 -0
  222. package/lib/test/common/utxobased/network/BlockBook.spec.d.ts +1 -0
  223. package/lib/test/util/objectKeys.d.ts +8 -0
  224. package/lib/test/util/testLog.d.ts +3 -0
  225. package/lib/test/utils.d.ts +10 -0
  226. package/lib/types.js +7 -0
  227. package/lib/util/delay.js +4 -0
  228. package/lib/util/filterUndefined.js +4 -0
  229. package/lib/util/indexAtProtected.js +9 -0
  230. package/lib/util/typeUtil.js +9 -0
  231. package/lib/util/undefinedIfEmptyString.js +2 -0
  232. package/lib/util/unixTime.js +2 -0
  233. package/package.json +101 -0
@@ -0,0 +1,690 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _biggystring = require('biggystring'); var bs = _interopRequireWildcard(_biggystring);
2
+ var _cleaners = require('cleaners');
3
+ var _disklet = require('disklet');
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ var _types = require('edge-core-js/types');
17
+
18
+ var _filterUndefined = require('../../../util/filterUndefined');
19
+ var _unixTime = require('../../../util/unixTime');
20
+ var _makeFees = require('../../fees/makeFees');
21
+ var _makeEngineEmitter = require('../../plugin/makeEngineEmitter');
22
+ var _makeMetadata = require('../../plugin/makeMetadata');
23
+
24
+ var _makeProcessor = require('../db/makeProcessor');
25
+
26
+
27
+
28
+ var _ProcessorTransaction = require('../db/Models/ProcessorTransaction');
29
+
30
+
31
+
32
+
33
+
34
+ var _cleaners3 = require('../keymanager/cleaners');
35
+ var _keymanager = require('../keymanager/keymanager');
36
+ var _makeUtxoEngineState = require('./makeUtxoEngineState');
37
+ var _makeUtxoWalletTools = require('./makeUtxoWalletTools');
38
+ var _paymentRequest = require('./paymentRequest');
39
+ var _types7 = require('./types');
40
+ var _getOwnUtxosFromTx = require('./util/getOwnUtxosFromTx');
41
+ var _utils = require('./utils');
42
+
43
+ async function makeUtxoEngine(
44
+ config
45
+ ) {
46
+ const {
47
+ pluginInfo,
48
+ pluginDisklet,
49
+ // Rename to make it explicit that this is sensitive memory
50
+ walletInfo: sensitiveWalletInfo,
51
+ options,
52
+ io,
53
+ pluginState
54
+ } = config
55
+ const {
56
+ walletLocalDisklet,
57
+ walletLocalEncryptedDisklet,
58
+ emitter,
59
+ log
60
+ } = options
61
+ const { currencyInfo, engineInfo, coinInfo } = pluginInfo
62
+ const userSettings = _types7.asUtxoUserSettings.call(void 0, options.userSettings)
63
+
64
+ // We should move the active server list to the engine state,
65
+ // since multiple accounts can be logged in at once,
66
+ // each with a different list of custom servers.
67
+ // The Edge UI only allows for one active login, though,
68
+ // so this is OK for now:
69
+ await pluginState.updateServers(userSettings)
70
+
71
+ const asCurrencyPrivateKey = _cleaners3.asPrivateKey.call(void 0, coinInfo.name, coinInfo.coinType)
72
+ // Private key may be missing for watch-only wallets
73
+ const asMaybeCurrencyPrivateKey = _cleaners.asMaybe.call(void 0, asCurrencyPrivateKey)
74
+ // This walletInfo is desensitized (numb) and should be passed around over the original walletInfo
75
+ const walletInfo = _cleaners3.asNumbWalletInfo.call(void 0, pluginInfo)(sensitiveWalletInfo)
76
+ const { primaryFormat, publicKey, walletFormats } = walletInfo.keys
77
+
78
+ if (
79
+ engineInfo.formats == null ||
80
+ !engineInfo.formats.includes(primaryFormat)
81
+ ) {
82
+ const message = `Wallet format is not supported: ${primaryFormat}`
83
+ log.error(message)
84
+ throw new Error(message)
85
+ }
86
+
87
+ const walletTools = _makeUtxoWalletTools.makeUtxoWalletTools.call(void 0, {
88
+ publicKey,
89
+ coin: coinInfo.name
90
+ })
91
+
92
+ const fees = await _makeFees.makeFees.call(void 0, {
93
+ disklet: pluginDisklet,
94
+ pluginInfo,
95
+ io,
96
+ log: config.options.log
97
+ })
98
+
99
+ const metadata = await _makeMetadata.makeMetadata.call(void 0, {
100
+ disklet: walletLocalDisklet,
101
+ emitter,
102
+ log
103
+ })
104
+ const processor = await _makeProcessor.makeProcessor.call(void 0, {
105
+ disklet: walletLocalDisklet
106
+ })
107
+ const state = _makeUtxoEngineState.makeUtxoEngineState.call(void 0, {
108
+ ...config,
109
+ walletTools,
110
+ walletInfo,
111
+ processor,
112
+ pluginState
113
+ })
114
+
115
+ const fns = {
116
+ async startEngine() {
117
+ emitter.emit(
118
+ _makeEngineEmitter.EngineEvent.WALLET_BALANCE_CHANGED,
119
+ currencyInfo.currencyCode,
120
+ metadata.balance
121
+ )
122
+
123
+ pluginState.addEngine(state)
124
+ await fees.start()
125
+ await state.start()
126
+ },
127
+
128
+ async killEngine() {
129
+ await state.stop()
130
+ fees.stop()
131
+ pluginState.removeEngine(state)
132
+ },
133
+
134
+ getBalance(_opts) {
135
+ return metadata.balance
136
+ },
137
+
138
+ getBlockHeight() {
139
+ return metadata.lastSeenBlockHeight
140
+ },
141
+
142
+ async addCustomToken(_token) {
143
+ return await Promise.resolve(undefined)
144
+ },
145
+
146
+ async addGapLimitAddresses(addresses) {
147
+ return await state.addGapLimitAddresses(addresses)
148
+ },
149
+
150
+ async broadcastTx(transaction) {
151
+ const { otherParams } = transaction
152
+ if (
153
+ _optionalChain([otherParams, 'optionalAccess', _ => _.paymentProtocolInfo, 'optionalAccess', _2 => _2.payment]) != null &&
154
+ _optionalChain([otherParams, 'optionalAccess', _3 => _3.paymentProtocolInfo, 'optionalAccess', _4 => _4.paymentUrl]) != null
155
+ ) {
156
+ const paymentAck = await _paymentRequest.sendPayment.call(void 0,
157
+ io.fetch,
158
+ otherParams.paymentProtocolInfo.paymentUrl,
159
+ otherParams.paymentProtocolInfo.payment
160
+ )
161
+ if (typeof paymentAck === 'undefined') {
162
+ throw new Error(
163
+ `Error when sending to ${otherParams.paymentProtocolInfo.paymentUrl}`
164
+ )
165
+ }
166
+ }
167
+ const id = await state.broadcastTx(transaction)
168
+ if (id !== transaction.txid) {
169
+ throw new Error('broadcast response txid does not match original')
170
+ }
171
+ return transaction
172
+ },
173
+
174
+ async changeUserSettings(userSettings) {
175
+ await pluginState.updateServers(_types7.asUtxoUserSettings.call(void 0, userSettings))
176
+ },
177
+
178
+ async disableTokens(_tokens) {
179
+ return await Promise.resolve(undefined)
180
+ },
181
+
182
+ async dumpData() {
183
+ return {
184
+ walletId: walletInfo.id.split(' - ')[0],
185
+ walletType: walletInfo.type,
186
+ data: {
187
+ walletInfo: {
188
+ pluginType: currencyInfo.pluginId,
189
+ primaryFormat,
190
+ walletFormats
191
+ },
192
+ processorState: await processor.dumpData(),
193
+ pluginState: pluginState.dumpData()
194
+ }
195
+ }
196
+ },
197
+
198
+ async enableTokens(_tokens) {
199
+ return await Promise.resolve(undefined)
200
+ },
201
+
202
+ getDisplayPrivateSeed() {
203
+ const privateKey = asMaybeCurrencyPrivateKey(sensitiveWalletInfo.keys)
204
+ if (privateKey == null) return null
205
+ return privateKey.format === 'bip32'
206
+ ? Buffer.from(privateKey.seed, 'base64').toString('hex')
207
+ : privateKey.seed
208
+ },
209
+
210
+ getDisplayPublicSeed() {
211
+ const xpubs = publicKey.publicKeys
212
+ return Object.values(xpubs)
213
+ .filter(xpub => xpub != null)
214
+ .join('\n')
215
+ },
216
+
217
+ async getEnabledTokens() {
218
+ return await Promise.resolve([])
219
+ },
220
+
221
+ async getFreshAddress(
222
+ _opts
223
+ ) {
224
+ return await state.getFreshAddress()
225
+ },
226
+
227
+ getNumTransactions(_opts) {
228
+ return processor.numTransactions()
229
+ },
230
+
231
+ async getPaymentProtocolInfo(
232
+ paymentProtocolUrl
233
+ ) {
234
+ return await _paymentRequest.getPaymentDetails.call(void 0,
235
+ paymentProtocolUrl,
236
+ currencyInfo.currencyCode,
237
+ io.fetch
238
+ )
239
+ },
240
+
241
+ getTokenStatus(_token) {
242
+ return false
243
+ },
244
+
245
+ async getTransactions(
246
+ options
247
+ ) {
248
+ const txs = _filterUndefined.filterUndefined.call(void 0,
249
+ await processor.fetchTransactions({ options })
250
+ )
251
+ return await Promise.all(
252
+ txs.map(
253
+ async (tx) =>
254
+ await _ProcessorTransaction.toEdgeTransaction.call(void 0, {
255
+ tx,
256
+ currencyCode: currencyInfo.currencyCode,
257
+ pluginInfo,
258
+ processor,
259
+ walletBlockHeight: metadata.lastSeenBlockHeight,
260
+ walletTools
261
+ })
262
+ )
263
+ )
264
+ },
265
+
266
+ async isAddressUsed(address) {
267
+ const scriptPubkey = walletTools.addressToScriptPubkey(address)
268
+ const addressData = await processor.fetchAddress(scriptPubkey)
269
+ if (addressData == null) throw new Error('Address not found in wallet')
270
+ return addressData.used
271
+ },
272
+
273
+ async makeSpend(
274
+ edgeSpendInfo,
275
+ options
276
+ ) {
277
+ const { spendTargets } = edgeSpendInfo
278
+ if (_optionalChain([options, 'optionalAccess', _5 => _5.CPFP]) == null && spendTargets.length < 1) {
279
+ throw new Error('Need to provide Spend Targets')
280
+ }
281
+ // Calculate the total amount to send
282
+ const totalAmountToSend = spendTargets.reduce(
283
+ (sum, { nativeAmount }) => bs.add(sum, _nullishCoalesce(nativeAmount, () => ( '0'))),
284
+ '0'
285
+ )
286
+ const utxos =
287
+ await _asyncNullishCoalesce(await _asyncOptionalChain([options, 'optionalAccess', async _6 => _6.utxos]), async () => (
288
+ ((await processor.fetchUtxos({ utxoIds: [] })) )))
289
+
290
+ if (bs.gt(totalAmountToSend, `${_utils.sumUtxos.call(void 0, utxos)}`)) {
291
+ throw new (0, _types.InsufficientFundsError)(currencyInfo.currencyCode)
292
+ }
293
+
294
+ let targets = []
295
+ const ourReceiveAddresses = []
296
+ for (const target of spendTargets) {
297
+ if (target.publicAddress == null || target.nativeAmount == null) {
298
+ throw new Error('Invalid spend target')
299
+ }
300
+
301
+ // if script exists construct address from script
302
+ if (_optionalChain([target, 'access', _7 => _7.otherParams, 'optionalAccess', _8 => _8.script]) != null) {
303
+ const { script } = target.otherParams
304
+ if (script.type === 'replayProtection') {
305
+ // construct a replay protection p2sh address
306
+ const { publicAddress } = await state.deriveScriptAddress(
307
+ script.type
308
+ )
309
+ targets.push({
310
+ address: publicAddress,
311
+ value: parseInt(target.nativeAmount)
312
+ })
313
+ }
314
+ } else {
315
+ const scriptPubkey = walletTools.addressToScriptPubkey(
316
+ target.publicAddress
317
+ )
318
+ if (processor.fetchAddress(scriptPubkey) != null) {
319
+ ourReceiveAddresses.push(target.publicAddress)
320
+ }
321
+ targets.push({
322
+ address: target.publicAddress,
323
+ value: parseInt(target.nativeAmount)
324
+ })
325
+ }
326
+ }
327
+
328
+ if (targets.length < 1) {
329
+ throw new Error('Need to provide Spend Targets')
330
+ }
331
+
332
+ const freshAddress = await state.getFreshAddress(1)
333
+ const freshChangeAddress =
334
+ _nullishCoalesce(freshAddress.segwitAddress, () => ( freshAddress.publicAddress))
335
+ const setRBF = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _9 => _9.setRBF]), () => ( false))
336
+ const rbfTxid = edgeSpendInfo.rbfTxid
337
+ let maxUtxo
338
+ let feeRate = parseInt(await fees.getRate(edgeSpendInfo))
339
+ if (rbfTxid != null) {
340
+ const [rbfTx] = await processor.fetchTransactions({ txId: rbfTxid })
341
+ if (rbfTx == null) throw new Error('transaction not found')
342
+ // double the fee used for the RBF transaction
343
+ feeRate *= 2
344
+ const rbfInputs = rbfTx.inputs
345
+ const maxInput = rbfInputs.reduce((a, b) =>
346
+ bs.gt(a.amount, b.amount) ? a : b
347
+ )
348
+ const maxId = `${maxInput.txId}_${maxInput.outputIndex}`
349
+ maxUtxo = (await processor.fetchUtxos({ utxoIds: [maxId] }))[0]
350
+ if (maxUtxo == null) {
351
+ log.error('transaction to be replaced found, but not its input utxos')
352
+ throw new Error(
353
+ 'transaction to be replaced found, but not its input utxos'
354
+ )
355
+ }
356
+ }
357
+ if (_optionalChain([options, 'optionalAccess', _10 => _10.CPFP]) != null) {
358
+ const [childTx] = await processor.fetchTransactions({
359
+ txId: _optionalChain([options, 'optionalAccess', _11 => _11.CPFP])
360
+ })
361
+ if (childTx == null) throw new Error('transaction not found')
362
+ const utxos = []
363
+ for (const txid of childTx.ourOuts) {
364
+ const [output] = await processor.fetchUtxos({ utxoIds: [txid] })
365
+ if (output != null) utxos.push(output)
366
+ }
367
+ maxUtxo = utxos.reduce((a, b) => (bs.gt(a.value, b.value) ? a : b))
368
+ // cpfp just sends to change, no target addresses are required
369
+ targets = []
370
+ }
371
+ log.warn(`spend: Using fee rate ${feeRate} sat/B`)
372
+ const subtractFee =
373
+ _optionalChain([options, 'optionalAccess', _12 => _12.subtractFee]) != null ? options.subtractFee : false
374
+ const tx = await _keymanager.makeTx.call(void 0, {
375
+ utxos,
376
+ forceUseUtxo: maxUtxo != null ? [maxUtxo] : [],
377
+ targets,
378
+ feeRate,
379
+ coin: coinInfo.name,
380
+ setRBF,
381
+ freshChangeAddress,
382
+ subtractFee
383
+ })
384
+ if (tx.changeUsed) {
385
+ ourReceiveAddresses.push(freshChangeAddress)
386
+ }
387
+
388
+ let nativeAmount = '0'
389
+ const ourScriptPubkeys = tx.inputs.map(input =>
390
+ input.scriptPubkey.toString('hex')
391
+ )
392
+ for (const output of tx.outputs) {
393
+ const scriptPubkey = output.scriptPubkey.toString('hex')
394
+ const own = await processor.fetchAddress(scriptPubkey)
395
+ if (own == null) {
396
+ // Not our output
397
+ nativeAmount = bs.sub(nativeAmount, output.value.toString())
398
+ } else {
399
+ // Our output
400
+ ourScriptPubkeys.push(scriptPubkey)
401
+ }
402
+ }
403
+
404
+ const networkFee = tx.fee.toString()
405
+ nativeAmount = bs.sub(nativeAmount, networkFee)
406
+
407
+ const otherParams = {
408
+ txJson: { hex: tx.hex },
409
+ psbt: {
410
+ base64: tx.psbtBase64,
411
+ inputs: tx.inputs,
412
+ outputs: tx.outputs
413
+ },
414
+ edgeSpendInfo,
415
+ ourScriptPubkeys
416
+ }
417
+
418
+ const transaction = {
419
+ ourReceiveAddresses,
420
+ otherParams,
421
+ currencyCode: currencyInfo.currencyCode,
422
+ txid: '',
423
+ date: _unixTime.unixTime.call(void 0, ),
424
+ confirmations: 'unconfirmed',
425
+ blockHeight: 0,
426
+ nativeAmount,
427
+ networkFee,
428
+ feeRateUsed: {
429
+ satPerVByte: feeRate
430
+ },
431
+ signedTx: ''
432
+ }
433
+
434
+ return transaction
435
+ },
436
+
437
+ async resyncBlockchain() {
438
+ // Stops the engine
439
+ await fns.killEngine()
440
+
441
+ // Clear cache and state
442
+ await processor.clearAll()
443
+ await pluginState.clearCache()
444
+ await metadata.clear()
445
+ await fees.clearCache()
446
+
447
+ // Refresh the servers for the engine
448
+ await pluginState.refreshServers()
449
+
450
+ // Restart the engine
451
+ await fns.startEngine()
452
+ },
453
+
454
+ async saveTx(edgeTx) {
455
+ const tx = _ProcessorTransaction.fromEdgeTransaction.call(void 0, edgeTx)
456
+ await _makeUtxoEngineState.transactionChanged.call(void 0, {
457
+ emitter,
458
+ pluginInfo,
459
+ processor,
460
+ tx,
461
+ walletBlockHeight: metadata.lastSeenBlockHeight,
462
+ walletTools
463
+ })
464
+ await processor.saveTransaction({
465
+ tx,
466
+ scriptPubkeys: _optionalChain([edgeTx, 'access', _13 => _13.otherParams, 'optionalAccess', _14 => _14.ourScriptPubkeys])
467
+ })
468
+
469
+ /*
470
+ Get the wallet's UTXOs from the new transaction and save them to the processsor.
471
+ */
472
+ const utxos = await _getOwnUtxosFromTx.getOwnUtxosFromTx.call(void 0, engineInfo, processor, tx)
473
+ await Promise.all(utxos.map(async utxo => await processor.saveUtxo(utxo)))
474
+ },
475
+
476
+ async signTx(transaction) {
477
+ const otherParams = transaction.otherParams
478
+ if (otherParams == null) throw new Error('Invalid transaction data')
479
+
480
+ const { psbt, edgeSpendInfo } = otherParams
481
+ if (psbt == null || edgeSpendInfo == null)
482
+ throw new Error('Invalid transaction data')
483
+
484
+ const privateKey = asMaybeCurrencyPrivateKey(sensitiveWalletInfo.keys)
485
+
486
+ if (privateKey == null)
487
+ throw new Error('Cannot sign a transaction for a read-only wallet')
488
+
489
+ // Derive the xprivs on the fly, since we do not persist them
490
+ const xprivKeys = await _utils.fetchOrDeriveXprivFromKeys.call(void 0, {
491
+ privateKey,
492
+ walletLocalEncryptedDisklet,
493
+ coin: coinInfo.name
494
+ })
495
+
496
+ // Use the privateKeys (WIFs) from spendInfo, otherwise get them from the
497
+ // PBST inputs.
498
+ const privateKeys = await (async () => {
499
+ if (edgeSpendInfo.privateKeys != null) {
500
+ return edgeSpendInfo.privateKeys.map(wif =>
501
+ walletTools.getPrivateKeyFromWif(wif)
502
+ )
503
+ } else {
504
+ return await Promise.all(
505
+ psbt.inputs.map(async ({ hash, index }) => {
506
+ const txid = Buffer.from(hash).reverse().toString('hex')
507
+
508
+ const [utxo] = await processor.fetchUtxos({
509
+ utxoIds: [`${txid}_${index}`]
510
+ })
511
+ if (utxo == null) throw new Error('Invalid UTXO')
512
+
513
+ const address = await processor.fetchAddress(utxo.scriptPubkey)
514
+ if (_optionalChain([address, 'optionalAccess', _15 => _15.path]) == null)
515
+ throw new Error('Invalid script pubkey')
516
+
517
+ return walletTools.getPrivateKey({
518
+ path: address.path,
519
+ xprivKeys
520
+ })
521
+ })
522
+ )
523
+ }
524
+ })()
525
+ const signedTx = await _keymanager.signTx.call(void 0, {
526
+ psbtBase64: psbt.base64,
527
+ coin: coinInfo.name,
528
+ privateKeys
529
+ })
530
+ transaction.txid = signedTx.id
531
+ transaction.signedTx = signedTx.hex
532
+
533
+ const { paymentProtocolInfo } =
534
+ _nullishCoalesce(_optionalChain([transaction, 'access', _16 => _16.otherParams, 'optionalAccess', _17 => _17.edgeSpendInfo, 'optionalAccess', _18 => _18.otherParams]), () => ( {}))
535
+ if (paymentProtocolInfo != null) {
536
+ const payment = _paymentRequest.createPayment.call(void 0,
537
+ transaction.signedTx,
538
+ transaction.currencyCode
539
+ )
540
+ Object.assign(transaction.otherParams, {
541
+ paymentProtocolInfo: {
542
+ ...paymentProtocolInfo,
543
+ payment
544
+ }
545
+ })
546
+ }
547
+
548
+ // Update the transaction's date because it's has been modified
549
+ transaction.date = _unixTime.unixTime.call(void 0, )
550
+
551
+ return transaction
552
+ },
553
+
554
+ async sweepPrivateKeys(spendInfo) {
555
+ // Create the promise to return
556
+ let success
557
+
558
+
559
+ let failure
560
+ const end = new Promise((resolve, reject) => {
561
+ success = resolve
562
+ failure = reject
563
+ })
564
+
565
+ // The temporary wallet info should include all formats for the currency
566
+ const allFormats = engineInfo.formats
567
+ if (allFormats == null) {
568
+ throw new Error(
569
+ `Missing formats for wallet type ${currencyInfo.walletType}`
570
+ )
571
+ }
572
+
573
+ const tmpWalletInfo = {
574
+ id: walletInfo.id,
575
+ type: walletInfo.type,
576
+ keys: {
577
+ primaryFormat: walletInfo.keys.primaryFormat,
578
+ walletFormats: allFormats,
579
+ publicKey: {
580
+ publicKeys: {}
581
+ }
582
+ }
583
+ }
584
+
585
+ const privateKeys = _nullishCoalesce(spendInfo.privateKeys, () => ( []))
586
+ if (privateKeys.length < 1) throw new Error('No private keys given')
587
+
588
+ // Make temporary wallet disklet
589
+ const tmpDisklet = _disklet.makeMemoryDisklet.call(void 0, )
590
+ const tmpEncryptedDisklet = _disklet.makeMemoryDisklet.call(void 0, )
591
+ const tmpEmitter = new (0, _makeEngineEmitter.EngineEmitter)()
592
+ const tmpConfig = {
593
+ disklet: tmpDisklet,
594
+ emitter: tmpEmitter,
595
+ log
596
+ }
597
+ const tmpMetadata = await _makeMetadata.makeMetadata.call(void 0, tmpConfig)
598
+ const tmpProcessor = await _makeProcessor.makeProcessor.call(void 0, tmpConfig)
599
+ const tmpWalletTools = _makeUtxoWalletTools.makeUtxoWalletTools.call(void 0, {
600
+ publicKey: tmpWalletInfo.keys.publicKey,
601
+ coin: coinInfo.name
602
+ })
603
+
604
+ // Max spend after imported wallet finishes sync
605
+ tmpEmitter.on(_makeEngineEmitter.EngineEvent.ADDRESSES_CHECKED, async (ratio) => {
606
+ if (ratio === 1) {
607
+ try {
608
+ await tmpState.stop()
609
+
610
+ const tmpUtxos = (await tmpProcessor.fetchUtxos({
611
+ utxoIds: []
612
+ }))
613
+ if (tmpUtxos === null || tmpUtxos.length < 1) {
614
+ throw new Error('Private key has no funds')
615
+ }
616
+ const destAddress = await this.getFreshAddress({})
617
+ const nativeAmount = tmpMetadata.balance
618
+ const options = { utxos: tmpUtxos, subtractFee: true }
619
+ spendInfo.spendTargets = [
620
+ { publicAddress: destAddress.publicAddress, nativeAmount }
621
+ ]
622
+ // @ts-expect-error TODO: TheCharlatan - add option to makeSpend declaration in edge-core-js
623
+ const tx = await this.makeSpend(spendInfo, options)
624
+ success(tx)
625
+ } catch (e) {
626
+ failure(e)
627
+ }
628
+ }
629
+ })
630
+
631
+ const tmpState = _makeUtxoEngineState.makeUtxoEngineState.call(void 0, {
632
+ ...config,
633
+ options: {
634
+ ...config.options,
635
+ walletLocalDisklet: tmpDisklet,
636
+ walletLocalEncryptedDisklet: tmpEncryptedDisklet,
637
+ emitter: tmpEmitter
638
+ },
639
+ pluginInfo: {
640
+ ...pluginInfo,
641
+ engineInfo: {
642
+ ...engineInfo,
643
+ // Disables setLookAhead because we're gonna load from WIFs
644
+ gapLimit: 0
645
+ }
646
+ },
647
+ processor: tmpProcessor,
648
+ walletTools: tmpWalletTools,
649
+ walletInfo: tmpWalletInfo
650
+ })
651
+ await tmpState.loadWifs(privateKeys)
652
+ await tmpState.start()
653
+
654
+ return await end
655
+ },
656
+
657
+ otherMethods: {
658
+ signMessageBase64: async (
659
+ message,
660
+ address
661
+ ) => {
662
+ const scriptPubkey = walletTools.addressToScriptPubkey(address)
663
+ const processorAddress = await processor.fetchAddress(scriptPubkey)
664
+ if (_optionalChain([processorAddress, 'optionalAccess', _19 => _19.path]) == null) {
665
+ throw new Error('Missing address to sign with')
666
+ }
667
+ const privateKey = asMaybeCurrencyPrivateKey(sensitiveWalletInfo.keys)
668
+
669
+ if (privateKey == null)
670
+ throw new Error('Cannot sign a message for a read-only wallet')
671
+
672
+ // Derive the xprivs on the fly, since we do not persist them
673
+ const xprivKeys = await _utils.fetchOrDeriveXprivFromKeys.call(void 0, {
674
+ privateKey,
675
+ walletLocalEncryptedDisklet,
676
+ coin: coinInfo.name
677
+ })
678
+
679
+ const signature = await walletTools.signMessageBase64({
680
+ path: _optionalChain([processorAddress, 'optionalAccess', _20 => _20.path]),
681
+ message,
682
+ xprivKeys
683
+ })
684
+ return signature
685
+ }
686
+ }
687
+ }
688
+
689
+ return fns
690
+ } exports.makeUtxoEngine = makeUtxoEngine;