-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfusion.dart
More file actions
1826 lines (1568 loc) · 62.5 KB
/
fusion.dart
File metadata and controls
1826 lines (1568 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:bitbox/bitbox.dart' as bitbox;
import 'package:coinlib/coinlib.dart' as coinlib;
import 'package:fixnum/fixnum.dart';
import 'package:fusiondart/src/comms.dart';
import 'package:fusiondart/src/connection.dart';
import 'package:fusiondart/src/covert/covert_submitter.dart';
import 'package:fusiondart/src/encrypt.dart';
import 'package:fusiondart/src/exceptions.dart';
import 'package:fusiondart/src/extensions/on_big_int.dart';
import 'package:fusiondart/src/extensions/on_list_int.dart';
import 'package:fusiondart/src/extensions/on_uint8list.dart';
import 'package:fusiondart/src/models/address.dart';
import 'package:fusiondart/src/models/blind_signature_request.dart';
import 'package:fusiondart/src/models/output.dart';
import 'package:fusiondart/src/models/transaction.dart';
import 'package:fusiondart/src/models/utxo_dto.dart';
import 'package:fusiondart/src/output_handling.dart';
import 'package:fusiondart/src/protobuf/fusion.pb.dart';
import 'package:fusiondart/src/protocol.dart';
import 'package:fusiondart/src/receive_messages.dart';
import 'package:fusiondart/src/status.dart';
import 'package:fusiondart/src/util.dart';
import 'package:fusiondart/src/validation.dart';
import 'package:protobuf/protobuf.dart';
final bool kDebugPrintEnabled = true;
final class FusionParams {
/// CashFusion server host.
///
/// Should default to Electron Cash's default: `fusion.servo.cash`.
final String serverHost;
/// CashFusion server port.
///
/// Should default to Electron Cash's default: `8789`.
final int serverPort;
/// Should SSL be used to connect to the CashFusion server?
final bool serverSsl;
FusionParams({
// TODO change this to Electron Cash's default before release:
// this.serverHost = "fusion.servo.cash",
// this.serverPort = 8789,
this.serverHost = "cashfusion.stackwallet.com",
this.serverPort = 8787,
this.serverSsl = false,
});
}
class Fusion {
final FusionParams _fusionParams;
// Private late finals used for dependency injection.
late final Future<List<Map<String, dynamic>>> Function(String address)
_getTransactionsByAddress;
late final Future<List<Address>> Function(int numberOfAddresses)
_getUnusedReservedChangeAddresses;
late final Future<({InternetAddress host, int port})> Function()
_getSocksProxyAddress;
late final Future<int> Function() _getChainHeight;
late final void Function({required FusionStatus status, String? info})
_updateStatusCallback;
late final Future<Map<String, dynamic>> Function(String txid)
_getTransactionJson;
late final Future<Uint8List> Function(List<int> pubKey)
_getPrivateKeyForPubKey;
late final Future<String> Function(String txHex) _broadcastTransaction;
late final Future<void> Function(List<Address> addresses) _unReserveAddresses;
Fusion(this._fusionParams);
/// Method to initialize Fusion instance with necessary wallet methods.
Future<void> initFusion({
required final Future<List<Map<String, dynamic>>> Function(String address)
getTransactionsByAddress,
required final Future<List<Address>> Function(int numberOfAddresses)
getUnusedReservedChangeAddresses,
required final Future<({InternetAddress host, int port})> Function()
getSocksProxyAddress,
required final Future<int> Function() getChainHeight,
required final void Function({required FusionStatus status, String? info})
updateStatusCallback,
required final Future<Map<String, dynamic>> Function(String txid)
getTransactionJson,
required final Future<Uint8List> Function(List<int> pubKey)
getPrivateKeyForPubKey,
required final Future<String> Function(String txHex) broadcastTransaction,
required final Future<void> Function(List<Address> addresses)
unReserveAddresses,
}) async {
_getTransactionsByAddress = getTransactionsByAddress;
_getUnusedReservedChangeAddresses = getUnusedReservedChangeAddresses;
_getSocksProxyAddress = getSocksProxyAddress;
_getChainHeight = getChainHeight;
_updateStatusCallback = updateStatusCallback;
_getTransactionJson = getTransactionJson;
_getPrivateKeyForPubKey = getPrivateKeyForPubKey;
_broadcastTransaction = broadcastTransaction;
_unReserveAddresses = unReserveAddresses;
// Load coinlib.
await coinlib.loadCoinlib();
}
///
/// Current status of the fusion process
///
({FusionStatus status, String info}) get status => _status;
late ({FusionStatus status, String info}) _status;
void _updateStatus({
required FusionStatus status,
required String info,
}) {
_status = (status: status, info: info);
_updateStatusCallback(status: status, info: info);
Utilities.debugPrint(
"======= FusionStatus update ====================================");
Utilities.debugPrint("=~ Status: $status");
Utilities.debugPrint("=~ info: $info");
Utilities.debugPrint(
"================================================================");
}
/// Have we connected to the server?
// Assigned but not used.
// bool _serverConnectedAndGreeted = false;
Completer<void>? _stopCompleter;
bool _stopRequested = false;
({
int numComponents,
int componentFeeRate,
int minExcessFee,
int maxExcessFee,
List<int> availableTiers,
})? _serverParams;
({
List<UtxoDTO> inputs,
Map<int, List<int>> tierOutputs,
BigInt safetySumIn,
Map<int, int> safetyExcessFees,
})? _allocatedOutputs;
({
int tier,
int covertPort,
bool covertSSL,
Uint8List covertDomainB,
double beginTime,
List<Output> outputs,
List<int> lastHash,
})? _registerAndWaitResult;
/// List of reserved addresses.
List<Address> _reservedAddresses = <Address>[];
/// The time when Fusion began.
DateTime _tFusionBegin = DateTime.now();
static const INACTIVE_TIME_LIMIT = Duration(minutes: 10);
/// Maturity for coinbase UTXOs.
static const int COINBASE_MATURITY = 100;
// https://github.com/Electron-Cash/Electron-Cash/blob/48ac434f9c7d94b335e1a31834ee2d7d47df5802/electroncash/bitcoin.py#L65
/// Outputs to allocate for fusion.
static const int DEFAULT_MAX_COINS = 20;
// https://github.com/Electron-Cash/Electron-Cash/blob/master/electroncash_plugins/fusion/plugin.py#L68
/// For semi-linked addresses (that share txids in their history), allow linking them with this probability.
static const double KEEP_LINKED_PROBABILITY = 0.1;
// https://github.com/Electron-Cash/Electron-Cash/blob/master/electroncash_plugins/fusion/plugin.py#L62
/// Guess that expected number of coins in wallet in equilibrium is = (this number) / fraction
static const COIN_FRACTION_FUDGE_FACTOR = 10;
// https://github.com/Electron-Cash/Electron-Cash/blob/48ac434f9c7d94b335e1a31834ee2d7d47df5802/electroncash_plugins/fusion/plugin.py#L60
// /// Not currently used. If needed, this should be made private and accessed using set/get
// bool autofuseCoinbase = false; // link to a setting in the wallet.
// https://github.com/Electron-Cash/Electron-Cash/blob/48ac434f9c7d94b335e1a31834ee2d7d47df5802/electroncash_plugins/fusion/conf.py#L68
/// The transaction ID of the most recent fusion transaction.
///
/// Null until first successful fusion.
String? lastTxId;
/// Executes the fusion operation.
///
/// This method orchestrates the entire lifecycle of a CashFusion operation.
Future<void> fuse({
required List<UtxoDTO> inputsFromWallet,
required coinlib.NetworkParams network,
}) async {
Utilities.debugPrint("DEBUG FUSION 223...fusion run....");
// new stopping completer
_stopCompleter = Completer();
_stopRequested = false;
/// Number runRound calls
int roundCount = 0;
// set connecting state if not already done
_updateStatus(
status: FusionStatus.connecting,
info: "Connecting to the CashFusion server.");
try {
if (inputsFromWallet.isEmpty) {
throw FusionError('Started with no coins');
}
} catch (e, s) {
Utilities.debugPrint("$e\n$s");
return;
}
Connection? connection;
try {
// Check if can connect to Tor proxy, if not, raise FusionError.
try {
await _getSocksProxyAddress();
} catch (e) {
throw FusionError("Can't connect to Tor proxy");
}
if (_checkStop(connection, null)) {
return;
}
// Connect to server.
try {
connection = await Connection.openConnection(
host: _fusionParams.serverHost,
port: _fusionParams.serverPort,
connTimeout: Duration(seconds: 5),
defaultTimeout: Duration(seconds: 5),
ssl: _fusionParams.serverSsl,
proxyInfo: await _getSocksProxyAddress(),
);
} catch (e, s) {
_updateStatus(
status: FusionStatus.failed,
info: "Failed to connect to the server! Please try again.");
Utilities.debugPrint("Connect failed: $e");
Utilities.debugPrint(s);
String sslStr = _fusionParams.serverSsl ? ' SSL ' : '';
throw FusionError(
"Could not connect to "
"$sslStr${_fusionParams.serverHost}:${_fusionParams.serverPort}",
);
}
if (_checkStop(connection, null)) {
return;
}
// Once connection is successful, wrap operations inside this block.
//
// Within this block, version checks, downloads server params, handles coins and runs rounds.
try {
// Version check and download server params.
try {
_serverParams = await Comms.greet(
connection: connection,
);
} catch (e, s) {
Utilities.debugPrint("Exception greeting server: $e");
Utilities.debugPrint("$s");
rethrow;
}
// _serverConnectedAndGreeted = true;
// In principle we can hook a pause in here -- user can insert coins after seeing server params.
// If this can/will be done then this function should be broken in two
//
//
// move this further up for now
// try {
// if (_coins.isEmpty) {
// throw FusionError('Started with no coins');
// }
// } catch (e) {
// Utilities.debugPrint(e);
// return;
// }
if (_checkStop(connection, null)) {
return;
}
final currentChainHeight = await _getChainHeight();
// Allocate outputs for fusion.
_updateStatus(
status: FusionStatus.setup, info: "Allocating inputs for fusion.");
try {
_allocatedOutputs = await OutputHandling.allocateOutputs(
connection: connection,
// A non-null [connection] would've been caught by IO.greet()'s try-catch above, no need to check or handle it here.
status: status.status,
coins: inputsFromWallet,
currentChainHeight: currentChainHeight,
serverParams: _serverParams!,
getTransactionsByAddress: _getTransactionsByAddress,
);
} on FusionStopRequested {
return;
} catch (e, s) {
_updateStatus(
status: FusionStatus.failed,
info: "Failed to allocate inputs, please try again.");
Utilities.debugPrint("Exception allocating outputs: $e");
Utilities.debugPrint("$s");
}
// In principle we can hook a pause in here -- user can tweak tier_outputs, perhaps cancelling some unwanted tiers.
Utilities.debugPrint("Registering for tiers, waiting for a pool...");
if (_checkStop(connection, null)) {
return;
}
try {
// Register for tiers, wait for a pool.
_registerAndWaitResult = await registerAndWait(
connection: connection,
allocatedOutputs: _allocatedOutputs!,
network: network,
);
} on FusionStopRequested {
return;
}
if (_checkStop(connection, null)) {
return;
}
Utilities.debugPrint("Starting covert submitter...");
final CovertSubmitter covert;
try {
// launch the covert submitter
covert = await startCovert(
connection: connection,
covertPort: _registerAndWaitResult!.covertPort,
covertSSL: _registerAndWaitResult!.covertSSL,
covertDomainB: _registerAndWaitResult!.covertDomainB,
tFusionBegin: _tFusionBegin,
serverParams: _serverParams!,
);
} on FusionStopRequested {
return;
}
if (_checkStop(connection, covert)) {
return;
}
_updateStatus(
status: FusionStatus.running, info: "Running fusion rounds.");
try {
// Pool started. Keep running rounds until fail or complete.
bool done = false;
while (!done) {
try {
done = await runRound(
roundCount: roundCount,
covert: covert,
connection: connection,
network: network,
);
roundCount += 1;
} catch (e, s) {
Utilities.debugPrint("runRound failed: $e\n$s");
_updateStatus(status: FusionStatus.failed, info: "$e");
done = true;
}
}
} finally {
covert.stop();
}
} finally {
try {
// Close connection.
await connection.close();
} catch (e, s) {
Utilities.debugPrint("Exception closing connection: $e");
Utilities.debugPrint("$s");
}
}
// Wait for transaction to show up in wallet.
waitForTx:
for (int i = 0; i < 60; i++) {
if (_stopRequested) {
break; // not an error
}
if (lastTxId != null) {
// This null check shouldn't be moved outside of this for because if
// we don't know what txid to wait for, we still want to wait 60 secs.
bool wait = true;
try {
await _getTransactionJson(lastTxId!).then((tx) {
if (tx['confirmations'] as int > 0) {
_updateStatus(
status: FusionStatus.complete,
info: "Fusion complete. Transaction confirmed.");
wait = false;
}
});
} catch (e, s) {
if (e
.toString()
.contains("No such mempool or blockchain transaction")) {
// Transaction not found, wait.
Utilities.debugPrint("Transaction not found, waiting...");
} else {
Utilities.debugPrint("Exception getting transaction: $e");
Utilities.debugPrint("$s");
rethrow;
}
}
if (!wait) {
break waitForTx;
}
}
await Future<void>.delayed(Duration(seconds: 1));
}
// Set status to 'complete' with txid.
_updateStatus(status: FusionStatus.complete, info: "Fusion complete.");
} finally {
// clearCoins();
if (status.status != FusionStatus.complete) {
await _unReserveAddresses(_reservedAddresses);
}
}
} // End of `fuse()`.
Future<void> stop() async {
_updateStatus(status: FusionStatus.running, info: "Stopping fusion.");
if (_stopRequested) {
return;
}
_stopRequested = true;
return _stopCompleter?.future;
}
/// Checks if the system should stop the current operation.
///
/// This function is periodically called to determine whether the system should
/// halt its operation.
bool _checkStop(
Connection? connection,
CovertSubmitter? covertSubmitter,
) {
// Gets called occasionally from fusion thread to allow a stop point.
if (_stopRequested) {
final List<Future<void>> futures = [];
if (connection != null) {
futures.add(connection.close());
}
if (covertSubmitter != null) {
futures.add(covertSubmitter.killConnections());
}
Future.wait(futures).then((value) => _stopCompleter!.complete());
return true;
}
return false;
}
/// Registers a client to a fusion server and waits for the fusion process to start.
///
/// This method is responsible for the client-side setup and management of the
/// CashFusion protocol. It sends registration messages to the server,
/// maintains state, and listens for updates through a [socketWrapper]
Future<
({
int tier,
int covertPort,
bool covertSSL,
Uint8List covertDomainB,
double beginTime,
List<Output> outputs,
List<int> lastHash,
})> registerAndWait({
required Connection connection,
required ({
List<UtxoDTO> inputs,
Map<int, List<int>> tierOutputs,
BigInt safetySumIn,
Map<int, int> safetyExcessFees,
}) allocatedOutputs,
required coinlib.NetworkParams network,
}) async {
// Initialize a stopwatch to measure elapsed time.
Stopwatch stopwatch = Stopwatch()..start();
// Placeholder for messages from the server.
GeneratedMessage msg;
// Initialize a map to store the outputs for each tier.
Map<int, List<int>> tierOutputs = allocatedOutputs.tierOutputs;
// Sort the tiers in ascending order.
List<int> tiersSorted = tierOutputs.keys.toList()..sort();
// Check if tierOutputs is empty and throw an error if so.
if (tierOutputs.isEmpty) {
_updateStatus(
status: FusionStatus.failed,
info: "Failed to allocate inputs, please try again.");
throw FusionError(
'No outputs available at any tier (selected inputs were too small / too large).');
}
Utilities.debugPrint('registering for tiers: $tiersSorted');
_updateStatus(status: FusionStatus.waiting, info: "");
// Temporary initialization of some CashFusion parameters.
int selfFuse = 1; // Temporary value for now.
List<int> cashfusionTag = [1]; // Temporary value for now.
// Prechecks before proceeding.
if (_checkStop(connection, null)) {
throw FusionStopRequested();
}
// Prepare tags for joining the pool.
List<JoinPools_PoolTag> tags = [
JoinPools_PoolTag(id: cashfusionTag, limit: selfFuse)
];
// Create the JoinPools message.
JoinPools joinPools =
JoinPools(tiers: tiersSorted.map((i) => Int64(i)).toList(), tags: tags);
// Wrap it in a ClientMessage.
ClientMessage clientMessage = ClientMessage()..joinpools = joinPools;
// Send the message to the server.
await Comms.sendPb(
connection,
clientMessage,
);
_updateStatus(status: FusionStatus.waiting, info: 'Registered for tiers');
Map<dynamic, String> tiersStrings = {
for (var entry in tierOutputs.entries)
entry.key:
(entry.key * 1e-8).toStringAsFixed(8).replaceAll(RegExp(r'0+$'), '')
};
// Main loop to receive updates from the server.
while (true) {
Utilities.debugPrint("RECEIVE LOOP 870............DEBUG");
msg = await Comms.recvPb(
[
ReceiveMessages.tierStatusUpdate,
ReceiveMessages.fusionBegin,
],
connection: connection,
covert: false,
timeout: Duration(seconds: 10),
);
// Check for a FusionBegin message.
FieldInfo<dynamic>? fieldInfoFusionBegin =
msg.info_.byName[ReceiveMessages.fusionBegin];
if (fieldInfoFusionBegin == null) {
throw FusionError(
'Expected field not found in message: $ReceiveMessages.fusionbegin');
}
// Validate that the received message is indeed a FusionBegin message.
final bool messageIsFusionBegin =
msg.hasField(fieldInfoFusionBegin.tagNumber);
if (messageIsFusionBegin) {
Utilities.debugPrint("DEBUG 867 Fusion Begin message...");
break;
} /* else {
throw FusionError('Expected a FusionBegin message');
}
*/
// Prechecks before processing the received message.
if (_checkStop(connection, null)) {
throw FusionStopRequested();
}
// Initialize a variable to store field information for "tierstatusupdate" in the message.
FieldInfo<dynamic>? fieldInfo =
msg.info_.byName[ReceiveMessages.tierStatusUpdate];
// Check if the field exists in the message, if not, throw an error.
if (fieldInfo == null) {
throw FusionError(
'Expected field not found in message: ${ReceiveMessages.tierStatusUpdate}');
}
// Determine if the message contains a "TierStatusUpdate"
final bool messageIsTierStatusUpdate = msg.hasField(fieldInfo.tagNumber);
Utilities.debugPrint("DEBUG 889 getting tier update.");
// If the message doesn't contain a "TierStatusUpdate", throw an error.
if (!messageIsTierStatusUpdate) {
throw FusionError('Expected a TierStatusUpdate message');
}
// Initialize a map to store the statuses from the TierStatusUpdate message.
final Map<Int64, TierStatusUpdate_TierStatus> statuses;
// Populate the statuses map if "TierStatusUpdate" exists in the message.
if (messageIsTierStatusUpdate) {
/*TierStatusUpdate tierStatusUpdate = msg.tierstatusupdate;*/
TierStatusUpdate tierStatusUpdate =
msg.getField(fieldInfo.tagNumber) as TierStatusUpdate;
statuses = tierStatusUpdate.statuses;
} else {
throw Exception("messageIsTierStatusUpdate is false");
}
// Utilities.debugPrint("DEBUG 8892 statuses: $statuses.");
// Utilities.debugPrint("DEBUG 8893 statuses: ${statuses!.entries}.");
// Initialize variables to store the maximum fraction and tier numbers.
double maxFraction = 0.0;
List<int> maxTiers = <int>[];
int? bestTime;
int? bestTimeTier;
// Loop through each entry in statuses to find the maximum fraction and best time.
for (var entry in statuses.entries) {
// Calculate the fraction of players to minimum players.
final double frac = ((entry.value.players.toInt())) /
((entry.value.minPlayers.toInt()));
// Update 'maxFraction' and 'maxTiers' if the current fraction is greater than or equal to the current 'maxFraction'.
if (frac >= maxFraction) {
if (frac > maxFraction) {
maxFraction = frac;
maxTiers.clear();
}
maxTiers.add(entry.key.toInt());
}
// // Check if "timeRemaining" field exists and find the smallest time.
FieldInfo<dynamic>? fieldInfoTimeRemaining =
entry.value.info_.byName["timeRemaining"];
/*
if (fieldInfoTimeRemaining == null) {
throw FusionError(
'Expected field not found in message: timeRemaining');
}
*/
// Check if the field 'timeRemaining' exists in the current entry.
if (fieldInfoTimeRemaining != null) {
// Confirm that the message contains the 'timeRemaining' field.
if (entry.value.hasField(fieldInfoTimeRemaining.tagNumber)) {
// Convert 'timeRemaining' to integer
int tr = entry.value.timeRemaining.toInt();
// Update 'bestTime' and 'bestTimeTier' if this is the first time or if 'tr' is smaller than the current 'bestTime'
if (bestTime == null || tr < bestTime) {
bestTime = tr;
bestTimeTier = entry.key.toInt();
}
}
}
// Do we need to handle the else case when timeRemaining is missing?
}
// Initialize lists to store tiers for different display sections.
List<String> displayBest = <String>[];
List<String> displayMid = <String>[];
List<String> displayQueued = <String>[];
// Populate the display lists based on the tier status.
for (int tier in tiersSorted) {
if (statuses.containsKey(tier)) {
String? tierStr = tiersStrings[tier];
if (tierStr == null) {
throw FusionError(
'server reported status on tier we are not registered for');
}
if (tier == bestTimeTier) {
displayBest.insert(0, '**$tierStr**');
} else if (maxTiers.contains(tier)) {
displayBest.add('[$tierStr]');
} else {
displayMid.add(tierStr);
}
} else {
displayQueued.add(tiersStrings[tier]!);
}
}
// Construct the final display string for tiers.
List<String> parts = <String>[];
if (displayBest.isNotEmpty || displayMid.isNotEmpty) {
parts.add("Tiers: ${displayBest.join(', ')} ${displayMid.join(', ')}");
}
if (displayQueued.isNotEmpty) {
parts.add("Queued: ${displayQueued.join(', ')}");
}
String tiersString = parts.join(' ');
// Determine the overall status based on the best time and maximum fraction.
if (bestTime == null) {
if (stopwatch.elapsedMilliseconds >
INACTIVE_TIME_LIMIT.inMilliseconds) {
throw FusionError('stopping due to inactivity');
}
}
// Final status assignment based on calculated variables
if (bestTime != null) {
_updateStatus(
status: FusionStatus.waiting,
info: 'Starting in ${bestTime}s. $tiersString',
);
} else if (maxFraction >= 1) {
_updateStatus(
status: FusionStatus.waiting,
info: 'Starting soon. $tiersString',
);
} else if (displayBest.isNotEmpty || displayMid.isNotEmpty) {
_updateStatus(
status: FusionStatus.waiting,
info: '${(maxFraction * 100).round()}% full. $tiersString',
);
} else {
_updateStatus(
status: FusionStatus.waiting,
info: tiersString,
);
}
} // End of while loop. Loop exits with a break if a FusionBegin message is received.
// Check if the field 'fusionbegin' exists in the message.
FieldInfo<dynamic>? fieldInfoFusionBegin =
msg.info_.byName[ReceiveMessages.fusionBegin];
if (fieldInfoFusionBegin == null) {
throw FusionError(
'Expected field not found in message: $ReceiveMessages.fusionbegin');
}
// Determine if the message contains a FusionBegin message.
bool messageIsFusionBegin = msg.hasField(fieldInfoFusionBegin.tagNumber);
// Check if the received message is a FusionBegin message.
if (!messageIsFusionBegin) {
throw FusionError('Expected a FusionBegin message');
}
// Record the time when the fusion process began.
_tFusionBegin = DateTime.now();
// Check if the received message is a ServerMessage.
if (msg is! ServerMessage) {
throw FusionError('Expected a ServerMessage');
}
// Retrieve the FusionBegin message from the ServerMessage.
FusionBegin fusionBeginMsg = msg.fusionbegin;
// Calculate the time discrepancy between the server and the client.
double clockMismatch = fusionBeginMsg.serverTime.toInt() -
DateTime.now().millisecondsSinceEpoch / 1000;
// Check if the clock mismatch exceeds the maximum allowed discrepancy.
if (clockMismatch.abs().toDouble() > Protocol.MAX_CLOCK_DISCREPANCY) {
throw FusionError(
"Clock mismatch too large: ${(clockMismatch.toDouble()).toStringAsFixed(3)}.");
}
// Retrieve the tier in which the fusion process will occur.
final tier = fusionBeginMsg.tier.toInt();
// Populate covertDomainB with the received covert domain information.
final covertDomainB = Uint8List.fromList(fusionBeginMsg.covertDomain);
// Retrieve additional information such as port, SSL status, and server time for the fusion process.
final covertPort = fusionBeginMsg.covertPort;
final covertSSL = fusionBeginMsg.covertSsl;
final beginTime = fusionBeginMsg.serverTime.toDouble();
// Calculate the initial hash value for the fusion process
final lastHash = Utilities.calcInitialHash(
tier,
covertDomainB,
covertPort,
covertSSL,
beginTime,
);
// Retrieve the output amounts for the given tier and prepare the output addresses.
List<int>? outAmounts = tierOutputs[tier];
final List<Address> outAddrs;
if (outAmounts != null && outAmounts.isNotEmpty) {
outAddrs = await _getUnusedReservedChangeAddresses(outAmounts.length);
} else {
outAddrs = [];
}
// Populate reservedAddresses and outputs with the prepared amounts and addresses.
_reservedAddresses = outAddrs;
final outputs = Utilities.zip(outAmounts ?? [], outAddrs)
.map((pair) => Output.fromAddress(
value: pair[0] as int,
address: (pair[1] as Address).address,
network: network,
))
.toList();
Utilities.debugPrint(
"starting fusion rounds at tier $tier: ${allocatedOutputs.inputs.length} inputs and ${outputs.length} outputs");
return (
tier: tier,
covertPort: covertPort,
covertSSL: covertSSL,
covertDomainB: covertDomainB,
beginTime: beginTime,
outputs: outputs,
lastHash: lastHash,
);
}
/// Starts a CovertSubmitter and schedules Tor connections.
///
/// This method initializes a `CovertSubmitter` with the specified configuration,
/// schedules the connections, and continuously checks the connection status.
Future<CovertSubmitter> startCovert({
required Connection? connection,
required int covertPort,
required bool covertSSL,
required Uint8List covertDomainB,
required DateTime tFusionBegin,
required ({
int numComponents,
int componentFeeRate,
int minExcessFee,
int maxExcessFee,
List<int> availableTiers,
}) serverParams,
}) async {
Utilities.debugPrint("DEBUG START COVERT!");
// set status record/tuple.
_updateStatus(
status: FusionStatus.running,
info: 'Setting up Tor connections',
);
// Get the Tor host and port from the wallet configuration.
final ({InternetAddress host, int port}) proxyInfo;
try {
proxyInfo = await _getSocksProxyAddress();
} catch (e) {
throw FusionError("startCovert() can't connect to Tor proxy");
}
// Decode the covert domain and validate it.
String covertDomain;
try {
covertDomain = utf8.decode(covertDomainB);
} catch (e) {
throw FusionError('badly encoded covert domain');
}
// Create a new CovertSubmitter instance.
CovertSubmitter covert = CovertSubmitter(
destAddr: covertDomain,
destPort: covertPort,
ssl: covertSSL,
proxyInfo: proxyInfo,
numSlots: serverParams.numComponents,
randSpan: Protocol.COVERT_SUBMIT_WINDOW,
submitTimeout: Duration(seconds: Protocol.COVERT_SUBMIT_TIMEOUT),
);
try {
// Schedule Tor connections for the CovertSubmitter.
covert.scheduleConnectionsAndStartRunningThem(
tFusionBegin,
Duration(seconds: Protocol.COVERT_CONNECT_WINDOW),
numSpares: Protocol.COVERT_CONNECT_SPARES,
connectTimeout: Duration(
seconds: Protocol.COVERT_CONNECT_TIMEOUT,
),
);
// Loop a bit before we're expecting startRound, watching for status updates.
final tend = tFusionBegin.add(Duration(
seconds: (Protocol.WARMUP_TIME - Protocol.WARMUP_SLOP - 1).round()));
// Poll the status of the connections until the ending time.
while (DateTime.now().millisecondsSinceEpoch / 1000 <
tend.millisecondsSinceEpoch / 1000) {
// Count the number of established main and spare connections.
int numConnected =
covert.slots.where((s) => s.covConn?.connection != null).length;
int numSpareConnected =
covert.spareConnections.where((c) => c.connection != null).length;
// Update the status based on connection counts.
_updateStatus(
status: FusionStatus.running,
info: "Setting up Tor connections "
"($numConnected+$numSpareConnected out"
" of ${serverParams.numComponents})",
);
// Wait for 1 second before re-checking.
await Future<void>.delayed(Duration(seconds: 1));
// Check the health of the CovertSubmitter and overall system.
covert.checkOk();
if (_checkStop(connection, covert)) {
throw FusionStopRequested();
}
}
} catch (e) {
// Stop the CovertSubmitter and re-throw the error.
covert.stop();
rethrow;
}
// Return the CovertSubmitter instance.
return covert;
}
/// Runs a round of the Fusion protocol.
///
/// This method takes care of various steps in the Fusion protocol round,
/// including receiving and validating server messages, creating commitments,
/// and submitting components.
///
/// [covert] is a `CovertSubmitter` instance used for covert submissions.
Future<bool> runRound({
required int roundCount,
required CovertSubmitter covert,
required Connection connection,
required coinlib.NetworkParams network,
}) async {
Utilities.debugPrint("START OF RUN ROUND");
// Initial round status and timeout calculation.
_updateStatus(
status: FusionStatus.running,
info: "Starting round $roundCount",
);
int timeoutInSeconds =
(2 * Protocol.WARMUP_SLOP + Protocol.STANDARD_TIMEOUT).toInt();
// Await the start of round message from the server.
GeneratedMessage msg = await Comms.recvPb(
[ReceiveMessages.startRound],
connection: connection,
covert: false,
timeout: Duration(seconds: timeoutInSeconds),
);
/// The time when the covert timer was started.
final covertT0 = DateTime.now().millisecondsSinceEpoch / 1000;
/// Returns the time since the covert timer was started in seconds.
double covertClock() =>
(DateTime.now().millisecondsSinceEpoch / 1000) - covertT0;
// Check if the received message is a ServerMessage.
if (msg is! ServerMessage) {
throw FusionError('Expected a ServerMessage');
}