Skip to content

Commit

Permalink
Improve SP CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
xevisalle committed Nov 20, 2023
1 parent 97546c0 commit fdab630
Show file tree
Hide file tree
Showing 11 changed files with 68 additions and 40 deletions.
21 changes: 15 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,31 @@ cargo t --release --features="int_tests" -- --test-threads=1
## Usage

The moat-cli utility can be used from the POV of any of the parties involved in the Citadel protocol, let them be:
- **License Provider (LP):** A party receiving onchain requests from users to issue licenses onchain addressed to them.
- **User:** A party requesting licenses onchain to LPs, and being able to use the licenses onchain as well.
- **License Provider (LP):** A party receiving onchain requests from users to issue licenses onchain addressed to them.
- **Service Provider (SP):** A party receiving offchain requests from users to grant services.


### User

Users can request licenses and use them. To run the user CLI, simply run:

```sh
cargo r --release --bin moat-cli-user -- --wallet-path ~/.dusk/rusk-wallet --wallet-pass <PASSWORD>
```

### License Provider

LPs can then scan the Blockchain for requests and issue licenses if the requests are valid. To run the LP CLI, simply run:
LPs can scan the Blockchain for requests and issue licenses if the requests are valid. To run the LP CLI, simply run:

```sh
cargo r --release --bin moat-cli-lp -- --wallet-path ~/.dusk/rusk-wallet --wallet-pass <PASSWORD>
```

### User
### Service Provider

Users can request licenses and use them. To run the user CLI, simply run:
SPs can get requests from users to grant their services, and accept or deny them by checking if the session cookies provided by the users are valid. To run the SP CLI, simply run:

```sh
cargo r --release --bin moat-cli-user -- --wallet-path ~/.dusk/rusk-wallet --wallet-pass <PASSWORD>
cargo r --release --bin moat-cli-sp -- --wallet-path ~/.dusk/rusk-wallet --wallet-pass <PASSWORD>
```

1 change: 1 addition & 0 deletions moat-cli-sp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ reqwest = "0.11"
bytecheck = "0.6"
sha3 = "0.10"
thiserror = "1.0"
bs58 = "0.4"
4 changes: 2 additions & 2 deletions moat-cli-sp/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ pub struct Args {
pub wallet_path: PathBuf,

/// Blockchain access config directory
#[clap(short, long)]
#[clap(short, long, default_value = "./config.toml")]
pub config_path: PathBuf,

/// Password for the wallet
#[clap(long, default_value_t = String::from(""), env = "RUSK_WALLET_PWD")]
pub password: String,
pub wallet_pass: String,

/// Hash of the password for the wallet [default: ``]
#[clap(short, long, default_value_t = String::from(""))]
Expand Down
36 changes: 18 additions & 18 deletions moat-cli-sp/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use crate::config::SPCliConfig;
use crate::run_result::{
LicenseContractSummary, RunResult, ServiceRequestSummery, SessionSummary,
};
Expand All @@ -13,6 +12,7 @@ use dusk_bls12_381::BlsScalar;
use dusk_bytes::DeserializableSlice;
use dusk_jubjub::JubJubAffine;
use dusk_pki::PublicSpendKey;
use dusk_bytes::Serializable;
use dusk_wallet::RuskHttpClient;
use moat_core::{CitadelInquirer, LicenseSessionId};
use wallet_accessor::BlockchainAccessConfig;
Expand All @@ -22,7 +22,7 @@ use zk_citadel::license::{Session, SessionCookie};
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub(crate) enum Command {
/// Request Service (User)
RequestService { session_cookie: String },
VerifyRequestedService { session_cookie: String, psk_lp_bytes: String },
/// Get session (SP)
GetSession { session_id: String },
/// Show state
Expand All @@ -34,14 +34,13 @@ impl Command {
pub async fn run(
self,
blockchain_access_config: &BlockchainAccessConfig,
config: &SPCliConfig,
) -> Result<RunResult, Error> {
let run_result = match self {
Command::RequestService { session_cookie } => {
Self::request_service(
Command::VerifyRequestedService { session_cookie, psk_lp_bytes } => {
Self::verify_requested_service(
blockchain_access_config,
&session_cookie,
config,
&psk_lp_bytes,
)
.await?
}
Expand All @@ -56,10 +55,10 @@ impl Command {
}

/// Command: Request Service
async fn request_service(
async fn verify_requested_service(
blockchain_access_config: &BlockchainAccessConfig,
session_cookie: &str,
config: &SPCliConfig,
psk_lp_bytes: &str,
) -> Result<RunResult, Error> {
let client =
RuskHttpClient::new(blockchain_access_config.rusk_address.clone());
Expand All @@ -68,23 +67,24 @@ impl Command {
.map_err(|_| Error::InvalidEntry("session cookie".into()))?;
let sc: SessionCookie = rkyv::from_bytes(bytes.as_slice())
.map_err(|_| Error::InvalidEntry("session cookie".into()))?;
let psk_lp: &str = &config.psk_lp;
let psk_lp_bytes = hex::decode(psk_lp.as_bytes()).map_err(|_| {
Error::InvalidConfigValue("license provider psk".into())
})?;
let psk_lp = PublicSpendKey::from_slice(psk_lp_bytes.as_slice())
.map_err(|_| {
Error::InvalidConfigValue("license provider psk".into())
})?;
let pk_lp = JubJubAffine::from(*psk_lp.A());

let psk_lp_bytes_formatted: [u8; 64] =
bs58::decode(&psk_lp_bytes.clone())
.into_vec()
.unwrap()
.try_into()
.unwrap();
let psk_lp =
PublicSpendKey::from_bytes(&psk_lp_bytes_formatted).unwrap();
let psk_lp_a = JubJubAffine::from(*psk_lp.A());

let session_id = LicenseSessionId { id: sc.session_id };
let session = CitadelInquirer::get_session(&client, session_id)
.await?
.ok_or(Error::NotFound("Session not found".into()))?;

let session = Session::from(&session.public_inputs);
let granted = session.verifies_ok(sc, pk_lp);
let granted = session.verifies_ok(sc, psk_lp_a);
println!("session id={}", hex::encode(session_id.id.to_bytes()));
let service_request_summary = ServiceRequestSummery {
service_granted: granted,
Expand Down
1 change: 0 additions & 1 deletion moat-cli-sp/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use toml_base_config::BaseConfig;
pub struct SPCliConfig {
pub rusk_address: String,
pub prover_address: String,
pub psk_lp: String,
}

impl BaseConfig for SPCliConfig {
Expand Down
3 changes: 0 additions & 3 deletions moat-cli-sp/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ pub enum Error {
/// Invalid entry
#[error("Invalid entry: {0:?}")]
InvalidEntry(Cow<'static, str>),
/// Invalid config value
#[error("Invalid config value: {0:?}")]
InvalidConfigValue(Cow<'static, str>),
}

impl From<moat_core::Error> for Error {
Expand Down
7 changes: 4 additions & 3 deletions moat-cli-sp/src/interactor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fn menu_operation() -> Result<OpSelection, ErrorKind> {
let cmd_menu = Menu::new()
.add(
CommandMenuItem::RequestService,
"Request Service (Off-Chain)",
"Verify Requested Service (Off-Chain)",
)
.add(CommandMenuItem::GetSession, "Get Session (SP)")
.add(CommandMenuItem::ShowState, "Show state")
Expand All @@ -46,8 +46,9 @@ fn menu_operation() -> Result<OpSelection, ErrorKind> {
let cmd = cmd_menu.answer(&answer).to_owned();
Ok(match cmd {
CommandMenuItem::RequestService => {
OpSelection::Run(Box::from(Command::RequestService {
OpSelection::Run(Box::from(Command::VerifyRequestedService {
session_cookie: prompt::request_session_cookie()?,
psk_lp_bytes: prompt::request_psk_lp()?,
}))
}
CommandMenuItem::GetSession => {
Expand Down Expand Up @@ -79,7 +80,7 @@ impl Interactor {
OpSelection::Exit => return Ok(()),
OpSelection::Run(command) => {
let result = command
.run(&self.blockchain_access_config, &self.config)
.run(&self.blockchain_access_config)
.await;
match result {
Ok(run_result) => {
Expand Down
2 changes: 1 addition & 1 deletion moat-cli-sp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async fn main() -> Result<(), Error> {

let config_path = cli.config_path.as_path();
let wallet_path = cli.wallet_path.as_path();
let password = cli.password;
let password = cli.wallet_pass;
let pwd_hash = cli.pwd_hash;
let gas_limit = cli.gas_limit;
let gas_price = cli.gas_price;
Expand Down
20 changes: 20 additions & 0 deletions moat-cli-sp/src/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,23 @@ pub(crate) fn request_session_cookie() -> Result<String, ErrorKind> {
let a_str = a.as_string().expect("answer to be a string").to_string();
Ok(a_str)
}

pub(crate) fn request_psk_lp() -> Result<String, ErrorKind> {
let q = Question::input("psk_lp_bytes")
.message("Please enter the LP address:".to_string())
.validate_on_key(|_, _| {
true // todo: add some validation of psk_lp
})
.validate(|id, _| {
if id.is_empty() {
Err("Please enter a valid address for the LP".to_string())
} else {
Ok(())
}
})
.build();

let a = requestty::prompt_one(q)?;
let a_str = a.as_string().expect("answer to be a string").to_string();
Ok(a_str)
}
4 changes: 2 additions & 2 deletions moat-cli-sp/src/run_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ impl fmt::Display for RunResult {
match self {
RequestService(summary) => {
if summary.service_granted {
writeln!(f, "Service granted")?;
writeln!(f, "Session Cookie is correct, service can be granted")?;
} else {
writeln!(f, "Service denied")?;
writeln!(f, "Session Cookie is NOT correct, service must be denied")?;
}
Ok(())
}
Expand Down
9 changes: 5 additions & 4 deletions moat-cli-user/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,11 @@ impl Command {
psk_lp_bytes: String,
) -> Result<RunResult, Error> {
let psk_lp_bytes_formatted: [u8; 64] =
hex::decode(psk_lp_bytes.clone())
.expect("Decoded.")
.try_into()
.unwrap();
bs58::decode(&psk_lp_bytes.clone())
.into_vec()
.unwrap()
.try_into()
.unwrap();
let psk_lp =
PublicSpendKey::from_bytes(&psk_lp_bytes_formatted).unwrap();

Expand Down

0 comments on commit fdab630

Please sign in to comment.