commonware_consensus/
lib.rs

1//! Order opaque messages in a Byzantine environment.
2//!
3//! # Status
4//!
5//! `commonware-consensus` is **ALPHA** software and is not yet recommended for production use. Developers should
6//! expect breaking changes and occasional instability.
7
8use bytes::Bytes;
9use commonware_utils::Array;
10
11pub mod simplex;
12pub mod threshold_simplex;
13
14/// Activity is specified by the underlying consensus implementation and can be interpreted if desired.
15///
16/// Examples of activity would be "vote", "finalize", or "fault". Various consensus implementations may
17/// want to reward (or penalize) participation in different ways and in different places. For example,
18/// validators could be required to send multiple types of messages (i.e. vote and finalize) and rewarding
19/// both equally may better align incentives with desired behavior.
20pub type Activity = u8;
21
22/// Proof is a blob that attests to some data.
23pub type Proof = Bytes;
24
25cfg_if::cfg_if! {
26    if #[cfg(not(target_arch = "wasm32"))] {
27        use futures::channel::oneshot;
28        use std::future::Future;
29
30        /// Parsed is a wrapper around a message that has a parsable digest.
31        #[derive(Clone)]
32        struct Parsed<Message, Digest: Array> {
33            /// Raw message that has some field that can be parsed into a digest.
34            pub message: Message,
35
36            /// Parsed digest.
37            pub digest: Digest,
38        }
39
40        /// Automaton is the interface responsible for driving the consensus forward by proposing new payloads
41        /// and verifying payloads proposed by other participants.
42        pub trait Automaton: Clone + Send + 'static {
43            /// Context is metadata provided by the consensus engine associated with a given payload.
44            ///
45            /// This often includes things like the proposer, view number, the height, or the epoch.
46            type Context;
47
48            /// Hash of an arbitrary payload.
49            type Digest: Array;
50
51            /// Payload used to initialize the consensus engine.
52            fn genesis(&mut self) -> impl Future<Output = Self::Digest> + Send;
53
54            /// Generate a new payload for the given context.
55            ///
56            /// If it is possible to generate a payload, the Digest should be returned over the provided
57            /// channel. If it is not possible to generate a payload, the channel can be dropped. If construction
58            /// takes too long, the consensus engine may drop the provided proposal.
59            fn propose(
60                &mut self,
61                context: Self::Context,
62            ) -> impl Future<Output = oneshot::Receiver<Self::Digest>> + Send;
63
64            /// Verify the payload is valid.
65            ///
66            /// If it is possible to verify the payload, a boolean should be returned indicating whether
67            /// the payload is valid. If it is not possible to verify the payload, the channel can be dropped.
68            fn verify(
69                &mut self,
70                context: Self::Context,
71                payload: Self::Digest,
72            ) -> impl Future<Output = oneshot::Receiver<bool>> + Send;
73        }
74
75        /// Relay is the interface responsible for broadcasting payloads to the network.
76        ///
77        /// The consensus engine is only aware of a payload's digest, not its contents. It is up
78        /// to the relay to efficiently broadcast the full payload to other participants.
79        pub trait Relay: Clone + Send + 'static {
80            /// Hash of an arbitrary payload.
81            type Digest: Array;
82
83            /// Called once consensus begins working towards a proposal provided by `Automaton` (i.e.
84            /// it isn't dropped).
85            ///
86            /// Other participants may not begin voting on a proposal until they have the full contents,
87            /// so timely delivery often yields better performance.
88            fn broadcast(&mut self, payload: Self::Digest) -> impl Future<Output = ()> + Send;
89        }
90
91        /// Committer is the interface responsible for handling notifications of payload status.
92        pub trait Committer: Clone + Send + 'static {
93            /// Hash of an arbitrary payload.
94            type Digest: Array;
95
96            /// Event that a payload has made some progress towards finalization but is not yet finalized.
97            ///
98            /// This is often used to provide an early ("best guess") confirmation to users.
99            fn prepared(&mut self, proof: Proof, payload: Self::Digest) -> impl Future<Output = ()> + Send;
100
101            /// Event indicating the container has been finalized.
102            fn finalized(&mut self, proof: Proof, payload: Self::Digest) -> impl Future<Output = ()> + Send;
103        }
104
105        /// Supervisor is the interface responsible for managing which participants are active at a given time.
106        ///
107        /// ## Synchronization
108        ///
109        /// It is up to the user to ensure changes in this list are synchronized across nodes in the network
110        /// at a given `Index`. If care is not taken to do this, consensus could halt (as different participants
111        /// may have a different view of who is active at a given time).
112        ///
113        /// The simplest way to avoid this complexity is to use a consensus implementation that reaches finalization
114        /// on application data before transitioning to a new `Index` (i.e. [Tendermint](https://arxiv.org/abs/1807.04938)).
115        ///
116        /// Implementations that do not work this way (like `simplex`) must introduce some synchrony bound for changes
117        /// (where it is assumed all participants have finalized some previous set change by some point) or "sync points"
118        /// (i.e. epochs) where participants agree that some finalization occurred at some point in the past.
119        pub trait Supervisor: Clone + Send + Sync + 'static {
120            /// Index is the type used to indicate the in-progress consensus decision.
121            type Index;
122
123            /// Public key used to identify participants.
124            type PublicKey: Array;
125
126            /// Return the leader at a given index for the provided seed.
127            fn leader(&self, index: Self::Index) -> Option<Self::PublicKey>;
128
129            /// Get the **sorted** participants for the given view. This is called when entering a new view before
130            /// listening for proposals or votes. If nothing is returned, the view will not be entered.
131            fn participants(&self, index: Self::Index) -> Option<&Vec<Self::PublicKey>>;
132
133            // Indicate whether some candidate is a participant at the given view.
134            fn is_participant(&self, index: Self::Index, candidate: &Self::PublicKey) -> Option<u32>;
135
136            /// Report some activity observed by the consensus implementation.
137            fn report(&self, activity: Activity, proof: Proof) -> impl Future<Output = ()> + Send;
138        }
139
140        /// ThresholdSupervisor is the interface responsible for managing which `identity` (typically a group polynomial with
141        /// a fixed constant factor) and `share` for a participant is active at a given time.
142        ///
143        /// ## Synchronization
144        ///
145        /// The same considerations for `Supervisor` apply here.
146        pub trait ThresholdSupervisor: Supervisor {
147            /// Seed is some random value used to bias the leader selection process.
148            type Seed;
149
150            /// Identity is the type against which partial signatures are verified.
151            type Identity;
152
153            /// Share is the type used to generate a partial signature that can be verified
154            /// against `Identity`.
155            type Share;
156
157            /// Return the leader at a given index over the provided seed.
158            fn leader(&self, index: Self::Index, seed: Self::Seed) -> Option<Self::PublicKey>;
159
160            /// Returns the identity (typically a group polynomial with a fixed constant factor)
161            /// at the given index. This is used to verify partial signatures from participants
162            /// enumerated in `Supervisor::participants`.
163            fn identity(&self, index: Self::Index) -> Option<&Self::Identity>;
164
165            /// Returns share to sign with at a given index. After resharing, the share
166            /// may change (and old shares may be deleted).
167            fn share(&self, index: Self::Index) -> Option<&Self::Share>;
168        }
169    }
170}