Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Key storage proof v2 #12843

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions client/api/src/proof_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ pub trait ProofProvider<Block: BlockT> {
keys: &mut dyn Iterator<Item = &[u8]>,
) -> sp_blockchain::Result<StorageProof>;

/// Reads storage values at a given block + storage_key + key, returning
/// read proof.
/// For each keys, if boolean is true, then we only access value hash.
fn read_child_proof_v2(
&self,
hash: Block::Hash,
child_info: Option<&ChildInfo>,
keys: &mut dyn Iterator<Item = (&[u8], bool)>,
) -> sp_blockchain::Result<StorageProof>;

/// Execute a call to a contract on top of state in a block of given hash
/// AND returning execution proof.
///
Expand Down
83 changes: 83 additions & 0 deletions client/network/light/src/light_client_requests/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ where
self.on_remote_read_request(&peer, r)?,
Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) =>
self.on_remote_read_child_request(&peer, r)?,
Some(schema::v1::light::request::Request::RemoteReadRequestV2(r)) =>
self.on_remote_read_request_v2(&peer, r)?,
None =>
return Err(HandleRequestError::BadRequest("Remote request without request data.")),
};
Expand Down Expand Up @@ -280,6 +282,72 @@ where
response: Some(schema::v1::light::response::Response::RemoteReadResponse(response)),
})
}

fn on_remote_read_request_v2(
&mut self,
peer: &PeerId,
request: &schema::v1::light::RemoteReadRequestV2,
) -> Result<schema::v1::light::Response, HandleRequestError> {
if request.keys.is_empty() {
debug!("Invalid remote read request sent by {}.", peer);
return Err(HandleRequestError::BadRequest("Remote read request without keys."))
}
let child_info = match request.child_trie_info.as_ref() {
Some(n)
if n.namespace ==
(schema::v1::light::child_trie_info::ChildTrieNamespace::Default as i32) =>
{
let storage_key =
request.child_trie_info.as_ref().expect("has a namespace").name.clone();
trace!(
"Remote default child trie read request v2 from {} ({} {} at {:?}).",
peer,
HexDisplay::from(&storage_key),
fmt_keys_v2(request.keys.first(), request.keys.last()),
request.block,
);
Some(ChildInfo::new_default(&storage_key[..]))
},
None => {
trace!(
"Remote read request v2 from {} ({} at {:?}).",
peer,
fmt_keys_v2(request.keys.first(), request.keys.last()),
request.block,
);
None
},
Some(n) => {
debug!("Invalid child type {:?} in remote read request sent by {}.", n, peer);
return Err(HandleRequestError::BadRequest(
"Remote read request with unsupported child type.",
))
},
};
let block = Decode::decode(&mut request.block.as_ref())?;
let response = match self.client.read_child_proof_v2(
block,
child_info.as_ref(),
&mut request.keys.iter().map(|key| (&key.key[..], key.skip_value.unwrap_or(false))),
) {
Ok(proof) => schema::v1::light::RemoteReadResponse { proof: Some(proof.encode()) },
Err(error) => {
trace!(
"remote read child request from {} ({:?} {} at {:?}) failed with: {}",
peer,
child_info,
fmt_keys_v2(request.keys.first(), request.keys.last()),
request.block,
error,
);
schema::v1::light::RemoteReadResponse { proof: None }
},
};

Ok(schema::v1::light::Response {
response: Some(schema::v1::light::response::Response::RemoteReadResponse(response)),
})
}
}

#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -309,3 +377,18 @@ fn fmt_keys(first: Option<&Vec<u8>>, last: Option<&Vec<u8>>) -> String {
String::from("n/a")
}
}

fn fmt_keys_v2(
first: Option<&schema::v1::light::Key>,
last: Option<&schema::v1::light::Key>,
) -> String {
if let (Some(first), Some(last)) = (first, last) {
if first.key == last.key {
HexDisplay::from(&first.key).to_string()
} else {
format!("{}..{}", HexDisplay::from(&first.key), HexDisplay::from(&last.key))
}
} else {
String::from("n/a")
}
}
22 changes: 22 additions & 0 deletions client/network/light/src/schema/light.v1.proto
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ message Request {
RemoteReadRequest remote_read_request = 2;
RemoteReadChildRequest remote_read_child_request = 4;
// Note: ids 3 and 5 were used in the past. It would be preferable to not re-use them.
RemoteReadRequestV2 remote_read_request_v2 = 6;
}
}

Expand Down Expand Up @@ -48,6 +49,22 @@ message RemoteReadRequest {
repeated bytes keys = 3;
}

message RemoteReadRequestV2 {
required bytes block = 2;
optional ChildTrieInfo child_trie_info = 3; // Read from the main trie if missing.
repeated Key keys = 6;
}

message ChildTrieInfo {
enum ChildTrieNamespace {
DEFAULT = 1;
}

// child trie identifier.
required ChildTrieNamespace namespace = 1;
required bytes name = 2;
}

// Remote read response.
message RemoteReadResponse {
// Read proof. If missing, indicates that the remote couldn't answer, for example because
Expand All @@ -65,3 +82,8 @@ message RemoteReadChildRequest {
// Storage keys.
repeated bytes keys = 6;
}

message Key {
required bytes key = 1;
optional bool skipValue = 2; // Defaults to `false` if missing
}
12 changes: 11 additions & 1 deletion client/service/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ use sp_runtime::{
Digest, Justification, Justifications, StateVersion,
};
use sp_state_machine::{
prove_child_read, prove_range_read_with_child_with_size, prove_read,
prove_child_read, prove_range_read_with_child_with_size, prove_read, prove_read_v2,
read_range_proof_check_with_child_on_proving_backend, Backend as StateBackend,
ChildStorageCollection, KeyValueStates, KeyValueStorageLevel, StorageCollection,
MAX_NESTED_TRIE_DEPTH,
Expand Down Expand Up @@ -1253,6 +1253,16 @@ where
.and_then(|state| prove_child_read(state, child_info, keys).map_err(Into::into))
}

fn read_child_proof_v2(
&self,
hash: Block::Hash,
child_info: Option<&ChildInfo>,
keys: &mut dyn Iterator<Item = (&[u8], bool)>,
) -> sp_blockchain::Result<StorageProof> {
self.state_at(hash)
.and_then(|state| prove_read_v2(state, child_info, keys).map_err(Into::into))
}

fn execution_proof(
&self,
hash: Block::Hash,
Expand Down
Loading