-
Notifications
You must be signed in to change notification settings - Fork 235
/
Copy pathheaders_process.rs
372 lines (341 loc) · 12.6 KB
/
headers_process.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
use crate::block_status::BlockStatus;
use crate::synchronizer::Synchronizer;
use crate::types::{ActiveChain, SyncShared};
use crate::{Status, StatusCode};
use ckb_constant::sync::MAX_HEADERS_LEN;
use ckb_error::Error;
use ckb_logger::{debug, log_enabled, warn, Level};
use ckb_network::{CKBProtocolContext, PeerIndex};
use ckb_traits::HeaderFieldsProvider;
use ckb_types::{core, packed, prelude::*};
use ckb_verification::{HeaderError, HeaderVerifier};
use ckb_verification_traits::Verifier;
pub struct HeadersProcess<'a> {
message: packed::SendHeadersReader<'a>,
synchronizer: &'a Synchronizer,
peer: PeerIndex,
nc: &'a dyn CKBProtocolContext,
active_chain: ActiveChain,
}
impl<'a> HeadersProcess<'a> {
pub fn new(
message: packed::SendHeadersReader<'a>,
synchronizer: &'a Synchronizer,
peer: PeerIndex,
nc: &'a dyn CKBProtocolContext,
) -> Self {
let active_chain = synchronizer.shared.active_chain();
HeadersProcess {
message,
nc,
synchronizer,
peer,
active_chain,
}
}
fn is_continuous(&self, headers: &[core::HeaderView]) -> bool {
for window in headers.windows(2) {
if let [parent, header] = &window {
if header.data().raw().parent_hash() != parent.hash() {
debug!(
"header.parent_hash {} parent.hash {}",
header.parent_hash(),
parent.hash()
);
return false;
}
}
}
true
}
pub fn accept_first(&self, first: &core::HeaderView) -> ValidationResult {
let shared: &SyncShared = self.synchronizer.shared();
let verifier = HeaderVerifier::new(shared, shared.consensus());
let acceptor = HeaderAcceptor::new(first, self.peer, verifier, self.active_chain.clone());
acceptor.accept()
}
fn debug(&self) {
if log_enabled!(Level::Debug) {
// Regain the updated best known
let shared_best_known = self.synchronizer.shared.state().shared_best_header();
let peer_best_known = self.synchronizer.peers().get_best_known_header(self.peer);
debug!(
"chain: num={}, diff={:#x};",
self.active_chain.tip_number(),
self.active_chain.total_difficulty()
);
debug!(
"shared best_known_header: num={}, diff={:#x}, hash={};",
shared_best_known.number(),
shared_best_known.total_difficulty(),
shared_best_known.hash(),
);
if let Some(header) = peer_best_known {
debug!(
"peer's best_known_header: peer: {}, num={}; diff={:#x}, hash={};",
self.peer,
header.number(),
header.total_difficulty(),
header.hash()
);
} else {
debug!("state: null;");
}
debug!("peer: {}", self.peer);
}
}
pub fn execute(self) -> Status {
debug!("HeadersProcess begins");
let shared: &SyncShared = self.synchronizer.shared();
let consensus = shared.consensus();
let headers = self
.message
.headers()
.to_entity()
.into_iter()
.map(packed::Header::into_view)
.collect::<Vec<_>>();
if headers.len() > MAX_HEADERS_LEN {
warn!("HeadersProcess is oversized");
return StatusCode::HeadersIsInvalid.with_context("oversize");
}
if headers.is_empty() {
// Empty means that the other peer's tip may be consistent with our own best known,
// but empty cannot 100% confirm this, so it does not set the other peer's best header
// to the shared best known.
// This action means that if the newly connected node has not been sync with headers,
// it cannot be used as a synchronization node.
debug!("HeadersProcess is_empty (synchronized)");
if let Some(mut state) = self.synchronizer.peers().state.get_mut(&self.peer) {
self.synchronizer
.shared()
.state()
.tip_synced(state.value_mut());
}
return Status::ok();
}
if !self.is_continuous(&headers) {
warn!("HeadersProcess is not continuous");
return StatusCode::HeadersIsInvalid.with_context("not continuous");
}
let result = self.accept_first(&headers[0]);
match result.state {
ValidationState::Invalid => {
debug!(
"HeadersProcess accept_first result is invalid, error = {:?}, first header = {:?}",
result.error, headers[0]
);
return StatusCode::HeadersIsInvalid
.with_context(format!("accept first header {:?}", headers[0]));
}
ValidationState::TemporaryInvalid => {
debug!(
"HeadersProcess accept_first result is temporary invalid, first header = {:?}",
headers[0]
);
return Status::ok();
}
ValidationState::Valid => {
// Valid, do nothing
}
};
for header in headers.iter().skip(1) {
let verifier = HeaderVerifier::new(shared, consensus);
let acceptor =
HeaderAcceptor::new(header, self.peer, verifier, self.active_chain.clone());
let result = acceptor.accept();
match result.state {
ValidationState::Invalid => {
debug!(
"HeadersProcess accept result is invalid, error = {:?}, header = {:?}",
result.error, headers,
);
return StatusCode::HeadersIsInvalid
.with_context(format!("accept header {header:?}"));
}
ValidationState::TemporaryInvalid => {
debug!(
"HeadersProcess accept result is temporarily invalid, header = {:?}",
header
);
return Status::ok();
}
ValidationState::Valid => {
// Valid, do nothing
}
};
}
self.debug();
if headers.len() == MAX_HEADERS_LEN {
let start = headers.last().expect("empty checked").into();
self.active_chain
.send_getheaders_to_peer(self.nc, self.peer, start);
} else if let Some(mut state) = self.synchronizer.peers().state.get_mut(&self.peer) {
self.synchronizer
.shared()
.state()
.tip_synced(state.value_mut());
}
// If we're in IBD, we want outbound peers that will serve us a useful
// chain. Disconnect peers that are on chains with insufficient work.
let peer_flags = self
.synchronizer
.peers()
.get_flag(self.peer)
.unwrap_or_default();
if self.active_chain.is_initial_block_download()
&& headers.len() != MAX_HEADERS_LEN
&& (!peer_flags.is_protect && !peer_flags.is_whitelist && peer_flags.is_outbound)
{
debug!("Disconnect an unprotected outbound peer ({})", self.peer);
if let Err(err) = self
.nc
.disconnect(self.peer, "useless outbound peer in IBD")
{
return StatusCode::Network.with_context(format!("Disconnect error: {err:?}"));
}
}
Status::ok()
}
}
pub struct HeaderAcceptor<'a, DL: HeaderFieldsProvider> {
header: &'a core::HeaderView,
active_chain: ActiveChain,
peer: PeerIndex,
verifier: HeaderVerifier<'a, DL>,
}
impl<'a, DL: HeaderFieldsProvider> HeaderAcceptor<'a, DL> {
pub fn new(
header: &'a core::HeaderView,
peer: PeerIndex,
verifier: HeaderVerifier<'a, DL>,
active_chain: ActiveChain,
) -> Self {
HeaderAcceptor {
header,
peer,
verifier,
active_chain,
}
}
pub fn prev_block_check(&self, state: &mut ValidationResult) -> Result<(), ()> {
if self.active_chain.contains_block_status(
&self.header.data().raw().parent_hash(),
BlockStatus::BLOCK_INVALID,
) {
state.invalid(Some(ValidationError::InvalidParent));
return Err(());
}
Ok(())
}
pub fn non_contextual_check(&self, state: &mut ValidationResult) -> Result<(), bool> {
self.verifier.verify(self.header).map_err(|error| {
debug!(
"HeadersProcess accepted {:?} error {:?}",
self.header.number(),
error
);
// HeaderVerifier return HeaderError or UnknownParentError
if let Some(header_error) = error.downcast_ref::<HeaderError>() {
if header_error.is_too_new() {
state.temporary_invalid(Some(ValidationError::Verify(error)));
false
} else {
state.invalid(Some(ValidationError::Verify(error)));
true
}
} else {
state.invalid(Some(ValidationError::Verify(error)));
true
}
})
}
pub fn version_check(&self, state: &mut ValidationResult) -> Result<(), ()> {
if self.header.version() != 0 {
state.invalid(Some(ValidationError::Version));
Err(())
} else {
Ok(())
}
}
pub fn accept(&self) -> ValidationResult {
let mut result = ValidationResult::default();
let shared = self.active_chain.shared();
let state = shared.state();
// FIXME If status == BLOCK_INVALID then return early. But which error
// type should we return?
let status = self.active_chain.get_block_status(&self.header.hash());
if status.contains(BlockStatus::HEADER_VALID) {
let header_index = shared
.get_header_index_view(
&self.header.hash(),
status.contains(BlockStatus::BLOCK_STORED),
)
.expect("header with HEADER_VALID should exist")
.as_header_index();
state
.peers()
.may_set_best_known_header(self.peer, header_index);
return result;
}
if self.prev_block_check(&mut result).is_err() {
debug!(
"HeadersProcess rejected invalid-parent header: {} {}",
self.header.number(),
self.header.hash(),
);
state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID);
return result;
}
if let Some(is_invalid) = self.non_contextual_check(&mut result).err() {
debug!(
"HeadersProcess rejected non-contextual header: {} {}",
self.header.number(),
self.header.hash(),
);
if is_invalid {
state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID);
}
return result;
}
if self.version_check(&mut result).is_err() {
debug!(
"HeadersProcess rejected invalid-version header: {} {}",
self.header.number(),
self.header.hash(),
);
state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID);
return result;
}
shared.insert_valid_header(self.peer, self.header);
result
}
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub enum ValidationState {
#[default]
Valid,
TemporaryInvalid,
Invalid,
}
#[derive(Debug)]
pub enum ValidationError {
Verify(Error),
Version,
InvalidParent,
}
#[derive(Debug, Default)]
pub struct ValidationResult {
pub error: Option<ValidationError>,
pub state: ValidationState,
}
impl ValidationResult {
pub fn invalid(&mut self, error: Option<ValidationError>) {
self.error = error;
self.state = ValidationState::Invalid;
}
pub fn temporary_invalid(&mut self, error: Option<ValidationError>) {
self.error = error;
self.state = ValidationState::TemporaryInvalid;
}
}