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
use crate::{
chain::Client,
config::ProtocolId,
request_responses::{IncomingRequest, OutgoingResponse, ProtocolConfig},
schema::v1::{StateEntry, StateRequest, StateResponse},
PeerId, ReputationChange,
};
use codec::{Decode, Encode};
use futures::{
channel::{mpsc, oneshot},
stream::StreamExt,
};
use log::debug;
use lru::LruCache;
use prost::Message;
use sp_runtime::{generic::BlockId, traits::Block as BlockT};
use std::{
hash::{Hash, Hasher},
sync::Arc,
time::Duration,
};
const LOG_TARGET: &str = "sync";
const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
const MAX_NUMBER_OF_SAME_REQUESTS_PER_PEER: usize = 2;
mod rep {
use super::ReputationChange as Rep;
pub const SAME_REQUEST: Rep = Rep::new(i32::MIN, "Same state request multiple times");
}
pub fn generate_protocol_config(protocol_id: &ProtocolId) -> ProtocolConfig {
ProtocolConfig {
name: generate_protocol_name(protocol_id).into(),
max_request_size: 1024 * 1024,
max_response_size: 16 * 1024 * 1024,
request_timeout: Duration::from_secs(40),
inbound_queue: None,
}
}
fn generate_protocol_name(protocol_id: &ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/state/1");
s
}
#[derive(Eq, PartialEq, Clone)]
struct SeenRequestsKey<B: BlockT> {
peer: PeerId,
block: B::Hash,
start: Vec<u8>,
}
impl<B: BlockT> Hash for SeenRequestsKey<B> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.peer.hash(state);
self.block.hash(state);
self.start.hash(state);
}
}
enum SeenRequestsValue {
First,
Fulfilled(usize),
}
pub struct StateRequestHandler<B: BlockT> {
client: Arc<dyn Client<B>>,
request_receiver: mpsc::Receiver<IncomingRequest>,
seen_requests: LruCache<SeenRequestsKey<B>, SeenRequestsValue>,
}
impl<B: BlockT> StateRequestHandler<B> {
pub fn new(
protocol_id: &ProtocolId,
client: Arc<dyn Client<B>>,
num_peer_hint: usize,
) -> (Self, ProtocolConfig) {
let (tx, request_receiver) = mpsc::channel(num_peer_hint);
let mut protocol_config = generate_protocol_config(protocol_id);
protocol_config.inbound_queue = Some(tx);
let seen_requests = LruCache::new(num_peer_hint * 2);
(Self { client, request_receiver, seen_requests }, protocol_config)
}
pub async fn run(mut self) {
while let Some(request) = self.request_receiver.next().await {
let IncomingRequest { peer, payload, pending_response } = request;
match self.handle_request(payload, pending_response, &peer) {
Ok(()) => debug!(target: LOG_TARGET, "Handled block request from {}.", peer),
Err(e) => debug!(
target: LOG_TARGET,
"Failed to handle state request from {}: {}", peer, e,
),
}
}
}
fn handle_request(
&mut self,
payload: Vec<u8>,
pending_response: oneshot::Sender<OutgoingResponse>,
peer: &PeerId,
) -> Result<(), HandleRequestError> {
let request = StateRequest::decode(&payload[..])?;
let block: B::Hash = Decode::decode(&mut request.block.as_ref())?;
let key =
SeenRequestsKey { peer: *peer, block: block.clone(), start: request.start.clone() };
let mut reputation_changes = Vec::new();
match self.seen_requests.get_mut(&key) {
Some(SeenRequestsValue::First) => {},
Some(SeenRequestsValue::Fulfilled(ref mut requests)) => {
*requests = requests.saturating_add(1);
if *requests > MAX_NUMBER_OF_SAME_REQUESTS_PER_PEER {
reputation_changes.push(rep::SAME_REQUEST);
}
},
None => {
self.seen_requests.put(key.clone(), SeenRequestsValue::First);
},
}
log::trace!(
target: LOG_TARGET,
"Handling state request from {}: Block {:?}, Starting at {:?}, no_proof={}",
peer,
request.block,
sp_core::hexdisplay::HexDisplay::from(&request.start),
request.no_proof,
);
let result = if reputation_changes.is_empty() {
let mut response = StateResponse::default();
if !request.no_proof {
let (proof, count) = self.client.read_proof_collection(
&BlockId::hash(block),
&request.start,
MAX_RESPONSE_BYTES,
)?;
response.proof = proof.encode();
if count == 0 {
response.complete = true;
}
} else {
let entries = self.client.storage_collection(
&BlockId::hash(block),
&request.start,
MAX_RESPONSE_BYTES,
)?;
response.entries =
entries.into_iter().map(|(key, value)| StateEntry { key, value }).collect();
if response.entries.is_empty() {
response.complete = true;
}
}
log::trace!(
target: LOG_TARGET,
"StateResponse contains {} keys, {}, proof nodes, complete={}, from {:?} to {:?}",
response.entries.len(),
response.proof.len(),
response.complete,
response.entries.first().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)),
response.entries.last().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)),
);
if let Some(value) = self.seen_requests.get_mut(&key) {
if let SeenRequestsValue::First = value {
*value = SeenRequestsValue::Fulfilled(1);
}
}
let mut data = Vec::with_capacity(response.encoded_len());
response.encode(&mut data)?;
Ok(data)
} else {
Err(())
};
pending_response
.send(OutgoingResponse { result, reputation_changes, sent_feedback: None })
.map_err(|_| HandleRequestError::SendResponse)
}
}
#[derive(derive_more::Display, derive_more::From)]
enum HandleRequestError {
#[display(fmt = "Failed to decode request: {}.", _0)]
DecodeProto(prost::DecodeError),
#[display(fmt = "Failed to encode response: {}.", _0)]
EncodeProto(prost::EncodeError),
#[display(fmt = "Failed to decode block hash: {}.", _0)]
InvalidHash(codec::Error),
Client(sp_blockchain::Error),
#[display(fmt = "Failed to send response.")]
SendResponse,
}