leadcoin.rs 19 KB

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