main.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::BTreeMap,
  20. time::{Instant, UNIX_EPOCH},
  21. };
  22. use darkfi::{
  23. zk::{empty_witnesses, halo2::Value, Proof, ProvingKey, VerifyingKey, Witness, ZkCircuit},
  24. zkas::ZkBinary,
  25. };
  26. use darkfi_sdk::{
  27. bridgetree::Position,
  28. crypto::{pasta_prelude::Field, poseidon_hash, MerkleNode, MerkleTree},
  29. pasta::{group::ff::FromUniformBytes, pallas},
  30. };
  31. use rand::rngs::OsRng;
  32. struct Account {
  33. identity_nullifier: pallas::Base,
  34. identity_trapdoor: pallas::Base,
  35. identity_leaf_pos: Position,
  36. user_message_limit: pallas::Base,
  37. }
  38. impl Account {
  39. fn register(
  40. membership_tree: &mut MerkleTree,
  41. membership_map: &mut BTreeMap<pallas::Base, Position>,
  42. ) -> Self {
  43. let identity_nullifier = pallas::Base::random(&mut OsRng);
  44. let identity_trapdoor = pallas::Base::random(&mut OsRng);
  45. let identity_secret_hash = poseidon_hash([identity_nullifier, identity_trapdoor]);
  46. let user_message_limit = pallas::Base::from(100);
  47. let identity_commitment = poseidon_hash([identity_secret_hash, user_message_limit]);
  48. membership_tree.append(MerkleNode::from(identity_commitment));
  49. let identity_leaf_pos = membership_tree.mark().unwrap();
  50. membership_map.insert(identity_commitment, identity_leaf_pos);
  51. Self {
  52. identity_nullifier,
  53. identity_trapdoor,
  54. identity_leaf_pos,
  55. // message id < user_message_limit
  56. user_message_limit,
  57. }
  58. }
  59. }
  60. /// Hash message modulo Fp
  61. /// In DarkIRC/eventgraph this could be the event ID
  62. fn hash_message(msg: &str) -> pallas::Base {
  63. let message_hash = blake3::hash(msg.as_bytes());
  64. let mut buf = [0u8; 64];
  65. buf[..blake3::OUT_LEN].copy_from_slice(message_hash.as_bytes());
  66. pallas::Base::from_uniform_bytes(&buf)
  67. }
  68. fn main() {
  69. // There exists a Merkle tree of identity commitments that serves
  70. // as the user registry.
  71. let mut membership_tree = MerkleTree::new(1);
  72. // Since bridgetree is append-only, we'll maintain a BTreeMap of all the
  73. // identity commitments and their indexes. Whenever some idenity is banned
  74. // we'll zero out that leaf and rebuild the bridgetree from the BTreeMap.
  75. let mut membership_map = BTreeMap::new();
  76. // Per-app identifier
  77. let rln_identifier = pallas::Base::from(42);
  78. // Current epoch
  79. let epoch = pallas::Base::from(UNIX_EPOCH.elapsed().unwrap().as_secs() as u64);
  80. // Register account
  81. let account0 = Account::register(&mut membership_tree, &mut membership_map);
  82. // ==========
  83. // Signalling
  84. // ==========
  85. let signal_zkbin = include_bytes!("../signal.zk.bin");
  86. let signal_zkbin = ZkBinary::decode(signal_zkbin, false).unwrap();
  87. let signal_empty_circuit =
  88. ZkCircuit::new(empty_witnesses(&signal_zkbin).unwrap(), &signal_zkbin);
  89. print!("[Signal] Building Proving key... ");
  90. let now = Instant::now();
  91. let signal_pk = ProvingKey::build(signal_zkbin.k, &signal_empty_circuit);
  92. println!("[{:?}]", now.elapsed());
  93. print!("[Signal] Building Verifying key... ");
  94. let now = Instant::now();
  95. let signal_vk = VerifyingKey::build(signal_zkbin.k, &signal_empty_circuit);
  96. println!("[{:?}]", now.elapsed());
  97. // =========================
  98. // Account 0 sends a message
  99. // =========================
  100. // 1. Construct share:
  101. let message_id = pallas::Base::from(1);
  102. let external_nullifier = poseidon_hash([epoch, rln_identifier]);
  103. let a_0 = poseidon_hash([account0.identity_nullifier, account0.identity_trapdoor]);
  104. let a_1 = poseidon_hash([a_0, external_nullifier, message_id]);
  105. let x = hash_message("hello i wanna spam");
  106. let y = a_0 + x * a_1;
  107. let internal_nullifier = poseidon_hash([a_1]);
  108. // 2. Create Merkle proof:
  109. let identity_root = membership_tree.root(0).unwrap();
  110. let identity_path = membership_tree.witness(account0.identity_leaf_pos, 0).unwrap();
  111. // 3. Create ZK proof:
  112. let witnesses = vec![
  113. Witness::Base(Value::known(account0.identity_nullifier)),
  114. Witness::Base(Value::known(account0.identity_trapdoor)),
  115. Witness::MerklePath(Value::known(identity_path.clone().try_into().unwrap())),
  116. Witness::Uint32(Value::known(u64::from(account0.identity_leaf_pos).try_into().unwrap())),
  117. Witness::Base(Value::known(x)),
  118. Witness::Base(Value::known(external_nullifier)),
  119. Witness::Base(Value::known(message_id)),
  120. Witness::Base(Value::known(account0.user_message_limit)),
  121. Witness::Base(Value::known(epoch)),
  122. ];
  123. let public_inputs =
  124. vec![epoch, external_nullifier, x, y, internal_nullifier, identity_root.inner()];
  125. print!("[Signal] Creating ZK proof for 0:0...");
  126. let now = Instant::now();
  127. let signal_circuit = ZkCircuit::new(witnesses, &signal_zkbin);
  128. let proof = Proof::create(&signal_pk, &[signal_circuit], &public_inputs, &mut OsRng).unwrap();
  129. println!("[{:?}]", now.elapsed());
  130. // ============
  131. // Verification
  132. // ============
  133. print!("[Signal] Verifying ZK proof... ");
  134. let now = Instant::now();
  135. assert!(proof.verify(&signal_vk, &public_inputs).is_ok());
  136. println!("[{:?}]", now.elapsed());
  137. }