Skip to content

Commit 25f68e8

Browse files
authored
test(bitcoin): expand send E2E coverage (#47234)
## **Description** This pull request introduces several improvements and new utilities to the Bitcoin end-to-end (E2E) test suite, focusing on more robust and flexible Bitcoin transaction testing. The most significant changes include new helper functions for sending and confirming Bitcoin transactions, enhanced activity tab assertions, and refactoring of the Bitcoin node seeder for improved block mining and address management. **E2E Bitcoin transaction flow enhancements:** * Added `landOnBitcoinSendScreen`, `confirmBitcoinSendAndAssertPending`, and `waitForBitcoinSendConfirmation` helper functions to streamline and clarify Bitcoin send E2E flows, including robust balance checks and confirmation waits. [[1]](diffhunk://#diff-12faa4bbc8672b24b5b1ab66785152b91f63b431785307f7b261e88e2e8efe49R4-R42) [[2]](diffhunk://#diff-12faa4bbc8672b24b5b1ab66785152b91f63b431785307f7b261e88e2e8efe49R84-R143) **Activity tab and transaction status assertions:** * Enhanced the `ActivityTab` page object with methods to wait for transactions with a specific amount and status, improving reliability of transaction state assertions in tests. [[1]](diffhunk://#diff-af5a4e69660c3aecba247b96e1878009cdb4158dee534de0bfa486aee226a17aR81-R83) [[2]](diffhunk://#diff-af5a4e69660c3aecba247b96e1878009cdb4158dee534de0bfa486aee226a17aR511-R570) **Bitcoin node seeder improvements:** * Refactored `BitcoinNode` to add a `mineBlocks` method for mining blocks to a fresh address, centralized address generation via a new `getNewAddress` helper, and removed unused P2P port configuration. [[1]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eL41) [[2]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eR362-R376) [[3]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eL632-R646) [[4]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eR675-R678) [[5]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eL774-R788) [[6]](diffhunk://#diff-e17aad52c59176635dd97c1e03cf95e92c340dd99f249e9b58038760a0c5533eL793-R807) **Test and assertion robustness:** * Improved assertions on the Bitcoin review transaction page to check for the exact send amount using a stricter selector and value comparison. [[1]](diffhunk://#diff-479d4f36276fc7f5132be843d652bcba71848d95c8c7ba330c8eb49860c13e61R1) [[2]](diffhunk://#diff-479d4f36276fc7f5132be843d652bcba71848d95c8c7ba330c8eb49860c13e61L69-R73) * Added error checking for invalid value errors in the send page, making negative test cases clearer and more maintainable. [[1]](diffhunk://#diff-23828c5e64c661f3108743386dec1d663d909fafaff393d01548c25e6d6e754cR69-R72) [[2]](diffhunk://#diff-23828c5e64c661f3108743386dec1d663d909fafaff393d01548c25e6d6e754cR250-R254) **Test coverage and fixtures:** * Introduced a comprehensive test suite for `withBitcoinFixtures`, covering fixture forwarding, node options, static mocks, error propagation, and custom hooks. * Added a unit test for the new `mineBlocks` method in the Bitcoin node helper tests. * Added a `refreshPage` utility to the home page object to ensure UI state is reliably updated after network or balance changes. ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: WPN-2136 ## **Manual testing steps** 1. Build and load the extension, then unlock the test wallet. 2. Select Bitcoin and open the Send flow. 3. Enter a valid recipient without an amount, continue, and verify that a transaction error is shown and Continue becomes disabled. 4. Enter the available BTC balance minus the displayed network fee and verify that the transaction can be reviewed and submitted. 5. Send `0.5 BTC` and open Activity. 6. Verify that the activity entry displays `-0.5 BTC`, initially shows Pending, and changes to Confirmed after the transaction is mined. <!-- ## **Screenshots/Recordings** ### **Before** ### **After** --> ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [ ] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Changes are confined to E2E test helpers, mocks, and page objects; production wallet or send logic is not modified. > > **Overview** > Expands Bitcoin send E2E coverage by splitting the old monolithic send specs into focused scenarios under `tests/send/bitcoin/` (invalid address, empty amount, over-balance, review amounts, max send, partial send with on-chain confirmation). Those specs share a new **`withBitcoinFixtures`** wrapper that starts anvil plus an optional regtest `BitcoinNode`, wires `proxyBitcoinBlockchainCalls` or static `mockInitialFullScan`, and registers the usual price/token mocks. > > **Test infrastructure changes:** Esplora **`POST /tx`** now returns the real witness-stripped txid (with unit tests in `bitcoin-esplora.test.ts`); **`BitcoinNode.mineBlocks`** and shared **`getNewAddress`** support confirming sends in E2E; regtest bitcoind drops P2P port allocation and runs with **`-listen=0`**. Page objects gain **`HomePage.refreshPage`**, **`SendPage.checkInvalidValueError`**, stricter snap review amount matching via XPath, and **`ActivityTab.checkWaitForTransactionStatusByAmount`** for rows identified by amount. The shared **`broadcastBitcoinSend`** flow file is removed in favor of inline steps (activity spec updated). Jest coverage documents **`withBitcoinFixtures`** behavior and **`mineBlocks`** RPC usage. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3d62499. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 0d6c299 commit 25f68e8

21 files changed

Lines changed: 1141 additions & 403 deletions
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { createHash } from 'crypto';
2+
import { it as jestIt } from '@jest/globals';
3+
import type { CompletedRequest, Mockttp } from 'mockttp';
4+
import { mockInitialFullScan } from '../tests/btc/mocks/esplora';
5+
6+
type EndpointCallback = Parameters<
7+
ReturnType<Mockttp['forGet']>['thenCallback']
8+
>[0];
9+
10+
/**
11+
* Captures Mockttp handlers without opening sockets or starting an E2E server.
12+
*
13+
* @returns A mock server and a dispatcher for the registered public endpoints.
14+
*/
15+
function captureEndpoints() {
16+
const endpoints: {
17+
method: string;
18+
pattern: RegExp;
19+
callback: EndpointCallback;
20+
}[] = [];
21+
const register = (method: string) => (pattern: RegExp) => {
22+
const builder = {
23+
always: () => builder,
24+
thenCallback: (callback: EndpointCallback) => {
25+
endpoints.push({ method, pattern, callback });
26+
return Promise.resolve();
27+
},
28+
};
29+
return builder;
30+
};
31+
const server = {
32+
forGet: jest.fn(register('GET')),
33+
forPost: jest.fn(register('POST')),
34+
} as unknown as Mockttp;
35+
36+
return {
37+
server,
38+
request: async (method: string, path: string, body = '') => {
39+
const url = `https://bitcoin-mainnet.infura.io/v3/${'a'.repeat(32)}/esplora${path}`;
40+
const endpoint = endpoints.find(
41+
(candidate) =>
42+
candidate.method === method && candidate.pattern.test(url),
43+
);
44+
if (!endpoint) {
45+
throw new Error(`No mock registered for ${method} ${path}`);
46+
}
47+
return await endpoint.callback({
48+
url,
49+
body: { getText: async () => body },
50+
} as unknown as CompletedRequest);
51+
},
52+
};
53+
}
54+
55+
describe('mockInitialFullScan', () => {
56+
beforeEach(() => {
57+
jest.spyOn(console, 'log').mockImplementation(() => undefined);
58+
});
59+
60+
afterEach(() => {
61+
jest.restoreAllMocks();
62+
});
63+
64+
// Explicit serialized fields make the independent txid preimage inspectable:
65+
// version, one input (prevout, scriptSig, sequence), one output, locktime.
66+
const version = '01000000';
67+
const inputsAndOutputs = `01${'00'.repeat(32)}000000000151ffffffff0101000000000000000151`;
68+
const locktime = '00000000';
69+
const strippedHex = version + inputsAndOutputs + locktime;
70+
const witnessHex = `${version}0001${inputsAndOutputs}0201aa02bbbb${locktime}`;
71+
72+
jestIt.each([
73+
['legacy', strippedHex],
74+
['SegWit', witnessHex],
75+
])('returns the real txid for a %s broadcast', async (_format, rawHex) => {
76+
const { server, request } = captureEndpoints();
77+
await mockInitialFullScan(server);
78+
// Hash an explicitly witness-free preimage, not production parsing output.
79+
const expectedTxid = createHash('sha256')
80+
.update(
81+
createHash('sha256').update(Buffer.from(strippedHex, 'hex')).digest(),
82+
)
83+
.digest()
84+
.reverse()
85+
.toString('hex');
86+
87+
const response = await request('POST', '/tx', rawHex);
88+
89+
expect(response).toStrictEqual({ statusCode: 200, body: expectedTxid });
90+
if (rawHex === witnessHex) {
91+
const wtxid = createHash('sha256')
92+
.update(
93+
createHash('sha256').update(Buffer.from(rawHex, 'hex')).digest(),
94+
)
95+
.digest()
96+
.reverse()
97+
.toString('hex');
98+
expect(expectedTxid).not.toBe(wtxid);
99+
}
100+
});
101+
102+
it('keeps static funding and chain responses unchanged after broadcasts', async () => {
103+
const { server, request } = captureEndpoints();
104+
await mockInitialFullScan(server);
105+
const fundingTxid =
106+
'7a9d27d80e05abc2cf15c6bc87a70a6badf5f5aa6615aa8e346d92fccf7dfc10';
107+
const fundingBlockHash =
108+
'000000000000000000013d73c3bd23225714f2fd8b801ed076818f2971897748';
109+
const tipHash =
110+
'00000000000000000001d3a19bc9dbde9d1d26b25aa49269b575282bb6d74409';
111+
const scripthash =
112+
'538c172f4f5ff9c24693359c4cdc8ee4666565326a789d5e4b2df1db7acb4721';
113+
const paths = [
114+
'/blocks',
115+
'/blocks/tip/height',
116+
'/blocks/tip/hash',
117+
`/scripthash/${scripthash}/txs`,
118+
`/scripthash/${scripthash}/utxo`,
119+
`/tx/${fundingTxid}`,
120+
`/tx/${fundingTxid}/outspends`,
121+
`/block/${fundingBlockHash}`,
122+
'/block-height/932935',
123+
'/block-height/932937',
124+
'/fee-estimates',
125+
`/tx/${'f'.repeat(64)}`,
126+
];
127+
const before = await Promise.all(paths.map((path) => request('GET', path)));
128+
// Save values, not references that a stateful mock might mutate later.
129+
const original = JSON.parse(JSON.stringify(before));
130+
expect(before[0]).toMatchObject({
131+
statusCode: 200,
132+
json: [{ id: tipHash, height: 932936 }, {}, {}],
133+
});
134+
expect(before[1]).toStrictEqual({ statusCode: 200, body: '932936' });
135+
expect(before[2]).toStrictEqual({ statusCode: 200, body: tipHash });
136+
expect(before[3]).toMatchObject({
137+
statusCode: 200,
138+
json: [{ txid: fundingTxid, status: { confirmed: true } }],
139+
});
140+
expect(before[4]).toMatchObject({
141+
statusCode: 200,
142+
json: [{ txid: fundingTxid, vout: 0, value: 100000000 }],
143+
});
144+
expect(before[6]).toStrictEqual({
145+
statusCode: 200,
146+
json: [{ spent: false }],
147+
});
148+
expect(before[9]).toStrictEqual({
149+
statusCode: 200,
150+
body: '0'.repeat(64),
151+
});
152+
expect(before[11]).toStrictEqual({
153+
statusCode: 404,
154+
body: 'Transaction not found',
155+
});
156+
157+
await request('POST', '/tx', strippedHex);
158+
await request('POST', '/tx', witnessHex);
159+
const after = await Promise.all(paths.map((path) => request('GET', path)));
160+
161+
expect(after).toStrictEqual(original);
162+
const broadcastResponse = await request('POST', '/tx', witnessHex);
163+
const broadcastTxid = (broadcastResponse as { body: string }).body;
164+
expect(await request('GET', `/tx/${broadcastTxid}`)).toStrictEqual({
165+
statusCode: 404,
166+
body: 'Transaction not found',
167+
});
168+
});
169+
});

0 commit comments

Comments
 (0)