Clearmatics Libsnark  0.1
C++ library for zkSNARK proofs
set_commitment.tcc
Go to the documentation of this file.
1 /** @file
2  *****************************************************************************
3 
4  Implementation of a Merkle tree based set commitment scheme.
5 
6  *****************************************************************************
7  * @author This file is part of libsnark, developed by SCIPR Lab
8  * and contributors (see AUTHORS).
9  * @copyright MIT license (see LICENSE file)
10  *****************************************************************************/
11 
12 #ifndef SET_COMMITMENT_TCC_
13 #define SET_COMMITMENT_TCC_
14 
15 namespace libsnark
16 {
17 
18 template<typename HashT>
19 set_commitment_accumulator<HashT>::set_commitment_accumulator(
20  const size_t max_entries, const size_t value_size)
21  : value_size(value_size)
22 {
23  depth = libff::log2(max_entries);
24  digest_size = HashT::get_digest_len();
25 
26  tree.reset(new merkle_tree<HashT>(depth, digest_size));
27 }
28 
29 template<typename HashT>
30 void set_commitment_accumulator<HashT>::add(const libff::bit_vector &value)
31 {
32  assert(value_size == 0 || value.size() == value_size);
33  const libff::bit_vector hash = HashT::get_hash(value);
34  if (hash_to_pos.find(hash) == hash_to_pos.end()) {
35  const size_t pos = hash_to_pos.size();
36  tree->set_value(pos, hash);
37  hash_to_pos[hash] = pos;
38  }
39 }
40 
41 template<typename HashT>
42 bool set_commitment_accumulator<HashT>::is_in_set(
43  const libff::bit_vector &value) const
44 {
45  assert(value_size == 0 || value.size() == value_size);
46  const libff::bit_vector hash = HashT::get_hash(value);
47  return (hash_to_pos.find(hash) != hash_to_pos.end());
48 }
49 
50 template<typename HashT>
51 set_commitment set_commitment_accumulator<HashT>::get_commitment() const
52 {
53  return tree->get_root();
54 }
55 
56 template<typename HashT>
57 set_membership_proof set_commitment_accumulator<HashT>::get_membership_proof(
58  const libff::bit_vector &value) const
59 {
60  const libff::bit_vector hash = HashT::get_hash(value);
61  auto it = hash_to_pos.find(hash);
62  assert(it != hash_to_pos.end());
63 
64  set_membership_proof proof;
65  proof.address = it->second;
66  proof.merkle_path = tree->get_path(it->second);
67 
68  return proof;
69 }
70 
71 } // namespace libsnark
72 
73 #endif // SET_COMMITMENT_TCC_