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

bin/dao: Change MoneyWallets to be a HashMap<PublicKey, MoneyWallet>

Dastan-glitch 3 лет назад
Родитель
Сommit
1f682611c6

+ 13 - 14
bin/dao/dao-cli/run_demo.sh

@@ -7,36 +7,35 @@ echo $addr3
 
 cargo run mint 1000000 $addr3
 
-alice=$(cargo run keygen alice)
-alice=$(cargo run keygen alice | cut -d " " -f 4)
+alice=$(cargo run keygen)
+alice=$(cargo run keygen | cut -d " " -f 4)
 alice2=$(echo $alice | cut -c 2-)
 alice3=${alice2::-1}
 echo $alice3
 
-bob=$(cargo run keygen bob)
-bob=$(cargo run keygen bob | cut -d " " -f 4)
+bob=$(cargo run keygen)
+bob=$(cargo run keygen | cut -d " " -f 4)
 bob2=$(echo $bob | cut -c 2-)
 bob3=${bob2::-1}
 echo $bob3
 
-charlie=$(cargo run keygen charlie)
-charlie=$(cargo run keygen charlie | cut -d " " -f 4)
+charlie=$(cargo run keygen)
+charlie=$(cargo run keygen | cut -d " " -f 4)
 charlie2=$(echo $charlie | cut -c 2-)
 charlie3=${charlie2::-1}
 echo $charlie3
 
-cargo run airdrop alice 10000
-cargo run airdrop bob 100000
-cargo run airdrop charlie 10000
+cargo run airdrop $alice3 10000
+cargo run airdrop $bob3 100000
+cargo run airdrop $charlie3 10000
 
-proposal=$(cargo run propose alice $charlie3 10000 | cut -d " " -f 3)
+proposal=$(cargo run propose $alice3 $charlie3 10000 | cut -d " " -f 3)
 proposal2=$(echo $proposal | cut -c 2-)
 proposal3=${proposal2::-1}
 echo $proposal3
 
-cargo run vote alice yes
-cargo run vote bob yes
-cargo run vote charlie no
+cargo run vote $alice3 yes
+cargo run vote $bob3 yes
+cargo run vote $charlie3 no
 
 cargo run exec $proposal3
-

+ 3 - 5
bin/dao/dao-cli/src/main.rs

@@ -40,9 +40,7 @@ pub enum CliDaoSubCommands {
     },
     DaoBalance {},
     DaoBulla {},
-    Keygen {
-        nym: String,
-    },
+    Keygen {},
     /// Airdrop tokens
     Airdrop {
         nym: String,
@@ -126,8 +124,8 @@ async fn start(options: CliDao) -> Result<()> {
             println!("{}", &reply.as_str().unwrap().to_string());
             return Ok(())
         }
-        Some(CliDaoSubCommands::Keygen { nym }) => {
-            let reply = client.keygen(nym).await?;
+        Some(CliDaoSubCommands::Keygen {}) => {
+            let reply = client.keygen().await?;
             println!("User public key: {}", &reply.to_string());
             return Ok(())
         }

+ 2 - 2
bin/dao/dao-cli/src/rpc.rs

@@ -49,8 +49,8 @@ impl Rpc {
 
     // --> {"jsonrpc": "2.0", "method": "airdrop", "params": [], "id": 42}
     // <-- {"jsonrpc": "2.0", "result": "airdropping tokens...", "id": 42}
-    pub async fn keygen(&self, nym: String) -> Result<Value> {
-        let req = JsonRequest::new("keygen", json!([nym]));
+    pub async fn keygen(&self) -> Result<Value> {
+        let req = JsonRequest::new("keygen", json!([]));
         self.client.request(req).await
     }
 

+ 15 - 21
bin/dao/daod/src/main.rs

@@ -164,7 +164,7 @@ use crate::{
 
 pub struct Client {
     dao_wallet: DaoWallet,
-    money_wallets: HashMap<String, MoneyWallet>,
+    money_wallets: FxHashMap<PublicKey, MoneyWallet>,
     cashier_wallet: CashierWallet,
     states: StateRegistry,
     zk_bins: ZkContractTable,
@@ -174,7 +174,7 @@ impl Client {
     fn new() -> Self {
         // For this early demo we store all wallets in a single Client.
         let dao_wallet = DaoWallet::new();
-        let money_wallets = HashMap::default();
+        let money_wallets = FxHashMap::default();
         let cashier_wallet = CashierWallet::new();
 
         // Lookup table for smart contract states
@@ -245,16 +245,10 @@ impl Client {
         Ok(())
     }
 
-    // Strictly for demo purposes.
-    fn new_money_wallet(&mut self, key: String) {
-        let keypair = Keypair::random(&mut OsRng);
-        let signature_secret = SecretKey::random(&mut OsRng);
-        let own_coins: Vec<(OwnCoin, bool)> = Vec::new();
-        let money_wallet = MoneyWallet { keypair, signature_secret, own_coins };
-        money_wallet.track(&mut self.states);
+    // // Strictly for demo purposes.
+    // fn new_money_wallet(&mut self) {
 
-        self.money_wallets.insert(key.clone(), money_wallet);
-    }
+    // }
 
     fn create_dao(
         &mut self,
@@ -324,9 +318,9 @@ impl Client {
         Ok(())
     }
 
-    fn airdrop_user(&mut self, value: u64, token_id: pallas::Base, nym: String) -> Result<()> {
-        let wallet = self.money_wallets.get(&nym).unwrap();
-        let addr = wallet.get_public_key();
+    fn airdrop_user(&mut self, value: u64, token_id: pallas::Base, addr: PublicKey) -> Result<()> {
+        // let wallet = self.money_wallets.get(&nym).unwrap();
+        // let addr = wallet.get_public_key();
 
         let tx = self.cashier_wallet.airdrop(value, token_id, addr, &self.zk_bins).unwrap();
         self.validate(&tx).unwrap();
@@ -444,7 +438,7 @@ impl Client {
         recipient: PublicKey,
         token_id: pallas::Base,
         amount: u64,
-        sender: String,
+        sender: PublicKey,
     ) -> Result<pallas::Base> {
         let params = self.dao_wallet.params[0].clone();
 
@@ -473,18 +467,18 @@ impl Client {
         Ok(proposal_bulla)
     }
 
-    fn get_addr_from_nym(&self, nym: String) -> Result<PublicKey> {
-        let wallet = self.money_wallets.get(&nym).unwrap();
-        Ok(wallet.get_public_key())
-    }
+    // fn get_addr_from_nym(&self, nym: String) -> Result<PublicKey> {
+    //     let wallet = self.money_wallets.get(&nym).unwrap();
+    //     Ok(wallet.get_public_key())
+    // }
 
-    fn cast_vote(&mut self, nym: String, vote: bool) -> Result<()> {
+    fn cast_vote(&mut self, pubkey: PublicKey, vote: bool) -> Result<()> {
         let dao_key = self.dao_wallet.keypair;
         let proposal = self.dao_wallet.proposals[0].clone();
         let dao_params = self.dao_wallet.params[0].clone();
         let dao_keypair = self.dao_wallet.keypair;
 
-        let mut voter_wallet = self.money_wallets.get_mut(&nym).unwrap();
+        let mut voter_wallet = self.money_wallets.get_mut(&pubkey).unwrap();
 
         let tx = voter_wallet
             .vote_tx(

+ 25 - 14
bin/dao/daod/src/rpc.rs

@@ -152,9 +152,11 @@ impl JsonRpcInterface {
 
     async fn user_balance(&self, id: Value, params: &[Value]) -> JsonResult {
         let mut client = self.client.lock().await;
-        let nym = params[0].as_str().unwrap().to_string();
+        let nym = params[0].as_str().unwrap();
 
-        let wallet = client.money_wallets.get(&nym).unwrap();
+        let pubkey = PublicKey::from_str(nym).unwrap();
+
+        let wallet = client.money_wallets.get(&pubkey).unwrap();
         let balance = wallet.balances().unwrap();
         JsonResponse::new(json!(balance), id).into()
     }
@@ -173,16 +175,22 @@ impl JsonRpcInterface {
     }
 
     // Create a new wallet for governance tokens.
-    async fn keygen(&self, id: Value, params: &[Value]) -> JsonResult {
+    async fn keygen(&self, id: Value, _params: &[Value]) -> JsonResult {
         let mut client = self.client.lock().await;
-        let nym = params[0].as_str().unwrap().to_string();
+        // let nym = params[0].as_str().unwrap().to_string();
 
-        client.new_money_wallet(nym.clone());
+        let keypair = Keypair::random(&mut OsRng);
+        let signature_secret = SecretKey::random(&mut OsRng);
+        let own_coins: Vec<(OwnCoin, bool)> = Vec::new();
+        let money_wallet = MoneyWallet { keypair, signature_secret, own_coins };
+        money_wallet.track(&mut client.states);
 
-        let wallet = client.money_wallets.get(&nym).unwrap();
-        let pubkey = wallet.get_public_key();
+        client.money_wallets.insert(keypair.public, money_wallet);
 
-        let addr: String = bs58::encode(pubkey.to_bytes()).into_string();
+        // let wallet = client.money_wallets.get(&nym).unwrap();
+        // let pubkey = wallet.get_public_key();
+
+        let addr: String = bs58::encode(keypair.public.to_bytes()).into_string();
         JsonResponse::new(json!(addr), id).into()
     }
 
@@ -192,10 +200,10 @@ impl JsonRpcInterface {
         let mut client = self.client.lock().await;
         let zk_bins = &client.zk_bins;
 
-        let nym = params[0].as_str().unwrap().to_string();
+        let addr = PublicKey::from_str(params[0].as_str().unwrap()).unwrap();
         let value = params[1].as_u64().unwrap();
 
-        client.airdrop_user(value, *GOV_ID, nym.clone()).unwrap();
+        client.airdrop_user(value, *GOV_ID, addr).unwrap();
 
         JsonResponse::new(json!("Tokens airdropped successfully."), id).into()
     }
@@ -204,13 +212,14 @@ impl JsonRpcInterface {
     async fn create_proposal(&self, id: Value, params: &[Value]) -> JsonResult {
         let mut client = self.client.lock().await;
 
-        let sender = params[0].as_str().unwrap().to_string();
+        let sender = params[0].as_str().unwrap();
         let recipient = params[1].as_str().unwrap();
         let amount = params[2].as_u64().unwrap();
 
         let recv_addr = PublicKey::from_str(recipient).unwrap();
+        let sndr_addr = PublicKey::from_str(sender).unwrap();
 
-        let proposal_bulla = client.propose(recv_addr, *DRK_ID, amount, sender).unwrap();
+        let proposal_bulla = client.propose(recv_addr, *DRK_ID, amount, sndr_addr).unwrap();
         let bulla: String = bs58::encode(proposal_bulla.to_repr()).into_string();
 
         JsonResponse::new(json!(bulla), id).into()
@@ -220,9 +229,11 @@ impl JsonRpcInterface {
     async fn vote(&self, id: Value, params: &[Value]) -> JsonResult {
         let mut client = self.client.lock().await;
 
-        let nym = params[0].as_str().unwrap().to_string();
+        let addr = params[0].as_str().unwrap();
         let vote_str = params[1].as_str().unwrap();
 
+        let addr = PublicKey::from_str(addr).unwrap();
+
         // This would be cleaner as a match statement,
         // but we need to sort out error handling first.
         let mut vote_bool = true;
@@ -232,7 +243,7 @@ impl JsonRpcInterface {
             vote_bool = false
         }
 
-        client.cast_vote(nym, vote_bool).unwrap();
+        client.cast_vote(addr, vote_bool).unwrap();
         JsonResponse::new(json!("Vote cast successfully."), id).into()
     }
     // --> {"method": "execute", "params": []}

+ 13 - 1
src/crypto/keypair.rs

@@ -1,4 +1,9 @@
-use std::{convert::TryFrom, io, str::FromStr};
+use std::{
+    convert::TryFrom,
+    hash::{Hash, Hasher},
+    io,
+    str::FromStr,
+};
 
 use halo2_gadgets::ecc::chip::FixedPoint;
 use pasta_curves::{
@@ -93,6 +98,13 @@ impl PublicKey {
     }
 }
 
+impl Hash for PublicKey {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        let bytes = self.0.to_affine().to_bytes();
+        bytes.hash(state);
+    }
+}
+
 impl FromStr for PublicKey {
     type Err = crate::Error;