Skip to main content

fedimint_core/
session_outcome.rs

1#[cfg(test)]
2mod tests;
3
4use std::collections::BTreeMap;
5use std::io::Write as _;
6
7use bitcoin::hashes::{Hash, sha256};
8use fedimint_core::core::DynModuleConsensusItem as ModuleConsensusItem;
9use secp256k1::{Message, PublicKey, SECP256K1};
10
11use crate::encoding::{Decodable, Encodable};
12use crate::transaction::Transaction;
13use crate::{NumPeersExt as _, PeerId, secp256k1};
14
15/// All the items that may be produced during a consensus epoch
16#[derive(Debug, Clone, Eq, PartialEq, Hash, Encodable, Decodable)]
17pub enum ConsensusItem {
18    /// Threshold sign the epoch history for verification via the API
19    Transaction(Transaction),
20    /// Any data that modules require consensus on
21    Module(ModuleConsensusItem),
22    /// Allows us to add new items in the future without crashing old clients
23    /// that try to interpret the session log.
24    #[encodable_default]
25    Default { variant: u64, bytes: Vec<u8> },
26}
27
28/// A consensus item accepted in the consensus
29///
30/// If two correct nodes obtain two ordered items from the broadcast they
31/// are guaranteed to be in the same order. However, an ordered items is
32/// only guaranteed to be seen by all correct nodes if a correct node decides to
33/// accept it.
34#[derive(Clone, Debug, PartialEq, Eq, Encodable, Decodable)]
35pub struct AcceptedItem {
36    pub item: ConsensusItem,
37    pub peer: PeerId,
38}
39
40/// Items ordered in a single session that have been accepted by Fedimint
41/// consensus.
42///
43/// A running Federation produces a [`SessionOutcome`] every couple of minutes.
44/// Therefore, just like in Bitcoin, a [`SessionOutcome`] might be empty if no
45/// items are ordered in that time or all ordered items are discarded by
46/// Fedimint Consensus.
47///
48/// When session is closed it is signed over by the peers and produces a
49/// [`SignedSessionOutcome`].
50#[derive(Clone, Debug, PartialEq, Eq, Encodable, Decodable)]
51pub struct SessionOutcome {
52    pub items: Vec<AcceptedItem>,
53}
54
55impl SessionOutcome {
56    /// A blocks header consists of 40 bytes formed by its index in big endian
57    /// bytes concatenated with the merkle root build from the consensus
58    /// hashes of its [`AcceptedItem`]s or 32 zero bytes if the block is
59    /// empty. The use of a merkle tree allows for efficient inclusion
60    /// proofs of accepted consensus items for clients.
61    pub fn header(&self, index: u64) -> [u8; 40] {
62        let mut header = [0; 40];
63
64        header[..8].copy_from_slice(&index.to_be_bytes());
65
66        let leaf_hashes = self
67            .items
68            .iter()
69            .map(Encodable::consensus_hash::<sha256::Hash>);
70
71        if let Some(root) = bitcoin::merkle_tree::calculate_root(leaf_hashes) {
72            header[8..].copy_from_slice(&root.to_byte_array());
73        } else {
74            assert!(self.items.is_empty());
75        }
76
77        header
78    }
79}
80
81/// A [`SessionOutcome`], signed by the Federation.
82///
83/// A signed block combines a block with the naive threshold secp schnorr
84/// signature for its header created by the federation. The signed blocks allow
85/// clients and recovering guardians to verify the federations consensus
86/// history. After a signed block has been created it is stored in the database.
87#[derive(Clone, Debug, Encodable, Decodable, Eq, PartialEq)]
88pub struct SignedSessionOutcome {
89    pub session_outcome: SessionOutcome,
90    pub signatures: std::collections::BTreeMap<PeerId, secp256k1::schnorr::Signature>,
91}
92
93impl SignedSessionOutcome {
94    pub fn verify(
95        &self,
96        broadcast_public_keys: &BTreeMap<PeerId, PublicKey>,
97        block_index: u64,
98    ) -> bool {
99        let message = {
100            let mut engine = sha256::HashEngine::default();
101            engine
102                .write_all(broadcast_public_keys.consensus_hash_sha256().as_ref())
103                .expect("Writing to a hash engine can not fail");
104            engine
105                .write_all(&self.session_outcome.header(block_index))
106                .expect("Writing to a hash engine can not fail");
107            Message::from_digest(sha256::Hash::from_engine(engine).to_byte_array())
108        };
109
110        let Ok(num_peers) = broadcast_public_keys.try_num_peers() else {
111            return false;
112        };
113        let threshold = num_peers.threshold();
114        if self.signatures.len() < threshold {
115            return false;
116        }
117
118        self.signatures.iter().all(|(peer_id, signature)| {
119            let Some(pub_key) = broadcast_public_keys.get(peer_id) else {
120                return false;
121            };
122
123            SECP256K1
124                .verify_schnorr(signature, &message, &pub_key.x_only_public_key().0)
125                .is_ok()
126        })
127    }
128}
129
130#[derive(Debug, Clone, Eq, PartialEq, Encodable, Decodable)]
131pub enum SessionStatus {
132    Initial,
133    Pending(Vec<AcceptedItem>),
134    Complete(SessionOutcome),
135}
136
137#[derive(Debug, Clone, Eq, PartialEq, Encodable, Decodable)]
138pub enum SessionStatusV2 {
139    Initial,
140    Pending(Vec<AcceptedItem>),
141    Complete(SignedSessionOutcome),
142}
143
144impl From<SessionStatusV2> for SessionStatus {
145    fn from(value: SessionStatusV2) -> Self {
146        match value {
147            SessionStatusV2::Initial => Self::Initial,
148            SessionStatusV2::Pending(items) => Self::Pending(items),
149            SessionStatusV2::Complete(signed_session_outcome) => {
150                Self::Complete(signed_session_outcome.session_outcome)
151            }
152        }
153    }
154}