main.rs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. use std::{sync::Arc, time::Instant};
  2. use fxhash::FxHashMap;
  3. use incrementalmerkletree::{Position, Tree};
  4. use log::debug;
  5. use pasta_curves::{
  6. arithmetic::CurveAffine,
  7. group::{ff::Field, Curve, Group},
  8. pallas,
  9. };
  10. use rand::rngs::OsRng;
  11. use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
  12. use url::Url;
  13. use darkfi::{
  14. crypto::{
  15. keypair::{Keypair, PublicKey, SecretKey},
  16. merkle_node::MerkleNode,
  17. proof::{ProvingKey, VerifyingKey},
  18. types::{DrkSpendHook, DrkUserData, DrkValue},
  19. util::{pedersen_commitment_u64, poseidon_hash},
  20. },
  21. rpc::server::listen_and_serve,
  22. zk::circuit::{BurnContract, MintContract},
  23. zkas::ZkBinary,
  24. Result,
  25. };
  26. mod contract;
  27. mod error;
  28. mod note;
  29. mod rpc;
  30. mod util;
  31. use crate::{
  32. contract::{
  33. dao::{self, mint::wallet::DaoParams, propose::wallet::Proposal, DaoBulla},
  34. money::{self, state::OwnCoin},
  35. },
  36. error::{DaoError, DaoResult},
  37. rpc::JsonRpcInterface,
  38. util::{sign, StateRegistry, Transaction, ZkContractTable, DRK_ID, GOV_ID},
  39. };
  40. //////////////////////////////////////////////////////////////////////////
  41. //////////////////////////////////////////////////////////////////////////
  42. //// dao-demo 0.1
  43. ////
  44. //// This is a very early prototype intended to demonstrate the underlying
  45. //// crypto of fully anonymous DAOs. DAO participants can own and operate
  46. //// a collective treasury according to rules set by the DAO. Communities
  47. //// can coordinate financially in the cover of a protective darkness,
  48. //// free from surveillance and persecution.
  49. ////
  50. //// The following information is completely hidden:
  51. ////
  52. //// * DAO treasury
  53. //// * DAO parameters
  54. //// * DAO participants
  55. //// * Proposals
  56. //// * Votes
  57. ////
  58. //// The DAO enables participants to make proposals, cast votes, and spend
  59. //// money from the DAO treasury if a proposal passes. The basic operation
  60. //// involves transferring money from a treasury to a public key specified
  61. //// in a Proposal. This operation can only happen if several conditions are
  62. //// met.
  63. ////
  64. //// At its basis, the DAO is a treasury that is owned by everyone who holds
  65. //// the DAO governance token. These constraints, also known as DAO parameters,
  66. //// are configured by DAO participants and enforced by ZK cryptography.
  67. ////
  68. //// In this demo, the constraints are:
  69. ////
  70. //// 1. DAO quorum: the number of governance tokens that must be allocated
  71. //// to a proposal in order for a proposal to pass.
  72. //// 2. Proposer limit: the number of governance tokens required to make a
  73. //// proposal.
  74. //// 3. DAO approval ratio: The ratio of yes/ no votes required for a
  75. //// proposal to pass.
  76. ////
  77. //// In addition, DAO participants must prove ownership of governance tokens
  78. //// order to vote. Their vote is weighted according to the number of governance
  79. //// tokens in their wallet. In this current implementation, users do not spend
  80. //// or lock up these coins in order to vote- they simply prove ownership of them.
  81. ////
  82. //// In the current prototype, the following information is exposed:
  83. ////
  84. //// * Encrypted votes are publicly linked to the proposal identifier hash,
  85. //// meaning that it is possible to see that there is voting activity associated
  86. //// with a particular proposal identifier, but the contents of the proposal,
  87. //// how one has voted, and the associated DAO is fully private.
  88. //// * In the burn phase of casting a vote, we reveal a public value called a
  89. //// nullifier. The same public value is revealed when we spend the coins we
  90. //// used to vote, meaning you can link a vote with a user when they spend
  91. //// governance tokens. This is bad but is easily fixable. We will update the
  92. //// code to use different values in the vote (by creating an intermediate Coin
  93. //// used for voting).
  94. //// * Votes are currently encrypted to the DAO public key. This means that
  95. //// any DAO participant can decrypt votes as they come in. In the future,
  96. //// we can delay the decryption so that you cannot read votes until the final
  97. //// tally.
  98. ////
  99. //// Additionally, the dao-demo app shown below is highly limited. Namely, we use
  100. //// a single God daemon to operate all the wallets. In the next version, every user
  101. //// wallet will be a seperate daemon connecting over a network and running on a
  102. //// blockchain.
  103. ////
  104. //// /////////////////////////////////////////////////////////////////////
  105. ////
  106. //// dao-demo 0.1 TODOs:
  107. ////
  108. //// High priority:
  109. ////
  110. //// 5. vote() should pass a ProposalBulla
  111. ////
  112. //// Less priority:
  113. ////
  114. //// 1. Better document CLI/ CLI help.
  115. ////
  116. //// 2. Token id is hardcoded rn. Change this so users can specify token_id
  117. //// as either xdrk or gdrk. In dao-cli we run a match statement to link to
  118. //// the corresponding static values XDRK_ID and GDRK_ID. Note: xdrk is used
  119. //// only for the DAO treasury. gdrk is the governance token used to operate
  120. //// the DAO.
  121. ////
  122. //// 3. Implement money transfer between MoneyWallets so users can send tokens to
  123. //// eachother.
  124. ////
  125. //// 4. Make CLI usage more interactive. Example: when I cast a vote, output:
  126. //// "You voted {} with value {}." where value is the number of gDRK in a users
  127. //// wallet (and the same for making a proposal etc).
  128. ////
  129. //// 5. Currently, DaoWallet stores DaoParams, DaoBulla's and Proposal's in a
  130. //// Vector. We retrieve values through indexing, meaning that we
  131. //// cannot currently support multiple DAOs and multiple proposals.
  132. ////
  133. //// Instead, dao_wallet.create_dao() should create a struct called Dao
  134. //// which stores dao_info: HashMap<DaoBulla, DaoParams> and proposals:
  135. //// HashMap<ProposalBulla, Proposal>. Users pass the DaoBulla and
  136. //// ProposalBulla and we lookup the corresponding data. struct Dao should
  137. //// be owned by DaoWallet.
  138. ////
  139. //// 6. Error handling :)
  140. ////
  141. //////////////////////////////////////////////////////////////////////////
  142. //////////////////////////////////////////////////////////////////////////
  143. pub struct Client {
  144. dao_wallet: DaoWallet,
  145. money_wallets: FxHashMap<PublicKey, MoneyWallet>,
  146. cashier_wallet: CashierWallet,
  147. states: StateRegistry,
  148. zk_bins: ZkContractTable,
  149. }
  150. impl Client {
  151. fn new() -> Self {
  152. // For this early demo we store all wallets in a single Client.
  153. let dao_wallet = DaoWallet::new();
  154. let money_wallets = FxHashMap::default();
  155. let cashier_wallet = CashierWallet::new();
  156. // Lookup table for smart contract states
  157. let states = StateRegistry::new();
  158. // Initialize ZK binary table
  159. let zk_bins = ZkContractTable::new();
  160. Self { dao_wallet, money_wallets, cashier_wallet, states, zk_bins }
  161. }
  162. // Load ZK contracts into the ZkContractTable and initialize the StateRegistry.
  163. fn init(&mut self) -> Result<()> {
  164. //We use these to initialize the money state.
  165. let faucet_signature_secret = SecretKey::random(&mut OsRng);
  166. let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
  167. debug!(target: "demo", "Loading dao-mint.zk");
  168. let zk_dao_mint_bincode = include_bytes!("../proof/dao-mint.zk.bin");
  169. let zk_dao_mint_bin = ZkBinary::decode(zk_dao_mint_bincode)?;
  170. self.zk_bins.add_contract("dao-mint".to_string(), zk_dao_mint_bin, 13);
  171. debug!(target: "demo", "Loading money-transfer contracts");
  172. let start = Instant::now();
  173. let mint_pk = ProvingKey::build(11, &MintContract::default());
  174. debug!("Mint PK: [{:?}]", start.elapsed());
  175. let start = Instant::now();
  176. let burn_pk = ProvingKey::build(11, &BurnContract::default());
  177. debug!("Burn PK: [{:?}]", start.elapsed());
  178. let start = Instant::now();
  179. let mint_vk = VerifyingKey::build(11, &MintContract::default());
  180. debug!("Mint VK: [{:?}]", start.elapsed());
  181. let start = Instant::now();
  182. let burn_vk = VerifyingKey::build(11, &BurnContract::default());
  183. debug!("Burn VK: [{:?}]", start.elapsed());
  184. self.zk_bins.add_native("money-transfer-mint".to_string(), mint_pk, mint_vk);
  185. self.zk_bins.add_native("money-transfer-burn".to_string(), burn_pk, burn_vk);
  186. debug!(target: "demo", "Loading dao-propose-main.zk");
  187. let zk_dao_propose_main_bincode = include_bytes!("../proof/dao-propose-main.zk.bin");
  188. let zk_dao_propose_main_bin = ZkBinary::decode(zk_dao_propose_main_bincode)?;
  189. self.zk_bins.add_contract("dao-propose-main".to_string(), zk_dao_propose_main_bin, 13);
  190. debug!(target: "demo", "Loading dao-propose-burn.zk");
  191. let zk_dao_propose_burn_bincode = include_bytes!("../proof/dao-propose-burn.zk.bin");
  192. let zk_dao_propose_burn_bin = ZkBinary::decode(zk_dao_propose_burn_bincode)?;
  193. self.zk_bins.add_contract("dao-propose-burn".to_string(), zk_dao_propose_burn_bin, 13);
  194. debug!(target: "demo", "Loading dao-vote-main.zk");
  195. let zk_dao_vote_main_bincode = include_bytes!("../proof/dao-vote-main.zk.bin");
  196. let zk_dao_vote_main_bin = ZkBinary::decode(zk_dao_vote_main_bincode)?;
  197. self.zk_bins.add_contract("dao-vote-main".to_string(), zk_dao_vote_main_bin, 13);
  198. debug!(target: "demo", "Loading dao-vote-burn.zk");
  199. let zk_dao_vote_burn_bincode = include_bytes!("../proof/dao-vote-burn.zk.bin");
  200. let zk_dao_vote_burn_bin = ZkBinary::decode(zk_dao_vote_burn_bincode)?;
  201. self.zk_bins.add_contract("dao-vote-burn".to_string(), zk_dao_vote_burn_bin, 13);
  202. let zk_dao_exec_bincode = include_bytes!("../proof/dao-exec.zk.bin");
  203. let zk_dao_exec_bin = ZkBinary::decode(zk_dao_exec_bincode)?;
  204. self.zk_bins.add_contract("dao-exec".to_string(), zk_dao_exec_bin, 13);
  205. let cashier_signature_public = self.cashier_wallet.signature_public();
  206. let money_state =
  207. money::state::State::new(cashier_signature_public, faucet_signature_public);
  208. self.states.register(*money::CONTRACT_ID, money_state);
  209. let dao_state = dao::State::new();
  210. self.states.register(*dao::CONTRACT_ID, dao_state);
  211. Ok(())
  212. }
  213. fn create_dao(
  214. &mut self,
  215. dao_proposer_limit: u64,
  216. dao_quorum: u64,
  217. dao_approval_ratio_quot: u64,
  218. dao_approval_ratio_base: u64,
  219. token_id: pallas::Base,
  220. ) -> DaoResult<pallas::Base> {
  221. let tx = self.dao_wallet.mint_tx(
  222. dao_proposer_limit,
  223. dao_quorum,
  224. dao_approval_ratio_quot,
  225. dao_approval_ratio_base,
  226. token_id,
  227. &self.zk_bins,
  228. );
  229. self.validate(&tx)?;
  230. // Only witness the value once the transaction is confirmed.
  231. self.dao_wallet.update_witness(&mut self.states).unwrap();
  232. // Retrieve DAO bulla from the state.
  233. let dao_bulla = {
  234. let func_call = &tx.func_calls[0];
  235. let call_data = func_call.call_data.as_any();
  236. let call_data = call_data.downcast_ref::<dao::mint::validate::CallData>().unwrap();
  237. call_data.dao_bulla.clone()
  238. };
  239. debug!(target: "demo", "Create DAO bulla: {:?}", dao_bulla.0);
  240. // We store these values in a vector we can easily retrieve DAO values for the demo.
  241. let dao_params = DaoParams {
  242. proposer_limit: dao_proposer_limit,
  243. quorum: dao_quorum,
  244. approval_ratio_quot: dao_approval_ratio_quot,
  245. approval_ratio_base: dao_approval_ratio_base,
  246. gov_token_id: token_id,
  247. public_key: self.dao_wallet.keypair.public,
  248. bulla_blind: self.dao_wallet.bulla_blind,
  249. };
  250. self.dao_wallet.params.push(dao_params);
  251. self.dao_wallet.bullas.push(dao_bulla.clone());
  252. Ok(dao_bulla.0)
  253. }
  254. fn mint_treasury(
  255. &mut self,
  256. token_id: pallas::Base,
  257. token_supply: u64,
  258. recipient: PublicKey,
  259. ) -> DaoResult<()> {
  260. self.dao_wallet.track(&mut self.states)?;
  261. let tx = self
  262. .cashier_wallet
  263. .mint(token_id, token_supply, self.dao_wallet.bullas[0].0, recipient, &self.zk_bins)
  264. .unwrap();
  265. self.validate(&tx)?;
  266. self.update_wallets()?;
  267. Ok(())
  268. }
  269. fn airdrop_user(
  270. &mut self,
  271. value: u64,
  272. token_id: pallas::Base,
  273. addr: PublicKey,
  274. ) -> DaoResult<()> {
  275. // let wallet = self.money_wallets.get(&nym).unwrap();
  276. // let addr = wallet.get_public_key();
  277. let tx = self.cashier_wallet.airdrop(value, token_id, addr, &self.zk_bins).unwrap();
  278. self.validate(&tx)?;
  279. self.update_wallets()?;
  280. Ok(())
  281. }
  282. // TODO: Change these into errors instead of expects.
  283. fn validate(&mut self, tx: &Transaction) -> DaoResult<()> {
  284. debug!(target: "dao_demo::client::validate()", "commencing validate sequence");
  285. let mut updates = vec![];
  286. // Validate all function calls in the tx
  287. for (idx, func_call) in tx.func_calls.iter().enumerate() {
  288. // So then the verifier will lookup the corresponding state_transition and apply
  289. // functions based off the func_id
  290. if func_call.func_id == *money::transfer::FUNC_ID {
  291. debug!("money_contract::transfer::state_transition()");
  292. match money::transfer::validate::state_transition(&self.states, idx, &tx) {
  293. Ok(update) => {
  294. updates.push(update);
  295. }
  296. Err(e) => return Err(DaoError::StateTransitionFailed(e.to_string())),
  297. }
  298. } else if func_call.func_id == *dao::mint::FUNC_ID {
  299. debug!("dao_contract::mint::state_transition()");
  300. match dao::mint::validate::state_transition(&self.states, idx, &tx) {
  301. Ok(update) => {
  302. updates.push(update);
  303. }
  304. Err(e) => return Err(DaoError::StateTransitionFailed(e.to_string())),
  305. }
  306. } else if func_call.func_id == *dao::propose::FUNC_ID {
  307. debug!(target: "demo", "dao_contract::propose::state_transition()");
  308. match dao::propose::validate::state_transition(&self.states, idx, &tx) {
  309. Ok(update) => {
  310. updates.push(update);
  311. }
  312. Err(e) => return Err(DaoError::StateTransitionFailed(e.to_string())),
  313. }
  314. } else if func_call.func_id == *dao::vote::FUNC_ID {
  315. debug!(target: "demo", "dao_contract::vote::state_transition()");
  316. match dao::vote::validate::state_transition(&self.states, idx, &tx) {
  317. Ok(update) => {
  318. updates.push(update);
  319. }
  320. Err(e) => return Err(DaoError::StateTransitionFailed(e.to_string())),
  321. }
  322. } else if func_call.func_id == *dao::exec::FUNC_ID {
  323. debug!("dao_contract::exec::state_transition()");
  324. match dao::exec::validate::state_transition(&self.states, idx, &tx) {
  325. Ok(update) => {
  326. updates.push(update);
  327. }
  328. Err(e) => return Err(DaoError::StateTransitionFailed(e.to_string())),
  329. }
  330. }
  331. }
  332. // Atomically apply all changes
  333. for update in updates {
  334. update.apply(&mut self.states);
  335. }
  336. tx.zk_verify(&self.zk_bins)?;
  337. tx.verify_sigs();
  338. Ok(())
  339. }
  340. fn update_wallets(&mut self) -> DaoResult<()> {
  341. let state = self.states.lookup_mut::<money::State>(*money::CONTRACT_ID);
  342. if state.is_none() {
  343. return Err(DaoError::StateNotFound)
  344. }
  345. let state = state.unwrap();
  346. let dao_coins = state.wallet_cache.get_received(&self.dao_wallet.keypair.secret);
  347. for coin in dao_coins {
  348. let note = coin.note.clone();
  349. let coords = self.dao_wallet.keypair.public.0.to_affine().coordinates().unwrap();
  350. let coin_hash = poseidon_hash::<8>([
  351. *coords.x(),
  352. *coords.y(),
  353. DrkValue::from(note.value),
  354. note.token_id,
  355. note.serial,
  356. note.spend_hook,
  357. note.user_data,
  358. note.coin_blind,
  359. ]);
  360. assert_eq!(coin_hash, coin.coin.0);
  361. assert_eq!(note.spend_hook, *dao::exec::FUNC_ID);
  362. assert_eq!(note.user_data, self.dao_wallet.bullas[0].0);
  363. self.dao_wallet.own_coins.push((coin, false));
  364. debug!("DAO received a coin worth {} xDRK", note.value);
  365. }
  366. for (_key, wallet) in &mut self.money_wallets {
  367. let coins = state.wallet_cache.get_received(&wallet.keypair.secret);
  368. for coin in coins {
  369. let note = coin.note.clone();
  370. let coords = wallet.keypair.public.0.to_affine().coordinates().unwrap();
  371. let coin_hash = poseidon_hash::<8>([
  372. *coords.x(),
  373. *coords.y(),
  374. DrkValue::from(note.value),
  375. note.token_id,
  376. note.serial,
  377. note.spend_hook,
  378. note.user_data,
  379. note.coin_blind,
  380. ]);
  381. assert_eq!(coin_hash, coin.coin.0);
  382. wallet.own_coins.push((coin, false));
  383. }
  384. }
  385. Ok(())
  386. }
  387. fn propose(
  388. &mut self,
  389. recipient: PublicKey,
  390. token_id: pallas::Base,
  391. amount: u64,
  392. sender: PublicKey,
  393. ) -> DaoResult<pallas::Base> {
  394. let params = self.dao_wallet.params[0].clone();
  395. let dao_leaf_position = self.dao_wallet.leaf_position;
  396. // To be able to make a proposal, we must prove we have ownership
  397. // of governance tokens, and that the quantity of governance
  398. // tokens is within the accepted proposer limit.
  399. let sender_wallet = self.money_wallets.get_mut(&sender);
  400. if sender_wallet.is_none() {
  401. return Err(DaoError::NoWalletFound)
  402. }
  403. let sender_wallet = sender_wallet.unwrap();
  404. let tx = sender_wallet.propose_tx(
  405. params.clone(),
  406. recipient,
  407. token_id,
  408. amount,
  409. dao_leaf_position,
  410. &self.zk_bins,
  411. &mut self.states,
  412. )?;
  413. self.validate(&tx)?;
  414. self.update_wallets()?;
  415. let proposal_bulla = self.dao_wallet.store_proposal(&tx)?;
  416. Ok(proposal_bulla)
  417. }
  418. fn cast_vote(&mut self, pubkey: PublicKey, vote: bool) -> DaoResult<()> {
  419. let dao_key = self.dao_wallet.keypair;
  420. if self.dao_wallet.proposals.is_empty() {
  421. return Err(DaoError::NoProposals)
  422. }
  423. let proposal = self.dao_wallet.proposals[0].clone();
  424. if self.dao_wallet.params.is_empty() {
  425. return Err(DaoError::DaoNotConfigured)
  426. }
  427. let dao_params = self.dao_wallet.params[0].clone();
  428. let dao_keypair = self.dao_wallet.keypair;
  429. let voter_wallet = self.money_wallets.get_mut(&pubkey);
  430. if voter_wallet.is_none() {
  431. return Err(DaoError::NoWalletFound)
  432. }
  433. let voter_wallet = voter_wallet.unwrap();
  434. let tx = voter_wallet.vote_tx(
  435. vote,
  436. dao_key,
  437. proposal,
  438. dao_params,
  439. dao_keypair,
  440. &self.zk_bins,
  441. &mut self.states,
  442. )?;
  443. self.validate(&tx)?;
  444. self.update_wallets()?;
  445. self.dao_wallet.store_vote(&tx).unwrap();
  446. Ok(())
  447. }
  448. fn exec_proposal(&mut self, bulla: pallas::Base) -> DaoResult<()> {
  449. if self.dao_wallet.proposals.is_empty() {
  450. return Err(DaoError::NoProposals)
  451. }
  452. let proposal = self.dao_wallet.proposals[0].clone();
  453. if self.dao_wallet.params.is_empty() {
  454. return Err(DaoError::DaoNotConfigured)
  455. }
  456. let dao_params = self.dao_wallet.params[0].clone();
  457. let tx = self
  458. .dao_wallet
  459. .exec_tx(proposal, bulla, dao_params, &self.zk_bins, &mut self.states)
  460. .unwrap();
  461. self.validate(&tx)?;
  462. self.update_wallets()?;
  463. Ok(())
  464. }
  465. }
  466. struct DaoWallet {
  467. keypair: Keypair,
  468. signature_secret: SecretKey,
  469. bulla_blind: pallas::Base,
  470. leaf_position: Position,
  471. proposal_bullas: Vec<pallas::Base>,
  472. bullas: Vec<DaoBulla>,
  473. params: Vec<DaoParams>,
  474. own_coins: Vec<(OwnCoin, bool)>,
  475. proposals: Vec<Proposal>,
  476. vote_notes: Vec<dao::vote::wallet::Note>,
  477. }
  478. impl DaoWallet {
  479. fn new() -> Self {
  480. let keypair = Keypair::random(&mut OsRng);
  481. let signature_secret = SecretKey::random(&mut OsRng);
  482. let bulla_blind = pallas::Base::random(&mut OsRng);
  483. let leaf_position = Position::zero();
  484. let proposal_bullas = Vec::new();
  485. let bullas = Vec::new();
  486. let params = Vec::new();
  487. let own_coins: Vec<(OwnCoin, bool)> = Vec::new();
  488. let proposals: Vec<Proposal> = Vec::new();
  489. let vote_notes = Vec::new();
  490. Self {
  491. keypair,
  492. signature_secret,
  493. bulla_blind,
  494. leaf_position,
  495. proposal_bullas,
  496. bullas,
  497. params,
  498. own_coins,
  499. proposals,
  500. vote_notes,
  501. }
  502. }
  503. fn get_public_key(&self) -> PublicKey {
  504. self.keypair.public
  505. }
  506. fn track(&self, states: &mut StateRegistry) -> DaoResult<()> {
  507. let state = states.lookup_mut::<money::State>(*money::CONTRACT_ID);
  508. if state.is_none() {
  509. return Err(DaoError::StateNotFound)
  510. }
  511. let state = state.unwrap();
  512. state.wallet_cache.track(self.keypair.secret);
  513. Ok(())
  514. }
  515. // Mint the DAO bulla.
  516. fn mint_tx(
  517. &mut self,
  518. dao_proposer_limit: u64,
  519. dao_quorum: u64,
  520. dao_approval_ratio_quot: u64,
  521. dao_approval_ratio_base: u64,
  522. token_id: pallas::Base,
  523. zk_bins: &ZkContractTable,
  524. ) -> Transaction {
  525. debug!(target: "dao-demo::dao::mint_tx()", "START");
  526. let builder = dao::mint::wallet::Builder {
  527. dao_proposer_limit,
  528. dao_quorum,
  529. dao_approval_ratio_quot,
  530. dao_approval_ratio_base,
  531. gov_token_id: token_id,
  532. dao_pubkey: self.keypair.public,
  533. dao_bulla_blind: self.bulla_blind,
  534. _signature_secret: self.signature_secret,
  535. };
  536. let func_call = builder.build(zk_bins);
  537. let func_calls = vec![func_call];
  538. let signatures = sign(vec![self.signature_secret], &func_calls);
  539. Transaction { func_calls, signatures }
  540. }
  541. fn update_witness(&mut self, states: &mut StateRegistry) -> DaoResult<()> {
  542. let state = states.lookup_mut::<dao::State>(*dao::CONTRACT_ID);
  543. if state.is_none() {
  544. return Err(DaoError::StateNotFound)
  545. }
  546. let state = state.unwrap();
  547. let path = state.dao_tree.witness().unwrap();
  548. self.leaf_position = path;
  549. Ok(())
  550. }
  551. // TODO: Make this a HashMap<TokenID, u64>
  552. // only parse it to a String in the cli.
  553. fn balances(&self) -> Result<FxHashMap<String, u64>> {
  554. let mut ret: FxHashMap<String, u64> = FxHashMap::default();
  555. for (coin, is_spent) in &self.own_coins {
  556. if *is_spent {}
  557. if coin.note.token_id == *DRK_ID {
  558. let id = "DRK".to_owned();
  559. ret.insert(id, coin.note.value);
  560. } else if coin.note.token_id == *GOV_ID {
  561. let id = "GOV".to_owned();
  562. ret.insert(id, coin.note.value);
  563. }
  564. }
  565. Ok(ret)
  566. }
  567. fn store_proposal(&mut self, tx: &Transaction) -> Result<pallas::Base> {
  568. let (proposal, proposal_bulla) = {
  569. let func_call = &tx.func_calls[0];
  570. let call_data = func_call.call_data.as_any();
  571. let call_data = call_data.downcast_ref::<dao::propose::validate::CallData>().unwrap();
  572. let header = &call_data.header;
  573. let note: dao::propose::wallet::Note =
  574. header.enc_note.decrypt(&self.keypair.secret).unwrap();
  575. // Return the proposal info
  576. (note.proposal, call_data.header.proposal_bulla)
  577. };
  578. debug!(target: "demo", "Proposal now active!");
  579. debug!(target: "demo", " destination: {:?}", proposal.dest);
  580. debug!(target: "demo", " amount: {}", proposal.amount);
  581. debug!(target: "demo", " token_id: {:?}", proposal.token_id);
  582. debug!(target: "demo", "Proposal bulla: {:?}", proposal_bulla);
  583. self.proposals.push(proposal);
  584. self.proposal_bullas.push(proposal_bulla);
  585. Ok(proposal_bulla)
  586. }
  587. // We decrypt the votes in a transaction and add it to the wallet.
  588. fn store_vote(&mut self, tx: &Transaction) -> Result<()> {
  589. let vote_note = {
  590. let func_call = &tx.func_calls[0];
  591. let call_data = func_call.call_data.as_any();
  592. let call_data = call_data.downcast_ref::<dao::vote::validate::CallData>().unwrap();
  593. let header = &call_data.header;
  594. let note: dao::vote::wallet::Note =
  595. header.enc_note.decrypt(&self.keypair.secret).unwrap();
  596. note
  597. };
  598. self.vote_notes.push(vote_note);
  599. Ok(())
  600. }
  601. fn get_proposals(&self) -> &Vec<Proposal> {
  602. &self.proposals
  603. }
  604. fn get_votes(&self) -> &Vec<dao::vote::wallet::Note> {
  605. &self.vote_notes
  606. }
  607. // TODO: Explicit error handling.
  608. fn get_treasury_path(
  609. &self,
  610. own_coin: &OwnCoin,
  611. states: &StateRegistry,
  612. ) -> Result<(Position, Vec<MerkleNode>)> {
  613. let (money_leaf_position, money_merkle_path) = {
  614. let state = states.lookup::<money::State>(*money::CONTRACT_ID).unwrap();
  615. let tree = &state.tree;
  616. let leaf_position = own_coin.leaf_position.clone();
  617. let root = tree.root(0).unwrap();
  618. let merkle_path = tree.authentication_path(leaf_position, &root).unwrap();
  619. (leaf_position, merkle_path)
  620. };
  621. Ok((money_leaf_position, money_merkle_path))
  622. }
  623. fn exec_tx(
  624. &self,
  625. proposal: Proposal,
  626. _proposal_bulla: pallas::Base,
  627. dao_params: DaoParams,
  628. zk_bins: &ZkContractTable,
  629. states: &mut StateRegistry,
  630. ) -> Result<Transaction> {
  631. let dao_bulla = self.bullas[0].clone();
  632. let mut inputs = Vec::new();
  633. let mut total_input_value = 0;
  634. let tx_signature_secret = SecretKey::random(&mut OsRng);
  635. let exec_signature_secret = SecretKey::random(&mut OsRng);
  636. let user_serial = pallas::Base::random(&mut OsRng);
  637. let user_coin_blind = pallas::Base::random(&mut OsRng);
  638. let user_data_blind = pallas::Base::random(&mut OsRng);
  639. let input_value_blind = pallas::Scalar::random(&mut OsRng);
  640. let dao_serial = pallas::Base::random(&mut OsRng);
  641. let dao_coin_blind = pallas::Base::random(&mut OsRng);
  642. // disabled
  643. let user_spend_hook = pallas::Base::from(0);
  644. let user_data = pallas::Base::from(0);
  645. for (coin, is_spent) in &self.own_coins {
  646. let is_spent = is_spent.clone();
  647. if is_spent {
  648. continue
  649. }
  650. let (treasury_leaf_position, treasury_merkle_path) =
  651. self.get_treasury_path(&coin, states)?;
  652. let input_value = coin.note.value;
  653. let input = {
  654. money::transfer::wallet::BuilderInputInfo {
  655. leaf_position: treasury_leaf_position,
  656. merkle_path: treasury_merkle_path,
  657. secret: self.keypair.secret,
  658. note: coin.note.clone(),
  659. user_data_blind,
  660. value_blind: input_value_blind,
  661. signature_secret: tx_signature_secret,
  662. }
  663. };
  664. total_input_value += input_value;
  665. inputs.push(input);
  666. }
  667. let builder = {
  668. money::transfer::wallet::Builder {
  669. clear_inputs: vec![],
  670. inputs,
  671. outputs: vec![
  672. // Sending money
  673. money::transfer::wallet::BuilderOutputInfo {
  674. value: proposal.amount,
  675. token_id: proposal.token_id,
  676. public: proposal.dest,
  677. serial: proposal.serial,
  678. coin_blind: proposal.blind,
  679. spend_hook: user_spend_hook,
  680. user_data,
  681. },
  682. // Change back to DAO
  683. money::transfer::wallet::BuilderOutputInfo {
  684. value: total_input_value - proposal.amount,
  685. token_id: *DRK_ID,
  686. public: self.keypair.public,
  687. serial: dao_serial,
  688. coin_blind: dao_coin_blind,
  689. spend_hook: *dao::exec::FUNC_ID,
  690. user_data: dao_bulla.0,
  691. },
  692. ],
  693. }
  694. };
  695. let transfer_func_call = builder.build(zk_bins).unwrap();
  696. let mut yes_votes_value = 0;
  697. let mut yes_votes_blind = pallas::Scalar::from(0);
  698. let mut yes_votes_commit = pallas::Point::identity();
  699. let mut all_votes_value = 0;
  700. let mut all_votes_blind = pallas::Scalar::from(0);
  701. let mut all_votes_commit = pallas::Point::identity();
  702. for (i, note) in self.vote_notes.iter().enumerate() {
  703. let vote_commit = pedersen_commitment_u64(note.vote_value, note.vote_value_blind);
  704. all_votes_commit += vote_commit;
  705. all_votes_blind += note.vote_value_blind;
  706. let yes_vote_commit = pedersen_commitment_u64(
  707. note.vote.vote_option as u64 * note.vote_value,
  708. note.vote.vote_option_blind,
  709. );
  710. yes_votes_commit += yes_vote_commit;
  711. yes_votes_blind += note.vote.vote_option_blind;
  712. let vote_option = note.vote.vote_option;
  713. if vote_option {
  714. yes_votes_value += note.vote_value;
  715. }
  716. all_votes_value += note.vote_value;
  717. let vote_result: String =
  718. if vote_option { "yes".to_string() } else { "no".to_string() };
  719. debug!("Voter {} voted {}", i, vote_result);
  720. }
  721. debug!("Outcome = {} / {}", yes_votes_value, all_votes_value);
  722. assert!(all_votes_commit == pedersen_commitment_u64(all_votes_value, all_votes_blind));
  723. assert!(yes_votes_commit == pedersen_commitment_u64(yes_votes_value, yes_votes_blind));
  724. let builder = {
  725. dao::exec::wallet::Builder {
  726. proposal: proposal.clone(),
  727. dao: dao_params.clone(),
  728. yes_votes_value,
  729. all_votes_value,
  730. yes_votes_blind,
  731. all_votes_blind,
  732. user_serial,
  733. user_coin_blind,
  734. dao_serial,
  735. dao_coin_blind,
  736. input_value: total_input_value,
  737. input_value_blind,
  738. hook_dao_exec: *dao::exec::FUNC_ID,
  739. signature_secret: exec_signature_secret,
  740. }
  741. };
  742. let exec_func_call = builder.build(zk_bins);
  743. let func_calls = vec![transfer_func_call, exec_func_call];
  744. let signatures = sign(vec![tx_signature_secret, exec_signature_secret], &func_calls);
  745. Ok(Transaction { func_calls, signatures })
  746. }
  747. }
  748. // Stores governance tokens and related secret values.
  749. struct MoneyWallet {
  750. keypair: Keypair,
  751. signature_secret: SecretKey,
  752. own_coins: Vec<(OwnCoin, bool)>,
  753. }
  754. impl MoneyWallet {
  755. // fn signature_public(&self) -> PublicKey {
  756. // PublicKey::from_secret(self.signature_secret)
  757. // }
  758. // fn get_public_key(&self) -> PublicKey {
  759. // self.keypair.public
  760. // }
  761. fn track(&self, states: &mut StateRegistry) -> DaoResult<()> {
  762. let state = states.lookup_mut::<money::State>(*money::CONTRACT_ID);
  763. if state.is_none() {
  764. return Err(DaoError::StateNotFound)
  765. }
  766. let state = state.unwrap();
  767. state.wallet_cache.track(self.keypair.secret);
  768. Ok(())
  769. }
  770. // TODO: Make this a HashMap<TokenID, u64>
  771. // only parse it to a String in the cli.
  772. fn balances(&self) -> Result<FxHashMap<String, u64>> {
  773. let mut ret: FxHashMap<String, u64> = FxHashMap::default();
  774. for (coin, is_spent) in &self.own_coins {
  775. if *is_spent {}
  776. if coin.note.token_id == *DRK_ID {
  777. let id = "DRK".to_owned();
  778. ret.insert(id, coin.note.value);
  779. } else if coin.note.token_id == *GOV_ID {
  780. let id = "GOV".to_owned();
  781. ret.insert(id, coin.note.value);
  782. }
  783. }
  784. Ok(ret)
  785. }
  786. fn propose_tx(
  787. &mut self,
  788. params: DaoParams,
  789. recipient: PublicKey,
  790. token_id: pallas::Base,
  791. amount: u64,
  792. dao_leaf_position: Position,
  793. zk_bins: &ZkContractTable,
  794. states: &mut StateRegistry,
  795. ) -> Result<Transaction> {
  796. let mut inputs = Vec::new();
  797. for (coin, is_spent) in &self.own_coins {
  798. let is_spent = is_spent.clone();
  799. if is_spent {
  800. continue
  801. }
  802. let (money_leaf_position, money_merkle_path) = self.get_path(&states, &coin).unwrap();
  803. let input = {
  804. dao::propose::wallet::BuilderInput {
  805. secret: self.keypair.secret,
  806. note: coin.note.clone(),
  807. leaf_position: money_leaf_position,
  808. merkle_path: money_merkle_path,
  809. signature_secret: self.signature_secret,
  810. }
  811. };
  812. inputs.push(input);
  813. }
  814. let (dao_merkle_path, dao_merkle_root) = {
  815. let state = states.lookup::<dao::State>(*dao::CONTRACT_ID).unwrap();
  816. let tree = &state.dao_tree;
  817. let root = tree.root(0).unwrap();
  818. let merkle_path = tree.authentication_path(dao_leaf_position, &root).unwrap();
  819. (merkle_path, root)
  820. };
  821. let proposal = {
  822. dao::propose::wallet::Proposal {
  823. dest: recipient,
  824. amount,
  825. serial: pallas::Base::random(&mut OsRng),
  826. token_id,
  827. blind: pallas::Base::random(&mut OsRng),
  828. }
  829. };
  830. let builder = dao::propose::wallet::Builder {
  831. inputs,
  832. proposal,
  833. dao: params.clone(),
  834. dao_leaf_position,
  835. dao_merkle_path,
  836. dao_merkle_root,
  837. };
  838. let func_call = builder.build(zk_bins);
  839. let func_calls = vec![func_call];
  840. let signatures = sign(vec![self.signature_secret], &func_calls);
  841. Ok(Transaction { func_calls, signatures })
  842. }
  843. fn get_path(
  844. &self,
  845. states: &StateRegistry,
  846. own_coin: &OwnCoin,
  847. ) -> Result<(Position, Vec<MerkleNode>)> {
  848. let (money_leaf_position, money_merkle_path) = {
  849. let state = states.lookup::<money::State>(*money::CONTRACT_ID).unwrap();
  850. let tree = &state.tree;
  851. let leaf_position = own_coin.leaf_position.clone();
  852. let root = tree.root(0).unwrap();
  853. let merkle_path = tree.authentication_path(leaf_position, &root).unwrap();
  854. (leaf_position, merkle_path)
  855. };
  856. Ok((money_leaf_position, money_merkle_path))
  857. }
  858. fn vote_tx(
  859. &mut self,
  860. vote_option: bool,
  861. _dao_key: Keypair,
  862. proposal: Proposal,
  863. dao_params: DaoParams,
  864. dao_keypair: Keypair,
  865. zk_bins: &ZkContractTable,
  866. states: &mut StateRegistry,
  867. ) -> Result<Transaction> {
  868. let mut inputs = Vec::new();
  869. // We must prove we have sufficient governance tokens in order to vote.
  870. for (coin, _is_spent) in &self.own_coins {
  871. let (money_leaf_position, money_merkle_path) = self.get_path(states, &coin).unwrap();
  872. let input = {
  873. dao::vote::wallet::BuilderInput {
  874. secret: self.keypair.secret,
  875. note: coin.note.clone(),
  876. leaf_position: money_leaf_position,
  877. merkle_path: money_merkle_path,
  878. signature_secret: self.signature_secret,
  879. }
  880. };
  881. inputs.push(input);
  882. }
  883. let builder = {
  884. dao::vote::wallet::Builder {
  885. inputs,
  886. vote: dao::vote::wallet::Vote {
  887. vote_option,
  888. vote_option_blind: pallas::Scalar::random(&mut OsRng),
  889. },
  890. // For this demo votes are encrypted for the DAO.
  891. vote_keypair: dao_keypair,
  892. proposal: proposal.clone(),
  893. dao: dao_params.clone(),
  894. }
  895. };
  896. let func_call = builder.build(zk_bins);
  897. let func_calls = vec![func_call];
  898. let signatures = sign(vec![self.signature_secret], &func_calls);
  899. Ok(Transaction { func_calls, signatures })
  900. }
  901. }
  902. async fn start_rpc(client: Client) -> Result<()> {
  903. let rpc_addr = Url::parse("tcp://127.0.0.1:7777").unwrap();
  904. let rpc_client = JsonRpcInterface::new(client);
  905. let rpc_interface = Arc::new(rpc_client);
  906. listen_and_serve(rpc_addr, rpc_interface).await.unwrap();
  907. Ok(())
  908. }
  909. // Mint authority that mints the DAO treasury and airdrops governance tokens.
  910. #[derive(Clone)]
  911. struct CashierWallet {
  912. // keypair: Keypair,
  913. signature_secret: SecretKey,
  914. }
  915. impl CashierWallet {
  916. fn new() -> Self {
  917. // let keypair = Keypair::random(&mut OsRng);
  918. let signature_secret = SecretKey::random(&mut OsRng);
  919. // Self { keypair, signature_secret }
  920. Self { signature_secret }
  921. }
  922. fn signature_public(&self) -> PublicKey {
  923. PublicKey::from_secret(self.signature_secret)
  924. }
  925. fn mint(
  926. &mut self,
  927. token_id: pallas::Base,
  928. token_supply: u64,
  929. dao_bulla: pallas::Base,
  930. recipient: PublicKey,
  931. zk_bins: &ZkContractTable,
  932. ) -> Result<Transaction> {
  933. let spend_hook = *dao::exec::FUNC_ID;
  934. let user_data = dao_bulla;
  935. let value = token_supply;
  936. let tx =
  937. self.transfer_tx(value, token_id, spend_hook, user_data, recipient, zk_bins).unwrap();
  938. Ok(tx)
  939. }
  940. fn transfer_tx(
  941. &self,
  942. value: u64,
  943. token_id: pallas::Base,
  944. spend_hook: pallas::Base,
  945. user_data: pallas::Base,
  946. recipient: PublicKey,
  947. zk_bins: &ZkContractTable,
  948. ) -> Result<Transaction> {
  949. let builder = {
  950. money::transfer::wallet::Builder {
  951. clear_inputs: vec![money::transfer::wallet::BuilderClearInputInfo {
  952. value,
  953. token_id,
  954. signature_secret: self.signature_secret,
  955. }],
  956. inputs: vec![],
  957. outputs: vec![money::transfer::wallet::BuilderOutputInfo {
  958. value,
  959. token_id,
  960. public: recipient,
  961. serial: pallas::Base::random(&mut OsRng),
  962. coin_blind: pallas::Base::random(&mut OsRng),
  963. spend_hook,
  964. user_data,
  965. }],
  966. }
  967. };
  968. let func_call = builder.build(zk_bins).unwrap();
  969. let func_calls = vec![func_call];
  970. let signatures = sign(vec![self.signature_secret], &func_calls);
  971. Ok(Transaction { func_calls, signatures })
  972. }
  973. fn airdrop(
  974. &mut self,
  975. value: u64,
  976. token_id: pallas::Base,
  977. recipient: PublicKey,
  978. zk_bins: &ZkContractTable,
  979. ) -> Result<Transaction> {
  980. // Spend hook and user data disabled
  981. let spend_hook = DrkSpendHook::from(0);
  982. let user_data = DrkUserData::from(0);
  983. let tx =
  984. self.transfer_tx(value, token_id, spend_hook, user_data, recipient, zk_bins).unwrap();
  985. Ok(tx)
  986. }
  987. }
  988. #[async_std::main]
  989. async fn main() -> Result<()> {
  990. TermLogger::init(
  991. LevelFilter::Debug,
  992. simplelog::Config::default(),
  993. TerminalMode::Mixed,
  994. ColorChoice::Auto,
  995. )
  996. .unwrap();
  997. let mut client = Client::new();
  998. client.init()?;
  999. start_rpc(client).await.unwrap();
  1000. Ok(())
  1001. }