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
use std::sync::Arc;
use nimiq_block::Block;
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_blockchain_proxy::BlockchainProxy;
use nimiq_hash::Blake2bHash;
use nimiq_network_interface::{
network::{CloseReason, Network},
request::RequestError,
};
use nimiq_primitives::policy::Policy;
use crate::{
messages::{BlockError, MacroChain, MacroChainError, RequestMacroChain},
sync::{
light::LightMacroSync,
sync_interface::{EpochIds, MacroSync, MacroSyncReturn},
},
};
impl<TNetwork: Network> LightMacroSync<TNetwork> {
/// Requests epoch IDs from a peer by sending a macro chain request.
/// Performs basic validation on the result and may ban the peer on invalid responses.
pub(crate) async fn request_epoch_ids(
blockchain: BlockchainProxy,
network: Arc<TNetwork>,
peer_id: TNetwork::PeerId,
) -> Option<EpochIds<TNetwork::PeerId>> {
let (locators, epoch_number) = {
// Order matters here. The first hash found by the recipient of the request will be
// used, so they need to be in backwards block height order.
let blockchain = blockchain.read();
let election_head = blockchain.election_head();
let macro_head = blockchain.macro_head();
// So if there is a checkpoint hash that should be included in addition to the election
// block hash, it should come first.
let mut locators = vec![];
if macro_head.hash() != election_head.hash() {
locators.push(macro_head.hash());
}
// The election block is at the end here
locators.push(election_head.hash());
(locators, election_head.epoch_number())
};
let result = Self::request_macro_chain(
Arc::clone(&network),
peer_id,
locators,
Self::MAX_REQUEST_EPOCHS,
)
.await;
match result {
Ok(Err(error)) => {
debug!(%error, "Error requesting macro chain");
Some(EpochIds {
locator_found: false,
ids: Vec::new(),
checkpoint: None,
first_epoch_number: 0,
sender: peer_id,
})
}
Ok(Ok(macro_chain)) => {
// Validate that the maximum number of epochs is not exceeded.
if macro_chain.epochs.len() > Self::MAX_REQUEST_EPOCHS as usize {
log::warn!(
num_epochs = macro_chain.epochs.len(),
%peer_id,
"Banning peer because requesting macro chain failed: too many epochs returned"
);
network
.disconnect_peer(peer_id, CloseReason::MaliciousPeer)
.await;
return None;
}
// Sanity-check checkpoint block number:
// * is in checkpoint epoch
// * is a non-election macro block
if let Some(checkpoint) = ¯o_chain.checkpoint {
let checkpoint_epoch = epoch_number + macro_chain.epochs.len() as u32 + 1;
if Policy::epoch_at(checkpoint.block_number) != checkpoint_epoch
|| !Policy::is_macro_block_at(checkpoint.block_number)
|| Policy::is_election_block_at(checkpoint.block_number)
{
// Peer provided an invalid checkpoint block number, close connection.
log::warn!(
block_number = checkpoint.block_number,
checkpoint_epoch,
%peer_id,
"Banning peer because requesting macro chain failed: invalid checkpoint"
);
network
.disconnect_peer(peer_id, CloseReason::MaliciousPeer)
.await;
return None;
}
}
log::debug!(
received_epochs = macro_chain.epochs.len(),
start_epoch = epoch_number + 1,
checkpoint = macro_chain.checkpoint.is_some(),
sender = %peer_id,
"Received epoch_ids"
);
Some(EpochIds {
locator_found: true,
ids: macro_chain.epochs,
checkpoint: macro_chain.checkpoint,
first_epoch_number: epoch_number as usize + 1,
sender: peer_id,
})
}
Err(error) => {
log::warn!(%error, %peer_id, "Request macro chain failed");
network.disconnect_peer(peer_id, CloseReason::Error).await;
None
}
}
}
/// Creates block header requests for election blocks and an optional checkpoint
/// received from a peer.
pub(crate) fn request_macro_headers(
&mut self,
mut epoch_ids: EpochIds<TNetwork::PeerId>,
) -> Option<MacroSyncReturn<TNetwork::PeerId>> {
// Read our current blockchain state.
let (our_epoch_id, our_epoch_number, our_block_number) = {
let blockchain = self.blockchain.read();
(
blockchain.election_head_hash(),
blockchain.election_head().epoch_number() as usize,
blockchain.block_number(),
)
};
// Truncate epoch_ids by epoch_number: Discard all epoch_ids prior to our accepted state.
if !epoch_ids.ids.is_empty() && epoch_ids.first_epoch_number <= our_epoch_number {
let peers_epoch_number = epoch_ids.last_epoch_number();
if peers_epoch_number < our_epoch_number
|| (peers_epoch_number == our_epoch_number && epoch_ids.checkpoint.is_none())
{
// Peer is behind, emit it as useless.
debug!(
our_epoch_number,
peers_epoch_number,
peer = %epoch_ids.sender,
"Peer is behind"
);
return Some(MacroSyncReturn::Outdated(epoch_ids.sender));
} else {
// Check that the epoch_id sent by the peer at our current epoch number corresponds to
// our accepted state. If it doesn't, the peer is on a "permanent" fork, so we ban it.
let peers_epoch_id =
&epoch_ids.ids[our_epoch_number - epoch_ids.first_epoch_number];
if our_epoch_id != *peers_epoch_id {
// TODO Actually ban the peer.
debug!(
our_epoch_number,
%our_epoch_id,
%peers_epoch_id,
peer = %epoch_ids.sender,
"Peer is on a different chain"
);
return Some(MacroSyncReturn::Outdated(epoch_ids.sender));
}
epoch_ids.ids = epoch_ids
.ids
.split_off(our_epoch_number - epoch_ids.first_epoch_number + 1);
epoch_ids.first_epoch_number = our_epoch_number + 1;
}
}
// Discard checkpoint block if it is old.
if let Some(checkpoint) = &epoch_ids.checkpoint
&& checkpoint.block_number <= our_block_number
{
epoch_ids.checkpoint = None;
}
// After discarding all epoch_ids & checkpoint prior to our current state
// It could happen that we don't have anything new to learn from this peer
if epoch_ids.ids.is_empty() && epoch_ids.checkpoint.is_none() {
log::debug!("Nothing new to learn from this peer, emit it as good");
return Some(MacroSyncReturn::Good(epoch_ids.sender));
}
// The highest block this peer reports: once our head reaches it, the peer is fully synced
// from our side. Drives the tip-follow re-request in `poll_macro_block_queue`. A checkpoint
// (a later, non-election macro block) is always higher than the last election block.
//
// A peer reporting a nonsensically large epoch number yields a `u32::MAX` target it has no
// hope of reaching, so it just sits in `waiting_macro_peers` until it disconnects. Harmless:
// it never gets emitted, but it also wastes nothing (it is requested no blocks).
let target_block_number = if let Some(checkpoint) = &epoch_ids.checkpoint {
checkpoint.block_number
} else {
Policy::election_block_of(epoch_ids.last_epoch_number() as u32).unwrap_or(u32::MAX)
};
log::trace!(%epoch_ids.sender, "Queueing macro block requests");
// Enqueue the election blocks (and optional checkpoint) into the shared, bounded,
// failover-capable macro block queue. Deduplicate against blocks already in flight so
// overlapping epoch_ids from multiple peers don't request the same block twice. The sender
// is passed as the preferred peer; the queue fails over to others on timeout.
let mut ids = Vec::new();
for block_hash in epoch_ids.ids {
if self.in_flight_macro_blocks.insert(block_hash.clone()) {
ids.push((block_hash, Some(epoch_ids.sender)));
}
}
if let Some(checkpoint) = &epoch_ids.checkpoint {
let block_hash = checkpoint.hash.clone();
if self.in_flight_macro_blocks.insert(block_hash.clone()) {
ids.push((block_hash, Some(epoch_ids.sender)));
}
}
// If everything this peer reported is already in flight (driven by another peer) and we
// have already reached its target, it is fully synced now: emit it as good. Otherwise wait
// until the queue advances our head to its target (see `poll_macro_block_queue`).
if ids.is_empty() && target_block_number <= our_block_number {
return Some(MacroSyncReturn::Good(epoch_ids.sender));
}
self.waiting_macro_peers
.insert(epoch_ids.sender, target_block_number);
self.macro_block_queue.add_ids(ids);
None
}
/// Sends a macro block request to a peer.
pub async fn request_macro_block(
network: Arc<TNetwork>,
peer_id: TNetwork::PeerId,
hash: Blake2bHash,
) -> Result<Result<Block, BlockError>, RequestError> {
// Macro sync only needs the header, so the body is not requested
crate::sync::request_block(network, peer_id, hash, false).await
}
/// Sends a macro chain request to a peer, using the provided locators and maximum number of epochs.
pub async fn request_macro_chain(
network: Arc<TNetwork>,
peer_id: TNetwork::PeerId,
locators: Vec<Blake2bHash>,
max_epochs: u16,
) -> Result<Result<MacroChain, MacroChainError>, RequestError> {
network
.request::<RequestMacroChain>(
RequestMacroChain {
locators,
max_epochs,
},
peer_id,
)
.await
}
}