util.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 std::{any::Any, collections::HashMap, hash::Hasher};
  19. use lazy_static::lazy_static;
  20. use log::debug;
  21. use pasta_curves::{
  22. group::ff::{Field, PrimeField},
  23. pallas,
  24. };
  25. use rand::rngs::OsRng;
  26. use darkfi::{
  27. crypto::{
  28. keypair::{PublicKey, SecretKey},
  29. proof::{ProvingKey, VerifyingKey},
  30. schnorr::{SchnorrPublic, SchnorrSecret, Signature},
  31. types::DrkCircuitField,
  32. Proof,
  33. },
  34. zk::{vm::ZkCircuit, vm_stack::empty_witnesses},
  35. zkas::decoder::ZkBinary,
  36. };
  37. use darkfi_serial::Encodable;
  38. use crate::error::{DaoError, DaoResult};
  39. // /// Parse pallas::Base from a base58-encoded string
  40. // pub fn parse_b58(s: &str) -> std::result::Result<pallas::Base, darkfi::Error> {
  41. // let bytes = bs58::decode(s).into_vec()?;
  42. // if bytes.len() != 32 {
  43. // return Err(Error::ParseFailed("Failed parsing DrkTokenId from base58 string"))
  44. // }
  45. // let ret = pallas::Base::from_repr(bytes.try_into().unwrap());
  46. // if ret.is_some().unwrap_u8() == 1 {
  47. // return Ok(ret.unwrap())
  48. // }
  49. // Err(Error::ParseFailed("Failed parsing DrkTokenId from base58 string"))
  50. // }
  51. // The token of the DAO treasury.
  52. lazy_static! {
  53. pub static ref DRK_ID: pallas::Base = pallas::Base::random(&mut OsRng);
  54. }
  55. // Governance tokens that are airdropped to users to operate the DAO.
  56. lazy_static! {
  57. pub static ref GOV_ID: pallas::Base = pallas::Base::random(&mut OsRng);
  58. }
  59. #[derive(Eq, PartialEq, Debug)]
  60. pub struct HashableBase(pub pallas::Base);
  61. impl std::hash::Hash for HashableBase {
  62. fn hash<H: Hasher>(&self, state: &mut H) {
  63. let bytes = self.0.to_repr();
  64. bytes.hash(state);
  65. }
  66. }
  67. #[derive(Clone)]
  68. pub struct ZkBinaryContractInfo {
  69. pub k_param: u32,
  70. pub bincode: ZkBinary,
  71. pub proving_key: ProvingKey,
  72. pub verifying_key: VerifyingKey,
  73. }
  74. #[derive(Clone)]
  75. pub struct ZkNativeContractInfo {
  76. pub proving_key: ProvingKey,
  77. pub verifying_key: VerifyingKey,
  78. }
  79. #[derive(Clone)]
  80. pub enum ZkContractInfo {
  81. Binary(ZkBinaryContractInfo),
  82. Native(ZkNativeContractInfo),
  83. }
  84. #[derive(Clone)]
  85. pub struct ZkContractTable {
  86. // Key will be a hash of zk binary contract on chain
  87. table: HashMap<String, ZkContractInfo>,
  88. }
  89. impl ZkContractTable {
  90. pub fn new() -> Self {
  91. Self { table: HashMap::new() }
  92. }
  93. pub fn add_contract(&mut self, key: String, bincode: ZkBinary, k_param: u32) {
  94. let witnesses = empty_witnesses(&bincode);
  95. let circuit = ZkCircuit::new(witnesses, bincode.clone());
  96. let proving_key = ProvingKey::build(k_param, &circuit);
  97. let verifying_key = VerifyingKey::build(k_param, &circuit);
  98. let info = ZkContractInfo::Binary(ZkBinaryContractInfo {
  99. k_param,
  100. bincode,
  101. proving_key,
  102. verifying_key,
  103. });
  104. self.table.insert(key, info);
  105. }
  106. pub fn add_native(
  107. &mut self,
  108. key: String,
  109. proving_key: ProvingKey,
  110. verifying_key: VerifyingKey,
  111. ) {
  112. self.table.insert(
  113. key,
  114. ZkContractInfo::Native(ZkNativeContractInfo { proving_key, verifying_key }),
  115. );
  116. }
  117. pub fn lookup(&self, key: &String) -> Option<&ZkContractInfo> {
  118. self.table.get(key)
  119. }
  120. }
  121. pub struct Transaction {
  122. pub func_calls: Vec<FuncCall>,
  123. pub signatures: Vec<Signature>,
  124. }
  125. impl Transaction {
  126. /// Verify ZK contracts for the entire tx
  127. /// In real code, we could parallelize this for loop
  128. /// TODO: fix use of unwrap with Result type stuff
  129. pub fn zk_verify(&self, zk_bins: &ZkContractTable) -> DaoResult<()> {
  130. for func_call in &self.func_calls {
  131. let proofs_public_vals = &func_call.call_data.zk_public_values();
  132. assert_eq!(
  133. proofs_public_vals.len(),
  134. func_call.proofs.len(),
  135. "proof_public_vals.len()={} and func_call.proofs.len()={} do not match",
  136. proofs_public_vals.len(),
  137. func_call.proofs.len()
  138. );
  139. for (i, (proof, (key, public_vals))) in
  140. func_call.proofs.iter().zip(proofs_public_vals.iter()).enumerate()
  141. {
  142. match zk_bins.lookup(key).unwrap() {
  143. ZkContractInfo::Binary(info) => {
  144. let verifying_key = &info.verifying_key;
  145. let verify_result = proof.verify(&verifying_key, public_vals);
  146. if verify_result.is_err() {
  147. return Err(DaoError::VerifyProofFailed(i, key.to_string()))
  148. }
  149. //assert!(verify_result.is_ok(), "verify proof[{}]='{}' failed", i, key);
  150. }
  151. ZkContractInfo::Native(info) => {
  152. let verifying_key = &info.verifying_key;
  153. let verify_result = proof.verify(&verifying_key, public_vals);
  154. if verify_result.is_err() {
  155. return Err(DaoError::VerifyProofFailed(i, key.to_string()))
  156. }
  157. //assert!(verify_result.is_ok(), "verify proof[{}]='{}' failed", i, key);
  158. }
  159. };
  160. debug!(target: "demo", "zk_verify({}) passed [i={}]", key, i);
  161. }
  162. }
  163. Ok(())
  164. }
  165. pub fn verify_sigs(&self) {
  166. let mut unsigned_tx_data = vec![];
  167. for (i, (func_call, signature)) in
  168. self.func_calls.iter().zip(self.signatures.clone()).enumerate()
  169. {
  170. func_call.encode(&mut unsigned_tx_data).expect("failed to encode data");
  171. let signature_pub_keys = func_call.call_data.signature_public_keys();
  172. for signature_pub_key in signature_pub_keys {
  173. let verify_result = signature_pub_key.verify(&unsigned_tx_data[..], &signature);
  174. assert!(verify_result, "verify sigs[{}] failed", i);
  175. }
  176. debug!(target: "demo", "verify_sigs({}) passed", i);
  177. }
  178. }
  179. }
  180. pub fn sign(signature_secrets: Vec<SecretKey>, func_calls: &Vec<FuncCall>) -> Vec<Signature> {
  181. let mut signatures = vec![];
  182. let mut unsigned_tx_data = vec![];
  183. for (_i, (signature_secret, func_call)) in
  184. signature_secrets.iter().zip(func_calls.iter()).enumerate()
  185. {
  186. func_call.encode(&mut unsigned_tx_data).expect("failed to encode data");
  187. let signature = signature_secret.sign(&unsigned_tx_data[..]);
  188. signatures.push(signature);
  189. }
  190. signatures
  191. }
  192. type ContractId = pallas::Base;
  193. type FuncId = pallas::Base;
  194. pub struct FuncCall {
  195. pub contract_id: ContractId,
  196. pub func_id: FuncId,
  197. pub call_data: Box<dyn CallDataBase + Send + Sync>,
  198. pub proofs: Vec<Proof>,
  199. }
  200. impl Encodable for FuncCall {
  201. fn encode<W: std::io::Write>(&self, mut w: W) -> std::result::Result<usize, std::io::Error> {
  202. let mut len = 0;
  203. len += self.contract_id.encode(&mut w)?;
  204. len += self.func_id.encode(&mut w)?;
  205. len += self.proofs.encode(&mut w)?;
  206. len += self.call_data.encode_bytes(&mut w)?;
  207. Ok(len)
  208. }
  209. }
  210. pub trait CallDataBase {
  211. // Public values for verifying the proofs
  212. // Needed so we can convert internal types so they can be used in Proof::verify()
  213. fn zk_public_values(&self) -> Vec<(String, Vec<DrkCircuitField>)>;
  214. // For upcasting to CallData itself so it can be read in state_transition()
  215. fn as_any(&self) -> &dyn Any;
  216. // Public keys we will use to verify transaction signatures.
  217. fn signature_public_keys(&self) -> Vec<PublicKey>;
  218. fn encode_bytes(
  219. &self,
  220. writer: &mut dyn std::io::Write,
  221. ) -> std::result::Result<usize, std::io::Error>;
  222. }
  223. type GenericContractState = Box<dyn Any + Send>;
  224. pub struct StateRegistry {
  225. pub states: HashMap<HashableBase, GenericContractState>,
  226. }
  227. impl StateRegistry {
  228. pub fn new() -> Self {
  229. Self { states: HashMap::new() }
  230. }
  231. pub fn register(&mut self, contract_id: ContractId, state: GenericContractState) {
  232. debug!(target: "StateRegistry::register()", "contract_id: {:?}", contract_id);
  233. self.states.insert(HashableBase(contract_id), state);
  234. }
  235. pub fn lookup_mut<'a, S: 'static>(&'a mut self, contract_id: ContractId) -> Option<&'a mut S> {
  236. self.states.get_mut(&HashableBase(contract_id)).and_then(|state| state.downcast_mut())
  237. }
  238. pub fn lookup<'a, S: 'static>(&'a self, contract_id: ContractId) -> Option<&'a S> {
  239. self.states.get(&HashableBase(contract_id)).and_then(|state| state.downcast_ref())
  240. }
  241. }
  242. pub trait UpdateBase {
  243. fn apply(self: Box<Self>, states: &mut StateRegistry);
  244. }