1use crate::schema;
26use codec::{self, Decode, Encode};
27use futures::prelude::*;
28use log::{debug, trace};
29use prost::Message;
30use sc_client_api::{BlockBackend, ProofProvider};
31use sc_network::{
32 config::ProtocolId,
33 request_responses::{IncomingRequest, OutgoingResponse},
34 NetworkBackend, ReputationChange,
35};
36use sc_network_types::PeerId;
37use sp_core::{
38 hexdisplay::HexDisplay,
39 storage::{ChildInfo, ChildType, PrefixedStorageKey},
40};
41use sp_runtime::traits::Block;
42use std::{marker::PhantomData, sync::Arc};
43
44const LOG_TARGET: &str = "light-client-request-handler";
45
46const MAX_LIGHT_REQUEST_QUEUE: usize = 20;
49
50pub struct LightClientRequestHandler<B, Client> {
52 request_receiver: async_channel::Receiver<IncomingRequest>,
53 client: Arc<Client>,
55 _block: PhantomData<B>,
56}
57
58impl<B, Client> LightClientRequestHandler<B, Client>
59where
60 B: Block,
61 Client: BlockBackend<B> + ProofProvider<B> + Send + Sync + 'static,
62{
63 pub fn new<N: NetworkBackend<B, <B as Block>::Hash>>(
65 protocol_id: &ProtocolId,
66 fork_id: Option<&str>,
67 client: Arc<Client>,
68 ) -> (Self, N::RequestResponseProtocolConfig) {
69 let (tx, request_receiver) = async_channel::bounded(MAX_LIGHT_REQUEST_QUEUE);
70
71 let protocol_config = super::generate_protocol_config::<_, B, N>(
72 protocol_id,
73 client
74 .block_hash(0u32.into())
75 .ok()
76 .flatten()
77 .expect("Genesis block exists; qed"),
78 fork_id,
79 tx,
80 );
81
82 (Self { client, request_receiver, _block: PhantomData::default() }, protocol_config)
83 }
84
85 pub async fn run(mut self) {
87 while let Some(request) = self.request_receiver.next().await {
88 let IncomingRequest { peer, payload, pending_response } = request;
89
90 match self.handle_request(peer, payload) {
91 Ok(response_data) => {
92 let response = OutgoingResponse {
93 result: Ok(response_data),
94 reputation_changes: Vec::new(),
95 sent_feedback: None,
96 };
97
98 match pending_response.send(response) {
99 Ok(()) => trace!(
100 target: LOG_TARGET,
101 "Handled light client request from {}.",
102 peer,
103 ),
104 Err(_) => debug!(
105 target: LOG_TARGET,
106 "Failed to handle light client request from {}: {}",
107 peer,
108 HandleRequestError::SendResponse,
109 ),
110 };
111 },
112 Err(e) => {
113 debug!(
114 target: LOG_TARGET,
115 "Failed to handle light client request from {}: {}", peer, e,
116 );
117
118 let reputation_changes = match e {
119 HandleRequestError::BadRequest(_) => {
120 vec![ReputationChange::new(-(1 << 12), "bad request")]
121 },
122 _ => Vec::new(),
123 };
124
125 let response = OutgoingResponse {
126 result: Err(()),
127 reputation_changes,
128 sent_feedback: None,
129 };
130
131 if pending_response.send(response).is_err() {
132 debug!(
133 target: LOG_TARGET,
134 "Failed to handle light client request from {}: {}",
135 peer,
136 HandleRequestError::SendResponse,
137 );
138 };
139 },
140 }
141 }
142 }
143
144 fn handle_request(
145 &mut self,
146 peer: PeerId,
147 payload: Vec<u8>,
148 ) -> Result<Vec<u8>, HandleRequestError> {
149 let request = schema::v1::light::Request::decode(&payload[..])?;
150
151 let response = match &request.request {
152 Some(schema::v1::light::request::Request::RemoteCallRequest(r)) =>
153 self.on_remote_call_request(&peer, r)?,
154 Some(schema::v1::light::request::Request::RemoteReadRequest(r)) =>
155 self.on_remote_read_request(&peer, r)?,
156 Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) =>
157 self.on_remote_read_child_request(&peer, r)?,
158 None =>
159 return Err(HandleRequestError::BadRequest("Remote request without request data.")),
160 };
161
162 let mut data = Vec::new();
163 response.encode(&mut data)?;
164
165 Ok(data)
166 }
167
168 fn on_remote_call_request(
169 &mut self,
170 peer: &PeerId,
171 request: &schema::v1::light::RemoteCallRequest,
172 ) -> Result<schema::v1::light::Response, HandleRequestError> {
173 trace!("Remote call request from {} ({} at {:?}).", peer, request.method, request.block,);
174
175 let block = Decode::decode(&mut request.block.as_ref())?;
176
177 let response = match self.client.execution_proof(block, &request.method, &request.data) {
178 Ok((_, proof)) => schema::v1::light::RemoteCallResponse { proof: Some(proof.encode()) },
179 Err(e) => {
180 trace!(
181 "remote call request from {} ({} at {:?}) failed with: {}",
182 peer,
183 request.method,
184 request.block,
185 e,
186 );
187 schema::v1::light::RemoteCallResponse { proof: None }
188 },
189 };
190
191 Ok(schema::v1::light::Response {
192 response: Some(schema::v1::light::response::Response::RemoteCallResponse(response)),
193 })
194 }
195
196 fn on_remote_read_request(
197 &mut self,
198 peer: &PeerId,
199 request: &schema::v1::light::RemoteReadRequest,
200 ) -> Result<schema::v1::light::Response, HandleRequestError> {
201 if request.keys.is_empty() {
202 debug!("Invalid remote read request sent by {}.", peer);
203 return Err(HandleRequestError::BadRequest("Remote read request without keys."))
204 }
205
206 trace!(
207 "Remote read request from {} ({} at {:?}).",
208 peer,
209 fmt_keys(request.keys.first(), request.keys.last()),
210 request.block,
211 );
212
213 let block = Decode::decode(&mut request.block.as_ref())?;
214
215 let response =
216 match self.client.read_proof(block, &mut request.keys.iter().map(AsRef::as_ref)) {
217 Ok(proof) => schema::v1::light::RemoteReadResponse { proof: Some(proof.encode()) },
218 Err(error) => {
219 trace!(
220 "remote read request from {} ({} at {:?}) failed with: {}",
221 peer,
222 fmt_keys(request.keys.first(), request.keys.last()),
223 request.block,
224 error,
225 );
226 schema::v1::light::RemoteReadResponse { proof: None }
227 },
228 };
229
230 Ok(schema::v1::light::Response {
231 response: Some(schema::v1::light::response::Response::RemoteReadResponse(response)),
232 })
233 }
234
235 fn on_remote_read_child_request(
236 &mut self,
237 peer: &PeerId,
238 request: &schema::v1::light::RemoteReadChildRequest,
239 ) -> Result<schema::v1::light::Response, HandleRequestError> {
240 if request.keys.is_empty() {
241 debug!("Invalid remote child read request sent by {}.", peer);
242 return Err(HandleRequestError::BadRequest("Remove read child request without keys."))
243 }
244
245 trace!(
246 "Remote read child request from {} ({} {} at {:?}).",
247 peer,
248 HexDisplay::from(&request.storage_key),
249 fmt_keys(request.keys.first(), request.keys.last()),
250 request.block,
251 );
252
253 let block = Decode::decode(&mut request.block.as_ref())?;
254
255 let prefixed_key = PrefixedStorageKey::new_ref(&request.storage_key);
256 let child_info = match ChildType::from_prefixed_key(prefixed_key) {
257 Some((ChildType::ParentKeyId, storage_key)) => Ok(ChildInfo::new_default(storage_key)),
258 None => Err(sp_blockchain::Error::InvalidChildStorageKey),
259 };
260 let response = match child_info.and_then(|child_info| {
261 self.client.read_child_proof(
262 block,
263 &child_info,
264 &mut request.keys.iter().map(AsRef::as_ref),
265 )
266 }) {
267 Ok(proof) => schema::v1::light::RemoteReadResponse { proof: Some(proof.encode()) },
268 Err(error) => {
269 trace!(
270 "remote read child request from {} ({} {} at {:?}) failed with: {}",
271 peer,
272 HexDisplay::from(&request.storage_key),
273 fmt_keys(request.keys.first(), request.keys.last()),
274 request.block,
275 error,
276 );
277 schema::v1::light::RemoteReadResponse { proof: None }
278 },
279 };
280
281 Ok(schema::v1::light::Response {
282 response: Some(schema::v1::light::response::Response::RemoteReadResponse(response)),
283 })
284 }
285}
286
287#[derive(Debug, thiserror::Error)]
288enum HandleRequestError {
289 #[error("Failed to decode request: {0}.")]
290 DecodeProto(#[from] prost::DecodeError),
291 #[error("Failed to encode response: {0}.")]
292 EncodeProto(#[from] prost::EncodeError),
293 #[error("Failed to send response.")]
294 SendResponse,
295 #[error("bad request: {0}")]
297 BadRequest(&'static str),
298 #[error("codec error: {0}")]
300 Codec(#[from] codec::Error),
301}
302
303fn fmt_keys(first: Option<&Vec<u8>>, last: Option<&Vec<u8>>) -> String {
304 if let (Some(first), Some(last)) = (first, last) {
305 if first == last {
306 HexDisplay::from(first).to_string()
307 } else {
308 format!("{}..{}", HexDisplay::from(first), HexDisplay::from(last))
309 }
310 } else {
311 String::from("n/a")
312 }
313}