leadcoin.rs 19 KB

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