client.rs 12 KB

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