Skip to content

Commit

Permalink
Merged from parity repo (#126)
Browse files Browse the repository at this point in the history
Merged from Parity repository
  • Loading branch information
pgolovkin authored Sep 13, 2022
1 parent df52654 commit 0517f22
Show file tree
Hide file tree
Showing 13 changed files with 572 additions and 489 deletions.
753 changes: 395 additions & 358 deletions Cargo.lock

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,22 @@ anyhow = "1.0"
toml = "0.5"
serde = { version = "1.0", features = ["derive"] }
dialoguer = "0.10"
qr_reader_phone = {git = "https://github.com/paritytech/parity-signer"}
qr_reader_pc = {git = "https://github.com/paritytech/parity-signer"}
definitions = {git = "https://github.com/paritytech/parity-signer"}
generate_message = {git = "https://github.com/paritytech/parity-signer"}
transaction_parsing = {git = "https://github.com/paritytech/parity-signer"}
qr_reader_phone = {git = "https://github.com/paritytech/parity-signer", rev = "197e9e0"}
qr_reader_pc = {git = "https://github.com/paritytech/parity-signer", rev = "197e9e0"}
definitions = {git = "https://github.com/paritytech/parity-signer", rev = "197e9e0"}
generate_message = {git = "https://github.com/paritytech/parity-signer", rev = "197e9e0"}
transaction_parsing = {git = "https://github.com/paritytech/parity-signer", rev = "197e9e0"}
tempfile = "3.3"
sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, features = ["full_crypto"]}
parity-scale-codec = {version = "3.1.2"}
image = "0.24"
quircs = "0.10"
hex = "0.4"
indicatif = "0.16"
indicatif = "0.17"
serde_json = "1.0"
octocrab = "0.16"
octocrab = "0.17"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json", "blocking"]}

sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, features = ["full_crypto"]}
png = "0.17.5"
blake2-rfc = "0.2.18"
# Hash table which preserves insertion order
Expand Down
9 changes: 4 additions & 5 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ pub(crate) struct AppConfig {
pub(crate) public_dir: PathBuf,
pub(crate) qr_dir: PathBuf,
pub(crate) verifier: Verifier,
pub(crate) github: Option<GitHub>,
pub(crate) chains: Vec<Chain>,
}

Expand All @@ -62,7 +61,6 @@ impl Default for AppConfig {
public_dir: PathBuf::from("src/public"),
qr_dir: PathBuf::from("qr"),
verifier: Verifier::default(),
github: None,
chains: vec![Chain::default()],
}
}
Expand Down Expand Up @@ -101,9 +99,10 @@ impl Default for Verifier {
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub(crate) struct GitHub {
pub(crate) struct GithubRepo {
pub(crate) owner: String,
pub(crate) repo: String,
pub(crate) genesis_hash: String,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
Expand All @@ -116,9 +115,9 @@ pub(crate) struct Chain {
pub(crate) icon: String,
#[serde(alias = "rpc_endpoint", deserialize_with = "string_or_vec")]
pub(crate) rpc_endpoints: Vec<String>,
pub(crate) genesis_hash: Option<String>,
pub(crate) token_unit: Option<String>,
pub(crate) token_decimals: Option<u8>,
pub(crate) github_release: Option<GithubRepo>,
}

fn color_default() -> String {
Expand All @@ -134,9 +133,9 @@ impl Default for Chain {
color: color_default(),
icon: "Polkadot.svg".to_string(),
rpc_endpoints: vec!["wss://example.com".to_string()],
genesis_hash: None,
token_unit: None,
token_decimals: None,
github_release: None,
}
}
}
14 changes: 6 additions & 8 deletions cli/src/fetch.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{bail, Result};
use anyhow::{anyhow, bail, Result};
use definitions::crypto::Encryption;
use definitions::error_active::ErrorActive;
use definitions::network_specs::NetworkSpecsToSend;
use generate_message::helpers::{meta_fetch, specs_agnostic, MetaFetched};
use generate_message::parser::Token;
Expand All @@ -14,16 +13,15 @@ pub(crate) trait Fetcher {
}

// try to call all urls unless successful
fn call_urls<F, T>(urls: &Vec<String>, f: F) -> Result<T, ErrorActive>
fn call_urls<F, T>(urls: &[String], f: F) -> Result<T, generate_message::Error>
where
F: Fn(&str) -> Result<T, ErrorActive>,
F: Fn(&str) -> Result<T, generate_message::Error>,
{
let n = urls.len();
for url in urls.iter().take(n - 1) {
match f(url) {
Ok(res) => return Ok(res),
Err(ErrorActive::Fetch(e)) => warn!("Failed to fetch {}: {:?}", url, e),
Err(e) => return Err(e),
Err(e) => warn!("Failed to fetch {}: {:?}", url, e),
}
}
f(&urls[n - 1])
Expand All @@ -42,7 +40,7 @@ impl Fetcher for RpcFetcher {
);
specs_agnostic(url, Encryption::Sr25519, optional_token_override, None)
})
.map_err(anyhow::Error::msg)?;
.map_err(|e| anyhow!("{:?}", e))?;
if specs.name.to_lowercase() != chain.name {
bail!(
"Network name mismatch. Expected {}, got {}. Please fix it in `config.toml`",
Expand All @@ -54,7 +52,7 @@ impl Fetcher for RpcFetcher {
}

fn fetch_metadata(&self, chain: &Chain) -> Result<MetaFetched> {
let meta = call_urls(&chain.rpc_endpoints, meta_fetch).map_err(anyhow::Error::msg)?;
let meta = call_urls(&chain.rpc_endpoints, meta_fetch).map_err(|e| anyhow!("{:?}", e))?;
if meta.meta_values.name.to_lowercase() != chain.name {
bail!(
"Network name mismatch. Expected {}, got {}. Please fix it in `config.toml`",
Expand Down
1 change: 0 additions & 1 deletion cli/src/lib/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub(crate) mod camera;
pub(crate) mod path;
pub(crate) mod string;
pub(crate) mod types;
4 changes: 0 additions & 4 deletions cli/src/lib/string.rs

This file was deleted.

51 changes: 36 additions & 15 deletions cli/src/signer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
mod prompt;

use std::fs::File;
use std::io::Write;
use std::ops::Deref;
use std::process::Command;

use anyhow::bail;
use definitions::crypto::SufficientCrypto;
use anyhow::{anyhow, bail};
use definitions::crypto::Encryption;
use definitions::error::TransferContent;
use generate_message::full_run;
use generate_message::parser::{Command as SignerCommand, Crypto, Goal, Make, Msg};
use parity_scale_codec::Decode;
use generate_message::parser::{
Command as SignerCommand, Goal, Make, Msg, Signature, Sufficient, Verifier,
};
use qr_reader_pc::{run_with_camera, CameraSettings};
use transaction_parsing::check_signature::pass_crypto;

use crate::config::AppConfig;
use crate::lib::camera::read_qr_file;
use crate::lib::path::{ContentType, QrPath};
use crate::lib::string::hex_to_bytes;
use crate::qrs::qrs_in_dir;
use crate::signer::prompt::{select_file, want_to_continue};
use crate::source::{read_png_source, save_source_info};
Expand Down Expand Up @@ -50,14 +53,12 @@ fn run_for_file(qr_path: &QrPath) -> anyhow::Result<()> {
Err(e) => bail!("QR reading error. {}", e),
};

sign_qr(qr_path, &signature)?;
sign_qr(qr_path, signature)?;
println!("🎉 Signed!");
Ok(())
}

fn sign_qr(unsigned_qr: &QrPath, signature: &str) -> anyhow::Result<QrPath> {
let signature = hex_to_bytes(signature)?;
let sufficient_crypto = <SufficientCrypto>::decode(&mut &signature[..])?;
fn sign_qr(unsigned_qr: &QrPath, signature: String) -> anyhow::Result<QrPath> {
let mut signed_qr = unsigned_qr.clone();
signed_qr.file_name.is_signed = true;

Expand All @@ -66,21 +67,41 @@ fn sign_qr(unsigned_qr: &QrPath, signature: &str) -> anyhow::Result<QrPath> {
ContentType::Metadata(_) => TransferContent::LoadMeta,
ContentType::Specs => TransferContent::AddSpecs,
};
let passed_crypto = pass_crypto(&raw_read, transfer_content)
.map_err(|e| anyhow::Error::msg(format!("{:?}", e)))?;
let passed_crypto = pass_crypto(&raw_read, transfer_content).map_err(|e| anyhow!("{:?}", e))?;

let msg_type = match unsigned_qr.file_name.content_type {
ContentType::Metadata(_) => Msg::LoadMetadata,
ContentType::Specs => Msg::AddSpecs,
};
let tmp_dir = tempfile::tempdir()?;
let content_file = tmp_dir.path().join("content");
let mut f = File::create(&content_file)?;
f.write_all(passed_crypto.message.deref())?;

let make = Make {
goal: Goal::Qr,
crypto: Crypto::Sufficient(sufficient_crypto),
msg: msg_type(passed_crypto.message),
name: Some(signed_qr.to_string()),
verifier: Verifier {
verifier_alice: None,
verifier_hex: None,
verifier_file: None,
},
signature: Signature {
signature_hex: None,
signature_file: None,
},
sufficient: Sufficient {
sufficient_hex: Some(signature),
sufficient_file: None,
},
msg: msg_type,
name: Some(signed_qr.to_path_buf()),
files_dir: signed_qr.dir.clone(),
payload: content_file,
export_dir: signed_qr.dir.clone(),
crypto: Some(Encryption::Sr25519),
};
println!("⚙ generating {}...", signed_qr);
full_run(SignerCommand::Make(make)).map_err(anyhow::Error::msg)?;
full_run(SignerCommand::Make(make)).map_err(|e| anyhow!("{:?}", e))?;
// Preserve png source information
if let Some(png_source) = read_png_source(&unsigned_qr.to_path_buf())? {
save_source_info(&signed_qr.to_path_buf(), &png_source)?;
Expand Down
6 changes: 4 additions & 2 deletions cli/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use anyhow::Result;
use png::Encoder;
use serde::{Deserialize, Serialize};
use sp_core::H256;
use tempfile::tempdir;

const SOURCE: &str = "Source";

Expand All @@ -24,8 +25,9 @@ pub(crate) fn save_source_info(path: &Path, source: &Source) -> Result<()> {
// If the text chunk is before the image data frames, `reader.info()` already contains the text.
let in_info = reader.info();

let out_path = Path::new(r"/tmp/qr.apng");
let file = File::create(out_path).unwrap();
let tmp_dir = tempdir().unwrap();
let out_path = tmp_dir.path().join("qr.apng");
let file = File::create(&out_path).unwrap();
let w = &mut BufWriter::new(file);
let mut encoder = Encoder::new(w, in_info.width, in_info.height);
encoder.set_color(in_info.color_type);
Expand Down
Loading

0 comments on commit 0517f22

Please sign in to comment.