From 7b439b79407db524cf71843a6274fcaa53f4ac4f Mon Sep 17 00:00:00 2001 From: sneurlax Date: Tue, 17 Nov 2026 12:05:59 -0600 Subject: [PATCH] test: add Grin native-chain end-to-end coverage Exercise real wallet, Slatepack, invoice, cancellation, repost, payment-proof, restore, reopen, and delete flows on the native test chain. --- docs/building/testing.md | 27 + .../grin/grin_test_chain_test.dart | 731 ++++++++++++++++++ integration_test/grin/test_chain_backend.dart | 359 +++++++++ scripts/grin_e2e_test.sh | 116 +++ scripts/grin_symbol_gate.sh | 57 ++ 5 files changed, 1290 insertions(+) create mode 100644 integration_test/grin/grin_test_chain_test.dart create mode 100644 integration_test/grin/test_chain_backend.dart create mode 100755 scripts/grin_e2e_test.sh create mode 100755 scripts/grin_symbol_gate.sh diff --git a/docs/building/testing.md b/docs/building/testing.md index b34bfa4211..0c7715a534 100644 --- a/docs/building/testing.md +++ b/docs/building/testing.md @@ -29,6 +29,33 @@ compiler: python3 -m unittest discover -s scripts/linux/tests -p 'test_*.py' -v ``` +## Grin integration tests + +The unit tests in `test/wallets/grin` use fakes and need no native code. + +`integration_test/grin/grin_test_chain_test.dart` drives `GrinWallet` against +the real `grin-ffi` library on its in-process test chain. It covers mining, +Slatepack S1/S2/S3, invoices, cancellation, reposting, payment proofs, +mnemonic restore with a scan, and wallet deletion. Run it through the wrapper: + +```sh +bash scripts/grin_e2e_test.sh # host desktop +bash scripts/grin_e2e_test.sh linux # explicit device +``` + +The wrapper temporarily enables `grin_native`'s `test_utils` build, restores +the generated pubspec files when it exits, and removes the test-enabled Grin +library from the application build directory. If the process is killed before +cleanup, configure the app again and delete its build output before producing +a distributable build. + +After a normal release build, verify that it contains only the 36 production +exports and no `grin_test_` exports: + +```sh +bash scripts/grin_symbol_gate.sh build/linux/x64/release/bundle +``` + ## Xelis integration tests Run these on a configured desktop target (`windows`, `linux`, or `macos`) with diff --git a/integration_test/grin/grin_test_chain_test.dart b/integration_test/grin/grin_test_chain_test.dart new file mode 100644 index 0000000000..6f1fb62a39 --- /dev/null +++ b/integration_test/grin/grin_test_chain_test.dart @@ -0,0 +1,731 @@ +// Drives GrinWallet against the real grin-ffi library on its in-process test +// chain. Needs the library built with the test_utils user-define; run it +// with scripts/grin_e2e_test.sh (see docs/building.md, Grin). + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:event_bus/event_bus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:logger/logger.dart'; +import 'package:path/path.dart' as p; +import 'package:stackwallet/db/hive/db.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; +import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/logger.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/prefs.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin_wallet_info_extension.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; + +import '../../test/support/memory_secrets.dart'; +import 'test_chain_backend.dart'; + +/// Coinbase reward on the test chain. +const int reward = 60; +final BigInt _nano = BigInt.from(1000000000); + +Amount grin(int whole) => + Amount(rawValue: BigInt.from(whole) * _nano, fractionDigits: 9); +Amount nano(BigInt raw) => Amount(rawValue: raw, fractionDigits: 9); + +/// GrinWallet with the test backend and a fixed wallet id. Tor is compiled +/// out so the transport is direct. +class E2eGrinWallet extends GrinWallet { + E2eGrinWallet(this._id, TestChainBackend backend, EventBus bus) + : super(CryptoCurrencyNetwork.main, backend: backend, eventBus: bus); + + final String _id; + + @override + String get walletId => _id; + + @override + bool get torFeatureEnabled => false; +} + +late MemorySecrets secrets; +late NodeService nodes; +late Directory root; + +/// One test chain and the wallets on it. +class Chain { + Chain._(this.dir) : backend = TestChainBackend(dir); + + static int _sequence = 0; + + static Future start() async { + final dir = Directory(p.join(root.path, 'chains', 'c${_sequence++}')); + await dir.create(recursive: true); + final chain = Chain._(dir.path); + addTearDown(chain.dispose); + return chain; + } + + final String dir; + final TestChainBackend backend; + final bus = EventBus(); + final List _wallets = []; + + /// Sync status events GrinWallet fired itself, by wallet id. + final Map> statuses = {}; + StreamSubscription? _sub; + + /// A wallet with its WalletInfo and mnemonic stored. Opened unless + /// [restore] is set, in which case the caller recovers it. + Future wallet( + String name, { + String? mnemonic, + int restoreHeight = 0, + bool restore = false, + }) async { + _sub ??= bus.on().listen( + (e) => statuses.putIfAbsent(e.walletId, () => []).add(e.newStatus), + ); + final walletId = 'e2e-$name-${_sequence++}'; + await MainDB.instance.putWalletInfo( + WalletInfo( + walletId: walletId, + name: name, + mainAddressType: AddressType.mimbleWimble, + coinName: 'grin', + restoreHeight: restoreHeight, + ), + ); + secrets.values[Wallet.mnemonicKey(walletId: walletId)] = + mnemonic ?? await backend.generateMnemonic(); + secrets.values[Wallet.mnemonicPassphraseKey(walletId: walletId)] = ''; + final wallet = open(walletId); + if (!restore) await wallet.init(); + return wallet; + } + + /// A new instance for an existing wallet id, as a later app start makes. + E2eGrinWallet open(String walletId) { + final wallet = E2eGrinWallet(walletId, backend, bus) + ..mainDB = MainDB.instance + ..secureStorageInterface = secrets + ..prefs = Prefs.instance + ..nodeService = nodes; + _wallets.add(wallet); + return wallet; + } + + Future dirOf(GrinWallet wallet) => + GrinWallet.walletDirPath(wallet.walletId); + + Future api(GrinWallet wallet) async => + backend.apiFor(await dirOf(wallet)); + + Future mine(GrinWallet wallet, int blocks) async => + backend.mine(await dirOf(wallet), blocks); + + Future dispose() async { + for (final wallet in _wallets.reversed) { + try { + await wallet.exit(); + } catch (_) {} + } + await _sub?.cancel(); + } +} + +/// Waits for a refresh a call started, then updates height, history and +/// balance with errors surfaced. The base refresh only logs them. +Future sync(GrinWallet wallet) async { + await wallet.refresh(); + await wallet.refreshMutex.protect(() async { + await wallet.updateChainHeight(); + await wallet.updateTransactions(); + await wallet.updateBalance(); + }); +} + +Future> rows(GrinWallet wallet) => MainDB + .instance + .isar + .transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll(); + +Future row(GrinWallet wallet, String txid) async { + final tx = await MainDB.instance.isar.transactionV2s + .where() + .txidWalletIdEqualTo(txid, wallet.walletId) + .findFirst(); + expect(tx, isNotNull, reason: 'no row $txid in ${wallet.walletId}'); + return tx!; +} + +Map otherData(TransactionV2 tx) => + Map.from(jsonDecode(tx.otherData!) as Map); + +String label(GrinWallet wallet, TransactionV2 tx) => tx.statusLabel( + currentChainHeight: wallet.info.cachedChainHeight, + minConfirms: wallet.cryptoCurrency.minConfirms, + minCoinbaseConfirms: wallet.cryptoCurrency.minCoinbaseConfirms, +); + +Amount received(TransactionV2 tx) => + tx.getAmountReceivedInThisWallet(fractionDigits: 9); + +Amount sent(TransactionV2 tx) => + tx.getAmountSentFromThisWallet(fractionDigits: 9, subtractFee: true); + +Amount fee(TransactionV2 tx) => tx.getFee(fractionDigits: 9); + +TxData sendTo(String address, Amount amount) => TxData( + recipients: [ + TxRecipient( + address: address, + amount: amount, + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], +); + +/// Polls [check] in real time. +Future eventually( + FutureOr Function() check, { + required String reason, + Duration timeout = const Duration(seconds: 90), +}) async { + final deadline = DateTime.now().add(timeout); + while (!await check()) { + if (DateTime.now().isAfter(deadline)) fail('timed out: $reason'); + await Future.delayed(const Duration(milliseconds: 200)); + } +} + +/// A funded sender at height 15 and an empty receiver. With 10 +/// confirmations required, the coinbase outputs of heights 1 to 6 are +/// spendable. +Future<({Chain chain, E2eGrinWallet alice, E2eGrinWallet bob})> +fundedPair() async { + final chain = await Chain.start(); + final alice = await chain.wallet('alice'); + final bob = await chain.wallet('bob'); + expect(await chain.mine(alice, 15), 15); + await sync(alice); + await sync(bob); + expect(alice.info.cachedBalance.spendable, grin(6 * reward)); + return (chain: chain, alice: alice, bob: bob); +} + +const _timeout = Timeout(Duration(minutes: 10)); + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() async { + if (!(Platform.isLinux || Platform.isMacOS || Platform.isWindows)) { + fail('Run the Grin test chain suite on a desktop host.'); + } + root = await Directory.systemTemp.createTemp('stack_grin_e2e_'); + StackFileSystem.setDesktopOverrideDir(root.path); + // A device run has no FLUTTER_TEST, so the logger needs its isolate. + final logs = Directory(p.join(root.path, 'logs'))..createSync(); + await Logging.instance.initialize(logs.path, level: Level.warning); + await MainDB.instance.initMainDB(); + final hive = DB.instance.hive..init(p.join(root.path, 'hive')); + hive.registerAdapter(NodeModelAdapter()); + await hive.openBox(DB.boxNamePrefs); + await hive.openBox(DB.boxNameNodeModels); + await Prefs.instance.init(); + secrets = MemorySecrets({}); + nodes = NodeService(secureStorageInterface: secrets); + }); + + tearDownAll(() async { + try { + await MainDB.instance.isar.close(); + await DB.instance.hive.close(); + } finally { + await root.delete(recursive: true); + } + }); + + testWidgets('a new wallet needs no scan and sees coinbase it mined', ( + tester, + ) async { + final chain = await Chain.start(); + final alice = await chain.wallet('alice'); + final dir = await chain.dirOf(alice); + + // Created as new, so no genesis scan is pending. + expect(chain.backend.calls, ['create:${alice.walletId}:new=true']); + expect(alice.info.grinData?.pendingScanFrom, isNull); + expect(alice.info.grinData?.creationHeight, greaterThan(0)); + final address = (await alice.getCurrentReceivingAddress())!; + expect(address.value, startsWith('tgrin1')); + expect(address.type, AddressType.mimbleWimble); + expect(address.derivationIndex, 0); + expect(alice.info.cachedReceivingAddress, address.value); + expect(Directory(p.join(dir, 'wallet_data')).existsSync(), isTrue); + expect(secrets.values[GrinWallet.passwordKey(alice.walletId)], isNotEmpty); + + expect(await chain.mine(alice, 12), 12); + await alice.refresh(); + await sync(alice); + + expect(chain.backend.calls.where((c) => c.startsWith('scan')), isEmpty); + expect(alice.isScanPending, isFalse); + expect(alice.info.cachedChainHeight, 12); + final balance = alice.info.cachedBalance; + expect(balance.total, grin(12 * reward)); + // Heights 1 to 3 have 10 confirmations at 12. + expect(balance.spendable, grin(3 * reward)); + expect(balance.pendingSpendable, grin(9 * reward)); + + final txs = await rows(alice); + expect(txs, hasLength(12)); + final heights = {}; + for (final tx in txs) { + expect(tx.txid, startsWith('grin_cb_')); + expect(tx.type, TransactionType.incoming); + expect(tx.isCoinbase(), isTrue); + expect(received(tx), grin(reward)); + expect(fee(tx), grin(0)); + heights.add(tx.height!); + final data = otherData(tx); + expect(data[TxV2OdKeys.isGrinTransaction], isTrue); + expect(data[TxV2OdKeys.slateId], isNull); + expect(data[TxV2OdKeys.isCancelled], isFalse); + expect(data[TxV2OdKeys.grinLogIds], hasLength(1)); + // Coinbase needs Stack's 1440 confirmations. + expect(label(alice, tx), startsWith('Receiving (')); + expect(label(alice, tx), endsWith('/1440)')); + } + expect(heights, {for (var h = 1; h <= 12; h++) h}); + expect((await chain.api(alice)).networkUpdates, isEmpty); + }, timeout: _timeout); + + testWidgets('Slatepack S1, S2, S3 between two GrinWallets', (tester) async { + final (:chain, :alice, :bob) = await fundedPair(); + final bobAddress = await bob.slatepackAddress(); + final aliceAddress = await alice.slatepackAddress(); + final before = alice.info.cachedBalance.spendable; + + final prepared = await alice.prepareSend( + txData: sendTo(bobAddress, grin(50)), + ); + expect(prepared.fee!.raw, greaterThan(BigInt.zero)); + expect(prepared.recipients!.single.amount, grin(50)); + final confirmed = await alice.confirmSend(txData: prepared); + final slateId = confirmed.txid!; + final s1 = confirmed.slatepack!; + expect(s1, startsWith('BEGINSLATEPACK.')); + expect(confirmed.fee, prepared.fee); + + await sync(alice); + var a = await row(alice, slateId); + expect(a.type, TransactionType.outgoing); + expect(a.height, isNull); + expect(label(alice, a), 'Sending (waiting for response)'); + var data = otherData(a); + expect(data[TxV2OdKeys.slateId], slateId); + expect(data[TxV2OdKeys.grinSlateState], 'S1'); + expect(data[TxV2OdKeys.counterpartyAddress], bobAddress); + expect(data[TxV2OdKeys.grinHasPaymentProof], isTrue); + expect(data[TxV2OdKeys.grinHasStoredTx], isFalse); + expect(data[TxV2OdKeys.grinTtlCutoff], isNotNull); + expect(fee(a), confirmed.fee); + // The inputs are locked, and libwallet leaves locked outputs out. + expect(alice.info.cachedBalance.spendable < before, isTrue); + expect(await alice.pendingSlatepackFor(slateId), s1); + + final inspected = await bob.inspectSlatepack(s1); + expect(inspected.state, GrinSlateState.s1); + expect(inspected.amount, grin(50).raw); + expect(inspected.sender, aliceAddress); + final s2 = await bob.receiveSlatepack(s1); + expect(s2.state, GrinSlateState.s2); + expect(s2.slateId, slateId); + + await sync(bob); + var b = await row(bob, slateId); + expect(b.type, TransactionType.incoming); + expect(label(bob, b), 'Receiving (waiting for sender to finalize)'); + expect(otherData(b)[TxV2OdKeys.grinSlateState], 'S2'); + expect(otherData(b)[TxV2OdKeys.counterpartyAddress], aliceAddress); + expect(received(b), grin(50)); + expect(bob.info.cachedBalance.pendingSpendable, grin(50)); + expect(bob.info.cachedBalance.spendable, grin(0)); + + final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + expect(s3.posted, isTrue); + expect(s3.kernelExcess, hasLength(66)); + // Posting mined height 16; ten more give it 11 confirmations. + expect(await chain.mine(alice, 10), 26); + + await sync(alice); + await sync(bob); + a = await row(alice, slateId); + data = otherData(a); + expect(a.height, 16); + expect(label(alice, a), 'Sent'); + expect(data[TxV2OdKeys.grinSlateState], 'S3'); + expect(data[TxV2OdKeys.grinKernelExcess], s3.kernelExcess); + expect(data[TxV2OdKeys.grinHasStoredTx], isTrue); + expect(a.hash, s3.kernelExcess); + expect(sent(a), grin(50)); + expect(fee(a), nano(s3.fee)); + + b = await row(bob, slateId); + expect(b.height, 16); + expect(label(bob, b), 'Received'); + expect(otherData(b)[TxV2OdKeys.grinKernelExcess], s3.kernelExcess); + expect(bob.info.cachedBalance.spendable, grin(50)); + expect(bob.info.cachedBalance.total, grin(50)); + expect((await chain.api(alice)).networkUpdates, isEmpty); + expect((await chain.api(bob)).networkUpdates, isEmpty); + }, timeout: _timeout); + + testWidgets('invoice I1, I2, I3 with the amount guard', (tester) async { + final (:chain, :alice, :bob) = await fundedPair(); + final aliceAddress = await alice.slatepackAddress(); + final before = alice.info.cachedBalance.spendable; + + final i1 = await bob.issueInvoice( + amount: grin(30), + payerAddress: aliceAddress, + ); + expect(i1.state, GrinSlateState.i1); + await sync(bob); + var b = await row(bob, i1.slateId); + expect(b.type, TransactionType.incoming); + expect(label(bob, b), 'Invoice issued (waiting for payer)'); + expect(otherData(b)[TxV2OdKeys.grinSlateState], 'I1'); + + // An amount other than the invoice's is refused before the library is + // asked to pay, and nothing is recorded or locked. + await expectLater( + alice.processInvoice( + i1.armoredSlatepack, + confirmedAmount: nano(grin(30).raw - BigInt.one), + ), + throwsA( + predicate( + (e) => e.toString().contains('does not match'), + 'amount mismatch', + ), + ), + ); + expect( + chain.backend.calls.where((c) => c.startsWith('processInvoice')), + isEmpty, + ); + await sync(alice); + expect( + await MainDB.instance.isar.transactionV2s + .where() + .txidWalletIdEqualTo(i1.slateId, alice.walletId) + .findFirst(), + isNull, + ); + expect(alice.info.cachedBalance.spendable, before); + + final i2 = await alice.processInvoice( + i1.armoredSlatepack, + confirmedAmount: grin(30), + ); + expect(i2.state, GrinSlateState.i2); + expect( + chain.backend.calls.where((c) => c.startsWith('processInvoice')), + hasLength(1), + ); + await sync(alice); + var a = await row(alice, i1.slateId); + expect(a.type, TransactionType.outgoing); + expect(label(alice, a), 'Paying invoice (waiting for invoicer)'); + expect(otherData(a)[TxV2OdKeys.grinSlateState], 'I2'); + expect(alice.info.cachedBalance.spendable < before, isTrue); + + final i3 = await bob.finalizeInvoice(i2.armoredSlatepack); + expect(i3.posted, isTrue); + // Posting mined height 16, to Bob. + expect(await chain.mine(alice, 10), 26); + await sync(alice); + await sync(bob); + + b = await row(bob, i1.slateId); + expect(b.height, 16); + expect(label(bob, b), 'Received'); + expect(received(b), grin(30)); + expect(otherData(b)[TxV2OdKeys.grinKernelExcess], i3.kernelExcess); + a = await row(alice, i1.slateId); + expect(a.height, 16); + expect(label(alice, a), 'Sent'); + expect(sent(a), grin(30)); + expect(fee(a), nano(i2.fee)); + // Bob also got the block 16 coinbase and the fee. + expect(bob.info.cachedBalance.total, grin(30 + reward) + nano(i2.fee)); + }, timeout: _timeout); + + testWidgets('cancelling an unfinalized send unlocks its inputs', ( + tester, + ) async { + final (:chain, :alice, :bob) = await fundedPair(); + final before = alice.info.cachedBalance; + + final slate = await alice.createSlatepack( + amount: grin(10), + recipientAddress: await bob.slatepackAddress(), + ); + await sync(alice); + expect(alice.info.cachedBalance.spendable < before.spendable, isTrue); + expect( + label(alice, await row(alice, slate.slateId)), + 'Sending (waiting for response)', + ); + + expect(await alice.cancelPendingTransactionAndPost(slate.slateId), ''); + await sync(alice); + final tx = await row(alice, slate.slateId); + expect(tx.isCancelled, isTrue); + expect(label(alice, tx), 'Cancelled'); + expect(tx.height, isNull); + expect(alice.info.cachedBalance.spendable, before.spendable); + expect(alice.info.cachedBalance.total, before.total); + + // A second cancel is reported, not thrown. + expect( + await alice.cancelPendingTransactionAndPost(slate.slateId), + isNotEmpty, + ); + }, timeout: _timeout); + + testWidgets('repost broadcasts a finalized send that was not posted', ( + tester, + ) async { + final (:chain, :alice, :bob) = await fundedPair(); + final slate = await alice.createSlatepack( + amount: grin(20), + recipientAddress: await bob.slatepackAddress(), + ); + + // Nothing is stored to post yet. + await sync(alice); + await expectLater(alice.repost(slate.slateId), throwsA(anything)); + expect(chain.backend.calls.where((c) => c.startsWith('repost')), isEmpty); + + final s2 = await bob.receiveSlatepack(slate.armoredSlatepack); + (await chain.api(alice)).skipNextBroadcast = true; + final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + expect(s3.posted, isFalse); + await sync(alice); + var tx = await row(alice, slate.slateId); + expect(otherData(tx)[TxV2OdKeys.grinHasStoredTx], isTrue); + expect(tx.height, isNull); + expect(alice.info.cachedChainHeight, 15); + + await alice.repost(slate.slateId); + expect( + chain.backend.calls.where((c) => c.startsWith('repost')), + hasLength(1), + ); + // Posting mined height 16. + expect(await chain.mine(alice, 10), 26); + await sync(alice); + await sync(bob); + tx = await row(alice, slate.slateId); + expect(tx.height, 16); + expect(label(alice, tx), 'Sent'); + expect(otherData(tx)[TxV2OdKeys.grinKernelExcess], s3.kernelExcess); + expect(bob.info.cachedBalance.spendable, grin(20)); + }, timeout: _timeout); + + testWidgets('payment proof export and verify', (tester) async { + final (:chain, :alice, :bob) = await fundedPair(); + final slate = await alice.createSlatepack( + amount: grin(25), + recipientAddress: await bob.slatepackAddress(), + ); + final s2 = await bob.receiveSlatepack(slate.armoredSlatepack); + final s3 = await alice.finalizeSlatepack(s2.armoredSlatepack); + await chain.mine(alice, 1); + await sync(alice); + await sync(bob); + + final json = await alice.exportPaymentProof(slate.slateId); + final proof = GrinPaymentProof.fromJsonString(json); + expect(proof.amount, grin(25).raw); + expect(proof.excess, s3.kernelExcess); + expect(proof.senderAddress, await alice.slatepackAddress()); + expect(proof.recipientAddress, await bob.slatepackAddress()); + + final asSender = await alice.verifyPaymentProof(json); + expect(asSender.isSender, isTrue); + expect(asSender.isRecipient, isFalse); + final asRecipient = await bob.verifyPaymentProof(json); + expect(asRecipient.isSender, isFalse); + expect(asRecipient.isRecipient, isTrue); + + final tampered = jsonEncode({...proof.toJson(), 'amount': '20'}); + await expectLater(bob.verifyPaymentProof(tampered), throwsA(anything)); + await expectLater( + bob.verifyPaymentProof('not a proof'), + throwsA( + predicate((e) => e.toString().contains('not a Grin payment proof')), + ), + ); + // The receiving side keeps no proof. + expect( + otherData(await row(bob, slate.slateId))[TxV2OdKeys.grinHasPaymentProof], + isFalse, + ); + await expectLater( + bob.exportPaymentProof(slate.slateId), + throwsA(predicate((e) => e.toString().contains('no payment proof'))), + ); + }, timeout: _timeout); + + testWidgets('restore from a mnemonic scans from the restore height and ' + 'resumes a cancelled scan', (tester) async { + final chain = await Chain.start(); + final miner = await chain.wallet('miner'); + final original = await chain.wallet('original'); + expect(await chain.mine(miner, 3), 3); + // Heights 4 to 15 pay the original wallet. + expect(await chain.mine(original, 12), 15); + await sync(original); + final mnemonic = await original.getMnemonic(); + final address = await original.slatepackAddress(); + + final restored = await chain.wallet( + 'restored', + mnemonic: mnemonic, + restoreHeight: 4, + restore: true, + ); + await restored.init(isRestore: true); + expect( + chain.backend.calls.where((c) => c.contains(restored.walletId)), + isEmpty, + ); + + chain.backend.cancelNextScan = true; + await restored.recover(isRescan: false); + expect( + chain.backend.calls, + contains('create:${restored.walletId}:new=false'), + ); + expect((await restored.getCurrentReceivingAddress())!.value, address); + + // The scan job ends cancelled: the resume height is saved, no error is + // reported and nothing is found yet. + final api = await chain.api(restored); + await eventually( + () => api.scanStarts.length == 1 && !restored.refreshMutex.isLocked, + reason: 'first scan', + ); + expect(api.scanStarts, [4]); + expect(restored.info.grinData?.pendingScanFrom, 4); + expect(restored.isScanPending, isTrue); + expect( + chain.statuses[restored.walletId], + isNot(contains(WalletSyncStatus.unableToSync)), + ); + expect(await rows(restored), isEmpty); + + // Sends wait for the scan. + await expectLater( + restored.prepareSend(txData: sendTo(address, grin(1))), + throwsA(predicate((e) => e.toString().contains('scanning'))), + ); + + // The next refresh resumes it and the funds appear. + await restored.refresh(); + await eventually( + () async => + restored.info.grinData?.pendingScanFrom == null && + restored.info.cachedBalance.total == grin(12 * reward), + reason: 'resumed scan and refresh', + ); + expect(api.scanStarts, [4, 4]); + expect(restored.restoreProgress, 1); + await sync(restored); + expect( + restored.info.cachedBalance.spendable, + original.info.cachedBalance.spendable, + ); + expect( + restored.info.cachedBalance.total, + original.info.cachedBalance.total, + ); + final found = await rows(restored); + expect(found, hasLength(12)); + expect( + found.fold(grin(0), (sum, tx) => sum + received(tx)), + grin(12 * reward), + ); + expect(found.every((tx) => tx.type == TransactionType.incoming), isTrue); + expect( + chain.statuses[restored.walletId], + contains(WalletSyncStatus.syncing), + ); + }, timeout: _timeout); + + testWidgets('reopen with the stored password, then delete', (tester) async { + final chain = await Chain.start(); + final first = await chain.wallet('doomed'); + final walletId = first.walletId; + final dir = await chain.dirOf(first); + final address = await first.slatepackAddress(); + await chain.mine(first, 2); + await sync(first); + await first.exit(); + expect(first.isOpen, isFalse); + + // A later start opens the same files with the stored password. + final again = chain.open(walletId); + await again.init(); + expect(chain.backend.calls, contains('open:$walletId')); + expect( + chain.backend.calls.where((c) => c.startsWith('create:$walletId')), + hasLength(1), + ); + expect(await again.getNativeReceivingAddress(), address); + await sync(again); + expect(again.info.cachedBalance.total, grin(2 * reward)); + final api = await chain.api(again); + + // Delete closes the live instance first. + expect( + await GrinWallet.deleteWalletFiles( + walletId: walletId, + secureStore: secrets, + backend: chain.backend, + ), + isTrue, + ); + expect(again.isOpen, isFalse); + expect(api.isClosed, isTrue); + expect(chain.backend.calls.last, 'delete:$walletId'); + expect(Directory(p.join(dir, 'wallet_data')).existsSync(), isFalse); + expect(Directory(dir).existsSync(), isFalse); + expect( + secrets.values.containsKey(GrinWallet.passwordKey(walletId)), + isFalse, + ); + expect(secrets.deletes, contains(GrinWallet.passwordKey(walletId))); + // Calls after the delete return quietly. + await again.refresh(); + }, timeout: _timeout); +} diff --git a/integration_test/grin/test_chain_backend.dart b/integration_test/grin/test_chain_backend.dart new file mode 100644 index 0000000000..2a81618c9b --- /dev/null +++ b/integration_test/grin/test_chain_backend.dart @@ -0,0 +1,359 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:grin_native/grin_native.dart'; +import 'package:grin_native/testing.dart'; +import 'package:path/path.dart' as p; + +/// What [TestChainApi.updateNetwork] was asked to apply. +typedef NetworkUpdate = ({ + String nodeUrl, + String? apiSecret, + String? socksProxy, + bool networkEnabled, +}); + +GrinException _grinError(int code, String message, [Object? details]) => + GrinException.fromJson( + code, + jsonEncode({'code': code, 'message': message, 'details': details}), + ); + +/// A [GrinWalletBackend] whose wallets live on one in-process test chain. +/// +/// GrinWallet passes its own network (mainnet in this app config) and node +/// URL. Both are replaced here: every wallet runs on automated testing, the +/// only chain the harness mines, and node calls go to the chain itself. +/// Needs the native library built with the test_utils user-define. +class TestChainBackend implements GrinWalletBackend { + TestChainBackend(this.chainDir); + + final String chainDir; + static const network = GrinNetwork.automatedTesting; + static const _native = GrinNativeBackend(); + + /// Calls made through this backend and its wallets, in order. + final List calls = []; + + /// Open wallets by wallet directory. + final Map _apis = {}; + + /// When true, the next scan on any wallet ends the way a scan cancelled + /// before its first batch does. + bool cancelNextScan = false; + + /// The open wallet in [walletDir]. + TestChainApi apiFor(String walletDir) { + final api = _apis[p.normalize(walletDir)]; + if (api == null || api.isClosed) { + throw StateError('No open test chain wallet in $walletDir'); + } + return api; + } + + /// Mines [count] blocks to the wallet in [walletDir] and returns the new + /// chain height. + Future mine(String walletDir, int count) => + GrinTestChain.mineBlocks(apiFor(walletDir).inner, count); + + Future _attach({ + required GrinWalletConfig config, + required String password, + String? mnemonic, + bool isNewWallet = false, + }) async { + final dir = p.normalize(config.walletDir); + final client = await GrinTestChain.createWallet( + chainDir: chainDir, + walletDir: dir, + // The wallet id: unique per chain, and stable so a reopen re-attaches. + clientId: p.basename(dir), + network: network, + mnemonic: mnemonic, + password: password, + isNewWallet: isNewWallet, + ); + final api = TestChainApi(client, this); + _apis[dir] = api; + return api; + } + + bool _hasSeed(String walletDir) => + File(p.join(walletDir, 'wallet_data', 'wallet.seed')).existsSync(); + + @override + Future create({ + required GrinWalletConfig config, + String? mnemonic, + required String password, + bool isNewWallet = false, + }) async { + calls.add('create:${p.basename(config.walletDir)}:new=$isNewWallet'); + // The harness opens an existing wallet instead; keep create's contract. + if (_hasSeed(config.walletDir)) { + throw _grinError(6, 'wallet exists', {'wallet_dir': config.walletDir}); + } + return _attach( + config: config, + password: password, + mnemonic: mnemonic, + isNewWallet: isNewWallet, + ); + } + + @override + Future open({ + required GrinWalletConfig config, + required String password, + }) async { + calls.add('open:${p.basename(config.walletDir)}'); + if (!_hasSeed(config.walletDir)) { + throw _grinError(4, 'wallet not found', {'wallet_dir': config.walletDir}); + } + return _attach(config: config, password: password); + } + + @override + Future delete({required String walletDir}) { + calls.add('delete:${p.basename(walletDir)}'); + return _native.delete(walletDir: walletDir); + } + + /// The chain tip, read through any open wallet on the chain. + @override + Future testNodeConnection({ + required String nodeUrl, + String? apiSecret, + String? socksProxy, + }) async { + final open = _apis.values.where((api) => !api.isClosed); + if (open.isEmpty) throw _grinError(9, 'no wallet on the test chain'); + final tip = await open.first.inner.getChainHeight(); + return GrinNodeInfo( + nodeVersion: 'test-chain', + blockHeaderVersion: 1, + height: tip.height, + hash: tip.hash, + ); + } + + @override + Future generateMnemonic({int wordCount = 24}) => + _native.generateMnemonic(wordCount: wordCount); + + @override + Future validateMnemonic(String mnemonic) => + _native.validateMnemonic(mnemonic); + + @override + Future validateAddress( + String address, + GrinNetwork network, + ) => _native.validateAddress(address, TestChainBackend.network); + + @override + GrinAddressValidation validateAddressSync( + String address, + GrinNetwork network, + ) => _native.validateAddressSync(address, TestChainBackend.network); + + @override + Future decodeSlatepackWithoutWallet( + String armored, + GrinNetwork network, + ) => _native.decodeSlatepackWithoutWallet(armored, TestChainBackend.network); +} + +/// A test chain wallet as GrinWallet sees it. +/// +/// updateNetwork is recorded and not applied: the real call swaps the +/// in-process chain client for an HTTP one, and the wallet would lose the +/// chain. Everything else goes to the real wallet. +class TestChainApi implements GrinWalletApi { + TestChainApi(this.inner, this._backend); + + final GrinWalletClient inner; + final TestChainBackend _backend; + final List networkUpdates = []; + final List scanStarts = []; + + List get _calls => _backend.calls; + + @override + String get walletDir => inner.walletDir; + + @override + GrinNetwork get network => inner.network; + + @override + bool get isClosed => inner.isClosed; + + @override + Stream get events => inner.events; + + @override + Future getAddress({int index = 0}) => + inner.getAddress(index: index); + + @override + Future getChainHeight() => inner.getChainHeight(); + + @override + Future getBalance({ + bool refreshFromNode = true, + int minimumConfirmations = 10, + }) => inner.getBalance( + refreshFromNode: refreshFromNode, + minimumConfirmations: minimumConfirmations, + ); + + @override + Future scan({ + int startHeight = 0, + bool deleteUnconfirmed = false, + }) async { + _calls.add('scan:${p.basename(walletDir)}:$startHeight'); + scanStarts.add(startHeight); + if (_backend.cancelNextScan) { + _backend.cancelNextScan = false; + // A chain this short is one 10,001-height batch, so a real cancel + // cannot be timed. Report what the library reports for a cancel that + // arrives before the first batch: nothing scanned below the start. + final tip = (await inner.getChainHeight()).height; + final start = startHeight < 1 ? 1 : startHeight; + final scanned = (start - 1) < tip ? start - 1 : tip; + throw _grinError(14, 'scan cancelled', { + 'scanned_height': scanned, + 'tip_height': tip, + }); + } + return inner.scan( + startHeight: startHeight, + deleteUnconfirmed: deleteUnconfirmed, + ); + } + + @override + Future lastScannedHeight() => inner.lastScannedHeight(); + + @override + GrinScanProgress scanProgress() => inner.scanProgress(); + + @override + void cancelScan() => inner.cancelScan(); + + @override + Future changePassword(String oldPassword, String newPassword) => + inner.changePassword(oldPassword, newPassword); + + @override + Future getMnemonic(String password) => inner.getMnemonic(password); + + @override + Future updateNetwork({ + required String nodeUrl, + required String? apiSecret, + required String? socksProxy, + required bool networkEnabled, + }) async { + networkUpdates.add(( + nodeUrl: nodeUrl, + apiSecret: apiSecret, + socksProxy: socksProxy, + networkEnabled: networkEnabled, + )); + } + + @override + Future estimateFee({ + required BigInt amount, + int minimumConfirmations = 10, + bool selectionStrategyIsAll = false, + bool amountIncludesFee = false, + }) => inner.estimateFee( + amount: amount, + minimumConfirmations: minimumConfirmations, + selectionStrategyIsAll: selectionStrategyIsAll, + amountIncludesFee: amountIncludesFee, + ); + + @override + Future getTransactions({bool refreshFromNode = true}) { + if (refreshFromNode) _calls.add('refresh:${p.basename(walletDir)}'); + return inner.getTransactions(refreshFromNode: refreshFromNode); + } + + @override + Future decodeSlatepack( + String armored, { + int secretIndex = 0, + }) => inner.decodeSlatepack(armored, secretIndex: secretIndex); + + @override + Future initSend(GrinSendArgs args) => inner.initSend(args); + + @override + Future sendHttp(GrinHttpSendArgs args) => + throw UnsupportedError('HTTP sends are not part of these tests'); + + @override + Future receiveSlatepack(String armoredS1) => + inner.receiveSlatepack(armoredS1); + + /// When true, the next finalize keeps the transaction without posting it, + /// as if the broadcast had failed. + bool skipNextBroadcast = false; + + @override + Future finalizeSlatepack( + String armoredS2, { + bool broadcast = true, + bool fluff = false, + }) { + final post = broadcast && !skipNextBroadcast; + skipNextBroadcast = false; + return inner.finalizeSlatepack(armoredS2, broadcast: post, fluff: fluff); + } + + @override + Future issueInvoice(GrinInvoiceArgs args) => + inner.issueInvoice(args); + + @override + Future processInvoice( + String armoredI1, + GrinProcessInvoiceArgs args, + ) { + _calls.add('processInvoice:${p.basename(walletDir)}'); + return inner.processInvoice(armoredI1, args); + } + + @override + Future finalizeInvoice( + String armoredI2, { + bool broadcast = true, + bool fluff = false, + }) => inner.finalizeInvoice(armoredI2, broadcast: broadcast, fluff: fluff); + + @override + Future repost({int? txId, String? slateId, bool fluff = false}) { + _calls.add('repost:${p.basename(walletDir)}'); + return inner.repost(txId: txId, slateId: slateId, fluff: fluff); + } + + @override + Future cancelTransaction({int? txId, String? slateId}) => + inner.cancelTransaction(txId: txId, slateId: slateId); + + @override + Future exportPaymentProof({int? txId, String? slateId}) => + inner.exportPaymentProof(txId: txId, slateId: slateId); + + @override + Future verifyPaymentProof( + GrinPaymentProof proof, + ) => inner.verifyPaymentProof(proof); + + @override + Future close() => inner.close(); +} diff --git a/scripts/grin_e2e_test.sh b/scripts/grin_e2e_test.sh new file mode 100755 index 0000000000..128171970b --- /dev/null +++ b/scripts/grin_e2e_test.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs the Grin end-to-end suite (integration_test/grin) against the real +# grin-ffi library on its in-process test chain. +# +# That chain exists only in a library built with grin_native's test_utils +# user-define. This script adds the define to the generated pubspec.yaml, +# runs the suite, and puts pubspec.yaml and pubspec.lock back however the run +# ends. The define never goes into the committed template, and release builds +# must not have it (scripts/grin_symbol_gate.sh checks). +# +# The first run compiles the library a second time with the feature on; the +# build hook keeps both builds under .dart_tool, so later runs and normal +# builds reuse them. The run leaves the test library in the app bundle under +# build/, so the script removes every Grin library from build/ when it ends. +# The next normal build puts the release library back; a bundle packaged +# without building again fails to load Grin instead of shipping the test +# chain. +# +# A run that is killed outright (SIGKILL, power loss) cannot clean up. Then +# pubspec.yaml still has the define and build/ still has the test library: +# configure the app again (scripts/build_app.sh) and delete build/ before +# building anything that will be distributed. +# +# Usage: bash scripts/grin_e2e_test.sh [device] [flutter test options] +# The device defaults to the host desktop. Set FLUTTER_BIN to use a Flutter +# executable other than the one on PATH. + +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." + +flutter_bin="${FLUTTER_BIN:-flutter}" +case "$(uname -s)" in + Linux*) default_device=linux ;; + Darwin*) default_device=macos ;; + *) default_device=windows ;; +esac +device="${1:-$default_device}" +if (( $# > 0 )); then shift; fi + +if [[ ! -f pubspec.yaml ]]; then + printf 'pubspec.yaml not found. Configure the app first (scripts/build_app.sh).\n' >&2 + exit 1 +fi +if ! grep -q '^ grin_native:' pubspec.yaml; then + printf 'grin_native is not a dependency. Configure an app with GRIN enabled.\n' >&2 + exit 1 +fi +if grep -q 'test_utils' pubspec.yaml; then + printf 'pubspec.yaml already mentions test_utils. Remove it and run again.\n' >&2 + exit 1 +fi + +backup_dir="$(mktemp -d "${TMPDIR:-/tmp}/grin_e2e.XXXXXX")" +cp pubspec.yaml "$backup_dir/pubspec.yaml" +if [[ -f pubspec.lock ]]; then cp pubspec.lock "$backup_dir/pubspec.lock"; fi + +restore() { + cp "$backup_dir/pubspec.yaml" pubspec.yaml + if [[ -f "$backup_dir/pubspec.lock" ]]; then + cp "$backup_dir/pubspec.lock" pubspec.lock + else + rm -f -- pubspec.lock + fi + rm -rf -- "$backup_dir" + remove_test_libraries +} + +# Deletes the Grin libraries the run left under build/. They were built with +# the test chain and must not be packaged. +remove_test_libraries() { + [[ -d build ]] || return 0 + find build -depth \( -name 'libgrin_ffi.so' -o -name 'libgrin_ffi.dylib' \ + -o -name 'grin_ffi.dll' -o -name 'grin_ffi.framework' \ + -o -name 'grin_ffi.framework.dSYM' \) -exec rm -rf -- {} + || true +} +trap restore EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +# Adds hooks.user_defines.grin_native.test_utils: true, inside an existing +# hooks block (the native prebuilts one) or as a new block at the end. +python3 - pubspec.yaml <<'PY' +import sys + +path = sys.argv[1] +with open(path) as f: + lines = f.read().split("\n") + +entry = [" grin_native:", " test_utils: true"] +try: + hooks = lines.index("hooks:") +except ValueError: + hooks = None + +if hooks is None: + while lines and lines[-1] == "": + lines.pop() + lines += ["", "hooks:", " user_defines:"] + entry + [""] +else: + end = hooks + 1 + while end < len(lines) and (lines[end].startswith(" ") or lines[end] == ""): + end += 1 + block = lines[hooks + 1:end] + if " user_defines:" in block: + at = hooks + 1 + block.index(" user_defines:") + 1 + lines[at:at] = entry + else: + lines[hooks + 1:hooks + 1] = [" user_defines:"] + entry + +with open(path, "w") as f: + f.write("\n".join(lines)) +PY + +"$flutter_bin" test integration_test/grin/grin_test_chain_test.dart \ + -d "$device" "$@" diff --git a/scripts/grin_symbol_gate.sh b/scripts/grin_symbol_gate.sh new file mode 100755 index 0000000000..1e8324170d --- /dev/null +++ b/scripts/grin_symbol_gate.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Checks that a built libgrin_ffi exports the grin-ffi API and no test hooks: +# exactly 36 `grin_` symbols and none starting with `grin_test_`. A library +# built with grin_native's test_utils user-define (scripts/grin_e2e_test.sh) +# fails, which is the point: release bundles must never carry the in-process +# test chain. +# +# Usage: bash scripts/grin_symbol_gate.sh [bundle dir or library file] +# Default: build/linux/x64/release/bundle. Set NM to use another nm. +# +# Linux and Android (.so): `nm -D --defined-only`, as here. llvm-nm from the +# NDK works the same way on Android libraries. +# macOS and iOS (grin_ffi.framework/grin_ffi or .dylib): `nm -gU ` or +# `llvm-nm --defined-only --extern-only `; Mach-O names carry a leading +# underscore (`_grin_...`), strip it before counting. +# Windows (grin_ffi.dll): `dumpbin /exports grin_ffi.dll` from a Visual +# Studio prompt, or `llvm-readobj --coff-exports grin_ffi.dll`, and count the +# export names the same way. + +expected=36 +target="${1:-build/linux/x64/release/bundle}" +nm_bin="${NM:-nm}" + +if [[ -d "$target" ]]; then + mapfile -t found < <(find "$target" -name 'libgrin_ffi.so*' -type f) + if (( ${#found[@]} != 1 )); then + printf 'Expected one libgrin_ffi.so under %s, found %d.\n' \ + "$target" "${#found[@]}" >&2 + exit 2 + fi + lib="${found[0]}" +elif [[ -f "$target" ]]; then + lib="$target" +else + printf '%s does not exist.\n' "$target" >&2 + exit 2 +fi + +symbols="$("$nm_bin" -D --defined-only "$lib" | awk '{print $NF}')" +api=$(grep -c '^grin_' <<<"$symbols" || true) +test_hooks=$(grep -c '^grin_test_' <<<"$symbols" || true) + +printf '%s: %d grin_ exports, %d grin_test_ exports\n' "$lib" "$api" "$test_hooks" +status=0 +if (( test_hooks != 0 )); then + printf 'FAIL: built with test_utils:\n' >&2 + grep '^grin_test_' <<<"$symbols" | sed 's/^/ /' >&2 + status=1 +fi +if (( api != expected )); then + printf 'FAIL: expected %d grin_ exports.\n' "$expected" >&2 + status=1 +fi +if (( status == 0 )); then printf 'OK\n'; fi +exit "$status"