validate.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. use std::any::{Any, TypeId};
  2. use darkfi_serial::{Encodable, SerialDecodable, SerialEncodable};
  3. use log::error;
  4. use pasta_curves::{
  5. arithmetic::CurveAffine,
  6. group::{Curve, Group},
  7. pallas,
  8. };
  9. use darkfi::{
  10. crypto::{keypair::PublicKey, merkle_node::MerkleNode, types::DrkCircuitField},
  11. Error as DarkFiError,
  12. };
  13. use crate::{
  14. contract::{
  15. dao_contract, dao_contract::State as DaoState, money_contract,
  16. money_contract::state::State as MoneyState,
  17. },
  18. note::EncryptedNote2,
  19. util::{CallDataBase, StateRegistry, Transaction, UpdateBase},
  20. };
  21. // used for debugging
  22. // const TARGET: &str = "dao_contract::propose::validate::state_transition()";
  23. #[derive(Debug, Clone, thiserror::Error)]
  24. pub enum Error {
  25. #[error("Invalid input merkle root")]
  26. InvalidInputMerkleRoot,
  27. #[error("Invalid DAO merkle root")]
  28. InvalidDaoMerkleRoot,
  29. #[error("DarkFi error: {0}")]
  30. DarkFiError(String),
  31. }
  32. type Result<T> = std::result::Result<T, Error>;
  33. impl From<DarkFiError> for Error {
  34. fn from(err: DarkFiError) -> Self {
  35. Self::DarkFiError(err.to_string())
  36. }
  37. }
  38. #[derive(Clone, SerialEncodable, SerialDecodable)]
  39. pub struct CallData {
  40. pub header: Header,
  41. pub inputs: Vec<Input>,
  42. }
  43. impl CallDataBase for CallData {
  44. fn zk_public_values(&self) -> Vec<(String, Vec<DrkCircuitField>)> {
  45. let mut zk_publics = Vec::new();
  46. let mut total_funds_commit = pallas::Point::identity();
  47. assert!(!self.inputs.is_empty(), "inputs length cannot be zero");
  48. for input in &self.inputs {
  49. total_funds_commit += input.value_commit;
  50. let value_coords = input.value_commit.to_affine().coordinates().unwrap();
  51. let sigpub_coords = input.signature_public.0.to_affine().coordinates().unwrap();
  52. zk_publics.push((
  53. "dao-propose-burn".to_string(),
  54. vec![
  55. *value_coords.x(),
  56. *value_coords.y(),
  57. self.header.token_commit,
  58. input.merkle_root.0,
  59. *sigpub_coords.x(),
  60. *sigpub_coords.y(),
  61. ],
  62. ));
  63. }
  64. let total_funds_coords = total_funds_commit.to_affine().coordinates().unwrap();
  65. zk_publics.push((
  66. "dao-propose-main".to_string(),
  67. vec![
  68. self.header.token_commit,
  69. self.header.dao_merkle_root.0,
  70. self.header.proposal_bulla,
  71. *total_funds_coords.x(),
  72. *total_funds_coords.y(),
  73. ],
  74. ));
  75. zk_publics
  76. }
  77. fn as_any(&self) -> &dyn Any {
  78. self
  79. }
  80. fn signature_public_keys(&self) -> Vec<PublicKey> {
  81. let mut signature_public_keys = vec![];
  82. for input in self.inputs.clone() {
  83. signature_public_keys.push(input.signature_public);
  84. }
  85. signature_public_keys
  86. }
  87. fn encode_bytes(
  88. &self,
  89. mut writer: &mut dyn std::io::Write,
  90. ) -> core::result::Result<usize, std::io::Error> {
  91. self.encode(&mut writer)
  92. }
  93. }
  94. #[derive(Clone, SerialEncodable, SerialDecodable)]
  95. pub struct Header {
  96. pub dao_merkle_root: MerkleNode,
  97. pub token_commit: pallas::Base,
  98. pub proposal_bulla: pallas::Base,
  99. pub enc_note: EncryptedNote2,
  100. }
  101. #[derive(Clone, SerialEncodable, SerialDecodable)]
  102. pub struct Input {
  103. pub value_commit: pallas::Point,
  104. pub merkle_root: MerkleNode,
  105. pub signature_public: PublicKey,
  106. }
  107. pub fn state_transition(
  108. states: &StateRegistry,
  109. func_call_index: usize,
  110. parent_tx: &Transaction,
  111. ) -> Result<Box<dyn UpdateBase + Send>> {
  112. let func_call = &parent_tx.func_calls[func_call_index];
  113. let call_data = func_call.call_data.as_any();
  114. assert_eq!((*call_data).type_id(), TypeId::of::<CallData>());
  115. let call_data = call_data.downcast_ref::<CallData>();
  116. // This will be inside wasm so unwrap is fine.
  117. let call_data = call_data.unwrap();
  118. // Check the merkle roots for the input coins are valid
  119. for input in &call_data.inputs {
  120. let money_state = states.lookup::<MoneyState>(*money_contract::CONTRACT_ID).unwrap();
  121. if !money_state.is_valid_merkle(&input.merkle_root) {
  122. return Err(Error::InvalidInputMerkleRoot)
  123. }
  124. }
  125. let state = states.lookup::<DaoState>(*dao_contract::CONTRACT_ID).unwrap();
  126. // Is the DAO bulla generated in the ZK proof valid
  127. if !state.is_valid_dao_merkle(&call_data.header.dao_merkle_root) {
  128. return Err(Error::InvalidDaoMerkleRoot)
  129. }
  130. // TODO: look at gov tokens avoid using already spent ones
  131. // Need to spend original coin and generate 2 nullifiers?
  132. Ok(Box::new(Update { proposal_bulla: call_data.header.proposal_bulla }))
  133. }
  134. #[derive(Clone)]
  135. pub struct Update {
  136. pub proposal_bulla: pallas::Base,
  137. }
  138. impl UpdateBase for Update {
  139. fn apply(self: Box<Self>, states: &mut StateRegistry) {
  140. let state = states.lookup_mut::<DaoState>(*dao_contract::CONTRACT_ID).unwrap();
  141. state.add_proposal_bulla(self.proposal_bulla);
  142. }
  143. }