pub use crate::ValidationError;
use exonum_crypto::Hash;
use serde::{Deserializer, Serializer};
use serde_derive::{Deserialize, Serialize};
use thiserror::Error;
use std::{borrow::Cow, marker::PhantomData};
use super::{
key::{BitsRange, ChildKind, ProofPath, KEY_SIZE},
node::BranchNode,
};
use crate::{BinaryValue, HashTag, ObjectHash};
use crate::indexes::proof_map::key::{Hashed, ToProofPath};
impl serde::Serialize for ProofPath {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut repr = String::with_capacity(KEY_SIZE * 8);
for index in 0..self.len() {
match self.bit(index) {
ChildKind::Left => {
repr.push('0');
}
ChildKind::Right => {
repr.push('1');
}
}
}
ser.serialize_str(&repr)
}
}
#[allow(clippy::use_self)]
impl<'de> serde::Deserialize<'de> for ProofPath {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::{self, Unexpected, Visitor};
use std::fmt;
struct ProofPathVisitor;
impl<'de> Visitor<'de> for ProofPathVisitor {
type Value = ProofPath;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"binary string with length between 1 and {}",
KEY_SIZE * 8
)
}
fn visit_str<E>(self, value: &str) -> Result<ProofPath, E>
where
E: de::Error,
{
let len = value.len();
if len == 0 || len > 8 * KEY_SIZE {
return Err(de::Error::invalid_value(Unexpected::Str(value), &self));
}
let mut bytes = [0_u8; KEY_SIZE];
for (i, ch) in value.chars().enumerate() {
match ch {
'0' => {}
'1' => bytes[i / 8] += 1 << (i % 8),
_ => return Err(de::Error::invalid_value(Unexpected::Str(value), &self)),
}
}
Ok(if len == 8 * KEY_SIZE {
ProofPath::from_bytes(&bytes)
} else {
ProofPath::from_bytes(&bytes).prefix(len as u16)
})
}
}
deserializer.deserialize_str(ProofPathVisitor)
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum MapProofError {
#[error("non-terminal node as a single key in the proof")]
NonTerminalNode(ProofPath),
#[error("embedded paths in the proof")]
EmbeddedPaths {
prefix: ProofPath,
path: ProofPath,
},
#[error("duplicate path in the proof")]
DuplicatePath(ProofPath),
#[error("invalid path ordering")]
InvalidOrdering(ProofPath, ProofPath),
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
struct MapProofEntry {
path: ProofPath,
hash: Hash,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
enum OptionalEntry<K, V> {
Missing { missing: K },
KV { key: K, value: V },
}
impl<K, V> OptionalEntry<K, V> {
fn missing(key: K) -> Self {
Self::Missing { missing: key }
}
fn value(key: K, value: V) -> Self {
Self::KV { key, value }
}
fn key(&self) -> &K {
match self {
Self::Missing { missing } => missing,
Self::KV { key, .. } => key,
}
}
fn as_missing(&self) -> Option<&K> {
match self {
Self::Missing { missing } => Some(missing),
_ => None,
}
}
fn as_kv(&self) -> Option<(&K, &V)> {
match self {
Self::KV { key, value } => Some((key, value)),
_ => None,
}
}
fn as_tuple(&self) -> (&K, Option<&V>) {
match self {
Self::Missing { missing } => (missing, None),
Self::KV { key, value } => (key, Some(value)),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MapProof<K, V, KeyMode = Hashed> {
entries: Vec<OptionalEntry<K, V>>,
proof: Vec<MapProofEntry>,
#[serde(skip)]
_key_mode: PhantomData<KeyMode>,
}
#[derive(Debug, Serialize)]
pub struct CheckedMapProof<'a, K, V> {
entries: &'a [OptionalEntry<K, V>],
hash: Hash,
}
fn collect(entries: &[Cow<'_, MapProofEntry>]) -> Result<Hash, MapProofError> {
fn common_prefix(x: &ProofPath, y: &ProofPath) -> ProofPath {
x.prefix(x.common_prefix_len(y))
}
fn hash_branch(left_child: &MapProofEntry, right_child: &MapProofEntry) -> Hash {
let mut branch = BranchNode::empty();
branch.set_child(ChildKind::Left, &left_child.path, &left_child.hash);
branch.set_child(ChildKind::Right, &right_child.path, &right_child.hash);
branch.object_hash()
}
fn fold(contour: &mut Vec<MapProofEntry>, last_prefix: ProofPath) -> Option<ProofPath> {
let last_entry = contour.pop().unwrap();
let penultimate_entry = contour.pop().unwrap();
contour.push(MapProofEntry {
path: last_prefix,
hash: hash_branch(&penultimate_entry, &last_entry),
});
if contour.len() > 1 {
let penultimate_entry = contour[contour.len() - 2];
Some(common_prefix(&penultimate_entry.path, &last_prefix))
} else {
None
}
}
match entries.len() {
0 => Ok(Hash::default()),
1 => {
if entries[0].path.is_leaf() {
Ok(HashTag::hash_single_entry_map(
&entries[0].path,
&entries[0].hash,
))
} else {
Err(MapProofError::NonTerminalNode(entries[0].path))
}
}
_ => {
let (first_entry, second_entry) = (&entries[0], &entries[1]);
let mut contour: Vec<MapProofEntry> = vec![**first_entry, **second_entry];
let mut last_prefix = common_prefix(&first_entry.path, &second_entry.path);
for entry in entries.iter().skip(2) {
let new_prefix = common_prefix(&contour.last().unwrap().path, &entry.path);
let new_prefix_len = new_prefix.len();
while contour.len() > 1 && new_prefix_len < last_prefix.len() {
if let Some(prefix) = fold(&mut contour, last_prefix) {
last_prefix = prefix;
}
}
contour.push(**entry);
last_prefix = new_prefix;
}
while contour.len() > 1 {
if let Some(prefix) = fold(&mut contour, last_prefix) {
last_prefix = prefix;
}
}
Ok(contour[0].hash)
}
}
}
impl<K, V, KeyMode> MapProof<K, V, KeyMode> {
pub fn proof_unchecked(&self) -> Vec<(ProofPath, Hash)> {
self.proof
.iter()
.cloned()
.map(|e| (e.path, e.hash))
.collect()
}
pub fn missing_keys_unchecked(&self) -> impl Iterator<Item = &K> {
self.entries.iter().filter_map(OptionalEntry::as_missing)
}
pub fn all_entries_unchecked(&self) -> impl Iterator<Item = (&K, Option<&V>)> {
self.entries.iter().map(|e| match e {
OptionalEntry::Missing { ref missing } => (missing, None),
OptionalEntry::KV { ref key, ref value } => (key, Some(value)),
})
}
pub(crate) fn new() -> Self {
Self {
entries: vec![],
proof: vec![],
_key_mode: PhantomData,
}
}
pub(crate) fn add_entry(mut self, key: K, value: V) -> Self {
self.entries.push(OptionalEntry::value(key, value));
self
}
pub(crate) fn add_missing(mut self, key: K) -> Self {
self.entries.push(OptionalEntry::missing(key));
self
}
pub(crate) fn add_proof_entry(mut self, path: ProofPath, hash: Hash) -> Self {
debug_assert!(self.proof.last().map_or(true, |last| last.path < path));
self.proof.push(MapProofEntry { path, hash });
self
}
pub(crate) fn add_proof_entries<I>(mut self, paths: I) -> Self
where
I: IntoIterator<Item = (ProofPath, Hash)>,
{
self.proof.extend(
paths
.into_iter()
.map(|(path, hash)| MapProofEntry { path, hash }),
);
debug_assert!(self.proof.windows(2).all(|w| w[0].path < w[1].path));
self
}
}
#[allow(clippy::use_self)] impl<K, V, KeyMode> MapProof<K, V, KeyMode>
where
V: BinaryValue,
KeyMode: ToProofPath<K>,
{
fn precheck(&self) -> Result<(), MapProofError> {
use self::MapProofError::*;
use std::cmp::Ordering;
for w in self.proof.windows(2) {
let (prev_path, path) = (&w[0].path, &w[1].path);
match prev_path.partial_cmp(path) {
Some(Ordering::Less) => {
if path.starts_with(prev_path) {
return Err(EmbeddedPaths {
prefix: *prev_path,
path: *path,
});
}
}
Some(Ordering::Equal) => {
return Err(DuplicatePath(*path));
}
Some(Ordering::Greater) => {
return Err(InvalidOrdering(*prev_path, *path));
}
None => unreachable!("Incomparable keys in proof"),
}
}
for e in &self.entries {
let path = KeyMode::transform_key(e.key());
match self.proof.binary_search_by(|pe| {
pe.path
.partial_cmp(&path)
.expect("Incomparable paths in proof")
}) {
Ok(_) => {
return Err(DuplicatePath(path));
}
Err(index) if index > 0 => {
let prev_path = &self.proof[index - 1].path;
if path.starts_with(prev_path) {
return Err(EmbeddedPaths {
prefix: *prev_path,
path,
});
}
}
_ => {}
}
}
Ok(())
}
pub fn check(&self) -> Result<CheckedMapProof<'_, K, V>, MapProofError> {
self.precheck()?;
let mut proof: Vec<_> = self.proof.iter().map(Cow::Borrowed).collect();
proof.extend(self.entries.iter().filter_map(|e| {
e.as_kv().map(|(key, value)| {
Cow::Owned(MapProofEntry {
path: KeyMode::transform_key(key),
hash: HashTag::hash_leaf(&value.to_bytes()),
})
})
}));
proof.sort_unstable_by(|x, y| {
x.path.partial_cmp(&y.path).expect(
"Incorrectly formed paths supplied to MapProof; \
paths should have `start` field set to 0",
)
});
for window in proof.windows(2) {
if window[0].path == window[1].path {
return Err(MapProofError::DuplicatePath(window[0].path));
}
}
collect(&proof).map(|merkle_root| CheckedMapProof {
entries: &self.entries,
hash: HashTag::hash_map_node(merkle_root),
})
}
pub fn check_against_hash(
&self,
expected_map_hash: Hash,
) -> Result<CheckedMapProof<'_, K, V>, ValidationError<MapProofError>> {
self.check()
.map_err(ValidationError::Malformed)
.and_then(|checked| {
if checked.index_hash() == expected_map_hash {
Ok(checked)
} else {
Err(ValidationError::UnmatchedRootHash)
}
})
}
pub fn map_values<U, F>(self, mut map_fn: F) -> MapProof<K, U, KeyMode>
where
U: BinaryValue,
F: FnMut(V) -> U,
{
MapProof {
entries: self
.entries
.into_iter()
.map(|entry| match entry {
OptionalEntry::Missing { missing } => OptionalEntry::Missing { missing },
OptionalEntry::KV { key, value } => OptionalEntry::KV {
key,
value: map_fn(value),
},
})
.collect(),
proof: self.proof,
_key_mode: PhantomData,
}
}
}
impl<'a, K, V> CheckedMapProof<'a, K, V> {
pub fn missing_keys(&self) -> impl Iterator<Item = &'a K> {
self.entries.iter().filter_map(OptionalEntry::as_missing)
}
pub fn entries(&self) -> impl Iterator<Item = (&'a K, &'a V)> {
self.entries.iter().filter_map(OptionalEntry::as_kv)
}
pub fn all_entries(&self) -> impl Iterator<Item = (&'a K, Option<&'a V>)> {
self.entries.iter().map(OptionalEntry::as_tuple)
}
pub fn index_hash(&self) -> Hash {
self.hash
}
}