-
Notifications
You must be signed in to change notification settings - Fork 36
/
body_sync.rs
196 lines (172 loc) · 5.33 KB
/
body_sync.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
// Copyright 2020 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use chrono::prelude::{DateTime, Utc};
use chrono::Duration;
use std::cmp;
use std::sync::Arc;
use crate::chain::{self, SyncState, SyncStatus};
use crate::core::core::hash::Hash;
use crate::p2p;
pub struct BodySync {
chain: Arc<chain::Chain>,
peers: Arc<p2p::Peers>,
sync_state: Arc<SyncState>,
blocks_requested: u64,
receive_timeout: DateTime<Utc>,
prev_blocks_received: u64,
}
impl BodySync {
pub fn new(
sync_state: Arc<SyncState>,
peers: Arc<p2p::Peers>,
chain: Arc<chain::Chain>,
) -> BodySync {
BodySync {
sync_state,
peers,
chain,
blocks_requested: 0,
receive_timeout: Utc::now(),
prev_blocks_received: 0,
}
}
/// Check whether a body sync is needed and run it if so.
/// Return true if txhashset download is needed (when requested block is under the horizon).
pub fn check_run(
&mut self,
head: &chain::Tip,
highest_height: u64,
) -> Result<bool, chain::Error> {
// run the body_sync every 5s
if self.body_sync_due()? {
if self.body_sync()? {
return Ok(true);
}
self.sync_state.update(SyncStatus::BodySync {
current_height: head.height,
highest_height: highest_height,
});
}
Ok(false)
}
/// Return true if txhashset download is needed (when requested block is under the horizon).
fn body_sync(&mut self) -> Result<bool, chain::Error> {
let mut hashes: Option<Vec<Hash>> = Some(vec![]);
let txhashset_needed = match self
.chain
.check_txhashset_needed("body_sync".to_owned(), &mut hashes)
{
Ok(v) => v,
Err(e) => {
error!("body_sync: failed to call txhashset_needed: {:?}", e);
return Ok(false);
}
};
if txhashset_needed {
debug!(
"body_sync: cannot sync full blocks earlier than horizon. will request txhashset",
);
return Ok(true);
}
let mut hashes = match hashes {
Some(v) => v,
None => {
error!("unexpected: hashes is None");
return Ok(false);
}
};
hashes.reverse();
let peers = self.peers.more_work_peers()?;
// if we have 5 peers to sync from then ask for 50 blocks total (peer_count *
// 10) max will be 80 if all 8 peers are advertising more work
// also if the chain is already saturated with orphans, throttle
let block_count = cmp::min(
cmp::min(100, peers.len() * 10),
chain::MAX_ORPHAN_SIZE.saturating_sub(self.chain.orphans_len()) + 1,
);
let hashes_to_get = hashes
.iter()
.filter(|x| {
// only ask for blocks that we have not yet processed
// either successfully stored or in our orphan list
!self.chain.get_block(x).is_ok() && !self.chain.is_orphan(x)
})
.take(block_count)
.collect::<Vec<_>>();
if hashes_to_get.len() > 0 {
let body_head = self.chain.head()?;
let header_head = self.chain.header_head()?;
debug!(
"block_sync: {}/{} requesting blocks {:?} from {} peers",
body_head.height,
header_head.height,
hashes_to_get,
peers.len(),
);
// reinitialize download tracking state
self.blocks_requested = 0;
self.receive_timeout = Utc::now() + Duration::seconds(6);
let mut peers_iter = peers.iter();
//let mut peers_iter = peers.iter().cycle();
for hash in hashes_to_get.clone() {
if let Some(peer) = peers_iter.next() {
if let Err(e) = peer.send_block_request(*hash, chain::Options::SYNC) {
debug!("Skipped request to {}: {:?}", peer.info.addr, e);
peer.stop();
} else {
self.blocks_requested += 1;
}
}
}
}
return Ok(false);
}
// Should we run block body sync and ask for more full blocks?
fn body_sync_due(&mut self) -> Result<bool, chain::Error> {
let blocks_received = self.blocks_received()?;
// some blocks have been requested
if self.blocks_requested > 0 {
// but none received since timeout, ask again
let timeout = Utc::now() > self.receive_timeout;
if timeout && blocks_received <= self.prev_blocks_received {
debug!(
"body_sync: expecting {} more blocks and none received for a while",
self.blocks_requested,
);
return Ok(true);
}
}
if blocks_received > self.prev_blocks_received {
// some received, update for next check
self.receive_timeout = Utc::now() + Duration::seconds(1);
self.blocks_requested = self
.blocks_requested
.saturating_sub(blocks_received - self.prev_blocks_received);
self.prev_blocks_received = blocks_received;
}
// off by one to account for broadcast adding a couple orphans
if self.blocks_requested < 2 {
// no pending block requests, ask more
debug!("body_sync: no pending block request, asking more");
return Ok(true);
}
Ok(false)
}
// Total numbers received on this chain, including the head and orphans
fn blocks_received(&self) -> Result<u64, chain::Error> {
Ok((self.chain.head()?).height
+ self.chain.orphans_len() as u64
+ self.chain.orphans_evicted_len() as u64)
}
}