plonky2/src/hash/merkle_proofs.rs

225 lines
7.4 KiB
Rust
Raw Normal View History

2021-08-11 08:33:58 +02:00
use std::convert::TryInto;
use anyhow::{ensure, Result};
use serde::{Deserialize, Serialize};
2021-08-10 13:33:44 +02:00
use crate::field::extension_field::target::ExtensionTarget;
use crate::field::extension_field::Extendable;
use crate::field::field_types::{Field, RichField};
2021-04-12 10:38:07 +02:00
use crate::gates::gmimc::GMiMCGate;
2021-08-10 13:33:44 +02:00
use crate::hash::hash_types::{HashOut, HashOutTarget, MerkleCapTarget};
use crate::hash::hashing::{compress, hash_or_noop};
2021-08-10 13:33:44 +02:00
use crate::hash::merkle_tree::MerkleCap;
use crate::iop::target::{BoolTarget, Target};
use crate::iop::wire::Wire;
use crate::plonk::circuit_builder::CircuitBuilder;
2021-04-12 10:38:07 +02:00
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
2021-04-12 10:38:07 +02:00
pub struct MerkleProof<F: Field> {
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
pub siblings: Vec<HashOut<F>>,
2021-04-12 10:38:07 +02:00
}
2021-07-08 17:16:26 +02:00
#[derive(Clone)]
2021-04-12 10:38:07 +02:00
pub struct MerkleProofTarget {
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
pub siblings: Vec<HashOutTarget>,
2021-04-12 10:38:07 +02:00
}
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
2021-08-10 15:53:27 +02:00
/// given cap.
pub(crate) fn verify_merkle_proof<F: RichField>(
2021-04-12 10:38:07 +02:00
leaf_data: Vec<F>,
leaf_index: usize,
2021-08-10 13:33:44 +02:00
merkle_cap: &MerkleCap<F>,
2021-04-21 22:31:45 +02:00
proof: &MerkleProof<F>,
2021-04-22 09:27:59 +02:00
) -> Result<()> {
2021-08-23 11:57:35 +02:00
let mut index = leaf_index;
2021-04-12 10:38:07 +02:00
let mut current_digest = hash_or_noop(leaf_data);
2021-08-10 13:33:44 +02:00
for &sibling_digest in proof.siblings.iter() {
let bit = index & 1;
index >>= 1;
current_digest = if bit == 1 {
2021-04-12 10:38:07 +02:00
compress(sibling_digest, current_digest)
} else {
compress(current_digest, sibling_digest)
}
}
2021-08-10 13:33:44 +02:00
ensure!(
current_digest == merkle_cap.0[index],
"Invalid Merkle proof."
);
2021-04-22 09:27:59 +02:00
Ok(())
2021-04-12 10:38:07 +02:00
}
impl<F: RichField + Extendable<D>, const D: usize> CircuitBuilder<F, D> {
2021-04-12 10:38:07 +02:00
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
2021-08-10 15:53:27 +02:00
/// given cap. The index is given by it's little-endian bits.
2021-08-10 16:18:42 +02:00
/// Note: Works only for D=4.
2021-04-12 10:38:07 +02:00
pub(crate) fn verify_merkle_proof(
&mut self,
leaf_data: Vec<Target>,
leaf_index_bits: &[BoolTarget],
2021-08-10 15:53:27 +02:00
merkle_cap: &MerkleCapTarget,
2021-06-04 17:36:48 +02:00
proof: &MerkleProofTarget,
2021-04-12 10:38:07 +02:00
) {
let zero = self.zero();
let mut state: HashOutTarget = self.hash_or_noop(leaf_data);
2021-04-12 10:38:07 +02:00
2021-07-22 15:10:55 +02:00
for (&bit, &sibling) in leaf_index_bits.iter().zip(&proof.siblings) {
let inputs = [state.elements, sibling.elements, [zero; 4]]
.concat()
.try_into()
.unwrap();
let outputs = self.gmimc_permute_swapped(inputs, bit);
state = HashOutTarget::from_vec(outputs[0..4].to_vec());
2021-04-12 10:38:07 +02:00
}
2021-08-10 13:33:44 +02:00
let index = self.le_sum(leaf_index_bits[proof.siblings.len()..].to_vec().into_iter());
2021-08-11 08:33:58 +02:00
let state_ext = state.elements[..].try_into().expect("requires D = 4");
2021-08-10 13:33:44 +02:00
let state_ext = ExtensionTarget(state_ext);
2021-08-10 15:53:27 +02:00
let cap_ext = merkle_cap
2021-08-10 13:33:44 +02:00
.0
.iter()
.map(|h| {
2021-08-11 08:33:58 +02:00
let tmp = h.elements[..].try_into().expect("requires D = 4");
2021-08-10 13:33:44 +02:00
ExtensionTarget(tmp)
})
.collect();
self.random_access(index, state_ext, cap_ext);
2021-04-12 10:38:07 +02:00
}
2021-08-10 16:18:42 +02:00
/// Same a `verify_merkle_proof` but with the final "cap index" as extra parameter.
/// Note: Works only for D=4.
2021-08-10 15:03:29 +02:00
pub(crate) fn verify_merkle_proof_with_cap_index(
&mut self,
leaf_data: Vec<Target>,
leaf_index_bits: &[BoolTarget],
2021-08-10 15:03:29 +02:00
cap_index: Target,
2021-08-10 15:53:27 +02:00
merkle_cap: &MerkleCapTarget,
2021-08-10 15:03:29 +02:00
proof: &MerkleProofTarget,
) {
let zero = self.zero();
let mut state: HashOutTarget = self.hash_or_noop(leaf_data);
for (&bit, &sibling) in leaf_index_bits.iter().zip(&proof.siblings) {
let gate_type = GMiMCGate::<F, D, 12>::new();
2021-08-10 15:03:29 +02:00
let gate = self.add_gate(gate_type, vec![]);
let swap_wire = GMiMCGate::<F, D, 12>::WIRE_SWAP;
2021-08-10 15:03:29 +02:00
let swap_wire = Target::Wire(Wire {
gate,
input: swap_wire,
});
self.generate_copy(bit.target, swap_wire);
2021-08-10 15:03:29 +02:00
let input_wires = (0..12)
.map(|i| {
Target::Wire(Wire {
gate,
input: GMiMCGate::<F, D, 12>::wire_input(i),
2021-08-10 15:03:29 +02:00
})
})
.collect::<Vec<_>>();
for i in 0..4 {
2021-08-24 08:25:11 +02:00
self.connect(state.elements[i], input_wires[i]);
self.connect(sibling.elements[i], input_wires[4 + i]);
self.connect(zero, input_wires[8 + i]);
2021-08-10 15:03:29 +02:00
}
state = HashOutTarget::from_vec(
(0..4)
.map(|i| {
Target::Wire(Wire {
gate,
input: GMiMCGate::<F, D, 12>::wire_output(i),
2021-08-10 15:03:29 +02:00
})
})
.collect(),
)
}
2021-08-11 08:33:58 +02:00
let state_ext = state.elements[..].try_into().expect("requires D = 4");
2021-08-10 15:03:29 +02:00
let state_ext = ExtensionTarget(state_ext);
2021-08-10 15:53:27 +02:00
let cap_ext = merkle_cap
2021-08-10 15:03:29 +02:00
.0
.iter()
.map(|h| {
2021-08-11 08:33:58 +02:00
let tmp = h.elements[..].try_into().expect("requires D = 4");
2021-08-10 15:03:29 +02:00
ExtensionTarget(tmp)
})
.collect();
self.random_access(cap_index, state_ext, cap_ext);
}
pub fn assert_hashes_equal(&mut self, x: HashOutTarget, y: HashOutTarget) {
2021-04-12 10:38:07 +02:00
for i in 0..4 {
2021-08-24 08:25:11 +02:00
self.connect(x.elements[i], y.elements[i]);
2021-04-12 10:38:07 +02:00
}
}
}
2021-07-13 09:44:35 +02:00
#[cfg(test)]
mod tests {
use anyhow::Result;
use rand::{thread_rng, Rng};
use super::*;
use crate::field::crandall_field::CrandallField;
use crate::hash::merkle_tree::MerkleTree;
2021-08-20 09:50:07 +02:00
use crate::iop::witness::{PartialWitness, Witness};
use crate::plonk::circuit_builder::CircuitBuilder;
use crate::plonk::circuit_data::CircuitConfig;
use crate::plonk::verifier::verify;
2021-07-13 09:44:35 +02:00
fn random_data<F: Field>(n: usize, k: usize) -> Vec<Vec<F>> {
(0..n).map(|_| F::rand_vec(k)).collect()
}
#[test]
2021-07-13 15:20:14 +02:00
fn test_recursive_merkle_proof() -> Result<()> {
2021-07-13 09:44:35 +02:00
type F = CrandallField;
let config = CircuitConfig::large_config();
2021-08-20 11:56:57 +02:00
let mut pw = PartialWitness::new();
2021-07-13 09:44:35 +02:00
let mut builder = CircuitBuilder::<F, 4>::new(config);
let log_n = 8;
let n = 1 << log_n;
2021-08-10 13:33:44 +02:00
let cap_height = 1;
2021-07-13 09:44:35 +02:00
let leaves = random_data::<F>(n, 7);
let tree = MerkleTree::new(leaves, cap_height);
2021-08-09 10:11:42 -07:00
let i: usize = thread_rng().gen_range(0..n);
2021-07-13 09:44:35 +02:00
let proof = tree.prove(i);
let proof_t = MerkleProofTarget {
siblings: builder.add_virtual_hashes(proof.siblings.len()),
};
for i in 0..proof.siblings.len() {
pw.set_hash_target(proof_t.siblings[i], proof.siblings[i]);
}
2021-08-10 15:53:27 +02:00
let cap_t = builder.add_virtual_cap(cap_height);
pw.set_cap_target(&cap_t, &tree.cap);
2021-07-13 09:44:35 +02:00
let i_c = builder.constant(F::from_canonical_usize(i));
2021-07-22 15:10:55 +02:00
let i_bits = builder.split_le(i_c, log_n);
2021-07-13 09:44:35 +02:00
let data = builder.add_virtual_targets(tree.leaves[i].len());
for j in 0..data.len() {
pw.set_target(data[j], tree.leaves[i][j]);
}
2021-08-10 15:53:27 +02:00
builder.verify_merkle_proof(data, &i_bits, &cap_t, &proof_t);
2021-07-13 09:44:35 +02:00
let data = builder.build();
let proof = data.prove(pw)?;
2021-07-14 20:54:30 +02:00
verify(proof, &data.verifier_only, &data.common)
}
2021-07-13 09:44:35 +02:00
}