util.rs 8.5 KB

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