-
Notifications
You must be signed in to change notification settings - Fork 106
/
chain_tip.rs
444 lines (388 loc) · 14.6 KB
/
chain_tip.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Access to Zebra chain tip information.
//!
//! Zebra has 3 different interfaces for access to chain tip information:
//! * [zebra_state::Request](crate::request): [tower::Service] requests about chain state,
//! * [LatestChainTip] for efficient access to the current best tip, and
//! * [ChainTipChange] to `await` specific changes to the chain tip.
use std::sync::Arc;
use tokio::sync::watch;
use zebra_chain::{
block,
chain_tip::ChainTip,
parameters::{Network, NetworkUpgrade},
transaction,
};
use crate::{request::ContextuallyValidBlock, FinalizedBlock};
use TipAction::*;
#[cfg(test)]
mod tests;
/// The internal watch channel data type for [`ChainTipSender`], [`LatestChainTip`],
/// and [`ChainTipChange`].
type ChainTipData = Option<ChainTipBlock>;
/// A chain tip block, with precalculated block data.
///
/// Used to efficiently update [`ChainTipSender`], [`LatestChainTip`],
/// and [`ChainTipChange`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChainTipBlock {
/// The hash of the best chain tip block.
pub hash: block::Hash,
/// The height of the best chain tip block.
pub height: block::Height,
/// The mined transaction IDs of the transactions in `block`,
/// in the same order as `block.transactions`.
pub transaction_hashes: Arc<[transaction::Hash]>,
/// The hash of the previous block in the best chain.
/// This block is immediately behind the best chain tip.
///
/// ## Note
///
/// If the best chain fork has changed, or some blocks have been skipped,
/// this hash will be different to the last returned `ChainTipBlock.hash`.
pub(crate) previous_block_hash: block::Hash,
}
impl From<ContextuallyValidBlock> for ChainTipBlock {
fn from(contextually_valid: ContextuallyValidBlock) -> Self {
let ContextuallyValidBlock {
block,
hash,
height,
new_outputs: _,
transaction_hashes,
chain_value_pool_change: _,
} = contextually_valid;
Self {
hash,
height,
transaction_hashes,
previous_block_hash: block.header.previous_block_hash,
}
}
}
impl From<FinalizedBlock> for ChainTipBlock {
fn from(finalized: FinalizedBlock) -> Self {
let FinalizedBlock {
block,
hash,
height,
new_outputs: _,
transaction_hashes,
} = finalized;
Self {
hash,
height,
transaction_hashes,
previous_block_hash: block.header.previous_block_hash,
}
}
}
/// A sender for changes to the non-finalized and finalized chain tips.
#[derive(Debug)]
pub struct ChainTipSender {
/// Have we got any chain tips from the non-finalized state?
///
/// Once this flag is set, we ignore the finalized state.
/// `None` tips don't set this flag.
non_finalized_tip: bool,
/// The sender channel for chain tip data.
sender: watch::Sender<ChainTipData>,
/// A copy of the data in `sender`.
// TODO: Replace with calls to `watch::Sender::borrow` once Tokio is updated to 1.0.0 (#2573)
active_value: ChainTipData,
}
impl ChainTipSender {
/// Create new linked instances of [`ChainTipSender`], [`LatestChainTip`], and [`ChainTipChange`],
/// using an `initial_tip` and a [`Network`].
pub fn new(
initial_tip: impl Into<Option<ChainTipBlock>>,
network: Network,
) -> (Self, LatestChainTip, ChainTipChange) {
let (sender, receiver) = watch::channel(None);
let mut sender = ChainTipSender {
non_finalized_tip: false,
sender,
active_value: None,
};
let current = LatestChainTip::new(receiver.clone());
let change = ChainTipChange::new(receiver, network);
sender.update(initial_tip);
(sender, current, change)
}
/// Update the latest finalized tip.
///
/// May trigger an update to the best tip.
pub fn set_finalized_tip(&mut self, new_tip: impl Into<Option<ChainTipBlock>>) {
if !self.non_finalized_tip {
self.update(new_tip);
}
}
/// Update the latest non-finalized tip.
///
/// May trigger an update to the best tip.
pub fn set_best_non_finalized_tip(&mut self, new_tip: impl Into<Option<ChainTipBlock>>) {
let new_tip = new_tip.into();
// once the non-finalized state becomes active, it is always populated
// but ignoring `None`s makes the tests easier
if new_tip.is_some() {
self.non_finalized_tip = true;
self.update(new_tip)
}
}
/// Possibly send an update to listeners.
///
/// An update is only sent if the current best tip is different from the last best tip
/// that was sent.
fn update(&mut self, new_tip: impl Into<Option<ChainTipBlock>>) {
let new_tip = new_tip.into();
let needs_update = match (new_tip.as_ref(), self.active_value.as_ref()) {
// since the blocks have been contextually validated,
// we know their hashes cover all the block data
(Some(new_tip), Some(active_value)) => new_tip.hash != active_value.hash,
(Some(_new_tip), None) => true,
(None, _active_value) => false,
};
if needs_update {
let _ = self.sender.send(new_tip.clone());
self.active_value = new_tip;
}
}
}
/// Efficient access to the state's current best chain tip.
///
/// Each method returns data from the latest tip,
/// regardless of how many times you call it.
///
/// Cloned instances provide identical tip data.
///
/// The chain tip data is based on:
/// * the best non-finalized chain tip, if available, or
/// * the finalized tip.
///
/// ## Note
///
/// If a lot of blocks are committed at the same time,
/// the latest tip will skip some blocks in the chain.
#[derive(Clone, Debug)]
pub struct LatestChainTip {
/// The receiver for the current chain tip's data.
receiver: watch::Receiver<ChainTipData>,
}
impl LatestChainTip {
/// Create a new [`LatestChainTip`] from a watch channel receiver.
fn new(receiver: watch::Receiver<ChainTipData>) -> Self {
Self { receiver }
}
}
impl ChainTip for LatestChainTip {
/// Return the height of the best chain tip.
fn best_tip_height(&self) -> Option<block::Height> {
self.receiver.borrow().as_ref().map(|block| block.height)
}
/// Return the block hash of the best chain tip.
fn best_tip_hash(&self) -> Option<block::Hash> {
self.receiver.borrow().as_ref().map(|block| block.hash)
}
/// Return the mined transaction IDs of the transactions in the best chain tip block.
///
/// All transactions with these mined IDs should be rejected from the mempool,
/// even if their authorizing data is different.
fn best_tip_mined_transaction_ids(&self) -> Arc<[transaction::Hash]> {
self.receiver
.borrow()
.as_ref()
.map(|block| block.transaction_hashes.clone())
.unwrap_or_else(|| Arc::new([]))
}
}
/// A chain tip change monitor.
///
/// Awaits changes and resets of the state's best chain tip,
/// returning the latest [`TipAction`] once the state is updated.
///
/// Each cloned instance separately tracks the last block data it provided.
/// If the best chain fork has changed since the last [`tip_change`] on that instance,
/// it returns a [`Reset`].
///
/// The chain tip data is based on:
/// * the best non-finalized chain tip, if available, or
/// * the finalized tip.
#[derive(Debug)]
pub struct ChainTipChange {
/// The receiver for the current chain tip's data.
receiver: watch::Receiver<ChainTipData>,
/// The most recent [`block::Hash`] provided by this instance.
///
/// ## Note
///
/// If the best chain fork has changed, or some blocks have been skipped,
/// this hash will be different to the last returned `ChainTipBlock.hash`.
last_change_hash: Option<block::Hash>,
/// The network for the chain tip.
network: Network,
}
/// Actions that we can take in response to a [`ChainTipChange`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TipAction {
/// The chain tip was updated continuously,
/// using a child `block` of the previous block.
///
/// The genesis block action is a `Grow`.
Grow {
/// Information about the block used to grow the chain.
block: ChainTipBlock,
},
/// The chain tip was reset to a block with `height` and `hash`.
///
/// Resets can happen for different reasons:
/// * a newly created or cloned [`ChainTipChange`], which is behind the current tip,
/// * extending the chain with a network upgrade activation block,
/// * switching to a different best [`Chain`], also known as a rollback, and
/// * receiving multiple blocks since the previous change.
///
/// To keep the code and tests simple, Zebra performs the same reset actions,
/// regardless of the reset reason.
///
/// `Reset`s do not have the transaction hashes from the tip block,
/// because all transactions should be cleared by a reset.
Reset {
/// The block height of the tip, after the chain reset.
height: block::Height,
/// The block hash of the tip, after the chain reset.
///
/// Mainly useful for logging and debugging.
hash: block::Hash,
},
}
impl ChainTipChange {
/// Wait until the tip has changed, then return the corresponding [`TipAction`].
///
/// The returned action describes how the tip has changed
/// since the last call to this method.
///
/// If there have been no changes since the last time this method was called,
/// it waits for the next tip change before returning.
///
/// If there have been multiple changes since the last time this method was called,
/// they are combined into a single [`TipAction::Reset`].
///
/// Returns an error if communication with the state is lost.
///
/// ## Note
///
/// If a lot of blocks are committed at the same time,
/// the change will skip some blocks, and return a [`Reset`].
pub async fn tip_change(&mut self) -> Result<TipAction, watch::error::RecvError> {
let block = self.tip_block_change().await?;
let action = self.action(block.clone());
self.last_change_hash = Some(block.hash);
Ok(action)
}
/// Return an action based on `block` and the last change we returned.
fn action(&self, block: ChainTipBlock) -> TipAction {
// check for an edge case that's dealt with by other code
assert!(
Some(block.hash) != self.last_change_hash,
"ChainTipSender ignores unchanged tips"
);
// If the previous block hash doesn't match, reset.
// We've either:
// - just initialized this instance,
// - changed the best chain to another fork (a rollback), or
// - skipped some blocks in the best chain.
//
// Consensus rules:
//
// > It is possible for a reorganization to occur
// > that rolls back from after the activation height, to before that height.
// > This can handled in the same way as any regular chain orphaning or reorganization,
// > as long as the new chain is valid.
//
// https://zips.z.cash/zip-0200#chain-reorganization
// If we're at a network upgrade activation block, reset.
//
// Consensus rules:
//
// > When the current chain tip height reaches ACTIVATION_HEIGHT,
// > the node's local transaction memory pool SHOULD be cleared of transactions
// > that will never be valid on the post-upgrade consensus branch.
//
// https://zips.z.cash/zip-0200#memory-pool
//
// Skipped blocks can include network upgrade activation blocks.
// Fork changes can activate or deactivate a network upgrade.
// So we must perform the same actions for network upgrades and skipped blocks.
if Some(block.previous_block_hash) != self.last_change_hash
|| NetworkUpgrade::is_activation_height(self.network, block.height)
{
TipAction::reset_with(block)
} else {
TipAction::grow_with(block)
}
}
/// Create a new [`ChainTipChange`] from a watch channel receiver and [`Network`].
fn new(receiver: watch::Receiver<ChainTipData>, network: Network) -> Self {
Self {
receiver,
last_change_hash: None,
network,
}
}
/// Wait until the next chain tip change, then return the corresponding [`ChainTipBlock`].
///
/// Returns an error if communication with the state is lost.
async fn tip_block_change(&mut self) -> Result<ChainTipBlock, watch::error::RecvError> {
loop {
// If there are multiple changes while this code is executing,
// we don't rely on getting the first block or the latest block
// after the change notification.
// Any block update after the change will do,
// we'll catch up with the tip after the next change.
self.receiver.changed().await?;
// Wait until there is actually Some block,
// so we don't have `Option`s inside `TipAction`s.
if let Some(block) = self.best_tip_block() {
return Ok(block);
}
}
}
/// Return the current best [`ChainTipBlock`],
/// or `None` if no block has been committed yet.
fn best_tip_block(&self) -> Option<ChainTipBlock> {
self.receiver.borrow().clone()
}
}
impl Clone for ChainTipChange {
fn clone(&self) -> Self {
Self {
receiver: self.receiver.clone(),
// clear the previous change hash, so the first action is a reset
last_change_hash: None,
network: self.network,
}
}
}
impl TipAction {
/// Is this tip action a [`Reset`]?
pub fn is_reset(&self) -> bool {
matches!(self, Reset { .. })
}
/// Returns the block hash of this tip action,
/// regardless of the underlying variant.
pub fn best_tip_hash(&self) -> block::Hash {
match self {
Grow { block } => block.hash,
Reset { hash, .. } => *hash,
}
}
/// Returns a [`Grow`] based on `block`.
pub(crate) fn grow_with(block: ChainTipBlock) -> Self {
Grow { block }
}
/// Returns a [`Reset`] based on `block`.
pub(crate) fn reset_with(block: ChainTipBlock) -> Self {
Reset {
height: block.height,
hash: block.hash,
}
}
}