use crate::*;
use serde_json::json;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::mem::discriminant;
use tracing::{debug, error, instrument, trace};
#[derive(Debug)]
pub struct BallotState {
heard_from_quorum: bool,
current: Option<thruput_scp::SCPBallot>, prepared: Option<thruput_scp::SCPBallot>, prepared_prime: Option<thruput_scp::SCPBallot>, high: Option<thruput_scp::SCPBallot>, commit: Option<thruput_scp::SCPBallot>, value_override: Option<thruput_scp::SCPValue>, latest_envelopes: HashMap<thruput_scp::SCPNodeID, thruput_scp::SCPEnvelope>, phase: Phase,
msg_level: i64, timer_exp_count: i64,
last_envelope_gen: Option<thruput_scp::SCPEnvelope>, last_envelope_emit: Option<thruput_scp::SCPEnvelope>, }
impl Default for BallotState {
fn default() -> Self {
BallotState {
heard_from_quorum: false,
current: None,
prepared: None,
prepared_prime: None,
high: None,
commit: None,
value_override: None,
latest_envelopes: HashMap::new(),
phase: Phase::Prepare,
msg_level: 0,
timer_exp_count: 0,
last_envelope_gen: None,
last_envelope_emit: None,
}
}
}
impl BallotState {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Debug)]
pub struct BallotProto<'a, 'b, C: Consensus, D: Driver>(
pub &'a mut SlotProto<'b, C, D>,
);
impl<'a, 'b, C: Consensus, D: Driver> BallotProto<'a, 'b, C, D> {
fn slot_proto_mut(&mut self) -> &mut SlotProto<'b, C, D> {
self.0
}
fn slot_proto(&self) -> &SlotProto<'b, C, D> {
self.0
}
fn ballot_state(&self) -> &BallotState {
self.slot_proto().ballot_state()
}
fn ballot_state_mut(&mut self) -> &mut BallotState {
self.slot_proto_mut().ballot_state_mut()
}
fn driver(&self) -> &D {
self.slot_proto().driver()
}
fn consensus(&self) -> &C {
self.slot_proto().consensus()
}
fn record_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
let node_id = env.statement.node_id.clone();
self.ballot_state_mut()
.latest_envelopes
.insert(node_id, env.clone());
self.slot_proto_mut().record_statement(&env.statement);
}
pub fn is_newer_node_statement(
&self,
node_id: &thruput_scp::SCPNodeID,
st: &thruput_scp::SCPStatement,
) -> bool {
match self.ballot_state().latest_envelopes.get(node_id) {
Some(old) => Self::is_newer_statement(&old.statement, st),
None => true,
}
}
pub fn is_newer_statement(
older: &thruput_scp::SCPStatement,
newer: &thruput_scp::SCPStatement,
) -> bool {
if discriminant(&older.pledges) != discriminant(&newer.pledges) {
older.pledges.stmt_type() < newer.pledges.stmt_type()
} else if newer.pledges.stmt_type()
== thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE
{
false
} else {
match (&older.pledges, &newer.pledges) {
(
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm: older_confirm,
},
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm: newer_confirm,
},
) => match compare_ballots(
&older_confirm.ballot,
&newer_confirm.ballot,
) {
Ordering::Less => true,
Ordering::Equal => {
if older_confirm.n_prepared == newer_confirm.n_prepared
{
older_confirm.n_h < newer_confirm.n_h
} else {
older_confirm.n_prepared < newer_confirm.n_prepared
}
}
Ordering::Greater => false,
},
(
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
prepare: older_prepare,
},
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
prepare: newer_prepare,
},
) => match compare_ballots(
&older_prepare.ballot,
&newer_prepare.ballot,
) {
Ordering::Less => true,
Ordering::Equal => {
match compare_opt_ballots(
&older_prepare.prepared,
&newer_prepare.prepared,
) {
Ordering::Less => true,
Ordering::Equal => match compare_opt_ballots(
&older_prepare.prepared_prime,
&newer_prepare.prepared_prime,
) {
Ordering::Less => true,
Ordering::Equal => {
older_prepare.n_h < newer_prepare.n_h
}
Ordering::Greater => false,
},
Ordering::Greater => false,
}
}
Ordering::Greater => false,
},
_ => panic!(),
}
}
}
pub fn get_statement_values(
st: &thruput_scp::SCPStatement,
) -> HashSet<thruput_scp::SCPValue> {
let mut values = HashSet::new();
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
let b = &prepare.ballot;
if b.counter != 0 {
values.insert(prepare.ballot.value.clone());
}
if let Some(prepared) = &prepare.prepared {
values.insert(prepared.value.clone());
}
if let Some(prepared_prime) = &prepare.prepared_prime {
values.insert(prepared_prime.value.clone());
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
values.insert(confirm.ballot.value.clone());
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
values.insert(externalize.commit.value.clone());
}
_ => panic!("bug"),
}
values
}
fn check_valid(
ballot_proto: &BallotProto<'a, 'b, C, D>,
statement: &thruput_scp::SCPStatement,
ours: bool,
env: &thruput_scp::SCPEnvelope,
) -> EnvelopeState {
if !ballot_proto.is_statement_sane(statement, ours) {
if ours {
error!(env = ?env, "not sane statement from self, skipping e: {}", ballot_proto.0.cd.envelope_to_str(env, false));
}
return EnvelopeState::Invalid;
}
if !ballot_proto.is_newer_node_statement(&statement.node_id, statement)
{
if ours {
error!(env = ?env, "stale statement from self, skipping e: {}", ballot_proto.0.cd.envelope_to_str(env, false))
} else {
trace!(
slot_index = ballot_proto.slot_proto().index(),
"stale statement, skipping"
)
}
return EnvelopeState::Invalid;
}
EnvelopeState::Valid
}
pub fn should_process_envelope(
&self,
env: &thruput_scp::SCPEnvelope,
ours: bool,
) -> bool {
assert!(env.statement.slot_index == self.slot_proto().index());
let statement = &env.statement;
!matches!(
Self::check_valid(self, statement, ours, env),
EnvelopeState::Invalid
)
}
#[instrument(skip_all, name = "ballot.process_envelope", fields(slot_index = i64::try_from(env.statement.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(env.statement.slot_index).unwrap_or(i64::MAX)))]
pub fn process_envelope(
&mut self,
env: &thruput_scp::SCPEnvelope,
ours: bool,
) -> EnvelopeState {
assert!(env.statement.slot_index == self.slot_proto().index());
let statement = &env.statement;
if let EnvelopeState::Invalid =
Self::check_valid(self, statement, ours, env)
{
return EnvelopeState::Invalid;
}
let validation_result = self.validate_values(statement);
if validation_result == ValidationLevel::Invalid {
if ours {
error!(env = ?env, "invalid value from self, skipping e: {}", self.0.cd.envelope_to_str(env, false))
} else {
trace!(slot_index = self.slot_proto().index(), "invalid value")
}
return EnvelopeState::Invalid;
}
if let EnvelopeState::Invalid =
Self::check_valid(self, statement, ours, env)
{
return EnvelopeState::Invalid;
}
if !matches!(self.ballot_state().phase, Phase::Externalize) {
if let ValidationLevel::MaybeValid = validation_result {
self.slot_proto_mut().set_fully_validated(false);
}
self.record_envelope(env);
self.advance_slot(statement);
return EnvelopeState::Valid;
}
match &self.ballot_state().commit {
Some(c) => {
if c.value == Self::get_working_ballot(statement).value {
self.record_envelope(env);
return EnvelopeState::Valid;
}
}
_ => unreachable!(),
}
if ours {
error!(env = ?env, "externalize statement with invalid value from self, skipping e: {}", self.0.cd.envelope_to_str(env, false));
}
EnvelopeState::Invalid
}
pub fn is_statement_sane(
&self,
statement: &thruput_scp::SCPStatement,
ours: bool,
) -> bool {
match &self.slot_proto().get_quorum_set_from_statement(statement) {
Some(qset) => {
if let Result::Err(e) = is_qset_sane(qset, false) {
debug!(err = ?e, "invalid quorum set received");
return false;
}
}
None => {
debug!(statement = ?statement, "unknown quorum set");
return false;
}
}
match &statement.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
if !(ours || prepare.ballot.counter > 0) {
trace!(statement = ?statement, "malformed PREPARE message");
return false;
}
if let (Some(pp), Some(p)) =
(&prepare.prepared_prime, &prepare.prepared)
&& !are_ballots_less_and_incompatible(pp, p)
{
trace!(statement = ?statement, "malformed PREPARE message");
return false;
}
if prepare.n_h != 0 {
match &prepare.prepared {
Some(p) => {
if prepare.n_h > p.counter {
trace!(statement = ?statement, "malformed PREPARE message");
return false;
}
}
_ => {
trace!(statement = ?statement, "malformed PREPARE message");
return false;
}
}
}
if prepare.n_c != 0
&& !(prepare.n_h != 0
&& prepare.ballot.counter >= prepare.n_h
&& prepare.n_h >= prepare.n_c)
{
trace!(statement = ?statement, "malformed PREPARE message");
return false;
}
true
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
if confirm.ballot.counter == 0 {
trace!(statement = ?statement, "malformed CONFIRM message");
return false;
}
if confirm.n_h > confirm.ballot.counter {
trace!(statement = ?statement, "malformed CONFIRM message");
return false;
}
if confirm.n_commit > confirm.n_h {
trace!(statement = ?statement, "malformed CONFIRM message");
return false;
}
true
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
if externalize.commit.counter == 0 {
trace!(statement = ?statement, "malformed EXTERNALIZE message");
return false;
}
if externalize.n_h < externalize.commit.counter {
trace!(statement = ?statement, "malformed EXTERNALIZE message");
return false;
}
true
}
thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
nominate: _,
} => {
panic!("unreachable");
}
_ => panic!("unreachable"),
}
}
#[instrument(skip_all, fields(slot_index = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), ballot_counter = i64::from(n)))]
pub fn abandon_ballot(&mut self, n: u32) -> bool {
trace!("abandoning ballot");
let v = match self.slot_proto_mut().get_latest_composite_candidate() {
Some(w) => {
if w.is_empty() {
self.ballot_state()
.current
.as_ref()
.map(|cv| cv.value.clone())
} else {
Some(w.clone())
}
}
None => self
.ballot_state()
.current
.as_ref()
.map(|cv| cv.value.clone()),
};
match v {
Some(w) => {
if w.is_empty() {
false
} else if n == 0 {
self.bump_state(w, true)
} else {
self.bump_state_n(w, n)
}
}
None => false,
}
}
#[instrument(skip_all)]
pub fn bump_state(
&mut self,
value: thruput_scp::SCPValue,
force: bool,
) -> bool {
let n = match &self.ballot_state().current {
Some(b) => {
if !force {
return false;
}
b.counter + 1
}
None => 1,
};
self.bump_state_n(value, n)
}
fn bump_state_n(&mut self, value: thruput_scp::SCPValue, n: u32) -> bool {
match self.ballot_state().phase {
Phase::Prepare | Phase::Confirm => {
let newv = match &self.ballot_state().value_override {
Some(v) => v.clone(),
None => value,
};
let newb = thruput_scp::SCPBallot {
counter: n,
value: newv,
};
trace!(
slot_index = self.slot_proto().index(),
ballot = ?newb,
"ballot protocol bump state"
);
let updated = self.update_current_value(newb);
if updated {
self.emit_current_state_statement();
self.check_heard_from_quorum();
};
updated
}
Phase::Externalize | Phase::Num => false,
}
}
#[instrument(skip_all, fields(slot_index = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), ballot_counter = i64::from(new_ballot.counter)))]
fn update_current_value(
&mut self,
new_ballot: thruput_scp::SCPBallot,
) -> bool {
if self.ballot_state().phase != Phase::Prepare
&& self.ballot_state().phase != Phase::Confirm
{
return false;
};
let updated = match &self.ballot_state().current {
None => {
self.bump_to_ballot(new_ballot, true);
true
}
Some(current) => {
assert!(
compare_ballots(current, &new_ballot) != Ordering::Greater
);
if let Some(commit) = &self.ballot_state().commit
&& !are_ballots_compatible(commit, &new_ballot)
{
return false;
}
match compare_ballots(current, &new_ballot) {
Ordering::Less => {
self.bump_to_ballot(new_ballot, true);
true
}
Ordering::Equal => false,
Ordering::Greater => {
error!(
"ballot protocol update_current_value attempt to bump to a smaller value"
);
return false;
}
}
}
};
self.check_invariants();
updated
}
#[instrument(
skip_all,
fields(slot_index = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(self.slot_proto().index()).unwrap_or(i64::MAX), ballot_counter = i64::from(ballot.counter))
)]
fn bump_to_ballot(&mut self, ballot: thruput_scp::SCPBallot, check: bool) {
trace!(
slot_index = self.slot_proto().index(),
ballot = ?ballot,
"ballot proto bump_to_ballot"
);
assert!(self.ballot_state().phase != Phase::Externalize);
if check && let Some(current) = &self.ballot_state().current {
assert!(compare_ballots(&ballot, current) != Ordering::Less);
}
let got_bumped = match &self.ballot_state().current {
Some(current) => current.counter != ballot.counter,
None => true,
};
if self.ballot_state().current.is_none() {
self.slot_proto()
.cd
.consensus
.started_ballot_proto(self.slot_proto().index(), &ballot);
}
self.ballot_state_mut().current = Some(ballot);
if let Some(high) = &self.ballot_state().high
&& !are_ballots_compatible(
self.ballot_state().current.as_ref().unwrap(),
high,
)
{
self.ballot_state_mut().high = None;
self.ballot_state_mut().commit = None;
}
if got_bumped {
self.ballot_state_mut().heard_from_quorum = false;
}
}
fn start_timer(&mut self) {
let driver = &self.slot_proto().cd.driver;
let timeout = driver.compute_timeout(
self.ballot_state().current.as_ref().unwrap().counter,
false,
);
let slot_index = self.slot_proto().index();
driver.start_timer(
slot_index,
Timer::Ballot,
timeout,
DriverCallback::BallotTimerExpired { slot_index },
);
}
fn stop_timer(&mut self) {
let driver = &self.slot_proto().cd.driver;
driver.stop_timer(self.slot_proto().index(), Timer::Ballot);
}
pub fn driver_calling_back(&mut self, cb: DriverCallback) {
if let DriverCallback::BallotTimerExpired { slot_index: _ } = cb {
self.timer_expired();
}
}
pub fn timer_expired(&mut self) {
self.ballot_state_mut().timer_exp_count += 1;
self.abandon_ballot(0);
}
#[instrument(skip_all)]
fn create_statement(
&self,
typ: thruput_scp::SCPStatementType,
) -> thruput_scp::SCPStatement {
self.check_invariants();
let pledges = match typ {
thruput_scp::SCPStatementType::SCP_ST_PREPARE => {
let mut prepare = thruput_scp::SCPStatementPrepare {
quorum_set_hash: *self
.slot_proto()
.local_proto()
.get_qset_hash(),
ballot: thruput_scp::SCPBallot {
counter: 0,
value: Default::default(),
},
prepared: None,
prepared_prime: None,
n_c: 0,
n_h: 0,
};
if let Some(ref current) = self.ballot_state().current {
prepare.ballot = current.clone();
}
if let Some(ref commit) = self.ballot_state().commit {
prepare.n_c = commit.counter;
}
if let Some(ref prepared) = self.ballot_state().prepared {
prepare.prepared = Some(prepared.clone());
}
if let Some(ref prepared_prime) =
self.ballot_state().prepared_prime
{
prepare.prepared_prime = Some(prepared_prime.clone());
}
if let Some(ref high) = self.ballot_state().high {
prepare.n_h = high.counter;
}
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare }
}
thruput_scp::SCPStatementType::SCP_ST_CONFIRM => {
let confirm = thruput_scp::SCPStatementConfirm {
ballot: self
.ballot_state()
.current
.as_ref()
.unwrap()
.clone(),
n_prepared: self
.ballot_state()
.prepared
.as_ref()
.unwrap()
.counter,
n_commit: self
.ballot_state()
.commit
.as_ref()
.unwrap()
.counter,
n_h: self.ballot_state().high.as_ref().unwrap().counter,
quorum_set_hash: *self
.slot_proto()
.local_proto()
.get_qset_hash(),
};
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm }
}
thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE => {
let externalize = thruput_scp::SCPStatementExternalize {
commit: self
.ballot_state()
.commit
.as_ref()
.unwrap()
.clone(),
n_h: self.ballot_state().high.as_ref().unwrap().counter,
commit_quorum_set_hash: *self
.slot_proto()
.local_proto()
.get_qset_hash(),
};
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
}
}
thruput_scp::SCPStatementType::SCP_ST_NOMINATE => {
panic!(
"create_statement should not be called with SCP_ST_NOMINATE"
);
}
_ => panic!("unreachable"),
};
thruput_scp::SCPStatement {
node_id: self.slot_proto().local_proto().get_node_id().clone(),
slot_index: self.slot_proto().index(),
pledges,
}
}
#[instrument(skip_all)]
fn send_latest_envelope(&mut self) {
if self.ballot_state().msg_level == 0
&& self.slot_proto().is_fully_validated()
{
let driver = &self.slot_proto().cd.driver;
let ballot_mut = self.ballot_state_mut();
if let Some(last_gen) = &ballot_mut.last_envelope_gen {
let should_emit = match &ballot_mut.last_envelope_emit {
None => true,
Some(last_emit) => last_gen != last_emit,
};
if should_emit {
ballot_mut.last_envelope_emit = Some(last_gen.clone());
driver.emit_envelope(last_gen.clone());
}
}
}
}
#[instrument(skip_all)]
fn emit_current_state_statement(&mut self) {
let statement_type = match self.ballot_state().phase {
Phase::Prepare => thruput_scp::SCPStatementType::SCP_ST_PREPARE,
Phase::Confirm => thruput_scp::SCPStatementType::SCP_ST_CONFIRM,
Phase::Externalize => {
thruput_scp::SCPStatementType::SCP_ST_EXTERNALIZE
}
Phase::Num => panic!("bug"),
};
let statement = self.create_statement(statement_type);
let envelope = self.slot_proto_mut().create_envelope(statement);
let can_emit = self.ballot_state().current.is_some();
let local_proto = self.slot_proto().local_proto();
let local_node_id = local_proto.get_node_id();
let last_env = self.ballot_state().latest_envelopes.get(local_node_id);
let should_process = match last_env {
None => true,
Some(last_envelope) => last_envelope != &envelope,
};
if should_process {
let envelope_state = self.process_envelope(&envelope, true);
if envelope_state == EnvelopeState::Valid {
let should_emit = can_emit && {
match &self.ballot_state().last_envelope_gen {
None => true,
Some(last_gen) => Self::is_newer_statement(
&last_gen.statement,
&envelope.statement,
),
}
};
if should_emit {
self.ballot_state_mut().last_envelope_gen =
Some(envelope.clone());
self.send_latest_envelope();
}
} else {
error!(env = ?envelope, "ballot moved to a bad state, due to envelope: {}",
self.0.cd.envelope_to_str(&envelope, false));
panic!("moved to a bad state (ballot protocol)");
}
}
}
#[instrument(skip_all)]
fn get_prepare_candidates(
&self,
hint: &thruput_scp::SCPStatement,
) -> HashSet<thruput_scp::SCPBallot> {
let mut hint_ballots = HashSet::new();
match &hint.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
hint_ballots.insert(prepare.ballot.clone());
if let Some(ref prepared) = prepare.prepared {
hint_ballots.insert(prepared.clone());
}
if let Some(ref prepared_prime) = prepare.prepared_prime {
hint_ballots.insert(prepared_prime.clone());
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
hint_ballots.insert(thruput_scp::SCPBallot {
counter: confirm.n_prepared,
value: confirm.ballot.value.clone(),
});
hint_ballots.insert(thruput_scp::SCPBallot {
counter: u32::MAX,
value: confirm.ballot.value.clone(),
});
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
hint_ballots.insert(thruput_scp::SCPBallot {
counter: u32::MAX,
value: externalize.commit.value.clone(),
});
}
thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
panic!(
"getPrepareCandidates should not be called with SCP_ST_NOMINATE"
);
}
_ => panic!("unreachable"),
}
let mut candidates = HashSet::new();
while !hint_ballots.is_empty() {
let top_vote = hint_ballots
.iter()
.max_by(|a, b| compare_ballots(a, b))
.unwrap()
.clone();
hint_ballots.remove(&top_vote);
let val = &top_vote.value;
for envelope in self.ballot_state().latest_envelopes.values() {
match &envelope.statement.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
prepare,
} => {
if are_ballots_less_and_compatible(
&prepare.ballot,
&top_vote,
) {
candidates.insert(prepare.ballot.clone());
}
if let Some(ref prepared) = prepare.prepared
&& are_ballots_less_and_compatible(
prepared, &top_vote,
)
{
candidates.insert(prepared.clone());
}
if let Some(ref prepared_prime) = prepare.prepared_prime
&& are_ballots_less_and_compatible(
prepared_prime,
&top_vote,
)
{
candidates.insert(prepared_prime.clone());
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm,
} => {
if are_ballots_compatible(&top_vote, &confirm.ballot) {
candidates.insert(top_vote.clone());
if confirm.n_prepared < top_vote.counter {
candidates.insert(thruput_scp::SCPBallot {
counter: confirm.n_prepared,
value: val.clone(),
});
}
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
if are_ballots_compatible(
&top_vote,
&externalize.commit,
) {
candidates.insert(top_vote.clone());
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE {
..
} => {
panic!("bug");
}
_ => panic!("unreachable"),
}
}
}
candidates
}
fn update_current_if_needed(&mut self, h: &thruput_scp::SCPBallot) -> bool {
let should_update = match &self.ballot_state().current {
None => true,
Some(current) => compare_ballots(current, h) == Ordering::Less,
};
if should_update {
self.bump_to_ballot(h.clone(), true);
true
} else {
false
}
}
fn has_prepared_ballot(
ballot: &thruput_scp::SCPBallot,
st: &thruput_scp::SCPStatement,
) -> bool {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
let prepared_check = prepare
.prepared
.as_ref()
.map(|p| are_ballots_less_and_compatible(ballot, p))
.unwrap_or(false);
let prepared_prime_check = prepare
.prepared_prime
.as_ref()
.map(|pp| are_ballots_less_and_compatible(ballot, pp))
.unwrap_or(false);
prepared_check || prepared_prime_check
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
let prepared = thruput_scp::SCPBallot {
counter: confirm.n_prepared,
value: confirm.ballot.value.clone(),
};
are_ballots_less_and_compatible(ballot, &prepared)
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => are_ballots_compatible(ballot, &externalize.commit),
thruput_scp::SCPStatement_pledges::SCP_ST_NOMINATE { .. } => {
panic!("bug");
}
_ => panic!("unreachable"),
}
}
#[instrument(skip(self, voted, accepted))]
fn federated_accept<F1, F2>(&self, voted: &F1, accepted: &F2) -> bool
where
F1: Fn(&thruput_scp::SCPStatement) -> bool,
F2: Fn(&thruput_scp::SCPStatement) -> bool,
{
self.slot_proto().federated_accept(
voted,
accepted,
&self.ballot_state().latest_envelopes,
)
}
fn set_accept_prepared(&mut self, ballot: &thruput_scp::SCPBallot) -> bool {
trace!(
slot_index = self.slot_proto().index(),
ballot = ?ballot,
"ballot proto set_accept_prepared"
);
let mut did_work = self.set_prepared(ballot.clone());
if let (Some(_commit), Some(high)) =
(&self.ballot_state().commit, &self.ballot_state().high)
{
let should_clear_commit =
if let Some(prepared) = &self.ballot_state().prepared {
are_ballots_less_and_incompatible(high, prepared)
} else {
false
} || if let Some(prepared_prime) =
&self.ballot_state().prepared_prime
{
are_ballots_less_and_incompatible(high, prepared_prime)
} else {
false
};
if should_clear_commit {
assert_eq!(self.ballot_state().phase, Phase::Prepare);
self.ballot_state_mut().commit = None;
did_work = true;
}
}
if did_work {
self.consensus()
.accepted_ballot_prepared(self.slot_proto().index(), ballot);
self.emit_current_state_statement();
}
did_work
}
fn set_prepared(&mut self, ballot: thruput_scp::SCPBallot) -> bool {
let mut did_work = false;
if let Some(ref prepared) = self.ballot_state().prepared {
match compare_ballots(prepared, &ballot) {
Ordering::Less => {
if !are_ballots_compatible(prepared, &ballot) {
self.ballot_state_mut().prepared_prime =
Some(prepared.clone());
}
self.ballot_state_mut().prepared = Some(ballot);
did_work = true;
}
Ordering::Greater => {
let should_update_prime = match &self
.ballot_state()
.prepared_prime
{
None => true,
Some(prepared_prime) => {
compare_ballots(prepared_prime, &ballot)
== Ordering::Less
&& !are_ballots_compatible(prepared, &ballot)
}
};
if should_update_prime {
self.ballot_state_mut().prepared_prime = Some(ballot);
did_work = true;
}
}
Ordering::Equal => {
}
}
} else {
self.ballot_state_mut().prepared = Some(ballot);
did_work = true;
}
did_work
}
#[instrument(skip(self, voted))]
fn federated_ratify<F>(&self, voted: F) -> bool
where
F: Fn(&thruput_scp::SCPStatement) -> bool,
{
self.slot_proto()
.federated_ratify(&voted, &self.ballot_state().latest_envelopes)
}
#[instrument(skip_all)]
fn set_confirm_prepared(
&mut self,
new_c: &thruput_scp::SCPBallot,
new_h: &thruput_scp::SCPBallot,
) -> bool {
trace!(
slot_index = self.slot_proto().index(),
new_h = ?new_h,
"ballot proto set_confirm_prepared"
);
let mut did_work = false;
self.ballot_state_mut().value_override = Some(new_h.value.clone());
let should_update = match &self.ballot_state().current {
None => true,
Some(current) => are_ballots_compatible(current, new_h),
};
if should_update {
if let Some(ref high) = self.ballot_state().high {
if compare_ballots(new_h, high) == Ordering::Greater {
did_work = true;
self.ballot_state_mut().high = Some(new_h.clone());
}
} else {
did_work = true;
self.ballot_state_mut().high = Some(new_h.clone());
}
if new_c.counter != 0 {
assert!(self.ballot_state().commit.is_none());
self.ballot_state_mut().commit = Some(new_c.clone());
did_work = true;
}
if did_work {
self.consensus().confirmed_ballot_prepared(
self.slot_proto().index(),
new_h,
);
}
}
let current_updated = self.update_current_if_needed(new_h);
did_work = current_updated || did_work;
if did_work {
self.emit_current_state_statement();
}
did_work
}
fn attempt_confirm_prepared(
&mut self,
hint: &thruput_scp::SCPStatement,
) -> bool {
if self.ballot_state().phase != Phase::Prepare {
return false;
}
if self.ballot_state().prepared.is_none() {
return false;
}
let candidates = self.get_prepare_candidates(hint);
let mut new_h: Option<thruput_scp::SCPBallot> = None;
let mut sorted_candidates: Vec<_> = candidates.into_iter().collect();
sorted_candidates.sort_by(|a, b| compare_ballots(b, a));
let mut iter = sorted_candidates.iter();
let mut cur = iter.next();
while cur.is_some() {
let ballot = cur.unwrap();
if let Some(ref high) = self.ballot_state().high
&& compare_ballots(high, ballot) != Ordering::Less
{
break;
}
let ratified = self.federated_ratify(
|st: &thruput_scp::SCPStatement| -> bool {
Self::has_prepared_ballot(ballot, st)
},
);
if ratified {
new_h = Some(ballot.clone());
break;
}
cur = iter.next();
}
if let Some(new_h_ballot) = new_h {
let mut new_c = thruput_scp::SCPBallot {
counter: 0,
value: Default::default(),
};
let current = match &self.ballot_state().current {
Some(b) => b,
None => &thruput_scp::SCPBallot {
counter: 0,
value: Default::default(),
},
};
let should_find_commit = self.ballot_state().commit.is_none()
&& (self
.ballot_state()
.prepared
.as_ref()
.map(|p| {
!are_ballots_less_and_incompatible(&new_h_ballot, p)
})
.unwrap_or(true))
&& (self
.ballot_state()
.prepared_prime
.as_ref()
.map(|pp| {
!are_ballots_less_and_incompatible(&new_h_ballot, pp)
})
.unwrap_or(true));
if should_find_commit {
while cur.is_some() {
let ballot = cur.unwrap();
cur = iter.next();
if compare_ballots(ballot, current) == Ordering::Less {
break;
}
if !are_ballots_less_and_compatible(ballot, &new_h_ballot) {
continue;
}
let ratified = self.federated_ratify(
|st: &thruput_scp::SCPStatement| -> bool {
Self::has_prepared_ballot(ballot, st)
},
);
if ratified {
new_c = ballot.clone();
} else {
break;
}
}
}
return self.set_confirm_prepared(&new_c, &new_h_ballot);
}
false
}
#[instrument(skip_all)]
fn check_heard_from_quorum(&mut self) {
if let Some(current_ballot) = &self.ballot_state().current.clone() {
let is_quorum = LocalProto::<C, D>::is_quorum(
self.slot_proto().local_proto().get_qset(),
&self.ballot_state().latest_envelopes,
&|st: &thruput_scp::SCPStatement| -> Option<thruput_scp::SCPQuorumSet> {
self.slot_proto().get_quorum_set_from_statement(st)
},
&|st: &thruput_scp::SCPStatement| -> bool {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
current_ballot.counter <= prepare.ballot.counter
}
_ => true,
}
},
);
if is_quorum {
let old_hq = self.ballot_state().heard_from_quorum;
self.ballot_state_mut().heard_from_quorum = true;
if !old_hq {
self.consensus().ballot_did_hear_from_quorum(
self.slot_proto().index(),
current_ballot,
);
if self.ballot_state().phase != Phase::Externalize {
self.start_timer();
}
}
if self.ballot_state().phase == Phase::Externalize {
self.stop_timer();
}
} else {
self.ballot_state_mut().heard_from_quorum = false;
self.stop_timer();
}
}
}
fn check_invariants(&self) {
match self.ballot_state().phase {
Phase::Prepare => {}
Phase::Confirm | Phase::Externalize => {
assert!(self.ballot_state().current.is_some());
assert!(self.ballot_state().prepared.is_some());
assert!(self.ballot_state().commit.is_some());
assert!(self.ballot_state().high.is_some());
}
Phase::Num => {
panic!("bug");
}
}
if let Some(current) = &self.ballot_state().current {
assert!(current.counter != 0);
}
if let (Some(prepared_prime), Some(prepared)) = (
&self.ballot_state().prepared_prime,
&self.ballot_state().prepared,
) {
assert!(are_ballots_less_and_incompatible(
prepared_prime,
prepared
));
}
if let Some(high) = &self.ballot_state().high {
assert!(self.ballot_state().current.is_some(),);
assert!(are_ballots_less_and_compatible(
high,
self.ballot_state().current.as_ref().unwrap()
),);
}
if let Some(commit) = &self.ballot_state().commit {
assert!(self.ballot_state().current.is_some());
assert!(self.ballot_state().high.is_some());
let high = self.ballot_state().high.as_ref().unwrap();
let current = self.ballot_state().current.as_ref().unwrap();
assert!(are_ballots_less_and_compatible(commit, high));
assert!(are_ballots_less_and_compatible(high, current));
}
}
#[instrument(skip_all)]
fn attempt_accept_prepared(
&mut self,
hint: &thruput_scp::SCPStatement,
) -> bool {
if self.ballot_state().phase != Phase::Prepare
&& self.ballot_state().phase != Phase::Confirm
{
return false;
}
let candidates = self.get_prepare_candidates(hint);
let mut sorted_candidates: Vec<_> = candidates.into_iter().collect();
sorted_candidates.sort_by(|a, b| compare_ballots(b, a));
for ballot in sorted_candidates {
if self.ballot_state().phase == Phase::Confirm {
if !are_ballots_less_and_compatible(
self.ballot_state().prepared.as_ref().unwrap(),
&ballot,
) {
continue;
}
assert!(are_ballots_compatible(
self.ballot_state().commit.as_ref().unwrap(),
&ballot
));
}
if let Some(ref prepared_prime) = self.ballot_state().prepared_prime
&& compare_ballots(&ballot, prepared_prime) != Ordering::Greater
{
continue;
}
if let Some(ref prepared) = self.ballot_state().prepared {
if are_ballots_less_and_compatible(&ballot, prepared) {
continue;
}
}
let accepted = self.federated_accept(
&|st: &thruput_scp::SCPStatement| -> bool {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
are_ballots_less_and_compatible(&ballot, &prepare.ballot)
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
are_ballots_compatible(&ballot, &confirm.ballot)
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { externalize } => {
are_ballots_compatible(&ballot, &externalize.commit)
}
_ => panic!("bug"),
}
},
&|st: &thruput_scp::SCPStatement| -> bool { Self::has_prepared_ballot(&ballot, st) },
);
if accepted {
return self.set_accept_prepared(&ballot);
}
}
false
}
fn commit_predicate(
ballot: &thruput_scp::SCPBallot,
check: &Interval,
st: &thruput_scp::SCPStatement,
) -> bool {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { .. } => false,
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
if are_ballots_compatible(ballot, &confirm.ballot) {
confirm.n_commit <= check.lo && check.hi <= confirm.n_h
} else {
false
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
if are_ballots_compatible(ballot, &externalize.commit) {
externalize.commit.counter <= check.lo
} else {
false
}
}
_ => panic!("bug"),
}
}
fn find_extended_interval<F>(
candidate: &mut Interval,
boundaries: &HashSet<thruput_scp::SCPCount>,
pred: F,
) where
F: Fn(&Interval) -> bool,
{
let mut sorted_boundaries: Vec<thruput_scp::SCPCount> =
boundaries.iter().copied().collect();
sorted_boundaries.sort();
for &b in sorted_boundaries.iter().rev() {
let cur = if candidate.lo == 0 {
Interval { lo: b, hi: b }
} else if b > candidate.hi {
continue;
} else {
Interval {
lo: b,
hi: candidate.hi,
}
};
if pred(&cur) {
*candidate = cur;
} else if candidate.lo != 0 {
break;
}
}
}
fn get_commit_boundaries_from_statements(
&self,
ballot: &thruput_scp::SCPBallot,
) -> HashSet<thruput_scp::SCPCount> {
let mut res = HashSet::new();
for envelope in self.ballot_state().latest_envelopes.values() {
match &envelope.statement.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
prepare,
} => {
if are_ballots_compatible(ballot, &prepare.ballot)
&& prepare.n_c != 0
{
res.insert(prepare.n_c);
res.insert(prepare.n_h);
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm,
} => {
if are_ballots_compatible(ballot, &confirm.ballot) {
res.insert(confirm.n_commit);
res.insert(confirm.n_h);
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
if are_ballots_compatible(ballot, &externalize.commit) {
res.insert(externalize.commit.counter);
res.insert(externalize.n_h);
res.insert(u32::MAX);
}
}
_ => panic!("bug"),
}
}
res
}
#[instrument(skip_all)]
fn set_accept_commit(
&mut self,
c: &thruput_scp::SCPBallot,
h: &thruput_scp::SCPBallot,
) -> bool {
trace!(
slot_index = self.slot_proto().index(),
c = ?c,
h = ?h,
"ballot proto set_accept_commit"
);
let mut did_work = false;
self.ballot_state_mut().value_override = Some(h.value.clone());
let high_changed = match &self.ballot_state().high {
None => true,
Some(current_high) => {
compare_ballots(current_high, h) != Ordering::Equal
}
};
let commit_changed = match &self.ballot_state().commit {
None => true,
Some(current_commit) => {
compare_ballots(current_commit, c) != Ordering::Equal
}
};
if high_changed || commit_changed {
self.ballot_state_mut().commit = Some(c.clone());
self.ballot_state_mut().high = Some(h.clone());
did_work = true;
}
if self.ballot_state().phase == Phase::Prepare {
self.ballot_state_mut().phase = Phase::Confirm;
if let Some(current) = &self.ballot_state().current
&& !are_ballots_less_and_compatible(h, current)
{
self.bump_to_ballot(h.clone(), false);
}
self.ballot_state_mut().prepared_prime = None;
did_work = true;
}
if did_work {
self.update_current_if_needed(
&self.ballot_state().high.as_ref().unwrap().clone(),
);
self.consensus()
.accepted_commit(self.slot_proto().index(), h);
self.emit_current_state_statement();
}
did_work
}
#[instrument(skip_all)]
fn attempt_accept_commit(
&mut self,
hint: &thruput_scp::SCPStatement,
) -> bool {
if self.ballot_state().phase != Phase::Prepare
&& self.ballot_state().phase != Phase::Confirm
{
return false;
}
let ballot = match &hint.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
if prepare.n_c != 0 {
thruput_scp::SCPBallot {
counter: prepare.n_h,
value: prepare.ballot.value.clone(),
}
} else {
return false;
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
thruput_scp::SCPBallot {
counter: confirm.n_h,
value: confirm.ballot.value.clone(),
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => thruput_scp::SCPBallot {
counter: externalize.n_h,
value: externalize.commit.value.clone(),
},
_ => panic!("bug"),
};
if self.ballot_state().phase == Phase::Confirm
&& !are_ballots_compatible(
&ballot,
self.ballot_state().high.as_ref().unwrap(),
)
{
return false;
}
let pred = |cur: &Interval| -> bool {
self.federated_accept(
&|st: &thruput_scp::SCPStatement| -> bool {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
are_ballots_compatible(&ballot, &prepare.ballot)
&& prepare.n_c != 0
&& prepare.n_c <= cur.lo
&& cur.hi <= prepare.n_h
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
if are_ballots_compatible(&ballot, &confirm.ballot) {
confirm.n_commit <= cur.lo
} else {
false
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { externalize } => {
if are_ballots_compatible(&ballot, &externalize.commit) {
externalize.commit.counter <= cur.lo
} else {
false
}
}
_ => panic!("bug"),
}
},
&|st: &thruput_scp::SCPStatement| -> bool {
Self::commit_predicate(&ballot, cur, st)
},
)
};
let boundaries = self.get_commit_boundaries_from_statements(&ballot);
if boundaries.is_empty() {
return false;
}
let mut candidate = Interval { lo: 0, hi: 0 };
Self::find_extended_interval(&mut candidate, &boundaries, pred);
if candidate.lo != 0
&& (self.ballot_state().phase != Phase::Confirm
|| candidate.hi
> self.ballot_state().high.as_ref().unwrap().counter)
{
let c = thruput_scp::SCPBallot {
counter: candidate.lo,
value: ballot.value.clone(),
};
let h = thruput_scp::SCPBallot {
counter: candidate.hi,
value: ballot.value.clone(),
};
return self.set_accept_commit(&c, &h);
}
false
}
#[instrument(skip_all)]
fn attempt_bump(&mut self) -> bool {
if self.ballot_state().phase == Phase::Prepare
|| self.ballot_state().phase == Phase::Confirm
{
let local_counter = match &self.ballot_state().current {
Some(current) => current.counter,
None => 0,
};
if !has_v_blocking_subset_strictly_ahead_of(
&self.slot_proto().local_proto(),
&self.ballot_state().latest_envelopes,
local_counter,
) {
return false;
}
let mut all_counters = HashSet::new();
for envelope in self.ballot_state().latest_envelopes.values() {
let c = statement_ballot_counter(&envelope.statement);
if c > local_counter {
all_counters.insert(c);
}
}
let mut all_counters_sorted: Vec<thruput_scp::SCPCount> =
all_counters.into_iter().collect();
all_counters_sorted.sort();
for n in all_counters_sorted {
if !has_v_blocking_subset_strictly_ahead_of(
&self.slot_proto().local_proto(),
&self.ballot_state().latest_envelopes,
n,
) {
return self.abandon_ballot(n);
}
}
}
false
}
#[instrument(skip_all)]
fn attempt_confirm_commit(
&mut self,
hint: &thruput_scp::SCPStatement,
) -> bool {
if self.ballot_state().phase != Phase::Confirm {
return false;
}
if self.ballot_state().high.is_none()
|| self.ballot_state().commit.is_none()
{
return false;
}
let ballot = match &hint.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { .. } => {
return false;
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
thruput_scp::SCPBallot {
counter: confirm.n_h,
value: confirm.ballot.value.clone(),
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => thruput_scp::SCPBallot {
counter: externalize.n_h,
value: externalize.commit.value.clone(),
},
_ => panic!("bug"),
};
if !are_ballots_compatible(
&ballot,
self.ballot_state().commit.as_ref().unwrap(),
) {
return false;
}
let boundaries = self.get_commit_boundaries_from_statements(&ballot);
let mut candidate = Interval { lo: 0, hi: 0 };
let pred = |cur: &Interval| -> bool {
self.federated_ratify(|st: &thruput_scp::SCPStatement| -> bool {
Self::commit_predicate(&ballot, cur, st)
})
};
Self::find_extended_interval(&mut candidate, &boundaries, pred);
if candidate.lo != 0 {
let c = thruput_scp::SCPBallot {
counter: candidate.lo,
value: ballot.value.clone(),
};
let h = thruput_scp::SCPBallot {
counter: candidate.hi,
value: ballot.value.clone(),
};
return self.set_confirm_commit(&c, &h);
}
false
}
#[instrument(skip_all)]
fn set_confirm_commit(
&mut self,
c: &thruput_scp::SCPBallot,
h: &thruput_scp::SCPBallot,
) -> bool {
trace!(
slot_index = self.slot_proto().index(),
c = ?c,
h = ?h,
"ballot proto set_confirm_commit"
);
self.ballot_state_mut().commit = Some(c.clone());
self.ballot_state_mut().high = Some(h.clone());
self.update_current_if_needed(h);
self.ballot_state_mut().phase = Phase::Externalize;
self.emit_current_state_statement();
self.slot_proto_mut().stop_nomination();
self.consensus()
.value_externalized(self.slot_proto().index(), &c.value);
true
}
fn get_working_ballot(
st: &thruput_scp::SCPStatement,
) -> thruput_scp::SCPBallot {
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
prepare.ballot.clone()
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
thruput_scp::SCPBallot {
counter: confirm.n_commit,
value: confirm.ballot.value.clone(),
}
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => externalize.commit.clone(),
_ => panic!("bug"),
}
}
#[instrument(skip_all)]
pub fn set_state_from_envelope(&mut self, env: &thruput_scp::SCPEnvelope) {
assert!(self.ballot_state().current.is_none());
self.record_envelope(env);
self.ballot_state_mut().last_envelope_gen = Some(env.clone());
self.ballot_state_mut().last_envelope_emit = Some(env.clone());
match &env.statement.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE { prepare } => {
let b = &prepare.ballot;
self.bump_to_ballot(b.clone(), true);
if let Some(prepared) = &prepare.prepared {
self.ballot_state_mut().prepared = Some(prepared.clone());
}
if let Some(prepared_prime) = &prepare.prepared_prime {
self.ballot_state_mut().prepared_prime =
Some(prepared_prime.clone());
}
if prepare.n_h != 0 {
self.ballot_state_mut().high =
Some(thruput_scp::SCPBallot {
counter: prepare.n_h,
value: b.value.clone(),
});
}
if prepare.n_c != 0 {
self.ballot_state_mut().commit =
Some(thruput_scp::SCPBallot {
counter: prepare.n_c,
value: b.value.clone(),
});
}
self.ballot_state_mut().phase = Phase::Prepare;
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { confirm } => {
let v = &confirm.ballot.value;
self.bump_to_ballot(confirm.ballot.clone(), true);
self.ballot_state_mut().prepared =
Some(thruput_scp::SCPBallot {
counter: confirm.n_prepared,
value: v.clone(),
});
self.ballot_state_mut().high = Some(thruput_scp::SCPBallot {
counter: confirm.n_h,
value: v.clone(),
});
self.ballot_state_mut().commit = Some(thruput_scp::SCPBallot {
counter: confirm.n_commit,
value: v.clone(),
});
self.ballot_state_mut().phase = Phase::Confirm;
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
let v = &externalize.commit.value;
self.bump_to_ballot(
thruput_scp::SCPBallot {
counter: u32::MAX,
value: v.clone(),
},
true,
);
self.ballot_state_mut().prepared =
Some(thruput_scp::SCPBallot {
counter: u32::MAX,
value: v.clone(),
});
self.ballot_state_mut().high = Some(thruput_scp::SCPBallot {
counter: externalize.n_h,
value: v.clone(),
});
self.ballot_state_mut().commit =
Some(externalize.commit.clone());
self.ballot_state_mut().phase = Phase::Externalize;
}
_ => panic!("bug"),
}
}
pub fn process_current_state<F>(&self, f: &mut F, force_self: bool) -> bool
where
F: FnMut(&thruput_scp::SCPEnvelope) -> bool,
{
for (node_id, envelope) in &self.ballot_state().latest_envelopes {
if (force_self
|| node_id != self.slot_proto().local_proto().get_node_id()
|| self.slot_proto().is_fully_validated())
&& !f(envelope)
{
return false;
}
}
true
}
pub fn get_latest_message(
&self,
id: &thruput_scp::SCPNodeID,
) -> Option<thruput_scp::SCPEnvelope> {
self.ballot_state().latest_envelopes.get(id).cloned()
}
pub fn get_externalizing_state(&self) -> Vec<thruput_scp::SCPEnvelope> {
let mut res = Vec::new();
if self.ballot_state().phase == Phase::Externalize {
res.reserve(self.ballot_state().latest_envelopes.len());
for (node_id, envelope) in &self.ballot_state().latest_envelopes {
if node_id != self.slot_proto().local_proto().get_node_id() {
if are_ballots_compatible(
&Self::get_working_ballot(&envelope.statement),
self.ballot_state().commit.as_ref().unwrap(),
) {
res.push(envelope.clone());
}
} else if self.slot_proto().is_fully_validated() {
res.push(envelope.clone());
}
}
}
res
}
#[instrument(skip_all)]
fn validate_values(
&self,
st: &thruput_scp::SCPStatement,
) -> ValidationLevel {
let values = Self::get_statement_values(st);
if values.is_empty() {
return ValidationLevel::Invalid;
}
let mut res = ValidationLevel::FullyValid;
for value in values {
if res > ValidationLevel::Invalid {
let validation_result = self
.consensus()
.validate_ballot_value(self.slot_proto().index(), &value);
res = std::cmp::min(validation_result, res);
}
}
res
}
pub fn get_state(
&self,
n: &thruput_scp::SCPNodeID,
self_already_moved_on: bool,
) -> QuorumInfoNodeState {
let mut state = QuorumInfoNodeState::Agree;
if n == self.slot_proto().local_proto().get_node_id() {
return state;
}
if let Some(envelope) = self.ballot_state().latest_envelopes.get(n) {
if let Some(last_envelope_emit) =
&self.ballot_state().last_envelope_emit
{
let st = &envelope.statement;
let externalized = matches!(
st.pledges,
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { .. }
);
let confirmed_commit = match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm,
} => confirm.ballot.counter == u32::MAX,
_ => false,
};
if self.ballot_state().phase == Phase::Externalize
&& (!externalized || !confirmed_commit)
&& self_already_moved_on
{
state = QuorumInfoNodeState::Delayed;
}
let self_accepted_confirm = self.ballot_state().phase
== Phase::Confirm
|| self.ballot_state().phase == Phase::Externalize;
let other_accepted_confirm = matches!(
st.pledges,
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM { .. }
| thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE { .. }
);
let self_st = &last_envelope_emit.statement;
if self_accepted_confirm
&& other_accepted_confirm
&& !are_ballots_compatible(
&Self::get_working_ballot(st),
&Self::get_working_ballot(self_st),
)
{
state = QuorumInfoNodeState::Disagree;
}
}
} else if self.ballot_state().timer_exp_count
>= NUM_TIMEOUTS_THRESHOLD_FOR_REPORTING
|| self_already_moved_on
{
state = QuorumInfoNodeState::Missing;
} else {
state = QuorumInfoNodeState::NoInfo;
}
state
}
pub fn get_json_quorum_info(
&self,
id: &thruput_scp::SCPNodeID,
summary: bool,
full_keys: bool,
) -> serde_json::Value {
let mut ret = serde_json::json!({});
let mut b = thruput_scp::SCPBallot {
counter: 0,
value: thruput_scp::SCPValue::default(),
};
let mut q_set_hash = thruput_scp::SCPHash::default();
if let Some(envelope) = self.ballot_state().latest_envelopes.get(id) {
let st = &envelope.statement;
match &st.pledges {
thruput_scp::SCPStatement_pledges::SCP_ST_PREPARE {
prepare,
} => {
ret["phase"] =
serde_json::Value::String("PREPARE".to_string());
b = prepare.ballot.clone();
}
thruput_scp::SCPStatement_pledges::SCP_ST_CONFIRM {
confirm,
} => {
ret["phase"] =
serde_json::Value::String("CONFIRM".to_string());
b = confirm.ballot.clone();
}
thruput_scp::SCPStatement_pledges::SCP_ST_EXTERNALIZE {
externalize,
} => {
ret["phase"] =
serde_json::Value::String("EXTERNALIZE".to_string());
b = externalize.commit.clone();
}
_ => panic!("bug"),
}
q_set_hash =
federated::get_companion_quorum_set_hash_from_statement(st);
} else {
ret["phase"] = serde_json::Value::String("unknown".to_string());
if id == self.slot_proto().local_proto().get_node_id() {
q_set_hash = *self.slot_proto().local_proto().get_qset_hash();
}
}
let Some(q_set) = self.driver().get_qset(&q_set_hash) else {
ret["phase"] = serde_json::Value::String("expired".to_string());
return ret;
};
let local_proto = self.slot_proto().local_proto();
let f = local_proto.find_closest_v_blocking_envelopes(
&q_set,
&self.ballot_state().latest_envelopes,
|st: &thruput_scp::SCPStatement| -> bool {
are_ballots_compatible(&Self::get_working_ballot(st), &b)
},
Some(id),
);
ret["fail_at"] =
serde_json::Value::Number(serde_json::Number::from(f.len()));
if !summary {
let mut f_ex = serde_json::json!([]);
for n in f {
f_ex.as_array_mut().unwrap().push(serde_json::Value::String(
self.driver().to_str_key(&n, full_keys),
));
}
ret["fail_with"] = f_ex;
ret["value"] =
self.slot_proto().local_proto().to_json(&q_set, full_keys);
}
ret["hash"] = serde_json::Value::String(hex_abbrev(&q_set_hash));
ret
}
#[instrument(skip_all, fields(slot_index = i64::try_from(hint.slot_index).unwrap_or(i64::MAX), thruput.block.height = i64::try_from(hint.slot_index).unwrap_or(i64::MAX)))]
fn advance_slot(&mut self, hint: &thruput_scp::SCPStatement) {
const MAX_ADVANCE_SLOT_RECURSION: i64 = 100;
self.ballot_state_mut().msg_level += 1;
trace!(
msg_level = self.ballot_state().msg_level,
local_state = ?self.get_local_state(),
"ballot proto advance_slot"
);
if self.ballot_state().msg_level >= MAX_ADVANCE_SLOT_RECURSION {
panic!("maximum number of transitions reached in advance_slot");
}
let mut did_work = false;
did_work = self.attempt_accept_prepared(hint) || did_work;
did_work = self.attempt_confirm_prepared(hint) || did_work;
did_work = self.attempt_accept_commit(hint) || did_work;
did_work = self.attempt_confirm_commit(hint) || did_work;
if self.ballot_state().msg_level == 1 {
#[allow(unused_assignments)]
let mut did_bump = false;
loop {
did_bump = self.attempt_bump();
did_work = did_bump || did_work;
if !did_bump {
break;
}
}
self.check_heard_from_quorum();
}
trace!(
msg_level = self.ballot_state().msg_level,
local_state = ?self.get_local_state(),
"ballot proto advance_slot exiting"
);
self.ballot_state_mut().msg_level -= 1;
if did_work {
self.send_latest_envelope();
}
}
fn get_local_state(&self) -> String {
let state = BallotLocalState {
slot_index: self.slot_proto().index(),
ballot: self.ballot_state(),
};
format!("{:?}", state)
}
pub fn get_json_info(&self) -> serde_json::Value {
json!({
"heard": self.ballot_state().heard_from_quorum,
"ballot": self.0.cd.opt_ballot_to_str(self.ballot_state().current.as_ref()),
"phase": self.ballot_state().phase.to_string(),
"state": self.get_local_state(),
})
}
pub fn get_last_message_send(&self) -> Option<thruput_scp::SCPEnvelope> {
self.ballot_state().last_envelope_emit.clone()
}
}
#[derive(Debug)]
#[allow(dead_code)]
struct BallotLocalState<'a> {
pub slot_index: thruput_scp::SCPSlotIndex,
pub ballot: &'a BallotState,
}