-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathchain_head.rs
1496 lines (1396 loc) · 66.9 KB
/
chain_head.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
// Smoldot
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! All JSON-RPC method handlers that related to the `chainHead` API.
use super::{Background, FollowSubscription, SubscriptionTy};
use crate::{platform::Platform, runtime_service, sync_service};
use alloc::{borrow::ToOwned as _, boxed::Box, format, string::ToString as _, sync::Arc, vec::Vec};
use core::{
cmp, iter,
num::{NonZeroU32, NonZeroUsize},
sync::atomic,
time::Duration,
};
use futures::prelude::*;
use hashbrown::HashMap;
use smoldot::{
chain::fork_tree,
executor::{self, runtime_host},
header,
json_rpc::{self, methods, requests_subscriptions},
network::protocol,
};
impl<TPlat: Platform> Background<TPlat> {
/// Handles a call to [`methods::MethodCall::chainHead_unstable_call`].
pub(super) async fn chain_head_call(
self: &Arc<Self>,
request_id: &str,
state_machine_request_id: &requests_subscriptions::RequestId,
follow_subscription: &str,
hash: methods::HashHexString,
function_to_call: &str,
call_parameters: methods::HexString,
network_config: Option<methods::NetworkConfig>,
) {
let network_config = network_config.unwrap_or(methods::NetworkConfig {
max_parallel: 1,
timeout_ms: 8000,
total_attempts: 3,
});
let task = {
let me = self.clone();
let request_id = request_id.to_owned();
let function_to_call = function_to_call.to_owned();
let state_machine_request_id = state_machine_request_id.clone();
let follow_subscription = follow_subscription.to_owned();
async move {
// Determine whether the requested block hash is valid and start the call.
let pre_runtime_call = {
let lock = me.subscriptions.lock().await;
if let Some(subscription) = lock.chain_head_follow.get(&follow_subscription) {
let runtime_service_subscribe_all = match subscription.runtime_subscribe_all
{
Some(sa) => sa,
None => {
me.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
&request_id,
json_rpc::parse::ErrorResponse::InvalidParams,
None,
),
)
.await;
return;
}
};
if !subscription.pinned_blocks_headers.contains_key(&hash.0) {
me.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
&request_id,
json_rpc::parse::ErrorResponse::InvalidParams,
None,
),
)
.await;
return;
}
me.runtime_service
.pinned_block_runtime_lock(runtime_service_subscribe_all, &hash.0)
.await
.ok()
} else {
None
}
};
let state_machine_subscription = match me
.requests_subscriptions
.start_subscription(&state_machine_request_id, 1)
.await
{
Ok(v) => v,
Err(requests_subscriptions::StartSubscriptionError::LimitReached) => {
me.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
&request_id,
json_rpc::parse::ErrorResponse::ServerError(
-32000,
"Too many active subscriptions",
),
None,
),
)
.await;
return;
}
};
let subscription_id = me
.next_subscription_id
.fetch_add(1, atomic::Ordering::Relaxed)
.to_string();
// TODO: make use of this
let _abort_registration = {
let (abort_handle, abort_registration) = future::AbortHandle::new_pair();
let mut subscriptions_list = me.subscriptions.lock().await;
subscriptions_list.misc.insert(
(subscription_id.clone(), SubscriptionTy::ChainHeadCall),
(abort_handle, state_machine_subscription.clone()),
);
abort_registration
};
me.requests_subscriptions
.respond(
&state_machine_request_id,
methods::Response::chainHead_unstable_call((&subscription_id).into())
.to_json_response(&request_id),
)
.await;
let pre_runtime_call = if let Some(pre_runtime_call) = &pre_runtime_call {
Some(
pre_runtime_call
.start(
&function_to_call,
iter::once(&call_parameters.0),
cmp::min(10, network_config.total_attempts),
Duration::from_millis(u64::from(cmp::min(
20000,
network_config.timeout_ms,
))),
NonZeroU32::new(network_config.max_parallel.clamp(1, 5)).unwrap(),
)
.await,
)
} else {
None
};
let final_notif = match pre_runtime_call {
Some(Ok((runtime_call_lock, virtual_machine))) => {
match runtime_host::run(runtime_host::Config {
virtual_machine,
function_to_call: &function_to_call,
parameter: iter::once(&call_parameters.0),
top_trie_root_calculation_cache: None,
offchain_storage_changes: Default::default(),
storage_top_trie_changes: Default::default(),
}) {
Err((error, prototype)) => {
runtime_call_lock.unlock(prototype);
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: error.to_string().into(),
},
}
.to_json_call_object_parameters(None)
}
Ok(mut runtime_call) => {
loop {
match runtime_call {
runtime_host::RuntimeHostVm::Finished(Ok(success)) => {
let output =
success.virtual_machine.value().as_ref().to_owned();
runtime_call_lock
.unlock(success.virtual_machine.into_prototype());
break methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Done {
output: methods::HexString(output),
},
}
.to_json_call_object_parameters(None);
}
runtime_host::RuntimeHostVm::Finished(Err(error)) => {
runtime_call_lock.unlock(error.prototype);
break methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: error.detail.to_string().into(),
},
}
.to_json_call_object_parameters(None);
}
runtime_host::RuntimeHostVm::StorageGet(get) => {
// TODO: what if the remote lied to us?
let storage_value =
runtime_call_lock.storage_entry(get.key().as_ref());
let storage_value = match storage_value {
Ok(v) => v,
Err(error) => {
runtime_call_lock.unlock(
runtime_host::RuntimeHostVm::StorageGet(
get,
)
.into_prototype(),
);
break methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Inaccessible {
error: error.to_string().into(),
},
}
.to_json_call_object_parameters(None);
}
};
runtime_call =
get.inject_value(storage_value.map(iter::once));
}
runtime_host::RuntimeHostVm::NextKey(nk) => {
// TODO: implement somehow
runtime_call_lock.unlock(
runtime_host::RuntimeHostVm::NextKey(nk)
.into_prototype(),
);
break methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Inaccessible {
error: "getting next key not implemented".into(),
},
}
.to_json_call_object_parameters(None);
}
runtime_host::RuntimeHostVm::PrefixKeys(nk) => {
// TODO: implement somehow
runtime_call_lock.unlock(
runtime_host::RuntimeHostVm::PrefixKeys(nk)
.into_prototype(),
);
break methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Inaccessible {
error: "getting prefix keys not implemented".into(),
},
}
.to_json_call_object_parameters(None);
}
runtime_host::RuntimeHostVm::SignatureVerification(sig) => {
runtime_call = sig.verify_and_resume();
}
}
}
}
}
}
Some(Err(runtime_service::RuntimeCallError::InvalidRuntime(error))) => {
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: error.to_string().into(),
},
}
.to_json_call_object_parameters(None)
}
Some(Err(runtime_service::RuntimeCallError::StorageRetrieval(error))) => {
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: error.to_string().into(),
},
}
.to_json_call_object_parameters(None)
}
Some(Err(runtime_service::RuntimeCallError::MissingProofEntry)) => {
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: "incomplete call proof".into(),
},
}
.to_json_call_object_parameters(None)
}
Some(Err(runtime_service::RuntimeCallError::CallProof(error))) => {
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: error.to_string().into(),
},
}
.to_json_call_object_parameters(None)
}
Some(Err(runtime_service::RuntimeCallError::StorageQuery(error))) => {
methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Error {
error: format!("failed to fetch call proof: {}", error).into(),
},
}
.to_json_call_object_parameters(None)
}
None => methods::ServerToClient::chainHead_unstable_callEvent {
subscription: (&subscription_id).into(),
result: methods::ChainHeadCallEvent::Disjoint {},
}
.to_json_call_object_parameters(None),
};
me.requests_subscriptions
.push_notification(&state_machine_subscription, final_notif)
.await;
me.requests_subscriptions
.stop_subscription(&state_machine_subscription)
.await;
let _ = me
.subscriptions
.lock()
.await
.misc
.remove(&(subscription_id.to_owned(), SubscriptionTy::ChainHeadCall));
}
};
self.new_child_tasks_tx
.lock()
.await
.unbounded_send(task.boxed())
.unwrap();
}
/// Handles a call to [`methods::MethodCall::chainHead_unstable_follow`].
pub(super) async fn chain_head_follow(
self: &Arc<Self>,
request_id: &str,
state_machine_request_id: &requests_subscriptions::RequestId,
runtime_updates: bool,
) {
let state_machine_subscription = match self
.requests_subscriptions
.start_subscription(state_machine_request_id, 16)
.await
{
Ok(v) => v,
Err(requests_subscriptions::StartSubscriptionError::LimitReached) => {
self.requests_subscriptions
.respond(
state_machine_request_id,
json_rpc::parse::build_error_response(
request_id,
json_rpc::parse::ErrorResponse::ServerError(
-32000,
"Too many active subscriptions",
),
None,
),
)
.await;
return;
}
};
let (mut subscribe_all, runtime_subscribe_all) = if runtime_updates {
let subscribe_all = self
.runtime_service
.subscribe_all("chainHead_follow", 32, NonZeroUsize::new(32).unwrap())
.await;
let id = subscribe_all.new_blocks.id();
(either::Left(subscribe_all), Some(id))
} else {
(
either::Right(self.sync_service.subscribe_all(32, false).await),
None,
)
};
let (subscription_id, initial_notifications, abort_registration) = {
let subscription_id = self
.next_subscription_id
.fetch_add(1, atomic::Ordering::Relaxed)
.to_string();
self.requests_subscriptions
.respond(
&state_machine_request_id,
methods::Response::chainHead_unstable_follow((&subscription_id).into())
.to_json_response(request_id),
)
.await;
let mut initial_notifications = Vec::with_capacity(match &subscribe_all {
either::Left(sa) => 1 + sa.non_finalized_blocks_ancestry_order.len(),
either::Right(sa) => 1 + sa.non_finalized_blocks_ancestry_order.len(),
});
let mut pinned_blocks_headers =
HashMap::with_capacity_and_hasher(0, Default::default());
let mut non_finalized_blocks = fork_tree::ForkTree::new();
match &subscribe_all {
either::Left(subscribe_all) => {
let finalized_block_hash = header::hash_from_scale_encoded_header(
&subscribe_all.finalized_block_scale_encoded_header[..],
);
pinned_blocks_headers.insert(
finalized_block_hash,
subscribe_all.finalized_block_scale_encoded_header.clone(),
);
initial_notifications.push({
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::Initialized {
finalized_block_hash: methods::HashHexString(finalized_block_hash),
finalized_block_runtime: Some(convert_runtime_spec(
&subscribe_all.finalized_block_runtime,
)),
},
}
.to_json_call_object_parameters(None)
});
for block in &subscribe_all.non_finalized_blocks_ancestry_order {
let hash =
header::hash_from_scale_encoded_header(&block.scale_encoded_header);
let _was_in =
pinned_blocks_headers.insert(hash, block.scale_encoded_header.clone());
debug_assert!(_was_in.is_none());
let parent_node_index = if block.parent_hash == finalized_block_hash {
None
} else {
// TODO: O(n)
Some(
non_finalized_blocks
.find(|b| *b == block.parent_hash)
.unwrap(),
)
};
non_finalized_blocks.insert(parent_node_index, hash);
initial_notifications.push(
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::NewBlock {
block_hash: methods::HashHexString(hash),
new_runtime: if let Some(new_runtime) = &block.new_runtime {
Some(convert_runtime_spec(new_runtime))
} else {
None
},
parent_block_hash: methods::HashHexString(block.parent_hash),
},
}
.to_json_call_object_parameters(None),
);
if block.is_new_best {
initial_notifications.push(
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(hash),
},
}
.to_json_call_object_parameters(None),
);
}
}
}
either::Right(subscribe_all) => {
let finalized_block_hash = header::hash_from_scale_encoded_header(
&subscribe_all.finalized_block_scale_encoded_header[..],
);
pinned_blocks_headers.insert(
finalized_block_hash,
subscribe_all.finalized_block_scale_encoded_header.clone(),
);
initial_notifications.push(
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::Initialized {
finalized_block_hash: methods::HashHexString(finalized_block_hash),
finalized_block_runtime: None,
},
}
.to_json_call_object_parameters(None),
);
for block in &subscribe_all.non_finalized_blocks_ancestry_order {
let hash =
header::hash_from_scale_encoded_header(&block.scale_encoded_header);
let _was_in =
pinned_blocks_headers.insert(hash, block.scale_encoded_header.clone());
debug_assert!(_was_in.is_none());
let parent_node_index = if block.parent_hash == finalized_block_hash {
None
} else {
// TODO: O(n)
Some(
non_finalized_blocks
.find(|b| *b == block.parent_hash)
.unwrap(),
)
};
non_finalized_blocks.insert(parent_node_index, hash);
initial_notifications.push(
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::NewBlock {
block_hash: methods::HashHexString(hash),
new_runtime: None,
parent_block_hash: methods::HashHexString(block.parent_hash),
},
}
.to_json_call_object_parameters(None),
);
if block.is_new_best {
initial_notifications.push(
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(hash),
},
}
.to_json_call_object_parameters(None),
);
}
}
}
}
let (abort_handle, abort_registration) = future::AbortHandle::new_pair();
let mut lock = self.subscriptions.lock().await;
lock.chain_head_follow.insert(
subscription_id.clone(),
FollowSubscription {
non_finalized_blocks,
pinned_blocks_headers,
runtime_subscribe_all,
abort_handle: abort_handle,
},
);
(subscription_id, initial_notifications, abort_registration)
};
// Spawn a separate task for the subscription.
let task = {
let me = self.clone();
async move {
// Send back to the user the initial notifications.
for notif in initial_notifications {
me.requests_subscriptions
.push_notification(&state_machine_subscription, notif)
.await;
}
loop {
let next_block = match &mut subscribe_all {
either::Left(subscribe_all) => {
future::Either::Left(subscribe_all.new_blocks.next().map(either::Left))
}
either::Right(subscribe_all) => future::Either::Right(
subscribe_all.new_blocks.next().map(either::Right),
),
};
futures::pin_mut!(next_block);
// TODO: doesn't enforce any maximum number of pinned blocks
match next_block.await {
either::Left(None) | either::Right(None) => {
// TODO: clear queue of notifications?
break;
}
either::Left(Some(runtime_service::Notification::Finalized {
best_block_hash,
hash,
..
}))
| either::Right(Some(sync_service::Notification::Finalized {
best_block_hash,
hash,
})) => {
let mut finalized_blocks_hashes = Vec::new();
let mut pruned_blocks_hashes = Vec::new();
let mut subscriptions = me.subscriptions.lock().await;
if let Some(sub) =
subscriptions.chain_head_follow.get_mut(&subscription_id)
{
let node_index =
sub.non_finalized_blocks.find(|b| *b == hash).unwrap();
for pruned in sub.non_finalized_blocks.prune_ancestors(node_index) {
if pruned.is_prune_target_ancestor {
finalized_blocks_hashes
.push(methods::HashHexString(pruned.user_data));
} else {
pruned_blocks_hashes
.push(methods::HashHexString(pruned.user_data));
}
}
}
// TODO: don't always generate
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(
best_block_hash,
),
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::Finalized {
finalized_blocks_hashes,
pruned_blocks_hashes,
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
}
either::Left(Some(runtime_service::Notification::BestBlockChanged {
hash,
}))
| either::Right(Some(sync_service::Notification::BestBlockChanged {
hash,
})) => {
let _ = me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(hash),
},
}
.to_json_call_object_parameters(None),
)
.await;
}
either::Left(Some(runtime_service::Notification::Block(block))) => {
let hash =
header::hash_from_scale_encoded_header(&block.scale_encoded_header);
let mut subscriptions = me.subscriptions.lock().await;
if let Some(sub) =
subscriptions.chain_head_follow.get_mut(&subscription_id)
{
let _was_in = sub
.pinned_blocks_headers
.insert(hash, block.scale_encoded_header);
debug_assert!(_was_in.is_none());
// TODO: check if it matches current finalized block
// TODO: O(n)
let parent_node_index =
sub.non_finalized_blocks.find(|b| *b == block.parent_hash);
sub.non_finalized_blocks.insert(parent_node_index, hash);
}
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::NewBlock {
block_hash: methods::HashHexString(hash),
parent_block_hash: methods::HashHexString(
block.parent_hash,
),
new_runtime: if let Some(new_runtime) =
&block.new_runtime
{
Some(convert_runtime_spec(new_runtime))
} else {
None
},
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
if block.is_new_best {
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(hash),
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
}
}
either::Right(Some(sync_service::Notification::Block(block))) => {
let hash =
header::hash_from_scale_encoded_header(&block.scale_encoded_header);
let mut subscriptions = me.subscriptions.lock().await;
if let Some(sub) =
subscriptions.chain_head_follow.get_mut(&subscription_id)
{
let _was_in = sub
.pinned_blocks_headers
.insert(hash, block.scale_encoded_header);
debug_assert!(_was_in.is_none());
// TODO: check if it matches current finalized block
// TODO: O(n)
let parent_node_index =
sub.non_finalized_blocks.find(|b| *b == block.parent_hash);
sub.non_finalized_blocks.insert(parent_node_index, hash);
}
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::NewBlock {
block_hash: methods::HashHexString(hash),
parent_block_hash: methods::HashHexString(
block.parent_hash,
),
new_runtime: None, // TODO:
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
if block.is_new_best {
if me
.requests_subscriptions
.try_push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::BestBlockChanged {
best_block_hash: methods::HashHexString(hash),
},
}
.to_json_call_object_parameters(None),
)
.await
.is_err()
{
break;
}
}
}
}
}
let _ = me
.subscriptions
.lock()
.await
.chain_head_follow
.remove(&subscription_id);
me.requests_subscriptions
.push_notification(
&state_machine_subscription,
methods::ServerToClient::chainHead_unstable_followEvent {
subscription: (&subscription_id).into(),
result: methods::FollowEvent::Stop {},
}
.to_json_call_object_parameters(None),
)
.await;
me.requests_subscriptions
.stop_subscription(&state_machine_subscription)
.await;
}
};
self.new_child_tasks_tx
.lock()
.await
.unbounded_send(Box::pin(
future::Abortable::new(task, abort_registration).map(|_| ()),
))
.unwrap();
}
/// Handles a call to [`methods::MethodCall::chainHead_unstable_storage`].
pub(super) async fn chain_head_storage(
self: &Arc<Self>,
request_id: &str,
state_machine_request_id: &requests_subscriptions::RequestId,
follow_subscription: &str,
hash: methods::HashHexString,
key: methods::HexString,
child_key: Option<methods::HexString>,
network_config: Option<methods::NetworkConfig>,
) {
let network_config = network_config.unwrap_or(methods::NetworkConfig {
max_parallel: 1,
timeout_ms: 8000,
total_attempts: 3,
});
if child_key.is_some() {
self.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
request_id,
json_rpc::parse::ErrorResponse::ServerError(
-32000,
"Child key storage queries not supported yet",
),
None,
),
)
.await;
log::warn!(
target: &self.log_target,
"chainHead_unstable_storage with a non-null childKey has been called. \
This isn't supported by smoldot yet."
);
return;
}
// Obtain the header of the requested block.
// Contains `None` if the subscription is disjoint.
let block_scale_encoded_header = {
let lock = self.subscriptions.lock().await;
if let Some(subscription) = lock.chain_head_follow.get(follow_subscription) {
if let Some(header) = subscription.pinned_blocks_headers.get(&hash.0) {
Some(header.clone())
} else {
self.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
request_id,
json_rpc::parse::ErrorResponse::InvalidParams,
None,
),
)
.await;
return;
}
} else {
None
}
};
let state_machine_subscription = match self
.requests_subscriptions
.start_subscription(&state_machine_request_id, 1)
.await
{
Ok(v) => v,
Err(requests_subscriptions::StartSubscriptionError::LimitReached) => {
self.requests_subscriptions
.respond(
&state_machine_request_id,
json_rpc::parse::build_error_response(
request_id,
json_rpc::parse::ErrorResponse::ServerError(
-32000,
"Too many active subscriptions",
),
None,
),
)
.await;
return;
}
};
let subscription_id = self
.next_subscription_id
.fetch_add(1, atomic::Ordering::Relaxed)
.to_string();
let abort_registration = {
let (abort_handle, abort_registration) = future::AbortHandle::new_pair();
let mut subscriptions_list = self.subscriptions.lock().await;
subscriptions_list.misc.insert(
(subscription_id.clone(), SubscriptionTy::ChainHeadStorage),
(abort_handle, state_machine_subscription.clone()),
);
abort_registration
};
self.requests_subscriptions
.respond(
&state_machine_request_id,
methods::Response::chainHead_unstable_storage((&subscription_id).into())
.to_json_response(request_id),
)
.await;
let task = {
let me = self.clone();
async move {
let response = match block_scale_encoded_header
.as_ref()
.map(|h| header::decode(&h, me.sync_service.block_number_bytes()))
{
Some(Ok(decoded_header)) => {
let response = me
.sync_service
.clone()
.storage_query(
decoded_header.number,
&hash.0,
&decoded_header.state_root,
iter::once(&key.0),
cmp::min(10, network_config.total_attempts),
Duration::from_millis(u64::from(cmp::min(
20000,
network_config.timeout_ms,
))),
NonZeroU32::new(network_config.max_parallel.clamp(1, 5)).unwrap(),
)