forked from linera-io/linera-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
4284 lines (3996 loc) · 163 KB
/
mod.rs
File metadata and controls
4284 lines (3996 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Facebook, Inc. and its affiliates.
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::{
collections::{hash_map, BTreeMap, BTreeSet, HashMap, HashSet},
convert::Infallible,
iter,
sync::{Arc, RwLock},
};
use chain_client_state::ChainClientState;
use custom_debug_derive::Debug;
use futures::{
future::{self, Either, FusedFuture, Future},
stream::{self, AbortHandle, FusedStream, FuturesUnordered, StreamExt, TryStreamExt},
};
#[cfg(with_metrics)]
use linera_base::prometheus_util::MeasureLatency as _;
use linera_base::{
abi::Abi,
crypto::{signer, AccountPublicKey, CryptoHash, Signer, ValidatorPublicKey},
data_types::{
Amount, ApplicationPermissions, ArithmeticError, Blob, BlobContent, BlockHeight,
ChainDescription, Epoch, Round, Timestamp,
},
ensure,
identifiers::{
Account, AccountOwner, ApplicationId, BlobId, BlobType, ChainId, EventId, IndexAndEvent,
ModuleId, StreamId,
},
ownership::{ChainOwnership, TimeoutConfig},
time::{Duration, Instant},
};
#[cfg(not(target_arch = "wasm32"))]
use linera_base::{data_types::Bytecode, vm::VmRuntime};
use linera_chain::{
data_types::{
BlockProposal, ChainAndHeight, IncomingBundle, LiteVote, MessageAction, ProposedBlock,
Transaction,
},
manager::LockingBlock,
types::{
Block, CertificateValue, ConfirmedBlock, ConfirmedBlockCertificate, GenericCertificate,
LiteCertificate, Timeout, TimeoutCertificate, ValidatedBlock, ValidatedBlockCertificate,
},
ChainError, ChainExecutionContext, ChainStateView,
};
use linera_execution::{
committee::Committee,
system::{
AdminOperation, OpenChainConfig, SystemOperation, EPOCH_STREAM_NAME,
REMOVED_EPOCH_STREAM_NAME,
},
ExecutionError, Operation, Query, QueryOutcome, QueryResponse, SystemQuery, SystemResponse,
};
use linera_storage::{Clock as _, ResultReadCertificates, Storage as _};
use linera_views::ViewError;
use rand::prelude::SliceRandom as _;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::{mpsc, OwnedRwLockReadGuard};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tracing::{debug, error, info, instrument, warn, Instrument as _};
use crate::{
data_types::{ChainInfo, ChainInfoQuery, ChainInfoResponse, ClientOutcome, RoundTimeout},
environment::Environment,
local_node::{LocalChainInfoExt as _, LocalNodeClient, LocalNodeError},
node::{
CrossChainMessageDelivery, NodeError, NotificationStream, ValidatorNode,
ValidatorNodeProvider as _,
},
notifier::ChannelNotifier,
remote_node::RemoteNode,
updater::{communicate_with_quorum, CommunicateAction, CommunicationError, ValidatorUpdater},
worker::{Notification, ProcessableCertificate, Reason, WorkerError, WorkerState},
CHAIN_INFO_MAX_RECEIVED_LOG_ENTRIES,
};
mod chain_client_state;
#[cfg(test)]
#[path = "../unit_tests/client_tests.rs"]
mod client_tests;
#[cfg(with_metrics)]
mod metrics {
use std::sync::LazyLock;
use linera_base::prometheus_util::{exponential_bucket_latencies, register_histogram_vec};
use prometheus::HistogramVec;
pub static PROCESS_INBOX_WITHOUT_PREPARE_LATENCY: LazyLock<HistogramVec> =
LazyLock::new(|| {
register_histogram_vec(
"process_inbox_latency",
"process_inbox latency",
&[],
exponential_bucket_latencies(500.0),
)
});
pub static PREPARE_CHAIN_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec(
"prepare_chain_latency",
"prepare_chain latency",
&[],
exponential_bucket_latencies(500.0),
)
});
pub static SYNCHRONIZE_CHAIN_STATE_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec(
"synchronize_chain_state_latency",
"synchronize_chain_state latency",
&[],
exponential_bucket_latencies(500.0),
)
});
pub static EXECUTE_BLOCK_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec(
"execute_block_latency",
"execute_block latency",
&[],
exponential_bucket_latencies(500.0),
)
});
pub static FIND_RECEIVED_CERTIFICATES_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
register_histogram_vec(
"find_received_certificates_latency",
"find_received_certificates latency",
&[],
exponential_bucket_latencies(500.0),
)
});
}
/// A builder that creates [`ChainClient`]s which share the cache and notifiers.
pub struct Client<Env: Environment> {
environment: Env,
/// Local node to manage the execution state and the local storage of the chains that we are
/// tracking.
local_node: LocalNodeClient<Env::Storage>,
/// The admin chain ID.
admin_id: ChainId,
/// Chains that should be tracked by the client.
// TODO(#2412): Merge with set of chains the client is receiving notifications from validators
tracked_chains: Arc<RwLock<HashSet<ChainId>>>,
/// References to clients waiting for chain notifications.
notifier: Arc<ChannelNotifier<Notification>>,
/// Chain state for the managed chains.
chains: papaya::HashMap<ChainId, ChainClientState>,
/// Configuration options.
options: ChainClientOptions,
}
impl<Env: Environment> Client<Env> {
/// Creates a new `Client` with a new cache and notifiers.
#[expect(clippy::too_many_arguments)]
#[instrument(level = "trace", skip_all)]
pub fn new(
environment: Env,
admin_id: ChainId,
long_lived_services: bool,
tracked_chains: impl IntoIterator<Item = ChainId>,
name: impl Into<String>,
chain_worker_ttl: Duration,
sender_chain_worker_ttl: Duration,
options: ChainClientOptions,
) -> Self {
let tracked_chains = Arc::new(RwLock::new(tracked_chains.into_iter().collect()));
let state = WorkerState::new_for_client(
name.into(),
environment.storage().clone(),
tracked_chains.clone(),
)
.with_long_lived_services(long_lived_services)
.with_allow_inactive_chains(true)
.with_allow_messages_from_deprecated_epochs(true)
.with_chain_worker_ttl(chain_worker_ttl)
.with_sender_chain_worker_ttl(sender_chain_worker_ttl);
let local_node = LocalNodeClient::new(state);
Self {
environment,
local_node,
chains: papaya::HashMap::new(),
admin_id,
tracked_chains,
notifier: Arc::new(ChannelNotifier::default()),
options,
}
}
/// Returns the storage client used by this client's local node.
pub fn storage_client(&self) -> &Env::Storage {
self.environment.storage()
}
pub fn validator_node_provider(&self) -> &Env::Network {
self.environment.network()
}
/// Returns a reference to the [`Signer`] of the client.
#[instrument(level = "trace", skip(self))]
pub fn signer(&self) -> &impl Signer {
self.environment.signer()
}
/// Adds a chain to the set of chains tracked by the local node.
#[instrument(level = "trace", skip(self))]
pub fn track_chain(&self, chain_id: ChainId) {
self.tracked_chains
.write()
.expect("Panics should not happen while holding a lock to `tracked_chains`")
.insert(chain_id);
}
/// Creates a new `ChainClient`.
#[instrument(level = "trace", skip_all, fields(chain_id, next_block_height))]
pub fn create_chain_client(
self: &Arc<Self>,
chain_id: ChainId,
block_hash: Option<CryptoHash>,
next_block_height: BlockHeight,
pending_proposal: Option<PendingProposal>,
preferred_owner: Option<AccountOwner>,
timing_sender: Option<mpsc::UnboundedSender<(u64, TimingType)>>,
) -> ChainClient<Env> {
// If the entry already exists we assume that the entry is more up to date than
// the arguments: If they were read from the wallet file, they might be stale.
self.chains
.pin()
.get_or_insert_with(chain_id, || ChainClientState::new(pending_proposal.clone()));
ChainClient {
client: self.clone(),
chain_id,
options: self.options.clone(),
preferred_owner,
initial_block_hash: block_hash,
initial_next_block_height: next_block_height,
timing_sender,
}
}
/// Fetches the chain description blob if needed, and returns the chain info.
async fn fetch_chain_info(
&self,
chain_id: ChainId,
validators: &[RemoteNode<Env::ValidatorNode>],
) -> Result<Box<ChainInfo>, ChainClientError> {
match self.local_node.chain_info(chain_id).await {
Ok(info) => Ok(info),
Err(LocalNodeError::BlobsNotFound(blob_ids)) => {
// Make sure the admin chain is up to date.
self.synchronize_chain_state(self.admin_id).await?;
// If the chain is missing then the error is a WorkerError
// and so a BlobsNotFound
self.update_local_node_with_blobs_from(blob_ids, validators)
.await?;
Ok(self.local_node.chain_info(chain_id).await?)
}
Err(err) => Err(err.into()),
}
}
/// Downloads and processes all certificates up to (excluding) the specified height.
#[instrument(level = "trace", skip(self))]
async fn download_certificates(
&self,
chain_id: ChainId,
target_next_block_height: BlockHeight,
) -> Result<Box<ChainInfo>, ChainClientError> {
let mut validators = self.validator_nodes().await?;
// Sequentially try each validator in random order.
validators.shuffle(&mut rand::thread_rng());
let mut info = self.fetch_chain_info(chain_id, &validators).await?;
for remote_node in validators {
if target_next_block_height <= info.next_block_height {
return Ok(info);
}
match self
.download_certificates_from(&remote_node, chain_id, target_next_block_height)
.await
{
Err(err) => warn!(
"Failed to download certificates from validator {:?}: {err}",
remote_node.public_key
),
Ok(Some(new_info)) => info = new_info,
Ok(None) => {}
}
}
ensure!(
target_next_block_height <= info.next_block_height,
ChainClientError::CannotDownloadCertificates {
chain_id,
target_next_block_height,
}
);
Ok(info)
}
/// Downloads and processes all certificates up to (excluding) the specified height from the
/// given validator.
#[instrument(level = "trace", skip_all)]
async fn download_certificates_from(
&self,
remote_node: &RemoteNode<Env::ValidatorNode>,
chain_id: ChainId,
stop: BlockHeight,
) -> Result<Option<Box<ChainInfo>>, ChainClientError> {
let mut last_info = None;
// First load any blocks from local storage, if available.
let mut hashes = Vec::new();
let mut next_height = BlockHeight::ZERO;
{
let chain = self.local_node.chain_state_view(chain_id).await?;
next_height = next_height.max(chain.tip_state.get().next_block_height);
while next_height < stop {
let Some(hash) = chain.preprocessed_blocks.get(&next_height).await? else {
break;
};
hashes.push(hash);
next_height = next_height.try_add_one()?;
}
}
let certificates = self
.storage_client()
.read_certificates(hashes.clone())
.await?;
let certificates = match ResultReadCertificates::new(certificates, hashes) {
ResultReadCertificates::Certificates(certificates) => certificates,
ResultReadCertificates::InvalidHashes(hashes) => {
return Err(ChainClientError::ReadCertificatesError(hashes))
}
};
for certificate in certificates {
last_info = Some(self.handle_certificate(certificate).await?.info);
}
// Now download the rest in batches from the remote node.
while next_height < stop {
// TODO(#2045): Analyze network errors instead of using a fixed batch size.
let limit = u64::from(stop)
.checked_sub(u64::from(next_height))
.ok_or(ArithmeticError::Overflow)?
.min(self.options.certificate_download_batch_size);
let certificates = remote_node
.query_certificates_from(chain_id, next_height, limit)
.await?;
let Some(info) = self.process_certificates(remote_node, certificates).await? else {
break;
};
assert!(info.next_block_height > next_height);
next_height = info.next_block_height;
last_info = Some(info);
}
Ok(last_info)
}
async fn download_blobs(
&self,
remote_node: &RemoteNode<impl ValidatorNode>,
blob_ids: impl IntoIterator<Item = BlobId>,
) -> Result<(), ChainClientError> {
self.local_node
.store_blobs(
&futures::stream::iter(blob_ids.into_iter().map(|blob_id| async move {
remote_node.try_download_blob(blob_id).await.unwrap()
}))
.buffer_unordered(self.options.max_joined_tasks)
.collect::<Vec<_>>()
.await,
)
.await
.map_err(Into::into)
}
/// Tries to process all the certificates, requesting any missing blobs from the given node.
/// Returns the chain info of the last successfully processed certificate.
#[instrument(level = "trace", skip_all)]
async fn process_certificates(
&self,
remote_node: &RemoteNode<impl ValidatorNode>,
certificates: Vec<ConfirmedBlockCertificate>,
) -> Result<Option<Box<ChainInfo>>, ChainClientError> {
let mut info = None;
let required_blob_ids: Vec<_> = certificates
.iter()
.flat_map(|certificate| certificate.value().required_blob_ids())
.collect();
match self
.local_node
.read_blob_states_from_storage(&required_blob_ids)
.await
{
Err(LocalNodeError::BlobsNotFound(blob_ids)) => {
self.download_blobs(remote_node, blob_ids).await?;
}
x => {
x?;
}
}
for certificate in certificates {
info = Some(
match self.handle_certificate(certificate.clone()).await {
Err(LocalNodeError::BlobsNotFound(blob_ids)) => {
self.download_blobs(remote_node, blob_ids).await?;
self.handle_certificate(certificate).await?
}
x => x?,
}
.info,
);
}
// Done with all certificates.
Ok(info)
}
async fn handle_certificate<T: ProcessableCertificate>(
&self,
certificate: GenericCertificate<T>,
) -> Result<ChainInfoResponse, LocalNodeError> {
self.local_node
.handle_certificate(certificate, &self.notifier)
.await
}
async fn chain_info_with_committees(
&self,
chain_id: ChainId,
) -> Result<Box<ChainInfo>, LocalNodeError> {
let query = ChainInfoQuery::new(chain_id).with_committees();
let info = self.local_node.handle_chain_info_query(query).await?.info;
Ok(info)
}
/// Obtains all the committees trusted by any of the given chains. Also returns the highest
/// of their epochs.
#[instrument(level = "trace", skip_all)]
async fn admin_committees(
&self,
) -> Result<(Epoch, BTreeMap<Epoch, Committee>), LocalNodeError> {
let info = self.chain_info_with_committees(self.admin_id).await?;
Ok((info.epoch, info.into_committees()?))
}
/// Obtains the committee for the latest epoch on the admin chain.
pub async fn admin_committee(&self) -> Result<(Epoch, Committee), LocalNodeError> {
let info = self.chain_info_with_committees(self.admin_id).await?;
Ok((info.epoch, info.into_current_committee()?))
}
/// Obtains the validators for the latest epoch.
async fn validator_nodes(
&self,
) -> Result<Vec<RemoteNode<Env::ValidatorNode>>, ChainClientError> {
let (_, committee) = self.admin_committee().await?;
Ok(self.make_nodes(&committee)?)
}
/// Creates a [`RemoteNode`] for each validator in the committee.
fn make_nodes(
&self,
committee: &Committee,
) -> Result<Vec<RemoteNode<Env::ValidatorNode>>, NodeError> {
Ok(self
.validator_node_provider()
.make_nodes(committee)?
.map(|(public_key, node)| RemoteNode { public_key, node })
.collect())
}
/// Ensures that the client has the `ChainDescription` blob corresponding to this
/// client's `ChainId`.
pub async fn get_chain_description(
&self,
chain_id: ChainId,
) -> Result<ChainDescription, ChainClientError> {
let chain_desc_id = BlobId::new(chain_id.0, BlobType::ChainDescription);
let blob = self
.local_node
.storage_client()
.read_blob(chain_desc_id)
.await?;
if let Some(blob) = blob {
// We have the blob - return it.
return Ok(bcs::from_bytes(blob.bytes())?);
};
// Recover history from the current validators, according to the admin chain.
self.synchronize_chain_state(self.admin_id).await?;
let nodes = self.validator_nodes().await?;
let blob = self
.update_local_node_with_blobs_from(vec![chain_desc_id], &nodes)
.await?
.pop()
.unwrap(); // Returns exactly as many blobs as passed-in IDs.
Ok(bcs::from_bytes(blob.bytes())?)
}
/// Updates the latest block and next block height and round information from the chain info.
#[instrument(level = "trace", skip_all, fields(chain_id = format!("{:.8}", info.chain_id)))]
fn update_from_info(&self, info: &ChainInfo) {
self.chains.pin().update(info.chain_id, |state| {
let mut state = state.clone_for_update_unchecked();
state.update_from_info(info);
state
});
}
/// Handles the certificate in the local node and the resulting notifications.
#[instrument(level = "trace", skip_all)]
async fn process_certificate<T: ProcessableCertificate>(
&self,
certificate: Box<GenericCertificate<T>>,
) -> Result<(), LocalNodeError> {
let info = self.handle_certificate(*certificate).await?.info;
self.update_from_info(&info);
Ok(())
}
/// Submits a validated block for finalization and returns the confirmed block certificate.
#[instrument(level = "trace", skip_all)]
async fn finalize_block(
&self,
committee: &Committee,
certificate: ValidatedBlockCertificate,
) -> Result<ConfirmedBlockCertificate, ChainClientError> {
debug!(round = %certificate.round, "Submitting block for confirmation");
let hashed_value = ConfirmedBlock::new(certificate.inner().block().clone());
let finalize_action = CommunicateAction::FinalizeBlock {
certificate: Box::new(certificate),
delivery: self.options.cross_chain_message_delivery,
};
let certificate = self
.communicate_chain_action(committee, finalize_action, hashed_value)
.await?;
self.receive_certificate(certificate.clone(), ReceiveCertificateMode::AlreadyChecked)
.await?;
Ok(certificate)
}
/// Submits a block proposal to the validators.
#[instrument(level = "trace", skip_all)]
async fn submit_block_proposal<T: ProcessableCertificate>(
&self,
committee: &Committee,
proposal: Box<BlockProposal>,
value: T,
) -> Result<GenericCertificate<T>, ChainClientError> {
debug!(
round = %proposal.content.round,
"Submitting block proposal to validators"
);
let submit_action = CommunicateAction::SubmitBlock {
proposal,
blob_ids: value.required_blob_ids().into_iter().collect(),
};
let certificate = self
.communicate_chain_action(committee, submit_action, value)
.await?;
self.process_certificate(Box::new(certificate.clone()))
.await?;
Ok(certificate)
}
/// Broadcasts certified blocks to validators.
#[instrument(level = "trace", skip_all, fields(chain_id, block_height, delivery))]
async fn communicate_chain_updates(
&self,
committee: &Committee,
chain_id: ChainId,
height: BlockHeight,
delivery: CrossChainMessageDelivery,
) -> Result<(), ChainClientError> {
let nodes = self.make_nodes(committee)?;
communicate_with_quorum(
&nodes,
committee,
|_: &()| (),
|remote_node| {
let mut updater = ValidatorUpdater {
remote_node,
local_node: self.local_node.clone(),
admin_id: self.admin_id,
};
Box::pin(async move {
updater
.send_chain_information(chain_id, height, delivery)
.await
})
},
self.options.grace_period,
)
.await?;
Ok(())
}
/// Broadcasts certified blocks and optionally a block proposal, certificate or
/// leader timeout request.
///
/// In that case, it verifies that the validator votes are for the provided value,
/// and returns a certificate.
#[instrument(level = "trace", skip_all)]
async fn communicate_chain_action<T: CertificateValue>(
&self,
committee: &Committee,
action: CommunicateAction,
value: T,
) -> Result<GenericCertificate<T>, ChainClientError> {
let nodes = self.make_nodes(committee)?;
let ((votes_hash, votes_round), votes) = communicate_with_quorum(
&nodes,
committee,
|vote: &LiteVote| (vote.value.value_hash, vote.round),
|remote_node| {
let mut updater = ValidatorUpdater {
remote_node,
local_node: self.local_node.clone(),
admin_id: self.admin_id,
};
let action = action.clone();
Box::pin(async move { updater.send_chain_update(action).await })
},
self.options.grace_period,
)
.await?;
ensure!(
(votes_hash, votes_round) == (value.hash(), action.round()),
ChainClientError::UnexpectedQuorum {
hash: votes_hash,
round: votes_round,
expected_hash: value.hash(),
expected_round: action.round(),
}
);
// Certificate is valid because
// * `communicate_with_quorum` ensured a sufficient "weight" of
// (non-error) answers were returned by validators.
// * each answer is a vote signed by the expected validator.
let certificate = LiteCertificate::try_from_votes(votes)
.ok_or_else(|| {
ChainClientError::InternalError("Vote values or rounds don't match; this is a bug")
})?
.with_value(value)
.ok_or_else(|| {
ChainClientError::ProtocolError("A quorum voted for an unexpected value")
})?;
Ok(certificate)
}
/// Processes the confirmed block certificate and its ancestors in the local node, then
/// updates the validators up to that certificate.
#[instrument(level = "trace", skip_all)]
async fn receive_certificate_and_update_validators(
&self,
certificate: ConfirmedBlockCertificate,
mode: ReceiveCertificateMode,
) -> Result<(), ChainClientError> {
let block_chain_id = certificate.block().header.chain_id;
let block_height = certificate.block().header.height;
self.receive_certificate(certificate, mode).await?;
// Make sure a quorum of validators (according to the chain's new committee) are up-to-date
// for data availability.
let local_committee = self
.chain_info_with_committees(block_chain_id)
.await?
.into_current_committee()?;
self.communicate_chain_updates(
&local_committee,
block_chain_id,
block_height.try_add_one()?,
CrossChainMessageDelivery::Blocking,
)
.await?;
Ok(())
}
/// Processes the confirmed block certificate in the local node. Also downloads and processes
/// all ancestors that are still missing.
#[instrument(level = "trace", skip_all)]
async fn receive_certificate(
&self,
certificate: ConfirmedBlockCertificate,
mode: ReceiveCertificateMode,
) -> Result<(), ChainClientError> {
let certificate = Box::new(certificate);
let block = certificate.block();
// Verify the certificate before doing any expensive networking.
let (max_epoch, committees) = self.admin_committees().await?;
if let ReceiveCertificateMode::NeedsCheck = mode {
Self::check_certificate(max_epoch, &committees, &certificate)?.into_result()?;
}
// Recover history from the network.
self.download_certificates(block.header.chain_id, block.header.height)
.await?;
// Process the received operations. Download required hashed certificate values if
// necessary.
if let Err(err) = self.process_certificate(certificate.clone()).await {
match &err {
LocalNodeError::BlobsNotFound(blob_ids) => {
let blobs = RemoteNode::download_blobs(
blob_ids,
&self.validator_nodes().await?,
self.options.blob_download_timeout,
)
.await
.ok_or(err)?;
self.local_node.store_blobs(&blobs).await?;
self.process_certificate(certificate).await?;
}
_ => {
// The certificate is not as expected. Give up.
warn!("Failed to process network hashed certificate value");
return Err(err.into());
}
}
}
Ok(())
}
/// Processes the confirmed block in the local node, possibly without executing it.
#[instrument(level = "trace", skip_all)]
#[allow(dead_code)] // Otherwise CI fails when built for docker.
async fn receive_sender_certificate(
&self,
certificate: ConfirmedBlockCertificate,
mode: ReceiveCertificateMode,
nodes: Option<Vec<RemoteNode<Env::ValidatorNode>>>,
) -> Result<(), ChainClientError> {
// Verify the certificate before doing any expensive networking.
let (max_epoch, committees) = self.admin_committees().await?;
if let ReceiveCertificateMode::NeedsCheck = mode {
Self::check_certificate(max_epoch, &committees, &certificate)?.into_result()?;
}
// Recover history from the network.
let nodes = if let Some(nodes) = nodes {
nodes
} else {
self.validator_nodes().await?
};
if let Err(err) = self.handle_certificate(certificate.clone()).await {
match &err {
LocalNodeError::BlobsNotFound(blob_ids) => {
let blobs = RemoteNode::download_blobs(
blob_ids,
&nodes,
self.options.blob_download_timeout,
)
.await
.ok_or(err)?;
self.local_node.store_blobs(&blobs).await?;
self.handle_certificate(certificate.clone()).await?;
}
_ => {
// The certificate is not as expected. Give up.
warn!("Failed to process network hashed certificate value");
return Err(err.into());
}
}
}
Ok(())
}
/// Downloads a limited batch of received certificates from a validator.
/// Returns the updated tracker and whether there are more certificates to fetch.
#[instrument(level = "trace", skip(self))]
async fn synchronize_received_certificates_batch_from_validator(
&self,
chain_id: ChainId,
remote_node: &RemoteNode<Env::ValidatorNode>,
) -> Result<(ReceivedCertificatesFromValidator, bool), ChainClientError> {
let mut tracker = self
.local_node
.chain_state_view(chain_id)
.await?
.received_certificate_trackers
.get()
.get(&remote_node.public_key)
.copied()
.unwrap_or(0);
let (max_epoch, committees) = self.admin_committees().await?;
// Retrieve a limited batch of received certificates from this validator.
let offset = tracker;
let query = ChainInfoQuery::new(chain_id).with_received_log_excluding_first_n(offset);
let info = remote_node.handle_chain_info_query(query).await?;
let received_entries = info.requested_received_log.len();
let has_more = received_entries >= CHAIN_INFO_MAX_RECEIVED_LOG_ENTRIES;
let remote_log = info.requested_received_log;
let remote_heights = Self::heights_per_chain(&remote_log);
// Obtain the next block height we need in the local node, for each chain.
let local_next_heights = self
.local_node
.next_outbox_heights(remote_heights.keys(), chain_id)
.await?;
// We keep track of the height we've successfully downloaded and checked, per chain.
let mut downloaded_heights = BTreeMap::new();
// And we make a list of chains we already fully have locally. We need to make sure to
// put all their sent messages into the inbox.
let mut other_sender_chains = Vec::new();
let certificates = stream::iter(remote_heights.into_iter().filter_map(
|(sender_chain_id, remote_heights)| {
let local_next = *local_next_heights.get(&sender_chain_id)?;
if let Ok(height) = local_next.try_sub_one() {
downloaded_heights.insert(sender_chain_id, height);
}
let remote_heights = remote_heights
.into_iter()
.filter(|h| *h >= local_next)
.collect::<Vec<_>>();
if remote_heights.is_empty() {
// Our highest, locally executed block is higher than any block height
// from the current batch. Skip this batch, but remember to wait for
// the messages to be delivered to the inboxes.
other_sender_chains.push(sender_chain_id);
return None;
};
Some(async move {
let certificates = remote_node
.download_certificates_by_heights(sender_chain_id, remote_heights)
.await?;
Ok::<Vec<_>, ChainClientError>(certificates)
})
},
))
.buffer_unordered(self.options.max_joined_tasks)
.try_collect::<Vec<_>>()
.await?
.into_iter()
.flatten()
.collect::<Vec<_>>();
let mut certificates_by_height_by_chain = BTreeMap::new();
// Check the signatures and keep only the ones that are valid.
for confirmed_block_certificate in certificates {
let block_header = &confirmed_block_certificate.inner().block().header;
let sender_chain_id = block_header.chain_id;
let height = block_header.height;
let epoch = block_header.epoch;
match Self::check_certificate(max_epoch, &committees, &confirmed_block_certificate)? {
CheckCertificateResult::FutureEpoch => {
warn!(
"Postponing received certificate from {sender_chain_id:.8} at height \
{height} from future epoch {epoch}"
);
// Do not process this certificate now. It can still be
// downloaded later, once our committee is updated.
}
CheckCertificateResult::OldEpoch => {
// This epoch is not recognized any more. Let's skip the certificate.
// If a higher block with a recognized epoch comes up later from the
// same chain, the call to `receive_certificate` below will download
// the skipped certificate again.
warn!("Skipping received certificate from past epoch {epoch:?}");
}
CheckCertificateResult::New => {
certificates_by_height_by_chain
.entry(sender_chain_id)
.or_insert_with(BTreeMap::new)
.insert(height, confirmed_block_certificate);
}
}
}
// Increase the tracker up to the first position we haven't downloaded.
for entry in remote_log {
if certificates_by_height_by_chain
.get(&entry.chain_id)
.is_some_and(|certs| certs.contains_key(&entry.height))
{
tracker += 1;
} else {
break;
}
}
for (sender_chain_id, certs) in &mut certificates_by_height_by_chain {
if certs
.values()
.any(|cert| !cert.block().recipients().contains(&chain_id))
{
warn!(
"Skipping received certificates from chain {sender_chain_id:.8}:
No messages for {chain_id:.8}."
);
certs.clear();
}
}
Ok((
ReceivedCertificatesFromValidator {
public_key: remote_node.public_key,
tracker,
certificates: certificates_by_height_by_chain
.into_values()
.flat_map(BTreeMap::into_values)
.collect(),
other_sender_chains,
},
has_more,
))
}
/// Downloads only the specific sender blocks needed for missing cross-chain messages.
/// This is a targeted alternative to `find_received_certificates` that only downloads
/// the exact sender blocks we're missing, rather than searching through all received
/// certificates.
async fn download_missing_sender_blocks(
&self,
receiver_chain_id: ChainId,
missing_blocks: BTreeMap<ChainId, Vec<BlockHeight>>,
) -> Result<(), ChainClientError> {
if missing_blocks.is_empty() {
return Ok(());
}
let (_, committee) = self.admin_committee().await?;
let nodes = self.make_nodes(&committee)?;
// Download certificates for each sender chain at the specific heights.
stream::iter(missing_blocks.into_iter())
.map(|(sender_chain_id, heights)| {
let height = heights.into_iter().max();
let mut shuffled_nodes = nodes.clone();
shuffled_nodes.shuffle(&mut rand::thread_rng());
async move {
let Some(height) = height else {
return Ok(());
};
// Try to download from any node.
for node in &shuffled_nodes {
if let Err(err) = self
.download_sender_block_with_sending_ancestors(
receiver_chain_id,
sender_chain_id,
height,
node,
)
.await
{
tracing::debug!(
%height,
%receiver_chain_id,
%sender_chain_id,
%err,
validator = %node.public_key,
"Failed to fetch sender block",
);
} else {
return Ok::<_, ChainClientError>(());
}
}
// If all nodes fail, return an error.
Err(ChainClientError::CannotDownloadMissingSenderBlock {
chain_id: sender_chain_id,
height,
})
}
})
.buffer_unordered(self.options.max_joined_tasks)
.try_collect::<Vec<_>>()
.await?;
Ok(())
}
/// Downloads a specific sender block and recursively downloads any earlier blocks
/// that also sent a message to our chain, based on `previous_message_blocks`.
///
/// This ensures that we have all the sender blocks needed to preprocess the target block
/// and put the messages to our chain into the outbox.
async fn download_sender_block_with_sending_ancestors(
&self,
receiver_chain_id: ChainId,
sender_chain_id: ChainId,
height: BlockHeight,
remote_node: &RemoteNode<Env::ValidatorNode>,
) -> Result<(), ChainClientError> {
let next_outbox_height = self
.local_node
.next_outbox_heights(&[sender_chain_id], receiver_chain_id)
.await?
.get(&sender_chain_id)
.copied()