util.rs 8.5 KB

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