Skip to content

Commit

Permalink
cleaned up verification imports
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantumExplorer committed Jul 9, 2024
1 parent ded5054 commit 196d9fa
Show file tree
Hide file tree
Showing 14 changed files with 190 additions and 209 deletions.
3 changes: 1 addition & 2 deletions grovedb/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ derive_more = { version = "0.99.18" }
integer-encoding = { version = "4.0.0", optional = true }
grovedb-costs = { version = "1.0.0-rc.2", path = "../costs", optional = true }
nohash-hasher = { version = "0.2.0", optional = true }
indexmap = { version = "2.2.6", optional = true }
indexmap = { version = "2.2.6"}
intmap = { version = "2.0.0", optional = true }
grovedb-path = { version = "1.0.0-rc.2", path = "../path" }
grovedbg-types = { path = "../grovedbg-types", optional = true }
Expand Down Expand Up @@ -57,7 +57,6 @@ full = [
"integer-encoding",
"grovedb-costs",
"nohash-hasher",
"indexmap",
"intmap"
]
visualize = [
Expand Down
10 changes: 6 additions & 4 deletions grovedb/src/element/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,17 @@ use grovedb_merk::{
#[cfg(feature = "full")]
use integer_encoding::VarInt;

#[cfg(feature = "full")]
use crate::reference_path::path_from_reference_path_type;
#[cfg(any(feature = "full", feature = "verify"))]
use crate::reference_path::{path_from_reference_path_type, ReferencePathType};
#[cfg(any(feature = "full", feature = "verify"))]
use crate::{element::SUM_ITEM_COST_SIZE, Element, Error};
use crate::reference_path::ReferencePathType;
#[cfg(feature = "full")]
use crate::{
element::{SUM_TREE_COST_SIZE, TREE_COST_SIZE},
element::{SUM_ITEM_COST_SIZE, SUM_TREE_COST_SIZE, TREE_COST_SIZE},
ElementFlags,
};
#[cfg(any(feature = "full", feature = "verify"))]
use crate::{Element, Error};

impl Element {
#[cfg(any(feature = "full", feature = "verify"))]
Expand Down
32 changes: 2 additions & 30 deletions grovedb/src/element/mod.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,3 @@
// MIT LICENSE
//
// Copyright (c) 2021 Dash Core Group
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! Module for subtrees handling.
//! Subtrees handling is isolated so basically this module is about adapting
//! Merk API to GroveDB needs.
Expand All @@ -48,8 +20,8 @@ mod query;
pub use query::QueryOptions;
#[cfg(any(feature = "full", feature = "verify"))]
mod serialize;
#[cfg(feature = "full")]
use core::fmt;
#[cfg(any(feature = "full", feature = "verify"))]
use std::fmt;

use bincode::{Decode, Encode};
#[cfg(any(feature = "full", feature = "verify"))]
Expand Down
9 changes: 7 additions & 2 deletions grovedb/src/element/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ use grovedb_costs::{
};
#[cfg(feature = "full")]
use grovedb_merk::proofs::query::query_item::QueryItem;
#[cfg(feature = "full")]
use grovedb_merk::proofs::query::SubqueryBranch;
#[cfg(any(feature = "full", feature = "verify"))]
use grovedb_merk::proofs::Query;
#[cfg(feature = "full")]
use grovedb_path::SubtreePath;
#[cfg(feature = "full")]
use grovedb_storage::{rocksdb_storage::RocksDbStorage, RawIterator, StorageContext};

#[cfg(feature = "full")]
use crate::operations::proof::util::hex_to_ascii;
#[cfg(feature = "full")]
use crate::{
element::helpers::raw_decode,
Expand All @@ -58,9 +62,8 @@ use crate::{
util::{merk_optional_tx, merk_optional_tx_internal_error, storage_context_optional_tx},
Error, PathQuery, TransactionArg,
};
use crate::{operations::proof::util::hex_to_ascii, query_result_type::Path};
#[cfg(any(feature = "full", feature = "verify"))]
use crate::{Element, SizedQuery};
use crate::{query_result_type::Path, Element, SizedQuery};

#[cfg(any(feature = "full", feature = "verify"))]
#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -130,6 +133,7 @@ where
pub offset: &'a mut Option<u16>,
}

#[cfg(feature = "full")]
fn format_query(query: &Query, indent: usize) -> String {
let indent_str = " ".repeat(indent);
let mut output = format!("{}Query {{\n", indent_str);
Expand Down Expand Up @@ -165,6 +169,7 @@ fn format_query(query: &Query, indent: usize) -> String {
output
}

#[cfg(feature = "full")]
fn format_subquery_branch(branch: &SubqueryBranch, indent: usize) -> String {
let indent_str = " ".repeat(indent);
let mut output = format!("SubqueryBranch {{\n");

Check warning on line 175 in grovedb/src/element/query.rs

View workflow job for this annotation

GitHub Actions / clippy

useless use of `format!`

warning: useless use of `format!` --> grovedb/src/element/query.rs:175:22 | 175 | let mut output = format!("SubqueryBranch {{\n"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `"SubqueryBranch {\n".to_string()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_format = note: `#[warn(clippy::useless_format)]` on by default
Expand Down
4 changes: 3 additions & 1 deletion grovedb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ use grovedb_merk::{
tree::{combine_hash, value_hash},
BatchEntry, CryptoHash, KVIterator, Merk,
};
#[cfg(feature = "full")]
use grovedb_path::SubtreePath;
#[cfg(feature = "full")]
use grovedb_storage::rocksdb_storage::PrefixedRocksDbImmediateStorageContext;
Expand All @@ -226,7 +227,7 @@ use crate::element::helpers::raw_decode;
pub use crate::error::Error;
#[cfg(feature = "full")]
use crate::util::{root_merk_optional_tx, storage_context_optional_tx};
#[cfg(any(feature = "full", feature = "verify"))]
#[cfg(feature = "full")]
use crate::Error::MerkError;

#[cfg(feature = "full")]
Expand All @@ -238,6 +239,7 @@ pub struct GroveDb {
db: RocksDbStorage,
}

#[cfg(feature = "full")]
pub(crate) type SubtreePrefix = [u8; blake3::OUT_LEN];

/// Transaction
Expand Down
154 changes: 5 additions & 149 deletions grovedb/src/operations/proof/generate.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
//! Generate proof operations
use std::{collections::BTreeMap, fmt};
use std::collections::BTreeMap;

use bincode::{Decode, Encode};
use derive_more::From;
use grovedb_costs::{
cost_return_on_error, cost_return_on_error_default, cost_return_on_error_no_add, CostResult,
CostsExt, OperationCost,
};
use grovedb_merk::{
proofs::{
encode_into,
query::{Key, QueryItem},
Decoder, Node, Op,
},
proofs::{encode_into, query::QueryItem, Node, Op},
tree::value_hash,
Merk, ProofWithoutEncodingResult,
};
Expand All @@ -22,151 +16,13 @@ use grovedb_storage::StorageContext;
#[cfg(feature = "proof_debug")]
use crate::query_result_type::QueryResultType;
use crate::{
operations::proof::util::{element_hex_to_ascii, hex_to_ascii},
operations::proof::{
util::hex_to_ascii, GroveDBProof, GroveDBProofV0, LayerProof, ProveOptions,
},
reference_path::path_from_reference_path_type,
Element, Error, GroveDb, PathQuery,
};

#[derive(Debug, Clone, Copy, Encode, Decode)]
pub struct ProveOptions {
pub decrease_limit_on_empty_sub_query_result: bool,
}

impl fmt::Display for ProveOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"ProveOptions {{ decrease_limit_on_empty_sub_query_result: {} }}",
self.decrease_limit_on_empty_sub_query_result
)
}
}

impl Default for ProveOptions {
fn default() -> Self {
ProveOptions {
decrease_limit_on_empty_sub_query_result: true,
}
}
}

#[derive(Encode, Decode)]
pub struct LayerProof {
pub merk_proof: Vec<u8>,
pub lower_layers: BTreeMap<Key, LayerProof>,
}

#[derive(Encode, Decode, From)]
pub enum GroveDBProof {
V0(GroveDBProofV0),
}

#[derive(Encode, Decode)]
pub struct GroveDBProofV0 {
pub root_layer: LayerProof,
pub prove_options: ProveOptions,
}

impl fmt::Display for LayerProof {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "LayerProof {{")?;
writeln!(f, " merk_proof: {}", decode_merk_proof(&self.merk_proof))?;
if !self.lower_layers.is_empty() {
writeln!(f, " lower_layers: {{")?;
for (key, layer_proof) in &self.lower_layers {
writeln!(f, " {} => {{", hex_to_ascii(key))?;
for line in format!("{}", layer_proof).lines() {
writeln!(f, " {}", line)?;
}
writeln!(f, " }}")?;
}
writeln!(f, " }}")?;
}
write!(f, "}}")
}
}

impl fmt::Display for GroveDBProof {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GroveDBProof::V0(proof) => write!(f, "{}", proof),
}
}
}

impl fmt::Display for GroveDBProofV0 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "GroveDBProofV0 {{")?;
for line in format!("{}", self.root_layer).lines() {
writeln!(f, " {}", line)?;
}
write!(f, "}}")
}
}

fn decode_merk_proof(proof: &[u8]) -> String {
let mut result = String::new();
let ops = Decoder::new(proof);

for (i, op) in ops.enumerate() {
match op {
Ok(op) => {
result.push_str(&format!("\n {}: {}", i, op_to_string(&op)));
}
Err(e) => {
result.push_str(&format!("\n {}: Error decoding op: {}", i, e));
}
}
}

result
}

fn op_to_string(op: &Op) -> String {
match op {
Op::Push(node) => format!("Push({})", node_to_string(node)),
Op::PushInverted(node) => format!("PushInverted({})", node_to_string(node)),
Op::Parent => "Parent".to_string(),
Op::Child => "Child".to_string(),
Op::ParentInverted => "ParentInverted".to_string(),
Op::ChildInverted => "ChildInverted".to_string(),
}
}

fn node_to_string(node: &Node) -> String {
match node {
Node::Hash(hash) => format!("Hash(HASH[{}])", hex::encode(hash)),
Node::KVHash(kv_hash) => format!("KVHash(HASH[{}])", hex::encode(kv_hash)),
Node::KV(key, value) => {
format!("KV({}, {})", hex_to_ascii(key), element_hex_to_ascii(value))
}
Node::KVValueHash(key, value, value_hash) => format!(
"KVValueHash({}, {}, HASH[{}])",
hex_to_ascii(key),
element_hex_to_ascii(value),
hex::encode(value_hash)
),
Node::KVDigest(key, value_hash) => format!(
"KVDigest({}, HASH[{}])",
hex_to_ascii(key),
hex::encode(value_hash)
),
Node::KVRefValueHash(key, value, value_hash) => format!(
"KVRefValueHash({}, {}, HASH[{}])",
hex_to_ascii(key),
element_hex_to_ascii(value),
hex::encode(value_hash)
),
Node::KVValueHashFeatureType(key, value, value_hash, feature_type) => format!(
"KVValueHashFeatureType({}, {}, HASH[{}], {:?})",
hex_to_ascii(key),
element_hex_to_ascii(value),
hex::encode(value_hash),
feature_type
),
}
}

impl GroveDb {
/// Prove one or more path queries.
/// If we have more than one path query, we merge into a single path query
Expand Down
Loading

0 comments on commit 196d9fa

Please sign in to comment.