dao.rs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{collections::HashMap, fmt};
  19. use lazy_static::lazy_static;
  20. use rand::rngs::OsRng;
  21. use rusqlite::types::Value;
  22. use darkfi::{
  23. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  24. util::parse::encode_base10,
  25. zk::{empty_witnesses, halo2::Field, ProvingKey, ZkCircuit},
  26. zkas::ZkBinary,
  27. Error, Result,
  28. };
  29. use darkfi_dao_contract::{
  30. client::{make_mint_call, DaoProposeCall, DaoProposeStakeInput, DaoVoteCall, DaoVoteInput},
  31. model::{DaoAuthCall, DaoBulla, DaoMintParams, DaoProposeParams, DaoVoteParams},
  32. DaoFunction, DAO_CONTRACT_ZKAS_DAO_MINT_NS, DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS,
  33. DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS, DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS,
  34. DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS,
  35. };
  36. use darkfi_money_contract::{client::OwnCoin, model::TokenId, MoneyFunction};
  37. use darkfi_sdk::{
  38. bridgetree,
  39. crypto::{
  40. poseidon_hash,
  41. util::{fp_mod_fv, fp_to_u64},
  42. BaseBlind, Blind, FuncId, FuncRef, Keypair, MerkleNode, MerkleTree, PublicKey, ScalarBlind,
  43. SecretKey, DAO_CONTRACT_ID, MONEY_CONTRACT_ID,
  44. },
  45. pasta::pallas,
  46. ContractCall,
  47. };
  48. use darkfi_serial::{
  49. async_trait, deserialize, serialize, Encodable, SerialDecodable, SerialEncodable,
  50. };
  51. use crate::{
  52. convert_named_params,
  53. error::{WalletDbError, WalletDbResult},
  54. money::BALANCE_BASE10_DECIMALS,
  55. Drk,
  56. };
  57. // Wallet SQL table constant names. These have to represent the `wallet.sql`
  58. // SQL schema. Table names are prefixed with the contract ID to avoid collisions.
  59. lazy_static! {
  60. pub static ref DAO_DAOS_TABLE: String = format!("{}_dao_daos", DAO_CONTRACT_ID.to_string());
  61. pub static ref DAO_TREES_TABLE: String = format!("{}_dao_trees", DAO_CONTRACT_ID.to_string());
  62. pub static ref DAO_COINS_TABLE: String = format!("{}_dao_coins", DAO_CONTRACT_ID.to_string());
  63. pub static ref DAO_PROPOSALS_TABLE: String =
  64. format!("{}_dao_proposals", DAO_CONTRACT_ID.to_string());
  65. pub static ref DAO_VOTES_TABLE: String = format!("{}_dao_votes", DAO_CONTRACT_ID.to_string());
  66. }
  67. // DAO_DAOS_TABLE
  68. pub const DAO_DAOS_COL_DAO_ID: &str = "dao_id";
  69. pub const DAO_DAOS_COL_NAME: &str = "name";
  70. pub const DAO_DAOS_COL_PROPOSER_LIMIT: &str = "proposer_limit";
  71. pub const DAO_DAOS_COL_QUORUM: &str = "quorum";
  72. pub const DAO_DAOS_COL_APPROVAL_RATIO_BASE: &str = "approval_ratio_base";
  73. pub const DAO_DAOS_COL_APPROVAL_RATIO_QUOT: &str = "approval_ratio_quot";
  74. pub const DAO_DAOS_COL_GOV_TOKEN_ID: &str = "gov_token_id";
  75. pub const DAO_DAOS_COL_SECRET: &str = "secret";
  76. pub const DAO_DAOS_COL_BULLA_BLIND: &str = "bulla_blind";
  77. pub const DAO_DAOS_COL_LEAF_POSITION: &str = "leaf_position";
  78. pub const DAO_DAOS_COL_TX_HASH: &str = "tx_hash";
  79. pub const DAO_DAOS_COL_CALL_INDEX: &str = "call_index";
  80. // DAO_TREES_TABLE
  81. pub const DAO_TREES_COL_DAOS_TREE: &str = "daos_tree";
  82. pub const DAO_TREES_COL_PROPOSALS_TREE: &str = "proposals_tree";
  83. // DAO_COINS_TABLE
  84. pub const _DAO_COINS_COL_COIN_ID: &str = "coin_id";
  85. pub const _DAO_COINS_COL_DAO_ID: &str = "dao_id";
  86. // DAO_PROPOSALS_TABLE
  87. pub const DAO_PROPOSALS_COL_PROPOSAL_ID: &str = "proposal_id";
  88. pub const DAO_PROPOSALS_COL_DAO_ID: &str = "dao_id";
  89. pub const DAO_PROPOSALS_COL_RECV_PUBLIC: &str = "recv_public";
  90. pub const DAO_PROPOSALS_COL_AMOUNT: &str = "amount";
  91. pub const DAO_PROPOSALS_COL_SENDCOIN_TOKEN_ID: &str = "sendcoin_token_id";
  92. pub const DAO_PROPOSALS_COL_BULLA_BLIND: &str = "bulla_blind";
  93. pub const DAO_PROPOSALS_COL_LEAF_POSITION: &str = "leaf_position";
  94. pub const DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE: &str = "money_snapshot_tree";
  95. pub const DAO_PROPOSALS_COL_TX_HASH: &str = "tx_hash";
  96. pub const DAO_PROPOSALS_COL_CALL_INDEX: &str = "call_index";
  97. pub const _DAO_PROPOSALS_COL_OUR_VOTE_ID: &str = "our_vote_id";
  98. // DAO_VOTES_TABLE
  99. pub const _DAO_VOTES_COL_VOTE_ID: &str = "vote_id";
  100. pub const DAO_VOTES_COL_PROPOSAL_ID: &str = "proposal_id";
  101. pub const DAO_VOTES_COL_VOTE_OPTION: &str = "vote_option";
  102. pub const DAO_VOTES_COL_YES_VOTE_BLIND: &str = "yes_vote_blind";
  103. pub const DAO_VOTES_COL_ALL_VOTE_VALUE: &str = "all_vote_value";
  104. pub const DAO_VOTES_COL_ALL_VOTE_BLIND: &str = "all_vote_blind";
  105. pub const DAO_VOTES_COL_TX_HASH: &str = "tx_hash";
  106. pub const DAO_VOTES_COL_CALL_INDEX: &str = "call_index";
  107. #[derive(SerialEncodable, SerialDecodable, Clone)]
  108. pub struct DaoProposalInfo {
  109. pub dest: PublicKey,
  110. pub amount: u64,
  111. pub token_id: TokenId,
  112. pub blind: BaseBlind,
  113. }
  114. #[derive(SerialEncodable, SerialDecodable)]
  115. pub struct DaoProposeNote {
  116. pub proposal: DaoProposalInfo,
  117. }
  118. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  119. /// Parameters representing a DAO to be initialized
  120. pub struct DaoParams {
  121. /// The minimum amount of governance tokens needed to open a proposal
  122. pub proposer_limit: u64,
  123. /// Minimal threshold of participating total tokens needed for a proposal to pass
  124. pub quorum: u64,
  125. /// The ratio of winning/total votes needed for a proposal to pass
  126. pub approval_ratio_base: u64,
  127. pub approval_ratio_quot: u64,
  128. /// DAO's governance token ID
  129. pub gov_token_id: TokenId,
  130. /// Secret key for the DAO
  131. pub secret_key: SecretKey,
  132. /// DAO bulla blind
  133. pub bulla_blind: pallas::Base,
  134. }
  135. impl fmt::Display for DaoParams {
  136. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  137. let s = format!(
  138. "{}\n{}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {:?}",
  139. "DAO Parameters",
  140. "==============",
  141. "Proposer limit",
  142. encode_base10(self.proposer_limit, BALANCE_BASE10_DECIMALS),
  143. self.proposer_limit,
  144. "Quorum",
  145. encode_base10(self.quorum, BALANCE_BASE10_DECIMALS),
  146. self.quorum,
  147. "Approval ratio",
  148. self.approval_ratio_quot as f64 / self.approval_ratio_base as f64,
  149. "Governance Token ID",
  150. self.gov_token_id,
  151. "Public key",
  152. PublicKey::from_secret(self.secret_key),
  153. "Secret key",
  154. self.secret_key,
  155. "Bulla blind",
  156. self.bulla_blind,
  157. );
  158. write!(f, "{}", s)
  159. }
  160. }
  161. #[derive(Debug, Clone)]
  162. /// Parameters representing an intialized DAO, optionally deployed on-chain
  163. pub struct Dao {
  164. /// Numeric identifier for the DAO
  165. pub id: u64,
  166. /// Named identifier for the DAO
  167. pub name: String,
  168. /// The minimum amount of governance tokens needed to open a proposal
  169. pub proposer_limit: u64,
  170. /// Minimal threshold of participating total tokens needed for a proposal to pass
  171. pub quorum: u64,
  172. /// The ratio of winning/total votes needed for a proposal to pass
  173. pub approval_ratio_base: u64,
  174. pub approval_ratio_quot: u64,
  175. /// DAO's governance token ID
  176. pub gov_token_id: TokenId,
  177. /// Secret key for the DAO
  178. pub secret_key: SecretKey,
  179. /// DAO bulla blind
  180. pub bulla_blind: BaseBlind,
  181. /// Leaf position of the DAO in the Merkle tree of DAOs
  182. pub leaf_position: Option<bridgetree::Position>,
  183. /// The transaction hash where the DAO was deployed
  184. pub tx_hash: Option<blake3::Hash>,
  185. /// The call index in the transaction where the DAO was deployed
  186. pub call_index: Option<u32>,
  187. }
  188. impl Dao {
  189. pub fn bulla(&self) -> DaoBulla {
  190. let (x, y) = PublicKey::from_secret(self.secret_key).xy();
  191. DaoBulla::from(poseidon_hash([
  192. pallas::Base::from(self.proposer_limit),
  193. pallas::Base::from(self.quorum),
  194. pallas::Base::from(self.approval_ratio_quot),
  195. pallas::Base::from(self.approval_ratio_base),
  196. self.gov_token_id.inner(),
  197. x,
  198. y,
  199. self.bulla_blind.inner(),
  200. ]))
  201. }
  202. pub fn keypair(&self) -> Keypair {
  203. let public = PublicKey::from_secret(self.secret_key);
  204. Keypair { public, secret: self.secret_key }
  205. }
  206. }
  207. impl fmt::Display for Dao {
  208. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  209. let s = format!(
  210. "{}\n{}\n{}: {}\n{}: {}\n{}: {} ({})\n{}: {} ({})\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {:?}\n{}: {:?}\n{}: {:?}\n{}: {:?}",
  211. "DAO Parameters",
  212. "==============",
  213. "Name",
  214. self.name,
  215. "Bulla",
  216. self.bulla(),
  217. "Proposer limit",
  218. encode_base10(self.proposer_limit, BALANCE_BASE10_DECIMALS),
  219. self.proposer_limit,
  220. "Quorum",
  221. encode_base10(self.quorum, BALANCE_BASE10_DECIMALS),
  222. self.quorum,
  223. "Approval ratio",
  224. self.approval_ratio_quot as f64 / self.approval_ratio_base as f64,
  225. "Governance Token ID",
  226. self.gov_token_id,
  227. "Public key",
  228. PublicKey::from_secret(self.secret_key),
  229. "Secret key",
  230. self.secret_key,
  231. "Bulla blind",
  232. self.bulla_blind,
  233. "Leaf position",
  234. self.leaf_position,
  235. "Tx hash",
  236. self.tx_hash,
  237. "Call idx",
  238. self.call_index,
  239. );
  240. write!(f, "{}", s)
  241. }
  242. }
  243. #[derive(Debug, Clone)]
  244. /// Parameters representing an initialized DAO proposal, optionally deployed on-chain
  245. pub struct DaoProposal {
  246. /// Numeric identifier for the proposal
  247. pub id: u64,
  248. /// The DAO bulla related to this proposal
  249. pub dao_bulla: DaoBulla,
  250. /// Recipient of this proposal's funds
  251. pub recipient: PublicKey,
  252. /// Amount of this proposal
  253. pub amount: u64,
  254. /// Token ID to be sent
  255. pub token_id: TokenId,
  256. /// Proposal's bulla blind
  257. pub bulla_blind: BaseBlind,
  258. /// Leaf position of this proposal in the Merkle tree of proposals
  259. pub leaf_position: Option<bridgetree::Position>,
  260. /// Snapshotted Money Merkle tree
  261. pub money_snapshot_tree: Option<MerkleTree>,
  262. /// Transaction hash where this proposal was proposed
  263. pub tx_hash: Option<blake3::Hash>,
  264. /// call index in the transaction where this proposal was proposed
  265. pub call_index: Option<u32>,
  266. /// The vote ID we've voted on this proposal
  267. pub vote_id: Option<pallas::Base>,
  268. }
  269. impl DaoProposal {
  270. pub fn bulla(&self) -> pallas::Base {
  271. let (dest_x, dest_y) = self.recipient.xy();
  272. poseidon_hash([
  273. dest_x,
  274. dest_y,
  275. pallas::Base::from(self.amount),
  276. self.token_id.inner(),
  277. self.dao_bulla.inner(),
  278. self.bulla_blind.inner(),
  279. ])
  280. }
  281. }
  282. impl fmt::Display for DaoProposal {
  283. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  284. let s = format!(
  285. concat!(
  286. "Proposal parameters\n",
  287. "===================\n",
  288. "DAO Bulla: {}\n",
  289. "Recipient: {}\n",
  290. "Proposal amount: {} ({})\n",
  291. "Proposal Token ID: {:?}\n",
  292. "Proposal bulla blind: {:?}\n",
  293. "Proposal leaf position: {:?}\n",
  294. "Proposal tx hash: {:?}\n",
  295. "Proposal call index: {:?}\n",
  296. "Proposal vote ID: {:?}",
  297. ),
  298. self.dao_bulla,
  299. self.recipient,
  300. encode_base10(self.amount, BALANCE_BASE10_DECIMALS),
  301. self.amount,
  302. self.token_id,
  303. self.bulla_blind,
  304. self.leaf_position,
  305. self.tx_hash,
  306. self.call_index,
  307. self.vote_id,
  308. );
  309. write!(f, "{}", s)
  310. }
  311. }
  312. #[derive(Debug, Clone)]
  313. /// Parameters representing a vote we've made on a DAO proposal
  314. pub struct DaoVote {
  315. /// Numeric identifier for the vote
  316. pub id: u64,
  317. /// Numeric identifier for the proposal related to this vote
  318. pub proposal_id: u64,
  319. /// The vote
  320. pub vote_option: bool,
  321. /// Blinding factor for the yes vote
  322. pub yes_vote_blind: ScalarBlind,
  323. /// Value of all votes
  324. pub all_vote_value: u64,
  325. /// Blinding facfor of all votes
  326. pub all_vote_blind: ScalarBlind,
  327. /// Transaction hash where this vote was casted
  328. pub tx_hash: Option<blake3::Hash>,
  329. /// call index in the transaction where this vote was casted
  330. pub call_index: Option<u32>,
  331. }
  332. impl Drk {
  333. /// Initialize wallet with tables for the DAO contract.
  334. pub async fn initialize_dao(&self) -> WalletDbResult<()> {
  335. // Initialize DAO wallet schema
  336. let wallet_schema = include_str!("../dao.sql");
  337. self.wallet.exec_batch_sql(wallet_schema).await?;
  338. // Check if we have to initialize the Merkle trees.
  339. // We check if one exists, but we actually create two. This should be written
  340. // a bit better and safer.
  341. // For now, on success, we don't care what's returned, but in the future
  342. // we should actually check it.
  343. if self
  344. .wallet
  345. .query_single(&DAO_TREES_TABLE, &[DAO_TREES_COL_DAOS_TREE], &[])
  346. .await
  347. .is_err()
  348. {
  349. eprintln!("Initializing DAO Merkle trees");
  350. let tree = MerkleTree::new(100);
  351. self.put_dao_trees(&tree, &tree).await?;
  352. eprintln!("Successfully initialized Merkle trees for the DAO contract");
  353. }
  354. Ok(())
  355. }
  356. /// Replace the DAO Merkle trees in the wallet.
  357. pub async fn put_dao_trees(
  358. &self,
  359. daos_tree: &MerkleTree,
  360. proposals_tree: &MerkleTree,
  361. ) -> WalletDbResult<()> {
  362. // First we remove old records
  363. let query = format!("DELETE FROM {};", *DAO_TREES_TABLE);
  364. self.wallet.exec_sql(&query, &[]).await?;
  365. // then we insert the new one
  366. let query = format!(
  367. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  368. *DAO_TREES_TABLE, DAO_TREES_COL_DAOS_TREE, DAO_TREES_COL_PROPOSALS_TREE,
  369. );
  370. self.wallet
  371. .exec_sql(&query, rusqlite::params![serialize(daos_tree), serialize(proposals_tree)])
  372. .await
  373. }
  374. /// Fetch DAO Merkle trees from the wallet.
  375. pub async fn get_dao_trees(&self) -> Result<(MerkleTree, MerkleTree)> {
  376. let row = match self.wallet.query_single(&DAO_TREES_TABLE, &[], &[]).await {
  377. Ok(r) => r,
  378. Err(e) => {
  379. return Err(Error::RusqliteError(format!(
  380. "[get_dao_trees] Trees retrieval failed: {e:?}"
  381. )))
  382. }
  383. };
  384. let Value::Blob(ref daos_tree_bytes) = row[0] else {
  385. return Err(Error::ParseFailed("[get_dao_trees] DAO tree bytes parsing failed"))
  386. };
  387. let daos_tree = deserialize(daos_tree_bytes)?;
  388. let Value::Blob(ref proposals_tree_bytes) = row[1] else {
  389. return Err(Error::ParseFailed("[get_dao_trees] Proposals tree bytes parsing failed"))
  390. };
  391. let proposals_tree = deserialize(proposals_tree_bytes)?;
  392. Ok((daos_tree, proposals_tree))
  393. }
  394. /// Fetch all DAO secret keys from the wallet.
  395. pub async fn get_dao_secrets(&self) -> Result<Vec<SecretKey>> {
  396. let daos = self.get_daos().await?;
  397. let mut ret = Vec::with_capacity(daos.len());
  398. for dao in daos {
  399. ret.push(dao.secret_key);
  400. }
  401. Ok(ret)
  402. }
  403. /// Fetch all known DAOs from the wallet.
  404. pub async fn get_daos(&self) -> Result<Vec<Dao>> {
  405. let rows = match self.wallet.query_multiple(&DAO_DAOS_TABLE, &[], &[]).await {
  406. Ok(r) => r,
  407. Err(e) => {
  408. return Err(Error::RusqliteError(format!("[get_daos] DAOs retrieval failed: {e:?}")))
  409. }
  410. };
  411. let mut daos = Vec::with_capacity(rows.len());
  412. for row in rows {
  413. let Value::Integer(id) = row[0] else {
  414. return Err(Error::ParseFailed("[get_daos] ID parsing failed"))
  415. };
  416. let Ok(id) = u64::try_from(id) else {
  417. return Err(Error::ParseFailed("[get_daos] ID parsing failed"))
  418. };
  419. let Value::Text(ref name) = row[1] else {
  420. return Err(Error::ParseFailed("[get_daos] Name parsing failed"))
  421. };
  422. let name = name.clone();
  423. let Value::Blob(ref proposer_limit_bytes) = row[2] else {
  424. return Err(Error::ParseFailed("[get_daos] Proposer limit bytes parsing failed"))
  425. };
  426. let proposer_limit = deserialize(proposer_limit_bytes)?;
  427. let Value::Blob(ref quorum_bytes) = row[3] else {
  428. return Err(Error::ParseFailed("[get_daos] Quorum bytes parsing failed"))
  429. };
  430. let quorum = deserialize(quorum_bytes)?;
  431. let Value::Integer(approval_ratio_base) = row[4] else {
  432. return Err(Error::ParseFailed("[get_daos] Approval ratio base parsing failed"))
  433. };
  434. let Ok(approval_ratio_base) = u64::try_from(approval_ratio_base) else {
  435. return Err(Error::ParseFailed("[get_daos] Approval ratio base parsing failed"))
  436. };
  437. let Value::Integer(approval_ratio_quot) = row[5] else {
  438. return Err(Error::ParseFailed("[get_daos] Approval ratio quot parsing failed"))
  439. };
  440. let Ok(approval_ratio_quot) = u64::try_from(approval_ratio_quot) else {
  441. return Err(Error::ParseFailed("[get_daos] Approval ratio quot parsing failed"))
  442. };
  443. let Value::Blob(ref gov_token_bytes) = row[6] else {
  444. return Err(Error::ParseFailed("[get_daos] Gov token bytes parsing failed"))
  445. };
  446. let gov_token_id = deserialize(gov_token_bytes)?;
  447. let Value::Blob(ref secret_bytes) = row[7] else {
  448. return Err(Error::ParseFailed("[get_daos] Secret key bytes parsing failed"))
  449. };
  450. let secret_key = deserialize(secret_bytes)?;
  451. let Value::Blob(ref bulla_blind_bytes) = row[8] else {
  452. return Err(Error::ParseFailed("[get_daos] Bulla blind bytes parsing failed"))
  453. };
  454. let bulla_blind = deserialize(bulla_blind_bytes)?;
  455. let Value::Blob(ref leaf_position_bytes) = row[9] else {
  456. return Err(Error::ParseFailed("[get_daos] Leaf position bytes parsing failed"))
  457. };
  458. let leaf_position = if leaf_position_bytes.is_empty() {
  459. None
  460. } else {
  461. Some(deserialize(leaf_position_bytes)?)
  462. };
  463. let Value::Blob(ref tx_hash_bytes) = row[10] else {
  464. return Err(Error::ParseFailed("[get_daos] Transaction hash bytes parsing failed"))
  465. };
  466. let tx_hash =
  467. if tx_hash_bytes.is_empty() { None } else { Some(deserialize(tx_hash_bytes)?) };
  468. let Value::Integer(call_index) = row[11] else {
  469. return Err(Error::ParseFailed("[get_daos] Call index parsing failed"))
  470. };
  471. let Ok(call_index) = u32::try_from(call_index) else {
  472. return Err(Error::ParseFailed("[get_daos] Call index parsing failed"))
  473. };
  474. let call_index = Some(call_index);
  475. let dao = Dao {
  476. id,
  477. name,
  478. proposer_limit,
  479. quorum,
  480. approval_ratio_base,
  481. approval_ratio_quot,
  482. gov_token_id,
  483. secret_key,
  484. bulla_blind,
  485. leaf_position,
  486. tx_hash,
  487. call_index,
  488. };
  489. daos.push(dao);
  490. }
  491. // Here we sort the vec by ID. The SQL SELECT statement does not guarantee
  492. // this, so just do it here.
  493. daos.sort_by(|a, b| a.id.cmp(&b.id));
  494. Ok(daos)
  495. }
  496. /// Auxiliary function to parse a proposal record row.
  497. fn parse_dao_proposal(&self, dao: &Dao, row: &[Value]) -> Result<DaoProposal> {
  498. let Value::Integer(id) = row[0] else {
  499. return Err(Error::ParseFailed("[get_dao_proposals] ID parsing failed"))
  500. };
  501. let Ok(id) = u64::try_from(id) else {
  502. return Err(Error::ParseFailed("[get_dao_proposals] ID parsing failed"))
  503. };
  504. let Value::Integer(dao_id) = row[1] else {
  505. return Err(Error::ParseFailed("[get_dao_proposals] DAO ID parsing failed"))
  506. };
  507. let Ok(dao_id) = u64::try_from(dao_id) else {
  508. return Err(Error::ParseFailed("[get_dao_proposals] DAO ID parsing failed"))
  509. };
  510. assert!(dao_id == dao.id);
  511. let dao_bulla = dao.bulla();
  512. let Value::Blob(ref recipient_bytes) = row[2] else {
  513. return Err(Error::ParseFailed(
  514. "[get_dao_proposals] Recipient bytes bytes parsing failed",
  515. ))
  516. };
  517. let recipient = deserialize(recipient_bytes)?;
  518. let Value::Blob(ref amount_bytes) = row[3] else {
  519. return Err(Error::ParseFailed("[get_dao_proposals] Amount bytes parsing failed"))
  520. };
  521. let amount = deserialize(amount_bytes)?;
  522. let Value::Blob(ref token_id_bytes) = row[4] else {
  523. return Err(Error::ParseFailed("[get_dao_proposals] Token ID bytes parsing failed"))
  524. };
  525. let token_id = deserialize(token_id_bytes)?;
  526. let Value::Blob(ref bulla_blind_bytes) = row[5] else {
  527. return Err(Error::ParseFailed("[get_dao_proposals] Bulla blind bytes parsing failed"))
  528. };
  529. let bulla_blind = deserialize(bulla_blind_bytes)?;
  530. let Value::Blob(ref leaf_position_bytes) = row[6] else {
  531. return Err(Error::ParseFailed("[get_dao_proposals] Leaf position bytes parsing failed"))
  532. };
  533. let leaf_position = if leaf_position_bytes.is_empty() {
  534. None
  535. } else {
  536. Some(deserialize(leaf_position_bytes)?)
  537. };
  538. let Value::Blob(ref money_snapshot_tree_bytes) = row[7] else {
  539. return Err(Error::ParseFailed(
  540. "[get_dao_proposals] Money snapshot tree bytes parsing failed",
  541. ))
  542. };
  543. let money_snapshot_tree = if money_snapshot_tree_bytes.is_empty() {
  544. None
  545. } else {
  546. Some(deserialize(money_snapshot_tree_bytes)?)
  547. };
  548. let Value::Blob(ref tx_hash_bytes) = row[8] else {
  549. return Err(Error::ParseFailed(
  550. "[get_dao_proposals] Transaction hash bytes parsing failed",
  551. ))
  552. };
  553. let tx_hash =
  554. if tx_hash_bytes.is_empty() { None } else { Some(deserialize(tx_hash_bytes)?) };
  555. let Value::Integer(call_index) = row[9] else {
  556. return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed"))
  557. };
  558. let Ok(call_index) = u32::try_from(call_index) else {
  559. return Err(Error::ParseFailed("[get_dao_proposals] Call index parsing failed"))
  560. };
  561. let call_index = Some(call_index);
  562. let Value::Blob(ref vote_id_bytes) = row[10] else {
  563. return Err(Error::ParseFailed("[get_dao_proposals] Vote ID bytes parsing failed"))
  564. };
  565. let vote_id =
  566. if vote_id_bytes.is_empty() { None } else { Some(deserialize(vote_id_bytes)?) };
  567. Ok(DaoProposal {
  568. id,
  569. dao_bulla,
  570. recipient,
  571. amount,
  572. token_id,
  573. bulla_blind,
  574. leaf_position,
  575. money_snapshot_tree,
  576. tx_hash,
  577. call_index,
  578. vote_id,
  579. })
  580. }
  581. /// Fetch all known DAO proposals from the wallet given a DAO ID.
  582. pub async fn get_dao_proposals(&self, dao_id: u64) -> Result<Vec<DaoProposal>> {
  583. let daos = self.get_daos().await?;
  584. let Some(dao) = daos.get(dao_id as usize - 1) else {
  585. return Err(Error::RusqliteError(format!(
  586. "[get_dao_proposals] DAO with ID {dao_id} not found in wallet"
  587. )))
  588. };
  589. let rows = match self
  590. .wallet
  591. .query_multiple(
  592. &DAO_PROPOSALS_TABLE,
  593. &[],
  594. convert_named_params! {(DAO_PROPOSALS_COL_DAO_ID, dao_id)},
  595. )
  596. .await
  597. {
  598. Ok(r) => r,
  599. Err(e) => {
  600. return Err(Error::RusqliteError(format!(
  601. "[get_dao_proposals] Proposals retrieval failed: {e:?}"
  602. )))
  603. }
  604. };
  605. let mut proposals = Vec::with_capacity(rows.len());
  606. for row in rows {
  607. let proposal = self.parse_dao_proposal(dao, &row)?;
  608. proposals.push(proposal);
  609. }
  610. // Here we sort the vec by ID. The SQL SELECT statement does not guarantee
  611. // this, so just do it here.
  612. proposals.sort_by(|a, b| a.id.cmp(&b.id));
  613. Ok(proposals)
  614. }
  615. /// Append data related to DAO contract transactions into the wallet database.
  616. /// Optionally, if `confirm` is true, also append the data in the Merkle trees, etc.
  617. pub async fn apply_tx_dao_data(&self, tx: &Transaction, confirm: bool) -> Result<()> {
  618. let cid = *DAO_CONTRACT_ID;
  619. let mut daos = self.get_daos().await?;
  620. let mut daos_to_confirm = vec![];
  621. let (mut daos_tree, mut proposals_tree) = self.get_dao_trees().await?;
  622. // DAOs that have been minted
  623. let mut new_dao_bullas: Vec<(DaoBulla, Option<blake3::Hash>, u32)> = vec![];
  624. // DAO proposals that have been minted
  625. let mut new_dao_proposals: Vec<(
  626. DaoProposeParams,
  627. Option<MerkleTree>,
  628. Option<blake3::Hash>,
  629. u32,
  630. )> = vec![];
  631. let mut our_proposals: Vec<DaoProposal> = vec![];
  632. // DAO votes that have been seen
  633. let mut new_dao_votes: Vec<(DaoVoteParams, Option<blake3::Hash>, u32)> = vec![];
  634. let mut dao_votes: Vec<DaoVote> = vec![];
  635. // Run through the transaction and see what we got:
  636. for (i, call) in tx.calls.iter().enumerate() {
  637. if call.data.contract_id == cid && call.data.data[0] == DaoFunction::Mint as u8 {
  638. eprintln!("Found Dao::Mint in call {i}");
  639. let params: DaoMintParams = deserialize(&call.data.data[1..])?;
  640. let tx_hash = if confirm { Some(blake3::hash(&serialize(tx))) } else { None };
  641. new_dao_bullas.push((params.dao_bulla, tx_hash, i as u32));
  642. continue
  643. }
  644. if call.data.contract_id == cid && call.data.data[0] == DaoFunction::Propose as u8 {
  645. eprintln!("Found Dao::Propose in call {i}");
  646. let params: DaoProposeParams = deserialize(&call.data.data[1..])?;
  647. let tx_hash = if confirm { Some(blake3::hash(&serialize(tx))) } else { None };
  648. // We need to clone the tree here for reproducing the snapshot Merkle root
  649. let money_tree = if confirm { Some(self.get_money_tree().await?) } else { None };
  650. new_dao_proposals.push((params, money_tree, tx_hash, i as u32));
  651. continue
  652. }
  653. if call.data.contract_id == cid && call.data.data[0] == DaoFunction::Vote as u8 {
  654. eprintln!("Found Dao::Vote in call {i}");
  655. let params: DaoVoteParams = deserialize(&call.data.data[1..])?;
  656. let tx_hash = if confirm { Some(blake3::hash(&serialize(tx))) } else { None };
  657. new_dao_votes.push((params, tx_hash, i as u32));
  658. continue
  659. }
  660. if call.data.contract_id == cid && call.data.data[0] == DaoFunction::Exec as u8 {
  661. // This seems to not need any special action
  662. eprintln!("Found Dao::Exec in call {i}");
  663. continue
  664. }
  665. }
  666. // This code should only be executed when finalized blocks are being scanned.
  667. // Here we write the tx metadata, and actually do Merkle tree appends so we
  668. // have to make sure it's the same for everyone.
  669. if confirm {
  670. for new_bulla in new_dao_bullas {
  671. daos_tree.append(MerkleNode::from(new_bulla.0.inner()));
  672. for dao in daos.iter_mut() {
  673. if dao.bulla() == new_bulla.0 {
  674. eprintln!(
  675. "Found minted DAO {}, noting down for wallet update",
  676. new_bulla.0
  677. );
  678. // We have this DAO imported in our wallet. Add the metadata:
  679. dao.leaf_position = daos_tree.mark();
  680. dao.tx_hash = new_bulla.1;
  681. dao.call_index = Some(new_bulla.2);
  682. daos_to_confirm.push(dao.clone());
  683. }
  684. }
  685. }
  686. for proposal in new_dao_proposals {
  687. proposals_tree.append(MerkleNode::from(proposal.0.proposal_bulla.inner()));
  688. // If we're able to decrypt this note, that's the way to link it
  689. // to a specific DAO.
  690. for dao in &daos {
  691. if let Ok(note) = proposal.0.note.decrypt::<DaoProposeNote>(&dao.secret_key) {
  692. // We managed to decrypt it. Let's place this in a proper
  693. // DaoProposal object. We assume we can just increment the
  694. // ID by looking at how many proposals we already have.
  695. // We also assume we don't mantain duplicate DAOs in the
  696. // wallet.
  697. eprintln!("Managed to decrypt DAO proposal note");
  698. let daos_proposals = self.get_dao_proposals(dao.id).await?;
  699. let our_prop = DaoProposal {
  700. // This ID stuff is flaky.
  701. id: daos_proposals.len() as u64 + our_proposals.len() as u64 + 1,
  702. dao_bulla: dao.bulla(),
  703. recipient: note.proposal.dest,
  704. amount: note.proposal.amount,
  705. token_id: note.proposal.token_id,
  706. bulla_blind: note.proposal.blind,
  707. leaf_position: proposals_tree.mark(),
  708. money_snapshot_tree: proposal.1,
  709. tx_hash: proposal.2,
  710. call_index: Some(proposal.3),
  711. vote_id: None,
  712. };
  713. our_proposals.push(our_prop);
  714. break
  715. }
  716. }
  717. }
  718. for vote in new_dao_votes {
  719. for dao in &daos {
  720. // TODO: we shouldn't decrypt with all DAOs here
  721. let note = vote.0.note.decrypt(&dao.secret_key);
  722. eprintln!("Managed to decrypt DAO proposal vote note");
  723. let daos_proposals = self.get_dao_proposals(dao.id).await?;
  724. let mut proposal_id = None;
  725. for i in daos_proposals {
  726. if i.bulla() == vote.0.proposal_bulla.inner() {
  727. proposal_id = Some(i.id);
  728. break
  729. }
  730. }
  731. if proposal_id.is_none() {
  732. eprintln!("Warning: Decrypted DaoVoteNote but did not find proposal");
  733. break
  734. }
  735. let vote_option = fp_to_u64(note[0]).unwrap();
  736. assert!(vote_option == 0 || vote_option == 1);
  737. let vote_option = vote_option != 0;
  738. let yes_vote_blind = Blind(fp_mod_fv(note[1]));
  739. let all_vote_value = fp_to_u64(note[2]).unwrap();
  740. let all_vote_blind = Blind(fp_mod_fv(note[3]));
  741. let v = DaoVote {
  742. id: 0,
  743. proposal_id: proposal_id.unwrap(),
  744. vote_option,
  745. yes_vote_blind,
  746. all_vote_value,
  747. all_vote_blind,
  748. tx_hash: vote.1,
  749. call_index: Some(vote.2),
  750. };
  751. dao_votes.push(v);
  752. }
  753. }
  754. }
  755. if confirm {
  756. if let Err(e) = self.put_dao_trees(&daos_tree, &proposals_tree).await {
  757. return Err(Error::RusqliteError(format!(
  758. "[apply_tx_dao_data] Put DAO tree failed: {e:?}"
  759. )))
  760. }
  761. if let Err(e) = self.confirm_daos(&daos_to_confirm).await {
  762. return Err(Error::RusqliteError(format!(
  763. "[apply_tx_dao_data] Confirm DAOs failed: {e:?}"
  764. )))
  765. }
  766. self.put_dao_proposals(&our_proposals).await?;
  767. if let Err(e) = self.put_dao_votes(&dao_votes).await {
  768. return Err(Error::RusqliteError(format!(
  769. "[apply_tx_dao_data] Put DAO votes failed: {e:?}"
  770. )))
  771. }
  772. }
  773. Ok(())
  774. }
  775. /// Confirm already imported DAO metadata into the wallet.
  776. /// Here we just write the leaf position, tx hash, and call index.
  777. /// Panics if the fields are None.
  778. pub async fn confirm_daos(&self, daos: &[Dao]) -> WalletDbResult<()> {
  779. for dao in daos {
  780. let query = format!(
  781. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = {};",
  782. *DAO_DAOS_TABLE,
  783. DAO_DAOS_COL_LEAF_POSITION,
  784. DAO_DAOS_COL_TX_HASH,
  785. DAO_DAOS_COL_CALL_INDEX,
  786. DAO_DAOS_COL_DAO_ID,
  787. dao.id,
  788. );
  789. self.wallet
  790. .exec_sql(
  791. &query,
  792. rusqlite::params![
  793. serialize(&dao.leaf_position.unwrap()),
  794. serialize(&dao.tx_hash.unwrap()),
  795. dao.call_index.unwrap()
  796. ],
  797. )
  798. .await?;
  799. }
  800. Ok(())
  801. }
  802. /// Unconfirm imported DAOs by removing the leaf position, txid, and call index.
  803. pub async fn unconfirm_daos(&self, daos: &[Dao]) -> WalletDbResult<()> {
  804. for dao in daos {
  805. let query = format!(
  806. "UPDATE {} SET {} = ?1, {} = ?2, {} = ?3 WHERE {} = {};",
  807. *DAO_DAOS_TABLE,
  808. DAO_DAOS_COL_LEAF_POSITION,
  809. DAO_DAOS_COL_TX_HASH,
  810. DAO_DAOS_COL_CALL_INDEX,
  811. DAO_DAOS_COL_DAO_ID,
  812. dao.id,
  813. );
  814. self.wallet
  815. .exec_sql(&query, rusqlite::params![None::<Vec<u8>>, None::<Vec<u8>>, None::<u64>,])
  816. .await?;
  817. }
  818. Ok(())
  819. }
  820. /// Import given DAO proposals into the wallet.
  821. pub async fn put_dao_proposals(&self, proposals: &[DaoProposal]) -> Result<()> {
  822. let daos = self.get_daos().await?;
  823. for proposal in proposals {
  824. let Some(dao) = daos.iter().find(|x| x.bulla() == proposal.dao_bulla) else {
  825. return Err(Error::RusqliteError(
  826. "[put_dao_proposals] Couldn't find respective DAO".to_string(),
  827. ))
  828. };
  829. let query = format!(
  830. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9);",
  831. *DAO_PROPOSALS_TABLE,
  832. DAO_PROPOSALS_COL_DAO_ID,
  833. DAO_PROPOSALS_COL_RECV_PUBLIC,
  834. DAO_PROPOSALS_COL_AMOUNT,
  835. DAO_PROPOSALS_COL_SENDCOIN_TOKEN_ID,
  836. DAO_PROPOSALS_COL_BULLA_BLIND,
  837. DAO_PROPOSALS_COL_LEAF_POSITION,
  838. DAO_PROPOSALS_COL_MONEY_SNAPSHOT_TREE,
  839. DAO_PROPOSALS_COL_TX_HASH,
  840. DAO_PROPOSALS_COL_CALL_INDEX,
  841. );
  842. if let Err(e) = self
  843. .wallet
  844. .exec_sql(
  845. &query,
  846. rusqlite::params![
  847. dao.id,
  848. serialize(&proposal.recipient),
  849. serialize(&proposal.amount),
  850. serialize(&proposal.token_id),
  851. serialize(&proposal.bulla_blind),
  852. serialize(&proposal.leaf_position.unwrap()),
  853. serialize(&proposal.money_snapshot_tree.clone().unwrap()),
  854. serialize(&proposal.tx_hash.unwrap()),
  855. proposal.call_index,
  856. ],
  857. )
  858. .await
  859. {
  860. return Err(Error::RusqliteError(format!(
  861. "[put_dao_proposals] Proposal insert failed: {e:?}"
  862. )))
  863. };
  864. }
  865. Ok(())
  866. }
  867. /// Import given DAO votes into the wallet.
  868. pub async fn put_dao_votes(&self, votes: &[DaoVote]) -> WalletDbResult<()> {
  869. for vote in votes {
  870. eprintln!("Importing DAO vote into wallet");
  871. let query = format!(
  872. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);",
  873. *DAO_VOTES_TABLE,
  874. DAO_VOTES_COL_PROPOSAL_ID,
  875. DAO_VOTES_COL_VOTE_OPTION,
  876. DAO_VOTES_COL_YES_VOTE_BLIND,
  877. DAO_VOTES_COL_ALL_VOTE_VALUE,
  878. DAO_VOTES_COL_ALL_VOTE_BLIND,
  879. DAO_VOTES_COL_TX_HASH,
  880. DAO_VOTES_COL_CALL_INDEX,
  881. );
  882. self.wallet
  883. .exec_sql(
  884. &query,
  885. rusqlite::params![
  886. vote.proposal_id,
  887. vote.vote_option as u64,
  888. serialize(&vote.yes_vote_blind),
  889. serialize(&vote.all_vote_value),
  890. serialize(&vote.all_vote_blind),
  891. serialize(&vote.tx_hash.unwrap()),
  892. vote.call_index.unwrap(),
  893. ],
  894. )
  895. .await?;
  896. eprintln!("DAO vote added to wallet");
  897. }
  898. Ok(())
  899. }
  900. /// Reset the DAO Merkle trees in the wallet.
  901. pub async fn reset_dao_trees(&self) -> WalletDbResult<()> {
  902. eprintln!("Resetting DAO Merkle trees");
  903. let tree = MerkleTree::new(100);
  904. self.put_dao_trees(&tree, &tree).await?;
  905. eprintln!("Successfully reset DAO Merkle trees");
  906. Ok(())
  907. }
  908. /// Reset confirmed DAOs in the wallet.
  909. pub async fn reset_daos(&self) -> WalletDbResult<()> {
  910. eprintln!("Resetting DAO confirmations");
  911. let daos = match self.get_daos().await {
  912. Ok(d) => d,
  913. Err(e) => {
  914. eprintln!("[reset_daos] DAOs retrieval failed: {e:?}");
  915. return Err(WalletDbError::GenericError);
  916. }
  917. };
  918. self.unconfirm_daos(&daos).await?;
  919. eprintln!("Successfully unconfirmed DAOs");
  920. Ok(())
  921. }
  922. /// Reset all DAO proposals in the wallet.
  923. pub async fn reset_dao_proposals(&self) -> WalletDbResult<()> {
  924. eprintln!("Resetting DAO proposals");
  925. let query = format!("DELETE FROM {};", *DAO_PROPOSALS_TABLE);
  926. self.wallet.exec_sql(&query, &[]).await
  927. }
  928. /// Reset all DAO votes in the wallet.
  929. pub async fn reset_dao_votes(&self) -> WalletDbResult<()> {
  930. eprintln!("Resetting DAO votes");
  931. let query = format!("DELETE FROM {};", *DAO_VOTES_TABLE);
  932. self.wallet.exec_sql(&query, &[]).await
  933. }
  934. /// Import given DAO params into the wallet with a given name.
  935. pub async fn import_dao(&self, dao_name: String, dao_params: DaoParams) -> Result<()> {
  936. // First let's check if we've imported this DAO with the given name before.
  937. // TODO: instead of getting all DAOs and filtering in rust,
  938. // we can use the DB api directly to query for the record
  939. // and return the error if it exists
  940. let daos = self.get_daos().await?;
  941. if daos.iter().any(|x| x.name == dao_name) {
  942. return Err(Error::RusqliteError(
  943. "[import_dao] This DAO has already been imported".to_string(),
  944. ))
  945. }
  946. eprintln!("Importing \"{dao_name}\" DAO into the wallet");
  947. let query = format!(
  948. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
  949. *DAO_DAOS_TABLE,
  950. DAO_DAOS_COL_NAME,
  951. DAO_DAOS_COL_PROPOSER_LIMIT,
  952. DAO_DAOS_COL_QUORUM,
  953. DAO_DAOS_COL_APPROVAL_RATIO_BASE,
  954. DAO_DAOS_COL_APPROVAL_RATIO_QUOT,
  955. DAO_DAOS_COL_GOV_TOKEN_ID,
  956. DAO_DAOS_COL_SECRET,
  957. DAO_DAOS_COL_BULLA_BLIND,
  958. );
  959. if let Err(e) = self
  960. .wallet
  961. .exec_sql(
  962. &query,
  963. rusqlite::params![
  964. dao_name,
  965. serialize(&dao_params.proposer_limit),
  966. serialize(&dao_params.quorum),
  967. dao_params.approval_ratio_base,
  968. dao_params.approval_ratio_quot,
  969. serialize(&dao_params.gov_token_id),
  970. serialize(&dao_params.secret_key),
  971. serialize(&dao_params.bulla_blind),
  972. ],
  973. )
  974. .await
  975. {
  976. return Err(Error::RusqliteError(format!("[import_dao] DAO insert failed: {e:?}")))
  977. };
  978. Ok(())
  979. }
  980. /// Retrieve DAO ID using provided alias filter.
  981. pub async fn get_dao_id_by_alias(&self, alias_filter: &str) -> Result<u64> {
  982. let row = match self
  983. .wallet
  984. .query_single(
  985. &DAO_DAOS_TABLE,
  986. &[DAO_DAOS_COL_DAO_ID],
  987. convert_named_params! {(DAO_DAOS_COL_NAME, alias_filter)},
  988. )
  989. .await
  990. {
  991. Ok(r) => r,
  992. Err(e) => {
  993. return Err(Error::RusqliteError(format!(
  994. "[get_dao_id_by_alias] DAO retrieval failed: {e:?}"
  995. )))
  996. }
  997. };
  998. let Value::Integer(dao_id) = row[0] else {
  999. return Err(Error::ParseFailed("[get_dao_id_by_alias] Key ID parsing failed"))
  1000. };
  1001. let Ok(dao_id) = u64::try_from(dao_id) else {
  1002. return Err(Error::ParseFailed("[get_dao_id_by_alias] Key ID parsing failed"))
  1003. };
  1004. Ok(dao_id)
  1005. }
  1006. /// Convenience function. Interprets the alias either as the DAO alias or its ID.
  1007. pub async fn get_dao_id(&self, alias: &str) -> Result<u64> {
  1008. if let Ok(id) = self.get_dao_id_by_alias(alias).await {
  1009. return Ok(id)
  1010. }
  1011. Ok(alias.parse()?)
  1012. }
  1013. /// Fetch a DAO given a numeric ID.
  1014. pub async fn get_dao_by_id(&self, dao_id: u64) -> Result<Dao> {
  1015. // TODO: instead of getting all DAOs and filtering in rust,
  1016. // we can use the DB api directly to query for the record
  1017. // and then parse it
  1018. let daos = self.get_daos().await?;
  1019. let Some(dao) = daos.iter().find(|x| x.id == dao_id) else {
  1020. return Err(Error::RusqliteError("[get_dao_by_id] DAO not found in wallet".to_string()))
  1021. };
  1022. Ok(dao.clone())
  1023. }
  1024. /// List DAO(s) imported in the wallet. If an ID is given, just print the
  1025. /// metadata for that specific one, if found.
  1026. pub async fn dao_list(&self, dao_id: Option<u64>) -> Result<()> {
  1027. if let Some(dao_id) = dao_id {
  1028. return self.dao_list_single(dao_id).await
  1029. }
  1030. let daos = self.get_daos().await?;
  1031. for dao in daos {
  1032. eprintln!("[{}] {}", dao.id, dao.name);
  1033. }
  1034. Ok(())
  1035. }
  1036. /// Retrieve DAO for provided ID and print its metadata.
  1037. async fn dao_list_single(&self, dao_id: u64) -> Result<()> {
  1038. let dao = self.get_dao_by_id(dao_id).await?;
  1039. eprintln!("{dao}");
  1040. Ok(())
  1041. }
  1042. /// Fetch known unspent balances from the wallet for the given DAO ID
  1043. pub async fn dao_balance(&self, dao_id: u64) -> Result<HashMap<String, u64>> {
  1044. // TODO: instead of getting all DAOs and filtering in rust,
  1045. // we can use the DB api directly to query for the record
  1046. // and then parse it
  1047. let daos = self.get_daos().await?;
  1048. let Some(dao) = daos.get(dao_id as usize - 1) else {
  1049. return Err(Error::RusqliteError(format!("DAO with ID {dao_id} not found in wallet")))
  1050. };
  1051. let dao_spend_hook =
  1052. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1053. .to_func_id();
  1054. let mut coins = self.get_coins(false).await?;
  1055. coins.retain(|x| x.0.note.spend_hook == dao_spend_hook);
  1056. coins.retain(|x| x.0.note.user_data == dao.bulla().inner());
  1057. // Fill this map with balances
  1058. let mut balmap: HashMap<String, u64> = HashMap::new();
  1059. for coin in coins {
  1060. let mut value = coin.0.note.value;
  1061. if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
  1062. value += prev;
  1063. }
  1064. balmap.insert(coin.0.note.token_id.to_string(), value);
  1065. }
  1066. Ok(balmap)
  1067. }
  1068. /// Fetch a DAO proposal by its ID
  1069. pub async fn get_dao_proposal_by_id(&self, proposal_id: u64) -> Result<DaoProposal> {
  1070. // Grab the proposal record
  1071. let row = match self
  1072. .wallet
  1073. .query_single(
  1074. &DAO_PROPOSALS_TABLE,
  1075. &[],
  1076. convert_named_params! {(DAO_PROPOSALS_COL_PROPOSAL_ID, proposal_id)},
  1077. )
  1078. .await
  1079. {
  1080. Ok(r) => r,
  1081. Err(e) => {
  1082. return Err(Error::RusqliteError(format!(
  1083. "[get_dao_proposal_by_id] DAO proposal retrieval failed: {e:?}"
  1084. )))
  1085. }
  1086. };
  1087. // Parse DAO ID to grab the DAO record
  1088. let Value::Integer(dao_id) = row[1] else {
  1089. return Err(Error::ParseFailed("[get_dao_proposal_by_id] DAO ID parsing failed"))
  1090. };
  1091. let Ok(dao_id) = u64::try_from(dao_id) else {
  1092. return Err(Error::ParseFailed("[get_dao_proposal_by_id] DAO ID parsing failed"))
  1093. };
  1094. let dao = self.get_dao_by_id(dao_id).await?;
  1095. // Parse rest of the record
  1096. self.parse_dao_proposal(&dao, &row)
  1097. }
  1098. // Fetch all known DAO proposal votes from the wallet given a proposal ID
  1099. pub async fn get_dao_proposal_votes(&self, proposal_id: u64) -> Result<Vec<DaoVote>> {
  1100. let rows = match self
  1101. .wallet
  1102. .query_multiple(
  1103. &DAO_VOTES_TABLE,
  1104. &[],
  1105. convert_named_params! {(DAO_VOTES_COL_PROPOSAL_ID, proposal_id)},
  1106. )
  1107. .await
  1108. {
  1109. Ok(r) => r,
  1110. Err(e) => {
  1111. return Err(Error::RusqliteError(format!(
  1112. "[get_dao_proposal_votes] Votes retrieval failed: {e:?}"
  1113. )))
  1114. }
  1115. };
  1116. let mut votes = Vec::with_capacity(rows.len());
  1117. for row in rows {
  1118. let Value::Integer(id) = row[0] else {
  1119. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1120. };
  1121. let Ok(id) = u64::try_from(id) else {
  1122. return Err(Error::ParseFailed("[get_dao_proposal_votes] ID parsing failed"))
  1123. };
  1124. let Value::Integer(proposal_id) = row[1] else {
  1125. return Err(Error::ParseFailed(
  1126. "[get_dao_proposal_votes] Proposal ID parsing failed",
  1127. ))
  1128. };
  1129. let Ok(proposal_id) = u64::try_from(proposal_id) else {
  1130. return Err(Error::ParseFailed(
  1131. "[get_dao_proposal_votes] Proposal ID parsing failed",
  1132. ))
  1133. };
  1134. let Value::Integer(vote_option) = row[2] else {
  1135. return Err(Error::ParseFailed(
  1136. "[get_dao_proposal_votes] Vote option parsing failed",
  1137. ))
  1138. };
  1139. let Ok(vote_option) = u32::try_from(vote_option) else {
  1140. return Err(Error::ParseFailed(
  1141. "[get_dao_proposal_votes] Vote option parsing failed",
  1142. ))
  1143. };
  1144. let vote_option = vote_option != 0;
  1145. let Value::Blob(ref yes_vote_blind_bytes) = row[3] else {
  1146. return Err(Error::ParseFailed(
  1147. "[get_dao_proposal_votes] Yes vote blind bytes parsing failed",
  1148. ))
  1149. };
  1150. let yes_vote_blind = deserialize(yes_vote_blind_bytes)?;
  1151. let Value::Blob(ref all_vote_value_bytes) = row[4] else {
  1152. return Err(Error::ParseFailed(
  1153. "[get_dao_proposal_votes] All vote value bytes parsing failed",
  1154. ))
  1155. };
  1156. let all_vote_value = deserialize(all_vote_value_bytes)?;
  1157. let Value::Blob(ref all_vote_blind_bytes) = row[5] else {
  1158. return Err(Error::ParseFailed(
  1159. "[get_dao_proposal_votes] All vote blind bytes parsing failed",
  1160. ))
  1161. };
  1162. let all_vote_blind = deserialize(all_vote_blind_bytes)?;
  1163. let Value::Blob(ref tx_hash_bytes) = row[6] else {
  1164. return Err(Error::ParseFailed(
  1165. "[get_dao_proposal_votes] Transaction hash bytes parsing failed",
  1166. ))
  1167. };
  1168. let tx_hash =
  1169. if tx_hash_bytes.is_empty() { None } else { Some(deserialize(tx_hash_bytes)?) };
  1170. let Value::Integer(call_index) = row[7] else {
  1171. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1172. };
  1173. let Ok(call_index) = u32::try_from(call_index) else {
  1174. return Err(Error::ParseFailed("[get_dao_proposal_votes] Call index parsing failed"))
  1175. };
  1176. let call_index = Some(call_index);
  1177. let vote = DaoVote {
  1178. id,
  1179. proposal_id,
  1180. vote_option,
  1181. yes_vote_blind,
  1182. all_vote_value,
  1183. all_vote_blind,
  1184. tx_hash,
  1185. call_index,
  1186. };
  1187. votes.push(vote);
  1188. }
  1189. Ok(votes)
  1190. }
  1191. /// Mint a DAO on-chain
  1192. pub async fn dao_mint(&self, dao_id: u64) -> Result<Transaction> {
  1193. let dao = self.get_dao_by_id(dao_id).await?;
  1194. if dao.tx_hash.is_some() {
  1195. return Err(Error::Custom(
  1196. "[dao_mint] This DAO seems to have already been minted on-chain".to_string(),
  1197. ))
  1198. }
  1199. // TODO: Simplify this model struct import once
  1200. // we use the structs from contract everwhere
  1201. let dao_info = darkfi_dao_contract::model::Dao {
  1202. proposer_limit: dao.proposer_limit,
  1203. quorum: dao.quorum,
  1204. approval_ratio_base: dao.approval_ratio_base,
  1205. approval_ratio_quot: dao.approval_ratio_quot,
  1206. gov_token_id: dao.gov_token_id,
  1207. public_key: PublicKey::from_secret(dao.secret_key),
  1208. bulla_blind: dao.bulla_blind,
  1209. };
  1210. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1211. let Some(dao_mint_zkbin) = zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_MINT_NS)
  1212. else {
  1213. return Err(Error::RusqliteError("[dao_mint] DAO Mint circuit not found".to_string()))
  1214. };
  1215. let dao_mint_zkbin = ZkBinary::decode(&dao_mint_zkbin.1)?;
  1216. let dao_mint_circuit = ZkCircuit::new(empty_witnesses(&dao_mint_zkbin)?, &dao_mint_zkbin);
  1217. eprintln!("Creating DAO Mint proving key");
  1218. let dao_mint_pk = ProvingKey::build(dao_mint_zkbin.k, &dao_mint_circuit);
  1219. let (params, proofs) =
  1220. make_mint_call(&dao_info, &dao.secret_key, &dao_mint_zkbin, &dao_mint_pk)?;
  1221. let mut data = vec![DaoFunction::Mint as u8];
  1222. params.encode(&mut data)?;
  1223. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1224. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1225. let mut tx = tx_builder.build()?;
  1226. let sigs = tx.create_sigs(&mut OsRng, &[dao.secret_key])?;
  1227. tx.signatures = vec![sigs];
  1228. Ok(tx)
  1229. }
  1230. /// Create a DAO proposal
  1231. pub async fn dao_propose(
  1232. &self,
  1233. dao_id: u64,
  1234. _recipient: PublicKey,
  1235. amount: u64,
  1236. token_id: TokenId,
  1237. ) -> Result<Transaction> {
  1238. let Ok(dao) = self.get_dao_by_id(dao_id).await else {
  1239. return Err(Error::RusqliteError("[dao_propose] DAO not found in wallet".to_string()))
  1240. };
  1241. if dao.leaf_position.is_none() || dao.tx_hash.is_none() {
  1242. return Err(Error::Custom(
  1243. "[dao_propose] DAO seems to not have been deployed yet".to_string(),
  1244. ))
  1245. }
  1246. let bulla = dao.bulla();
  1247. let owncoins = self.get_coins(false).await?;
  1248. let dao_spend_hook =
  1249. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1250. .to_func_id();
  1251. let mut dao_owncoins: Vec<OwnCoin> = owncoins.iter().map(|x| x.0.clone()).collect();
  1252. dao_owncoins.retain(|x| {
  1253. x.note.token_id == token_id &&
  1254. x.note.spend_hook == dao_spend_hook &&
  1255. x.note.user_data == bulla.inner()
  1256. });
  1257. let mut gov_owncoins: Vec<OwnCoin> = owncoins.iter().map(|x| x.0.clone()).collect();
  1258. gov_owncoins.retain(|x| x.note.token_id == dao.gov_token_id);
  1259. if dao_owncoins.is_empty() {
  1260. return Err(Error::Custom(format!(
  1261. "[dao_propose] Did not find any {token_id} coins owned by this DAO"
  1262. )))
  1263. }
  1264. if gov_owncoins.is_empty() {
  1265. return Err(Error::Custom(format!(
  1266. "[dao_propose] Did not find any governance {} coins in wallet",
  1267. dao.gov_token_id
  1268. )))
  1269. }
  1270. if dao_owncoins.iter().map(|x| x.note.value).sum::<u64>() < amount {
  1271. return Err(Error::Custom(format!(
  1272. "[dao_propose] Not enough DAO balance for token ID: {}",
  1273. token_id
  1274. )))
  1275. }
  1276. if gov_owncoins.iter().map(|x| x.note.value).sum::<u64>() < dao.proposer_limit {
  1277. return Err(Error::Custom(format!(
  1278. "[dao_propose] Not enough gov token {} balance to propose",
  1279. dao.gov_token_id
  1280. )))
  1281. }
  1282. // FIXME: Here we're looking for a coin == proposer_limit but this shouldn't have to
  1283. // be the case {
  1284. let Some(gov_coin) = gov_owncoins.iter().find(|x| x.note.value == dao.proposer_limit)
  1285. else {
  1286. return Err(Error::Custom(format!(
  1287. "[dao_propose] Did not find a single gov coin of value {}",
  1288. dao.proposer_limit
  1289. )))
  1290. };
  1291. // }
  1292. // Lookup the zkas bins
  1293. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1294. let Some(propose_burn_zkbin) =
  1295. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_INPUT_NS)
  1296. else {
  1297. return Err(Error::Custom("[dao_propose] Propose Burn circuit not found".to_string()))
  1298. };
  1299. let Some(propose_main_zkbin) =
  1300. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_PROPOSE_MAIN_NS)
  1301. else {
  1302. return Err(Error::Custom("[dao_propose] Propose Main circuit not found".to_string()))
  1303. };
  1304. let propose_burn_zkbin = ZkBinary::decode(&propose_burn_zkbin.1)?;
  1305. let propose_main_zkbin = ZkBinary::decode(&propose_main_zkbin.1)?;
  1306. let propose_burn_circuit =
  1307. ZkCircuit::new(empty_witnesses(&propose_burn_zkbin)?, &propose_burn_zkbin);
  1308. let propose_main_circuit =
  1309. ZkCircuit::new(empty_witnesses(&propose_main_zkbin)?, &propose_main_zkbin);
  1310. eprintln!("Creating Propose Burn circuit proving key");
  1311. let propose_burn_pk = ProvingKey::build(propose_burn_zkbin.k, &propose_burn_circuit);
  1312. eprintln!("Creating Propose Main circuit proving key");
  1313. let propose_main_pk = ProvingKey::build(propose_main_zkbin.k, &propose_main_circuit);
  1314. // Now create the parameters for the proposal tx
  1315. let signature_secret = SecretKey::random(&mut OsRng);
  1316. // Get the Merkle path for the gov coin in the money tree
  1317. let money_merkle_tree = self.get_money_tree().await?;
  1318. let gov_coin_merkle_path = money_merkle_tree.witness(gov_coin.leaf_position, 0).unwrap();
  1319. // Fetch the daos Merkle tree
  1320. let (daos_tree, _) = self.get_dao_trees().await?;
  1321. let input = DaoProposeStakeInput {
  1322. secret: gov_coin.secret, // <-- TODO: Is this correct?
  1323. note: gov_coin.note.clone(),
  1324. leaf_position: gov_coin.leaf_position,
  1325. merkle_path: gov_coin_merkle_path,
  1326. signature_secret,
  1327. };
  1328. let (dao_merkle_path, dao_merkle_root) = {
  1329. let root = daos_tree.root(0).unwrap();
  1330. let leaf_pos = dao.leaf_position.unwrap();
  1331. let dao_merkle_path = daos_tree.witness(leaf_pos, 0).unwrap();
  1332. (dao_merkle_path, root)
  1333. };
  1334. // TODO:
  1335. /*
  1336. // Convert coin_params to actual coins
  1337. let mut proposal_coins = vec![];
  1338. for coin_params in proposal_coinattrs {
  1339. proposal_coins.push(coin_params.to_coin());
  1340. }
  1341. */
  1342. let proposal_data = vec![];
  1343. //proposal_coins.encode(&mut proposal_data).unwrap();
  1344. let auth_calls = vec![
  1345. DaoAuthCall {
  1346. contract_id: *DAO_CONTRACT_ID,
  1347. function_code: DaoFunction::AuthMoneyTransfer as u8,
  1348. auth_data: proposal_data,
  1349. },
  1350. DaoAuthCall {
  1351. contract_id: *MONEY_CONTRACT_ID,
  1352. function_code: MoneyFunction::TransferV1 as u8,
  1353. auth_data: vec![],
  1354. },
  1355. ];
  1356. // TODO: get current height to calculate day
  1357. // Also contract must check we don't mint a proposal that its creation day is
  1358. // less than current height
  1359. // TODO: Simplify this model struct import once
  1360. // we use the structs from contract everwhere
  1361. let proposal = darkfi_dao_contract::model::DaoProposal {
  1362. auth_calls,
  1363. creation_day: 0,
  1364. duration_days: 30,
  1365. user_data: pallas::Base::ZERO,
  1366. dao_bulla: dao.bulla(),
  1367. blind: Blind::random(&mut OsRng),
  1368. };
  1369. // TODO: Simplify this model struct import once
  1370. // we use the structs from contract everwhere
  1371. let daoinfo = darkfi_dao_contract::model::Dao {
  1372. proposer_limit: dao.proposer_limit,
  1373. quorum: dao.quorum,
  1374. approval_ratio_quot: dao.approval_ratio_quot,
  1375. approval_ratio_base: dao.approval_ratio_base,
  1376. gov_token_id: dao.gov_token_id,
  1377. public_key: PublicKey::from_secret(dao.secret_key),
  1378. bulla_blind: dao.bulla_blind,
  1379. };
  1380. let call = DaoProposeCall {
  1381. inputs: vec![input],
  1382. proposal,
  1383. dao: daoinfo,
  1384. dao_leaf_position: dao.leaf_position.unwrap(),
  1385. dao_merkle_path,
  1386. dao_merkle_root,
  1387. };
  1388. eprintln!("Creating ZK proofs...");
  1389. let (params, proofs) = call.make(
  1390. &propose_burn_zkbin,
  1391. &propose_burn_pk,
  1392. &propose_main_zkbin,
  1393. &propose_main_pk,
  1394. )?;
  1395. let mut data = vec![DaoFunction::Propose as u8];
  1396. params.encode(&mut data)?;
  1397. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1398. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1399. let mut tx = tx_builder.build()?;
  1400. let sigs = tx.create_sigs(&mut OsRng, &[signature_secret])?;
  1401. tx.signatures = vec![sigs];
  1402. Ok(tx)
  1403. }
  1404. /// Vote on a DAO proposal
  1405. pub async fn dao_vote(
  1406. &self,
  1407. dao_id: u64,
  1408. proposal_id: u64,
  1409. vote_option: bool,
  1410. weight: u64,
  1411. ) -> Result<Transaction> {
  1412. let dao = self.get_dao_by_id(dao_id).await?;
  1413. let proposals = self.get_dao_proposals(dao_id).await?;
  1414. let Some(proposal) = proposals.iter().find(|x| x.id == proposal_id) else {
  1415. return Err(Error::Custom("[dao_vote] Proposal ID not found".to_string()))
  1416. };
  1417. let money_tree = proposal.money_snapshot_tree.clone().unwrap();
  1418. let mut coins: Vec<OwnCoin> =
  1419. self.get_coins(false).await?.iter().map(|x| x.0.clone()).collect();
  1420. coins.retain(|x| x.note.token_id == dao.gov_token_id);
  1421. coins.retain(|x| x.note.spend_hook == FuncId::none());
  1422. if coins.iter().map(|x| x.note.value).sum::<u64>() < weight {
  1423. return Err(Error::Custom("[dao_vote] Not enough balance for vote weight".to_string()))
  1424. }
  1425. // TODO: The spent coins need to either be marked as spent here, and/or on scan
  1426. let mut spent_value = 0;
  1427. let mut spent_coins = vec![];
  1428. let mut inputs = vec![];
  1429. let mut input_secrets = vec![];
  1430. // FIXME: We don't take back any change so it's possible to vote with > requested weight.
  1431. for coin in coins {
  1432. if spent_value >= weight {
  1433. break
  1434. }
  1435. spent_value += coin.note.value;
  1436. spent_coins.push(coin.clone());
  1437. let signature_secret = SecretKey::random(&mut OsRng);
  1438. input_secrets.push(signature_secret);
  1439. let leaf_position = coin.leaf_position;
  1440. let merkle_path = money_tree.witness(coin.leaf_position, 0).unwrap();
  1441. let input = DaoVoteInput {
  1442. secret: coin.secret,
  1443. note: coin.note.clone(),
  1444. leaf_position,
  1445. merkle_path,
  1446. signature_secret,
  1447. };
  1448. inputs.push(input);
  1449. }
  1450. // We use the DAO secret to encrypt the vote.
  1451. let dao_keypair = Keypair::new(dao.secret_key);
  1452. // TODO: Fix this
  1453. // TODO: Simplify this model struct import once
  1454. // we use the structs from contract everwhere
  1455. let proposal = darkfi_dao_contract::model::DaoProposal {
  1456. auth_calls: vec![],
  1457. creation_day: 0,
  1458. duration_days: 30,
  1459. user_data: pallas::Base::ZERO,
  1460. dao_bulla: dao.bulla(),
  1461. blind: Blind::random(&mut OsRng),
  1462. };
  1463. // TODO: Simplify this model struct import once
  1464. // we use the structs from contract everwhere
  1465. let dao_info = darkfi_dao_contract::model::Dao {
  1466. proposer_limit: dao.proposer_limit,
  1467. quorum: dao.quorum,
  1468. approval_ratio_quot: dao.approval_ratio_quot,
  1469. approval_ratio_base: dao.approval_ratio_base,
  1470. gov_token_id: dao.gov_token_id,
  1471. public_key: PublicKey::from_secret(dao.secret_key),
  1472. bulla_blind: dao.bulla_blind,
  1473. };
  1474. // TODO: get current height to calculate day
  1475. let call = DaoVoteCall {
  1476. inputs,
  1477. vote_option,
  1478. current_day: 0,
  1479. dao_keypair,
  1480. proposal,
  1481. dao: dao_info,
  1482. };
  1483. let zkas_bins = self.lookup_zkas(&DAO_CONTRACT_ID).await?;
  1484. let Some(dao_vote_burn_zkbin) =
  1485. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_INPUT_NS)
  1486. else {
  1487. return Err(Error::Custom("[dao_vote] DAO Vote Burn circuit not found".to_string()))
  1488. };
  1489. let Some(dao_vote_main_zkbin) =
  1490. zkas_bins.iter().find(|x| x.0 == DAO_CONTRACT_ZKAS_DAO_VOTE_MAIN_NS)
  1491. else {
  1492. return Err(Error::Custom("[dao_vote] DAO Vote Main circuit not found".to_string()))
  1493. };
  1494. let dao_vote_burn_zkbin = ZkBinary::decode(&dao_vote_burn_zkbin.1)?;
  1495. let dao_vote_main_zkbin = ZkBinary::decode(&dao_vote_main_zkbin.1)?;
  1496. let dao_vote_burn_circuit =
  1497. ZkCircuit::new(empty_witnesses(&dao_vote_burn_zkbin)?, &dao_vote_burn_zkbin);
  1498. let dao_vote_main_circuit =
  1499. ZkCircuit::new(empty_witnesses(&dao_vote_main_zkbin)?, &dao_vote_main_zkbin);
  1500. eprintln!("Creating DAO Vote Burn proving key");
  1501. let dao_vote_burn_pk = ProvingKey::build(dao_vote_burn_zkbin.k, &dao_vote_burn_circuit);
  1502. eprintln!("Creating DAO Vote Main proving key");
  1503. let dao_vote_main_pk = ProvingKey::build(dao_vote_main_zkbin.k, &dao_vote_main_circuit);
  1504. let (params, proofs) = call.make(
  1505. &dao_vote_burn_zkbin,
  1506. &dao_vote_burn_pk,
  1507. &dao_vote_main_zkbin,
  1508. &dao_vote_main_pk,
  1509. )?;
  1510. let mut data = vec![DaoFunction::Vote as u8];
  1511. params.encode(&mut data)?;
  1512. let call = ContractCall { contract_id: *DAO_CONTRACT_ID, data };
  1513. let mut tx_builder = TransactionBuilder::new(ContractCallLeaf { call, proofs }, vec![])?;
  1514. let mut tx = tx_builder.build()?;
  1515. let sigs = tx.create_sigs(&mut OsRng, &input_secrets)?;
  1516. tx.signatures = vec![sigs];
  1517. Ok(tx)
  1518. }
  1519. /// Import given DAO votes into the wallet
  1520. /// This function is really bad but I'm also really tired and annoyed.
  1521. pub async fn dao_exec(&self, _dao: Dao, _proposal: DaoProposal) -> Result<Transaction> {
  1522. // TODO
  1523. unimplemented!()
  1524. }
  1525. }