Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ on:
- sprint
- dev
- main
- release/2.6.4
pull_request:
branches:
- sprint
- codex/r3-release-baseline-to-sprint
- dev
- main
- release/2.6.4

permissions:
actions: read
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ on:
- dev
- main
- release/2.6.3
- release/2.6.4
pull_request:
branches:
- sprint
- codex/r3-release-baseline-to-sprint
- dev
- main
- release/2.6.3
- release/2.6.4

permissions:
contents: read
Expand Down
149 changes: 111 additions & 38 deletions tests/services/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,88 @@ import ElectrumClient from '../../src/services/electrum/client';
import { predefinedTestnetNodes } from '../../src/services/electrum/predefinedNodes';
import * as bitcoinJS from 'bitcoinjs-lib';

const mockClients: any[] = [];
const mockTxid = '24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8';

// Exercise the real ElectrumClient facade against deterministic protocol replies.
// A public Electrum server is outside the control of CI.
jest.mock('electrum-client', () => ({
__esModule: true,
default: jest.fn().mockImplementation((_net, _tls, _port, host) => {
const client = {
host,
initElectrum: jest.fn(async () => {
if (host === 'blackie.c3-soft.com') {
throw new Error('connect ECONNREFUSED 127.0.0.1:50002');
}
return ['fixture-server', '1.4'];
}),
close: jest.fn(),
onError: null,
server_ping: jest.fn(async () => undefined),
server_features: jest.fn(async () => ({
server_version: 'fixture-server',
protocol_min: '1.4',
protocol_max: '1.4.3',
})),
blockchainScripthash_listunspentBatch: jest.fn(async (hashes) =>
hashes.map((param, index) => ({
param,
result: index === 0 ? [{ tx_hash: mockTxid, tx_pos: 1, value: 12345, height: 100 }] : [],
}))
),
blockchainScripthash_getHistoryBatch: jest.fn(async (hashes) =>
hashes.map((param, index) => ({
param,
result: index === 0 ? [{ tx_hash: mockTxid, height: 100 }] : [],
}))
),
blockchainEstimatefee: jest.fn(async () => 0.00002),
blockchainTransaction_getBatch: jest.fn(async (txids) =>
txids.map((param) => ({
param,
result: {
txid: param,
hex: 'fixture-hex',
vout: [{ scriptPubKey: { address: 'tb1qfixture' } }],
},
}))
),
};
mockClients.push(client);
return client;
}),
}));

jest.mock('src/store/store', () => ({
store: {
getState: () => ({
settings: {
bitcoinNetwork: 'testnet',
},
settings: { bitcoinNetworkType: 'TESTNET' },
}),
},
}));

beforeAll(async () => {
try {
ElectrumClient.setActivePeer(predefinedTestnetNodes);
await ElectrumClient.connect();
} catch (err) {
console.log('failed to connect to Electrum:', err);
process.exit(1);
}
const onlineNode = {
...predefinedTestnetNodes[0],
id: 337,
host: 'electrum-fixture.test',
isConnected: true,
};
const offlineNode = {
...predefinedTestnetNodes[0],
isConnected: true,
};
const addresses = [
'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
];

beforeEach(async () => {
mockClients.length = 0;
ElectrumClient.setActivePeer([onlineNode], onlineNode);
ElectrumClient.resetCurrentPeerIndex();
const connection = await ElectrumClient.connect();
assert.ok(connection.connected);
});

afterAll(() => {
Expand All @@ -30,23 +94,33 @@ afterAll(() => {
describe('ElectrumClient', () => {
describe('Connection Tests', () => {
it('should test connection successfully', async () => {
const result = await ElectrumClient.testConnection(predefinedTestnetNodes[0]);
const result = await ElectrumClient.testConnection(onlineNode);
assert.ok(result.connected);
});

it('should fail connection when node is unreachable', async () => {
const unreachableNode = { ...predefinedTestnetNodes[0], host: 'invalid.host' };
const result = await ElectrumClient.testConnection(unreachableNode);
const result = await ElectrumClient.testConnection(offlineNode);
assert.ok(!result.connected);
assert.ok(result.error);
assert.strictEqual(result.errorType, 'network');
});

it('should reconnect to the next peer when connection fails', async () => {
ElectrumClient.setActivePeer(predefinedTestnetNodes);
ElectrumClient.setActivePeer([offlineNode, onlineNode], offlineNode);
ElectrumClient.resetCurrentPeerIndex();
const result = await ElectrumClient.connect();
assert.ok(result.connected);
assert.strictEqual(result.connectedTo, onlineNode.host);
assert.strictEqual(ElectrumClient.getActivePeer()?.host, onlineNode.host);

assert.ok(mockClients.some((client) => client.host === offlineNode.host));
});

it('should reconnect after explicit disconnection', async () => {
ElectrumClient.forceDisconnect();
const result = await ElectrumClient.reconnect();
assert.ok(result.connected);
assert.ok(result.connectedTo);
assert.strictEqual(result.connectedTo, onlineNode.host);
});
});

Expand All @@ -60,51 +134,50 @@ describe('ElectrumClient', () => {
describe('Feature Tests', () => {
it('should retrieve server features', async () => {
const features = await ElectrumClient.serverFeatures();
assert.ok(features.server_version);
assert.ok(features.protocol_min);
assert.ok(features.protocol_max);
assert.strictEqual(features.server_version, 'fixture-server');
assert.strictEqual(features.protocol_min, '1.4');
assert.strictEqual(features.protocol_max, '1.4.3');
});
});

describe('UTXO and History Tests', () => {
it('should sync UTXOs by address', async () => {
const addresses = [
'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
];
const utxos = await ElectrumClient.syncUTXOByAddress(addresses, bitcoinJS.networks.testnet);
assert.ok(Object.keys(utxos).length > 0);
assert.deepStrictEqual(utxos[addresses[0]], [
{ txId: mockTxid, vout: 1, value: 12345, height: 100, address: addresses[0] },
]);
assert.deepStrictEqual(utxos[addresses[1]], []);
});

it('should sync history by address', async () => {
const addresses = [
'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
];
const history = await ElectrumClient.syncHistoryByAddress(
addresses,
bitcoinJS.networks.testnet
);
assert.ok(Object.keys(history.historyByAddress).length > 0);
assert.ok(history.txids.length > 0);
assert.deepStrictEqual(history.historyByAddress[addresses[0]], [
{ tx_hash: mockTxid, height: 100 },
]);
assert.deepStrictEqual(history.historyByAddress[addresses[1]], []);
assert.deepStrictEqual(history.txids, [mockTxid]);
assert.strictEqual(history.txidToAddress[mockTxid], addresses[0]);
});
});

describe('Transaction Tests', () => {
it('should estimate fee', async () => {
const fee = await ElectrumClient.estimateFee(1);
assert.ok(fee > 0);
assert.strictEqual(fee, 2);
});

it('should fetch transactions by ID', async () => {
const txids = [
'24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8',
'9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce',
];
const txids = [mockTxid, '9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce'];
const transactions = await ElectrumClient.getTransactionsById(txids);
assert.ok(Object.keys(transactions).length === txids.length);
assert.deepStrictEqual(transactions[txids[0]].txid, txids[0]);
assert.deepStrictEqual(transactions[txids[1]].txid, txids[1]);
assert.deepStrictEqual(Object.keys(transactions), txids);
for (const txid of txids) {
assert.strictEqual(transactions[txid].txid, txid);
assert.strictEqual(transactions[txid].hex, undefined);
assert.deepStrictEqual(transactions[txid].vout[0].scriptPubKey.addresses, ['tb1qfixture']);
}
});
});
});
79 changes: 79 additions & 0 deletions tests/services/electrumWalletFixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import ElectrumClient from 'src/services/electrum/client';
import WalletOperations from 'src/services/wallets/operations';

const fundingTxid = '608710eb040d935dedb6c4d6321369382b2bd45533a7442a6fa98add3860d46b';
const previousTxid = '89b193b61f7681ee588939932219f3d92e54a1873a9fb823647038f3879fba00';
const externalAddress = 'tb1ql7w62elx9ucw4pj5lgw4l028hmuw80sndtntxt';

// The wallet and vault suites exercise address scanning, transaction parsing, coin selection,
// and PSBT signing. Give each generated wallet one funded testnet address without using a
// public Electrum server or a mutable public wallet balance.
export const installElectrumWalletFixture = () => {
let fundedAddress: string | null = null;
const syncWallets = WalletOperations.syncWalletsViaElectrumClient;

jest.spyOn(WalletOperations, 'syncWalletsViaElectrumClient').mockImplementation((...args) => {
fundedAddress = null;
return syncWallets(...args);
});
jest.spyOn(WalletOperations, 'fetchFeeRatesByPriority').mockImplementation(async () =>
WalletOperations.mockFeeRates()
);

jest.spyOn(ElectrumClient, 'setActivePeer').mockImplementation(() => undefined);
jest.spyOn(ElectrumClient, 'connect').mockResolvedValue({
connected: true,
connectedTo: 'fixture.electrum.test',
});
jest.spyOn(ElectrumClient, 'forceDisconnect').mockImplementation(() => undefined);
jest.spyOn(ElectrumClient, 'getBlockchainHeaders').mockResolvedValue({ height: 85172, hex: '00' });
jest.spyOn(ElectrumClient, 'syncUTXOByAddress').mockImplementation(async (addresses) => {
if (!fundedAddress) fundedAddress = addresses[0];
return Object.fromEntries(
addresses.map((address) => [
address,
address === fundedAddress
? [{ txId: fundingTxid, vout: 1, value: 6000, height: 85000, address }]
: [],
])
);
});
jest.spyOn(ElectrumClient, 'syncHistoryByAddress').mockImplementation(async (addresses) => {
const hasFunding = addresses.includes(fundedAddress);
return {
historyByAddress: Object.fromEntries(
addresses.map((address) => [
address,
hasFunding && address === fundedAddress ? [{ tx_hash: fundingTxid, height: 85000 }] : [],
])
),
txids: hasFunding ? [fundingTxid] : [],
txidToAddress: hasFunding ? { [fundingTxid]: fundedAddress } : {},
};
});
jest.spyOn(ElectrumClient, 'getTransactionsById').mockImplementation(async (txids) => {
const transactions: Record<string, any> = {};
for (const txid of txids) {
if (txid === fundingTxid) {
transactions[txid] = {
txid,
vin: [{ txid: previousTxid, vout: 0 }],
vout: [
{ value: 0.00001, scriptPubKey: { addresses: [externalAddress] } },
{ value: 0.00006, scriptPubKey: { addresses: [fundedAddress] } },
],
confirmations: 12,
time: 1700000000,
blocktime: 1700000000,
};
} else if (txid === previousTxid) {
transactions[txid] = {
txid,
vin: [],
vout: [{ value: 0.0001, scriptPubKey: { addresses: [externalAddress] } }],
};
}
}
return transactions;
});
};
8 changes: 7 additions & 1 deletion tests/services/encryption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,13 @@ describe('Testing cryptographic primitives', () => {

test('Decryption::Incorrect key', () => {
const incorrectKey = 'a'.repeat(64);
const decrypted = decrypt(incorrectKey, encrypted);
let decrypted: string;
try {
decrypted = decrypt(incorrectKey, encrypt(key, message));
} catch (error) {
expect(error).toEqual(new Error('Malformed UTF-8 data'));
return;
}
expect(decrypted).not.toBe(message);
});
});
9 changes: 9 additions & 0 deletions tests/services/vault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
generateOutputDescriptors,
parseTextforVaultConfig,
} from 'src/utils/service-utilities/utils';
import { installElectrumWalletFixture } from './electrumWalletFixture';

jest.mock('src/store/store', () => ({
store: {
Expand All @@ -56,6 +57,10 @@ jest.mock('src/store/store', () => ({

jest.mock('realm', () => ({}));

beforeAll(() => {
installElectrumWalletFixture();
});

const connectToElectrumClient = async () => {
try {
ElectrumClient.setActivePeer(predefinedTestnetNodes);
Expand All @@ -67,6 +72,10 @@ const connectToElectrumClient = async () => {
}
};

afterAll(() => {
ElectrumClient.forceDisconnect();
});

describe('Vault: Single-Sig(1-of-1)', () => {
let primaryMnemonic: string;
let vault: Vault;
Expand Down
5 changes: 5 additions & 0 deletions tests/services/wallet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
TransactionPrerequisite,
} from 'src/services/wallets/interfaces';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
import { installElectrumWalletFixture } from './electrumWalletFixture';

jest.mock('src/store/store', () => ({
store: {
Expand All @@ -25,6 +26,10 @@ jest.mock('src/store/store', () => ({

jest.mock('realm', () => ({}));

beforeAll(() => {
installElectrumWalletFixture();
});

describe('Wallet Functionality Tests', () => {
let primaryMnemonic: string;
let wallet: Wallet;
Expand Down
Loading