leadcoin.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 darkfi_sdk::{
  19. crypto::{
  20. pedersen::{pedersen_commitment_base, pedersen_commitment_u64},
  21. poseidon_hash,
  22. util::mod_r_p,
  23. MerkleNode, SecretKey,
  24. },
  25. incrementalmerkletree::{bridgetree::BridgeTree, Tree},
  26. pasta::{arithmetic::CurveAffine, group::Curve, pallas},
  27. };
  28. use halo2_proofs::{arithmetic::Field, circuit::Value};
  29. use log::info;
  30. use rand::rngs::OsRng;
  31. use super::constants::EPOCH_LENGTH;
  32. use crate::{
  33. consensus::{constants, TransferStx, TxRcpt},
  34. zk::{
  35. proof::{Proof, ProvingKey},
  36. vm::ZkCircuit,
  37. vm_stack::Witness,
  38. },
  39. zkas::ZkBinary,
  40. Result,
  41. };
  42. pub const MERKLE_DEPTH_LEADCOIN: usize = 32;
  43. pub const MERKLE_DEPTH: u8 = 32;
  44. pub const ZERO: pallas::Base = pallas::Base::zero();
  45. pub const ONE: pallas::Base = pallas::Base::one();
  46. pub const PREFIX_EVL: u64 = 2;
  47. pub const PREFIX_SEED: u64 = 3;
  48. pub const PREFIX_CM: u64 = 4;
  49. pub const PREFIX_PK: u64 = 5;
  50. pub const PREFIX_SN: u64 = 6;
  51. // TODO: Unify item names with the names in the ZK proof (those are more descriptive)
  52. /// Structure representing the consensus leader coin
  53. #[derive(Debug, Clone, Copy)]
  54. pub struct LeadCoin {
  55. /// Coin's stake value
  56. pub value: u64,
  57. /// Coin creation slot.
  58. pub slot: u64,
  59. /// Coin nonce
  60. pub nonce: pallas::Base,
  61. /// Commitment for coin1
  62. pub coin1_commitment: pallas::Point,
  63. /// Commitment for coin2 (rcpt coin)
  64. pub coin2_commitment: pallas::Point,
  65. /// Merkle root of coin1 commitment
  66. pub coin1_commitment_root: MerkleNode,
  67. /// Coin commitment position
  68. pub coin1_commitment_pos: u32,
  69. /// Merkle path to the coin1's commitment
  70. pub coin1_commitment_merkle_path: [MerkleNode; MERKLE_DEPTH_LEADCOIN],
  71. /// coin1 sk
  72. pub coin1_sk: pallas::Base,
  73. /// Merkle root of the `coin1` secret key
  74. pub coin1_sk_root: MerkleNode,
  75. /// coin1 sk position in merkle tree
  76. pub coin1_sk_pos: u32,
  77. /// Merkle path to the secret key of `coin1`
  78. pub coin1_sk_merkle_path: [MerkleNode; MERKLE_DEPTH_LEADCOIN],
  79. /// coin1 commitment blinding factor
  80. pub coin1_blind: pallas::Scalar,
  81. /// coin2 commitment blinding factor
  82. pub coin2_blind: pallas::Scalar,
  83. /// Leader election nonce derived from eta at onset of epoch
  84. pub y_mu: pallas::Base,
  85. /// Leader election nonce derived from eta at onset of epoch
  86. pub rho_mu: pallas::Base,
  87. /// eta
  88. pub eta: pallas::Base,
  89. }
  90. impl LeadCoin {
  91. /// Create a new `LeadCoin` object using given parameters.
  92. #[allow(clippy::too_many_arguments)]
  93. pub fn new(
  94. // emulation of global random oracle output from previous epoch randomness.
  95. eta: pallas::Base,
  96. // Stake value
  97. value: u64,
  98. // Slot absolute index
  99. slot: u64,
  100. // coin1 sk
  101. coin1_sk: pallas::Base,
  102. // Merkle root of the `coin_1` secret key in the Merkle tree of secret keys
  103. coin1_sk_root: MerkleNode,
  104. // sk pos
  105. coin1_sk_pos: usize,
  106. // Merkle path to the secret key of `coin_1` in the Merkle tree of secret keys
  107. coin1_sk_merkle_path: [MerkleNode; MERKLE_DEPTH_LEADCOIN],
  108. // coin1 nonce
  109. seed: pallas::Base,
  110. // Merkle tree of coin commitments
  111. coin_commitment_tree: &mut BridgeTree<MerkleNode, MERKLE_DEPTH>,
  112. ) -> Self {
  113. // Generate random blinding values for commitments:
  114. let coin1_blind = pallas::Scalar::random(&mut OsRng);
  115. let coin2_blind = pallas::Scalar::random(&mut OsRng);
  116. // pk
  117. let pk = Self::util_pk(coin1_sk_root, slot);
  118. // Derive the nonce for coin2
  119. let coin2_seed = Self::util_derived_rho(coin1_sk_root, seed);
  120. info!(target: "consensus::leadcoin", "coin2_seed[{}]: {:?}", slot, coin2_seed);
  121. let coin1_commitment = Self::commitment(pk, pallas::Base::from(value), seed, coin1_blind);
  122. // Hash its coordinates to get a base field element
  123. let c1_cm_coords = coin1_commitment.to_affine().coordinates().unwrap();
  124. let c1_base_msg = [*c1_cm_coords.x(), *c1_cm_coords.y()];
  125. let coin1_commitment_base = poseidon_hash(c1_base_msg);
  126. // Append the element to the Merkle tree
  127. coin_commitment_tree.append(&MerkleNode::from(coin1_commitment_base));
  128. let coin1_commitment_pos = coin_commitment_tree.witness().unwrap();
  129. let coin1_commitment_root = coin_commitment_tree.root(0).unwrap();
  130. let coin1_commitment_merkle_path = coin_commitment_tree
  131. .authentication_path(coin1_commitment_pos, &coin1_commitment_root)
  132. .unwrap();
  133. // Create commitment to coin2
  134. let coin2_commitment = Self::commitment(
  135. pk,
  136. pallas::Base::from(value + constants::REWARD),
  137. coin2_seed,
  138. coin2_blind,
  139. );
  140. // Derive election seeds
  141. let (y_mu, rho_mu) = Self::election_seeds_u64(eta, slot);
  142. // Return the object
  143. Self {
  144. value,
  145. slot,
  146. nonce: seed,
  147. coin1_commitment,
  148. coin2_commitment,
  149. coin1_commitment_root,
  150. coin1_commitment_pos: u32::try_from(usize::from(coin1_commitment_pos)).unwrap(),
  151. coin1_commitment_merkle_path: coin1_commitment_merkle_path.try_into().unwrap(),
  152. coin1_sk,
  153. coin1_sk_root,
  154. coin1_sk_pos: u32::try_from(coin1_sk_pos).unwrap(),
  155. coin1_sk_merkle_path,
  156. coin1_blind,
  157. coin2_blind,
  158. y_mu,
  159. rho_mu,
  160. eta,
  161. }
  162. }
  163. pub fn sn(&self) -> pallas::Base {
  164. let sn_msg = [pallas::Base::from(PREFIX_SN), self.coin1_sk_root.inner(), self.nonce, ZERO];
  165. poseidon_hash(sn_msg)
  166. }
  167. pub fn election_seeds_u64(eta: pallas::Base, slotu64: u64) -> (pallas::Base, pallas::Base) {
  168. Self::election_seeds(eta, pallas::Base::from(slotu64))
  169. }
  170. /// Derive election seeds from given parameters
  171. pub fn election_seeds(eta: pallas::Base, slot: pallas::Base) -> (pallas::Base, pallas::Base) {
  172. info!(target: "consensus::leadcoin", "election_seeds: eta: {:?}, slot: {:?}", eta, slot);
  173. let election_seed_nonce = pallas::Base::from(3);
  174. let election_seed_lead = pallas::Base::from(22);
  175. // mu_y
  176. let lead_msg = [election_seed_lead, eta, slot];
  177. let lead_mu = poseidon_hash(lead_msg);
  178. // mu_rho
  179. let nonce_msg = [election_seed_nonce, eta, slot];
  180. let nonce_mu = poseidon_hash(nonce_msg);
  181. (lead_mu, nonce_mu)
  182. }
  183. /// Create a vector of `pallas::Base` elements from the `LeadCoin` to be
  184. /// used as public inputs for the ZK proof.
  185. pub fn public_inputs(&self, sigma1: pallas::Base, sigma2: pallas::Base) -> Vec<pallas::Base> {
  186. // pk
  187. let pk = self.pk();
  188. // coin 1-2 cm/commitment
  189. let c1_cm = self.coin1_commitment.to_affine().coordinates().unwrap();
  190. let c2_cm = self.coin2_commitment.to_affine().coordinates().unwrap();
  191. // lottery seed
  192. let seed_msg =
  193. [pallas::Base::from(PREFIX_SEED), self.coin1_sk_root.inner(), self.nonce, ZERO];
  194. let seed = poseidon_hash(seed_msg);
  195. // y
  196. let y_msg = [seed, self.y_mu];
  197. let y = poseidon_hash(y_msg);
  198. // rho
  199. let rho_msg = [seed, self.rho_mu];
  200. let rho = poseidon_hash(rho_msg);
  201. let public_inputs = vec![
  202. pk,
  203. *c1_cm.x(),
  204. *c1_cm.y(),
  205. *c2_cm.x(),
  206. *c2_cm.y(),
  207. self.coin1_commitment_root.inner(),
  208. self.coin1_sk_root.inner(),
  209. self.sn(),
  210. self.y_mu,
  211. y,
  212. self.rho_mu,
  213. rho,
  214. sigma1,
  215. sigma2,
  216. ];
  217. public_inputs
  218. }
  219. fn util_pk(sk_root: MerkleNode, slot: u64) -> pallas::Base {
  220. let pk_msg =
  221. [pallas::Base::from(PREFIX_PK), sk_root.inner(), pallas::Base::from(slot), ZERO];
  222. poseidon_hash(pk_msg)
  223. }
  224. /// calculate coin public key: hash of root coin secret key
  225. /// and creation slot.
  226. pub fn pk(&self) -> pallas::Base {
  227. Self::util_pk(self.coin1_sk_root, self.slot)
  228. }
  229. fn util_derived_rho(sk_root: MerkleNode, nonce: pallas::Base) -> pallas::Base {
  230. let rho_msg = [pallas::Base::from(PREFIX_EVL), sk_root.inner(), nonce, ZERO];
  231. poseidon_hash(rho_msg)
  232. }
  233. /// calculate derived coin nonce: hash of root coin secret key
  234. /// and old nonce
  235. pub fn derived_rho(&self) -> pallas::Base {
  236. Self::util_derived_rho(self.coin1_sk_root, self.nonce)
  237. }
  238. pub fn is_leader(&self, sigma1: pallas::Base, sigma2: pallas::Base) -> bool {
  239. let y_exp = [self.coin1_sk_root.inner(), self.nonce];
  240. let y_exp_hash = poseidon_hash(y_exp);
  241. let y_coords = pedersen_commitment_base(y_exp_hash, mod_r_p(self.y_mu))
  242. .to_affine()
  243. .coordinates()
  244. .unwrap();
  245. let y_coords = [*y_coords.x(), *y_coords.y()];
  246. let y = poseidon_hash(y_coords);
  247. let value = pallas::Base::from(self.value);
  248. let target = sigma1 * value + sigma2 * value * value;
  249. info!(target: "consensus::leadcoin", "is_leader(): y = {:?}", y);
  250. info!(target: "consensus::leadcoin", "is_leader(): T = {:?}", target);
  251. y < target
  252. }
  253. fn commitment(
  254. pk: pallas::Base,
  255. value: pallas::Base,
  256. seed: pallas::Base,
  257. blind: pallas::Scalar,
  258. ) -> pallas::Point {
  259. let commit_msg = [pallas::Base::from(PREFIX_CM), pk, value, seed];
  260. // Create commitment to coin
  261. let commit_v = poseidon_hash(commit_msg);
  262. pedersen_commitment_base(commit_v, blind)
  263. }
  264. /// calculated derived coin commitment
  265. pub fn derived_commitment(&self, blind: pallas::Scalar) -> pallas::Point {
  266. let pk = self.pk();
  267. let rho = self.derived_rho();
  268. Self::commitment(pk, pallas::Base::from(self.value + constants::REWARD), rho, blind)
  269. }
  270. /// the new coin to be minted after the current coin is spent
  271. /// in lottery.
  272. pub fn derive_coin(
  273. &self,
  274. coin_commitment_tree: &mut BridgeTree<MerkleNode, MERKLE_DEPTH>,
  275. ) -> LeadCoin {
  276. info!(target: "consensus::leadcoin", "derive_coin(): Deriving new coin!");
  277. let derived_c1_rho = self.derived_rho();
  278. let blind = pallas::Scalar::random(&mut OsRng);
  279. let derived_c2_cm = Self::commitment(
  280. self.pk(),
  281. pallas::Base::from(self.value + 2 * constants::REWARD),
  282. Self::util_derived_rho(self.coin1_sk_root, derived_c1_rho),
  283. blind,
  284. );
  285. let derived_c1_cm = { self.derived_commitment(self.coin2_blind) };
  286. let derived_c1_cm_coord = derived_c1_cm.to_affine().coordinates().unwrap();
  287. let derived_c1_cm_msg = [*derived_c1_cm_coord.x(), *derived_c1_cm_coord.y()];
  288. let derived_c1_cm_base = poseidon_hash(derived_c1_cm_msg);
  289. coin_commitment_tree.append(&MerkleNode::from(derived_c1_cm_base));
  290. let leaf_pos = coin_commitment_tree.witness().unwrap();
  291. let commitment_root = coin_commitment_tree.root(0).unwrap();
  292. let commitment_merkle_path =
  293. coin_commitment_tree.authentication_path(leaf_pos, &commitment_root).unwrap();
  294. LeadCoin {
  295. value: self.value + constants::REWARD,
  296. slot: self.slot,
  297. nonce: derived_c1_rho,
  298. coin1_commitment: self.coin2_commitment,
  299. coin2_commitment: derived_c2_cm,
  300. coin1_commitment_root: commitment_root,
  301. coin1_commitment_pos: u32::try_from(usize::from(leaf_pos)).unwrap(),
  302. coin1_commitment_merkle_path: commitment_merkle_path.try_into().unwrap(),
  303. coin1_sk: self.coin1_sk,
  304. coin1_sk_root: self.coin1_sk_root,
  305. coin1_sk_pos: self.coin1_sk_pos,
  306. coin1_sk_merkle_path: self.coin1_sk_merkle_path,
  307. coin1_blind: self.coin2_blind,
  308. coin2_blind: blind,
  309. y_mu: self.y_mu,
  310. rho_mu: self.rho_mu,
  311. eta: self.eta,
  312. }
  313. }
  314. pub fn coin_commitment_base(&self) -> pallas::Base {
  315. let c1_cm_coord = self.coin1_commitment.to_affine().coordinates().unwrap();
  316. let c1_cm_msg = [*c1_cm_coord.x(), *c1_cm_coord.y()];
  317. poseidon_hash(c1_cm_msg)
  318. }
  319. /// Try to create a ZK proof of consensus leadership
  320. pub fn create_lead_proof(
  321. &self,
  322. sigma1: pallas::Base,
  323. sigma2: pallas::Base,
  324. pk: &ProvingKey,
  325. ) -> (Result<Proof>, Vec<pallas::Base>) {
  326. let bincode = include_bytes!("../../proof/lead.zk.bin");
  327. let zkbin = ZkBinary::decode(bincode).unwrap();
  328. let witnesses = vec![
  329. Witness::MerklePath(Value::known(self.coin1_commitment_merkle_path)),
  330. Witness::Uint32(Value::known(self.coin1_commitment_pos)),
  331. Witness::Uint32(Value::known(self.coin1_sk_pos)),
  332. Witness::Base(Value::known(self.coin1_sk)),
  333. Witness::Base(Value::known(self.coin1_sk_root.inner())),
  334. Witness::MerklePath(Value::known(self.coin1_sk_merkle_path)),
  335. Witness::Base(Value::known(pallas::Base::from(self.slot))),
  336. Witness::Base(Value::known(self.nonce)),
  337. Witness::Scalar(Value::known(self.coin1_blind)),
  338. Witness::Base(Value::known(pallas::Base::from(self.value))),
  339. Witness::Scalar(Value::known(self.coin2_blind)),
  340. Witness::Base(Value::known(self.rho_mu)),
  341. Witness::Base(Value::known(self.y_mu)),
  342. Witness::Base(Value::known(sigma1)),
  343. Witness::Base(Value::known(sigma2)),
  344. ];
  345. let circuit = ZkCircuit::new(witnesses, zkbin);
  346. let public_inputs = self.public_inputs(sigma1, sigma2);
  347. (Ok(Proof::create(pk, &[circuit], &public_inputs, &mut OsRng).unwrap()), public_inputs)
  348. }
  349. #[allow(clippy::too_many_arguments)]
  350. pub fn create_xfer_proof(
  351. &self,
  352. pk: &ProvingKey,
  353. change_coin: TxRcpt,
  354. change_pk: pallas::Base, //change coin public key
  355. transfered_coin: TxRcpt,
  356. transfered_pk: pallas::Base, // recipient coin's public key
  357. sigma1: pallas::Base,
  358. sigma2: pallas::Base,
  359. ) -> Result<TransferStx> {
  360. assert!(change_coin.value + transfered_coin.value == self.value && self.value > 0);
  361. let bincode = include_bytes!("../../proof/tx.zk.bin");
  362. let zkbin = ZkBinary::decode(bincode)?;
  363. let retval = pallas::Base::from(change_coin.value);
  364. let xferval = pallas::Base::from(transfered_coin.value);
  365. let pos: u32 = self.coin1_commitment_pos;
  366. let value = pallas::Base::from(self.value);
  367. let witnesses = vec![
  368. // coin (1) burned coin
  369. Witness::Base(Value::known(self.coin1_commitment_root.inner())),
  370. Witness::Base(Value::known(self.coin1_sk_root.inner())),
  371. Witness::Base(Value::known(self.coin1_sk)),
  372. Witness::MerklePath(Value::known(self.coin1_sk_merkle_path)),
  373. Witness::Uint32(Value::known(self.coin1_sk_pos)),
  374. Witness::Base(Value::known(self.nonce)),
  375. Witness::Scalar(Value::known(self.coin1_blind)),
  376. Witness::Base(Value::known(value)),
  377. Witness::MerklePath(Value::known(self.coin1_commitment_merkle_path)),
  378. Witness::Uint32(Value::known(pos)),
  379. Witness::Base(Value::known(self.sn())),
  380. // coin (3)
  381. Witness::Base(Value::known(change_pk)),
  382. Witness::Base(Value::known(change_coin.rho)),
  383. Witness::Scalar(Value::known(change_coin.opening)),
  384. Witness::Base(Value::known(retval)),
  385. // coin (4)
  386. Witness::Base(Value::known(transfered_pk)),
  387. Witness::Base(Value::known(transfered_coin.rho)),
  388. Witness::Scalar(Value::known(transfered_coin.opening)),
  389. Witness::Base(Value::known(xferval)),
  390. ];
  391. let circuit = ZkCircuit::new(witnesses, zkbin);
  392. let proof = Proof::create(pk, &[circuit], &self.public_inputs(sigma1, sigma2), &mut OsRng)?;
  393. let cm3_msg_in = [
  394. pallas::Base::from(PREFIX_CM),
  395. change_pk,
  396. pallas::Base::from(change_coin.value),
  397. change_coin.rho,
  398. ];
  399. let cm3_msg = poseidon_hash(cm3_msg_in);
  400. let cm3 = pedersen_commitment_base(cm3_msg, change_coin.opening);
  401. let cm4_msg_in = [
  402. pallas::Base::from(PREFIX_CM),
  403. transfered_pk,
  404. pallas::Base::from(transfered_coin.value),
  405. transfered_coin.rho,
  406. ];
  407. let cm4_msg = poseidon_hash(cm4_msg_in);
  408. let cm4 = pedersen_commitment_base(cm4_msg, transfered_coin.opening);
  409. let tx = TransferStx {
  410. coin_commitment: self.coin1_commitment,
  411. coin_pk: self.pk(),
  412. coin_root_sk: self.coin1_sk_root,
  413. change_coin_commitment: cm3,
  414. transfered_coin_commitment: cm4,
  415. nullifier: self.sn(),
  416. slot: pallas::Base::from(self.slot),
  417. root: self.coin1_commitment_root,
  418. proof,
  419. };
  420. Ok(tx)
  421. }
  422. }
  423. /// This struct holds the secrets for creating LeadCoins during one epoch.
  424. pub struct LeadCoinSecrets {
  425. pub secret_keys: Vec<SecretKey>,
  426. pub merkle_roots: Vec<MerkleNode>,
  427. pub merkle_paths: Vec<[MerkleNode; MERKLE_DEPTH_LEADCOIN]>,
  428. }
  429. impl LeadCoinSecrets {
  430. /// Generate epoch coins secret keys.
  431. /// First clot coin secret key is sampled at random, while the secret keys of the
  432. /// remaining slots derive from the previous slot secret.
  433. /// Clarification:
  434. /// ```plaintext
  435. /// sk[0] -> random,
  436. /// sk[1] -> derive_function(sk[0]),
  437. /// ...
  438. /// sk[n] -> derive_function(sk[n-1]),
  439. /// ```
  440. pub fn generate() -> Self {
  441. let mut tree = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(EPOCH_LENGTH);
  442. let mut sks = Vec::with_capacity(EPOCH_LENGTH);
  443. let mut root_sks = Vec::with_capacity(EPOCH_LENGTH);
  444. let mut path_sks = Vec::with_capacity(EPOCH_LENGTH);
  445. let mut prev_sk = SecretKey::from(pallas::Base::one());
  446. for i in 0..EPOCH_LENGTH {
  447. let secret = if i == 0 {
  448. pedersen_commitment_u64(1, pallas::Scalar::random(&mut OsRng))
  449. } else {
  450. pedersen_commitment_u64(1, mod_r_p(prev_sk.inner()))
  451. };
  452. let secret_coords = secret.to_affine().coordinates().unwrap();
  453. let secret_msg = [*secret_coords.x(), *secret_coords.y()];
  454. let secret_key = SecretKey::from(poseidon_hash(secret_msg));
  455. sks.push(secret_key);
  456. prev_sk = secret_key;
  457. let node = MerkleNode::from(secret_key.inner());
  458. tree.append(&node);
  459. let leaf_pos = tree.witness().unwrap();
  460. let root = tree.root(0).unwrap();
  461. let path = tree.authentication_path(leaf_pos, &root).unwrap();
  462. root_sks.push(root);
  463. path_sks.push(path.try_into().unwrap());
  464. }
  465. Self { secret_keys: sks, merkle_roots: root_sks, merkle_paths: path_sks }
  466. }
  467. }