I am currently working on a cryptography project and I am new to Rust, and I am pretty confused on how to print out these public and private keys right now.
Goal: Print out the private and public key so I can see it.
Rust Code
pub use pqcrypto_dilithium::dilithium5::{
public_key_bytes as public_key_bytes,
secret_key_bytes as secret_key_bytes,
signature_bytes as signature_bytes,
verify_detached_signature as verify_detached_signature,
detached_sign as detached_sign,
keypair as keypair,
open as open,
sign as sign,
};
fn main () {
let (public_key, private_key) = keypair();
// Print variable here...
}
Cargo.toml
[package]
name = "project"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
pqcrypto-dilithium = "0.4.5"
Error
error[E0277]: `pqcrypto_dilithium::dilithium5::PublicKey` doesn't implement `Debug`
--> src\main.rs:14:23
|
14 | println!("{:#?}", public_key)
| ^^^^^^^^^^ `pqcrypto_dilithium::dilithium5::PublicKey` cannot be formatted using `{:?}` because it doesn't implement `Debug`
|
= help: the trait `Debug` is not implemented for `pqcrypto_dilithium::dilithium5::PublicKey`
= note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
Run this code using cargo run
In order to print an instance of any type with the {:?} formatting placeholder, the type has to implement the Debug trait. This trait tells rust how to display the contents of the instance.
Neither PublicKey nor SecretKey types directly implement Debug. However, both of them have methods that expose slices of u8 containing the keys: the as_bytes method.
Note that the as_bytes() method is part of a trait, pqcrypto_traits::sign::PublicKey. In order to use trait methods you need to have the trait in scope, so you have to use it in your source file.
Slices implement Debug as long as the slice elements implement Debug, which u8 does, so you can print a u8 slice.
use pqcrypto_traits::sign::PublicKey;
//...
println!("Public key: {:#?}", public_key.as_bytes());
The solution for me was the following
Adding pqcrypto-traits = "0.3.4" to Cargo.toml, and saving the .toml file.
Using pub use pqcrypto_traits::sign::PublicKey;, and saving the .rs file.
If you get problems with Sha256::new(), put pub use pqcrypto_traits::sign::PublicKey; under that line. This is what worked for me.
Related
I am learning yewdux and have implemented the tutorial code for global state:
use yew::prelude::*;
use yewdux::prelude::*;
#[derive(Default, Clone, PartialEq, Eq, Store)]
struct State {
count: u32,
}
#[function_component]
fn App() -> Html {
let (state, dispatch) = use_store::<State>();
let onclick = dispatch.reduce_mut_callback(|state| state.count += 1);
html! {
<>
<p>{ state.count }</p>
<button {onclick}>{"+1"}</button>
</>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
However I am getting a compiler error for the line:
let (state, dispatch) = use_store::<State>();
The compiler error reads:
error[E0277]: the trait bound `impl yew::functional::hooks::Hook<Output = (Rc<State>, Dispatch<State>)>: Hook` is not satisfied
--> src/main.rs:11:29
|
11 | let (state, dispatch) = use_store::<State>();
| ---------^^^^^^^^^^^
| |
| the trait `Hook` is not implemented for `impl yew::functional::hooks::Hook<Output = (Rc<State>, Dispatch<State>)>`
| required by a bound introduced by this call
|
= help: the trait `Hook` is implemented for `BoxedHook<'_, T>`
My Cargo.toml file is:
[package]
name = "yewdux_tutorial"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
yew = { git = "https://github.com/yewstack/yew/", features = ["csr"] }
stdweb = "0.4.20"
yewdux = "0.9.0"
Please could someone help point me in the right direction for solving this compiler error.
I have searched online for this this answer and found this question Failed to follow yew tutorial on Mac m1 - use of undeclared type `Vec` (Also on a mac m1) and followed the answer to no success.
I also attempted to manually implement a default Store on the State struct but that also did not fix it.
Try to add yew crate this way:
[dependencies]
yew = { version = "0.20", features = ["csr"] }
yewdux = "0.9"
When we did not specify yew by its source, we actually refer to the one in the official crate registry. But if we specify yew by its git repository, we refer to the crate at the default branch if no branch specified. The two crates are not the same in the eye of the Rust compiler.
The crate yewdux in the official crate registry probably also relies on the yew that is in the official crate registry as well, so we need to refer to yew in the official crate registry.
The file Cargo.lock shows more details about crate dependencies. If source = "registry+https://github.com/rust-lang/crates.io-index", then the crate is from the official crate registry. If source = "git+https://github.com/yewstack/yew.git#c40bd0b456f9c80146c99d56bc0b441c88c3fefe", then the crate is from the repo specified and the code version is at the commit c40bd0b456f9c80146c99d56bc0b441c88c3fefe.
Reference: https://intendednull.github.io/yewdux/setup.html#stable-release
I have the csvdump.rs code as:
impl EvaluatedTxOut {
#[inline]
fn as_csv(&self, txid: &str, index: usize) -> String {
let address = match self.script.address.clone() {
Some(address) => address,
None => {
debug!(target: "csvdump", "Unable to evaluate address for utxo in txid: {} ({})",
txid, self.script.pattern);
String::new()
}
};
// (#txid, indexOut, value, #scriptPubKey, address)
//format!("{};{};{};{};{}\n",
format!(
"{};\n",
//&txid,
//&index,
//&self.out.value,
//&utils::arr_to_hex(&self.out.script_pubkey),
&self.script.address
)
}
}
I get the following error:
Compiling rusty-blockparser v0.8.2 (C:\Users\allsc\Downloads\Compressed\rusty-blockparser-master\rusty-blockparser-master)
error[E0277]: `Option<std::string::String>` doesn't implement `std::fmt::Display`
--> src\callbacks\csvdump.rs:203:13
|
203 | &self.script.address)
| ^^^^^^^^^^^^^^^^^^^^ `Option<std::string::String>` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Option<std::string::String>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: this error originates in the macro `$crate::__export::format_args` which comes from the expansion of the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
warning: `rusty-blockparser` (bin "rusty-blockparser") generated 1 warning
error: could not compile `rusty-blockparser` due to previous error; 1 warning emitted
Can some one please help with this ?
To display variables, Rust uses traits. Currently, you're using format!("{}", ...), note the {}. The fact that the brackets are empty means you use the trait named Display. To resolve your issue, either you impl Display for Option<String>, or you use another trait. For debugging prints, you usually want to use format!("{:?}", ...), saying to use the Debug trait. Option implements Debug if and only if the type it depends on does also implement Debug, which is the case of String. Option doesn't implement Display however because this trait is meant to display to the user (and Option doesn't have one way to display that everyone wants).
You can find everything you need about formatting on https://doc.rust-lang.org/std/fmt/index.html
I'm using the prost crate in a very "hello world" way, with a basic ProtoBuf file:
foo.proto
syntax = "proto3";
package foo;
message Foo {
string mystring = 1;
}
I can verify the types that prost produces at compile time by inspecting ./target/PROJECT/build/PROJECT-{some hash}/out/foo.rs:
foo.rs
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
#[prost(string, tag="1")]
pub mystring: ::prost::alloc::string::String,
}
See that the prost::Message trait gets derived? Its docs claim I have tons of functions at my disposal for this trait, but only the two required ones, encoded_len() and clear(), can be called without error. Any of the provided ones (those with default implementations) result in a cannot find function in this scope error.
main.rs
use prost::Message;
pub mod foo {
include!(concat!(env!("OUT_DIR"), "/foo.rs"));
}
fn main() {
let f = foo::Foo { mystring: "bar".to_string() };
let v = encode_to_vec(&f);
}
cargo run
error[E0425]: cannot find function `encode_to_vec` in this scope
|
| let v = encode_to_vec(&f);
| ^^^^^^^^^^^^^ not found in this scope
And, worryingly, this warning implies it's not even looking at the trait it needs to:
warning: unused import: prost::Message
(edit) For reference:
Cargo.toml
[package]
name = "testing"
version = "0.1.0"
edition = "2018"
[dependencies]
prost = { version = "0.7.0", features = ["std"] }
[build-dependencies]
prost-build = "0.7.0"
encode_to_vec is not a free function. You need to call it as one of
f.encode_to_vec()
foo::Foo::encode_to_vec(&f)
Message::encode_to_vec(&f)
<foo::Foo as Message>::encode_to_vec(&f)
The first method is the most normal, but the other ones may produce useful error messages when you get confused about what's going on.
[Edit:] Well, encode_to_vec was added in prost 0.8.0, so with 0.7.0, it won't be usable.
How would I decode the standard Substrate extrinsic format into a Transaction object in a way where it would be possible to get the Sender, preferably as a string?
I have started with this code with a hardcoded sample extrinsic data for testing in the extrinsic_hex variable:
use hex::decode;
use hex_literal::hex;
use parity_codec::{Decode, Encode, Input};
use primitives::generic::UncheckedMortalExtrinsic;
use std::fmt;
use std::fmt::Debug;
fn main() {
let extrinsic_hex: &'static str = "81ffd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d3c6b8941e2976034e67bdd1a999c3eff4403c8ceaf717f18d9760ab18573ab2ce870e9b751c2f14dd9883e54746e1eb6639978ceab49968c25176cc0d2507205040003000ca10f";
let result = hex::decode(extrinsic_hex);
match result {
Ok(v1) => {
let extr_option = UncheckedMortalExtrinsic::decode(&mut v1);
()
}
_ => {
println!("Error decoding");
()
}
}
}
The error I get is:
error: duplicate lang item in crate `sr_io`: `panic_impl`.
|
= note: first defined in crate `std`.
error: duplicate lang item in crate `sr_io`: `oom`.
|
= note: first defined in crate `std`.
error[E0277]: the trait bound `std::vec::Vec<u8>: parity_codec::codec::Input` is not satisfied
--> core/decaddr/src/main.rs:13:20
|
13 | let extr_option=UncheckedMortalExtrinsic::decode(&mut v1);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `parity_codec::codec::Input` is not implemented for `std::vec::Vec<u8>`
|
= note: required by `parity_codec::codec::Decode::decode`
Let's pretend that the error error: duplicate lang item in cratesr_io:panic_impl. doesn't exist for now.
If I am understanding correctly, it doesn't work because Vec doesn't implement the parity_codec::Input trait, am I right? If so, how would one add this trait to Vec? Or better said, what are the functions from the Substrate framework I am missing so the Input trait is automatically provided?
If so, how would one add this trait to Vec ?
In your code, you can't. For coherence reasons, Rust says that an implementation of a trait X for a type Y must exist in the crate for X or the crate for Y.
Or better said, what are the functions from Susbtrate framework I am missing so the Input trait is automatically provided?
If you look at the "Implementors" part of the Input trait documentation - you can see that every type that implements std::io::Read will implement Input.
As the comments say, the implementation that is useful for you is the one on &[u8], which exists because it implements std::io::Read.
I'd like to write a server that resizes a huge image. Since loading it on every request would take a lot of time, I decided to pre-load it. Unfortunately I got the following error:
Compiling hello_world v0.0.0 (/tmp/Rocket/examples/hello_world)
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> examples/hello_world/src/main.rs:9:35
|
9 | static img: image::DynamicImage = image::open("/home/d33tah/tmp/combined.png").unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> examples/hello_world/src/main.rs:9:35
|
9 | static img: image::DynamicImage = image::open("/home/d33tah/tmp/combined.png").unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0015`.
error: Could not compile `hello_world`.
To learn more, run the command again with --verbose.
Here's the code:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[cfg(test)] mod tests;
extern crate image;
static img: image::DynamicImage = image::open("/home/d33tah/tmp/combined.png").unwrap();
#[get("/")]
fn hello() -> Vec<u8> {
"".into()
}
fn main() {
rocket::ignite().mount("/", routes![hello]).launch();
}
To compile it, you'll need rocket installed based on its latest Github checkout (currently: 831d8dfbe30dd69f0367a75361e027127b2100e1) and image crate.
Is it possible to create such a global variable? If not, do I have any other options?
EDIT: this was flagged as a duplicate of this question, but as Boiethios showed, this specific case is better solved by Rocket's API.
If you want to share something in Rocket, you will have to use a managed state:
Say to Rocket you want to manage the resource:
let image = image::open("/home/d33tah/tmp/combined.png").unwrap();
rocket::ignite().manage(image);
Retrieve it in the routes where you need it:
#[get("/foo")]
fn foo(image: State<DynamicImage>) {
// Can use `image`.
}