From 8312af8b4a50070e37fec78f8917e6d068775828 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 2 Dec 2026 09:43:44 -0600 Subject: [PATCH 1/2] style: dart format five views that predate the 3.13 SDK bump These files were last changed before the SDK constraint moved to 3.13, so CI's format check would fail on any later change to them. This commit is the formatter's output only. --- .../restore_options_view.dart | 106 ++++++------ .../sub_widgets/restoring_wallet_card.dart | 42 ++--- .../wallet_network_settings_view.dart | 156 +++++++++--------- .../wallet_settings_wallet_settings_view.dart | 42 +++-- .../sub_widgets/wallet_options_button.dart | 54 +++--- 5 files changed, 194 insertions(+), 206 deletions(-) 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 e650564a1..f6b66df93 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 @@ -273,9 +273,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 +309,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(() { @@ -434,9 +433,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, @@ -474,9 +473,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 +490,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( @@ -528,9 +525,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), ), @@ -582,9 +579,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 +589,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 +629,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 +666,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 +701,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 +729,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 +794,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 +831,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 +848,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 +878,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/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 9a792c48d..7493cd0b7 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 @@ -116,9 +116,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 +195,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 +227,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 +284,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 +316,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 3eccb7928..55c177e39 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 @@ -376,9 +376,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 +403,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 +427,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 +545,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 +570,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 +608,9 @@ class _WalletNetworkSettingsViewState Assets.svg.radioSyncing, height: 14, width: 14, - color: Theme.of( - context, - ).extension()!.accentColorYellow, + color: Theme.of(context) + .extension()! + .accentColorYellow, ), ), ), @@ -649,9 +649,8 @@ class _WalletNetworkSettingsViewState coin is Mimblewimblecoin || (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 +670,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 +708,9 @@ class _WalletNetworkSettingsViewState Assets.svg.radioProblem, height: 14, width: 14, - color: Theme.of( - context, - ).extension()!.accentColorRed, + color: Theme.of(context) + .extension()! + .accentColorRed, ), ), ), @@ -726,17 +725,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 +745,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 +762,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 +856,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 +869,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 +880,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 +900,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 +1011,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 +1037,9 @@ class _WalletNetworkSettingsViewState STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), Text( @@ -1058,9 +1058,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 6a266b247..fc48d5e02 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 @@ -392,11 +392,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 +440,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 +488,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 +537,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? ?? @@ -655,9 +651,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_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 dc7fc8b3a..5e6c6ac65 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 @@ -324,9 +324,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 +418,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -453,9 +453,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -488,9 +488,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -524,9 +524,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -559,9 +559,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -594,9 +594,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -631,9 +631,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -665,9 +665,9 @@ class WalletOptionsPopupMenu extends ConsumerWidget { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), From 07b96f2615d035aa07a6e5d8fa7680f01e8a4180 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 2 Dec 2026 09:46:22 -0600 Subject: [PATCH 2/2] feat: add Grin wallet through grin_native Add the Grin coin, wallet core and transport policy through grin_native, the only Grin Dart dependency. grin_native 001df2a builds grin-ffi from cypherstack/grin-wallet, whose grin submodule is cypherstack/grin. Every app depends on grin_native for the API lib/ uses, but only an app configured with GRIN builds and bundles grin-ffi. process_pubspec_deps.dart sets hooks.user_defines.grin_native.enabled from the GRIN flag, so Stack Duo and Campfire turn the hook off. Grin is not in the app's coin list yet. A send to a grin1 address creates a Slatepack that only the Slatepack screens can show, so the coin list entry comes with them. Until then, tests that build a Grin wallet add Grin to the coin list through AppConfig.coinsOverride, so they run in every app config. Grin tests reuse the MemorySecrets fixture from xelis_test_fakes.dart. --- docs/building/native-libraries.md | 8 + .../desktop_forgot_password/harness.dart | 1 + lib/app_config.dart | 12 +- .../blockchain_data/v2/transaction_v2.dart | 65 + lib/models/slatepack_models.dart | 7 +- ...w_wallet_recovery_phrase_warning_view.dart | 1 + .../restore_options_view.dart | 22 +- .../restore_wallet_view.dart | 5 + lib/pages/send_view/send_view.dart | 11 +- .../add_edit_node_view.dart | 95 +- .../helpers/restore_create_backup.dart | 114 +- .../sub_widgets/restoring_wallet_card.dart | 6 + .../wallet_network_settings_view.dart | 54 +- .../wallet_settings_wallet_settings_view.dart | 9 +- .../tx_v2/transaction_v2_details_view.dart | 6 +- .../wallet_view/sub_widgets/desktop_send.dart | 2 +- .../sub_widgets/wallet_options_button.dart | 5 +- lib/services/price.dart | 1 + lib/services/wallets.dart | 101 +- lib/utilities/amount/amount_unit.dart | 5 +- lib/utilities/desktop_startup_and_reset.dart | 1 + lib/utilities/enums/slatepack_method.dart | 12 +- lib/utilities/native_library_check.dart | 8 + lib/utilities/owner_only_directory.dart | 62 + lib/utilities/stack_file_system.dart | 14 + lib/utilities/test_grin_node_connection.dart | 76 + lib/utilities/test_node_connection.dart | 14 + lib/wallets/crypto_currency/coins/grin.dart | 197 ++ .../coins/grin_checkpoints.dart | 190 ++ .../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 | 2049 +++++++++++++++++ .../wallet/supporting/grin/grin_errors.dart | 174 ++ .../wallet/supporting/grin/grin_node_url.dart | 85 + .../supporting/grin/grin_transport.dart | 212 ++ .../supporting/grin/grin_tx_mapping.dart | 249 ++ .../grin_wallet_info_extension.dart | 58 + lib/wallets/wallet/wallet.dart | 4 + .../slatepack_interface.dart | 35 + lib/wl_gen/interfaces/libgrin_interface.dart | 13 + pubspec.lock | 9 + scripts/app_config/configure_stack_wallet.sh | 6 +- .../templates/pubspec.template.yaml | 14 + scripts/ensure_test_app_config.sh | 1 + scripts/tests/native_build_config_test.dart | 8 +- .../restored_wallet_ids_test.dart | 36 + test/utilities/native_library_check_test.dart | 20 +- test/utilities/owner_only_directory_test.dart | 45 + test/wallets/grin/grin_balance_test.dart | 100 + test/wallets/grin/grin_coin_test.dart | 124 + test/wallets/grin/grin_errors_test.dart | 219 ++ test/wallets/grin/grin_invoice_test.dart | 91 + test/wallets/grin/grin_lifecycle_test.dart | 376 +++ .../grin/grin_network_settings_test.dart | 53 + test/wallets/grin/grin_node_url_test.dart | 86 + test/wallets/grin/grin_scan_test.dart | 671 ++++++ test/wallets/grin/grin_send_policy_test.dart | 350 +++ test/wallets/grin/grin_swb_test.dart | 146 ++ .../grin/grin_transport_policy_test.dart | 206 ++ test/wallets/grin/grin_transport_test.dart | 481 ++++ test/wallets/grin/grin_tx_mapping_test.dart | 392 ++++ .../grin/grin_wallets_service_test.dart | 154 ++ test/wallets/support/grin_fakes.dart | 920 ++++++++ test/widget_tests/node_tls_trust_test.dart | 219 ++ tool/process_pubspec_deps.dart | 10 +- .../GRIN_libgrin_interface_impl.template.dart | 23 + 67 files changed, 8689 insertions(+), 74 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/crypto_currency/coins/grin_checkpoints.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/pages/settings_views/stack_backup_views/restored_wallet_ids_test.dart create mode 100644 test/utilities/owner_only_directory_test.dart create mode 100644 test/wallets/grin/grin_balance_test.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_network_settings_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/docs/building/native-libraries.md b/docs/building/native-libraries.md index e9f4e38a8..429a04053 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 sources from `cypherstack/grin-wallet` and `cypherstack/grin`, fetched over public HTTPS. Every app depends on `grin_native`, because `lib/` uses the API it re-exports, but only an app configured with the `GRIN` flag builds and bundles `grin-ffi`; the others turn the hook off with `hooks.user_defines.grin_native.enabled: false` | | 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 32c5d966b..730789afb 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/lib/app_config.dart b/lib/app_config.dart index d594cf5d9..52ee5e1e3 100644 --- a/lib/app_config.dart +++ b/lib/app_config.dart @@ -1,6 +1,8 @@ // ignore: unused_import import 'dart:io'; +import 'package:meta/meta.dart'; + import 'models/isar/models/ethereum/eth_contract.dart'; import 'utilities/default_eth_tokens.dart'; import 'wallets/crypto_currency/crypto_currency.dart'; @@ -28,7 +30,15 @@ abstract class AppConfig { static ({String light, String dark})? get appIconAsset => _appIconAsset; - static List get coins => _supportedCoins; + static List get coins => _coinsOverride ?? _supportedCoins; + + static List? _coinsOverride; + + /// Replaces [coins] for tests of a coin this app config does not list. + /// Null restores the configured list. + @visibleForTesting + static set coinsOverride(List? coins) => + _coinsOverride = coins == null ? null : List.unmodifiable(coins); static List get defaultEthTokens => _defaultEthTokens; 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 fd6a189e8..f57346b94 100644 --- a/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart +++ b/lib/models/isar/models/blockchain_data/v2/transaction_v2.dart @@ -104,6 +104,18 @@ class TransactionV2 implements WalletTransaction { 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?; @@ -303,6 +315,15 @@ class TransactionV2 implements WalletTransaction { } } + if (isGrinTransaction) { + return _grinStatusLabel( + currentChainHeight: currentChainHeight, + minConfirms: minConfirms, + minCoinbaseConfirms: minCoinbaseConfirms, + prettyConfirms: prettyConfirms, + ); + } + if (isMimblewimblecoinTransaction) { if (slateId == null) { return "Restored Funds"; @@ -365,6 +386,40 @@ class TransactionV2 implements WalletTransaction { } } + 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; @@ -422,4 +477,14 @@ 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 grinPaymentProofLogId = "grinPaymentProofLogId"; + static const counterpartyAddress = "counterpartyAddress"; + static const isReverted = "isReverted"; } diff --git a/lib/models/slatepack_models.dart b/lib/models/slatepack_models.dart index a0f42dd68..930dd8ea4 100644 --- a/lib/models/slatepack_models.dart +++ b/lib/models/slatepack_models.dart @@ -151,12 +151,16 @@ class FinalizeResult { /// broadcast status (MWC). final bool? posted; + /// Null for Epic Cash and MWC. + final String? kernelExcess; + FinalizeResult({ required this.success, this.error, this.slateId, this.commitId, this.posted, + this.kernelExcess, }); @override @@ -166,7 +170,8 @@ class FinalizeResult { "error: $error, " "slateId: $slateId, " "commitId: $commitId, " - "posted: $posted" + "posted: $posted, " + "kernelExcess: $kernelExcess" ")"; } } 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 b6651294f..e04af2dc1 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 @@ -205,6 +205,7 @@ class _NewWalletRecoveryPhraseWarningViewState if (coin is Epiccash || coin is Mimblewimblecoin || coin is Tezos || + coin is Grin || coin is Solana) { mnemonicPassphrase = ""; } 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 f6b66df93..132252098 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; @@ -425,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: [ @@ -452,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, @@ -512,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( @@ -535,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", 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 8da30ef48..5b9a5c742 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 @@ -42,6 +42,7 @@ import '../../../utilities/util.dart'; import '../../../wallets/crypto_currency/crypto_currency.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'; @@ -368,6 +369,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 32d6231a0..67ffe109c 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -654,8 +654,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 @@ -1227,7 +1228,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]); } @@ -2447,14 +2448,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 4944dce4c..2f5b3ab7a 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 @@ -36,6 +36,9 @@ 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_node_url.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'; @@ -792,6 +795,10 @@ class _NodeFormState extends ConsumerState { late TorPlainNetworkOption netOption; bool _isPrimary = false; + /// The network option and SSL settings an onion host replaced, put back + /// when the host stops being an onion host. + ({TorPlainNetworkOption net, bool ssl, bool sslEnabled})? _beforeOnion; + late final bool enableAuthFields; void Function(bool canSave, bool canTestConnection)? onChanged; @@ -813,7 +820,20 @@ class _NodeFormState extends ConsumerState { } bool get canTestConnection { - return _hostController.text.isNotEmpty && isValidNodePort(port); + return _hostController.text.isNotEmpty && + isValidNodePort(port) && + _grinHostError == null; + } + + /// Why the Grin library would refuse this address, or null. + String? get _grinHostError { + if (widget.coin is! Grin || _hostController.text.isEmpty) return null; + try { + grinNodeUrl(host: _hostController.text, port: 0, useSSL: _useSSL); + return null; + } on GrinNodeUrlException catch (e) { + return e.message; + } } bool enableField(TextEditingController controller) { @@ -827,6 +847,21 @@ class _NodeFormState extends ConsumerState { bool get shouldBeReadOnly => _inputsReadOnly || widget.node?.isDefault == true; + bool _isGrinOnion(String host) => widget.coin is Grin && isOnionHost(host); + + /// Puts back the network and SSL settings from before a Grin onion host, + /// once [host] is no longer one. A scheme in [host] has set SSL already. + void _restoreBeforeOnion(String host) { + final before = _beforeOnion; + if (before == null) return; + _beforeOnion = null; + netOption = before.net; + if (!host.startsWith("http://") && !host.startsWith("https://")) { + _useSSL = before.ssl; + enableSSLCheckbox = before.sslEnabled; + } + } + void _updateState() { if (widget.busy || _changing) return; _copyToFormData(); @@ -908,10 +943,20 @@ class _NodeFormState extends ConsumerState { } else { netOption = TorPlainNetworkOption.both; } + if (_isGrinOnion(node.host)) { + netOption = TorPlainNetworkOption.tor; + // Nothing earlier to put back: a clearnet Grin node gets the + // defaults of the public nodes. + _beforeOnion = ( + net: TorPlainNetworkOption.both, + ssl: true, + sslEnabled: true, + ); + } 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; @@ -1033,7 +1078,10 @@ class _NodeFormState extends ConsumerState { child: const XIcon(), onTap: () async { _hostController.text = ""; + // As typing the host away would. + _restoreBeforeOnion(""); _updateState(); + setState(() {}); }, ), ], @@ -1043,6 +1091,11 @@ class _NodeFormState extends ConsumerState { : null, ), onChanged: (newValue) { + final previous = ( + net: netOption, + ssl: _useSSL, + sslEnabled: enableSSLCheckbox, + ); // parse port hack try { final uri = Uri.parse(newValue); @@ -1098,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; @@ -1109,11 +1162,28 @@ class _NodeFormState extends ConsumerState { enableSSLCheckbox = true; } } + if (_isGrinOnion(newValue)) { + // Onion nodes need Tor and plain HTTP. + _beforeOnion ??= previous; + netOption = TorPlainNetworkOption.tor; + _useSSL = false; + enableSSLCheckbox = false; + } else { + _restoreBeforeOnion(newValue); + } _updateState(); setState(() {}); }, ), ), + if (_grinHostError case final error?) + Padding( + padding: const EdgeInsets.only(left: 12, top: 4), + child: Align( + alignment: Alignment.centerLeft, + child: Text(error, style: STextStyles.errorSmall(context)), + ), + ), const SizedBox(height: 8), ClipRRect( borderRadius: BorderRadius.circular( @@ -1256,7 +1326,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, @@ -1303,7 +1373,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: [ @@ -1454,11 +1525,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( @@ -1549,11 +1622,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(); } @@ -1566,11 +1639,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 b131db831..52f53210c 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 @@ -50,11 +50,13 @@ import '../../../../../utilities/format.dart'; import '../../../../../utilities/logger.dart'; import '../../../../../utilities/prefs.dart'; import '../../../../../utilities/util.dart'; +import '../../../../../wallets/crypto_currency/coins/grin.dart'; import '../../../../../wallets/crypto_currency/intermediate/frost_currency.dart'; 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'; @@ -132,6 +134,7 @@ abstract class SWB { _cancelCompleter = null; _cancelCompleter = Completer(); _shouldCancelRestore = true; + if (!_cancelRequested.isCompleted) _cancelRequested.complete(); Logging.instance.d("SWB cancel restore requested"); } else { Logging.instance.d( @@ -145,6 +148,15 @@ abstract class SWB { static bool _shouldCancelRestore = false; + /// Completes when a cancel is requested, for a restore step that waits + /// longer than the checks of [_shouldCancelRestore] between steps allow. + static Completer _cancelRequested = Completer(); + + static void _endCancel() { + _shouldCancelRestore = false; + _cancelRequested = Completer(); + } + static bool _checkShouldCancel( PreRestoreState? revertToState, SecureStorageInterface secureStorageInterface, @@ -155,7 +167,7 @@ abstract class SWB { _revert(revertToState, secureStorageInterface, shopinbitService); } else { _cancelCompleter!.complete(); - _shouldCancelRestore = false; + _endCancel(); } return true; @@ -495,6 +507,10 @@ abstract class SWB { await wallet.init(isRestore: true); break; + case GrinWallet(): + await wallet.init(isRestore: true); + break; + default: await wallet.init(); } @@ -503,7 +519,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; @@ -571,6 +588,13 @@ abstract class SWB { } await restoringFuture; + // Its recover() only starts the scan. Exiting the wallet now would + // cancel it, and a wallet outside the startup sync would stay + // unscanned behind a success message. A cancel ends the wait: the + // scan can take hours, and the revert removes the wallet anyway. + if (wallet is GrinWallet && !await waitForGrinRecovery(wallet)) { + return false; + } final currentAddress = await wallet.getCurrentReceivingAddress(); @@ -694,6 +718,60 @@ abstract class SWB { // uiState?.notifications = RestoringState.done; } + /// The id each wallet in a backup is restored under: its own, unless a + /// wallet uses it or it waits to be deleted at the next start. The + /// startup cleanup removes whatever is stored under a queued id, so a + /// wallet restored under one would be deleted too. + /// Waits for [wallet]'s restore scan. False when a cancel was requested + /// first: the scan can take hours, and the revert removes the wallet. + @visibleForTesting + static Future waitForGrinRecovery(GrinWallet wallet) async { + await Future.any([wallet.waitForRecovery(), _cancelRequested.future]); + return !_shouldCancelRestore; + } + + /// Deletes the directory and password of each Grin wallet in [infos]. + /// Returns the ids whose files are still there, for the next start. + @visibleForTesting + static Future> deleteGrinWalletFiles( + Iterable infos, + SecureStorageInterface secureStorageInterface, + ) async { + final remaining = []; + for (final info in infos.where((e) => e.coin is Grin)) { + var deleted = false; + try { + deleted = await GrinWallet.deleteWalletFiles( + walletId: info.walletId, + secureStore: secureStorageInterface, + ); + } catch (e) { + Logging.instance.w("SWB revert: Grin files of ${info.walletId}: $e"); + } + if (!deleted) remaining.add(info.walletId); + } + return remaining; + } + + /// Clears a cancel that no restore will finish, in tests. + @visibleForTesting + static void debugEndCancel() => _endCancel(); + + @visibleForTesting + static Map restoredWalletIds( + Iterable backupIds, { + required Iterable currentWalletIds, + }) { + final taken = { + ...currentWalletIds, + ...DB.instance.values(boxName: DB.boxNameWalletsToDeleteOnStart), + }; + return { + for (final id in backupIds) + id: taken.contains(id) ? const Uuid().v1() : id, + }; + } + static Future restoreStackWalletJSON( String jsonBackup, StackRestoringUIState? uiState, @@ -725,14 +803,12 @@ abstract class SWB { final List wallets = validJSON["wallets"] as List; - // check for duplicate walletIds and assign new ones if required - for (final wallet in wallets) { - if (_currentWalletIds.contains(wallet["id"] as String)) { - oldToNewWalletIdMap[wallet["id"] as String] = const Uuid().v1(); - } else { - oldToNewWalletIdMap[wallet["id"] as String] = wallet["id"] as String; - } - } + oldToNewWalletIdMap.addAll( + restoredWalletIds( + wallets.map((wallet) => wallet["id"] as String), + currentWalletIds: _currentWalletIds, + ), + ); uiState?.decryption = StackRestoringStatus.success; @@ -1132,6 +1208,22 @@ abstract class SWB { .findAll()) .toSet(); final walletIdsToDelete = allWalletIds.difference(revertToState.walletIds); + // A Grin wallet also has a directory and a password outside its record. + // Left behind, they would refuse the same backup's next restore, which + // reuses the id. A busy directory is deleted at the next start. + final added = await MainDB.instance.isar.walletInfo.getAllByWalletId( + walletIdsToDelete.toList(), + ); + final busy = await deleteGrinWalletFiles( + added.nonNulls, + secureStorageInterface, + ); + for (final walletId in busy) { + await DB.instance.add( + boxName: DB.boxNameWalletsToDeleteOnStart, + value: walletId, + ); + } await MainDB.instance.isar.writeTxn(() async { await MainDB.instance.isar.walletInfo.deleteAllByWalletId( walletIdsToDelete.toList(), @@ -1139,7 +1231,7 @@ abstract class SWB { }); _cancelCompleter!.complete(); - _shouldCancelRestore = false; + _endCancel(); Logging.instance.d("Revert SWB complete"); } 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 7493cd0b7..e21e5cfcf 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,11 +76,16 @@ class _RestoringWalletCardState extends ConsumerState { await wallet.init(isRestore: true); break; + case GrinWallet(): + await wallet.init(isRestore: true); + break; + default: await wallet.init(); } await wallet.recover(isRescan: true); + if (wallet is GrinWallet) await wallet.waitForRecovery(); final address = await wallet.getCurrentReceivingAddress(); 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 55c177e39..dc9979e29 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,16 +34,21 @@ 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'; import '../../../../wallets/crypto_currency/coins/salvium.dart'; +import '../../../../wallets/crypto_currency/crypto_currency.dart' + show CryptoCurrency; 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.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; import '../../../../widgets/animated_text.dart'; @@ -64,6 +69,23 @@ import '../../sub_widgets/nodes_list.dart'; import 'sub_widgets/confirm_full_rescan.dart'; import 'sub_widgets/rescanning_dialog.dart'; +/// Whether the sync line shows the blocks still to go for [wallet]. Grin +/// counts blocks only while a scan is pending; a refresh has none to count. +@visibleForTesting +bool showsBlocksRemaining( + CryptoCurrency coin, + Wallet wallet, { + required bool mwebEnabled, +}) { + if (wallet is GrinWallet) return wallet.isScanPending; + return coin is Monero || + coin is Wownero || + coin is Epiccash || + coin is Salvium || + coin is Mimblewimblecoin || + (coin is Litecoin && mwebEnabled); +} + /// [eventBus] should only be set during testing class WalletNetworkSettingsView extends ConsumerStatefulWidget { const WalletNetworkSettingsView({ @@ -155,7 +177,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 +304,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,7 +394,23 @@ 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); + } } + final showBlocksRemaining = showsBlocksRemaining( + coin, + ref.watch(pWallets).getWallet(widget.walletId), + mwebEnabled: + coin is Litecoin && + ref.watch( + pWalletInfo(widget.walletId).select((s) => s.isMwebEnabled), + ), + ); return ConditionalParent( condition: !isDesktop, @@ -642,16 +683,7 @@ class _WalletNetworkSettingsViewState .accentColorYellow, ), ), - if (coin is Monero || - coin is Wownero || - coin is Epiccash || - coin is Salvium || - coin is Mimblewimblecoin || - (coin is Litecoin && - ref.watch( - pWalletInfo(widget.walletId) - .select((s) => s.isMwebEnabled), - ))) + if (showBlocksRemaining) Text( " (Blocks to go: ${_blocksRemaining == -1 ? "?" : _blocksRemaining})", style: STextStyles.syncPercent(context) 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 fc48d5e02..e8690392a 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'; @@ -588,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( 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 111f818b8..3d11bb159 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 @@ -2000,10 +2000,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 d464487ac..30df65a68 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 @@ -2200,7 +2200,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 5e6c6ac65..ca6521ce0 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'; @@ -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( diff --git a/lib/services/price.dart b/lib/services/price.dart index ab47c8ebc..6f5603e94 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 4f6448555..8d75407a8 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'; @@ -144,14 +146,7 @@ class Wallets { if (await directory.exists()) await directory.delete(recursive: true); } - await secureStorage.delete(key: Wallet.mnemonicKey(walletId: walletId)); - await secureStorage.delete( - key: Wallet.mnemonicPassphraseKey(walletId: walletId), - ); - await secureStorage.delete(key: Wallet.privateKeyKey(walletId: walletId)); - await secureStorage.delete( - key: Wallet.getViewOnlyWalletDataSecStoreKey(walletId: walletId), - ); + await _deleteWalletSecrets(walletId, secureStorage); if (isFrostWallet) { await BitcoinFrostWallet.deleteSecureStorage( @@ -186,6 +181,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 +477,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 +490,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() @@ -706,21 +724,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; + } + } + + /// The recovery phrase, passphrase, private key and view-only data the + /// creation and restore paths write for every coin. + static Future _deleteWalletSecrets( + String walletId, + SecureStorageInterface secureStorage, + ) async { + await secureStorage.delete(key: Wallet.mnemonicKey(walletId: walletId)); + await secureStorage.delete( + key: Wallet.mnemonicPassphraseKey(walletId: walletId), + ); + await secureStorage.delete(key: Wallet.privateKeyKey(walletId: walletId)); + await secureStorage.delete( + key: Wallet.getViewOnlyWalletDataSecStoreKey(walletId: walletId), + ); + } + + /// 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; + // Creation wrote the recovery phrase before the user confirmed it. + await _deleteWalletSecrets(walletId, nodeService.secureStorageInterface); 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 4af50c345..4550da4be 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 41db48fb3..006a44999 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/enums/slatepack_method.dart b/lib/utilities/enums/slatepack_method.dart index f24413655..a9b300652 100644 --- a/lib/utilities/enums/slatepack_method.dart +++ b/lib/utilities/enums/slatepack_method.dart @@ -4,10 +4,20 @@ enum SlatepackMethod { slatepack("Slatepack"), /// Automatic exchange through the coin's relay server (epicbox, mwcmqs). - relay("Automatic"); + relay("Automatic"), + + /// Direct send to the recipient's listener (http(s), Tor). + http("Address"); const SlatepackMethod(this.label); /// Label on the method toggle. final String label; + + static SlatepackMethod? fromName(String? name) { + for (final m in values) { + if (m.name == name) return m; + } + return null; + } } diff --git a/lib/utilities/native_library_check.dart b/lib/utilities/native_library_check.dart index 1bd621976..aa4b51680 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 000000000..b97fb6c6c --- /dev/null +++ b/lib/utilities/owner_only_directory.dart @@ -0,0 +1,62 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:meta/meta.dart'; + +import 'logger.dart'; + +typedef _ChmodNative = Int32 Function(Pointer, Uint32); +typedef _ChmodDart = int Function(Pointer, int); + +_ChmodDart? _chmod; + +/// Replaces chmod in tests. Returns what chmod returns: 0 on success. +@visibleForTesting +int Function(String path, int mode)? debugChmod; + +/// 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 override = debugChmod; + if (override != null) { + if (override(path, 448) != 0) { + throw FileSystemException("Could not restrict directory", path); + } + 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. +/// +/// A filesystem without Unix modes, such as FAT or exFAT, refuses the +/// change, and its mount options set the mode instead. A refused change is +/// accepted only when the directory already has no group or other access, +/// as a desktop automount of such a filesystem usually gives it. +Future createOwnerOnlyDirectory(String path) async { + final dir = Directory(path); + if (!await dir.exists()) await dir.create(recursive: true); + try { + restrictDirectoryToOwner(dir.path); + } on FileSystemException { + final mode = (await dir.stat()).mode; + if (mode & 0x3F != 0) rethrow; + Logging.instance.i( + "Could not set the mode of ${dir.path}; it is already owner-only.", + ); + } + return dir; +} diff --git a/lib/utilities/stack_file_system.dart b/lib/utilities/stack_file_system.dart index 292dda136..0ed5647e9 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 000000000..e917849c4 --- /dev/null +++ b/lib/utilities/test_grin_node_connection.dart @@ -0,0 +1,76 @@ +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, +/// and whether it is on [network]: both networks answer the tip request. +/// +/// Returns [data] with the scheme in its host, or null when the node cannot +/// be reached, is on the other network, or the Tor settings do not allow +/// it. The foreign API's calls need no API secret, so a missing secret does +/// not fail this. +Future testGrinNodeConnection( + NodeFormData data, { + required GrinNetwork network, + 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, + network: network, + ); + } 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 811e74664..3d3f768d0 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,19 @@ Future testNodeConnection({ } break; + case final Grin grin: + final data = await testGrinNodeConnection( + formData, + network: grin.grinNetwork, + 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 000000000..7b9ac5085 --- /dev/null +++ b/lib/wallets/crypto_currency/coins/grin.dart @@ -0,0 +1,197 @@ +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'; +import 'grin_checkpoints.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 plus one. A reward at height h is spendable from tip + /// h + 1440, and Stack counts the reward's own block as a confirmation. + @override + int get minCoinbaseConfirms => 1441; + + @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; + } + } + + /// A height to scan from that misses no block mined on or after [date], + /// for restore heights: the last checkpoint at least a day older than + /// [date], or 0. The day covers miners' clocks and a date picked as a + /// local midnight. A date past the last checkpoint gets the last one. + /// + /// Grin's block times vary too much for a count of blocks since genesis + /// to be safe: mainnet's first day ran about four times as fast as one a + /// minute, and testnet has had long stalls. + int heightFromDate(DateTime date) { + final checkpoints = network == CryptoCurrencyNetwork.main + ? grinMainnetCheckpoints + : grinTestnetCheckpoints; + final before = date.millisecondsSinceEpoch ~/ 1000 - 86400; + var height = 0; + for (final (checkpointHeight, time) in checkpoints) { + if (time > before) break; + height = checkpointHeight; + } + return height; + } + + /// 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/coins/grin_checkpoints.dart b/lib/wallets/crypto_currency/coins/grin_checkpoints.dart new file mode 100644 index 000000000..17e6ef739 --- /dev/null +++ b/lib/wallets/crypto_currency/coins/grin_checkpoints.dart @@ -0,0 +1,190 @@ +/// Grin block headers, one every 43,200 blocks (about 30 days), as +/// (height, timestamp in seconds since the epoch). Each was read from two +/// nodes per network, which agreed on every hash and timestamp: +/// grinnode.live and grincoin.org for mainnet, testapi.grin.money and +/// testnet.grincoin.org for testnet, at mainnet height 4,133,986 and +/// testnet height 3,364,759. +/// +/// Grin refuses a header whose timestamp is not later than its parent's, so +/// every block below a checkpoint is older than the checkpoint. +library; + +const grinMainnetCheckpoints = <(int, int)>[ + (0, 1547568086), + (43200, 1550173975), + (86400, 1552773954), + (129600, 1555376305), + (172800, 1557980239), + (216000, 1560581717), + (259200, 1563183577), + (302400, 1565783301), + (345600, 1568386938), + (388800, 1570991485), + (432000, 1573594689), + (475200, 1576197214), + (518400, 1578800655), + (561600, 1581405661), + (604800, 1584009901), + (648000, 1586612248), + (691200, 1589217081), + (734400, 1591820867), + (777600, 1594424440), + (820800, 1597028810), + (864000, 1599635406), + (907200, 1602240475), + (950400, 1604846861), + (993600, 1607453301), + (1036800, 1610060018), + (1080000, 1612664740), + (1123200, 1615259597), + (1166400, 1617878832), + (1209600, 1620478283), + (1252800, 1623072434), + (1296000, 1625679070), + (1339200, 1628276188), + (1382400, 1630867826), + (1425600, 1633459519), + (1468800, 1636057502), + (1512000, 1638655905), + (1555200, 1641251523), + (1598400, 1643850166), + (1641600, 1646446423), + (1684800, 1649045140), + (1728000, 1651640604), + (1771200, 1654246196), + (1814400, 1656844022), + (1857600, 1659441494), + (1900800, 1662037841), + (1944000, 1664630755), + (1987200, 1667229213), + (2030400, 1669828070), + (2073600, 1672419644), + (2116800, 1675019551), + (2160000, 1677616048), + (2203200, 1680214164), + (2246400, 1682812263), + (2289600, 1685411571), + (2332800, 1688009410), + (2376000, 1690608977), + (2419200, 1693207713), + (2462400, 1695805321), + (2505600, 1698400657), + (2548800, 1700998352), + (2592000, 1703593954), + (2635200, 1706188316), + (2678400, 1708786657), + (2721600, 1711384926), + (2764800, 1713982425), + (2808000, 1716581079), + (2851200, 1719180712), + (2894400, 1721780571), + (2937600, 1724377484), + (2980800, 1726975174), + (3024000, 1729570609), + (3067200, 1732168460), + (3110400, 1734764379), + (3153600, 1737362241), + (3196800, 1739958817), + (3240000, 1742558251), + (3283200, 1745157560), + (3326400, 1747757738), + (3369600, 1750352058), + (3412800, 1752940792), + (3456000, 1755542205), + (3499200, 1758140939), + (3542400, 1760738482), + (3585600, 1763332897), + (3628800, 1765931558), + (3672000, 1768526139), + (3715200, 1771122012), + (3758400, 1773715299), + (3801600, 1776313341), + (3844800, 1778912645), + (3888000, 1781512880), + (3931200, 1784117878), + (3974400, 1786716957), + (4017600, 1789315913), + (4060800, 1791910256), + (4104000, 1794510861), +]; + +const grinTestnetCheckpoints = <(int, int)>[ + (0, 1546030084), + (43200, 1549958302), + (86400, 1552710331), + (129600, 1556134963), + (172800, 1560555469), + (216000, 1564795255), + (259200, 1574201523), + (302400, 1577199796), + (345600, 1580209693), + (388800, 1582856414), + (432000, 1585541588), + (475200, 1588070002), + (518400, 1590550812), + (561600, 1593430808), + (604800, 1605155697), + (648000, 1607916432), + (691200, 1611542374), + (734400, 1615549480), + (777600, 1618398451), + (820800, 1620985635), + (864000, 1623600837), + (907200, 1626185591), + (950400, 1628774412), + (993600, 1631358918), + (1036800, 1638742570), + (1080000, 1641328872), + (1123200, 1644358089), + (1166400, 1646943912), + (1209600, 1650027139), + (1252800, 1652612556), + (1296000, 1655199068), + (1339200, 1657785037), + (1382400, 1660422771), + (1425600, 1663007613), + (1468800, 1669364735), + (1512000, 1671958394), + (1555200, 1674550793), + (1598400, 1677364585), + (1641600, 1679949256), + (1684800, 1682550841), + (1728000, 1685145889), + (1771200, 1687757605), + (1814400, 1690346589), + (1857600, 1695279863), + (1900800, 1697882059), + (1944000, 1700470062), + (1987200, 1703071228), + (2030400, 1705658813), + (2073600, 1708249500), + (2116800, 1714528516), + (2160000, 1718689865), + (2203200, 1721469406), + (2246400, 1727831819), + (2289600, 1730453448), + (2332800, 1733176854), + (2376000, 1735785288), + (2419200, 1738551990), + (2462400, 1741241953), + (2505600, 1743829344), + (2548800, 1746433496), + (2592000, 1749132353), + (2635200, 1751919707), + (2678400, 1754702449), + (2721600, 1757404531), + (2764800, 1760042774), + (2808000, 1762679405), + (2851200, 1765277153), + (2894400, 1767864102), + (2937600, 1770717903), + (2980800, 1773304781), + (3024000, 1775893946), + (3067200, 1778480508), + (3110400, 1781075389), + (3153600, 1783664626), + (3196800, 1786251659), + (3240000, 1788840314), + (3283200, 1791425797), + (3326400, 1794014229), +]; diff --git a/lib/wallets/crypto_currency/crypto_currency.dart b/lib/wallets/crypto_currency/crypto_currency.dart index d46382ea0..4a712d2e3 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 12329f8ce..c4f607e05 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 b6519b513..ce15cf230 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 000000000..cfaf0402d --- /dev/null +++ b/lib/wallets/wallet/impl/grin_wallet.dart @@ -0,0 +1,2049 @@ +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 and the wallet's transaction log. +/// +/// libwallet leaves locked outputs out of its total, so they are not +/// counted here either. Its amount awaiting finalization is every output of +/// an unconfirmed transaction: the change of the wallet's own sends, but +/// also what an S2 it answered or an invoice it issued would pay it, which +/// only arrives if the other wallet finalizes. Only the change, and both +/// halves of a send to itself, count as pending. +Balance grinBalanceToStack( + GrinBalance balance, + int fractionDigits, { + required List entries, +}) { + Amount amount(BigInt raw) => + Amount(rawValue: raw, fractionDigits: fractionDigits); + final unconfirmed = entries.where((e) => !e.confirmed).toList(); + final sentSlates = { + for (final e in unconfirmed) + if (e.type == GrinTxType.txSent && e.slateId != null) e.slateId, + }; + var own = BigInt.zero; + for (final e in unconfirmed) { + final isOwn = + e.type == GrinTxType.txSent || + (e.type == GrinTxType.txReceived && sentSlates.contains(e.slateId)); + if (isOwn) own += e.amountCredited; + } + final ownUnfinalized = own < balance.amountAwaitingFinalization + ? own + : balance.amountAwaitingFinalization; + final pending = + balance.amountAwaitingConfirmation + + balance.amountImmature + + ownUnfinalized; + 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; + + /// How long a node call waits for Tor to finish connecting. + @visibleForTesting + static Duration torConnectWait = const 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) { + try { + await walletDirPath(walletId); + } catch (_) { + continue; + } + try { + // Also when the directory is already gone: the password may not be. + 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; + + /// Completed by [_stopScanJob]. A job that has not handed its scan to the + /// library yet ends without starting it, and stops waiting for Tor. + Completer _scanStop = Completer(); + bool _exited = false; + + /// The scan job is inside the library's scan, where a cancel reaches it. + bool _scanInLibrary = false; + + /// A transport change cancelled a running scan, or a scan could not + /// start because the network was blocked. It is started again once the + /// library has a usable transport, whether or not this wallet syncs on + /// its own: a restore or rescan that was asked for keeps going. + bool _resumeScan = false; + + /// Starts the pending scan again after one failed, as when the node timed + /// out, whether or not this wallet syncs on its own. + Timer? _scanRetry; + int _scanFailures = 0; + + /// How long after [failures] failed scans in a row the next one starts. + @visibleForTesting + static Duration Function(int failures) scanRetryDelay = (failures) => + Duration(seconds: math.min(30 * (1 << math.min(failures - 1, 5)), 600)); + + /// Completed when the pending restore or rescan has scanned to the tip, + /// or with an error when it stopped short. Made by [waitForRecovery]. + Completer? _recovery; + + _AppliedNetwork? _applied; + final _transportMutex = Mutex(); + Completer? _torConnecting; + StreamSubscription? _torStatusSub; + StreamSubscription? _torPrefSub; + + /// The last node refresh could not reach the node. + bool _offline = false; + + /// Why the last open failed, until an open succeeds. + Object? _openError; + + /// 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. The scan the restore owes is recorded + /// first, so a start after an interrupted restore does not take the + /// wallet for a new one. + @override + Future init({bool? isRestore}) async { + final closing = _closing; + if (closing != null) await closing; + + if (isRestore == true) { + if (info.grinData == null) await _recordRestoreOwed(); + } else { + final pending = _initializing; + if (pending != null) { + await pending; + } else if (_api == null) { + final opening = _open(); + _initializing = opening; + try { + await opening; + _openError = null; + } catch (e) { + _openError = e; + rethrow; + } 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?.pendingScanFrom != null) { + // A restore stopped before it wrote the password, so before the + // wallet was created. The scan it owes rebuilds everything. + api = await _recreate(dir); + } 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; + _scanRetry?.cancel(); + _scanRetry = null; + 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)}", + ); + } + } + _endRecovery(GrinWalletException("The Grin wallet was closed.")); + 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); + } + // Closed part way, as when a restore is cancelled while the native + // wallet is created: its files are being deleted. + if (_exited) { + throw GrinWalletException( + "The ${isRescan ? "rescan" : "restore"} was cancelled.", + ); + } + unawaited(_runScanJob()); + } + + /// Waits until the restore or rescan [recover] started has scanned to the + /// chain tip. A scan that a transport change interrupts is resumed and + /// waited for. Throws when it stops short (closed, failed, or the network + /// is blocked): the wallet keeps its resume height, and a later refresh + /// or rescan carries on from there. + Future waitForRecovery() { + if (!_scanPending) return Future.value(); + if (_api == null || _exited) { + return Future.error( + GrinWalletException("The Grin wallet is not open."), + ); + } + final recovery = _recovery ??= Completer(); + // A job that already ended, for example on a blocked network, is + // tried once more; it ends this wait if it stops short again. + if (_scanJob == null) unawaited(_runScanJob()); + return recovery.future; + } + + void _endRecovery([Object? error]) { + final recovery = _recovery; + if (recovery == null || recovery.isCompleted) return; + _recovery = null; + if (error == null) { + recovery.complete(); + } else { + recovery.completeError(error); + } + } + + /// 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(); + await _recordRestoreOwed(); + _api = await _createFromMnemonic(dir); + } catch (e) { + await _releaseOwnership(); + rethrow; + } + }); + await _storeAddress(); + highestPercent = 0; + }); + } + + /// 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 taken for a new one, or scanned from the + /// first block by its first refresh. + Future _recordRestoreOwed() { + final height = info.restoreHeight; + return info.updateGrinData( + grinData: GrinWalletData(creationHeight: height, pendingScanFrom: height), + isar: mainDB.isar, + ); + } + + /// 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 { + // Nothing else starts a scan from the old resume height meanwhile, such + // as the resume after a transport change; it would hold the refresh + // lock for its whole scan before this one could mark its start. + _rescansWaiting++; + try { + _scanRetry?.cancel(); + _scanRetry = null; + await _stopScanJob(); + await _rescanUnlocked(); + } finally { + _rescansWaiting--; + } + } + + int _rescansWaiting = 0; + + Future _rescanUnlocked() async { + 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; + if (!_scanStop.isCompleted) _scanStop.complete(); + _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; + // The rescan starts its own once it has marked where to scan from. + if (_rescansWaiting > 0) return Future.value(); + _resumeScan = false; + _scanRetry?.cancel(); + _scanRetry = null; + late final Future job; + _scanStop = Completer(); + job = _scan().whenComplete(() { + if (identical(_scanJob, job)) _scanJob = null; + if (!_exited) ensurePeriodicRefreshTimer(); + }); + _scanJob = job; + return job; + } + + Future _scan() async { + var succeeded = false; + var nothingOwed = false; + Object? failure; + await refreshMutex.protect(() async { + final api = _api; + final from = info.grinData?.pendingScanFrom; + if (from == null) { + nothingOwed = true; + return; + } + if (api == null || _exited) return; + + _fireSyncStatus(WalletSyncStatus.syncing); + // The resume height follows the batches the library has saved, so a + // scan ended by the app quitting or the OS killing it resumes there. + var checkpointing = true; + var checkpoint = Future.value(); + var resumeFrom = from; + final timer = Timer.periodic(const Duration(seconds: 1), (_) { + final progress = _reportScanProgress(api); + if (progress == null || !checkpointing || !_scanInLibrary) return; + // Only the scan this job started; heights of an earlier one may + // still show until the library resets them. + if (!progress.isScanning || + progress.startHeight != math.max(from, 1) || + progress.savedHeight < resumeFrom) { + return; + } + final next = progress.savedHeight + 1; + resumeFrom = next; + checkpoint = checkpoint.then((_) async { + if (checkpointing) await _setPendingScanFrom(next); + }); + }); + try { + try { + await _requireNetwork(stop: _scanStop.future); + } catch (_) { + // Blocked (Tor off, the kill switch, an invalid node) or still + // connecting: the scan starts once a usable transport is applied. + if (!_exited && !_scanStop.isCompleted && !_transportUsable) { + _resumeScan = true; + } + rethrow; + } + // Stopped before it started: nothing was scanned. + if (_scanStop.isCompleted) return; + _scanInLibrary = true; + try { + await api.scan(startHeight: from); + } finally { + _scanInLibrary = false; + // No checkpoint may land after the end of the scan is saved. + checkpointing = false; + await checkpoint; + } + await _setPendingScanFrom(null); + succeeded = true; + } on GrinCancelledException catch (e) { + await _saveScanProgress(e, from); + if (!_resumeScan) { + failure = GrinWalletException("The Grin scan was cancelled."); + } + } catch (e) { + // Closing or a rescan deliberately wakes a scan waiting for Tor. That + // is normal cancellation, not a sync failure to show to the user. + if (_exited || _scanStop.isCompleted) 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)}"); + failure = sanitizeGrinError(e); + _fireSyncStatus(WalletSyncStatus.unableToSync); + // A blocked network resumes the scan when a transport is applied. + if (!_resumeScan) _scheduleScanRetry(); + } finally { + timer.cancel(); + } + }); + if (succeeded) _scanFailures = 0; + if (succeeded || nothingOwed) { + _endRecovery(); + } else if (failure != null) { + _endRecovery(failure); + } + if (succeeded && !_exited) { + highestPercent = 1; + _fireScanProgress(0); + await refresh(); + } + } + + void _scheduleScanRetry() { + _scanRetry?.cancel(); + _scanFailures++; + _scanRetry = Timer(scanRetryDelay(_scanFailures), () { + _scanRetry = null; + if (_exited || _api == null || !_scanPending) return; + unawaited(_runScanJob()); + }); + } + + /// 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); + } + + GrinScanProgress? _reportScanProgress(GrinWalletApi api) { + try { + final progress = api.scanProgress(); + if (!progress.isScanning || progress.tipHeight <= 0) return progress; + highestPercent = math.max( + highestPercent, + _scanPercent(scanned: progress.scannedHeight, tip: progress.tipHeight), + ); + _fireScanProgress( + math.max(progress.tipHeight - progress.scannedHeight, 0), + ); + return progress; + } catch (_) { + // Closed under us; the scan ends with it. + return null; + } + } + + /// How much of the whole restore or rescan is done. The library's own + /// percent covers only the current run, which starts again at zero when a + /// scan resumes, so this measures from the restore height that every scan + /// starts from. + double _scanPercent({required int scanned, required int tip}) { + final origin = info.restoreHeight; + if (tip <= origin) return 1; + return ((scanned - origin) / (tip - origin)).clamp(0.0, 1.0); + } + + void _fireScanProgress(int blocksRemaining) { + if (doNotFireRefreshEvents) return; + _bus.fire(RefreshPercentChangedEvent(highestPercent, walletId)); + _bus.fire(BlocksRemainingEvent(blocksRemaining, walletId)); + } + + /// The restore or rescan percentage while one is pending, else 0, so a + /// finished scan does not cover the progress of later refreshes. + double get restoreProgress => _scanPending ? highestPercent : 0; + + 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. + /// + /// A wallet whose open failed reports that it cannot sync, rather than + /// leaving its cached state looking synchronized. + @override + Future refresh() async { + if (_exited) return; + if (_api == null) { + final error = _openError; + if (error != null) { + Logging.instance.w( + "Grin wallet is not open: ${describeGrinError(error)}", + ); + _fireDisconnected(); + } + 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); + // The default node's URL is only a placeholder for the library while + // the network is blocked; the selected node's secret is not for it. + return (nodeUrl: url, apiSecret: null, transport: transport); + } + return (nodeUrl: url, apiSecret: node.nodeApiSecret, transport: transport); + } + + bool get _transportUsable { + final transport = _resolveNetwork().transport; + return transport is GrinDirect || transport is GrinProxy; + } + + void _subscribeTor() { + _torStatusSub ??= _bus.on().listen(( + event, + ) { + switch (event.newStatus) { + case TorConnectionStatus.connecting: + _torConnecting ??= Completer(); + // Holds a transport that was falling back to clearnet. + _applyTransportInBackground(); + case TorConnectionStatus.connected: + case TorConnectionStatus.disconnected: + _releaseTorWaiters(); + _applyTransportInBackground(); + } + }); + _torPrefSub ??= _bus.on().listen( + (_) => _applyTransportInBackground(), + ); + // The kill switch fires no event; without this a running scan would keep + // a clearnet transport after it is turned on. + if (_killSwitch == null) { + _killSwitch = prefs.torKillSwitch; + prefs.addListener(_onPrefsChanged); + } + } + + bool? _killSwitch; + + void _onPrefsChanged() { + final killSwitch = prefs.torKillSwitch; + if (killSwitch == _killSwitch) return; + _killSwitch = killSwitch; + _applyTransportInBackground(); + } + + /// For listeners, which have no caller to report to. The next node call + /// applies the transport again and reports the error there. + void _applyTransportInBackground() { + unawaited( + _applyTransport().catchError((Object e) { + Logging.instance.w( + "Grin transport not applied: ${describeGrinError(e)}", + ); + }), + ); + } + + 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; + if (_killSwitch != null) { + prefs.removeListener(_onPrefsChanged); + _killSwitch = 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 starts again from its + /// saved resume height once a transport is usable, also for a wallet that + /// does not sync on its own. + 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 && _applied?.transport is! GrinDirect) { + return false; + } + if (network == _applied) return false; + + if (_scanJob != null) { + cancelledScan = _scanJob; + _resumeScan = true; + api.cancelScan(); + } + await api.updateNetwork( + nodeUrl: network.nodeUrl, + apiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + networkEnabled: transport is GrinDirect || transport is GrinProxy, + ); + _applied = network; + return true; + }); + if (!changed) { + // A scan that gave up waiting for Tor, which then connected through + // the proxy already applied: nothing changed, but the scan is owed. + if (_resumeScan && _transportUsable) unawaited(_resumeScanAfter(null)); + return; + } + + // On hold: the Tor event that ends the wait applies the next transport + // and refreshes. + if (_applied?.transport is GrinHold) return; + + if (_applied?.transport is GrinBlocked) { + _fireDisconnected(); + // The scan resumes when the network is usable again, but whoever + // waits for the recovery is told now. + _endRecovery( + GrinWalletException("The Grin wallet's network is blocked."), + ); + return; + } + if (_resumeScan) unawaited(_resumeScanAfter(cancelledScan)); + 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()); + } + } + + /// Starts the scan a transport change cancelled, once the cancelled job + /// has saved its resume height. + Future _resumeScanAfter(Future? cancelled) async { + if (cancelled != null) await cancelled; + if (!_resumeScan || _exited || _api == null) return; + if (!_scanPending) { + _resumeScan = false; + return; + } + unawaited(_runScanJob()); + } + + /// The node, secret and transport for a node call, after waiting out a + /// Tor connect, or until [stop] completes. All three come from one read + /// made after the wait. Throws when the network is blocked. + Future<_AppliedNetwork> _usableNetwork({Future? stop}) async { + var network = _resolveNetwork(); + if (network.transport is GrinHold) { + final waiter = _torConnecting ??= Completer(); + await Future.any([waiter.future, ?stop]) + .timeout(torConnectWait, onTimeout: () {}); + network = _resolveNetwork(); + } + return switch (network.transport) { + GrinHold() => throw GrinWalletException("Tor is still connecting."), + GrinBlocked(:final reason) => throw _blockedException(reason), + GrinDirect() || GrinProxy() => network, + }; + } + + 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({Future? stop}) async { + _requireApi(); + await _usableNetwork(stop: stop); + await _applyTransport(refreshAfter: false); + final transport = _applied?.transport; + if (transport is GrinBlocked) throw _blockedException(transport.reason); + // Tor started connecting after the wait above, and the library's network + // is off until it connects. + if (transport is GrinHold) { + throw GrinWalletException("Tor is still connecting."); + } + return _requireApi(); + } + + GrinWalletApi _requireApi() { + final api = _api; + if (api == null || _exited) { + final error = _openError; + if (error != null && !_exited) { + final reason = sanitizeGrinError(error).toString(); + throw GrinWalletException( + "The Grin wallet could not be opened. $reason", + ); + } + throw GrinWalletException("The Grin wallet is not open."); + } + return api; + } + + static const _scanningMessage = + "Wait for the Grin wallet to finish scanning and try again."; + + void _refuseWhileScanning() { + if (_scanPending) throw GrinWalletException(_scanningMessage); + } + + 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 network = await _usableNetwork(); + final transport = network.transport; + final nodeInfo = await backend.testNodeConnection( + nodeUrl: network.nodeUrl, + apiSecret: network.apiSecret, + socksProxy: transport is GrinProxy ? transport.address : null, + network: cryptoCurrency.grinNetwork, + ); + 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, + network: cryptoCurrency.grinNetwork, + ); + 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, kernelLookup: fromNode && !_offline); + } catch (e) { + throw _fail("updateTransactions", e); + } + } + + /// Stores the library's history. With [kernelLookup], a confirmed entry + /// that has no height from the library and none stored gets the height of + /// the block holding its kernel from the node. The library only knows the + /// height of a transaction from an unspent output of ours, so a send with + /// no change has none. + Future _storeTransactions( + GrinTxList list, { + bool kernelLookup = false, + }) 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, + }; + if (kernelLookup) { + await _lookUpKernelHeights(list.transactions, storedHeights); + } + + final transactions = mapGrinTransactions( + entries: list.transactions, + walletId: walletId, + ownAddress: (await getCurrentReceivingAddress())?.value, + storedHeights: storedHeights, + chainHeight: info.cachedChainHeight, + fractionDigits: cryptoCurrency.fractionDigits, + ); + await mainDB.updateOrPutTransactionV2s(transactions); + } + + /// Adds to [heights] the kernel heights of confirmed entries that have no + /// height yet. An entry whose lookup fails is tried again on the next + /// refresh. + Future _lookUpKernelHeights( + List entries, + Map heights, + ) async { + final api = _api; + if (api == null) return; + final withHeight = { + for (final entry in entries) + if (entry.confirmedHeight != null) grinTxid(entry), + }; + for (final entry in entries) { + final txid = grinTxid(entry); + final excess = entry.kernelExcess; + if (!entry.confirmed || + excess == null || + withHeight.contains(txid) || + heights[txid] != null) { + continue; + } + try { + final height = await api.kernelHeight( + excess: excess, + minHeight: entry.kernelLookupMinHeight, + ); + if (height != null) heights[txid] = height; + } catch (e) { + Logging.instance.w( + "Grin kernel height lookup failed: ${describeGrinError(e)}", + ); + } + } + } + + @override + Future updateBalance() async { + final api = _api; + if (api == null || _exited) return; + try { + final balance = await api.getBalance( + refreshFromNode: false, + minimumConfirmations: cryptoCurrency.minConfirms, + ); + final txs = await api.getTransactions(refreshFromNode: false); + await info.updateBalance( + newBalance: grinBalanceToStack( + balance, + cryptoCurrency.fractionDigits, + entries: txs.transactions, + ), + 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. The + /// wallet info's cached copy, which the receive screen reads, follows it. + 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, + ), + ]); + await info.updateReceivingAddress( + newAddress: address.slatepackAddress, + isar: mainDB.isar, + ); + } + + // ========== 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); + if (kind == GrinAddressKind.onion || kind == GrinAddressKind.http) { + return SlatepackMethod.http; + } + // A caller that does not ask for a Slatepack, such as an exchange send, + // would lock the inputs and never hand the S1 to the recipient. + throw GrinWalletException( + "Send Grin to a Slatepack address from the wallet's Send screen.", + ); + } + + 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); + // What the user reviewed. The library selects inputs again and + // refuses, before locking or sending anything, a send whose fee or + // net amount comes out different. + final expectedFee = fee == null ? null : _nano(fee); + final expectedAmount = _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, + expectedFee: expectedFee, + expectedAmount: expectedAmount, + ); + 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, + expectedFee: expectedFee, + expectedAmount: expectedAmount, + ), + ); + unawaited(refresh()); + return txData.copyWith( + txid: result.slateId, + fee: _amount(result.fee), + ); + } + } catch (e) { + await _storeHistoryAfterFailure(); + throw _fail("confirmSend", e); + } + } + + /// For a send-side call that failed. The library may already hold a + /// transaction for it (inputs locked, or a slate finalized but not + /// posted), so its history is stored before the error is shown and the + /// entry the error names is in the list. + Future _storeHistoryAfterFailure() async { + final api = _api; + if (api == null || _exited || _scanPending) return; + try { + await _storeTransactions( + await api.getTransactions(refreshFromNode: false), + ); + } catch (e) { + Logging.instance.w( + "Grin history not stored after a failed call: " + "${describeGrinError(e)}", + ); + } + unawaited(refresh()); + } + + Future _initSend({ + required BigInt amount, + required String? recipientAddress, + required bool sendAll, + BigInt? expectedFee, + BigInt? expectedAmount, + }) async { + _refuseWhileScanning(); + final api = await _requireNetwork(); + return await api.initSend( + GrinSendArgs( + amount: amount, + minimumConfirmations: cryptoCurrency.minConfirms, + selectionStrategyIsAll: sendAll, + amountIncludesFee: sendAll, + recipientAddress: recipientAddress, + ttlBlocks: slatepackTtlBlocks, + expectedFee: expectedFee, + expectedAmount: expectedAmount, + ), + ); + } + + @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. The scan holds the + /// native wallet until it ends, so during one a plain Slatepack is read + /// without the wallet and an encrypted one is refused. + Future inspectSlatepack(String armored) async { + try { + if (_scanPending) { + try { + return await backend.decodeSlatepackWithoutWallet( + armored, + cryptoCurrency.grinNetwork, + ); + } on GrinSlateException { + // Not readable without the wallet, which is busy until the scan + // ends. An encrypted Slatepack and a damaged one look the same + // here. + throw GrinWalletException( + "This Slatepack cannot be read while the Grin wallet is scanning. " + "If it is encrypted, wait for the scan to finish and try again.", + ); + } + } + 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. + /// + /// With [expectedFee], the fee the user reviewed, a send whose fee or net + /// amount comes out different is refused before anything is locked. + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + bool sendAll = false, + Amount? expectedFee, + }) 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 fee = expectedFee == null ? null : _nano(expectedFee); + final result = await _initSend( + amount: _nano(amount), + recipientAddress: (address?.isEmpty ?? true) ? null : address, + sendAll: sendAll, + expectedFee: fee, + expectedAmount: fee == null + ? null + : sendAll + ? _nano(amount) - fee + : _nano(amount), + ); + unawaited(refresh()); + return result; + } catch (e) { + await _storeHistoryAfterFailure(); + throw _fail("createSlatepack", e); + } + } + + /// Answers an S1 and returns the S2. + Future receiveSlatepack(String s1) async { + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.receiveSlatepack(s1); + unawaited(refresh()); + return result; + } catch (e) { + await _storeHistoryAfterFailure(); + throw _fail("receiveSlatepack", e); + } + } + + /// Finalizes a send from its S2 and broadcasts it. + Future finalizeSlatepack(String s2) async { + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.finalizeSlatepack(s2); + unawaited(refresh()); + return result; + } catch (e) { + await _storeHistoryAfterFailure(); + throw _fail("finalizeSlatepack", e); + } + } + + /// Requests a payment and returns the I1. + Future issueInvoice({ + required Amount amount, + String? payerAddress, + }) async { + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.issueInvoice( + GrinInvoiceArgs(amount: _nano(amount), recipientAddress: payerAddress), + ); + unawaited(refresh()); + return result; + } catch (e) { + await _storeHistoryAfterFailure(); + 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) { + await _storeHistoryAfterFailure(); + throw _fail("processInvoice", e); + } + } + + /// Finalizes an invoice from its I2 and broadcasts it. + Future finalizeInvoice(String i2) async { + try { + _refuseWhileScanning(); + final api = await _requireNetwork(); + final result = await api.finalizeInvoice(i2); + unawaited(refresh()); + return result; + } catch (e) { + await _storeHistoryAfterFailure(); + 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 { + _refuseWhileScanning(); + 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."); + } + // The details screen can still offer repost after the transaction + // confirmed while it was open. + if ((tx.height ?? 0) > 0) { + throw GrinWalletException("This transaction is already confirmed."); + } + _refuseWhileScanning(); + 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."); + } + _refuseWhileScanning(); + final owner = _decode(tx.otherData!)[TxV2OdKeys.grinPaymentProofLogId]; + final logIds = _logIds(tx); + final proof = await _requireApi().exportPaymentProof( + txId: owner is int ? owner : (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."); + } + _refuseWhileScanning(); + 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 000000000..ce396d2ea --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_errors.dart @@ -0,0 +1,174 @@ +import 'package:grin_native/grin_native.dart'; + +import '../../../../exceptions/sw_exception.dart'; +import '../../../../exceptions/wallet/insufficient_balance_exception.dart'; +import '../../../../exceptions/wallet/node_tor_mismatch_config_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, + this.finalized = false, + this.released = false, + this.termsChanged = false, + }); + + /// 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; + + /// The library finalized and stored the transaction before the call + /// failed. + final bool finalized; + + /// The library cancelled the transaction again before the call returned: + /// nothing is locked and nothing was sent. + final bool released; + + /// The send was refused because its fee or amount came out different + /// from what the user reviewed. Nothing was locked or sent. + final bool termsChanged; + + /// A finalized transaction whose broadcast failed. Offer repost. + bool get finalizedNotBroadcast => finalized && slateId != null; + + /// The call failed and left a transaction in the wallet that is neither + /// finalized nor cancelled. Its inputs may be locked. + bool get leftPendingTransaction => slateId != null && !finalized && !released; +} + +/// Shown for a call that failed after the transaction was finalized. +const grinFinalizedNotBroadcastMessage = + "The transaction was finalized but the node did not accept it. " + "You can try to repost it."; + +/// Shown for a send the library cancelled again after it failed. +const grinReleasedMessage = + "The transaction could not be completed. Nothing was sent and no funds " + "are locked."; + +/// Shown for a send whose fee or amount changed after the user reviewed it. +const grinTermsChangedMessage = + "The fee or amount of this send changed after you reviewed it, because " + "the wallet's spendable funds changed. Nothing was sent or locked. " + "Review the send again."; + +/// Shown for a node that is on the other Grin network. +const grinWrongNetworkMessage = + "This Grin node is on a different network than the wallet."; + +/// Added to the message of a call that failed and left a transaction behind. +const grinLeftPendingNote = + "The transaction is still in this wallet and may hold funds locked. " + "Open it in the transaction history to cancel it."; + +/// 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; + // The wallet's own text about the node and the Tor setting. + if (error is NodeTorMismatchConfigException) { + return GrinWalletException(error.message); + } + if (error is! GrinException) { + return GrinWalletException("Grin wallet error (${error.runtimeType})"); + } + + final base = 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() => "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 GrinTransactionException && error.termsChanged) { + return GrinWalletException( + grinTermsChangedMessage, + type: "${error.runtimeType}", + code: error.code, + termsChanged: true, + ); + } + if (error is GrinNodeException && error.wrongNetwork) { + return GrinWalletException( + grinWrongNetworkMessage, + type: "${error.runtimeType}", + code: error.code, + ); + } + + // Not found carries the slate id it looked for, but no transaction of + // this wallet is left pending: the slate is unknown here, or finalized + // already. Cancelling a finalized one would drop its change. + final slateId = error is GrinNotFoundException ? null : error.slateId; + final String message; + if (slateId == null) { + message = base; + } else if (error.finalized) { + message = grinFinalizedNotBroadcastMessage; + } else if (error.released) { + message = grinReleasedMessage; + } else { + message = "$base $grinLeftPendingNote"; + } + + if (error is GrinInsufficientFundsException) { + return InsufficientBalanceException(message); + } + + return GrinWalletException( + message, + type: "${error.runtimeType}", + code: error.code, + slateId: slateId, + finalized: slateId != null && error.finalized, + released: slateId != null && error.released, + ); +} 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 000000000..f5d05a149 --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_node_url.dart @@ -0,0 +1,85 @@ +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."); + } + // Uri.parse percent-encodes what a host cannot hold, such as a space, + // and the library would refuse the result when the wallet opens. + final validHost = uri.host.contains(":") + ? RegExp(r"^[0-9a-f:.]+$").hasMatch(uri.host) + : RegExp(r"^[a-z0-9._-]+$").hasMatch(uri.host); + if (!validHost) { + throw GrinNodeUrlException( + "The node address has characters a host name cannot have.", + ); + } + 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 000000000..b9558a3b3 --- /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 000000000..e74bb014d --- /dev/null +++ b/lib/wallets/wallet/supporting/grin/grin_tx_mapping.dart @@ -0,0 +1,249 @@ +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, +/// and the kernel heights looked up for entries the library has no height +/// for. [chainHeight] is used for a confirmed entry with no height at all +/// and no kernel to look up, such as funds found by a scan. One with a +/// kernel stays unconfirmed until its kernel height is known: the chain +/// height when it was first seen can be far above the block it is in. +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: _withoutSuperseded(group), + walletId: walletId, + ownAddress: ownAddress, + storedHeight: storedHeights[txid], + chainHeight: chainHeight, + fractionDigits: fractionDigits, + ), + ]; +} + +/// Drops a cancelled entry that a later entry of the same direction +/// replaced, so each direction counts once. +/// +/// The library refuses an S1 that the wallet already received, unless that +/// receive was cancelled. Receiving it again then logs another entry under +/// the same slate id. Only a live entry holds funds; with none, the latest +/// cancelled one stands for the transaction. +List _withoutSuperseded(List group) { + if (group.length < 2) return group; + bool replaced(GrinTxLogEntry e) { + final live = switch (e.type) { + GrinTxType.txSentCancelled => GrinTxType.txSent, + GrinTxType.txReceivedCancelled => GrinTxType.txReceived, + _ => null, + }; + if (live == null) return false; + return group.any( + (other) => + other.type == live || (other.type == e.type && other.id > e.id), + ); + } + + return [ + for (final e in group) + if (!replaced(e)) e, + ]; +} + +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; + + final kernelExcess = group + .map((e) => e.kernelExcess) + .whereType() + .firstOrNull; + + int? height; + if (confirmed) { + height = + group.map((e) => e.confirmedHeight).whereType().firstOrNull ?? + storedHeight ?? + (chainHeight > 0 && kernelExcess == null ? 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, + ), + ]; + + // The library exports a proof only with both signatures and the kernel, + // and from the row that holds it. + final proofOwner = group + .where( + (e) => + e.paymentProof != null && + e.paymentProof!.receiverSignaturePresent && + e.paymentProof!.senderSignaturePresent && + e.kernelExcess != null, + ) + .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: proofOwner != null, + TxV2OdKeys.grinPaymentProofLogId: proofOwner?.id, + 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 000000000..f00885a2d --- /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 7a8f79c9d..4e0e1ee7f 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'; @@ -396,6 +397,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 89b7f2b77..87f8a39cc 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'; String _normalizeSlateId(String slateId) => slateId.trim().toLowerCase(); @@ -405,6 +406,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 000000000..c1540f433 --- /dev/null +++ b/lib/wl_gen/interfaces/libgrin_interface.dart @@ -0,0 +1,13 @@ +import 'package:grin_native/grin_native.dart'; + +export '../generated/libgrin_interface_impl.dart'; + +/// Selects the native Grin backend. The rest of the app uses the API that +/// grin_native re-exports, so every app config depends on grin_native. Only +/// an app configured with GRIN builds its library, and in any other the +/// backend throws instead of calling the missing library. +abstract class LibGrinInterface { + const LibGrinInterface(); + + GrinWalletBackend get backend; +} diff --git a/pubspec.lock b/pubspec.lock index 1a56118de..07c80da8c 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: 001df2a47375dc03b7d5a8024b53d96f458cccaf + resolved-ref: 001df2a47375dc03b7d5a8024b53d96f458cccaf + 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 6f41d27b7..65e3d0cfb 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="" diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index b02fa80fc..19e984716 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -64,6 +64,16 @@ dependencies: # ref: d4852f3ebaaef20d71a8954098634af8e25c3b50 # %%END_ENABLE_MWC%% +# grin_native re-exports the shared Grin API and builds the grin-ffi Rust +# library in its hook. Every app depends on it because lib/ uses that API +# directly; the GRIN flag decides whether the library is built and bundled +# (hooks.user_defines below) and selects the native backend. + grin_native: + git: + url: https://github.com/cypherstack/grin_native.git + path: packages/grin_native + ref: 001df2a47375dc03b7d5a8024b53d96f458cccaf + # %%ENABLE_TOR%% # tor_ffi_plugin: # git: @@ -384,6 +394,10 @@ hooks: flutter_libmwc: build: PLACEHOLDER_DNIX_BUILD_MODE wsl_distribution: PLACEHOLDER_DNIX_WSL_DISTRIBUTION + # Not a dnix package. process_pubspec_deps.dart sets this to true only for + # apps configured with GRIN; the others neither build nor bundle grin-ffi. + grin_native: + enabled: PLACEHOLDER_IF_GRIN # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/scripts/ensure_test_app_config.sh b/scripts/ensure_test_app_config.sh index 696c853b4..829b2d79d 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/native_build_config_test.dart b/scripts/tests/native_build_config_test.dart index ab215d173..c353b35df 100644 --- a/scripts/tests/native_build_config_test.dart +++ b/scripts/tests/native_build_config_test.dart @@ -221,6 +221,11 @@ void main(List args) { ) as YamlMap; final dependencies = (pubspec['dependencies'] as YamlMap).keys.toSet(); expect(dependencies.intersection(allPackages), enabledDnixPackages(app)); + final defines = (pubspec['hooks'] as YamlMap)['user_defines'] as YamlMap; + expect(dependencies, contains('grin_native')); + expect(defines['grin_native'], { + 'enabled': app == 'stack_wallet', + }, reason: 'only an app configured with GRIN builds grin-ffi'); } } @@ -228,7 +233,7 @@ void main(List args) { final text = File(p.join(root.path, 'pubspec.yaml')).readAsStringSync(); final pubspec = loadYaml(text) as YamlMap; final defines = (pubspec['hooks'] as YamlMap)['user_defines'] as YamlMap; - expect(defines.keys.toSet(), allPackages); + expect(defines.keys.toSet(), {...allPackages, 'grin_native'}); for (final package in allPackages) { expect(defines[package], { 'build': mode, @@ -236,6 +241,7 @@ void main(List args) { }); } expect(text, isNot(contains('PLACEHOLDER_DNIX_BUILD_MODE'))); + expect(text, isNot(contains('PLACEHOLDER_IF_'))); expect(text, isNot(contains('native_build:'))); expect(text, isNot(contains('prebuilt_manifest_'))); expect(text, isNot(contains('PLACEHOLDER_DNIX_WSL_DISTRIBUTION'))); diff --git a/test/pages/settings_views/stack_backup_views/restored_wallet_ids_test.dart b/test/pages/settings_views/stack_backup_views/restored_wallet_ids_test.dart new file mode 100644 index 000000000..0c6ac0506 --- /dev/null +++ b/test/pages/settings_views/stack_backup_views/restored_wallet_ids_test.dart @@ -0,0 +1,36 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/db/hive/db.dart'; +import 'package:stackwallet/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart'; + +void main() { + late Directory root; + + setUp(() async { + root = await Directory.systemTemp.createTemp('stack_swb_ids_'); + DB.instance.hive.init(root.path); + await DB.instance.hive.openBox(DB.boxNameWalletsToDeleteOnStart); + }); + tearDown(() async { + await DB.instance.hive.close(); + await root.delete(recursive: true); + }); + + test('a backup restores a deleted wallet under a new id while the old one ' + 'waits for the startup cleanup', () async { + await DB.instance.add( + boxName: DB.boxNameWalletsToDeleteOnStart, + value: 'deleted', + ); + final ids = SWB.restoredWalletIds( + ['deleted', 'open', 'new'], + currentWalletIds: ['open'], + ); + expect(ids.keys, ['deleted', 'open', 'new']); + expect(ids['deleted'], isNot('deleted')); + expect(ids['open'], isNot('open')); + expect(ids['deleted'], isNot(ids['open'])); + expect(ids['new'], 'new'); + }); +} diff --git a/test/utilities/native_library_check_test.dart b/test/utilities/native_library_check_test.dart index 7a8d0ad40..4da681e8c 100644 --- a/test/utilities/native_library_check_test.dart +++ b/test/utilities/native_library_check_test.dart @@ -2,8 +2,10 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:logger/logger.dart'; +import 'package:stackwallet/app_config.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/native_library_check.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; const _exe = r"C:\Program Files\Stack Wallet\stack_wallet.exe"; const _dll = "monero_libwallet2_api_c.dll"; @@ -140,6 +142,21 @@ void main() { expect(failures.first.result.path, _path); }); + test("a missing Grin library is reported only in an app with Grin", () { + final failures = _startup({"grin_ffi.dll"}); + if (AppConfig.coins.whereType().isEmpty) { + // Stack Duo and Campfire do not build or bundle it. + expect(failures, isEmpty); + return; + } + 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 +204,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/utilities/owner_only_directory_test.dart b/test/utilities/owner_only_directory_test.dart new file mode 100644 index 000000000..dfd1c5424 --- /dev/null +++ b/test/utilities/owner_only_directory_test.dart @@ -0,0 +1,45 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:stackwallet/utilities/owner_only_directory.dart'; + +void main() { + final unix = Platform.isLinux || Platform.isMacOS; + late Directory root; + + setUp(() async { + root = await Directory.systemTemp.createTemp('owner_only_'); + }); + tearDown(() async { + debugChmod = null; + await root.delete(recursive: true); + }); + + int mode(String path) => FileStat.statSync(path).mode & 0x1FF; + + Future setMode(String path, String octal) async { + final r = await Process.run('chmod', [octal, path]); + expect(r.exitCode, 0, reason: '${r.stderr}'); + } + + test('a new directory is owner-only', () async { + final dir = await createOwnerOnlyDirectory(p.join(root.path, 'a', 'b')); + expect(mode(dir.path), 0x1C0); + }, skip: !unix); + + test('a refused mode change is accepted only for an owner-only ' + 'directory', () async { + debugChmod = (_, _) => -1; + final locked = Directory(p.join(root.path, 'locked'))..createSync(); + await setMode(locked.path, '700'); + await createOwnerOnlyDirectory(locked.path); + + final open = Directory(p.join(root.path, 'open'))..createSync(); + await setMode(open.path, '755'); + await expectLater( + createOwnerOnlyDirectory(open.path), + throwsA(isA()), + ); + }, skip: !unix); +} diff --git a/test/wallets/grin/grin_balance_test.dart b/test/wallets/grin/grin_balance_test.dart new file mode 100644 index 000000000..ba6726237 --- /dev/null +++ b/test/wallets/grin/grin_balance_test.dart @@ -0,0 +1,100 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:grin_native/grin_native.dart'; +import 'package:stackwallet/wallets/wallet/impl/grin_wallet.dart'; + +import '../support/grin_fakes.dart'; + +void main() { + BigInt raw(int whole) => BigInt.from(whole) * BigInt.from(1000000000); + GrinBalance balance({ + int spendable = 0, + int awaitingFinalization = 0, + int awaitingConfirmation = 0, + int locked = 0, + }) => balanceOf( + spendable: spendable * 1000000000, + awaitingFinalization: awaitingFinalization * 1000000000, + awaitingConfirmation: awaitingConfirmation * 1000000000, + locked: locked * 1000000000, + ); + + test('an invoice the wallet issued is not counted until it is paid', () { + // 100 held, an invoice for 1,000 issued. + final b = grinBalanceToStack( + balance(spendable: 100, awaitingFinalization: 1000), + 9, + entries: [ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.i1, + credited: 1000 * 1000000000, + fee: null, + ), + ], + ); + expect(b.total.raw, raw(100)); + expect(b.pendingSpendable.raw, BigInt.zero); + }); + + test('an S2 the wallet answered is not counted until it confirms', () { + final b = grinBalanceToStack( + balance(spendable: 100, awaitingFinalization: 50), + 9, + entries: [ + entryOf( + id: 1, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 50 * 1000000000, + fee: null, + ), + ], + ); + expect(b.total.raw, raw(100)); + }); + + test('the change of an unconfirmed send stays pending', () { + // 360 held, 50 sent: the 360 is locked and 309 comes back as change. + final b = grinBalanceToStack( + balance(locked: 360, awaitingFinalization: 309), + 9, + entries: [ + entryOf(id: 1, debited: 360 * 1000000000, credited: 309 * 1000000000), + ], + ); + expect(b.pendingSpendable.raw, raw(309)); + expect(b.total.raw, raw(309)); + }); + + test('both halves of a send to itself stay pending', () { + final b = grinBalanceToStack( + balance(locked: 100, awaitingFinalization: 99), + 9, + entries: [ + entryOf(id: 1, debited: 100 * 1000000000, credited: 49 * 1000000000), + entryOf( + id: 2, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 50 * 1000000000, + fee: null, + ), + ], + ); + expect(b.pendingSpendable.raw, raw(99)); + }); + + test('confirmed and cancelled entries add nothing', () { + final b = grinBalanceToStack( + balance(spendable: 10, awaitingConfirmation: 5), + 9, + entries: [ + entryOf(id: 1, credited: 7, confirmed: true, confirmedHeight: 90), + entryOf(id: 2, type: GrinTxType.txSentCancelled, credited: 3), + ], + ); + expect(b.pendingSpendable.raw, raw(5)); + expect(b.total.raw, raw(15)); + }); +} diff --git a/test/wallets/grin/grin_coin_test.dart b/test/wallets/grin/grin_coin_test.dart new file mode 100644 index 000000000..cc3cb1f71 --- /dev/null +++ b/test/wallets/grin/grin_coin_test.dart @@ -0,0 +1,124 @@ +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/coins/grin_checkpoints.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, 1441); + 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', () { + expect(main.isSlatepack(' BEGINSLATEPACK. abc ENDSLATEPACK. '), isTrue); + expect(main.isSlatepack('BEGINSLATEPACK. abc'), isFalse); + }); + + test('heightFromDate never starts above a block mined on that date', () { + // Mainnet block 400 was mined at 02:23:33 UTC on 16 January 2019, and + // testnet block 2,000,000 at 08:34:28 UTC on 29 December 2023. + expect(main.heightFromDate(DateTime.utc(2019, 1, 16)), lessThan(400)); + expect( + test_.heightFromDate(DateTime.utc(2023, 12, 29)), + lessThanOrEqualTo(2000000), + ); + expect(main.heightFromDate(DateTime.utc(2000)), 0); + expect(test_.heightFromDate(DateTime.utc(2000)), 0); + + for (final (coin, checkpoints) in [ + (main, grinMainnetCheckpoints), + (test_, grinTestnetCheckpoints), + ]) { + expect(checkpoints.first.$1, 0); + for (var i = 1; i < checkpoints.length; i++) { + expect(checkpoints[i].$1, greaterThan(checkpoints[i - 1].$1)); + expect(checkpoints[i].$2, greaterThan(checkpoints[i - 1].$2)); + } + for (final (height, time) in checkpoints) { + DateTime at(int seconds) => + DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true); + // A checkpoint is used from a day after its block. + expect(coin.heightFromDate(at(time + 86400)), height); + expect( + coin.heightFromDate(at(time + 86399)), + lessThan(height == 0 ? 1 : height), + ); + } + expect(coin.heightFromDate(DateTime.utc(2100)), checkpoints.last.$1); + } + }); +} + +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 000000000..6f0dfa7bf --- /dev/null +++ b/test/wallets/grin/grin_errors_test.dart @@ -0,0 +1,219 @@ +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/exceptions/wallet/node_tor_mismatch_config_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() { + useGrinCoinConfig(); + 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); + // Not found leaves nothing of this wallet pending. + expect(wallet.slateId, code == 13 ? isNull : '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', 'finalized': true}), + ) as GrinWalletException; + expect(safe.finalizedNotBroadcast, isTrue); + expect( + (sanitizeGrinError( + grinError(9), + ) as GrinWalletException).finalizedNotBroadcast, + isFalse, + ); + }); + + test('a slate id alone means a transaction was left behind', () { + final safe = sanitizeGrinError( + grinError(12, details: {'slate_id': 's'}), + ) as GrinWalletException; + expect(safe.leftPendingTransaction, isTrue); + expect(safe.finalizedNotBroadcast, isFalse); + expect(safe.message, endsWith(grinLeftPendingNote)); + }); + + test('an unknown or already finalized slate leaves nothing to cancel', () { + final safe = sanitizeGrinError( + grinError(13, details: {'slate_id': 's', 'finalized': true}), + ) as GrinWalletException; + expect(safe.leftPendingTransaction, isFalse); + expect(safe.finalizedNotBroadcast, isFalse); + expect(safe.message, 'No matching transaction in this wallet.'); + }); + + test('the node and Tor setting mismatch keeps its own text', () { + final safe = sanitizeGrinError( + NodeTorMismatchConfigException(message: 'Tor is on, node is not'), + ); + expect(safe, isA()); + expect((safe as GrinWalletException).message, 'Tor is on, node is not'); + }); + + test('released means nothing is locked', () { + final safe = sanitizeGrinError( + grinError(12, details: {'slate_id': 's', 'released': true}), + ) as GrinWalletException; + expect(safe.released, isTrue); + expect(safe.leftPendingTransaction, isFalse); + expect(safe.message, grinReleasedMessage); + }); + + test('the flags mean nothing without a slate id', () { + final safe = sanitizeGrinError( + grinError(9, details: {'finalized': true, 'released': true}), + ) as GrinWalletException; + expect(safe.finalized, isFalse); + expect(safe.released, isFalse); + expect(safe.message, 'Could not reach the Grin node.'); + }); + + 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 000000000..375bee8fe --- /dev/null +++ b/test/wallets/grin/grin_invoice_test.dart @@ -0,0 +1,91 @@ +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() { + useGrinCoinConfig(); + 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 000000000..ae0be94ca --- /dev/null +++ b/test/wallets/grin/grin_lifecycle_test.dart @@ -0,0 +1,376 @@ +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/services/event_bus/events/global/wallet_sync_status_changed_event.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() { + useGrinCoinConfig(); + 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 wallet that did not open reports that it cannot sync and says why ' + 'its calls fail', () async { + await h.wallet.init(); + await h.wallet.exit(); + h.backend.wallets.clear(); + final next = h.newWallet(); + await expectLater(next.init(), throwsA(isA())); + + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + await next.refresh(); + await pumpEventQueue(); + expect(statuses, [WalletSyncStatus.unableToSync]); + await expectLater( + next.inspectSlatepack('s1'), + throwsA( + predicate( + (e) => + e.toString().contains('could not be opened') && + e.toString().contains('files are missing'), + ), + ), + ); + }); + + 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 restore stopped before it wrote the password is finished from the ' + 'phrase on the next start', () async { + final r = await GrinHarness.create(restoreHeight: 1000); + addTearDown(r.dispose); + await r.wallet.init(isRestore: true); + expect(r.wallet.info.grinData!.pendingScanFrom, 1000); + expect( + r.secrets.values, + isNot(contains(GrinWallet.passwordKey(r.walletId))), + ); + + // Killed here, before recover. The next start does not take the wallet + // for a new one. + final next = r.newWallet(); + addTearDown(next.exit); + await next.init(); + expect(r.backend.calls, ['create']); + expect(r.backend.creates.single.isNewWallet, isFalse); + expect(r.backend.creates.single.mnemonic, testMnemonic); + expect(next.info.restoreHeight, 1000); + expect(next.info.grinData!.pendingScanFrom, 1000); + expect(r.secrets.values, contains(GrinWallet.passwordKey(r.walletId))); + }); + + 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); + // The first wallet's refresh after its scan may or may not have tested + // the node before it closed. + expect(r.backend.calls.where((c) => c != 'testNodeConnection'), [ + '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_network_settings_test.dart b/test/wallets/grin/grin_network_settings_test.dart new file mode 100644 index 000000000..0b73514df --- /dev/null +++ b/test/wallets/grin/grin_network_settings_test.dart @@ -0,0 +1,53 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart'; + +import '../support/grin_fakes.dart'; + +/// What the wallet network settings show for a Grin wallet. +void main() { + useGrinCoinConfig(); + 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); + }); + tearDown(() async { + await h.dispose(); + await isar.close(); + await isarRoot.delete(recursive: true); + }); + + bool shows() => showsBlocksRemaining( + h.wallet.cryptoCurrency, + h.wallet, + mwebEnabled: false, + ); + + test('an opened wallet shows no blocks to go', () async { + await h.wallet.init(); + expect(shows(), isFalse, reason: 'an ordinary refresh has none to count'); + }); + + test('a restore shows blocks to go while its scan is pending', () async { + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + expect(h.wallet.isScanPending, isTrue); + expect(shows(), isTrue); + final api = h.backend.api; + await eventually(() => api.scanRunning); + api.finishScan(); + await eventually(() => !h.wallet.isScanPending); + expect(shows(), 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 000000000..b1052b6fa --- /dev/null +++ b/test/wallets/grin/grin_node_url_test.dart @@ -0,0 +1,86 @@ +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, + ); + } + }); + + test('a host with characters a host name cannot have is refused', () { + for (final host in [ + 'https://exa mple.com', + 'exa mple.com', + 'https://exa%20mple.com', + 'https://exämple.com', + 'https://node.example', + ]) { + expect( + () => url(host), + throwsA(isA()), + reason: host, + ); + } + expect(url('https://Node.Example'), 'https://node.example:3413'); + expect(url('https://my_node.example'), 'https://my_node.example:3413'); + expect(url('http://[::1]', useSSL: false), 'http://[::1]:3413'); + }); +} diff --git a/test/wallets/grin/grin_scan_test.dart b/test/wallets/grin/grin_scan_test.dart new file mode 100644 index 000000000..c23b1156d --- /dev/null +++ b/test/wallets/grin/grin_scan_test.dart @@ -0,0 +1,671 @@ +import 'dart:async'; +import 'dart:convert'; +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/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.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/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() { + useGrinCoinConfig(); + 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(); + await eventually(() => api.scanRunning); + 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', + ]); + }); + + GrinScanProgress running({ + int start = 1000, + required int saved, + bool scanning = true, + }) => GrinScanProgress( + isScanning: scanning, + cancelRequested: false, + startHeight: start, + scannedHeight: saved + 5000, + savedHeight: saved, + tipHeight: 50000, + progressPct: 30, + ); + + test('a running scan saves its resume height after each saved batch, so ' + 'a scan the app never ended resumes there', () async { + final api = await restore(); + api.progress = running(saved: 11000); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == 11001); + expect(api.scanRunning, isTrue); + api.progress = running(saved: 21001); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == 21002); + + // The close reports no height, as a kill would leave none. + await h.wallet.exit(); + expect(h.wallet.info.grinData!.pendingScanFrom, 21002); + final next = h.newWallet(); + addTearDown(next.exit); + await next.init(); + await next.refresh(); + await eventually(() => h.backend.api.calls.contains('scan:21002:false')); + }); + + test( + 'heights of an earlier scan are not saved as the resume height', + () async { + final api = await restore(); + api.progress = running(start: 500, saved: 30000); + await Future.delayed(const Duration(milliseconds: 1200)); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + api.progress = running(saved: 30000, scanning: false); + await Future.delayed(const Duration(milliseconds: 1200)); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + api.finishScan(); + }, + ); + + test('a finished scan is not reopened by a late resume height', () async { + final api = await restore(); + api.progress = running(saved: 11000); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == 11001); + api.finishScan(); + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + await Future.delayed(const Duration(milliseconds: 1200)); + expect(h.wallet.info.grinData!.pendingScanFrom, isNull); + }); + + 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 returns at once and ' + 'does not run the scan it replaces', () 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); + + // The replaced job stops waiting for Tor, so the rescan dialog closes. + await h.wallet.recover(isRescan: true).timeout(const Duration(seconds: 5)); + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + expect(statuses, isNot(contains(WalletSyncStatus.unableToSync))); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + 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, + savedHeight: 0, + 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( + 'progress after a resumed scan counts from the restore height', + () 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(); + // A run resumed at 3000: the library's own percent starts again at 0. + api.progress = const GrinScanProgress( + isScanning: true, + cancelRequested: false, + startHeight: 3000, + scannedHeight: 3000, + savedHeight: 0, + tipHeight: 5000, + progressPct: 0, + ); + await Future.delayed(const Duration(milliseconds: 1100)); + expect(h.wallet.restoreProgress, 0.5); + expect(percents, contains(0.5)); + expect(remaining, contains(2000)); + + api.finishScan(); + await eventually(() => percents.last == 1); + expect(remaining.last, 0); + }, + ); + + Future storeSend({int? height}) => isar.writeTxn( + () => isar.transactionV2s.put( + TransactionV2( + walletId: h.walletId, + blockHash: null, + hash: '', + txid: 'slate-1', + timestamp: 0, + height: height, + inputs: const [], + outputs: const [], + version: 0, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: jsonEncode({ + TxV2OdKeys.isGrinTransaction: true, + TxV2OdKeys.slateId: 'slate-1', + TxV2OdKeys.grinHasPaymentProof: true, + TxV2OdKeys.grinHasStoredTx: true, + }), + ), + ), + ); + + test('calls that would wait for the whole scan are refused', () async { + final api = await restore(); + final proof = (await api.exportPaymentProof()).toJsonString(); + await storeSend(); + final before = api.calls.length; + final scanning = throwsA( + predicate((e) => e.toString().contains('finish scanning')), + ); + + await expectLater(h.wallet.pendingSlatepackFor('slate-1'), scanning); + await expectLater(h.wallet.exportPaymentProof('slate-1'), scanning); + await expectLater(h.wallet.verifyPaymentProof(proof), scanning); + await expectLater(h.wallet.repost('slate-1'), scanning); + await expectLater(h.wallet.finalizeSlatepack('s2'), scanning); + await expectLater(h.wallet.finalizeInvoice('i2'), scanning); + // Encrypted: only the wallet could read it. + h.backend.decodeError = grinError(11); + await expectLater( + h.wallet.inspectSlatepack('encrypted'), + throwsA(predicate((e) => e.toString().contains('wait for the scan'))), + ); + expect(api.calls.sublist(before), isEmpty); + + // A plain Slatepack is still read without the wallet. + h.backend.decodeError = null; + await h.wallet.inspectSlatepack('plain'); + expect(api.calls.sublist(before), isEmpty); + api.finishScan(); + }); + + test('repost refuses a transaction that has confirmed', () async { + final api = await restore(); + api.finishScan(); + await eventually(() => h.wallet.info.grinData?.pendingScanFrom == null); + await storeSend(height: 4000); + await expectLater( + h.wallet.repost('slate-1'), + throwsA(predicate((e) => e.toString().contains('already confirmed'))), + ); + expect(api.calls, isNot(contains('repost'))); + }); + + test( + 'a restore closed while its wallet is created does not succeed', + () async { + final gate = Completer(); + h.backend.createGate = gate.future; + await h.wallet.init(isRestore: true); + final restoring = h.wallet.recover(isRescan: false); + await eventually(() => h.backend.calls.contains('create')); + final closing = h.wallet.exit(); + gate.complete(); + await expectLater(restoring, throwsA(isA())); + await closing; + expect(h.backend.api.calls.where((c) => c.startsWith('scan')), isEmpty); + }, + ); + + 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); + }, + ); + + test('a restore that starts while the network is blocked scans once a ' + 'usable transport is applied, without automatic sync', () async { + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await eventually(() => statuses.contains(WalletSyncStatus.unableToSync)); + final api = h.backend.api; + expect(h.wallet.shouldAutoSync, isFalse); + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + 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('a blocked restore that is closed is not started by a later ' + 'transport', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await pumpEventQueue(times: 50); + final api = h.backend.api; + await h.wallet.exit(); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await pumpEventQueue(times: 50); + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + }); + + test('waitForRecovery returns once the restore has scanned to the tip, ' + 'across a scan a node change restarted', () async { + final api = await restore(); + var done = false; + final wait = h.wallet.waitForRecovery().then((_) => done = true); + await pumpEventQueue(); + expect(done, isFalse); + + api.cancelScannedHeight = 1500; + h.wallet.node = grinNode(host: 'https://other.node'); + await h.wallet.updateNode(); + await eventually(() => api.calls.contains('scan:1501:false')); + expect(done, isFalse); + + api.finishScan(); + await wait; + expect(h.wallet.info.grinData!.pendingScanFrom, isNull); + }); + + test('waitForRecovery fails when the wallet is closed first or the scan ' + 'fails, and keeps the resume height', () async { + await restore(); + final closed = expectLater( + h.wallet.waitForRecovery(), + throwsA(isA()), + ); + await h.wallet.exit(); + await closed; + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + + h.backend.scanBlocks = false; + final next = h.newWallet(); + addTearDown(next.exit); + await next.init(); + final api = h.backend.api; + api.scanError = grinError(9); + await expectLater( + next.waitForRecovery(), + throwsA(isA()), + ); + expect(api.calls, contains('scan:1000:false')); + expect(next.info.grinData!.pendingScanFrom, 1000); + }); + + test('waitForRecovery fails at once when the network is blocked', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await expectLater( + h.wallet.waitForRecovery().timeout(const Duration(seconds: 5)), + throwsA(isA()), + ); + }); + + test('a finished restore does not hold the progress at 100%', () async { + final api = await restore(); + api.progress = running(saved: 11000); + await eventually(() => h.wallet.restoreProgress > 0); + api.finishScan(); + // The job sets the percent once it has stored the end of the scan. + await eventually(() => h.wallet.highestPercent == 1); + expect(h.wallet.info.grinData!.pendingScanFrom, isNull); + expect(h.wallet.restoreProgress, 0); + }); + + test( + 'a restore caches the receiving address the receive screen reads', + () async { + await restore(); + expect(h.wallet.info.cachedReceivingAddress, 'grin1ownaddress'); + }, + ); + + test('a failed scan is tried again later, without automatic sync, until ' + 'it finishes', () async { + final original = GrinWallet.scanRetryDelay; + final delays = []; + GrinWallet.scanRetryDelay = (failures) { + delays.add(failures); + return const Duration(milliseconds: 20); + }; + addTearDown(() => GrinWallet.scanRetryDelay = original); + h.backend.scanBlocks = false; + expect(h.wallet.shouldAutoSync, isFalse); + await h.wallet.init(isRestore: true); + h.backend.scanError = grinError(9); + await h.wallet.recover(isRescan: false); + final api = h.backend.api; + await eventually( + () => api.calls.where((c) => c.startsWith('scan:')).length >= 3, + ); + expect(delays.take(2), [1, 2]); + expect(h.wallet.info.grinData!.pendingScanFrom, 1000); + + api.scanError = null; + await eventually(() => h.wallet.info.grinData!.pendingScanFrom == null); + final scans = api.calls.where((c) => c.startsWith('scan:')).length; + await Future.delayed(const Duration(milliseconds: 100)); + expect(api.calls.where((c) => c.startsWith('scan:')).length, scans); + }); + + test('no failed scan is tried again after the wallet closes', () async { + final original = GrinWallet.scanRetryDelay; + GrinWallet.scanRetryDelay = (_) => const Duration(milliseconds: 50); + addTearDown(() => GrinWallet.scanRetryDelay = original); + h.backend.scanBlocks = false; + await h.wallet.init(isRestore: true); + h.backend.scanError = grinError(9); + await h.wallet.recover(isRescan: false); + final api = h.backend.api; + await eventually(() => api.calls.contains('scan:1000:false')); + await pumpEventQueue(); + await h.wallet.exit(); + final scans = api.calls.where((c) => c.startsWith('scan:')).length; + await Future.delayed(const Duration(milliseconds: 200)); + expect(api.calls.where((c) => c.startsWith('scan:')).length, scans); + }); +} 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 000000000..ce66939ae --- /dev/null +++ b/test/wallets/grin/grin_send_policy_test.dart @@ -0,0 +1,350 @@ +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/models/isar/models/blockchain_data/v2/transaction_v2.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() { + useGrinCoinConfig(); + 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', method: SlatepackMethod.slatepack), + ); + 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 send that does not ask for a Slatepack is refused for a grin1 ' + 'address', () async { + // As an exchange's send does: nothing would hand the S1 to the payee. + await h.wallet.init(); + await expectLater( + h.wallet.prepareSend(txData: send('grin1friend')), + throwsA(predicate((e) => e.toString().contains('Send screen'))), + ); + await expectLater( + h.wallet.confirmSend(txData: send('grin1friend')), + throwsA(predicate((e) => e.toString().contains('Send screen'))), + ); + expect(h.backend.api.initSends, 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', + method: SlatepackMethod.slatepack, + ).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); + expect(args.expectedFee, BigInt.from(23500000)); + expect(args.expectedAmount, BigInt.from(1000000000 - 23500000)); + }); + + test('a send whose fee changed after review is refused before anything ' + 'is locked or sent', () async { + await torOn(); + await h.wallet.init(); + final api = h.backend.api; + GrinFeeEstimate feeOf(int fee) => GrinFeeEstimate( + fee: BigInt.from(fee), + amount: BigInt.zero, + netAmount: BigInt.zero, + total: BigInt.zero, + inputsCount: 1, + changeOutputs: 1, + ); + for (final (target, method) in [ + ('grin1friend', SlatepackMethod.slatepack), + ('http://abc.onion', SlatepackMethod.http), + ]) { + for (final all in [false, true]) { + api.fee = feeOf(10000000); + final prepared = await h.wallet.prepareSend( + txData: send( + target, + method: method, + ).copyWith(subtractFeeFromAmount: all), + ); + // The wallet's outputs changed: the inputs selected now cost more. + api.fee = feeOf(23500000); + await expectLater( + h.wallet.confirmSend(txData: prepared), + throwsA( + isA().having( + (e) => e.termsChanged, + 'termsChanged', + isTrue, + ), + ), + reason: '$target, send all: $all', + ); + } + } + expect(api.initSends, isEmpty); + expect(api.httpSends, isEmpty); + final http = api.sendAttempts.whereType().last; + expect(http.post, isTrue); + expect(http.amount, BigInt.from(1000000000)); + expect(http.expectedFee, BigInt.from(10000000)); + expect(http.expectedAmount, BigInt.from(1000000000 - 10000000)); + }); + + 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)); + }); + + test('a send that fails part way has its transaction in the history ' + 'before the error is shown', () async { + await torOn(); + await h.wallet.init(); + final api = h.backend.api; + api.transactions = GrinTxList( + refreshedFromNode: false, + transactions: [ + entryOf( + id: 3, + slateId: 'slate-http', + state: GrinSlateState.s3, + debited: 2000000000, + credited: 900000000, + hasStoredTx: true, + ), + ], + ); + api.sendError = grinError( + 9, + details: {'slate_id': 'slate-http', 'finalized': true}, + ); + await expectLater( + h.wallet.confirmSend(txData: send('http://abc.onion')), + throwsA(isA()), + ); + expect( + await isar.transactionV2s.filter().txidEqualTo('slate-http').findFirst(), + isNotNull, + ); + expect(api.transactionRefreshes.first, isFalse); + }); + + test('a confirmed send with no change gets the height of its kernel, ' + 'looked up once', () async { + await h.wallet.init(); + final api = h.backend.api; + final sendAll = entryOf( + id: 4, + slateId: 'slate-all', + state: GrinSlateState.s3, + debited: 2000000000, + confirmed: true, + kernelExcess: '08bb', + ); + api.transactions = GrinTxList( + refreshedFromNode: true, + transactions: [sendAll], + ); + api.kernelError = grinError(9); + await h.wallet.updateTransactions(); + Future height() async => + (await isar.transactionV2s + .filter() + .txidEqualTo('slate-all') + .findFirst())! + .height; + expect(await height(), isNull, reason: 'not the chain height'); + + api.kernelError = null; + api.kernelHeights['08bb'] = 3900123; + await h.wallet.updateTransactions(); + expect(await height(), 3900123); + expect(api.kernelLookups.last, (excess: '08bb', minHeight: 1)); + + await h.wallet.updateTransactions(); + expect(api.kernelLookups, hasLength(2), reason: 'the height is stored'); + expect(await height(), 3900123); + }); +} diff --git a/test/wallets/grin/grin_swb_test.dart b/test/wallets/grin/grin_swb_test.dart new file mode 100644 index 000000000..4deab4a10 --- /dev/null +++ b/test/wallets/grin/grin_swb_test.dart @@ -0,0 +1,146 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.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() { + useGrinCoinConfig(); + 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(); + }); + + group('a Stack Backup restore', () { + Future restoring() async { + final r = await GrinHarness.create(restoreHeight: 1000); + addTearDown(r.dispose); + r.backend.scanBlocks = true; + await r.wallet.init(isRestore: true); + await r.wallet.recover(isRescan: false); + await eventually(() => r.backend.api.scanRunning); + return r; + } + + test('waits for the Grin scan to finish', () async { + final r = await restoring(); + final result = []; + unawaited(SWB.waitForGrinRecovery(r.wallet).then(result.add)); + await pumpEventQueue(); + expect(result, isEmpty); + r.backend.api.finishScan(); + await eventually(() => result.isNotEmpty); + expect(result.single, isTrue); + }); + + test('that is cancelled stops waiting for the Grin scan', () async { + final r = await restoring(); + addTearDown(SWB.debugEndCancel); + final result = []; + unawaited(SWB.waitForGrinRecovery(r.wallet).then(result.add)); + await pumpEventQueue(); + expect(result, isEmpty); + // Completes only when a revert finishes, which this test has none of. + unawaited(SWB.cancelRestore()); + await eventually(() => result.isNotEmpty); + expect(result.single, isFalse); + }); + + test('that is reverted removes its Grin wallet files and password, so ' + 'the same backup can be restored again', () async { + final r = await restoring(); + final key = GrinWallet.passwordKey(r.walletId); + expect(r.secrets.values, contains(key)); + final left = await SWB.deleteGrinWalletFiles([r.wallet.info], r.secrets); + expect(left, isEmpty); + expect(r.backend.calls, contains('delete')); + expect(r.secrets.values, isNot(contains(key))); + expect(r.wallet.isOpen, isFalse); + }); + }); +} 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 000000000..31502ffc2 --- /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 000000000..181dbe9fd --- /dev/null +++ b/test/wallets/grin/grin_transport_test.dart @@ -0,0 +1,481 @@ +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/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/services/event_bus/events/global/wallet_sync_status_changed_event.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() { + useGrinCoinConfig(); + 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('Tor connecting after a direct transport disables the network until ' + 'it connects', () async { + await h.wallet.init(); + final api = h.backend.api; + + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire(TorPreferenceChangedEvent(status: TorStatus.enabled)); + await settle(); + expect(api.networkUpdates.single.networkEnabled, isFalse); + expect(api.networkUpdates.single.socksProxy, isNull); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await settle(); + expect(api.networkUpdates.last.socksProxy, '127.0.0.1:9050'); + expect(api.networkUpdates.last.networkEnabled, isTrue); + }); + + test( + 'Tor starting to connect stops a scan on the clearnet fallback', + () async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await settle(); + final api = h.backend.api; + expect(h.backend.creates.single.config.networkEnabled, isTrue); + expect(h.backend.creates.single.config.socksProxy, isNull); + expect(api.scanRunning, isTrue); + + // Only the status event: the preference is already on. + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connecting, ''), + ); + await settle(); + expect(api.calls, contains('cancelScan')); + expect(api.networkUpdates.single.networkEnabled, isFalse); + }, + ); + + test( + 'Tor starting to connect just before a node call stops the call', + () async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + await h.wallet.init(); + final api = h.backend.api; + + final estimate = h.wallet.estimateFeeFor( + Amount(rawValue: BigInt.from(5), fractionDigits: 9), + BigInt.one, + ); + // After the call's wait for Tor, before it applies the transport. + h.tor.current = TorConnectionStatus.connecting; + await expectLater( + estimate, + throwsA(predicate((e) => e.toString().contains('still connecting'))), + ); + expect(api.networkUpdates.single.networkEnabled, isFalse); + expect(api.calls, isNot(contains('estimateFee'))); + }, + ); + + test('turning the kill switch on stops a scan over clearnet', () async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await settle(); + final api = h.backend.api; + expect(h.backend.creates.single.config.networkEnabled, isTrue); + expect(api.scanRunning, isTrue); + + h.prefs.killSwitch = true; + await settle(); + expect(api.calls, contains('cancelScan')); + expect(api.networkUpdates.single.networkEnabled, isFalse); + }); + + 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('a scan a node change stopped starts again in a wallet that does not ' + 'sync on its own', () 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(h.wallet.shouldAutoSync, isFalse); + api.cancelScannedHeight = 20000; + + h.wallet.node = grinNode(host: 'https://other.node'); + await h.wallet.updateNode(); + await eventually(() => api.calls.contains('scan:20001:false')); + expect(api.scanRunning, isTrue); + }); + + test('a rescan right after a node change does not wait for the resumed ' + 'scan', () async { + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await settle(); + final api = h.backend.api; + api.cancelScannedHeight = 20000; + + h.wallet.node = grinNode(host: 'https://other.node'); + await h.wallet.updateNode(); + // The node change has queued the resume of the scan it cancelled. + await h.wallet.recover(isRescan: true); + await eventually( + () => api.calls.where((c) => c.startsWith('scan:')).length == 2, + reason: 'the rescan scans', + ); + expect(api.calls.where((c) => c.startsWith('scan:')), [ + 'scan:10:false', + 'scan:10:false', + ]); + }); + + test('a scan stopped while Tor connects starts again once it has ' + 'connected', () async { + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.disconnected; + h.backend.scanBlocks = true; + await h.wallet.init(isRestore: true); + await h.wallet.recover(isRescan: false); + await settle(); + final api = h.backend.api; + + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connecting, ''), + ); + await settle(); + expect(api.calls, contains('cancelScan')); + expect(api.scanRunning, isFalse); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await eventually( + () => api.calls.where((c) => c.startsWith('scan:')).length == 2, + ); + expect(api.networkUpdates.last.socksProxy, isNotNull); + expect(api.scanRunning, isTrue); + }); + + test('a scan that gave up waiting for Tor starts again when Tor connects ' + 'through the same proxy', () async { + final original = GrinWallet.torConnectWait; + GrinWallet.torConnectWait = const Duration(milliseconds: 10); + addTearDown(() => GrinWallet.torConnectWait = original); + h.prefs.tor = true; + h.prefs.killSwitch = false; + h.tor.current = TorConnectionStatus.connected; + h.backend.scanBlocks = true; + await h.wallet.init(); + final api = h.backend.api; + expect(h.backend.creates.single.config.socksProxy, isNotNull); + + // Tor drops back to connecting; the proxy stays applied. + h.tor.current = TorConnectionStatus.connecting; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connecting, ''), + ); + await settle(); + expect(api.networkUpdates, isEmpty); + + // A rescan's job waits out the connect and gives up. + final statuses = []; + h.bus.on().listen( + (e) => statuses.add(e.newStatus), + ); + unawaited(h.wallet.recover(isRescan: true).catchError((Object _) {})); + await eventually( + () => statuses.contains(WalletSyncStatus.unableToSync), + reason: 'the rescan job gives up', + ); + expect(h.wallet.isScanPending, isTrue); + await settle(); + expect(api.calls.where((c) => c.startsWith('scan:')), isEmpty); + + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await eventually( + () => api.calls.any((c) => c.startsWith('scan:')), + reason: 'the owed scan starts', + ); + expect(api.networkUpdates, isEmpty); + }); + + test('a transport a listener cannot apply is logged, not thrown, and the ' + 'next node call reports it', () async { + await h.wallet.init(); + final api = h.backend.api; + api.updateNetworkError = grinError(1); + + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connected; + h.bus.fire(TorPreferenceChangedEvent(status: TorStatus.enabled)); + await settle(); + expect(api.calls, contains('updateNetwork')); + expect(api.networkUpdates, isEmpty); + + await expectLater( + h.wallet.estimateFeeFor( + Amount(rawValue: BigInt.from(5), fractionDigits: 9), + BigInt.one, + ), + throwsA(isA()), + ); + api.updateNetworkError = null; + await h.wallet.estimateFeeFor( + Amount(rawValue: BigInt.from(5), fractionDigits: 9), + BigInt.one, + ); + expect(api.networkUpdates.single.socksProxy, isNotNull); + }); + + 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); + }); + + test('the chain height and the ping check ask for the wallet\'s network, ' + 'and a node on the other one is refused', () async { + await h.wallet.init(); + await h.wallet.updateChainHeight(); + expect(h.backend.nodeTests.single.network, GrinNetwork.mainnet); + expect(h.wallet.info.cachedChainHeight, 4096748); + + h.backend.nodeNetwork = GrinNetwork.testnet; + h.backend.nodeHeight = 3364730; + await expectLater( + h.wallet.updateChainHeight(), + throwsA( + isA().having( + (e) => e.message, + 'message', + grinWrongNetworkMessage, + ), + ), + ); + expect(h.wallet.info.cachedChainHeight, 4096748); + expect(await h.wallet.pingCheck(), isFalse); + expect( + h.backend.nodeTests.map((t) => t.network), + everyElement(GrinNetwork.mainnet), + ); + }); + + test('an invalid node is replaced without its API secret', () async { + h.wallet.node = grinNode( + host: 'https://node.example?x=1', + secret: 'node-secret', + ); + await h.wallet.init(); + final config = h.backend.creates.single.config; + expect(config.networkEnabled, isFalse); + expect(config.nodeUrl, 'https://grinnode.live:3413'); + expect(config.nodeApiSecret, isNull); + await expectLater(h.wallet.updateChainHeight(), throwsException); + expect(h.backend.nodeTests, isEmpty); + + // A valid node gets its own secret again. + h.wallet.node = grinNode(secret: 'node-secret'); + await h.wallet.updateNode(); + expect(h.backend.api.networkUpdates.last.apiSecret, 'node-secret'); + await h.wallet.updateChainHeight(); + expect(h.backend.nodeTests.single.apiSecret, 'node-secret'); + }); + + test('a chain height request takes the node, secret and transport from ' + 'one read after Tor connects', () async { + h.prefs.tor = true; + h.tor.current = TorConnectionStatus.connecting; + h.wallet.node = grinNode(host: 'https://first.node', secret: 'first'); + await h.wallet.init(); + final height = h.wallet.updateChainHeight(); + await settle(); + expect(h.backend.nodeTests, isEmpty); + + // The node changes again right after the first read once Tor connects. + // URL, secret and proxy must all come from that one read. + var reads = 0; + h.wallet.onNodeRead = () { + if (++reads == 1) { + h.wallet.node = grinNode(host: 'https://third.node', secret: 'third'); + } + }; + h.wallet.node = grinNode(host: 'https://second.node', secret: 'second'); + h.tor.current = TorConnectionStatus.connected; + h.bus.fire( + TorConnectionStatusChangedEvent(TorConnectionStatus.connected, ''), + ); + await height; + final test = h.backend.nodeTests.single; + expect(test.nodeUrl, 'https://second.node:3413'); + expect(test.apiSecret, 'second'); + expect(test.socksProxy, '127.0.0.1:9050'); + }); +} 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 000000000..56079ec87 --- /dev/null +++ b/test/wallets/grin/grin_tx_mapping_test.dart @@ -0,0 +1,392 @@ +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: 1441, +); + +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('a payment received again after a cancelled receive counts once and ' + 'is live', () { + final tx = map([ + entryOf( + id: 4, + type: GrinTxType.txReceivedCancelled, + state: GrinSlateState.s2, + credited: 500, + fee: null, + ), + entryOf( + id: 5, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 500, + fee: null, + ), + ]).single; + expect(tx.type, TransactionType.incoming); + expect(od(tx)[TxV2OdKeys.isCancelled], isFalse); + expect(od(tx)[TxV2OdKeys.grinLogIds], [5]); + expect( + tx.getAmountReceivedInThisWallet(fractionDigits: 9).raw, + BigInt.from(500), + ); + }); + + test('a payment received and cancelled twice counts once', () { + final tx = map([ + for (final id in [4, 5]) + entryOf( + id: id, + type: GrinTxType.txReceivedCancelled, + state: GrinSlateState.s2, + credited: 500, + fee: null, + ), + ]).single; + expect(od(tx)[TxV2OdKeys.isCancelled], isTrue); + expect(od(tx)[TxV2OdKeys.grinLogIds], [5]); + expect( + tx.getAmountReceivedInThisWallet(fractionDigits: 9).raw, + BigInt.from(500), + ); + }); + + 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); + // grin-wallet locks a reward at height h until tip h + 1440. + expect(tx.isConfirmed(600, 10, 1441), isFalse); + expect(tx.isConfirmed(1939, 10, 1441), isFalse); + expect(tx.isConfirmed(1940, 10, 1441), isTrue); + expect(label(tx, height: 600), startsWith('Receiving')); + expect(label(tx, height: 1939), startsWith('Receiving')); + expect(label(tx, height: 1940), isNot(startsWith('Receiving'))); + }); + + test('a payment proof is offered only when it is complete, from the row ' + 'that holds it', () { + GrinPaymentProofSummary proof({required bool signed}) => + GrinPaymentProofSummary( + receiverAddress: 'grin1friend', + senderAddress: own, + receiverSignaturePresent: signed, + senderSignaturePresent: signed, + ); + // An S1 carries both addresses before anyone has signed. + final unsigned = map([ + entryOf(id: 1, debited: 1000, proof: proof(signed: false)), + ]).single; + expect(od(unsigned)[TxV2OdKeys.grinHasPaymentProof], isFalse); + expect(od(unsigned)[TxV2OdKeys.grinPaymentProofLogId], isNull); + + // Signed but without the kernel the export needs. + final noKernel = map([ + entryOf(id: 2, debited: 1000, proof: proof(signed: true)), + ]).single; + expect(od(noKernel)[TxV2OdKeys.grinHasPaymentProof], isFalse); + + // A self-send whose second row holds the proof. + final grouped = map([ + entryOf( + id: 3, + type: GrinTxType.txReceived, + state: GrinSlateState.s2, + credited: 590, + fee: null, + counterparty: own, + ), + entryOf( + id: 4, + debited: 1000, + credited: 400, + fee: 10, + counterparty: own, + kernelExcess: '08ab', + proof: proof(signed: true), + ), + ]).single; + expect(od(grouped)[TxV2OdKeys.grinHasPaymentProof], isTrue); + expect(od(grouped)[TxV2OdKeys.grinPaymentProofLogId], 4); + }); + + 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); + }); + + test('a confirmed entry with a kernel and no height waits for the kernel ' + 'height instead of taking the chain height', () { + final unknown = map([ + entryOf(id: 7, debited: 10, confirmed: true, kernelExcess: '08aa'), + ], chainHeight: 1234).single; + expect(unknown.height, isNull); + + final looked = map( + [entryOf(id: 7, debited: 10, confirmed: true, kernelExcess: '08aa')], + stored: {'slate-1': 900}, + chainHeight: 1234, + ).single; + expect(looked.height, 900); + }); + + 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 000000000..0cf7a6111 --- /dev/null +++ b/test/wallets/grin/grin_wallets_service_test.dart @@ -0,0 +1,154 @@ +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() { + useGrinCoinConfig(); + 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('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); + // Creation wrote the recovery phrase; it goes with the wallet. + expect( + h.secrets.values.containsKey(Wallet.mnemonicKey(walletId: h.walletId)), + isFalse, + ); + expect( + h.secrets.values.containsKey( + Wallet.mnemonicPassphraseKey(walletId: h.walletId), + ), + isFalse, + ); + }); + + test('the startup retry deletes the password of a wallet whose directory ' + 'is already gone', () async { + await h.wallet.init(); + await h.wallet.exit(); + // The files went, but the password delete did not happen. + await h.backend.delete( + walletDir: await GrinWallet.walletDirPath(h.walletId), + ); + await Directory(await GrinWallet.walletDirPath(h.walletId)).delete(); + expect(h.secrets.values.containsKey(passwordKey()), isTrue); + + final remaining = await GrinWallet.retryDeferredDeletes( + walletIds: [h.walletId], + secureStore: h.secrets, + backend: h.backend, + ); + expect(remaining, isEmpty); + expect(h.secrets.values.containsKey(passwordKey()), isFalse); + }); + + for (final code in [18, 15]) { + final what = code == 18 ? 'is busy' : 'fails'; + test('an unfinished wallet whose delete $what is queued, and the ' + 'startup retry deletes it', () 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 000000000..fc50cd716 --- /dev/null +++ b/test/wallets/support/grin_fakes.dart @@ -0,0 +1,920 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.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/app_config.dart'; +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 'xelis_test_fakes.dart' show MemorySecrets; + +export 'xelis_test_fakes.dart' show MemorySecrets; + +/// 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 = []; + + /// Every send asked for, including ones refused before anything locked. + final sendAttempts = []; + 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; + Object? updateNetworkError; + + /// 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, + savedHeight: 0, + tipHeight: 0, + progressPct: 0, + ); + + /// Kernel heights by excess, as the node would report them. + final kernelHeights = {}; + final kernelLookups = <({String excess, int? minHeight})>[]; + Object? kernelError; + + 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'); + final error = updateNetworkError; + if (error != null) throw error; + 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 kernelHeight({required String excess, int? minHeight}) async { + _check('kernelHeight'); + kernelLookups.add((excess: excess, minHeight: minHeight)); + if (kernelError != null) throw kernelError!; + return kernelHeights[excess]; + } + + @override + Future decodeSlatepack( + String armored, { + int secretIndex = 0, + }) async { + _check('decodeSlatepack'); + final info = decoded; + if (info == null) throw grinError(11); + return info; + } + + /// The library's check of the reviewed fee and net amount, against the + /// fee [estimateFee] reports now. + void _checkTerms({ + required BigInt amount, + required bool amountIncludesFee, + required BigInt? expectedFee, + required BigInt? expectedAmount, + }) { + final net = amountIncludesFee ? amount - fee.fee : amount; + if ((expectedFee != null && expectedFee != fee.fee) || + (expectedAmount != null && expectedAmount != net)) { + throw grinError(12, details: {'reason': 'terms_changed'}); + } + } + + @override + Future initSend(GrinSendArgs args) async { + _check('initSend'); + sendAttempts.add(args); + if (sendError != null) throw sendError!; + _checkTerms( + amount: args.amount, + amountIncludesFee: args.amountIncludesFee, + expectedFee: args.expectedFee, + expectedAmount: args.expectedAmount, + ); + initSends.add(args); + return slatepackOf(GrinSlateState.s1, amount: args.amount); + } + + @override + Future sendHttp(GrinHttpSendArgs args) async { + _check('sendHttp'); + sendAttempts.add(args); + if (sendError != null) throw sendError!; + _checkTerms( + amount: args.amount, + amountIncludesFee: args.amountIncludesFee, + expectedFee: args.expectedFee, + expectedAmount: args.expectedAmount, + ); + 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, + GrinNetwork? network, + }) + >[]; + 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; + + /// When set, create waits for it after recording the call. + Future? createGate; + Object? createError; + Object? deleteError; + Object? nodeError; + + /// The network the node answers for; a probe for another one fails. + GrinNetwork nodeNetwork = GrinNetwork.mainnet; + Object? decodeError; + int nodeHeight = 4096748; + + /// New wallets' scans wait for [FakeGrinWalletApi.finishScan] or a cancel. + bool scanBlocks = false; + + /// What new wallets' scans throw, until a test clears it on the wallet. + Object? scanError; + + FakeGrinWalletApi get api => apis.last; + + FakeGrinWalletApi _newApi(GrinWalletConfig config) { + final api = + FakeGrinWalletApi(walletDir: config.walletDir, network: config.network) + ..scanBlocks = scanBlocks + ..scanError = scanError; + 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); + await createGate; + 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, + GrinNetwork? network, + }) async { + calls.add('testNodeConnection'); + nodeTests.add(( + nodeUrl: nodeUrl, + apiSecret: apiSecret, + socksProxy: socksProxy, + network: network, + )); + if (nodeError != null) throw nodeError!; + if (network != null && network != nodeNetwork) { + throw grinError(9, details: {'reason': 'wrong_network'}); + } + 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 with ChangeNotifier implements Prefs { + bool tor = false; + + bool get killSwitch => _killSwitch; + bool _killSwitch = true; + set killSwitch(bool value) { + _killSwitch = value; + notifyListeners(); + } + + @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; + + /// Called on every node read, so a test can change the node or prefs + /// between two reads. + void Function()? onNodeRead; + + @override + NodeModel getCurrentNode() { + final current = node; + onNodeRead?.call(); + return current; + } + + @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; +} + +/// Puts Grin in the app config's coin list for this test file, because a +/// wallet's coin must be listed there. An app config that does not list +/// Grin (Stack Duo, Campfire, or Stack Wallet before Grin is offered) gets +/// it for the tests, which use a fake library. +void useGrinCoinConfig() { + if (AppConfig.coins.whereType().isNotEmpty) return; + AppConfig.coinsOverride = [ + ...AppConfig.coins, + Grin(CryptoCurrencyNetwork.main), + ]; +} + +/// 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, + GrinPaymentProofSummary? proof, +}) => 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: proof, + 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/widget_tests/node_tls_trust_test.dart b/test/widget_tests/node_tls_trust_test.dart index 6873d8b32..0d405e9b5 100644 --- a/test/widget_tests/node_tls_trust_test.dart +++ b/test/widget_tests/node_tls_trust_test.dart @@ -9,6 +9,7 @@ import 'package:logger/logger.dart' show Level; import 'package:mockito/mockito.dart'; import 'package:mutex/mutex.dart'; import 'package:platform/platform.dart'; +import 'package:stackwallet/widgets/icon_widgets/x_icon.dart'; import 'package:stackwallet/db/hive/db.dart'; import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/models/node_model.dart'; @@ -26,6 +27,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 +407,223 @@ 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('a Grin host that stops being an onion host gets its earlier ' + 'network and SSL settings back', (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, + ), + ), + ), + ); + final field = find.byKey(const Key('addCustomNodeNodeAddressFieldKey')); + await tester.enterText(field, 'node.example'); + await tester.pump(); + await tester.tap(find.text('Use SSL')); + await tester.pump(); + await tester.tap(find.text('Only non-TOR traffic')); + await tester.pump(); + expect(data.useSSL, true); + expect(data.netOption, TorPlainNetworkOption.clear); + + await tester.enterText(field, 'wallet.example.onion'); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.tor); + expect(data.useSSL, false); + + await tester.enterText(field, 'other.example'); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.clear); + expect(data.useSSL, true); + }); + + testWidgets('clearing a Grin onion host with X puts back the earlier ' + 'settings, and a network option picked after it stays', (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, + ), + ), + ), + ); + final field = find.byKey(const Key('addCustomNodeNodeAddressFieldKey')); + await tester.enterText(field, 'node.example'); + await tester.pump(); + await tester.tap(find.text('Use SSL')); + await tester.pump(); + expect(data.useSSL, true); + await tester.enterText(field, 'wallet.example.onion'); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.tor); + expect(data.useSSL, false); + + await tester.tap(find.descendant(of: field, matching: find.byType(XIcon))); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.both); + expect(data.useSSL, true); + + await tester.tap(find.text('Only non-TOR traffic')); + await tester.pump(); + await tester.enterText(field, 'n'); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.clear); + expect(data.useSSL, true); + }); + + testWidgets('a saved Grin onion node changed to a clearnet host gets the ' + 'public node defaults', (tester) async { + coin = Grin(CryptoCurrencyNetwork.main); + final data = NodeFormData(); + await pump( + tester, + Scaffold( + body: SingleChildScrollView( + child: NodeForm( + node: NodeModel( + host: 'http://wallet.example.onion', + port: 3413, + name: 'onion', + id: 'onion-node', + useSSL: false, + enabled: true, + coinName: coin.identifier, + isFailover: false, + isDown: false, + torEnabled: true, + clearnetEnabled: false, + isPrimary: false, + ), + data: data, + secureStore: storage, + readOnly: false, + coin: coin, + ), + ), + ), + ); + await tester.enterText( + find.byKey(const Key('addCustomNodeNodeAddressFieldKey')), + 'node.example', + ); + await tester.pump(); + expect(data.netOption, TorPlainNetworkOption.both); + expect(data.useSSL, true); + }); + + testWidgets('a Grin onion node typed with https:// says why it cannot be ' + 'tested', (tester) async { + coin = Grin(CryptoCurrencyNetwork.main); + bool? canTest; + await pump( + tester, + Scaffold( + body: SingleChildScrollView( + child: NodeForm( + data: NodeFormData(), + secureStore: storage, + readOnly: false, + coin: coin, + onChanged: (_, test) => canTest = test, + ), + ), + ), + ); + final field = find.byKey(const Key('addCustomNodeNodeAddressFieldKey')); + await tester.enterText( + find.byKey(const Key('addCustomNodeNodePortFieldKey')), + '3413', + ); + + await tester.enterText(field, 'https://wallet.example.onion'); + await tester.pump(); + expect(find.text('Onion nodes must use http://.'), findsOneWidget); + expect(canTest, isFalse); + + await tester.enterText(field, 'http://wallet.example.onion'); + await tester.pump(); + expect(find.text('Onion nodes must use http://.'), findsNothing); + expect(canTest, isTrue); + }); + testWidgets( 'Forget in read-only Details is an immediate certificate-only write', (tester) async { diff --git a/tool/process_pubspec_deps.dart b/tool/process_pubspec_deps.dart index d6c2b09cd..227812c2e 100644 --- a/tool/process_pubspec_deps.dart +++ b/tool/process_pubspec_deps.dart @@ -53,7 +53,15 @@ void _process(String filePath, List enableCoinMarkers) { } } - File(filePath).writeAsStringSync(updatedLines.join('\n')); + // PLACEHOLDER_IF_ becomes true for an enabled marker and false for + // any other, for a setting that follows a marker outside its block. + final output = updatedLines + .join('\n') + .replaceAllMapped( + RegExp(r'PLACEHOLDER_IF_([A-Z0-9_]+)'), + (match) => '${enableCoinMarkers.contains(match[1])}', + ); + File(filePath).writeAsStringSync(output); print( 'Updated pubspec.yaml with enabled blocks: ${enableCoinMarkers.join(", ")}', ); 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 000000000..14a9e3a88 --- /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 +}