refactor TorService

This commit is contained in:
julian 2023-09-15 13:51:20 -06:00
parent d86b7a19c8
commit 4e3390a7c0
32 changed files with 257 additions and 268 deletions

View file

@ -187,8 +187,8 @@ class ElectrumX {
void _checkRpcClient() {
// If we're supposed to use Tor...
if (_prefs.useTor) {
// But Tor isn't enabled...
if (!_torService.enabled) {
// But Tor isn't running...
if (_torService.status != TorConnectionStatus.connected) {
// And the killswitch isn't set...
if (!_prefs.torKillSwitch) {
// Then we'll just proceed and connect to ElectrumX through clearnet at the bottom of this function.
@ -203,7 +203,7 @@ class ElectrumX {
}
} else {
// Get the proxy info from the TorService.
final proxyInfo = _torService.proxyInfo;
final proxyInfo = _torService.getProxyInfo();
if (currentFailoverIndex == -1) {
_rpcClient ??= JsonRPC(

View file

@ -173,7 +173,9 @@ void main() async {
// Some refactoring will need to be done here to make sure we don't make any
// network calls before starting up tor
if (Prefs.instance.useTor) {
TorService.sharedInstance.init();
TorService.sharedInstance.init(
torDataDirPath: (await StackFileSystem.applicationTorDirectory()).path,
);
await TorService.sharedInstance.start();
}

View file

@ -38,14 +38,16 @@ class BuyView extends ConsumerStatefulWidget {
class _BuyViewState extends ConsumerState<BuyView> {
Coin? coin;
EthContract? tokenContract;
late bool torEnabled = false;
late bool torEnabled;
@override
void initState() {
coin = widget.coin;
tokenContract = widget.tokenContract;
torEnabled = ref.read(pTorService).enabled;
torEnabled =
ref.read(pTorService).status != TorConnectionStatus.disconnected;
super.initState();
}

View file

@ -12,6 +12,7 @@ import 'package:stackwallet/models/isar/ordinal.dart';
import 'package:stackwallet/networking/http.dart';
import 'package:stackwallet/notifications/show_flush_bar.dart';
import 'package:stackwallet/providers/db/main_db_provider.dart';
import 'package:stackwallet/providers/global/prefs_provider.dart';
import 'package:stackwallet/providers/global/wallets_provider.dart';
import 'package:stackwallet/services/tor_service.dart';
import 'package:stackwallet/themes/stack_colors.dart';
@ -20,7 +21,6 @@ import 'package:stackwallet/utilities/amount/amount_formatter.dart';
import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/constants.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/prefs.dart';
import 'package:stackwallet/utilities/show_loading.dart';
import 'package:stackwallet/utilities/text_styles.dart';
import 'package:stackwallet/widgets/background.dart';
@ -219,7 +219,7 @@ class _DetailsItemWCopy extends StatelessWidget {
}
}
class _OrdinalImageGroup extends StatelessWidget {
class _OrdinalImageGroup extends ConsumerWidget {
const _OrdinalImageGroup({
Key? key,
required this.walletId,
@ -231,13 +231,14 @@ class _OrdinalImageGroup extends StatelessWidget {
static const _spacing = 12.0;
Future<String> _savePngToFile() async {
Future<String> _savePngToFile(WidgetRef ref) async {
HTTP client = HTTP();
final response = await client.get(
url: Uri.parse(ordinal.content),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: ref.read(prefsChangeNotifierProvider).useTor
? ref.read(pTorService).getProxyInfo()
: null,
);
if (response.code != 200) {
@ -268,7 +269,7 @@ class _OrdinalImageGroup extends StatelessWidget {
}
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
@ -318,7 +319,7 @@ class _OrdinalImageGroup extends StatelessWidget {
onPressed: () async {
bool didError = false;
final filePath = await showLoading<String>(
whileFuture: _savePngToFile(),
whileFuture: _savePngToFile(ref),
context: context,
isDesktop: true,
message: "Saving ordinal image",

View file

@ -50,8 +50,9 @@ Future<bool> doesCommitExist(
final commitQuery = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final response = jsonDecode(commitQuery.body.toString());
@ -89,8 +90,9 @@ Future<bool> isHeadCommit(
final commitQuery = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final response = jsonDecode(commitQuery.body.toString());

View file

@ -20,6 +20,7 @@ import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/constants.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/stack_file_system.dart';
import 'package:stackwallet/utilities/text_styles.dart';
import 'package:stackwallet/widgets/background.dart';
import 'package:stackwallet/widgets/conditional_parent.dart';
@ -270,9 +271,7 @@ class _TorIconState extends ConsumerState<TorIcon> {
@override
void initState() {
_status = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
_status = ref.read(pTorService).status;
super.initState();
}
@ -399,9 +398,7 @@ class _TorButtonState extends ConsumerState<TorButton> {
@override
void initState() {
_status = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
_status = ref.read(pTorService).status;
super.initState();
}
@ -455,11 +452,11 @@ class _TorButtonState extends ConsumerState<TorButton> {
///
/// Returns a Future that completes when the Tor service has started.
Future<void> _connectTor(WidgetRef ref, BuildContext context) async {
// Init the Tor service if it hasn't already been.
ref.read(pTorService).init();
// Start the Tor service.
try {
// Init the Tor service if it hasn't already been.
final torDir = await StackFileSystem.applicationTorDirectory();
ref.read(pTorService).init(torDataDirPath: torDir.path);
// Start the Tor service.
await ref.read(pTorService).start();
// Toggle the useTor preference on success.
@ -485,7 +482,7 @@ Future<void> _connectTor(WidgetRef ref, BuildContext context) async {
Future<void> _disconnectTor(WidgetRef ref, BuildContext context) async {
// Stop the Tor service.
try {
await ref.read(pTorService).stop();
await ref.read(pTorService).disable();
// Toggle the useTor preference on success.
ref.read(prefsChangeNotifierProvider).useTor = false;

View file

@ -36,6 +36,7 @@ import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/constants.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/stack_file_system.dart';
import 'package:stackwallet/utilities/text_styles.dart';
import 'package:stackwallet/utilities/util.dart';
import 'package:stackwallet/widgets/animated_text.dart';
@ -48,6 +49,7 @@ import 'package:stackwallet/widgets/progress_bar.dart';
import 'package:stackwallet/widgets/rounded_container.dart';
import 'package:stackwallet/widgets/rounded_white_container.dart';
import 'package:stackwallet/widgets/stack_dialog.dart';
import 'package:stackwallet/widgets/tor_subscription.dart';
import 'package:tuple/tuple.dart';
import 'package:wakelock/wakelock.dart';
@ -98,10 +100,6 @@ class _WalletNetworkSettingsViewState
/// The current status of the Tor connection.
late TorConnectionStatus _torConnectionStatus;
/// The subscription to the TorConnectionStatusChangedEvent.
late final StreamSubscription<TorConnectionStatusChangedEvent>
_torConnectionStatusSubscription;
Future<void> _attemptRescan() async {
if (!Platform.isLinux) await Wakelock.enable();
@ -280,22 +278,7 @@ class _WalletNetworkSettingsViewState
// );
// Initialize the TorConnectionStatus.
_torConnectionStatus = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
// Subscribe to the TorConnectionStatusChangedEvent.
_torConnectionStatusSubscription =
eventBus.on<TorConnectionStatusChangedEvent>().listen(
(event) async {
// Rebuild the widget.
setState(() {
_torConnectionStatus = event.newStatus;
});
// TODO implement spinner or animations and control from here
},
);
_torConnectionStatus = ref.read(pTorService).status;
super.initState();
}
@ -306,7 +289,6 @@ class _WalletNetworkSettingsViewState
_syncStatusSubscription.cancel();
_refreshSubscription.cancel();
_blocksRemainingSubscription?.cancel();
_torConnectionStatusSubscription.cancel();
super.dispose();
}
@ -793,7 +775,7 @@ class _WalletNetworkSettingsViewState
onTap: () async {
// Stop the Tor service.
try {
await ref.read(pTorService).stop();
await ref.read(pTorService).disable();
// Toggle the useTor preference on success.
ref.read(prefsChangeNotifierProvider).useTor = false;
@ -813,11 +795,12 @@ class _WalletNetworkSettingsViewState
prefsChangeNotifierProvider.select((value) => value.useTor)))
GestureDetector(
onTap: () async {
// Init the Tor service if it hasn't already been.
ref.read(pTorService).init();
// Start the Tor service.
try {
// Init the Tor service if it hasn't already been.
final torDir =
await StackFileSystem.applicationTorDirectory();
ref.read(pTorService).init(torDataDirPath: torDir.path);
// Start the Tor service.
await ref.read(pTorService).start();
// Toggle the useTor preference on success.
@ -827,6 +810,7 @@ class _WalletNetworkSettingsViewState
"Error starting tor: $e\n$s",
level: LogLevel.Error,
);
// TODO: show dialog with error message
}
},
child: Text(
@ -896,35 +880,46 @@ class _WalletNetworkSettingsViewState
SizedBox(
width: _boxPadding,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Tor status",
style: STextStyles.desktopTextExtraExtraSmall(context)
.copyWith(
color: Theme.of(context)
.extension<StackColors>()!
.textDark,
),
),
if (_torConnectionStatus == TorConnectionStatus.connected)
TorSubscription(
onTorStatusChanged: (status) {
setState(() {
_torConnectionStatus = status;
});
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Connected",
style: STextStyles.desktopTextExtraExtraSmall(context),
"Tor status",
style: STextStyles.desktopTextExtraExtraSmall(context)
.copyWith(
color: Theme.of(context)
.extension<StackColors>()!
.textDark,
),
),
if (_torConnectionStatus == TorConnectionStatus.connecting)
Text(
"Connecting...",
style: STextStyles.desktopTextExtraExtraSmall(context),
),
if (_torConnectionStatus ==
TorConnectionStatus.disconnected)
Text(
"Disconnected",
style: STextStyles.desktopTextExtraExtraSmall(context),
),
],
if (_torConnectionStatus == TorConnectionStatus.connected)
Text(
"Connected",
style:
STextStyles.desktopTextExtraExtraSmall(context),
),
if (_torConnectionStatus ==
TorConnectionStatus.connecting)
Text(
"Connecting...",
style:
STextStyles.desktopTextExtraExtraSmall(context),
),
if (_torConnectionStatus ==
TorConnectionStatus.disconnected)
Text(
"Disconnected",
style:
STextStyles.desktopTextExtraExtraSmall(context),
),
],
),
),
],
),

View file

@ -31,11 +31,12 @@ class DesktopBuyView extends ConsumerStatefulWidget {
}
class _DesktopBuyViewState extends ConsumerState<DesktopBuyView> {
late bool torEnabled = false;
late bool torEnabled;
@override
void initState() {
torEnabled = ref.read(pTorService).enabled;
torEnabled =
ref.read(pTorService).status != TorConnectionStatus.disconnected;
super.initState();
}
@ -62,8 +63,8 @@ class _DesktopBuyViewState extends ConsumerState<DesktopBuyView> {
),
),
),
body: Padding(
padding: const EdgeInsets.only(
body: const Padding(
padding: EdgeInsets.only(
left: 24,
right: 24,
bottom: 24,
@ -75,7 +76,7 @@ class _DesktopBuyViewState extends ConsumerState<DesktopBuyView> {
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
children: [
SizedBox(
height: 16,
),
@ -86,7 +87,7 @@ class _DesktopBuyViewState extends ConsumerState<DesktopBuyView> {
],
),
),
const SizedBox(
SizedBox(
width: 16,
),
// Expanded(

View file

@ -56,8 +56,9 @@ class _DesktopOrdinalDetailsViewState
final response = await client.get(
url: Uri.parse(widget.ordinal.content),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code != 200) {

View file

@ -22,6 +22,7 @@ import 'package:stackwallet/services/tor_service.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/stack_file_system.dart';
import 'package:stackwallet/utilities/text_styles.dart';
import 'package:stackwallet/utilities/util.dart';
import 'package:stackwallet/widgets/custom_buttons/draggable_switch_button.dart';
@ -59,11 +60,11 @@ class _TorSettingsState extends ConsumerState<TorSettings> {
width: 200,
buttonHeight: ButtonHeight.m,
onPressed: () async {
// Init the Tor service if it hasn't already been.
ref.read(pTorService).init();
// Start the Tor service.
try {
// Init the Tor service if it hasn't already been.
final torDir = await StackFileSystem.applicationTorDirectory();
ref.read(pTorService).init(torDataDirPath: torDir.path);
// Start the Tor service.
await ref.read(pTorService).start();
// Toggle the useTor preference on success.
@ -73,6 +74,7 @@ class _TorSettingsState extends ConsumerState<TorSettings> {
"Error starting tor: $e\n$s",
level: LogLevel.Error,
);
// TODO: show dialog with error message
}
},
);
@ -93,7 +95,7 @@ class _TorSettingsState extends ConsumerState<TorSettings> {
onPressed: () async {
// Stop the Tor service.
try {
await ref.read(pTorService).stop();
await ref.read(pTorService).disable();
// Toggle the useTor preference on success.
ref.read(prefsChangeNotifierProvider).useTor = false;
@ -114,9 +116,7 @@ class _TorSettingsState extends ConsumerState<TorSettings> {
eventBus = GlobalEventBus.instance;
// Set the initial Tor connection status.
_torConnectionStatus = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
_torConnectionStatus = ref.read(pTorService).status;
// Subscribe to the TorConnectionStatusChangedEvent.
_torConnectionStatusSubscription =

View file

@ -59,7 +59,7 @@ class SimplexAPI {
url: url,
headers: headers,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
Prefs.instance.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
if (res.code != 200) {
throw Exception(
@ -125,7 +125,7 @@ class SimplexAPI {
url: url,
headers: headers,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
Prefs.instance.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
if (res.code != 200) {
throw Exception(
@ -206,7 +206,7 @@ class SimplexAPI {
url: url,
headers: headers,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
Prefs.instance.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
if (res.code != 200) {
throw Exception('getQuote exception: statusCode= ${res.code}');
@ -313,7 +313,7 @@ class SimplexAPI {
url: url,
headers: headers,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
Prefs.instance.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
if (res.code != 200) {
throw Exception('newOrder exception: statusCode= ${res.code}');

View file

@ -160,7 +160,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
},
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
)
.then((client) {
if (client.code == 200) {
@ -195,7 +195,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: balanceBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final balanceData = jsonDecode(balanceResponse.body);
@ -215,7 +215,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final String frontier =
@ -270,7 +270,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: processBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final Map<String, dynamic> decoded =
@ -344,7 +344,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: body,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final data = jsonDecode(response.body);
_balance = Balance(
@ -388,7 +388,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final infoData = jsonDecode(infoResponse.body);
@ -408,7 +408,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: balanceBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final balanceData = jsonDecode(balanceResponse.body);
@ -483,7 +483,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: processBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final Map<String, dynamic> decoded =
@ -504,7 +504,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
"count": "-1",
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final receivableData = await jsonDecode(receivableResponse.body);
@ -536,7 +536,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
"count": "-1",
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final data = await jsonDecode(response.body);
final transactions =
@ -858,7 +858,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
},
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
return response.code == 200;
@ -952,7 +952,7 @@ class BananoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final infoData = jsonDecode(infoResponse.body);

View file

@ -169,7 +169,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
},
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
)
.then((Response response) {
if (response.code == 200) {
@ -204,7 +204,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: balanceBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final balanceData = jsonDecode(balanceResponse.body);
@ -224,7 +224,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final String frontier =
@ -279,7 +279,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: processBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final Map<String, dynamic> decoded =
@ -349,7 +349,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: body,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final data = jsonDecode(response.body);
_balance = Balance(
@ -393,7 +393,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final infoData = jsonDecode(infoResponse.body);
@ -413,7 +413,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: balanceBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final balanceData = jsonDecode(balanceResponse.body);
@ -488,7 +488,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: processBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final Map<String, dynamic> decoded =
@ -509,7 +509,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
"count": "-1",
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final receivableData = await jsonDecode(receivableResponse.body);
@ -541,7 +541,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
"count": "-1",
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final data = await jsonDecode(response.body);
final transactions =
@ -869,7 +869,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
},
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
return response.code == 200;
@ -963,7 +963,7 @@ class NanoWallet extends CoinServiceAPI with WalletCache, WalletDB {
headers: headers,
body: infoBody,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
final infoData = jsonDecode(infoResponse.body);

View file

@ -245,7 +245,7 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
var response = jsonDecode((await client.get(
url: Uri.parse(api),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
))
.body)[0];
double totalFees = response[4] as double;
@ -270,7 +270,7 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
var response = jsonDecode((await client.get(
url: Uri.parse(api),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
))
.body);
double totalFees = response[0][4] as double;
@ -509,9 +509,8 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
var response = jsonDecode(await client
.get(
url: Uri.parse(balanceCall),
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.proxyInfo
: null,
proxyInfo:
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
)
.then((value) => value.body));
Amount balanceInAmount = Amount(
@ -538,9 +537,8 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
var response = jsonDecode(await client
.get(
url: Uri.parse(transactionsCall),
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.proxyInfo
: null,
proxyInfo:
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
)
.then((value) => value.body));
List<Tuple2<Transaction, Address>> txs = [];
@ -619,9 +617,8 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
var jsonParsedResponse = jsonDecode(await client
.get(
url: Uri.parse(api),
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.proxyInfo
: null,
proxyInfo:
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
)
.then((value) => value.body));
final int intHeight = int.parse(jsonParsedResponse["level"].toString());
@ -707,7 +704,7 @@ class TezosWallet extends CoinServiceAPI with WalletCache, WalletDB {
url: Uri.parse(
"${getCurrentNode().host}:${getCurrentNode().port}/chains/main/blocks/head/header/shell"),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
_prefs.useTor ? TorService.sharedInstance.getProxyInfo() : null,
);
return true;
} catch (e) {

View file

@ -61,8 +61,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/export?addrs=$address&firstBlock=$firstBlock",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -184,8 +185,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/transactions?transactions=${txns.map((e) => e.hash).join(" ")}&raw=true",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -244,8 +246,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/transactions?transactions=${txids.join(" ")}",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -303,8 +306,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/export?addrs=$address&emitter=$tokenContractAddress&logs=true",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -437,8 +441,9 @@ abstract class EthereumAPI {
);
final response = await client.get(
url: uri,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -488,8 +493,9 @@ abstract class EthereumAPI {
);
final response = await client.get(
url: uri,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -535,8 +541,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/gas-prices",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -606,8 +613,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/tokens?addrs=$contractAddress&parts=all",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -675,8 +683,9 @@ abstract class EthereumAPI {
url: Uri.parse(
"$stackBaseServer/abis?addrs=$contractAddress&verbose=true",
),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
@ -717,8 +726,9 @@ abstract class EthereumAPI {
final response = await client.get(
url: Uri.parse(
"$stackBaseServer/state?addrs=$contractAddress&parts=proxy"),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
final json = jsonDecode(response.body);

View file

@ -60,8 +60,9 @@ class ChangeNowAPI {
final response = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
String? data;
try {
@ -90,8 +91,9 @@ class ChangeNowAPI {
// 'Content-Type': 'application/json',
'x-changenow-api-key': apiKey,
},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final data = response.body;
@ -114,8 +116,9 @@ class ChangeNowAPI {
url: uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
String? data;

View file

@ -49,8 +49,9 @@ class MajesticBankAPI {
try {
final response = await client.get(
url: uri,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
code = response.code;

View file

@ -47,8 +47,9 @@ class SimpleSwapAPI {
try {
final response = await client.get(
url: uri,
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
code = response.code;
@ -74,8 +75,9 @@ class SimpleSwapAPI {
url: uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {

View file

@ -52,8 +52,9 @@ abstract class TrocadorAPI {
final response = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
code = response.code;

View file

@ -22,8 +22,9 @@ class LitescribeAPI {
Future<LitescribeResponse> _getResponse(String endpoint) async {
final response = await client.get(
url: Uri.parse('$baseUrl$endpoint'),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {
return LitescribeResponse(data: _validateJson(response.body));

View file

@ -25,8 +25,9 @@ class MonKeyService {
final response = await client.get(
url: Uri.parse(url),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
if (response.code == 200) {

View file

@ -31,8 +31,9 @@ class NanoAPI {
"representative": "true",
"account": account,
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final map = jsonDecode(response.body);
@ -124,8 +125,9 @@ class NanoAPI {
"subtype": "change",
"block": block,
}),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
return jsonDecode(response.body);

View file

@ -107,8 +107,9 @@ class PriceAPI {
final coinGeckoResponse = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final coinGeckoData = jsonDecode(coinGeckoResponse.body) as List<dynamic>;
@ -154,8 +155,9 @@ class PriceAPI {
final response = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final json = jsonDecode(response.body) as List<dynamic>;
@ -195,8 +197,9 @@ class PriceAPI {
final coinGeckoResponse = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final coinGeckoData = jsonDecode(coinGeckoResponse.body) as Map;

View file

@ -10,38 +10,45 @@ final pTorService = Provider((_) => TorService.sharedInstance);
class TorService {
Tor? _tor;
String? _torDataDirPath;
/// Current status. Same as that fired on the event bus
TorConnectionStatus get status => _status;
// set to some default value
TorConnectionStatus _status = TorConnectionStatus.disconnected;
/// Flag to indicate that a Tor circuit is thought to have been established.
bool _enabled = false;
/// Getter for the enabled flag.
bool get enabled => _enabled;
TorService._();
/// Singleton instance of the TorService.
///
/// Use this to access the TorService and its properties.
static final sharedInstance = TorService._();
// private constructor for singleton
TorService._();
/// Getter for the proxyInfo.
///
/// Returns null if disabled on the stack wallet level.
({
InternetAddress host,
int port,
}) get proxyInfo => (
}) getProxyInfo() {
if (status == TorConnectionStatus.connected) {
return (
host: InternetAddress.loopbackIPv4,
port: _tor!.port!,
port: _tor!.port,
);
} else {
throw Exception("Tor proxy info fetched while not connected!");
}
}
/// Initialize the tor ffi lib instance if it hasn't already been set. Nothing
/// changes if _tor is already been set.
void init({Tor? mockableOverride}) {
void init({
required String torDataDirPath,
Tor? mockableOverride,
}) {
_tor ??= mockableOverride ?? Tor.instance;
_torDataDirPath ??= torDataDirPath;
}
/// Start the Tor service.
@ -52,31 +59,25 @@ class TorService {
///
/// Returns a Future that completes when the Tor service has started.
Future<void> start() async {
if (_tor == null) {
if (_tor == null || _torDataDirPath == null) {
throw Exception("TorService.init has not been called!");
}
if (_enabled) {
// already started so just return
return;
}
// Start the Tor service.
try {
_updateStatusAndFireEvent(
status: TorConnectionStatus.connecting,
message: "Tor connection status changed: connecting",
message: "TorService.start call in progress",
);
await _tor!.start();
await _tor!.start(torDataDirPath: _torDataDirPath!);
// no exception or error so we can (probably?) assume tor
// has started successfully
_enabled = true;
// Fire a TorConnectionStatusChangedEvent on the event bus.
_updateStatusAndFireEvent(
status: TorConnectionStatus.connected,
message: "Tor connection status changed: connect ($_enabled)",
message: "TorService.start call success",
);
} catch (e, s) {
Logging.instance.log(
@ -88,42 +89,27 @@ class TorService {
// Fire a TorConnectionStatusChangedEvent on the event bus.
_updateStatusAndFireEvent(
status: TorConnectionStatus.disconnected,
message: "Tor connection status changed: $_enabled (failed)",
message: "TorService.start call failed",
);
rethrow;
}
}
Future<void> stop() async {
/// disable tor
Future<void> disable() async {
if (_tor == null) {
throw Exception("TorService.init has not been called!");
}
if (!_enabled) {
// already stopped so just return
// could throw an exception here or something so the caller
// is explicitly made aware of this
// TODO make sure to kill
// no need to update status and fire event if status won't change
if (_status == TorConnectionStatus.disconnected) {
return;
}
// Stop the Tor service.
try {
_tor!.disable();
// no exception or error so we can (probably?) assume tor
// has started successfully
_enabled = false;
_updateStatusAndFireEvent(
status: TorConnectionStatus.disconnected,
message: "Tor connection status changed: $_enabled (disabled)",
);
} catch (e, s) {
Logging.instance.log(
"TorService.stop failed: $e\n$s",
level: LogLevel.Warning,
);
rethrow;
}
_updateStatusAndFireEvent(
status: TorConnectionStatus.disconnected,
message: "TorService.disable call success",
);
}
void _updateStatusAndFireEvent({

View file

@ -213,8 +213,9 @@ class ThemeService {
try {
final response = await client.get(
url: Uri.parse("$baseServerUrl/themes"),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final jsonList = jsonDecode(response.body) as List;
@ -240,8 +241,9 @@ class ThemeService {
try {
final response = await client.get(
url: Uri.parse("$baseServerUrl/theme/${themeMetaData.id}"),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
final bytes = Uint8List.fromList(response.bodyBytes);

View file

@ -52,8 +52,9 @@ class PaynymIsApi {
url: uri,
headers: headers,
body: jsonEncode(body),
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
);
debugPrint("Paynym request uri: $uri");

View file

@ -24,7 +24,7 @@ Future<bool> _testEpicBoxNodeConnection(Uri uri) async {
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.proxyInfo
? TorService.sharedInstance.getProxyInfo()
: null,
)
.timeout(const Duration(milliseconds: 2000),

View file

@ -13,8 +13,9 @@ Future<bool> testStellarNodeConnection(String host, int port) async {
.get(
url: uri,
headers: {'Content-Type': 'application/json'},
proxyInfo:
Prefs.instance.useTor ? TorService.sharedInstance.proxyInfo : null,
proxyInfo: Prefs.instance.useTor
? TorService.sharedInstance.getProxyInfo()
: null,
)
.timeout(const Duration(milliseconds: 2000),
onTimeout: () async => http.Response(utf8.encode('Error'), 408));

View file

@ -81,9 +81,7 @@ class _DesktopTorStatusButtonState extends ConsumerState<DesktopTorStatusButton>
eventBus = GlobalEventBus.instance;
// Initialize the TorConnectionStatus.
_torConnectionStatus = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
_torConnectionStatus = ref.read(pTorService).status;
// Subscribe to the TorConnectionStatusChangedEvent.
_torConnectionStatusSubscription =
@ -93,25 +91,6 @@ class _DesktopTorStatusButtonState extends ConsumerState<DesktopTorStatusButton>
setState(() {
_torConnectionStatus = event.newStatus;
});
// TODO implement spinner or animations and control from here
// switch (event.newStatus) {
// case TorConnectionStatus.disconnected:
// // if (_spinController.hasLoadedAnimation) {
// // _spinController.stop?.call();
// // }
// break;
// case TorConnectionStatus.connecting:
// // if (_spinController.hasLoadedAnimation) {
// // _spinController.repeat?.call();
// // }
// break;
// case TorConnectionStatus.connected:
// // if (_spinController.hasLoadedAnimation) {
// // _spinController.stop?.call();
// // }
// break;
// }
},
);

View file

@ -37,9 +37,7 @@ class _SmallTorIconState extends ConsumerState<SmallTorIcon> {
@override
void initState() {
_status = ref.read(pTorService).enabled
? TorConnectionStatus.connected
: TorConnectionStatus.disconnected;
_status = ref.read(pTorService).status;
super.initState();
}

View file

@ -693,7 +693,7 @@ class MockTorService extends _i1.Mock implements _i11.TorService {
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> stop() => (super.noSuchMethod(
_i4.Future<void> disable() => (super.noSuchMethod(
Invocation.method(
#stop,
[],

View file

@ -1059,7 +1059,7 @@ class MockTorService extends _i1.Mock implements _i19.TorService {
returnValueForMissingStub: _i12.Future<void>.value(),
) as _i12.Future<void>);
@override
_i12.Future<void> stop() => (super.noSuchMethod(
_i12.Future<void> disable() => (super.noSuchMethod(
Invocation.method(
#stop,
[],