forked from informalsystems/tendermint-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
supervisor.rs
862 lines (724 loc) · 29 KB
/
supervisor.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
//! Supervisor and Handle implementation.
use crossbeam_channel as channel;
use tendermint::evidence::{ConflictingHeadersEvidence, Evidence};
use crate::{
errors::Error,
evidence::EvidenceReporter,
fork_detector::{Fork, ForkDetection, ForkDetector},
light_client::LightClient,
peer_list::PeerList,
state::State,
verifier::types::{Height, LatestStatus, LightBlock, PeerId, Status},
};
/// Provides an interface to the supervisor for use in downstream code.
pub trait Handle: Send + Sync {
/// Get latest trusted block.
fn latest_trusted(&self) -> Result<Option<LightBlock>, Error>;
/// Get the latest status.
fn latest_status(&self) -> Result<LatestStatus, Error>;
/// Verify to the highest block.
fn verify_to_highest(&self) -> Result<LightBlock, Error>;
/// Verify to the block at the given height.
fn verify_to_target(&self, _height: Height) -> Result<LightBlock, Error>;
/// Terminate the underlying [`Supervisor`].
fn terminate(&self) -> Result<(), Error>;
}
/// Input events sent by the [`Handle`]s to the [`Supervisor`]. They carry a [`Callback`] which is
/// used to communicate back the responses of the requests.
#[derive(Debug)]
enum HandleInput {
/// Terminate the supervisor process
Terminate(channel::Sender<()>),
/// Verify to the highest height, call the provided callback with result
VerifyToHighest(channel::Sender<Result<LightBlock, Error>>),
/// Verify to the given height, call the provided callback with result
VerifyToTarget(Height, channel::Sender<Result<LightBlock, Error>>),
/// Get the latest trusted block.
LatestTrusted(channel::Sender<Option<LightBlock>>),
/// Get the current status of the LightClient
GetStatus(channel::Sender<LatestStatus>),
}
/// A light client `Instance` packages a `LightClient` together with its `State`.
#[derive(Debug)]
pub struct Instance {
/// The light client for this instance
pub light_client: LightClient,
/// The state of the light client for this instance
pub state: State,
}
impl Instance {
/// Constructs a new instance from the given light client and its state.
pub fn new(light_client: LightClient, state: State) -> Self {
Self {
light_client,
state,
}
}
/// Get the latest trusted block.
pub fn latest_trusted(&self) -> Option<LightBlock> {
self.state.light_store.highest(Status::Trusted)
}
/// Trust the given block.
pub fn trust_block(&mut self, lb: &LightBlock) {
self.state.light_store.update(lb, Status::Trusted);
}
}
/// The supervisor manages multiple light client instances, of which one
/// is deemed to be the primary instance through which blocks are retrieved
/// and verified. The other instances are considered as witnesses
/// which are consulted to perform fork detection.
///
/// If primary verification fails, the primary client is removed and a witness
/// is promoted to primary. If a witness is deemed faulty, then the witness is
/// removed.
///
/// The supervisor is intended to be ran in its own thread, and queried
/// via a `Handle`.
///
/// ## Example
///
/// ```rust,ignore
/// let mut supervisor: Supervisor = todo!();
/// let mut handle = supervisor.handle();
///
/// // Spawn the supervisor in its own thread.
/// std::thread::spawn(|| supervisor.run());
///
/// loop {
/// // Asynchronously query the supervisor via a handle
/// let maybe_block = handle.verify_to_highest();
/// match maybe_block {
/// Ok(light_block) => {
/// println!("[info] synced to block {}", light_block.height());
/// }
/// Err(e) => {
/// println!("[error] sync failed: {}", e);
/// }
/// };
///
/// std::thread::sleep(Duration::from_millis(800));
/// }
/// ```
pub struct Supervisor {
/// List of peers and their instances (primary, witnesses, full and faulty nodes)
peers: PeerList<Instance>,
/// An instance of the fork detector
fork_detector: Box<dyn ForkDetector>,
/// Reporter of fork evidence
evidence_reporter: Box<dyn EvidenceReporter>,
/// Channel through which to reply to `Handle`s
sender: channel::Sender<HandleInput>,
/// Channel through which to receive events from the `Handle`s
receiver: channel::Receiver<HandleInput>,
}
impl std::fmt::Debug for Supervisor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Supervisor")
.field("peers", &self.peers)
.finish()
}
}
// Ensure the `Supervisor` can be sent across thread boundaries.
static_assertions::assert_impl_all!(Supervisor: Send);
impl Supervisor {
/// Constructs a new supervisor from the given list of peers and fork detector instance.
pub fn new(
peers: PeerList<Instance>,
fork_detector: impl ForkDetector + 'static,
evidence_reporter: impl EvidenceReporter + 'static,
) -> Self {
let (sender, receiver) = channel::unbounded::<HandleInput>();
Self {
peers,
sender,
receiver,
fork_detector: Box::new(fork_detector),
evidence_reporter: Box::new(evidence_reporter),
}
}
/// Create a new handle to this supervisor.
pub fn handle(&self) -> SupervisorHandle {
SupervisorHandle::new(self.sender.clone())
}
/// Get the latest trusted state of the primary peer, if any
pub fn latest_trusted(&self) -> Option<LightBlock> {
self.peers.primary().latest_trusted()
}
/// Verify to the highest block.
pub fn verify_to_highest(&mut self) -> Result<LightBlock, Error> {
self.verify(None)
}
/// Return latest trusted status summary.
fn latest_status(&mut self) -> LatestStatus {
let latest_trusted = self.peers.primary().latest_trusted();
let mut connected_nodes = vec![self.peers.primary_id()];
connected_nodes.append(&mut self.peers.witnesses_ids().iter().copied().collect());
match latest_trusted {
Some(trusted) => LatestStatus::new(
Some(trusted.signed_header.header.height.value()),
Some(trusted.signed_header.header.hash()),
Some(trusted.next_validators.hash()),
connected_nodes,
),
// only return connected nodes to see what is going on:
None => LatestStatus::new(None, None, None, connected_nodes),
}
}
/// Verify to the block at the given height.
pub fn verify_to_target(&mut self, height: Height) -> Result<LightBlock, Error> {
self.verify(Some(height))
}
/// Verify either to the latest block (if `height == None`) or to a given block (if `height ==
/// Some(height)`).
fn verify(&mut self, height: Option<Height>) -> Result<LightBlock, Error> {
let primary = self.peers.primary_mut();
// Perform light client core verification for the given height (or highest).
let verdict = match height {
None => primary.light_client.verify_to_highest(&mut primary.state),
Some(height) => primary
.light_client
.verify_to_target(height, &mut primary.state),
};
match verdict {
// Verification succeeded, let's perform fork detection
Ok(verified_block) => {
let trusted_block = primary
.latest_trusted()
.ok_or_else(|| Error::no_trusted_state(Status::Trusted))?;
// Perform fork detection with the highest verified block and the trusted block.
let outcome = self.detect_forks(&verified_block, &trusted_block)?;
match outcome {
// There was a fork or a faulty peer
ForkDetection::Detected(forks) => {
let forked = self.process_forks(forks)?;
if !forked.is_empty() {
// Fork detected, exiting
return Err(Error::fork_detected(forked));
}
// If there were no hard forks, perform verification again
self.verify(height)
},
ForkDetection::NotDetected => {
// We need to re-ask for the primary here as the compiler
// is not smart enough to realize that we do not mutate
// the `primary` field of `PeerList` between the initial
// borrow of the primary and here (can't blame it, it's
// not that obvious).
self.peers.primary_mut().trust_block(&verified_block);
// No fork detected, exiting
Ok(verified_block)
},
}
},
// Verification failed
Err(err) => {
// Swap primary, and continue with new primary, if there is any witness left.
self.peers.replace_faulty_primary(Some(err))?;
self.verify(height)
},
}
}
fn process_forks(&mut self, forks: Vec<Fork>) -> Result<Vec<PeerId>, Error> {
let mut forked = Vec::with_capacity(forks.len());
for fork in forks {
match fork {
// An actual fork was detected, report evidence and record forked peer.
// TODO: also report to primary
Fork::Forked { primary, witness } => {
let provider = witness.provider;
self.report_evidence(provider, &primary, &witness)?;
forked.push(provider);
},
// A witness has timed out, remove it from the peer list.
Fork::Timeout(provider, _error) => {
self.peers.replace_faulty_witness(provider);
// TODO: Log/record the error
},
// A witness has been deemed faulty, remove it from the peer list.
Fork::Faulty(block, _error) => {
self.peers.replace_faulty_witness(block.provider);
// TODO: Log/record the error
},
}
}
Ok(forked)
}
/// Report the given evidence of a fork.
fn report_evidence(
&mut self,
provider: PeerId,
primary: &LightBlock,
witness: &LightBlock,
) -> Result<(), Error> {
let evidence = ConflictingHeadersEvidence::new(
primary.signed_header.clone(),
witness.signed_header.clone(),
);
self.evidence_reporter
.report(Evidence::ConflictingHeaders(Box::new(evidence)), provider)
.map_err(Error::io)?;
Ok(())
}
/// Perform fork detection with the given verified block and trusted block.
fn detect_forks(
&self,
verified_block: &LightBlock,
trusted_block: &LightBlock,
) -> Result<ForkDetection, Error> {
if self.peers.witnesses_ids().is_empty() {
return Err(Error::no_witnesses());
}
let witnesses = self
.peers
.witnesses_ids()
.iter()
.filter_map(|id| self.peers.get(id))
.collect();
self.fork_detector
.detect_forks(verified_block, trusted_block, witnesses)
}
/// Run the supervisor event loop in the same thread.
///
/// This method should typically be called within a new thread with `std::thread::spawn`.
pub fn run(mut self) -> Result<(), Error> {
loop {
let event = self.receiver.recv().map_err(Error::recv)?;
match event {
HandleInput::LatestTrusted(sender) => {
let outcome = self.latest_trusted();
sender.send(outcome).map_err(Error::send)?;
},
HandleInput::Terminate(sender) => {
sender.send(()).map_err(Error::send)?;
return Ok(());
},
HandleInput::VerifyToTarget(height, sender) => {
let outcome = self.verify_to_target(height);
sender.send(outcome).map_err(Error::send)?;
},
HandleInput::VerifyToHighest(sender) => {
let outcome = self.verify_to_highest();
sender.send(outcome).map_err(Error::send)?;
},
HandleInput::GetStatus(sender) => {
let outcome = self.latest_status();
sender.send(outcome).map_err(Error::send)?;
},
}
}
}
}
/// A [`Handle`] to the [`Supervisor`] which allows to communicate with
/// the supervisor across thread boundaries via message passing.
#[derive(Clone)]
pub struct SupervisorHandle {
sender: channel::Sender<HandleInput>,
}
impl SupervisorHandle {
/// Crate a new handle that sends events to the supervisor via
/// the given channel. For internal use only.
fn new(sender: channel::Sender<HandleInput>) -> Self {
Self { sender }
}
fn verify(
&self,
make_event: impl FnOnce(channel::Sender<Result<LightBlock, Error>>) -> HandleInput,
) -> Result<LightBlock, Error> {
let (sender, receiver) = channel::bounded::<Result<LightBlock, Error>>(1);
let event = make_event(sender);
self.sender.send(event).map_err(Error::send)?;
receiver.recv().map_err(Error::recv)?
}
}
impl Handle for SupervisorHandle {
fn latest_trusted(&self) -> Result<Option<LightBlock>, Error> {
let (sender, receiver) = channel::bounded::<Option<LightBlock>>(1);
self.sender
.send(HandleInput::LatestTrusted(sender))
.map_err(Error::send)?;
receiver.recv().map_err(Error::recv)
}
fn latest_status(&self) -> Result<LatestStatus, Error> {
let (sender, receiver) = channel::bounded::<LatestStatus>(1);
self.sender
.send(HandleInput::GetStatus(sender))
.map_err(Error::send)?;
receiver.recv().map_err(Error::recv)
}
fn verify_to_highest(&self) -> Result<LightBlock, Error> {
self.verify(HandleInput::VerifyToHighest)
}
fn verify_to_target(&self, height: Height) -> Result<LightBlock, Error> {
self.verify(|sender| HandleInput::VerifyToTarget(height, sender))
}
fn terminate(&self) -> Result<(), Error> {
let (sender, receiver) = channel::bounded::<()>(1);
self.sender
.send(HandleInput::Terminate(sender))
.map_err(Error::send)?;
receiver.recv().map_err(Error::recv)
}
}
#[cfg(test)]
mod tests {
use core::{
convert::{Into, TryFrom},
time::Duration,
};
use std::collections::HashMap;
use tendermint::{
block::Height, evidence::Duration as DurationStr, trust_threshold::TrustThresholdFraction,
};
use tendermint_rpc::{
self as rpc,
response_error::{Code, ResponseError},
};
use tendermint_testgen::{
helpers::get_time, light_block::TmLightBlock, Commit, Generator, Header,
LightBlock as TestgenLightBlock, LightChain, ValidatorSet,
};
use super::*;
use crate::{
components::{
io::{self, AtHeight, Io},
scheduler,
},
errors::{Error, ErrorDetail},
fork_detector::ProdForkDetector,
store::{memory::MemoryStore, LightStore},
tests::{MockClock, MockEvidenceReporter, MockIo, TrustOptions},
verifier::{operations::ProdHasher, options::Options, types::Time, ProdVerifier},
};
trait IntoLightBlock {
fn into_light_block(self) -> LightBlock;
}
impl IntoLightBlock for TmLightBlock {
fn into_light_block(self) -> LightBlock {
LightBlock {
signed_header: self.signed_header,
validators: self.validators,
next_validators: self.next_validators,
provider: self.provider,
}
}
}
fn make_instance(
peer_id: PeerId,
trust_options: TrustOptions,
io: MockIo,
now: Time,
) -> Instance {
let trusted_height = trust_options.height;
let trusted_state = io
.fetch_light_block(AtHeight::At(trusted_height))
.expect("could not 'request' light block");
let mut light_store = MemoryStore::new();
light_store.insert(trusted_state, Status::Trusted);
let state = State {
light_store: Box::new(light_store),
verification_trace: HashMap::new(),
};
let options = Options {
trust_threshold: trust_options.trust_level,
trusting_period: trust_options.period.into(),
clock_drift: Duration::from_secs(0),
};
let verifier = ProdVerifier::default();
let clock = MockClock { now };
let scheduler = scheduler::basic_bisecting_schedule;
let hasher = ProdHasher::default();
let light_client =
LightClient::new(peer_id, options, clock, scheduler, verifier, hasher, io);
Instance::new(light_client, state)
}
fn run_bisection_test(
peer_list: PeerList<Instance>,
height_to_verify: u64,
) -> (Result<LightBlock, Error>, LatestStatus) {
let supervisor = Supervisor::new(
peer_list,
ProdForkDetector::default(),
MockEvidenceReporter::new(),
);
let handle = supervisor.handle();
std::thread::spawn(|| supervisor.run());
let target_height = Height::try_from(height_to_verify).expect("Error while making height");
(
handle.verify_to_target(target_height),
handle.latest_status().unwrap(),
)
}
fn make_peer_list(
primary: Option<Vec<LightBlock>>,
witnesses: Option<Vec<Vec<LightBlock>>>,
now: Time,
) -> PeerList<Instance> {
let trust_options = TrustOptions {
period: DurationStr(Duration::new(604800, 0)),
height: Height::try_from(1_u64).expect("Error while making height"),
trust_level: TrustThresholdFraction::TWO_THIRDS,
};
let mut peer_list = PeerList::builder();
if let Some(primary) = primary {
let io = MockIo::new(primary.clone());
let primary_instance =
make_instance(primary[0].provider, trust_options.clone(), io, now);
peer_list.primary(primary[0].provider, primary_instance);
}
if let Some(witnesses) = witnesses {
for provider in witnesses.into_iter() {
let peer_id = provider[0].provider;
let io = MockIo::new(provider);
let instance = make_instance(peer_id, trust_options.clone(), io.clone(), now);
peer_list.witness(peer_id, instance);
}
}
peer_list.build()
}
fn change_provider(
mut light_blocks: Vec<LightBlock>,
peer_id: Option<&str>,
) -> Vec<LightBlock> {
let provider = peer_id.unwrap_or("0BEFEEDC0C0ADEADBEBADFADADEFC0FFEEFACADE");
for lb in light_blocks.iter_mut() {
lb.provider = provider.parse().unwrap();
}
light_blocks
}
fn make_conflicting_witness(
length: u64,
val_ids: Option<Vec<&str>>,
chain_id: Option<&str>,
provider: Option<&str>,
) -> Vec<LightBlock> {
let vals = match val_ids {
Some(val_ids) => ValidatorSet::new(val_ids).validators.unwrap(),
None => ValidatorSet::new(vec!["1"]).validators.unwrap(),
};
let chain = chain_id.unwrap_or("other-chain");
let peer_id = provider.unwrap_or("0BEFEEDC0C0ADEADBEBADFADADEFC0FFEEFACADE");
let header = Header::new(&vals)
.height(1)
.chain_id(chain)
.time(Time::from_unix_timestamp(1, 0).unwrap());
let commit = Commit::new(header.clone(), 1);
let mut lb = TestgenLightBlock::new(header, commit).provider(peer_id);
let mut witness: Vec<LightBlock> = vec![lb.generate().unwrap().into_light_block()];
for _ in 1..length {
lb = lb.next();
let tm_lb = lb.generate().unwrap().into_light_block();
witness.push(tm_lb);
}
witness
}
#[test]
fn test_bisection_happy_path() {
let chain = LightChain::default_with_length(10);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let witness = change_provider(primary.clone(), None);
let peer_list = make_peer_list(
Some(primary.clone()),
Some(vec![witness]),
get_time(11).unwrap(),
);
let (result, _) = run_bisection_test(peer_list, 10);
let expected_state = primary[9].clone();
let new_state = result.unwrap();
assert_eq!(expected_state, new_state);
}
#[test]
fn test_bisection_no_witnesses() {
let chain = LightChain::default_with_length(10);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let peer_list = make_peer_list(Some(primary), None, get_time(11).unwrap());
let (result, _) = run_bisection_test(peer_list, 10);
match result {
Err(Error(ErrorDetail::NoWitnesses(_), _)) => {},
_ => panic!("expected NoWitnesses error, instead got {:?}", result),
}
}
#[test]
fn test_bisection_io_error() {
let chain = LightChain::default_with_length(10);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let mut light_blocks = primary.clone();
light_blocks.truncate(9);
let witness = change_provider(light_blocks, None);
let peer_list = make_peer_list(Some(primary), Some(vec![witness]), get_time(11).unwrap());
let (result, _) = run_bisection_test(peer_list, 10);
match result {
Err(Error(ErrorDetail::Io(e), _)) => match e.source {
io::IoErrorDetail::Rpc(e) => match e.source {
rpc::error::ErrorDetail::Response(e) => {
assert_eq!(e.source, ResponseError::new(Code::InvalidRequest, None))
},
_ => panic!("expected Response error"),
},
_ => panic!("expected Rpc error"),
},
_ => panic!("expected Io error"),
}
}
#[test]
fn test_bisection_no_witness_left() {
let chain = LightChain::default_with_length(5);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let witness = make_conflicting_witness(5, None, None, None);
let peer_list = make_peer_list(Some(primary), Some(vec![witness]), get_time(11).unwrap());
let (result, _) = run_bisection_test(peer_list, 10);
// FIXME: currently this test does not test what it is supposed to test,
// because MockIo returns an InvalidRequest error. This was previously
// treated as a NoWitnessLeft error, which was misclassified.
match result {
Err(Error(ErrorDetail::Io(e), _)) => match e.source {
crate::components::io::IoErrorDetail::Rpc(e) => match e.source {
rpc::error::ErrorDetail::Response(e) => {
assert_eq!(e.source.code(), rpc::Code::InvalidRequest)
},
_ => {
panic!("expected Response error, instead got {:?}", e)
},
},
_ => {
panic!("expected Rpc error, instead got {:?}", e)
},
},
_ => panic!("expected Io error, instead got {:?}", result),
}
}
#[test]
fn test_bisection_fork_detected() {
let mut chain = LightChain::default_with_length(5);
let primary = chain
.light_blocks
.clone()
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let mut header = chain.light_blocks[4].header.clone().unwrap();
let time = (header.time.unwrap() + Duration::from_secs(3)).unwrap();
header.time = Some(time);
chain.light_blocks[4].header = Some(header.clone());
chain.light_blocks[4].commit = Some(Commit::new(header, 1));
let witness = change_provider(
chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>(),
None,
);
let peer_list = make_peer_list(Some(primary), Some(vec![witness]), get_time(11).unwrap());
let (result, _) = run_bisection_test(peer_list, 5);
match result {
Err(Error(ErrorDetail::ForkDetected(_), _)) => {},
_ => panic!("expected ForkDetected error"),
}
}
#[test]
fn test_bisection_no_initial_trusted_state() {
let chain = LightChain::default_with_length(10);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let witness1 = change_provider(primary.clone(), None);
let witness2 = change_provider(
witness1.clone(),
Some("EDC0C0ADEADBEBA0BEFEDFADADEFC0FFEEFACADE"),
);
let mut peer_list = make_peer_list(
Some(primary.clone()),
Some(vec![witness1.clone(), witness2]),
get_time(11).unwrap(),
);
peer_list
.get_mut(&primary[0].provider)
.expect("cannot find instance")
.state
.light_store
.remove(
Height::try_from(1_u64).expect("bad height"),
Status::Trusted,
);
let (result, latest_status) = run_bisection_test(peer_list, 10);
// In the case where there is no initial trusted state found from a primary peer,
// the primary node is marked as faulty and replaced with a witness node (if available)
// and continues verification
let expected_state = &witness1[9];
let new_state = result.unwrap();
assert_eq!(expected_state, &new_state);
// Check that we successfully disconnected from the "faulty" primary node
assert!(!latest_status
.connected_nodes
.iter()
.any(|&peer| peer == primary[0].provider));
}
#[test]
fn test_bisection_trusted_state_outside_trusting_period() {
let chain = LightChain::default_with_length(10);
let primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
let witness = change_provider(primary.clone(), None);
let peer_list = make_peer_list(
Some(primary.clone()),
Some(vec![witness]),
get_time(604801).unwrap(),
);
let (_, latest_status) = run_bisection_test(peer_list, 2);
// In the case where trusted state of a primary peer is outside the trusting period,
// the primary node is marked as faulty and replaced with a witness node (if available)
// and continues verification
// Check if the node was removed from the list
assert!(!latest_status
.connected_nodes
.iter()
.any(|&peer| peer == primary[0].provider));
}
#[test]
fn test_bisection_invalid_light_block() {
let chain = LightChain::default_with_length(10);
let mut primary = chain
.light_blocks
.into_iter()
.map(|lb| lb.generate().unwrap().into_light_block())
.collect::<Vec<LightBlock>>();
primary[9].signed_header.commit.round = primary[9].signed_header.commit.round.increment();
let witness = change_provider(primary.clone(), None);
let peer_list = make_peer_list(
Some(primary.clone()),
Some(vec![witness]),
get_time(11).unwrap(),
);
let (_, latest_status) = run_bisection_test(peer_list, 10);
// In the case where a primary peer provides an invalid light block
// i.e. verification for the light block failed,
// the primary node is marked as faulty and replaced with a witness node (if available)
// and continues verification
// Check if the node was removed from the list
assert!(!latest_status
.connected_nodes
.iter()
.any(|&peer| peer == primary[0].provider));
}
}