-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathapp.rs
More file actions
481 lines (410 loc) · 15.9 KB
/
app.rs
File metadata and controls
481 lines (410 loc) · 15.9 KB
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
// Copyright 2025 Circle Internet Group, Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use eyre::{eyre, Context as _};
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tracing::{error, info, warn};
use malachitebft_app_channel::{AppMsg, Channels};
use malachitebft_core_types::utils::height::DisplayRange;
use malachitebft_core_types::Context;
use arc_consensus_types::{ArcContext, StoredCommitCertificate};
use arc_eth_engine::engine::Engine;
use crate::handlers::*;
use crate::request::{AppRequest, CommitCertificateInfo};
use crate::state::State;
pub async fn run(
mut state: State,
channels: Channels<ArcContext>,
engine: Engine,
rx_app_req: Receiver<AppRequest>,
cancel_token: CancellationToken,
) -> eyre::Result<()> {
if let Some(halt_height) = state.env_config().halt_height {
warn!("Consensus configured to halt at block height: {halt_height}");
}
let result = cancel_token
.run_until_cancelled_owned(go(&mut state, channels, &engine, rx_app_req))
.await;
let result = match result {
Some(Err(e)) => {
error!("🔴 Error in application: {e:#}");
error!("🔴 Shutting down");
Err(e)
}
None => {
info!("🟢🟢 Application is shutting down gracefully");
Ok(())
}
};
// Create a savepoint in the database helps avoiding its repair on next startup.
state.savepoint();
result
}
/// A type that cannot be instantiated.
///
/// Used to indicate that the function never returns normally.
enum Never {}
/// The main event loop of the application.
///
/// It listens for messages from consensus and application requests,
/// and dispatches them to the appropriate handlers.
///
/// # Errors
/// Returns an error if handling a message fails or one of the channels is closed unexpectedly.
/// This will cause the application to shut down.
/// Otherwise, it runs indefinitely until cancelled.
async fn go(
state: &mut State,
mut channels: Channels<ArcContext>,
engine: &Engine,
mut rx_app_req: Receiver<AppRequest>,
) -> eyre::Result<Never> {
loop {
tokio::select! {
biased;
msg = channels.consensus.recv() => match msg {
Some(msg) => {
// Abort on error to shut down the application.
handle_consensus(msg, state, &mut channels, engine).await
.wrap_err("Error handling consensus message")?;
},
None => {
return Err(eyre!("Consensus channel closed unexpectedly"));
}
},
req = rx_app_req.recv() => match req {
Some(req) => {
if let Err(e) = handle_app_request(req, state, engine).await {
error!("🔴 Error handling application request: {e:#}");
// We continue processing other requests even if one fails.
continue;
}
},
None => {
return Err(eyre!("Application request channel closed unexpectedly"));
}
}
}
}
}
async fn handle_consensus(
msg: AppMsg<ArcContext>,
state: &mut State,
channels: &mut Channels<ArcContext>,
engine: &Engine,
) -> eyre::Result<()> {
match msg {
// Consensus is ready.
// The application replies with a message to instruct
// consensus to start at a given height.
AppMsg::ConsensusReady { reply } => {
let _guard = state.metrics.start_msg_process_timer("ConsensusReady");
info!("🚦 Consensus is ready");
consensus_ready::handle(state, engine, reply).await?;
}
// Consensus has started a new round.
// The application replies to this message with the previously undecided proposals for the round.
AppMsg::StartedRound {
height,
round,
proposer,
role,
reply_value,
} => {
let _guard = state.metrics.start_msg_process_timer("StartedRound");
started_round::handle(state, engine, height, round, proposer, role, reply_value).await;
}
// Request to build a local value to propose.
// The application replies to this message with the requested value within the timeout.
AppMsg::GetValue {
height,
round,
timeout,
reply,
} => {
let _guard = state.metrics.start_msg_process_timer("GetValue");
info!(%height, %round, "Consensus is requesting a value to propose");
get_value::handle(
state,
channels.network.clone(),
engine,
height,
round,
timeout,
reply,
)
.await?;
}
// Notification for a new proposal part.
// If a full proposal can be assembled, the application responds
// with the complete proposed value. Otherwise, it responds with `None`.
AppMsg::ReceivedProposalPart { from, part, reply } => {
let _guard = state
.metrics
.start_msg_process_timer("ReceivedProposalPart");
received_proposal_part::handle(state, engine, from, part, reply).await;
}
// Notification that consensus has decided a value.
AppMsg::Decided { certificate, .. } => {
let _guard = state.metrics.start_msg_process_timer("Decided");
let height = certificate.height;
let round = certificate.round;
let value_id = certificate.value_id;
let signatures = certificate.commit_signatures.len();
info!(%height, %round, %value_id, %signatures, "🎉 Consensus has decided on value");
decided::handle(state, engine, certificate).await?;
}
// Notification that a height has been finalized.
AppMsg::Finalized {
certificate,
extensions: _,
evidence,
reply,
} => {
let _guard = state.metrics.start_msg_process_timer("Finalized");
let height = certificate.height;
let round = certificate.round;
let value_id = certificate.value_id;
let signatures = certificate.commit_signatures.len();
info!(
%height, %round, %value_id, %signatures,
"📜 Consensus has finalized the height"
);
finalized::handle(state, certificate, evidence, reply).await?;
}
// A value has been synced from the network.
// This may happen when the node is catching up with the network.
AppMsg::ProcessSyncedValue {
height,
round,
proposer,
value_bytes,
reply,
} => {
let _guard = state.metrics.start_msg_process_timer("ProcessSyncedValue");
info!(%height, %round, "Processing synced value");
process_synced_value::handle(
state,
engine,
height,
round,
proposer,
value_bytes,
reply,
)
.await?;
}
// Request for previously decided blocks from the application's storage.
AppMsg::GetDecidedValues { range, reply } => {
info!(range = %DisplayRange(&range), "Received sync request");
get_decided_values::handle(state, engine, range, reply).await?;
}
// Request for the earliest height available in the block store.
AppMsg::GetHistoryMinHeight { reply } => {
let _guard = state.metrics.start_msg_process_timer("GetHistoryMinHeight");
get_history_min_height::handle(state, engine, reply).await?;
}
// Request to re-stream a proposal that was previously seen at valid_round or round (if valid_round is Nil).
AppMsg::RestreamProposal {
height,
round,
valid_round,
address: _,
value_id,
} => {
let _guard = state.metrics.start_msg_process_timer("RestreamProposal");
info!(%height, %round, %valid_round, %value_id, "Restreaming proposal");
restream_proposal::handle(state, channels, height, round, valid_round, value_id)
.await?;
}
// Currently not supported
// Request to extend a precommit
AppMsg::ExtendVote { reply, .. } => {
if let Err(e) = reply.send(None) {
error!("🔴 Failed to send ExtendVote reply: {e:?}");
}
}
// Currently not supported
// Request to verify a vote extension
AppMsg::VerifyVoteExtension { reply, .. } => {
if let Err(e) = reply.send(Ok(())) {
error!("🔴 Failed to send VerifyVoteExtension reply: {e:?}");
}
}
}
Ok(())
}
#[allow(clippy::unit_arg)]
async fn handle_app_request(req: AppRequest, state: &State, engine: &Engine) -> eyre::Result<()> {
match req {
AppRequest::GetCertificate(height, reply) => {
let result = state
.store()
.get_certificate(height)
.await
.wrap_err_with(|| {
format!("GetCertificate: Failed to get certificate for height {height:?}")
})?;
let info = match result {
Some(certificate) => get_certificate_info(&state.ctx, engine, certificate).await,
None => None,
};
if let Err(e) = reply.send(info) {
error!("GetCertificate: Failed to reply: {e:?}");
}
}
AppRequest::GetMisbehaviorEvidence(height, reply) => {
let evidence = state.store().get_misbehavior_evidence(height).await.wrap_err_with(|| {
format!(
"GetMisbehaviorEvidence: Failed to get misbehavior evidence for height {height:?}",
)
})?;
if let Err(e) = reply.send(evidence) {
error!("GetMisbehaviorEvidence: Failed to reply: {e:?}");
}
}
AppRequest::GetProposalMonitorData(height, reply) => {
let data = state
.store()
.get_proposal_monitor_data(height)
.await
.wrap_err_with(|| {
format!(
"Failed to get proposal monitor data for height {:?} in response to a GetProposalMonitorData request",
height,
)
})?;
if let Err(e) = reply.send(data) {
error!("Failed to reply to GetProposalMonitorData: {e:?}");
}
}
AppRequest::GetInvalidPayloads(height, reply) => {
let payloads = state.store().get_invalid_payloads(height).await.wrap_err_with(|| {
format!(
"Failed to get invalid payloads for height {:?} in response to a GetInvalidPayloads request", height,
)
})?;
if let Err(e) = reply.send(payloads) {
error!("Failed to reply to GetInvalidPayloads: {e:?}");
}
}
AppRequest::GetStatus(reply) => {
let status = state
.get_status()
.await
.wrap_err("GetStatus: Failed to get the current status")?;
if let Err(e) = reply.send(status) {
error!("GetStatus: Failed to reply: {e:?}");
}
}
AppRequest::GetHealth(reply) => {
if let Err(e) = reply.send(state.get_health()) {
error!("GetHealth: Failed to reply: {e:?}");
}
}
AppRequest::GetSyncState(reply) => {
if let Err(e) = reply.send(state.sync_state) {
error!("GetSyncState: Failed to reply: {e:?}");
}
}
}
Ok(())
}
async fn get_certificate_info(
ctx: &ArcContext,
engine: &Engine,
stored: StoredCommitCertificate,
) -> Option<CommitCertificateInfo> {
// The validator set that signed the certificate is the one *before* executing that block,
// since the block itself could contain validator set changes.
let prev_height = stored.certificate.height.as_u64().saturating_sub(1);
let validator_set = engine
.eth
.get_active_validator_set(prev_height)
.await
.ok()?;
let proposer = stored.proposer.unwrap_or_else(|| {
ctx.select_proposer(
&validator_set,
stored.certificate.height,
stored.certificate.round,
)
.address
});
Some(CommitCertificateInfo {
certificate: stored.certificate,
certificate_type: stored.certificate_type,
proposer,
})
}
#[cfg(test)]
mod tests {
use super::*;
use arc_consensus_types::{
Address, BlockHash, CommitCertificate, CommitCertificateType, Height, Round, ValueId,
};
use arc_eth_engine::engine::{MockEngineAPI, MockEthereumAPI};
use mockall::predicate::eq;
fn stored_cert(height: u64) -> StoredCommitCertificate {
StoredCommitCertificate {
certificate: CommitCertificate::new(
Height::new(height),
Round::new(0),
ValueId::new(BlockHash::new([0xAA; 32])),
vec![],
),
certificate_type: CommitCertificateType::Minimal,
// Set so get_certificate_info skips select_proposer (keeps the test focused
// on the validator set lookup).
proposer: Some(Address::new([0x42; 20])),
}
}
/// get_certificate_info must fetch the validator set at `certificate.height - 1` — the
/// set that signed the certificate, i.e. the state *before* executing the certified block.
#[tokio::test]
async fn get_certificate_info_queries_validator_set_at_prev_height() {
let cert_height = 42u64;
let mut mock_eth = MockEthereumAPI::new();
mock_eth
.expect_get_active_validator_set()
.with(eq(cert_height - 1))
.once()
.returning(|_| Ok(Default::default()));
let engine = Engine::new(Box::new(MockEngineAPI::new()), Box::new(mock_eth));
let ctx = ArcContext::default();
let info = get_certificate_info(&ctx, &engine, stored_cert(cert_height))
.await
.expect("should return Some");
assert_eq!(info.certificate.height, Height::new(cert_height));
}
/// At genesis (height 0), the saturating subtraction must keep the query at 0 rather
/// than underflowing.
#[tokio::test]
async fn get_certificate_info_handles_genesis_height() {
let mut mock_eth = MockEthereumAPI::new();
mock_eth
.expect_get_active_validator_set()
.with(eq(0u64))
.once()
.returning(|_| Ok(Default::default()));
let engine = Engine::new(Box::new(MockEngineAPI::new()), Box::new(mock_eth));
let ctx = ArcContext::default();
let info = get_certificate_info(&ctx, &engine, stored_cert(0))
.await
.expect("should return Some");
assert_eq!(info.certificate.height, Height::new(0));
}
}