mod.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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;
  19. use darkfi_sdk::{
  20. crypto::{
  21. schnorr::{SchnorrPublic, SchnorrSecret, Signature},
  22. PublicKey, SecretKey,
  23. },
  24. dark_tree::{dark_forest_leaf_vec_integrity_check, DarkForest, DarkLeaf, DarkTree},
  25. error::DarkTreeResult,
  26. pasta::pallas,
  27. tx::{ContractCall, TransactionHash},
  28. AsHex,
  29. };
  30. #[cfg(feature = "async-serial")]
  31. use darkfi_serial::async_trait;
  32. use darkfi_serial::{Encodable, SerialDecodable, SerialEncodable};
  33. use log::{debug, error};
  34. use crate::{
  35. error::TxVerifyFailed,
  36. zk::{proof::VerifyingKey, Proof},
  37. Error, Result,
  38. };
  39. macro_rules! zip {
  40. ($x:expr) => ($x);
  41. ($x:expr, $($y:expr), +) => (
  42. $x.iter().zip(zip!($($y), +))
  43. )
  44. }
  45. // ANCHOR: transaction
  46. /// A Transaction contains an arbitrary number of `ContractCall` objects,
  47. /// along with corresponding ZK proofs and Schnorr signatures. `DarkLeaf`
  48. /// is used to map relations between contract calls in the transaction.
  49. #[derive(Clone, Default, Eq, PartialEq, SerialEncodable, SerialDecodable)]
  50. pub struct Transaction {
  51. /// Calls executed in this transaction
  52. pub calls: Vec<DarkLeaf<ContractCall>>,
  53. /// Attached ZK proofs
  54. pub proofs: Vec<Vec<Proof>>,
  55. /// Attached Schnorr signatures
  56. pub signatures: Vec<Vec<Signature>>,
  57. }
  58. // ANCHOR_END: transaction
  59. impl Transaction {
  60. /// Verify ZK proofs for the entire transaction.
  61. pub async fn verify_zkps(
  62. &self,
  63. verifying_keys: &HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
  64. zkp_table: Vec<Vec<(String, Vec<pallas::Base>)>>,
  65. ) -> Result<()> {
  66. // TODO: Are we sure we should assert here?
  67. assert_eq!(self.calls.len(), self.proofs.len());
  68. assert_eq!(self.calls.len(), zkp_table.len());
  69. for (call, (proofs, pubvals)) in zip!(self.calls, self.proofs, zkp_table) {
  70. assert_eq!(proofs.len(), pubvals.len());
  71. let Some(contract_map) = verifying_keys.get(&call.data.contract_id.to_bytes()) else {
  72. error!(
  73. target: "tx::verify_zkps",
  74. "[TX] Verifying keys not found for contract {}",
  75. call.data.contract_id,
  76. );
  77. return Err(TxVerifyFailed::InvalidZkProof.into())
  78. };
  79. for (proof, (zk_ns, public_vals)) in proofs.iter().zip(pubvals.iter()) {
  80. if let Some(vk) = contract_map.get(zk_ns) {
  81. // We have a verifying key for this
  82. debug!(target: "tx::verify_zkps", "[TX] public inputs: {:#?}", public_vals);
  83. if let Err(e) = proof.verify(vk, public_vals) {
  84. error!(
  85. target: "tx::verify_zkps",
  86. "[TX] Failed verifying {}::{} ZK proof: {:#?}",
  87. call.data.contract_id, zk_ns, e
  88. );
  89. return Err(TxVerifyFailed::InvalidZkProof.into())
  90. }
  91. debug!(
  92. target: "tx::verify_zkps",
  93. "[TX] Successfully verified {}::{} ZK proof",
  94. call.data.contract_id, zk_ns,
  95. );
  96. continue
  97. }
  98. error!(
  99. target: "tx::verify_zkps",
  100. "[TX] {}::{} circuit VK nonexistent",
  101. call.data.contract_id, zk_ns,
  102. );
  103. return Err(TxVerifyFailed::InvalidZkProof.into())
  104. }
  105. }
  106. Ok(())
  107. }
  108. /// Verify Schnorr signatures for the entire transaction.
  109. pub fn verify_sigs(&self, pub_table: Vec<Vec<PublicKey>>) -> Result<()> {
  110. // Hash the transaction without the signatures
  111. let mut hasher = blake3::Hasher::new();
  112. self.calls.encode(&mut hasher)?;
  113. self.proofs.encode(&mut hasher)?;
  114. let data_hash = hasher.finalize();
  115. debug!(
  116. target: "tx::verify_sigs",
  117. "tx.verify_sigs: data_hash: {}", data_hash.as_bytes().hex(),
  118. );
  119. assert_eq!(self.signatures.len(), pub_table.len());
  120. for (i, (sigs, pubkeys)) in self.signatures.iter().zip(pub_table.iter()).enumerate() {
  121. assert_eq!(sigs.len(), pubkeys.len());
  122. for (pubkey, signature) in pubkeys.iter().zip(sigs) {
  123. debug!(
  124. target: "tx::verify_sigs",
  125. "[TX] Verifying signature with public key: {}", pubkey,
  126. );
  127. if !pubkey.verify(&data_hash.as_bytes()[..], signature) {
  128. error!(
  129. target: "tx::verify_sigs",
  130. "[TX] tx::verify_sigs[{}] failed to verify signature", i,
  131. );
  132. return Err(Error::InvalidSignature)
  133. }
  134. }
  135. debug!(target: "tx::verify_sigs", "[TX] tx::verify_sigs[{}] passed", i);
  136. }
  137. Ok(())
  138. }
  139. /// Create Schnorr signatures for the entire transaction.
  140. pub fn create_sigs(&self, secret_keys: &[SecretKey]) -> Result<Vec<Signature>> {
  141. // Hash the transaction without the signatures
  142. let mut hasher = blake3::Hasher::new();
  143. self.calls.encode(&mut hasher)?;
  144. self.proofs.encode(&mut hasher)?;
  145. let data_hash = hasher.finalize();
  146. debug!(
  147. target: "tx::create_sigs",
  148. "[TX] tx.create_sigs: data_hash: {:?}", data_hash.as_bytes().hex(),
  149. );
  150. let mut sigs = vec![];
  151. for secret in secret_keys {
  152. debug!(
  153. target: "tx::create_sigs",
  154. "[TX] Creating signature with public key: {}", PublicKey::from_secret(*secret),
  155. );
  156. let signature = secret.sign(&data_hash.as_bytes()[..]);
  157. sigs.push(signature);
  158. }
  159. Ok(sigs)
  160. }
  161. /// Get the transaction hash
  162. pub fn hash(&self) -> TransactionHash {
  163. let mut hasher = blake3::Hasher::new();
  164. // Blake3 hasher .update() method never fails.
  165. // This call returns a Result due to how the Write trait is specified.
  166. // Calling unwrap() here should be safe.
  167. self.encode(&mut hasher).expect("blake3 hasher");
  168. TransactionHash(hasher.finalize().into())
  169. }
  170. }
  171. // Avoid showing the proofs and sigs in the debug output since often they are very long.
  172. impl std::fmt::Debug for Transaction {
  173. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  174. writeln!(f, "Transaction {{")?;
  175. for (i, call) in self.calls.iter().enumerate() {
  176. writeln!(f, " Call {} {{", i)?;
  177. writeln!(f, " contract_id: {:?}", call.data.contract_id.inner())?;
  178. let calldata = &call.data.data;
  179. if !calldata.is_empty() {
  180. writeln!(f, " function_code: {}", calldata[0])?;
  181. }
  182. writeln!(f, " parent: {:?}", call.parent_index)?;
  183. writeln!(f, " children: {:?}", call.children_indexes)?;
  184. writeln!(f, " }},")?;
  185. }
  186. writeln!(f, "}}")
  187. }
  188. }
  189. #[cfg(feature = "net")]
  190. use crate::net::Message;
  191. #[cfg(feature = "net")]
  192. crate::impl_p2p_message!(Transaction, "tx");
  193. /// Calls tree bounds definitions
  194. // TODO: increase min to 2 when fees are implement
  195. pub const MIN_TX_CALLS: usize = 1;
  196. // TODO: verify max value
  197. pub const MAX_TX_CALLS: usize = 20;
  198. /// Auxiliarry structure containing all the information
  199. /// required to execute a contract call.
  200. #[derive(Clone)]
  201. pub struct ContractCallLeaf {
  202. /// Call executed
  203. pub call: ContractCall,
  204. /// Attached ZK proofs
  205. pub proofs: Vec<Proof>,
  206. }
  207. /// Auxiliary structure to build a full [`Transaction`] using
  208. /// [`DarkTree`] to order everything.
  209. pub struct TransactionBuilder {
  210. /// Contract calls trees forest
  211. pub calls: DarkForest<ContractCallLeaf>,
  212. }
  213. // TODO: for now we build the trees manually, but we should
  214. // add all the proper functions for easier building.
  215. impl TransactionBuilder {
  216. /// Initialize the builder, using provided data to
  217. /// generate its initial [`DarkTree`] root.
  218. pub fn new(
  219. data: ContractCallLeaf,
  220. children: Vec<DarkTree<ContractCallLeaf>>,
  221. ) -> DarkTreeResult<Self> {
  222. let calls = DarkForest::new(Some(MIN_TX_CALLS), Some(MAX_TX_CALLS));
  223. let mut self_ = Self { calls };
  224. self_.append(data, children)?;
  225. Ok(self_)
  226. }
  227. /// Append a new call tree to the forest
  228. pub fn append(
  229. &mut self,
  230. data: ContractCallLeaf,
  231. children: Vec<DarkTree<ContractCallLeaf>>,
  232. ) -> DarkTreeResult<()> {
  233. let tree = DarkTree::new(data, children, None, None);
  234. self.calls.append(tree)
  235. }
  236. /// Builder builds the calls vector using the [`DarkForest`]
  237. /// and generates the corresponding [`Transaction`].
  238. pub fn build(&mut self) -> DarkTreeResult<Transaction> {
  239. // Build the leafs vector
  240. let leafs = self.calls.build_vec()?;
  241. // Double check integrity
  242. dark_forest_leaf_vec_integrity_check(&leafs, Some(MIN_TX_CALLS), Some(MAX_TX_CALLS))?;
  243. // Build the corresponding transaction
  244. let mut calls = Vec::with_capacity(leafs.len());
  245. let mut proofs = Vec::with_capacity(leafs.len());
  246. for leaf in leafs {
  247. let call = DarkLeaf {
  248. data: leaf.data.call,
  249. parent_index: leaf.parent_index,
  250. children_indexes: leaf.children_indexes,
  251. };
  252. calls.push(call);
  253. proofs.push(leaf.data.proofs);
  254. }
  255. Ok(Transaction { calls, proofs, signatures: vec![] })
  256. }
  257. }