Sfoglia il codice sorgente

drk: Introduce SQL schema for Deployooor contract

parazyd 2 anni fa
parent
commit
f011b02336
5 ha cambiato i file con 97 aggiunte e 12 eliminazioni
  1. 4 1
      bin/drk/Makefile
  2. 7 0
      bin/drk/deploy.sql
  3. 65 0
      bin/drk/src/deploy.rs
  4. 15 11
      bin/drk/src/main.rs
  5. 6 0
      src/sdk/src/crypto/contract_id.rs

+ 4 - 1
bin/drk/Makefile

@@ -27,6 +27,9 @@ $(BIN): $(SRC)
 	cp -f ../../target/$(RUST_TARGET)/release/$@ $@
 	cp -f ../../target/$(RUST_TARGET)/release/$@ ../../$@
 
+clippy: all
+	RUSTFLAGS="$(RUSTFLAGS)" $(CARGO) clippy --target=$(RUST_TARGET) --release --package $(BIN) --tests
+
 clean:
 	RUSTFLAGS="$(RUSTFLAGS)" $(CARGO) clean --target=$(RUST_TARGET) --release --package $(BIN)
 	rm -f $(BIN) ../../$(BIN)
@@ -39,4 +42,4 @@ install: all
 uninstall:
 	rm -f $(DESTDIR)$(PREFIX)/bin/$(BIN)
 
-.PHONY: all clean install uninstall
+.PHONY: all clippy clean install uninstall

+ 7 - 0
bin/drk/deploy.sql

@@ -0,0 +1,7 @@
+-- Wallet definition for Deployooor contractt
+-- Native Contract ID: EJs7oEjKkvCeEVCmpRsd6fEoTGCFJ7WKUBfmAjwaegN
+
+CREATE TABLE IF NOT EXISTS EJs7oEjKkvCeEVCmpRsd6fEoTGCFJ7WKUBfmAjwaegN_deploy_auth (
+	deploy_authority BLOB PRIMARY KEY NOT NULL,
+	is_frozen INTEGER NOT NULL
+);

+ 65 - 0
bin/drk/src/deploy.rs

@@ -0,0 +1,65 @@
+/* This file is part of DarkFi (https://dark.fi)
+ *
+ * Copyright (C) 2020-2024 Dyne.org foundation
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+use lazy_static::lazy_static;
+use rand::rngs::OsRng;
+
+use darkfi_sdk::crypto::{ContractId, Keypair, DEPLOYOOOR_CONTRACT_ID};
+use darkfi_serial::serialize_async;
+
+use crate::{error::WalletDbResult, Drk};
+
+// Wallet SQL table constant names. These have to represent the `wallet.sql`
+// SQL schema. Table names are prefixed with the contract ID to avoid collisions.
+lazy_static! {
+    pub static ref DEPLOY_AUTH_TABLE: String =
+        format!("{}_deploy_auth", DEPLOYOOOR_CONTRACT_ID.to_string());
+}
+
+// DEPLOY_AUTH_TABLE
+pub const DEPLOY_AUTH_COL_DEPLOY_AUTHORITY: &str = "deploy_authority";
+pub const DEPLOY_AUTH_COL_IS_FROZEN: &str = "is_frozen";
+
+impl Drk {
+    /// Initialize wallet with tables for the Deployooor contract.
+    pub async fn initialize_deployooor(&self) -> WalletDbResult<()> {
+        // Initialize Deployooor wallet schema
+        let wallet_schema = include_str!("../deploy.sql");
+        self.wallet.exec_batch_sql(wallet_schema).await?;
+
+        Ok(())
+    }
+
+    /// Generate a new deploy authority keypair and place it into the wallet
+    pub async fn deploy_auth_keygen(&self) -> WalletDbResult<()> {
+        eprintln!("Generating a new keypair");
+
+        let keypair = Keypair::random(&mut OsRng);
+
+        let query = format!(
+            "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
+            *DEPLOY_AUTH_TABLE, DEPLOY_AUTH_COL_DEPLOY_AUTHORITY, DEPLOY_AUTH_COL_IS_FROZEN,
+        );
+        self.wallet.exec_sql(&query, rusqlite::params![serialize_async(&keypair).await, 0]).await?;
+
+        eprintln!("Created new contract deploy authority");
+        println!("Contract ID: {}", ContractId::derive_public(keypair.public));
+
+        Ok(())
+    }
+}

+ 15 - 11
bin/drk/src/main.rs

@@ -45,7 +45,7 @@ use darkfi::{
 };
 use darkfi_money_contract::model::{Coin, TokenId};
 use darkfi_sdk::{
-    crypto::{ContractId, FuncId, PublicKey, SecretKey},
+    crypto::{FuncId, PublicKey, SecretKey},
     pasta::{group::ff::PrimeField, pallas},
     tx::TransactionHash,
 };
@@ -79,6 +79,9 @@ use money::BALANCE_BASE10_DECIMALS;
 mod dao;
 use dao::DaoParams;
 
+/// Wallet functionality related to Deployooor
+mod deploy;
+
 /// Wallet functionality related to transactions history
 mod txs_history;
 
@@ -617,6 +620,10 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
                     eprintln!("Failed to initialize DAO: {e:?}");
                     exit(2);
                 }
+                if let Err(e) = drk.initialize_deployooor().await {
+                    eprintln!("Failed to initialize Deployooor: {e:?}");
+                    exit(2);
+                }
                 return Ok(())
             }
 
@@ -1644,16 +1651,13 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
 
         Subcmd::Contract { command } => match command {
             ContractSubcmd::GenerateDeploy => {
-                let deploy_authority = SecretKey::random(&mut OsRng);
-                let contract_id = ContractId::derive(deploy_authority);
-                println!(
-                    "Deploy authority: {}",
-                    bs58::encode(deploy_authority.inner().to_repr()).into_string()
-                );
-                println!(
-                    "Contract ID: {}",
-                    bs58::encode(&contract_id.inner().to_repr()).into_string()
-                );
+                let drk = Drk::new(args.wallet_path, args.wallet_pass, args.endpoint, ex).await?;
+
+                if let Err(e) = drk.deploy_auth_keygen().await {
+                    eprintln!("Error creating deploy auth keypair: {:?}", e);
+                    exit(1);
+                }
+
                 Ok(())
             }
         },

+ 6 - 0
src/sdk/src/crypto/contract_id.rs

@@ -35,14 +35,20 @@ lazy_static! {
     pub static ref CONTRACT_ID_PREFIX: pallas::Base = pallas::Base::from(42);
 
     /// Contract ID for the native money contract
+    ///
+    /// `BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o`
     pub static ref MONEY_CONTRACT_ID: ContractId =
         ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(0)]));
 
     /// Contract ID for the native DAO contract
+    ///
+    /// `Fd8kfCuqU8BoFFp6GcXv5pC8XXRkBK7gUPQX5XDz7iXj`
     pub static ref DAO_CONTRACT_ID: ContractId =
         ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(1)]));
 
     /// Contract ID for the native Deployooor contract
+    ///
+    /// `EJs7oEjKkvCeEVCmpRsd6fEoTGCFJ7WKUBfmAjwaegN`
     pub static ref DEPLOYOOOR_CONTRACT_ID: ContractId =
         ContractId::from(poseidon_hash([*CONTRACT_ID_PREFIX, pallas::Base::zero(), pallas::Base::from(2)]));
 }