Skip to content

Commit

Permalink
authorization and execution gen from cli
Browse files Browse the repository at this point in the history
  • Loading branch information
Meshiest committed Mar 22, 2024
1 parent 5ce96e2 commit 2e27453
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 23 deletions.
65 changes: 51 additions & 14 deletions crates/aot/src/authorized.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
use std::str::FromStr;

use anyhow::{bail, Result};
use clap::Args;
use rand::{CryptoRng, Rng};
use snarkvm::prelude::{
de, Deserialize, DeserializeExt, Deserializer, Serialize, SerializeStruct, Serializer,
use snarkvm::{
ledger::{
query::Query,
store::{helpers::memory::ConsensusMemory, ConsensusStore},
},
prelude::{
de, Deserialize, DeserializeExt, Deserializer, Serialize, SerializeStruct, Serializer,
},
};

use crate::{
credits::PROCESS, Aleo, Authorization, DbLedger, Network, PrivateKey, Transaction, Value,
credits::PROCESS, Aleo, Authorization, DbLedger, MemVM, Network, PrivateKey, Transaction, Value,
};

#[derive(Clone, Debug)]
pub struct Authorized {
/// The authorization for the main function execution.
function: Authorization,
Expand All @@ -17,11 +27,24 @@ pub struct Authorized {
broadcast: bool,
}

pub enum ExecutionMode {
Local(Option<String>),
pub enum ExecutionMode<'a> {
Local(Option<&'a DbLedger>, Option<String>),
Remote(String),
}

#[derive(Debug, Args)]
pub struct Execute {
pub authorization: Authorized,
#[arg(short, long)]
pub query: Option<String>,
}

impl Execute {
pub fn parse(self) -> Result<()> {
Ok(())
}
}

impl Authorized {
/// Initializes a new authorization.
const fn new(function: Authorization, fee: Option<Authorization>, broadcast: bool) -> Self {
Expand Down Expand Up @@ -92,27 +115,33 @@ impl Authorized {
/// Executes the authorization locally, returning the resulting transaction.
pub fn execute_local<R: Rng + CryptoRng>(
self,
ledger: &DbLedger,
ledger: Option<&DbLedger>,
rng: &mut R,
query: Option<String>,
) -> Result<Transaction> {
let query = query.map(|q| q.try_into()).transpose()?;

// Execute the transaction.
ledger
.vm()
.execute_authorization(self.function, self.fee, query, rng)
if let Some(ledger) = ledger {
let query = query.map(Query::REST);

ledger
.vm()
.execute_authorization(self.function, self.fee, query, rng)
} else {
let query = query.map(Query::REST);

let store = ConsensusStore::<crate::Network, ConsensusMemory<_>>::open(None)?;
MemVM::from(store)?.execute_authorization(self.function, self.fee, query, rng)
}
}

pub fn execute<R: Rng + CryptoRng>(
self,
ledger: &DbLedger,
rng: &mut R,
mode: ExecutionMode,
mode: ExecutionMode<'_>,
) -> Result<Transaction> {
// Execute the transaction.
match mode {
ExecutionMode::Local(query) => self.execute_local(ledger, rng, query),
ExecutionMode::Local(ledger, query) => self.execute_local(ledger, rng, query),
ExecutionMode::Remote(ref api_url) => self.execute_remote(api_url),
}
}
Expand Down Expand Up @@ -157,3 +186,11 @@ impl<'de> Deserialize<'de> for Authorized {
})
}
}

impl FromStr for Authorized {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self> {
serde_json::from_str(s).map_err(anyhow::Error::from)
}
}
10 changes: 9 additions & 1 deletion crates/aot/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tracing_subscriber::{layer::SubscriberExt, Layer};

#[cfg(feature = "node")]
use crate::runner::Runner;
use crate::{genesis::Genesis, ledger::Ledger};
use crate::{authorized::Execute, credits::Authorize, genesis::Genesis, ledger::Ledger};

#[derive(Debug, Parser)]
#[clap(name = "snarkOS AoT", author = "MONADIC.US")]
Expand All @@ -36,6 +36,9 @@ pub enum Command {
Ledger(Ledger),
#[cfg(feature = "node")]
Run(Runner),
Execute(Execute),
#[command(subcommand)]
Authorize(Authorize),
}

impl Cli {
Expand Down Expand Up @@ -175,6 +178,11 @@ impl Cli {
Command::Ledger(command) => command.parse(),
#[cfg(feature = "node")]
Command::Run(command) => command.parse(),
Command::Execute(command) => command.parse(),
Command::Authorize(command) => {
println!("{}", serde_json::to_string(&command.parse()?)?);
Ok(())
}
}
}
}
46 changes: 40 additions & 6 deletions crates/aot/src/credits.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::str::FromStr;

use anyhow::Result;
use clap::Parser;
use rand::{CryptoRng, Rng};
use snarkvm::{
console::{
Expand All @@ -16,6 +17,43 @@ lazy_static::lazy_static! {
/// The main process.
pub(crate) static ref PROCESS: Process<Network> = Process::load().unwrap();
}
#[derive(Clone, Debug, Parser)]
pub enum Authorize {
TransferPublic {
#[clap(required = true, long)]
private_key: PrivateKey,
#[clap(required = true, long)]
recipient: Address,
#[clap(required = true, short, long)]
amount: u64,
#[clap(long, default_value_t = 0)]
priority_fee: u64,
#[clap(long, default_value_t = false)]
broadcast: bool,
},
}

impl Authorize {
/// Initializes a new authorization.
pub fn parse(self) -> Result<Authorized> {
match self {
Self::TransferPublic {
private_key,
recipient,
amount,
priority_fee,
broadcast,
} => Credits::transfer_public(
private_key,
recipient,
amount,
priority_fee,
broadcast,
&mut rand::thread_rng(),
),
}
}
}

pub struct Credits;

Expand Down Expand Up @@ -178,17 +216,13 @@ impl Credits {
/// Returns a transaction that transfers public credits from the sender to
/// the recipient.
pub fn transfer_public(
private_key: &str,
recipient: &str,
private_key: PrivateKey,
recipient: Address,
amount_in_microcredits: u64,
priority_fee_in_microcredits: u64,
broadcast: bool,
rng: &mut (impl Rng + CryptoRng),
) -> Result<Authorized> {
// Initialize the private key.
let private_key = PrivateKey::from_str(private_key)?;
// Initialize the recipient.
let recipient = Address::from_str(recipient)?;
// Initialize the amount in microcredits.
let amount_in_microcredits = U64::new(amount_in_microcredits);

Expand Down
13 changes: 12 additions & 1 deletion crates/aot/src/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::Result;
use clap::{Args, Subcommand};
use rand::{seq::SliceRandom, CryptoRng, Rng};

use crate::{Address, PrivateKey};
use crate::{authorized::Execute, Address, PrivateKey};

pub mod add;
pub mod distribute;
Expand Down Expand Up @@ -91,6 +91,7 @@ pub enum Commands {
View(view::View),
Distribute(distribute::Distribute),
Truncate(truncate::Truncate),
Execute(Execute),
}

impl Ledger {
Expand Down Expand Up @@ -130,6 +131,16 @@ impl Ledger {
}

Commands::Truncate(truncate) => truncate.parse(genesis, ledger),
Commands::Execute(execute) => {
let ledger = util::open_ledger(genesis, ledger)?;
let tx = execute.authorization.execute_local(
Some(&ledger),
&mut rand::thread_rng(),
None,
)?;
println!("{}", serde_json::to_string(&tx)?);
Ok(())
}
}
}
}
2 changes: 1 addition & 1 deletion crates/snot-agent/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ pub struct Cli {
/// Specify the IP address and port for the REST server
#[clap(long = "rest", default_value = "3030")]
pub rest: u16,
// TODO: specify allowed modes
// TODO: specify allowed modes (--validator --client --tx-gen)
}
8 changes: 8 additions & 0 deletions scripts/addr.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash

BINARY="$(pwd)/target/release/snarkos-aot"

TEST_PATH=$(scripts/test_path.sh)
COMMITTEE=$TEST_PATH/committee.json

cat $COMMITTEE | jq "(. | keys)[$1]" -r;
8 changes: 8 additions & 0 deletions scripts/pk.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash

BINARY="$(pwd)/target/release/snarkos-aot"

TEST_PATH=$(scripts/test_path.sh)
COMMITTEE=$TEST_PATH/committee.json

cat $COMMITTEE | jq "[.[][0]][$1]" -r;

0 comments on commit 2e27453

Please sign in to comment.