/
main.rs
1524 lines (1448 loc) · 66.7 KB
/
main.rs
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
use crate::period::Period;
use blake2::{digest::consts::U32, Blake2b, Digest};
use chrono::prelude::*;
use indicatif::{ProgressBar, ProgressStyle};
use receipt::{
CloudUnits, FixupReceipt, MintingReceipt, ResourceRewards, ResourceUnits, ResourceUtilization,
RetryPayoutReceipt, Reward,
};
use std::{
collections::{BTreeMap, HashMap},
fs,
io::Write,
os::unix::prelude::OsStrExt,
path,
};
use tfchain_client::dynamic::DynamicClient;
use tokio::sync::mpsc;
// use tfchain_client::runtimes::v115::{client::Client, runtime};
use tfchain_client::{
client::{height_at_timestamp, RuntimeClient},
types::{
Contract as ChainContract, ContractData, ContractResources, Farm, FarmPolicy, Location,
Node, NodeCertification, NodePower, Power, PowerState, Resources, RuntimeEvents,
},
};
mod period;
mod receipt;
mod stellar;
mod types;
const RPC_THREADS: usize = 24;
const PRE_FETCH: usize = 5;
const UPTIME_GRACE_PERIOD_SECONDS: i64 = 300; // 5 Minutes
const GIB: u128 = 1024 * 1024 * 1024;
const ONE_MILL: u128 = 1_000_000;
/// The amount of "units" that make 1 TFT.
const UNITS_PER_TFT: u64 = 10_000_000;
/// The amount of blocks expected in an hour.
const BLOCKS_IN_HOUR: u32 = 10 * 60; // 10 blocks per minute
/// The price of 1 CU related to carbon offset.
/// Value taken from [this]
/// (https://docs.google.com/spreadsheets/d/16uUJEArEb-3aDkHNTlsMpMovyqgLp9xtwzdgjdu-lGw/edit#gid=1395768004)
/// on 01-02-2022.
const CU_CARBON_OFFSET_MUSD: u64 = 354;
/// The price of 1 SU related to carbon offset
/// Value taken from [this]
/// (https://docs.google.com/spreadsheets/d/16uUJEArEb-3aDkHNTlsMpMovyqgLp9xtwzdgjdu-lGw/edit#gid=1395768004)
/// on 01-02-2022.
const SU_CARBON_OFFSET_MUSD: u64 = 122;
/// Required uptime percentage in a period for nodes to be eligible for rewards.
const UPTIME_SLA_PERCENT: u64 = 95;
/// The address to which the carbon credit tft will be sent.
/// Value provided by Andreas Hartl in a Telegram DM on 03-02-2022
const CARBON_CREDIT_ADDRESS: &str = "GDIJY6K2BBRIRX423ZFUYKKFDN66XP2KMSBZFQSE2PSNDZ6EDVQTRLSU";
/// Address of horizon server to use
//const HORIZON_URL: &str = "https://stellar-mainnet.grid.tf";
const HORIZON_URL: &str = "https://horizon.stellar.org";
/// Maximum amount of seconds a node can be offline because of the power managment feature while
/// still getting rewards.
const MAX_POWER_MANAGER_DOWNTIME: u64 = 60 * 60 * 25;
#[tokio::main]
async fn main() {
// TODO: use `clap` to properly have flags for this
// let network = Network::Test;
let mut args = std::env::args();
// ignore binary name
args.next();
let period_offset = args.next().unwrap().parse().unwrap();
let period = Period::at_offset(period_offset);
let start_ts: i64 = period.start();
let end_ts: i64 = period.end();
let wss_url = args.next().unwrap();
// load previous receipts
let previous_period_offset = period_offset - 1;
println!("Loading receipts from period {}", previous_period_offset);
let mut previous_receipt_dir = path::PathBuf::new();
previous_receipt_dir.push("receipts");
previous_receipt_dir.push(previous_period_offset.to_string());
let mut previous_receipts = HashMap::new();
match std::fs::read_dir(&previous_receipt_dir) {
Err(_) => println!("Previous receipt dir does not exist, skip loading receipts"),
Ok(dir_iter) => {
for file in dir_iter {
let file = file.unwrap();
if !file.file_type().unwrap().is_file() {
continue;
}
let mut hash = [0; 32];
hex::decode_to_slice(file.file_name().as_bytes(), &mut hash).unwrap();
let mut path = previous_receipt_dir.clone();
path.push(file.file_name());
let data = fs::read_to_string(path).unwrap();
let receipt: MintingReceipt = serde_json::from_str(&data).unwrap();
previous_receipts.insert(hash, receipt);
}
}
}
// load previous fixup receipts
println!(
"Loading fixup receipts from period {}",
previous_period_offset
);
let mut previous_fixup_receipt_dir = path::PathBuf::new();
previous_fixup_receipt_dir.push("receipts");
previous_fixup_receipt_dir.push("fixed");
previous_fixup_receipt_dir.push(previous_period_offset.to_string());
let mut previous_fixup_receipts = HashMap::new();
match std::fs::read_dir(&previous_fixup_receipt_dir) {
Err(_) => {
println!("Previous fixup receipt dir does not exist, skip loading fixup receipts")
}
Ok(dir_iter) => {
for file in dir_iter {
let file = file.unwrap();
if !file.file_type().unwrap().is_file() {
continue;
}
let mut hash = [0; 32];
hex::decode_to_slice(file.file_name().as_bytes(), &mut hash).unwrap();
let mut path = previous_fixup_receipt_dir.clone();
path.push(file.file_name());
let data = fs::read_to_string(path).unwrap();
let receipt: FixupReceipt = serde_json::from_str(&data).unwrap();
previous_fixup_receipts.insert(hash, receipt);
}
}
}
if previous_receipts.len() > 0 || previous_fixup_receipts.len() > 0 {
println!(
"Filtering receipts, pre filter length {}",
previous_receipts.len() + previous_fixup_receipts.len()
);
let horizon = stellar::Horizon::new(HORIZON_URL);
horizon
.filter_previous_mints(&mut previous_receipts, &mut previous_fixup_receipts)
.await;
println!(
"Done filtering receipts, post filter length {}",
previous_receipts.len() + previous_fixup_receipts.len()
);
}
let client = DynamicClient::new(&wss_url).await.unwrap();
println!("Finding start block");
let start_block = height_at_timestamp(&client, start_ts).await.unwrap();
println!("Finding end block");
let end_block = height_at_timestamp(&client, end_ts).await.unwrap();
// Grab existing nodes
let mut nodes: BTreeMap<_, _> = get_nodes(&client, start_block)
.await
.unwrap()
.into_iter()
.map(|node| {
(
node.id,
MintingNode {
id: node.id,
farm_id: node.farm_id,
twin_id: node.twin_id,
resources: node.resources,
location: node.location,
country: node.country,
city: node.city,
created: node.created,
certification_type: node.certification,
uptime_info: None,
first_uptime_violation: None,
connected: NodeConnected::Old,
connection_price: node.connection_price,
capacity_consumption: TotalConsumption::default(),
virtualized: node.virtualized,
farming_policy_id: node.farming_policy_id,
power_managed: None,
},
)
})
.collect();
println!("Found {} existing nodes", nodes.len());
let mut power_states: BTreeMap<_, _> = get_power_states(&client, start_block)
.await
.unwrap()
.into_iter()
.collect();
println!("Found {} power states", power_states.len());
// Insert missing entries for power state, and update node power managed if it currently is
// power managed.
for (node_id, node) in nodes.iter_mut() {
match power_states.get(&node_id) {
None => {
power_states.insert(
*node_id,
NodePower {
state: PowerState::Up,
target: Power::Up,
},
);
}
Some(NodePower {
state: PowerState::Down(block),
target: _,
}) => {
let hash = client.hash_at_height(Some(*block)).await.unwrap();
let ts = client.timestamp(hash).await.unwrap() / 1000;
node.power_managed = Some(ts as i64);
}
_ => {}
}
}
// Load farms at the end of the period. This means we don't have to parse individual farm
// events, as we can just fetch the last known state.
let farms: BTreeMap<_, _> = get_farms(&client, end_block)
.await
.unwrap()
.into_iter()
.map(|farm| (farm.id, farm))
.collect();
println!("Found {} existing farms", farms.len());
let payout_addresses: BTreeMap<_, _> = get_payout_addresses(&client, &farms, end_block)
.await
.unwrap();
// Grab existing contracts
let mut contracts: BTreeMap<_, _> = get_contracts(&client, start_block)
.await
.unwrap()
.into_iter()
.filter_map(|(contract, resources)| {
// Namecontract is actually billed once deployed through a node contract.
if let ContractData::NodeContract(nc) = contract.contract_type {
Some((
contract.contract_id,
Contract {
contract_id: contract.contract_id,
node_id: nc.node_id,
// a report should pop up for this
last_report_ts: 0,
ips: nc.public_ips,
resources,
},
))
} else {
None
}
})
.collect();
println!("Found {} existing contracts", contracts.len());
// Get farming policies
let farming_policies: BTreeMap<_, _> = get_farming_policies(&client, end_block)
.await
.unwrap()
.into_iter()
.filter_map(|policy| Some((policy.id, policy)))
.collect();
println!("Found {} farming policies", farming_policies.len());
println!("Setup block import pipeline");
let blocks = end_block - start_block + 1;
//let block_stream = block_import(client.clone(), start_block, end_block, network);
let bar = ProgressBar::new(blocks as u64);
bar.set_style(
ProgressStyle::default_bar()
.template("[Time on chain: {msg}] {wide_bar} {pos:>6}/{len:>6} (ETA: {eta_precise})"),
);
let mut last_height = start_block - 1;
let mut height = start_block;
let mut import_queue = block_import(&wss_url, height as usize, end_block as usize).await;
loop {
let (ts, evts) = if let Some((ts, evts)) = import_queue.recv().await {
(ts, evts)
} else {
panic!("Block import exitted too early");
};
for evt in evts.into_iter() {
match evt {
RuntimeEvents::NodeStoredEvent(node) => {
nodes.insert(
node.id,
MintingNode {
id: node.id,
farm_id: node.farm_id,
twin_id: node.twin_id,
resources: node.resources,
location: node.location,
country: node.country,
city: node.city,
created: node.created,
certification_type: node.certification.clone(),
uptime_info: None,
first_uptime_violation: None,
connected: NodeConnected::Current(ts as i64),
connection_price: node.connection_price,
capacity_consumption: TotalConsumption::default(),
virtualized: node.virtualized,
farming_policy_id: node.farming_policy_id,
power_managed: None,
},
);
power_states.insert(
node.id,
NodePower {
state: PowerState::Up,
target: Power::Up,
},
);
}
RuntimeEvents::NodeUpdatedEvent(node) => {
let old_node = nodes
.get_mut(&node.id)
.expect("node update of unknown node");
old_node.farm_id = node.farm_id;
old_node.twin_id = node.twin_id;
// update resources, but only lower them in case of dead or removed
// hardware. Do not update in case of added hardware as this is currently
// unresolved.
old_node.resources.cru =
std::cmp::min(old_node.resources.cru, node.resources.cru);
old_node.resources.mru =
std::cmp::min(old_node.resources.mru, node.resources.mru);
old_node.resources.hru =
std::cmp::min(old_node.resources.hru, node.resources.hru);
old_node.resources.sru =
std::cmp::min(old_node.resources.sru, node.resources.sru);
old_node.location = node.location;
old_node.resources = node.resources;
old_node.country = node.country;
old_node.city = node.city;
// Don't care about "create" as that should be fixed anyway
// Update certification type. It's technically possible for a node to jump
// from DIY to certified and back in the same period, but practically that
// should not happen.
old_node.certification_type = node.certification.clone();
// It is possible that this also causes a node to get a different farming
// policy ID.
old_node.farming_policy_id = node.farming_policy_id;
// Update connection price. This should not happen, but it is here in case
// we modify the connection price of the node in place in the future and
// emit this generic event when the 5 year fixed time is expired.
old_node.connection_price = node.connection_price;
// Even though this likely means the node is rebooted, don't mess with
// uptime_info. The reboot will be detected in the `NodeUptimeReported`
// handler.
// This does not change when the node was connected.
//
// Once a VM, always a VM
if node.virtualized {
old_node.virtualized = node.virtualized;
}
}
RuntimeEvents::NodeUptimeReported(id, current_time, reported_uptime) => {
let node = match nodes.get_mut(&id) {
Some(node) => node,
None => panic!(
"can't report uptime for unknown node {} in block {}",
id, height
),
};
if let Some(time_set_down) = node.power_managed {
// Ignore the event if it is sent after the node is supposed to go down,
// this will be accounted for once the node starts up again.
// For the node to have been properly power managed, it must be booted
// after it was set to down.
if (current_time - reported_uptime) as i64 > time_set_down {
// node got power managed to down
let time_delta = current_time as i64 - time_set_down;
assert!(time_delta >= 0, "uptime events can't travel back in time");
let mut total_uptime =
if let Some((_, _, total_uptime)) = node.uptime_info {
total_uptime
} else {
0
};
// Only add uptime if node came back online in time.
if time_delta as u64 <= MAX_POWER_MANAGER_DOWNTIME {
// Check and scale to match the actual period start if needed
if time_set_down < start_ts {
total_uptime += (current_time as i64 - start_ts) as u64;
} else {
total_uptime += time_delta as u64;
}
}
// Clear the fact that we got power managed, if it is still the case, it
// will be set again in the proper event handler.
node.power_managed = None;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
}
} else {
if let Some((last_reported_at, last_reported_uptime, mut total_uptime)) =
node.uptime_info
{
let report_delta = current_time as i64 - last_reported_at;
let uptime_delta = reported_uptime as i64 - last_reported_uptime as i64;
// There are quite some situations here. Notice that due to the
// blockchain only producing blocks every 6 seconds, and network delay
// + a host of other issues, we will allow a node to report uptime with
// "grace period" of a couple of minutes or so in either direction.
//
// 1. uptime_delta > report_delta + GRACE_PERIOD. Node is talking
// rubish.
if uptime_delta > report_delta + UPTIME_GRACE_PERIOD_SECONDS {
// This is possible if a node lags when sending uptime (extrinsic
// takes a while to be accepted). Manual data validation found no
// issues (i.e. all incidents of this type were a result of the
// above). This should be changed in the future.
total_uptime += uptime_delta as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 2. The difference in uptime is within reason of the difference in
// report times, i.e. the node is properly reporting.
if uptime_delta <= report_delta + UPTIME_GRACE_PERIOD_SECONDS
&& uptime_delta >= report_delta - UPTIME_GRACE_PERIOD_SECONDS
{
// It is technically possible for the delta to be less than 0 and
// within the expected time frame. If nodes boot, send uptime, then
// immediately reboot that is possible. In those cases, handle that
// below, as that is the reboot detection.
if uptime_delta > 0 {
// Simply add the uptime delta. If this is too large or low by a
// couple of seconds it will be corrected by the next pings anyhow.
total_uptime += uptime_delta as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
}
// 3. The difference in uptime is too low. Again there are multiple
// scenarios. Either way we consider the node rebooted. Depending on
// the reported uptime, the node reports legit uptime, or it reports
// an uptime which is too high.
//
// 1. Uptime is within bounds.
if reported_uptime as i64 <= report_delta {
total_uptime += reported_uptime;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 2. Uptime is higher than previously recorded uptime but too low.
// This might be a result off network congestion.
if reported_uptime > last_reported_uptime {
total_uptime += uptime_delta as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 3. Uptime is too high, this is garbage
if node.first_uptime_violation.is_none() {
node.first_uptime_violation = Some((last_reported_at, height));
}
continue;
} else {
let period_duration = current_time as i64 - start_ts;
// Make sure we don't give more credit than the current length of the
// period.
let up_in_period =
std::cmp::min(period_duration as u64, reported_uptime);
// Save uptime info
node.uptime_info =
Some((current_time as i64, reported_uptime, up_in_period));
}
}
}
RuntimeEvents::ContractUsedResourcesUpdated(data) => {
let contract = match contracts.get_mut(&data.contract_id) {
Some(contract) => contract,
// Contract needs to exist.
None => {
panic!("Can't set used resources for contract {} which does not exist in block {}", data.contract_id, height);
}
};
contract.resources = data.used;
}
RuntimeEvents::NruConsumptionReceived(data) => {
let contract = match contracts.get_mut(&data.contract_id) {
Some(contract) => contract,
// Contract needs to exist.
None => {
// If a contract is in grace period, there seem to still be NRU
// reports. These may or may not be legit, depending on how zos is set
// up. This warrants further investigation, as it would indicate the
// network is not properly disconnected, but at this point in time we
// will ignore this.
continue;
// panic!("Can't set used resources for contract {} which does not exist in block {}", data.contract_id, height);
}
};
let node = match nodes.get_mut(&contract.node_id) {
Some(node) => node,
None => {
panic!(
"can't process consumption for unknown node {} in block {}",
contract.node_id, height
)
}
};
// Just to make sure reports are ordered
if ts as i64 <= contract.last_report_ts {
// Silently ignore reports out of order, we already covered this in an
// already processed consumption report. This can happen if the node pushes
// a contract consumption report twice.
continue;
}
// If report ts predates start we ignore it.
if (ts as i64) < start_ts {
continue;
}
node.capacity_consumption.cru += (contract.resources.cru * data.window) as u128;
node.capacity_consumption.mru += (contract.resources.mru * data.window) as u128;
node.capacity_consumption.hru += (contract.resources.hru * data.window) as u128;
node.capacity_consumption.sru += (contract.resources.sru * data.window) as u128;
node.capacity_consumption.ips += contract.ips as u64 * data.window;
node.capacity_consumption.nru += data.nru;
contract.last_report_ts = ts as i64;
}
RuntimeEvents::ContractCreated(contract) => {
if let ContractData::NodeContract(nc) = &contract.contract_type {
contracts.insert(
contract.contract_id,
Contract {
contract_id: contract.contract_id,
node_id: nc.node_id,
last_report_ts: ts as i64,
ips: nc.public_ips,
resources: Resources {
hru: 0,
sru: 0,
cru: 0,
mru: 0,
},
},
);
};
}
RuntimeEvents::PowerTargetChanged(ptc) => {
let node_power = match power_states.get_mut(&ptc.node_id) {
Some(ps) => ps,
None => panic!(
"can't change power target for unknown node {} in block {}",
ptc.node_id, height
),
};
node_power.target = ptc.power_target;
}
RuntimeEvents::PowerStateChanged(psc) => {
let node_power = match power_states.get_mut(&psc.node_id) {
Some(ps) => ps,
None => panic!(
"can't change power target for unknown node {} in block {}",
psc.node_id, height
),
};
// Add exception to allow node 1 uptime ping once it gets back on which
// indicates a reboot.
// Also, we only allow this if the target is down as well.
if node_power.target == Power::Down {
// Only on state transition
if node_power.state == PowerState::Up
&& matches!(psc.power_state, PowerState::Down(_))
{
// Keep track of this timestamp
let node = match nodes.get_mut(&psc.node_id) {
Some(node) => node,
None => {
panic!("Node must be registered if its power target changes")
}
};
// Either this is Some(timestamp), indicating a previous state
// transition which was not followed by an uptime ping once the node
// came online. In this case, we ignore that here. This would mean the
// node did not come up again.
// Otherwise, if None, set the current timestamp as time of going down.
if node.power_managed.is_none() {
// Also add an implicit uptime.
node.power_managed = Some(ts);
// While we are at it, credit uptime since last uptime event as
// well, as we will use this timestamp as the base for future
// uptime calculations.
// We don't have to overwrite this since future calculations will
// first work on the saved power_managed variable, and will have a
// reboot either way.
if let Some((last_reported_at, _, mut total_uptime)) =
node.uptime_info
{
let delta = ts - last_reported_at;
assert!(
delta >= 0,
"Power state changes can't travel back in time"
);
total_uptime += delta as u64;
// We can set uptime to 0, node will reboot anyway.
node.uptime_info = Some((ts, 0, total_uptime));
}
}
}
}
}
}
}
// finally update progress bar
bar.set_message(Utc.timestamp(ts as i64, 0).to_rfc2822());
bar.inc(1);
height += 1;
if height > end_block {
break;
}
}
bar.finish();
println!("Getting uptime info from post period");
let bar = ProgressBar::new(BLOCKS_IN_HOUR as u64 * 27);
bar.set_style(
ProgressStyle::default_bar()
.template("[Time on chain: {msg}] {wide_bar} {pos:>6}/{len:>6} (ETA: {eta_precise})"),
);
// Collect post-period uptime events. Violations don't matter here, those will be handled next
// period.
let mut import_queue = block_import(
&wss_url,
height as usize,
end_block as usize + BLOCKS_IN_HOUR as usize * 27,
)
.await;
loop {
let (ts, evts) = if let Some((ts, evts)) = import_queue.recv().await {
(ts, evts)
} else {
panic!("Block import exitted too early");
};
// let hash = client.hash_at_height(Some(height)).await.unwrap();
// let evts = client.events(hash).await.unwrap();
// let ts = client.timestamp(hash).await.unwrap() / 1000;
for evt in evts.into_iter() {
match evt {
RuntimeEvents::NodeUptimeReported(id, current_time, reported_uptime) => {
let node = match nodes.get_mut(&id) {
Some(node) => node,
// This is possible if its an uptime report for a node which came online after
// the period ended
None => continue,
};
if let Some(time_set_down) = node.power_managed {
// node got power managed to down
let time_delta = current_time as i64 - time_set_down;
assert!(time_delta >= 0, "uptime events can't travel back in time");
let mut total_uptime = if let Some((last_reported_at, _, total_uptime)) =
node.uptime_info
{
assert!(
last_reported_at < end_ts,
"there can only be 1 uptime event post period for a power managed node"
);
total_uptime
} else {
0
};
// Only add uptime if node came back online in time.
if time_delta as u64 <= MAX_POWER_MANAGER_DOWNTIME {
let uptime_diff = end_ts - i64::max(start_ts, time_set_down);
assert!(
uptime_diff >= 0,
"uptime event must be sent after node wen't down, chronology"
);
total_uptime += uptime_diff as u64;
}
// Clear the fact that we got power managed, if it is still the case, it
// will be set again in the proper event handler.
node.power_managed = None;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
} else {
if let Some((last_reported_at, last_reported_uptime, mut total_uptime)) =
node.uptime_info
{
// only collect 1 uptime event after the period ended
if last_reported_at >= end_ts {
continue;
}
let report_delta = current_time as i64 - last_reported_at;
let uptime_delta = reported_uptime as i64 - last_reported_uptime as i64;
let delta_in_period = end_ts - last_reported_at;
// There are quite some situations here. Notice that due to the
// blockchain only producing blocks every 6 seconds, and network delay
// + a host of other issues, we will allow a node to report uptime with
// "grace period" of a minute or so in either direction.
//
// 1. uptime_delta > report_delta + GRACE_PERIOD. Node is talking
// rubish.
if uptime_delta > report_delta + UPTIME_GRACE_PERIOD_SECONDS {
// This will actually be picked up next period as a violation if we
// care for that.
total_uptime += delta_in_period as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 2. The difference in uptime is within reason of the difference in
// report times, i.e. the node is properly reporting.
if uptime_delta <= report_delta + UPTIME_GRACE_PERIOD_SECONDS
&& uptime_delta >= report_delta - UPTIME_GRACE_PERIOD_SECONDS
{
// It is technically possible for the delta to be less than 0 and
// within the expected time frame. If nodes boot, send uptime, then
// immediately reboot that is possible. In those cases, handle that
// below, as that is the reboot detection.
if uptime_delta > 0 {
// Simply add the uptime delta. If this is too large or low by a
// couple of seconds it will be corrected by the next pings anyhow.
//
// Make sure we don't add too much based on the period.
total_uptime += delta_in_period as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
}
// 3. The difference in uptime is too low. Again there are multiple
// scenarios. Either way we consider the node rebooted. Depending on
// the reported uptime, the node reports legit uptime, or it reports
// an uptime which is too high.
//
// 1. Uptime is within bounds.
if reported_uptime as i64 <= report_delta {
// Account for the fact that we are actually out of the period
let out_of_period = current_time - end_ts as u64;
if out_of_period < reported_uptime {
total_uptime += reported_uptime - out_of_period;
}
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 2. Uptime is higher than previously recorded uptime but too low.
// This might be a result off network congestion.
if reported_uptime > last_reported_uptime {
total_uptime += uptime_delta as u64;
node.uptime_info =
Some((current_time as i64, reported_uptime, total_uptime));
continue;
}
// 3. Uptime is too high, this is garbage
if node.first_uptime_violation.is_none() {
node.first_uptime_violation = Some((last_reported_at, height));
continue;
}
// We should have handled all cases. Make this explicit here.
unreachable!();
}
}
}
_ => {
// Don't care here
}
}
}
//bar.set_message(format!("{}/7200", height - end_block,));
bar.set_message(Utc.timestamp(ts as i64, 0).to_rfc2822());
bar.inc(1);
height += 1;
if height > end_block + BLOCKS_IN_HOUR * 27 {
break;
}
}
bar.finish_and_clear();
let mut receipts = BTreeMap::new();
let mut payout_file = std::fs::File::create("payouts.csv").unwrap();
let mut overview_file = std::fs::File::create("overview.csv").unwrap();
let mut retry_file = std::fs::File::create("retries.csv").unwrap();
let mut carbon_tft_units = 0;
writeln!(overview_file,"node id,twin id,farm name (farm id),period start,period end,measured uptime,CU,SU,NU,USD reward,TFT reward,TFT price on connect,carbon offset USD generated,carbon offset TFT generated,cru,cru used,mru,mru used,hru,hru used,sru,sru used,IP used,DIY state,Virtualized,violation,stellar address").unwrap();
for (_, node) in nodes {
let node_period = node.real_period(period);
let node_period_duration = node_period.duration();
let node_start = Utc.timestamp(node_period.start(), 0);
let node_end = Utc.timestamp(node_period.end(), 0);
let (cu, su, nu) = node.cloud_units_permill();
let (musd, tft) = node.scaled_payout(period, &farming_policies);
let (co_musd, co_tft) = node.scaled_carbon_payout(period);
let cru_used = (node.capacity_consumption.cru / node_period_duration as u128) as u64;
let mru_used = (node.capacity_consumption.mru / node_period_duration as u128) as u64;
let hru_used = (node.capacity_consumption.hru / node_period_duration as u128) as u64;
let sru_used = (node.capacity_consumption.sru / node_period_duration as u128) as u64;
let farm = if let Some(farm) = farms.get(&node.farm_id) {
farm
} else {
println!(
"node {} is in farm {} which does not exist anymore",
node.id, node.farm_id
);
continue;
};
let stellar_address = if let Some(stellar_address) = payout_addresses.get(&node.farm_id) {
&stellar_address
} else {
""
};
writeln!(overview_file,
"{},{},{} ({}),{},{},{},{},{},{},{} $,{},{} $,{} $,{} TFT,{},{:.2}%,{},{:.2}%,{},{:.2}%,{},{:.2}%,{:.2} hours,{},{},{},{}",
node.id,
node.twin_id,
farm.name,
node.farm_id,
node_start,
node_end,
node.uptime(period),
format_args!("{}.{:06}", cu / ONE_MILL as u64, cu % ONE_MILL as u64),
format_args!("{}.{:06}", su / ONE_MILL as u64, su % ONE_MILL as u64),
format_args!("{}.{:06}", nu / ONE_MILL as u64, nu % ONE_MILL as u64),
format_args!("{}.{:03}", musd / 1_000, musd % 1_000),
format_args!("{}.{:07}", tft / UNITS_PER_TFT, tft % UNITS_PER_TFT),
format_args!(
"{}.{:03}",
node.connection_price / 1_000,
node.connection_price % 1_000
),
format_args!("{}.{:03}", co_musd / 1_000, co_musd % 1_000),
format_args!("{}.{:07}", co_tft / UNITS_PER_TFT, co_tft % UNITS_PER_TFT),
node.resources.cru,
if node.resources.cru > 0 {cru_used as f64 * 100. / node.resources.cru as f64} else { 0.},
node.resources.mru,
if node.resources.mru > 0 {mru_used as f64 * 100. / node.resources.mru as f64} else {0.},
node.resources.hru,
if node.resources.hru > 0 {hru_used as f64 * 100. / node.resources.hru as f64} else {0.},
node.resources.sru,
if node.resources.sru > 0 {sru_used as f64 * 100. / node.resources.sru as f64} else {0.},
node.capacity_consumption.ips as f64 / 3600.,
if let NodeCertification::Certified = node.certification_type {
"CERTIFIED"
} else {
"DIY"
},
node.virtualized,
if let Some((lra, violation)) = node.first_uptime_violation {
format!("violation of uptime measurement in block {} (previous report {})", violation, lra)
} else {
"".into()
},
stellar_address,
).unwrap();
let receipt = node.receipt(period, &farms, &payout_addresses, &farming_policies);
if !stellar_address.is_empty() && tft != 0 {
writeln!(
payout_file,
"{},{}.{:07},{}",
stellar_address,
tft / UNITS_PER_TFT,
tft % UNITS_PER_TFT,
hex::encode(receipt.hash()),
)
.unwrap();
}
receipts.insert(receipt.hash(), receipt);
// Count carbon TFT credits
carbon_tft_units += co_tft;
}
// Retry payments once
let mut retry_receipts = HashMap::new();
for (hash, failed_receipt) in previous_receipts {
// no point in doing this
if failed_receipt.reward.tft == 0 {
continue;
}
let retry_receipt = RetryPayoutReceipt {
failed_payout_period: failed_receipt.period,
retry_period: period,
farm_id: failed_receipt.farm_id,
previous_stellar_payout_address: failed_receipt.stellar_payout_address,
stellar_payout_address: payout_addresses
.get(&failed_receipt.farm_id)
.map(|a| a.clone())
.unwrap_or("".to_string()),
retry_for_receipt: hex::encode(hash),
reward: failed_receipt.reward,
};
let retry_hash = hex::encode(retry_receipt.hash());
if !retry_receipt.stellar_payout_address.is_empty() && retry_receipt.reward.tft != 0 {
writeln!(
payout_file,
"{},{}.{:07},{}",
retry_receipt.stellar_payout_address,
retry_receipt.reward.tft / UNITS_PER_TFT,
retry_receipt.reward.tft % UNITS_PER_TFT,
retry_hash,
)
.unwrap();
}
retry_receipts.insert(retry_hash, retry_receipt);
}
let mut retry_fixed_receipts = HashMap::new();
for (hash, failed_receipt) in previous_fixup_receipts {
// no point in doing this
if failed_receipt.fixup_reward.tft == 0 {
continue;
}
let retry_receipt = RetryPayoutReceipt {
failed_payout_period: failed_receipt.period,
retry_period: period,
farm_id: failed_receipt.farm_id,
previous_stellar_payout_address: failed_receipt.stellar_payout_address,
stellar_payout_address: payout_addresses
.get(&failed_receipt.farm_id)
.map(|a| a.clone())
.unwrap_or("".to_string()),
retry_for_receipt: hex::encode(hash),
reward: failed_receipt.fixup_reward,
};
let retry_hash = hex::encode(retry_receipt.hash());
if !retry_receipt.stellar_payout_address.is_empty() && retry_receipt.reward.tft != 0 {
writeln!(
payout_file,
"{},{}.{:07},{}",
retry_receipt.stellar_payout_address,
retry_receipt.reward.tft / UNITS_PER_TFT,
retry_receipt.reward.tft % UNITS_PER_TFT,
retry_hash,
)
.unwrap();
}
retry_fixed_receipts.insert(retry_hash, retry_receipt);
}
// Sort hashes in lexicographical order
let mut receipt_hashes = receipts.keys().cloned().collect::<Vec<_>>();
receipt_hashes.sort_unstable();
let mut hasher = Blake2b::<U32>::new();
for receipt_hash in receipt_hashes {
hasher.update(receipt_hash);
}
let carbon_hash: [u8; 32] = hasher.finalize().into();
writeln!(
payout_file,
"{},{}.{:07},{}",
CARBON_CREDIT_ADDRESS,
carbon_tft_units / UNITS_PER_TFT,
carbon_tft_units % UNITS_PER_TFT,
hex::encode(carbon_hash),
)
.unwrap();
// Write generated receipts
let mut receipt_dir = path::PathBuf::new();
receipt_dir.push("receipts");
receipt_dir.push(period_offset.to_string());
std::fs::create_dir_all(&receipt_dir).unwrap();
for (hash, receipt) in receipts {
let mut path = receipt_dir.clone();
path.push(hex::encode(hash));
std::fs::write(path, serde_json::to_vec(&receipt).unwrap()).unwrap();
}
// Write retry receipts
writeln!(
retry_file,
"farm_id,previous_stellar_address,new_stellar_address,amount TFT,retry_for",
)
.unwrap();
let mut retry_receipt_dir = path::PathBuf::new();
retry_receipt_dir.push("receipts");
retry_receipt_dir.push("retries");