thruput-scp-server 3.0.0

scpd, a standalone Stellar Consensus Protocol (SCP) daemon serving the SCP kernel over ONC-RPC
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
use crate::telemetry::{link_slot, slot_span};
use scp_kernel::*;
use std::collections::HashMap;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use thruput_scp::*;
use tokio::sync::RwLock as TokioRwLock;
use tokio::sync::RwLockWriteGuard as TokioRwLockWriteGuard;
use tokio::sync::mpsc;
use tokio::sync::mpsc::{
    Receiver, Sender, UnboundedReceiver, error::TryRecvError,
};
use tokio::sync::oneshot;
use tokio::time::sleep;
use tracing::Instrument;
use tracing::{debug, info};
use xdr_common::*;

#[derive(Clone)]
pub struct ControlService(Arc<TokioRwLock<ControlServiceState>>);

struct ControlServiceState {
    pub tx_request: Sender<ControlRequest>,
    pub rx_reply: Receiver<ControlReply>,
}

impl ControlService {
    pub fn new(
        tx_request: Sender<ControlRequest>,
        rx_reply: Receiver<ControlReply>,
    ) -> ControlService {
        ControlService(Arc::new(TokioRwLock::new(ControlServiceState {
            tx_request,
            rx_reply,
        })))
    }

    async fn lock_mut(&self) -> TokioRwLockWriteGuard<'_, ControlServiceState> {
        self.0.write().await
    }

    pub async fn control_set_qset(
        &self,
        qset: SCPQuorumSet,
    ) -> Result<SCPOptQuorumSet, ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::SetKnownQSet(qset))
            .await
            .unwrap();
        if let ControlReply::SetKnownQSet(optq) =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(optq)
        } else {
            panic!("bug")
        }
    }

    pub async fn control_nominate(
        &self,
        slot_index: SCPSlotIndex,
        value: SCPValue,
        prev_value: SCPValue,
    ) -> Result<bool, ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::Nominate(slot_index, value, prev_value))
            .await
            .unwrap();
        if let ControlReply::Nominate(r) = x.rx_reply.recv().await.unwrap() {
            Ok(r)
        } else {
            panic!("bug")
        }
    }

    pub async fn control_received_envelope(
        &self,
        env: SCPEnvelope,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::ReceivedEnvelope(env))
            .await
            .unwrap();
        if let ControlReply::ReceivedEnvelope() =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(())
        } else {
            panic!("bug")
        }
    }

    pub async fn set_state_from_envelope(
        &self,
        slot_index: SCPSlotIndex,
        env: SCPEnvelope,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::SetStateFromEnvelope(slot_index, env))
            .await
            .unwrap();
        if let ControlReply::SetStateFromEnvelope() =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(())
        } else {
            panic!("bug")
        }
    }
}

#[allow(clippy::large_enum_variant)]
pub enum ControlRequest {
    Nominate(SCPSlotIndex, SCPValue, SCPValue),
    StopNomination(SCPSlotIndex),
    UpdateLocalQuorumSet(SCPQuorumSet),
    ReceivedEnvelope(SCPEnvelope),
    SetStateFromEnvelope(SCPSlotIndex, SCPEnvelope),
    SetKnownQSet(SCPQuorumSet),
    GetKnownQSet(SCPHash),
    RemoveKnownQSet(SCPHash),
    SetLowestNonExternalizedSlot(SCPSlotIndex),
}

pub enum ControlReply {
    Nominate(bool),
    StopNomination(),
    UpdateLocalQuorumSet(),
    ReceivedEnvelope(),
    SetStateFromEnvelope(),
    SetKnownQSet(Option<SCPQuorumSet>),
    GetKnownQSet(Option<SCPQuorumSet>),
    RemoveKnownQSet(Option<SCPQuorumSet>),
    SetLowestNonExternalizedSlot(),
}

// The handler trait returns `impl Future`; these async fns name their
// concrete reply types.
#[allow(refining_impl_trait)]
impl thruput_scp::SCP_Control_SCP_Control1 for ControlService {
    async fn scp_control_null(
        &self,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        Ok(())
    }

    async fn scp_control_nominate(
        &self,
        slot_index: SCPSlotIndex,
        value: SCPValue,
        prev_value: SCPValue,
    ) -> Result<bool, ::thruput_rpc_driver::ProgramError> {
        self.control_nominate(slot_index, value, prev_value).await
    }

    async fn scp_control_stop_nomination(
        &self,
        slot_index: SCPSlotIndex,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::StopNomination(slot_index))
            .await
            .unwrap();
        if let ControlReply::StopNomination() = x.rx_reply.recv().await.unwrap()
        {
            Ok(())
        } else {
            panic!("bug")
        }
    }

    async fn scp_control_update_local_quorum_set(
        &self,
        qset: SCPQuorumSet,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::UpdateLocalQuorumSet(qset))
            .await
            .unwrap();
        if let ControlReply::UpdateLocalQuorumSet() =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(())
        } else {
            panic!("bug")
        }
    }

    async fn scp_control_received_envelope(
        &self,
        env: SCPEnvelope,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let height =
            i64::try_from(env.statement.slot_index).unwrap_or(i64::MAX);
        let span = tracing::info_span!(
            target: "scpd::slot",
            "scp_control_received_envelope",
            slot_index = height,
            "thruput.block.height" = height
        );
        link_slot(&span, env.statement.slot_index);
        self.control_received_envelope(env).instrument(span).await
    }

    async fn scp_control_set_state_from_envelope(
        &self,
        slot_index: SCPSlotIndex,
        env: SCPEnvelope,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        self.set_state_from_envelope(slot_index, env).await
    }

    async fn scp_control_set_qset(
        &self,
        qset: SCPQuorumSet,
    ) -> Result<SCPOptQuorumSet, ::thruput_rpc_driver::ProgramError> {
        self.control_set_qset(qset).await
    }

    async fn scp_control_get_qset(
        &self,
        qhash: SCPHash,
    ) -> Result<SCPOptQuorumSet, ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::GetKnownQSet(qhash))
            .await
            .unwrap();
        if let ControlReply::GetKnownQSet(optq) =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(optq)
        } else {
            panic!("bug")
        }
    }

    async fn scp_control_remove_qset(
        &self,
        qhash: SCPHash,
    ) -> Result<SCPOptQuorumSet, ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::RemoveKnownQSet(qhash))
            .await
            .unwrap();
        if let ControlReply::RemoveKnownQSet(optq) =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(optq)
        } else {
            panic!("bug")
        }
    }

    async fn scp_control_set_lowest_non_externalized_slot(
        &self,
        slot_index: SCPSlotIndex,
    ) -> Result<(), ::thruput_rpc_driver::ProgramError> {
        let mut x = self.lock_mut().await;
        x.tx_request
            .send(ControlRequest::SetLowestNonExternalizedSlot(slot_index))
            .await
            .unwrap();
        if let ControlReply::SetLowestNonExternalizedSlot() =
            x.rx_reply.recv().await.unwrap()
        {
            Ok(())
        } else {
            panic!("bug")
        }
    }
}

use crate::handler::*;

pub type ValidatedValues =
    HashMap<SlotIndex, HashMap<SCPValue, ValidationLevel>>;

pub struct ValidateEnvelope {
    pub env: SCPEnvelope,
    pub validate_nomination_values: Vec<SCPValue>,
    pub validate_ballot_values: Vec<SCPValue>,
}

pub struct EnvelopeValidated {
    pub env: SCPEnvelope,
    pub validated_values: Vec<(SlotIndex, SCPValue, ValidationLevel)>,
}

#[derive(Debug, Clone)]
pub struct TimerExpired {
    slot_index: SlotIndex,
    timer: Timer,
    cb: DriverCallback,
}

impl std::fmt::Display for TimerExpired {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TimerExpired{{ i: {} | {} }}", self.slot_index, self.cb,)
    }
}

pub enum ControlSignal {
    ControlRequest(ControlRequest),
    EnvelopeValidated(EnvelopeValidated),
    TimerExpired(TimerExpired),
}

pub struct ControlKernel {
    tokio_handle: tokio::runtime::Handle,
    rx_signal: Receiver<ControlSignal>,
    tx_reply: Sender<ControlReply>,
    kernel: StellarKernel<HandleKernel, HandleKernel>,
    handler: HandleKernel,
    rx_switch_timer: UnboundedReceiver<SwitchTimer>,
    armed_timers: HashMap<SlotIndex, HashMap<Timer, oneshot::Sender<()>>>,
    tx_validate_envelope: Sender<ValidateEnvelope>,
    tx_timer_expired: Arc<TokioRwLock<Sender<TimerExpired>>>,
}

impl ControlKernel {
    #[allow(clippy::too_many_arguments)]
    pub async fn new(
        tokio_handle: tokio::runtime::Handle,
        rx_request: Receiver<ControlRequest>,
        tx_reply: Sender<ControlReply>,
        rx_switch_timer: UnboundedReceiver<SwitchTimer>,
        tx_validate_envelope: Sender<ValidateEnvelope>,
        rx_envelope_validated: Receiver<EnvelopeValidated>,
        kernel: StellarKernel<HandleKernel, HandleKernel>,
        handler: HandleKernel,
    ) -> ControlKernel {
        let (tx_timer_expired, rx_timer_expired) =
            mpsc::channel::<TimerExpired>(1);
        let rx_request_or_validated =
            Self::merge_rx(rx_request, rx_envelope_validated, rx_timer_expired)
                .await;
        ControlKernel {
            tokio_handle,
            rx_signal: rx_request_or_validated,
            tx_reply,
            kernel,
            handler,
            rx_switch_timer,
            armed_timers: HashMap::new(),
            tx_validate_envelope,
            tx_timer_expired: Arc::new(TokioRwLock::new(tx_timer_expired)),
        }
    }

    pub async fn merge_rx(
        mut rx_request: Receiver<ControlRequest>,
        mut rx_envelope_validated: Receiver<EnvelopeValidated>,
        mut rx_timer_expired: Receiver<TimerExpired>,
    ) -> Receiver<ControlSignal> {
        let (tx, rx) = mpsc::channel::<ControlSignal>(1);
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    msg = rx_request.recv() => {
                        tx.send(ControlSignal::ControlRequest(msg.unwrap())).await.unwrap();
                    },
                    msg = rx_envelope_validated.recv() => {
                        tx.send(ControlSignal::EnvelopeValidated(msg.unwrap())).await.unwrap();
                    }
                    msg = rx_timer_expired.recv() => {
                        tx.send(ControlSignal::TimerExpired(msg.unwrap())).await.unwrap();
                    }
                }
            }
        });
        rx
    }

    #[tracing::instrument(skip_all)]
    fn flush_timer_switches(&mut self) {
        loop {
            match self.rx_switch_timer.try_recv() {
                Ok(v) => match v {
                    SwitchTimer::StartTimer(slot_index, timer, timeout, cb) => {
                        self.start_timer(slot_index, timer, timeout, cb);
                    }
                    SwitchTimer::StopTimer(slot_index, timer) => {
                        self.stop_timer(slot_index, timer);
                    }
                    SwitchTimer::SlotExternalized(slot_index) => {
                        let height =
                            i64::try_from(slot_index).unwrap_or(i64::MAX);
                        let span = tracing::info_span!(
                            target: "scpd::slot",
                            "slot_externalized",
                            slot_index = height,
                            "thruput.block.height" = height
                        );
                        link_slot(&span, slot_index);
                        span.in_scope(|| {
                            self.stop_timers_not_above(slot_index);
                            // purge slots not above slot_index
                            self.kernel
                                .proto()
                                .purge_slots(slot_index + 1, slot_index + 1);
                        });
                    }
                },
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => panic!("bug"),
            }
        }
    }

    fn start_timer(
        &mut self,
        slot_index: SlotIndex,
        timer: Timer,
        timeout: Duration,
        cb: DriverCallback,
    ) {
        self.stop_timer(slot_index, timer);

        let (cancel_tx, cancel_rx) = oneshot::channel::<()>();

        self.tokio_handle.spawn({
            let tx_timer_expired = self.tx_timer_expired.clone();
            async move {
                tokio::select! {
                    _ = sleep(timeout) => {
                        tx_timer_expired.write().await.send(TimerExpired{slot_index, timer, cb}).await.unwrap();
                    }
                    _ = cancel_rx => {
                    }
                }
            }
        });

        let slot_timers = self.armed_timers.entry(slot_index).or_default();
        if slot_timers.insert(timer, cancel_tx).is_some() {
            panic!("there should be no prior timer")
        }
    }

    fn stop_timer(&mut self, slot_index: SlotIndex, timer: Timer) {
        if let Some(slot_timers) = self.armed_timers.get_mut(&slot_index)
            && let Some(cancel_tx) = slot_timers.remove(&timer)
        {
            let _ = cancel_tx.send(());
        }
    }

    fn stop_timers_not_above(&mut self, not_above: SlotIndex) {
        let mut to_stop = vec![];
        for (slot_index, timers) in &self.armed_timers {
            if *slot_index <= not_above {
                for timer in timers.keys() {
                    to_stop.push((*slot_index, *timer));
                }
            }
        }
        for (slot_index, timer) in to_stop {
            self.stop_timer(slot_index, timer);
        }
    }

    pub fn start(mut self) -> std::thread::JoinHandle<()> {
        thread::spawn(move || {
            loop {
                let msg = self.rx_signal.blocking_recv().unwrap();
                match msg {
                    ControlSignal::TimerExpired(x) => {
                        self.handle_timer_expired(x);
                    }
                    ControlSignal::ControlRequest(x) => {
                        self.handle_request(x);
                    }
                    ControlSignal::EnvelopeValidated(x) => {
                        self.handle_envelope_validated(x);
                    }
                }
            }
        })
    }

    fn handle_envelope_validated(&mut self, x: EnvelopeValidated) {
        slot_span(x.env.statement.slot_index)
            .in_scope(|| self.handle_envelope_validated_in_slot(x));
    }

    fn handle_envelope_validated_in_slot(&mut self, x: EnvelopeValidated) {
        if self
            .handler
            .is_above_highest_externalized(x.env.statement.slot_index)
        {
            for (slot_index, value, level) in x.validated_values.into_iter() {
                self.handler.set_cached_validation(slot_index, value, level);
            }
            self.call_received_envelope(&x.env);
        }
    }

    fn call_received_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
        debug!(
            "---> control kernel calling scp received envelope {}",
            self.kernel.proto().envelope_to_str(env, false),
        );
        if self
            .handler
            .is_above_highest_externalized(env.statement.slot_index)
        {
            self.kernel.proto().received_envelope(env);
            self.flush_timer_switches();
        }
        debug!(
            "<--- control kernel called scp receive envelope {}",
            self.kernel.proto().envelope_to_str(env, false),
        );
    }

    fn handle_timer_expired(&mut self, x: TimerExpired) {
        let height = i64::try_from(x.slot_index).unwrap_or(i64::MAX);
        let span = tracing::info_span!(
            target: "scpd::slot",
            "handle_timer_expired",
            slot_index = height,
            "thruput.block.height" = height
        );
        link_slot(&span, x.slot_index);
        span.in_scope(|| self.handle_timer_expired_in_slot(x));
    }

    fn handle_timer_expired_in_slot(&mut self, x: TimerExpired) {
        debug!("---> timer expired, driver calling back {}", x);
        self.stop_timer(x.slot_index, x.timer);
        if self.handler.is_above_highest_externalized(x.slot_index) {
            self.kernel.proto().driver_calling_back(x.cb.clone());
            self.flush_timer_switches();
        }
        debug!("<--- timer expired, driver called back {}", x);
    }

    fn handle_request(&mut self, req: ControlRequest) {
        let index = match &req {
            ControlRequest::Nominate(index, ..)
            | ControlRequest::StopNomination(index)
            | ControlRequest::SetStateFromEnvelope(index, ..)
            | ControlRequest::SetLowestNonExternalizedSlot(index) => {
                Some(*index)
            }
            ControlRequest::ReceivedEnvelope(env) => {
                Some(env.statement.slot_index)
            }
            _ => None,
        };
        if let Some(index) = index {
            slot_span(index).in_scope(|| self.handle_request_in_slot(req));
        } else {
            self.handle_request_in_slot(req);
        }
    }

    fn handle_request_in_slot(&mut self, req: ControlRequest) {
        match req {
            ControlRequest::Nominate(slot_index, value, prev_value) => {
                if self.handler.is_above_highest_externalized(slot_index) {
                    // pre-register our nominations as fully valid;
                    // necessary because `nominate` calls `process_envelope` on its own envelopes internally
                    self.handler.set_cached_validation(
                        slot_index,
                        value.clone(),
                        ValidationLevel::FullyValid,
                    );
                    let r = self.kernel.proto().nominate(
                        slot_index,
                        &value,
                        &prev_value,
                    );
                    self.flush_timer_switches();
                    self.tx_reply
                        .blocking_send(ControlReply::Nominate(r))
                        .unwrap()
                } else {
                    self.tx_reply
                        .blocking_send(ControlReply::Nominate(false))
                        .unwrap()
                }
            }
            ControlRequest::StopNomination(slot_index) => {
                if self.handler.is_above_highest_externalized(slot_index) {
                    self.kernel.proto().stop_nomination(slot_index);
                    self.flush_timer_switches();
                }
                self.tx_reply
                    .blocking_send(ControlReply::StopNomination())
                    .unwrap()
            }
            ControlRequest::UpdateLocalQuorumSet(qset) => {
                self.kernel.proto().update_local_quorum_set(&qset);
                self.flush_timer_switches();
                self.tx_reply
                    .blocking_send(ControlReply::UpdateLocalQuorumSet())
                    .unwrap()
            }
            ControlRequest::ReceivedEnvelope(env) => {
                debug!(
                    "control kernel received envelope {}",
                    self.kernel.proto().envelope_to_str(&env, false)
                );
                if self
                    .handler
                    .is_above_highest_externalized(env.statement.slot_index)
                    && self.kernel.proto().should_process_envelope(&env)
                {
                    // XXX: if the envelope is coming from us, should we forward it to set_state_from_envelope?

                    let slot_index = env.statement.slot_index;
                    let (nom_values, ballot_values) = StellarProto::<
                        '_,
                        HandleKernel,
                        HandleKernel,
                    >::get_statement_values(
                        &env.statement
                    );

                    // filter non-cached values
                    let validate_nomination_values = nom_values
                        .into_iter()
                        .filter(|value| {
                            self.handler
                                .get_cached_validation(slot_index, value)
                                .is_none()
                        })
                        .collect::<Vec<_>>();
                    let validate_ballot_values = ballot_values
                        .into_iter()
                        .filter(|value| {
                            self.handler
                                .get_cached_validation(slot_index, value)
                                .is_none()
                        })
                        .collect::<Vec<_>>();

                    // XXX: if the envelope is coming from us, should we cache values as fully valid?

                    // skip validate_envelope if no values to validate
                    if validate_nomination_values.is_empty()
                        && validate_ballot_values.is_empty()
                    {
                        self.call_received_envelope(&env);
                    } else {
                        self.tx_validate_envelope
                            .blocking_send(ValidateEnvelope {
                                env,
                                validate_nomination_values,
                                validate_ballot_values,
                            })
                            .unwrap();
                    }
                }
                self.tx_reply
                    .blocking_send(ControlReply::ReceivedEnvelope())
                    .unwrap()
            }
            ControlRequest::SetStateFromEnvelope(slot_index, env) => {
                info!(
                    "control kernel setting state from envelope {}",
                    self.kernel.proto().envelope_to_str(&env, false)
                );
                let local_node_id = self.kernel.proto().get_local_node_id();
                assert_eq!(
                    env.statement.node_id, local_node_id,
                    "set_state_from_envelope requires a local envelope"
                );
                if self.handler.is_above_highest_externalized(slot_index) {
                    // mark all values from our envelopes as fully valid
                    let (nom_values, ballot_values) = StellarProto::<
                        '_,
                        HandleKernel,
                        HandleKernel,
                    >::get_statement_values(
                        &env.statement
                    );

                    for value in nom_values {
                        self.handler.set_cached_validation(
                            slot_index,
                            value,
                            ValidationLevel::FullyValid,
                        );
                    }
                    for value in ballot_values {
                        self.handler.set_cached_validation(
                            slot_index,
                            value,
                            ValidationLevel::FullyValid,
                        );
                    }

                    self.kernel
                        .proto()
                        .set_state_from_envelope(slot_index, &env);
                }
                self.tx_reply
                    .blocking_send(ControlReply::SetStateFromEnvelope())
                    .unwrap()
            }
            ControlRequest::SetKnownQSet(qset) => {
                let optq = self.handler.set_known_qset(qset);
                self.tx_reply
                    .blocking_send(ControlReply::SetKnownQSet(optq))
                    .unwrap()
            }
            ControlRequest::GetKnownQSet(qhash) => {
                let optq = self.handler.get_known_qset(&qhash);
                self.tx_reply
                    .blocking_send(ControlReply::GetKnownQSet(optq))
                    .unwrap()
            }
            ControlRequest::RemoveKnownQSet(qhash) => {
                let optq = self.handler.remove_known_qset(&qhash);
                self.tx_reply
                    .blocking_send(ControlReply::RemoveKnownQSet(optq))
                    .unwrap()
            }
            ControlRequest::SetLowestNonExternalizedSlot(slot_index) => {
                self.handler.set_lowest_non_externalized_slot(slot_index);
                self.tx_reply
                    .blocking_send(ControlReply::SetLowestNonExternalizedSlot())
                    .unwrap()
            }
        }
    }
}