client.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. use crate::blockchain::{rocks::columns, Rocks, RocksColumn, Slab};
  2. use crate::crypto::{
  3. load_params,
  4. merkle::{CommitmentTree, IncrementalWitness},
  5. merkle_node::MerkleNode,
  6. note::{EncryptedNote, Note},
  7. nullifier::Nullifier,
  8. save_params, setup_mint_prover, setup_spend_prover, OwnCoin, OwnCoins,
  9. };
  10. use crate::rpc::adapters::{RpcClient, RpcClientAdapter};
  11. use crate::rpc::jsonserver;
  12. use crate::serial::Encodable;
  13. use crate::serial::{deserialize, Decodable};
  14. use crate::service::{CashierClient, GatewayClient, GatewaySlabsSubscriber};
  15. use crate::state::{state_transition, ProgramState, StateUpdate};
  16. use crate::wallet::WalletApi;
  17. use crate::wallet::WalletPtr;
  18. use crate::{tx, Result};
  19. use super::ClientFailed;
  20. use async_executor::Executor;
  21. use bellman::groth16;
  22. use bls12_381::Bls12;
  23. use log::*;
  24. use jsonrpc_core::IoHandler;
  25. use async_std::sync::{Arc, Mutex};
  26. use std::net::SocketAddr;
  27. use std::path::PathBuf;
  28. pub struct Client {
  29. pub state: State,
  30. mint_params: bellman::groth16::Parameters<Bls12>,
  31. spend_params: bellman::groth16::Parameters<Bls12>,
  32. gateway: GatewayClient,
  33. }
  34. impl Client {
  35. pub fn new(
  36. rocks: Arc<Rocks>,
  37. gateway_addrs: (SocketAddr, SocketAddr),
  38. params_paths: (PathBuf, PathBuf),
  39. wallet: WalletPtr,
  40. ) -> Result<Self> {
  41. let slabstore = RocksColumn::<columns::Slabs>::new(rocks.clone());
  42. let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
  43. let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
  44. let mint_params_path = params_paths.0.to_str().unwrap_or("mint.params");
  45. let spend_params_path = params_paths.1.to_str().unwrap_or("spend.params");
  46. // Auto create trusted ceremony parameters if they don't exist
  47. if !params_paths.0.exists() {
  48. let params = setup_mint_prover();
  49. save_params(mint_params_path, &params)?;
  50. }
  51. if !params_paths.1.exists() {
  52. let params = setup_spend_prover();
  53. save_params(spend_params_path, &params)?;
  54. }
  55. // Load trusted setup parameters
  56. let (mint_params, mint_pvk) = load_params(mint_params_path)?;
  57. let (spend_params, spend_pvk) = load_params(spend_params_path)?;
  58. let state = State {
  59. tree: CommitmentTree::empty(),
  60. merkle_roots,
  61. nullifiers,
  62. mint_pvk,
  63. spend_pvk,
  64. wallet,
  65. };
  66. // create gateway client
  67. debug!(target: "CLIENT", "Creating GatewayClient");
  68. let gateway = GatewayClient::new(gateway_addrs.0, gateway_addrs.1, slabstore)?;
  69. Ok(Self {
  70. state,
  71. mint_params,
  72. spend_params,
  73. gateway,
  74. })
  75. }
  76. pub async fn start(&mut self) -> Result<()> {
  77. self.gateway.start().await?;
  78. Ok(())
  79. }
  80. pub async fn connect_to_cashier(
  81. client: Client,
  82. executor: Arc<Executor<'_>>,
  83. cashier_addr: SocketAddr,
  84. rpc_url: SocketAddr,
  85. ) -> Result<()> {
  86. // create cashier client
  87. debug!(target: "CLIENT", "Creating cashier client");
  88. let mut cashier_client = CashierClient::new(cashier_addr)?;
  89. // start cashier_client
  90. cashier_client.start().await?;
  91. let client_mutex = Arc::new(Mutex::new(client));
  92. let cashier_mutex = Arc::new(Mutex::new(cashier_client));
  93. let mut io = IoHandler::new();
  94. let rpc_client_adapter = RpcClientAdapter::new(client_mutex.clone(), cashier_mutex.clone());
  95. io.extend_with(rpc_client_adapter.to_delegate());
  96. let io = Arc::new(io);
  97. // start the rpc server
  98. debug!(target: "CLIENT", "Start RPC server");
  99. let _ = jsonserver::start(executor.clone(), rpc_url, io).await?;
  100. // start subscriber
  101. Client::connect_to_subscriber(client_mutex.clone(), executor.clone()).await?;
  102. Ok(())
  103. }
  104. pub async fn transfer(self: &mut Self, pub_key: String, amount: f64) -> Result<()> {
  105. let address = bs58::decode(pub_key.clone())
  106. .into_vec()
  107. .map_err(|_| ClientFailed::UnvalidAddress(pub_key.clone()))?;
  108. let address: jubjub::SubgroupPoint =
  109. deserialize(&address).map_err(|_| ClientFailed::UnvalidAddress(pub_key))?;
  110. if amount <= 0.0 {
  111. return Err(ClientFailed::UnvalidAmount(amount as u64).into());
  112. }
  113. let own_coins = self.state.wallet.get_own_coins()?;
  114. self.send(
  115. own_coins,
  116. address.clone(),
  117. amount.clone() as u64,
  118. 1,
  119. )
  120. .await?;
  121. Ok(())
  122. }
  123. pub async fn send(
  124. self: &mut Self,
  125. own_coins: OwnCoins,
  126. pub_key: jubjub::SubgroupPoint,
  127. amount: u64,
  128. asset_id: u64,
  129. ) -> Result<()> {
  130. let slab = self.build_slab_from_tx(
  131. own_coins,
  132. pub_key.clone(),
  133. amount.clone() as u64,
  134. asset_id
  135. )?;
  136. self.gateway.put_slab(slab).await?;
  137. Ok(())
  138. }
  139. fn build_slab_from_tx(
  140. &self,
  141. own_coins: OwnCoins,
  142. pub_key: jubjub::SubgroupPoint,
  143. amount: u64,
  144. asset_id: u64,
  145. ) -> Result<Slab> {
  146. let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
  147. let mut inputs_value: u64 = 0;
  148. let mut outputs: Vec<tx::TransactionBuilderOutputInfo> = vec![];
  149. for own_coin in own_coins.iter() {
  150. if inputs_value >= amount {
  151. break;
  152. }
  153. let witness = &own_coin.witness;
  154. let merkle_path = witness.path().unwrap();
  155. inputs_value += own_coin.note.value;
  156. let input = tx::TransactionBuilderInputInfo {
  157. merkle_path,
  158. secret: own_coin.secret,
  159. note: own_coin.note.clone(),
  160. };
  161. inputs.push(input);
  162. }
  163. if inputs_value < amount {
  164. return Err(ClientFailed::NotEnoughValue(0).into());
  165. }
  166. if inputs_value > amount {
  167. let inputs_len = inputs.len();
  168. let input = &inputs[inputs_len - 1];
  169. let return_value: u64 = inputs_value - amount;
  170. let own_pub_key = zcash_primitives::constants::SPENDING_KEY_GENERATOR * input.secret;
  171. outputs.push(tx::TransactionBuilderOutputInfo {
  172. value: return_value,
  173. asset_id: 1,
  174. public: own_pub_key,
  175. });
  176. }
  177. outputs.push(tx::TransactionBuilderOutputInfo {
  178. value: amount,
  179. asset_id,
  180. public: pub_key,
  181. });
  182. let builder = tx::TransactionBuilder {
  183. clear_inputs: vec![],
  184. inputs,
  185. outputs,
  186. };
  187. let mut tx_data = vec![];
  188. {
  189. let tx = builder.build(&self.mint_params, &self.spend_params);
  190. tx.encode(&mut tx_data).expect("encode tx");
  191. }
  192. let slab = Slab::new(tx_data);
  193. Ok(slab)
  194. }
  195. pub async fn connect_to_subscriber(
  196. client: Arc<Mutex<Client>>,
  197. executor: Arc<Executor<'_>>,
  198. ) -> Result<()> {
  199. // start subscribing
  200. debug!(target: "CLIENT", "Start subscriber");
  201. let gateway_slabs_sub: GatewaySlabsSubscriber = client
  202. .lock()
  203. .await
  204. .gateway
  205. .start_subscriber(executor.clone())
  206. .await?;
  207. loop {
  208. let slab = gateway_slabs_sub.recv().await?;
  209. let tx = tx::Transaction::decode(&slab.get_payload()[..])?;
  210. let mut client = client.lock().await;
  211. let update = state_transition(&client.state, tx)?;
  212. let secret_keys = client.state.wallet.get_private_keys()?;
  213. client.state.apply(update, secret_keys.clone()).await?;
  214. }
  215. }
  216. }
  217. pub struct State {
  218. // The entire merkle tree state
  219. pub tree: CommitmentTree<MerkleNode>,
  220. // List of all previous and the current merkle roots
  221. // This is the hashed value of all the children.
  222. pub merkle_roots: RocksColumn<columns::MerkleRoots>,
  223. // Nullifiers prevent double spending
  224. pub nullifiers: RocksColumn<columns::Nullifiers>,
  225. // Mint verifying key used by ZK
  226. pub mint_pvk: groth16::PreparedVerifyingKey<Bls12>,
  227. // Spend verifying key used by ZK
  228. pub spend_pvk: groth16::PreparedVerifyingKey<Bls12>,
  229. pub wallet: WalletPtr,
  230. }
  231. impl ProgramState for State {
  232. fn is_valid_cashier_public_key(&self, public: &jubjub::SubgroupPoint) -> bool {
  233. self.wallet
  234. .get_cashier_public_keys()
  235. .expect("Get cashier public keys")
  236. .contains(public)
  237. }
  238. fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
  239. self.merkle_roots
  240. .key_exist(*merkle_root)
  241. .expect("Check if the merkle_root valid")
  242. }
  243. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
  244. self.nullifiers
  245. .key_exist(nullifier.repr)
  246. .expect("Check if nullifier exists")
  247. }
  248. // load from disk
  249. fn mint_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12> {
  250. &self.mint_pvk
  251. }
  252. fn spend_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12> {
  253. &self.spend_pvk
  254. }
  255. }
  256. impl State {
  257. pub async fn apply(&mut self, update: StateUpdate, secret_keys: Vec<jubjub::Fr>) -> Result<()> {
  258. // Extend our list of nullifiers with the ones from the update
  259. for nullifier in update.nullifiers {
  260. self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
  261. }
  262. // Update merkle tree and witnesses
  263. for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.iter()) {
  264. // Add the new coins to the merkle tree
  265. let node = MerkleNode::from_coin(&coin);
  266. self.tree.append(node).expect("Append to merkle tree");
  267. // Keep track of all merkle roots that have existed
  268. self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
  269. // Also update all the coin witnesses
  270. for (coin_id, witness) in self.wallet.get_witnesses()?.iter_mut() {
  271. witness.append(node).expect("Append to witness");
  272. self.wallet
  273. .update_witness(coin_id.clone(), witness.clone())?;
  274. }
  275. for secret in secret_keys.iter() {
  276. if let Some(note) = Self::try_decrypt_note(enc_note.clone(), secret.clone()) {
  277. // We need to keep track of the witness for this coin.
  278. // This allows us to prove inclusion of the coin in the merkle tree with ZK.
  279. // Just as we update the merkle tree with every new coin, so we do the same with
  280. // the witness.
  281. // Derive the current witness from the current tree.
  282. // This is done right after we add our coin to the tree (but before any other
  283. // coins are added)
  284. // Make a new witness for this coin
  285. let witness = IncrementalWitness::from_tree(&self.tree);
  286. let own_coin = OwnCoin {
  287. coin: coin.clone(),
  288. note: note.clone(),
  289. secret: secret.clone(),
  290. witness: witness.clone(),
  291. };
  292. self.wallet.put_own_coins(own_coin)?;
  293. }
  294. }
  295. }
  296. Ok(())
  297. }
  298. fn try_decrypt_note(ciphertext: &EncryptedNote, secret: jubjub::Fr) -> Option<Note> {
  299. match ciphertext.decrypt(&secret) {
  300. Ok(note) => {
  301. // ... and return the decrypted note for this coin.
  302. return Some(note);
  303. }
  304. Err(_) => {}
  305. }
  306. // We weren't able to decrypt the note with our key.
  307. None
  308. }
  309. }