-
Notifications
You must be signed in to change notification settings - Fork 629
/
lib.rs
1446 lines (1358 loc) · 59.5 KB
/
lib.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
#![doc = include_str!("../README.md")]
use std::time::{Duration, Instant};
use actix::Addr;
use actix_cors::Cors;
use actix_web::{http, middleware, web, App, Error as HttpError, HttpResponse, HttpServer};
use futures::Future;
use futures::FutureExt;
use prometheus;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::time::{sleep, timeout};
use tracing::info;
use near_chain_configs::GenesisConfig;
use near_client::{
ClientActor, GetBlock, GetBlockProof, GetChunk, GetExecutionOutcome, GetGasPrice,
GetNetworkInfo, GetNextLightClientBlock, GetProtocolConfig, GetReceipt, GetStateChanges,
GetStateChangesInBlock, GetValidatorInfo, GetValidatorOrdered, Query, Status, TxStatus,
TxStatusError, ViewClientActor,
};
pub use near_jsonrpc_client as client;
use near_jsonrpc_primitives::errors::RpcError;
use near_jsonrpc_primitives::message::{Message, Request};
use near_jsonrpc_primitives::types::config::RpcProtocolConfigResponse;
use near_metrics::{Encoder, TextEncoder};
use near_network::types::{NetworkClientMessages, NetworkClientResponses};
use near_primitives::hash::CryptoHash;
use near_primitives::serialize::BaseEncode;
use near_primitives::transaction::SignedTransaction;
use near_primitives::types::AccountId;
use near_primitives::views::FinalExecutionOutcomeViewEnum;
mod metrics;
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct RpcPollingConfig {
pub polling_interval: Duration,
pub polling_timeout: Duration,
}
impl Default for RpcPollingConfig {
fn default() -> Self {
Self {
polling_interval: Duration::from_millis(500),
polling_timeout: Duration::from_secs(10),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RpcLimitsConfig {
/// Maximum byte size of the json payload.
pub json_payload_max_size: usize,
}
impl Default for RpcLimitsConfig {
fn default() -> Self {
Self { json_payload_max_size: 10 * 1024 * 1024 }
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RpcConfig {
pub addr: String,
// If provided, will start an http server exporting only Prometheus metrics on that address.
pub prometheus_addr: Option<String>,
pub cors_allowed_origins: Vec<String>,
pub polling_config: RpcPollingConfig,
#[serde(default)]
pub limits_config: RpcLimitsConfig,
}
impl Default for RpcConfig {
fn default() -> Self {
RpcConfig {
addr: "0.0.0.0:3030".to_owned(),
prometheus_addr: None,
cors_allowed_origins: vec!["*".to_owned()],
polling_config: Default::default(),
limits_config: Default::default(),
}
}
}
impl RpcConfig {
pub fn new(addr: &str) -> Self {
RpcConfig { addr: addr.to_owned(), ..Default::default() }
}
}
#[cfg(feature = "test_features")]
fn parse_params<T: serde::de::DeserializeOwned>(value: Option<Value>) -> Result<T, RpcError> {
if let Some(value) = value {
serde_json::from_value(value)
.map_err(|err| RpcError::invalid_params(format!("Failed parsing args: {}", err)))
} else {
Err(RpcError::invalid_params("Require at least one parameter".to_owned()))
}
}
#[cfg(feature = "test_features")]
fn jsonify<T: serde::Serialize>(
response: Result<Result<T, String>, actix::MailboxError>,
) -> Result<Value, RpcError> {
response
.map_err(|err| err.to_string())
.and_then(|value| {
value.and_then(|value| serde_json::to_value(value).map_err(|err| err.to_string()))
})
.map_err(|err| RpcError::server_error(Some(err)))
}
#[easy_ext::ext(FromNetworkClientResponses)]
impl near_jsonrpc_primitives::types::transactions::RpcTransactionError {
pub fn from_network_client_responses(responses: NetworkClientResponses) -> Self {
match responses {
NetworkClientResponses::InvalidTx(context) => Self::InvalidTransaction { context },
NetworkClientResponses::NoResponse => Self::TimeoutError,
NetworkClientResponses::DoesNotTrackShard | NetworkClientResponses::RequestRouted => {
Self::DoesNotTrackShard
}
internal_error => Self::InternalError { debug_info: format!("{:?}", internal_error) },
}
}
}
/// This function processes response from query method to introduce
/// backward compatible response in case of specific errors
fn process_query_response(
query_response: Result<
near_jsonrpc_primitives::types::query::RpcQueryResponse,
near_jsonrpc_primitives::types::query::RpcQueryError,
>,
) -> Result<Value, RpcError> {
// This match is used here to give backward compatible error message for specific
// error variants. Should be refactored once structured errors fully shipped
match query_response {
Ok(rpc_query_response) => serde_json::to_value(rpc_query_response)
.map_err(|err| RpcError::parse_error(err.to_string())),
Err(err) => match err {
near_jsonrpc_primitives::types::query::RpcQueryError::ContractExecutionError {
vm_error,
block_height,
block_hash,
} => Ok(json!({
"error": vm_error,
"logs": json!([]),
"block_height": block_height,
"block_hash": block_hash,
})),
near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccessKey {
public_key,
block_height,
block_hash,
} => Ok(json!({
"error": format!(
"access key {} does not exist while viewing",
public_key.to_string()
),
"logs": json!([]),
"block_height": block_height,
"block_hash": block_hash,
})),
near_jsonrpc_primitives::types::query::RpcQueryError::UnknownBlock {
ref block_reference,
} => match block_reference {
near_primitives::types::BlockReference::BlockId(block_id) => {
let error_data = Some(match block_id {
near_primitives::types::BlockId::Height(height) => json!(format!(
"DB Not Found Error: BLOCK HEIGHT: {} \n Cause: Unknown",
height
)),
near_primitives::types::BlockId::Hash(block_hash) => {
json!(format!("DB Not Found Error: BLOCK HEADER: {}", block_hash))
}
});
let error_data_value = match serde_json::to_value(err) {
Ok(value) => value,
Err(err) => {
return Err(RpcError::new_internal_error(
None,
format!("Failed to serialize RpcQueryError: {:?}", err),
))
}
};
Err(RpcError::new_internal_or_handler_error(error_data, error_data_value))
}
_ => Err(err.into()),
},
_ => Err(err.into()),
},
}
}
struct JsonRpcHandler {
client_addr: Addr<ClientActor>,
view_client_addr: Addr<ViewClientActor>,
polling_config: RpcPollingConfig,
genesis_config: GenesisConfig,
#[cfg(feature = "test_features")]
peer_manager_addr: Addr<near_network::PeerManagerActor>,
#[cfg(feature = "test_features")]
routing_table_addr: Addr<near_network::RoutingTableActor>,
}
impl JsonRpcHandler {
pub async fn process(&self, message: Message) -> Result<Message, HttpError> {
let id = message.id();
match message {
Message::Request(request) => {
Ok(Message::response(id, self.process_request(request).await))
}
_ => Ok(Message::error(RpcError::parse_error(
"JSON RPC Request format was expected".to_owned(),
))),
}
}
// `process_request` increments affected metrics but the request processing is done by
// `process_request_internal`.
async fn process_request(&self, request: Request) -> Result<Value, RpcError> {
let timer = Instant::now();
let request_method = request.method.clone();
let response = self.process_request_internal(request).await;
let request_method = if let Err(err) = &response {
if err.code == -32_601 {
"UNSUPPORTED_METHOD"
} else {
&request_method
}
} else {
&request_method
};
metrics::HTTP_RPC_REQUEST_COUNT.with_label_values(&[request_method]).inc();
metrics::RPC_PROCESSING_TIME
.with_label_values(&[request_method])
.observe(timer.elapsed().as_secs_f64());
if let Err(err) = &response {
metrics::RPC_ERROR_COUNT
.with_label_values(&[request_method, &err.code.to_string()])
.inc();
}
response
}
// Processes the request but doesn't update any metrics.
async fn process_request_internal(&self, request: Request) -> Result<Value, RpcError> {
#[cfg(feature = "test_features")]
{
let params = request.params.clone();
let res = match request.method.as_ref() {
// Adversarial controls
"adv_set_weight" => Some(self.adv_set_sync_info(params).await),
"adv_disable_header_sync" => Some(self.adv_disable_header_sync(params).await),
"adv_disable_doomslug" => Some(self.adv_disable_doomslug(params).await),
"adv_produce_blocks" => Some(self.adv_produce_blocks(params).await),
"adv_switch_to_height" => Some(self.adv_switch_to_height(params).await),
"adv_get_saved_blocks" => Some(self.adv_get_saved_blocks(params).await),
"adv_check_store" => Some(self.adv_check_store(params).await),
"adv_set_options" => {
let params = parse_params::<
near_jsonrpc_adversarial_primitives::SetAdvOptionsRequest,
>(params)?;
self.peer_manager_addr
.send(near_network::types::PeerManagerMessageRequest::SetAdvOptions(
near_network::test_utils::SetAdvOptions {
disable_edge_signature_verification: params
.disable_edge_signature_verification,
disable_edge_propagation: params.disable_edge_propagation,
disable_edge_pruning: params.disable_edge_pruning,
set_max_peers: None,
},
))
.await?;
Some(
serde_json::to_value(())
.map_err(|err| RpcError::serialization_error(err.to_string())),
)
}
#[cfg(feature = "protocol_feature_routing_exchange_algorithm")]
"adv_set_routing_table" => {
let request =
near_jsonrpc_adversarial_primitives::SetRoutingTableRequest::parse(params)?;
self.peer_manager_addr
.send(near_network::types::PeerManagerMessageRequest::SetRoutingTable(
near_network::test_utils::SetRoutingTable {
add_edges: request.add_edges,
remove_edges: request.remove_edges,
prune_edges: request.prune_edges,
},
))
.await?;
Some(
serde_json::to_value(())
.map_err(|err| RpcError::serialization_error(err.to_string())),
)
}
#[cfg(feature = "protocol_feature_routing_exchange_algorithm")]
"adv_start_routing_table_syncv2" => {
let params = parse_params::<
near_jsonrpc_adversarial_primitives::StartRoutingTableSyncRequest,
>(params)?;
self.peer_manager_addr
.send(
near_network::types::PeerManagerMessageRequest::StartRoutingTableSync(
near_network::private_actix::StartRoutingTableSync {
peer_id: params.peer_id,
},
),
)
.await?;
Some(
serde_json::to_value(())
.map_err(|err| RpcError::serialization_error(err.to_string())),
)
}
"adv_get_peer_id" => {
let response = self
.peer_manager_addr
.send(near_network::types::PeerManagerMessageRequest::GetPeerId(
near_network::private_actix::GetPeerId {},
))
.await?;
Some(
serde_json::to_value(response.as_peer_id_result())
.map_err(|err| RpcError::serialization_error(err.to_string())),
)
}
"adv_get_routing_table" => {
let result = self
.routing_table_addr
.send(near_network::RoutingTableMessages::RequestRoutingTable)
.await?;
match result {
near_network::RoutingTableMessagesResponse::RequestRoutingTableResponse {
edges_info: routing_table,
} => {
let response = {
near_network::routing::GetRoutingTableResult {
edges_info: routing_table
.iter()
.map(|x| x.to_simple_edge())
.collect(),
}
};
Some(
serde_json::to_value(response)
.map_err(|err| RpcError::serialization_error(err.to_string())),
)
}
_ => None,
}
}
_ => None,
};
if let Some(res) = res {
return res;
}
}
let response: Result<Value, RpcError> = match request.method.as_ref() {
// Handlers ordered alphabetically
"block" => {
let rpc_block_request =
near_jsonrpc_primitives::types::blocks::RpcBlockRequest::parse(request.params)?;
let block = self.block(rpc_block_request).await?;
serde_json::to_value(block)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"broadcast_tx_async" => {
let rpc_transaction_request =
near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest::parse(
request.params,
)?;
let transaction_hash = self.send_tx_async(rpc_transaction_request).await;
serde_json::to_value((&transaction_hash).to_base())
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"broadcast_tx_commit" => {
let rpc_transaction_request =
near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest::parse(
request.params,
)?;
let send_tx_response = self.send_tx_commit(rpc_transaction_request).await?;
serde_json::to_value(send_tx_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"chunk" => {
let rpc_chunk_request =
near_jsonrpc_primitives::types::chunks::RpcChunkRequest::parse(request.params)?;
let chunk = self.chunk(rpc_chunk_request).await?;
serde_json::to_value(chunk)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"gas_price" => {
let rpc_gas_price_request =
near_jsonrpc_primitives::types::gas_price::RpcGasPriceRequest::parse(
request.params,
)?;
let gas_price = self.gas_price(rpc_gas_price_request).await?;
serde_json::to_value(gas_price)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"health" => {
let health_response = self.health().await?;
serde_json::to_value(health_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"light_client_proof" => {
let rpc_light_client_execution_proof_request = near_jsonrpc_primitives::types::light_client::RpcLightClientExecutionProofRequest::parse(request.params)?;
let rpc_light_client_execution_proof_response = self
.light_client_execution_outcome_proof(rpc_light_client_execution_proof_request)
.await?;
serde_json::to_value(rpc_light_client_execution_proof_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"next_light_client_block" => {
let rpc_light_client_next_block_request = near_jsonrpc_primitives::types::light_client::RpcLightClientNextBlockRequest::parse(request.params)?;
let next_light_client_block =
self.next_light_client_block(rpc_light_client_next_block_request).await?;
serde_json::to_value(next_light_client_block)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"network_info" => {
let network_info_response = self.network_info().await?;
serde_json::to_value(network_info_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"query" => {
let rpc_query_request =
near_jsonrpc_primitives::types::query::RpcQueryRequest::parse(request.params)?;
let query_response = self.query(rpc_query_request).await;
process_query_response(query_response)
}
"status" => {
let status_response = self.status().await?;
serde_json::to_value(status_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"tx" => {
let rpc_transaction_status_common_request =
near_jsonrpc_primitives::types::transactions::RpcTransactionStatusCommonRequest::parse(request.params)?;
let rpc_transaction_response =
self.tx_status_common(rpc_transaction_status_common_request, false).await?;
serde_json::to_value(rpc_transaction_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"validators" => {
let rpc_validator_request =
near_jsonrpc_primitives::types::validator::RpcValidatorRequest::parse(
request.params,
)?;
let validator_info = self.validators(rpc_validator_request).await?;
serde_json::to_value(validator_info)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_broadcast_tx_sync" => {
let rpc_transaction_request =
near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest::parse(
request.params,
)?;
let broadcast_tx_sync_response = self.send_tx_sync(rpc_transaction_request).await?;
serde_json::to_value(broadcast_tx_sync_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_changes" => {
let rpc_state_changes_request =
near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockByTypeRequest::parse(
request.params,
)?;
let state_changes =
self.changes_in_block_by_type(rpc_state_changes_request).await?;
serde_json::to_value(state_changes)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_changes_in_block" => {
let rpc_state_changes_request =
near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockRequest::parse(
request.params,
)?;
let state_changes = self.changes_in_block(rpc_state_changes_request).await?;
serde_json::to_value(state_changes)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_check_tx" => {
let rpc_transaction_request =
near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest::parse(
request.params,
)?;
let broadcast_tx_sync_response = self.check_tx(rpc_transaction_request).await?;
serde_json::to_value(broadcast_tx_sync_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_genesis_config" => {
let genesis_config = self.genesis_config().await;
serde_json::to_value(genesis_config)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_light_client_proof" => {
let rpc_light_client_execution_proof_request = near_jsonrpc_primitives::types::light_client::RpcLightClientExecutionProofRequest::parse(request.params)?;
let rpc_light_client_execution_proof_response = self
.light_client_execution_outcome_proof(rpc_light_client_execution_proof_request)
.await?;
serde_json::to_value(rpc_light_client_execution_proof_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_protocol_config" => {
let rpc_protocol_config_request =
near_jsonrpc_primitives::types::config::RpcProtocolConfigRequest::parse(
request.params,
)?;
let config = self.protocol_config(rpc_protocol_config_request).await?;
serde_json::to_value(config)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_receipt" => {
let rpc_receipt_request =
near_jsonrpc_primitives::types::receipts::RpcReceiptRequest::parse(
request.params,
)?;
let receipt = self.receipt(rpc_receipt_request).await?;
serde_json::to_value(receipt)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_tx_status" => {
let rpc_transaction_status_common_request = near_jsonrpc_primitives::types::transactions::RpcTransactionStatusCommonRequest::parse(request.params)?;
let rpc_transaction_response =
self.tx_status_common(rpc_transaction_status_common_request, true).await?;
serde_json::to_value(rpc_transaction_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
"EXPERIMENTAL_validators_ordered" => {
let rpc_validators_ordered_request =
near_jsonrpc_primitives::types::validator::RpcValidatorsOrderedRequest::parse(
request.params,
)?;
let validators = self.validators_ordered(rpc_validators_ordered_request).await?;
serde_json::to_value(validators)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
#[cfg(feature = "sandbox")]
"sandbox_patch_state" => {
let sandbox_patch_state_request =
near_jsonrpc_primitives::types::sandbox::RpcSandboxPatchStateRequest::parse(
request.params,
)?;
let sandbox_patch_state_response =
self.sandbox_patch_state(sandbox_patch_state_request).await?;
serde_json::to_value(sandbox_patch_state_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
#[cfg(feature = "sandbox")]
"sandbox_fast_forward" => {
let sandbox_fast_forward_request =
near_jsonrpc_primitives::types::sandbox::RpcSandboxFastForwardRequest::parse(
request.params,
)?;
let sandbox_fast_forward_response =
self.sandbox_fast_forward(sandbox_fast_forward_request).await?;
serde_json::to_value(sandbox_fast_forward_response)
.map_err(|err| RpcError::serialization_error(err.to_string()))
}
_ => Err(RpcError::method_not_found(request.method.clone())),
};
response
}
async fn send_tx_async(
&self,
request_data: near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest,
) -> CryptoHash {
let tx = request_data.signed_transaction;
let hash = tx.get_hash().clone();
self.client_addr.do_send(NetworkClientMessages::Transaction {
transaction: tx,
is_forwarded: false,
check_only: false, // if we set true here it will not actually send the transaction
});
hash
}
async fn tx_exists(
&self,
tx_hash: CryptoHash,
signer_account_id: &AccountId,
) -> Result<bool, near_jsonrpc_primitives::types::transactions::RpcTransactionError> {
timeout(self.polling_config.polling_timeout, async {
loop {
// TODO(optimization): Introduce a view_client method to only get transaction
// status without the information about execution outcomes.
match self
.view_client_addr
.send(TxStatus {
tx_hash,
signer_account_id: signer_account_id.clone(),
fetch_receipt: false,
})
.await
{
Ok(Ok(Some(_))) => {
return Ok(true);
}
Ok(Err(TxStatusError::MissingTransaction(_))) => {
return Ok(false);
}
Err(err) => return Err(near_jsonrpc_primitives::types::transactions::RpcTransactionError::InternalError {
debug_info: format!("{:?}", err)
}),
_ => {}
}
sleep(self.polling_config.polling_interval).await;
}
})
.await
.map_err(|_| {
metrics::RPC_TIMEOUT_TOTAL.inc();
tracing::warn!(
target: "jsonrpc", "Timeout: tx_exists method. tx_hash {:?} signer_account_id {:?}",
tx_hash,
signer_account_id
);
near_jsonrpc_primitives::types::transactions::RpcTransactionError::TimeoutError
})?
}
async fn tx_status_fetch(
&self,
tx_info: near_jsonrpc_primitives::types::transactions::TransactionInfo,
fetch_receipt: bool,
) -> Result<FinalExecutionOutcomeViewEnum, TxStatusError> {
let (tx_hash, account_id) = match &tx_info {
near_jsonrpc_primitives::types::transactions::TransactionInfo::Transaction(tx) => {
(tx.get_hash(), tx.transaction.signer_id.clone())
}
near_jsonrpc_primitives::types::transactions::TransactionInfo::TransactionId {
hash,
account_id,
} => (*hash, account_id.clone()),
};
timeout(self.polling_config.polling_timeout, async {
loop {
let tx_status_result = self
.view_client_addr
.send(TxStatus {
tx_hash,
signer_account_id: account_id.clone(),
fetch_receipt,
})
.await;
match tx_status_result {
Ok(Ok(Some(outcome))) => break Ok(outcome),
Ok(Ok(None)) => {} // No such transaction recorded on chain yet
Ok(Err(err @ TxStatusError::MissingTransaction(_))) => {
if let near_jsonrpc_primitives::types::transactions::TransactionInfo::Transaction(tx) = &tx_info {
if let Ok(NetworkClientResponses::InvalidTx(e)) =
self.send_tx(tx.clone(), true).await
{
break Err(TxStatusError::InvalidTx(e));
}
}
break Err(err);
}
Ok(Err(err)) => break Err(err),
Err(err) => break Err(TxStatusError::InternalError(err.to_string())),
}
let _ = sleep(self.polling_config.polling_interval).await;
}
})
.await
.map_err(|_| {
metrics::RPC_TIMEOUT_TOTAL.inc();
tracing::warn!(
target: "jsonrpc", "Timeout: tx_status_fetch method. tx_info {:?} fetch_receipt {:?}",
tx_info,
fetch_receipt,
);
TxStatusError::TimeoutError
})?
}
async fn tx_polling(
&self,
tx_info: near_jsonrpc_primitives::types::transactions::TransactionInfo,
) -> Result<
near_jsonrpc_primitives::types::transactions::RpcTransactionResponse,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
timeout(self.polling_config.polling_timeout, async {
loop {
match self.tx_status_fetch(tx_info.clone(), false).await {
Ok(tx_status) => {
break Ok(
near_jsonrpc_primitives::types::transactions::RpcTransactionResponse {
final_execution_outcome: tx_status,
},
)
}
// If transaction is missing, keep polling.
Err(TxStatusError::MissingTransaction(_)) => {}
// If we hit any other error, we return to the user.
Err(err) => {
break Err(err.into());
}
}
let _ = sleep(self.polling_config.polling_interval).await;
}
})
.await
.map_err(|_| {
metrics::RPC_TIMEOUT_TOTAL.inc();
tracing::warn!(
target: "jsonrpc", "Timeout: tx_polling method. tx_info {:?}",
tx_info,
);
near_jsonrpc_primitives::types::transactions::RpcTransactionError::TimeoutError
})?
}
/// Send a transaction idempotently (subsequent send of the same transaction will not cause
/// any new side-effects and the result will be the same unless we garbage collected it
/// already).
async fn send_tx(
&self,
tx: SignedTransaction,
check_only: bool,
) -> Result<
NetworkClientResponses,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
let tx_hash = tx.get_hash();
let signer_account_id = tx.transaction.signer_id.clone();
let response = self
.client_addr
.send(NetworkClientMessages::Transaction {
transaction: tx,
is_forwarded: false,
check_only,
})
.await?;
// If we receive InvalidNonce error, it might be the case that the transaction was
// resubmitted, and we should check if that is the case and return ValidTx response to
// maintain idempotence of the send_tx method.
if let NetworkClientResponses::InvalidTx(
near_primitives::errors::InvalidTxError::InvalidNonce { .. },
) = response
{
if self.tx_exists(tx_hash, &signer_account_id).await? {
return Ok(NetworkClientResponses::ValidTx);
}
}
Ok(response)
}
async fn send_tx_sync(
&self,
request_data: near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest,
) -> Result<
near_jsonrpc_primitives::types::transactions::RpcBroadcastTxSyncResponse,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
match self.send_tx(request_data.clone().signed_transaction, false).await? {
NetworkClientResponses::ValidTx => {
Ok(near_jsonrpc_primitives::types::transactions::RpcBroadcastTxSyncResponse {
transaction_hash: request_data.signed_transaction.get_hash(),
})
}
NetworkClientResponses::RequestRouted => {
Err(near_jsonrpc_primitives::types::transactions::RpcTransactionError::RequestRouted {
transaction_hash: request_data.signed_transaction.get_hash(),
})
}
network_client_responses=> Err(
near_jsonrpc_primitives::types::transactions::RpcTransactionError::from_network_client_responses(
network_client_responses
)
)
}
}
async fn check_tx(
&self,
request_data: near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest,
) -> Result<
near_jsonrpc_primitives::types::transactions::RpcBroadcastTxSyncResponse,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
match self.send_tx(request_data.clone().signed_transaction, true).await? {
NetworkClientResponses::ValidTx => {
Ok(near_jsonrpc_primitives::types::transactions::RpcBroadcastTxSyncResponse {
transaction_hash: request_data.signed_transaction.get_hash(),
})
}
NetworkClientResponses::RequestRouted => {
Err(near_jsonrpc_primitives::types::transactions::RpcTransactionError::RequestRouted {
transaction_hash: request_data.signed_transaction.get_hash(),
})
}
network_client_responses => Err(
near_jsonrpc_primitives::types::transactions::RpcTransactionError::from_network_client_responses(network_client_responses)
)
}
}
async fn send_tx_commit(
&self,
request_data: near_jsonrpc_primitives::types::transactions::RpcBroadcastTransactionRequest,
) -> Result<
near_jsonrpc_primitives::types::transactions::RpcTransactionResponse,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
let tx = request_data.signed_transaction;
match self
.tx_status_fetch(
near_jsonrpc_primitives::types::transactions::TransactionInfo::Transaction(
tx.clone(),
),
false,
)
.await
{
Ok(outcome) => {
return Ok(near_jsonrpc_primitives::types::transactions::RpcTransactionResponse {
final_execution_outcome: outcome,
});
}
Err(TxStatusError::InvalidTx(invalid_tx_error)) => {
return Err(near_jsonrpc_primitives::types::transactions::RpcTransactionError::InvalidTransaction {
context: invalid_tx_error
});
}
_ => {}
}
match self.send_tx(tx.clone(), false).await? {
NetworkClientResponses::ValidTx | NetworkClientResponses::RequestRouted => {
self.tx_polling(near_jsonrpc_primitives::types::transactions::TransactionInfo::Transaction(tx)).await
}
network_client_response=> {
Err(
near_jsonrpc_primitives::types::transactions::RpcTransactionError::from_network_client_responses(
network_client_response
)
)
}
}
}
async fn health(
&self,
) -> Result<
near_jsonrpc_primitives::types::status::RpcHealthResponse,
near_jsonrpc_primitives::types::status::RpcStatusError,
> {
Ok(self.client_addr.send(Status { is_health_check: true }).await??.into())
}
pub async fn status(
&self,
) -> Result<
near_jsonrpc_primitives::types::status::RpcStatusResponse,
near_jsonrpc_primitives::types::status::RpcStatusError,
> {
Ok(self.client_addr.send(Status { is_health_check: false }).await??.into())
}
/// Expose Genesis Config (with internal Runtime Config) without state records to keep the
/// output at a reasonable size.
///
/// See also `genesis_records` API.
pub async fn genesis_config(&self) -> &GenesisConfig {
&self.genesis_config
}
pub async fn protocol_config(
&self,
request_data: near_jsonrpc_primitives::types::config::RpcProtocolConfigRequest,
) -> Result<
near_jsonrpc_primitives::types::config::RpcProtocolConfigResponse,
near_jsonrpc_primitives::types::config::RpcProtocolConfigError,
> {
let config_view = self
.view_client_addr
.send(GetProtocolConfig(request_data.block_reference.into()))
.await??;
Ok(RpcProtocolConfigResponse { config_view })
}
async fn query(
&self,
request_data: near_jsonrpc_primitives::types::query::RpcQueryRequest,
) -> Result<
near_jsonrpc_primitives::types::query::RpcQueryResponse,
near_jsonrpc_primitives::types::query::RpcQueryError,
> {
let query = Query::new(request_data.block_reference, request_data.request);
Ok(self.view_client_addr.send(query).await??.into())
}
async fn tx_status_common(
&self,
request_data: near_jsonrpc_primitives::types::transactions::RpcTransactionStatusCommonRequest,
fetch_receipt: bool,
) -> Result<
near_jsonrpc_primitives::types::transactions::RpcTransactionResponse,
near_jsonrpc_primitives::types::transactions::RpcTransactionError,
> {
Ok(self.tx_status_fetch(request_data.transaction_info, fetch_receipt).await?.into())
}
async fn block(
&self,
request_data: near_jsonrpc_primitives::types::blocks::RpcBlockRequest,
) -> Result<
near_jsonrpc_primitives::types::blocks::RpcBlockResponse,
near_jsonrpc_primitives::types::blocks::RpcBlockError,
> {
let block_view =
self.view_client_addr.send(GetBlock(request_data.block_reference.into())).await??;
Ok(near_jsonrpc_primitives::types::blocks::RpcBlockResponse { block_view })
}
async fn chunk(
&self,
request_data: near_jsonrpc_primitives::types::chunks::RpcChunkRequest,
) -> Result<
near_jsonrpc_primitives::types::chunks::RpcChunkResponse,
near_jsonrpc_primitives::types::chunks::RpcChunkError,
> {
let chunk_view =
self.view_client_addr.send(GetChunk::from(request_data.chunk_reference)).await??;
Ok(near_jsonrpc_primitives::types::chunks::RpcChunkResponse { chunk_view })
}
async fn receipt(
&self,
request_data: near_jsonrpc_primitives::types::receipts::RpcReceiptRequest,
) -> Result<
near_jsonrpc_primitives::types::receipts::RpcReceiptResponse,
near_jsonrpc_primitives::types::receipts::RpcReceiptError,
> {
match self
.view_client_addr
.send(GetReceipt { receipt_id: request_data.receipt_reference.receipt_id })
.await??
{
Some(receipt_view) => {
Ok(near_jsonrpc_primitives::types::receipts::RpcReceiptResponse { receipt_view })
}
None => {
Err(near_jsonrpc_primitives::types::receipts::RpcReceiptError::UnknownReceipt {
receipt_id: request_data.receipt_reference.receipt_id,
})
}
}
}
async fn changes_in_block(
&self,
request: near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockRequest,
) -> Result<
near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockByTypeResponse,
near_jsonrpc_primitives::types::changes::RpcStateChangesError,
> {
let block = self.view_client_addr.send(GetBlock(request.block_reference.into())).await??;
let block_hash = block.header.hash.clone();
let changes = self.view_client_addr.send(GetStateChangesInBlock { block_hash }).await??;
Ok(near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockByTypeResponse {
block_hash: block.header.hash,
changes,
})
}
async fn changes_in_block_by_type(
&self,
request: near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockByTypeRequest,
) -> Result<
near_jsonrpc_primitives::types::changes::RpcStateChangesInBlockResponse,
near_jsonrpc_primitives::types::changes::RpcStateChangesError,
> {
let block = self.view_client_addr.send(GetBlock(request.block_reference.into())).await??;
let block_hash = block.header.hash.clone();
let changes = self
.view_client_addr
.send(GetStateChanges {