validate.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. use std::any::{Any, TypeId};
  2. use darkfi_sdk::crypto::{MerkleNode, Nullifier};
  3. use darkfi_serial::{Encodable, SerialDecodable, SerialEncodable};
  4. use log::error;
  5. use pasta_curves::{
  6. arithmetic::CurveAffine,
  7. group::{Curve, Group},
  8. pallas,
  9. };
  10. use darkfi::{
  11. crypto::{keypair::PublicKey, types::DrkCircuitField},
  12. Error as DarkFiError,
  13. };
  14. use crate::{
  15. contract::{
  16. dao_contract, dao_contract::State as DaoState, money_contract,
  17. money_contract::state::State as MoneyState,
  18. },
  19. note::EncryptedNote2,
  20. util::{CallDataBase, StateRegistry, Transaction, UpdateBase},
  21. };
  22. #[derive(Debug, Clone, thiserror::Error)]
  23. pub enum Error {
  24. #[error("Invalid proposal")]
  25. InvalidProposal,
  26. #[error("Voting with already spent coinage")]
  27. SpentCoin,
  28. #[error("Double voting")]
  29. DoubleVote,
  30. #[error("Invalid input merkle root")]
  31. InvalidInputMerkleRoot,
  32. #[error("DarkFi error: {0}")]
  33. DarkFiError(String),
  34. }
  35. type Result<T> = std::result::Result<T, Error>;
  36. impl From<DarkFiError> for Error {
  37. fn from(err: DarkFiError) -> Self {
  38. Self::DarkFiError(err.to_string())
  39. }
  40. }
  41. #[derive(Clone, SerialEncodable, SerialDecodable)]
  42. pub struct CallData {
  43. pub header: Header,
  44. pub inputs: Vec<Input>,
  45. }
  46. impl CallDataBase for CallData {
  47. fn zk_public_values(&self) -> Vec<(String, Vec<DrkCircuitField>)> {
  48. let mut zk_publics = Vec::new();
  49. let mut all_votes_commit = pallas::Point::identity();
  50. assert!(!self.inputs.is_empty(), "inputs length cannot be zero");
  51. for input in &self.inputs {
  52. all_votes_commit += input.vote_commit;
  53. let value_coords = input.vote_commit.to_affine().coordinates().unwrap();
  54. let sigpub_coords = input.signature_public.0.to_affine().coordinates().unwrap();
  55. zk_publics.push((
  56. "dao-vote-burn".to_string(),
  57. vec![
  58. input.nullifier.inner(),
  59. *value_coords.x(),
  60. *value_coords.y(),
  61. self.header.token_commit,
  62. input.merkle_root.inner(),
  63. *sigpub_coords.x(),
  64. *sigpub_coords.y(),
  65. ],
  66. ));
  67. }
  68. let yes_vote_commit_coords = self.header.yes_vote_commit.to_affine().coordinates().unwrap();
  69. let vote_commit_coords = all_votes_commit.to_affine().coordinates().unwrap();
  70. zk_publics.push((
  71. "dao-vote-main".to_string(),
  72. vec![
  73. self.header.token_commit,
  74. self.header.proposal_bulla,
  75. *yes_vote_commit_coords.x(),
  76. *yes_vote_commit_coords.y(),
  77. *vote_commit_coords.x(),
  78. *vote_commit_coords.y(),
  79. ],
  80. ));
  81. zk_publics
  82. }
  83. fn as_any(&self) -> &dyn Any {
  84. self
  85. }
  86. fn signature_public_keys(&self) -> Vec<PublicKey> {
  87. let mut signature_public_keys = vec![];
  88. for input in self.inputs.clone() {
  89. signature_public_keys.push(input.signature_public);
  90. }
  91. signature_public_keys
  92. }
  93. fn encode_bytes(
  94. &self,
  95. mut writer: &mut dyn std::io::Write,
  96. ) -> core::result::Result<usize, std::io::Error> {
  97. self.encode(&mut writer)
  98. }
  99. }
  100. #[derive(Clone, SerialEncodable, SerialDecodable)]
  101. pub struct Header {
  102. pub token_commit: pallas::Base,
  103. pub proposal_bulla: pallas::Base,
  104. pub yes_vote_commit: pallas::Point,
  105. pub enc_note: EncryptedNote2,
  106. }
  107. #[derive(Clone, SerialEncodable, SerialDecodable)]
  108. pub struct Input {
  109. pub nullifier: Nullifier,
  110. pub vote_commit: pallas::Point,
  111. pub merkle_root: MerkleNode,
  112. pub signature_public: PublicKey,
  113. }
  114. pub fn state_transition(
  115. states: &StateRegistry,
  116. func_call_index: usize,
  117. parent_tx: &Transaction,
  118. ) -> Result<Box<dyn UpdateBase + Send>> {
  119. let func_call = &parent_tx.func_calls[func_call_index];
  120. let call_data = func_call.call_data.as_any();
  121. assert_eq!((*call_data).type_id(), TypeId::of::<CallData>());
  122. let call_data = call_data.downcast_ref::<CallData>();
  123. // This will be inside wasm so unwrap is fine.
  124. let call_data = call_data.unwrap();
  125. let dao_state = states.lookup::<DaoState>(*dao_contract::CONTRACT_ID).unwrap();
  126. // Check proposal_bulla exists
  127. let votes_info = dao_state.lookup_proposal_votes(call_data.header.proposal_bulla);
  128. if votes_info.is_none() {
  129. return Err(Error::InvalidProposal)
  130. }
  131. let votes_info = votes_info.unwrap();
  132. // Check the merkle roots for the input coins are valid
  133. let mut vote_nulls = Vec::new();
  134. let mut all_vote_commit = pallas::Point::identity();
  135. for input in &call_data.inputs {
  136. let money_state = states.lookup::<MoneyState>(*money_contract::CONTRACT_ID).unwrap();
  137. if !money_state.is_valid_merkle(&input.merkle_root) {
  138. return Err(Error::InvalidInputMerkleRoot)
  139. }
  140. if money_state.nullifier_exists(&input.nullifier) {
  141. return Err(Error::SpentCoin)
  142. }
  143. if votes_info.nullifier_exists(&input.nullifier) {
  144. return Err(Error::DoubleVote)
  145. }
  146. all_vote_commit += input.vote_commit;
  147. vote_nulls.push(input.nullifier);
  148. }
  149. Ok(Box::new(Update {
  150. proposal_bulla: call_data.header.proposal_bulla,
  151. vote_nulls,
  152. yes_vote_commit: call_data.header.yes_vote_commit,
  153. all_vote_commit,
  154. }))
  155. }
  156. #[derive(Clone)]
  157. pub struct Update {
  158. proposal_bulla: pallas::Base,
  159. vote_nulls: Vec<Nullifier>,
  160. pub yes_vote_commit: pallas::Point,
  161. pub all_vote_commit: pallas::Point,
  162. }
  163. impl UpdateBase for Update {
  164. fn apply(mut self: Box<Self>, states: &mut StateRegistry) {
  165. let state = states.lookup_mut::<DaoState>(*dao_contract::CONTRACT_ID).unwrap();
  166. let votes_info = state.lookup_proposal_votes_mut(self.proposal_bulla).unwrap();
  167. votes_info.yes_votes_commit += self.yes_vote_commit;
  168. votes_info.all_votes_commit += self.all_vote_commit;
  169. votes_info.vote_nulls.append(&mut self.vote_nulls);
  170. }
  171. }