util.rs 9.0 KB

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