Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Circuits for Signer (copy of #222) #228

Merged
merged 3 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
587 changes: 242 additions & 345 deletions Cargo.lock

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ derivative = { version = "2.2.0", default-features = false, features = ["use_cor
dirs-next = { version = "2.0.0", default-features = false }
futures = { version = "0.3.17", default-features = false, features = ["alloc"] }
http-types = { version = "2.12.0", default-features = false }
manta-accounting = { git = "https://github.com/manta-network/manta-rs", tag = "v0.5.7", default-features = false, features = ["cocoon-fs"] }
manta-crypto = { git = "https://github.com/manta-network/manta-rs", tag = "v0.5.7", default-features = false, features = ["getrandom"] }
manta-parameters = { git = "https://github.com/manta-network/manta-rs", tag = "v0.5.7", default-features = false, features = ["download"] }
manta-pay = { git = "https://github.com/manta-network/manta-rs", tag = "v0.5.7", default-features = false, features = ["bs58", "groth16", "network", "serde", "wallet"] }
manta-util = { git = "https://github.com/manta-network/manta-rs", tag = "v0.5.7", default-features = false }
manta-accounting = { git = "https://github.com/manta-network/manta-rs", default-features = false, features = ["cocoon-fs"] }
manta-crypto = { git = "https://github.com/manta-network/manta-rs", default-features = false, features = ["getrandom"] }
manta-parameters = { git = "https://github.com/manta-network/manta-rs", default-features = false, features = ["download"] }
manta-pay = { git = "https://github.com/manta-network/manta-rs", default-features = false, features = ["bs58", "groth16", "serde", "wallet", "network", "parameters"] }
manta-util = { git = "https://github.com/manta-network/manta-rs", default-features = false }
parking_lot = { version = "0.12.1", default-features = false }
password-hash = { version = "0.4.2", default-features = false, features = ["alloc"] }
reqwest = { version = "0.11.11", default-features = false, features = ["json"] }
secrecy = { version = "0.8.0", default-features = false, features = ["alloc"] }
serde_json = { version = "1.0.68", default-features = false }
subtle = { version = "2.4.1", default-features = false }
Expand Down
3 changes: 2 additions & 1 deletion examples/test_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ impl Authorizer for MockUser {

#[inline]
fn setup(&mut self, data_exists: bool) -> SetupFuture {
let new_mnemonic = Mnemonic::sample(&mut OsRng);
if data_exists {
Box::pin(async move { Setup::Login })
} else {
Box::pin(async move { Setup::CreateAccount(Mnemonic::sample(&mut OsRng)) })
Box::pin(async move { Setup::CreateAccount(new_mnemonic) })
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl Config {
Ok(metadata) if metadata.is_file() => Ok(true),
Ok(metadata) => Err(io::Error::new(
io::ErrorKind::Other,
format!("Invalid file format: {:?}.", metadata),
format!("Invalid file format: {metadata:?}."),
)),
_ => Ok(false),
}
Expand Down Expand Up @@ -173,7 +173,7 @@ impl Config {
}
Ok(metadata) => Err(io::Error::new(
io::ErrorKind::Other,
format!("Invalid file format: {:?}.", metadata),
format!("Invalid file format: {metadata:?}."),
)),
_ => Ok(false),
}
Expand Down
49 changes: 17 additions & 32 deletions src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,8 @@

// TODO: Report a more informative error.

use manta_pay::{
config::{
MultiProvingContext, NoteEncryptionScheme, Parameters, ProvingContext,
UtxoAccumulatorModel, UtxoCommitmentScheme, VoidNumberCommitmentScheme,
},
signer::base::SignerParameters,
};
use manta_parameters::{Download, Get};
use manta_pay::{config, parameters::load_transfer_parameters, signer::base::SignerParameters};
use manta_util::codec::{Decode, IoReader};
use std::{
fs::{self, File},
Expand All @@ -44,43 +39,33 @@ where
directory.push("testnet");
directory.push("proving");
fs::create_dir_all(&directory).ok()?;
let mint = directory.join("mint.dat");
manta_parameters::pay::testnet::proving::Mint::download_if_invalid(&mint).ok()?;
let mint = directory.join("to-private.dat");
manta_parameters::pay::testnet::proving::ToPrivate::download_if_invalid(&mint).ok()?;
let private_transfer = directory.join("private-transfer.dat");
manta_parameters::pay::testnet::proving::PrivateTransfer::download_if_invalid(
&private_transfer,
)
.ok()?;
let reclaim = directory.join("reclaim.dat");
manta_parameters::pay::testnet::proving::Reclaim::download_if_invalid(&reclaim).ok()?;
let reclaim = directory.join("to-public.dat");
manta_parameters::pay::testnet::proving::ToPublic::download_if_invalid(&reclaim).ok()?;
let parameters = load_transfer_parameters();
Some(SignerParameters {
proving_context: MultiProvingContext {
mint: ProvingContext::decode(IoReader(File::open(mint).ok()?)).ok()?,
private_transfer: ProvingContext::decode(IoReader(File::open(private_transfer).ok()?))
.ok()?,
reclaim: ProvingContext::decode(IoReader(File::open(reclaim).ok()?)).ok()?,
},
parameters: Parameters {
note_encryption_scheme: NoteEncryptionScheme::decode(
manta_parameters::pay::testnet::parameters::NoteEncryptionScheme::get()?,
)
.ok()?,
utxo_commitment: UtxoCommitmentScheme::decode(
manta_parameters::pay::testnet::parameters::UtxoCommitmentScheme::get()?,
)
.ok()?,
void_number_commitment: VoidNumberCommitmentScheme::decode(
manta_parameters::pay::testnet::parameters::VoidNumberCommitmentScheme::get()?,
)
proving_context: config::MultiProvingContext {
to_private: config::ProvingContext::decode(IoReader(File::open(mint).ok()?)).ok()?,
private_transfer: config::ProvingContext::decode(IoReader(
File::open(private_transfer).ok()?,
))
.ok()?,
to_public: config::ProvingContext::decode(IoReader(File::open(reclaim).ok()?)).ok()?,
},
parameters,
})
}

/// Loads the [`UtxoAccumulatorModel`] from the Manta SDK.
/// Loads the \[`UtxoAccumulatorModel`\](config::UtxoAccumulatorModel) from the Manta SDK.
#[inline]
pub fn load_utxo_accumulator_model() -> Option<UtxoAccumulatorModel> {
UtxoAccumulatorModel::decode(
pub fn load_utxo_accumulator_model() -> Option<config::UtxoAccumulatorModel> {
config::UtxoAccumulatorModel::decode(
manta_parameters::pay::testnet::parameters::UtxoAccumulatorModel::get()?,
)
.ok()
Expand Down
77 changes: 31 additions & 46 deletions src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,13 @@ use http_types::headers::HeaderValue;
use manta_accounting::{
asset::{Asset, AssetMetadata},
fs::{cocoon::File, File as _, SaveError},
key::HierarchicalKeyDerivationScheme,
transfer::canonical::TransferShape,
};
use manta_pay::{
config::Transaction,
key::{Mnemonic, TestnetKeySecret},
signer::{
base::{
HierarchicalKeyDerivationFunction, Signer, SignerParameters, SignerState,
UtxoAccumulator,
},
base::{Signer, SignerParameters, SignerState, UtxoAccumulator},
client::network::{Message, Network, NetworkSpecific},
},
};
Expand All @@ -63,7 +59,7 @@ use tokio::{
};

pub use manta_pay::{
config::{receiving_key_to_base58, ReceivingKey},
config::{address_to_base58, Address},
signer::{self, SignError, SignResponse, SyncError, SyncResponse},
};

Expand All @@ -74,7 +70,7 @@ pub type SyncRequest = Message<signer::SyncRequest>;
pub type SignRequest = Message<signer::SignRequest>;

/// Receiving Key Request
pub type ReceivingKeyRequest = Message<signer::ReceivingKeyRequest>;
pub type ReceivingKeyRequest = Message<signer::GetRequest>;

/// Password Retry Interval
pub const PASSWORD_RETRY_INTERVAL: Duration = Duration::from_millis(1000);
Expand Down Expand Up @@ -140,11 +136,11 @@ impl Display for Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::AddrParseError(err) => write!(f, "Address Parse Error: {}", err),
Self::JoinError(err) => write!(f, "Join Error: {}", err),
Self::AddrParseError(err) => write!(f, "Address Parse Error: {err}"),
Self::JoinError(err) => write!(f, "Join Error: {err}"),
Self::ParameterLoadingError => write!(f, "Parameter Loading Error"),
Self::SaveError(err) => write!(f, "Save Error: {}", err),
Self::Io(err) => write!(f, "I/O Error: {}", err),
Self::SaveError(err) => write!(f, "Save Error: {err}"),
Self::Io(err) => write!(f, "I/O Error: {err}"),
Self::AuthorizationError => write!(f, "Authorization Error"),
Self::Delayed => write!(f, "Delay Error"),
}
Expand All @@ -162,24 +158,26 @@ pub fn display_transaction(
network: Network,
) -> String {
match transaction {
Transaction::Mint(Asset { value, .. }) => format!(
Transaction::ToPrivate(Asset { value, .. }) => format!(
"Privatize {} on {} network",
metadata.display(*value),
metadata.display(*value, metadata.decimals),
network
),
Transaction::PrivateTransfer(Asset { value, .. }, receiving_key) => {
format!(
"Send {} to {} on {} network",
metadata.display(*value),
receiving_key_to_base58(receiving_key),
metadata.display(*value, metadata.decimals),
address_to_base58(receiving_key),
network
)
}
Transaction::ToPublic(Asset { value, .. }) => {
format!(
"Public {} on {} network",
metadata.display(*value, metadata.decimals),
network
)
}
Transaction::Reclaim(Asset { value, .. }) => format!(
"Withdraw {} on {} network",
metadata.display(*value),
network
),
}
}

Expand Down Expand Up @@ -302,7 +300,6 @@ where
mnemonic.clone(),
)
.await?;

break (
password_hash,
Signer::from_parts(parameters.clone(), dolphin_state),
Expand Down Expand Up @@ -403,18 +400,17 @@ where
} else {
&config.data_path.manta
};
let exisitng_signer = Signer::from_parts(
let existing_signer = Signer::from_parts(
parameters.clone(),
Self::load_state(existing_state_path, password_hash)
.await
.expect("Unable to get dolphin state")?,
);
Some(
exisitng_signer
existing_signer
.state()
.accounts()
.keys()
.base()
.expose_mnemonic()
.clone(),
)
Expand All @@ -437,7 +433,7 @@ where
recovery_mnemonic.expect("unable to retrieve mnemonic for account recreation."),
)
.await
.expect("Unable to recreate signer instance from exisitng mnemonic.");
.expect("Unable to recreate signer instance from existing mnemonic.");
Ok(Some(state))
} else {
Self::load_state(data_path, password_hash).await
Expand Down Expand Up @@ -471,7 +467,7 @@ where
.get(|_| http::into_body(Server::<A>::version));
http::register_post(&mut api, "/sync", Server::sync);
http::register_post(&mut api, "/sign", Server::sign);
http::register_post(&mut api, "/receivingKeys", Server::receiving_keys);
http::register_post(&mut api, "/address", Server::address);
info!("serving signer API at {}", socket_address)?;
api.listen(socket_address).await?;
Ok(())
Expand All @@ -495,7 +491,7 @@ where
) -> Result<SignerState> {
info!("creating signer state")?;
let state = SignerState::new(
TestnetKeySecret::new(mnemonic, "").map(HierarchicalKeyDerivationFunction::default()),
TestnetKeySecret::new(mnemonic, ""),
UtxoAccumulator::new(
task::spawn_blocking(crate::parameters::load_utxo_accumulator_model)
.await?
Expand Down Expand Up @@ -589,7 +585,7 @@ where
},
} = request;
match transaction.shape() {
TransferShape::Mint => {
TransferShape::ToPrivate => {
// NOTE: We skip authorization on mint transactions because they are deposits not
// withdrawals from the point of view of the signer. Everything else, by
// default, requests authorization.
Expand Down Expand Up @@ -621,36 +617,25 @@ where
.state()
.accounts()
.keys()
.base()
.expose_mnemonic()
.clone();
Ok(stored_mnemonic)
}

/// Runs the receiving key sampling protocol on the signer.
#[inline]
pub async fn receiving_keys(self, request: ReceivingKeyRequest) -> Result<Vec<ReceivingKey>> {
info!("[REQUEST] processing `receivingKeys`: {:?}", request)?;
let response = self.state.lock().signer[request.network].receiving_keys(request.message);
info!(
"[RESPONSE] responding to `receivingKeys` with: {:?}",
response
)?;
pub async fn address(self, request: ReceivingKeyRequest) -> Result<Address> {
let response = self.state.lock().signer[request.network].address();
info!("[RESPONSE] responding to `receivingKeys` with: {response:?}")?;
Ok(response)
}

/// Runs the receiving key sampling protocol on a mutable reference of the signer, and formats
/// the result to base 58.
#[inline]
pub async fn get_receiving_keys(
&mut self,
request: ReceivingKeyRequest,
) -> Result<Vec<String>, ()> {
let response = self.state.lock().signer[request.network].receiving_keys(request.message);
let keys = response
.into_iter()
.map(|key| receiving_key_to_base58(&key))
.collect();
Ok(keys)
pub async fn get_address(&mut self, request: ReceivingKeyRequest) -> Result<String, ()> {
let response = self.state.lock().signer[request.network].address();
let key = address_to_base58(&response);
Ok(key)
}
}
Binary file removed ui/public/Square89x89Logo.png
Binary file not shown.
4 changes: 2 additions & 2 deletions ui/public/about.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

main {
text-align: center;
margin-top: 3em;
margin-top: 1em;
}

p {
Expand All @@ -36,7 +36,7 @@

<body>
<main>
<img src="manta.png" style="width: 5rem;"/>
<img src="manta.png"/>
<h3>Manta Signer</h3>
<p>Version 0.8.0</p>
<p>Copyright © 2019-2022 Manta Network</p>
Expand Down
Binary file modified ui/public/manta.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading