forked from witnet/witnet-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.rs
2735 lines (2494 loc) · 99.2 KB
/
api.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 std::{
collections::HashMap,
convert::TryFrom,
fmt::Debug,
net::SocketAddr,
path::PathBuf,
str::FromStr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use actix::MailboxError;
#[cfg(not(test))]
use actix::SystemService;
use futures::FutureExt;
use itertools::Itertools;
use jsonrpc_core::{BoxFuture, Error, Params, Value};
use jsonrpc_pubsub::{Subscriber, SubscriptionId};
use serde::{Deserialize, Serialize};
use strum_macros::IntoStaticStr;
use witnet_crypto::key::KeyPath;
use witnet_data_structures::{
chain::{
tapi::ActiveWips, Block, DataRequestOutput, Epoch, Hash, Hashable, KeyedSignature,
PublicKeyHash, RADType, StakeOutput, StateMachine, SyncStatus,
},
get_environment, get_protocol_version,
proto::versioning::{ProtocolVersion, VersionedHashable},
staking::prelude::*,
transaction::Transaction,
vrf::VrfMessage,
};
use crate::{
actors::{
chain_manager::{run_dr_locally, ChainManager, ChainManagerError},
epoch_manager::{EpochManager, EpochManagerError},
inventory_manager::{InventoryManager, InventoryManagerError},
json_rpc::Subscriptions,
messages::{
AddCandidates, AddPeers, AddTransaction, AuthorizeStake, BuildDrt, BuildStake,
BuildStakeParams, BuildStakeResponse, BuildUnstake, BuildUnstakeParams, BuildVtt,
ClearPeers, DropAllPeers, EstimatePriority, GetBalance, GetBalanceTarget,
GetBlocksEpochRange, GetConsolidatedPeers, GetDataRequestInfo, GetEpoch,
GetHighestCheckpointBeacon, GetItemBlock, GetItemSuperblock, GetItemTransaction,
GetKnownPeers, GetMemoryTransaction, GetMempool, GetNodeStats, GetProtocolInfo,
GetReputation, GetSignalingInfo, GetState, GetSupplyInfo, GetSupplyInfo2, GetUtxoInfo,
InitializePeers, IsConfirmedBlock, MagicEither, QueryStakePowers, QueryStakes,
QueryStakesFilter, Rewind, SnapshotExport, SnapshotImport, StakeAuthorization,
},
peers_manager::PeersManager,
sessions_manager::SessionsManager,
},
config_mngr, signature_mngr,
utils::Force,
};
#[cfg(test)]
use self::mock_actix::SystemService;
type JsonRpcResult = jsonrpc_core::Result<jsonrpc_core::Value>;
/// Guard methods that assume that JSON-RPC is only accessible by the owner of the node.
///
/// A method is sensitive if it touches in some way the master key of the node or leaks addresses.
/// For example: methods that can be used to create transactions (spending value from this node),
/// sign arbitrary messages with the node master key, or even export the master key.
async fn if_authorized<F, Fut>(
enable_sensitive_methods: bool,
method_name: &str,
params: Params,
method: F,
) -> JsonRpcResult
where
F: FnOnce(Params) -> Fut,
Fut: futures::Future<Output = JsonRpcResult>,
{
if enable_sensitive_methods {
method(params).await
} else {
Err(internal_error_s(unauthorized_message(method_name)))
}
}
/// Attach the regular JSON-RPC methods to a multi-transport server.
pub fn attach_regular_methods<H>(
server: &mut impl witty_jsonrpc::server::ActixServer<H>,
system: &Option<actix::System>,
) where
H: witty_jsonrpc::handler::Handler,
{
server.add_actix_method(system, "inventory", |params: Params| {
Box::pin(inventory(params.parse()))
});
server.add_actix_method(system, "getBlockChain", |params: Params| {
Box::pin(get_block_chain(params.parse()))
});
server.add_actix_method(system, "getBlock", |params: Params| {
Box::pin(get_block(params))
});
server.add_actix_method(system, "getTransaction", |params: Params| {
Box::pin(get_transaction(params.parse()))
});
server.add_actix_method(system, "syncStatus", |_params: Params| Box::pin(status()));
server.add_actix_method(system, "dataRequestReport", |params: Params| {
Box::pin(data_request_report(params.parse()))
});
server.add_actix_method(system, "getBalance", |params: Params| {
Box::pin(get_balance(params))
});
server.add_actix_method(system, "getReputation", |params: Params| {
Box::pin(get_reputation(params.parse(), false))
});
server.add_actix_method(system, "getReputationAll", |_params: Params| {
Box::pin(get_reputation(Ok((PublicKeyHash::default(),)), true))
});
server.add_actix_method(system, "getSupplyInfo", |_params: Params| {
Box::pin(get_supply_info())
});
server.add_actix_method(system, "getSupplyInfo2", |_params: Params| {
Box::pin(get_supply_info_2())
});
server.add_actix_method(system, "peers", |_params: Params| Box::pin(peers()));
server.add_actix_method(system, "knownPeers", |_params: Params| {
Box::pin(known_peers())
});
server.add_actix_method(
system,
"nodeStats",
|_params: Params| Box::pin(node_stats()),
);
server.add_actix_method(system, "getMempool", |params: Params| {
Box::pin(get_mempool(params.parse()))
});
server.add_actix_method(system, "getConsensusConstants", |params: Params| {
Box::pin(get_consensus_constants(params.parse()))
});
server.add_actix_method(system, "getSuperblock", |params: Params| {
Box::pin(get_superblock(params.parse()))
});
server.add_actix_method(system, "signalingInfo", |_params: Params| {
Box::pin(signaling_info())
});
server.add_actix_method(system, "priority", |_params: Params| Box::pin(priority()));
server.add_actix_method(system, "protocol", |_params: Params| Box::pin(protocol()));
server.add_actix_method(system, "queryStakes", |params: Params| {
Box::pin(query_stakes(params.parse()))
});
server.add_actix_method(system, "queryPowers", |params: Params| {
Box::pin(query_powers(params.parse()))
});
server.add_actix_method(system, "getUtxoInfo", move |params: Params| {
Box::pin(get_utxo_info(params.parse()))
});
}
/// Attach the sensitive JSON-RPC methods to a multi-transport server.
pub fn attach_sensitive_methods<H>(
server: &mut impl witty_jsonrpc::server::ActixServer<H>,
enable_sensitive_methods: bool,
system: &Option<actix::System>,
) where
H: witty_jsonrpc::handler::Handler,
{
server.add_actix_method(system, "sendRequest", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"sendRequest",
params,
|params| send_request(params.parse()),
))
});
server.add_actix_method(system, "tryRequest", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"tryRequest",
params,
|params| try_request(params.parse()),
))
});
server.add_actix_method(system, "sendValue", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"sendValue",
params,
|params| send_value(params.parse()),
))
});
server.add_actix_method(system, "getPublicKey", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"getPublicKey",
params,
|_params| get_public_key(),
))
});
server.add_actix_method(system, "getPkh", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"getPkh",
params,
|_params| get_pkh(),
))
});
server.add_actix_method(system, "sign", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"sign",
params,
|params| sign_data(params.parse()),
))
});
server.add_actix_method(system, "createVRF", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"createVRF",
params,
|params| create_vrf(params.parse()),
))
});
server.add_actix_method(system, "masterKeyExport", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"masterKeyExport",
params,
|_params| master_key_export(),
))
});
server.add_actix_method(system, "addPeers", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"addPeers",
params,
|params| add_peers(params.parse()),
))
});
server.add_actix_method(system, "clearPeers", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"clearPeers",
params,
|_params| clear_peers(),
))
});
server.add_actix_method(system, "initializePeers", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"initializePeers",
params,
|_params| initialize_peers(),
))
});
server.add_actix_method(system, "rewind", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"rewind",
params,
|params| rewind(params.parse()),
))
});
server.add_actix_method(system, "chainExport", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"chainExport",
params,
|params| snapshot_export(params.parse()),
))
});
server.add_actix_method(system, "chainImport", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"chainImport",
params,
|params| snapshot_import(params.parse()),
))
});
server.add_actix_method(system, "stake", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"stake",
params,
|params| stake(params.parse()),
))
});
server.add_actix_method(system, "authorizeStake", move |params: Params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"authorizeStake",
params,
|params| authorize_stake(params.parse()),
))
});
server.add_actix_method(system, "unstake", move |params| {
Box::pin(if_authorized(
enable_sensitive_methods,
"unstake",
params,
|params| unstake(params.parse()),
))
});
}
fn extract_topic_and_params(params: Params) -> Result<(String, Value), Error> {
if let Params::Array(values) = params {
let mut values_iter = values.into_iter();
// Try to read a first param that must be a String representing the topic
let topic = String::from(values_iter
.next()
.ok_or(Error::invalid_params(
"At least one subscription param is expected, representing the topic to subscribe to",
))?.as_str().ok_or(Error::invalid_params("The first subscription param is expected to be a String representing the topic to subscribe to"))?);
// Try to read a second param that will be used as the topic param (defaults to Null)
let params = values_iter.next().unwrap_or(Value::Null);
Ok((topic, params))
} else {
Err(Error::invalid_params(
"Subscription params must be an Array",
))
}
}
/// Attach the JSON-RPC subscriptions to a multi-transport server.
pub fn attach_subscriptions<H>(
server: &mut impl witty_jsonrpc::server::ActixServer<H>,
subscriptions: Subscriptions,
system: &Option<actix::System>,
) where
H: witty_jsonrpc::handler::Handler,
{
// Atomic counter that keeps track of the next subscriber ID
let atomic_counter = AtomicUsize::new(1);
// Cloned the subscriptions for reuse in subscribe / unsubscribe closures
let cloned_subscriptions = subscriptions.clone();
// Wrapped in `Arc` for spawning the subscriptions in other threads safely
let subscribe_arc = Arc::new(
move |params: Params, meta: H::Metadata, subscriber: Subscriber| {
log::debug!(
"Called subscribe method with params {:?} and meta {:?}",
params,
meta
);
// Main business logic for registering a new subscription
let register = |topic: String, params: Value, subscriber: Subscriber| {
if let Ok(mut all_subscriptions) = cloned_subscriptions.lock() {
// Generate a subscription ID and assign it to the subscriber, getting a sink
let id = SubscriptionId::String(
atomic_counter.fetch_add(1, Ordering::SeqCst).to_string(),
);
let sink = subscriber.assign_id(id.clone());
// If we got a sink, we can register the subscription
if let Ok(sink) = sink {
let topic_subscriptions = all_subscriptions
.entry(topic.clone())
.or_insert_with(HashMap::new);
topic_subscriptions.insert(id, (sink, params));
log::debug!(
"Subscribed to topic '{}'. There are {} subscriptions to this topic",
topic,
topic_subscriptions.len()
);
} else {
// If we couldn't get a sync, it's probably because the session closed before we
// got a chance to reply
log::debug!("Failed to assign id: session closed");
}
} else {
log::error!("Failed to acquire lock on subscriptions Arc");
subscriber
.reject(internal_error_s(
"failed to acquire lock on subscriptions Arc",
))
.ok();
};
};
// Try to extract the method name and true params from raw JSON-RPC params
match extract_topic_and_params(params) {
Ok((topic, params)) => {
// Deal with supported / unsupported subscription methods
match topic.as_str() {
"blocks" | "superblocks" | "status" => {
// If using a supported topic, register the subscription
register(topic, params, subscriber);
}
other => {
// If the topic is unknown, reject the subscription
log::error!(
"got a subscription request for an unsupported topic: {}",
other
);
subscriber
.reject(Error::invalid_params_with_details(
"unknown subscription topic",
other,
))
.ok();
}
}
}
Err(error) => {
// Upon any error, reject the subscriber and exit
subscriber.reject(error).ok();
}
}
},
);
// Wrapped in `Arc` for spawning the unsubscriptions in other threads safely
let unsubscribe_arc = Arc::new(
move |id: SubscriptionId, meta: Option<H::Metadata>| -> BoxFuture<JsonRpcResult> {
log::debug!(
"called unsubscribe method for id {:?} with meta {:?}",
id,
meta
);
match subscriptions.lock() {
Ok(mut subscriptions) => {
let mut found = false;
for (_topic, subscribers) in subscriptions.iter_mut() {
if subscribers.remove(&id).is_some() {
found = true;
// Each id can only appear once because subscriptions to multiple topics
// from the same client will have different IDs.
break;
}
}
Box::pin(futures::future::ok(Value::from(found)))
}
Err(error) => {
log::error!("Failed to acquire lock on subscriptions Arc");
Box::pin(futures::future::err(internal_error(error)))
}
}
},
);
server.add_actix_subscription(
system,
"witnet_subscription",
("witnet_subscribe", subscribe_arc),
("witnet_unsubscribe", unsubscribe_arc),
);
}
/// Attach the whole Node API to a multi-transport server, including regular and sensistive methods,
/// as well as subscriptions.
pub fn attach_api<H>(
server: &mut impl witty_jsonrpc::server::ActixServer<H>,
enable_sensitive_methods: bool,
subscriptions: Subscriptions,
system: &Option<actix::System>,
) where
H: witty_jsonrpc::handler::Handler,
{
attach_regular_methods(server, system);
attach_sensitive_methods(server, enable_sensitive_methods, system);
attach_subscriptions(server, subscriptions, system);
}
fn internal_error<T: std::fmt::Debug>(e: T) -> jsonrpc_core::Error {
jsonrpc_core::Error {
code: jsonrpc_core::ErrorCode::InternalError,
message: format!("{:?}", e),
data: None,
}
}
fn internal_error_s<T: std::fmt::Display>(e: T) -> jsonrpc_core::Error {
jsonrpc_core::Error {
code: jsonrpc_core::ErrorCode::InternalError,
message: format!("{}", e),
data: None,
}
}
/// Message that appears when calling a sensitive method when sensitive methods are disabled
fn unauthorized_message(method_name: &str) -> String {
format!("Method {} not allowed while node setting json_rpc.enable_sensitive_methods is set to false", method_name)
}
/// Inventory element: block, transaction, etc
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
// TODO Remove Clippy allow
#[allow(clippy::large_enum_variant)]
pub enum InventoryItem {
/// Error
#[serde(rename = "error")]
Error,
/// Transaction
#[serde(rename = "transaction")]
Transaction(Transaction),
/// Block
#[serde(rename = "block")]
Block(Block),
}
/// Make the node process, validate and potentially broadcast a new inventory entry.
///
/// Input: the JSON serialization of a well-formed inventory entry
///
/// Returns a boolean indicating success.
/* Test string:
{"jsonrpc": "2.0","method": "inventory","params": {"block": {"block_header":{"version":1,"beacon":{"checkpoint":2,"hash_prev_block": {"SHA256": [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]}},"hash_merkle_root":{"SHA256":[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]}},"proof":{"block_sig": null}"txns":[null]}},"id": 1}
*/
pub async fn inventory(params: Result<InventoryItem, Error>) -> JsonRpcResult {
let inv_elem = match params {
Ok(x) => x,
Err(e) => return Err(e),
};
match inv_elem {
InventoryItem::Block(block) => {
log::debug!("Got block from JSON-RPC. Sending AnnounceItems message.");
let chain_manager_addr = ChainManager::from_registry();
let res = chain_manager_addr
.send(AddCandidates {
blocks: vec![block],
})
.await;
res.map_err(internal_error).map(|()| Value::Bool(true))
}
InventoryItem::Transaction(transaction) => {
log::debug!("Got transaction from JSON-RPC. Sending AnnounceItems message.");
let chain_manager_addr = ChainManager::from_registry();
chain_manager_addr
.send(AddTransaction {
transaction,
broadcast_flag: true,
})
.await
.map_err(internal_error)
.and_then(|res| match res {
Ok(()) => Ok(Value::Bool(true)),
Err(e) => Err(internal_error_s(e)),
})
}
inv_elem => {
log::debug!(
"Invalid type of inventory item from JSON-RPC: {:?}",
inv_elem
);
Err(Error::invalid_params("Item type not implemented"))
}
}
}
/// Params of getBlockChain method
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct GetBlockChainParams {
/// First epoch for which to return block hashes.
/// If negative, return block hashes from the last n epochs.
#[serde(default)] // default to 0
pub epoch: i64,
/// Number of block hashes to return.
/// If negative, return the last n block hashes from this epoch range.
/// If zero, unlimited.
#[serde(default)] // default to 0
pub limit: i64,
}
/// Get the list of all the known block hashes.
///
/// Returns a list of `(epoch, block_hash)` pairs.
/* test
{"jsonrpc": "2.0","method": "getBlockChain", "id": 1}
*/
pub async fn get_block_chain(params: Result<Option<GetBlockChainParams>, Error>) -> JsonRpcResult {
// Helper function to convert the result of GetBlockEpochRange to a JSON value, or a JSON-RPC error
async fn process_get_block_chain(
res: Result<Result<Vec<(u32, Hash)>, ChainManagerError>, MailboxError>,
) -> JsonRpcResult {
match res {
Ok(Ok(vec_inv_entry)) => {
let epoch_and_hash: Vec<_> = vec_inv_entry
.into_iter()
.map(|(epoch, hash)| {
let hash_string = format!("{}", hash);
(epoch, hash_string)
})
.collect();
let value = match serde_json::to_value(epoch_and_hash) {
Ok(x) => x,
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
Ok(value)
}
Ok(Err(e)) => {
let err = internal_error(e);
Err(err)
}
Err(e) => {
let err = internal_error(e);
Err(err)
}
}
}
fn epoch_range(start_epoch: u32, limit: u32, limit_negative: bool) -> GetBlocksEpochRange {
if limit_negative {
GetBlocksEpochRange::new_with_limit_from_end(start_epoch.., limit as usize)
} else {
GetBlocksEpochRange::new_with_limit(start_epoch.., limit as usize)
}
}
fn convert_negative_to_positive_with_negative_flag(x: i64) -> Result<(u32, bool), String> {
let positive_x = u32::try_from(x.unsigned_abs()).map_err(|_e| {
format!(
"out of bounds: {} must be between -{} and {} inclusive",
x,
u32::MAX,
u32::MAX
)
})?;
Ok((positive_x, x.is_negative()))
}
let GetBlockChainParams { epoch, limit } = match params {
Ok(x) => x.unwrap_or_default(),
Err(e) => return Err(e),
};
let (epoch, epoch_negative) = match convert_negative_to_positive_with_negative_flag(epoch) {
Ok(x) => x,
Err(mut err_str) => {
err_str.insert_str(0, "Epoch ");
return Err(internal_error_s(err_str));
}
};
let (limit, limit_negative) = match convert_negative_to_positive_with_negative_flag(limit) {
Ok(x) => x,
Err(mut err_str) => {
err_str.insert_str(0, "Limit ");
return Err(internal_error_s(err_str));
}
};
let chain_manager_addr = ChainManager::from_registry();
if epoch_negative {
// On negative epoch, get blocks from last n epochs
// But, what is the current epoch?
let res = EpochManager::from_registry().send(GetEpoch).await;
match res {
Ok(Ok(current_epoch)) => {
let epoch = current_epoch.saturating_sub(epoch);
let res = chain_manager_addr
.send(epoch_range(epoch, limit, limit_negative))
.await;
process_get_block_chain(res).await
}
Ok(Err(e)) => {
let err = internal_error(e);
Err(err)
}
Err(e) => {
let err = internal_error(e);
Err(err)
}
}
} else {
let res = chain_manager_addr
.send(epoch_range(epoch, limit, limit_negative))
.await;
process_get_block_chain(res).await
}
}
/// Get block by hash
///
/// - First argument is the hash of the block that we are querying.
/// - Second argument is whether we want the response to contain a list of hashes of the
/// transactions found in the block.
/* test
{"jsonrpc":"2.0","id":1,"method":"getBlock","params":["c0002c6b25615c0f71069f159dffddf8a0b3e529efb054402f0649e969715bdb", false]}
*/
pub async fn get_block(params: Params) -> Result<Value, Error> {
let (block_hash, include_txns_metadata): (Hash, bool);
// Handle parameters as an array with a first obligatory hash field plus an optional bool field
if let Params::Array(params) = params {
if let Some(Value::String(hash)) = params.first() {
match hash.parse() {
Ok(hash) => block_hash = hash,
Err(e) => {
return Err(internal_error(e));
}
}
} else {
return Err(Error::invalid_params(
"First argument of `get_block` must have type `Hash`",
));
};
match params.get(1) {
None => include_txns_metadata = true,
Some(Value::Bool(ith)) => include_txns_metadata = *ith,
Some(_) => {
return Err(Error::invalid_params(
"Second argument of `get_block` must have type `Bool`",
))
}
};
} else {
return Err(Error::invalid_params(
"Params of `get_block` method must have type `Array`",
));
};
let inventory_manager = InventoryManager::from_registry();
let res = inventory_manager
.send(GetItemBlock { hash: block_hash })
.await;
match res {
Ok(Ok(mut output)) => {
let block_epoch = output.block_header.beacon.checkpoint;
let block_hash = output.versioned_hash(get_protocol_version(Some(block_epoch)));
let dr_weight = match serde_json::to_value(output.dr_weight()) {
Ok(x) => x,
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
let vt_weight = match serde_json::to_value(output.vt_weight()) {
Ok(x) => x,
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
let block_weight = match serde_json::to_value(output.weight()) {
Ok(x) => x,
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
// Only include the `txns_hashes` field if explicitly requested, as hash
// operations are quite expensive, and transactions read from storage cannot
// benefit from hash memoization
let txns_hashes = if include_txns_metadata {
let vtt_hashes: Vec<_> = output
.txns
.value_transfer_txns
.iter()
.map(|txn| txn.hash())
.collect();
let drt_hashes: Vec<_> = output
.txns
.data_request_txns
.iter()
.map(|txn| txn.hash())
.collect();
let ct_hashes: Vec<_> = output
.txns
.commit_txns
.iter()
.map(|txn| txn.hash())
.collect();
let rt_hashes: Vec<_> = output
.txns
.reveal_txns
.iter()
.map(|txn| txn.hash())
.collect();
let tt_hashes: Vec<_> = output
.txns
.tally_txns
.iter()
.map(|txn| txn.hash())
.collect();
let mut hashes = Some(serde_json::json!({
"mint" : output.txns.mint.hash(),
"value_transfer" : vtt_hashes,
"data_request" : drt_hashes,
"commit" : ct_hashes,
"reveal" : rt_hashes,
"tally" : tt_hashes
}));
if ProtocolVersion::from_epoch(block_epoch) >= ProtocolVersion::V1_8 {
let st_hashes: Vec<_> = output
.txns
.stake_txns
.iter()
.map(|txn| txn.hash())
.collect();
if let Some(ref mut hashes) = hashes {
hashes
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("stake".to_string(), serde_json::json!(st_hashes));
}
}
if ProtocolVersion::from_epoch(block_epoch) == ProtocolVersion::V2_0 {
let ut_hashes: Vec<_> = output
.txns
.unstake_txns
.iter()
.map(|txn| txn.hash())
.collect();
if let Some(ref mut hashes) = hashes {
hashes
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("unstake".to_string(), serde_json::json!(ut_hashes));
}
}
hashes
} else {
None
};
// Only include the `txns_weights` field if explicitly requested
let txns_weights = if include_txns_metadata {
let vtt_weights: Vec<_> = output
.txns
.value_transfer_txns
.iter()
.map(|txn| txn.weight())
.collect();
let drt_weights: Vec<_> = output
.txns
.data_request_txns
.iter()
.map(|txn| txn.weight())
.collect();
let mut weights = Some(serde_json::json!({
"value_transfer": vtt_weights,
"data_request": drt_weights,
}));
if ProtocolVersion::from_epoch(block_epoch) >= ProtocolVersion::V1_8 {
let st_weights: Vec<_> = output
.txns
.stake_txns
.iter()
.map(|txn| txn.weight())
.collect();
if let Some(ref mut weights) = weights {
weights
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("stake".to_string(), st_weights.into());
}
}
if ProtocolVersion::from_epoch(block_epoch) >= ProtocolVersion::V2_0 {
let ut_weights: Vec<_> = output
.txns
.unstake_txns
.iter()
.map(|txn| txn.weight())
.collect();
if let Some(ref mut weights) = weights {
weights
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("unstake".to_string(), ut_weights.into());
}
}
weights
} else {
None
};
// Check if there were data request transactions included in the block which require RADType replacement
// It is imperative to apply this after the transaction hash calculation to conserve the correct hashes
if !output.txns.data_request_txns.is_empty() {
// Create Active WIPs
let signaling_info = ChainManager::from_registry()
.send(GetSignalingInfo {})
.await;
let active_wips = match signaling_info {
Ok(Ok(wips)) => ActiveWips {
active_wips: wips.active_upgrades,
block_epoch,
},
Ok(Err(e)) => {
let err = internal_error(e);
return Err(err);
}
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
if !active_wips.wip0019() {
// Replace RADType::Unknown with RADType::HttpGet for all epochs before the activation of WIP0019
for dr_txn in &mut output.txns.data_request_txns {
for retrieve in &mut dr_txn.body.dr_output.data_request.retrieve {
retrieve.kind = RADType::HttpGet
}
}
}
}
let mut value = match serde_json::to_value(output) {
Ok(x) => x,
Err(e) => {
let err = internal_error(e);
return Err(err);
}
};
// See explanation above about optional `txns_hashes` field
if let Some(txns_hashes) = txns_hashes {
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("txns_hashes".to_string(), txns_hashes);
}
// See explanation above about optional `txns_weights` field
if let Some(txns_weights) = txns_weights {
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("txns_weights".to_string(), txns_weights);
}
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("dr_weight".to_string(), dr_weight);
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("vt_weight".to_string(), vt_weight);
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("block_weight".to_string(), block_weight);
// Check if this block is confirmed by a majority of superblock votes
let chain_manager = ChainManager::from_registry();
let res = chain_manager
.send(IsConfirmedBlock {
block_hash,
block_epoch,
})
.await;
match res {
Ok(Ok(confirmed)) => {
// Append {"confirmed":true} to the result
value
.as_object_mut()
.expect("The result of getBlock should be an object")
.insert("confirmed".to_string(), Value::Bool(confirmed));
Ok(value)
}
Ok(Err(e)) => {
let err = internal_error(e);
Err(err)
}
Err(e) => {
let err = internal_error(e);
Err(err)
}