1use heika_core::hash::Hash256;
9use heika_core::merkle::{MerklePathNode, Position};
10use heika_core::patricia::TreeNode;
11use serde::{Deserialize, Serialize};
12
13use crate::{RestError, hex_array, hex_vec};
14
15#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
23#[serde(rename_all = "camelCase")]
24pub struct MerkleProofInfo {
25 pub merkle_path: Vec<MerklePathItem>,
26}
27
28#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
30pub struct MerklePathItem {
31 pub position: String,
33 pub hash: String,
34}
35
36impl TryFrom<&MerkleProofInfo> for Vec<MerklePathNode> {
38 type Error = RestError;
39
40 fn try_from(info: &MerkleProofInfo) -> Result<Self, Self::Error> {
41 info.merkle_path
42 .iter()
43 .map(|item| {
44 let position = match item.position.as_str() {
45 "left" => Position::Left,
46 "right" => Position::Right,
47 _ => return Err(RestError::InvalidValue { field: "position" }),
48 };
49 Ok(MerklePathNode {
50 hash: Hash256(hex_array(&item.hash, "hash")?),
51 position,
52 })
53 })
54 .collect()
55 }
56}
57
58#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
60pub struct MerkleStateInfo {
61 pub raw: String,
63}
64
65impl TryFrom<&MerkleStateInfo> for Vec<TreeNode> {
67 type Error = RestError;
68
69 fn try_from(info: &MerkleStateInfo) -> Result<Self, Self::Error> {
70 TreeNode::decode_all(&hex_vec(&info.raw, "raw")?).map_err(RestError::InvalidTreeNodes)
71 }
72}
73
74impl MerkleStateInfo {
75 pub fn prove(&self, key: &Hash256, root: &Hash256) -> Result<Option<Hash256>, RestError> {
78 let nodes = Vec::<TreeNode>::try_from(self)?;
79 heika_core::patricia::prove(key, &nodes, root).map_err(RestError::InvalidProof)
80 }
81}