Skip to content

Commit cd55770

Browse files
committed
2 parents e427916 + aef6465 commit cd55770

File tree

165 files changed

+1975
-1917
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

165 files changed

+1975
-1917
lines changed

eslint.config.mjs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@ export default defineConfig([
5151
'no-undef': 'error',
5252
'no-async-promise-executor': 'off',
5353
'semi': ['error', 'always'],
54-
'indent': ['error', 2, { SwitchCase: 1 }],
5554
'no-case-declarations': 'off',
5655
'no-bitwise': 'error',
5756
'spaced-comment': ['error', 'always', { exceptions: ['-', '+'] }],
5857
'@stylistic/object-curly-spacing': ['error', 'always'],
58+
'@stylistic/indent': ['error', 2, { SwitchCase: 1 }],
5959
'object-curly-spacing': ['error', 'always'],
6060
'key-spacing': ['error', { beforeColon: false, afterColon: true }],
6161
'comma-spacing': ['error', { before: false, after: true }],
@@ -101,6 +101,8 @@ export default defineConfig([
101101
},
102102
rules: {
103103
'@typescript-eslint/no-unused-vars': 'off',
104+
'@typescript-eslint/no-this-alias': 'warn',
105+
'@typescript-eslint/no-unused-expressions': 'off',
104106
'sort-imports': 'off',
105107
'import/order': 'off'
106108
}

packages/bitcore-lib/lib/address.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -593,7 +593,7 @@ Address.getValidationError = function(data, network, type) {
593593
*
594594
* @param {string} data - The encoded data
595595
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
596-
* @param {string} type - The type of address: 'script' or 'pubkey'
596+
* @param {string} [type] - The type of address: 'script' or 'pubkey'
597597
* @returns {boolean} The corresponding error message
598598
*/
599599
Address.isValid = function(data, network, type) {

packages/bitcore-lib/lib/privatekey.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ const TaggedHash = require('./crypto/taggedhash');
3030
* var imported = PrivateKey.fromWIF(exported);
3131
* ```
3232
*
33-
* @param {string} data - The encoded data in various formats
34-
* @param {Network|string=} network - a {@link Network} object, or a string with the network name
33+
* @param {string} [data] - The encoded data in various formats
34+
* @param {Network|string=} [network] - a {@link Network} object, or a string with the network name
3535
* @returns {PrivateKey} A new valid instance of an PrivateKey
3636
* @constructor
3737
*/

packages/bitcore-lib/lib/publickey.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ const TaggedHash = require('./crypto/taggedhash');
2727
* var imported = PublicKey.fromString(exported);
2828
* ```
2929
*
30-
* @param {string} data - The encoded data in various formats
31-
* @param {Object} extra - additional options
30+
* @param {string|PrivateKey} [data] - The encoded data in various formats
31+
* @param {Object} [extra] - additional options
3232
* @param {Network=} extra.network - Which network should the address for this public key be for
3333
* @param {String=} extra.compressed - If the public key is compressed
3434
* @returns {PublicKey} A new valid instance of an PublicKey
@@ -467,8 +467,8 @@ PublicKey.prototype._getID = function _getID() {
467467
/**
468468
* Will return an address for the public key
469469
*
470-
* @param {String|Network=} network - Which network should the address be for
471-
* @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash'
470+
* @param {String|Network=} [network] - Which network should the address be for
471+
* @param {string} [type] - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash'
472472
* @returns {Address} An address generated from the public key
473473
*/
474474
PublicKey.prototype.toAddress = function(network, type) {

packages/bitcore-node/package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@
4242
"api:cluster": "npm run tsc && node build/src/workers/api.js --CLUSTER true",
4343
"pruning": "npm run tsc && node build/src/workers/pruning.js --EXIT true",
4444
"p2p": "npm run tsc && node build/src/workers/p2p.js",
45-
"precommit": "echo 'TODO: npm run fix && npm run lint'",
4645
"lint": "eslint .",
47-
"fix": "eslint --fix --quiet .",
46+
"fix:errors": "eslint --fix --quiet .",
47+
"fix:all": "eslint --fix .",
48+
"precommit": "npm run lint; npm run fix:errors",
4849
"test:scripts": "npx mocha scripts/test"
4950
},
5051
"nyc": {

packages/bitcore-node/scripts/addBlockFees.js

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
#!/usr/bin/env node
22

3-
const { Storage } = require('../build/src/services/storage');
4-
const { BitcoinBlockStorage } = require('../build/src/models/block')
3+
import { BitcoinBlockStorage } from '../build/src/models/block';
4+
import { Storage } from '../build/src/services/storage';
55

66
function usage(errMsg) {
77
console.log('USAGE: ./addBlockFees [options]');
88
console.log('[OPTIONS]:');
99
console.log(' --chain <value> BTC, BCH, DOGE, or LTC');
1010
console.log(' --network <value> mainnet, testnet, or regtest');
11-
console.log(' --remove remove all fee data from chain on network')
12-
console.log(' --reset remove and re add all fee data')
13-
console.log(' --verbose enable verbose logging')
14-
console.log(' --print-number number of times to print fee data insertions (default 20)')
15-
console.log(' --pause-every number of blocks sync before pausing 50ms (default 10)')
11+
console.log(' --remove remove all fee data from chain on network');
12+
console.log(' --reset remove and re add all fee data');
13+
console.log(' --verbose enable verbose logging');
14+
console.log(' --print-number number of times to print fee data insertions (default 20)');
15+
console.log(' --pause-every number of blocks sync before pausing 50ms (default 10)');
1616
if (errMsg) {
1717
console.error(errMsg);
1818
}
@@ -55,13 +55,13 @@ Storage.start()
5555
console.log(`Removing fee data from ${prevBlocksWithFeesCount} of ${totalBlocks} blocks on ${chain} ${network}`);
5656
await BitcoinBlockStorage.collection.updateMany({ chain, network }, { $unset: { feeData: {} } });
5757
const seconds = (Date.now() - startTime) / 1000;
58-
console.log(`Finished in ${seconds} seconds | ${(prevBlocksWithFeesCount / seconds).toFixed(2)} blocks/sec`)
58+
console.log(`Finished in ${seconds} seconds | ${(prevBlocksWithFeesCount / seconds).toFixed(2)} blocks/sec`);
5959

6060
const blocksWithFeesCount = await BitcoinBlockStorage.collection.countDocuments({ chain, network, feeData: { $exists: true } });
6161
if (blocksWithFeesCount == 0) {
62-
console.log('Successfully removed fee data from blocks')
62+
console.log('Successfully removed fee data from blocks');
6363
} else {
64-
console.log(`${blocksWithFeesCount} blocks still have fee data`)
64+
console.log(`${blocksWithFeesCount} blocks still have fee data`);
6565
if (verbose) {
6666
const blocksWithFees = await BitcoinBlockStorage.collection.find({ chain, network, feeData: { $exists: true } }).toArray();
6767
process.stdout.write('Blocks with fees:');
@@ -75,7 +75,7 @@ Storage.start()
7575
return;
7676
}
7777

78-
const prevBlocksWithoutFeesCount = await BitcoinBlockStorage.collection.countDocuments({ chain, network, feeData: { $exists: false }});
78+
const prevBlocksWithoutFeesCount = await BitcoinBlockStorage.collection.countDocuments({ chain, network, feeData: { $exists: false } });
7979
if (prevBlocksWithoutFeesCount === 0) {
8080
console.log(`${chain} ${network} already has fee data`);
8181
return;
@@ -87,7 +87,7 @@ Storage.start()
8787
let feeDataAddedCount = 0;
8888

8989
const stream = BitcoinBlockStorage.collection
90-
.find({ chain, network, feeData: { $exists: false } }, { projection: { height: 1, _id: 0 }})
90+
.find({ chain, network, feeData: { $exists: false } }, { projection: { height: 1, _id: 0 } })
9191
.addCursorFlag('noCursorTimeout', true)
9292
.stream();
9393

@@ -96,7 +96,7 @@ Storage.start()
9696
const fee = await BitcoinBlockStorage.getBlockFee({ chain, network, blockId: height });
9797
feeDataAddedCount++;
9898
if (feeDataAddedCount < prevBlocksWithoutFeesCount) {
99-
BitcoinBlockStorage.collection.updateOne({ chain, network, height }, { $set: { feeData: fee } })
99+
BitcoinBlockStorage.collection.updateOne({ chain, network, height }, { $set: { feeData: fee } });
100100
// Resolve promise on last block
101101
} else {
102102
await BitcoinBlockStorage.collection.updateOne({ chain, network, height }, { $set: { feeData: fee } });
@@ -107,11 +107,11 @@ Storage.start()
107107
await sleep(50);
108108
}
109109

110-
console.log('100%')
110+
console.log('100%');
111111
const seconds = (Date.now() - startTime) / 1000;
112-
console.log(`Finished in ${seconds} seconds | ${(prevBlocksWithoutFeesCount / seconds).toFixed(2)} blocks/sec`)
112+
console.log(`Finished in ${seconds} seconds | ${(prevBlocksWithoutFeesCount / seconds).toFixed(2)} blocks/sec`);
113113

114-
const blocksWithoutFeesCount = await BitcoinBlockStorage.collection.countDocuments({ chain, network, feeData: { $exists: false }});
114+
const blocksWithoutFeesCount = await BitcoinBlockStorage.collection.countDocuments({ chain, network, feeData: { $exists: false } });
115115
if (blocksWithoutFeesCount == 0) {
116116
console.log(`Successfully added fee data to blocks on ${chain} ${network}`);
117117
} else {

packages/bitcore-node/scripts/addGenesisBlock.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
#!/usr/bin/env node
22

3+
import * as readline from 'readline';
4+
import Config from '../build/src/config';
5+
import { BitcoinBlockStorage } from '../build/src/models/block';
6+
import { BitcoinP2PWorker } from '../build/src/modules/bitcoin/p2p';
7+
import { Storage } from '../build/src/services/storage';
38

4-
const { Storage } = require('../build/src/services/storage');
5-
const { BitcoinBlockStorage } = require('../build/src/models/block');
6-
const Config = require('../build/src/config');
7-
const { BitcoinP2PWorker } = require('../build/src/modules/bitcoin/p2p');
8-
9-
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
10-
9+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1110

1211
function usage(errMsg) {
1312
console.log('USAGE: ./addGenesisBlock.js [options]');
@@ -35,7 +34,7 @@ if (!['BTC', 'BCH', 'DOGE', 'LTC'].includes(chain) || !['mainnet', 'testnet', 'r
3534

3635
const real = !!args.find(a => a === '--real');
3736
console.log('Real:', real);
38-
real && console.log('~~~~ REAL RUN ~~~~');
37+
if (real) console.log('~~~~ REAL RUN ~~~~');
3938

4039
let p2pWorker;
4140

@@ -79,7 +78,8 @@ Storage.start()
7978
network
8079
});
8180
const cnt = await BitcoinBlockStorage.collection.countDocuments({ chain, network, height: 0 });
82-
cnt == 1 ? console.log('Genesis block added') : console.log(`Somethings wrong. There are ${cnt} genesis blocks in the db`);
81+
if (cnt == 1) console.log('Genesis block added');
82+
else console.log(`Somethings wrong. There are ${cnt} genesis blocks in the db`);
8383
} else {
8484
console.log('Dry run. Genesis block not added.');
8585
}
@@ -89,4 +89,4 @@ Storage.start()
8989
rl.close();
9090
p2pWorker?.disconnect();
9191
Storage.stop();
92-
})
92+
});

packages/bitcore-node/scripts/findReplacedTx.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
#!/usr/bin/env node
22

3-
const { Storage } = require('../build/src/services/storage');
4-
const { TransactionStorage } = require('../build/src/models/transaction');
3+
import { TransactionStorage } from '../build/src/models/transaction';
4+
import { Storage } from '../build/src/services/storage';
55

66
function usage(errMsg) {
77
console.log('USAGE: ./findReplacedTx.js <options>');
88
console.log('OPTIONS:');
99
console.log(' --chain <value> REQUIRED - e.g. BTC, BCH, DOGE, LTC...');
1010
console.log(' --network <value> REQUIRED - e.g. mainnet, testnet3, regtest...');
1111
console.log(' --txid <value> REQUIRED Transaction Id that replaced');
12-
console.log(' --window [value] Minutes to look back (default: 10)')
12+
console.log(' --window [value] Minutes to look back (default: 10)');
1313
if (errMsg) {
1414
console.log('\nERROR: ' + errMsg);
1515
}
@@ -49,7 +49,7 @@ Storage.start()
4949
}
5050
const $lt = new Date(confirmedTx.blockTimeNormalized);
5151
const $gt = new Date($lt.getTime() - (1000 * 60 * windowMins));
52-
const related = TransactionStorage.collection.find({ chain, network, blockTimeNormalized: { $lt, $gt }, blockHeight: -3 });
52+
const related = TransactionStorage.collection.find({ chain, network, blockTimeNormalized: { $lt, $gt }, blockHeight: -3 });
5353
for await (const tx of related) {
5454
if (tx.replacedByTxid === txid) {
5555
console.log(tx);

packages/bitcore-node/scripts/fixOldSpentTxid.js

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env node
2+
// eslint-disable-next-line spaced-comment
23
/****************************************
34
*** This migration script will fix historical instances
45
*** of an issue where coins that were used in a now invalid
@@ -12,22 +13,23 @@
1213
*** select the chain and network to run against.
1314
*** You must have valid RPC connection specified in bitcore.config.json.
1415
********************************************/
15-
const { CryptoRpc } = require('crypto-rpc');
16-
const { TransactionStorage } = require('../build/src/models/transaction');
17-
const { CoinStorage } = require('../build/src/models/coin');
18-
const fs = require('fs');
16+
import fs from 'fs';
17+
import { CryptoRpc } from 'crypto-rpc';
18+
import Config from '../build/src/config';
19+
import { CoinStorage } from '../build/src/models/coin';
20+
import { TransactionStorage } from '../build/src/models/transaction';
21+
import { Storage } from '../build/src/services/storage';
22+
import { wait } from '../build/src/utils/wait';
23+
1924
const fsPromises = fs.promises;
20-
const { Storage } = require('../build/src/services/storage');
21-
const { wait } = require('../build/src/utils/wait');
22-
const Config = require('../build/src/config');
2325

2426
class Migration {
2527
constructor({ transactionModel = TransactionStorage, coinModel = CoinStorage } = {}) {
2628
this.transactionModel = transactionModel;
2729
this.coinModel = coinModel;
2830
}
2931
async connect() {
30-
console.log("Attempting connection to the database...")
32+
console.log('Attempting connection to the database...');
3133
try {
3234
if (!Storage.connected) {
3335
await Storage.start();
@@ -39,23 +41,23 @@ class Migration {
3941
}
4042

4143
async endProcess() {
42-
if (Storage.connected){
44+
if (Storage.connected) {
4345
await Storage.stop();
4446
}
4547
process.exit();
4648
}
4749

4850
processArgs(argv) {
49-
let retArgs = {
51+
const retArgs = {
5052
dryrun: true,
5153
chain: '',
5254
network: ''
5355
};
54-
let args = argv.slice(2);
56+
const args = argv.slice(2);
5557

5658
const helpIdx = args.findIndex(i => i == '--help');
5759
if (helpIdx >= 0) {
58-
console.log("Usage: node fixOldSpentTxid.js --chain [CHAIN] --network [NETWORK] --dryrun [BOOL - default: true]");
60+
console.log('Usage: node fixOldSpentTxid.js --chain [CHAIN] --network [NETWORK] --dryrun [BOOL - default: true]');
5961
this.endProcess();
6062
}
6163

@@ -65,8 +67,8 @@ class Migration {
6567
args[dryRunIdx + 1] == undefined || args[dryRunIdx + 1] == 'true'
6668
? true
6769
: args[dryRunIdx + 1] == 'false'
68-
? false
69-
: true;
70+
? false
71+
: true;
7072
}
7173

7274
const chainIdx = args.findIndex(i => i == '--chain');
@@ -80,7 +82,7 @@ class Migration {
8082
}
8183

8284
if (!retArgs.chain || !retArgs.network) {
83-
console.log("You must specify a chain and network for the script to run on. Use --help for more info.");
85+
console.log('You must specify a chain and network for the script to run on. Use --help for more info.');
8486
this.endProcess();
8587
}
8688

@@ -89,14 +91,14 @@ class Migration {
8991

9092
async runScript(args) {
9193
console.log('Running script with these args: ', args);
92-
let output = {};
93-
let actuallySpent = {};
94+
const output = {};
95+
const actuallySpent = {};
9496
const { chain, network, dryrun } = args;
9597
console.log(`Checking records for ${chain}:${network}`);
9698
// Get all unspent coins that have a spentTxid specified
9799
const stream = this.coinModel.collection
98100
.find(
99-
{ chain, network, mintHeight: { $gt: -1 }, spentHeight: -2, spentTxid: {$exists: true, $ne: null, $ne: ""} } // -2 is unspent status
101+
{ chain, network, mintHeight: { $gt: -1 }, spentHeight: -2, spentTxid: { $exists: true, $and: [{ $ne: null }, { $ne: '' }] } } // -2 is unspent status
100102
)
101103
.addCursorFlag('noCursorTimeout', true);
102104

@@ -134,7 +136,7 @@ class Migration {
134136
});
135137
isUnspent = !!coinData;
136138
} catch (e) {
137-
if (e.message && e.message.match(`No info found for ${data.mintTxid}`)){
139+
if (e.message && e.message.match(`No info found for ${data.mintTxid}`)) {
138140
// Coin must be spent or actually pending in mempool - log so that we can diagnose, this is unexpected
139141
if (actuallySpent[`${chain}-${network}`]) {
140142
actuallySpent[`${chain}-${network}`].push(data);
@@ -170,20 +172,20 @@ class Migration {
170172
console.log(`Writing output to ${filename}`);
171173
try {
172174
await fsPromises.writeFile(filename, JSON.stringify(output));
173-
} catch (e) {
175+
} catch {
174176
// write to stdout
175177
console.log('Failed to write output to file. Writing to stdout instead.');
176178
console.log(output);
177179
}
178180
// if we found some spent coins mislabelled as unspent, log it
179181
if (actuallySpent[`${chain}-${network}`]) {
180-
console.log("WARNING: Found some coins that were marked unspent that were actually spent.");
182+
console.log('WARNING: Found some coins that were marked unspent that were actually spent.');
181183
const date = new Date().getTime();
182184
const filename = `fixOldSpentTxid-actually-spent-${chain}-${network}-${date}.log`;
183185
console.log(`Writing them to ${filename}`);
184186
try {
185187
await fsPromises.writeFile(filename, JSON.stringify(actuallySpent));
186-
} catch (e) {
188+
} catch {
187189
// write to stdout
188190
console.log('Failed to write output to file. Writing to stdout instead.');
189191
console.log(output);
@@ -208,8 +210,8 @@ migration
208210
.catch(err => {
209211
console.error(err);
210212
migration.endProcess()
211-
.catch(err => {
212-
console.error(err);
213-
process.exit(1);
214-
});
213+
.catch(err => {
214+
console.error(err);
215+
process.exit(1);
216+
});
215217
});

0 commit comments

Comments
 (0)