This repository has been archived by the owner on Dec 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
farmr.dart
808 lines (665 loc) · 24 KB
/
farmr.dart
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
import 'dart:convert';
import 'dart:isolate';
import 'package:path/path.dart';
import 'package:universal_io/io.dart' as io;
import 'dart:core';
import 'dart:math' as Math;
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'package:intl/intl.dart';
import 'package:farmr_client/farmer/farmer.dart';
import 'package:farmr_client/harvester/harvester.dart';
import 'package:farmr_client/config.dart';
import 'package:farmr_client/blockchain.dart';
import 'package:farmr_client/hpool/hpool.dart';
import 'package:farmr_client/id.dart';
import 'package:farmr_client/log/filter.dart';
import 'package:farmr_client/log/signagepoint.dart';
import 'package:farmr_client/log/shortsync.dart';
import 'package:farmr_client/log/logitem.dart';
import 'package:farmr_client/environment_config.dart';
import 'package:farmr_client/stats.dart';
import 'package:farmr_client/server/netspace.dart';
import 'package:farmr_client/server/price.dart';
import 'package:uuid/uuid.dart';
import "package:console/console.dart";
import 'package:dart_console/dart_console.dart' as dartconsole;
final log = Logger('Client');
Duration reportIntervalDuration =
Duration(minutes: 10); //10 minutes delay between updates
// '/home/user/.farmr' for package installs, '.' (project path) for the rest
String rootPath = "";
const String url = "https://farmr.net/send12.php";
const String urlBackup = "https://chiabot.znc.sh/send12.php";
//prepares rootPath
prepareRootPath(bool package) {
rootPath = (io.Platform.isLinux && package)
? io.Platform.environment['HOME']! + "/.farmr/"
: "";
//Creates /home/user/.farmr folder if that doesnt exist
if (package && !io.Directory(rootPath).existsSync()) {
//creates .farmr
io.Directory(rootPath).createSync();
}
io.Directory defaultFolder = io.Directory("/etc/farmr/blockchain");
//copies blockchain templates to .farmr
if (package) {
String blockchainDir = rootPath + "blockchain";
if (!io.Directory(blockchainDir).existsSync()) {
io.Directory(blockchainDir).createSync();
}
//Links files from /etc/farmr/blockchain to user's .farmr/blockchain folder
for (var path in defaultFolder.listSync()) {
io.File file = io.File(path.path);
io.File destFile = io.File(blockchainDir + "/" + basename(file.path));
if (file.existsSync() && !destFile.existsSync()) {
io.Link(destFile.path).createSync(file.path);
}
}
}
}
createDirsAndportOldFiles(String rootPath) {
io.Directory configDir = io.Directory(rootPath + "config");
io.File configFile = io.File(rootPath + "config.json");
if (!configDir.existsSync()) {
configDir.createSync();
if (configFile.existsSync()) {
configFile.copySync(rootPath + "config/config-xch.json");
configFile.deleteSync();
}
}
io.Directory cacheDir = io.Directory(rootPath + "cache");
List<io.File> cacheFiles = [
io.File(rootPath + ".chiabot_cache.json"),
io.File(rootPath + ".farmr_cache.json")
];
if (!cacheDir.existsSync()) {
cacheDir.createSync();
for (io.File cacheFile in cacheFiles) {
if (cacheFile.existsSync()) {
cacheFile.copySync(rootPath + "cache/cache-xch.json");
cacheFile.deleteSync();
}
}
}
}
List<Blockchain> readBlockchains(ID id, String rootPath, List<String> args) {
List<Blockchain> blockchains = [];
io.Directory blockchainDir = io.Directory(rootPath + "blockchain");
if (blockchainDir.existsSync()) {
for (var file in blockchainDir.listSync()) {
//only loads files ending in .json and not .json.template
if (file.path.endsWith(".json")) {
Blockchain blockchain = Blockchain(id, rootPath, args,
jsonDecode(io.File(file.path).readAsStringSync()));
blockchains.add(blockchain);
if (blockchain.binaryName == "chia")
reportIntervalDuration = blockchain.reportIntervalDuration;
}
}
}
return blockchains;
}
void updateIDs(ID id, int userNumber) {
/** Generate Discord Id's */
if (id.ids.length != userNumber) {
if (userNumber > id.ids.length) {
// More Id's (add)
int newIds = userNumber - id.ids.length;
for (int i = 0; i < newIds; i++) id.ids.add(Uuid().v4());
} else if (userNumber < id.ids.length) {
// Less Id's (fresh list)
id.ids = [];
for (int i = 0; i < userNumber; i++) id.ids.add(Uuid().v4());
}
id.save();
}
}
Map<String, String> outputs = {};
main(List<String> args) async {
clearLog();
initLogger(); //initializes farmr logger
//Kills command on ctrl c
io.ProcessSignal.sigint.watch().listen((signal) {
io.exit(0);
});
//launches client in onetime mode, where it runs one time and doesnt loop
bool onetime = args.contains("onetime");
//launches client in standalone mode where it doesnt send info to server
bool standalone = args.contains("standalone") || args.contains("offline");
bool packageMode = args.contains("package"); // alternative .deb config path
//runs farmr in headless mode (doesnt ask for user input)
bool headless = args.contains("headless");
prepareRootPath(packageMode);
createDirsAndportOldFiles(rootPath);
ID id = ID(rootPath);
await id.init(); //creates id.json or loads ids from id.json
List<Blockchain> blockchains = readBlockchains(id, rootPath, args);
for (Blockchain blockchain in blockchains) {
//initializes ports and detects harvester/farmer mode
await blockchain.initializePorts();
//initializes blockchain class
await blockchain.init(true);
outputs.putIfAbsent(
"${blockchain.currencySymbol.toUpperCase()} - View report",
() => "Generating ${blockchain.currencySymbol} report");
outputs.putIfAbsent(
"${blockchain.currencySymbol.toUpperCase()} - View addresses",
() => "Generating ${blockchain.currencySymbol} report");
}
//shows info with ids to link
final String info = await id.info(blockchains);
outputs.putIfAbsent("View list of IDs", () => info);
outputs.putIfAbsent("Quit", () => "quit");
int maxUsers = blockchains
.map((e) => e.config.userNumber)
.reduce((n1, n2) => Math.max(n1, n2));
updateIDs(id, maxUsers);
log.warning(info);
final receivePort = ReceivePort();
final mainIsolate = await Isolate.spawn(
spawnBlokchains,
[receivePort.sendPort, blockchains, onetime, standalone],
);
receivePort.listen((message) {
var map = (message as Map<String, String>);
for (var entry in map.entries)
outputs.update(
entry.key,
(value) =>
(entry.key == map.entries.first.key ? (value + "\n\n") : "") +
entry.value);
if ((message).entries.first.value.contains("not linked")) {
receivePort.close();
mainIsolate.kill();
io.exit(1);
}
});
//does not ask for user input in github workflow
if (!blockchains.first.configPath.contains(".github/workflows") && !headless)
reportSelector();
else if (headless) log.warning("Running in headless mode");
}
bool firstTime = true;
late dartconsole.Console console;
Future<void> reportSelector() async {
print("""\nfarmr sends a report every 10 minutes.
Do not close this window or these stats will not show up in farmr.net and farmrBot
""");
try {
//initializes consoles if its the first time this function is running
if (firstTime) {
console = dartconsole.Console();
Console.init();
firstTime = false;
}
var chooser = Chooser<String>(
outputs.entries.map((entry) => entry.key).toList(),
message: 'Select action number: ',
);
chooser.choose().then((value) {
if (value != null) {
//otherwise clears screen
console.clearScreen();
if (outputs[value] != "quit")
print(outputs[value]);
else
io.exit(0);
}
reportSelector();
});
//catches error in case one of the console library crashes, e.g.: if requires user input
} catch (error) {}
}
Future<void> timeoutIsolate(SendPort timeoutPort) async {
final int timeOutMins = reportIntervalDuration.inMinutes * 2;
await Future.delayed(Duration(minutes: timeOutMins));
timeoutPort.send("timeout");
}
//blockchain spawner
//evenly distributes blockchains within delay time
//e.g.: 3 blockchains over 10 mins -> 3.33 mins per blockchain
void spawnBlokchains(List<Object> arguments) async {
SendPort sendPort = arguments[0] as SendPort;
List<Blockchain> blockchains = arguments[1] as List<Blockchain>;
bool onetime = arguments[2] as bool;
bool standalone = arguments[3] as bool;
initLogger(); //initializes logger
int counter = 0;
final int reportDelayBetweenInMilliseconds =
(reportIntervalDuration.inMilliseconds / blockchains.length).round();
//log parser isolate
//starts isolate for log parsing
final logParserReceivePort = ReceivePort();
final logParserIsolate = await Isolate.spawn(
startLogParsing,
[logParserReceivePort.sendPort, blockchains, onetime],
);
log.warning("Starting log parsers...");
logParserReceivePort.listen((message) {
if (message[0] is int) {
int key = message[0] as int;
if (message[1] is String) {
log.warning(message);
if (message[1].contains("stopped")) {
blockchains[key].completedFirstLogParse = true;
logParserReceivePort.close();
logParserIsolate.kill();
} else if (message[1].contains("not found")) {
blockchains[key].config.parseLogs = false;
logParserReceivePort.close();
logParserIsolate.kill();
}
} else if (message[1] is List<Object>) {
List<Object> logItems = message[1] as List<Object>;
blockchains[key].log.filters = logItems[0] as List<Filter>;
blockchains[key].log.signagePoints = logItems[1] as List<SignagePoint>;
blockchains[key].log.shortSyncs = logItems[2] as List<ShortSync>;
blockchains[key].log.poolErrors = logItems[3] as List<LogItem>;
blockchains[key].log.harvesterErrors = logItems[4] as List<LogItem>;
blockchains[key].log.genSubSlots();
if (!blockchains[key].completedFirstLogParse) {
blockchains[key].completedFirstLogParse = true;
log.warning(
"${blockchains[key].currencySymbol.toUpperCase()}: first log parse complete.");
}
}
}
});
//if log parsing is enabled then that implies blockchain must have completed first log parse
while (blockchains.any((blockchain) =>
!(!blockchain.config.parseLogs || blockchain.completedFirstLogParse))) {
await Future.delayed(Duration(milliseconds: 100));
}
while (true) {
clearLog(); //clears log
counter++;
log.info("Generating new report #$counter");
for (int i = 0; i < blockchains.length; i++) {
Blockchain blockchain = blockchains[i];
//evenly distributes blockchains
final int blockchainDelay =
(counter > 1) ? i * reportDelayBetweenInMilliseconds : 0;
final reporterReceivePort = ReceivePort();
final reporterIsolate = await Isolate.spawn(
handleBlockchainReport,
[
reporterReceivePort.sendPort,
blockchain,
blockchains.length,
onetime,
standalone,
blockchainDelay
],
);
void killMainIsolate() {
reporterReceivePort.close();
reporterIsolate.kill();
if (standalone) io.exit(0);
}
reporterReceivePort.listen((message) {
sendPort.send({
"${blockchain.currencySymbol.toUpperCase()} - View report":
(message as List<String>)[0],
"${blockchain.currencySymbol.toUpperCase()} - View addresses": """
Farmer Reward Address: ${message[3]}
Pool Reward Address: ${message[4]}
Local Addresses:
${message[1]}
Cold Addresses:
${message[2]}
These addresses are NOT reported to farmr.net or farmrBot
""",
});
killMainIsolate();
});
//kills main isolate after 20 minutes
final timeoutPort = ReceivePort();
final timeOutIsolate =
await Isolate.spawn(timeoutIsolate, timeoutPort.sendPort);
timeoutPort.listen((message) {
timeOutIsolate.kill();
killMainIsolate();
});
}
await Future.delayed(reportIntervalDuration);
if (onetime) io.exit(0);
}
}
void startLogParsing(List<Object> arguments) async {
SendPort sendPort = arguments[0] as SendPort;
List<Blockchain> blockchains = arguments[1] as List<Blockchain>;
bool onetime = arguments[2] as bool;
List<Future<void>> blockchainFutures = blockchains
.map((blockchain) => blockchain.log.initLogParsing(
blockchain.config.parseLogs,
onetime,
blockchain.currencySymbol,
blockchains.indexOf(blockchain),
sendPort))
.toList();
await Future.wait(blockchainFutures);
}
//blockchain isolate
void handleBlockchainReport(List<Object> arguments) async {
SendPort sendPort = arguments[0] as SendPort;
Blockchain blockchain = arguments[1] as Blockchain;
int blockchainsLength = arguments[2] as int;
bool onetime = arguments[3] as bool;
bool standalone = arguments[4] as bool;
int blockchainDelay = arguments[5] as int;
//kills isolate after 20 minutes
Future.delayed(
Duration(
minutes: (!onetime) ? (reportIntervalDuration.inMinutes * 2) : 1),
() {
sendPort.send([
"${blockchain.currencySymbol} report killed. Are ${blockchain.binaryName} services running?",
"",
"",
"",
""
]);
});
clearLog(blockchain.fileExtension); //clears log
initLogger(blockchain.fileExtension); //initializes logger
// ClientType type = arguments[5] as ClientType;
//sendPort.send(42 + number);
String lastPlotID = "";
String balance = "";
String status = "";
String copyJson = "";
String name = "";
String drives = "";
String coldBalance = "";
String output = "";
String localAddresses = "";
String coldAddresses = "";
String farmerRewardAddress = "";
String poolRewardAddress = "";
//delays blockchain report by amount defined in isolate spawner
await Future.delayed(Duration(milliseconds: blockchainDelay));
//PARSES DATA
// try {
//loads cache every 10 minutes
//loads config every 10 minutes
await blockchain.init(false);
//starts parsing logs every x seconds
var client;
//initializes client based on type detected by blockchain
switch (blockchain.type) {
case ClientType.Farmer:
client = client = Farmer(
rootPath: rootPath,
blockchain: blockchain,
version: EnvironmentConfig.version,
type: blockchain.config.type);
break;
case ClientType.Harvester:
client = Harvester(blockchain, EnvironmentConfig.version);
break;
case ClientType.HPool:
client =
HPool(blockchain: blockchain, version: EnvironmentConfig.version);
break;
}
//hpool has a special config.yaml directory, as defined in farmr's config.json
await client.init();
//Throws exception in case no plots were found
if (client.plots.length == 0)
log.warning(
"No plots have been found! Make sure your user has access to the folders where plots are stored.");
//if plot notifications are off then it will default to 0
lastPlotID =
(blockchain.config.sendPlotNotifications) ? client.lastPlotID() : "0";
//if hard drive notifications are disabled then it will default to 0
drives = (blockchain.config.sendDriveNotifications)
? client.drives.length.toString()
: "0";
//sends notifications about cold wallet if that is enabled
if (client is Farmer) {
if (client.coldWallets.length > 0) {
if (client.coldWalletAggregate.farmedBalance >= 0)
coldBalance = client.coldWalletAggregate.farmedBalanceMajor
.toStringAsFixed(2); //flax //LEGACY
else if (client.coldWalletAggregate.grossBalance >= 0)
coldBalance = client.coldWalletAggregate.grossBalanceMajor
.toStringAsFixed(2); //chia // LEGACY
else if (client.coldWalletAggregate.netBalance >= 0)
coldBalance = client.coldWalletAggregate.netBalanceMajor
.toStringAsFixed(2); //every other fork through posat.io
}
if (client.balance >= 0) balance = client.balance.toStringAsFixed(2);
}
for (String address in client.localAddresses)
localAddresses += "\n - $address";
for (String address in client.coldAddresses)
coldAddresses += "\n - $address";
farmerRewardAddress = client.farmerRewardAddress;
poolRewardAddress = client.poolRewardAddress;
status = client.status;
if (blockchainsLength > 1)
output += "\nStats for ${blockchain.binaryName} farm:";
//shows stats in client
output += Stats.showHarvester(
client,
0,
0,
//shows netspace is client is farmer or foxypoolOG since foxypoolOG uses same chia client and full node
(client is Farmer) ? client.netSpace : NetSpace(),
false,
true,
Rate(0, 0, 0),
false);
name = client.name;
if (blockchainsLength > 1) name += " (${blockchain.currencySymbol})";
//copies object to a json string
copyJson = jsonEncode(client);
// } catch (exception) {
// log.severe("Oh no! Something went wrong.");
// log.severe(exception.toString());
// log.info("Config:\n${blockchain.cache}\n");
// log.info("Cache:\n${blockchain.cache}");
// if (onetime) io.exit(1);
//}
if (!standalone) {
await Future.sync(() {
//SENDS DATA TO SERVER
try {
//clones farm so it can clear ids before sending them to server
//copy.clearIDs();
//deprecated
//String that's actually sent to server
String sendJson = copyJson;
String notifyOffline = (blockchain.config.sendOfflineNotifications)
? '1'
: '0'; //whether user wants to be notified when rig goes offline
String isFarming = (status == "Farming" || status == "Harvesting")
? '1' //1 means is farming/harvesting
: '0';
String publicAPI = (blockchain.config.publicAPI)
? '1' //1 means client data can be seen from public api
: '0';
Map<String, String> post = {
"data": sendJson,
"notifyOffline": notifyOffline,
"name": name,
"publicAPI": publicAPI
};
if (blockchain.config.sendStatusNotifications)
post.putIfAbsent("isFarming", () => isFarming);
//Adds the following if sendPlotNotifications is enabled then it will send plotID
if (blockchain.config.sendPlotNotifications)
post.putIfAbsent("lastPlot", () => lastPlotID);
//Adds the following if hard drive notifications are enabled then it will send the number of drives connected to pc
if (blockchain.config.sendDriveNotifications)
post.putIfAbsent("drives", () => drives);
bool isFarmerLike = (blockchain.config.type == ClientType.Farmer);
//If the client is a farmer and it is farming and sendBalanceNotifications is enabled then it will send balance
if (isFarmerLike &&
blockchain.config.sendBalanceNotifications &&
status == "Farming" &&
balance != "") post.putIfAbsent("balance", () => balance);
//if cold balance has been read and cold balance notifications are enabled then it will send coldBalance to server
if (blockchain.config.sendColdWalletNotifications && coldBalance != "")
post.putIfAbsent("coldBalance", () => coldBalance);
String type = isFarmerLike ? "farmer" : "harvester";
for (String id in blockchain.id.ids) {
//Appends blockchain symbol to id
post.putIfAbsent("id", () => id + blockchain.fileExtension);
post.update("id", (value) => id + blockchain.fileExtension);
sendReport(
id,
post,
blockchain,
type,
sendPort,
output,
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress);
}
log.info("url:$url");
log.info("data sent:\n$sendJson");
} catch (exception) {
log.severe("Oh no, failed to connect to server!");
log.severe(exception.toString());
}
}).catchError((error) {
log.info(error);
});
}
}
Future<void> sendReport(
String id,
Object? post,
Blockchain blockchain,
String type,
SendPort sendPort,
String previousOutput,
String localAddresses,
String coldAddresses,
String farmerRewardAddress,
String poolRewardAddress,
[bool retry = true]) async {
String contents = "";
//sends report to farmr.net
await http.post(Uri.parse(url), body: post).then((_) {
contents = _.body;
String idText = (blockchain.id.ids.length == 1)
? ''
: "for id " + id + blockchain.fileExtension;
String timestamp = DateFormat.Hms().format(DateTime.now());
previousOutput +=
"\n$timestamp - Sent ${blockchain.binaryName} $type report to server $idText\nResending it in ${reportIntervalDuration.inMinutes} minutes";
checkIfLinked(
contents,
previousOutput,
sendPort,
id + blockchain.fileExtension,
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress);
}).catchError((error) {
previousOutput +=
"Server timeout, could not access farmr.net.\nRetrying with backup domain.";
log.info(error.toString());
//sends report to chiabot.znc.sh (legacy/backup domain)
if (retry)
sendReport(
id,
post,
blockchain,
type,
sendPort,
previousOutput,
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress,
false);
else
sendPort.send([
previousOutput +=
"\nServer timeout, could not access farmr.net (or the backup domain chiabot.znc.sh)",
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress
]);
});
}
Future<void> checkIfLinked(
String response,
String previousOutput,
SendPort sendPort,
String id,
String localAddresses,
String coldAddresses,
String farmerRewardAddress,
String poolRewardAddress) async {
if (response.trim().contains("Not linked")) {
final errorString = """\n\nID $id is not linked to an account.
Link it in farmr.net or through farmrbot and then start this program again
Press enter to quit""";
print(errorString);
sendPort.send([
"not linked",
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress
]);
Future.delayed(Duration(minutes: 10)).then((value) {
io.exit(1);
});
io.stdin.readByteSync();
io.exit(1);
} else
sendPort.send([
previousOutput,
localAddresses,
coldAddresses,
farmerRewardAddress,
poolRewardAddress
]);
}
void clearLog([String blockchainExtension = ""]) {
//logging on windows is disabled
if (!io.Platform.isWindows) {
try {
io.File logFile = io.File(rootPath + "log$blockchainExtension.txt");
//Deletes log file if it already exists
if (logFile.existsSync()) {
logFile.deleteSync();
}
//creates log.txt
logFile.createSync();
} catch (err) {
log.info("Failed to delete/create log.txt.\n$err");
}
}
}
void initLogger([String blockchainExtension = ""]) {
//TODO fix logging on windows
//Initializes logger
Logger.root.level = Level.ALL; // defaults to Level.INFO
Logger.root.onRecord.listen((record) {
String output = '${record.message}';
if (record.level.value >= Level.WARNING.value)
print(output); //prints output if level is warning/error
//otherwise logs stuff to log file
//2021-05-02 03:02:26.548953 Client: Sent farmer report to server.
//logs on windows is disabled
if (!io.Platform.isWindows) {
try {
io.File logFile = io.File(rootPath + "log$blockchainExtension.txt");
logFile.writeAsStringSync(
'\n${record.time} ${record.loggerName}: ' + output,
mode: io.FileMode.writeOnlyAppend);
} catch (e) {}
}
});
}