mod.rs 11 KB

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