-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathwal.rs
More file actions
276 lines (234 loc) · 9.28 KB
/
wal.rs
File metadata and controls
276 lines (234 loc) · 9.28 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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use pathfinder_consensus::*;
use tokio::sync::mpsc;
use tokio::time::{pause, sleep, Duration};
use tracing::{debug, error, info};
mod common;
use common::{drive_until, ConsensusValue, NodeAddress};
#[tokio::test]
async fn wal_concurrent_heights_retention_test() {
//common::setup_tracing_full();
const NUM_VALIDATORS: usize = 2;
const NUM_HEIGHTS: u64 = 15; // More than config.history_depth
let consensus_value = ConsensusValue("Hello, world!".to_string());
// Create a temporary directory for WAL files
let temp_dir = tempfile::tempdir().expect("Failed to create temp directory");
let wal_dir = temp_dir.path();
// Create validators and channels
let mut validators = vec![];
let mut validator_set = vec![];
let mut senders = HashMap::new();
let mut receivers = HashMap::new();
for i in 1..=NUM_VALIDATORS {
let sk = SigningKey::new(rand::rngs::OsRng);
let pk = sk.verification_key();
let addr = NodeAddress(format!("0x{i}"));
let pubkey = PublicKey::from_bytes(pk.to_bytes());
validator_set.push(Validator {
address: addr.clone(),
public_key: pubkey,
voting_power: 1,
});
let (tx, rx) = mpsc::unbounded_channel();
senders.insert(addr.clone(), tx);
receivers.insert(addr.clone(), rx);
validators.push((addr, sk));
}
// Create validator set
let validator_set = ValidatorSet::new(validator_set);
// Track decisions for each height
let decisions = Arc::new(Mutex::new(HashMap::new()));
// Spawn each validator in its own task
let mut handles = vec![];
for (addr, _) in validators {
let mut rx = receivers.remove(&addr).unwrap();
let peers = senders.clone();
let validator_set = validator_set.clone();
let decisions = Arc::clone(&decisions);
let consensus_value = consensus_value.clone();
let wal_dir = wal_dir.to_path_buf();
let handle = tokio::spawn(async move {
let config = Config::new(addr.clone()).with_wal_dir(wal_dir);
let mut consensus = Consensus::new(config);
// Start all heights up front
for current_height in 1..=NUM_HEIGHTS {
let height = current_height;
consensus
.handle_command(ConsensusCommand::StartHeight(height, validator_set.clone()));
}
sleep(Duration::from_millis(100)).await;
// Now process events for all heights
loop {
while let Some(event) = consensus.next_event().await {
match event {
ConsensusEvent::RequestProposal {
height: h,
round: r,
..
} => {
info!(
"🔍 {} is proposing at height {h}, round {r:?}",
pretty_addr(&addr)
);
let proposal = Proposal {
height: h,
round: Round::new(r),
proposer: addr.clone(),
pol_round: Round::nil(),
value: consensus_value.clone(),
};
consensus.handle_command(ConsensusCommand::Propose(proposal));
}
ConsensusEvent::Gossip(msg) => {
for (peer, chan) in peers.iter() {
if peer != &addr {
info!("🔍 {} sending to {peer}", pretty_addr(&addr));
let _ = chan.send(msg.clone());
}
}
}
ConsensusEvent::Decision {
height: h,
round: r,
value,
} => {
info!(
"✅ {} decided on {value:?} at height {h} round {r}",
pretty_addr(&addr)
);
let mut decisions = decisions.lock().unwrap();
decisions.insert((addr.clone(), h), value);
}
ConsensusEvent::Error(error) => {
error!("❌ {} error: {error:?}", pretty_addr(&addr));
break;
}
}
}
while let Ok(msg) = rx.try_recv() {
info!(
"💌 Validator {} received command: {msg:?}",
pretty_addr(&addr)
);
let cmd = match msg {
NetworkMessage::Proposal(p) => ConsensusCommand::Proposal(p),
NetworkMessage::Vote(v) => ConsensusCommand::Vote(v),
};
consensus.handle_command(cmd);
}
// Break if all heights are decided
if decisions.lock().unwrap().len() == (NUM_HEIGHTS as usize * NUM_VALIDATORS) {
break;
}
sleep(Duration::from_millis(5)).await;
}
});
handles.push(handle);
}
// Instead of waiting for all to finish, just sleep for a while
tokio::time::sleep(Duration::from_secs(2)).await;
// Check that at least config.history_depth WAL files exist
let files = std::fs::read_dir(wal_dir)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().starts_with("wal-"))
.collect::<Vec<_>>();
assert!(
files.len() >= 10, // 10 is the default config.history_depth
"Expected at least 10 WAL files in {}, found {}",
wal_dir.display(),
files.len()
);
}
fn pretty_addr(addr: &NodeAddress) -> String {
let addr_str = addr.to_string();
addr_str.chars().skip(addr_str.len() - 4).collect()
}
#[tokio::test]
async fn recover_from_wal_restores_and_continues() {
use std::sync::Arc;
use pathfinder_consensus::{
Config,
Consensus,
ConsensusCommand,
ConsensusEvent,
Proposal,
Round,
ValidatorSetProvider,
};
//common::setup_tracing_full();
pause();
// Create a temporary directory for WAL files
let temp_dir = tempfile::tempdir().expect("Failed to create temp directory");
let wal_dir = temp_dir.path();
// Static validator
let addr = NodeAddress("0x1".to_string());
let sk = SigningKey::new(rand::rngs::OsRng);
let pk = sk.verification_key();
let pubkey = PublicKey::from_bytes(pk.to_bytes());
let validator = Validator {
address: addr.clone(),
public_key: pubkey,
voting_power: 1,
};
let validators = ValidatorSet::new(vec![validator.clone()]);
// Config with temporary WAL directory
let config = Config::new(addr.clone()).with_wal_dir(wal_dir.to_path_buf());
let height = 42;
// Create and run consensus to log data to WAL
{
let mut consensus = Consensus::new(config.clone());
consensus.handle_command(ConsensusCommand::StartHeight(height, validators.clone()));
// Expect RequestProposal for round 0
let _ = drive_until(
&mut consensus,
Duration::from_secs(1),
5,
|evt| matches!(evt, ConsensusEvent::RequestProposal { round, .. } if *round == 0),
)
.await;
// Send a proposal to enter prevote
let value = ConsensusValue("Hello, world!".to_string());
let proposal = Proposal {
height,
round: Round::new(0),
value,
pol_round: Round::nil(),
proposer: addr.clone(),
};
let signed = SignedProposal {
proposal,
signature: Signature::from_bytes([0u8; 64]),
};
consensus.handle_command(ConsensusCommand::Proposal(signed));
}
// Create a validator set provider
#[derive(Clone)]
struct StaticSet(ValidatorSet<NodeAddress>);
impl ValidatorSetProvider<NodeAddress> for StaticSet {
fn get_validator_set(
&self,
_height: u64,
) -> Result<ValidatorSet<NodeAddress>, anyhow::Error> {
Ok(self.0.clone())
}
}
debug!("---------------------- Recovering from WAL ----------------------");
// Now recover from WAL
let mut consensus: Consensus<ConsensusValue, NodeAddress> =
Consensus::recover(config.clone(), Arc::new(StaticSet(validators))).unwrap();
debug!("------------ Driving consensus post WAL recovery ----------------");
// Expect RequestProposal again for round 0
let event = drive_until(
&mut consensus,
Duration::from_secs(5),
10,
|evt| matches!(evt, ConsensusEvent::RequestProposal { round, .. } if *round == 0),
)
.await;
assert!(
event.is_some(),
"Recovered consensus should continue to operate and advance rounds"
);
}