-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathjson_rpc_client.rs
More file actions
1695 lines (1501 loc) · 57.8 KB
/
Copy pathjson_rpc_client.rs
File metadata and controls
1695 lines (1501 loc) · 57.8 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
use ansi_term::Color::{Purple, Red, White, Yellow};
use failure::{bail, Fail};
use itertools::Itertools;
use num_format::{Locale, ToFormattedString};
use prettytable::{cell, row, Table};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
collections::HashMap,
convert::TryFrom,
fmt,
fs::File,
io::{self, BufRead, BufReader, Read, Write},
net::{SocketAddr, TcpStream},
path::Path,
str::FromStr,
};
use witnet_crypto::{
hash::calculate_sha256,
key::{CryptoEngine, ExtendedPK, ExtendedSK},
};
use witnet_data_structures::{
chain::{
Block, ConsensusConstants, DataRequestInfo, DataRequestOutput, Environment, Epoch,
Hashable, KeyedSignature, NodeStats, OutputPointer, PublicKey, PublicKeyHash, StateMachine,
SupplyInfo, SyncStatus, ValueTransferOutput,
},
mainnet_validations::{current_active_wips, ActiveWips},
proto::ProtobufConvert,
transaction::Transaction,
transaction_factory::NodeBalance,
utxo_pool::{UtxoInfo, UtxoSelectionStrategy},
};
use witnet_node::actors::{
chain_manager::run_dr_locally,
json_rpc::json_rpc_methods::{
AddrType, GetBalanceParams, GetBlockChainParams, GetTransactionOutput, PeersResult,
},
messages::{BuildVtt, GetReputationResult, SignalingInfo},
};
use witnet_rad::types::RadonTypes;
use witnet_util::{credentials::create_credentials_file, timestamp::pretty_print};
use witnet_validations::validations::{
run_tally_panic_safe, validate_data_request_output, validate_rad_request, Wit,
};
pub fn raw(addr: SocketAddr) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
// The request is read from stdin, one line at a time
let mut request = String::new();
let stdin = io::stdin();
let mut stdin = stdin.lock();
loop {
request.clear();
let count = stdin.read_line(&mut request)?;
if count == 0 {
break Ok(());
}
let response = send_request(&mut stream, &request)?;
// The response includes a newline, so use print instead of println
print!("{}", response);
}
}
pub fn get_blockchain(addr: SocketAddr, epoch: i64, limit: i64) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let params = GetBlockChainParams { epoch, limit };
let response = send_request(
&mut stream,
&format!(
r#"{{"jsonrpc": "2.0","method": "getBlockChain", "params": {}, "id": 1}}"#,
serde_json::to_string(¶ms).unwrap()
),
)?;
log::info!("{}", response);
let block_chain: ResponseBlockChain<'_> = parse_response(&response)?;
for (epoch, hash) in block_chain {
println!("block for epoch #{} had digest {}", epoch, hash);
}
Ok(())
}
// Get integer part of `nanowits / 10^9`: number of whole wits
fn whole_wits(nanowits: u64) -> u64 {
Wit::wits_and_nanowits(Wit::from_nanowits(nanowits)).0
}
#[allow(
clippy::cast_possible_wrap,
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)]
pub fn get_supply_info(addr: SocketAddr) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = r#"{"jsonrpc": "2.0","method": "getSupplyInfo", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let supply_info = parse_response::<SupplyInfo>(&response)?;
log::info!("{:?}", supply_info);
println!(
"\nSupply info at {} (epoch {}):\n",
pretty_print(supply_info.current_time as i64, 0),
supply_info.epoch
);
let block_rewards_wit = whole_wits(supply_info.blocks_minted_reward);
let block_rewards_missing_wit = whole_wits(supply_info.blocks_missing_reward);
let collateralized_data_requests_total_wit = whole_wits(supply_info.locked_wits_by_requests);
let current_supply =
whole_wits(supply_info.current_unlocked_supply + supply_info.locked_wits_by_requests);
let locked_supply = whole_wits(supply_info.current_locked_supply);
let total_supply = whole_wits(supply_info.maximum_supply - supply_info.blocks_missing_reward);
let expected_total_supply = whole_wits(supply_info.maximum_supply);
let mut supply_table = Table::new();
supply_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
supply_table.set_titles(row!["Supply type", r->"Total WITs"]);
supply_table.add_row(row![
"Temporarily locked in data requests".to_string(),
r->collateralized_data_requests_total_wit.to_formatted_string(&Locale::en)
]);
supply_table.add_row(row![
"Unlocked supply".to_string(),
r->current_supply.to_formatted_string(&Locale::en)
]);
supply_table.add_row(row![
"Locked supply".to_string(),
r->locked_supply.to_formatted_string(&Locale::en)
]);
supply_table.add_row(row![
"Circulating supply".to_string(),
r->(current_supply + locked_supply).to_formatted_string(&Locale::en)
]);
supply_table.add_row(row![
"Actual maximum supply".to_string(),
r->total_supply.to_formatted_string(&Locale::en)
]);
supply_table.add_row(row![
"Expected maximum supply".to_string(),
r->expected_total_supply.to_formatted_string(&Locale::en)
]);
supply_table.printstd();
println!();
let mut blocks_table = Table::new();
blocks_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
blocks_table.set_titles(row!["Blocks", r->"Amount", r->"Total WITs"]);
blocks_table.add_row(row![
"Minted".to_string(),
r->supply_info.blocks_minted.to_formatted_string(&Locale::en),
r->block_rewards_wit.to_formatted_string(&Locale::en)
]);
blocks_table.add_row(row![
"Reverted".to_string(),
r->supply_info.blocks_missing.to_formatted_string(&Locale::en),
r->block_rewards_missing_wit.to_formatted_string(&Locale::en)
]);
blocks_table.add_row(row![
"Expected".to_string(),
r->(supply_info.blocks_minted + supply_info.blocks_missing).to_formatted_string(&Locale::en),
r->(block_rewards_wit + block_rewards_missing_wit).to_formatted_string(&Locale::en)
]);
blocks_table.printstd();
println!();
println!(
"{}% of circulating supply is locked.",
((locked_supply as f64 / (current_supply + locked_supply) as f64) * 100.0).round() as u8
);
println!(
"{}% of all blocks so far have been reverted.",
((block_rewards_missing_wit as f64
/ (block_rewards_wit + block_rewards_missing_wit) as f64)
* 100.0)
.round() as u8
);
println!("For more information about block rewards and halvings, see:\nhttps://github.com/witnet/WIPs/blob/master/wip-0003.md");
Ok(())
}
pub fn get_balance(
addr: SocketAddr,
pkh: Option<PublicKeyHash>,
simple: bool,
) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let pkh = match pkh {
Some(pkh) => pkh,
None => {
log::info!("No pkh specified, will default to node pkh");
let request = r#"{"jsonrpc": "2.0","method": "getPkh", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let node_pkh = parse_response::<PublicKeyHash>(&response)?;
log::info!("Node pkh: {}", node_pkh);
node_pkh
}
};
let params = GetBalanceParams { pkh, simple };
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getBalance", "params": {}, "id": "1"}}"#,
serde_json::to_string(¶ms).unwrap()
);
log::info!("{}", request);
let response = send_request(&mut stream, &request)?;
log::info!("{}", response);
let amount = parse_response::<NodeBalance>(&response)?;
if simple {
println!("Balance: {} wits", Wit::from_nanowits(amount.total));
} else {
println!(
"Confirmed balance: {} wits\n\
Pending balance: {} wits",
Wit::from_nanowits(amount.confirmed.unwrap()),
wit_difference_to_string(amount.confirmed.unwrap(), amount.total)
);
}
Ok(())
}
// Check if the pending balance is positive or negative
fn wit_difference_to_string(confirmed: u64, total: u64) -> String {
if total >= confirmed {
Wit::from_nanowits(total - confirmed).to_string()
} else {
let mut neg = String::from("-");
neg.push_str(&Wit::from_nanowits(confirmed - total).to_string());
neg
}
}
pub fn get_pkh(addr: SocketAddr) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = r#"{"jsonrpc": "2.0","method": "getPkh", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
log::info!("{}", response);
let pkh = parse_response::<PublicKeyHash>(&response)?;
println!("{}", pkh);
println!("Testnet address: {}", pkh.bech32(Environment::Testnet));
println!("Mainnet address: {}", pkh.bech32(Environment::Mainnet));
Ok(())
}
#[allow(clippy::cast_possible_wrap)]
pub fn get_utxo_info(
addr: SocketAddr,
long: bool,
pkh: Option<PublicKeyHash>,
) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let pkh = match pkh {
Some(pkh) => pkh,
None => {
log::info!("No pkh specified, will default to node pkh");
let request = r#"{"jsonrpc": "2.0","method": "getPkh", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let node_pkh = parse_response::<PublicKeyHash>(&response)?;
log::info!("Node pkh: {}", node_pkh);
node_pkh
}
};
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getUtxoInfo", "params": [{}], "id": "1"}}"#,
serde_json::to_string(&pkh)?,
);
let response = send_request(&mut stream, &request)?;
let utxo_info = parse_response::<UtxoInfo>(&response)?;
let utxos_len = utxo_info.utxos.len();
let mut utxo_sum = 0;
let mut utxo_too_small_counter = 0;
let mut utxo_too_small_sum = 0;
let mut utxo_not_ready_counter = 0;
let mut utxo_not_ready_sum = 0;
let mut utxo_ready_counter = 0;
let mut utxo_ready_sum = 0;
let mut table = Table::new();
table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
table.set_titles(row![
"OutputPointer",
"Value (in wits)",
"Time lock",
"Ready for collateral"
]);
for utxo_metadata in utxo_info
.utxos
.into_iter()
.sorted_by_key(|um| (um.value, um.output_pointer.clone()))
{
let ready_for_collateral: bool = (utxo_metadata.value >= utxo_info.collateral_min)
&& utxo_metadata.utxo_mature
&& utxo_metadata.timelock == 0;
if long {
let value = Wit::from_nanowits(utxo_metadata.value).to_string();
let time_lock = if utxo_metadata.timelock == 0 {
"Ready".to_string()
} else {
pretty_print(utxo_metadata.timelock as i64, 0)
};
table.add_row(row![
utxo_metadata.output_pointer.to_string(),
value,
time_lock,
ready_for_collateral.to_string()
]);
}
utxo_sum += utxo_metadata.value;
// Utxo bigger than collateral minimum, no timelock and mature
if ready_for_collateral {
utxo_ready_counter += 1;
utxo_ready_sum += utxo_metadata.value;
// Utxo smaller than collateral_min, can never be collateralized (until joined)
} else if utxo_metadata.value < utxo_info.collateral_min {
utxo_too_small_counter += 1;
utxo_too_small_sum += utxo_metadata.value;
// Utxo with a timelock enabled or utxo bigger than collateral minimum, no timelock but not mature
} else {
utxo_not_ready_counter += 1;
utxo_not_ready_sum += utxo_metadata.value;
}
}
if long {
table.printstd();
println!("-----------------------");
}
let mut utxos_table = Table::new();
utxos_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
utxos_table.set_titles(row!["Utxos", "Number", "Value (in wits)"]);
utxos_table.add_row(row![
"Total utxos".to_string(),
utxos_len,
Wit::from_nanowits(utxo_sum).to_string()
]);
utxos_table.add_row(row![
"Utxos smaller than collateral minimum".to_string(),
utxo_too_small_counter,
Wit::from_nanowits(utxo_too_small_sum).to_string()
]);
utxos_table.add_row(row![
"Utxos bigger than collateral minimum".to_string(),
(utxos_len - utxo_too_small_counter),
Wit::from_nanowits(utxo_sum - utxo_too_small_sum).to_string()
]);
utxos_table.add_row(row![
"Utxos bigger than and ready for collateral".to_string(),
utxo_ready_counter,
Wit::from_nanowits(utxo_ready_sum).to_string()
]);
utxos_table.add_row(row![
"Utxos bigger than and not ready for collateral".to_string(),
utxo_not_ready_counter,
Wit::from_nanowits(utxo_not_ready_sum).to_string()
]);
utxos_table.printstd();
Ok(())
}
#[allow(clippy::cast_precision_loss)]
pub fn get_reputation(
addr: SocketAddr,
opt_pkh: Option<PublicKeyHash>,
all: bool,
) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = if all {
r#"{"jsonrpc": "2.0","method": "getReputationAll", "id": "1"}"#.to_string()
} else {
let pkh = match opt_pkh {
Some(pkh) => pkh,
None => {
log::info!("No pkh specified, will default to node pkh");
let request = r#"{"jsonrpc": "2.0","method": "getPkh", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let node_pkh = parse_response::<PublicKeyHash>(&response)?;
log::info!("Node pkh: {}", node_pkh);
node_pkh
}
};
format!(
r#"{{"jsonrpc": "2.0","method": "getReputation", "params": [{}], "id": "1"}}"#,
serde_json::to_string(&pkh)?,
)
};
let response = send_request(&mut stream, &request)?;
let res = parse_response::<GetReputationResult>(&response)?;
if res.stats.is_empty() {
println!("No identities have reputation yet");
}
for (pkh, rep_stats) in res.stats.into_iter().sorted_by_key(|(_, rep_stats)| {
std::cmp::Reverse((rep_stats.reputation.0, rep_stats.eligibility))
}) {
let eligibility = f64::from(rep_stats.eligibility) / res.total_reputation as f64;
let active = if rep_stats.is_active { 'A' } else { ' ' };
if rep_stats.is_active || !all {
println!(
" [{}] {} -> Reputation: {}, Eligibility: {:.6}%",
active,
pkh,
rep_stats.reputation.0,
eligibility * 100_f64
);
} else {
println!(
" [{}] {} -> Reputation: {}",
active, pkh, rep_stats.reputation.0
);
}
}
Ok(())
}
pub fn get_miners(addr: SocketAddr, start: i64, end: i64, csv: bool) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let params = GetBlockChainParams {
epoch: start,
limit: end,
};
let response = send_request(
&mut stream,
&format!(
r#"{{"jsonrpc": "2.0","method": "getBlockChain", "params": {}, "id": 1}}"#,
serde_json::to_string(¶ms).unwrap()
),
)?;
log::info!("{}", response);
let block_chain: ResponseBlockChain<'_> = parse_response(&response)?;
let mut hm = HashMap::new();
if csv {
println!("Block number;Block hash;Miner hash")
} else {
println!("Blockchain:");
}
for (epoch, hash) in block_chain {
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getBlock", "params": [{:?}], "id": "1"}}"#,
hash,
);
let response = send_request(&mut stream, &request)?;
let block: Block = parse_response(&response)?;
let miner_hash = block.block_sig.public_key.pkh().to_string();
if csv {
println!("{};{};{}", epoch, hash, miner_hash);
} else {
println!(
"Block for epoch #{} had digest {} ans was mined by {}",
epoch, hash, miner_hash
);
}
*hm.entry(miner_hash).or_insert(0) += 1;
}
let mut scoreboard: Vec<(String, i32)> = hm.into_iter().collect();
scoreboard.sort_by_key(|(m, _n)| m.clone());
if csv {
println!("\nMiner address;Mined blocks count");
} else {
println!("\nScoreboard:");
}
for (miner, n) in scoreboard.iter() {
if csv {
println!("{};{}", miner, n);
} else {
println!("{} has mined {} blocks", miner, n);
}
}
Ok(())
}
pub fn get_block(addr: SocketAddr, hash: String) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getBlock", "params": [{:?}], "id": "1"}}"#,
hash,
);
let response = send_request(&mut stream, &request)?;
println!("{}", response);
Ok(())
}
pub fn get_transaction(addr: SocketAddr, hash: String) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getTransaction", "params": [{:?}], "id": "1"}}"#,
hash,
);
let response = send_request(&mut stream, &request)?;
println!("{}", response);
Ok(())
}
pub fn get_output(addr: SocketAddr, pointer: String) -> Result<(), failure::Error> {
let mut _stream = start_client(addr)?;
let output_pointer = OutputPointer::from_str(&pointer)?;
let request_payload = serde_json::to_string(&output_pointer)?;
let _request = format!(
r#"{{"jsonrpc": "2.0","method": "getOutput", "params": [{}], "id": "1"}}"#,
request_payload,
);
//let response = send_request(&mut stream, request)?;
let response = "unimplemented yet";
println!("{}", response);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn send_vtt(
addr: SocketAddr,
pkh: Option<PublicKeyHash>,
value: u64,
size: Option<u64>,
fee: u64,
time_lock: u64,
sorted_bigger: Option<bool>,
dry_run: bool,
) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let size = size.unwrap_or(value);
if value / size > 1000 {
bail!("This transaction is creating more than 1000 outputs and may not be accepted by the miners");
}
let pkh = match pkh {
Some(pkh) => pkh,
None => {
log::info!("No pkh specified, will default to node pkh");
let request = r#"{"jsonrpc": "2.0","method": "getPkh", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let node_pkh = parse_response::<PublicKeyHash>(&response)?;
log::info!("Node pkh: {}", node_pkh);
node_pkh
}
};
let mut vt_outputs = vec![];
let mut value = value;
while value >= 2 * size {
value -= size;
vt_outputs.push(ValueTransferOutput {
pkh,
value: size,
time_lock,
})
}
vt_outputs.push(ValueTransferOutput {
pkh,
value,
time_lock,
});
let utxo_strategy = match sorted_bigger {
Some(true) => UtxoSelectionStrategy::BigFirst { from: None },
Some(false) => UtxoSelectionStrategy::SmallFirst { from: None },
None => UtxoSelectionStrategy::Random { from: None },
};
let params = BuildVtt {
vto: vt_outputs,
fee,
utxo_strategy,
};
let request = format!(
r#"{{"jsonrpc": "2.0","method": "sendValue", "params": {}, "id": "1"}}"#,
serde_json::to_string(¶ms)?
);
if dry_run {
println!("{}", request);
} else {
let response = send_request(&mut stream, &request)?;
println!("{}", response);
}
Ok(())
}
fn deserialize_and_validate_hex_dr(hex_bytes: String) -> Result<DataRequestOutput, failure::Error> {
let dr_bytes = hex::decode(hex_bytes)?;
let dr: DataRequestOutput = ProtobufConvert::from_pb_bytes(&dr_bytes)?;
log::debug!("{}", serde_json::to_string(&dr)?);
validate_data_request_output(&dr)?;
validate_rad_request(&dr.data_request, ¤t_active_wips())?;
// Is the data request serialized correctly?
// Check that serializing the deserialized struct results in exactly the same bytes
let witnet_dr_bytes = dr.to_pb_bytes()?;
if dr_bytes != witnet_dr_bytes {
log::warn!("Data request uses an invalid serialization, will be ignored.\nINPUT BYTES: {:02x?}\nWIT DR BYTES: {:02x?}",
dr_bytes, witnet_dr_bytes
);
log::warn!(
"This usually happens when some fields are set to 0. \
The Rust implementation of ProtocolBuffer skips those fields, \
as missing fields are deserialized with the default value."
);
bail!("Invalid serialization");
}
Ok(dr)
}
pub fn send_dr(
addr: SocketAddr,
hex_bytes: String,
fee: u64,
dry_run: bool,
) -> Result<(), failure::Error> {
let dr_output = deserialize_and_validate_hex_dr(hex_bytes)?;
if dry_run {
let tally_result = run_dr_locally(&dr_output)?;
println!("Request run locally with Tally result: {}", tally_result);
} else {
let bdr_params = json!({"dro": dr_output, "fee": fee});
let request = format!(
r#"{{"jsonrpc": "2.0","method": "sendRequest", "params": {}, "id": "1"}}"#,
serde_json::to_string(&bdr_params)?
);
let mut stream = start_client(addr)?;
let response = send_request(&mut stream, &request)?;
println!("{}", response);
}
Ok(())
}
pub fn master_key_export(
addr: SocketAddr,
write_to_path: Option<&Path>,
) -> Result<(), failure::Error> {
let request = r#"{"jsonrpc": "2.0","method":"masterKeyExport","id": "1"}"#;
let mut stream = start_client(addr)?;
let response = send_request(&mut stream, request)?;
match parse_response(&response) {
Ok(private_key_slip32) => {
let private_key_slip32: String = private_key_slip32;
let private_key = ExtendedSK::from_slip32(&private_key_slip32).unwrap().0;
let public_key = ExtendedPK::from_secret_key(&CryptoEngine::new(), &private_key);
let pkh = PublicKey::from(public_key.key).pkh();
if let Some(base_path) = write_to_path {
let path = base_path.join(format!("private_key_{}.txt", pkh));
let mut file = create_credentials_file(&path)?;
file.write_all(format!("{}\n", private_key_slip32).as_bytes())?;
let full_path = Path::new(&path);
println!(
"Private key written to {}",
full_path.canonicalize()?.as_path().display()
);
} else {
println!("Private key for pkh {}:\n{}", pkh, private_key_slip32);
}
}
Err(error) => {
println!("{}", error);
}
}
Ok(())
}
#[derive(Debug, Serialize)]
struct DataRequestTransactionInfo {
data_request_tx_hash: String,
data_request_output: DataRequestOutput,
data_request_creator_pkh: String,
block_hash_data_request_tx: String,
#[serde(skip_serializing_if = "Option::is_none")]
block_hash_tally_tx: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
data_request_state: Option<DataRequestState>,
// [(pkh, reveal, reward_value)]
#[serde(skip_serializing_if = "Option::is_none")]
reveals: Option<Vec<(String, String, String)>>,
#[serde(skip_serializing_if = "Option::is_none")]
tally: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
local_tally: Option<String>,
#[serde(skip)]
print_data_request: bool,
}
#[derive(Debug, Serialize)]
struct DataRequestState {
stage: String,
current_commit_round: u16,
current_reveal_round: u16,
}
impl fmt::Display for DataRequestTransactionInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
f,
"Report for data request {}:",
White.bold().paint(&self.data_request_tx_hash)
)?;
if self.print_data_request {
writeln!(
f,
"data_request_output: {}",
serde_json::to_string_pretty(&self.data_request_output).unwrap()
)?;
}
if self.block_hash_data_request_tx == "pending" {
writeln!(
f,
"Deployed by {}, not yet included in any block",
self.data_request_creator_pkh
)?;
} else {
writeln!(
f,
"Deployed in block {} by {}",
Purple.bold().paint(&self.block_hash_data_request_tx),
self.data_request_creator_pkh
)?;
let data_request_state = self.data_request_state.as_ref().unwrap();
let num_commits = self.reveals.as_ref().unwrap().len();
let num_reveals = self
.reveals
.as_ref()
.unwrap()
.iter()
.filter_map(
|(_pkh, reveal, _honest)| {
if reveal.is_empty() {
None
} else {
Some(())
}
},
)
.count();
if data_request_state.stage == "FINISHED" {
writeln!(
f,
"{} with {} commits and {} reveals",
White.bold().paint(&data_request_state.stage),
num_commits,
num_reveals,
)?;
} else {
writeln!(
f,
"In {} stage with {} commits and {} reveals",
White.bold().paint(&data_request_state.stage),
num_commits,
num_reveals,
)?;
}
writeln!(
f,
"Commit rounds: {}",
data_request_state.current_commit_round,
)?;
writeln!(
f,
"Reveal rounds: {}",
data_request_state.current_reveal_round,
)?;
}
if let Some(reveals) = &self.reveals {
let data_request_state = self.data_request_state.as_ref().unwrap();
if data_request_state.stage == "COMMIT" {
writeln!(
f,
"Commits:{}",
if reveals.is_empty() {
" (no commits)"
} else {
""
}
)?;
} else {
writeln!(
f,
"Reveals:{}",
if reveals.is_empty() {
" (no reveals)"
} else {
""
}
)?;
}
for (pkh, reveal, reward) in reveals {
let reveal_str = if reveal.is_empty() {
"No reveal"
} else {
reveal
};
match reward.chars().next() {
Some('+') => {
writeln!(
f,
" [Rewarded ] {}: {}",
pkh,
Yellow.bold().paint(reveal_str)
)?;
}
Some('-') => {
writeln!(
f,
" {} {}: {}",
Red.bold().paint("[Penalized]"),
Red.bold().paint(pkh),
Yellow.bold().paint(reveal_str)
)?;
}
// Neither positive or negative means that the collateral was returned to the
// witness, but it has not been rewarded. This happens when the witness
// committed an error but the consensus is not an error.
_ => {
if data_request_state.stage == "FINISHED" {
writeln!(
f,
" [ Error ] {}: {}",
pkh,
Yellow.bold().paint(reveal_str)
)?;
} else {
writeln!(f, " {}: {}", pkh, Yellow.bold().paint(reveal_str))?;
}
}
}
}
} else {
writeln!(f, "No reveals yet")?;
}
if let Some(tally) = &self.tally {
writeln!(f, "Tally: {}", Yellow.bold().paint(tally))?;
}
if let Some(local_tally) = &self.local_tally {
writeln!(f, "Local tally: {}", Yellow.bold().paint(local_tally))?;
}
Ok(())
}
}
pub fn data_request_report(
addr: SocketAddr,
hash: String,
json: bool,
print_data_request: bool,
create_local_tally: bool,
) -> Result<(), failure::Error> {
let mut stream = start_client(addr)?;
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getTransaction", "params": [{:?}], "id": "1"}}"#,
hash,
);
let response = send_request(&mut stream, &request)?;
let transaction: GetTransactionOutput = parse_response(&response)?;
let data_request_transaction_block_hash = transaction.block_hash.clone();
let transaction_block_hash = if transaction.block_hash == "pending" {
None
} else {
Some(transaction.block_hash)
};
let dr_tx = if let Transaction::DataRequest(dr_tx) = transaction.transaction {
dr_tx
} else {
bail!("This is not a data request transaction");
};
let mut dr_output = dr_tx.body.dr_output;
let dr_creator_pkh = dr_tx.signatures[0].public_key.pkh();
// When collateral is set to 0, it is actually the default collateral
// Get the consensus constants from to node to find out what is the default collateral
if dr_output.collateral == 0 {
let request = r#"{"jsonrpc": "2.0","method": "getConsensusConstants", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let consensus_constants: ConsensusConstants = parse_response(&response)?;
dr_output.collateral = consensus_constants.collateral_minimum;
}
let (data_request_state, reveals, tally, local_tally, block_hash_tally_tx) =
if transaction_block_hash.is_none() {
(None, None, None, None, None)
} else {
let request = format!(
r#"{{"jsonrpc": "2.0","method": "dataRequestReport", "params": [{:?}], "id": "1"}}"#,
hash,
);
let response = send_request(&mut stream, &request)?;
let dr_info: DataRequestInfo = parse_response(&response)?;
let data_request_state = DataRequestState {
stage: dr_info
.current_stage
.map(|x| format!("{:?}", x))
.unwrap_or_else(|| "FINISHED".to_string()),
current_commit_round: dr_info.current_commit_round,
current_reveal_round: dr_info.current_reveal_round,
};
let mut reveals = vec![];
let mut reveal_txns = vec![];
for (pkh, reveal_transaction) in &dr_info.reveals {
let reveal_radon_types =
RadonTypes::try_from(reveal_transaction.body.reveal.as_slice())?;
reveals.push((*pkh, Some(reveal_radon_types)));
reveal_txns.push(reveal_transaction);
}
for pkh in dr_info.commits.keys() {
if !reveals.iter().any(|(reveal_pkh, _)| reveal_pkh == pkh) {
reveals.push((*pkh, None));
}
}
// Sort reveal list by pkh
reveals.sort_unstable_by_key(|(pkh, _)| *pkh);
let reveals = reveals;
let tally = dr_info
.tally
.as_ref()
.map(|t| RadonTypes::try_from(t.tally.as_slice()))
.transpose()?;
let mut local_tally = None;
if create_local_tally {
// Run the tally stage locally. This can be useful if the result is a RadonError,
// because it may report a better error message.
// Get the activation epochs of the current active WIPs from the node
let request = r#"{"jsonrpc": "2.0","method": "signalingInfo", "id": "1"}"#;
let response = send_request(&mut stream, request)?;
let signaling_info: SignalingInfo = parse_response(&response)?;
// Get the tally block epoch from the tally block hash
let request = format!(
r#"{{"jsonrpc": "2.0","method": "getBlock", "params": [{:?}], "id": "1"}}"#,
dr_info.block_hash_tally_tx.unwrap().to_string(),
);
let response = send_request(&mut stream, &request)?;
let tally_block: Block = parse_response(&response)?;
let tally_block_epoch = tally_block.block_header.beacon.checkpoint;
// Run tally locally
let active_wips = ActiveWips {
active_wips: signaling_info.active_upgrades,
block_epoch: tally_block_epoch,
};
let non_error_min = f64::from(dr_output.min_consensus_percentage) / 100.0;