diff --git a/helpers/silent-payments/RustTransactionProcessor.ts b/helpers/silent-payments/RustTransactionProcessor.ts index f9aaaa64f..0d3581e35 100644 --- a/helpers/silent-payments/RustTransactionProcessor.ts +++ b/helpers/silent-payments/RustTransactionProcessor.ts @@ -11,6 +11,20 @@ import { spScanTransactions, RustMatchedUTXO, RustBatchScanResult } from '../../ import { hexToUint8Array } from '../../modules/uint8array-extras'; import type { NetworkConfig } from '../../modules/network'; +// Transactions per JSI call. The call is synchronous and holds the JS thread for its whole run, so taps, +// timers and JS-driven animation wait on it: a window of tens of thousands of transactions froze the +// app for seconds. At the ~30k tx/s in RUST_INTEGRATION.md, 1000 is ~35ms, short enough to go unnoticed. +export const SCAN_SLICE_SIZE = 1000; + +// How long slices may run back to back before the scan yields. A yield costs up to a frame on iOS, where +// timers under 18ms wait for the next display frame (RCTTiming), so yielding after every slice left a +// fast device idle about as long as it scanned; a slow device's slice takes this long anyway. +export const SCAN_YIELD_AFTER_MS = 30; + +// A macrotask: microtasks (and the setImmediate shim, built on them in bridgeless RN) all run before the +// runtime gets back to touches, timers and rendering. +const yieldToEventLoop = () => new Promise(resolve => setTimeout(resolve, 0)); + export class RustTransactionProcessor { private scanPrivkeyHex: string; /** Main spend pubkey plus the label-0 (change) spend pubkey — the scanner tries both. */ @@ -62,16 +76,43 @@ export class RustTransactionProcessor { } try { - const result: RustBatchScanResult = spScanTransactions(this.scanPrivkeyHex, this.spendPubkeysHex, transactions); + const matched: RustMatchedUTXO[] = []; + let transactionsScanned = 0; + let outputsScanned = 0; + + let holdingSince = Date.now(); + for (let start = 0; start < transactions.length; start += SCAN_SLICE_SIZE) { + if (start > 0) { + if (Date.now() - holdingSince >= SCAN_YIELD_AFTER_MS) { + await yieldToEventLoop(); + holdingSince = Date.now(); + } + // Thrown rather than returning what's found so far: once this resolves the caller marks the + // whole window scanned, so the slices not yet scanned would be skipped for good. + if (cancelScanCallback?.()) { + throw new Error('SCAN_CANCELLED'); + } + } + + const result: RustBatchScanResult = spScanTransactions( + this.scanPrivkeyHex, + this.spendPubkeysHex, + transactions.slice(start, start + SCAN_SLICE_SIZE), + ); + transactionsScanned += result.transactionsScanned; + outputsScanned += result.outputsScanned; + matched.push(...result.matchedUtxos); + } console.log( - `[RustTransactionProcessor] Scanned ${result.transactionsScanned} txs, ` + - `${result.outputsScanned} outputs, found ${result.matchedUtxos.length} matches`, + `[RustTransactionProcessor] Scanned ${transactionsScanned} txs, ${outputsScanned} outputs, found ${matched.length} matches`, ); - return result.matchedUtxos.map(utxo => this.convertToSilentPaymentUTXO(utxo)); - } catch (error) { - console.error('[RustTransactionProcessor] Batch processing error:', error); + return matched.map(utxo => this.convertToSilentPaymentUTXO(utxo)); + } catch (error: any) { + if (error?.message !== 'SCAN_CANCELLED') { + console.error('[RustTransactionProcessor] Batch processing error:', error); + } throw error; } } diff --git a/modules/socks5Fetch.ts b/modules/socks5Fetch.ts index 3a24e02e0..be549ed4b 100644 --- a/modules/socks5Fetch.ts +++ b/modules/socks5Fetch.ts @@ -47,32 +47,66 @@ function parseUrl(url: string): { host: string; port: number; path: string } { return { host, port, path }; } -// Returns complete: false whenever more bytes are needed - on a short/malformed chunk this must -// signal "not done yet" rather than returning the partial body, or a truncated read looks like success. -// Operates on the raw Buffer throughout - chunk sizes are byte counts, and indexing a UTF-8 -// string instead would misalign on any multi-byte character in the body. -function decodeChunked(data: Buffer): { body: Buffer; complete: boolean } { - const chunks: Buffer[] = []; - let remaining = data; - - while (remaining.length > 0) { - const lineEnd = remaining.indexOf('\r\n'); - if (lineEnd === -1) return { body: Buffer.concat(chunks), complete: false }; - - const chunkSizeStr = remaining.subarray(0, lineEnd).toString('ascii').trim(); - if (!chunkSizeStr) return { body: Buffer.concat(chunks), complete: false }; - - const chunkSize = parseInt(chunkSizeStr, 16); - if (isNaN(chunkSize)) return { body: Buffer.concat(chunks), complete: false }; - if (chunkSize === 0) return { body: Buffer.concat(chunks), complete: true }; - - const chunkStart = lineEnd + 2; - if (remaining.length < chunkStart + chunkSize + 2) return { body: Buffer.concat(chunks), complete: false }; - chunks.push(remaining.subarray(chunkStart, chunkStart + chunkSize)); - remaining = remaining.subarray(chunkStart + chunkSize + 2); // +2 for trailing \r\n - } +interface ChunkedDecoder { + /** Takes the body's next bytes; true once the terminal zero-size chunk is in. */ + push: (bytes: Buffer) => boolean; + body: () => Buffer; +} + +// Decodes a chunked body as it arrives, looking at each byte once however the packets split it: +// re-decoding the whole body on every packet was quadratic in its size, on the JS thread. A +// short or malformed chunk never completes (a truncated read must not look like success), so the +// socket closing rejects it. Works on raw bytes throughout - chunk sizes are byte counts, and +// indexing a UTF-8 string instead would misalign on any multi-byte character in the body. +function createChunkedDecoder(): ChunkedDecoder { + const parts: Buffer[] = []; + let length = 0; + let sizeLine: Buffer = Buffer.alloc(0); // a size line split across packets + let owed = 0; // bytes of the current chunk still to come + let crlfOwed = 0; // the CRLF after a chunk's data, skipped unchecked + let state: 'size' | 'done' | 'stuck' = 'size'; + + return { + push(bytes: Buffer): boolean { + let rest = bytes; + while (rest.length > 0 && state === 'size') { + if (owed > 0) { + const taken = Math.min(owed, rest.length); + parts.push(rest.subarray(0, taken)); + length += taken; + owed -= taken; + rest = rest.subarray(taken); + if (owed === 0) crlfOwed = 2; + continue; + } + if (crlfOwed > 0) { + const skipped = Math.min(crlfOwed, rest.length); + crlfOwed -= skipped; + rest = rest.subarray(skipped); + continue; + } + + const line = sizeLine.length ? Buffer.concat([sizeLine, rest]) : rest; + const lineEnd = line.indexOf('\r\n'); + if (lineEnd === -1) { + sizeLine = line; + // no real size line runs this long: don't keep buffering one + if (sizeLine.length > 1024) state = 'stuck'; + break; + } - return { body: Buffer.concat(chunks), complete: false }; + const sizeText = line.subarray(0, lineEnd).toString('ascii').trim(); + const size = parseInt(sizeText, 16); + sizeLine = Buffer.alloc(0); + rest = line.subarray(lineEnd + 2); + if (!sizeText || isNaN(size) || size < 0) state = 'stuck'; + else if (size === 0) state = 'done'; + else owed = size; + } + return state === 'done'; + }, + body: () => Buffer.concat(parts, length), + }; } /** @@ -120,7 +154,14 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom let phase: 'greeting' | 'connect' | 'http' = 'greeting'; let pending: Buffer = Buffer.alloc(0); - let httpBuffer: Buffer = Buffer.alloc(0); + // The response so far: the header bytes until their terminator, then the body as the packets that + // carried it, joined once at the end. Appending every packet to one growing Buffer copied the whole + // response again each time, quadratic in its size, on the JS thread. + let headerBytes: Buffer = Buffer.alloc(0); + let receivedBytes = 0; + const bodyParts: Buffer[] = []; + let bodyLength = 0; + let chunkedBody: ChunkedDecoder | null = null; let headerEnd = -1; let status = 0; let statusText = ''; @@ -132,11 +173,11 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom // while more bytes are still needed. const parseHeadersIfNeeded = (): boolean => { if (headerEnd !== -1) return true; - const idx = httpBuffer.indexOf('\r\n\r\n'); + const idx = headerBytes.indexOf('\r\n\r\n'); if (idx === -1) return false; headerEnd = idx; - const headerPart = httpBuffer.subarray(0, headerEnd).toString('utf-8'); + const headerPart = headerBytes.subarray(0, headerEnd).toString('utf-8'); const statusLine = headerPart.split('\r\n')[0]; const statusMatch = statusLine.match(/HTTP\/[\d.]+\s+(\d+)\s*(.*)/); status = statusMatch ? parseInt(statusMatch[1], 10) : 0; @@ -153,6 +194,7 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom } isChunked = responseHeaders['transfer-encoding']?.includes('chunked') ?? false; + if (isChunked) chunkedBody = createChunkedDecoder(); const contentLengthHeader = responseHeaders['content-length']; expectedBodyLength = contentLengthHeader ? parseInt(contentLengthHeader, 10) : null; return true; @@ -167,30 +209,30 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom text: async () => bodyText, }); - // Resolves as soon as the body is verifiably complete (Content-Length reached, or the - // chunked terminator seen). Returns false when there's not yet enough to tell - including - // when there's no length info at all, in which case only the 'close' handler can finish it. - const tryFinalizeHttpResponse = (): boolean => { - if (!parseHeadersIfNeeded()) return false; - const bodyBuf = httpBuffer.subarray(headerEnd + 4); - - if (isChunked) { - const decoded = decodeChunked(bodyBuf); - if (!decoded.complete) return false; - finish(() => resolve(buildResponse(decoded.body.toString('utf-8')))); - return true; + // Takes the body's next bytes, and resolves as soon as the body is verifiably complete + // (Content-Length reached, or the chunked terminator seen). With no length info at all, only the + // 'close' handler can finish it. + const receiveBody = (bytes: Buffer) => { + if (chunkedBody) { + if (chunkedBody.push(bytes)) { + const decoded = chunkedBody.body(); + finish(() => resolve(buildResponse(decoded.toString('utf-8')))); + } + return; } - if (expectedBodyLength !== null) { - if (bodyBuf.length < expectedBodyLength) return false; - finish(() => resolve(buildResponse(bodyBuf.subarray(0, expectedBodyLength as number).toString('utf-8')))); - return true; + if (bytes.length > 0) { + bodyParts.push(bytes); + bodyLength += bytes.length; + } + if (expectedBodyLength !== null && !(bodyLength < expectedBodyLength)) { + const declared = expectedBodyLength; + finish(() => resolve(buildResponse(Buffer.concat(bodyParts, bodyLength).subarray(0, declared).toString('utf-8')))); } - - return false; }; client.on('data', (data: string | Buffer) => { + if (resolved) return; const buf = Buffer.isBuffer(data) ? data : Buffer.from(data); pending = pending.length ? Buffer.from(Buffer.concat([pending, buf])) : buf; @@ -266,10 +308,11 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom client.write(Buffer.from(httpRequest)); } else if (phase === 'http') { - httpBuffer = httpBuffer.length ? Buffer.concat([httpBuffer, pending]) : pending; + const segment = pending; pending = Buffer.alloc(0); - if (httpBuffer.length > MAX_RESPONSE_BYTES) { + receivedBytes += segment.length; + if (receivedBytes > MAX_RESPONSE_BYTES) { finish(() => { client.destroy(); reject(new Error(`SOCKS5 response exceeded ${MAX_RESPONSE_BYTES} byte limit`)); @@ -277,7 +320,13 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom return; } - tryFinalizeHttpResponse(); + if (headerEnd !== -1) { + receiveBody(segment); + } else { + headerBytes = headerBytes.length ? Buffer.concat([headerBytes, segment]) : segment; + // the body's first bytes can arrive in the same packet as the end of the headers + if (parseHeadersIfNeeded()) receiveBody(headerBytes.subarray(headerEnd + 4)); + } } } }); @@ -298,8 +347,7 @@ export function socks5Fetch(url: string, options: Socks5FetchOptions = {}): Prom reject(new Error('SOCKS5 response ended before the declared body length was received')); return; } - const bodyBuf = httpBuffer.subarray(headerEnd + 4); - resolve(buildResponse(bodyBuf.toString('utf-8'))); + resolve(buildResponse(Buffer.concat(bodyParts, bodyLength).toString('utf-8'))); } catch (error) { reject(new Error(`Failed to parse response: ${error instanceof Error ? error.message : String(error)}`)); } diff --git a/tests/unit/rustTransactionProcessor.test.ts b/tests/unit/rustTransactionProcessor.test.ts new file mode 100644 index 000000000..94e1db3d4 --- /dev/null +++ b/tests/unit/rustTransactionProcessor.test.ts @@ -0,0 +1,131 @@ +import * as bip39 from 'bip39'; +import * as bitcoin from 'bitcoinjs-lib'; + +import { RustTransactionProcessor, SCAN_SLICE_SIZE, SCAN_YIELD_AFTER_MS } from '../../helpers/silent-payments/RustTransactionProcessor'; +import type { IndexerTransaction } from '../../helpers/silent-payments/types'; +import { getNetwork } from '../../modules/network'; +import ecc from '../../modules/noble_ecc'; +import { spScanTransactions } from '../../modules/RustJsiBridge'; + +jest.mock('../../modules/RustJsiBridge', () => ({ + ...jest.requireActual('../../modules/RustJsiBridge'), + spScanTransactions: jest.fn(), +})); + +// matches are turned into taproot addresses, as the app does once a wallet module has loaded +bitcoin.initEccLib(ecc); + +const mockScan = spScanTransactions as jest.Mock; +const TEST_SEED = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; +// any valid x-only key will do: the generator point's +const X_ONLY_KEY = '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; + +const transactions = (count: number): IndexerTransaction[] => + Array.from( + { length: count }, + (_, i) => ({ id: `tx${i}`, blockHeight: 900_000, blockHash: 'h', blockTime: 0, scanTweak: 'aa', outputs: [] }) as any, + ); + +// A clock the scanner moves on by however long its slice takes, so tests can say how long that is. +let clock = 0; + +// The scanner's answer for a slice: one match per slice, named after the slice's first transaction. +const answerPerSlice = (onCall: () => void = () => {}) => + mockScan.mockImplementation((_priv: string, _pubs: string[], slice: IndexerTransaction[]) => { + onCall(); + return { + transactionsScanned: slice.length, + outputsScanned: 0, + matchedUtxos: [ + { + txid: slice[0].id, + vout: 0, + value: 1000, + height: 900_000, + pubKey: X_ONLY_KEY, + tweakHex: '00'.repeat(32), + blockHash: 'h', + isSpent: false, + blockTime: 0, + }, + ], + }; + }); + +describe('unit - RustTransactionProcessor', () => { + const processor = new RustTransactionProcessor(bip39.mnemonicToSeedSync(TEST_SEED), getNetwork('bitcoin')); + + beforeEach(() => { + mockScan.mockReset(); + clock = 0; + jest.spyOn(Date, 'now').mockImplementation(() => clock); + jest.spyOn(console, 'log').mockImplementation(() => {}); + }); + + // Each slice holds the thread `ms`. A task queued just before the batch starts shows where the batch let + // other work run, and `yields` counts the batch's own yields. + const runWithSlicesOf = async (ms: number, sliceCount: number) => { + const order: string[] = []; + answerPerSlice(() => { + clock += ms; + order.push('slice'); + }); + setTimeout(() => order.push('other task'), 0); + const timers = jest.spyOn(global, 'setTimeout'); + + await processor.processBatch(transactions((sliceCount - 1) * SCAN_SLICE_SIZE + 1)); + + const yields = timers.mock.calls.length; + timers.mockRestore(); + return { order, yields }; + }; + + afterEach(() => jest.restoreAllMocks()); + + it('scans a window in slices, finding what one call over all of it would, in order', async () => { + answerPerSlice(); + + const found = await processor.processBatch(transactions(2 * SCAN_SLICE_SIZE + 1)); + + expect(mockScan.mock.calls.map(call => call[2].length)).toEqual([SCAN_SLICE_SIZE, SCAN_SLICE_SIZE, 1]); + expect(found.map(utxo => utxo.txid)).toEqual(['tx0', `tx${SCAN_SLICE_SIZE}`, `tx${2 * SCAN_SLICE_SIZE}`]); + }); + + it(`lets the app run once slices have held the thread ${SCAN_YIELD_AFTER_MS}ms`, async () => { + const { order, yields } = await runWithSlicesOf(20, 3); + + // 20ms, then 40ms: the waiting task gets its turn before the third slice + expect(order).toEqual(['slice', 'slice', 'other task', 'slice']); + expect(yields).toBe(1); + }); + + it('yields after every slice that holds the thread that long on its own', async () => { + const { order, yields } = await runWithSlicesOf(SCAN_YIELD_AFTER_MS + 10, 3); + + expect(order).toEqual(['slice', 'other task', 'slice', 'slice']); + expect(yields).toBe(2); + }); + + it('runs quick slices back to back, without idling between them', async () => { + const { order, yields } = await runWithSlicesOf(5, 3); + + // 15ms in all, so no yield, which would cost up to a frame on iOS: the waiting task runs after the batch + expect(order).toEqual(['slice', 'slice', 'slice']); + expect(yields).toBe(0); + }); + + it('stops between slices on a cancel, by throwing, so the caller never marks the window scanned', async () => { + let cancelled = false; + answerPerSlice(() => { + cancelled = true; + }); + + await expect(processor.processBatch(transactions(2 * SCAN_SLICE_SIZE), () => cancelled)).rejects.toThrow('SCAN_CANCELLED'); + expect(mockScan).toHaveBeenCalledTimes(1); + }); + + it('has nothing to scan in an empty window', async () => { + await expect(processor.processBatch([])).resolves.toEqual([]); + expect(mockScan).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/socks5Fetch.test.ts b/tests/unit/socks5Fetch.test.ts index 7b20f875b..32375c433 100644 --- a/tests/unit/socks5Fetch.test.ts +++ b/tests/unit/socks5Fetch.test.ts @@ -1,4 +1,5 @@ import assert from 'assert'; +import { Buffer as ModuleBuffer } from 'buffer'; import { EventEmitter } from 'events'; import TcpSocket from 'react-native-tcp-socket'; import { socks5Fetch } from '../../modules/socks5Fetch'; @@ -195,4 +196,103 @@ describe('unit - socks5Fetch', () => { await assert.rejects(promise, /CONNECT failed \(code: 4\)/); }); + describe('reading the response', () => { + const CHUNKED_HEADER = Buffer.from('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n'); + + const chunked = (payload: Buffer, chunkSize: number): Buffer => { + const parts: Buffer[] = []; + for (let i = 0; i < payload.length; i += chunkSize) { + const chunk = payload.subarray(i, i + chunkSize); + parts.push(Buffer.from(`${chunk.length.toString(16)}\r\n`), chunk, Buffer.from('\r\n')); + } + parts.push(Buffer.from('0\r\n\r\n')); + return Buffer.concat(parts); + }; + + const emitInPackets = (socket: EventEmitter, bytes: Buffer, packetSize: number) => { + for (let i = 0; i < bytes.length; i += packetSize) socket.emit('data', bytes.subarray(i, i + packetSize)); + }; + + const fetchWith = async (send: (socket: EventEmitter & { destroy: jest.Mock }) => void) => { + const promise = socks5Fetch('http://abc123.onion/status'); + const socket = latestSocket(); + await completeHandshake(socket); + send(socket); + return promise; + }; + + it('resolves a Content-Length body that arrives a byte at a time', async () => { + const response = await fetchWith(socket => emitInPackets(socket, httpResponse(200, { 'Content-Length': '11' }, '{"ok":true}'), 1)); + + assert.deepStrictEqual(await response.json(), { ok: true }); + }); + + it('decodes a chunked body however the packets split it, multi-byte characters included', async () => { + // 5-byte chunks, so é, ☕ and the rest straddle chunk boundaries as well as packet ones + const payload = Buffer.from('{"msg":"café ☕ ünïcödé"}', 'utf-8'); + const whole = Buffer.concat([CHUNKED_HEADER, chunked(payload, 5)]); + + for (let split = 1; split < whole.length; split++) { + const response = await fetchWith(socket => { + socket.emit('data', whole.subarray(0, split)); + socket.emit('data', whole.subarray(split)); + }); + assert.deepStrictEqual(await response.json(), { msg: 'café ☕ ünïcödé' }, `split at byte ${split}`); + } + + const response = await fetchWith(socket => emitInPackets(socket, whole, 1)); + assert.deepStrictEqual(await response.json(), { msg: 'café ☕ ünïcödé' }); + }); + + it('resolves as soon as the terminal chunk is in, without waiting for trailers or the socket to close', async () => { + const response = await fetchWith(socket => socket.emit('data', Buffer.concat([CHUNKED_HEADER, Buffer.from('2\r\n{}\r\n0\r\n')]))); + + assert.deepStrictEqual(await response.json(), {}); + }); + + it('never completes a chunked body with a malformed size line, rejecting once the socket closes', async () => { + const promise = fetchWith(socket => { + socket.emit('data', Buffer.concat([CHUNKED_HEADER, Buffer.from('zz\r\n{}\r\n0\r\n\r\n')])); + socket.emit('close'); + }); + + await assert.rejects(promise, /body length/); + }); + + it('resolves an empty body declared with Content-Length: 0', async () => { + const response = await fetchWith(socket => socket.emit('data', httpResponse(200, { 'Content-Length': '0' }, ''))); + + assert.strictEqual(await response.text(), ''); + }); + + it('enforces the size cap across many packets, as for one', async () => { + let socketUsed!: { destroy: jest.Mock }; + const promise = fetchWith(socket => { + socketUsed = socket; + socket.emit('data', Buffer.from(`HTTP/1.1 200 OK\r\nContent-Length: ${21 * 1024 * 1024}\r\n\r\n`)); + for (let i = 0; i < 21; i++) socket.emit('data', Buffer.alloc(1024 * 1024)); + }); + + await assert.rejects(promise, /byte limit/); + assert.strictEqual(socketUsed.destroy.mock.calls.length, 1); + }); + + it('copies a large response a bounded number of times, not once per packet', async () => { + const payload = Buffer.from(JSON.stringify({ data: 'x'.repeat(2 * 1024 * 1024) })); + const whole = Buffer.concat([CHUNKED_HEADER, chunked(payload, 4096)]); + const concat = jest.spyOn(ModuleBuffer, 'concat'); + + try { + const response = await fetchWith(socket => emitInPackets(socket, whole, 2048)); + assert.strictEqual((await response.text()).length, payload.length); + + // The whole body once at the end, plus the odd split size line. Joining every packet onto + // what came before copied over a gigabyte for this one. + const copied = concat.mock.results.reduce((total, result) => total + (result.value as Buffer).length, 0); + assert.ok(copied < 3 * payload.length, `copied ${copied} bytes for a ${payload.length}-byte body`); + } finally { + concat.mockRestore(); + } + }); + }); }); diff --git a/tests/unit/sp-scan-lifecycle.test.ts b/tests/unit/sp-scan-lifecycle.test.ts index e9c44ae41..e1605a3bf 100644 --- a/tests/unit/sp-scan-lifecycle.test.ts +++ b/tests/unit/sp-scan-lifecycle.test.ts @@ -2,12 +2,18 @@ import * as Electrum from '../../modules/Electrum'; import { AbstractHDElectrumWallet } from '../../class/wallets/abstract-hd-electrum-wallet'; import { HDSilentPaymentsWallet } from '../../class/wallets/hd-bip352-wallet'; import { type ScanStateInfo, type SilentPaymentUTXO } from '../../helpers/silent-payments/types'; +import { SCAN_SLICE_SIZE } from '../../helpers/silent-payments/RustTransactionProcessor'; +import { spScanTransactions } from '../../modules/RustJsiBridge'; import * as indexerModule from '../../modules/SilentPaymentIndexer'; jest.mock('../../modules/Electrum', () => ({ multiGetUtxoByAddress: jest.fn(), multiGetHistoryByAddress: jest.fn(), })); +jest.mock('../../modules/RustJsiBridge', () => ({ + ...jest.requireActual('../../modules/RustJsiBridge'), + spScanTransactions: jest.fn(), +})); const TEST_SEED = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; const TIP = 900_000; @@ -178,6 +184,33 @@ describe('scan lifecycle', () => { expect(indexer.getLatestBlockHeight).toHaveBeenCalledTimes(2); }); + it('leaves a window unscanned when the scan is cancelled between its slices', async () => { + const window = Array.from({ length: SCAN_SLICE_SIZE + 1 }, (_, i) => ({ + id: `tx${i}`, + blockHeight: TIP, + blockHash: 'h', + blockTime: 0, + scanTweak: 'aa', + outputs: [{ transactionId: `tx${i}`, vout: 0, pubKey: 'bb', value: 1000, isSpent: false }], + })); + stubIndexer({ + scanForwardWithCallback: jest.fn(async (_from: number, to: number, onRange: (txs: unknown[], end: number) => Promise) => { + await onRange(window, to); + }), + }); + const wallet = track(syncedWallet(TIP - 10)); + // the user leaves the chain while the first slice is being scanned + (spScanTransactions as jest.Mock).mockImplementation(() => { + wallet.cancelScan(); + return { transactionsScanned: SCAN_SLICE_SIZE, outputsScanned: 0, matchedUtxos: [] }; + }); + + await expect(wallet.scanForPayments()).resolves.toBe(0); + + expect(spScanTransactions).toHaveBeenCalledTimes(1); + expect(wallet.getScanState()).toMatchObject({ status: 'idle', lastScannedBlock: TIP - 10 }); + }); + it('stops polling while the birth height is still unknown, leaving its retries to refreshes', async () => { stubIndexer({ getBlockHeightByTimestamp: jest.fn().mockRejectedValue(new Error('indexer down')) }); const wallet = track(syncedWallet(0));