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

Subscan API key #31

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,13 @@ Make sure the `service` binary and the `glove.eif` file are in the same director
will both be in `target/release`:

```shell
target/release/service --address=<LISTEN> --proxy-secret-phrase=<SECRET PHRASE> --node-endpoint=<URL> dynamodb --table-name=<GLOVE TABLE>
target/release/service --address=<LISTEN> --proxy-secret-phrase=<SECRET PHRASE> --node-endpoint=<URL> --subscan-api-key=<API KEY> dynamodb --table-name=<GLOVE TABLE>
shamsasari marked this conversation as resolved.
Show resolved Hide resolved
```

To understand what these arguments mean and others, you will need to first read the help with `--help`.
The service makes use of [Subscan](https://support.subscan.io/) and it is recommended an API key be provided, though
not required.

Full documenation of the arguments, along with other flags, can be found with `--help`.

You can check the enclave is running with:

Expand Down
17 changes: 12 additions & 5 deletions client-interface/src/subscan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ use common::ExtrinsicLocation;

#[derive(Clone)]
pub struct Subscan {
http_client: reqwest::Client,
network: String,
api_key: Option<String>,
http_client: reqwest::Client,
}

impl Subscan {
pub fn new(network: String) -> Self {
pub fn new(network: String, api_key: Option<String>) -> Self {
Self {
http_client: reqwest::Client::new(),
network,
api_key,
http_client: reqwest::Client::new(),
}
}

Expand Down Expand Up @@ -87,8 +89,13 @@ impl Subscan {
end_point: &str,
request: &(impl Serialize + ?Sized)
) -> Result<(HeaderMap, Resp), Error> {
let http_response = self.http_client
.post(format!("https://{}.api.subscan.io/api/scan/{}", self.network, end_point))
let request_builder = self.http_client
.post(format!("https://{}.api.subscan.io/api/scan/{}", self.network, end_point));
let request_builder = match &self.api_key {
Some(api_key) => request_builder.header("X-API-Key", api_key),
None => request_builder
};
let http_response = request_builder
.json(&request)
.send().await?;
let headers = http_response.headers().clone();
Expand Down
56 changes: 7 additions & 49 deletions client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use common::{attestation, Conviction, SignedVoteRequest, VoteRequest};
use common::attestation::{Attestation, EnclaveInfo};
use RuntimeError::Proxy;

use crate::verify::{Error, try_verify_glove_result};
use crate::verify::try_verify_glove_result;

pub mod verify;

Expand Down Expand Up @@ -125,51 +125,9 @@ async fn vote(
if response.status() != StatusCode::OK {
bail!(response.text().await?)
}
if cmd.await_glove_proof {
listen_for_glove_votes(&network, &cmd, nonce, &service_info.proxy_account).await?;
}
return Ok(SuccessOutput::Voted { nonce });
}

// TODO Stop waiting when the poll is closed.
async fn listen_for_glove_votes(
network: &CallableSubstrateNetwork,
vote_cmd: &VoteCmd,
nonce: u32,
proxy_account: &AccountId32
) -> Result<()> {
network.subscribe_successful_extrinsics(|extrinsic, _| async move {
let verification_result = try_verify_glove_result(
&network,
&extrinsic,
proxy_account,
vote_cmd.poll_index,
).await;
let verified_glove_proof = match verification_result {
Ok(None) => return Ok(()), // Not what we're looking for
Ok(Some(verified_glove_proof)) => verified_glove_proof,
Err(Error::Subxt(subxt_error)) => return Err(subxt_error.into()),
Err(error) => {
eprintln!("Error verifying Glove proof: {}", error);
return Ok(());
}
};
if let Some(balance) = verified_glove_proof.get_vote_balance(&network.account(), nonce) {
println!("Glove vote {:?} with balance {}",
verified_glove_proof.result.direction, network.token.amount(balance));
if let Some(_) = &verified_glove_proof.enclave_info {
// TODO Check measurement
} else {
eprintln!("WARNING: Secure enclave wasn't used");
}
} else {
eprintln!("WARNING: Received Glove proof for poll, but vote was not included");
}
Ok(())
}).await?;
Ok(())
}

async fn remove_vote(
service_info: ServiceInfo,
cmd: RemoveVoteCmd,
Expand Down Expand Up @@ -203,7 +161,7 @@ async fn verify_vote(service_info: ServiceInfo, cmd: VerifyVoteCmd) -> Result<Su
let Some(poll_info) = network.get_poll(cmd.poll_index).await? else {
bail!("Poll does not exist")
};
let subscan = Subscan::new(service_info.network_name.clone());
let subscan = Subscan::new(service_info.network_name.clone(), cmd.subscan_api_key);
let votes = subscan.get_votes(cmd.poll_index, Some(cmd.account.clone())).await?;
let Some(vote) = votes.first() else {
if matches!(poll_info, ReferendumInfoFor::Ongoing(_)) {
Expand Down Expand Up @@ -407,10 +365,7 @@ struct VoteCmd {
balance: BigDecimal,
/// The vote conviction multiplier
#[arg(long, short, verbatim_doc_comment, default_value_t = 0)]
conviction: u8,
/// Wait for the vote to be included in the Glove mixing process and confirmation received.
#[arg(long, short, verbatim_doc_comment)]
await_glove_proof: bool
conviction: u8
}

impl VoteCmd {
Expand Down Expand Up @@ -455,7 +410,10 @@ struct VerifyVoteCmd {
enclave_measurement: Vec<String>,
/// Optional, the nonce value used in the most recent vote request.
#[arg(long, short, verbatim_doc_comment)]
nonce: Option<u32>
nonce: Option<u32>,
/// Optional, API key to use with Subscan
#[arg(long, short, verbatim_doc_comment)]
subscan_api_key: Option<String>
}

#[derive(Debug, Parser)]
Expand Down
3 changes: 0 additions & 3 deletions client/src/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub struct VerifiedGloveProof {
pub attested_data: AttestedData
}

// TODO API for checking EnclaveInfo for expected measurements
impl VerifiedGloveProof {
pub fn get_assigned_balance(&self, account: &AccountId32) -> Option<AssignedBalance> {
self.result
Expand Down Expand Up @@ -246,5 +245,3 @@ pub enum Error {
#[error("Invalid attestation: {0}")]
Attestation(#[from] attestation::Error)
}

// TODO Tests
1 change: 0 additions & 1 deletion common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ subxt.workspace = true
[dev-dependencies]
serde_json.workspace = true
subxt-signer.workspace = true
# TODO client-interface and enclave-interface should be merged into common but behind feature flags
10 changes: 5 additions & 5 deletions service/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ struct Args {
#[arg(long, verbatim_doc_comment)]
node_endpoint: String,

/// API key to use when querying Subscan.
#[arg(long, verbatim_doc_comment)]
subscan_api_key: Option<String>,

/// The storage to use for the service.
#[clap(subcommand, verbatim_doc_comment)]
storage: Storage,
Expand Down Expand Up @@ -129,7 +133,6 @@ enum EnclaveMode {
Mock
}

// TODO Probably need to specify API key for subscan
// TODO Sign the enclave image
// TODO Permantely ban accounts which vote directly
// TODO Endpoint for poll end time and other info?
Expand Down Expand Up @@ -196,7 +199,7 @@ async fn main() -> anyhow::Result<()> {
state: GloveState::default()
});

let subscan = Subscan::new(glove_context.network.network_name.clone());
let subscan = Subscan::new(glove_context.network.network_name.clone(), args.subscan_api_key);
if args.regular_mix {
warn!("Regular mixing of votes is enabled. This is not suitable for production.");
} else {
Expand Down Expand Up @@ -532,9 +535,6 @@ async fn submit_glove_result_on_chain(
signed_requests: &Vec<SignedVoteRequest>,
signed_glove_result: SignedGloveResult
) -> Result<(), ProxyError> {
// TODO Should the enclave produce the extrinic calls structs? It would prove the enclave
// intiated the abstain votes. Otherwise, users are trusting the host service is correctly
// interpreting the enclave's None mixing output.
let mut batched_calls = Vec::with_capacity(signed_requests.len() + 1);

let glove_result = &signed_glove_result.result;
Expand Down
2 changes: 1 addition & 1 deletion stress-tool/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ async fn extrinsic(extrinsic_location: ExtrinsicLocation, args: Args) -> Result<
.send().await?
.error_for_status()?
.json::<ServiceInfo>().await?;
let subscan = Subscan::new(service_info.network_name);
let subscan = Subscan::new(service_info.network_name, None);
match subscan.get_extrinsic(extrinsic_location).await? {
Some(extrinsic) => println!("{:#?}", extrinsic),
None => bail!("Extrinsic not found")
Expand Down