Clearmatics Libsnark  0.1
C++ library for zkSNARK proofs
merkle_authentication_path_variable.tcc
Go to the documentation of this file.
1 /**
2  *****************************************************************************
3  * @author This file is part of libsnark, developed by SCIPR Lab
4  * and contributors (see AUTHORS).
5  * @copyright MIT license (see LICENSE file)
6  *****************************************************************************/
7 
8 #ifndef MERKLE_AUTHENTICATION_PATH_VARIABLE_TCC_
9 #define MERKLE_AUTHENTICATION_PATH_VARIABLE_TCC_
10 
11 namespace libsnark
12 {
13 
14 template<typename FieldT, typename HashT>
15 merkle_authentication_path_variable<FieldT, HashT>::
16  merkle_authentication_path_variable(
17  protoboard<FieldT> &pb,
18  const size_t tree_depth,
19  const std::string &annotation_prefix)
20  : gadget<FieldT>(pb, annotation_prefix), tree_depth(tree_depth)
21 {
22  for (size_t i = 0; i < tree_depth; ++i) {
23  left_digests.emplace_back(digest_variable<FieldT>(
24  pb,
25  HashT::get_digest_len(),
26  FMT(annotation_prefix, " left_digests_%zu", i)));
27  right_digests.emplace_back(digest_variable<FieldT>(
28  pb,
29  HashT::get_digest_len(),
30  FMT(annotation_prefix, " right_digests_%zu", i)));
31  }
32 }
33 
34 template<typename FieldT, typename HashT>
35 void merkle_authentication_path_variable<FieldT, HashT>::
36  generate_r1cs_constraints()
37 {
38  for (size_t i = 0; i < tree_depth; ++i) {
39  left_digests[i].generate_r1cs_constraints();
40  right_digests[i].generate_r1cs_constraints();
41  }
42 }
43 
44 template<typename FieldT, typename HashT>
45 void merkle_authentication_path_variable<FieldT, HashT>::generate_r1cs_witness(
46  const size_t address, const merkle_authentication_path &path)
47 {
48  assert(path.size() == tree_depth);
49 
50  for (size_t i = 0; i < tree_depth; ++i) {
51  if (address & (1ul << (tree_depth - 1 - i))) {
52  left_digests[i].generate_r1cs_witness(path[i]);
53  } else {
54  right_digests[i].generate_r1cs_witness(path[i]);
55  }
56  }
57 }
58 
59 template<typename FieldT, typename HashT>
60 merkle_authentication_path merkle_authentication_path_variable<FieldT, HashT>::
61  get_authentication_path(const size_t address) const
62 {
63  merkle_authentication_path result;
64  for (size_t i = 0; i < tree_depth; ++i) {
65  if (address & (1ul << (tree_depth - 1 - i))) {
66  result.emplace_back(left_digests[i].get_digest());
67  } else {
68  result.emplace_back(right_digests[i].get_digest());
69  }
70  }
71 
72  return result;
73 }
74 
75 } // namespace libsnark
76 
77 #endif // MERKLE_AUTHENTICATION_PATH_VARIABLE_TCC