util.rs 9.5 KB

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