瀏覽代碼

implemented asset_id as hash with hash->u64 conversions

lunar-mining 4 年之前
父節點
當前提交
2273f69965
共有 9 個文件被更改,包括 76 次插入44 次删除
  1. 3 1
      src/bin/cashierd.rs
  2. 17 13
      src/bin/drk.rs
  3. 2 2
      src/cli/drk_cli.rs
  4. 1 0
      src/cli/mod.rs
  5. 6 3
      src/client/client.rs
  6. 20 14
      src/rpc/adapters/client_adapter.rs
  7. 0 2
      src/service/bridge.rs
  8. 23 9
      src/service/cashier.rs
  9. 4 0
      src/util.rs

+ 3 - 1
src/bin/cashierd.rs

@@ -46,7 +46,9 @@ async fn start(executor: Arc<Executor<'_>>, config: Arc<CashierdConfig>) -> Resu
     )
     .await?;
 
-    cashier.start(ex.clone(), btc_endpoint).await?;
+    let dummy_asset = Vec::new();
+
+    cashier.start(ex.clone(), btc_endpoint, dummy_asset).await?;
 
     //let rpc_url: std::net::SocketAddr = config.rpc_url.parse()?;
     //let adapter = Arc::new(CashierAdapter::new(wallet.clone())?);

+ 17 - 13
src/bin/drk.rs

@@ -2,10 +2,10 @@ use std::path::PathBuf;
 
 use serde_json::json;
 
-use drk::serial::serialize;
-use drk::cli::{Config, DrkCli, DrkConfig};
+use drk::cli::{Asset, Config, DrkCli, DrkConfig};
 use drk::rpc::jsonrpc;
 use drk::rpc::jsonrpc::JsonResult;
+use drk::serial::serialize;
 use drk::util::join_config_path;
 use drk::{Error, Result};
 
@@ -81,20 +81,20 @@ impl Drk {
         Ok(self.request("stop", r).await?)
     }
 
-    pub async fn deposit(&self) -> Result<()> {
-        let r = jsonrpc::request(json!("deposit"), json!([]));
-        Ok(self.request("deposit BTC to this address:", r).await?)
+    pub async fn deposit(&self, asset: Asset) -> Result<()> {
+        let r = jsonrpc::request(json!("deposit"), json!([asset]));
+        Ok(self.request("deposit coins to this address:", r).await?)
     }
 
-    pub async fn transfer(&self, address: String, amount: f64) -> Result<()> {
+    pub async fn transfer(&self, asset: Asset, address: String, amount: f64) -> Result<()> {
         let address = serialize(&address);
-        let r = jsonrpc::request(json!("transfer"), json!([address, amount]));
+        let r = jsonrpc::request(json!("transfer"), json!([asset, address, amount]));
         Ok(self.request("transfer", r).await?)
     }
 
-    pub async fn withdraw(&self, address: String, amount: f64) -> Result<()> {
+    pub async fn withdraw(&self, asset: Asset, address: String, amount: f64) -> Result<()> {
         let address = serialize(&address);
-        let r = jsonrpc::request(json!("withdraw"), json!([address, amount]));
+        let r = jsonrpc::request(json!("withdraw"), json!([asset, address, amount]));
         Ok(self.request("withdraw", r).await?)
     }
 }
@@ -124,15 +124,19 @@ async fn start(config: &DrkConfig, options: DrkCli) -> Result<()> {
     }
 
     if let Some(transfer) = options.transfer {
-        client.transfer(transfer.pub_key, transfer.amount).await?;
+        client
+            .transfer(transfer.asset, transfer.pub_key, transfer.amount)
+            .await?;
     }
 
-    if let Some(_deposit) = options.deposit {
-        client.deposit().await?;
+    if let Some(deposit) = options.deposit {
+        client.deposit(deposit.asset).await?;
     }
 
     if let Some(withdraw) = options.withdraw {
-        client.withdraw(withdraw.pub_key, withdraw.amount).await?;
+        client
+            .withdraw(withdraw.asset, withdraw.pub_key, withdraw.amount)
+            .await?;
     }
 
     if options.stop {

+ 2 - 2
src/cli/drk_cli.rs

@@ -3,7 +3,7 @@ use crate::Result;
 
 use blake2b_simd::Params;
 use clap::{App, Arg};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
 
 use crate::serial;
 use std::path::PathBuf;
@@ -62,7 +62,7 @@ impl WithdrawParams {
     }
 }
 
-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Serialize, Debug)]
 pub struct Asset {
     pub ticker: String,
     pub id: Vec<u8>,

+ 1 - 0
src/cli/mod.rs

@@ -7,6 +7,7 @@ pub mod gatewayd_cli;
 pub use cashierd_cli::CashierdCli;
 pub use cli_config::{CashierdConfig, Config, DarkfidConfig, DrkConfig, GatewaydConfig};
 pub use darkfid_cli::DarkfidCli;
+pub use drk_cli::Asset;
 pub use drk_cli::DrkCli;
 pub use drk_cli::{TransferParams, WithdrawParams};
 pub use gatewayd_cli::GatewaydCli;

+ 6 - 3
src/client/client.rs

@@ -13,6 +13,7 @@ use crate::serial::Decodable;
 use crate::serial::Encodable;
 use crate::service::{CashierClient, GatewayClient, GatewaySlabsSubscriber};
 use crate::state::{state_transition, ProgramState, StateUpdate};
+use crate::util::hash_to_u64;
 use crate::wallet::{CashierDbPtr, WalletPtr};
 use crate::{tx, Result};
 
@@ -126,7 +127,7 @@ impl Client {
 
     pub async fn transfer(
         self: &mut Self,
-        asset_id: u64,
+        asset_id: Vec<u8>,
         pub_key: jubjub::SubgroupPoint,
         amount: f64,
     ) -> Result<()> {
@@ -144,7 +145,7 @@ impl Client {
         self: &mut Self,
         pub_key: jubjub::SubgroupPoint,
         amount: u64,
-        asset_id: u64,
+        asset_id: Vec<u8>,
         clear_input: bool,
     ) -> Result<()> {
         let slab = self.build_slab_from_tx(
@@ -163,13 +164,15 @@ impl Client {
         &self,
         pub_key: jubjub::SubgroupPoint,
         amount: u64,
-        asset_id: u64,
+        asset_id: Vec<u8>,
         clear_input: bool,
     ) -> Result<Slab> {
         let mut clear_inputs: Vec<tx::TransactionBuilderClearInputInfo> = vec![];
         let mut inputs: Vec<tx::TransactionBuilderInputInfo> = vec![];
         let mut outputs: Vec<tx::TransactionBuilderOutputInfo> = vec![];
 
+        let asset_id = hash_to_u64(asset_id);
+
         if clear_input {
             let cashier_secret = self.state.wallet.get_private_keys()?[0];
             let input = tx::TransactionBuilderClearInputInfo {

+ 20 - 14
src/rpc/adapters/client_adapter.rs

@@ -1,3 +1,4 @@
+use crate::cli::Asset;
 use crate::client::{Client, ClientFailed};
 use crate::serial::{deserialize, serialize, Decodable};
 use crate::service::CashierClient;
@@ -31,15 +32,15 @@ pub trait RpcClient {
 
     /// transfer
     #[rpc(name = "transfer")]
-    fn transfer(&self, asset_id: u64, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>>;
+    fn transfer(&self, asset: Asset, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>>;
 
     /// withdraw
     #[rpc(name = "withdraw")]
-    fn withdraw(&self, asset_id: u64, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>>;
+    fn withdraw(&self, asset: Asset, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>>;
 
     /// deposit
     #[rpc(name = "deposit")]
-    fn deposit(&self, asset_id: u64) -> BoxFuture<Result<String>>;
+    fn deposit(&self, asset: Asset) -> BoxFuture<Result<String>>;
 }
 
 pub struct RpcClientAdapter {
@@ -75,7 +76,7 @@ impl RpcClientAdapter {
 
     async fn transfer_process(
         client: Arc<Mutex<Client>>,
-        asset_id: u64,
+        asset: Asset,
         address: Vec<u8>,
         amount: f64,
     ) -> Result<String> {
@@ -90,7 +91,7 @@ impl RpcClientAdapter {
         client
             .lock()
             .await
-            .transfer(asset_id, address.clone(), amount)
+            .transfer(asset.id, address.clone(), amount)
             .await?;
 
         Ok(format!("transfered {} DRK to {}", amount, address))
@@ -99,14 +100,14 @@ impl RpcClientAdapter {
     async fn withdraw_process(
         client: Arc<Mutex<Client>>,
         cashier_client: Arc<Mutex<CashierClient>>,
-        asset_id: u64,
+        asset: Asset,
         address: Vec<u8>,
         amount: f64,
     ) -> Result<String> {
         let drk_public = cashier_client
             .lock()
             .await
-            .withdraw(asset_id, address)
+            .withdraw(asset.id.clone(), address)
             .await
             .map_err(|err| ClientFailed::from(err))?;
 
@@ -114,7 +115,7 @@ impl RpcClientAdapter {
             client
                 .lock()
                 .await
-                .transfer(asset_id, drk_addr.clone(), amount)
+                .transfer(asset.id.clone(), drk_addr.clone(), amount)
                 .await?;
 
             return Ok(format!(
@@ -129,7 +130,7 @@ impl RpcClientAdapter {
     async fn deposit_process<T>(
         client: Arc<Mutex<Client>>,
         cashier_client: Arc<Mutex<CashierClient>>,
-        asset_id: u64,
+        asset: Asset,
     ) -> Result<String>
     where
         T: Decodable + ToString,
@@ -138,7 +139,7 @@ impl RpcClientAdapter {
         let coin_public = cashier_client
             .lock()
             .await
-            .get_address(asset_id, deposit_addr)
+            .get_address(asset.id, deposit_addr)
             .await
             .map_err(|err| ClientFailed::from(err))?;
 
@@ -172,12 +173,17 @@ impl RpcClient for RpcClientAdapter {
         Self::key_gen_process(self.client.clone()).boxed()
     }
 
-    fn transfer(&self, asset_id: u64, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>> {
+    fn transfer(&self, asset: Asset, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>> {
         debug!(target: "RPC USER ADAPTER", "transfer() [START]");
-        Self::transfer_process(self.client.clone(), asset_id, pub_key, amount).boxed()
+        Self::transfer_process(self.client.clone(), asset, pub_key, amount).boxed()
     }
 
-    fn withdraw(&self, asset_id: u64, pub_key: Vec<u8>, amount: f64) -> BoxFuture<Result<String>> {
+    fn withdraw(
+        &self,
+        asset_id: Asset,
+        pub_key: Vec<u8>,
+        amount: f64,
+    ) -> BoxFuture<Result<String>> {
         debug!(target: "RPC USER ADAPTER", "withdraw() [START]");
         Self::withdraw_process(
             self.client.clone(),
@@ -189,7 +195,7 @@ impl RpcClient for RpcClientAdapter {
         .boxed()
     }
 
-    fn deposit(&self, asset_id: u64) -> BoxFuture<Result<String>> {
+    fn deposit(&self, asset_id: Asset) -> BoxFuture<Result<String>> {
         debug!(target: "RPC USER ADAPTER", "deposit() [START]");
         #[cfg(feature = "default")]
         Self::deposit_process::<bitcoin::PublicKey>(

+ 0 - 2
src/service/bridge.rs

@@ -97,5 +97,3 @@ pub trait CoinClient {
     async fn watch(&self) -> Result<(Vec<u8>, Vec<u8>)>;
     async fn send(&self, address: Vec<u8>, amount: u64) -> Result<()>;
 }
-
-

+ 23 - 9
src/service/cashier.rs

@@ -3,6 +3,7 @@ use super::reqrep::{PeerId, RepProtocol, Reply, ReqProtocol, Request};
 use crate::blockchain::Rocks;
 use crate::client::Client;
 use crate::serial::{deserialize, serialize};
+use crate::util::hash_to_u64;
 use crate::wallet::{CashierDbPtr, WalletPtr};
 use crate::{Error, Result};
 
@@ -60,6 +61,7 @@ impl CashierService {
         &mut self,
         executor: Arc<Executor<'_>>,
         client_address: String,
+        asset_id: Vec<u8>,
     ) -> Result<()> {
         debug!(target: "CASHIER DAEMON", "Start Cashier");
         let service_name = String::from("CASHIER DAEMON");
@@ -74,10 +76,15 @@ impl CashierService {
 
         let bridge = bridge::Bridge::new();
 
+        let asset_id = hash_to_u64(asset_id);
+
         #[cfg(feature = "default")]
         let btc_client = super::btc::BtcClient::new(client_address)?;
         #[cfg(feature = "default")]
-        bridge.clone().add_clients(1, Arc::new(btc_client)).await;
+        bridge
+            .clone()
+            .add_clients(asset_id, Arc::new(btc_client))
+            .await;
 
         let handle_request_task = executor.spawn(Self::handle_request_loop(
             send.clone(),
@@ -114,7 +121,7 @@ impl CashierService {
                     // send equivalent amount of coin to this address
                     bridge_subscribtion.sender.send(
                         bridge::BridgeRequests {
-                            asset_id: 1,
+                            asset_id,
                             payload: bridge::BridgeRequestsPayload::SendRequest(addr.clone(), amount)
                         }
                     ).await.expect("send request to bridge");
@@ -149,11 +156,16 @@ impl CashierService {
         Ok(())
     }
 
-    async fn _mint_coin(&mut self, dkey_pub: jubjub::SubgroupPoint, value: u64) -> Result<()> {
+    async fn _mint_coin(
+        &mut self,
+        dkey_pub: jubjub::SubgroupPoint,
+        value: u64,
+        asset_id: Vec<u8>,
+    ) -> Result<()> {
         self.client
             .lock()
             .await
-            .send(dkey_pub, value, 1, true)
+            .send(dkey_pub, value, asset_id, true)
             .await?;
         Ok(())
     }
@@ -199,12 +211,14 @@ impl CashierService {
             0 => {
                 debug!(target: "CASHIER DAEMON", "Received deposit request");
                 // Exchange zk_pubkey for bitcoin address
-                let (asset_id, dpub): (u64, jubjub::SubgroupPoint) = deserialize(&request.get_payload())?;
+                let (asset_id, dpub): (Vec<u8>, jubjub::SubgroupPoint) =
+                    deserialize(&request.get_payload())?;
 
                 //TODO: check if key has already been issued
                 let _check =
                     cashier_wallet.get_deposit_coin_keys_by_dkey_public(&dpub, &serialize(&1));
 
+                let asset_id = hash_to_u64(asset_id);
                 bridge_subscribtion
                     .sender
                     .send(bridge::BridgeRequests {
@@ -249,8 +263,8 @@ impl CashierService {
 
                 let cashier_public: jubjub::SubgroupPoint;
 
-                if let Some(addr) = cashier_wallet
-                    .get_withdraw_keys_by_coin_public_key(&coin_address, &asset_id)?
+                if let Some(addr) =
+                    cashier_wallet.get_withdraw_keys_by_coin_public_key(&coin_address, &asset_id)?
                 {
                     cashier_public = addr.0;
                 } else {
@@ -300,7 +314,7 @@ impl CashierClient {
 
     pub async fn withdraw(
         &mut self,
-        asset_id: u64,
+        asset_id: Vec<u8>,
         coin_address: Vec<u8>,
     ) -> Result<Option<jubjub::SubgroupPoint>> {
         let handle_error = Arc::new(handle_error);
@@ -322,7 +336,7 @@ impl CashierClient {
 
     pub async fn get_address(
         &mut self,
-        asset_id: u64,
+        asset_id: Vec<u8>,
         index: jubjub::SubgroupPoint,
     ) -> Result<Option<Vec<u8>>> {
         let handle_error = Arc::new(handle_error);

+ 4 - 0
src/util.rs

@@ -17,3 +17,7 @@ pub fn join_config_path(file: &PathBuf) -> Result<PathBuf> {
 
     Ok(path)
 }
+
+pub fn hash_to_u64(asset_id: Vec<u8>) -> u64 {
+    asset_id.iter().fold(0, |x, &i| x << 8 | i as u64)
+}