Просмотр исходного кода

implemented deposit on rpc/adapter

lunar-mining 5 лет назад
Родитель
Сommit
a0f5854ecb
5 измененных файлов с 63 добавлено и 56 удалено
  1. 6 19
      src/bin/darkfid.rs
  2. 2 0
      src/error.rs
  3. 25 23
      src/rpc/adapter.rs
  4. 6 2
      src/rpc/jsonserver.rs
  5. 24 12
      src/service/cashier.rs

+ 6 - 19
src/bin/darkfid.rs

@@ -23,13 +23,10 @@ use bellman::groth16;
 use bls12_381::Bls12;
 use easy_parallel::Parallel;
 use ff::Field;
-use futures::AsyncWriteExt;
 use rand::rngs::OsRng;
 use rusqlite::Connection;
-use std::net::TcpStream;
 
 use async_std::sync::Arc;
-use smol::Async;
 use std::net::SocketAddr;
 use std::path::Path;
 use std::path::PathBuf;
@@ -126,11 +123,7 @@ impl State {
     }
 
     async fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
-        let vec = self.wallet.get_private().ok()?;
-        let secret = self
-            .wallet
-            .get_value_deserialized::<jubjub::Fr>(vec)
-            .expect("Deserialize failed");
+        let secret = self.wallet.get_private().ok()?;
         match ciphertext.decrypt(&secret) {
             Ok(note) => {
                 // ... and return the decrypted note for this coin.
@@ -153,15 +146,6 @@ pub async fn subscribe(gateway_slabs_sub: GatewaySlabsSubscriber, mut state: Sta
     }
 }
 
-// TODO: test function once we merge cashier branch
-pub async fn send_key_to_cashier(pubkey: Vec<u8>) -> Result<()> {
-    // TODO: cashier address should be hardcoded (and public e.g cashier.dark.fi)
-    let mut stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 3333)).await?;
-    println!("Connected to {}", stream.get_ref().peer_addr()?);
-    stream.write_all(&pubkey).await?;
-    Ok(())
-}
-
 async fn start(executor: Arc<Executor<'_>>, config: Arc<&DarkfidConfig>) -> Result<()> {
     let connect_addr: SocketAddr = config.connect_url.parse()?;
     let sub_addr: SocketAddr = config.subscriber_url.parse()?;
@@ -170,7 +154,10 @@ async fn start(executor: Arc<Executor<'_>>, config: Arc<&DarkfidConfig>) -> Resu
     let database_path = join_config_path(&PathBuf::from(database_path))?;
     let rocks = Rocks::new(&database_path)?;
 
-    let slabstore = RocksColumn::<columns::Slabs>::new(rocks.clone());
+    let rocks2 = rocks.clone();
+    let slabstore = RocksColumn::<columns::Slabs>::new(rocks2.clone());
+    let rocks3 = rocks2.clone();
+    let cashier_column = RocksColumn::<columns::CashierKeys>::new(rocks3);
 
     // Auto create trusted ceremony parameters if they don't exist
     if !Path::new("mint.params").exists() {
@@ -224,7 +211,7 @@ async fn start(executor: Arc<Executor<'_>>, config: Arc<&DarkfidConfig>) -> Resu
     debug!(target: "fn::start client", "start() Client started");
     client.start().await?;
 
-    let adapter = RpcAdapter::new(wallet.clone())?;
+    let adapter = RpcAdapter::new(wallet.clone(), config.connect_url.clone(), cashier_column)?;
     // start the rpc server
     jsonserver::start(ex.clone(), config.clone(), adapter).await?;
 

+ 2 - 0
src/error.rs

@@ -49,6 +49,7 @@ pub enum Error {
     EmptyPassword,
     TomlDeserializeError(String),
     TomlSerializeError(String),
+    CashierNoReply,
 }
 
 impl std::error::Error for Error {}
@@ -96,6 +97,7 @@ impl fmt::Display for Error {
             Error::EmptyPassword => f.write_str("Password is empty. Cannot create database"),
             Error::TomlDeserializeError(ref err) => write!(f, "Toml parsing error: {}", err),
             Error::TomlSerializeError(ref err) => write!(f, "Toml parsing error: {}", err),
+            Error::CashierNoReply => f.write_str("Cashier did not reply with BTC address"),
         }
     }
 }

+ 25 - 23
src/rpc/adapter.rs

@@ -1,19 +1,35 @@
+use crate::blockchain::{rocks::columns, CashierStore, RocksColumn};
+use crate::service::cashier::CashierClient;
 use crate::wallet::WalletDb;
-use crate::Result;
+use crate::{Error, Result};
 use async_std::sync::Arc;
+use bitcoin::util::address::Address;
 use log::*;
+use std::net::SocketAddr;
 //use std::sync::Arc;
 
 pub type AdapterPtr = Arc<RpcAdapter>;
 // Dummy adapter for now
 pub struct RpcAdapter {
     pub wallet: Arc<WalletDb>,
+    pub client: CashierClient,
+    pub connect_url: String,
 }
 
 impl RpcAdapter {
-    pub fn new(wallet: Arc<WalletDb>) -> Result<Self> {
+    pub fn new(
+        wallet: Arc<WalletDb>,
+        connect_url: String,
+        rocks: RocksColumn<columns::CashierKeys>,
+    ) -> Result<Self> {
         debug!(target: "ADAPTER", "new() [CREATING NEW WALLET]");
-        Ok(Self { wallet })
+        let connect_addr: SocketAddr = connect_url.parse().unwrap();
+        let mut client = CashierClient::new(connect_addr, rocks)?;
+        Ok(Self {
+            wallet,
+            client,
+            connect_url,
+        })
     }
 
     pub fn init_db(&self) -> Result<()> {
@@ -64,30 +80,16 @@ impl RpcAdapter {
         Ok(())
     }
 
-    pub fn deposit(&self) -> Result<()> {
+    pub async fn deposit(&mut self) -> Result<Address> {
         debug!(target: "deposit", "deposit: START");
         let (public, private) = self.wallet.key_gen();
         self.wallet.put_keypair(public, private)?;
-        Ok(())
+        let dkey = self.wallet.get_public()?;
+        match self.client.get_address(dkey).await? {
+            Some(key) => Ok(key),
+            None => Err(Error::CashierNoReply),
+        }
     }
-    //pub async fn walletdb(&self) -> WalletPtr {
-    //    self.wallet.clone();
-    //}
-
-    //pub async fn create_
-    //pub async fn save_key(&self, pubkey: Vec<u8>) -> Result<()> {
-    //    debug!(target: "adapter", "save_key() [START]");
-    //    //let path = WalletDb::path("wallet.db")?;
-    //    //WalletDb::save(path, pubkey).await?;
-    //    Ok(())
-    //}
-
-    //pub async fn save_cash_key(&self, pubkey: Vec<u8>) -> Result<()> {
-    //    debug!(target: "adapter", "save_cash_key() [START]");
-    //    //let path = WalletDb::path("cashier.db")?;
-    //    //WalletDb::save(path, pubkey).await?;
-    //    Ok(())
-    //}
 
     pub fn get_info(&self) {}
 

+ 6 - 2
src/rpc/jsonserver.rs

@@ -244,10 +244,14 @@ impl RpcInterface {
             }
         });
 
-        let self1 = self.clone();
+        let mut self1 = self.clone();
         io.add_method("deposit", move |_| {
             let self2 = self1.clone();
-            async move { Ok(jsonrpc_core::Value::String("Initiating deposit... ".into())) }
+            async move {
+                println!("Deposit initiated");
+                //let btckey = self2.adapter.deposit().await?;
+                Ok(jsonrpc_core::Value::String("Initiating deposit... ".into()))
+            }
         });
 
         io.add_method("transfer", |params: jsonrpc_core::Params| async move {

+ 24 - 12
src/service/cashier.rs

@@ -1,22 +1,22 @@
-use bitcoin::util::address::Address;
-use bitcoin::util::ecdsa::{PrivateKey, PublicKey as BitcoinPubKey};
-use rand::distributions::Alphanumeric;
 use rand::{thread_rng, Rng};
+use rand::distributions::Alphanumeric;
 use secp256k1::key::SecretKey;
+use bitcoin::util::ecdsa::{PrivateKey, PublicKey as BitcoinPubKey};
+use bitcoin::util::address::Address;
 
 use bitcoin::network::constants::Network;
 
+use bitcoin::hash_types::PubkeyHash;
 use super::reqrep::{PeerId, RepProtocol, Reply, ReqProtocol, Request};
-use crate::blockchain::{rocks::columns, CashierKeypair, CashierStore, RocksColumn};
+use crate::blockchain::{rocks::columns, RocksColumn, CashierKeypair, CashierStore};
 use crate::{serial::deserialize, serial::serialize, Error, Result};
-use bitcoin::hash_types::PubkeyHash;
 
 use crate::wallet::{WalletDb, WalletPtr};
 
-use async_executor::Executor;
+use std::net::SocketAddr;
 use async_std::sync::Arc;
+use async_executor::Executor;
 use log::*;
-use std::net::SocketAddr;
 
 #[repr(u8)]
 enum CashierError {
@@ -39,7 +39,10 @@ pub struct BitcoinKeys {
 }
 
 impl BitcoinKeys {
-    pub fn new() -> Result<BitcoinKeys> {
+    pub fn new(
+
+    ) -> Result<BitcoinKeys> {
+
         let context = secp256k1::Secp256k1::new();
 
         // Probably not good enough for release
@@ -90,7 +93,7 @@ impl CashierService {
         addr: SocketAddr,
         rocks: RocksColumn<columns::CashierKeys>,
         wallet: Arc<WalletDb>,
-    ) -> Result<Arc<CashierService>> {
+    )-> Result<Arc<CashierService>> {
         let cashierstore = CashierStore::new(rocks)?;
 
         Ok(Arc::new(CashierService {
@@ -106,8 +109,11 @@ impl CashierService {
 
         let (send, recv) = protocol.start().await?;
 
-        let handle_request_task =
-            executor.spawn(self.handle_request_loop(send.clone(), recv.clone(), executor.clone()));
+        let handle_request_task = executor.spawn(self.handle_request_loop(
+            send.clone(),
+            recv.clone(),
+            executor.clone(),
+        ));
 
         protocol.run(executor.clone()).await?;
 
@@ -126,7 +132,11 @@ impl CashierService {
                 Ok(msg) => {
                     let cashierstore = self.cashierstore.clone();
                     let _ = executor
-                        .spawn(Self::handle_request(msg, cashierstore, send_queue.clone()))
+                        .spawn(Self::handle_request(
+                            msg,
+                            cashierstore,
+                            send_queue.clone(),
+                        ))
                         .detach();
                 }
                 Err(_) => {
@@ -164,6 +174,7 @@ impl CashierService {
                 send_queue.send((peer, reply)).await?;
 
                 info!("Received dkey->btc msg");
+
             }
             1 => {
                 // Withdraw
@@ -221,6 +232,7 @@ impl CashierClient {
     pub fn get_cashierstore(&self) -> Arc<CashierStore> {
         self.cashierstore.clone()
     }
+
 }
 
 fn handle_error(status_code: u32) {