Skip to content

Commit

Permalink
Merge pull request #19 from dusk-network/refactorings
Browse files Browse the repository at this point in the history
Refactorings
  • Loading branch information
miloszm authored Sep 29, 2023
2 parents f40650b + 046f305 commit c1e12c7
Show file tree
Hide file tree
Showing 25 changed files with 143 additions and 212 deletions.
9 changes: 6 additions & 3 deletions integration-tests/tests/int_test_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use moat_core::Error::InvalidQueryResponse;
use moat_core::{
BcInquirer, CitadelInquirer, Error, JsonLoader, LicenseCircuit,
LicenseSessionId, PayloadSender, RequestCreator, RequestJson, StreamAux,
TxAwaiter, ARITY, DEPTH,
TxAwaiter, ARITY, DEPTH, LICENSE_CONTRACT_ID, USE_LICENSE_METHOD_NAME,
};
use poseidon_merkle::Opening;
use rand::rngs::StdRng;
Expand Down Expand Up @@ -146,13 +146,15 @@ async fn prove_and_send_use_license(
public_inputs,
};

let tx_id = PayloadSender::send_use_license(
let tx_id = PayloadSender::send_to_contract_method(
use_license_arg,
&blockchain_config,
&wallet_path,
&PwdHash(PWD_HASH.to_string()),
GAS_LIMIT,
GAS_PRICE,
LICENSE_CONTRACT_ID,
USE_LICENSE_METHOD_NAME,
)
.await?;
TxAwaiter::wait_for(&client, tx_id).await?;
Expand Down Expand Up @@ -332,6 +334,7 @@ async fn user_round_trip() -> Result<(), Error> {
hex::encode(session.public_inputs[0].to_bytes())
);

// if we try to call use_license again, it will be rejected
// if we try to call use_license with the same license again, it will be
// rejected
Ok(())
}
6 changes: 4 additions & 2 deletions integration-tests/tests/send_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use dusk_jubjub::BlsScalar;
use dusk_wallet::{RuskHttpClient, WalletPath};
use moat_core::{
Error, PayloadRetriever, PayloadSender, RequestCreator, RequestJson,
MAX_REQUEST_SIZE,
LICENSE_CONTRACT_ID, MAX_REQUEST_SIZE, NOOP_METHOD_NAME,
};
use moat_core::{JsonLoader, TxAwaiter};
use rand::rngs::StdRng;
Expand Down Expand Up @@ -59,13 +59,15 @@ async fn send_request() -> Result<(), Error> {
PathBuf::from(WALLET_PATH).as_path().join("wallet.dat"),
);

let tx_id = PayloadSender::send_noop(
let tx_id = PayloadSender::send_to_contract_method(
(request, 0u64, BlsScalar::one()),
&config,
&wallet_path,
&PwdHash(PWD_HASH.to_string()),
GAS_LIMIT,
GAS_PRICE,
LICENSE_CONTRACT_ID,
NOOP_METHOD_NAME,
)
.await?;
let client = RuskHttpClient::new(config.rusk_address);
Expand Down
13 changes: 9 additions & 4 deletions integration-tests/tests/stake_add_owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_wallet::{RuskHttpClient, WalletPath};
use moat_core::{
Error, JsonLoader, PayloadSender, RequestJson, TxAwaiter,
ADD_OWNER_METHOD_NAME, STAKE_CONTRACT_ID,
};
use moat_core::{Error, JsonLoader, PayloadSender, RequestJson, TxAwaiter};
use phoenix_core::transaction::ModuleId;
use std::path::PathBuf;
use toml_base_config::BaseConfig;
use wallet_accessor::BlockchainAccessConfig;
Expand All @@ -20,6 +18,13 @@ const PWD_HASH: &str =
const GAS_LIMIT: u64 = 5_000_000_000;
const GAS_PRICE: u64 = 1;

pub const STAKE_CONTRACT_ID: ModuleId = {
let mut bytes = [0u8; 32];
bytes[0] = 0x02;
bytes
};
pub const ADD_OWNER_METHOD_NAME: &str = "add_owner";

#[tokio::test(flavor = "multi_thread")]
#[cfg_attr(not(feature = "int_tests"), ignore)]
async fn stake_add_owner() -> Result<(), Error> {
Expand Down
9 changes: 7 additions & 2 deletions license-provider/src/license_issuer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use dusk_jubjub::{BlsScalar, JubJubAffine, JubJubScalar};
use dusk_pki::SecretSpendKey;
use dusk_poseidon::sponge;
use dusk_wallet::{RuskHttpClient, WalletPath};
use moat_core::{Error, PayloadSender, TxAwaiter, MAX_LICENSE_SIZE};
use moat_core::{
Error, PayloadSender, TxAwaiter, ISSUE_LICENSE_METHOD_NAME,
LICENSE_CONTRACT_ID, MAX_LICENSE_SIZE,
};
use rand::{CryptoRng, RngCore};
use tracing::trace;
use wallet_accessor::{BlockchainAccessConfig, Password};
Expand Down Expand Up @@ -59,13 +62,15 @@ impl LicenseIssuer {
"sending issue license with license blob size={}",
tuple.0.len()
);
let tx_id = PayloadSender::send_issue_license(
let tx_id = PayloadSender::send_to_contract_method(
tuple,
&self.config,
&self.wallet_path,
&self.password,
self.gas_limit,
self.gas_price,
LICENSE_CONTRACT_ID,
ISSUE_LICENSE_METHOD_NAME,
)
.await?;
let client = RuskHttpClient::new(self.config.rusk_address.clone());
Expand Down
24 changes: 9 additions & 15 deletions license-provider/src/reference_lp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl ReferenceLP {
RequestScanner::scan_block_range(height, height_end, cfg)
.await?;
total += requests.len();
let owned_requests = self.filter_owned_requests(&requests)?;
let owned_requests = self.retain_owned_requests(requests);
total_owned += owned_requests.len();
for owned_request in owned_requests {
self.insert_request(owned_request);
Expand All @@ -95,28 +95,22 @@ impl ReferenceLP {
let mut total_owned = 0usize;
let requests = RequestScanner::scan_last_blocks(n, cfg).await?;
total += requests.len();
let owned_requests = self.filter_owned_requests(&requests)?;
let owned_requests = self.retain_owned_requests(requests);
total_owned += owned_requests.len();
for owned_request in owned_requests {
self.insert_request(owned_request);
}
Ok((total, total_owned))
}

/// Given a collection of requests, returns a new collection
/// containing only requests relevant to `this` license provider
pub fn filter_owned_requests(
/// Given a collection of requests, retain only those requests
/// in the collection which are owned by 'this' license provider
pub fn retain_owned_requests(
&self,
requests: &[Request],
) -> Result<Vec<Request>, Error> {
let mut relevant_requests: Vec<Request> = Vec::new();
for request in requests.iter() {
if self.is_owned_request(request) {
let r = Request { ..*request };
relevant_requests.push(r);
}
}
Ok(relevant_requests)
mut requests: Vec<Request>,
) -> Vec<Request> {
requests.retain(|request| self.is_owned_request(request));
requests
}

fn is_owned_request(&self, request: &Request) -> bool {
Expand Down
7 changes: 3 additions & 4 deletions license-provider/tests/test_lp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@ fn lp_filter_requests() -> Result<(), Error> {
.expect("transactions file should load correctly");

let requests = RequestScanner::scan_transactions(txs);

let relevant_requests = reference_lp.filter_owned_requests(&requests)?;

assert_eq!(requests.len(), 9);
assert_eq!(relevant_requests.len(), 2);

let owned_requests = reference_lp.retain_owned_requests(requests);
assert_eq!(owned_requests.len(), 2);

Ok(())
}
9 changes: 7 additions & 2 deletions moat-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ use crate::args::Args;

use clap::Parser;
use dusk_wallet::WalletPath;
use moat_core::{JsonLoader, PayloadSender, RequestCreator, RequestJson};
use moat_core::{
JsonLoader, PayloadSender, RequestCreator, RequestJson,
LICENSE_CONTRACT_ID, NOOP_METHOD_NAME,
};
use rand::rngs::StdRng;
use rand::SeedableRng;
use std::error::Error;
Expand Down Expand Up @@ -104,13 +107,15 @@ async fn main() -> Result<(), Box<dyn Error>> {
PwdHash(pwd_hash)
};

PayloadSender::send_noop(
PayloadSender::send_to_contract_method(
request,
&blockchain_access_config,
&wallet_path,
&psw,
gas_limit,
gas_price,
LICENSE_CONTRACT_ID,
NOOP_METHOD_NAME,
)
.await?;

Expand Down
47 changes: 0 additions & 47 deletions moat-core/src/types.rs → moat-core/src/bc_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,50 +5,9 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

use crate::JsonLoader;
use phoenix_core::transaction::ModuleId;

pub const STAKE_CONTRACT_ID: ModuleId = {
let mut bytes = [0u8; 32];
bytes[0] = 0x02;
bytes
};
pub const LICENSE_CONTRACT_ID: ModuleId = {
let mut bytes = [0u8; 32];
bytes[0] = 0x03;
bytes
};

// license contract method names
pub const NOOP_METHOD_NAME: &str = "noop";
pub const ISSUE_LICENSE_METHOD_NAME: &str = "issue_license";
pub const USE_LICENSE_METHOD_NAME: &str = "use_license";
pub const GET_LICENSES_METHOD_NAME: &str = "get_licenses";
pub const GET_MERKLE_OPENING_METHOD_NAME: &str = "get_merkle_opening";
pub const GET_SESSION_METHOD_NAME: &str = "get_session";
pub const GET_INFO_METHOD_NAME: &str = "get_info";

// stake contract method names
pub const ADD_OWNER_METHOD_NAME: &str = "add_owner";

pub const MAX_CALL_SIZE: usize = 65536;
pub const MAX_REQUEST_SIZE: usize = 8192;
pub const MAX_LICENSE_SIZE: usize = 16384;
pub const MAX_RESPONSE_SIZE: usize = 65536;

#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct RequestJson {
pub user_ssk: String,
pub provider_psk: String,
}

impl JsonLoader for RequestJson {}

#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct ContractInfo {
pub method: String,
pub contract: String,
}

#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Tx {
pub id: String,
Expand All @@ -75,12 +34,6 @@ pub struct CallInfoJson {
pub data: String,
}

#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct TxJson {
pub anchor: String,
pub call: CallInfoJson,
}

#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Header {
pub height: u64,
Expand Down
2 changes: 1 addition & 1 deletion moat-core/src/blockchain_requests/payload_extractor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use rkyv::{check_archived_root, Archive, Deserialize, Infallible};

use crate::bc_types::Tx;
use crate::error::Error;
use crate::types::Tx;
use crate::Error::PayloadNotPresent;
use bytecheck::CheckBytes;
use rkyv::validation::validators::DefaultValidator;
Expand Down
81 changes: 1 addition & 80 deletions moat-core/src/blockchain_requests/payload_sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

use crate::error::Error;
use crate::{
ISSUE_LICENSE_METHOD_NAME, LICENSE_CONTRACT_ID, MAX_CALL_SIZE,
NOOP_METHOD_NAME, USE_LICENSE_METHOD_NAME,
};
use crate::MAX_CALL_SIZE;
use dusk_jubjub::BlsScalar;
use dusk_wallet::WalletPath;
use phoenix_core::transaction::ModuleId;
Expand All @@ -18,81 +15,6 @@ use wallet_accessor::{BlockchainAccessConfig, Password, WalletAccessor};
pub struct PayloadSender;

impl PayloadSender {
/// Sends a given payload to the noop method
pub async fn send_noop<P>(
payload: P,
cfg: &BlockchainAccessConfig,
wallet_path: &WalletPath,
password: &Password,
gas_limit: u64,
gas_price: u64,
) -> Result<BlsScalar, Error>
where
P: rkyv::Serialize<AllocSerializer<MAX_CALL_SIZE>>,
{
Self::send_to_contract_method(
payload,
cfg,
wallet_path,
password,
gas_limit,
gas_price,
LICENSE_CONTRACT_ID,
NOOP_METHOD_NAME,
)
.await
}

/// Sends a given payload to the issue license method
pub async fn send_issue_license<P>(
payload: P,
cfg: &BlockchainAccessConfig,
wallet_path: &WalletPath,
password: &Password,
gas_limit: u64,
gas_price: u64,
) -> Result<BlsScalar, Error>
where
P: rkyv::Serialize<AllocSerializer<MAX_CALL_SIZE>>,
{
Self::send_to_contract_method(
payload,
cfg,
wallet_path,
password,
gas_limit,
gas_price,
LICENSE_CONTRACT_ID,
ISSUE_LICENSE_METHOD_NAME,
)
.await
}

/// Sends a given payload to the use license method
pub async fn send_use_license<P>(
payload: P,
cfg: &BlockchainAccessConfig,
wallet_path: &WalletPath,
password: &Password,
gas_limit: u64,
gas_price: u64,
) -> Result<BlsScalar, Error>
where
P: rkyv::Serialize<AllocSerializer<MAX_CALL_SIZE>>,
{
Self::send_to_contract_method(
payload,
cfg,
wallet_path,
password,
gas_limit,
gas_price,
LICENSE_CONTRACT_ID,
USE_LICENSE_METHOD_NAME,
)
.await
}

/// Sends payload to a given method
#[allow(clippy::too_many_arguments)]
pub async fn send_to_contract_method<P, M>(
Expand All @@ -113,7 +35,6 @@ impl PayloadSender {
WalletAccessor::new(wallet_path.clone(), password.clone());
let tx_id = wallet_accessor
.send(
// (payload, 1u64, BlsScalar::one()),
payload,
contract_id,
method.as_ref().to_string(),
Expand Down
1 change: 0 additions & 1 deletion moat-core/src/blockchain_requests/request_scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ impl RequestScanner {
height_end: u64,
cfg: &BlockchainAccessConfig,
) -> Result<(Vec<Request>, u64), Error> {
// let client = Client::new(cfg.graphql_address.clone());
let client = RuskHttpClient::new(cfg.rusk_address.clone());
let (txs, top) =
TxRetriever::txs_from_block_range(&client, height_beg, height_end)
Expand Down
Loading

0 comments on commit c1e12c7

Please sign in to comment.