client.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. use async_std::sync::{Arc, Mutex};
  2. use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
  3. use log::{debug, info, trace, warn};
  4. use smol::Executor;
  5. use url::Url;
  6. use crate::{
  7. blockchain::{rocks::columns, Rocks, RocksColumn, Slab},
  8. circuit::{MintContract, SpendContract},
  9. crypto::{
  10. coin::Coin,
  11. keypair::{Keypair, PublicKey, SecretKey},
  12. merkle_node::MerkleNode,
  13. proof::ProvingKey,
  14. OwnCoin,
  15. },
  16. serial::{Decodable, Encodable},
  17. service::GatewayClient,
  18. state::{state_transition, State, StateUpdate},
  19. tx,
  20. types::DrkTokenId,
  21. util::Address,
  22. wallet::{
  23. cashierdb::CashierDbPtr,
  24. walletdb::{Balances, WalletPtr},
  25. },
  26. Result,
  27. };
  28. #[derive(Debug, Clone, thiserror::Error)]
  29. pub enum ClientFailed {
  30. #[error("Here is not enough value {0}")]
  31. NotEnoughValue(u64),
  32. #[error("Invalid Address {0}")]
  33. InvalidAddress(String),
  34. #[error("Invalid Amount {0}")]
  35. InvalidAmount(u64),
  36. #[error("Unable to get deposit address")]
  37. UnableToGetDepositAddress,
  38. #[error("Unable to get withdraw address")]
  39. UnableToGetWithdrawAddress,
  40. #[error("Does not have cashier public key")]
  41. DoesNotHaveCashierPublicKey,
  42. #[error("Does not have keypair")]
  43. DoesNotHaveKeypair,
  44. #[error("Password is empty. Cannot create database")]
  45. EmptyPassword,
  46. #[error("Wallet already initialized")]
  47. WalletInitialized,
  48. #[error("Keypair already exists")]
  49. KeyExists,
  50. #[error("{0}")]
  51. ClientError(String),
  52. #[error("Verify error: {0}")]
  53. VerifyError(String),
  54. #[error("Merkle tree already exists")]
  55. TreeExists,
  56. }
  57. pub type ClientResult<T> = std::result::Result<T, ClientFailed>;
  58. impl From<super::error::Error> for ClientFailed {
  59. fn from(err: super::error::Error) -> ClientFailed {
  60. ClientFailed::ClientError(err.to_string())
  61. }
  62. }
  63. impl From<crate::state::VerifyFailed> for ClientFailed {
  64. fn from(err: crate::state::VerifyFailed) -> ClientFailed {
  65. ClientFailed::VerifyError(err.to_string())
  66. }
  67. }
  68. pub struct Client {
  69. pub main_keypair: Keypair,
  70. gateway: GatewayClient,
  71. wallet: WalletPtr,
  72. mint_pk: ProvingKey,
  73. spend_pk: ProvingKey,
  74. }
  75. impl Client {
  76. pub async fn new(
  77. rocks: Arc<Rocks>,
  78. gateway_addrs: (Url, Url),
  79. wallet: WalletPtr,
  80. ) -> Result<Self> {
  81. wallet.init_db().await?;
  82. // Check if there is a default keypair
  83. if wallet.get_default_keypair().await.is_err() {
  84. // Generate a new keypair if we don't have any.
  85. if wallet.get_keypairs().await?.is_empty() {
  86. wallet.key_gen().await?;
  87. }
  88. // set the first keypair as the default one
  89. wallet.set_default_keypair(&wallet.get_keypairs().await?[0].public).await?;
  90. }
  91. // Generate merkle tree if we don't have one.
  92. if wallet.get_tree().await.is_err() {
  93. wallet.tree_gen().await?;
  94. }
  95. let main_keypair = wallet.get_default_keypair().await?;
  96. info!("Main keypair: {}", Address::from(main_keypair.public).to_string());
  97. trace!("Creating GatewayClient");
  98. let slabstore = RocksColumn::<columns::Slabs>::new(rocks);
  99. let gateway = GatewayClient::new(gateway_addrs.0, gateway_addrs.1, slabstore)?;
  100. // TODO: These should go to a better place.
  101. debug!("Building proving key for the mint contract...");
  102. let mint_pk = ProvingKey::build(11, MintContract::default());
  103. debug!("Building proving key for the spend contract...");
  104. let spend_pk = ProvingKey::build(11, SpendContract::default());
  105. let client = Client { main_keypair, gateway, wallet, mint_pk, spend_pk };
  106. Ok(client)
  107. }
  108. pub async fn start(&mut self) -> Result<()> {
  109. self.gateway.start().await
  110. }
  111. async fn build_slab_from_tx(
  112. &mut self,
  113. pubkey: PublicKey,
  114. value: u64,
  115. token_id: DrkTokenId,
  116. clear_input: bool,
  117. state: Arc<Mutex<State>>,
  118. ) -> ClientResult<Vec<Coin>> {
  119. trace!("Begin building slab from tx");
  120. let mut clear_inputs: Vec<tx::TransactionBuilderClearInputInfo> = vec![];
  121. let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
  122. let mut outputs: Vec<tx::TransactionBuilderOutputInfo> = vec![];
  123. let mut coins: Vec<Coin> = vec![];
  124. if clear_input {
  125. // TODO: FIXME:
  126. let signature_secret = self.main_keypair.secret;
  127. let input = tx::TransactionBuilderClearInputInfo { value, token_id, signature_secret };
  128. clear_inputs.push(input);
  129. } else {
  130. trace!("Start building tx inputs");
  131. let mut inputs_value = 0_u64;
  132. let state_m = state.lock().await;
  133. let own_coins = self.wallet.get_own_coins().await?;
  134. for own_coin in own_coins.iter() {
  135. if inputs_value >= value {
  136. break
  137. }
  138. let node = MerkleNode(own_coin.coin.0);
  139. let (leaf_position, merkle_path) = state_m.tree.authentication_path(&node).unwrap();
  140. // TODO: What is this counting? Is it everything or does it know to separate
  141. // different tokens?
  142. inputs_value += own_coin.note.value;
  143. let input = tx::TransactionBuilderInputInfo {
  144. leaf_position,
  145. merkle_path,
  146. secret: own_coin.secret,
  147. note: own_coin.note,
  148. };
  149. inputs.push(input);
  150. coins.push(own_coin.coin);
  151. }
  152. if inputs_value < value {
  153. return Err(ClientFailed::NotEnoughValue(inputs_value))
  154. }
  155. if inputs_value > value {
  156. let return_value: u64 = inputs_value - value;
  157. outputs.push(tx::TransactionBuilderOutputInfo {
  158. value: return_value,
  159. token_id,
  160. public: self.main_keypair.public,
  161. });
  162. }
  163. trace!("Finish building inputs");
  164. }
  165. outputs.push(tx::TransactionBuilderOutputInfo { value, token_id, public: pubkey });
  166. let builder = tx::TransactionBuilder { clear_inputs, inputs, outputs };
  167. let mut tx_data = vec![];
  168. let tx: tx::Transaction = builder.build(&self.mint_pk, &self.spend_pk)?;
  169. tx.encode(&mut tx_data).expect("encode tx");
  170. let slab = Slab::new(tx_data);
  171. trace!("Finish building slab from tx");
  172. // Check if it's valid before sending to gateway
  173. let state = &*state.lock().await;
  174. state_transition(state, tx)?;
  175. trace!("Sending slab to gateway");
  176. self.gateway.put_slab(slab).await?;
  177. trace!("Slab sent to gateway successfully");
  178. Ok(coins)
  179. }
  180. pub async fn send(
  181. &mut self,
  182. pubkey: PublicKey,
  183. amount: u64,
  184. token_id: DrkTokenId,
  185. clear_input: bool,
  186. state: Arc<Mutex<State>>,
  187. ) -> ClientResult<()> {
  188. // TODO: TOKEN debug
  189. debug!("Sending {}", amount);
  190. if amount == 0 {
  191. return Err(ClientFailed::InvalidAmount(0))
  192. }
  193. let coins = self.build_slab_from_tx(pubkey, amount, token_id, clear_input, state).await?;
  194. for coin in coins.iter() {
  195. self.wallet.confirm_spend_coin(coin).await?;
  196. }
  197. debug!("Sent {}", amount);
  198. Ok(())
  199. }
  200. pub async fn transfer(
  201. &mut self,
  202. token_id: DrkTokenId,
  203. pubkey: PublicKey,
  204. amount: u64,
  205. state: Arc<Mutex<State>>,
  206. ) -> ClientResult<()> {
  207. debug!("Start transfer {}", amount);
  208. let token_id_exists = self.wallet.token_id_exists(token_id).await?;
  209. if token_id_exists {
  210. self.send(pubkey, amount, token_id, false, state).await?;
  211. } else {
  212. return Err(ClientFailed::NotEnoughValue(amount))
  213. }
  214. debug!("Finish transfer {}", amount);
  215. Ok(())
  216. }
  217. async fn update_state(
  218. secret_keys: Vec<SecretKey>,
  219. slab: &Slab,
  220. state: Arc<Mutex<State>>,
  221. wallet: WalletPtr,
  222. notify: Option<async_channel::Sender<(PublicKey, u64)>>,
  223. ) -> Result<()> {
  224. trace!("Building tx from slab and updating the state");
  225. let payload = slab.get_payload();
  226. /*
  227. use std::io::Write;
  228. let mut file = std::fs::File::create("/tmp/payload.txt")?;
  229. file.write_all(&payload)?;
  230. */
  231. trace!("Decoding payload");
  232. let tx = tx::Transaction::decode(&payload[..])?;
  233. let update: StateUpdate;
  234. // This is separate because otherwise the mutex is never unlocked.
  235. {
  236. trace!("Acquiring state lock");
  237. let state = &*state.lock().await;
  238. update = state_transition(state, tx)?;
  239. trace!("Successfully passed state_transition");
  240. }
  241. trace!("Acquiring state lock");
  242. let mut state = state.lock().await;
  243. trace!("Trying to apply the new state");
  244. state.apply(update, secret_keys, notify, wallet).await?;
  245. trace!("Successfully passed state.apply");
  246. Ok(())
  247. }
  248. pub async fn connect_to_subscriber_from_cashier(
  249. &self,
  250. state: Arc<Mutex<State>>,
  251. cashier_wallet: CashierDbPtr,
  252. notify: async_channel::Sender<(PublicKey, u64)>,
  253. executor: Arc<Executor<'_>>,
  254. ) -> Result<()> {
  255. trace!("Start subscriber for cashier");
  256. let gateway_slabs_sub = self.gateway.start_subscriber(executor.clone()).await?;
  257. let secret_key = self.main_keypair.secret;
  258. let wallet = self.wallet.clone();
  259. let task: smol::Task<Result<()>> = executor.spawn(async move {
  260. loop {
  261. let slab = gateway_slabs_sub.recv().await?;
  262. trace!("Received new slab");
  263. let mut secret_keys = vec![secret_key];
  264. let mut withdraw_keys = cashier_wallet.get_withdraw_private_keys().await?;
  265. secret_keys.append(&mut withdraw_keys);
  266. let update_state = Self::update_state(
  267. secret_keys,
  268. &slab,
  269. state.clone(),
  270. wallet.clone(),
  271. Some(notify.clone()),
  272. )
  273. .await;
  274. if let Err(e) = update_state {
  275. warn!("Update state: {}", e);
  276. continue
  277. }
  278. }
  279. });
  280. task.detach();
  281. Ok(())
  282. }
  283. pub async fn connect_to_subscriber(
  284. &self,
  285. state: Arc<Mutex<State>>,
  286. executor: Arc<Executor<'_>>,
  287. ) -> Result<()> {
  288. trace!("Start subscriber for darkfid");
  289. let gateway_slabs_sub = self.gateway.start_subscriber(executor.clone()).await?;
  290. let secret_key = self.main_keypair.secret;
  291. let wallet = self.wallet.clone();
  292. let task: smol::Task<Result<()>> = executor.spawn(async move {
  293. loop {
  294. let slab = gateway_slabs_sub.recv().await?;
  295. trace!("Received new slab");
  296. let update_state = Self::update_state(
  297. vec![secret_key],
  298. &slab,
  299. state.clone(),
  300. wallet.clone(),
  301. None,
  302. )
  303. .await;
  304. if let Err(e) = update_state {
  305. warn!("Update state: {}", e);
  306. continue
  307. }
  308. }
  309. });
  310. task.detach();
  311. Ok(())
  312. }
  313. pub async fn init_db(&self) -> Result<()> {
  314. self.wallet.init_db().await
  315. }
  316. pub async fn get_own_coins(&self) -> Result<Vec<OwnCoin>> {
  317. self.wallet.get_own_coins().await
  318. }
  319. pub async fn confirm_spend_coin(&self, coin: &Coin) -> Result<()> {
  320. self.wallet.confirm_spend_coin(coin).await
  321. }
  322. pub async fn get_keypairs(&self) -> Result<Vec<Keypair>> {
  323. self.wallet.get_keypairs().await
  324. }
  325. pub async fn put_keypair(&self, keypair: &Keypair) -> Result<()> {
  326. self.wallet.put_keypair(keypair).await
  327. }
  328. pub async fn set_default_keypair(&mut self, public: &PublicKey) -> Result<()> {
  329. self.wallet.set_default_keypair(public).await?;
  330. self.main_keypair = self.wallet.get_default_keypair().await?;
  331. Ok(())
  332. }
  333. pub async fn key_gen(&self) -> Result<()> {
  334. self.wallet.key_gen().await
  335. }
  336. pub async fn get_balances(&self) -> Result<Balances> {
  337. self.wallet.get_balances().await
  338. }
  339. pub async fn get_tree(&self) -> Result<BridgeTree<MerkleNode, 32>> {
  340. self.wallet.get_tree().await
  341. }
  342. }