edge-currency-plugins 1.1.0 → 1.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # edge-currency-plugins
2
+
3
+ ## v1.1.1 (2022-07-12)
4
+
5
+ - Fix: Add feathercoin blockbook server
6
+ - Fix: Engine crashs on fetching server list network failure
7
+ - Fix: Spend issues caused by not saving UTXOs locally without needing a network event
8
+
9
+ ## v1.1.0 (2022-06-29)
10
+
11
+ - Change: Computes the sat/vByte used for a given transaction, and adds feeRateUsed object to the EdgeTransaction output.
12
+
13
+ ## v1.0.0 (2022-06-22)
14
+
15
+ - Fix: Fix a logic error in UtxoEngineState.processUtxos
16
+ - Change: Disable BCH to BSV splitting for now
17
+ - Change: Add detailed logs for Socket errors caused by cleaner
18
+
19
+ ## v1.0.0-rc.6 (2022-06-21)
20
+
21
+ - Fix: Fee rounding errors for some spending cases (particularly sweek keys for segwit wallets)
22
+ - Change: Use WhatsOnChain.com as the block explorer URLs for BSV
23
+
24
+ ## v1.0.0-rc.5 (2022-06-21)
25
+
26
+ - Fix: Insufficient funds error for edge case (max spend on a zero-balance wallet)
27
+
28
+ ## v1.0.0-rc.4 (2022-06-20)
29
+
30
+ - Fix: Avoid redundant ADDRESSES_CHECKED events after initial sync
31
+
32
+ ## v1.0.0-rc.3 (2022-06-20)
33
+
34
+ - Fix: Balance bug after sending transactions
35
+
36
+ ## v1.0.0-rc.2 (2022-06-17)
37
+
38
+ - Fix: Improve connection states and fix reconnection bugs caused when connections are unreliable
39
+ - Fix: Improve BSV address format support for addresses coming from networks
@@ -116,24 +116,21 @@ const asServerListInfo = _cleaners.asObject.call(void 0, _cleaners.asEither.call
116
116
  const fetchServers = async () => {
117
117
  log(`${pluginId} - GET ${serverListInfoUrl}`)
118
118
 
119
- const response = await io.fetch(serverListInfoUrl)
120
- const responseBody = await (async () => {
121
- try {
122
- if (response.ok) {
123
- return await response.json()
124
- }
125
- log(
126
- `${pluginId} - Fetching ${serverListInfoUrl} failed with status ${response.status}`
127
- )
128
- } catch (err) {
129
- log(`${pluginId} - Fetching ${serverListInfoUrl} failed: ${err}`)
119
+ try {
120
+ const response = await io.fetch(serverListInfoUrl)
121
+ if (!response.ok) {
122
+ throw new Error(`Failed with status ${response.status}`)
130
123
  }
131
- return {}
132
- })()
133
-
134
- const serverListInfo = asServerListInfo(responseBody)
124
+ const responseBody = await response.json()
125
+ const serverListInfo = asServerListInfo(responseBody)
135
126
 
136
- return _nullishCoalesce(serverListInfo[currencyCode], () => ( []))
127
+ return _nullishCoalesce(serverListInfo[currencyCode], () => ( []))
128
+ } catch (error) {
129
+ log.warn(
130
+ `${pluginId} - GET ${serverListInfoUrl} failed: ${error.toString()}`
131
+ )
132
+ return []
133
+ }
137
134
  }
138
135
 
139
136
  const refreshServers = async () => {
@@ -371,7 +371,7 @@ var _constants = require('./constants');
371
371
  pluginState.serverScoreDown(uri)
372
372
  _optionalChain([deferredAddressSub, 'optionalAccess', _3 => _3.reject, 'call', _4 => _4()])
373
373
  })
374
- blockbook.watchAddresses(Array.from(addresses), deferred)
374
+ blockbook.watchAddresses(Array.from(serverState.addresses), deferred)
375
375
  }
376
376
 
377
377
  const watchBlocks = (uri) => {
@@ -378,6 +378,7 @@ var _utils = require('./utils');
378
378
  targets,
379
379
  feeRate,
380
380
  coin: coinInfo.name,
381
+ currencyCode: currencyInfo.currencyCode,
381
382
  setRBF,
382
383
  freshChangeAddress,
383
384
  subtractFee
@@ -468,8 +469,8 @@ var _utils = require('./utils');
468
469
  /*
469
470
  Get the wallet's UTXOs from the new transaction and save them to the processsor.
470
471
  */
471
- const utxos = await _getOwnUtxosFromTx.getOwnUtxosFromTx.call(void 0, engineInfo, processor, tx)
472
- await engineState.processUtxos(utxos)
472
+ const ownUtxos = await _getOwnUtxosFromTx.getOwnUtxosFromTx.call(void 0, engineInfo, processor, tx)
473
+ await engineState.processUtxos(ownUtxos)
473
474
  },
474
475
 
475
476
  async signTx(transaction) {
@@ -40,7 +40,6 @@ var _keymanager = require('../keymanager/keymanager');
40
40
 
41
41
 
42
42
 
43
-
44
43
  var _BlockBookAPI = require('../network/BlockBookAPI');
45
44
  var _Deferred = require('../network/Deferred'); var _Deferred2 = _interopRequireDefault(_Deferred);
46
45
 
@@ -386,22 +385,6 @@ var _utils3 = require('./utils');
386
385
  async broadcastTx(transaction) {
387
386
  const txId = await serverStates.broadcastTx(transaction)
388
387
 
389
- /*
390
- After successfully broadcasting the tx, we must mark each UTXO, used as
391
- an input for the tx, as spent so we don't try to reuse the UTXO.
392
- */
393
- const txInputs = _nullishCoalesce(_optionalChain([transaction, 'access', _ => _.otherParams, 'optionalAccess', _2 => _2.psbt, 'access', _3 => _3.inputs]), () => ( []))
394
- for (const input of txInputs) {
395
- const scriptPubkey = Buffer.from(input.scriptPubkey).toString('hex')
396
- const [utxo] = await processor.fetchUtxos({
397
- scriptPubkey
398
- })
399
- if (utxo != null) {
400
- utxo.spent = true
401
- await processor.saveUtxo(utxo)
402
- }
403
- }
404
-
405
388
  return txId
406
389
  },
407
390
  refillServers() {
@@ -447,18 +430,37 @@ var _utils3 = require('./utils');
447
430
  }
448
431
  },
449
432
  async processUtxos(utxos) {
433
+ // Map of scriptPubkey to IUTXOs
450
434
  const utxoMap = new Map()
435
+ const utxoIds = new Set()
436
+
437
+ // Map updated utxos
451
438
  for (const utxo of utxos) {
452
- const utxoSet = _nullishCoalesce(utxoMap.get(utxo.scriptPubkey), () => ( new Set()))
439
+ const utxoSet = _nullishCoalesce(utxoMap.get(utxo.scriptPubkey), () => ( []))
453
440
  if (!utxoMap.has(utxo.scriptPubkey))
454
441
  utxoMap.set(utxo.scriptPubkey, utxoSet)
455
- utxoSet.add(utxo)
442
+ // Add utxo to set for scriptPubkey
443
+ utxoSet.push(utxo)
444
+ // Add UTXO ID set
445
+ utxoIds.add(utxo.id)
456
446
  }
447
+
448
+ // Process UTXO sets for each scriptPubkey in map
457
449
  for (const [scriptPubkey, utxos] of utxoMap.entries()) {
450
+ // Get saved utxo set
451
+ const savedUtxos = await processor.fetchUtxos({ scriptPubkey })
452
+ // Filter UTXOs to de-duplicate (and undefined utxo as a type assert)
453
+ const filteredUtxos = savedUtxos.filter(
454
+ utxo => utxo != null && !utxoIds.has(_optionalChain([utxo, 'optionalAccess', _ => _.id]))
455
+ )
456
+
457
+ // Add updated utxos to utxo set
458
+ const combinedUtxos = [...filteredUtxos, ...utxos]
459
+
458
460
  await processProcessorUtxos({
459
461
  ...commonArgs,
460
462
  scriptPubkey,
461
- utxos
463
+ utxos: combinedUtxos
462
464
  })
463
465
  }
464
466
  }
@@ -1221,25 +1223,71 @@ const processProcessorUtxos = async (
1221
1223
  pluginInfo: { currencyInfo }
1222
1224
  } = args
1223
1225
 
1226
+ const updatedUtxos = Object.fromEntries(
1227
+ [...utxos].map(utxo => [utxo.id, utxo])
1228
+ )
1229
+ const utxoIdsToRemove = []
1224
1230
  const currentUtxos = await processor.fetchUtxos({ scriptPubkey })
1225
- const currentUtxoIds = []
1231
+
1232
+ //
1233
+ // Modify existing UTXO set
1234
+ //
1235
+
1226
1236
  let oldBalance = '0'
1227
1237
  for (const utxo of currentUtxos) {
1228
1238
  if (utxo == null)
1229
1239
  throw new Error(
1230
1240
  'Unexpected undefined utxo when processing unspent transactions'
1231
1241
  )
1232
- oldBalance = _biggystring.add.call(void 0, utxo.value, oldBalance)
1233
- currentUtxoIds.push(utxo.id)
1242
+ if (!utxo.spent) {
1243
+ // Accumulate over the current address balance
1244
+ oldBalance = _biggystring.add.call(void 0, utxo.value, oldBalance)
1245
+ }
1246
+
1247
+ // If the UTXO isn't present in the update UTXO set, then it is spent.
1248
+ if (updatedUtxos[utxo.id] == null) {
1249
+ if (utxo.blockHeight > 0) {
1250
+ // Delete the UTXO from the database if it's spent and confirmed
1251
+ utxoIdsToRemove.push(utxo.id)
1252
+ } else {
1253
+ // Otherwise just mark it as spent.
1254
+ updatedUtxos[utxo.id] = { ...utxo, spent: true }
1255
+ }
1256
+ } else {
1257
+ /*
1258
+ If the UTXO is present in the updated UTXO set, enforce that the UTXO
1259
+ remains spent in the new UTXO set. This means, we will never mark a UTXO
1260
+ as unspent again. UTXOs only become unspent again if the tx is dropped
1261
+ which shall be affected by another routine.
1262
+ */
1263
+ // TODO: To fix this logic for dropped-tx, add a condition which uses the
1264
+ // network's block-height to determine whether to set it back as unspend
1265
+ updatedUtxos[utxo.id].spent = utxo.spent || updatedUtxos[utxo.id].spent
1266
+ }
1234
1267
  }
1235
- await processor.removeUtxos(currentUtxoIds)
1268
+
1269
+ // Remove any spent UTXOs that have confirmations
1270
+ await processor.removeUtxos(utxoIdsToRemove)
1271
+
1272
+ //
1273
+ // Save updated UTXO set
1274
+ //
1236
1275
 
1237
1276
  let newBalance = '0'
1238
- for (const utxo of Array.from(utxos)) {
1239
- newBalance = _biggystring.add.call(void 0, utxo.value, newBalance)
1277
+ for (const utxo of Object.values(updatedUtxos)) {
1278
+ if (!utxo.spent) {
1279
+ // Accumulate over the new address balance
1280
+ newBalance = _biggystring.add.call(void 0, utxo.value, newBalance)
1281
+ }
1282
+ // Save new UTXOs
1240
1283
  await processor.saveUtxo(utxo)
1241
1284
  }
1242
1285
 
1286
+ //
1287
+ // Balance update
1288
+ //
1289
+
1290
+ // Address balance and emit address balance change event
1243
1291
  const diff = _biggystring.sub.call(void 0, newBalance, oldBalance)
1244
1292
  if (diff !== '0') {
1245
1293
  log('balance changed:', { scriptPubkey, diff })
@@ -1392,19 +1440,19 @@ const processRawUtxo = async (
1392
1440
  }
1393
1441
 
1394
1442
  const addToProcessorUtxoCache = (
1395
- processorUtxosCache,
1443
+ processorUtxoCache,
1396
1444
  path,
1397
1445
  scriptPubkey,
1398
1446
  requiredCount,
1399
1447
  utxo
1400
1448
  ) => {
1401
- const processorUtxos = _nullishCoalesce(processorUtxosCache[scriptPubkey], () => ( {
1402
- utxos: new Set(),
1449
+ const processorUtxos = _nullishCoalesce(processorUtxoCache[scriptPubkey], () => ( {
1450
+ utxos: [],
1403
1451
  processing: false,
1404
1452
  path,
1405
1453
  full: false
1406
1454
  }))
1407
- if (utxo != null) processorUtxos.utxos.add(utxo)
1408
- processorUtxosCache[scriptPubkey] = processorUtxos
1409
- processorUtxos.full = processorUtxos.utxos.size >= requiredCount
1455
+ if (utxo != null) processorUtxos.utxos.push(utxo)
1456
+ processorUtxoCache[scriptPubkey] = processorUtxos
1457
+ processorUtxos.full = processorUtxos.utxos.length >= requiredCount
1410
1458
  }
@@ -12,7 +12,29 @@ var _utils = require('../utils');
12
12
  processor,
13
13
  tx
14
14
  ) => {
15
- const utxos = []
15
+ const ownUtxos = []
16
+
17
+ //
18
+ // Spent UTXOs (Inputs)
19
+ //
20
+
21
+ const inputUtxoIds = tx.inputs.map(
22
+ input => `${input.txId}_${input.outputIndex}`
23
+ )
24
+ const inputUtxos = await processor.fetchUtxos({
25
+ utxoIds: inputUtxoIds
26
+ })
27
+ for (const utxo of inputUtxos) {
28
+ if (utxo == null) continue
29
+ // Must create a new IUTXO object when mutating processor objects because
30
+ // memlet may keep a reference in memory.
31
+ ownUtxos.push({ ...utxo, spent: true })
32
+ }
33
+
34
+ //
35
+ // Unspent UTXOs (Outputs)
36
+ //
37
+
16
38
  for (const output of tx.outputs) {
17
39
  const scriptPubkey = output.scriptPubkey
18
40
  const address = await processor.fetchAddress(scriptPubkey)
@@ -46,9 +68,10 @@ var _utils = require('../utils');
46
68
  blockHeight: tx.blockHeight,
47
69
  spent: false
48
70
  }
49
- utxos.push(utxo)
71
+ ownUtxos.push(utxo)
50
72
  }
51
73
  }
52
74
  }
53
- return utxos
75
+
76
+ return ownUtxos
54
77
  }; exports.getOwnUtxosFromTx = getOwnUtxosFromTx
@@ -236,4 +236,7 @@ var _keymanager = require('../keymanager/keymanager');
236
236
  }; exports.parsePathname = parsePathname
237
237
 
238
238
  const sumUtxos = (utxos) =>
239
- utxos.reduce((sum, { value }) => bs.add(sum, value), '0'); exports.sumUtxos = sumUtxos
239
+ utxos.reduce(
240
+ (sum, { spent, value }) => (spent ? sum : bs.add(sum, value)),
241
+ '0'
242
+ ); exports.sumUtxos = sumUtxos
@@ -16,7 +16,7 @@ var _constants = require('../../constants');
16
16
  // Configuration options:
17
17
  defaultSettings: {
18
18
  customFeeSettings: ['satPerByte'],
19
- blockbookServers: [],
19
+ blockbookServers: ['wss://blockbook.feathercoin.com'],
20
20
  enableCustomServers: false
21
21
  },
22
22
  customFeeTemplate: [
@@ -229,6 +229,7 @@ var VerifyAddressEnum; (function (VerifyAddressEnum) {
229
229
 
230
230
 
231
231
 
232
+
232
233
 
233
234
 
234
235
  function bip43PurposeNumberToTypeEnum(
@@ -933,7 +934,7 @@ const wifToPrivateKeyInternal = (
933
934
  changeScript
934
935
  })
935
936
  if (result.inputs == null || result.outputs == null) {
936
- throw new (0, _types.InsufficientFundsError)(args.coin)
937
+ throw new (0, _types.InsufficientFundsError)(args.currencyCode)
937
938
  }
938
939
 
939
940
  const sortedInputs = _bip69.sortInputs.call(void 0, result.inputs)
@@ -74,7 +74,7 @@ interface ProcessorUtxoCache {
74
74
  [key: string]: {
75
75
  processing: boolean;
76
76
  full: boolean;
77
- utxos: Set<IUTXO>;
77
+ utxos: IUTXO[];
78
78
  path: ChangePath;
79
79
  };
80
80
  }
@@ -128,6 +128,7 @@ export interface MakeTxArgs {
128
128
  feeRate: number;
129
129
  setRBF: boolean;
130
130
  coin: string;
131
+ currencyCode: string;
131
132
  freshChangeAddress: string;
132
133
  subtractFee?: boolean;
133
134
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edge-currency-plugins",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Edge currency plugins to fetch and process wallet accounts, balances and transactions.",
5
5
  "repository": "https://github.com/EdgeApp/edge-currency-plugins",
6
6
  "license": "MIT",