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
//! Implementation of [`ConsensusServiceAPI`] for [`ConsensusService`].
use alloy_signer::Signer;
use crate::{
api::ConsensusServiceAPI,
error::ConsensusError,
events::ConsensusEventBus,
protos::consensus::v1::{Proposal, Vote},
scope::ConsensusScope,
service::ConsensusService,
session::{ConsensusConfig, ConsensusSession},
storage::ConsensusStorage,
types::CreateProposalRequest,
utils::{build_vote, validate_proposal_timestamp, validate_vote},
};
impl<Scope, S, E> ConsensusServiceAPI<Scope, S, E> for ConsensusService<Scope, S, E>
where
Scope: ConsensusScope,
S: ConsensusStorage<Scope>,
E: ConsensusEventBus<Scope>,
{
/// Create a new proposal and start the voting process.
///
/// This creates the proposal, sets up a session to track votes, and schedules automatic
/// timeout handling. The proposal will expire after the time specified in the request.
///
/// Configuration is resolved from: proposal config > scope config > global default.
/// If no config is provided, the scope's default configuration is used.
///
/// # Examples
///
/// ```rust
/// use hashgraph_like_consensus::{api::ConsensusServiceAPI, scope::ScopeID,
/// scope_config::NetworkType, service::DefaultConsensusService, types::CreateProposalRequest};
///
/// async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = DefaultConsensusService::default();
/// let scope = ScopeID::from("my_scope");
///
/// service
/// .scope(&scope)
/// .await?
/// .with_network_type(NetworkType::P2P)
/// .with_threshold(0.75)
/// .initialize()
/// .await?;
///
/// let request = CreateProposalRequest::new(
/// "Test Proposal".to_string(),
/// b"payload".to_vec(),
/// vec![0u8; 20],
/// 3,
/// 100,
/// true,
/// )?;
/// let proposal = service.create_proposal(&scope, request).await?;
/// Ok(())
/// }
/// ```
async fn create_proposal(
&self,
scope: &Scope,
request: CreateProposalRequest,
) -> Result<Proposal, ConsensusError> {
self.create_proposal_with_config(scope, request, None).await
}
/// Create a new proposal with explicit configuration override.
///
/// This allows you to override the scope's default configuration for a specific proposal.
/// The override takes precedence over scope config.
///
/// # Examples
///
/// ```rust
/// use hashgraph_like_consensus::{api::ConsensusServiceAPI, scope::ScopeID,
/// service::DefaultConsensusService, session::ConsensusConfig, types::CreateProposalRequest};
///
/// async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = DefaultConsensusService::default();
/// let scope = ScopeID::from("my_scope");
/// let request = CreateProposalRequest::new(
/// "Test Proposal".to_string(),
/// b"payload".to_vec(),
/// vec![0u8; 20],
/// 3,
/// 100,
/// true,
/// )?;
///
/// let proposal = service.create_proposal_with_config(
/// &scope,
/// request,
/// Some(ConsensusConfig::p2p())
/// ).await?;
///
/// let request2 = CreateProposalRequest::new(
/// "Another Proposal".to_string(),
/// b"payload2".to_vec(),
/// vec![0u8; 20],
/// 3,
/// 100,
/// true,
/// )?;
/// let proposal2 = service.create_proposal_with_config(
/// &scope,
/// request2,
/// None
/// ).await?;
/// Ok(())
/// }
/// ```
async fn create_proposal_with_config(
&self,
scope: &Scope,
request: CreateProposalRequest,
config: Option<ConsensusConfig>,
) -> Result<Proposal, ConsensusError> {
let proposal = request.into_proposal()?;
// Resolve config: override > scope config > global default, aligning timeout with proposal
let config = self.resolve_config(scope, config, Some(&proposal)).await?;
let (session, _) = ConsensusSession::from_proposal(proposal.clone(), config.clone())?;
self.save_session(scope, session).await?;
self.trim_scope_sessions(scope).await?;
Ok(proposal)
}
/// Cast your vote on a proposal (yes or no).
///
/// Vote is cryptographically signed and linked to previous votes in the hashgraph.
/// Returns the signed vote, which you can then send to other peers in the network.
/// Each voter can only vote once per proposal.
async fn cast_vote<SN: Signer + Sync + Send>(
&self,
scope: &Scope,
proposal_id: u32,
choice: bool,
signer: SN,
) -> Result<Vote, ConsensusError> {
let session = self.get_session(scope, proposal_id).await?;
validate_proposal_timestamp(session.proposal.expiration_timestamp)?;
let voter_address = signer.address().as_slice().to_vec();
if session.votes.contains_key(&voter_address) {
return Err(ConsensusError::UserAlreadyVoted);
}
let vote = build_vote(&session.proposal, choice, signer).await?;
let vote_clone = vote.clone();
let transition = self
.update_session(scope, proposal_id, move |session| {
session.add_vote(vote_clone)
})
.await?;
self.handle_transition(scope, proposal_id, transition);
Ok(vote)
}
/// Cast a vote and immediately get back the updated proposal.
///
/// This is a convenience method that combines `cast_vote` and fetching the proposal.
/// Useful for proposal creator as they can immediately see the proposal with their vote
/// and share it with other peers.
async fn cast_vote_and_get_proposal<SN: Signer + Sync + Send>(
&self,
scope: &Scope,
proposal_id: u32,
choice: bool,
signer: SN,
) -> Result<Proposal, ConsensusError> {
self.cast_vote(scope, proposal_id, choice, signer).await?;
let session = self.get_session(scope, proposal_id).await?;
Ok(session.proposal)
}
/// Process a proposal you received from another peer in the network.
///
/// This validates the proposal and all its votes (signatures, vote chains, timestamps),
/// then stores it locally.
/// If it necessary the consensus configuration is resolved from the proposal.
/// If the proposal already has enough votes, consensus is reached
/// immediately and an event is emitted.
async fn process_incoming_proposal(
&self,
scope: &Scope,
proposal: Proposal,
) -> Result<(), ConsensusError> {
if self.get_session(scope, proposal.proposal_id).await.is_ok() {
return Err(ConsensusError::ProposalAlreadyExist);
}
let config = self.resolve_config(scope, None, Some(&proposal)).await?;
let (session, transition) = ConsensusSession::from_proposal(proposal, config)?;
self.handle_transition(scope, session.proposal.proposal_id, transition);
self.save_session(scope, session).await?;
self.trim_scope_sessions(scope).await?;
Ok(())
}
/// Process a vote you received from another peer.
///
/// The vote is validated (signature, timestamp, vote chain) and added to the proposal.
/// If this vote brings the total to the consensus threshold, consensus is reached and
/// an event is emitted.
async fn process_incoming_vote(&self, scope: &Scope, vote: Vote) -> Result<(), ConsensusError> {
let session = self.get_session(scope, vote.proposal_id).await?;
validate_vote(
&vote,
session.proposal.expiration_timestamp,
session.proposal.timestamp,
)?;
let proposal_id = vote.proposal_id;
let transition = self
.update_session(scope, proposal_id, move |session| session.add_vote(vote))
.await?;
self.handle_transition(scope, proposal_id, transition);
Ok(())
}
async fn get_proposal(
&self,
scope: &Scope,
proposal_id: u32,
) -> Result<Proposal, ConsensusError> {
let session = self.get_session(scope, proposal_id).await?;
Ok(session.proposal)
}
async fn get_proposal_payload(
&self,
scope: &Scope,
proposal_id: u32,
) -> Result<Vec<u8>, ConsensusError> {
let session = self.get_session(scope, proposal_id).await?;
Ok(session.proposal.payload)
}
}