forked from informalsystems/tendermint-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
light_client.rs
423 lines (369 loc) · 15.3 KB
/
light_client.rs
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
//! Light client implementation as per the [Core Verification specification][1].
//!
//! [1]: https://github.com/informalsystems/tendermint-rs/blob/main/docs/spec/lightclient/verification/verification.md
use core::fmt;
use contracts::*;
// Re-export for backward compatibility
pub use crate::verifier::options::Options;
use crate::{
components::{clock::Clock, io::*, scheduler::*},
contracts::*,
errors::Error,
state::State,
verifier::{
types::{Height, LightBlock, PeerId, Status},
Verdict, Verifier,
},
};
/// The light client implements a read operation of a header from the blockchain,
/// by communicating with full nodes. As full nodes may be faulty, it cannot trust
/// the received information, but the light client has to check whether the header
/// it receives coincides with the one generated by Tendermint consensus.
///
/// In the Tendermint blockchain, the validator set may change with every new block.
/// The staking and unbonding mechanism induces a security model: starting at time
/// of the header, more than two-thirds of the next validators of a new block are
/// correct for the duration of the trusted period. The fault-tolerant read operation
/// is designed for this security model.
pub struct LightClient {
/// The peer id of the peer this client is connected to
pub peer: PeerId,
/// Options for this light client
pub options: Options,
clock: Box<dyn Clock>,
scheduler: Box<dyn Scheduler>,
verifier: Box<dyn Verifier>,
io: Box<dyn Io>,
}
impl fmt::Debug for LightClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LightClient")
.field("peer", &self.peer)
.field("options", &self.options)
.finish()
}
}
impl LightClient {
/// Constructs a new light client
pub fn new(
peer: PeerId,
options: Options,
clock: impl Clock + 'static,
scheduler: impl Scheduler + 'static,
verifier: impl Verifier + 'static,
io: impl Io + 'static,
) -> Self {
Self {
peer,
options,
clock: Box::new(clock),
scheduler: Box::new(scheduler),
verifier: Box::new(verifier),
io: Box::new(io),
}
}
/// Constructs a new light client from boxed components
pub fn from_boxed(
peer: PeerId,
options: Options,
clock: Box<dyn Clock>,
scheduler: Box<dyn Scheduler>,
verifier: Box<dyn Verifier>,
io: Box<dyn Io>,
) -> Self {
Self {
peer,
options,
clock,
scheduler,
verifier,
io,
}
}
/// Attempt to update the light client to the highest block of the primary node.
///
/// Note: This function delegates the actual work to `verify_to_target`.
pub fn verify_to_highest(&mut self, state: &mut State) -> Result<LightBlock, Error> {
let target_block = self
.io
.fetch_light_block(AtHeight::Highest)
.map_err(Error::io)?;
self.verify_to_target(target_block.height(), state)
}
/// Update the light client to a block of the primary node at the given height.
///
/// This is the main function and uses the following components:
///
/// - The I/O component is called to fetch the next light block. It is the only component that
/// communicates with other nodes.
/// - The Verifier component checks whether a header is valid and checks if a new light block
/// should be trusted based on a previously verified light block.
/// - When doing _forward_ verification, the Scheduler component decides which height to try to
/// verify next, in case the current block pass verification but cannot be trusted yet.
/// - When doing _backward_ verification, the Hasher component is used to determine whether the
/// `last_block_id` hash of a block matches the hash of the block right below it.
///
/// ## Implements
/// - [LCV-DIST-SAFE.1]
/// - [LCV-DIST-LIFE.1]
/// - [LCV-PRE-TP.1]
/// - [LCV-POST-LS.1]
/// - [LCV-INV-TP.1]
///
/// ## Postcondition
/// - The light store contains a light block that corresponds to a block of the blockchain of
/// height `target_height` [LCV-POST-LS.1]
///
/// ## Error conditions
/// - The light store does not contains a trusted light block within the trusting period
/// [LCV-PRE-TP.1]
/// - If the core verification loop invariant is violated [LCV-INV-TP.1]
/// - If verification of a light block fails
/// - If the fetching a light block from the primary node fails
#[allow(clippy::nonminimal_bool)]
#[ensures(
ret.is_ok() -> trusted_store_contains_block_at_target_height(
state.light_store.as_ref(),
target_height,
)
)]
pub fn verify_to_target(
&self,
target_height: Height,
state: &mut State,
) -> Result<LightBlock, Error> {
// Let's first look in the store to see whether
// we have already successfully verified this block.
if let Some(light_block) = state.light_store.get_trusted_or_verified(target_height) {
return Ok(light_block);
}
// Get the highest trusted state
let highest = state
.light_store
.highest_trusted_or_verified_before(target_height)
.or_else(|| state.light_store.lowest_trusted_or_verified())
.ok_or_else(Error::no_initial_trusted_state)?;
if target_height >= highest.height() {
// Perform forward verification with bisection
self.verify_forward(target_height, state)
} else {
// Perform sequential backward verification
self.verify_backward(target_height, state)
}
}
/// Perform forward verification with bisection.
fn verify_forward(
&self,
target_height: Height,
state: &mut State,
) -> Result<LightBlock, Error> {
let mut current_height = target_height;
loop {
let now = self.clock.now();
// Get the latest trusted state
let trusted_block = state
.light_store
.highest_trusted_or_verified_before(target_height)
.ok_or_else(Error::no_initial_trusted_state)?;
if target_height < trusted_block.height() {
return Err(Error::target_lower_than_trusted_state(
target_height,
trusted_block.height(),
));
}
// Check invariant [LCV-INV-TP.1]
if !is_within_trust_period(&trusted_block, self.options.trusting_period, now) {
return Err(Error::trusted_state_outside_trusting_period(
Box::new(trusted_block),
self.options,
));
}
// Log the current height as a dependency of the block at the target height
state.trace_block(target_height, current_height);
// If the trusted state is now at a height equal to the target height, we are done.
// [LCV-DIST-LIFE.1]
if target_height == trusted_block.height() {
return Ok(trusted_block);
}
// Fetch the block at the current height from the light store if already present,
// or from the primary peer otherwise.
let (current_block, status) = self.get_or_fetch_block(current_height, state)?;
// Validate and verify the current block
let verdict = self.verifier.verify_update_header(
current_block.as_untrusted_state(),
trusted_block.as_trusted_state(),
&self.options,
now,
);
match verdict {
Verdict::Success => {
// Verification succeeded, add the block to the light store with
// the `Verified` status or higher if already trusted.
let new_status = Status::most_trusted(Status::Verified, status);
state.light_store.update(¤t_block, new_status);
// Log the trusted height as a dependency of the block at the current height
state.trace_block(current_height, trusted_block.height());
},
Verdict::Invalid(e) => {
// Verification failed, add the block to the light store with `Failed` status,
// and abort.
state.light_store.update(¤t_block, Status::Failed);
return Err(Error::invalid_light_block(e));
},
Verdict::NotEnoughTrust(_) => {
// The current block cannot be trusted because of a missing overlap in the
// validator sets. Add the block to the light store with
// the `Unverified` status. This will engage bisection in an
// attempt to raise the height of the highest trusted state
// until there is enough overlap.
state.light_store.update(¤t_block, Status::Unverified);
},
}
// Compute the next height to fetch and verify
current_height =
self.scheduler
.schedule(state.light_store.as_ref(), current_height, target_height);
}
}
/// Stub for when "unstable" feature is disabled.
#[doc(hidden)]
#[cfg(not(feature = "unstable"))]
fn verify_backward(
&self,
target_height: Height,
state: &mut State,
) -> Result<LightBlock, Error> {
let trusted_state = state
.light_store
.highest_trusted_or_verified_before(target_height)
.or_else(|| state.light_store.lowest_trusted_or_verified())
.ok_or_else(Error::no_initial_trusted_state)?;
Err(Error::target_lower_than_trusted_state(
target_height,
trusted_state.height(),
))
}
/// Perform sequential backward verification.
///
/// Backward verification is implemented by taking a sliding window
/// of length two between the trusted state and the target block and
/// checking whether the last_block_id hash of the higher block
/// matches the computed hash of the lower block.
///
/// ## Performance
/// The algorithm implemented is very inefficient in case the target
/// block is much lower than the highest trusted state.
/// For a trusted state at height `T`, and a target block at height `H`,
/// it will fetch and check hashes of `T - H` blocks.
///
/// ## Stability
/// This feature is only available if the `unstable` flag of is enabled.
/// If the flag is disabled, then any attempt to verify a block whose
/// height is lower than the highest trusted state will result in a
/// `TargetLowerThanTrustedState` error.
#[cfg(feature = "unstable")]
fn verify_backward(
&self,
target_height: Height,
state: &mut State,
) -> Result<LightBlock, Error> {
use tendermint::crypto::default::Sha256;
let root = state
.light_store
.highest_trusted_or_verified_before(target_height)
.or_else(|| state.light_store.lowest_trusted_or_verified())
.ok_or_else(Error::no_initial_trusted_state)?;
assert!(root.height() >= target_height);
// Check invariant [LCV-INV-TP.1]
if !is_within_trust_period(&root, self.options.trusting_period, self.clock.now()) {
return Err(Error::trusted_state_outside_trusting_period(
Box::new(root),
self.options,
));
}
// Compute a range of `Height`s from `trusted_height - 1` to `target_height`, inclusive.
let range = (target_height.value()..root.height().value()).rev();
let heights = range.map(|h| Height::try_from(h).unwrap());
let mut latest = root;
for height in heights {
let (current, _status) = self.get_or_fetch_block(height, state)?;
let latest_last_block_id = latest
.signed_header
.header
.last_block_id
.ok_or_else(|| Error::missing_last_block_id(latest.height()))?;
let current_hash = current.signed_header.header.hash_with::<Sha256>();
if current_hash != latest_last_block_id.hash {
return Err(Error::invalid_adjacent_headers(
current_hash,
latest_last_block_id.hash,
));
}
// `latest` and `current` are linked together by `last_block_id`,
// therefore it is not relevant which we verified first.
// For consistency, we say that `latest` was verifed using
// `current` so that the trace is always pointing down the chain.
state.light_store.insert(current.clone(), Status::Trusted);
state.light_store.insert(latest.clone(), Status::Trusted);
state.trace_block(latest.height(), current.height());
latest = current;
}
// We reached the target height.
assert_eq!(latest.height(), target_height);
Ok(latest)
}
/// Look in the light store for a block from the given peer at the given height,
/// which has not previously failed verification (ie. its status is not `Failed`).
///
/// If one cannot be found, fetch the block from the given peer and store
/// it in the light store with `Unverified` status.
///
/// ## Postcondition
/// - The provider of block that is returned matches the given peer.
#[ensures(ret.as_ref().map(|(lb, _)| lb.provider == self.peer).unwrap_or(true))]
pub fn get_or_fetch_block(
&self,
height: Height,
state: &mut State,
) -> Result<(LightBlock, Status), Error> {
let block = state.light_store.get_non_failed(height);
if let Some(block) = block {
return Ok(block);
}
let block = self
.io
.fetch_light_block(AtHeight::At(height))
.map_err(Error::io)?;
state.light_store.insert(block.clone(), Status::Unverified);
Ok((block, Status::Unverified))
}
/// Get the block at the given height or the latest block from the chain if the given height is
/// lower than the latest height.
pub fn get_target_block_or_latest(
&mut self,
height: Height,
state: &mut State,
) -> Result<TargetOrLatest, Error> {
let block = state.light_store.get_non_failed(height);
if let Some((block, _)) = block {
return Ok(TargetOrLatest::Target(block));
}
let block = self.io.fetch_light_block(AtHeight::At(height));
if let Ok(block) = block {
return Ok(TargetOrLatest::Target(block));
}
let latest = self
.io
.fetch_light_block(AtHeight::Highest)
.map_err(Error::io)?;
if latest.height() == height {
Ok(TargetOrLatest::Target(latest))
} else {
Ok(TargetOrLatest::Latest(latest))
}
}
}
pub enum TargetOrLatest {
Latest(LightBlock),
Target(LightBlock),
}