From 026287986a4eccdd0ab8b2a453a40274da512ea7 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Tue, 17 Nov 2026 11:34:44 -0600 Subject: [PATCH] feat: add Grin wallet through grin_native Integrate Grin through the sole public Dart dependency grin_native, pinned directly to its final public commit. --- README.md | 1 + docs/building/native-libraries.md | 8 + .../desktop_forgot_password/harness.dart | 1 + .../wallet_creation/coin_matrix.dart | 1 + .../wallet_creation/seed_validators.dart | 3 + .../blockchain_data/v2/transaction_v2.dart | 64 + ...w_wallet_recovery_phrase_warning_view.dart | 33 +- .../restore_options_view.dart | 128 +- .../restore_wallet_view.dart | 5 + lib/pages/send_view/send_view.dart | 11 +- .../add_edit_node_view.dart | 36 +- .../helpers/restore_create_backup.dart | 8 +- .../sub_widgets/restoring_wallet_card.dart | 47 +- .../wallet_network_settings_view.dart | 171 +- .../wallet_settings_wallet_settings_view.dart | 51 +- .../tx_v2/transaction_v2_details_view.dart | 6 +- .../wallet_view/sub_widgets/desktop_send.dart | 2 +- .../sub_widgets/wallet_options_button.dart | 59 +- ...desktop_manage_block_explorers_dialog.dart | 76 +- lib/services/node_service.dart | 2 + lib/services/price.dart | 1 + lib/services/wallets.dart | 99 +- lib/utilities/amount/amount_unit.dart | 5 +- lib/utilities/desktop_startup_and_reset.dart | 1 + lib/utilities/native_library_check.dart | 8 + lib/utilities/owner_only_directory.dart | 35 + lib/utilities/stack_file_system.dart | 14 + lib/utilities/test_grin_node_connection.dart | 72 + lib/utilities/test_node_connection.dart | 13 + lib/wallets/crypto_currency/coins/grin.dart | 188 ++ .../crypto_currency/crypto_currency.dart | 1 + lib/wallets/isar/models/wallet_info.dart | 1 + lib/wallets/models/tx_data.dart | 18 + lib/wallets/wallet/impl/grin_wallet.dart | 1608 +++++++++++++++++ .../wallet/supporting/grin/grin_errors.dart | 92 + .../wallet/supporting/grin/grin_node_url.dart | 75 + .../supporting/grin/grin_transport.dart | 212 +++ .../supporting/grin/grin_tx_mapping.dart | 205 +++ .../grin_wallet_info_extension.dart | 58 + lib/wallets/wallet/wallet.dart | 4 + .../slatepack_interface.dart | 35 + lib/wl_gen/interfaces/libgrin_interface.dart | 11 + pubspec.lock | 9 + scripts/app_config/configure_stack_wallet.sh | 7 +- .../templates/pubspec.template.yaml | 8 + scripts/ensure_test_app_config.sh | 1 + .../tests/wallet_creation_runner_test.dart | 8 +- test/support/memory_secrets.dart | 42 + test/utilities/native_library_check_test.dart | 13 +- test/wallets/grin/grin_coin_test.dart | 106 ++ test/wallets/grin/grin_errors_test.dart | 172 ++ test/wallets/grin/grin_invoice_test.dart | 90 + test/wallets/grin/grin_lifecycle_test.dart | 317 ++++ test/wallets/grin/grin_node_url_test.dart | 67 + test/wallets/grin/grin_scan_test.dart | 325 ++++ test/wallets/grin/grin_send_policy_test.dart | 206 +++ test/wallets/grin/grin_swb_test.dart | 95 + .../grin/grin_transport_policy_test.dart | 206 +++ test/wallets/grin/grin_transport_test.dart | 165 ++ test/wallets/grin/grin_tx_mapping_test.dart | 281 +++ .../grin/grin_wallets_service_test.dart | 132 ++ test/wallets/support/grin_fakes.dart | 820 +++++++++ test/wallets/support/xelis_test_fakes.dart | 34 +- test/widget_tests/node_tls_trust_test.dart | 64 + .../GRIN_libgrin_interface_impl.template.dart | 23 + 65 files changed, 6308 insertions(+), 352 deletions(-) create mode 100644 lib/utilities/owner_only_directory.dart create mode 100644 lib/utilities/test_grin_node_connection.dart create mode 100644 lib/wallets/crypto_currency/coins/grin.dart create mode 100644 lib/wallets/wallet/impl/grin_wallet.dart create mode 100644 lib/wallets/wallet/supporting/grin/grin_errors.dart create mode 100644 lib/wallets/wallet/supporting/grin/grin_node_url.dart create mode 100644 lib/wallets/wallet/supporting/grin/grin_transport.dart create mode 100644 lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart create mode 100644 lib/wallets/wallet/supporting/grin_wallet_info_extension.dart create mode 100644 lib/wl_gen/interfaces/libgrin_interface.dart create mode 100644 test/support/memory_secrets.dart create mode 100644 test/wallets/grin/grin_coin_test.dart create mode 100644 test/wallets/grin/grin_errors_test.dart create mode 100644 test/wallets/grin/grin_invoice_test.dart create mode 100644 test/wallets/grin/grin_lifecycle_test.dart create mode 100644 test/wallets/grin/grin_node_url_test.dart create mode 100644 test/wallets/grin/grin_scan_test.dart create mode 100644 test/wallets/grin/grin_send_policy_test.dart create mode 100644 test/wallets/grin/grin_swb_test.dart create mode 100644 test/wallets/grin/grin_transport_policy_test.dart create mode 100644 test/wallets/grin/grin_transport_test.dart create mode 100644 test/wallets/grin/grin_tx_mapping_test.dart create mode 100644 test/wallets/grin/grin_wallets_service_test.dart create mode 100644 test/wallets/support/grin_fakes.dart create mode 100644 tool/wl_templates/GRIN_libgrin_interface_impl.template.dart diff --git a/README.md b/README.md index 70bf3f836f..319c235d1a 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Highlights include: - [Dogecoin](https://dogecoin.com/) - [Epic Cash](https://linktr.ee/epiccash) - [MimbleWimbleCoin](https://mwc.mw) + - [Grin](https://grin.mw/) - [Ethereum](https://ethereum.org/en/) - [Ecash](https://e.cash/) - [Fact0rn](https://www.fact0rn.io/) diff --git a/docs/building/native-libraries.md b/docs/building/native-libraries.md index e9f4e38a8c..5c2ab05459 100644 --- a/docs/building/native-libraries.md +++ b/docs/building/native-libraries.md @@ -61,6 +61,7 @@ to build them in `dev` mode. | Flutter and platform plugins | Target SDKs and the platform's C/C++ build tools in either mode | | OpenAlias / DNSSEC (every app) | Rustup on the Flutter host in both modes; `dnssec_resolver` builds from source with Rust **1.90.0** | | Xelis (Stack Wallet) | Rustup; its hook installs Rust **1.99.1** and the required target; Android needs NDK r28 or newer | +| Grin (Stack Wallet) | Rustup; the `grin_native` hook builds `grin-ffi` and its pinned Grin wallet/core sources fetched over public HTTPS | | Spark (Stack Wallet and Campfire) | CMake and a C++ compiler; its native-assets hook builds from source | | Coinlib secp256k1 | A separate platform build, described in each host guide | | MWEB (Stack Wallet) | Go **1.24.1** or newer; CI uses 1.24.13. The Windows executable has a separate WSL build (Go 1.24.0 or newer) or prebuilt download | @@ -78,6 +79,13 @@ This build doesn't use the earlier manual steps for these packages: host Rust toolchain lists, `cbindgen`, `cargo-lipo`, building the Epic, MWC and Tor libraries by hand, the MXE setup, or the Epic-specific CMake upgrade. +Stack Wallet depends only on `grin_native`, which re-exports the shared Grin +API; it does not depend on the separate `grin` Dart package. To build against +a local `grin_native` checkout, edit the generated `pubspec.yaml` after +configuration (it is not committed), replace the Git dependency with the +checkout path, and run `flutter pub upgrade grin_native` after each library +commit. + ## When native hooks run The icon and splash `dart run` commands during configuration use only those diff --git a/integration_test/desktop_forgot_password/harness.dart b/integration_test/desktop_forgot_password/harness.dart index 32c5d966b8..730789afbc 100644 --- a/integration_test/desktop_forgot_password/harness.dart +++ b/integration_test/desktop_forgot_password/harness.dart @@ -42,6 +42,7 @@ const _walletFiles = [ 'wallets/monero/test_wallet/test_wallet', 'wallets/monero/test_wallet/test_wallet.keys', 'epiccash/test_wallet/wallet_data/wallet.seed', + 'grin/test_wallet/wallet_data/wallet.seed', ]; /// Seeded files a reset must delete. diff --git a/integration_test/wallet_creation/coin_matrix.dart b/integration_test/wallet_creation/coin_matrix.dart index 8a051daf89..4cbec6b208 100644 --- a/integration_test/wallet_creation/coin_matrix.dart +++ b/integration_test/wallet_creation/coin_matrix.dart @@ -11,6 +11,7 @@ const defaultWordCounts = { 'ethereum': 12, 'fact0rn': 12, 'firo': 12, + 'grin': 24, 'litecoin': 12, 'mimblewimblecoin': 12, 'monero': 16, diff --git a/integration_test/wallet_creation/seed_validators.dart b/integration_test/wallet_creation/seed_validators.dart index cb8983b45f..2ead3b49d9 100644 --- a/integration_test/wallet_creation/seed_validators.dart +++ b/integration_test/wallet_creation/seed_validators.dart @@ -8,6 +8,7 @@ import 'package:stackwallet/services/wallets.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import 'package:stackwallet/wallets/wallet/intermediate/cryptonote_wallet.dart'; import 'package:stackwallet/wallets/wallet/intermediate/lib_xelis_wallet.dart'; @@ -31,6 +32,8 @@ Future verifyOpenNativeWallet(Wallet wallet, String expected) async { 0, await wallet.getMwcMqsConfig(), )).value; + } else if (wallet is GrinWallet) { + actual = await wallet.getNativeReceivingAddress(); } else if (wallet is LibXelisWallet) { wallet.checkInitialized(); actual = wallet.xelis.getAddress(wallet.wallet!); diff --git a/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart b/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart index 721d9a11c9..33ef796b03 100644 --- a/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart +++ b/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart @@ -103,6 +103,18 @@ class TransactionV2 { bool get isMimblewimblecoinTransaction => _getFromOtherData(key: TxV2OdKeys.isMimblewimblecoinTransaction) == true; + @ignore + bool get isGrinTransaction => + _getFromOtherData(key: TxV2OdKeys.isGrinTransaction) == true; + + /// The last slate state a Grin wallet saw, as its wire name ("S1" ...). + @ignore + String? get grinSlateState => + _getFromOtherData(key: TxV2OdKeys.grinSlateState) as String?; + + @ignore + bool get isReverted => _getFromOtherData(key: TxV2OdKeys.isReverted) == true; + int? get numberOfMessages => _getFromOtherData(key: TxV2OdKeys.numberOfMessages) as int?; String? get slateId => _getFromOtherData(key: TxV2OdKeys.slateId) as String?; @@ -302,6 +314,15 @@ class TransactionV2 { } } + if (isGrinTransaction) { + return _grinStatusLabel( + currentChainHeight: currentChainHeight, + minConfirms: minConfirms, + minCoinbaseConfirms: minCoinbaseConfirms, + prettyConfirms: prettyConfirms, + ); + } + if (isMimblewimblecoinTransaction) { if (slateId == null) { return "Restored Funds"; @@ -364,6 +385,40 @@ class TransactionV2 { } } + String _grinStatusLabel({ + required int currentChainHeight, + required int minConfirms, + required int minCoinbaseConfirms, + required String Function() prettyConfirms, + }) { + final incoming = type == TransactionType.incoming; + final outgoing = + type == TransactionType.outgoing || type == TransactionType.sentToSelf; + final state = grinSlateState; + final onChain = height != null; + + if (incoming && slateId == null && !isCoinbase()) return "Restored funds"; + if (isCancelled) return "Cancelled"; + if (isReverted) return "Reverted"; + if (isConfirmed(currentChainHeight, minConfirms, minCoinbaseConfirms)) { + if (type == TransactionType.sentToSelf) return "Sent to self"; + return incoming ? "Received" : "Sent"; + } + if (!onChain) { + if (state == "S1" && outgoing) return "Sending (waiting for response)"; + if (state == "S2" && incoming) { + return "Receiving (waiting for sender to finalize)"; + } + if (state == "I1") return "Invoice issued (waiting for payer)"; + if (state == "I2" && outgoing) { + return "Paying invoice (waiting for invoicer)"; + } + } + return incoming + ? "Receiving ${prettyConfirms()}" + : "Sending ${prettyConfirms()}"; + } + dynamic _getFromOtherData({required dynamic key}) { if (otherData == null) { return null; @@ -421,4 +476,13 @@ abstract final class TxV2OdKeys { static const salviumTypeInt = "salviumTypeInt"; static const salviumTypeString = "salviumTypeString"; static const memo = "onChainMemo"; + static const isGrinTransaction = "isGrinTransaction"; + static const grinLogIds = "grinLogIds"; + static const grinSlateState = "grinSlateState"; + static const grinHasStoredTx = "grinHasStoredTx"; + static const grinKernelExcess = "grinKernelExcess"; + static const grinTtlCutoff = "grinTtlCutoff"; + static const grinHasPaymentProof = "grinHasPaymentProof"; + static const counterpartyAddress = "counterpartyAddress"; + static const isReverted = "isReverted"; } diff --git a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart index 52a78a975f..7cc7cd837b 100644 --- a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart +++ b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart @@ -201,6 +201,7 @@ class _NewWalletRecoveryPhraseWarningViewState // this may not be epiccash and sol specific? if (coin is Epiccash || coin is Mimblewimblecoin || + coin is Grin || coin is Solana) { mnemonicPassphrase = ""; } @@ -287,15 +288,14 @@ class _NewWalletRecoveryPhraseWarningViewState right: 10, ), child: AppBarIconButton( - semanticsLabel: - "Question Button. Opens A Dialog For Recovery Phrase Explanation.", + semanticsLabel: "Question Button. Opens A Dialog For Recovery Phrase Explanation.", icon: SvgPicture.asset( Assets.svg.circleQuestion, width: 20, height: 20, - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), onPressed: () async { await showDialog( @@ -331,9 +331,8 @@ class _NewWalletRecoveryPhraseWarningViewState Text( walletName, textAlign: TextAlign.center, - style: STextStyles.label( - context, - ).copyWith(fontSize: 12), + style: STextStyles.label(context) + .copyWith(fontSize: 12), ), if (!isDesktop) const SizedBox(height: 4), Text( @@ -362,9 +361,8 @@ class _NewWalletRecoveryPhraseWarningViewState ? STextStyles.desktopTextMediumRegular( context, ) - : STextStyles.subtitle( - context, - ).copyWith(fontSize: 12), + : STextStyles.subtitle(context) + .copyWith(fontSize: 12), ) : Column( children: [ @@ -381,13 +379,11 @@ class _NewWalletRecoveryPhraseWarningViewState RichText( textAlign: TextAlign.center, text: TextSpan( - style: STextStyles.desktopH3( - context, - ).copyWith(fontSize: 18), + style: STextStyles.desktopH3(context) + .copyWith(fontSize: 18), children: [ TextSpan( - text: - "On the next screen you will be given ", + text: "On the next screen you will be given ", style: STextStyles.desktopH3(context) .copyWith( color: Theme.of(context) @@ -597,9 +593,8 @@ class _NewWalletRecoveryPhraseWarningViewState ? STextStyles.desktopTextMedium( context, ) - : STextStyles.baseXS( - context, - ).copyWith(height: 1.3), + : STextStyles.baseXS(context) + .copyWith(height: 1.3), ), ), ], diff --git a/lib/pages/add_wallet_views/restore_wallet_view/restore_options_view/restore_options_view.dart b/lib/pages/add_wallet_views/restore_wallet_view/restore_options_view/restore_options_view.dart index e650564a18..1322520981 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/restore_options_view/restore_options_view.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/restore_options_view/restore_options_view.dart @@ -228,6 +228,10 @@ class _RestoreOptionsViewState extends ConsumerState { height = 0; } + if (widget.coin is Grin) { + height = (widget.coin as Grin).heightFromDate(date); + } + if (widget.coin is Epiccash) { final int secondsSinceEpoch = date.millisecondsSinceEpoch ~/ 1000; const int epicCashFirstBlock = 1565370278; @@ -273,9 +277,8 @@ class _RestoreOptionsViewState extends ConsumerState { onPressed: () { if (textFieldFocusNode.hasFocus) { textFieldFocusNode.unfocus(); - Future.delayed( - const Duration(milliseconds: 100), - ).then((value) => Navigator.of(context).pop()); + Future.delayed(const Duration(milliseconds: 100)) + .then((value) => Navigator.of(context).pop()); } else { Navigator.of(context).pop(); } @@ -310,12 +313,12 @@ class _RestoreOptionsViewState extends ConsumerState { key: UniqueKey(), onText: "Seed", offText: "View Only", - onColor: Theme.of( - context, - ).extension()!.popupBG, - offColor: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + onColor: Theme.of(context) + .extension()! + .popupBG, + offColor: Theme.of(context) + .extension()! + .textFieldDefaultBG, isOn: _showViewOnlyOption, onValueChanged: (value) { setState(() { @@ -426,7 +429,8 @@ class _SeedRestoreOptionState extends ConsumerState { children: [ if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -434,9 +438,9 @@ class _SeedRestoreOptionState extends ConsumerState { ref.watch(_pIsUsingDate) ? "Choose start date" : "Block height", style: Util.isDesktop ? STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textDark3, + color: Theme.of(context) + .extension()! + .textDark3, ) : STextStyles.smallMed12(context), textAlign: TextAlign.left, @@ -453,11 +457,13 @@ class _SeedRestoreOptionState extends ConsumerState { ), if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) SizedBox(height: Util.isDesktop ? 16 : 8), if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) ref.watch(_pIsUsingDate) ? RestoreFromDatePicker( onTap: widget.dateChooserFunction, @@ -474,9 +480,8 @@ class _SeedRestoreOptionState extends ConsumerState { inputFormatters: [FilteringTextInputFormatter.digitsOnly], textInputAction: TextInputAction.done, style: Util.isDesktop - ? STextStyles.desktopTextMedium( - context, - ).copyWith(height: 2) + ? STextStyles.desktopTextMedium(context) + .copyWith(height: 2) : STextStyles.field(context), onChanged: (value) { setState(() { @@ -492,8 +497,7 @@ class _SeedRestoreOptionState extends ConsumerState { suffixIcon: UnconstrainedBox( child: TextFieldIconButton( child: Semantics( - label: - "Clear Block Height Field Button. Clears the block height field", + label: "Clear Block Height Field Button. Clears the block height field", excludeSemantics: true, child: !_blockFieldEmpty ? XIcon( @@ -515,11 +519,13 @@ class _SeedRestoreOptionState extends ConsumerState { ), if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) const SizedBox(height: 8), if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) RoundedWhiteContainer( child: Center( child: Text( @@ -528,9 +534,9 @@ class _SeedRestoreOptionState extends ConsumerState { : "Enter the initial block height of the wallet", style: Util.isDesktop ? STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, ) : STextStyles.smallMed12(context).copyWith(fontSize: 10), ), @@ -538,7 +544,8 @@ class _SeedRestoreOptionState extends ConsumerState { ), if (isCnAnd25 || widget.coin is Epiccash || - widget.coin is Mimblewimblecoin) + widget.coin is Mimblewimblecoin || + widget.coin is Grin) SizedBox(height: Util.isDesktop ? 24 : 16), Text( "Choose recovery phrase length", @@ -582,9 +589,9 @@ class _SeedRestoreOptionState extends ConsumerState { Assets.svg.chevronDown, width: 12, height: 6, - color: Theme.of( - context, - ).extension()!.textFieldActiveSearchIconRight, + color: Theme.of(context) + .extension()! + .textFieldActiveSearchIconRight, ), ), ), @@ -592,9 +599,9 @@ class _SeedRestoreOptionState extends ConsumerState { offset: const Offset(0, -10), elevation: 0, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -632,13 +639,12 @@ class _SeedRestoreOptionState extends ConsumerState { Text( "Advanced", style: Util.isDesktop - ? STextStyles.desktopTextExtraExtraSmall( - context, - ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark3, - ) + ? STextStyles.desktopTextExtraExtraSmall(context) + .copyWith( + color: Theme.of(context) + .extension()! + .textDark3, + ) : STextStyles.smallMed12(context), textAlign: TextAlign.left, ), @@ -670,9 +676,8 @@ class _SeedRestoreOptionState extends ConsumerState { focusNode: widget.pwFocusNode, controller: widget.pwController, style: Util.isDesktop - ? STextStyles.desktopTextMedium( - context, - ).copyWith(height: 2) + ? STextStyles.desktopTextMedium(context) + .copyWith(height: 2) : STextStyles.field(context), obscureText: _hidePassword, enableSuggestions: false, @@ -706,9 +711,9 @@ class _SeedRestoreOptionState extends ConsumerState { _hidePassword ? Assets.svg.eye : Assets.svg.eyeSlash, - color: Theme.of( - context, - ).extension()!.textDark3, + color: Theme.of(context) + .extension()! + .textDark3, width: Util.isDesktop ? 24 : 16, height: Util.isDesktop ? 24 : 16, ), @@ -734,13 +739,12 @@ class _SeedRestoreOptionState extends ConsumerState { "was created with an optional BIP39 passphrase " "you can enter it here.", style: Util.isDesktop - ? STextStyles.desktopTextExtraSmall( - context, - ).copyWith( - color: Theme.of( - context, - ).extension()!.textSubtitle1, - ) + ? STextStyles.desktopTextExtraSmall(context) + .copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, + ) : STextStyles.itemSubtitle(context), ), ), @@ -800,9 +804,9 @@ class _ViewOnlyRestoreOptionState extends ConsumerState { ref.watch(_pIsUsingDate) ? "Choose start date" : "Block height", style: Util.isDesktop ? STextStyles.desktopTextExtraExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textDark3, + color: Theme.of(context) + .extension()! + .textDark3, ) : STextStyles.smallMed12(context), textAlign: TextAlign.left, @@ -837,9 +841,8 @@ class _ViewOnlyRestoreOptionState extends ConsumerState { inputFormatters: [FilteringTextInputFormatter.digitsOnly], textInputAction: TextInputAction.done, style: Util.isDesktop - ? STextStyles.desktopTextMedium( - context, - ).copyWith(height: 2) + ? STextStyles.desktopTextMedium(context) + .copyWith(height: 2) : STextStyles.field(context), onChanged: (value) { setState(() { @@ -855,8 +858,7 @@ class _ViewOnlyRestoreOptionState extends ConsumerState { suffixIcon: UnconstrainedBox( child: TextFieldIconButton( child: Semantics( - label: - "Clear Block Height Field Button. Clears the block height field", + label: "Clear Block Height Field Button. Clears the block height field", excludeSemantics: true, child: !_blockFieldEmpty ? XIcon( @@ -886,9 +888,9 @@ class _ViewOnlyRestoreOptionState extends ConsumerState { : "Enter the initial block height of the wallet", style: Util.isDesktop ? STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, ) : STextStyles.smallMed12(context).copyWith(fontSize: 10), ), diff --git a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart index 180e3b8c60..58331dfbf7 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart @@ -45,6 +45,7 @@ import '../../../wallets/crypto_currency/coins/ethereum.dart'; import '../../../wallets/crypto_currency/coins/solana.dart'; import '../../../wallets/isar/models/wallet_info.dart'; import '../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../wallets/wallet/impl/xelis_wallet.dart'; import '../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; @@ -371,6 +372,10 @@ class _RestoreWalletViewState extends ConsumerState { await wallet.init(isRestore: true); break; + case GrinWallet(): + await wallet.init(isRestore: true); + break; + default: await wallet.init(); } diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 3c40737955..8c482ffb58 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -698,8 +698,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { } void _syncFeeAmount(Amount? amount) { - // Xelis obtains the exact fee when preparing the reviewed transaction. - if (hasFees && coin is! Xelis) followFeeAmount(amount); + // Xelis and Grin obtain the exact fee when preparing the reviewed + // transaction. + if (hasFees && coin is! Xelis && coin is! Grin) followFeeAmount(amount); } /// Looks up the OpenAlias in the address field. Returns null if the lookup @@ -1254,7 +1255,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { ref.refresh(pIsExchangeAddress); }); hasFees = hasSendFee(coin); - if (hasFees && coin is! Xelis) { + if (hasFees && coin is! Xelis && coin is! Grin) { retryFeeOnFocusLoss([_cryptoFocus, _baseFocus]); } @@ -2472,14 +2473,14 @@ class _SendViewState extends ConsumerState with SendFeeForm { const SizedBox(height: 12), if (hasFees) Text( - coin is Xelis || hasCustomFee + coin is Xelis || coin is Grin || hasCustomFee ? "Transaction fee" : "Transaction fee (estimated)", style: STextStyles.smallMed12(context), textAlign: TextAlign.left, ), if (hasFees) const SizedBox(height: 8), - if (coin is Xelis) + if (coin is Xelis || coin is Grin) Padding( padding: const EdgeInsets.all(12), child: Text( diff --git a/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart b/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart index 6d97d9a659..3a1c30607e 100644 --- a/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart +++ b/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart @@ -37,6 +37,8 @@ import '../../../../utilities/util.dart'; import '../../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../../wallets/crypto_currency/interfaces/electrumx_currency_interface.dart'; import '../../../../wallets/crypto_currency/intermediate/cryptonote_currency.dart'; +import '../../../../wallets/wallet/supporting/grin/grin_transport.dart' + show isOnionHost; import '../../../../widgets/background.dart'; import '../../../../widgets/conditional_parent.dart'; import '../../../../widgets/custom_buttons/app_bar_icon_button.dart'; @@ -873,6 +875,8 @@ class _NodeFormState extends ConsumerState { bool get shouldBeReadOnly => _inputsReadOnly || widget.node?.isDefault == true; + bool _isGrinOnion(String host) => widget.coin is Grin && isOnionHost(host); + void _updateState() { if (widget.busy || _changing) return; _copyToFormData(); @@ -954,10 +958,13 @@ class _NodeFormState extends ConsumerState { } else { netOption = TorPlainNetworkOption.both; } + if (_isGrinOnion(node.host)) { + netOption = TorPlainNetworkOption.tor; + } if (widget.coin is Epiccash) { enableSSLCheckbox = !node.host.startsWith("http"); - } else if (widget.coin is Mimblewimblecoin) { + } else if (widget.coin is Mimblewimblecoin || widget.coin is Grin) { enableSSLCheckbox = !node.host.startsWith("http"); } else { enableSSLCheckbox = true; @@ -1144,7 +1151,7 @@ class _NodeFormState extends ConsumerState { _useSSL = true; } } - if (widget.coin is Mimblewimblecoin) { + if (widget.coin is Mimblewimblecoin || widget.coin is Grin) { if (newValue.startsWith("https://")) { _useSSL = true; enableSSLCheckbox = false; @@ -1155,6 +1162,12 @@ class _NodeFormState extends ConsumerState { enableSSLCheckbox = true; } } + if (_isGrinOnion(newValue)) { + // Onion nodes need Tor and plain HTTP. + netOption = TorPlainNetworkOption.tor; + _useSSL = false; + enableSSLCheckbox = false; + } _updateState(); setState(() {}); }, @@ -1302,7 +1315,7 @@ class _NodeFormState extends ConsumerState { ), ), if (enableAuthFields) const SizedBox(height: 8), - if (widget.coin is Mimblewimblecoin) + if (widget.coin is Mimblewimblecoin || widget.coin is Grin) ClipRRect( borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -1349,7 +1362,8 @@ class _NodeFormState extends ConsumerState { }, ), ), - if (widget.coin is Mimblewimblecoin) const SizedBox(height: 8), + if (widget.coin is Mimblewimblecoin || widget.coin is Grin) + const SizedBox(height: 8), if (widget.coin is! CryptonoteCurrency) Row( children: [ @@ -1500,11 +1514,13 @@ class _NodeFormState extends ConsumerState { ), if (widget.coin is! CryptonoteCurrency && widget.coin is! Epiccash && - widget.coin is! Mimblewimblecoin) + widget.coin is! Mimblewimblecoin && + widget.coin is! Grin) const SizedBox(height: 8), if (widget.coin is! CryptonoteCurrency && widget.coin is! Epiccash && - widget.coin is! Mimblewimblecoin) + widget.coin is! Mimblewimblecoin && + widget.coin is! Grin) Row( children: [ GestureDetector( @@ -1595,11 +1611,11 @@ class _NodeFormState extends ConsumerState { children: [ RadioTextButton( label: "Only non-TOR traffic", - enabled: !_inputsReadOnly, + enabled: !_inputsReadOnly && !_isGrinOnion(_hostController.text), value: TorPlainNetworkOption.clear, groupValue: netOption, onChanged: (value) { - if (!_inputsReadOnly) { + if (!_inputsReadOnly && !_isGrinOnion(_hostController.text)) { setState(() => netOption = TorPlainNetworkOption.clear); _updateState(); } @@ -1612,11 +1628,11 @@ class _NodeFormState extends ConsumerState { children: [ RadioTextButton( label: "Allow both", - enabled: !_inputsReadOnly, + enabled: !_inputsReadOnly && !_isGrinOnion(_hostController.text), value: TorPlainNetworkOption.both, groupValue: netOption, onChanged: (value) { - if (!_inputsReadOnly) { + if (!_inputsReadOnly && !_isGrinOnion(_hostController.text)) { setState(() => netOption = TorPlainNetworkOption.both); _updateState(); } diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart index b131db8312..e23d78954c 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart @@ -55,6 +55,7 @@ import '../../../../../wallets/isar/models/frost_wallet_info.dart'; import '../../../../../wallets/isar/models/wallet_info.dart'; import '../../../../../wallets/wallet/impl/bitcoin_frost_wallet.dart'; import '../../../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../../wallets/wallet/impl/xelis_wallet.dart'; import '../../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; @@ -495,6 +496,10 @@ abstract class SWB { await wallet.init(isRestore: true); break; + case GrinWallet(): + await wallet.init(isRestore: true); + break; + default: await wallet.init(); } @@ -503,7 +508,8 @@ abstract class SWB { if (restoreHeight <= 0) { if (wallet is EpiccashWallet || wallet is CryptonoteWallet || - wallet is MimblewimblecoinWallet) { + wallet is MimblewimblecoinWallet || + wallet is GrinWallet) { restoreHeight = 0; } else { restoreHeight = walletbackup['storedChainHeight'] as int? ?? 0; diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart index 9a792c48de..2c464a9468 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart @@ -26,6 +26,7 @@ import '../../../../../utilities/logger.dart'; import '../../../../../utilities/text_styles.dart'; import '../../../../../utilities/util.dart'; import '../../../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../../wallets/wallet/impl/xelis_wallet.dart'; import '../../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; @@ -75,6 +76,10 @@ class _RestoringWalletCardState extends ConsumerState { await wallet.init(isRestore: true); break; + case GrinWallet(): + await wallet.init(isRestore: true); + break; + default: await wallet.init(); } @@ -116,9 +121,9 @@ class _RestoringWalletCardState extends ConsumerState { case StackRestoringStatus.waiting: return SvgPicture.asset( Assets.svg.loader, - color: Theme.of( - context, - ).extension()!.buttonBackSecondary, + color: Theme.of(context) + .extension()! + .buttonBackSecondary, ); case StackRestoringStatus.restoring: return const LoadingIndicator(); @@ -195,16 +200,16 @@ class _RestoringWalletCardState extends ConsumerState { ? Container( height: 20, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.buttonBackSecondary, + color: Theme.of(context) + .extension()! + .buttonBackSecondary, borderRadius: BorderRadius.circular(1000), ), child: RawMaterialButton( materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - splashColor: Theme.of( - context, - ).extension()!.highlight, + splashColor: Theme.of(context) + .extension()! + .highlight, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(1000), ), @@ -227,9 +232,9 @@ class _RestoringWalletCardState extends ConsumerState { child: Text( "Show recovery phrase", style: STextStyles.infoSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), ), @@ -284,16 +289,16 @@ class _RestoringWalletCardState extends ConsumerState { ? Container( height: 20, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.buttonBackSecondary, + color: Theme.of(context) + .extension()! + .buttonBackSecondary, borderRadius: BorderRadius.circular(1000), ), child: RawMaterialButton( materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - splashColor: Theme.of( - context, - ).extension()!.highlight, + splashColor: Theme.of(context) + .extension()! + .highlight, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(1000), ), @@ -316,9 +321,9 @@ class _RestoringWalletCardState extends ConsumerState { child: Text( "Show recovery phrase", style: STextStyles.infoSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), ), diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart index 3eccb79285..5f39a9e1be 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart @@ -34,6 +34,7 @@ import '../../../../utilities/constants.dart'; import '../../../../utilities/text_styles.dart'; import '../../../../utilities/util.dart'; import '../../../../wallets/crypto_currency/coins/epiccash.dart'; +import '../../../../wallets/crypto_currency/coins/grin.dart'; import '../../../../wallets/crypto_currency/coins/litecoin.dart'; import '../../../../wallets/crypto_currency/coins/mimblewimblecoin.dart'; import '../../../../wallets/crypto_currency/coins/monero.dart'; @@ -42,6 +43,7 @@ import '../../../../wallets/crypto_currency/coins/wownero.dart'; import '../../../../wallets/crypto_currency/intermediate/cryptonote_currency.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart'; @@ -155,7 +157,9 @@ class _WalletNetworkSettingsViewState Navigator.of(context, rootNavigator: isDesktop).pop(); final String message; - if (wallet is CryptonoteWallet || wallet is EpiccashWallet) { + if (wallet is CryptonoteWallet || + wallet is EpiccashWallet || + wallet is GrinWallet) { message = "Rescan started"; } else { message = "Rescan completed"; @@ -280,6 +284,7 @@ class _WalletNetworkSettingsViewState coin is Epiccash || coin is Salvium || coin is Mimblewimblecoin || + coin is Grin || (coin is Litecoin && ref.read(pWalletInfo(widget.walletId)).isMwebEnabled)) { _blocksRemainingSubscription = eventBus.on().listen( @@ -369,6 +374,13 @@ class _WalletNetworkSettingsViewState if (_percent < highestPercent) { _percent = highestPercent.clamp(0.0, 1.0); } + } else if (coin is Grin) { + final double highestPercent = + (ref.watch(pWallets).getWallet(widget.walletId) as GrinWallet) + .restoreProgress; + if (_percent < highestPercent) { + _percent = highestPercent.clamp(0.0, 1.0); + } } return ConditionalParent( @@ -376,9 +388,9 @@ class _WalletNetworkSettingsViewState builder: (child) { return Background( child: Scaffold( - backgroundColor: Theme.of( - context, - ).extension()!.background, + backgroundColor: Theme.of(context) + .extension()! + .background, appBar: AppBar( leading: AppBarBackButton( onPressed: () { @@ -403,14 +415,14 @@ class _WalletNetworkSettingsViewState ), size: 36, shadows: const [], - color: Theme.of( - context, - ).extension()!.background, + color: Theme.of(context) + .extension()! + .background, icon: SvgPicture.asset( Assets.svg.verticalEllipsis, - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, width: 20, height: 20, ), @@ -427,9 +439,9 @@ class _WalletNetworkSettingsViewState right: 10, child: Container( decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.popupBG, + color: Theme.of(context) + .extension()! + .popupBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -545,9 +557,9 @@ class _WalletNetworkSettingsViewState Assets.svg.radio, height: isDesktop ? 19 : 14, width: isDesktop ? 19 : 14, - color: Theme.of( - context, - ).extension()!.accentColorGreen, + color: Theme.of(context) + .extension()! + .accentColorGreen, ), ), ), @@ -570,12 +582,12 @@ class _WalletNetworkSettingsViewState ProgressBar( width: progressLength, height: 5, - fillColor: Theme.of( - context, - ).extension()!.accentColorGreen, - backgroundColor: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + fillColor: Theme.of(context) + .extension()! + .accentColorGreen, + backgroundColor: Theme.of(context) + .extension()! + .textFieldDefaultBG, percent: 1, ), ], @@ -608,9 +620,9 @@ class _WalletNetworkSettingsViewState Assets.svg.radioSyncing, height: 14, width: 14, - color: Theme.of( - context, - ).extension()!.accentColorYellow, + color: Theme.of(context) + .extension()! + .accentColorYellow, ), ), ), @@ -647,11 +659,11 @@ class _WalletNetworkSettingsViewState coin is Epiccash || coin is Salvium || coin is Mimblewimblecoin || + coin is Grin || (coin is Litecoin && ref.watch( - pWalletInfo( - widget.walletId, - ).select((s) => s.isMwebEnabled), + pWalletInfo(widget.walletId) + .select((s) => s.isMwebEnabled), ))) Text( " (Blocks to go: ${_blocksRemaining == -1 ? "?" : _blocksRemaining})", @@ -671,12 +683,12 @@ class _WalletNetworkSettingsViewState ProgressBar( width: progressLength, height: 5, - fillColor: Theme.of( - context, - ).extension()!.accentColorYellow, - backgroundColor: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + fillColor: Theme.of(context) + .extension()! + .accentColorYellow, + backgroundColor: Theme.of(context) + .extension()! + .textFieldDefaultBG, percent: _percent, ), ], @@ -709,9 +721,9 @@ class _WalletNetworkSettingsViewState Assets.svg.radioProblem, height: 14, width: 14, - color: Theme.of( - context, - ).extension()!.accentColorRed, + color: Theme.of(context) + .extension()! + .accentColorRed, ), ), ), @@ -726,17 +738,17 @@ class _WalletNetworkSettingsViewState Text( "Unable to synchronize", style: STextStyles.w600_12(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorRed, + color: Theme.of(context) + .extension()! + .accentColorRed, ), ), Text( "0%", style: STextStyles.syncPercent(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorRed, + color: Theme.of(context) + .extension()! + .accentColorRed, ), ), ], @@ -746,12 +758,12 @@ class _WalletNetworkSettingsViewState ProgressBar( width: progressLength, height: 5, - fillColor: Theme.of( - context, - ).extension()!.accentColorRed, - backgroundColor: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + fillColor: Theme.of(context) + .extension()! + .accentColorRed, + backgroundColor: Theme.of(context) + .extension()! + .textFieldDefaultBG, percent: 0, ), ], @@ -763,15 +775,15 @@ class _WalletNetworkSettingsViewState Padding( padding: const EdgeInsets.only(top: 12), child: RoundedContainer( - color: Theme.of( - context, - ).extension()!.warningBackground, + color: Theme.of(context) + .extension()! + .warningBackground, child: Text( "Please check your internet connection and make sure your current node is not having issues.", style: STextStyles.baseXS(context).copyWith( - color: Theme.of( - context, - ).extension()!.warningForeground, + color: Theme.of(context) + .extension()! + .warningForeground, ), ), ), @@ -857,9 +869,9 @@ class _WalletNetworkSettingsViewState Assets.svg.tor, height: isDesktop ? 19 : 14, width: isDesktop ? 19 : 14, - color: Theme.of( - context, - ).extension()!.accentColorGreen, + color: Theme.of(context) + .extension()! + .accentColorGreen, ), ), ), @@ -870,9 +882,10 @@ class _WalletNetworkSettingsViewState width: _iconSize, height: _iconSize, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.textDark.withOpacity(0.08), + color: Theme.of(context) + .extension()! + .textDark + .withOpacity(0.08), borderRadius: BorderRadius.circular(_iconSize), ), child: Center( @@ -880,9 +893,9 @@ class _WalletNetworkSettingsViewState Assets.svg.tor, height: isDesktop ? 19 : 14, width: isDesktop ? 19 : 14, - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -900,9 +913,9 @@ class _WalletNetworkSettingsViewState "Tor status", style: STextStyles.desktopTextExtraExtraSmall(context) .copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), if (_torConnectionStatus == @@ -1011,18 +1024,18 @@ class _WalletNetworkSettingsViewState width: _iconSize, height: _iconSize, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, borderRadius: BorderRadius.circular(_iconSize), ), child: Center( child: SvgPicture.asset( Assets.svg.networkWired, width: 24, - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -1037,9 +1050,9 @@ class _WalletNetworkSettingsViewState STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), Text( @@ -1058,9 +1071,9 @@ class _WalletNetworkSettingsViewState : Assets.svg.chevronDown, width: 12, height: 6, - color: Theme.of( - context, - ).extension()!.textSubtitle1, + color: Theme.of(context) + .extension()! + .textSubtitle1, ), ], ), diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart index 6a266b247a..e8690392af 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart @@ -24,6 +24,7 @@ import '../../../../wallets/isar/models/wallet_info.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; import '../../../../wallets/wallet/impl/bitcoin_wallet.dart'; import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/multi_address_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; @@ -392,11 +393,10 @@ class _WalletSettingsWalletSettingsViewState child: DraggableSwitchButton( isOn: ref.watch( - pWalletInfo( - widget.walletId, - ).select( - (value) => value.otherData, - ), + pWalletInfo(widget.walletId) + .select( + (value) => value.otherData, + ), )[WalletInfoKeys.reuseAddress] as bool? ?? false, @@ -441,11 +441,10 @@ class _WalletSettingsWalletSettingsViewState child: DraggableSwitchButton( isOn: ref.watch( - pWalletInfo( - widget.walletId, - ).select( - (value) => value.otherData, - ), + pWalletInfo(widget.walletId) + .select( + (value) => value.otherData, + ), )[WalletInfoKeys.mwebEnabled] as bool? ?? false, @@ -490,11 +489,10 @@ class _WalletSettingsWalletSettingsViewState child: DraggableSwitch( value: ref.watch( - pWalletInfo( - widget.walletId, - ).select( - (value) => value.otherData, - ), + pWalletInfo(widget.walletId) + .select( + (value) => value.otherData, + ), )[WalletInfoKeys .duressMarkedVisibleWalletKey] as bool? ?? @@ -540,11 +538,10 @@ class _WalletSettingsWalletSettingsViewState child: DraggableSwitch( value: ref.watch( - pWalletInfo( - widget.walletId, - ).select( - (value) => value.otherData, - ), + pWalletInfo(widget.walletId) + .select( + (value) => value.otherData, + ), )[WalletInfoKeys .enableLegacyAddresses] as bool? ?? @@ -592,9 +589,13 @@ class _WalletSettingsWalletSettingsViewState ), ), ), - if (wallet is CryptonoteWallet || wallet is EpiccashWallet) + if (wallet is CryptonoteWallet || + wallet is EpiccashWallet || + wallet is GrinWallet) const SizedBox(height: 8), - if (wallet is CryptonoteWallet || wallet is EpiccashWallet) + if (wallet is CryptonoteWallet || + wallet is EpiccashWallet || + wallet is GrinWallet) RoundedWhiteContainer( padding: const EdgeInsets.all(0), child: RawMaterialButton( @@ -655,9 +656,9 @@ class _WalletSettingsWalletSettingsViewState child: Text( "Cancel", style: STextStyles.button(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), ), diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart index 1ae13a8b07..a3d9298acc 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart @@ -2072,10 +2072,12 @@ class _TxidDetailItemState extends ConsumerState<_TxidDetailItem> { : STextStyles.itemSubtitle12(context), ), if (widget.coin is! Epiccash && - widget.coin is! Mimblewimblecoin) + widget.coin is! Mimblewimblecoin && + widget.coin is! Grin) const SizedBox(height: 8), if (widget.coin is! Epiccash && - widget.coin is! Mimblewimblecoin) + widget.coin is! Mimblewimblecoin && + widget.coin is! Grin) CustomTextButton( text: "Open in block explorer", onTap: () async { diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart index 977cee09e4..20afa0f621 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart @@ -2205,7 +2205,7 @@ class _DesktopSendState extends ConsumerState { ), ), if (!isPaynymSend) const SizedBox(height: 20), - if (hasSendFee(coin)) + if (hasSendFee(coin) && coin is! Grin) DesktopSendFeeForm( walletId: walletId, isToken: false, diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart index dc7fc8b3a4..ca6521ce04 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart @@ -32,6 +32,7 @@ import '../../../../wallets/crypto_currency/intermediate/frost_currency.dart'; import '../../../../wallets/crypto_currency/intermediate/nano_currency.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; +import '../../../../wallets/wallet/impl/grin_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; @@ -324,9 +325,9 @@ class WalletOptionsButton extends ConsumerWidget { Assets.svg.ellipsis, width: 20, height: 20, - color: Theme.of( - context, - ).extension()!.buttonTextSecondary, + color: Theme.of(context) + .extension()! + .buttonTextSecondary, ), ], ), @@ -418,9 +419,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -453,9 +454,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -488,9 +489,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -498,9 +499,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { ), ), ), - if (isCN || wallet is EpiccashWallet) + if (isCN || wallet is EpiccashWallet || wallet is GrinWallet) const SizedBox(height: 8), - if (isCN || wallet is EpiccashWallet) + if (isCN || wallet is EpiccashWallet || wallet is GrinWallet) TransparentButton( onPressed: onRefreshHeightPressed, child: Padding( @@ -524,9 +525,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -559,9 +560,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -594,9 +595,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -631,9 +632,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -665,9 +666,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), diff --git a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart index 41e65e9d76..ca988e1d82 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/desktop_manage_block_explorers_dialog.dart @@ -30,9 +30,7 @@ import '../../../../widgets/desktop/secondary_button.dart'; import '../../../../widgets/rounded_white_container.dart'; class DesktopManageBlockExplorersDialog extends ConsumerWidget { - const DesktopManageBlockExplorersDialog({ - super.key, - }); + const DesktopManageBlockExplorersDialog({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { @@ -40,9 +38,14 @@ class DesktopManageBlockExplorersDialog extends ConsumerWidget { prefsChangeNotifierProvider.select((value) => value.showTestNetCoins), ); + // Coins without a default explorer cannot be edited here. final coins = AppConfig.coins .where( - (e) => showTestNet || e.network == CryptoCurrencyNetwork.main, + (e) => + (showTestNet || e.network == CryptoCurrencyNetwork.main) && + e is! Epiccash && + e is! Mimblewimblecoin && + e is! Grin, ) .toList(); @@ -67,16 +70,10 @@ class DesktopManageBlockExplorersDialog extends ConsumerWidget { ), Expanded( child: Padding( - padding: const EdgeInsets.only( - left: 32, - right: 32, - bottom: 32, - ), + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), child: ListView.separated( itemCount: coins.length, - separatorBuilder: (_, __) => const SizedBox( - height: 12, - ), + separatorBuilder: (_, __) => const SizedBox(height: 12), itemBuilder: (_, index) { final coin = coins[index]; @@ -91,24 +88,18 @@ class DesktopManageBlockExplorersDialog extends ConsumerWidget { child: Row( children: [ SvgPicture.file( - File( - ref.watch(coinIconProvider(coin)), - ), + File(ref.watch(coinIconProvider(coin))), width: 24, height: 24, ), - const SizedBox( - width: 12, - ), + const SizedBox(width: 12), Expanded( child: Text( "${coin.prettyName} block explorer", style: STextStyles.desktopTextSmall(context), ), ), - const SizedBox( - width: 12, - ), + const SizedBox(width: 12), SvgPicture.asset( Assets.svg.chevronRight, width: 20, @@ -122,9 +113,7 @@ class DesktopManageBlockExplorersDialog extends ConsumerWidget { useSafeArea: false, barrierDismissible: true, builder: (context) { - return _DesktopEditBlockExplorerDialog( - coin: coin, - ); + return _DesktopEditBlockExplorerDialog(coin: coin); }, ); }, @@ -157,9 +146,10 @@ class _DesktopEditBlockExplorerDialogState @override void initState() { _textEditingController = TextEditingController( - text: getBlockExplorerTransactionUrlFor(coin: widget.coin, txid: "[TXID]") - .toString() - .replaceAll("%5BTXID%5D", "[TXID]"), + text: getBlockExplorerTransactionUrlFor( + coin: widget.coin, + txid: "[TXID]", + ).toString().replaceAll("%5BTXID%5D", "[TXID]"), ); _focusNode = FocusNode(); super.initState(); @@ -194,11 +184,7 @@ class _DesktopEditBlockExplorerDialogState ], ), Padding( - padding: const EdgeInsets.only( - left: 32, - right: 32, - bottom: 32, - ), + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -215,12 +201,11 @@ class _DesktopEditBlockExplorerDialogState style: STextStyles.field(context), ), ), - const SizedBox( - height: 16, - ), + const SizedBox(height: 16), RoundedWhiteContainer( - borderColor: - Theme.of(context).extension()!.textSubtitle6, + borderColor: Theme.of(context) + .extension()! + .textSubtitle6, child: Text( "Edit your block explorer above. Keep in mind that" " every block explorer has a slightly different URL scheme." @@ -232,9 +217,7 @@ class _DesktopEditBlockExplorerDialogState style: STextStyles.desktopTextExtraExtraSmall(context), ), ), - const SizedBox( - height: 16, - ), + const SizedBox(height: 16), Row( children: [ Expanded( @@ -244,21 +227,18 @@ class _DesktopEditBlockExplorerDialogState onPressed: Navigator.of(context).pop, ), ), - const SizedBox( - width: 16, - ), + const SizedBox(width: 16), Expanded( child: PrimaryButton( label: "Save", buttonHeight: ButtonHeight.l, onPressed: () async { - _textEditingController.text = - _textEditingController.text.trim(); + _textEditingController.text = _textEditingController + .text + .trim(); await setBlockExplorerForCoin( coin: widget.coin, - url: Uri.parse( - _textEditingController.text, - ), + url: Uri.parse(_textEditingController.text), ); if (mounted) { diff --git a/lib/services/node_service.dart b/lib/services/node_service.dart index 24339807f5..2623d31e47 100644 --- a/lib/services/node_service.dart +++ b/lib/services/node_service.dart @@ -93,6 +93,8 @@ class NodeService extends ChangeNotifier { loginName: savedNode.loginName, isPrimary: savedNode.isPrimary, forceNoTor: savedNode.forceNoTor, + // A secret the user set on a default node without one stays. + nodeApiSecret: defaultNode.nodeApiSecret ?? savedNode.nodeApiSecret, trustedCertificatePem: savedNode.sameEndpoint( host: defaultNode.host, diff --git a/lib/services/price.dart b/lib/services/price.dart index ab47c8ebc2..6f5603e94c 100644 --- a/lib/services/price.dart +++ b/lib/services/price.dart @@ -39,6 +39,7 @@ class PriceAPI { Ethereum: "ethereum", Fact0rn: "fact0rn", Firo: "zcoin", + Grin: "grin", Monero: "monero", Particl: "particl", Peercoin: "peercoin", diff --git a/lib/services/wallets.dart b/lib/services/wallets.dart index 4f64485550..8333ad61ec 100644 --- a/lib/services/wallets.dart +++ b/lib/services/wallets.dart @@ -12,6 +12,7 @@ import 'dart:async'; import 'dart:io'; import 'package:compat/compat.dart' as lib_monero_compat; +import 'package:flutter/foundation.dart'; import 'package:isar_community/isar.dart'; import '../app_config.dart'; @@ -29,6 +30,7 @@ import '../wallets/isar/models/frost_wallet_info.dart'; import '../wallets/isar/models/wallet_info.dart'; import '../wallets/wallet/impl/bitcoin_frost_wallet.dart'; import '../wallets/wallet/impl/epiccash_wallet.dart'; +import '../wallets/wallet/impl/grin_wallet.dart'; import '../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../wallets/wallet/intermediate/lib_salvium_wallet.dart'; @@ -186,6 +188,14 @@ class Wallets { Logging.instance.i( "Mimblewimblecoin wallet: $walletId deleted with result: $deleteResult", ); + } else if (info.coin is Grin) { + // Also reaches an instance that is not registered yet, such as a + // restore being cancelled. A busy directory is retried at next load + // from the wallets-to-delete list below, and so is a delete that + // failed: the recovery phrase is gone by now, so the rest of the + // wallet has to go too. + final deleted = await _deleteGrinWalletFiles(walletId, secureStorage); + Logging.instance.i("Grin wallet: $walletId files deleted: $deleted"); } // delete wallet data in main db @@ -474,10 +484,12 @@ class Wallets { } hasLoaded = true; + final idsToDelete = DB.instance + .values(boxName: DB.boxNameWalletsToDeleteOnStart) + .toList(); + // clear out any wallet hive boxes where the wallet was deleted in previous app run - for (final walletId in DB.instance.values( - boxName: DB.boxNameWalletsToDeleteOnStart, - )) { + for (final walletId in idsToDelete) { await mainDB.isar.writeTxn( () async => await mainDB.isar.walletInfo .where() @@ -485,10 +497,23 @@ class Wallets { .deleteAll(), ); } + + // Grin wallet files whose delete found the directory busy. + final grinRemaining = await GrinWallet.retryDeferredDeletes( + walletIds: idsToDelete, + secureStore: nodeService.secureStorageInterface, + ); + // clear list await DB.instance.deleteAll( boxName: DB.boxNameWalletsToDeleteOnStart, ); + for (final walletId in grinRemaining) { + await DB.instance.add( + boxName: DB.boxNameWalletsToDeleteOnStart, + value: walletId, + ); + } final walletInfoList = await mainDB.isar.walletInfo .where() @@ -577,9 +602,10 @@ class Wallets { final List idsToRefresh = []; final List> walletInitFutures = asyncWalletIds .map( - (id) => _wallets[id]!.init().then((_) { - if (shouldSyncAllOnceOnStartup || - walletIdsToSyncOnceOnStartup.contains(id)) { + (id) => initAtStartup(_wallets[id]!).then((opened) { + if (opened && + (shouldSyncAllOnceOnStartup || + walletIdsToSyncOnceOnStartup.contains(id))) { idsToRefresh.add(id); } }), @@ -706,21 +732,76 @@ class Wallets { } } + /// Deletes a Grin wallet's files and password. False when they are still + /// there, because the directory was busy or the delete failed. + static Future _deleteGrinWalletFiles( + String walletId, + SecureStorageInterface secureStorage, + ) async { + try { + return await GrinWallet.deleteWalletFiles( + walletId: walletId, + secureStore: secureStorage, + ); + } catch (e) { + Logging.instance.w("Grin wallet: $walletId files not deleted: $e"); + return false; + } + } + + /// Opens [wallet] at startup. A wallet that cannot be opened is logged + /// and reported as false, so it does not stop the others from being + /// refreshed. + @visibleForTesting + static Future initAtStartup(Wallet wallet) async { + try { + await wallet.init(); + return true; + } catch (e, s) { + Logging.instance.e( + "Wallet ${wallet.walletId} failed to open at startup", + error: e, + stackTrace: s, + ); + return false; + } + } + + /// Removes a wallet whose creation was never finished. + @visibleForTesting + Future deleteUnfinishedWallet(String walletId) => + _deleteWallet(walletId); + Future _deleteWallet(String walletId) async { // TODO proper clean up of other wallet data in addition to the following final info = await mainDB.isar.walletInfo .where() .walletIdEqualTo(walletId) .findFirst(); - final isFrostWallet = - info != null && - AppConfig.getCryptoCurrencyFor(info.coinName) is FrostCurrency; + final coin = info == null + ? null + : AppConfig.getCryptoCurrencyFor(info.coinName); + final isFrostWallet = coin is FrostCurrency; if (isFrostWallet) { await BitcoinFrostWallet.deleteSecureStorage( walletId: walletId, secureStorage: nodeService.secureStorageInterface, ); } + if (coin is Grin) { + // The native wallet and its password exist from the first open. + // What cannot be deleted now is retried at the next load. + final deleted = await _deleteGrinWalletFiles( + walletId, + nodeService.secureStorageInterface, + ); + if (!deleted) { + await DB.instance.add( + boxName: DB.boxNameWalletsToDeleteOnStart, + value: walletId, + ); + } + } await mainDB.isar.writeTxn(() async { if (isFrostWallet) { await mainDB.isar.frostWalletInfo.deleteByWalletId(walletId); diff --git a/lib/utilities/amount/amount_unit.dart b/lib/utilities/amount/amount_unit.dart index 4af50c345e..4550da4be6 100644 --- a/lib/utilities/amount/amount_unit.dart +++ b/lib/utilities/amount/amount_unit.dart @@ -98,7 +98,10 @@ extension AmountUnitExt on AmountUnit { case AmountUnit.nano: if (coin is Ethereum) { return "gwei"; - } else if (coin is Wownero || coin is Monero || coin is NanoCurrency) { + } else if (coin is Wownero || + coin is Monero || + coin is NanoCurrency || + coin is Grin) { return "n${coin.ticker}"; } else { return "sats"; diff --git a/lib/utilities/desktop_startup_and_reset.dart b/lib/utilities/desktop_startup_and_reset.dart index 41db48fb37..006a449992 100644 --- a/lib/utilities/desktop_startup_and_reset.dart +++ b/lib/utilities/desktop_startup_and_reset.dart @@ -31,6 +31,7 @@ abstract final class DesktopStartupAndReset { 'wallets', 'epiccash', 'mimblewimblecoin', + 'grin', 'xelis', 'drift', 'sqlite', diff --git a/lib/utilities/native_library_check.dart b/lib/utilities/native_library_check.dart index 1bd621976e..aa4b516806 100644 --- a/lib/utilities/native_library_check.dart +++ b/lib/utilities/native_library_check.dart @@ -56,6 +56,7 @@ bool _always() => true; bool _hasMonero() => AppConfig.coins.whereType().isNotEmpty; bool _hasWownero() => AppConfig.coins.whereType().isNotEmpty; bool _hasSalvium() => AppConfig.coins.whereType().isNotEmpty; +bool _hasGrin() => AppConfig.coins.whereType().isNotEmpty; /// coinlib's secp256k1, named as in its secp256k1_io.dart. Every non /// cryptonote wallet needs it. @@ -91,6 +92,13 @@ const nativeLibraries = [ macos: "SalviumWallet.framework/SalviumWallet", isBundled: _hasSalvium, ), + NativeLibrary( + displayName: "Grin wallets", + windows: "grin_ffi.dll", + linux: "libgrin_ffi.so", + macos: "grin_ffi.framework/grin_ffi", + isBundled: _hasGrin, + ), secp256k1NativeLibrary, ]; diff --git a/lib/utilities/owner_only_directory.dart b/lib/utilities/owner_only_directory.dart new file mode 100644 index 0000000000..c98ecb8ee9 --- /dev/null +++ b/lib/utilities/owner_only_directory.dart @@ -0,0 +1,35 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; + +typedef _ChmodNative = Int32 Function(Pointer, Uint32); +typedef _ChmodDart = int Function(Pointer, int); + +_ChmodDart? _chmod; + +/// Sets [path] to mode 0700 on Linux and macOS. Does nothing elsewhere. +/// +/// Throws [FileSystemException] if the mode cannot be set. +void restrictDirectoryToOwner(String path) { + if (!(Platform.isLinux || Platform.isMacOS)) return; + final chmod = _chmod ??= DynamicLibrary.process() + .lookupFunction<_ChmodNative, _ChmodDart>("chmod"); + final nativePath = path.toNativeUtf8(); + try { + if (chmod(nativePath, 448) != 0) { + throw FileSystemException("Could not restrict directory", path); + } + } finally { + malloc.free(nativePath); + } +} + +/// Creates [path] and its parents if needed, then restricts [path] to its +/// owner. +Future createOwnerOnlyDirectory(String path) async { + final dir = Directory(path); + if (!await dir.exists()) await dir.create(recursive: true); + restrictDirectoryToOwner(dir.path); + return dir; +} diff --git a/lib/utilities/stack_file_system.dart b/lib/utilities/stack_file_system.dart index 292dda1368..0ed5647e91 100644 --- a/lib/utilities/stack_file_system.dart +++ b/lib/utilities/stack_file_system.dart @@ -14,6 +14,7 @@ import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; import '../app_config.dart'; +import 'owner_only_directory.dart'; import 'prefs.dart'; import 'util.dart'; @@ -192,6 +193,19 @@ abstract class StackFileSystem { return dir; } + /// The absolute `/grin` directory, owner only on unix desktop. + /// + /// The desktop data dir override can be relative, and the Grin library + /// takes relative paths as given, so this is always made absolute. + static Future applicationGrinDirectory() async => + await createOwnerOnlyDirectory(await applicationGrinDirectoryPath()); + + /// The path of [applicationGrinDirectory], without creating it. + static Future applicationGrinDirectoryPath() async { + final root = await applicationRootDirectory(); + return path.normalize(path.absolute(path.join(root.path, "grin"))); + } + static Future initThemesDir() async { final root = await applicationRootDirectory(); diff --git a/lib/utilities/test_grin_node_connection.dart b/lib/utilities/test_grin_node_connection.dart new file mode 100644 index 0000000000..e506bc8dbb --- /dev/null +++ b/lib/utilities/test_grin_node_connection.dart @@ -0,0 +1,72 @@ +import 'package:grin_native/grin_native.dart'; + +import '../app_config.dart'; +import '../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; +import '../services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import '../services/tor_service.dart'; +import '../wallets/wallet/supporting/grin/grin_errors.dart'; +import '../wallets/wallet/supporting/grin/grin_node_url.dart'; +import '../wallets/wallet/supporting/grin/grin_transport.dart'; +import '../wl_gen/interfaces/libgrin_interface.dart'; +import 'logger.dart'; +import 'prefs.dart'; +import 'tor_plain_net_option_enum.dart'; + +/// Asks a Grin node for its tip through the transport the wallet would use. +/// +/// Returns [data] with the scheme in its host, or null when the node cannot +/// be reached or the Tor settings do not allow it. The foreign API's +/// `get_tip` needs no API secret, so a missing secret does not fail this. +Future testGrinNodeConnection( + NodeFormData data, { + required Prefs prefs, + required TorService Function() torService, + GrinWalletBackend? backend, + bool? torFeature, +}) async { + final host = data.host?.trim(); + final port = data.port; + final useSSL = data.useSSL; + if (host == null || host.isEmpty || port == null || useSSL == null) { + return null; + } + + final String url; + try { + url = grinNodeUrl(host: host, port: port, useSSL: useSSL); + } on GrinNodeUrlException catch (e) { + Logging.instance.w("Grin node test: ${e.message}"); + return null; + } + + final feature = torFeature ?? AppConfig.hasFeature(AppFeature.tor); + final transport = resolveGrinTransport( + torFeature: feature, + useTor: prefs.useTor, + torStatus: feature ? torService().status : TorConnectionStatus.disconnected, + killSwitch: prefs.torKillSwitch, + nodeNetOption: data.netOption ?? TorPlainNetworkOption.both, + nodeIsOnion: isOnionHost(host), + proxyAddress: () => grinProxyAddress(torService()), + ); + if (transport is! GrinDirect && transport is! GrinProxy) { + Logging.instance.w("Grin node test not run: $transport"); + return null; + } + + try { + await (backend ?? libGrin.backend).testNodeConnection( + nodeUrl: url, + apiSecret: data.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + ); + } catch (e) { + Logging.instance.w("Grin node test failed: ${describeGrinError(e)}"); + return null; + } + + final scheme = Uri.parse(url).scheme; + if (!host.contains("://")) data.host = "$scheme://$host"; + data.useSSL = scheme == "https"; + return data; +} diff --git a/lib/utilities/test_node_connection.dart b/lib/utilities/test_node_connection.dart index 811e74664d..5ac9816b8d 100644 --- a/lib/utilities/test_node_connection.dart +++ b/lib/utilities/test_node_connection.dart @@ -26,6 +26,7 @@ import 'connection_check/electrum_connection_check.dart'; import 'logger.dart'; import 'test_epic_box_connection.dart'; import 'test_eth_node_connection.dart'; +import 'test_grin_node_connection.dart'; import 'test_monero_node_connection.dart'; import 'test_mwcmqs_connection.dart'; import 'test_stellar_node_connection.dart'; @@ -169,6 +170,18 @@ Future testNodeConnection({ } break; + case Grin(): + final data = await testGrinNodeConnection( + formData, + prefs: read(prefsChangeNotifierProvider), + torService: () => read(pTorService), + ); + if (data != null) { + testPassed = true; + onSuccess?.call(data); + } + break; + case CryptonoteCurrency(): try { final proxyInfo = !AppConfig.hasFeature(AppFeature.tor) diff --git a/lib/wallets/crypto_currency/coins/grin.dart b/lib/wallets/crypto_currency/coins/grin.dart new file mode 100644 index 0000000000..5fcf87f688 --- /dev/null +++ b/lib/wallets/crypto_currency/coins/grin.dart @@ -0,0 +1,188 @@ +import 'package:grin_native/grin_native.dart'; + +import '../../../models/isar/models/blockchain_data/address.dart'; +import '../../../models/node_model.dart'; +import '../../../utilities/default_nodes.dart'; +import '../../../utilities/enums/derive_path_type_enum.dart'; +import '../../../wl_gen/interfaces/libgrin_interface.dart'; +import '../crypto_currency.dart'; +import '../intermediate/bip39_currency.dart'; + +class Grin extends Bip39Currency { + /// [addressBackend] replaces the native backend for address checks. + Grin(super.network, {this.addressBackend}) { + _idMain = "grin"; + _uriScheme = "grin"; + switch (network) { + case CryptoCurrencyNetwork.main: + _id = _idMain; + _name = "Grin"; + _ticker = "GRIN"; + _grinNetwork = GrinNetwork.mainnet; + case CryptoCurrencyNetwork.test: + _id = "grinTestNet"; + _name = "tGrin"; + _ticker = "tGRIN"; + _grinNetwork = GrinNetwork.testnet; + default: + throw Exception("Unsupported network: $network"); + } + } + + final GrinWalletBackend? addressBackend; + GrinWalletBackend get _addressBackend => addressBackend ?? libGrin.backend; + + late final String _id; + @override + String get identifier => _id; + + late final String _idMain; + @override + String get mainNetId => _idMain; + + late final String _name; + @override + String get prettyName => _name; + + late final String _uriScheme; + @override + String get uriScheme => _uriScheme; + + late final String _ticker; + @override + String get ticker => _ticker; + + late final GrinNetwork _grinNetwork; + + /// The chain as the Grin library names it. + GrinNetwork get grinNetwork => _grinNetwork; + + @override + String get genesisHash => "not used in grin"; + + /// libwallet's default. + @override + int get minConfirms => 10; + + /// COINBASE_MATURITY. + @override + int get minCoinbaseConfirms => 1440; + + @override + bool get torSupport => true; + + /// Accepts a Slatepack address, a v3 onion address and an http(s) URL of + /// this network. + @override + bool validateAddress(String address) => addressKind(address) != null; + + /// The kind of send target [address] is, or null when it is not one for + /// this network. + GrinAddressKind? addressKind(String address) { + try { + final result = _addressBackend.validateAddressSync(address, _grinNetwork); + return result.kind == GrinAddressKind.unknown ? null : result.kind; + } catch (_) { + return null; + } + } + + /// Genesis block times, in seconds since the epoch. + static const int genesisTimestampMain = 1547568086; + static const int genesisTimestampTest = 1546030084; + + /// A height at or below the chain height at [date], for restore heights. + /// Blocks are counted at 61 seconds, so the result runs a little low. + int heightFromDate(DateTime date) { + final genesis = network == CryptoCurrencyNetwork.main + ? genesisTimestampMain + : genesisTimestampTest; + final seconds = date.millisecondsSinceEpoch ~/ 1000 - genesis; + return seconds <= 0 ? 0 : seconds ~/ 61; + } + + /// Whether [text] looks like an armored Slatepack. + bool isSlatepack(String text) { + final trimmed = text.trim(); + return trimmed.startsWith("BEGINSLATEPACK.") && + trimmed.endsWith("ENDSLATEPACK."); + } + + @override + NodeModel defaultNode({required bool isPrimary}) { + switch (network) { + case CryptoCurrencyNetwork.main: + return NodeModel( + host: "https://grinnode.live", + port: 3413, + name: DefaultNodes.defaultName, + id: DefaultNodes.buildId(this), + useSSL: true, + enabled: true, + coinName: identifier, + isFailover: true, + isDown: false, + torEnabled: true, + clearnetEnabled: true, + isPrimary: isPrimary, + ); + + case CryptoCurrencyNetwork.test: + return NodeModel( + host: "http://127.0.0.1", + port: 13413, + name: DefaultNodes.defaultName, + id: DefaultNodes.buildId(this), + useSSL: false, + enabled: true, + coinName: identifier, + isFailover: true, + isDown: false, + torEnabled: true, + clearnetEnabled: true, + isPrimary: isPrimary, + ); + + default: + throw UnimplementedError(); + } + } + + @override + int get defaultSeedPhraseLength => 24; + + @override + int get fractionDigits => 9; + + @override + bool get hasBuySupport => false; + + @override + bool get hasMnemonicPassphraseSupport => false; + + @override + List get possibleMnemonicLengths => [defaultSeedPhraseLength, 12]; + + @override + AddressType get defaultAddressType => AddressType.mimbleWimble; + + @override + BigInt get satsPerCoin => BigInt.from(1000000000); + + @override + int get targetBlockTimeSeconds => 60; + + @override + DerivePathType get defaultDerivePathType => throw UnsupportedError( + "$runtimeType does not use bitcoin style derivation paths", + ); + + /// No explorer until a kernel search URL is chosen. + @override + Uri defaultBlockExplorer(String txid) => + throw UnsupportedError("$runtimeType has no default block explorer"); + + @override + AddressType? getAddressType(String address) => + validateAddress(address) ? AddressType.mimbleWimble : null; +} diff --git a/lib/wallets/crypto_currency/crypto_currency.dart b/lib/wallets/crypto_currency/crypto_currency.dart index d46382ea0e..4a712d2e39 100644 --- a/lib/wallets/crypto_currency/crypto_currency.dart +++ b/lib/wallets/crypto_currency/crypto_currency.dart @@ -14,6 +14,7 @@ export 'coins/epiccash.dart'; export 'coins/ethereum.dart'; export 'coins/fact0rn.dart'; export 'coins/firo.dart'; +export 'coins/grin.dart'; export 'coins/litecoin.dart'; export 'coins/mimblewimblecoin.dart'; export 'coins/monero.dart'; diff --git a/lib/wallets/isar/models/wallet_info.dart b/lib/wallets/isar/models/wallet_info.dart index 12329f8ceb..c4f607e05e 100644 --- a/lib/wallets/isar/models/wallet_info.dart +++ b/lib/wallets/isar/models/wallet_info.dart @@ -563,6 +563,7 @@ abstract class WalletInfoKeys { static const String tokenContractAddresses = "tokenContractAddressesKey"; static const String epiccashData = "epiccashDataKey"; static const String mimblewimblecoinData = "mimblewimblecoinDataKey"; + static const String grinData = "grinDataKey"; static const String bananoMonkeyImageBytes = "monkeyImageBytesKey"; static const String tezosDerivationPath = "tezosDerivationPathKey"; static const String xelisDerivationPath = "xelisDerivationPathKey"; diff --git a/lib/wallets/models/tx_data.dart b/lib/wallets/models/tx_data.dart index b6519b5130..ce15cf2306 100644 --- a/lib/wallets/models/tx_data.dart +++ b/lib/wallets/models/tx_data.dart @@ -115,6 +115,13 @@ class TxData { final TransactionV2? tempTx; + /// The armored Slatepack a send produced. Left out of [toString]. + final String? slatepack; + + // grin http sends + final bool grinClearnetAcknowledged; + final bool grinPlaintextAcknowledged; + final bool ignoreCachedBalanceChecks; final bool subtractFeeFromAmount; @@ -165,6 +172,9 @@ class TxData { this.sparkSpends, this.usedSparkCoins, this.tempTx, + this.slatepack, + this.grinClearnetAcknowledged = false, + this.grinPlaintextAcknowledged = false, this.ignoreCachedBalanceChecks = false, this.subtractFeeFromAmount = false, this.opNameState, @@ -318,6 +328,9 @@ class TxData { List? sparkSpends, List? usedSparkCoins, TransactionV2? tempTx, + String? slatepack, + bool? grinClearnetAcknowledged, + bool? grinPlaintextAcknowledged, bool? ignoreCachedBalanceChecks, bool? subtractFeeFromAmount, NameOpState? opNameState, @@ -370,6 +383,11 @@ class TxData { sparkSpends: sparkSpends ?? this.sparkSpends, usedSparkCoins: usedSparkCoins ?? this.usedSparkCoins, tempTx: tempTx ?? this.tempTx, + slatepack: slatepack ?? this.slatepack, + grinClearnetAcknowledged: + grinClearnetAcknowledged ?? this.grinClearnetAcknowledged, + grinPlaintextAcknowledged: + grinPlaintextAcknowledged ?? this.grinPlaintextAcknowledged, ignoreCachedBalanceChecks: ignoreCachedBalanceChecks ?? this.ignoreCachedBalanceChecks, subtractFeeFromAmount: diff --git a/lib/wallets/wallet/impl/grin_wallet.dart b/lib/wallets/wallet/impl/grin_wallet.dart new file mode 100644 index 0000000000..c6337cd495 --- /dev/null +++ b/lib/wallets/wallet/impl/grin_wallet.dart @@ -0,0 +1,1608 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:event_bus/event_bus.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:meta/meta.dart'; +import 'package:mutex/mutex.dart'; +import 'package:path/path.dart' as p; +import 'package:stack_wallet_backup/generate_password.dart'; + +import '../../../app_config.dart'; +import '../../../exceptions/wallet/node_tor_mismatch_config_exception.dart'; +import '../../../models/balance.dart'; +import '../../../models/isar/models/blockchain_data/address.dart'; +import '../../../models/isar/models/blockchain_data/transaction.dart'; +import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../../../models/node_model.dart'; +import '../../../models/paymint/fee_object_model.dart'; +import '../../../services/event_bus/events/global/blocks_remaining_event.dart'; +import '../../../services/event_bus/events/global/node_connection_status_changed_event.dart'; +import '../../../services/event_bus/events/global/refresh_percent_changed_event.dart'; +import '../../../services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import '../../../services/event_bus/events/global/tor_status_changed_event.dart'; +import '../../../services/event_bus/events/global/wallet_sync_status_changed_event.dart'; +import '../../../services/event_bus/global_event_bus.dart'; +import '../../../services/tor_service.dart'; +import '../../../utilities/amount/amount.dart'; +import '../../../utilities/enums/slatepack_method.dart'; +import '../../../utilities/flutter_secure_storage_interface.dart'; +import '../../../utilities/logger.dart'; +import '../../../utilities/owner_only_directory.dart'; +import '../../../utilities/stack_file_system.dart'; +import '../../../utilities/tor_plain_net_option_enum.dart'; +import '../../../wl_gen/interfaces/libgrin_interface.dart'; +import '../../crypto_currency/crypto_currency.dart'; +import '../../models/tx_data.dart'; +import '../intermediate/bip39_wallet.dart'; +import '../supporting/grin/grin_errors.dart'; +import '../supporting/grin/grin_node_url.dart'; +import '../supporting/grin/grin_transport.dart'; +import '../supporting/grin/grin_tx_mapping.dart'; +import '../supporting/grin_wallet_info_extension.dart'; +import '../wallet_mixin_interfaces/slatepack_interface.dart'; + +/// The Stack balance for a Grin balance. +/// +/// libwallet leaves locked outputs out of its total, so they are not +/// counted here either. +Balance grinBalanceToStack(GrinBalance balance, int fractionDigits) { + Amount amount(BigInt raw) => + Amount(rawValue: raw, fractionDigits: fractionDigits); + final pending = + balance.amountAwaitingConfirmation + + balance.amountImmature + + balance.amountAwaitingFinalization; + return Balance( + total: amount(balance.amountCurrentlySpendable + pending), + spendable: amount(balance.amountCurrentlySpendable), + blockedTotal: amount(BigInt.zero), + pendingSpendable: amount(pending), + ); +} + +typedef _AppliedNetwork = ({ + String nodeUrl, + String? apiSecret, + GrinTransport transport, +}); + +class GrinWallet extends Bip39Wallet { + GrinWallet( + CryptoCurrencyNetwork network, { + GrinWalletBackend? backend, + TorService? torService, + EventBus? eventBus, + }) : _backendOverride = backend, + _torServiceOverride = torService, + _eventBusOverride = eventBus, + super(Grin(network, addressBackend: backend)); + + // ========== Static ========================================================= + + /// The live instance for each wallet id, registered or not. A restore or a + /// new wallet is not in [Wallets] yet, and delete must still reach it. + static final Map _owners = {}; + + /// Serializes open, create, close and delete per wallet id. + static final Map _dirLocks = {}; + static Mutex _dirLock(String walletId) => + _dirLocks.putIfAbsent(walletId, Mutex.new); + + /// Secure storage key of the generated seed file password. + static String passwordKey(String walletId) => + "${walletId}_grinWalletPassword"; + + /// Blocks until an unfinished send or invoice payment expires, about a day. + static const int slatepackTtlBlocks = 1440; + + static const _torConnectWait = Duration(seconds: 60); + + static void _checkWalletId(String walletId) { + if (walletId.isEmpty || + walletId.contains("/") || + walletId.contains(r"\") || + walletId.contains("..")) { + throw GrinWalletException("Invalid wallet id."); + } + } + + /// The absolute directory of [walletId]'s Grin wallet. Nothing is created. + static Future walletDirPath(String walletId) async { + _checkWalletId(walletId); + final root = await StackFileSystem.applicationGrinDirectoryPath(); + final dir = p.normalize(p.join(root, walletId)); + if (!p.isAbsolute(dir)) { + throw GrinWalletException("The Grin wallet directory is not absolute."); + } + return dir; + } + + /// Deletes the native wallet of [walletId] and its password. + /// + /// Closes the live instance first, registered or not. Returns false when + /// the library reports the directory busy; nothing is deleted then and the + /// caller should try again later. + static Future deleteWalletFiles({ + required String walletId, + required SecureStorageInterface secureStore, + GrinWalletBackend? backend, + }) { + return _dirLock(walletId).protect(() async { + final owner = _owners[walletId]; + if (owner != null) { + owner.shouldAutoSync = false; + await owner._closeUnlocked(); + } + + final dir = await walletDirPath(walletId); + if (await Directory(dir).exists()) { + final lib = backend ?? owner?.backend ?? libGrin.backend; + try { + await lib.delete(walletDir: dir); + } on GrinWalletBusyException { + Logging.instance.w("Grin delete of $walletId deferred: busy"); + return false; + } catch (e) { + throw _failStatic("delete", e); + } + try { + // Only an empty directory goes; never recursive. + await Directory(dir).delete(); + } on FileSystemException { + Logging.instance.w("Grin wallet directory of $walletId not empty"); + } + } + + await secureStore.delete(key: passwordKey(walletId)); + return true; + }); + } + + /// Retries the native part of deletes that were busy. [walletIds] are the + /// ids deleted in earlier runs; returns the ones still not deleted. + static Future> retryDeferredDeletes({ + required Iterable walletIds, + required SecureStorageInterface secureStore, + GrinWalletBackend? backend, + }) async { + final remaining = []; + for (final walletId in walletIds) { + final String dir; + try { + dir = await walletDirPath(walletId); + } catch (_) { + continue; + } + try { + if (!await Directory(dir).exists()) continue; + final deleted = await deleteWalletFiles( + walletId: walletId, + secureStore: secureStore, + backend: backend, + ); + if (!deleted) remaining.add(walletId); + } catch (e) { + Logging.instance.w( + "Grin deferred delete of $walletId failed: ${describeGrinError(e)}", + ); + remaining.add(walletId); + } + } + return remaining; + } + + static Exception _failStatic(String operation, Object error) { + Logging.instance.w("Grin $operation failed: ${describeGrinError(error)}"); + return sanitizeGrinError(error); + } + + // ========== Fields ========================================================= + + final GrinWalletBackend? _backendOverride; + final TorService? _torServiceOverride; + final EventBus? _eventBusOverride; + + GrinWalletBackend get backend => _backendOverride ?? libGrin.backend; + EventBus get _bus => _eventBusOverride ?? GlobalEventBus.instance; + TorService get _tor => _torServiceOverride ?? TorService.sharedInstance; + + GrinWalletApi? _api; + Future? _initializing; + Future? _closing; + Future? _scanJob; + + /// Set by [_stopScanJob]. A job that has not handed its scan to the + /// library yet ends without starting it. + bool _scanStopRequested = false; + bool _exited = false; + + _AppliedNetwork? _applied; + final _transportMutex = Mutex(); + Completer? _torConnecting; + StreamSubscription? _torStatusSub; + StreamSubscription? _torPrefSub; + + /// The last node refresh could not reach the node. + bool _offline = false; + + /// Armored Slatepacks by txid from the last history read. + Map _slatepacks = const {}; + + double highestPercent = 0; + + /// Whether the Tor feature is compiled in. + @visibleForTesting + bool get torFeatureEnabled => AppConfig.hasFeature(AppFeature.tor); + + /// Whether a native wallet is open. + bool get isOpen => _api != null; + + bool get _scanPending => info.grinData?.pendingScanFrom != null; + + /// Whether a scan has to finish before node refreshes, fee estimates, + /// cancels and sends. + bool get isScanPending => _scanPending; + + // ========== Lifecycle ====================================================== + + @override + int get isarTransactionVersion => 2; + + @override + FilterOperation? get changeAddressFilterOperation => + FilterGroup.and(standardChangeAddressFilters); + + @override + FilterOperation? get receivingAddressFilterOperation => + FilterGroup.and(standardReceivingAddressFilters); + + /// Opens the native wallet, creating it the first time. + /// + /// Safe to call again on the same instance. Startup calls it for every + /// wallet, so it never starts a scan. With [isRestore] nothing is opened: + /// [recover] creates the wallet. + @override + Future init({bool? isRestore}) async { + final closing = _closing; + if (closing != null) await closing; + + if (isRestore != true) { + final pending = _initializing; + if (pending != null) { + await pending; + } else if (_api == null) { + final opening = _open(); + _initializing = opening; + try { + await opening; + } finally { + if (identical(_initializing, opening)) _initializing = null; + } + } + } + + await super.init(); + } + + Future _open() { + return _dirLock(walletId).protect(() async { + if (_api != null) return; + _claimOwnership(); + try { + final dir = await _ensureWalletDir(); + final existing = info.grinData; + final stored = await secureStorageInterface.read( + key: passwordKey(walletId), + ); + + GrinWalletApi api; + if (stored != null) { + try { + api = await backend.open( + config: _buildConfig(dir), + password: stored, + ); + } on GrinWalletNotFoundException { + if (existing == null) { + api = await _createNew(dir, stored); + } else if (existing.pendingScanFrom != null) { + // A restore or rescan stopped before the wallet was created. + // The scan it still owes rebuilds everything. + api = await _recreate(dir); + } else { + throw GrinWalletException( + "The Grin wallet files are missing. Restore this wallet from " + "its recovery phrase.", + ); + } + } + } else { + if (existing != null) { + throw GrinWalletException( + "The Grin wallet password is missing. Restore this wallet from " + "its recovery phrase.", + ); + } + final password = generatePassword(); + await secureStorageInterface.write( + key: passwordKey(walletId), + value: password, + ); + api = await _createNew(dir, password); + } + _api = api; + } catch (e) { + await _releaseOwnership(); + throw _fail("open", e); + } + }); + } + + /// A wallet Stack just made: its first refresh must not scan from genesis. + Future _createNew(String dir, String password) async { + final api = await _createClearingLeftovers( + dir: dir, + mnemonic: await getMnemonic(), + password: password, + isNewWallet: true, + ); + // A couple of days back, so a backup restored later cannot miss funds. + final creationHeight = cryptoCurrency.heightFromDate( + DateTime.now().subtract(const Duration(days: 2)), + ); + await info.updateGrinData( + grinData: GrinWalletData(creationHeight: creationHeight), + isar: mainDB.isar, + ); + await info.updateRestoreHeight( + newRestoreHeight: creationHeight, + isar: mainDB.isar, + ); + return api; + } + + void _claimOwnership() { + final owner = _owners[walletId]; + if (owner != null && !identical(owner, this) && owner._isLive) { + throw GrinWalletException( + "This Grin wallet is already open. Close it and try again.", + ); + } + _owners[walletId] = this; + _exited = false; + _subscribeTor(); + } + + bool get _isLive => _api != null || _scanJob != null; + + Future _releaseOwnership() async { + if (identical(_owners[walletId], this)) _owners.remove(walletId); + await _cancelTorSubscriptions(); + } + + Future _ensureWalletDir() async { + await StackFileSystem.applicationGrinDirectory(); + final dir = await walletDirPath(walletId); + final link = await FileSystemEntity.isLink(dir); + if (link) { + throw GrinWalletException("The Grin wallet directory is a link."); + } + await createOwnerOnlyDirectory(dir); + return dir; + } + + GrinWalletConfig _buildConfig(String dir) { + if (!p.isAbsolute(dir)) { + throw GrinWalletException("The Grin wallet directory is not absolute."); + } + final network = _resolveNetwork(); + _applied = network; + final transport = network.transport; + return GrinWalletConfig( + walletDir: dir, + network: cryptoCurrency.grinNetwork, + nodeUrl: network.nodeUrl, + nodeApiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + networkEnabled: transport is GrinDirect || transport is GrinProxy, + ); + } + + /// Closes the native wallet. A later [init] opens it again; nothing else + /// does. + @override + Future exit() async { + final closing = _closing ??= _dirLock(walletId).protect(_closeUnlocked); + try { + await closing; + } finally { + if (identical(_closing, closing)) _closing = null; + } + await super.exit(); + } + + Future _closeUnlocked() async { + _exited = true; + final api = _api; + // A scan may be waiting for Tor rather than inside the native library. + // Wake it before joining the job so close is never held by that timeout. + _releaseTorWaiters(); + // A cancelled scan still saves its resume height. Join that work before + // exit returns, otherwise wallet teardown can close Isar while the scan + // job is still writing to it. + if (_scanJob != null) { + await _stopScanJob(); + } else { + // Also stop a native scan that was not started by this instance. + try { + api?.cancelScan(); + } catch (e) { + Logging.instance.w( + "Grin scan cancellation failed: ${describeGrinError(e)}", + ); + } + } + await _releaseOwnership(); + _api = null; + _applied = null; + _slatepacks = const {}; + if (api == null) return; + try { + await api.close(); + } catch (e) { + Logging.instance.w("Grin close failed: ${describeGrinError(e)}"); + // An open handle keeps the directory busy until the app restarts, so + // try once more. + try { + await api.close(); + } catch (e) { + Logging.instance.w("Grin close failed again: ${describeGrinError(e)}"); + } + } + } + + // ========== Recovery and scanning ========================================== + + @override + Future recover({required bool isRescan}) async { + try { + if (isRescan) { + await _rescan(); + } else { + await _restore(); + } + } catch (e) { + throw _fail(isRescan ? "rescan" : "restore", e); + } + unawaited(_runScanJob()); + } + + /// A new wallet id from a mnemonic: create, then scan from the restore + /// height. + Future _restore() async { + await refreshMutex.protect(() async { + await _dirLock(walletId).protect(() async { + if (_api != null) { + throw GrinWalletException("This Grin wallet is already open."); + } + _claimOwnership(); + try { + final dir = await _ensureWalletDir(); + // Saved before the wallet exists. If anything from here on is + // interrupted, the next start still knows a scan is owed; a + // wallet created without that would be scanned from the first + // block by its first refresh. + final height = info.restoreHeight; + await info.updateGrinData( + grinData: GrinWalletData( + creationHeight: height, + pendingScanFrom: height, + ), + isar: mainDB.isar, + ); + _api = await _createFromMnemonic(dir); + } catch (e) { + await _releaseOwnership(); + rethrow; + } + }); + await _storeAddress(); + highestPercent = 0; + }); + } + + /// Keeps the history and scans again from the restore height. Creates the + /// wallet from the mnemonic first if its files are missing. + Future _rescan() async { + await _stopScanJob(); + + await refreshMutex.protect(() async { + // First, so a rescan that fails or is interrupted below is still owed. + await _markScanFromRestoreHeight(); + if (_api == null) { + final closing = _closing; + if (closing != null) await closing; + await _dirLock(walletId).protect(() async { + if (_api != null) return; + _claimOwnership(); + try { + final dir = await _ensureWalletDir(); + final stored = await secureStorageInterface.read( + key: passwordKey(walletId), + ); + if (stored != null) { + try { + _api = await backend.open( + config: _buildConfig(dir), + password: stored, + ); + return; + } on GrinWalletNotFoundException { + // Rebuilt from the mnemonic below. + } + } + _api = await _recreate(dir); + } catch (e) { + await _releaseOwnership(); + rethrow; + } + }); + await _storeAddress(); + } + highestPercent = 0; + }); + } + + /// Cancels the running scan job, if any, and waits for it to end. + /// + /// The library can only cancel a scan it has been given. A job that is + /// still waiting for its turn or for the network has not called it yet, + /// so the request is also kept for the job to see. + Future _stopScanJob() async { + final running = _scanJob; + if (running == null) return; + _scanStopRequested = true; + _api?.cancelScan(); + await running; + } + + Future _markScanFromRestoreHeight() async { + final height = info.restoreHeight; + await info.updateGrinData( + grinData: (info.grinData ?? GrinWalletData(creationHeight: height)) + .withPendingScanFrom(height), + isar: mainDB.isar, + ); + } + + /// Builds the native wallet again from the mnemonic when its files are + /// gone. The new wallet numbers its log from zero, so the stored history, + /// which refers to the old log, is dropped; the scan from the restore + /// height finds the funds again. + Future _recreate(String dir) async { + await _markScanFromRestoreHeight(); + final api = await _createFromMnemonic(dir); + _slatepacks = const {}; + await mainDB.isar.writeTxn(() async { + await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .deleteAll(); + }); + return api; + } + + /// Writes the password (reusing a stored one), then creates the wallet + /// from the stored mnemonic. Leftover data of an interrupted create or + /// delete is cleared once. + Future _createFromMnemonic(String dir) async { + var password = await secureStorageInterface.read( + key: passwordKey(walletId), + ); + if (password == null) { + password = generatePassword(); + await secureStorageInterface.write( + key: passwordKey(walletId), + value: password, + ); + } + return _createClearingLeftovers( + dir: dir, + mnemonic: await getMnemonic(), + password: password, + isNewWallet: false, + ); + } + + /// Creates the native wallet. Data left by an interrupted create or + /// delete, which holds no seed, is cleared once and the create repeated. + Future _createClearingLeftovers({ + required String dir, + required String mnemonic, + required String password, + required bool isNewWallet, + }) async { + Future create() => backend.create( + config: _buildConfig(dir), + mnemonic: mnemonic, + password: password, + isNewWallet: isNewWallet, + ); + try { + return await create(); + } on GrinWalletExistsException catch (e) { + if (e.details?["reason"] != "leftover_wallet_data") rethrow; + await backend.delete(walletDir: dir); + return await create(); + } + } + + Future _setPendingScanFrom(int? height) async { + try { + final current = info.grinData; + await info.updateGrinData( + grinData: (current ?? GrinWalletData(creationHeight: height ?? 0)) + .withPendingScanFrom(height), + isar: mainDB.isar, + ); + } catch (e) { + // The wallet may be gone after a delete. + Logging.instance.w("Grin scan state not saved: ${describeGrinError(e)}"); + } + } + + Future _runScanJob() { + final running = _scanJob; + if (running != null) return running; + late final Future job; + _scanStopRequested = false; + job = _scan().whenComplete(() { + if (identical(_scanJob, job)) _scanJob = null; + if (!_exited) ensurePeriodicRefreshTimer(); + }); + _scanJob = job; + return job; + } + + Future _scan() async { + var succeeded = false; + await refreshMutex.protect(() async { + final api = _api; + final from = info.grinData?.pendingScanFrom; + if (api == null || _exited || from == null) return; + + _fireSyncStatus(WalletSyncStatus.syncing); + final timer = Timer.periodic( + const Duration(seconds: 1), + (_) => _reportScanProgress(api), + ); + try { + await _requireNetwork(); + // Stopped before it started: nothing was scanned. + if (_scanStopRequested) return; + await api.scan(startHeight: from); + await _setPendingScanFrom(null); + succeeded = true; + } on GrinCancelledException catch (e) { + await _saveScanProgress(e, from); + } catch (e) { + // Closing deliberately wakes a scan waiting for Tor. That is normal + // cancellation, not a sync failure to show to the user. + if (_exited) return; + // The batches before the failure are saved, so a scan over a poor + // connection still gets further each time. + if (e is GrinException) await _saveScanProgress(e, from); + Logging.instance.w("Grin scan failed: ${describeGrinError(e)}"); + _fireSyncStatus(WalletSyncStatus.unableToSync); + } finally { + timer.cancel(); + } + }); + if (succeeded && !_exited) { + highestPercent = 1; + await refresh(); + } + } + + /// Moves the resume height past what the ended scan says it saved. + /// + /// An error without a height (a scan cancelled before it started, or one + /// that failed before it read the chain tip) saved nothing, and the + /// resume height stays. The wallet's last scanned height is no stand-in: + /// a refresh moves it to the tip, which would end a rescan early. + Future _saveScanProgress(GrinException ended, int from) async { + final scanned = ended.scannedHeight; + if (scanned == null || scanned < from) return; + await _setPendingScanFrom(scanned + 1); + } + + void _reportScanProgress(GrinWalletApi api) { + try { + final progress = api.scanProgress(); + if (!progress.isScanning || progress.tipHeight <= 0) return; + final percent = (progress.progressPct / 100).clamp(0.0, 1.0); + highestPercent = math.max(highestPercent, percent); + if (doNotFireRefreshEvents) return; + _bus.fire(RefreshPercentChangedEvent(highestPercent, walletId)); + _bus.fire( + BlocksRemainingEvent( + math.max(progress.tipHeight - progress.scannedHeight, 0), + walletId, + ), + ); + } catch (_) { + // Closed under us; the scan ends with it. + } + } + + double get restoreProgress => highestPercent; + + void _fireSyncStatus(WalletSyncStatus status) { + if (doNotFireRefreshEvents) return; + _bus.fire(WalletSyncStatusChangedEvent(status, walletId, cryptoCurrency)); + } + + void _fireDisconnected() { + if (doNotFireRefreshEvents) return; + _bus.fire( + NodeConnectionStatusChangedEvent( + NodeConnectionStatus.disconnected, + walletId, + cryptoCurrency, + ), + ); + _fireSyncStatus(WalletSyncStatus.unableToSync); + } + + /// Starts the pending scan if there is one, otherwise a normal refresh. + /// A scan is not awaited: it can take hours, and startup awaits refresh. + @override + Future refresh() async { + if (_api == null || _exited) return; + if (_scanPending) { + unawaited(_runScanJob()); + return; + } + return super.refresh(); + } + + // ========== Transport ====================================================== + + NodeModel get _node => getCurrentNode(); + + GrinTransport _resolveTransport(NodeModel node) { + final torFeature = torFeatureEnabled; + return resolveGrinTransport( + torFeature: torFeature, + useTor: prefs.useTor, + torStatus: torFeature ? _tor.status : TorConnectionStatus.disconnected, + killSwitch: prefs.torKillSwitch, + nodeNetOption: TorPlainNetworkOption.fromNodeData( + node.torEnabled, + node.clearnetEnabled, + ), + nodeIsOnion: isOnionHost(node.host), + proxyAddress: () => grinProxyAddress(_tor), + ); + } + + _AppliedNetwork _resolveNetwork() { + final node = _node; + var transport = _resolveTransport(node); + String url; + try { + url = grinNodeUrl(host: node.host, port: node.port, useSSL: node.useSSL); + } on GrinNodeUrlException { + final fallback = cryptoCurrency.defaultNode(isPrimary: true); + url = grinNodeUrl( + host: fallback.host, + port: fallback.port, + useSSL: fallback.useSSL, + ); + transport = const GrinBlocked(GrinBlockedReason.invalidNode); + } + return (nodeUrl: url, apiSecret: node.nodeApiSecret, transport: transport); + } + + void _subscribeTor() { + _torStatusSub ??= _bus.on().listen(( + event, + ) { + switch (event.newStatus) { + case TorConnectionStatus.connecting: + _torConnecting ??= Completer(); + case TorConnectionStatus.connected: + case TorConnectionStatus.disconnected: + _releaseTorWaiters(); + unawaited(_applyTransport()); + } + }); + _torPrefSub ??= _bus.on().listen( + (_) => unawaited(_applyTransport()), + ); + } + + void _releaseTorWaiters() { + final waiter = _torConnecting; + _torConnecting = null; + if (waiter != null && !waiter.isCompleted) waiter.complete(); + } + + Future _cancelTorSubscriptions() async { + final status = _torStatusSub; + final pref = _torPrefSub; + _torStatusSub = null; + _torPrefSub = null; + await status?.cancel(); + await pref?.cancel(); + } + + /// Hands the current transport to the library when it changed. + /// + /// Read at apply time, never from the event, because Tor events arrive + /// before the preference they belong to. A running scan is cancelled first + /// so the change does not wait a whole batch; it resumes on the next + /// refresh. + Future _applyTransport({bool refreshAfter = true}) async { + Future? cancelledScan; + final changed = await _transportMutex.protect(() async { + final api = _api; + if (api == null || _exited) return false; + final network = _resolveNetwork(); + final transport = network.transport; + if (transport is GrinHold) return false; + if (network == _applied) return false; + + if (_scanJob != null) { + cancelledScan = _scanJob; + api.cancelScan(); + } + await api.updateNetwork( + nodeUrl: network.nodeUrl, + apiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + networkEnabled: transport is! GrinBlocked, + ); + _applied = network; + return true; + }); + if (!changed) return; + + if (_applied?.transport is GrinBlocked) { + _fireDisconnected(); + } else if (refreshAfter && shouldAutoSync) { + // The next scan needs the resume height saved by the finishing job. + // Calls from that job use refreshAfter: false. + if (cancelledScan != null) await cancelledScan; + unawaited(refresh()); + } + } + + /// The transport for a node call, after waiting out a Tor connect. Throws + /// when the network is blocked. + Future _usableTransport() async { + var transport = _resolveNetwork().transport; + if (transport is GrinHold) { + final waiter = _torConnecting ??= Completer(); + await waiter.future.timeout(_torConnectWait, onTimeout: () {}); + transport = _resolveNetwork().transport; + } + return switch (transport) { + GrinHold() => throw GrinWalletException("Tor is still connecting."), + GrinBlocked(:final reason) => throw _blockedException(reason), + GrinDirect() || GrinProxy() => transport, + }; + } + + Exception _blockedException(GrinBlockedReason reason) => switch (reason) { + GrinBlockedReason.torOnlyNodeTorOff => NodeTorMismatchConfigException( + message: "TOR off but node set to TOR only", + ), + GrinBlockedReason.clearnetNodeTorOn => NodeTorMismatchConfigException( + message: "TOR enabled but node set to clearnet only", + ), + GrinBlockedReason.torDown => GrinWalletException("Tor is not connected."), + GrinBlockedReason.invalidNode => GrinWalletException( + "The Grin node address is not valid.", + ), + }; + + /// The open wallet with the current transport applied, for a call that + /// reaches the node. + Future _requireNetwork() async { + _requireApi(); + await _usableTransport(); + await _applyTransport(refreshAfter: false); + final transport = _applied?.transport; + if (transport is GrinBlocked) throw _blockedException(transport.reason); + return _requireApi(); + } + + GrinWalletApi _requireApi() { + final api = _api; + if (api == null || _exited) { + throw GrinWalletException("The Grin wallet is not open."); + } + return api; + } + + void _refuseWhileScanning() { + if (_scanPending) { + throw GrinWalletException( + "Wait for the Grin wallet to finish scanning and try again.", + ); + } + } + + Exception _fail(String operation, Object error) => + _failStatic(operation, error); + + // ========== Sync =========================================================== + + @override + Future updateNode() async { + if (_api == null || _exited) return; + try { + await _applyTransport(); + } catch (e) { + throw _fail("updateNode", e); + } + } + + @override + Future updateChainHeight() async { + if (_exited) return; + try { + final transport = await _usableTransport(); + final network = _resolveNetwork(); + final nodeInfo = await backend.testNodeConnection( + nodeUrl: network.nodeUrl, + apiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + ); + await info.updateCachedChainHeight( + newHeight: nodeInfo.height, + isar: mainDB.isar, + ); + } catch (e) { + throw _fail("updateChainHeight", e); + } + } + + @override + Future pingCheck() async { + try { + final network = _resolveNetwork(); + final transport = network.transport; + if (transport is! GrinDirect && transport is! GrinProxy) return false; + await backend.testNodeConnection( + nodeUrl: network.nodeUrl, + apiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + ); + return true; + } catch (_) { + return false; + } + } + + @override + Future updateTransactions() async { + final current = _api; + if (current == null || _exited) return; + try { + final fromNode = !_scanPending; + final api = fromNode ? await _requireNetwork() : current; + final list = await api.getTransactions(refreshFromNode: fromNode); + if (fromNode) _offline = !list.refreshedFromNode; + await _storeTransactions(list); + } catch (e) { + throw _fail("updateTransactions", e); + } + } + + Future _storeTransactions(GrinTxList list) async { + _slatepacks = { + for (final entry in list.transactions) + if (entry.armoredSlatepack != null) + grinTxid(entry): entry.armoredSlatepack!, + }; + + final txids = {for (final entry in list.transactions) grinTxid(entry)}; + final stored = await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .findAll(); + final storedHeights = { + for (final tx in stored) + if (txids.contains(tx.txid)) tx.txid: tx.height, + }; + + final transactions = mapGrinTransactions( + entries: list.transactions, + walletId: walletId, + ownAddress: (await getCurrentReceivingAddress())?.value, + storedHeights: storedHeights, + chainHeight: info.cachedChainHeight, + fractionDigits: cryptoCurrency.fractionDigits, + ); + await mainDB.updateOrPutTransactionV2s(transactions); + } + + @override + Future updateBalance() async { + final api = _api; + if (api == null || _exited) return; + try { + final balance = await api.getBalance( + refreshFromNode: false, + minimumConfirmations: cryptoCurrency.minConfirms, + ); + await info.updateBalance( + newBalance: grinBalanceToStack(balance, cryptoCurrency.fractionDigits), + isar: mainDB.isar, + ); + } catch (e) { + throw _fail("updateBalance", e); + } + if (_offline) throw GrinWalletException("Could not reach the Grin node."); + } + + @override + Future updateUTXOs() async => false; + + @override + Future checkSaveInitialReceivingAddress() async { + if (_api == null) return; + if (await getCurrentReceivingAddress() != null) return; + await _storeAddress(); + } + + /// Only the index 0 address receives, so it is the only one stored. + Future _storeAddress() async { + final api = _requireApi(); + final address = await api.getAddress(index: 0); + await mainDB.updateOrPutAddresses([ + Address( + walletId: walletId, + value: address.slatepackAddress, + publicKey: [], + derivationIndex: 0, + derivationPath: null, + type: AddressType.mimbleWimble, + subType: AddressSubType.receiving, + ), + ]); + } + + // ========== Sending ======================================================== + + /// Methods a Grin send can use. + List get supportedMethods => const [ + SlatepackMethod.slatepack, + SlatepackMethod.http, + ]; + + /// Slate V4 has no message. + bool get supportsOnChainNote => false; + + bool get supportsInvoices => true; + + BigInt _nano(Amount amount) { + if (amount.fractionDigits != cryptoCurrency.fractionDigits) { + throw GrinWalletException("Amount has the wrong precision."); + } + return amount.raw; + } + + Amount _amount(BigInt nanogrin) => + Amount(rawValue: nanogrin, fractionDigits: cryptoCurrency.fractionDigits); + + SlatepackMethod _methodFor(TxData txData, String address) { + final explicit = txData.slatepackMethod; + if (explicit != null) return explicit; + final kind = cryptoCurrency.addressKind(address); + return kind == GrinAddressKind.onion || kind == GrinAddressKind.http + ? SlatepackMethod.http + : SlatepackMethod.slatepack; + } + + bool get _torWanted => torFeatureEnabled && prefs.useTor; + + /// Throws unless an HTTP send to [address] is allowed now. + void _checkHttpPolicy( + String address, { + required bool clearnetAcknowledged, + required bool plaintextAcknowledged, + }) { + final kind = cryptoCurrency.addressKind(address); + final refusal = grinHttpSendRefusal( + transport: _applied?.transport ?? _resolveNetwork().transport, + torWanted: _torWanted, + kind: kind, + isPlainHttp: + kind == GrinAddressKind.http && + address.trim().toLowerCase().startsWith("http://"), + clearnetAcknowledged: clearnetAcknowledged, + plaintextAcknowledged: plaintextAcknowledged, + ); + if (refusal == null) return; + throw GrinWalletException(switch (refusal) { + GrinSendRefusal.blocked => "The Grin wallet's network is blocked.", + GrinSendRefusal.torRequired => + "Sending to this address needs Tor. Turn Tor on and try again.", + GrinSendRefusal.torDown => + "Tor is not connected. Nothing was sent or locked.", + GrinSendRefusal.clearnetNotAcknowledged => + "Sending without Tor shows your IP address to the recipient.", + GrinSendRefusal.plaintextNotAcknowledged => + "This address uses unencrypted http://.", + GrinSendRefusal.unsupportedTarget => + "This is not an address a Grin wallet can send to.", + }); + } + + @override + Future prepareSend({required TxData txData}) async { + try { + _refuseWhileScanning(); + final recipients = txData.recipients; + if (recipients == null || recipients.length != 1) { + throw GrinWalletException("A Grin send has exactly one recipient."); + } + final recipient = recipients.single; + final address = recipient.address.trim(); + final method = _methodFor(txData, address); + switch (method) { + case SlatepackMethod.relay: + throw GrinWalletException("Grin has no relay."); + case SlatepackMethod.http: + _checkHttpPolicy( + address, + clearnetAcknowledged: true, + plaintextAcknowledged: true, + ); + case SlatepackMethod.slatepack: + if (address.isNotEmpty && + cryptoCurrency.addressKind(address) != + GrinAddressKind.slatepack) { + throw GrinWalletException( + "A Slatepack can only be encrypted to a Grin address.", + ); + } + } + + final sendAll = + txData.subtractFeeFromAmount || + recipient.amount == info.cachedBalance.spendable; + final amount = _nano(recipient.amount); + if (amount <= BigInt.zero) { + throw GrinWalletException("The amount must be more than zero."); + } + + final api = await _requireNetwork(); + final estimate = await api.estimateFee( + amount: amount, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + ); + + return txData.copyWith( + recipients: [recipient.copyWith(amount: _amount(estimate.amount))], + fee: _amount(estimate.fee), + otherData: slatepackMethodOtherData(method, existing: txData.otherData), + subtractFeeFromAmount: sendAll, + ); + } catch (e) { + throw _fail("prepareSend", e); + } + } + + @override + Future confirmSend({required TxData txData}) async { + try { + _refuseWhileScanning(); + final recipient = txData.recipients!.single; + final address = recipient.address.trim(); + final method = _methodFor(txData, address); + final sendAll = txData.subtractFeeFromAmount; + final fee = txData.fee; + // A send-all was estimated with the fee taken out of the amount. + final amount = sendAll && fee != null + ? _nano(recipient.amount + fee) + : _nano(recipient.amount); + + switch (method) { + case SlatepackMethod.relay: + throw GrinWalletException("Grin has no relay."); + + case SlatepackMethod.slatepack: + final slatepack = await _initSend( + amount: amount, + recipientAddress: address.isEmpty ? null : address, + sendAll: sendAll, + ); + unawaited(refresh()); + return txData.copyWith( + txid: slatepack.slateId, + slatepack: slatepack.armoredSlatepack, + fee: _amount(slatepack.fee), + ); + + case SlatepackMethod.http: + final api = await _requireNetwork(); + _checkHttpPolicy( + address, + clearnetAcknowledged: txData.grinClearnetAcknowledged, + plaintextAcknowledged: txData.grinPlaintextAcknowledged, + ); + final result = await api.sendHttp( + GrinHttpSendArgs( + amount: amount, + recipientUrlOrAddress: address, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + ttlBlocks: slatepackTtlBlocks, + post: true, + ), + ); + unawaited(refresh()); + return txData.copyWith( + txid: result.slateId, + fee: _amount(result.fee), + ); + } + } catch (e) { + throw _fail("confirmSend", e); + } + } + + Future _initSend({ + required BigInt amount, + required String? recipientAddress, + required bool sendAll, + }) async { + _refuseWhileScanning(); + final api = await _requireNetwork(); + return await api.initSend( + GrinSendArgs( + amount: amount, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + recipientAddress: recipientAddress, + ttlBlocks: slatepackTtlBlocks, + ), + ); + } + + @override + Future estimateFeeFor(Amount amount, BigInt feeRate) async { + if (amount.raw <= BigInt.zero) return _amount(BigInt.zero); + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final estimate = await api.estimateFee( + amount: _nano(amount), + minimumConfirmations: cryptoCurrency.minConfirms, + ); + return _amount(estimate.fee); + } catch (e) { + throw _fail("estimateFee", e); + } + } + + @override + Future get fees async => FeeObject( + numberOfBlocksFast: 10, + numberOfBlocksAverage: 10, + numberOfBlocksSlow: 10, + fast: BigInt.one, + medium: BigInt.one, + slow: BigInt.one, + ); + + @override + Future updateSentCachedTxData({required TxData txData}) async => + txData; + + // ========== Slatepacks ===================================================== + + /// The address counterparties send to. + Future slatepackAddress() async { + final stored = await getCurrentReceivingAddress(); + if (stored != null) return stored.value; + try { + return (await _requireApi().getAddress()).slatepackAddress; + } catch (e) { + throw _fail("slatepackAddress", e); + } + } + + /// The index 0 address as the native wallet derives it, not the stored + /// copy. + Future getNativeReceivingAddress() async { + try { + return (await _requireApi().getAddress()).slatepackAddress; + } catch (e) { + throw _fail("getNativeReceivingAddress", e); + } + } + + /// Reads a Slatepack without changing anything. During a scan, a plain + /// one is read without the wallet so it does not wait for the batch. + Future inspectSlatepack(String armored) async { + try { + if (_scanJob != null) { + try { + return await backend.decodeSlatepackWithoutWallet( + armored, + cryptoCurrency.grinNetwork, + ); + } on GrinSlateException { + // Encrypted; only the wallet can read it. + } + } + return await _requireApi().decodeSlatepack(armored); + } catch (e) { + throw _fail("inspectSlatepack", e); + } + } + + /// Amount and fee of the stored transaction for [slateId]. + Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId) async { + final tx = await _storedTx(slateId); + if (tx == null) return null; + final fractionDigits = cryptoCurrency.fractionDigits; + final amount = tx.type == TransactionType.incoming + ? tx.getAmountReceivedInThisWallet(fractionDigits: fractionDigits) + : tx.getAmountSentFromThisWallet( + fractionDigits: fractionDigits, + subtractFee: true, + ); + return (amount: amount, fee: tx.getFee(fractionDigits: fractionDigits)); + } + + /// Starts a Slatepack send and returns the S1. Locks the inputs. + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + bool sendAll = false, + }) async { + try { + final address = recipientAddress?.trim(); + if (address != null && + address.isNotEmpty && + cryptoCurrency.addressKind(address) != GrinAddressKind.slatepack) { + throw GrinWalletException( + "A Slatepack can only be encrypted to a Grin address.", + ); + } + final result = await _initSend( + amount: _nano(amount), + recipientAddress: (address?.isEmpty ?? true) ? null : address, + sendAll: sendAll, + ); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("createSlatepack", e); + } + } + + /// Answers an S1 and returns the S2. + Future receiveSlatepack(String s1) async { + try { + final result = await _requireApi().receiveSlatepack(s1); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("receiveSlatepack", e); + } + } + + /// Finalizes a send from its S2 and broadcasts it. + Future finalizeSlatepack(String s2) async { + try { + final api = await _requireNetwork(); + final result = await api.finalizeSlatepack(s2); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("finalizeSlatepack", e); + } + } + + /// Requests a payment and returns the I1. + Future issueInvoice({ + required Amount amount, + String? payerAddress, + }) async { + try { + final result = await _requireApi().issueInvoice( + GrinInvoiceArgs(amount: _nano(amount), recipientAddress: payerAddress), + ); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("issueInvoice", e); + } + } + + /// Pays an I1 for exactly [confirmedAmount], the amount the user agreed + /// to, and returns the I2. Locks the inputs. + Future processInvoice( + String i1, { + required Amount confirmedAmount, + }) async { + try { + _refuseWhileScanning(); + final expected = _nano(confirmedAmount); + final api = await _requireNetwork(); + final decoded = await api.decodeSlatepack(i1); + if (decoded.state != GrinSlateState.i1) { + throw GrinWalletException("This Slatepack is not an invoice."); + } + if (decoded.amount != expected) { + throw GrinWalletException( + "The invoice amount does not match the amount you confirmed.", + ); + } + final result = await api.processInvoice( + i1, + GrinProcessInvoiceArgs( + minimumConfirmations: cryptoCurrency.minConfirms, + ttlBlocks: slatepackTtlBlocks, + expectedAmount: expected, + ), + ); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("processInvoice", e); + } + } + + /// Finalizes an invoice from its I2 and broadcasts it. + Future finalizeInvoice(String i2) async { + try { + final api = await _requireNetwork(); + final result = await api.finalizeInvoice(i2); + unawaited(refresh()); + return result; + } catch (e) { + throw _fail("finalizeInvoice", e); + } + } + + /// Cancels the unconfirmed transaction [slateId]. Returns "" or a message + /// to show. + Future cancelPendingTransactionAndPost(String slateId) async { + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final logIds = _logIds(await _storedTx(slateId)); + if (logIds.isEmpty) { + await api.cancelTransaction(slateId: slateId); + } else { + var cancelled = 0; + for (final id in logIds) { + try { + await api.cancelTransaction(txId: id); + cancelled++; + } on GrinTransactionException { + // A self-send's other half may already be cancelled. + if (id == logIds.last && cancelled == 0) rethrow; + } + } + } + unawaited(refresh()); + return ""; + } catch (e) { + return _fail("cancel", e).toString(); + } + } + + /// The latest Slatepack of [txid], if the wallet kept one. + Future pendingSlatepackFor(String txid) async { + final cached = _slatepacks[txid]; + if (cached != null) return cached; + try { + final list = await _requireApi().getTransactions(refreshFromNode: false); + _slatepacks = { + for (final entry in list.transactions) + if (entry.armoredSlatepack != null) + grinTxid(entry): entry.armoredSlatepack!, + }; + return _slatepacks[txid]; + } catch (e) { + throw _fail("pendingSlatepackFor", e); + } + } + + /// Broadcasts the stored finalized transaction [txid] again. + Future repost(String txid) async { + try { + final tx = await _storedTx(txid); + if (tx == null || !_otherDataFlag(tx, TxV2OdKeys.grinHasStoredTx)) { + throw GrinWalletException("No finalized transaction is stored."); + } + final api = await _requireNetwork(); + final logIds = _logIds(tx); + await api.repost( + txId: logIds.isEmpty ? null : logIds.first, + slateId: tx.slateId, + ); + unawaited(refresh()); + } catch (e) { + throw _fail("repost", e); + } + } + + /// The payment proof of [txid] as JSON. + Future exportPaymentProof(String txid) async { + try { + final tx = await _storedTx(txid); + if (tx == null || !_otherDataFlag(tx, TxV2OdKeys.grinHasPaymentProof)) { + throw GrinWalletException("This transaction has no payment proof."); + } + final logIds = _logIds(tx); + final proof = await _requireApi().exportPaymentProof( + txId: logIds.isEmpty ? null : logIds.first, + slateId: tx.slateId, + ); + return proof.toJsonString(); + } catch (e) { + throw _fail("exportPaymentProof", e); + } + } + + /// Checks a payment proof against the chain through the wallet's node. + Future verifyPaymentProof( + String proofJson, + ) async { + try { + final GrinPaymentProof proof; + try { + proof = GrinPaymentProof.fromJsonString(proofJson); + } on FormatException { + throw GrinWalletException("This is not a Grin payment proof."); + } + final api = await _requireNetwork(); + return await api.verifyPaymentProof(proof); + } catch (e) { + throw _fail("verifyPaymentProof", e); + } + } + + Future _storedTx(String txid) => mainDB.isar.transactionV2s + .where() + .txidWalletIdEqualTo(txid, walletId) + .findFirst(); + + List _logIds(TransactionV2? tx) { + final data = tx?.otherData; + if (data == null) return const []; + final ids = _decode(data)[TxV2OdKeys.grinLogIds]; + return ids is List ? ids.whereType().toList() : const []; + } + + bool _otherDataFlag(TransactionV2 tx, String key) { + final data = tx.otherData; + return data != null && _decode(data)[key] == true; + } + + Map _decode(String data) { + try { + return Map.from(jsonDecode(data) as Map); + } catch (_) { + return const {}; + } + } +} diff --git a/lib/wallets/wallet/supporting/grin/grin_errors.dart b/lib/wallets/wallet/supporting/grin/grin_errors.dart new file mode 100644 index 0000000000..888277a49d --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_errors.dart @@ -0,0 +1,92 @@ +import 'package:grin_native/grin_native.dart'; + +import '../../../../exceptions/sw_exception.dart'; +import '../../../../exceptions/wallet/insufficient_balance_exception.dart'; + +/// A Grin failure that is safe to show and log. +/// +/// It carries the library's error type, code and slate id, never the +/// library's message: that text can come from a node or a counterparty. +class GrinWalletException extends SWException { + GrinWalletException(super.message, {this.type, this.code, this.slateId}); + + /// The library exception's class name, if a library error caused this. + final String? type; + + /// The library's error code, if a library error caused this. + final int? code; + + /// The slate the failed call was working on, if the library said. + final String? slateId; + + /// A finalized transaction whose broadcast failed. Offer repost. + bool get finalizedNotBroadcast => code == 9 && slateId != null; +} + +/// The library class and code of [error] for logs, and nothing else. +String describeGrinError(Object error) => switch (error) { + GrinException() => "${error.runtimeType}(${error.code})", + GrinWalletException() => + "GrinWalletException(${error.type ?? "local"}, ${error.code})", + _ => "${error.runtimeType}", +}; + +/// [error] as an exception that can be shown and logged. +/// +/// Library errors become [GrinWalletException] or +/// [InsufficientBalanceException] with fixed text. Other errors keep only +/// their type. +Exception sanitizeGrinError(Object error) { + if (error is GrinWalletException || error is InsufficientBalanceException) { + return error as Exception; + } + if (error is SWException) return error; + if (error is! GrinException) { + return GrinWalletException("Grin wallet error (${error.runtimeType})"); + } + + final message = switch (error) { + GrinInvalidArgumentException() => "The Grin library refused an argument.", + GrinInvalidUtf8Exception() => "The Grin library refused an argument.", + GrinJsonException() => "The Grin library refused an argument.", + GrinWalletNotFoundException() => "The Grin wallet files were not found.", + GrinInvalidPasswordException() => + "The Grin wallet files did not open with the stored password.", + GrinWalletExistsException() => "A Grin wallet already exists here.", + GrinInvalidHandleException() => "The Grin wallet is closed.", + GrinLifecycleException() => "The Grin wallet could not be opened.", + GrinNodeException() => + error.slateId != null + ? "The transaction was finalized but the node did not accept it. " + "You can try to repost it." + : "Could not reach the Grin node.", + GrinInsufficientFundsException() => "Insufficient balance.", + GrinSlateException() => + "The Slatepack could not be read, or is not the one expected.", + GrinTransactionException() => "The transaction failed checks.", + GrinNotFoundException() => "No matching transaction in this wallet.", + GrinCancelledException() => "The scan was cancelled.", + GrinIoException() => "The Grin wallet files could not be read or written.", + GrinInternalPanicException() => "The Grin library failed internally.", + GrinInternalException() => "The Grin library failed internally.", + GrinWalletBusyException() => "The Grin wallet is busy. Try again later.", + GrinHttpException() => + "Could not complete the exchange with the recipient's wallet. " + "Nothing was sent or locked.", + GrinNotSupportedException() => "Not supported by this Grin library.", + GrinInvalidAddressException() => "Invalid Grin address.", + GrinInvalidMnemonicException() => "Invalid recovery phrase.", + GrinUnknownException() => "Grin wallet error.", + }; + + if (error is GrinInsufficientFundsException) { + return InsufficientBalanceException(message); + } + + return GrinWalletException( + message, + type: "${error.runtimeType}", + code: error.code, + slateId: error.slateId, + ); +} diff --git a/lib/wallets/wallet/supporting/grin/grin_node_url.dart b/lib/wallets/wallet/supporting/grin/grin_node_url.dart new file mode 100644 index 0000000000..598fbd2079 --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_node_url.dart @@ -0,0 +1,75 @@ +import 'grin_transport.dart'; + +class GrinNodeUrlException implements Exception { + GrinNodeUrlException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// The base URL the Grin library is given for a node. The library appends +/// `/v2/foreign` itself. +/// +/// The scheme comes from [host] when it has one, otherwise from [useSSL]. +/// [port] replaces any port in [host] when it is positive. Onion nodes are +/// reached over `http://` only: rustls cannot accept their self-signed +/// certificates. +String grinNodeUrl({ + required String host, + required int port, + required bool useSSL, +}) { + final trimmed = host.trim(); + if (trimmed.isEmpty) { + throw GrinNodeUrlException("The node address is empty."); + } + + final onion = isOnionHost(trimmed); + final hasScheme = trimmed.contains("://"); + final String text; + if (hasScheme) { + text = trimmed; + } else { + text = "${(useSSL && !onion) ? "https" : "http"}://$trimmed"; + } + + final Uri uri; + try { + uri = Uri.parse(text); + } on FormatException { + throw GrinNodeUrlException("The node address is not a valid URL."); + } + + final scheme = uri.scheme.toLowerCase(); + if (scheme != "http" && scheme != "https") { + throw GrinNodeUrlException("The node address must use http or https."); + } + if (uri.host.isEmpty) { + throw GrinNodeUrlException("The node address has no host."); + } + if (uri.userInfo.isNotEmpty) { + throw GrinNodeUrlException( + "Put the node API secret in its own field, not in the address.", + ); + } + if (onion && scheme == "https") { + throw GrinNodeUrlException("Onion nodes must use http://."); + } + if (uri.hasQuery || uri.hasFragment) { + throw GrinNodeUrlException("The node address must not have a query."); + } + + var path = uri.path; + while (path.endsWith("/")) { + path = path.substring(0, path.length - 1); + } + + return Uri( + scheme: scheme, + host: uri.host, + port: port > 0 ? port : (uri.hasPort ? uri.port : null), + path: path, + ).toString(); +} diff --git a/lib/wallets/wallet/supporting/grin/grin_transport.dart b/lib/wallets/wallet/supporting/grin/grin_transport.dart new file mode 100644 index 0000000000..b9558a3b30 --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_transport.dart @@ -0,0 +1,212 @@ +import 'dart:io'; + +import 'package:grin_native/grin_native.dart' show GrinAddressKind; + +import '../../../../services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import '../../../../services/tor_service.dart'; +import '../../../../utilities/tor_plain_net_option_enum.dart'; + +/// How node and HTTP traffic of a Grin wallet leaves the device. +sealed class GrinTransport { + const GrinTransport(); +} + +/// No proxy. +final class GrinDirect extends GrinTransport { + const GrinDirect(); + + @override + bool operator ==(Object other) => other is GrinDirect; + + @override + int get hashCode => (GrinDirect).hashCode; + + @override + String toString() => "GrinDirect"; +} + +/// Through the SOCKS proxy at [address] (`host:port`). +final class GrinProxy extends GrinTransport { + const GrinProxy(this.address); + + final String address; + + @override + bool operator ==(Object other) => + other is GrinProxy && other.address == address; + + @override + int get hashCode => address.hashCode; + + @override + String toString() => "GrinProxy($address)"; +} + +enum GrinBlockedReason { + torOnlyNodeTorOff, + clearnetNodeTorOn, + torDown, + invalidNode, +} + +/// No network at all. +final class GrinBlocked extends GrinTransport { + const GrinBlocked(this.reason); + + final GrinBlockedReason reason; + + @override + bool operator ==(Object other) => + other is GrinBlocked && other.reason == reason; + + @override + int get hashCode => reason.hashCode; + + @override + String toString() => "GrinBlocked(${reason.name})"; +} + +/// Tor is connecting. Node calls wait and the applied transport stays. +final class GrinHold extends GrinTransport { + const GrinHold(); + + @override + bool operator ==(Object other) => other is GrinHold; + + @override + int get hashCode => (GrinHold).hashCode; + + @override + String toString() => "GrinHold"; +} + +/// Whether [host] (with or without scheme, port and path) is an onion host. +bool isOnionHost(String host) { + var rest = host.trim().toLowerCase(); + final scheme = rest.indexOf("://"); + if (scheme >= 0) rest = rest.substring(scheme + 3); + final end = rest.indexOf(RegExp(r"[/:?#]")); + if (end >= 0) rest = rest.substring(0, end); + return rest.endsWith(".onion"); +} + +/// The SOCKS address of [tor] as `host:port`, or null when it has none. +/// The library takes IPv4 literals only. +String? grinProxyAddress(TorService tor) { + try { + final info = tor.getProxyInfo(); + final host = info.host.type == InternetAddressType.IPv4 + ? info.host.address + : "127.0.0.1"; + return "$host:${info.port}"; + } catch (_) { + return null; + } +} + +/// The transport policy for Grin node traffic. +/// +/// Read every input at the moment the transport is applied, never from the +/// event that triggered it: Tor events arrive before the preference they +/// belong to changes. [proxyAddress] is read only when a proxy is used, so +/// the port is always current; null means the proxy is not available. +GrinTransport resolveGrinTransport({ + required bool torFeature, + required bool useTor, + required TorConnectionStatus torStatus, + required bool killSwitch, + required TorPlainNetworkOption nodeNetOption, + required bool nodeIsOnion, + required String? Function() proxyAddress, +}) { + final torOnlyNode = nodeNetOption == TorPlainNetworkOption.tor || nodeIsOnion; + + if (!(torFeature && useTor)) { + return torOnlyNode + ? const GrinBlocked(GrinBlockedReason.torOnlyNodeTorOff) + : const GrinDirect(); + } + + if (nodeNetOption == TorPlainNetworkOption.clear) { + return const GrinBlocked(GrinBlockedReason.clearnetNodeTorOn); + } + + switch (torStatus) { + case TorConnectionStatus.connected: + final address = proxyAddress(); + return address == null + ? const GrinBlocked(GrinBlockedReason.torDown) + : GrinProxy(address); + + case TorConnectionStatus.connecting: + return const GrinHold(); + + case TorConnectionStatus.disconnected: + if (!killSwitch && !torOnlyNode) { + // Clearnet fallback for node calls only. HTTP sends stay refused. + return const GrinDirect(); + } + return const GrinBlocked(GrinBlockedReason.torDown); + } +} + +enum GrinSendRefusal { + /// The network is blocked for this wallet. + blocked, + + /// The target needs Tor and Tor is off. + torRequired, + + /// Tor is wanted but not connected. + torDown, + + /// A clearnet target with Tor off needs the IP disclosure accepted. + clearnetNotAcknowledged, + + /// An `http://` target needs the plaintext warning accepted. + plaintextNotAcknowledged, + + /// Not something an HTTP send can reach. + unsupportedTarget, +} + +/// Why an HTTP send to a target of [kind] must not start under [transport], +/// or null when it may. +/// +/// [torWanted] is the Tor feature and preference together. [isPlainHttp] +/// is an `http://` clearnet URL. +GrinSendRefusal? grinHttpSendRefusal({ + required GrinTransport transport, + required bool torWanted, + required GrinAddressKind? kind, + required bool isPlainHttp, + required bool clearnetAcknowledged, + required bool plaintextAcknowledged, +}) { + if (kind == null || kind == GrinAddressKind.unknown) { + return GrinSendRefusal.unsupportedTarget; + } + if (transport is GrinBlocked) return GrinSendRefusal.blocked; + if (transport is GrinHold) return GrinSendRefusal.torDown; + + final viaTor = transport is GrinProxy; + if (torWanted && !viaTor) return GrinSendRefusal.torDown; + + switch (kind) { + case GrinAddressKind.slatepack: + case GrinAddressKind.onion: + return viaTor ? null : GrinSendRefusal.torRequired; + + case GrinAddressKind.http: + if (!viaTor && !clearnetAcknowledged) { + return GrinSendRefusal.clearnetNotAcknowledged; + } + if (isPlainHttp && !plaintextAcknowledged) { + return GrinSendRefusal.plaintextNotAcknowledged; + } + return null; + + case GrinAddressKind.unknown: + return GrinSendRefusal.unsupportedTarget; + } +} diff --git a/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart new file mode 100644 index 0000000000..1160b85c06 --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart @@ -0,0 +1,205 @@ +import 'dart:convert'; + +import 'package:grin_native/grin_native.dart'; + +import '../../../../models/isar/models/blockchain_data/transaction.dart'; +import '../../../../models/isar/models/blockchain_data/v2/input_v2.dart'; +import '../../../../models/isar/models/blockchain_data/v2/output_v2.dart'; +import '../../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../../../../utilities/amount/amount.dart'; + +/// The Stack txid of a Grin log entry: the slate id, or a log id based one +/// for entries without a slate (coinbase, and outputs found by a scan). +String grinTxid(GrinTxLogEntry entry) { + final slateId = entry.slateId; + if (slateId != null) return slateId; + return entry.type == GrinTxType.confirmedCoinbase + ? "grin_cb_${entry.id}" + : "grin_log_${entry.id}"; +} + +bool _isSendType(GrinTxType type) => + type == GrinTxType.txSent || type == GrinTxType.txSentCancelled; + +bool _isReceiveType(GrinTxType type) => + type == GrinTxType.txReceived || + type == GrinTxType.txReceivedCancelled || + type == GrinTxType.confirmedCoinbase; + +/// Turns the Grin log into Stack transactions. +/// +/// Entries are grouped by txid. A self-send logs a send and a receive with +/// one slate id; they become a single row, because txid and walletId are a +/// unique index. [storedHeights] holds the heights already stored by txid, +/// which a confirmed entry keeps when the library no longer reports one. +/// [chainHeight] is used for a confirmed entry with no height at all. +List mapGrinTransactions({ + required List entries, + required String walletId, + required String? ownAddress, + required Map storedHeights, + required int chainHeight, + required int fractionDigits, +}) { + final groups = >{}; + for (final entry in entries) { + groups.putIfAbsent(grinTxid(entry), () => []).add(entry); + } + + return [ + for (final MapEntry(key: txid, value: group) in groups.entries) + _mapGroup( + txid: txid, + group: group, + walletId: walletId, + ownAddress: ownAddress, + storedHeight: storedHeights[txid], + chainHeight: chainHeight, + fractionDigits: fractionDigits, + ), + ]; +} + +TransactionV2 _mapGroup({ + required String txid, + required List group, + required String walletId, + required String? ownAddress, + required int? storedHeight, + required int chainHeight, + required int fractionDigits, +}) { + final sent = group.where((e) => _isSendType(e.type)).firstOrNull; + final received = group.where((e) => _isReceiveType(e.type)).firstOrNull; + final primary = sent ?? received ?? group.first; + final selfSend = sent != null && received != null; + + final debited = group.fold(BigInt.zero, (p, e) => p + e.amountDebited); + final credited = group.fold(BigInt.zero, (p, e) => p + e.amountCredited); + final fee = sent?.fee ?? primary.fee ?? BigInt.zero; + final counterparty = group + .map((e) => e.counterpartyAddress) + .whereType() + .firstOrNull; + + final TransactionType type; + if (selfSend) { + final toSelf = counterparty == null || counterparty == ownAddress; + type = toSelf + ? TransactionType.sentToSelf + : (credited > debited + ? TransactionType.incoming + : TransactionType.outgoing); + } else { + type = switch (primary.type) { + GrinTxType.txReceived || + GrinTxType.confirmedCoinbase || + GrinTxType.txReceivedCancelled => TransactionType.incoming, + GrinTxType.txSent || + GrinTxType.txSentCancelled => TransactionType.outgoing, + GrinTxType.txReverted => + primary.netAmount > BigInt.zero + ? TransactionType.incoming + : TransactionType.outgoing, + GrinTxType.unknown => TransactionType.unknown, + }; + } + + final isCoinbase = primary.type == GrinTxType.confirmedCoinbase; + final cancelled = primary.type.isCancelled; + final reverted = group.any((e) => e.type == GrinTxType.txReverted); + final confirmed = group.every((e) => e.confirmed) && !cancelled && !reverted; + + int? height; + if (confirmed) { + height = + group.map((e) => e.confirmedHeight).whereType().firstOrNull ?? + storedHeight ?? + (chainHeight > 0 ? chainHeight : null); + } + + final inputs = [ + if (isCoinbase) + InputV2.isarCantDoRequiredInDefaultConstructor( + scriptSigHex: null, + scriptSigAsm: null, + sequence: null, + outpoint: null, + addresses: const [], + valueStringSats: "0", + witness: null, + innerRedeemScriptAsm: null, + coinbase: "grin", + walletOwns: false, + ), + if (debited > BigInt.zero) + InputV2.isarCantDoRequiredInDefaultConstructor( + scriptSigHex: null, + scriptSigAsm: null, + sequence: null, + outpoint: null, + addresses: [?ownAddress], + valueStringSats: debited.toString(), + witness: null, + innerRedeemScriptAsm: null, + coinbase: null, + walletOwns: true, + ), + ]; + + final paid = debited - credited - fee; + final outputs = [ + if (credited > BigInt.zero) + OutputV2.isarCantDoRequiredInDefaultConstructor( + scriptPubKeyHex: "00", + valueStringSats: credited.toString(), + addresses: [?ownAddress], + walletOwns: true, + ), + if (type == TransactionType.outgoing && paid > BigInt.zero) + OutputV2.isarCantDoRequiredInDefaultConstructor( + scriptPubKeyHex: "00", + valueStringSats: paid.toString(), + addresses: [?counterparty], + walletOwns: false, + ), + ]; + + final kernelExcess = group + .map((e) => e.kernelExcess) + .whereType() + .firstOrNull; + + final otherData = { + TxV2OdKeys.isGrinTransaction: true, + TxV2OdKeys.slateId: primary.slateId, + TxV2OdKeys.isCancelled: cancelled, + TxV2OdKeys.isReverted: reverted, + TxV2OdKeys.grinLogIds: [for (final e in group) e.id], + TxV2OdKeys.grinSlateState: primary.slateState?.wireName, + TxV2OdKeys.grinHasStoredTx: group.any((e) => e.hasStoredTx), + TxV2OdKeys.grinKernelExcess: kernelExcess, + TxV2OdKeys.grinTtlCutoff: primary.ttlCutoffHeight, + TxV2OdKeys.grinHasPaymentProof: group.any((e) => e.paymentProof != null), + TxV2OdKeys.counterpartyAddress: counterparty, + TxV2OdKeys.overrideFee: Amount( + rawValue: fee, + fractionDigits: fractionDigits, + ).toJsonString(), + }; + + return TransactionV2( + walletId: walletId, + blockHash: null, + hash: kernelExcess ?? txid, + txid: txid, + timestamp: primary.creationTime.millisecondsSinceEpoch ~/ 1000, + height: height, + inputs: List.unmodifiable(inputs), + outputs: List.unmodifiable(outputs), + version: 0, + type: type, + subType: TransactionSubType.none, + otherData: jsonEncode(otherData), + ); +} diff --git a/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart b/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart new file mode 100644 index 0000000000..f00885a2de --- /dev/null +++ b/lib/wallets/wallet/supporting/grin_wallet_info_extension.dart @@ -0,0 +1,58 @@ +import 'dart:convert'; + +import 'package:isar_community/isar.dart'; + +import '../../isar/models/wallet_info.dart'; + +extension GrinWalletInfoExtension on WalletInfo { + GrinWalletData? get grinData { + final data = otherData[WalletInfoKeys.grinData]; + if (data is! String) return null; + try { + return GrinWalletData.fromMap( + Map.from(jsonDecode(data) as Map), + ); + } catch (_) { + return null; + } + } + + Future updateGrinData({ + required GrinWalletData grinData, + required Isar isar, + }) async { + await updateOtherData( + newEntries: {WalletInfoKeys.grinData: jsonEncode(grinData.toMap())}, + isar: isar, + ); + } +} + +/// Grin state Stack keeps beside the native wallet. +class GrinWalletData { + const GrinWalletData({required this.creationHeight, this.pendingScanFrom}); + + /// The height the wallet was created or restored from. + final int creationHeight; + + /// Where an unfinished scan resumes, or null when none is pending. + final int? pendingScanFrom; + + Map toMap() => { + "creationHeight": creationHeight, + "pendingScanFrom": pendingScanFrom, + }; + + factory GrinWalletData.fromMap(Map map) => GrinWalletData( + creationHeight: map["creationHeight"] as int, + pendingScanFrom: map["pendingScanFrom"] as int?, + ); + + GrinWalletData withPendingScanFrom(int? height) => + GrinWalletData(creationHeight: creationHeight, pendingScanFrom: height); + + @override + String toString() => + "GrinWalletData(creationHeight: $creationHeight, " + "pendingScanFrom: $pendingScanFrom)"; +} diff --git a/lib/wallets/wallet/wallet.dart b/lib/wallets/wallet/wallet.dart index bb6848c568..6dafcd78e1 100644 --- a/lib/wallets/wallet/wallet.dart +++ b/lib/wallets/wallet/wallet.dart @@ -38,6 +38,7 @@ import 'impl/epiccash_wallet.dart'; import 'impl/ethereum_wallet.dart'; import 'impl/fact0rn_wallet.dart'; import 'impl/firo_wallet.dart'; +import 'impl/grin_wallet.dart'; import 'impl/litecoin_wallet.dart'; import 'impl/mimblewimblecoin_wallet.dart'; import 'impl/monero_wallet.dart'; @@ -394,6 +395,9 @@ abstract class Wallet { case const (Firo): return FiroWallet(net); + case const (Grin): + return GrinWallet(net); + case const (Litecoin): return LitecoinWallet(net); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 795140ade7..9f8c7cd59a 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -11,6 +11,7 @@ import '../../../utilities/enums/slatepack_method.dart'; import '../../../utilities/slatepack_terms.dart'; import '../../../utilities/logger.dart'; import '../../crypto_currency/crypto_currency.dart'; +import '../../models/tx_data.dart'; import '../wallet.dart'; /// Slatepack exchange shared by the Mimblewimble coins. The slatepack @@ -273,6 +274,40 @@ mixin SlatepackInterface on Wallet { Future cancelPendingTransactionAndPost(String slateId); } +/// Key in [TxData.otherData] that records the selected slatepack transport. +const kSlatepackMethodKey = "transactionMethod"; + +String slatepackMethodOtherData(SlatepackMethod method, {String? existing}) { + final data = {}; + if (existing != null) { + try { + final decoded = jsonDecode(existing); + if (decoded is Map) { + data.addAll(decoded.cast()); + } + } catch (_) {} + } + data[kSlatepackMethodKey] = method.name; + return jsonEncode(data); +} + +extension SlatepackTxData on TxData { + SlatepackMethod? get slatepackMethod { + if (otherData == null) return null; + try { + final decoded = jsonDecode(otherData!); + if (decoded is Map) { + return SlatepackMethod.fromName( + decoded[kSlatepackMethodKey] as String?, + ); + } + } catch (_) {} + return null; + } + + bool get isSlatepackSend => slatepackMethod == SlatepackMethod.slatepack; +} + /// Reads the small durable record written when a wallet creates an S1. @visibleForTesting ({Amount amount, Amount fee, bool isSend, bool isCancelled})? diff --git a/lib/wl_gen/interfaces/libgrin_interface.dart b/lib/wl_gen/interfaces/libgrin_interface.dart new file mode 100644 index 0000000000..513a8f7f47 --- /dev/null +++ b/lib/wl_gen/interfaces/libgrin_interface.dart @@ -0,0 +1,11 @@ +import 'package:grin_native/grin_native.dart'; + +export '../generated/libgrin_interface_impl.dart'; + +/// The only native boundary for Grin. Everything else uses package:grin, +/// which every app config depends on. +abstract class LibGrinInterface { + const LibGrinInterface(); + + GrinWalletBackend get backend; +} diff --git a/pubspec.lock b/pubspec.lock index e4b66315c0..f2b13b6717 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1309,6 +1309,15 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" + grin_native: + dependency: "direct main" + description: + path: "packages/grin_native" + ref: "5b56ce4f90b50be67154797cbfc1a401bd9ab778" + resolved-ref: "5b56ce4f90b50be67154797cbfc1a401bd9ab778" + url: "https://github.com/cypherstack/grin_native.git" + source: git + version: "0.1.0" grpc: dependency: transitive description: diff --git a/scripts/app_config/configure_stack_wallet.sh b/scripts/app_config/configure_stack_wallet.sh index 6f41d27b7c..f1299d773b 100755 --- a/scripts/app_config/configure_stack_wallet.sh +++ b/scripts/app_config/configure_stack_wallet.sh @@ -31,7 +31,8 @@ dart "${APP_PROJECT_ROOT_DIR}/tool/process_pubspec_deps.dart" \ EPIC \ FIRO \ XEL \ - FROST + FROST \ + GRIN dart "${APP_PROJECT_ROOT_DIR}/tool/gen_interfaces.dart" \ "${APP_PROJECT_ROOT_DIR}/tool/wl_templates" \ @@ -45,7 +46,8 @@ dart "${APP_PROJECT_ROOT_DIR}/tool/gen_interfaces.dart" \ EPIC \ FIRO \ XEL \ - FROST + FROST \ + GRIN MWEBD_EXE_SHA256="" @@ -109,6 +111,7 @@ final List _supportedCoins = List.unmodifiable([ Ethereum(CryptoCurrencyNetwork.main), Fact0rn(CryptoCurrencyNetwork.main), Firo(CryptoCurrencyNetwork.main), + Grin(CryptoCurrencyNetwork.main), Litecoin(CryptoCurrencyNetwork.main), Mimblewimblecoin(CryptoCurrencyNetwork.main), Nano(CryptoCurrencyNetwork.main), diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index 3761771c1e..d279be0a96 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -64,6 +64,14 @@ dependencies: # ref: 5722fb3ba05c8f52e8e0255c485ae5ea52e9a694 # %%END_ENABLE_MWC%% +# grin_native compiles the grin-ffi Rust library in its build hook and +# re-exports the shared Grin API. + grin_native: + git: + url: https://github.com/cypherstack/grin_native.git + path: packages/grin_native + ref: 5b56ce4f90b50be67154797cbfc1a401bd9ab778 + # %%ENABLE_TOR%% # tor_ffi_plugin: # git: diff --git a/scripts/ensure_test_app_config.sh b/scripts/ensure_test_app_config.sh index 696c853b4e..829b2d79d4 100755 --- a/scripts/ensure_test_app_config.sh +++ b/scripts/ensure_test_app_config.sh @@ -54,6 +54,7 @@ final List _supportedCoins = List.unmodifiable([ Ethereum(CryptoCurrencyNetwork.main), Fact0rn(CryptoCurrencyNetwork.main), Firo(CryptoCurrencyNetwork.main), + Grin(CryptoCurrencyNetwork.main), Litecoin(CryptoCurrencyNetwork.main), Mimblewimblecoin(CryptoCurrencyNetwork.main), Nano(CryptoCurrencyNetwork.main), diff --git a/scripts/tests/wallet_creation_runner_test.dart b/scripts/tests/wallet_creation_runner_test.dart index 664254582a..ffab5efe46 100644 --- a/scripts/tests/wallet_creation_runner_test.dart +++ b/scripts/tests/wallet_creation_runner_test.dart @@ -69,11 +69,11 @@ void main() { .map((line) => jsonDecode(line) as Map) .toList(); - test('the shared matrix covers the 24 base wallets and excludes FROST', () { - expect(defaultWordCounts, hasLength(24)); + test('the shared matrix covers the 25 base wallets and excludes FROST', () { + expect(defaultWordCounts, hasLength(25)); expect( defaultWordCounts.keys, - containsAll(['eCash', 'epicCash', 'monero', 'solana']), + containsAll(['eCash', 'epicCash', 'grin', 'monero', 'solana']), ); expect(defaultWordCounts, isNot(contains('bitcoinFrost'))); }); @@ -269,7 +269,7 @@ void main() { final suite = runner(omitCoin: 'xelis'); expect(await suite.run(options(['--device', 'linux', '--all-coins'])), 1); expect(suite.results.first['failure'], 'incomplete_results'); - expect(suite.results.first['completed_coins'], hasLength(23)); + expect(suite.results.first['completed_coins'], hasLength(24)); expect(await events(), hasLength(1)); }, ); diff --git a/test/support/memory_secrets.dart b/test/support/memory_secrets.dart new file mode 100644 index 0000000000..86b43ea6ab --- /dev/null +++ b/test/support/memory_secrets.dart @@ -0,0 +1,42 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; + +/// Secure storage in a map, with failure hooks. +class MemorySecrets extends Fake implements SecureStorageInterface { + /// The Xelis tests expect their table preference to be set. + MemorySecrets([Map? initial]) + : values = initial ?? {'xelis_wants_full_tables': 'false'}; + + final Map values; + final List writes = []; + final List deletes = []; + String? failingKey; + String? failingDeleteKey; + Future Function(String)? beforeDelete; + @override + dynamic noSuchMethod(Invocation invocation) { + final key = invocation.namedArguments[#key] as String; + switch (invocation.memberName) { + case #delete: + return () async { + await beforeDelete?.call(key); + if (key == failingDeleteKey) { + throw StateError('fixture delete failure'); + } + deletes.add(key); + values.remove(key); + }(); + case #read: + return Future.value(values[key]); + case #write: + if (key == failingKey) { + return Future.error(StateError('fixture write failure')); + } + writes.add(key); + values[key] = invocation.namedArguments[#value] as String; + return Future.value(); + default: + return super.noSuchMethod(invocation); + } + } +} diff --git a/test/utilities/native_library_check_test.dart b/test/utilities/native_library_check_test.dart index 7a8d0ad40c..8d2cb648a4 100644 --- a/test/utilities/native_library_check_test.dart +++ b/test/utilities/native_library_check_test.dart @@ -140,6 +140,16 @@ void main() { expect(failures.first.result.path, _path); }); + test("a Grin library that is missing is reported for Grin wallets", () { + final failures = _startup({"grin_ffi.dll"}); + expect(failures.map((f) => f.displayName), ["Grin wallets"]); + expect(failures.single.result.problem, NativeLibraryProblem.missing); + expect( + failures.single.result.path, + r"C:\Program Files\Stack Wallet\grin_ffi.dll", + ); + }); + test("failures are handed over once", () { _startup({_dll}); expect(takeNativeLibraryFailures(), isEmpty); @@ -187,7 +197,8 @@ void main() { os: "windows", executable: _exe, open: (name) { - if (name != "salvium_libwallet2_api_c.dll") { + if (name != "salvium_libwallet2_api_c.dll" && + name != "grin_ffi.dll") { throw ArgumentError(_notFound); } }, diff --git a/test/wallets/grin/grin_coin_test.dart b/test/wallets/grin/grin_coin_test.dart new file mode 100644 index 0000000000..2cfda54acd --- /dev/null +++ b/test/wallets/grin/grin_coin_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + final backend = FakeGrinBackend(); + final main = Grin(CryptoCurrencyNetwork.main, addressBackend: backend); + final test_ = Grin(CryptoCurrencyNetwork.test, addressBackend: backend); + + test('fields', () { + expect(main.identifier, 'grin'); + expect(test_.identifier, 'grinTestNet'); + expect(main.mainNetId, 'grin'); + expect(test_.mainNetId, 'grin'); + expect(main.ticker, 'GRIN'); + expect(test_.ticker, 'tGRIN'); + expect(main.prettyName, 'Grin'); + expect(main.uriScheme, 'grin'); + expect(main.minConfirms, 10); + expect(main.minCoinbaseConfirms, 1440); + expect(main.fractionDigits, 9); + expect(main.satsPerCoin, BigInt.from(1000000000)); + expect(main.defaultSeedPhraseLength, 24); + expect(main.possibleMnemonicLengths, [24, 12]); + expect(main.hasMnemonicPassphraseSupport, isFalse); + expect(main.hasBuySupport, isFalse); + expect(main.torSupport, isTrue); + expect(main.defaultAddressType, AddressType.mimbleWimble); + expect(main.grinNetwork, GrinNetwork.mainnet); + expect(test_.grinNetwork, GrinNetwork.testnet); + expect(() => main.defaultDerivePathType, throwsUnsupportedError); + expect(() => main.defaultBlockExplorer('x'), throwsUnsupportedError); + expect(() => Grin(CryptoCurrencyNetwork.stage), throwsException); + }); + + test('default nodes, including testnet, never throw', () { + final m = main.defaultNode(isPrimary: false); + expect(m.host, 'https://grinnode.live'); + expect(m.port, 3413); + expect(m.useSSL, isTrue); + expect(m.torEnabled && m.clearnetEnabled, isTrue); + expect(m.isPrimary, isFalse, reason: 'isPrimary is passed through'); + expect(m.nodeApiSecret, isNull); + expect(main.defaultNode(isPrimary: true).isPrimary, isTrue); + + final t = test_.defaultNode(isPrimary: true); + expect(t.host, 'http://127.0.0.1'); + expect(t.port, 13413); + expect(t.useSSL, isFalse); + expect(t.coinName, 'grinTestNet'); + }); + + test('validateAddress uses the backend and rejects the other network', () { + expect(main.validateAddress('grin1abc'), isTrue); + expect(main.validateAddress('tgrin1abc'), isFalse); + expect(test_.validateAddress('tgrin1abc'), isTrue); + expect(main.validateAddress('http://x.onion'), isTrue); + expect(main.validateAddress('https://wallet.example'), isTrue); + expect(main.validateAddress('nonsense'), isFalse); + expect(main.addressKind('grin1abc'), GrinAddressKind.slatepack); + expect(main.addressKind('nonsense'), isNull); + expect(main.getAddressType('grin1abc'), AddressType.mimbleWimble); + expect(main.getAddressType('nonsense'), isNull); + }); + + test('validateAddress is false when the native library is missing', () { + final throwing = Grin( + CryptoCurrencyNetwork.main, + addressBackend: _ThrowingBackend(), + ); + expect(throwing.validateAddress('grin1abc'), isFalse); + }); + + test('isSlatepack and heightFromDate', () { + expect(main.isSlatepack(' BEGINSLATEPACK. abc ENDSLATEPACK. '), isTrue); + expect(main.isSlatepack('BEGINSLATEPACK. abc'), isFalse); + expect( + main.heightFromDate( + DateTime.fromMillisecondsSinceEpoch(1547568086 * 1000), + ), + 0, + ); + expect(main.heightFromDate(DateTime.utc(2000)), 0); + final day = main.heightFromDate( + DateTime.fromMillisecondsSinceEpoch((1547568086 + 86400) * 1000), + ); + expect(day, 86400 ~/ 61); + expect( + test_.heightFromDate( + DateTime.fromMillisecondsSinceEpoch((1546030084 + 610) * 1000), + ), + 10, + ); + }); +} + +class _ThrowingBackend extends FakeGrinBackend { + @override + GrinAddressValidation validateAddressSync( + String address, + GrinNetwork network, + ) => throw StateError('GRIN not enabled'); +} diff --git a/test/wallets/grin/grin_errors_test.dart b/test/wallets/grin/grin_errors_test.dart new file mode 100644 index 0000000000..316d9998d6 --- /dev/null +++ b/test/wallets/grin/grin_errors_test.dart @@ -0,0 +1,172 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/exceptions/wallet/insufficient_balance_exception.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; + +import '../support/grin_fakes.dart'; + +/// Runs [body] and returns everything printed, which is where Logging goes +/// in tests. +Future captureLogs(Future Function() body) async { + final out = StringBuffer(); + await runZoned( + body, + zoneSpecification: ZoneSpecification( + print: (self, parent, zone, line) => out.writeln(line), + ), + ); + return out.toString(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('sanitizeGrinError', () { + test('no library message in any user string', () { + for (var code = 1; code <= 23; code++) { + final error = grinError( + code, + details: {'slate_id': 'slate-x', 'wallet_dir': '/secret/dir'}, + ); + final safe = sanitizeGrinError(error); + expect(safe.toString(), isNot(contains(remoteText)), reason: '$code'); + expect(safe.toString(), isNot(contains('/secret/dir'))); + expect(describeGrinError(error), isNot(contains(remoteText))); + if (code == 10) { + expect(safe, isA()); + } else { + final wallet = safe as GrinWalletException; + expect(wallet.code, code); + expect(wallet.slateId, 'slate-x'); + expect(wallet.type, error.runtimeType.toString()); + } + } + }); + + test('a node error with a slate id means finalized, not broadcast', () { + final safe = sanitizeGrinError( + grinError(9, details: {'slate_id': 's'}), + ) as GrinWalletException; + expect(safe.finalizedNotBroadcast, isTrue); + expect( + (sanitizeGrinError( + grinError(9), + ) as GrinWalletException).finalizedNotBroadcast, + isFalse, + ); + }); + + test('other errors keep only their type', () { + final safe = sanitizeGrinError(const FormatException(remoteText)); + expect(safe.toString(), isNot(contains(remoteText))); + expect(safe.toString(), contains('FormatException')); + }); + }); + + group('wallet calls', () { + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + test('failures surface and log without remote text, slatepacks, the ' + 'mnemonic or the password', () async { + final shown = []; + final logs = await captureLogs(() async { + await h.wallet.init(); + final api = h.backend.api; + final password = h.backend.creates.single.password; + + api.sendError = grinError(19); + api.estimateError = null; + try { + await h.wallet.confirmSend( + txData: TxData( + recipients: [ + TxRecipient( + address: 'grin1friend', + amount: Amount(rawValue: BigInt.from(5), fractionDigits: 9), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + ), + ); + } catch (e) { + shown.add('$e'); + } + + h.backend.nodeError = grinError(9); + try { + await h.wallet.updateChainHeight(); + } catch (e) { + shown.add('$e'); + } + + api.decoded = null; + try { + await h.wallet.inspectSlatepack( + 'BEGINSLATEPACK. secret-slate ENDSLATEPACK.', + ); + } catch (e) { + shown.add('$e'); + } + + shown.add( + await h.wallet.cancelPendingTransactionAndPost('missing-slate'), + ); + + final s1 = await h.wallet.receiveSlatepack( + 'BEGINSLATEPACK. incoming ENDSLATEPACK.', + ); + expect(s1.state, GrinSlateState.s2); + + expect(password, isNotEmpty); + shown.add(password); + }); + + final password = shown.removeLast(); + expect(shown, hasLength(4)); + for (final text in [...shown, logs]) { + expect(text, isNot(contains(remoteText))); + expect(text, isNot(contains('SLATEPACK'))); + expect(text, isNot(contains('abandon'))); + expect(text, isNot(contains(password))); + expect(text, isNot(contains('secret-slate'))); + } + }); + + test('logs never print a node API secret', () async { + final logs = await captureLogs(() async { + h.wallet.node = grinNode(secret: 'node-api-secret'); + await h.wallet.init(); + h.backend.nodeError = grinError(9); + try { + await h.wallet.updateChainHeight(); + } catch (_) {} + await h.wallet.updateNode(); + }); + expect(logs, isNot(contains('node-api-secret'))); + }); + }); +} diff --git a/test/wallets/grin/grin_invoice_test.dart b/test/wallets/grin/grin_invoice_test.dart new file mode 100644 index 0000000000..4d45f3648f --- /dev/null +++ b/test/wallets/grin/grin_invoice_test.dart @@ -0,0 +1,90 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + await h.wallet.init(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Amount grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + + test('an amount mismatch never reaches processInvoice', () async { + h.backend.api.decoded = slateInfoOf(GrinSlateState.i1, amount: 2000); + await expectLater( + h.wallet.processInvoice('i1', confirmedAmount: grin(1000)), + throwsA(isA()), + ); + expect(h.backend.api.calls, isNot(contains('processInvoice'))); + }); + + test('a slate that is not an I1 never reaches processInvoice', () async { + for (final state in [GrinSlateState.s1, GrinSlateState.i2]) { + h.backend.api.decoded = slateInfoOf(state, amount: 1000); + await expectLater( + h.wallet.processInvoice('x', confirmedAmount: grin(1000)), + throwsA(isA()), + ); + } + expect(h.backend.api.calls, isNot(contains('processInvoice'))); + }); + + test('an unreadable invoice never reaches processInvoice', () async { + h.backend.api.decoded = null; + await expectLater( + h.wallet.processInvoice('garbage', confirmedAmount: grin(1000)), + throwsA(isA()), + ); + expect(h.backend.api.calls, isNot(contains('processInvoice'))); + }); + + test( + 'a match pays with the expected amount, TTL and confirmations', + () async { + h.backend.api.decoded = slateInfoOf(GrinSlateState.i1, amount: 1000); + final i2 = await h.wallet.processInvoice( + 'i1', + confirmedAmount: grin(1000), + ); + expect(i2.state, GrinSlateState.i2); + final args = h.backend.api.invoicePayments.single; + expect(args.expectedAmount, BigInt.from(1000)); + expect(args.ttlBlocks, GrinWallet.slatepackTtlBlocks); + expect(args.minimumConfirmations, 10); + }, + ); + + test('issuing and finalizing an invoice', () async { + final i1 = await h.wallet.issueInvoice( + amount: grin(1000), + payerAddress: 'grin1payer', + ); + expect(i1.state, GrinSlateState.i1); + final done = await h.wallet.finalizeInvoice('i2'); + expect(done.posted, isTrue); + }); +} diff --git a/test/wallets/grin/grin_lifecycle_test.dart b/test/wallets/grin/grin_lifecycle_test.dart new file mode 100644 index 0000000000..e0bfe2c957 --- /dev/null +++ b/test/wallets/grin/grin_lifecycle_test.dart @@ -0,0 +1,317 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:path/path.dart' as p; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin_wallet_info_extension.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + String passwordKey() => GrinWallet.passwordKey(h.walletId); + + test('a new wallet writes its password before create and starts at the ' + 'tip', () async { + String? storedAtCreate; + h.backend.onCreate = (_) => + storedAtCreate = h.secrets.values[passwordKey()]; + + await h.wallet.init(); + + final create = h.backend.creates.single; + expect(storedAtCreate, isNotNull); + expect(create.password, storedAtCreate); + expect(create.isNewWallet, isTrue); + expect(create.mnemonic, testMnemonic); + expect(h.backend.calls, ['create']); + expect(h.backend.api.calls, isNot(contains(startsWith('scan')))); + + final data = h.wallet.info.grinData!; + expect(data.pendingScanFrom, isNull); + expect(h.wallet.info.restoreHeight, data.creationHeight); + expect(data.creationHeight, greaterThan(3900000)); + + final address = await h.wallet.getCurrentReceivingAddress(); + expect(address!.value, 'grin1ownaddress'); + expect(address.type, AddressType.mimbleWimble); + expect(address.derivationIndex, 0); + }); + + test('the wallet directory is absolute although the data root is ' + 'relative', () async { + await h.wallet.init(); + final dir = h.backend.creates.single.config.walletDir; + expect(p.isAbsolute(dir), isTrue); + expect(p.basename(dir), h.walletId); + expect(p.basename(p.dirname(dir)), 'grin'); + expect(p.equals(p.dirname(p.dirname(dir)), dataRoot.path), isTrue); + if (Platform.isLinux || Platform.isMacOS) { + final mode = (await Directory(dir).stat()).mode & 0x1ff; + expect(mode, 0x1c0, reason: 'owner only'); + final parent = (await Directory(p.dirname(dir)).stat()).mode & 0x1ff; + expect(parent, 0x1c0); + } + }); + + test('an existing wallet is opened, not created', () async { + await h.wallet.init(); + await h.wallet.exit(); + final reopened = h.newWallet(); + await reopened.init(); + expect(h.backend.calls, ['create', 'open']); + expect( + h.backend.opens.single.walletDir, + h.backend.creates.single.config.walletDir, + ); + await reopened.exit(); + }); + + test('init is idempotent and coalesces', () async { + await Future.wait([h.wallet.init(), h.wallet.init()]); + await h.wallet.init(); + expect(h.backend.calls, ['create']); + }); + + test( + 'missing files of an existing wallet are not silently replaced', + () async { + await h.wallet.init(); + await h.wallet.exit(); + h.backend.wallets.clear(); + await expectLater( + h.newWallet().init(), + throwsA(isA()), + ); + expect(h.backend.calls, ['create', 'open']); + }, + ); + + test('a restore records the scan it owes before the wallet exists, and ' + 'the next start finishes an interrupted one', () async { + final r = await GrinHarness.create(restoreHeight: 1000); + addTearDown(r.dispose); + int? pendingAtCreate; + r.backend.onCreate = (_) => + pendingAtCreate = r.wallet.info.grinData?.pendingScanFrom; + r.backend.createError = grinError(15); + + await r.wallet.init(isRestore: true); + await expectLater(r.wallet.recover(isRescan: false), throwsException); + expect(pendingAtCreate, 1000); + expect(r.wallet.info.grinData!.pendingScanFrom, 1000); + expect(r.backend.wallets, isEmpty); + expect(r.wallet.isOpen, isFalse); + + // The app starts again: the wallet is made from the phrase, not as a + // new wallet, and its first refresh scans from the restore height. + r.backend.scanBlocks = true; + final next = r.newWallet(); + addTearDown(next.exit); + await next.init(); + expect(r.backend.calls, ['create', 'open', 'create']); + expect(r.backend.creates.last.isNewWallet, isFalse); + expect(r.backend.creates.last.mnemonic, testMnemonic); + expect(next.info.grinData!.pendingScanFrom, 1000); + expect(r.backend.api.calls, isNot(contains(startsWith('scan')))); + + await next.refresh(); + await eventually(() => r.backend.api.calls.contains('scan:1000:false')); + r.backend.api.finishScan(); + await eventually(() => next.info.grinData!.pendingScanFrom == null); + }); + + test('a rescan of a wallet whose files are gone rebuilds it, drops the ' + 'stored history and scans from the restore height', () async { + final r = await GrinHarness.create(restoreHeight: 1000); + addTearDown(r.dispose); + await r.wallet.init(isRestore: true); + await r.wallet.recover(isRescan: false); + await eventually(() => r.wallet.info.grinData!.pendingScanFrom == null); + r.backend.api.transactions = GrinTxList( + refreshedFromNode: true, + transactions: [entryOf(id: 7, slateId: 'old-slate', debited: 5)], + ); + await r.wallet.updateTransactions(); + expect(await isar.transactionV2s.count(), 1); + await r.wallet.exit(); + r.backend.wallets.clear(); + + r.backend.scanBlocks = true; + final next = r.newWallet(); + addTearDown(next.exit); + await next.recover(isRescan: true); + expect(r.backend.calls, ['create', 'open', 'create']); + expect(await isar.transactionV2s.count(), 0); + expect(next.info.grinData!.pendingScanFrom, 1000); + await eventually(() => r.backend.api.calls.contains('scan:1000:false')); + r.backend.api.finishScan(); + await eventually(() => next.info.grinData!.pendingScanFrom == null); + }); + + test('a rescan that cannot open the wallet is still owed', () async { + final r = await GrinHarness.create(restoreHeight: 1000); + addTearDown(r.dispose); + await r.wallet.init(isRestore: true); + await r.wallet.recover(isRescan: false); + await eventually(() => r.wallet.info.grinData!.pendingScanFrom == null); + await r.wallet.exit(); + r.backend.wallets.clear(); + r.backend.createError = grinError(15); + + final next = r.newWallet(); + addTearDown(next.exit); + await expectLater(next.recover(isRescan: true), throwsException); + expect(next.info.grinData!.pendingScanFrom, 1000); + }); + + test('data left by an interrupted create is cleared once for a new ' + 'wallet', () async { + h.backend.createError = grinError( + 6, + details: {'reason': 'leftover_wallet_data'}, + ); + await h.wallet.init(); + expect(h.backend.calls, ['create', 'delete', 'create']); + expect(h.backend.creates.last.isNewWallet, isTrue); + expect(h.wallet.isOpen, isTrue); + }); + + test('an existing wallet in the way of a new one is not deleted', () async { + h.backend.createError = grinError(6); + await expectLater(h.wallet.init(), throwsA(isA())); + expect(h.backend.calls, ['create']); + }); + + test('a close that fails is tried once more', () async { + await h.wallet.init(); + final api = h.backend.api; + api.closeError = grinError(15); + await h.wallet.exit(); + expect(api.calls.where((c) => c == 'close'), hasLength(2)); + expect(api.calls.last, 'closed'); + }); + + test('init with isRestore opens nothing', () async { + await h.wallet.init(isRestore: true); + expect(h.backend.calls, isEmpty); + expect(h.wallet.isOpen, isFalse); + }); + + test('exit awaits close, and init after exit opens again', () async { + await h.wallet.init(); + final api = h.backend.api; + final gate = api.closeGate = Completer(); + var exited = false; + final exiting = h.wallet.exit().then((_) => exited = true); + await pumpEventQueue(); + expect(api.calls, contains('close')); + expect(exited, isFalse); + gate.complete(); + await exiting; + expect(api.calls.last, 'closed'); + expect(h.wallet.isOpen, isFalse); + + await h.wallet.refresh(); + expect(h.backend.calls, ['create'], reason: 'refresh never reopens'); + + await h.wallet.init(); + expect(h.backend.calls, ['create', 'open']); + }); + + test('a second live instance is refused', () async { + await h.wallet.init(); + await expectLater( + h.newWallet().init(), + throwsA(isA()), + ); + }); + + test('delete closes the owner, removes the files, the empty directory and ' + 'then the password', () async { + await h.wallet.init(); + final api = h.backend.api; + final dir = h.backend.creates.single.config.walletDir; + final order = []; + h.secrets.beforeDelete = (key) async { + order.add('secret:$key'); + expect(await Directory(dir).exists(), isFalse); + }; + + final deleted = await GrinWallet.deleteWalletFiles( + walletId: h.walletId, + secureStore: h.secrets, + ); + + expect(deleted, isTrue); + expect(api.calls, containsAllInOrder(['cancelScan', 'close', 'closed'])); + expect(h.backend.deletes, [dir]); + expect(order, ['secret:${passwordKey()}']); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + }); + + test('a busy delete is reported, keeps the password and retries', () async { + await h.wallet.init(); + h.backend.deleteError = grinError(18); + final deleted = await GrinWallet.deleteWalletFiles( + walletId: h.walletId, + secureStore: h.secrets, + ); + expect(deleted, isFalse); + expect(h.secrets.values.containsKey(passwordKey()), isTrue); + + h.backend.deleteError = null; + final remaining = await GrinWallet.retryDeferredDeletes( + walletIds: [h.walletId, 'never-a-grin-wallet'], + secureStore: h.secrets, + backend: h.backend, + ); + expect(remaining, isEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + }); + + test('a restore being cancelled deletes the unregistered instance', () async { + final restore = h.wallet; + h.backend.scanBlocks = true; + await restore.init(isRestore: true); + await restore.recover(isRescan: false); + await pumpEventQueue(); + final api = h.backend.api; + api.cancelScannedHeight = 1500; + expect(api.scanRunning, isTrue); + + final deleted = await GrinWallet.deleteWalletFiles( + walletId: h.walletId, + secureStore: h.secrets, + ); + expect(deleted, isTrue); + expect(api.calls, containsAllInOrder(['cancelScan', 'close'])); + expect(restore.info.grinData!.pendingScanFrom, 1501); + expect(h.backend.wallets, isEmpty); + expect(restore.isOpen, isFalse); + }); +} diff --git a/test/wallets/grin/grin_node_url_test.dart b/test/wallets/grin/grin_node_url_test.dart new file mode 100644 index 0000000000..7fe4520612 --- /dev/null +++ b/test/wallets/grin/grin_node_url_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_node_url.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_transport.dart'; + +void main() { + String url(String host, {int port = 3413, bool useSSL = true}) => + grinNodeUrl(host: host, port: port, useSSL: useSSL); + + test('the scheme comes from the host, else from useSSL', () { + expect(url('https://grinnode.live'), 'https://grinnode.live:3413'); + expect(url('http://grinnode.live'), 'http://grinnode.live:3413'); + expect(url('grinnode.live'), 'https://grinnode.live:3413'); + expect(url('grinnode.live', useSSL: false), 'http://grinnode.live:3413'); + }); + + test('the port field replaces a port in the host', () { + expect( + url('https://node.example:443', port: 3413), + 'https://node.example:3413', + ); + expect(url('https://node.example:443', port: 0), 'https://node.example'); + expect( + url('http://127.0.0.1', port: 13413, useSSL: false), + 'http://127.0.0.1:13413', + ); + }); + + test('trailing slashes go, a path stays', () { + expect(url('https://node.example/'), 'https://node.example:3413'); + expect( + url('https://node.example/grin//'), + 'https://node.example:3413/grin', + ); + }); + + test('onion nodes use http only', () { + const onion = + 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz234567.onion'; + expect(url(onion), 'http://$onion:3413'); + expect(url('http://$onion'), 'http://$onion:3413'); + expect(() => url('https://$onion'), throwsA(isA())); + expect(isOnionHost('http://$onion:3413/v2'), isTrue); + expect(isOnionHost('https://grinnode.live'), isFalse); + }); + + test('userinfo, queries and bad schemes are refused with a message', () { + for (final host in [ + 'https://user:hunter2@node.example', + 'https://node.example?x=1', + 'ftp://node.example', + '', + ' ', + ]) { + expect( + () => url(host), + throwsA( + isA().having( + (e) => e.message, + 'message', + isNot(contains('hunter2')), + ), + ), + reason: host, + ); + } + }); +} diff --git a/test/wallets/grin/grin_scan_test.dart b/test/wallets/grin/grin_scan_test.dart new file mode 100644 index 0000000000..457bb14946 --- /dev/null +++ b/test/wallets/grin/grin_scan_test.dart @@ -0,0 +1,325 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/services/event_bus/events/global/blocks_remaining_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_errors.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin_wallet_info_extension.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(restoreHeight: 1000); + h.backend.scanBlocks = true; + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Future restore() async { + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await pumpEventQueue(); + return h.backend.api; + } + + Amount grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + + test('restore creates from the mnemonic, then scans from the restore ' + 'height', () async { + final api = await restore(); + final create = h.backend.creates.single; + expect(create.mnemonic, testMnemonic); + expect(create.isNewWallet, isFalse); + expect(api.calls, contains('scan:1000:false')); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + expect( + (await h.wallet.getCurrentReceivingAddress())!.type, + AddressType.mimbleWimble, + ); + + api.finishScan(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + }); + + test( + 'nothing that refreshes from the node runs while a scan is pending', + () async { + final api = await restore(); + expect(api.scanRunning, isTrue); + final before = List.of(api.calls); + + await h.wallet.refresh(); + await h.wallet.updateTransactions(); + await h.wallet.updateBalance(); + await expectLater( + h.wallet.estimateFeeFor(grin(5), BigInt.one), + throwsA(isA()), + ); + final txData = TxData( + recipients: [ + TxRecipient( + address: 'grin1recipient', + amount: grin(5), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + ); + await expectLater( + h.wallet.prepareSend(txData: txData), + throwsA(isA()), + ); + await expectLater( + h.wallet.confirmSend(txData: txData), + throwsA(isA()), + ); + expect( + await h.wallet.cancelPendingTransactionAndPost('slate-1'), + isNotEmpty, + ); + + final after = api.calls.sublist(before.length); + expect(api.transactionRefreshes, everyElement(isFalse)); + expect(api.balanceRefreshes, everyElement(isFalse)); + for (final call in [ + 'estimateFee', + 'initSend', + 'sendHttp', + 'cancelTransaction', + ]) { + expect(after, isNot(contains(call))); + } + expect(after.where((c) => c.startsWith('scan')), isEmpty); + }, + ); + + test('a cancelled scan resumes from scanned_height + 1', () async { + final api = await restore(); + api.cancelScannedHeight = 20000; + api.cancelScan(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == 20001); + + await h.wallet.refresh(); + await eventually(() => api.calls.contains('scan:20001:false')); + expect(api.calls.where((c) => c.startsWith('scan')).toList(), [ + 'scan:1000:false', + 'scan:20001:false', + ]); + }); + + test('a node change continues a pending restore', () async { + await h.wallet.init(isRestore: true); + h.wallet.shouldAutoSync = true; + await eventually(() => h.wallet.isConnected); + await h.wallet.recover(isRescan: false); + await eventually(() => h.backend.api.scanRunning); + final api = h.backend.api; + api.cancelScannedHeight = 1500; + h.wallet.node = grinNode(host: 'https://other.node'); + + await h.wallet.updateNode(); + await eventually(() => api.calls.contains('scan:1501:false')); + + expect(api.calls.where((c) => c.startsWith('scan:')).toList(), [ + 'scan:1000:false', + 'scan:1501:false', + ]); + expect(h.wallet.info.grinData!.pendingScanFrom, 1501); + }); + + test( + 'a node error keeps the resume height and reports unableToSync', + () async { + h.backend.scanBlocks = false; + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await eventually( + () => h.wallet.info.grinData!.pendingScanFrom == null, + reason: 'the default fake scan succeeds', + ); + + // Now a rescan whose node call fails. + h.backend.api.scanError = grinError(9); + await h.wallet.recover(isRescan: true); + await eventually(() => statuses.contains(WalletSyncStatus.unableToSync)); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + }, + ); + + test('a scan that fails part way resumes after the last batch it ' + 'saved', () async { + h.backend.scanBlocks = false; + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + final api = h.backend.api; + + api.scanError = grinError( + 9, + details: {'scanned_height': 20000, 'tip_height': 50000}, + ); + await h.wallet.recover(isRescan: true); + await eventually(() => statuses.contains(WalletSyncStatus.unableToSync)); + expect(h.wallet.info.grinData!.pendingScanFrom, 20001); + + // A failure before anything new was saved leaves the height alone. + statuses.clear(); + api.scanError = grinError( + 9, + details: {'scanned_height': 20000, 'tip_height': 50000}, + ); + await h.wallet.refresh(); + await eventually(() => statuses.contains(WalletSyncStatus.unableToSync)); + expect( + api.calls.where((c) => c.startsWith('scan:')).last, + 'scan:20001:false', + ); + expect(h.wallet.info.grinData!.pendingScanFrom, 20001); + + api.scanError = null; + await h.wallet.refresh(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + }); + + test('a scan cancelled before it started keeps its resume height, ' + 'whatever the wallet scanned last', () async { + h.backend.scanBlocks = false; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + final api = h.backend.api; + + // A synced wallet's last scanned height is the tip. A rescan whose + // scan never ran must still start from the restore height next time. + api.lastScanned = 50000; + api.scanError = grinError(14); + await h.wallet.recover(isRescan: true); + await eventually( + () => api.calls.where((c) => c.startsWith('scan:')).length == 2, + ); + await pumpEventQueue(); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + expect(api.calls, isNot(contains('lastScannedHeight'))); + }); + + test('a rescan asked for while the scan waits for Tor does not run the ' + 'scan it replaces', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connecting; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await pumpEventQueue(); + final api = h.backend.api; + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + + var rescanned = false; + final rescan = h.wallet + .recover(isRescan: true) + .then((_) => rescanned = true); + await pumpEventQueue(); + expect(rescanned, isFalse); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await rescan.timeout(const Duration(seconds: 5)); + await eventually(() => api.scanRunning); + expect(api.calls.where((c) => c.startsWith('scan:')).toList(), [ + 'scan:1000:false', + ]); + api.finishScan(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + }); + + test('closing wakes a pending scan that is waiting for Tor', () async { + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connecting; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await pumpEventQueue(); + final api = h.backend.api; + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + + await h.wallet.exit().timeout(const Duration(seconds: 1)); + + expect(api.calls, containsAllInOrder(['cancelScan', 'close', 'closed'])); + expect(h.wallet.isOpen, isFalse); + expect(statuses, isNot(contains(WalletSyncStatus.unableToSync))); + }); + + test('progress is reported as percent and blocks remaining', () async { + final percents = []; + final remaining = []; + h.bus.on().listen( + (e) => percents.add(e.percent), + ); + h.bus.on().listen( + (e) => remaining.add(e.blocksRemaining), + ); + final api = await restore(); + api.progress = const GrinScanProgress( + isScanning: true, + cancelRequested: false, + startHeight: 1000, + scannedHeight: 3000, + tipHeight: 5000, + progressPct: 50, + ); + await Future.delayed(const Duration(milliseconds: 1100)); + expect(percents, contains(0.5)); + expect(remaining, contains(2000)); + expect(h.wallet.restoreProgress, 0.5); + api.finishScan(); + }); + + test( + 'rescan keeps history and does not delete unconfirmed outputs', + () async { + final api = await restore(); + api.finishScan(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + await h.wallet.recover(isRescan: true); + await pumpEventQueue(); + expect( + api.calls.where((c) => c.startsWith('scan')).last, + 'scan:1000:false', + ); + expect(h.backend.calls.where((c) => c == 'delete'), isEmpty); + }, + ); +} diff --git a/test/wallets/grin/grin_send_policy_test.dart b/test/wallets/grin/grin_send_policy_test.dart new file mode 100644 index 0000000000..83e8d52feb --- /dev/null +++ b/test/wallets/grin/grin_send_policy_test.dart @@ -0,0 +1,206 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.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/grin_errors.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Amount grin(int nano) => + Amount(rawValue: BigInt.from(nano), fractionDigits: 9); + + TxData send( + String address, { + SlatepackMethod? method, + bool clearnetAck = false, + bool plaintextAck = false, + }) => TxData( + recipients: [ + TxRecipient( + address: address, + amount: grin(1000000000), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: method == null ? null : slatepackMethodOtherData(method), + grinClearnetAcknowledged: clearnetAck, + grinPlaintextAcknowledged: plaintextAck, + ); + + Future torOn() async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + } + + test('a slatepack send to a grin1 address is encrypted, asks for a proof ' + 'and expires', () async { + await h.wallet.init(); + final prepared = await h.wallet.prepareSend(txData: send('grin1friend')); + expect(prepared.slatepackMethod, SlatepackMethod.slatepack); + expect(prepared.fee, grin(23500000)); + final sent = await h.wallet.confirmSend(txData: prepared); + final args = h.backend.api.initSends.single; + expect(args.recipientAddress, 'grin1friend'); + expect(args.ttlBlocks, GrinWallet.slatepackTtlBlocks); + expect(args.minimumConfirmations, 10); + expect(sent.txid, 'slate-S1'); + expect(sent.slatepack, startsWith('BEGINSLATEPACK.')); + expect(sent.toString(), isNot(contains('BEGINSLATEPACK'))); + expect(h.backend.api.httpSends, isEmpty); + }); + + test('a plain slatepack send has no recipient address', () async { + await h.wallet.init(); + final prepared = await h.wallet.prepareSend( + txData: send('', method: SlatepackMethod.slatepack), + ); + await h.wallet.confirmSend(txData: prepared); + expect(h.backend.api.initSends.single.recipientAddress, isNull); + }); + + test('an onion or grin1 HTTP send without Tor is refused before anything ' + 'happens', () async { + await h.wallet.init(); + for (final target in ['http://abc.onion', 'grin1friend']) { + await expectLater( + h.wallet.confirmSend( + txData: send(target, method: SlatepackMethod.http), + ), + throwsA(isA()), + reason: target, + ); + } + expect(h.backend.api.httpSends, isEmpty); + }); + + test( + 'a clearnet send with Tor off needs the IP disclosure accepted', + () async { + await h.wallet.init(); + await expectLater( + h.wallet.confirmSend(txData: send('https://wallet.example')), + throwsA(isA()), + ); + expect(h.backend.api.httpSends, isEmpty); + + await h.wallet.confirmSend( + txData: send('https://wallet.example', clearnetAck: true), + ); + final args = h.backend.api.httpSends.single; + expect(args.post, isTrue); + expect(args.ttlBlocks, GrinWallet.slatepackTtlBlocks); + }, + ); + + test('http:// needs the plaintext warning even over Tor', () async { + await torOn(); + await h.wallet.init(); + await expectLater( + h.wallet.confirmSend(txData: send('http://wallet.example')), + throwsA(isA()), + ); + expect(h.backend.api.httpSends, isEmpty); + await h.wallet.confirmSend( + txData: send('http://wallet.example', plaintextAck: true), + ); + expect(h.backend.api.httpSends, hasLength(1)); + }); + + test( + 'Tor on but down refuses an HTTP send even with the kill switch off', + () async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(); + await expectLater( + h.wallet.confirmSend( + txData: send( + 'https://wallet.example', + clearnetAck: true, + plaintextAck: true, + ), + ), + throwsA(isA()), + ); + expect(h.backend.api.httpSends, isEmpty); + }, + ); + + test('an onion send over Tor goes out', () async { + await torOn(); + await h.wallet.init(); + await h.wallet.confirmSend(txData: send('http://abc.onion')); + expect( + h.backend.api.httpSends.single.recipientUrlOrAddress, + 'http://abc.onion', + ); + }); + + test('send all takes the fee out of the amount', () async { + await h.wallet.init(); + final prepared = await h.wallet.prepareSend( + txData: send('grin1friend').copyWith(subtractFeeFromAmount: true), + ); + expect(prepared.recipients!.single.amount, grin(1000000000 - 23500000)); + await h.wallet.confirmSend(txData: prepared); + final args = h.backend.api.initSends.single; + expect(args.amount, BigInt.from(1000000000)); + expect(args.amountIncludesFee, isTrue); + expect(args.selectionStrategyIsAll, isTrue); + }); + + test('a slatepack can only be encrypted to a grin1 address', () async { + await h.wallet.init(); + await expectLater( + h.wallet.prepareSend( + txData: send('https://x.example', method: SlatepackMethod.slatepack), + ), + throwsA(isA()), + ); + }); + + test('insufficient funds becomes InsufficientBalanceException', () async { + await h.wallet.init(); + h.backend.api.estimateError = grinError(10); + await expectLater( + h.wallet.estimateFeeFor(grin(5), BigInt.one), + throwsA( + isA().having( + (e) => e.runtimeType.toString(), + 'type', + 'InsufficientBalanceException', + ), + ), + ); + expect(await h.wallet.estimateFeeFor(grin(0), BigInt.one), grin(0)); + }); +} diff --git a/test/wallets/grin/grin_swb_test.dart b/test/wallets/grin/grin_swb_test.dart new file mode 100644 index 0000000000..47c018049b --- /dev/null +++ b/test/wallets/grin/grin_swb_test.dart @@ -0,0 +1,95 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin_wallet_info_extension.dart'; + +import '../support/grin_fakes.dart'; + +/// The per-wallet fields restore_create_backup writes for a mnemonic wallet. +Future> backupOf(GrinTestWallet wallet) async => { + 'name': wallet.info.name, + 'id': wallet.walletId, + 'otherDataJsonString': wallet.info.otherDataJsonString, + 'mnemonic': await wallet.getMnemonic(), + 'mnemonicPassphrase': await wallet.getMnemonicPassphrase(), + 'coinName': wallet.info.coin.identifier, + 'storedChainHeight': wallet.info.cachedChainHeight, + 'restoreHeight': wallet.info.restoreHeight, +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + }); + tearDown(() async { + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + test('a backup holds the mnemonic, an empty passphrase, the restore height ' + 'and grinData, and no password', () async { + final original = await GrinHarness.create(); + await original.wallet.init(); + final password = original.backend.creates.single.password; + + final backup = await backupOf(original.wallet); + final text = jsonEncode(backup); + + expect(backup['mnemonic'], testMnemonic); + expect(backup['mnemonicPassphrase'], ''); + expect(backup['coinName'], 'grin'); + final height = original.wallet.info.grinData!.creationHeight; + expect(backup['restoreHeight'], height); + final otherData = + jsonDecode(backup['otherDataJsonString'] as String) as Map; + expect(otherData[WalletInfoKeys.grinData], isNotNull); + expect(text, isNot(contains(password))); + expect(text, isNot(contains(GrinWallet.passwordKey(original.walletId)))); + await original.dispose(); + }); + + test('restoring a backup creates from the mnemonic, then scans from the ' + 'restore height, with a new password', () async { + final original = await GrinHarness.create(); + await original.wallet.init(); + final backup = await backupOf(original.wallet); + final oldPassword = original.backend.creates.single.password; + await original.dispose(); + + // A restore gets a new wallet id with the backed up WalletInfo fields. + final restored = await GrinHarness.create( + restoreHeight: backup['restoreHeight'] as int, + otherDataJsonString: backup['otherDataJsonString'] as String, + ); + await restored.wallet.init(isRestore: true); + expect(restored.backend.calls, isEmpty); + await restored.wallet.recover(isRescan: false); + await pumpEventQueue(); + + final create = restored.backend.creates.single; + expect(create.mnemonic, testMnemonic); + expect(create.isNewWallet, isFalse); + expect(create.password, isNot(oldPassword)); + expect( + restored.secrets.values[GrinWallet.passwordKey(restored.walletId)], + create.password, + ); + expect( + restored.backend.api.calls, + contains('scan:${backup['restoreHeight']}:false'), + ); + await restored.dispose(); + }); +} diff --git a/test/wallets/grin/grin_transport_policy_test.dart b/test/wallets/grin/grin_transport_policy_test.dart new file mode 100644 index 0000000000..31502ffc22 --- /dev/null +++ b/test/wallets/grin/grin_transport_policy_test.dart @@ -0,0 +1,206 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart'; +import 'package:stackwallet/wallets/wallet/supporting/grin/grin_transport.dart'; + +GrinTransport resolve({ + bool feature = true, + bool useTor = true, + TorConnectionStatus status = TorConnectionStatus.connected, + bool killSwitch = true, + TorPlainNetworkOption option = TorPlainNetworkOption.both, + bool onion = false, + String? proxy = '127.0.0.1:9050', +}) { + var proxyReads = 0; + final result = resolveGrinTransport( + torFeature: feature, + useTor: useTor, + torStatus: status, + killSwitch: killSwitch, + nodeNetOption: option, + nodeIsOnion: onion, + proxyAddress: () { + proxyReads++; + return proxy; + }, + ); + if (status != TorConnectionStatus.connected) { + expect(proxyReads, 0, reason: 'proxy read without being used'); + } + return result; +} + +void main() { + const torOnlyOff = GrinBlocked(GrinBlockedReason.torOnlyNodeTorOff); + const clearOn = GrinBlocked(GrinBlockedReason.clearnetNodeTorOn); + const torDown = GrinBlocked(GrinBlockedReason.torDown); + + group('Tor off or not compiled in', () { + for (final feature in [true, false]) { + for (final useTor in [true, false]) { + if (feature && useTor) continue; + test('feature $feature, useTor $useTor', () { + for (final status in TorConnectionStatus.values) { + for (final killSwitch in [true, false]) { + GrinTransport r(TorPlainNetworkOption o, {bool onion = false}) => + resolve( + feature: feature, + useTor: useTor, + status: status, + killSwitch: killSwitch, + option: o, + onion: onion, + ); + expect(r(TorPlainNetworkOption.tor), torOnlyOff); + expect(r(TorPlainNetworkOption.both, onion: true), torOnlyOff); + expect(r(TorPlainNetworkOption.clear), const GrinDirect()); + expect(r(TorPlainNetworkOption.both), const GrinDirect()); + } + } + }); + } + } + }); + + group('Tor on', () { + test('a clearnet-only node is blocked whatever the status', () { + for (final status in TorConnectionStatus.values) { + expect( + resolve(status: status, option: TorPlainNetworkOption.clear), + clearOn, + ); + } + }); + + test('connected uses the proxy, read at resolve time', () { + expect(resolve(), const GrinProxy('127.0.0.1:9050')); + expect( + resolve(proxy: '127.0.0.1:9150'), + const GrinProxy('127.0.0.1:9150'), + ); + expect( + resolve(option: TorPlainNetworkOption.tor, onion: true), + const GrinProxy('127.0.0.1:9050'), + ); + expect(resolve(proxy: null), torDown); + }); + + test('connecting holds', () { + expect(resolve(status: TorConnectionStatus.connecting), const GrinHold()); + }); + + test('disconnected with the kill switch is blocked', () { + for (final option in [ + TorPlainNetworkOption.tor, + TorPlainNetworkOption.both, + ]) { + expect( + resolve(status: TorConnectionStatus.disconnected, option: option), + torDown, + ); + } + }); + + test('disconnected without the kill switch falls back for both only', () { + GrinTransport r(TorPlainNetworkOption o, {bool onion = false}) => resolve( + status: TorConnectionStatus.disconnected, + killSwitch: false, + option: o, + onion: onion, + ); + expect(r(TorPlainNetworkOption.both), const GrinDirect()); + expect(r(TorPlainNetworkOption.tor), torDown); + expect(r(TorPlainNetworkOption.both, onion: true), torDown); + }); + }); + + group('HTTP send policy', () { + GrinSendRefusal? refusal({ + GrinTransport transport = const GrinProxy('127.0.0.1:9050'), + bool torWanted = true, + GrinAddressKind? kind = GrinAddressKind.http, + bool plain = false, + bool clearnetAck = false, + bool plaintextAck = false, + }) => grinHttpSendRefusal( + transport: transport, + torWanted: torWanted, + kind: kind, + isPlainHttp: plain, + clearnetAcknowledged: clearnetAck, + plaintextAcknowledged: plaintextAck, + ); + + test('grin1 and onion targets need a connected proxy', () { + for (final kind in [GrinAddressKind.slatepack, GrinAddressKind.onion]) { + expect(refusal(kind: kind), isNull); + expect( + refusal(kind: kind, transport: const GrinDirect(), torWanted: false), + GrinSendRefusal.torRequired, + ); + expect( + refusal(kind: kind, transport: const GrinDirect()), + GrinSendRefusal.torDown, + ); + expect( + refusal(kind: kind, transport: const GrinHold()), + GrinSendRefusal.torDown, + ); + expect( + refusal(kind: kind, transport: clearOn), + GrinSendRefusal.blocked, + ); + } + }); + + test('a clearnet target with Tor off needs the IP disclosure accepted', () { + expect( + refusal(transport: const GrinDirect(), torWanted: false), + GrinSendRefusal.clearnetNotAcknowledged, + ); + expect( + refusal( + transport: const GrinDirect(), + torWanted: false, + clearnetAck: true, + ), + isNull, + ); + }); + + test('Tor wanted but down refuses even an acknowledged clearnet send', () { + expect( + refusal(transport: const GrinDirect(), clearnetAck: true), + GrinSendRefusal.torDown, + ); + expect( + refusal(transport: torDown, clearnetAck: true), + GrinSendRefusal.blocked, + ); + }); + + test('http:// needs the plaintext warning, even over Tor', () { + expect(refusal(plain: true), GrinSendRefusal.plaintextNotAcknowledged); + expect(refusal(plain: true, plaintextAck: true), isNull); + expect( + refusal( + plain: true, + transport: const GrinDirect(), + torWanted: false, + clearnetAck: true, + ), + GrinSendRefusal.plaintextNotAcknowledged, + ); + }); + + test('unknown targets are refused', () { + expect(refusal(kind: null), GrinSendRefusal.unsupportedTarget); + expect( + refusal(kind: GrinAddressKind.unknown), + GrinSendRefusal.unsupportedTarget, + ); + }); + }); +} diff --git a/test/wallets/grin/grin_transport_test.dart b/test/wallets/grin/grin_transport_test.dart new file mode 100644 index 0000000000..df8e07c60e --- /dev/null +++ b/test/wallets/grin/grin_transport_test.dart @@ -0,0 +1,165 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_status_changed_event.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(restoreHeight: 10); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + Future settle() => pumpEventQueue(times: 50); + + test('the config carries the transport resolved at open', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + await h.wallet.init(); + final config = h.backend.creates.single.config; + expect(config.socksProxy, '127.0.0.1:9050'); + expect(config.networkEnabled, isTrue); + expect(config.nodeUrl, 'https://grinnode.live:3413'); + }); + + test( + 'blocked at open means network disabled, never a direct socket', + () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(); + final config = h.backend.creates.single.config; + expect(config.networkEnabled, isFalse); + expect(config.socksProxy, isNull); + }, + ); + + test('enabling Tor: events arrive before the preference flips', () async { + await h.wallet.init(); + final api = h.backend.api; + + // connectTor fires connecting and connected while useTor is still false. + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connecting, ''), + ); + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await settle(); + expect(api.networkUpdates, isEmpty, reason: 'still direct'); + + h.prefs.tor = true; + h.bus.fire(TorPreferenceChangedEvent(status: TorStatus.enabled)); + await settle(); + expect(api.networkUpdates.single.socksProxy, '127.0.0.1:9050'); + expect(api.networkUpdates.single.networkEnabled, isTrue); + }); + + test( + 'disabling Tor: disconnected arrives while useTor is still true', + () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + await h.wallet.init(); + final api = h.backend.api; + + h.tor.current = TorConnectionStatus.disconnected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.disconnected, ''), + ); + await settle(); + // Kill switch on: blocked until the preference catches up. + expect(api.networkUpdates.single.networkEnabled, isFalse); + + h.prefs.tor = false; + h.bus.fire(TorPreferenceChangedEvent(status: TorStatus.disabled)); + await settle(); + expect(api.networkUpdates, hasLength(2)); + expect(api.networkUpdates.last.networkEnabled, isTrue); + expect(api.networkUpdates.last.socksProxy, isNull); + }, + ); + + test('every blocked update disables the network', () async { + await h.wallet.init(); + final api = h.backend.api; + h.wallet.node = grinNode(tor: true, clear: false); + await h.wallet.updateNode(); + h.prefs.tor = true; + h.wallet.node = grinNode(tor: false, clear: true); + await h.wallet.updateNode(); + h.wallet.node = grinNode(); + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.updateNode(); + expect(api.networkUpdates, hasLength(3), reason: 'three blocked reasons'); + for (final update in api.networkUpdates) { + expect(update.networkEnabled, isFalse); + } + }); + + test('a node change cancels a running scan before updateNetwork', () async { + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await settle(); + final api = h.backend.api; + expect(api.scanRunning, isTrue); + + h.wallet.node = grinNode(host: 'https://other.node', secret: 'secret'); + await h.wallet.updateNode(); + final cancel = api.calls.indexOf('cancelScan'); + final update = api.calls.indexOf('updateNetwork'); + expect(cancel, greaterThanOrEqualTo(0)); + expect(update, greaterThan(cancel)); + expect(api.networkUpdates.single.nodeUrl, 'https://other.node:3413'); + expect(api.networkUpdates.single.apiSecret, 'secret'); + }); + + test('node calls are refused while blocked', () async { + await h.wallet.init(); + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + await expectLater(h.wallet.updateChainHeight(), throwsException); + await expectLater( + h.wallet.estimateFeeFor( + Amount(rawValue: BigInt.from(5), fractionDigits: 9), + BigInt.one, + ), + throwsException, + ); + expect(await h.wallet.pingCheck(), isFalse); + expect(h.backend.nodeTests, isEmpty); + expect(h.backend.api.calls, isNot(contains('estimateFee'))); + }); + + test('the chain height comes from a stateless node test through the ' + 'proxy', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + h.tor.port = 9150; + await h.wallet.init(); + await h.wallet.updateChainHeight(); + expect(h.backend.nodeTests.single.socksProxy, '127.0.0.1:9150'); + expect(h.wallet.info.cachedChainHeight, 4096748); + }); +} diff --git a/test/wallets/grin/grin_tx_mapping_test.dart b/test/wallets/grin/grin_tx_mapping_test.dart new file mode 100644 index 0000000000..a6a0fb2a44 --- /dev/null +++ b/test/wallets/grin/grin_tx_mapping_test.dart @@ -0,0 +1,281 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.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/wallets/wallet/supporting/grin/grin_tx_mapping.dart'; + +import '../support/grin_fakes.dart'; + +const own = 'grin1own'; + +List map( + List entries, { + Map stored = const {}, + int chainHeight = 1000, +}) => mapGrinTransactions( + entries: entries, + walletId: 'w', + ownAddress: own, + storedHeights: stored, + chainHeight: chainHeight, + fractionDigits: 9, +); + +Map od(TransactionV2 tx) => + jsonDecode(tx.otherData!) as Map; + +String label(TransactionV2 tx, {int height = 1000}) => tx.statusLabel( + currentChainHeight: height, + minConfirms: 10, + minCoinbaseConfirms: 1440, +); + +void main() { + test('a self-send becomes one sentToSelf row', () { + final txs = map([ + entryOf(id: 1, debited: 1000, credited: 400, fee: 10, counterparty: own), + entryOf( + id: 2, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 590, + fee: null, + counterparty: own, + ), + ]); + expect(txs, hasLength(1)); + final tx = txs.single; + expect(tx.txid, 'slate-1'); + expect(tx.type, TransactionType.sentToSelf); + expect(od(tx)[TxV2OdKeys.grinLogIds], [1, 2]); + expect(tx.getFee(fractionDigits: 9).raw, BigInt.from(10)); + expect( + tx.outputs.where((o) => !o.walletOwns), + isEmpty, + reason: 'nothing leaves the wallet but the fee', + ); + }); + + test('an outgoing send has a counterparty output and its fee', () { + final tx = map([ + entryOf(id: 3, debited: 1000, credited: 300, fee: 50, counterparty: 'b'), + ]).single; + expect(tx.type, TransactionType.outgoing); + final paid = tx.outputs.singleWhere((o) => !o.walletOwns); + expect(paid.value, BigInt.from(650)); + expect(paid.addresses, ['b']); + expect( + tx.getAmountSentFromThisWallet(fractionDigits: 9, subtractFee: true).raw, + BigInt.from(650), + ); + }); + + test('overrideFee is always set, so getFee never reduces an empty list', () { + final txs = map([ + entryOf( + id: 4, + slateId: null, + type: GrinTxType.txReceived, + state: null, + credited: 0, + fee: null, + ), + entryOf(id: 5, slateId: 's5', debited: 0, credited: 0, fee: null), + ]); + for (final tx in txs) { + expect(od(tx)[TxV2OdKeys.overrideFee], isNotNull); + expect(tx.getFee(fractionDigits: 9).raw, BigInt.zero); + } + }); + + test('a coinbase uses the coinbase maturity', () { + final tx = map([ + entryOf( + id: 6, + slateId: null, + type: GrinTxType.confirmedCoinbase, + state: null, + confirmed: true, + confirmedHeight: 500, + credited: 60, + fee: null, + ), + ]).single; + expect(tx.txid, 'grin_cb_6'); + expect(tx.isCoinbase(), isTrue); + expect(tx.isConfirmed(600, 10, 1440), isFalse); + expect(tx.isConfirmed(1940, 10, 1440), isTrue); + expect(label(tx, height: 600), startsWith('Receiving')); + }); + + test('heights: null until confirmed, then sticky, never the lookup hint', () { + final unconfirmed = map([entryOf(id: 7, debited: 10)]).single; + expect(unconfirmed.height, isNull); + + final reported = map([ + entryOf(id: 7, debited: 10, confirmed: true, confirmedHeight: 900), + ]).single; + expect(reported.height, 900); + + // The library stops reporting a height once the outputs are spent. + final kept = map( + [entryOf(id: 7, debited: 10, confirmed: true)], + stored: {'slate-1': 900}, + ).single; + expect(kept.height, 900); + + final firstSeen = map([ + entryOf(id: 7, debited: 10, confirmed: true), + ], chainHeight: 1234).single; + expect(firstSeen.height, 1234, reason: 'kernelLookupMinHeight is 1'); + + final cancelled = map([ + entryOf( + id: 7, + type: GrinTxType.txSentCancelled, + confirmed: true, + confirmedHeight: 900, + ), + ]).single; + expect(cancelled.height, isNull); + }); + + group('status labels', () { + test('restored funds', () { + final tx = map([ + entryOf( + id: 1, + slateId: null, + type: GrinTxType.txReceived, + state: null, + credited: 5, + confirmed: true, + confirmedHeight: 10, + ), + ]).single; + expect(tx.txid, 'grin_log_1'); + expect(label(tx), 'Restored funds'); + }); + + test('cancelled and reverted', () { + expect( + label(map([entryOf(id: 1, type: GrinTxType.txSentCancelled)]).single), + 'Cancelled', + ); + expect( + label( + map([ + entryOf(id: 1, type: GrinTxType.txReceivedCancelled, credited: 5), + ]).single, + ), + 'Cancelled', + ); + expect( + label( + map([entryOf(id: 1, type: GrinTxType.txReverted, credited: 5)]) + .single, + ), + 'Reverted', + ); + }); + + test('confirmed', () { + expect( + label( + map([ + entryOf(id: 1, debited: 9, confirmed: true, confirmedHeight: 900), + ]).single, + ), + 'Sent', + ); + expect( + label( + map([ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 9, + confirmed: true, + confirmedHeight: 900, + ), + ]).single, + ), + 'Received', + ); + }); + + test('waiting for the other party', () { + expect( + label(map([entryOf(id: 1, debited: 9)]).single), + 'Sending (waiting for response)', + ); + expect( + label( + map([ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 9, + ), + ]).single, + ), + 'Receiving (waiting for sender to finalize)', + ); + expect( + label( + map([ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.i1, + credited: 9, + ), + ]).single, + ), + 'Invoice issued (waiting for payer)', + ); + expect( + label( + map([entryOf(id: 1, state: GrinSlateState.i2, debited: 9)]).single, + ), + 'Paying invoice (waiting for invoicer)', + ); + }); + + test('otherwise the confirmation count', () { + expect( + label( + map([ + entryOf( + id: 1, + state: GrinSlateState.s3, + debited: 9, + confirmed: true, + confirmedHeight: 995, + ), + ]).single, + ), + 'Sending (6/10)', + ); + expect( + label( + map([ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 9, + confirmed: true, + confirmedHeight: 995, + ), + ]).single, + ), + 'Receiving (6/10)', + ); + }); + }); +} diff --git a/test/wallets/grin/grin_wallets_service_test.dart b/test/wallets/grin/grin_wallets_service_test.dart new file mode 100644 index 0000000000..3c4d09965d --- /dev/null +++ b/test/wallets/grin/grin_wallets_service_test.dart @@ -0,0 +1,132 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/db/hive/db.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/notification_model.dart'; +import 'package:stackwallet/models/trade_wallet_lookup.dart'; +import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/services/wallets.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; + +import '../support/grin_fakes.dart'; + +/// What the wallets service does with a Grin wallet at startup and when a +/// wallet is removed. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dataRoot; + late Directory isarRoot; + late Isar isar; + late GrinHarness h; + late Wallets service; + + setUpAll(() async => dataRoot = await setUpGrinTests()); + tearDownAll(() => dataRoot.delete(recursive: true)); + setUp(() async { + isarRoot = await Directory.systemTemp.createTemp('stack_grin_isar_'); + isar = await openTestIsar(isarRoot); + h = await GrinHarness.create(); + service = Wallets.sharedInstance + ..mainDB = MainDB.instance + ..nodeService = NodeService(secureStorageInterface: h.secrets); + final hive = DB.instance.hive; + hive.init(isarRoot.path); + await hive.openBox(DB.boxNameWalletsToDeleteOnStart); + await hive.openBox(DB.boxNameTradeLookup); + await hive.openBox(DB.boxNameNotifications); + }); + tearDown(() async { + await h.dispose(); + await DB.instance.hive.close(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + String passwordKey() => GrinWallet.passwordKey(h.walletId); + List toDeleteOnStart() => + DB.instance.values(boxName: DB.boxNameWalletsToDeleteOnStart); + Future storedInfo() => isar.walletInfo.getByWalletId(h.walletId); + + test('a wallet that cannot be opened at startup is reported, not ' + 'thrown', () async { + h.backend.createError = grinError(15); + expect(await Wallets.initAtStartup(h.wallet), isFalse); + expect(h.wallet.isOpen, isFalse); + + expect(await Wallets.initAtStartup(h.wallet), isTrue); + expect(h.wallet.isOpen, isTrue); + }); + + test('removing an unfinished wallet removes its files and ' + 'password', () async { + await h.wallet.init(); + expect(h.backend.wallets, isNotEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isTrue); + + await service.deleteUnfinishedWallet(h.walletId); + + expect(h.backend.wallets, isEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + expect(h.wallet.isOpen, isFalse); + expect(await storedInfo(), isNull); + expect(toDeleteOnStart(), isEmpty); + }); + + for (final code in [18, 15]) { + final what = code == 18 ? 'is busy' : 'fails'; + test('an unfinished wallet whose delete $what is deleted at the next ' + 'start', () async { + await h.wallet.init(); + h.backend.deleteError = grinError(code); + + await service.deleteUnfinishedWallet(h.walletId); + + expect(await storedInfo(), isNull); + expect(toDeleteOnStart(), [h.walletId]); + expect(h.secrets.values.containsKey(passwordKey()), isTrue); + + h.backend.deleteError = null; + final remaining = await GrinWallet.retryDeferredDeletes( + walletIds: toDeleteOnStart(), + secureStore: h.secrets, + backend: h.backend, + ); + expect(remaining, isEmpty); + expect(h.backend.wallets, isEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + }); + } + + test('a wallet is removed although its files could not be ' + 'deleted', () async { + await h.wallet.init(); + final info = h.wallet.info; + h.backend.deleteError = grinError(15); + + await service.deleteWallet(info, h.secrets); + + expect(await storedInfo(), isNull); + expect( + h.secrets.values.containsKey(Wallet.mnemonicKey(walletId: h.walletId)), + isFalse, + ); + expect(toDeleteOnStart(), [h.walletId]); + // The password stays until the files are gone, so the retry at the + // next start still has a wallet it can recognise. + expect(h.secrets.values.containsKey(passwordKey()), isTrue); + + h.backend.deleteError = null; + final remaining = await GrinWallet.retryDeferredDeletes( + walletIds: toDeleteOnStart(), + secureStore: h.secrets, + backend: h.backend, + ); + expect(remaining, isEmpty); + expect(h.backend.wallets, isEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + }); +} diff --git a/test/wallets/support/grin_fakes.dart b/test/wallets/support/grin_fakes.dart new file mode 100644 index 0000000000..9468a590ee --- /dev/null +++ b/test/wallets/support/grin_fakes.dart @@ -0,0 +1,820 @@ +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:isar_community/isar.dart'; +import 'package:path/path.dart' as p; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/address_label.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/utxo.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/isar/models/transaction_note.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'; +import 'package:stackwallet/services/tor_service.dart'; +import 'package:stackwallet/utilities/enums/sync_type_enum.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/spark_coin.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; + +import '../../support/isar_test_utils.dart'; +import '../../support/memory_secrets.dart'; + +export '../../support/memory_secrets.dart'; + +/// Text a counterparty or node could put in a library error. Tests assert it +/// never reaches user strings or logs. +const remoteText = 'REMOTE-TEXT-from-node'; + +GrinException grinError(int code, {Map? details}) => + GrinException.fromJson( + code, + jsonEncode({'code': code, 'message': remoteText, 'details': details}), + ); + +typedef NetworkUpdate = ({ + String nodeUrl, + String? apiSecret, + String? socksProxy, + bool networkEnabled, +}); + +/// A scripted [GrinWalletApi] that records what it was asked. +class FakeGrinWalletApi implements GrinWalletApi { + FakeGrinWalletApi({required this.walletDir, required this.network}); + + @override + final String walletDir; + @override + final GrinNetwork network; + + final calls = []; + final networkUpdates = []; + final transactionRefreshes = []; + final balanceRefreshes = []; + final initSends = []; + final httpSends = []; + final invoicePayments = []; + final cancelled = <({int? txId, String? slateId})>[]; + + String address = 'grin1ownaddress'; + GrinBalance balance = balanceOf(); + GrinTxList transactions = const GrinTxList( + refreshedFromNode: true, + transactions: [], + ); + GrinFeeEstimate fee = GrinFeeEstimate( + fee: GrinBigInts.fee, + amount: GrinBigInts.zero, + netAmount: GrinBigInts.zero, + total: GrinBigInts.zero, + inputsCount: 1, + changeOutputs: 1, + ); + Object? estimateError; + Object? sendError; + Object? scanError; + + /// Fails the next close once; the wallet stays open. + Object? closeError; + GrinSlateInfo? decoded; + int lastScanned = 0; + int cancelScannedHeight = 0; + + Completer? _scan; + bool scanBlocks = false; + GrinScanProgress progress = const GrinScanProgress( + isScanning: false, + cancelRequested: false, + startHeight: 0, + scannedHeight: 0, + tipHeight: 0, + progressPct: 0, + ); + + Completer? closeGate; + bool _closed = false; + final _events = StreamController.broadcast(); + + bool get scanRunning => _scan != null && !_scan!.isCompleted; + + /// Ends a blocked scan successfully. + void finishScan() => + _scan?.complete(const GrinScanResult(scannedHeight: 100, tipHeight: 100)); + + void _check(String call) { + if (_closed) throw StateError('closed'); + calls.add(call); + } + + @override + bool get isClosed => _closed; + + @override + Stream get events => _events.stream; + + @override + Future getAddress({int index = 0}) async { + _check('getAddress'); + return GrinAddressInfo( + slatepackAddress: address, + onionV3Url: 'http://own.onion', + index: index, + ); + } + + @override + Future getChainHeight() async { + _check('getChainHeight'); + return const GrinChainTip(height: 100, hash: 'tip'); + } + + @override + Future getBalance({ + bool refreshFromNode = true, + int minimumConfirmations = 10, + }) async { + _check('getBalance'); + balanceRefreshes.add(refreshFromNode); + return balance; + } + + @override + Future scan({ + int startHeight = 0, + bool deleteUnconfirmed = false, + }) async { + _check('scan:$startHeight:$deleteUnconfirmed'); + if (scanError != null) throw scanError!; + if (!scanBlocks) { + return const GrinScanResult(scannedHeight: 100, tipHeight: 100); + } + final scan = _scan = Completer(); + return scan.future; + } + + @override + GrinScanProgress scanProgress() { + if (_closed) throw StateError('closed'); + return progress; + } + + @override + void cancelScan() { + if (_closed) throw StateError('closed'); + calls.add('cancelScan'); + final scan = _scan; + if (scan != null && !scan.isCompleted) { + scan.completeError( + grinError(14, details: {'scanned_height': cancelScannedHeight}), + ); + } + } + + @override + Future lastScannedHeight() async { + _check('lastScannedHeight'); + return lastScanned; + } + + @override + Future changePassword(String oldPassword, String newPassword) => + throw UnimplementedError(); + + @override + Future getMnemonic(String password) => throw UnimplementedError(); + + @override + Future updateNetwork({ + required String nodeUrl, + required String? apiSecret, + required String? socksProxy, + required bool networkEnabled, + }) async { + _check('updateNetwork'); + 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, + }) async { + _check('estimateFee'); + if (estimateError != null) throw estimateError!; + final net = amountIncludesFee ? amount - fee.fee : amount; + return GrinFeeEstimate( + fee: fee.fee, + amount: net, + netAmount: net, + total: net + fee.fee, + inputsCount: fee.inputsCount, + changeOutputs: fee.changeOutputs, + ); + } + + @override + Future getTransactions({bool refreshFromNode = true}) async { + _check('getTransactions'); + transactionRefreshes.add(refreshFromNode); + return transactions; + } + + @override + Future decodeSlatepack( + String armored, { + int secretIndex = 0, + }) async { + _check('decodeSlatepack'); + final info = decoded; + if (info == null) throw grinError(11); + return info; + } + + @override + Future initSend(GrinSendArgs args) async { + _check('initSend'); + if (sendError != null) throw sendError!; + initSends.add(args); + return slatepackOf(GrinSlateState.s1, amount: args.amount); + } + + @override + Future sendHttp(GrinHttpSendArgs args) async { + _check('sendHttp'); + if (sendError != null) throw sendError!; + httpSends.add(args); + return GrinSendResult( + slateId: 'slate-http', + state: GrinSlateState.s3, + amount: args.amount, + fee: GrinBigInts.fee, + kernelExcess: '08ab', + posted: true, + ); + } + + @override + Future receiveSlatepack(String armoredS1) async { + _check('receiveSlatepack'); + return slatepackOf(GrinSlateState.s2); + } + + @override + Future finalizeSlatepack( + String armoredS2, { + bool broadcast = true, + bool fluff = false, + }) async { + _check('finalizeSlatepack'); + return finalizedOf(); + } + + @override + Future issueInvoice(GrinInvoiceArgs args) async { + _check('issueInvoice'); + return slatepackOf(GrinSlateState.i1, amount: args.amount); + } + + @override + Future processInvoice( + String armoredI1, + GrinProcessInvoiceArgs args, + ) async { + _check('processInvoice'); + invoicePayments.add(args); + return slatepackOf(GrinSlateState.i2); + } + + @override + Future finalizeInvoice( + String armoredI2, { + bool broadcast = true, + bool fluff = false, + }) async { + _check('finalizeInvoice'); + return finalizedOf(); + } + + @override + Future repost({int? txId, String? slateId, bool fluff = false}) async { + _check('repost'); + } + + @override + Future cancelTransaction({int? txId, String? slateId}) async { + _check('cancelTransaction'); + cancelled.add((txId: txId, slateId: slateId)); + } + + @override + Future exportPaymentProof({ + int? txId, + String? slateId, + }) async { + _check('exportPaymentProof'); + return GrinPaymentProof.fromJson({ + 'amount': 1, + 'excess': '08ab', + 'recipient_address': 'grin1recipient', + 'sender_address': address, + 'recipient_sig': 'r', + 'sender_sig': 's', + }); + } + + @override + Future verifyPaymentProof( + GrinPaymentProof proof, + ) async { + _check('verifyPaymentProof'); + return const GrinPaymentProofVerification( + isSender: true, + isRecipient: false, + ); + } + + @override + Future close() async { + if (_closed) return; + calls.add('close'); + final error = closeError; + if (error != null) { + closeError = null; + throw error; + } + _closed = true; + final scan = _scan; + if (scan != null && !scan.isCompleted) scan.completeError(grinError(14)); + await closeGate?.future; + calls.add('closed'); + await _events.close(); + } +} + +abstract final class GrinBigInts { + static final zero = BigInt.zero; + static final fee = BigInt.from(23500000); +} + +GrinBalance balanceOf({ + int spendable = 0, + int awaitingConfirmation = 0, + int immature = 0, + int awaitingFinalization = 0, + int locked = 0, +}) => GrinBalance( + lastConfirmedHeight: 100, + minimumConfirmations: 10, + total: BigInt.from(spendable + awaitingConfirmation + immature), + amountAwaitingFinalization: BigInt.from(awaitingFinalization), + amountAwaitingConfirmation: BigInt.from(awaitingConfirmation), + amountImmature: BigInt.from(immature), + amountCurrentlySpendable: BigInt.from(spendable), + amountLocked: BigInt.from(locked), + amountReverted: BigInt.zero, + refreshedFromNode: true, +); + +GrinSlatepack slatepackOf(GrinSlateState state, {BigInt? amount}) => + GrinSlatepack( + slateId: 'slate-${state.wireName}', + state: state, + armoredSlatepack: 'BEGINSLATEPACK. secret ENDSLATEPACK.', + amount: amount ?? BigInt.zero, + fee: GrinBigInts.fee, + sender: 'grin1sender', + recipients: const [], + isEncrypted: false, + ); + +GrinFinalizeResult finalizedOf() => GrinFinalizeResult( + slateId: 'slate-S3', + state: GrinSlateState.s3, + amount: BigInt.zero, + fee: GrinBigInts.fee, + kernelExcess: '08ab', + posted: true, + armoredSlatepack: 'BEGINSLATEPACK. final ENDSLATEPACK.', +); + +GrinSlateInfo slateInfoOf(GrinSlateState state, {required int amount}) => + GrinSlateInfo( + slateId: 'slate-in', + state: state, + amount: BigInt.from(amount), + fee: BigInt.zero, + kernelExcess: null, + sender: null, + recipients: const [], + ttlCutoffHeight: null, + numParticipants: 2, + isEncrypted: false, + slateJson: '{"secret":"slate"}', + ); + +typedef CreateCall = ({ + GrinWalletConfig config, + String? mnemonic, + String password, + bool isNewWallet, +}); + +/// A scripted [GrinWalletBackend]. +class FakeGrinBackend implements GrinWalletBackend { + final calls = []; + final creates = []; + final opens = []; + final deletes = []; + final nodeTests = + <({String nodeUrl, String? apiSecret, String? socksProxy})>[]; + final apis = []; + + /// Directories that hold a wallet, with its password. + final wallets = {}; + + /// Runs before create, so a test can look at storage at that moment. + void Function(CreateCall call)? onCreate; + Object? createError; + Object? deleteError; + Object? nodeError; + Object? decodeError; + int nodeHeight = 4096748; + + /// New wallets' scans wait for [FakeGrinWalletApi.finishScan] or a cancel. + bool scanBlocks = false; + + FakeGrinWalletApi get api => apis.last; + + FakeGrinWalletApi _newApi(GrinWalletConfig config) { + final api = FakeGrinWalletApi( + walletDir: config.walletDir, + network: config.network, + )..scanBlocks = scanBlocks; + apis.add(api); + return api; + } + + @override + Future create({ + required GrinWalletConfig config, + String? mnemonic, + required String password, + bool isNewWallet = false, + }) async { + calls.add('create'); + final call = ( + config: config, + mnemonic: mnemonic, + password: password, + isNewWallet: isNewWallet, + ); + onCreate?.call(call); + creates.add(call); + final error = createError; + if (error != null) { + createError = null; + throw error; + } + if (wallets.containsKey(config.walletDir)) throw grinError(6); + wallets[config.walletDir] = password; + return _newApi(config); + } + + @override + Future open({ + required GrinWalletConfig config, + required String password, + }) async { + calls.add('open'); + opens.add(config); + final stored = wallets[config.walletDir]; + if (stored == null) throw grinError(4); + if (stored != password) throw grinError(5); + return _newApi(config); + } + + @override + Future delete({required String walletDir}) async { + calls.add('delete'); + deletes.add(walletDir); + if (deleteError != null) throw deleteError!; + wallets.remove(walletDir); + } + + @override + Future testNodeConnection({ + required String nodeUrl, + String? apiSecret, + String? socksProxy, + }) async { + calls.add('testNodeConnection'); + nodeTests.add(( + nodeUrl: nodeUrl, + apiSecret: apiSecret, + socksProxy: socksProxy, + )); + if (nodeError != null) throw nodeError!; + return GrinNodeInfo( + nodeVersion: '5.3.0', + blockHeaderVersion: 5, + height: nodeHeight, + hash: 'tip', + ); + } + + @override + GrinAddressValidation validateAddressSync( + String address, + GrinNetwork network, + ) { + final text = address.trim(); + final prefix = network.usesTestPrefix ? 'tgrin1' : 'grin1'; + if (text.startsWith(prefix)) { + return GrinAddressValidation( + kind: GrinAddressKind.slatepack, + slatepackAddress: text, + url: 'http://x.onion', + ); + } + if (text.contains('.onion')) { + return GrinAddressValidation(kind: GrinAddressKind.onion, url: text); + } + if (text.startsWith('http://') || text.startsWith('https://')) { + return GrinAddressValidation(kind: GrinAddressKind.http, url: text); + } + throw grinError(21); + } + + @override + Future validateAddress( + String address, + GrinNetwork network, + ) async => validateAddressSync(address, network); + + @override + Future generateMnemonic({int wordCount = 24}) => + throw UnimplementedError(); + + @override + Future validateMnemonic(String mnemonic) => + throw UnimplementedError(); + + @override + Future decodeSlatepackWithoutWallet( + String armored, + GrinNetwork network, + ) async { + calls.add('decodeSlatepackWithoutWallet'); + if (decodeError != null) throw decodeError!; + return slateInfoOf(GrinSlateState.s1, amount: 1); + } +} + +class FakeTorService extends Fake implements TorService { + TorConnectionStatus current = TorConnectionStatus.disconnected; + int port = 9050; + + @override + TorConnectionStatus get status => current; + + @override + ({InternetAddress host, int port}) getProxyInfo() { + if (current != TorConnectionStatus.connected) { + throw StateError('Tor not connected'); + } + return (host: InternetAddress.loopbackIPv4, port: port); + } +} + +class GrinTestPrefs extends Fake implements Prefs { + bool tor = false; + bool killSwitch = true; + + @override + bool get useTor => tor; + @override + bool get torKillSwitch => killSwitch; + @override + SyncingType get syncType => SyncingType.allWalletsOnStartup; + @override + List get walletIdsSyncOnStartup => const []; +} + +const testMnemonic = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon abandon abandon abandon abandon art'; + +NodeModel grinNode({ + String host = 'https://grinnode.live', + int port = 3413, + bool tor = true, + bool clear = true, + String? secret, +}) => NodeModel( + host: host, + port: port, + name: 'node', + id: 'node', + useSSL: host.startsWith('https'), + enabled: true, + coinName: 'grin', + isFailover: false, + isDown: false, + torEnabled: tor, + clearnetEnabled: clear, + isPrimary: true, + nodeApiSecret: secret, +); + +/// A [GrinWallet] wired to fakes and an in-memory set of services. +class GrinTestWallet extends GrinWallet { + GrinTestWallet({ + required this.testWalletId, + required FakeGrinBackend backend, + required FakeTorService tor, + required EventBus bus, + required MemorySecrets secrets, + required GrinTestPrefs testPrefs, + }) : super( + CryptoCurrencyNetwork.main, + backend: backend, + torService: tor, + eventBus: bus, + ) { + mainDB = MainDB.instance; + secureStorageInterface = secrets; + prefs = testPrefs; + } + + final String testWalletId; + NodeModel node = grinNode(); + bool torFeature = true; + + @override + String get walletId => testWalletId; + + @override + NodeModel getCurrentNode() => node; + + @override + bool get torFeatureEnabled => torFeature; +} + +/// Everything a wallet test needs, made fresh per test. +class GrinHarness { + GrinHarness._(this.walletId); + + final String walletId; + final backend = FakeGrinBackend(); + final tor = FakeTorService(); + final bus = EventBus(); + final secrets = MemorySecrets({}); + final prefs = GrinTestPrefs(); + late final GrinTestWallet wallet = newWallet(); + + GrinTestWallet newWallet() => GrinTestWallet( + testWalletId: walletId, + backend: backend, + tor: tor, + bus: bus, + secrets: secrets, + testPrefs: prefs, + ); + + static int _sequence = 0; + + /// A WalletInfo and mnemonic for a new wallet id. + static Future create({ + int restoreHeight = 0, + String? otherDataJsonString, + }) async { + final harness = GrinHarness._('grin-test-${_sequence++}'); + await MainDB.instance.putWalletInfo( + WalletInfo( + walletId: harness.walletId, + name: 'fixture', + mainAddressType: AddressType.mimbleWimble, + coinName: 'grin', + restoreHeight: restoreHeight, + otherDataJsonString: otherDataJsonString, + ), + ); + harness.secrets.values[Wallet.mnemonicKey(walletId: harness.walletId)] = + testMnemonic; + harness.secrets.values[Wallet.mnemonicPassphraseKey( + walletId: harness.walletId, + )] = + ''; + return harness; + } + + /// Cleans up the wallet so the static owner map does not leak into the + /// next test. + Future dispose() async { + try { + await wallet.exit(); + } catch (_) {} + } +} + +/// Opens an Isar for the test and points MainDB at it. Call in setUp. +Future openTestIsar(Directory root) async { + final isar = await Isar.open( + [ + WalletInfoSchema, + TransactionV2Schema, + AddressSchema, + TransactionSchema, + UTXOSchema, + SparkCoinSchema, + AddressLabelSchema, + TransactionNoteSchema, + ], + directory: root.path, + name: 'grin-test', + inspector: false, + ); + await MainDB.instance.initMainDB(mock: isar); + return isar; +} + +/// One-time setup for tests that use Isar and the Grin data directory. +/// +/// The data root is given to StackFileSystem as a path relative to the +/// working directory, so tests can check the wallet directory is made +/// absolute. Returns the root; delete it in tearDownAll. +Future setUpGrinTests() async { + final root = await Directory.systemTemp.createTemp('stack_grin_'); + StackFileSystem.setDesktopOverrideDir(p.relative(root.path)); + await initializeTestIsar(); + return root; +} + +/// A Grin log entry with defaults. +GrinTxLogEntry entryOf({ + required int id, + String? slateId = 'slate-1', + GrinTxType type = GrinTxType.txSent, + GrinSlateState? state = GrinSlateState.s1, + bool confirmed = false, + int? confirmedHeight, + int credited = 0, + int debited = 0, + int? fee = 8000000, + String? counterparty, + String? kernelExcess, + bool hasStoredTx = false, + String? armored, + int? ttl, +}) => GrinTxLogEntry( + id: id, + slateId: slateId, + slateState: state, + type: type, + creationTime: DateTime.utc(2026, 11, 7), + confirmationTime: null, + confirmed: confirmed, + confirmedHeight: confirmedHeight, + numInputs: debited > 0 ? 1 : 0, + numOutputs: credited > 0 ? 1 : 0, + amountCredited: BigInt.from(credited), + amountDebited: BigInt.from(debited), + fee: fee == null ? null : BigInt.from(fee), + ttlCutoffHeight: ttl, + kernelExcess: kernelExcess, + kernelLookupMinHeight: confirmed ? 1 : null, + hasStoredTx: hasStoredTx, + paymentProof: null, + counterpartyAddress: counterparty, + armoredSlatepack: armored, + revertedAfterSecs: null, +); + +/// Waits until [check] holds, for work that finishes on Isar's thread. +Future eventually(bool Function() check, {String? reason}) async { + final deadline = DateTime.now().add(const Duration(seconds: 5)); + while (!check()) { + if (DateTime.now().isAfter(deadline)) { + fail('timed out waiting${reason == null ? '' : ': $reason'}'); + } + await Future.delayed(const Duration(milliseconds: 10)); + } +} diff --git a/test/wallets/support/xelis_test_fakes.dart b/test/wallets/support/xelis_test_fakes.dart index 06ff17da81..88a6e39b7f 100644 --- a/test/wallets/support/xelis_test_fakes.dart +++ b/test/wallets/support/xelis_test_fakes.dart @@ -4,13 +4,14 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/services/wallets.dart'; import 'package:stackwallet/utilities/enums/sync_type_enum.dart'; -import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/wallet/impl/xelis_wallet.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/wl_gen/interfaces/lib_xelis_interface.dart'; +export '../../support/memory_secrets.dart'; + class FakeNative extends Fake implements LibXelisInterface { @override String get xelisAsset => 'xel'; @@ -103,34 +104,3 @@ class ConfirmationPrefs extends ChangeNotifier implements Prefs { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } - -class MemorySecrets extends Fake implements SecureStorageInterface { - final values = {'xelis_wants_full_tables': 'false'}; - String? failingKey; - String? failingDeleteKey; - Future Function(String)? beforeDelete; - @override - dynamic noSuchMethod(Invocation invocation) { - final key = invocation.namedArguments[#key] as String; - switch (invocation.memberName) { - case #delete: - return () async { - await beforeDelete?.call(key); - if (key == failingDeleteKey) { - throw StateError('fixture delete failure'); - } - values.remove(key); - }(); - case #read: - return Future.value(values[key]); - case #write: - if (key == failingKey) { - return Future.error(StateError('fixture write failure')); - } - values[key] = invocation.namedArguments[#value] as String; - return Future.value(); - default: - return super.noSuchMethod(invocation); - } - } -} diff --git a/test/widget_tests/node_tls_trust_test.dart b/test/widget_tests/node_tls_trust_test.dart index 6873d8b324..0fa13d6a5d 100644 --- a/test/widget_tests/node_tls_trust_test.dart +++ b/test/widget_tests/node_tls_trust_test.dart @@ -26,6 +26,7 @@ import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/test_node_connection.dart'; +import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart'; import 'package:stackwallet/utilities/util.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; @@ -405,6 +406,69 @@ void main() { expect(node().trustedCertificatePem, pem); }); + testWidgets('Grin onion nodes stay Tor-only with plain HTTP', (tester) async { + coin = Grin(CryptoCurrencyNetwork.main); + final data = NodeFormData(); + await pump( + tester, + Scaffold( + body: SingleChildScrollView( + child: NodeForm( + data: data, + secureStore: storage, + readOnly: false, + coin: coin, + ), + ), + ), + ); + + await tester.enterText( + find.byKey(const Key('addCustomNodeNodeAddressFieldKey')), + 'http://wallet.example.onion', + ); + await tester.pump(); + + Finder option(String label) => find.byWidgetPredicate( + (widget) => + widget is RadioTextButton && + widget.label == label, + ); + final clear = option('Only non-TOR traffic'); + final both = option('Allow both'); + expect(data.netOption, TorPlainNetworkOption.tor); + expect(data.useSSL, false); + expect(find.text('API secret (optional)'), findsOneWidget); + expect( + tester.widget>(clear).enabled, + false, + ); + expect( + tester.widget>(both).enabled, + false, + ); + + // RadioTextButton's label gesture also calls onChanged, so the form-level + // policy must reject this path as well as disabling the Radio itself. + await tester.tap(find.text('Only non-TOR traffic')); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.tor); + + await tester.enterText( + find.byKey(const Key('addCustomNodeNodeAddressFieldKey')), + 'https://node.example', + ); + await tester.pump(); + expect( + tester.widget>(clear).enabled, + true, + ); + await tester.tap(find.text('Only non-TOR traffic')); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.clear); + expect(data.useSSL, true); + }); + testWidgets( 'Forget in read-only Details is an immediate certificate-only write', (tester) async { diff --git a/tool/wl_templates/GRIN_libgrin_interface_impl.template.dart b/tool/wl_templates/GRIN_libgrin_interface_impl.template.dart new file mode 100644 index 0000000000..14a9e3a88a --- /dev/null +++ b/tool/wl_templates/GRIN_libgrin_interface_impl.template.dart @@ -0,0 +1,23 @@ +//ON +import 'package:grin_native/grin_native.dart'; + +//END_ON +//OFF +import 'package:grin_native/grin_native.dart'; + +//END_OFF +import '../interfaces/libgrin_interface.dart'; + +LibGrinInterface get libGrin => const _LibGrinInterfaceImpl(); + +final class _LibGrinInterfaceImpl extends LibGrinInterface { + const _LibGrinInterfaceImpl(); + + @override + //OFF + GrinWalletBackend get backend => throw StateError("GRIN not enabled"); + //END_OFF + //ON + GrinWalletBackend get backend => const GrinNativeBackend(); + //END_ON +}