What changed, and why it matters
This is a large code-cleanup commit titled 'fix: run fmt and rust fix'. It applies Rust formatting, clippy lint fixes, and removes unstable nightly feature flags across many Rust files in the Keystone 3 firmware. The changes are mostly stylistic or idiomatic (e.g., replacing manual loops with while-let, using OsRng instead of deterministic seeds for Monero bulletproofs/CLSAG signatures, changing pointer-safety annotations to unsafe, and removing unused imports). There is no explicit vendor statement that this fixes a security vulnerability, and the diff does not show a clear, exploitable bug fix. However, the Monero RNG change is a meaningful functional change that could affect cryptographic security if the prior deterministic seeding was flawed, and the broad unsafe FFI annotation changes could hide or expose memory-safety issues. Overall the commit appears to be a routine refactor/tooling fix rather than a targeted security patch.
Treat this as a maintenance/refactor commit. Review the Monero RNG changes specifically to confirm they do not alter expected deterministic behavior required by protocol or tests, and verify that switching to OsRng is appropriate for all affected cryptographic operations. Audit the new extract_array! macro and unsafe FFI annotations for correctness. Investigate the build.rs change that silently ignores cbindgen errors, as this could cause stale or missing C headers without failing the build. No immediate security patch deployment is indicated by the supplied materials alone.
Security signals we found
Monero RNG source changed from deterministic ChaCha20Rng seeds (derived from transaction/extra data) to OsRng for bulletproofs, CLSAG signatures, and transaction keys
Many FFI functions re-annotated as unsafe extern "C" and raw-pointer length validation centralized via extract_array! macro
build.rs now silently ignores cbindgen binding-generation errors (empty error closure)
Removed unstable nightly feature gates (#![feature(error_in_core)], #![feature(prelude_2024)])
Large refactor touching 133 files with no explicit security context from the vendor
Evidence from the diff
The commit modifies 133 files, almost entirely in the Rust codebase. Key categories of change: (1) rustfmt/clippy style fixes—inline format args, replace loop/match with while-let, use is_empty(), use repeat_n, remove redundant clones, simplify match/return patterns; (2) removal of #![feature(error_in_core)] and #![feature(prelude_2024)] feature gates, indicating a move toward stable Rust; (3) API signature cleanups such as changing Vec
Changed components
rust/apps/monero (transaction signing, bulletproofs, CLSAG, key images, outputs)rust/rust_c FFI bindings (aptos, arweave, avalanche, bitcoin, cardano, cosmos, ethereum, iota, monero, near, solana, stellar, sui, ton, tron, xrp, zcash, wallet modules)rust/apps/aptos, arweave, bitcoin, cosmos, ethereum, solana, ton, utils, wallets, keystorerust/rust_c/Cargo.toml default featurerust/rust_c/build.rs cbindgen generationInspect captured patch +1805 / −1999
diff --git a/.gitignore b/.gitignore
index 2fe2940..a2cba79 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,4 +13,5 @@ pyenv
!/rust/apps/target/
!/rust/apps/Cargo.lock
*.rustfmt.toml
-/tools/boot.sig
\ No newline at end of file
+/tools/boot.sig
+/target
\ No newline at end of file
diff --git a/rust/apps/aptos/src/aptos_type/account_address.rs b/rust/apps/aptos/src/aptos_type/account_address.rs
index 0280fea..d30c5f0 100644
--- a/rust/apps/aptos/src/aptos_type/account_address.rs
+++ b/rust/apps/aptos/src/aptos_type/account_address.rs
@@ -51,8 +51,7 @@ impl AccountAddress {
pub fn from_hex_literal(literal: &str) -> crate::errors::Result<Self> {
if !literal.starts_with("0x") {
return Err(crate::errors::AptosError::InvalidData(format!(
- "{} not start with 0x",
- literal
+ "{literal} not start with 0x"
)));
}
@@ -82,7 +81,7 @@ impl AccountAddress {
}
pub fn to_hex(&self) -> String {
- format!("{:x}", self)
+ format!("{self:x}")
}
pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> crate::errors::Result<Self> {
@@ -108,13 +107,13 @@ impl core::ops::Deref for AccountAddress {
impl fmt::Display for AccountAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
- write!(f, "{:x}", self)
+ write!(f, "{self:x}")
}
}
impl fmt::Debug for AccountAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{:x}", self)
+ write!(f, "{self:x}")
}
}
@@ -125,7 +124,7 @@ impl fmt::LowerHex for AccountAddress {
}
for byte in &self.0 {
- write!(f, "{:02x}", byte)?;
+ write!(f, "{byte:02x}")?;
}
Ok(())
@@ -139,7 +138,7 @@ impl fmt::UpperHex for AccountAddress {
}
for byte in &self.0 {
- write!(f, "{:02X}", byte)?;
+ write!(f, "{byte:02X}")?;
}
Ok(())
diff --git a/rust/apps/aptos/src/aptos_type/chain_id.rs b/rust/apps/aptos/src/aptos_type/chain_id.rs
index 396ef39..4d55955 100644
--- a/rust/apps/aptos/src/aptos_type/chain_id.rs
+++ b/rust/apps/aptos/src/aptos_type/chain_id.rs
@@ -39,8 +39,7 @@ impl NamedChain {
PREMAINNET => NamedChain::PREMAINNET,
_ => {
return Err(crate::errors::AptosError::ParseTxError(format!(
- "Not a reserved chain: {:?}",
- s
+ "Not a reserved chain: {s:?}"
)));
}
};
@@ -107,7 +106,7 @@ where
impl fmt::Debug for ChainId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", self)
+ write!(f, "{self}")
}
}
@@ -157,7 +156,7 @@ impl FromStr for ChainId {
let value = s
.parse::<u8>()
.map_err(|e| crate::errors::AptosError::ParseTxError(e.to_string()))?;
- if value <= 0 {
+ if value == 0 {
return Err(crate::errors::AptosError::ParseTxError(
"cannot have chain ID with 0".to_string(),
));
diff --git a/rust/apps/aptos/src/aptos_type/identifier.rs b/rust/apps/aptos/src/aptos_type/identifier.rs
index 7327c9a..65c8916 100644
--- a/rust/apps/aptos/src/aptos_type/identifier.rs
+++ b/rust/apps/aptos/src/aptos_type/identifier.rs
@@ -55,8 +55,7 @@ impl Identifier {
Ok(Self(s))
} else {
Err(AptosError::ParseTxError(format!(
- "Invalid identifier '{}'",
- s
+ "Invalid identifier '{s}'"
)))
}
}
@@ -131,8 +130,7 @@ impl IdentStr {
Ok(IdentStr::ref_cast(s))
} else {
Err(AptosError::ParseTxError(format!(
- "Invalid identifier '{}'",
- s
+ "Invalid identifier '{s}'"
)))
}
}
diff --git a/rust/apps/aptos/src/aptos_type/language_storage.rs b/rust/apps/aptos/src/aptos_type/language_storage.rs
index df50102..ef369c0 100644
--- a/rust/apps/aptos/src/aptos_type/language_storage.rs
+++ b/rust/apps/aptos/src/aptos_type/language_storage.rs
@@ -174,9 +174,9 @@ impl Display for StructTag {
)?;
if let Some(first_ty) = self.type_params.first() {
write!(f, "<")?;
- write!(f, "{}", first_ty)?;
+ write!(f, "{first_ty}")?;
for ty in self.type_params.iter().skip(1) {
- write!(f, ", {}", ty)?;
+ write!(f, ", {ty}")?;
}
write!(f, ">")?;
}
@@ -187,8 +187,8 @@ impl Display for StructTag {
impl Display for TypeTag {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
match self {
- TypeTag::Struct(s) => write!(f, "{}", s),
- TypeTag::Vector(ty) => write!(f, "vector<{}>", ty),
+ TypeTag::Struct(s) => write!(f, "{s}"),
+ TypeTag::Vector(ty) => write!(f, "vector<{ty}>"),
TypeTag::U8 => write!(f, "u8"),
TypeTag::U64 => write!(f, "u64"),
TypeTag::U128 => write!(f, "u128"),
diff --git a/rust/apps/aptos/src/aptos_type/parser.rs b/rust/apps/aptos/src/aptos_type/parser.rs
index a7d81c3..c27da5c 100644
--- a/rust/apps/aptos/src/aptos_type/parser.rs
+++ b/rust/apps/aptos/src/aptos_type/parser.rs
@@ -235,8 +235,7 @@ impl<I: Iterator<Item = Token>> Parser<I> {
let t = self.next()?;
if t != tok {
return Err(AptosError::ParseTxError(format!(
- "expected token {:?}, got {:?}",
- tok, t
+ "expected token {tok:?}, got {t:?}"
)));
}
Ok(())
@@ -273,8 +272,7 @@ impl<I: Iterator<Item = Token>> Parser<I> {
Token::Name(s) => s,
tok => {
return Err(AptosError::ParseTxError(format!(
- "unexpected token {:?}, expected string",
- tok
+ "unexpected token {tok:?}, expected string"
)))
}
})
@@ -283,8 +281,7 @@ impl<I: Iterator<Item = Token>> Parser<I> {
fn parse_type_tag(&mut self, depth: u8) -> crate::errors::Result<TypeTag> {
if depth >= safe_serialize::MAX_TYPE_TAG_NESTING {
AptosError::ParseTxError(format!(
- "Exceeded TypeTag nesting limit during parsing: {}",
- depth
+ "Exceeded TypeTag nesting limit during parsing: {depth}"
));
}
@@ -329,24 +326,21 @@ impl<I: Iterator<Item = Token>> Parser<I> {
}
t => {
return Err(AptosError::ParseTxError(format!(
- "expected name, got {:?}",
- t
+ "expected name, got {t:?}"
)))
}
}
}
t => {
return Err(AptosError::ParseTxError(format!(
- "expected name, got {:?}",
- t
+ "expected name, got {t:?}"
)))
}
}
}
tok => {
return Err(AptosError::ParseTxError(format!(
- "unexpected token {:?}, expected type tag",
- tok
+ "unexpected token {tok:?}, expected type tag"
)))
}
})
@@ -365,8 +359,7 @@ impl<I: Iterator<Item = Token>> Parser<I> {
Token::Bytes(s) => TransactionArgument::U8Vector(hex::decode(s)?),
tok => {
return Err(AptosError::ParseTxError(format!(
- "unexpected token {:?}, expected transaction argument",
- tok
+ "unexpected token {tok:?}, expected transaction argument"
)))
}
})
@@ -420,13 +413,12 @@ pub fn parse_transaction_argument(s: &str) -> crate::errors::Result<TransactionA
pub fn parse_struct_tag(s: &str) -> crate::errors::Result<StructTag> {
let type_tag = parse(s, |parser| parser.parse_type_tag(0))
- .map_err(|e| AptosError::ParseTxError(format!("invalid struct tag: {}, {}", s, e)))?;
+ .map_err(|e| AptosError::ParseTxError(format!("invalid struct tag: {s}, {e}")))?;
if let TypeTag::Struct(struct_tag) = type_tag {
Ok(*struct_tag)
} else {
Err(AptosError::ParseTxError(format!(
- "invalid struct tag: {}",
- s
+ "invalid struct tag: {s}"
)))
}
}
diff --git a/rust/apps/aptos/src/aptos_type/transaction_argument.rs b/rust/apps/aptos/src/aptos_type/transaction_argument.rs
index 63843a6..ff09152 100644
--- a/rust/apps/aptos/src/aptos_type/transaction_argument.rs
+++ b/rust/apps/aptos/src/aptos_type/transaction_argument.rs
@@ -19,11 +19,11 @@ pub enum TransactionArgument {
impl fmt::Debug for TransactionArgument {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- TransactionArgument::U8(value) => write!(f, "{{U8: {}}}", value),
- TransactionArgument::U64(value) => write!(f, "{{U64: {}}}", value),
- TransactionArgument::U128(value) => write!(f, "{{U128: {}}}", value),
- TransactionArgument::Bool(boolean) => write!(f, "{{BOOL: {}}}", boolean),
- TransactionArgument::Address(address) => write!(f, "{{ADDRESS: {:?}}}", address),
+ TransactionArgument::U8(value) => write!(f, "{{U8: {value}}}"),
+ TransactionArgument::U64(value) => write!(f, "{{U64: {value}}}"),
+ TransactionArgument::U128(value) => write!(f, "{{U128: {value}}}"),
+ TransactionArgument::Bool(boolean) => write!(f, "{{BOOL: {boolean}}}"),
+ TransactionArgument::Address(address) => write!(f, "{{ADDRESS: {address:?}}}"),
TransactionArgument::U8Vector(vector) => {
write!(f, "{{U8Vector: 0x{}}}", hex::encode(vector))
}
@@ -60,8 +60,7 @@ impl TryFrom<MoveValue> for TransactionArgument {
Ok(byte)
} else {
Err(crate::errors::AptosError::ParseTxError(format!(
- "unexpected value in bytes: {:?}",
- mv
+ "unexpected value in bytes: {mv:?}"
)))
}
})
@@ -69,8 +68,7 @@ impl TryFrom<MoveValue> for TransactionArgument {
),
MoveValue::Signer(_) | MoveValue::Struct(_) => {
return Err(crate::errors::AptosError::ParseTxError(format!(
- "invalid transaction argument: {:?}",
- val
+ "invalid transaction argument: {val:?}"
)))
}
})
diff --git a/rust/apps/aptos/src/aptos_type/value.rs b/rust/apps/aptos/src/aptos_type/value.rs
index 170bd79..c359e19 100644
--- a/rust/apps/aptos/src/aptos_type/value.rs
+++ b/rust/apps/aptos/src/aptos_type/value.rs
@@ -493,8 +493,8 @@ impl fmt::Display for MoveTypeLayout {
U64 => write!(f, "u64"),
U128 => write!(f, "u128"),
Address => write!(f, "address"),
- Vector(typ) => write!(f, "vector<{}>", typ),
- Struct(s) => write!(f, "{}", s),
+ Vector(typ) => write!(f, "vector<{typ}>"),
+ Struct(s) => write!(f, "{s}"),
Signer => write!(f, "signer"),
}
}
@@ -510,19 +510,19 @@ impl fmt::Display for MoveStructLayout {
tag: _,
} => {
for (i, l) in layouts.iter().enumerate() {
- write!(f, "{}: {}, ", i, l)?
+ write!(f, "{i}: {l}, ")?
}
}
Self::WithFields(layouts) => {
for layout in layouts {
- write!(f, "{}, ", layout)?
+ write!(f, "{layout}, ")?
}
}
Self::WithTypes { type_, fields } => {
- write!(f, "Type: {}", type_)?;
+ write!(f, "Type: {type_}")?;
write!(f, "Fields:")?;
for field in fields {
- write!(f, "{}, ", field)?
+ write!(f, "{field}, ")?
}
}
}
@@ -567,9 +567,9 @@ impl TryInto<StructTag> for &MoveStructLayout {
impl fmt::Display for MoveValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- MoveValue::U8(u) => write!(f, "{}u8", u),
- MoveValue::U64(u) => write!(f, "{}u64", u),
- MoveValue::U128(u) => write!(f, "{}u128", u),
+ MoveValue::U8(u) => write!(f, "{u}u8"),
+ MoveValue::U64(u) => write!(f, "{u}u64"),
+ MoveValue::U128(u) => write!(f, "{u}u128"),
MoveValue::Bool(false) => write!(f, "false"),
MoveValue::Bool(true) => write!(f, "true"),
MoveValue::Address(a) => write!(f, "{}", a.to_hex_literal()),
@@ -600,7 +600,7 @@ struct DisplayFieldBinding<'a>(&'a (Identifier, MoveValue));
impl fmt::Display for DisplayFieldBinding<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let DisplayFieldBinding((field, value)) = self;
- write!(f, "{}: {}", field, value)
+ write!(f, "{field}: {value}")
}
}
@@ -610,14 +610,14 @@ fn fmt_list<T: fmt::Display>(
items: impl IntoIterator<Item = T>,
end: &str,
) -> fmt::Result {
- write!(f, "{}", begin)?;
+ write!(f, "{begin}")?;
let mut items = items.into_iter();
if let Some(x) = items.next() {
- write!(f, "{}", x)?;
+ write!(f, "{x}")?;
for x in items {
- write!(f, ", {}", x)?;
+ write!(f, ", {x}")?;
}
}
- write!(f, "{}", end)?;
+ write!(f, "{end}")?;
Ok(())
}
diff --git a/rust/apps/aptos/src/errors.rs b/rust/apps/aptos/src/errors.rs
index c956ad4..1b105ca 100644
--- a/rust/apps/aptos/src/errors.rs
+++ b/rust/apps/aptos/src/errors.rs
@@ -26,24 +26,24 @@ impl From<KeystoreError> for AptosError {
impl From<hex::FromHexError> for AptosError {
fn from(value: hex::FromHexError) -> Self {
- Self::InvalidData(format!("hex operation failed {}", value))
+ Self::InvalidData(format!("hex operation failed {value}"))
}
}
impl From<FromUtf8Error> for AptosError {
fn from(value: FromUtf8Error) -> Self {
- Self::InvalidData(format!("utf8 operation failed {}", value))
+ Self::InvalidData(format!("utf8 operation failed {value}"))
}
}
impl From<core::num::ParseIntError> for AptosError {
fn from(value: core::num::ParseIntError) -> Self {
- Self::InvalidData(format!("parseInt Failed {}", value))
+ Self::InvalidData(format!("parseInt Failed {value}"))
}
}
impl From<bcs::Error> for AptosError {
fn from(value: bcs::Error) -> Self {
- Self::InvalidData(format!("bsc operation failed {}", value))
+ Self::InvalidData(format!("bsc operation failed {value}"))
}
}
diff --git a/rust/apps/aptos/src/parser.rs b/rust/apps/aptos/src/parser.rs
index 280191d..efc764f 100644
--- a/rust/apps/aptos/src/parser.rs
+++ b/rust/apps/aptos/src/parser.rs
@@ -42,7 +42,7 @@ impl Parser {
data_parse = data[32..].to_vec();
}
let tx: RawTransaction = bcs::from_bytes(&data_parse)
- .map_err(|err| AptosError::ParseTxError(format!("bcs deserialize failed {}", err)))?;
+ .map_err(|err| AptosError::ParseTxError(format!("bcs deserialize failed {err}")))?;
Ok(AptosTx::new(tx))
}
pub fn parse_msg(data: &Vec<u8>) -> Result<String> {
@@ -70,13 +70,13 @@ impl AptosTx {
pub fn get_formatted_json(&self) -> Result<Value> {
match serde_json::to_string_pretty(&self.tx) {
Ok(v) => Ok(Value::String(v)),
- Err(e) => Err(AptosError::ParseTxError(format!("to json failed {}", e))),
+ Err(e) => Err(AptosError::ParseTxError(format!("to json failed {e}"))),
}
}
fn to_json_value(&self) -> Result<Value> {
let value = serde_json::to_value(&self.tx)
- .map_err(|e| AptosError::ParseTxError(format!("to json failed {}", e)))?;
+ .map_err(|e| AptosError::ParseTxError(format!("to json failed {e}")))?;
Ok(value)
}
diff --git a/rust/apps/arweave/src/ao_transaction.rs b/rust/apps/arweave/src/ao_transaction.rs
index bb2c8f5..3472811 100644
--- a/rust/apps/arweave/src/ao_transaction.rs
+++ b/rust/apps/arweave/src/ao_transaction.rs
@@ -42,11 +42,9 @@ impl TryFrom<DataItem> for AOTransferTransaction {
let to = recipient.get_value();
let quantity = quantity.get_value();
let mut tags = vec![];
- loop {
- match rest_tags.next() {
- Some(tag) => tags.push(tag.clone()),
- None => break,
- }
+
+ while let Some(tag) = rest_tags.next() {
+ tags.push(tag.clone());
}
let token_info = find_token(&token_id);
diff --git a/rust/apps/arweave/src/data_item.rs b/rust/apps/arweave/src/data_item.rs
index 3be77cf..ab1c98b 100644
--- a/rust/apps/arweave/src/data_item.rs
+++ b/rust/apps/arweave/src/data_item.rs
@@ -64,7 +64,7 @@ fn avro_decode_long(reader: &mut Vec<u8>) -> Result<i64> {
fn avro_decode_string(reader: &mut Vec<u8>) -> Result<String> {
let len = avro_decode_long(reader)?;
let buf = reader.drain(..len as usize).collect();
- String::from_utf8(buf).map_err(|e| ArweaveError::AvroError(format!("{}", e)))
+ String::from_utf8(buf).map_err(|e| ArweaveError::AvroError(format!("{e}")))
}
impl_public_struct!(DataItem {
diff --git a/rust/apps/arweave/src/lib.rs b/rust/apps/arweave/src/lib.rs
index e32a746..13b09e7 100644
--- a/rust/apps/arweave/src/lib.rs
+++ b/rust/apps/arweave/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
pub mod ao_transaction;
pub mod data_item;
@@ -82,12 +81,12 @@ pub fn generate_secret(seed: &[u8]) -> Result<RsaPrivateKey> {
fn u64_to_ar(value: u64) -> String {
let value = value as f64 / 1_000_000_000_000.0;
- let value = format!("{:.12}", value);
+ let value = format!("{value:.12}");
let value = value.trim_end_matches('0').to_string();
if value.ends_with('.') {
format!("{} AR", &value[..value.len() - 1])
} else {
- format!("{} AR", value)
+ format!("{value} AR")
}
}
@@ -139,13 +138,13 @@ pub fn parse(data: &Vec<u8>) -> Result<String> {
"quantity": u64_to_ar(tx.quantity),
"reward": u64_to_ar(tx.reward),
"data_size": tx.data_size,
- "signature_data": tx.deep_hash().map_or_else(|e| format!("unable to deep hash transaction, reason: {}", e), hex::encode),
+ "signature_data": tx.deep_hash().map_or_else(|e| format!("unable to deep hash transaction, reason: {e}"), hex::encode),
},
"status": "success"
})
}
Err(e) => {
- let readable = format!("unable to deserialize, reason: {}", e);
+ let readable = format!("unable to deserialize, reason: {e}");
json!({
"status": "failed",
"reason": readable
diff --git a/rust/apps/arweave/src/transaction.rs b/rust/apps/arweave/src/transaction.rs
index c6bec1e..caab798 100644
--- a/rust/apps/arweave/src/transaction.rs
+++ b/rust/apps/arweave/src/transaction.rs
@@ -54,7 +54,7 @@ pub mod stringify {
{
String::deserialize(deserializer)?
.parse::<T>()
- .map_err(|e| D::Error::custom(format!("{}", e)))
+ .map_err(|e| D::Error::custom(format!("{e}")))
}
pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
@@ -62,7 +62,7 @@ pub mod stringify {
S: Serializer,
T: fmt::Display,
{
- format!("{}", value).serialize(serializer)
+ format!("{value}").serialize(serializer)
}
}
@@ -160,7 +160,7 @@ pub struct Base64(pub Vec<u8>);
impl fmt::Display for Base64 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let string = &base64::display::Base64Display::with_config(&self.0, base64::URL_SAFE_NO_PAD);
- write!(f, "{}", string)
+ write!(f, "{string}")
}
}
diff --git a/rust/apps/bitcoin/src/lib.rs b/rust/apps/bitcoin/src/lib.rs
index a36d311..1a885aa 100644
--- a/rust/apps/bitcoin/src/lib.rs
+++ b/rust/apps/bitcoin/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
#[allow(unused_imports)] // stupid compiler
#[macro_use]
diff --git a/rust/apps/cosmos/src/errors.rs b/rust/apps/cosmos/src/errors.rs
index 56122a9..7a7080a 100644
--- a/rust/apps/cosmos/src/errors.rs
+++ b/rust/apps/cosmos/src/errors.rs
@@ -41,18 +41,18 @@ impl From<KeystoreError> for CosmosError {
impl From<hex::FromHexError> for CosmosError {
fn from(value: hex::FromHexError) -> Self {
- Self::InvalidData(format!("hex operation failed {}", value))
+ Self::InvalidData(format!("hex operation failed {value}"))
}
}
impl From<serde_json::Error> for CosmosError {
fn from(value: serde_json::Error) -> Self {
- Self::InvalidData(format!("serde_json operation failed {}", value))
+ Self::InvalidData(format!("serde_json operation failed {value}"))
}
}
impl From<core::num::ParseFloatError> for CosmosError {
fn from(value: core::num::ParseFloatError) -> Self {
- CosmosError::InvalidData(format!("parse float failed {}", value))
+ CosmosError::InvalidData(format!("parse float failed {value}"))
}
}
diff --git a/rust/apps/cosmos/src/lib.rs b/rust/apps/cosmos/src/lib.rs
index 2be28e8..99f9926 100644
--- a/rust/apps/cosmos/src/lib.rs
+++ b/rust/apps/cosmos/src/lib.rs
@@ -98,7 +98,7 @@ pub fn derive_address(
let sub_path = hd_path
.strip_prefix(&root_path)
.ok_or(CosmosError::InvalidHDPath(hd_path.to_string()))?;
- derive_public_key(&root_x_pub.to_string(), &format!("m/{}", sub_path))
+ derive_public_key(&root_x_pub.to_string(), &format!("m/{sub_path}"))
.map(|public_key| generate_address(public_key, prefix))
.map_err(CosmosError::from)?
}
diff --git a/rust/apps/cosmos/src/proto_wrapper/fee.rs b/rust/apps/cosmos/src/proto_wrapper/fee.rs
index 0cbd397..219e83d 100644
--- a/rust/apps/cosmos/src/proto_wrapper/fee.rs
+++ b/rust/apps/cosmos/src/proto_wrapper/fee.rs
@@ -86,8 +86,7 @@ pub fn parse_gas_limit(gas: &serde_json::Value) -> Result<f64> {
return Ok(gas_limit);
}
Err(CosmosError::InvalidData(format!(
- "failed to parse gas {:?}",
- gas
+ "failed to parse gas {gas:?}"
)))
}
@@ -122,7 +121,7 @@ pub fn format_fee_from_value(data: serde_json::Value) -> Result<FeeDetail> {
))
} else {
max_fee.push(format!("{} {}", value * gas_limit, denom));
- fee.push(format!("{} {}", value, denom));
+ fee.push(format!("{value} {denom}"));
};
}
}
diff --git a/rust/apps/cosmos/src/proto_wrapper/msg/common.rs b/rust/apps/cosmos/src/proto_wrapper/msg/common.rs
index 0e84807..f067b72 100644
--- a/rust/apps/cosmos/src/proto_wrapper/msg/common.rs
+++ b/rust/apps/cosmos/src/proto_wrapper/msg/common.rs
@@ -15,17 +15,17 @@ use alloc::vec::Vec;
use crate::CosmosError;
-pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosError> {
+pub fn map_messages(messages: &[Any]) -> Result<Vec<Box<dyn Msg>>, CosmosError> {
let mut message_vec: Vec<Box<dyn Msg>> = Vec::new();
- for message in messages.iter() {
+ for message in messages {
match message.type_url.as_str() {
MsgSendWrapper::TYPE_URL => {
let unpacked: proto::cosmos::bank::v1beta1::MsgSend = MessageExt::from_any(message)
.map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgSend deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgSend deserialize failed {e}"))
})?;
let msg_send = MsgSendWrapper::try_from(&unpacked).map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgSend deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgSend deserialize failed {e}"))
})?;
message_vec.push(Box::new(msg_send));
}
@@ -33,12 +33,11 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::cosmos::staking::v1beta1::MsgDelegate =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgDelegate deserialize failed {}",
- e
+ "proto MsgDelegate deserialize failed {e}"
))
})?;
let msg_delegate = MsgDelegateWrapper::try_from(&unpacked).map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgDelegate deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgDelegate deserialize failed {e}"))
})?;
message_vec.push(Box::new(msg_delegate));
}
@@ -46,14 +45,12 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::cosmos::staking::v1beta1::MsgUndelegate =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgUndelegate deserialize failed {}",
- e
+ "proto MsgUndelegate deserialize failed {e}"
))
})?;
let msg_undelegate = MsgUnDelegateWrapper::try_from(&unpacked).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgUndelegate deserialize failed {}",
- e
+ "proto MsgUndelegate deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_undelegate));
@@ -62,22 +59,21 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::ibc::applications::transfer::v1::MsgTransfer =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgTransfer deserialize failed {}",
- e
+ "proto MsgTransfer deserialize failed {e}"
))
})?;
let msg_transfer = MsgTransferWrapper::try_from(&unpacked).map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgTransfer deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgTransfer deserialize failed {e}"))
})?;
message_vec.push(Box::new(msg_transfer));
}
MsgVoteWrapper::TYPE_URL => {
let unpacked: proto::cosmos::gov::v1beta1::MsgVote =
proto::cosmos::gov::v1beta1::MsgVote::decode(&*message.value).map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgVote deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgVote deserialize failed {e}"))
})?;
let msg_vote = MsgVoteWrapper::try_from(&unpacked).map_err(|e| {
- CosmosError::ParseTxError(format!("proto MsgVote deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto MsgVote deserialize failed {e}"))
})?;
message_vec.push(Box::new(msg_vote));
}
@@ -85,15 +81,13 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::cosmos::distribution::v1beta1::MsgWithdrawDelegatorReward =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgTransfer deserialize failed {}",
- e
+ "proto MsgTransfer deserialize failed {e}"
))
})?;
let msg_withdraw_reward = MsgWithdrawDelegatorRewardWrapper::try_from(&unpacked)
.map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgTransfer deserialize failed {}",
- e
+ "proto MsgTransfer deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_withdraw_reward));
@@ -102,15 +96,13 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::cosmos::staking::v1beta1::MsgBeginRedelegate =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgTransfer deserialize failed {}",
- e
+ "proto MsgTransfer deserialize failed {e}"
))
})?;
let msg_redelegate =
MsgBeginRedelegateWrapper::try_from(&unpacked).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgTransfer deserialize failed {}",
- e
+ "proto MsgTransfer deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_redelegate));
@@ -119,14 +111,12 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
let unpacked: proto::cosmos::bank::v1beta1::MsgMultiSend =
MessageExt::from_any(message).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
})?;
let msg_multi_send = MsgMultiSendWrapper::try_from(&unpacked).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_multi_send));
@@ -136,15 +126,13 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
proto::ibc::core::client::v1::MsgUpdateClient::decode(&*message.value)
.map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
})?;
let msg_update_client =
MsgUpdateClientWrapper::try_from(&unpacked).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_update_client));
@@ -154,15 +142,13 @@ pub fn map_messages(messages: &Vec<Any>) -> Result<Vec<Box<dyn Msg>>, CosmosErro
proto::cosmos::authz::v1beta1::MsgExec::decode(&*message.value).map_err(
|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
},
)?;
let msg_exec = MsgExecWrapper::try_from(&unpacked).map_err(|e| {
CosmosError::ParseTxError(format!(
- "proto MsgMultiSend deserialize failed {}",
- e
+ "proto MsgMultiSend deserialize failed {e}"
))
})?;
message_vec.push(Box::new(msg_exec));
diff --git a/rust/apps/cosmos/src/proto_wrapper/msg/msg.rs b/rust/apps/cosmos/src/proto_wrapper/msg/msg.rs
index 5c5efeb..c4db0a1 100644
--- a/rust/apps/cosmos/src/proto_wrapper/msg/msg.rs
+++ b/rust/apps/cosmos/src/proto_wrapper/msg/msg.rs
@@ -18,7 +18,7 @@ pub struct NotSupportMessage {
impl SerializeJson for NotSupportMessage {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("NotSupportMessage serialize failed {}", err))
+ CosmosError::ParseTxError(format!("NotSupportMessage serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -64,7 +64,7 @@ impl TryFrom<&proto::cosmos::bank::v1beta1::MsgSend> for MsgSend {
impl SerializeJson for MsgSend {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgSend serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgSend serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -93,11 +93,10 @@ impl TryFrom<&proto::cosmos::staking::v1beta1::MsgDelegate> for MsgDelegate {
fn try_from(
proto: &proto::cosmos::staking::v1beta1::MsgDelegate,
) -> Result<MsgDelegate, CosmosError> {
- let amount: Option<Coin>;
- match &proto.amount {
- Some(coin) => amount = Some(coin.try_into()?),
- None => amount = None,
- }
+ let amount: Option<Coin> = match &proto.amount {
+ Some(coin) => Some(coin.try_into()?),
+ None => None,
+ };
Ok(MsgDelegate {
delegator_address: proto.delegator_address.clone(),
@@ -110,7 +109,7 @@ impl TryFrom<&proto::cosmos::staking::v1beta1::MsgDelegate> for MsgDelegate {
impl SerializeJson for MsgDelegate {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgDelegate serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgDelegate serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -139,11 +138,10 @@ impl TryFrom<&proto::cosmos::staking::v1beta1::MsgUndelegate> for MsgUndelegate
fn try_from(
proto: &proto::cosmos::staking::v1beta1::MsgUndelegate,
) -> Result<MsgUndelegate, CosmosError> {
- let amount: Option<Coin>;
- match &proto.amount {
- Some(coin) => amount = Some(coin.try_into()?),
- None => amount = None,
- }
+ let amount: Option<Coin> = match &proto.amount {
+ Some(coin) => Some(coin.try_into()?),
+ None => None,
+ };
Ok(MsgUndelegate {
delegator_address: proto.delegator_address.clone(),
@@ -156,7 +154,7 @@ impl TryFrom<&proto::cosmos::staking::v1beta1::MsgUndelegate> for MsgUndelegate
impl SerializeJson for MsgUndelegate {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgUndelegate serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgUndelegate serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -188,8 +186,7 @@ where
Ok(data)
} else {
Err(serde::de::Error::custom(format!(
- "invalid proposal id {:?}",
- value
+ "invalid proposal id {value:?}"
)))
}
}
@@ -208,8 +205,7 @@ where
Ok(Some(data))
} else {
Err(serde::de::Error::custom(format!(
- "invalid proposal id {:?}",
- value
+ "invalid proposal id {value:?}"
)))
}
}
@@ -237,7 +233,7 @@ impl TryFrom<&proto::cosmos::gov::v1beta1::MsgVote> for MsgVote {
impl SerializeJson for MsgVote {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgVote serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgVote serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -318,7 +314,7 @@ impl TryFrom<&proto::ibc::applications::transfer::v1::MsgTransfer> for MsgTransf
impl SerializeJson for MsgTransfer {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgTransfer serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgTransfer serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -359,8 +355,7 @@ impl SerializeJson for MsgWithdrawDelegatorReward {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
CosmosError::ParseTxError(format!(
- "MsgWithdrawDelegatorReward serialize failed {}",
- err
+ "MsgWithdrawDelegatorReward serialize failed {err}"
))
})?;
let msg = json!({
@@ -399,7 +394,7 @@ impl TryFrom<&proto::ibc::core::client::v1::MsgUpdateClient> for MsgUpdateClient
impl SerializeJson for MsgUpdateClient {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgUpdateClient serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgUpdateClient serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -445,7 +440,7 @@ impl TryFrom<&proto::cosmos::staking::v1beta1::MsgBeginRedelegate> for MsgBeginR
impl SerializeJson for MsgBeginRedelegate {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgBeginRedelegate serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgBeginRedelegate serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -485,7 +480,7 @@ impl TryFrom<&proto::cosmos::authz::v1beta1::MsgExec> for MsgExec {
impl SerializeJson for MsgExec {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgExec serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgExec serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
@@ -573,7 +568,7 @@ impl TryFrom<&proto::cosmos::bank::v1beta1::MsgMultiSend> for MsgMultiSend {
impl SerializeJson for MsgMultiSend {
fn to_json(&self) -> Result<Value, CosmosError> {
let value = serde_json::to_value(self).map_err(|err| {
- CosmosError::ParseTxError(format!("MsgMultiSend serialize failed {}", err))
+ CosmosError::ParseTxError(format!("MsgMultiSend serialize failed {err}"))
})?;
let msg = json!({
"type": Value::String(Self::TYPE_URL.to_string()),
diff --git a/rust/apps/cosmos/src/proto_wrapper/sign_doc.rs b/rust/apps/cosmos/src/proto_wrapper/sign_doc.rs
index 5bc030d..36b14fe 100644
--- a/rust/apps/cosmos/src/proto_wrapper/sign_doc.rs
+++ b/rust/apps/cosmos/src/proto_wrapper/sign_doc.rs
@@ -24,13 +24,13 @@ impl SignDoc {
fn from(proto: proto::cosmos::tx::v1beta1::SignDoc) -> Result<SignDoc> {
let tx_body: proto::cosmos::tx::v1beta1::TxBody =
Message::decode(Bytes::from(proto.body_bytes)).map_err(|e| {
- CosmosError::ParseTxError(format!("proto TxBody deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto TxBody deserialize failed {e}"))
})?;
let body = Body::try_from(tx_body)?;
let auth_info: proto::cosmos::tx::v1beta1::AuthInfo =
Message::decode(Bytes::from(proto.auth_info_bytes)).map_err(|e| {
- CosmosError::ParseTxError(format!("proto AuthInfo deserialize failed {}", e))
+ CosmosError::ParseTxError(format!("proto AuthInfo deserialize failed {e}"))
})?;
let auth_info = AuthInfo::try_from(auth_info)?;
@@ -43,10 +43,10 @@ impl SignDoc {
})
}
- pub fn parse(data: &Vec<u8>) -> Result<SignDoc> {
+ pub fn parse(data: &[u8]) -> Result<SignDoc> {
let proto_sign_doc: proto::cosmos::tx::v1beta1::SignDoc =
- Message::decode(Bytes::from(data.clone())).map_err(|e| {
- CosmosError::ParseTxError(format!("proto SignDoc deserialize failed {}", e))
+ Message::decode(Bytes::from(data.to_vec())).map_err(|e| {
+ CosmosError::ParseTxError(format!("proto SignDoc deserialize failed {e}"))
})?;
SignDoc::from(proto_sign_doc)
}
diff --git a/rust/apps/cosmos/src/proto_wrapper/signer_info.rs b/rust/apps/cosmos/src/proto_wrapper/signer_info.rs
index 93d45ab..6a3f53d 100644
--- a/rust/apps/cosmos/src/proto_wrapper/signer_info.rs
+++ b/rust/apps/cosmos/src/proto_wrapper/signer_info.rs
@@ -76,8 +76,7 @@ impl TryFrom<&Any> for PublicKey {
let pub_key: proto::cosmos::crypto::ed25519::PubKey = Message::decode(&*any.value)
.map_err(|err| {
CosmosError::ParseTxError(format!(
- "proto ed25519::PubKey deserialize failed {}",
- err
+ "proto ed25519::PubKey deserialize failed {err}"
))
})?;
Ok(PublicKey {
@@ -89,8 +88,7 @@ impl TryFrom<&Any> for PublicKey {
let pub_key: proto::cosmos::crypto::secp256k1::PubKey =
Message::decode(&*any.value).map_err(|err| {
CosmosError::ParseTxError(format!(
- "proto secp256k1::PubKey deserialize failed {}",
- err
+ "proto secp256k1::PubKey deserialize failed {err}"
))
})?;
Ok(PublicKey {
@@ -99,8 +97,7 @@ impl TryFrom<&Any> for PublicKey {
})
}
other => Err(CosmosError::ParseTxError(format!(
- "{} is not supported!!!",
- other
+ "{other} is not supported!!!"
))),
}
}
diff --git a/rust/apps/ethereum/src/structs.rs b/rust/apps/ethereum/src/structs.rs
index 5f33a0f..dccc6b8 100644
--- a/rust/apps/ethereum/src/structs.rs
+++ b/rust/apps/ethereum/src/structs.rs
@@ -1,5 +1,3 @@
-use core::ops::Add;
-
use crate::eip1559_transaction::ParsedEIP1559Transaction;
use crate::eip712::eip712::TypedData as Eip712TypedData;
use crate::errors::Result;
@@ -15,7 +13,7 @@ use ethabi::{encode, Address, Token};
use ethereum_types::{H160, U256};
use hex;
use rlp::{Decodable, DecoderError, Encodable, Rlp};
-use serde_json::{from_str, Value};
+use serde_json::Value;
#[derive(Clone)]
pub enum TransactionAction {
@@ -181,7 +179,7 @@ impl TypedData {
})
}
- pub fn from_raw(mut data: Eip712TypedData, from: Option<PublicKey>) -> Result<Self> {
+ pub fn from_raw(data: Eip712TypedData, from: Option<PublicKey>) -> Result<Self> {
Self::from(Into::into(data), from)
}
diff --git a/rust/apps/monero/src/address.rs b/rust/apps/monero/src/address.rs
index 77d2edd..6d978af 100644
--- a/rust/apps/monero/src/address.rs
+++ b/rust/apps/monero/src/address.rs
@@ -38,7 +38,7 @@ impl Address {
}
pub fn from_str(address: &str) -> Result<Address> {
- let decoded = match decode(address).map_err(|e| format!("decode error: {:?}", e)) {
+ let decoded = match decode(address).map_err(|e| format!("decode error: {e:?}")) {
Ok(decoded) => decoded,
_ => return Err(MoneroError::Base58DecodeError),
};
@@ -54,13 +54,13 @@ impl Address {
};
let is_subaddress = prefix == "2A" || prefix == "3F" || prefix == "24";
let public_spend = match PublicKey::from_bytes(&decoded[1..33])
- .map_err(|e| format!("decode error: {:?}", e))
+ .map_err(|e| format!("decode error: {e:?}"))
{
Ok(public_spend) => public_spend,
_ => return Err(MoneroError::FormatError),
};
let public_view = match PublicKey::from_bytes(&decoded[33..65])
- .map_err(|e| format!("decode error: {:?}", e))
+ .map_err(|e| format!("decode error: {e:?}"))
{
Ok(public_view) => public_view,
_ => return Err(MoneroError::FormatError),
@@ -97,10 +97,7 @@ pub fn get_address_from_seed(
major: u32,
minor: u32,
) -> Result<Address> {
- let keypair = match generate_keypair(seed, major) {
- Ok(keypair) => keypair,
- Err(e) => return Err(e),
- };
+ let keypair = generate_keypair(seed, major)?;
let mut public_spend_key = keypair.spend.get_public_key();
let mut public_view_key = keypair.view.get_public_key();
if is_subaddress {
@@ -127,19 +124,10 @@ pub fn pub_keyring_to_address(
if pub_keyring.len() != PUBKEY_LEH * 4 {
return Err(MoneroError::PubKeyringLengthError);
}
- let pub_spend_key = match PublicKey::from_bytes(&hex::decode(&pub_keyring[0..64]).unwrap()) {
- Ok(pub_spend_key) => pub_spend_key,
- Err(e) => return Err(e),
- };
- let pub_view_key = match PublicKey::from_bytes(&hex::decode(&pub_keyring[64..128]).unwrap()) {
- Ok(pub_view_key) => pub_view_key,
- Err(e) => return Err(e),
- };
+ let pub_spend_key = PublicKey::from_bytes(&hex::decode(&pub_keyring[0..64]).unwrap())?;
+ let pub_view_key = PublicKey::from_bytes(&hex::decode(&pub_keyring[64..128]).unwrap())?;
- match pub_keys_to_address(net, is_subaddress, &pub_spend_key, &pub_view_key) {
- Ok(address) => Ok(address),
- Err(e) => Err(e),
- }
+ pub_keys_to_address(net, is_subaddress, &pub_spend_key, &pub_view_key)
}
fn pub_keys_to_address(
@@ -197,7 +185,7 @@ pub fn generate_address(
return Ok(Address::new(
Network::Mainnet,
AddressType::Standard,
- public_spend_key.clone(),
+ *public_spend_key,
private_view_key.get_public_key(),
)
.to_string());
diff --git a/rust/apps/monero/src/errors.rs b/rust/apps/monero/src/errors.rs
index f4f6898..f37721b 100644
--- a/rust/apps/monero/src/errors.rs
+++ b/rust/apps/monero/src/errors.rs
@@ -37,8 +37,6 @@ pub type Result<T> = core::result::Result<T, MoneroError>;
impl From<KeystoreError> for MoneroError {
fn from(value: KeystoreError) -> Self {
- match value {
- _ => Self::KeystoreError(value.to_string()),
- }
+ Self::KeystoreError(value.to_string())
}
}
diff --git a/rust/apps/monero/src/extra.rs b/rust/apps/monero/src/extra.rs
index 4d42251..bb679f2 100644
--- a/rust/apps/monero/src/extra.rs
+++ b/rust/apps/monero/src/extra.rs
@@ -57,7 +57,7 @@ impl Extra {
match field {
ExtraField::Padding(size) => {
res.push(0x00);
- res.extend(core::iter::repeat(0).take(*size));
+ res.extend(core::iter::repeat_n(0, *size));
}
ExtraField::PublicKey(key) => {
res.push(0x01);
diff --git a/rust/apps/monero/src/key.rs b/rust/apps/monero/src/key.rs
index 0184a79..196a696 100644
--- a/rust/apps/monero/src/key.rs
+++ b/rust/apps/monero/src/key.rs
@@ -46,7 +46,7 @@ impl PublicKey {
pub fn from_bytes(bytes: &[u8]) -> Result<PublicKey> {
let pub_key = match CompressedEdwardsY::from_slice(bytes)
- .map_err(|e| format!("decode error: {:?}", e))
+ .map_err(|e| format!("decode error: {e:?}"))
{
Ok(point) => PublicKey { point },
_ => return Err(MoneroError::PublicKeyFromBytesError),
@@ -56,7 +56,7 @@ impl PublicKey {
pub fn from_str(s: &str) -> Result<PublicKey> {
let bytes = hex::decode(s)
- .map_err(|e| format!("decode error: {:?}", e))
+ .map_err(|e| format!("decode error: {e:?}"))
.unwrap();
PublicKey::from_bytes(&bytes)
}
@@ -64,7 +64,7 @@ impl PublicKey {
impl ToString for PublicKey {
fn to_string(&self) -> String {
- hex::encode(&self.point.to_bytes())
+ hex::encode(self.point.to_bytes())
}
}
@@ -140,9 +140,9 @@ impl KeyPair {
}
pub fn generate_keypair(seed: &[u8], major: u32) -> Result<KeyPair> {
- let path = format!("m/44'/128'/{}'/0/0", major);
+ let path = format!("m/44'/128'/{major}'/0/0");
let key =
- match keystore::algorithms::secp256k1::get_private_key_by_seed(&seed, &path.to_string()) {
+ match keystore::algorithms::secp256k1::get_private_key_by_seed(seed, &path.to_string()) {
Ok(key) => key,
_ => return Err(MoneroError::GenerateKeypairError),
};
diff --git a/rust/apps/monero/src/key_images.rs b/rust/apps/monero/src/key_images.rs
index 27b39bb..5e172ed 100644
--- a/rust/apps/monero/src/key_images.rs
+++ b/rust/apps/monero/src/key_images.rs
@@ -117,7 +117,7 @@ fn calc_output_key_offset(
hash_to_scalar(&[&recv_derivation.compress().0, scalar.as_slice()].concat());
if major != 0 || minor != 0 {
- key_offset = key_offset + Scalar::from_bytes_mod_order(keypair.get_m(major, minor));
+ key_offset += Scalar::from_bytes_mod_order(keypair.get_m(major, minor));
}
key_offset
@@ -273,14 +273,11 @@ impl ExportedTransferDetail {
}
pub fn generate_export_ur_data(keypair: KeyPair, request_data: Vec<u8>) -> Result<Vec<u8>> {
- let decrypted_data = match decrypt_data_with_pvk(
+ let decrypted_data = decrypt_data_with_pvk(
keypair.view.to_bytes().try_into().unwrap(),
request_data.clone(),
OUTPUT_EXPORT_MAGIC,
- ) {
- Ok(data) => data,
- Err(e) => return Err(e),
- };
+ )?;
if decrypted_data.pk1 != Some(keypair.get_public_spend()) {
panic!("Public spend key does not match");
@@ -289,10 +286,7 @@ pub fn generate_export_ur_data(keypair: KeyPair, request_data: Vec<u8>) -> Resul
panic!("Public view key does not match");
}
- let outputs = match ExportedTransferDetails::from_bytes(&decrypted_data.data) {
- Ok(data) => data,
- Err(e) => return Err(e),
- };
+ let outputs = ExportedTransferDetails::from_bytes(&decrypted_data.data)?;
let mut key_images: KeyImages = KeyImages(vec![]);
let rng_seed = keccak256(request_data.as_slice());
diff --git a/rust/apps/monero/src/lib.rs b/rust/apps/monero/src/lib.rs
index a8fdedb..a40ccbc 100644
--- a/rust/apps/monero/src/lib.rs
+++ b/rust/apps/monero/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
extern crate alloc;
mod extra;
diff --git a/rust/apps/monero/src/outputs.rs b/rust/apps/monero/src/outputs.rs
index e044d48..afb3ab7 100644
--- a/rust/apps/monero/src/outputs.rs
+++ b/rust/apps/monero/src/outputs.rs
@@ -50,7 +50,7 @@ pub struct ExportedTransferDetails {
impl ExportedTransferDetails {
pub fn from_bytes(bytes: &[u8]) -> Result<ExportedTransferDetails> {
let mut offset = 0;
- let has_transfers = read_varinteger(&bytes, &mut offset);
+ let has_transfers = read_varinteger(bytes, &mut offset);
if has_transfers == 0 {
return Ok(ExportedTransferDetails {
offset: 0,
@@ -59,34 +59,34 @@ impl ExportedTransferDetails {
});
}
// offset
- read_varinteger(&bytes, &mut offset);
+ read_varinteger(bytes, &mut offset);
// transfers.size()
- let value_offset = read_varinteger(&bytes, &mut offset);
+ let value_offset = read_varinteger(bytes, &mut offset);
// details size
- let value_size = read_varinteger(&bytes, &mut offset);
+ let value_size = read_varinteger(bytes, &mut offset);
// for size
let mut details = Vec::new();
for _ in 0..value_size {
// version ignore
- read_varinteger(&bytes, &mut offset);
+ read_varinteger(bytes, &mut offset);
let pubkey = PublicKey::from_bytes(&bytes[offset..offset + PUBKEY_LEH]).unwrap();
offset += PUBKEY_LEH;
- let internal_output_index = read_varinteger(&bytes, &mut offset);
- let global_output_index = read_varinteger(&bytes, &mut offset);
+ let internal_output_index = read_varinteger(bytes, &mut offset);
+ let global_output_index = read_varinteger(bytes, &mut offset);
let tx_pubkey = PublicKey::from_bytes(&bytes[offset..offset + PUBKEY_LEH]).unwrap();
let flags = bytes[offset + PUBKEY_LEH];
offset += PUBKEY_LEH + 1;
- let amount = read_varinteger(&bytes, &mut offset);
+ let amount = read_varinteger(bytes, &mut offset);
// FIXME: additional_tx_keys
- let keys_num = read_varinteger(&bytes, &mut offset);
+ let keys_num = read_varinteger(bytes, &mut offset);
let mut additional_tx_keys = Vec::new();
for _ in 0..keys_num {
let key = PublicKey::from_bytes(&bytes[offset..offset + PUBKEY_LEH]).unwrap();
additional_tx_keys.push(key);
offset += PUBKEY_LEH;
}
- let major = read_varinteger(&bytes, &mut offset);
- let minor = read_varinteger(&bytes, &mut offset);
+ let major = read_varinteger(bytes, &mut offset);
+ let minor = read_varinteger(bytes, &mut offset);
details.push(ExportedTransferDetail {
pubkey: pubkey.as_bytes(),
@@ -95,7 +95,7 @@ impl ExportedTransferDetails {
tx_pubkey: tx_pubkey.as_bytes(),
flags,
amount,
- additional_tx_keys: additional_tx_keys,
+ additional_tx_keys,
major: major as u32,
minor: minor as u32,
});
@@ -121,14 +121,8 @@ pub fn parse_display_info(
pvk: [u8; 32],
) -> Result<DisplayMoneroOutput> {
let decrypted_data =
- match decrypt_data_with_decrypt_key(decrypt_key, pvk, data.to_vec(), OUTPUT_EXPORT_MAGIC) {
- Ok(data) => data,
- Err(e) => return Err(e),
- };
- let outputs = match ExportedTransferDetails::from_bytes(&decrypted_data.data) {
- Ok(data) => data,
- Err(e) => return Err(e),
- };
+ decrypt_data_with_decrypt_key(decrypt_key, pvk, data.to_vec(), OUTPUT_EXPORT_MAGIC)?;
+ let outputs = ExportedTransferDetails::from_bytes(&decrypted_data.data)?;
let total_amount = outputs.details.iter().fold(0, |acc, x| acc + x.amount);
diff --git a/rust/apps/monero/src/signed_transaction.rs b/rust/apps/monero/src/signed_transaction.rs
index 48b4cdc..976d2ce 100644
--- a/rust/apps/monero/src/signed_transaction.rs
+++ b/rust/apps/monero/src/signed_transaction.rs
@@ -102,9 +102,9 @@ impl SignedTxSet {
}
let key_images_bytes = ptx.key_images.as_bytes();
res.extend_from_slice(write_varinteger(key_images_bytes.len() as u64).as_slice());
- if key_images_bytes.len() > 0 {
+ if !key_images_bytes.is_empty() {
// res.push(0x01);
- res.extend_from_slice(&key_images_bytes);
+ res.extend_from_slice(key_images_bytes);
}
// tx_key ZERO
res.extend_from_slice(&Scalar::ONE.to_bytes());
diff --git a/rust/apps/monero/src/transfer.rs b/rust/apps/monero/src/transfer.rs
index 3707207..a4d4beb 100644
--- a/rust/apps/monero/src/transfer.rs
+++ b/rust/apps/monero/src/transfer.rs
@@ -22,7 +22,7 @@ use monero_serai::ringct::{RctBase, RctProofs, RctPrunable};
use monero_serai::transaction::{
Input, NotPruned, Output, Timelock, Transaction, TransactionPrefix,
};
-use rand_core::SeedableRng;
+use rand_core::OsRng;
use zeroize::Zeroizing;
#[derive(Debug, Clone)]
@@ -99,7 +99,9 @@ pub struct AccountPublicAddress {
impl AccountPublicAddress {
pub fn to_address(&self, network: Network, is_subaddress: bool) -> Address {
- let address = Address {
+
+
+ Address {
network,
addr_type: if is_subaddress {
AddressType::Subaddress
@@ -108,9 +110,7 @@ impl AccountPublicAddress {
},
public_spend: PublicKey::from_bytes(&self.spend_public_key).unwrap(),
public_view: PublicKey::from_bytes(&self.view_public_key).unwrap(),
- };
-
- address
+ }
}
}
@@ -168,6 +168,12 @@ pub struct InnerInput {
pub struct InnerInputs(Vec<InnerInput>);
+impl Default for InnerInputs {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl InnerInputs {
pub fn new() -> InnerInputs {
InnerInputs(vec![])
@@ -203,6 +209,12 @@ pub struct InnerOutput {
pub struct InnerOutputs(Vec<InnerOutput>);
+impl Default for InnerOutputs {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl InnerOutputs {
pub fn new() -> InnerOutputs {
InnerOutputs(vec![])
@@ -222,7 +234,7 @@ impl InnerOutputs {
pub fn get_key_images(&self) -> Vec<Keyimage> {
self.0
.iter()
- .map(|inner_output| inner_output.key_image.clone())
+ .map(|inner_output| inner_output.key_image)
.collect()
}
}
@@ -242,7 +254,7 @@ impl TxConstructionData {
fn absolute_output_offsets_to_relative(&self, off: Vec<u64>) -> Vec<u64> {
let mut res = off;
- if res.len() == 0 {
+ if res.is_empty() {
return res;
}
res.sort();
@@ -385,7 +397,7 @@ impl UnsignedTx {
let mut outputs = vec![];
for tx in self.txes.iter() {
for source in tx.sources.iter() {
- let output = source.outputs[source.real_output as usize].clone();
+ let output = source.outputs[source.real_output as usize];
let amount = source.amount;
inputs.push((
PublicKey::from_bytes(&output.key.dest).unwrap(),
@@ -551,14 +563,10 @@ impl UnsignedTx {
encrypted_amounts.push(encrypted_amount);
}
let bulletproof = {
- let mut seed = vec![];
- seed.extend_from_slice(b"bulletproof");
- seed.extend_from_slice(&tx.extra);
- let mut bp_rng = rand_chacha::ChaCha20Rng::from_seed(keccak256(&seed));
(match tx.rct_config.bp_version {
- RctType::RCTTypeFull => Bulletproof::prove(&mut bp_rng, bp_commitments),
+ RctType::RCTTypeFull => Bulletproof::prove(&mut OsRng, bp_commitments),
RctType::RCTTypeNull | RctType::RCTTypeBulletproof2 => {
- Bulletproof::prove_plus(&mut bp_rng, bp_commitments)
+ Bulletproof::prove_plus(&mut OsRng, bp_commitments)
}
_ => panic!("unsupported RctType"),
})
@@ -598,8 +606,6 @@ impl UnsignedTx {
let mut penging_tx = vec![];
let txes = self.transaction_without_signatures(keypair);
let mut tx_key_images = vec![];
- let seed = keccak256(&txes[0].serialize());
- let mut rng = rand_chacha::ChaCha20Rng::from_seed(seed);
for (tx, unsigned_tx) in txes.iter().zip(self.txes.iter()) {
let mask_sum = unsigned_tx.sum_output_masks(keypair);
let inputs = unsigned_tx.inputs(keypair);
@@ -643,7 +649,8 @@ impl UnsignedTx {
}
let msg = tx.signature_hash().unwrap();
- let clsags_and_pseudo_outs = Clsag::sign(&mut rng, clsag_signs, mask_sum, msg).unwrap();
+ let clsags_and_pseudo_outs =
+ Clsag::sign(&mut OsRng, clsag_signs, mask_sum, msg).unwrap();
let mut tx = tx.clone();
let inputs_len = tx.prefix().inputs.len();
@@ -671,7 +678,7 @@ impl UnsignedTx {
}
let key_images = unsigned_tx.calc_key_images(keypair);
- let key_images_str = if key_images.len() == 0 {
+ let key_images_str = if key_images.is_empty() {
"".to_owned()
} else {
let mut key_images_str = "".to_owned();
diff --git a/rust/apps/monero/src/transfer_key.rs b/rust/apps/monero/src/transfer_key.rs
index 7df2934..cc74aad 100644
--- a/rust/apps/monero/src/transfer_key.rs
+++ b/rust/apps/monero/src/transfer_key.rs
@@ -1,7 +1,6 @@
use crate::extra::*;
use crate::key::*;
use crate::transfer::{TxConstructionData, TxDestinationEntry};
-use crate::utils::hash::*;
use crate::utils::*;
use alloc::vec;
use alloc::vec::Vec;
@@ -10,14 +9,14 @@ use curve25519_dalek::scalar::Scalar;
use monero_serai::primitives::Commitment;
use monero_serai::ringct::EncryptedAmount;
use monero_wallet::SharedKeyDerivations;
-use rand_core::SeedableRng;
+use rand_core::OsRng;
use zeroize::Zeroizing;
impl TxConstructionData {
fn should_use_additional_keys(&self) -> bool {
self.sources
.iter()
- .any(|source| source.real_out_additional_tx_keys.len() > 0)
+ .any(|source| !source.real_out_additional_tx_keys.is_empty())
}
fn has_payments_to_subaddresses(&self) -> bool {
@@ -27,14 +26,12 @@ impl TxConstructionData {
pub fn transaction_keys(
&self,
) -> (PrivateKey, Vec<PrivateKey>, EdwardsPoint, Vec<EdwardsPoint>) {
- let seed = keccak256(&self.extra);
- let mut rng = rand_chacha::ChaCha20Rng::from_seed(seed);
- let tx_key = generate_random_scalar(&mut rng);
+ let tx_key = generate_random_scalar(&mut OsRng);
let mut additional_keys = vec![];
if self.should_use_additional_keys() {
for _ in 0..self.splitted_dsts.len() {
additional_keys.push(PrivateKey::from_bytes(
- generate_random_scalar(&mut rng).as_bytes(),
+ generate_random_scalar(&mut OsRng).as_bytes(),
));
}
}
diff --git a/rust/apps/monero/src/utils/hash.rs b/rust/apps/monero/src/utils/hash.rs
index eb2ed8c..f1523b3 100644
--- a/rust/apps/monero/src/utils/hash.rs
+++ b/rust/apps/monero/src/utils/hash.rs
@@ -7,7 +7,7 @@ use cryptoxide::sha3::Keccak256;
use curve25519_dalek::scalar::Scalar;
pub(crate) fn sha256_digest(data: &[u8]) -> Vec<u8> {
- hashing::sha256(&data).to_vec()
+ hashing::sha256(data).to_vec()
}
fn ripemd160_digest(data: &[u8]) -> [u8; 20] {
diff --git a/rust/apps/monero/src/utils/io.rs b/rust/apps/monero/src/utils/io.rs
index 2640601..1b5521c 100644
--- a/rust/apps/monero/src/utils/io.rs
+++ b/rust/apps/monero/src/utils/io.rs
@@ -136,7 +136,7 @@ pub fn write_tx_construction_data(data: &TxConstructionData) -> Vec<u8> {
buffer.extend_from_slice(&write_varinteger(data.extra.len() as u64));
buffer.extend_from_slice(&data.extra);
buffer.extend_from_slice(&data.unlock_time.to_le_bytes());
- buffer.push(data.use_rct as u8);
+ buffer.push(data.use_rct);
buffer.extend_from_slice(&write_varinteger(data.rct_config.version as u64));
buffer.extend_from_slice(&write_varinteger(data.rct_config.range_proof_type as u64));
buffer.extend_from_slice(&write_varinteger(data.rct_config.bp_version as u64));
diff --git a/rust/apps/monero/src/utils/mod.rs b/rust/apps/monero/src/utils/mod.rs
index 9f6c131..843be33 100644
--- a/rust/apps/monero/src/utils/mod.rs
+++ b/rust/apps/monero/src/utils/mod.rs
@@ -204,12 +204,12 @@ pub fn get_key_image_from_input(input: Input) -> Result<Keyimage> {
pub fn fmt_monero_amount(value: u64) -> String {
let value = value as f64 / 1_000_000_000_000.0;
- let value = format!("{:.12}", value);
+ let value = format!("{value:.12}");
let value = value.trim_end_matches('0').to_string();
if value.ends_with('.') {
- format!("{} XMR", value[..value.len() - 1].to_string())
+ format!("{} XMR", &value[..value.len() - 1])
} else {
- format!("{} XMR", value)
+ format!("{value} XMR")
}
}
diff --git a/rust/apps/monero/src/utils/sign.rs b/rust/apps/monero/src/utils/sign.rs
index 5762af0..8c4723a 100644
--- a/rust/apps/monero/src/utils/sign.rs
+++ b/rust/apps/monero/src/utils/sign.rs
@@ -121,7 +121,7 @@ pub fn generate_ring_signature<R: RngCore + CryptoRng>(
let tmp3 = hash_to_point(tmp3.compress().0);
let tmp2 = EdwardsPoint::multiscalar_mul(
&[sig[index][1], sig[index][0]],
- &[tmp3, key_image.clone()],
+ &[tmp3, *key_image],
);
buff.extend_from_slice(&tmp2.compress().0);
sum += sig[index][0];
diff --git a/rust/apps/monero/src/utils/varinteger.rs b/rust/apps/monero/src/utils/varinteger.rs
index da0e61b..7f6fe89 100644
--- a/rust/apps/monero/src/utils/varinteger.rs
+++ b/rust/apps/monero/src/utils/varinteger.rs
@@ -40,8 +40,8 @@ pub fn decode(buf: &[u8], value: &mut u64) -> usize {
/// many bytes were decoded.
#[inline]
pub fn decode_with_offset(buf: &[u8], offset: usize, value: &mut u64) -> usize {
- let mut val = 0 as u64;
- let mut fac = 1 as u64;
+ let mut val = 0_u64;
+ let mut fac = 1_u64;
let mut off = offset;
loop {
@@ -110,7 +110,7 @@ fn unsign(value: i64) -> u64 {
#[inline]
fn sign(value: u64) -> i64 {
if value & 1 != 0 {
- -(((value + 1) / 2) as i64)
+ -(value.div_ceil(2) as i64)
} else {
(value / 2) as i64
}
diff --git a/rust/apps/solana/src/lib.rs b/rust/apps/solana/src/lib.rs
index 8501704..1166385 100644
--- a/rust/apps/solana/src/lib.rs
+++ b/rust/apps/solana/src/lib.rs
@@ -1,6 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
-#![feature(prelude_2024)]
#![allow(dead_code)] // add for solana use a lot of external code
extern crate alloc;
@@ -27,6 +25,7 @@ pub mod message;
pub mod parser;
pub mod read;
mod resolvers;
+#[allow(clippy::all)]
mod solana_lib;
pub mod structs;
pub mod utils;
diff --git a/rust/apps/ton/src/mnemonic.rs b/rust/apps/ton/src/mnemonic.rs
index 6912184..2dc323f 100644
--- a/rust/apps/ton/src/mnemonic.rs
+++ b/rust/apps/ton/src/mnemonic.rs
@@ -62,10 +62,10 @@ pub fn ton_mnemonic_validate(
Ok(())
}
-pub fn ton_entropy_to_seed(entropy: Vec<u8>) -> [u8; 64] {
+pub fn ton_entropy_to_seed(entropy: &[u8]) -> [u8; 64] {
let mut master_seed = [0u8; 64];
pbkdf2(
- &mut Hmac::new(Sha512::new(), &entropy),
+ &mut Hmac::new(Sha512::new(), entropy),
b"TON default seed",
PBKDF_ITERATIONS,
&mut master_seed,
@@ -83,7 +83,7 @@ pub fn ton_mnemonic_to_master_seed(
let normalized_words: Vec<String> = words.iter().map(|w| w.trim().to_lowercase()).collect();
ton_mnemonic_validate(&normalized_words, &password)?;
let entropy = ton_mnemonic_to_entropy(&normalized_words, &password);
- Ok(ton_entropy_to_seed(entropy))
+ Ok(ton_entropy_to_seed(&entropy))
}
pub fn ton_master_seed_to_keypair(master_seed: [u8; 64]) -> ([u8; 64], [u8; 32]) {
diff --git a/rust/apps/utils/src/lib.rs b/rust/apps/utils/src/lib.rs
index 0296477..d911d0a 100644
--- a/rust/apps/utils/src/lib.rs
+++ b/rust/apps/utils/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
extern crate alloc;
pub mod keystone;
diff --git a/rust/apps/wallets/src/lib.rs b/rust/apps/wallets/src/lib.rs
index 8744e99..b824645 100644
--- a/rust/apps/wallets/src/lib.rs
+++ b/rust/apps/wallets/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
#[allow(unused_imports)] // stupid compiler
#[macro_use]
diff --git a/rust/keystore/src/lib.rs b/rust/keystore/src/lib.rs
index 510d7a0..297ff9a 100644
--- a/rust/keystore/src/lib.rs
+++ b/rust/keystore/src/lib.rs
@@ -1,5 +1,4 @@
#![no_std]
-#![feature(error_in_core)]
pub mod algorithms;
mod bindings;
diff --git a/rust/rust_c/Cargo.toml b/rust/rust_c/Cargo.toml
index 54876e3..627a9bd 100644
--- a/rust/rust_c/Cargo.toml
+++ b/rust/rust_c/Cargo.toml
@@ -128,7 +128,7 @@ simulator-multi-coins = ["simulator", "multi-coins"]
simulator-btc-only = ["simulator", "btc-only"]
simulator-cypherpunk = ["simulator", "cypherpunk"]
# make IDE happy
-default = ["simulator-multi-coins"]
+default = ["simulator-cypherpunk"]
[dev-dependencies]
keystore = { path = "../keystore" }
diff --git a/rust/rust_c/build.rs b/rust/rust_c/build.rs
index 6b22956..fa75375 100644
--- a/rust/rust_c/build.rs
+++ b/rust/rust_c/build.rs
@@ -76,8 +76,7 @@ fn main() {
assert!(!features.is_empty(), "No build variant enabled");
assert!(
features.len() == 1,
- "Multiple build variants enabled: {:?}",
- features
+ "Multiple build variants enabled: {features:?}"
);
let output_target = env::var("CBINDGEN_BINDINGS_TARGET")
.unwrap_or(format!("bindings/{}/librust_c.h", features[0]));
@@ -89,6 +88,10 @@ fn main() {
.with_crate(".")
.with_config(config)
.generate()
- .expect("Failed to generate bindings")
- .write_to_file(output_target);
+ .map_or_else(
+ |error| {},
+ |bindings| {
+ bindings.write_to_file(output_target);
+ },
+ )
}
diff --git a/rust/rust_c/src/allocator.rs b/rust/rust_c/src/allocator.rs
index 260137c..b7344fa 100644
--- a/rust/rust_c/src/allocator.rs
+++ b/rust/rust_c/src/allocator.rs
@@ -10,7 +10,7 @@ use cstr_core::CString;
fn oom(layout: core::alloc::Layout) -> ! {
unsafe {
crate::bindings::LogRustPanic(
- CString::new(alloc::format!("Out of memory: {:?}", layout))
+ CString::new(alloc::format!("Out of memory: {layout:?}"))
.unwrap()
.into_raw(),
)
@@ -22,7 +22,7 @@ fn oom(layout: core::alloc::Layout) -> ! {
fn panic(e: &PanicInfo) -> ! {
unsafe {
crate::bindings::LogRustPanic(
- CString::new(alloc::format!("rust panic: {:?}", e))
+ CString::new(alloc::format!("rust panic: {e:?}"))
.unwrap()
.into_raw(),
)
diff --git a/rust/rust_c/src/aptos/mod.rs b/rust/rust_c/src/aptos/mod.rs
index 1ac7f84..0869e53 100644
--- a/rust/rust_c/src/aptos/mod.rs
+++ b/rust/rust_c/src/aptos/mod.rs
@@ -3,9 +3,9 @@ use crate::common::structs::{SimpleResponse, TransactionCheckResult, Transaction
use crate::common::types::{PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use crate::common::utils::{convert_c_char, recover_c_char};
+use crate::extract_array;
use crate::extract_ptr_with_type;
use alloc::format;
-use alloc::slice;
use alloc::string::ToString;
use alloc::vec::Vec;
@@ -21,7 +21,7 @@ use ur_registry::traits::RegistryItem;
pub mod structs;
-fn build_sign_result(
+unsafe fn build_sign_result(
ptr: PtrUR,
seed: &[u8],
pub_key: PtrString,
@@ -34,7 +34,7 @@ fn build_sign_result(
"invalid derivation path".to_string(),
))?;
if !path.starts_with("m/") {
- path = format!("m/{}", path);
+ path = format!("m/{path}");
}
let signature = app_aptos::sign(sign_request.get_sign_data().to_vec(), &path, seed)?;
let buf: Vec<u8> = hex::decode(pub_key)?;
@@ -46,7 +46,7 @@ fn build_sign_result(
}
#[no_mangle]
-pub extern "C" fn aptos_generate_address(pub_key: PtrString) -> *mut SimpleResponse<c_char> {
+pub unsafe extern "C" fn aptos_generate_address(pub_key: PtrString) -> *mut SimpleResponse<c_char> {
let pub_key = recover_c_char(pub_key);
let address = app_aptos::generate_address(&pub_key);
match address {
@@ -56,7 +56,7 @@ pub extern "C" fn aptos_generate_address(pub_key: PtrString) -> *mut SimpleRespo
}
#[no_mangle]
-pub extern "C" fn aptos_check_request(
+pub unsafe extern "C" fn aptos_check_request(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -64,7 +64,7 @@ pub extern "C" fn aptos_check_request(
if length != 4 {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let sign_request = extract_ptr_with_type!(ptr, AptosSignRequest);
let ur_mfp = sign_request.get_authentication_key_derivation_paths()[0].get_source_fingerprint();
@@ -83,7 +83,7 @@ pub extern "C" fn aptos_check_request(
}
#[no_mangle]
-pub extern "C" fn aptos_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<DisplayAptosTx>> {
+pub unsafe extern "C" fn aptos_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<DisplayAptosTx>> {
let sign_request = extract_ptr_with_type!(ptr, AptosSignRequest);
let sign_data = sign_request.get_sign_data();
let sign_type = match sign_request.get_sign_type() {
@@ -114,13 +114,13 @@ pub extern "C" fn aptos_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<Display
}
#[no_mangle]
-pub extern "C" fn aptos_sign_tx(
+pub unsafe extern "C" fn aptos_sign_tx(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
pub_key: PtrString,
) -> PtrT<UREncodeResult> {
- let seed = unsafe { alloc::slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
build_sign_result(ptr, seed, pub_key)
.map(|v| v.try_into())
.map_or_else(
@@ -142,7 +142,7 @@ pub extern "C" fn aptos_sign_tx(
}
#[no_mangle]
-pub extern "C" fn aptos_get_path(ptr: PtrUR) -> PtrString {
+pub unsafe extern "C" fn aptos_get_path(ptr: PtrUR) -> PtrString {
let aptos_sign_request = extract_ptr_with_type!(ptr, AptosSignRequest);
let derivation_path = &aptos_sign_request.get_authentication_key_derivation_paths()[0];
if let Some(path) = derivation_path.get_path() {
@@ -152,7 +152,7 @@ pub extern "C" fn aptos_get_path(ptr: PtrUR) -> PtrString {
}
#[no_mangle]
-pub extern "C" fn test_aptos_parse() -> *mut SimpleResponse<c_char> {
+pub unsafe extern "C" fn test_aptos_parse() -> *mut SimpleResponse<c_char> {
let data = "8bbbb70ae8b90a8686b2a27f10e21e44f2fb64ffffcaa4bb0242e9f1ea698659010000000000000002000000000000000000000000000000000000000000000000000000000000000104636f696e087472616e73666572010700000000000000000000000000000000000000000000000000000000000000010a6170746f735f636f696e094170746f73436f696e000220834f4b75dcaacbd7c549a993cdd3140676e172d1fee0609bf6876c74aaa7116008400d0300000000009a0e0000000000006400000000000000b6b747630000000021";
let buf_message = Vec::from_hex(data).unwrap();
match app_aptos::parse_tx(&buf_message) {
diff --git a/rust/rust_c/src/aptos/structs.rs b/rust/rust_c/src/aptos/structs.rs
index 2f2b77a..24b4faa 100644
--- a/rust/rust_c/src/aptos/structs.rs
+++ b/rust/rust_c/src/aptos/structs.rs
@@ -2,7 +2,7 @@ use crate::common::free::Free;
use crate::common::structs::TransactionParseResult;
use crate::common::types::{PtrString, PtrT};
use crate::common::utils::convert_c_char;
-use crate::{check_and_free_ptr, free_str_ptr, impl_c_ptr, make_free_method};
+use crate::{free_str_ptr, impl_c_ptr, make_free_method};
use alloc::string::{String, ToString};
use app_aptos::parser::AptosTx;
use serde_json::Value;
@@ -41,7 +41,7 @@ impl From<String> for DisplayAptosTx {
impl_c_ptr!(DisplayAptosTx);
impl Free for DisplayAptosTx {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.detail);
}
}
diff --git a/rust/rust_c/src/arweave/data_item.rs b/rust/rust_c/src/arweave/data_item.rs
index 1a11291..9aeddb4 100644
--- a/rust/rust_c/src/arweave/data_item.rs
+++ b/rust/rust_c/src/arweave/data_item.rs
@@ -9,7 +9,7 @@ use ur_registry::arweave::arweave_sign_request::ArweaveSignRequest;
use super::structs::{DisplayArweaveAOTransfer, DisplayArweaveDataItem};
#[no_mangle]
-pub extern "C" fn ar_is_ao_transfer(ptr: PtrUR) -> bool {
+pub unsafe extern "C" fn ar_is_ao_transfer(ptr: PtrUR) -> bool {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let sign_data = sign_request.get_sign_data();
let data_item = parse_data_item(&sign_data);
@@ -23,7 +23,7 @@ pub extern "C" fn ar_is_ao_transfer(ptr: PtrUR) -> bool {
}
#[no_mangle]
-pub extern "C" fn ar_parse_data_item(
+pub unsafe extern "C" fn ar_parse_data_item(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayArweaveDataItem>> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
@@ -38,7 +38,7 @@ pub extern "C" fn ar_parse_data_item(
}
#[no_mangle]
-pub extern "C" fn ar_parse_ao_transfer(
+pub unsafe extern "C" fn ar_parse_ao_transfer(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayArweaveAOTransfer>> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
diff --git a/rust/rust_c/src/arweave/mod.rs b/rust/rust_c/src/arweave/mod.rs
index f336535..fee926b 100644
--- a/rust/rust_c/src/arweave/mod.rs
+++ b/rust/rust_c/src/arweave/mod.rs
@@ -9,7 +9,7 @@ use crate::common::structs::{SimpleResponse, TransactionCheckResult, Transaction
use crate::common::types::{PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use crate::common::utils::{convert_c_char, recover_c_char};
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use alloc::slice;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
@@ -120,21 +120,21 @@ pub extern "C" fn aes256_decrypt_primes(
}
#[no_mangle]
-pub extern "C" fn arweave_get_address(xpub: PtrString) -> *mut SimpleResponse<c_char> {
+pub unsafe extern "C" fn arweave_get_address(xpub: PtrString) -> *mut SimpleResponse<c_char> {
let xpub = recover_c_char(xpub);
let address = app_arweave::generate_address(hex::decode(xpub).unwrap()).unwrap();
SimpleResponse::success(convert_c_char(address)).simple_c_ptr()
}
#[no_mangle]
-pub extern "C" fn fix_arweave_address(address: PtrString) -> *mut SimpleResponse<c_char> {
+pub unsafe extern "C" fn fix_arweave_address(address: PtrString) -> *mut SimpleResponse<c_char> {
let address = recover_c_char(address);
let fixed_address = fix_address(&address);
SimpleResponse::success(convert_c_char(fixed_address)).simple_c_ptr()
}
#[no_mangle]
-pub extern "C" fn ar_check_tx(
+pub unsafe extern "C" fn ar_check_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -142,7 +142,7 @@ pub extern "C" fn ar_check_tx(
if length != 4 {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let ur_mfp = sign_request.get_master_fingerprint();
@@ -157,7 +157,7 @@ pub extern "C" fn ar_check_tx(
}
#[no_mangle]
-pub extern "C" fn ar_request_type(ptr: PtrUR) -> *mut SimpleResponse<ArweaveRequestType> {
+pub unsafe extern "C" fn ar_request_type(ptr: PtrUR) -> *mut SimpleResponse<ArweaveRequestType> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let sign_type = sign_request.get_sign_type();
let sign_type_str = match sign_type {
@@ -170,7 +170,7 @@ pub extern "C" fn ar_request_type(ptr: PtrUR) -> *mut SimpleResponse<ArweaveRequ
}
#[no_mangle]
-pub extern "C" fn ar_message_parse(
+pub unsafe extern "C" fn ar_message_parse(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayArweaveMessage>> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
@@ -195,7 +195,7 @@ fn get_value(raw_json: &Value, key: &str) -> String {
}
#[no_mangle]
-pub extern "C" fn ar_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<DisplayArweaveTx>> {
+pub unsafe extern "C" fn ar_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<DisplayArweaveTx>> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let sign_data = sign_request.get_sign_data();
let raw_tx = parse(&sign_data).unwrap();
@@ -216,7 +216,7 @@ pub extern "C" fn ar_parse(ptr: PtrUR) -> PtrT<TransactionParseResult<DisplayArw
.c_ptr()
}
-fn parse_sign_data(ptr: PtrUR) -> Result<Vec<u8>, ArweaveError> {
+unsafe fn parse_sign_data(ptr: PtrUR) -> Result<Vec<u8>, ArweaveError> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let sign_data = sign_request.get_sign_data();
match sign_request.get_sign_type() {
@@ -237,7 +237,7 @@ fn parse_sign_data(ptr: PtrUR) -> Result<Vec<u8>, ArweaveError> {
}
}
-fn build_sign_result(ptr: PtrUR, p: &[u8], q: &[u8]) -> Result<ArweaveSignature, ArweaveError> {
+unsafe fn build_sign_result(ptr: PtrUR, p: &[u8], q: &[u8]) -> Result<ArweaveSignature, ArweaveError> {
let sign_request = extract_ptr_with_type!(ptr, ArweaveSignRequest);
let salt_len = match sign_request.get_salt_len() {
SaltLen::Zero => 0,
@@ -258,15 +258,15 @@ fn build_sign_result(ptr: PtrUR, p: &[u8], q: &[u8]) -> Result<ArweaveSignature,
}
#[no_mangle]
-pub extern "C" fn ar_sign_tx(
+pub unsafe extern "C" fn ar_sign_tx(
ptr: PtrUR,
p: PtrBytes,
p_len: u32,
q: PtrBytes,
q_len: u32,
) -> PtrT<UREncodeResult> {
- let p = unsafe { slice::from_raw_parts(p, p_len as usize) };
- let q = unsafe { slice::from_raw_parts(q, q_len as usize) };
+ let p = extract_array!(p, u8, p_len as usize);
+ let q = extract_array!(q, u8, q_len as usize);
build_sign_result(ptr, p, q)
.map(|v: ArweaveSignature| v.try_into())
diff --git a/rust/rust_c/src/arweave/structs.rs b/rust/rust_c/src/arweave/structs.rs
index d05d378..256045a 100644
--- a/rust/rust_c/src/arweave/structs.rs
+++ b/rust/rust_c/src/arweave/structs.rs
@@ -3,7 +3,7 @@ use crate::common::free::Free;
use crate::common::structs::TransactionParseResult;
use crate::common::types::{Ptr, PtrString, PtrT};
use crate::common::utils::convert_c_char;
-use crate::{check_and_free_ptr, free_str_ptr, free_vec, impl_c_ptr, make_free_method};
+use crate::{free_str_ptr, free_vec, impl_c_ptr, make_free_method};
use alloc::vec::Vec;
use app_arweave::{
ao_transaction::AOTransferTransaction,
@@ -35,7 +35,7 @@ pub struct DisplayArweaveMessage {
}
impl Free for DisplayArweaveTx {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.value);
free_str_ptr!(self.fee);
free_str_ptr!(self.from);
@@ -44,7 +44,7 @@ impl Free for DisplayArweaveTx {
}
impl Free for DisplayArweaveMessage {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.message);
free_str_ptr!(self.raw_message);
}
@@ -75,7 +75,7 @@ impl From<Tag> for DisplayTag {
}
impl Free for DisplayTag {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.name);
free_str_ptr!(self.value);
}
@@ -111,7 +111,7 @@ impl From<DataItem> for DisplayArweaveDataItem {
}
impl Free for DisplayArweaveDataItem {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.owner);
free_str_ptr!(self.target);
free_str_ptr!(self.anchor);
@@ -151,7 +151,7 @@ impl From<AOTransferTransaction> for DisplayArweaveAOTransfer {
}
impl Free for DisplayArweaveAOTransfer {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.from);
free_str_ptr!(self.to);
free_str_ptr!(self.token_id);
diff --git a/rust/rust_c/src/avalanche/address.rs b/rust/rust_c/src/avalanche/address.rs
index e52f134..7a29a28 100644
--- a/rust/rust_c/src/avalanche/address.rs
+++ b/rust/rust_c/src/avalanche/address.rs
@@ -8,7 +8,7 @@ use crate::common::utils::{convert_c_char, recover_c_char};
use app_avalanche::{errors::AvaxError, network::Network};
#[no_mangle]
-pub extern "C" fn avalanche_get_x_p_address(
+pub unsafe extern "C" fn avalanche_get_x_p_address(
hd_path: PtrString,
root_x_pub: PtrString,
root_path: PtrString,
diff --git a/rust/rust_c/src/avalanche/mod.rs b/rust/rust_c/src/avalanche/mod.rs
index 4461b09..e7b1b02 100644
--- a/rust/rust_c/src/avalanche/mod.rs
+++ b/rust/rust_c/src/avalanche/mod.rs
@@ -14,9 +14,9 @@ use crate::common::{
ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT, FRAGMENT_UNLIMITED_LENGTH},
utils::{recover_c_array, recover_c_char},
};
-use crate::{extract_ptr_with_type, impl_c_ptr};
+use crate::{extract_array, extract_ptr_with_type, impl_c_ptr};
use alloc::{
- format, slice,
+ format,
string::{String, ToString},
vec::Vec,
};
@@ -55,7 +55,7 @@ pub struct DerivationPath {
}
#[no_mangle]
-pub extern "C" fn avax_parse_transaction(
+pub unsafe extern "C" fn avax_parse_transaction(
ptr: PtrUR,
mfp: PtrBytes,
mfp_len: u32,
@@ -64,101 +64,96 @@ pub extern "C" fn avax_parse_transaction(
parse_transaction_by_type(extract_ptr_with_type!(ptr, AvaxSignRequest), public_keys)
}
-fn parse_transaction_by_type(
+unsafe fn parse_transaction_by_type(
sign_request: &mut AvaxSignRequest,
public_keys: PtrT<CSliceFFI<ExtendedPublicKey>>,
) -> PtrT<TransactionParseResult<DisplayAvaxTx>> {
let tx_data = sign_request.get_tx_data();
let type_id = get_avax_tx_type_id(sign_request.get_tx_data()).unwrap();
- unsafe {
- let mut path = get_avax_tx_type_id(sign_request.get_tx_data())
- .map_err(|_| AvaxError::InvalidInput)
- .and_then(|type_id| {
- determine_derivation_path(type_id, &sign_request, sign_request.get_wallet_index())
- })
- .unwrap();
+ let mut path = get_avax_tx_type_id(sign_request.get_tx_data())
+ .map_err(|_| AvaxError::InvalidInput)
+ .and_then(|type_id| {
+ determine_derivation_path(type_id, sign_request, sign_request.get_wallet_index())
+ })
+ .unwrap();
- let mut address = String::new();
- for key in recover_c_array(public_keys).iter() {
- if recover_c_char(key.path) == path.base_path {
- address = match (type_id, path.base_path.as_str()) {
- (TypeId::CchainExportTx, "m/44'/60'/0'") => {
- app_ethereum::address::derive_address(
- &path.full_path.as_str(),
- &recover_c_char(key.xpub),
- &path.base_path.as_str(),
- )
- .unwrap()
- }
- _ => app_avalanche::get_address(
- app_avalanche::network::Network::AvaxMainNet,
- &path.full_path.as_str(),
- &recover_c_char(key.xpub).as_str(),
- &path.base_path.as_str(),
- )
- .unwrap(),
- }
+ let mut address = String::new();
+ for key in recover_c_array(public_keys).iter() {
+ if recover_c_char(key.path) == path.base_path {
+ address = match (type_id, path.base_path.as_str()) {
+ (TypeId::CchainExportTx, "m/44'/60'/0'") => app_ethereum::address::derive_address(
+ path.full_path.as_str(),
+ &recover_c_char(key.xpub),
+ path.base_path.as_str(),
+ )
+ .unwrap(),
+ _ => app_avalanche::get_address(
+ app_avalanche::network::Network::AvaxMainNet,
+ path.full_path.as_str(),
+ recover_c_char(key.xpub).as_str(),
+ path.base_path.as_str(),
+ )
+ .unwrap(),
}
}
+ }
- macro_rules! parse_tx {
- ($tx_type:ty) => {
- parse_avax_tx::<$tx_type>(tx_data)
- .map(|parse_data| {
- TransactionParseResult::success(
- DisplayAvaxTx::from_tx_info(
- parse_data,
- path.full_path,
- address,
- sign_request.get_wallet_index(),
- type_id,
- )
- .c_ptr(),
+ macro_rules! parse_tx {
+ ($tx_type:ty) => {
+ parse_avax_tx::<$tx_type>(tx_data)
+ .map(|parse_data| {
+ TransactionParseResult::success(
+ DisplayAvaxTx::from_tx_info(
+ parse_data,
+ path.full_path,
+ address,
+ sign_request.get_wallet_index(),
+ type_id,
)
- .c_ptr()
- })
- .unwrap_or_else(|_| {
- TransactionParseResult::from(RustCError::InvalidMasterFingerprint).c_ptr()
- })
- };
- }
+ .c_ptr(),
+ )
+ .c_ptr()
+ })
+ .unwrap_or_else(|_| {
+ TransactionParseResult::from(RustCError::InvalidMasterFingerprint).c_ptr()
+ })
+ };
+ }
- match type_id {
- TypeId::BaseTx => {
- let header = get_avax_tx_header(tx_data.clone()).unwrap();
- if header.get_blockchain_id() == C_BLOCKCHAIN_ID
- || header.get_blockchain_id() == C_TEST_BLOCKCHAIN_ID
- {
- path.full_path = "".to_string();
- return parse_tx!(CchainImportTx);
- } else {
- return parse_tx!(BaseTx);
- }
+ match type_id {
+ TypeId::BaseTx => {
+ let header = get_avax_tx_header(tx_data.clone()).unwrap();
+ if header.get_blockchain_id() == C_BLOCKCHAIN_ID
+ || header.get_blockchain_id() == C_TEST_BLOCKCHAIN_ID
+ {
+ path.full_path = "".to_string();
+ parse_tx!(CchainImportTx)
+ } else {
+ parse_tx!(BaseTx)
}
- TypeId::PchainExportTx | TypeId::XchainExportTx => parse_tx!(ExportTx),
- TypeId::XchainImportTx | TypeId::PchainImportTx => parse_tx!(ImportTx),
- TypeId::CchainExportTx => parse_tx!(CchainExportTx),
- TypeId::AddPermissLessionValidator => parse_tx!(AddPermissLessionValidatorTx),
- TypeId::AddPermissLessionDelegator => parse_tx!(AddPermissLessionDelegatorTx),
- _ => TransactionParseResult::from(RustCError::InvalidData(format!(
- "{:?} not support",
- type_id
- )))
- .c_ptr(),
}
+ TypeId::PchainExportTx | TypeId::XchainExportTx => parse_tx!(ExportTx),
+ TypeId::XchainImportTx | TypeId::PchainImportTx => parse_tx!(ImportTx),
+ TypeId::CchainExportTx => parse_tx!(CchainExportTx),
+ TypeId::AddPermissLessionValidator => parse_tx!(AddPermissLessionValidatorTx),
+ TypeId::AddPermissLessionDelegator => parse_tx!(AddPermissLessionDelegatorTx),
+ _ => TransactionParseResult::from(RustCError::InvalidData(format!(
+ "{type_id:?} not support"
+ )))
+ .c_ptr(),
}
}
#[no_mangle]
-fn avax_sign_dynamic(
+unsafe fn avax_sign_dynamic(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
fragment_length: usize,
) -> PtrT<UREncodeResult> {
- let seed = unsafe { alloc::slice::from_raw_parts(seed, seed_len as usize) };
- build_sign_result(ptr, &seed)
+ let seed = extract_array!(seed, u8, seed_len as usize);
+ build_sign_result(ptr, seed)
.map(|v: AvaxSignature| v.try_into())
.map_or_else(
|e| UREncodeResult::from(e).c_ptr(),
@@ -183,21 +178,18 @@ pub fn determine_derivation_path(
sign_request: &AvaxSignRequest,
wallet_index: u64,
) -> Result<DerivationPath, AvaxError> {
- let wallet_suffix = format!("/0/{}", wallet_index);
+ let wallet_suffix = format!("/0/{wallet_index}");
let blockchain_id = get_avax_tx_header(sign_request.get_tx_data())?.get_blockchain_id();
let is_c_chain = |id: &[u8; 32]| *id == C_BLOCKCHAIN_ID || *id == C_TEST_BLOCKCHAIN_ID;
let (base_path, full_path) = match type_id {
- TypeId::CchainExportTx => (
- C_CHAIN_PREFIX,
- format!("{}{}", C_CHAIN_PREFIX, wallet_suffix),
- ),
+ TypeId::CchainExportTx => (C_CHAIN_PREFIX, format!("{C_CHAIN_PREFIX}{wallet_suffix}")),
TypeId::XchainImportTx | TypeId::PchainImportTx => {
let source_chain_id =
parse_avax_tx::<ImportTx>(sign_request.get_tx_data())?.get_source_chain_id();
(
X_P_CHAIN_PREFIX,
- format!("{}{}", X_P_CHAIN_PREFIX, wallet_suffix),
+ format!("{X_P_CHAIN_PREFIX}{wallet_suffix}"),
)
}
_ => {
@@ -206,7 +198,7 @@ pub fn determine_derivation_path(
} else {
X_P_CHAIN_PREFIX
};
- (prefix, format!("{}{}", prefix, wallet_suffix))
+ (prefix, format!("{prefix}{wallet_suffix}"))
}
};
@@ -216,13 +208,13 @@ pub fn determine_derivation_path(
})
}
-fn build_sign_result(ptr: PtrUR, seed: &[u8]) -> Result<AvaxSignature, AvaxError> {
+unsafe fn build_sign_result(ptr: PtrUR, seed: &[u8]) -> Result<AvaxSignature, AvaxError> {
let sign_request = extract_ptr_with_type!(ptr, AvaxSignRequest);
let path = get_avax_tx_type_id(sign_request.get_tx_data())
.map_err(|_| AvaxError::InvalidInput)
.and_then(|type_id| {
- determine_derivation_path(type_id, &sign_request, sign_request.get_wallet_index())
+ determine_derivation_path(type_id, sign_request, sign_request.get_wallet_index())
})?
.full_path;
@@ -231,27 +223,27 @@ fn build_sign_result(ptr: PtrUR, seed: &[u8]) -> Result<AvaxSignature, AvaxError
}
#[no_mangle]
-pub extern "C" fn avax_sign(ptr: PtrUR, seed: PtrBytes, seed_len: u32) -> PtrT<UREncodeResult> {
- avax_sign_dynamic(ptr, seed, seed_len, FRAGMENT_MAX_LENGTH_DEFAULT.clone())
+pub unsafe extern "C" fn avax_sign(ptr: PtrUR, seed: PtrBytes, seed_len: u32) -> PtrT<UREncodeResult> {
+ avax_sign_dynamic(ptr, seed, seed_len, FRAGMENT_MAX_LENGTH_DEFAULT)
}
#[no_mangle]
-pub extern "C" fn avax_sign_unlimited(
+pub unsafe extern "C" fn avax_sign_unlimited(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
) -> PtrT<UREncodeResult> {
- avax_sign_dynamic(ptr, seed, seed_len, FRAGMENT_UNLIMITED_LENGTH.clone())
+ avax_sign_dynamic(ptr, seed, seed_len, FRAGMENT_UNLIMITED_LENGTH)
}
#[no_mangle]
-pub extern "C" fn avax_check_transaction(
+pub unsafe extern "C" fn avax_check_transaction(
ptr: PtrUR,
mfp: PtrBytes,
mfp_len: u32,
) -> PtrT<TransactionCheckResult> {
let avax_tx = extract_ptr_with_type!(ptr, AvaxSignRequest);
- let mfp: [u8; 4] = match unsafe { slice::from_raw_parts(mfp, mfp_len as usize) }.try_into() {
+ let mfp: [u8; 4] = match extract_array!(mfp, u8, mfp_len as usize).try_into() {
Ok(mfp) => mfp,
Err(_) => {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
diff --git a/rust/rust_c/src/avalanche/structs.rs b/rust/rust_c/src/avalanche/structs.rs
index 020e7cc..bbb0a14 100644
--- a/rust/rust_c/src/avalanche/structs.rs
+++ b/rust/rust_c/src/avalanche/structs.rs
@@ -15,7 +15,7 @@ use app_avalanche::transactions::{
use crate::common::{
errors::RustCError,
ffi::{CSliceFFI, VecFFI},
- free::{free_ptr_string, Free},
+ free::Free,
structs::{ExtendedPublicKey, SimpleResponse, TransactionCheckResult, TransactionParseResult},
types::{Ptr, PtrBytes, PtrString, PtrT, PtrUR},
ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT, FRAGMENT_UNLIMITED_LENGTH},
@@ -23,8 +23,8 @@ use crate::common::{
};
use crate::{
- check_and_free_ptr, extract_ptr_with_type, free_str_ptr, impl_c_ptr, impl_new_error,
- impl_response, impl_simple_c_ptr, impl_simple_new_error, make_free_method,
+ extract_ptr_with_type, free_str_ptr, impl_c_ptr, impl_new_error, impl_response,
+ impl_simple_c_ptr, impl_simple_new_error, make_free_method,
};
#[repr(C)]
@@ -60,12 +60,10 @@ pub struct DisplayAvaxFromToInfo {
}
impl Free for DisplayAvaxFromToInfo {
- fn free(&self) {
- unsafe {
- free_ptr_string(self.address);
- free_ptr_string(self.amount);
- free_ptr_string(self.path);
- }
+ unsafe fn free(&self) {
+ free_str_ptr!(self.address);
+ free_str_ptr!(self.amount);
+ free_str_ptr!(self.path);
}
}
@@ -78,7 +76,7 @@ impl DisplayAvaxFromToInfo {
from_address: String,
type_id: TypeId,
) -> Self {
- let address = value.address.get(0).unwrap().clone();
+ let address = value.address.first().unwrap().clone();
let is_change = match type_id {
TypeId::XchainImportTx
| TypeId::PchainImportTx
@@ -86,7 +84,7 @@ impl DisplayAvaxFromToInfo {
| TypeId::PchainExportTx => false,
_ => address == from_address,
};
- let path = if is_change == false {
+ let path = if !is_change {
null_mut()
} else {
convert_c_char(format!("{}/0/{}", value.path_prefix, wallet_index))
@@ -114,11 +112,9 @@ pub struct DisplayAvaxMethodInfo {
impl_c_ptr!(DisplayAvaxMethodInfo);
impl Free for DisplayAvaxMethodInfo {
- fn free(&self) {
- unsafe {
- free_ptr_string(self.method_key);
- free_ptr_string(self.method);
- }
+ unsafe fn free(&self) {
+ free_str_ptr!(self.method_key);
+ free_str_ptr!(self.method);
}
}
@@ -223,37 +219,33 @@ impl DisplayTxAvaxData {
}
impl Free for DisplayTxAvaxData {
- fn free(&self) {
- unsafe {
- // let x = Box::from_raw(self.from);
- // let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- // ve.iter().for_each(|v| {
- // v.free();
- // });
- let x = Box::from_raw(self.to);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
-
- free_ptr_string(self.amount);
- free_ptr_string(self.network);
- free_ptr_string(self.network_key);
- free_ptr_string(self.subnet_id);
- free_ptr_string(self.total_output_amount);
- free_ptr_string(self.total_input_amount);
- free_ptr_string(self.fee_amount);
- free_ptr_string(self.reward_address);
- Box::from_raw(self.method);
- }
+ unsafe fn free(&self) {
+ // let x = Box::from_raw(self.from);
+ // let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ // ve.iter().for_each(|v| {
+ // v.free();
+ // });
+ let x = Box::from_raw(self.to);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+
+ free_str_ptr!(self.amount);
+ free_str_ptr!(self.network);
+ free_str_ptr!(self.network_key);
+ free_str_ptr!(self.subnet_id);
+ free_str_ptr!(self.total_output_amount);
+ free_str_ptr!(self.total_input_amount);
+ free_str_ptr!(self.fee_amount);
+ free_str_ptr!(self.reward_address);
+ Box::from_raw(self.method);
}
}
impl Free for DisplayAvaxTx {
- fn free(&self) {
- unsafe {
- Box::from_raw(self.data).free();
- }
+ unsafe fn free(&self) {
+ Box::from_raw(self.data).free();
}
}
diff --git a/rust/rust_c/src/bitcoin/address.rs b/rust/rust_c/src/bitcoin/address.rs
index a0ac321..936e1ad 100644
--- a/rust/rust_c/src/bitcoin/address.rs
+++ b/rust/rust_c/src/bitcoin/address.rs
@@ -7,7 +7,7 @@ use bitcoin::secp256k1::ffi::types::c_char;
use core::str::FromStr;
#[no_mangle]
-pub extern "C" fn utxo_get_address(
+pub unsafe extern "C" fn utxo_get_address(
hd_path: PtrString,
x_pub: PtrString,
) -> *mut SimpleResponse<c_char> {
@@ -21,7 +21,7 @@ pub extern "C" fn utxo_get_address(
}
#[no_mangle]
-pub extern "C" fn xpub_convert_version(
+pub unsafe extern "C" fn xpub_convert_version(
x_pub: PtrString,
target: PtrString,
) -> *mut SimpleResponse<c_char> {
diff --git a/rust/rust_c/src/bitcoin/legacy.rs b/rust/rust_c/src/bitcoin/legacy.rs
index e7d23af..919ece7 100644
--- a/rust/rust_c/src/bitcoin/legacy.rs
+++ b/rust/rust_c/src/bitcoin/legacy.rs
@@ -6,10 +6,10 @@ use crate::common::structs::{TransactionCheckResult, TransactionParseResult};
use crate::common::types::{PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{QRCodeType, UREncodeResult};
use alloc::boxed::Box;
-use alloc::slice;
+use crate::extract_array;
#[no_mangle]
-pub extern "C" fn utxo_parse_keystone(
+pub unsafe extern "C" fn utxo_parse_keystone(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -41,7 +41,7 @@ pub extern "C" fn utxo_parse_keystone(
}
#[no_mangle]
-pub extern "C" fn utxo_sign_keystone(
+pub unsafe extern "C" fn utxo_sign_keystone(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -51,7 +51,7 @@ pub extern "C" fn utxo_sign_keystone(
seed: PtrBytes,
seed_len: u32,
) -> *mut UREncodeResult {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
keystone::sign(
ptr,
ur_type,
@@ -64,7 +64,7 @@ pub extern "C" fn utxo_sign_keystone(
}
#[no_mangle]
-pub extern "C" fn utxo_check_keystone(
+pub unsafe extern "C" fn utxo_check_keystone(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
diff --git a/rust/rust_c/src/bitcoin/msg.rs b/rust/rust_c/src/bitcoin/msg.rs
index dd84d57..bf22b05 100644
--- a/rust/rust_c/src/bitcoin/msg.rs
+++ b/rust/rust_c/src/bitcoin/msg.rs
@@ -1,16 +1,17 @@
use super::structs::DisplayBtcMsg;
-use crate::common::{
- errors::RustCError,
- ffi::CSliceFFI,
- qrcode::seed_signer_message::SeedSignerMessage,
- structs::{ExtendedPublicKey, TransactionCheckResult, TransactionParseResult},
- types::{Ptr, PtrBytes, PtrT, PtrUR},
- ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT},
- utils::{convert_c_char, recover_c_array, recover_c_char},
+use crate::{
+ common::{
+ errors::RustCError,
+ ffi::CSliceFFI,
+ qrcode::seed_signer_message::SeedSignerMessage,
+ structs::{ExtendedPublicKey, TransactionCheckResult, TransactionParseResult},
+ types::{Ptr, PtrBytes, PtrT, PtrUR},
+ ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT},
+ utils::{convert_c_char, recover_c_array, recover_c_char},
+ },
+ extract_array, extract_ptr_with_type,
};
-use crate::extract_ptr_with_type;
use alloc::{
- slice,
string::{String, ToString},
vec::Vec,
};
@@ -22,7 +23,7 @@ use ur_registry::bitcoin::btc_signature::BtcSignature;
use ur_registry::traits::RegistryItem;
#[no_mangle]
-pub extern "C" fn btc_check_msg(
+pub unsafe extern "C" fn btc_check_msg(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -30,7 +31,7 @@ pub extern "C" fn btc_check_msg(
if length != 4 {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let sign_request = extract_ptr_with_type!(ptr, BtcSignRequest);
let ur_mfp = sign_request.get_derivation_paths()[0].get_source_fingerprint();
@@ -49,7 +50,7 @@ pub extern "C" fn btc_check_msg(
}
#[no_mangle]
-pub extern "C" fn btc_parse_msg(
+pub unsafe extern "C" fn btc_parse_msg(
ptr: PtrUR,
xpubs: Ptr<CSliceFFI<ExtendedPublicKey>>,
master_fingerprint: PtrBytes,
@@ -59,44 +60,41 @@ pub extern "C" fn btc_parse_msg(
return TransactionParseResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
let req = extract_ptr_with_type!(ptr, BtcSignRequest);
- unsafe {
- let public_keys = recover_c_array(xpubs);
- let mfp = alloc::slice::from_raw_parts(master_fingerprint, 4);
- let derivation_path = req.get_derivation_paths()[0].clone();
- if let Some(q_mfp) = derivation_path.get_source_fingerprint() {
- if q_mfp.eq(mfp) {
- match req.get_data_type() {
- DataType::Message => {
- let path = derivation_path.get_path();
- if let Some(path) = path {
- let address = public_keys
- .iter()
- .find(|key| {
- let xpub_path = recover_c_char(key.path);
- path.clone().starts_with(&xpub_path)
- })
- .map(|v| recover_c_char(v.xpub))
- .and_then(|xpub| app_bitcoin::get_address(path, &xpub).ok());
- let msg = req.get_sign_data();
- if let Ok(msg_uft8) = String::from_utf8(msg.to_vec()) {
- let display_msg = DisplayBtcMsg {
- detail: convert_c_char(msg_uft8),
- address: address.map(convert_c_char).unwrap_or(null_mut()),
- };
- return TransactionParseResult::success(display_msg.c_ptr())
- .c_ptr();
- }
+ let public_keys = recover_c_array(xpubs);
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let derivation_path = req.get_derivation_paths()[0].clone();
+ if let Some(q_mfp) = derivation_path.get_source_fingerprint() {
+ if q_mfp.eq(mfp) {
+ match req.get_data_type() {
+ DataType::Message => {
+ let path = derivation_path.get_path();
+ if let Some(path) = path {
+ let address = public_keys
+ .iter()
+ .find(|key| {
+ let xpub_path = recover_c_char(key.path);
+ path.clone().starts_with(&xpub_path)
+ })
+ .map(|v| recover_c_char(v.xpub))
+ .and_then(|xpub| app_bitcoin::get_address(path, &xpub).ok());
+ let msg = req.get_sign_data();
+ if let Ok(msg_uft8) = String::from_utf8(msg.to_vec()) {
+ let display_msg = DisplayBtcMsg {
+ detail: convert_c_char(msg_uft8),
+ address: address.map(convert_c_char).unwrap_or(null_mut()),
+ };
+ return TransactionParseResult::success(display_msg.c_ptr()).c_ptr();
}
}
}
}
}
- TransactionParseResult::from(RustCError::MasterFingerprintMismatch).c_ptr()
}
+ TransactionParseResult::from(RustCError::MasterFingerprintMismatch).c_ptr()
}
#[no_mangle]
-pub extern "C" fn btc_sign_msg(
+pub unsafe extern "C" fn btc_sign_msg(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -107,43 +105,41 @@ pub extern "C" fn btc_sign_msg(
return UREncodeResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
let req = extract_ptr_with_type!(ptr, BtcSignRequest);
- unsafe {
- let mfp = alloc::slice::from_raw_parts(master_fingerprint, 4);
- let seed = alloc::slice::from_raw_parts(seed, seed_len as usize);
- if let Some(q_mfp) = req.get_derivation_paths()[0].get_source_fingerprint() {
- if q_mfp.eq(mfp) {
- match req.get_data_type() {
- DataType::Message => {
- let msg_utf8 = String::from_utf8_unchecked(req.get_sign_data().to_vec());
- if let Some(path) = req.get_derivation_paths()[0].get_path() {
- if let Ok(sig) = app_bitcoin::sign_msg(msg_utf8.as_str(), seed, &path) {
- if let Ok(extended_key) =
- secp256k1::get_extended_public_key_by_seed(seed, &path)
- {
- let btc_signature = BtcSignature::new(
- req.get_request_id(),
- sig,
- extended_key.to_pub().to_bytes().to_vec(),
- );
- let data: Vec<u8> = match btc_signature.try_into() {
- Ok(v) => v,
- Err(e) => return UREncodeResult::from(e).c_ptr(),
- };
- return UREncodeResult::encode(
- data,
- BtcSignature::get_registry_type().get_type(),
- FRAGMENT_MAX_LENGTH_DEFAULT,
- )
- .c_ptr();
- }
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let seed = extract_array!(seed, u8, seed_len as usize);
+ if let Some(q_mfp) = req.get_derivation_paths()[0].get_source_fingerprint() {
+ if q_mfp.eq(mfp) {
+ match req.get_data_type() {
+ DataType::Message => {
+ let msg_utf8 = String::from_utf8_unchecked(req.get_sign_data().to_vec());
+ if let Some(path) = req.get_derivation_paths()[0].get_path() {
+ if let Ok(sig) = app_bitcoin::sign_msg(msg_utf8.as_str(), seed, &path) {
+ if let Ok(extended_key) =
+ secp256k1::get_extended_public_key_by_seed(seed, &path)
+ {
+ let btc_signature = BtcSignature::new(
+ req.get_request_id(),
+ sig,
+ extended_key.to_pub().to_bytes().to_vec(),
+ );
+ let data: Vec<u8> = match btc_signature.try_into() {
+ Ok(v) => v,
+ Err(e) => return UREncodeResult::from(e).c_ptr(),
+ };
+ return UREncodeResult::encode(
+ data,
+ BtcSignature::get_registry_type().get_type(),
+ FRAGMENT_MAX_LENGTH_DEFAULT,
+ )
+ .c_ptr();
}
- return UREncodeResult::from(RustCError::UnexpectedError(
- "failed to sign".to_string(),
- ))
- .c_ptr();
}
- return UREncodeResult::from(RustCError::InvalidHDPath).c_ptr();
+ return UREncodeResult::from(RustCError::UnexpectedError(
+ "failed to sign".to_string(),
+ ))
+ .c_ptr();
}
+ return UREncodeResult::from(RustCError::InvalidHDPath).c_ptr();
}
}
}
@@ -152,14 +148,14 @@ pub extern "C" fn btc_sign_msg(
}
#[no_mangle]
-pub extern "C" fn parse_seed_signer_message(
+pub unsafe extern "C" fn parse_seed_signer_message(
ptr: PtrUR,
xpubs: Ptr<CSliceFFI<ExtendedPublicKey>>,
) -> Ptr<TransactionParseResult<DisplayBtcMsg>> {
let req = extract_ptr_with_type!(ptr, SeedSignerMessage);
let path = req.get_path();
let message = req.get_message();
- let public_keys = unsafe { recover_c_array(xpubs) };
+ let public_keys = recover_c_array(xpubs);
let address = public_keys
.iter()
.find(|key| {
@@ -190,7 +186,7 @@ pub extern "C" fn parse_seed_signer_message(
}
#[no_mangle]
-pub extern "C" fn sign_seed_signer_message(
+pub unsafe extern "C" fn sign_seed_signer_message(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -198,12 +194,10 @@ pub extern "C" fn sign_seed_signer_message(
let req = extract_ptr_with_type!(ptr, SeedSignerMessage);
let path = req.get_path();
let message = req.get_message();
- unsafe {
- let seed = alloc::slice::from_raw_parts(seed, seed_len as usize);
- let sig = app_bitcoin::sign_msg(&message, seed, &path);
- match sig {
- Ok(sig) => UREncodeResult::text(base64::encode_config(&sig, base64::STANDARD)).c_ptr(),
- Err(e) => UREncodeResult::from(e).c_ptr(),
- }
+ let seed = extract_array!(seed, u8, seed_len as usize);
+ let sig = app_bitcoin::sign_msg(&message, seed, &path);
+ match sig {
+ Ok(sig) => UREncodeResult::text(base64::encode_config(&sig, base64::STANDARD)).c_ptr(),
+ Err(e) => UREncodeResult::from(e).c_ptr(),
}
}
diff --git a/rust/rust_c/src/bitcoin/multi_sig/mod.rs b/rust/rust_c/src/bitcoin/multi_sig/mod.rs
index 98f0ce5..58b5598 100644
--- a/rust/rust_c/src/bitcoin/multi_sig/mod.rs
+++ b/rust/rust_c/src/bitcoin/multi_sig/mod.rs
@@ -30,7 +30,7 @@ use crate::common::utils::{convert_c_char, recover_c_array, recover_c_char};
use structs::{MultiSigWallet, NetworkType};
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use ur_registry::crypto_account::CryptoAccount;
use ur_registry::error::URError;
use ur_registry::traits::RegistryItem;
@@ -44,8 +44,7 @@ pub extern "C" fn export_multi_sig_xpub_by_ur(
) -> *mut UREncodeResult {
if length != 4 {
return UREncodeResult::from(URError::UrEncodeError(format!(
- "master fingerprint length must be 4, current is {}",
- length
+ "master fingerprint length must be 4, current is {length}"
)))
.c_ptr();
}
@@ -107,8 +106,7 @@ pub extern "C" fn export_multi_sig_wallet_by_ur_test(
) -> *mut UREncodeResult {
if length != 4 {
return UREncodeResult::from(URError::UrEncodeError(format!(
- "master fingerprint length must be 4, current is {}",
- length
+ "master fingerprint length must be 4, current is {length}"
)))
.c_ptr();
}
@@ -149,7 +147,7 @@ pub extern "C" fn export_multi_sig_wallet_by_ur_test(
#[no_mangle]
#[cfg(feature = "btc-only")]
-pub extern "C" fn export_xpub_info_by_ur(
+pub unsafe extern "C" fn export_xpub_info_by_ur(
ur: PtrUR,
multi_sig_type: MultiSigFormatType,
viewType: ViewType,
@@ -188,8 +186,7 @@ pub extern "C" fn export_multi_sig_wallet_by_ur(
) -> *mut UREncodeResult {
if length != 4 {
return UREncodeResult::from(URError::UrEncodeError(format!(
- "master fingerprint length must be 4, current is {}",
- length
+ "master fingerprint length must be 4, current is {length}"
)))
.c_ptr();
}
@@ -234,7 +231,7 @@ pub extern "C" fn export_multi_sig_wallet_by_ur(
}
#[no_mangle]
-pub extern "C" fn import_multi_sig_wallet_by_ur(
+pub unsafe extern "C" fn import_multi_sig_wallet_by_ur(
ur: PtrUR,
master_fingerprint: PtrBytes,
master_fingerprint_len: u32,
@@ -242,7 +239,7 @@ pub extern "C" fn import_multi_sig_wallet_by_ur(
if master_fingerprint_len != 4 {
return Response::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -265,7 +262,7 @@ pub extern "C" fn import_multi_sig_wallet_by_ur(
}
#[no_mangle]
-pub extern "C" fn import_multi_sig_wallet_by_file(
+pub unsafe extern "C" fn import_multi_sig_wallet_by_file(
content: PtrString,
master_fingerprint: PtrBytes,
master_fingerprint_len: u32,
@@ -273,7 +270,7 @@ pub extern "C" fn import_multi_sig_wallet_by_file(
if master_fingerprint_len != 4 {
return Response::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -295,7 +292,7 @@ pub extern "C" fn import_multi_sig_wallet_by_file(
}
#[no_mangle]
-pub extern "C" fn check_multi_sig_wallet_exist(
+pub unsafe extern "C" fn check_multi_sig_wallet_exist(
content: PtrString,
master_fingerprint: PtrBytes,
master_fingerprint_len: u32,
@@ -303,7 +300,7 @@ pub extern "C" fn check_multi_sig_wallet_exist(
if master_fingerprint_len != 4 {
return false;
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -321,7 +318,7 @@ pub extern "C" fn check_multi_sig_wallet_exist(
}
#[no_mangle]
-pub extern "C" fn generate_address_for_multisig_wallet_config(
+pub unsafe extern "C" fn generate_address_for_multisig_wallet_config(
wallet_config: PtrString,
account: u32,
index: u32,
@@ -331,7 +328,7 @@ pub extern "C" fn generate_address_for_multisig_wallet_config(
if master_fingerprint_len != 4 {
return SimpleResponse::from(RustCError::InvalidMasterFingerprint).simple_c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -352,7 +349,7 @@ pub extern "C" fn generate_address_for_multisig_wallet_config(
}
#[no_mangle]
-pub extern "C" fn generate_psbt_file_name(
+pub unsafe extern "C" fn generate_psbt_file_name(
// origin_file_name: PtrString,
// wallet_name: PtrString,
psbt_hex: PtrBytes,
@@ -360,7 +357,7 @@ pub extern "C" fn generate_psbt_file_name(
time_stamp: u32,
) -> Ptr<SimpleResponse<c_char>> {
// let wallet_name = recover_c_char(wallet_name);
- let psbt_hex = unsafe { slice::from_raw_parts(psbt_hex, psbt_len as usize) };
+ let psbt_hex = extract_array!(psbt_hex, u8, psbt_len as usize);
let hash = sha256(psbt_hex);
let checksum = hex::encode(&hash[0..4]);
let name = format!("tx_{checksum}_{time_stamp}_signed.psbt");
@@ -379,7 +376,7 @@ pub extern "C" fn generate_psbt_file_name(
}
#[no_mangle]
-pub extern "C" fn parse_and_verify_multisig_config(
+pub unsafe extern "C" fn parse_and_verify_multisig_config(
seed: PtrBytes,
seed_len: u32,
wallet_config: PtrString,
@@ -389,8 +386,8 @@ pub extern "C" fn parse_and_verify_multisig_config(
if master_fingerprint_len != 4 {
return Response::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let seed = unsafe { core::slice::from_raw_parts(seed, seed_len as usize) };
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -403,7 +400,7 @@ pub extern "C" fn parse_and_verify_multisig_config(
let content = recover_c_char(wallet_config);
match parse_wallet_config(&content, &master_fingerprint.to_string()) {
Ok(mut config) => {
- match strict_verify_wallet_config(seed, &mut config, &master_fingerprint.to_string()) {
+ match strict_verify_wallet_config(seed, &config, &master_fingerprint.to_string()) {
Ok(()) => Response::success(MultiSigWallet::from(config)).c_ptr(),
Err(e) => Response::from(e).c_ptr(),
}
diff --git a/rust/rust_c/src/bitcoin/multi_sig/structs.rs b/rust/rust_c/src/bitcoin/multi_sig/structs.rs
index 66a0bee..dce3c45 100644
--- a/rust/rust_c/src/bitcoin/multi_sig/structs.rs
+++ b/rust/rust_c/src/bitcoin/multi_sig/structs.rs
@@ -7,7 +7,7 @@ use crate::common::free::Free;
use crate::common::types::{Ptr, PtrBytes, PtrString, PtrT};
use crate::common::ur::UREncodeResult;
use crate::common::utils::{convert_c_char, recover_c_char};
-use crate::{check_and_free_ptr, free_str_ptr, free_vec, impl_c_ptr, make_free_method};
+use crate::{free_str_ptr, free_vec, impl_c_ptr, make_free_method};
use alloc::vec::Vec;
use app_bitcoin::multi_sig::wallet::{BsmsWallet, MultiSigWalletConfig};
use app_bitcoin::multi_sig::{MultiSigFormat, MultiSigType, MultiSigXPubInfo, Network};
@@ -117,10 +117,12 @@ impl From<MultiSigXPubInfo> for MultiSigXPubInfoItem {
impl From<&MultiSigXPubInfoItem> for MultiSigXPubInfo {
fn from(val: &MultiSigXPubInfoItem) -> Self {
- MultiSigXPubInfo {
- path: recover_c_char(val.path),
- xfp: recover_c_char(val.xfp),
- xpub: recover_c_char(val.xpub),
+ unsafe {
+ MultiSigXPubInfo {
+ path: recover_c_char(val.path),
+ xfp: recover_c_char(val.xfp),
+ xpub: recover_c_char(val.xpub),
+ }
}
}
}
@@ -137,11 +139,13 @@ impl From<BsmsWallet> for MultiSigXPubInfoItem {
impl From<&MultiSigXPubInfoItem> for BsmsWallet {
fn from(val: &MultiSigXPubInfoItem) -> Self {
- BsmsWallet {
- bsms_version: "BSMS 1.0".to_string(),
- derivation_path: recover_c_char(val.path),
- xfp: recover_c_char(val.xfp),
- extended_pubkey: recover_c_char(val.xpub),
+ unsafe {
+ BsmsWallet {
+ bsms_version: "BSMS 1.0".to_string(),
+ derivation_path: recover_c_char(val.path),
+ xfp: recover_c_char(val.xfp),
+ extended_pubkey: recover_c_char(val.xpub),
+ }
}
}
}
@@ -149,7 +153,7 @@ impl From<&MultiSigXPubInfoItem> for BsmsWallet {
impl_c_ptr!(MultiSigXPubInfoItem);
impl Free for MultiSigXPubInfoItem {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.xfp);
free_str_ptr!(self.xpub);
free_str_ptr!(self.path);
@@ -174,9 +178,11 @@ impl From<&app_bitcoin::multi_sig::wallet::MultiSigXPubItem> for MultiSigXPubIte
impl From<&MultiSigXPubItem> for app_bitcoin::multi_sig::wallet::MultiSigXPubItem {
fn from(val: &MultiSigXPubItem) -> Self {
- app_bitcoin::multi_sig::wallet::MultiSigXPubItem {
- xfp: recover_c_char(val.xfp),
- xpub: recover_c_char(val.xpub),
+ unsafe {
+ app_bitcoin::multi_sig::wallet::MultiSigXPubItem {
+ xfp: recover_c_char(val.xfp),
+ xpub: recover_c_char(val.xpub),
+ }
}
}
}
@@ -184,7 +190,7 @@ impl From<&MultiSigXPubItem> for app_bitcoin::multi_sig::wallet::MultiSigXPubIte
impl_c_ptr!(MultiSigXPubItem);
impl Free for MultiSigXPubItem {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.xfp);
free_str_ptr!(self.xpub);
}
@@ -208,88 +214,92 @@ pub struct MultiSigWallet {
impl From<MultiSigWalletConfig> for MultiSigWallet {
fn from(value: MultiSigWalletConfig) -> Self {
- MultiSigWallet {
- creator: convert_c_char(value.creator.clone()),
- name: convert_c_char(value.name.clone()),
- policy: convert_c_char(format!("{} of {}", value.threshold, value.total)),
- threshold: value.threshold,
- total: value.total,
- derivations: VecFFI::from(
- value
- .derivations
- .clone()
- .iter()
- .map(|v| convert_c_char(v.to_string()))
- .collect::<Vec<_>>(),
- )
- .c_ptr(),
- format: convert_c_char(value.format.clone()),
- xpub_items: VecFFI::from(
- value
- .xpub_items
- .clone()
- .iter()
- .map(MultiSigXPubItem::from)
- .collect::<Vec<MultiSigXPubItem>>(),
- )
- .c_ptr(),
- verify_code: convert_c_char(value.verify_code.clone()),
- verify_without_mfp: convert_c_char(value.verify_without_mfp.clone()),
- config_text: convert_c_char(value.config_text.clone()),
- network: value.get_network_u32(),
+ unsafe {
+ MultiSigWallet {
+ creator: convert_c_char(value.creator.clone()),
+ name: convert_c_char(value.name.clone()),
+ policy: convert_c_char(format!("{} of {}", value.threshold, value.total)),
+ threshold: value.threshold,
+ total: value.total,
+ derivations: VecFFI::from(
+ value
+ .derivations
+ .clone()
+ .iter()
+ .map(|v| convert_c_char(v.to_string()))
+ .collect::<Vec<_>>(),
+ )
+ .c_ptr(),
+ format: convert_c_char(value.format.clone()),
+ xpub_items: VecFFI::from(
+ value
+ .xpub_items
+ .clone()
+ .iter()
+ .map(MultiSigXPubItem::from)
+ .collect::<Vec<MultiSigXPubItem>>(),
+ )
+ .c_ptr(),
+ verify_code: convert_c_char(value.verify_code.clone()),
+ verify_without_mfp: convert_c_char(value.verify_without_mfp.clone()),
+ config_text: convert_c_char(value.config_text.clone()),
+ network: value.get_network_u32(),
+ }
}
}
}
impl From<&mut MultiSigWallet> for MultiSigWalletConfig {
fn from(val: &mut MultiSigWallet) -> Self {
- MultiSigWalletConfig {
- creator: recover_c_char(val.creator),
- name: recover_c_char(val.name),
- threshold: val.threshold,
- total: val.total,
- derivations: {
- let rebuilt = unsafe {
- let ptr = (*val.derivations).data;
- let size = (*val.derivations).size;
- let cap = (*val.derivations).cap;
-
- let ptr = ptr as PtrT<PtrString>;
- Vec::from_raw_parts(ptr, size, cap)
- };
-
- rebuilt
- .iter()
- .map(|v| recover_c_char(*v))
- .collect::<Vec<_>>()
- },
- format: recover_c_char(val.format),
-
- xpub_items: {
- let rebuilt = unsafe {
- let ptr = (*val.derivations).data;
- let size = (*val.derivations).size;
- let cap = (*val.derivations).cap;
-
- let ptr = ptr as PtrT<MultiSigXPubItem>;
- Vec::from_raw_parts(ptr, size, cap)
- };
- rebuilt.iter().map(|v| v.into()).collect::<Vec<_>>()
- },
- verify_code: recover_c_char(val.verify_code),
- verify_without_mfp: recover_c_char(val.verify_without_mfp),
- config_text: recover_c_char(val.config_text),
- network: if val.network == 0 {
- Network::MainNet
- } else {
- Network::TestNet
- },
+ unsafe {
+ MultiSigWalletConfig {
+ creator: recover_c_char(val.creator),
+ name: recover_c_char(val.name),
+ threshold: val.threshold,
+ total: val.total,
+ derivations: {
+ let rebuilt = unsafe {
+ let ptr = (*val.derivations).data;
+ let size = (*val.derivations).size;
+ let cap = (*val.derivations).cap;
+
+ let ptr = ptr as PtrT<PtrString>;
+ Vec::from_raw_parts(ptr, size, cap)
+ };
+
+ rebuilt
+ .iter()
+ .map(|v| recover_c_char(*v))
+ .collect::<Vec<_>>()
+ },
+ format: recover_c_char(val.format),
+
+ xpub_items: {
+ let rebuilt = unsafe {
+ let ptr = (*val.derivations).data;
+ let size = (*val.derivations).size;
+ let cap = (*val.derivations).cap;
+
+ let ptr = ptr as PtrT<MultiSigXPubItem>;
+ Vec::from_raw_parts(ptr, size, cap)
+ };
+ rebuilt.iter().map(|v| v.into()).collect::<Vec<_>>()
+ },
+ verify_code: recover_c_char(val.verify_code),
+ verify_without_mfp: recover_c_char(val.verify_without_mfp),
+ config_text: recover_c_char(val.config_text),
+ network: if val.network == 0 {
+ Network::MainNet
+ } else {
+ Network::TestNet
+ },
+ }
}
}
}
impl Free for MultiSigWallet {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.creator);
free_str_ptr!(self.name);
free_str_ptr!(self.policy);
@@ -315,12 +325,10 @@ pub struct MultisigSignResult {
}
impl Free for MultisigSignResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.sign_status);
- unsafe {
- if !self.psbt_hex.is_null() {
- let _x = Box::from_raw(self.psbt_hex);
- }
+ if !self.psbt_hex.is_null() {
+ let _x = Box::from_raw(self.psbt_hex);
}
//do not free ur_result because it will be released by itself;
}
diff --git a/rust/rust_c/src/bitcoin/psbt.rs b/rust/rust_c/src/bitcoin/psbt.rs
index 5d85b0e..4cf391d 100644
--- a/rust/rust_c/src/bitcoin/psbt.rs
+++ b/rust/rust_c/src/bitcoin/psbt.rs
@@ -1,6 +1,5 @@
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
-use alloc::slice;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use app_bitcoin::multi_sig::wallet::parse_wallet_config;
@@ -15,6 +14,7 @@ use crate::common::structs::{
use crate::common::types::{Ptr, PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT, FRAGMENT_UNLIMITED_LENGTH};
use crate::common::utils::{convert_c_char, recover_c_array, recover_c_char};
+use crate::extract_array;
use crate::extract_ptr_with_type;
use app_bitcoin::parsed_tx::ParseContext;
use app_bitcoin::{self, parse_psbt_hex_sign_status, parse_psbt_sign_status};
@@ -27,7 +27,7 @@ use super::multi_sig::structs::MultisigSignResult;
use super::structs::DisplayTx;
#[no_mangle]
-pub extern "C" fn btc_parse_psbt(
+pub unsafe extern "C" fn btc_parse_psbt(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -40,20 +40,18 @@ pub extern "C" fn btc_parse_psbt(
let crypto_psbt = extract_ptr_with_type!(ptr, CryptoPSBT);
let psbt = crypto_psbt.get_psbt();
- unsafe {
- let multisig_wallet_config = if multisig_wallet_config.is_null() {
- None
- } else {
- Some(recover_c_char(multisig_wallet_config))
- };
- let mfp = core::slice::from_raw_parts(master_fingerprint, 4);
- let public_keys = recover_c_array(public_keys);
- parse_psbt(mfp, public_keys, psbt, multisig_wallet_config)
- }
+ let multisig_wallet_config = if multisig_wallet_config.is_null() {
+ None
+ } else {
+ Some(recover_c_char(multisig_wallet_config))
+ };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let public_keys = recover_c_array(public_keys);
+ parse_psbt(mfp, public_keys, psbt, multisig_wallet_config)
}
#[no_mangle]
-fn btc_sign_psbt_dynamic(
+unsafe fn btc_sign_psbt_dynamic(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -64,7 +62,7 @@ fn btc_sign_psbt_dynamic(
if master_fingerprint_len != 4 {
return UREncodeResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -78,7 +76,7 @@ fn btc_sign_psbt_dynamic(
let crypto_psbt = extract_ptr_with_type!(ptr, CryptoPSBT);
let psbt = crypto_psbt.get_psbt();
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let result = app_bitcoin::sign_psbt(psbt, seed, master_fingerprint);
match result.map(|v| CryptoPSBT::new(v).try_into()) {
@@ -96,7 +94,7 @@ fn btc_sign_psbt_dynamic(
}
#[no_mangle]
-pub extern "C" fn btc_sign_psbt(
+pub unsafe extern "C" fn btc_sign_psbt(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -114,7 +112,7 @@ pub extern "C" fn btc_sign_psbt(
}
#[no_mangle]
-pub extern "C" fn btc_sign_psbt_unlimited(
+pub unsafe extern "C" fn btc_sign_psbt_unlimited(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -132,7 +130,7 @@ pub extern "C" fn btc_sign_psbt_unlimited(
}
#[no_mangle]
-pub extern "C" fn btc_sign_multisig_psbt(
+pub unsafe extern "C" fn btc_sign_multisig_psbt(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -149,7 +147,7 @@ pub extern "C" fn btc_sign_multisig_psbt(
}
.c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -170,7 +168,7 @@ pub extern "C" fn btc_sign_multisig_psbt(
let crypto_psbt = extract_ptr_with_type!(ptr, CryptoPSBT);
let psbt = crypto_psbt.get_psbt();
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let result = app_bitcoin::sign_psbt_no_serialize(psbt, seed, master_fingerprint);
match result.map(|v| {
@@ -218,7 +216,7 @@ pub extern "C" fn btc_sign_multisig_psbt(
}
#[no_mangle]
-pub extern "C" fn btc_export_multisig_psbt(ptr: PtrUR) -> *mut MultisigSignResult {
+pub unsafe extern "C" fn btc_export_multisig_psbt(ptr: PtrUR) -> *mut MultisigSignResult {
let crypto_psbt = extract_ptr_with_type!(ptr, CryptoPSBT);
let psbt = crypto_psbt.get_psbt();
let sign_state = parse_psbt_hex_sign_status(&psbt);
@@ -251,45 +249,43 @@ pub extern "C" fn btc_export_multisig_psbt(ptr: PtrUR) -> *mut MultisigSignResul
}
#[no_mangle]
-pub extern "C" fn btc_export_multisig_psbt_bytes(
+pub unsafe extern "C" fn btc_export_multisig_psbt_bytes(
psbt_bytes: PtrBytes,
psbt_bytes_length: u32,
) -> *mut MultisigSignResult {
- unsafe {
- let psbt = core::slice::from_raw_parts(psbt_bytes, psbt_bytes_length as usize);
- let psbt = psbt.to_vec();
- let sign_state = parse_psbt_hex_sign_status(&psbt);
- match sign_state {
- Ok(state) => {
- let (ptr, size, _cap) = psbt.clone().into_raw_parts();
- MultisigSignResult {
- ur_result: UREncodeResult::encode(
- psbt,
- CryptoPSBT::get_registry_type().get_type(),
- FRAGMENT_MAX_LENGTH_DEFAULT,
- )
- .c_ptr(),
- sign_status: convert_c_char(state.sign_status.unwrap_or("".to_string())),
- is_completed: state.is_completed,
- psbt_hex: ptr,
- psbt_len: size as u32,
- }
- .c_ptr()
- }
- Err(e) => MultisigSignResult {
- ur_result: UREncodeResult::from(e).c_ptr(),
- sign_status: null_mut(),
- is_completed: false,
- psbt_hex: null_mut(),
- psbt_len: 0,
+ let psbt = extract_array!(psbt_bytes, u8, psbt_bytes_length as usize);
+ let psbt = psbt.to_vec();
+ let sign_state = parse_psbt_hex_sign_status(&psbt);
+ match sign_state {
+ Ok(state) => {
+ let (ptr, size, _cap) = psbt.clone().into_raw_parts();
+ MultisigSignResult {
+ ur_result: UREncodeResult::encode(
+ psbt,
+ CryptoPSBT::get_registry_type().get_type(),
+ FRAGMENT_MAX_LENGTH_DEFAULT,
+ )
+ .c_ptr(),
+ sign_status: convert_c_char(state.sign_status.unwrap_or("".to_string())),
+ is_completed: state.is_completed,
+ psbt_hex: ptr,
+ psbt_len: size as u32,
}
- .c_ptr(),
+ .c_ptr()
+ }
+ Err(e) => MultisigSignResult {
+ ur_result: UREncodeResult::from(e).c_ptr(),
+ sign_status: null_mut(),
+ is_completed: false,
+ psbt_hex: null_mut(),
+ psbt_len: 0,
}
+ .c_ptr(),
}
}
#[no_mangle]
-pub extern "C" fn btc_check_psbt(
+pub unsafe extern "C" fn btc_check_psbt(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -303,25 +299,23 @@ pub extern "C" fn btc_check_psbt(
let crypto_psbt = extract_ptr_with_type!(ptr, CryptoPSBT);
let psbt = crypto_psbt.get_psbt();
- unsafe {
- let verify_code = if verify_code.is_null() {
- None
- } else {
- Some(recover_c_char(verify_code))
- };
- let multisig_wallet_config = if multisig_wallet_config.is_null() {
- None
- } else {
- Some(recover_c_char(multisig_wallet_config))
- };
- let mfp = core::slice::from_raw_parts(master_fingerprint, 4);
- let public_keys = recover_c_array(public_keys);
- check_psbt(mfp, public_keys, psbt, verify_code, multisig_wallet_config)
- }
+ let verify_code = if verify_code.is_null() {
+ None
+ } else {
+ Some(recover_c_char(verify_code))
+ };
+ let multisig_wallet_config = if multisig_wallet_config.is_null() {
+ None
+ } else {
+ Some(recover_c_char(multisig_wallet_config))
+ };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let public_keys = recover_c_array(public_keys);
+ check_psbt(mfp, public_keys, psbt, verify_code, multisig_wallet_config)
}
#[no_mangle]
-pub extern "C" fn btc_check_psbt_bytes(
+pub unsafe extern "C" fn btc_check_psbt_bytes(
psbt_bytes: PtrBytes,
psbt_bytes_length: u32,
master_fingerprint: PtrBytes,
@@ -333,32 +327,30 @@ pub extern "C" fn btc_check_psbt_bytes(
if length != 4 {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- unsafe {
- let psbt = core::slice::from_raw_parts(psbt_bytes, psbt_bytes_length as usize);
- let psbt = match get_psbt_bytes(psbt) {
- Ok(psbt) => psbt,
- Err(e) => return TransactionCheckResult::from(e).c_ptr(),
- };
+ let psbt = extract_array!(psbt_bytes, u8, psbt_bytes_length as usize);
+ let psbt = match get_psbt_bytes(psbt) {
+ Ok(psbt) => psbt,
+ Err(e) => return TransactionCheckResult::from(e).c_ptr(),
+ };
- let verify_code = if verify_code.is_null() {
- None
- } else {
- Some(recover_c_char(verify_code))
- };
+ let verify_code = if verify_code.is_null() {
+ None
+ } else {
+ Some(recover_c_char(verify_code))
+ };
- let multisig_wallet_config = if multisig_wallet_config.is_null() {
- None
- } else {
- Some(recover_c_char(multisig_wallet_config))
- };
- let mfp = core::slice::from_raw_parts(master_fingerprint, 4);
- let public_keys = recover_c_array(public_keys);
- check_psbt(mfp, public_keys, psbt, verify_code, multisig_wallet_config)
- }
+ let multisig_wallet_config = if multisig_wallet_config.is_null() {
+ None
+ } else {
+ Some(recover_c_char(multisig_wallet_config))
+ };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let public_keys = recover_c_array(public_keys);
+ check_psbt(mfp, public_keys, psbt, verify_code, multisig_wallet_config)
}
#[no_mangle]
-pub extern "C" fn btc_parse_psbt_bytes(
+pub unsafe extern "C" fn btc_parse_psbt_bytes(
psbt_bytes: PtrBytes,
psbt_bytes_length: u32,
master_fingerprint: PtrBytes,
@@ -369,25 +361,23 @@ pub extern "C" fn btc_parse_psbt_bytes(
if length != 4 {
return TransactionParseResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- unsafe {
- let psbt = core::slice::from_raw_parts(psbt_bytes, psbt_bytes_length as usize);
- let psbt = match get_psbt_bytes(psbt) {
- Ok(psbt) => psbt,
- Err(e) => return TransactionParseResult::from(e).c_ptr(),
- };
- let multisig_wallet_config = if multisig_wallet_config.is_null() {
- None
- } else {
- Some(recover_c_char(multisig_wallet_config))
- };
- let mfp = core::slice::from_raw_parts(master_fingerprint, 4);
- let public_keys = recover_c_array(public_keys);
- parse_psbt(mfp, public_keys, psbt, multisig_wallet_config)
- }
+ let psbt = extract_array!(psbt_bytes, u8, psbt_bytes_length as usize);
+ let psbt = match get_psbt_bytes(psbt) {
+ Ok(psbt) => psbt,
+ Err(e) => return TransactionParseResult::from(e).c_ptr(),
+ };
+ let multisig_wallet_config = if multisig_wallet_config.is_null() {
+ None
+ } else {
+ Some(recover_c_char(multisig_wallet_config))
+ };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
+ let public_keys = recover_c_array(public_keys);
+ parse_psbt(mfp, public_keys, psbt, multisig_wallet_config)
}
#[no_mangle]
-pub extern "C" fn btc_sign_multisig_psbt_bytes(
+pub unsafe extern "C" fn btc_sign_multisig_psbt_bytes(
psbt_bytes: PtrBytes,
psbt_bytes_length: u32,
seed: PtrBytes,
@@ -405,7 +395,7 @@ pub extern "C" fn btc_sign_multisig_psbt_bytes(
}
.c_ptr();
}
- let master_fingerprint = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let master_fingerprint = extract_array!(master_fingerprint, u8, 4);
let master_fingerprint =
match bitcoin::bip32::Fingerprint::from_str(hex::encode(master_fingerprint).as_str())
.map_err(|_e| RustCError::InvalidMasterFingerprint)
@@ -423,8 +413,8 @@ pub extern "C" fn btc_sign_multisig_psbt_bytes(
}
};
- let psbt = unsafe {
- let psbt = core::slice::from_raw_parts(psbt_bytes, psbt_bytes_length as usize);
+ let psbt = {
+ let psbt = extract_array!(psbt_bytes, u8, psbt_bytes_length as usize);
match get_psbt_bytes(psbt) {
Ok(psbt) => psbt,
@@ -441,7 +431,7 @@ pub extern "C" fn btc_sign_multisig_psbt_bytes(
}
};
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let result = app_bitcoin::sign_psbt_no_serialize(psbt, seed, master_fingerprint);
match result.map(|v| {
@@ -488,7 +478,7 @@ pub extern "C" fn btc_sign_multisig_psbt_bytes(
}
}
-fn parse_psbt(
+unsafe fn parse_psbt(
mfp: &[u8],
public_keys: &[ExtendedPublicKey],
psbt: Vec<u8>,
@@ -536,7 +526,7 @@ fn parse_psbt(
}
}
-fn check_psbt(
+unsafe fn check_psbt(
mfp: &[u8],
public_keys: &[ExtendedPublicKey],
psbt: Vec<u8>,
diff --git a/rust/rust_c/src/bitcoin/structs.rs b/rust/rust_c/src/bitcoin/structs.rs
index c25dc3c..0029bba 100644
--- a/rust/rust_c/src/bitcoin/structs.rs
+++ b/rust/rust_c/src/bitcoin/structs.rs
@@ -9,7 +9,7 @@ use crate::common::structs::TransactionParseResult;
use crate::common::types::{PtrString, PtrT};
use crate::common::ur::UREncodeResult;
use crate::common::utils::convert_c_char;
-use crate::{check_and_free_ptr, free_str_ptr, impl_c_ptr, make_free_method};
+use crate::{free_str_ptr, impl_c_ptr, make_free_method};
use app_bitcoin;
use app_bitcoin::parsed_tx::{DetailTx, OverviewTx, ParsedInput, ParsedOutput, ParsedTx};
@@ -31,13 +31,11 @@ impl PsbtSignResult {
}
impl Free for PsbtSignResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.base_str);
free_str_ptr!(self.hex_str);
- unsafe {
- let x = Box::from_raw(self.ur_result);
- x.free();
- }
+ let x = Box::from_raw(self.ur_result);
+ x.free();
}
}
@@ -223,99 +221,85 @@ impl From<ParsedOutput> for DisplayTxDetailOutput {
}
impl Free for DisplayTx {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(self.overview);
- let y = Box::from_raw(self.detail);
- x.free();
- y.free();
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(self.overview);
+ let y = Box::from_raw(self.detail);
+ x.free();
+ y.free();
}
}
make_free_method!(TransactionParseResult<DisplayTx>);
impl Free for DisplayTxOverview {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(self.from);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
- let x = Box::from_raw(self.to);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
-
- let _ = Box::from_raw(self.total_output_amount);
- let _ = Box::from_raw(self.fee_amount);
- let _ = Box::from_raw(self.total_output_sat);
- let _ = Box::from_raw(self.fee_sat);
- let _ = Box::from_raw(self.network);
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(self.from);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+ let x = Box::from_raw(self.to);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+
+ let _ = Box::from_raw(self.total_output_amount);
+ let _ = Box::from_raw(self.fee_amount);
+ let _ = Box::from_raw(self.total_output_sat);
+ let _ = Box::from_raw(self.fee_sat);
+ let _ = Box::from_raw(self.network);
}
}
impl Free for DisplayTxDetail {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(self.from);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
- let x = Box::from_raw(self.to);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
-
- let _ = Box::from_raw(self.total_input_amount);
- let _ = Box::from_raw(self.total_output_amount);
- let _ = Box::from_raw(self.fee_amount);
- let _ = Box::from_raw(self.network);
- let _ = Box::from_raw(self.total_input_sat);
- let _ = Box::from_raw(self.total_output_sat);
- let _ = Box::from_raw(self.fee_sat);
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(self.from);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+ let x = Box::from_raw(self.to);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+
+ let _ = Box::from_raw(self.total_input_amount);
+ let _ = Box::from_raw(self.total_output_amount);
+ let _ = Box::from_raw(self.fee_amount);
+ let _ = Box::from_raw(self.network);
+ let _ = Box::from_raw(self.total_input_sat);
+ let _ = Box::from_raw(self.total_output_sat);
+ let _ = Box::from_raw(self.fee_sat);
}
}
impl Free for DisplayTxOverviewInput {
- fn free(&self) {
- unsafe {
- let _ = Box::from_raw(self.address);
- }
+ unsafe fn free(&self) {
+ let _ = Box::from_raw(self.address);
}
}
impl Free for DisplayTxDetailInput {
- fn free(&self) {
- unsafe {
- let _ = Box::from_raw(self.address);
- let _ = Box::from_raw(self.amount);
- let _ = Box::from_raw(self.path);
- }
+ unsafe fn free(&self) {
+ let _ = Box::from_raw(self.address);
+ let _ = Box::from_raw(self.amount);
+ let _ = Box::from_raw(self.path);
}
}
impl Free for DisplayTxOverviewOutput {
- fn free(&self) {
- unsafe {
- let _ = Box::from_raw(self.address);
- }
+ unsafe fn free(&self) {
+ let _ = Box::from_raw(self.address);
}
}
impl Free for DisplayTxDetailOutput {
- fn free(&self) {
- unsafe {
- let _ = Box::from_raw(self.address);
- let _ = Box::from_raw(self.amount);
- let _ = Box::from_raw(self.path);
- }
+ unsafe fn free(&self) {
+ let _ = Box::from_raw(self.address);
+ let _ = Box::from_raw(self.amount);
+ let _ = Box::from_raw(self.path);
}
}
@@ -328,7 +312,7 @@ pub struct DisplayBtcMsg {
impl_c_ptr!(DisplayBtcMsg);
impl Free for DisplayBtcMsg {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.detail);
free_str_ptr!(self.address);
}
diff --git a/rust/rust_c/src/cardano/address.rs b/rust/rust_c/src/cardano/address.rs
index 0b5bc35..36d8e40 100644
--- a/rust/rust_c/src/cardano/address.rs
+++ b/rust/rust_c/src/cardano/address.rs
@@ -6,7 +6,7 @@ use app_cardano::address::AddressType;
use cty::c_char;
#[no_mangle]
-pub extern "C" fn cardano_get_base_address(
+pub unsafe extern "C" fn cardano_get_base_address(
xpub: PtrString,
index: u32,
network_id: u8,
@@ -19,7 +19,7 @@ pub extern "C" fn cardano_get_base_address(
}
#[no_mangle]
-pub extern "C" fn cardano_get_enterprise_address(
+pub unsafe extern "C" fn cardano_get_enterprise_address(
xpub: PtrString,
index: u32,
network_id: u8,
@@ -39,7 +39,7 @@ pub extern "C" fn cardano_get_enterprise_address(
}
#[no_mangle]
-pub extern "C" fn cardano_get_stake_address(
+pub unsafe extern "C" fn cardano_get_stake_address(
xpub: PtrString,
index: u32,
network_id: u8,
diff --git a/rust/rust_c/src/cardano/mod.rs b/rust/rust_c/src/cardano/mod.rs
index 3fbf582..6776c7a 100644
--- a/rust/rust_c/src/cardano/mod.rs
+++ b/rust/rust_c/src/cardano/mod.rs
@@ -26,7 +26,7 @@ use crate::common::{
errors::{RustCError, R},
ur::FRAGMENT_UNLIMITED_LENGTH,
};
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use structs::{DisplayCardanoCatalyst, DisplayCardanoSignData, DisplayCardanoTx};
use ur_registry::cardano::cardano_sign_data_signature::CardanoSignDataSignature;
use ur_registry::cardano::cardano_sign_request::CardanoSignRequest;
@@ -54,7 +54,7 @@ pub mod address;
pub mod structs;
use cip8_cbor_data_ledger::CardanoCip8SigStructureLedgerType;
#[no_mangle]
-pub extern "C" fn cardano_catalyst_xpub(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
+pub unsafe extern "C" fn cardano_catalyst_xpub(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
let cardano_catalyst_request =
extract_ptr_with_type!(ptr, CardanoCatalystVotingRegistrationRequest);
let xpub = cardano_catalyst_request.get_stake_pub();
@@ -62,13 +62,13 @@ pub extern "C" fn cardano_catalyst_xpub(ptr: PtrUR) -> Ptr<SimpleResponse<c_char
}
#[no_mangle]
-pub extern "C" fn cardano_check_catalyst(
+pub unsafe extern "C" fn cardano_check_catalyst(
ptr: PtrUR,
master_fingerprint: PtrBytes,
) -> PtrT<TransactionCheckResult> {
let cardano_catalyst_request =
extract_ptr_with_type!(ptr, CardanoCatalystVotingRegistrationRequest);
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let ur_mfp = cardano_catalyst_request
.get_derivation_path()
.get_source_fingerprint()
@@ -84,7 +84,7 @@ pub extern "C" fn cardano_check_catalyst(
}
#[no_mangle]
-pub extern "C" fn cardano_check_catalyst_path_type(
+pub unsafe extern "C" fn cardano_check_catalyst_path_type(
ptr: PtrUR,
cardano_xpub: PtrString,
) -> PtrT<TransactionCheckResult> {
@@ -113,7 +113,9 @@ pub extern "C" fn cardano_check_catalyst_path_type(
}
#[no_mangle]
-pub extern "C" fn cardano_get_catalyst_root_index(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
+pub unsafe extern "C" fn cardano_get_catalyst_root_index(
+ ptr: PtrUR,
+) -> Ptr<SimpleResponse<c_char>> {
let cardano_catalyst_request =
extract_ptr_with_type!(ptr, CardanoCatalystVotingRegistrationRequest);
let derviation_path: CryptoKeyPath = cardano_catalyst_request.get_derivation_path();
@@ -128,7 +130,9 @@ pub extern "C" fn cardano_get_catalyst_root_index(ptr: PtrUR) -> Ptr<SimpleRespo
}
#[no_mangle]
-pub extern "C" fn cardano_get_sign_data_root_index(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
+pub unsafe extern "C" fn cardano_get_sign_data_root_index(
+ ptr: PtrUR,
+) -> Ptr<SimpleResponse<c_char>> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignDataRequest);
let derviation_path: CryptoKeyPath = cardano_sign_data_reqeust.get_derivation_path();
match derviation_path.get_components().get(2) {
@@ -136,13 +140,15 @@ pub extern "C" fn cardano_get_sign_data_root_index(ptr: PtrUR) -> Ptr<SimpleResp
let index = _data.get_index().unwrap();
SimpleResponse::success(convert_c_char(index.to_string())).simple_c_ptr()
}
- None => SimpleResponse::from(CardanoError::InvalidTransaction(format!("invalid path")))
+ None => SimpleResponse::from(CardanoError::InvalidTransaction("invalid path".to_string()))
.simple_c_ptr(),
}
}
#[no_mangle]
-pub extern "C" fn cardano_get_sign_cip8_data_root_index(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
+pub unsafe extern "C" fn cardano_get_sign_cip8_data_root_index(
+ ptr: PtrUR,
+) -> Ptr<SimpleResponse<c_char>> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignCip8DataRequest);
let derviation_path: CryptoKeyPath = cardano_sign_data_reqeust.get_derivation_path();
match derviation_path.get_components().get(2) {
@@ -150,13 +156,13 @@ pub extern "C" fn cardano_get_sign_cip8_data_root_index(ptr: PtrUR) -> Ptr<Simpl
let index = _data.get_index().unwrap();
SimpleResponse::success(convert_c_char(index.to_string())).simple_c_ptr()
}
- None => SimpleResponse::from(CardanoError::InvalidTransaction(format!("invalid path")))
+ None => SimpleResponse::from(CardanoError::InvalidTransaction("invalid path".to_string()))
.simple_c_ptr(),
}
}
#[no_mangle]
-pub extern "C" fn cardano_check_sign_data_path_type(
+pub unsafe extern "C" fn cardano_check_sign_data_path_type(
ptr: PtrUR,
cardano_xpub: PtrString,
) -> PtrT<TransactionCheckResult> {
@@ -185,7 +191,7 @@ pub extern "C" fn cardano_check_sign_data_path_type(
}
#[no_mangle]
-pub extern "C" fn cardano_check_sign_data_is_sign_opcert(
+pub unsafe extern "C" fn cardano_check_sign_data_is_sign_opcert(
ptr: PtrUR,
) -> PtrT<TransactionCheckResult> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignDataRequest);
@@ -201,12 +207,12 @@ pub extern "C" fn cardano_check_sign_data_is_sign_opcert(
}
#[no_mangle]
-pub extern "C" fn cardano_check_sign_data(
+pub unsafe extern "C" fn cardano_check_sign_data(
ptr: PtrUR,
master_fingerprint: PtrBytes,
) -> PtrT<TransactionCheckResult> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignDataRequest);
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let ur_mfp = cardano_sign_data_reqeust
.get_derivation_path()
.get_source_fingerprint()
@@ -222,12 +228,12 @@ pub extern "C" fn cardano_check_sign_data(
}
#[no_mangle]
-pub extern "C" fn cardano_check_sign_cip8_data(
+pub unsafe extern "C" fn cardano_check_sign_cip8_data(
ptr: PtrUR,
master_fingerprint: PtrBytes,
) -> PtrT<TransactionCheckResult> {
let cardano_sign_cip8_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignCip8DataRequest);
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let ur_mfp = cardano_sign_cip8_data_reqeust
.get_derivation_path()
.get_source_fingerprint()
@@ -243,7 +249,7 @@ pub extern "C" fn cardano_check_sign_cip8_data(
}
#[no_mangle]
-pub extern "C" fn cardano_check_sign_cip8_data_path_type(
+pub unsafe extern "C" fn cardano_check_sign_cip8_data_path_type(
ptr: PtrUR,
cardano_xpub: PtrString,
) -> PtrT<TransactionCheckResult> {
@@ -272,7 +278,7 @@ pub extern "C" fn cardano_check_sign_cip8_data_path_type(
}
#[no_mangle]
-pub extern "C" fn cardano_check_tx(
+pub unsafe extern "C" fn cardano_check_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -290,12 +296,12 @@ pub extern "C" fn cardano_check_tx(
}
}
#[no_mangle]
-pub extern "C" fn cardano_check_tx_hash(
+pub unsafe extern "C" fn cardano_check_tx_hash(
ptr: PtrUR,
master_fingerprint: PtrBytes,
) -> PtrT<TransactionCheckResult> {
let cardano_sign_tx_hash_reqeust = extract_ptr_with_type!(ptr, CardanoSignTxHashRequest);
- let expected_mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let expected_mfp = extract_array!(master_fingerprint, u8, 4);
// check mfp
let paths = cardano_sign_tx_hash_reqeust.get_paths();
for path in paths {
@@ -310,7 +316,7 @@ pub extern "C" fn cardano_check_tx_hash(
}
#[no_mangle]
-pub extern "C" fn cardano_parse_sign_tx_hash(
+pub unsafe extern "C" fn cardano_parse_sign_tx_hash(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayCardanoSignTxHash>> {
let sign_hash_request = extract_ptr_with_type!(ptr, CardanoSignTxHashRequest);
@@ -328,18 +334,14 @@ pub extern "C" fn cardano_parse_sign_tx_hash(
}
#[no_mangle]
-pub extern "C" fn cardano_get_path(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
+pub unsafe extern "C" fn cardano_get_path(ptr: PtrUR) -> Ptr<SimpleResponse<c_char>> {
let cardano_sign_reqeust = extract_ptr_with_type!(ptr, CardanoSignRequest);
- match cardano_sign_reqeust.get_cert_keys().first() {
- Some(_data) => match _data.get_key_path().get_path() {
- Some(_path) => {
- if let Some(path) = parse_cardano_root_path(_path) {
- return SimpleResponse::success(convert_c_char(path)).simple_c_ptr();
- }
+ if let Some(_data) = cardano_sign_reqeust.get_cert_keys().first() {
+ if let Some(_path) = _data.get_key_path().get_path() {
+ if let Some(path) = parse_cardano_root_path(_path) {
+ return SimpleResponse::success(convert_c_char(path)).simple_c_ptr();
}
- None => {}
- },
- None => {}
+ }
};
match cardano_sign_reqeust.get_utxos().first() {
Some(_data) => match _data.get_key_path().get_path() {
@@ -378,7 +380,7 @@ fn parse_cardano_root_path(path: String) -> Option<String> {
Some(path) => {
if let Some(index) = path.find('/') {
let sub_path = &path[..index];
- Some(format!("{}{}", root_path, sub_path))
+ Some(format!("{root_path}{sub_path}"))
} else {
None
}
@@ -388,7 +390,7 @@ fn parse_cardano_root_path(path: String) -> Option<String> {
}
#[no_mangle]
-pub extern "C" fn cardano_parse_sign_data(
+pub unsafe extern "C" fn cardano_parse_sign_data(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayCardanoSignData>> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignDataRequest);
@@ -407,7 +409,7 @@ pub extern "C" fn cardano_parse_sign_data(
}
#[no_mangle]
-pub extern "C" fn cardano_parse_sign_cip8_data(
+pub unsafe extern "C" fn cardano_parse_sign_cip8_data(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayCardanoSignData>> {
let cardano_sign_cip8_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignCip8DataRequest);
@@ -430,7 +432,7 @@ pub extern "C" fn cardano_parse_sign_cip8_data(
}
#[no_mangle]
-pub extern "C" fn cardano_parse_catalyst(
+pub unsafe extern "C" fn cardano_parse_catalyst(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayCardanoCatalyst>> {
let cardano_catalyst_request =
@@ -441,7 +443,7 @@ pub extern "C" fn cardano_parse_catalyst(
}
#[no_mangle]
-pub extern "C" fn cardano_parse_tx(
+pub unsafe extern "C" fn cardano_parse_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -460,7 +462,7 @@ pub extern "C" fn cardano_parse_tx(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_catalyst_with_ledger_bitbox02(
+pub unsafe extern "C" fn cardano_sign_catalyst_with_ledger_bitbox02(
ptr: PtrUR,
mnemonic: PtrString,
passphrase: PtrString,
@@ -480,14 +482,14 @@ pub extern "C" fn cardano_sign_catalyst_with_ledger_bitbox02(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_catalyst(
+pub unsafe extern "C" fn cardano_sign_catalyst(
ptr: PtrUR,
entropy: PtrBytes,
entropy_len: u32,
passphrase: PtrString,
is_slip39: bool,
) -> PtrT<UREncodeResult> {
- let entropy = unsafe { alloc::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = match generate_master_key(entropy, &passphrase, is_slip39) {
Ok(v) => v,
@@ -496,7 +498,10 @@ pub extern "C" fn cardano_sign_catalyst(
cardano_sign_catalyst_by_icarus(ptr, master_key)
}
-fn cardano_sign_catalyst_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT<UREncodeResult> {
+unsafe fn cardano_sign_catalyst_by_icarus(
+ ptr: PtrUR,
+ icarus_master_key: XPrv,
+) -> PtrT<UREncodeResult> {
let cardano_catalyst_request =
extract_ptr_with_type!(ptr, CardanoCatalystVotingRegistrationRequest);
@@ -535,7 +540,7 @@ fn cardano_sign_catalyst_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT<
}
#[no_mangle]
-pub extern "C" fn cardano_sign_sign_data_with_ledger_bitbox02(
+pub unsafe extern "C" fn cardano_sign_sign_data_with_ledger_bitbox02(
ptr: PtrUR,
mnemonic: PtrString,
passphrase: PtrString,
@@ -555,7 +560,7 @@ pub extern "C" fn cardano_sign_sign_data_with_ledger_bitbox02(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_sign_cip8_data_with_ledger_bitbox02(
+pub unsafe extern "C" fn cardano_sign_sign_cip8_data_with_ledger_bitbox02(
ptr: PtrUR,
mnemonic: PtrString,
passphrase: PtrString,
@@ -575,14 +580,14 @@ pub extern "C" fn cardano_sign_sign_cip8_data_with_ledger_bitbox02(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_sign_data(
+pub unsafe extern "C" fn cardano_sign_sign_data(
ptr: PtrUR,
entropy: PtrBytes,
entropy_len: u32,
passphrase: PtrString,
is_slip39: bool,
) -> PtrT<UREncodeResult> {
- let entropy = unsafe { alloc::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = match generate_master_key(entropy, &passphrase, is_slip39) {
Ok(v) => v,
@@ -592,7 +597,10 @@ pub extern "C" fn cardano_sign_sign_data(
cardano_sign_sign_data_by_icarus(ptr, master_key)
}
-fn cardano_sign_sign_data_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT<UREncodeResult> {
+unsafe fn cardano_sign_sign_data_by_icarus(
+ ptr: PtrUR,
+ icarus_master_key: XPrv,
+) -> PtrT<UREncodeResult> {
let cardano_sign_data_reqeust = extract_ptr_with_type!(ptr, CardanoSignDataRequest);
let sign_data = cardano_sign_data_reqeust.get_sign_data();
@@ -633,14 +641,14 @@ fn cardano_sign_sign_data_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT
}
#[no_mangle]
-pub extern "C" fn cardano_sign_sign_cip8_data(
+pub unsafe extern "C" fn cardano_sign_sign_cip8_data(
ptr: PtrUR,
entropy: PtrBytes,
entropy_len: u32,
passphrase: PtrString,
is_slip39: bool,
) -> PtrT<UREncodeResult> {
- let entropy = unsafe { alloc::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = match generate_master_key(entropy, &passphrase, is_slip39) {
Ok(v) => v,
@@ -651,7 +659,7 @@ pub extern "C" fn cardano_sign_sign_cip8_data(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_tx_with_ledger_bitbox02(
+pub unsafe extern "C" fn cardano_sign_tx_with_ledger_bitbox02(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -679,7 +687,7 @@ pub extern "C" fn cardano_sign_tx_with_ledger_bitbox02(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_tx_with_ledger_bitbox02_unlimited(
+pub unsafe extern "C" fn cardano_sign_tx_with_ledger_bitbox02_unlimited(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -703,7 +711,7 @@ pub extern "C" fn cardano_sign_tx_with_ledger_bitbox02_unlimited(
}
#[no_mangle]
-pub extern "C" fn cardano_sign_tx(
+pub unsafe extern "C" fn cardano_sign_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -713,7 +721,7 @@ pub extern "C" fn cardano_sign_tx(
enable_blind_sign: bool,
is_slip39: bool,
) -> PtrT<UREncodeResult> {
- let entropy = unsafe { alloc::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = match generate_master_key(entropy, &passphrase, is_slip39) {
Ok(v) => v,
@@ -727,7 +735,10 @@ pub extern "C" fn cardano_sign_tx(
}
}
-fn cardano_sign_tx_hash_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT<UREncodeResult> {
+unsafe fn cardano_sign_tx_hash_by_icarus(
+ ptr: PtrUR,
+ icarus_master_key: XPrv,
+) -> PtrT<UREncodeResult> {
let cardano_sign_tx_hash_request = extract_ptr_with_type!(ptr, CardanoSignTxHashRequest);
let tx_hash = cardano_sign_tx_hash_request.get_tx_hash();
let paths = cardano_sign_tx_hash_request.get_paths();
@@ -742,7 +753,7 @@ fn cardano_sign_tx_hash_by_icarus(ptr: PtrUR, icarus_master_key: XPrv) -> PtrT<U
}
#[no_mangle]
-pub extern "C" fn cardano_sign_tx_unlimited(
+pub unsafe extern "C" fn cardano_sign_tx_unlimited(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -751,7 +762,7 @@ pub extern "C" fn cardano_sign_tx_unlimited(
passphrase: PtrString,
is_slip39: bool,
) -> PtrT<UREncodeResult> {
- let entropy = unsafe { alloc::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = match generate_master_key(entropy, &passphrase, is_slip39) {
Ok(v) => v,
@@ -761,7 +772,7 @@ pub extern "C" fn cardano_sign_tx_unlimited(
}
#[no_mangle]
-pub extern "C" fn cardano_get_pubkey_by_slip23(
+pub unsafe extern "C" fn cardano_get_pubkey_by_slip23(
entropy: PtrBytes,
entropy_len: u32,
path: PtrString,
@@ -772,7 +783,7 @@ pub extern "C" fn cardano_get_pubkey_by_slip23(
))
.simple_c_ptr();
}
- let entropy = unsafe { core::slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let path = recover_c_char(path).to_lowercase();
let xpub = app_cardano::slip23::from_seed_slip23_path(entropy, path.as_str());
match xpub {
@@ -783,7 +794,7 @@ pub extern "C" fn cardano_get_pubkey_by_slip23(
}
}
-fn cardano_sign_tx_by_icarus(
+unsafe fn cardano_sign_tx_by_icarus(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -794,11 +805,11 @@ fn cardano_sign_tx_by_icarus(
master_fingerprint,
cardano_xpub,
icarus_master_key,
- FRAGMENT_MAX_LENGTH_DEFAULT.clone(),
+ FRAGMENT_MAX_LENGTH_DEFAULT,
)
}
-fn cardano_sign_tx_by_icarus_unlimited(
+unsafe fn cardano_sign_tx_by_icarus_unlimited(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -809,11 +820,11 @@ fn cardano_sign_tx_by_icarus_unlimited(
master_fingerprint,
cardano_xpub,
icarus_master_key,
- FRAGMENT_UNLIMITED_LENGTH.clone(),
+ FRAGMENT_UNLIMITED_LENGTH,
)
}
-fn cardano_sign_tx_by_icarus_dynamic(
+unsafe fn cardano_sign_tx_by_icarus_dynamic(
ptr: PtrUR,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -823,7 +834,7 @@ fn cardano_sign_tx_by_icarus_dynamic(
let cardano_sign_reqeust = extract_ptr_with_type!(ptr, CardanoSignRequest);
let tx_hex = cardano_sign_reqeust.get_sign_data();
let parse_context =
- prepare_parse_context(&cardano_sign_reqeust, master_fingerprint, cardano_xpub);
+ prepare_parse_context(cardano_sign_reqeust, master_fingerprint, cardano_xpub);
match parse_context {
Ok(parse_context) => {
let sign_result =
@@ -845,7 +856,7 @@ fn cardano_sign_tx_by_icarus_dynamic(
}
}
-fn cardano_sign_sign_cip8_data_by_icarus(
+unsafe fn cardano_sign_sign_cip8_data_by_icarus(
ptr: PtrUR,
icarus_master_key: XPrv,
) -> PtrT<UREncodeResult> {
@@ -863,7 +874,7 @@ fn cardano_sign_sign_cip8_data_by_icarus(
let address_type = cardano_sign_data_reqeust.get_address_type();
if address_type.as_str() == "ADDRESS" {
address_field = bitcoin::bech32::decode(
- &cardano_sign_data_reqeust
+ cardano_sign_data_reqeust
.get_address_bench32()
.unwrap()
.as_str(),
@@ -907,7 +918,7 @@ fn cardano_sign_sign_cip8_data_by_icarus(
UREncodeResult::encode(
data,
CARDANO_SIGN_CIP8_DATA_SIGNATURE.get_type(),
- FRAGMENT_MAX_LENGTH_DEFAULT.clone(),
+ FRAGMENT_MAX_LENGTH_DEFAULT,
)
.c_ptr()
},
@@ -915,10 +926,10 @@ fn cardano_sign_sign_cip8_data_by_icarus(
},
);
- return result;
+ result
}
-fn prepare_parse_context(
+unsafe fn prepare_parse_context(
cardano_sign_request: &CardanoSignRequest,
master_fingerprint: PtrBytes,
cardano_xpub: PtrString,
@@ -928,7 +939,7 @@ fn prepare_parse_context(
} else {
Some(recover_c_char(cardano_xpub))
};
- let mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
Ok(ParseContext::new(
cardano_sign_request
.get_utxos()
@@ -971,7 +982,7 @@ fn prepare_parse_context(
fn convert_key_path(key_path: CryptoKeyPath) -> R<DerivationPath> {
match key_path.get_path() {
Some(string) => {
- let path = format!("m/{}", string);
+ let path = format!("m/{string}");
DerivationPath::from_str(path.as_str()).map_err(|_e| RustCError::InvalidHDPath)
}
None => Err(RustCError::InvalidHDPath),
@@ -981,8 +992,8 @@ fn convert_key_path(key_path: CryptoKeyPath) -> R<DerivationPath> {
fn get_cardano_derivation_path(path: CryptoKeyPath) -> R<CryptoKeyPath> {
let components = path.get_components();
let mut new_components = Vec::new();
- for i in 3..components.len() {
- new_components.push(components[i]);
+ for item in components.iter().skip(3) {
+ new_components.push(*item);
}
Ok(CryptoKeyPath::new(
new_components,
diff --git a/rust/rust_c/src/cardano/structs.rs b/rust/rust_c/src/cardano/structs.rs
index d1fbc3f..3baa211 100644
--- a/rust/rust_c/src/cardano/structs.rs
+++ b/rust/rust_c/src/cardano/structs.rs
@@ -15,9 +15,7 @@ use crate::common::free::{free_ptr_string, Free};
use crate::common::structs::TransactionParseResult;
use crate::common::types::{Ptr, PtrString, PtrT};
use crate::common::utils::convert_c_char;
-use crate::{
- check_and_free_ptr, free_str_ptr, free_vec, impl_c_ptr, impl_c_ptrs, make_free_method,
-};
+use crate::{free_str_ptr, free_vec, impl_c_ptr, impl_c_ptrs, make_free_method};
#[repr(C)]
pub struct DisplayCardanoSignData {
@@ -159,7 +157,7 @@ impl_c_ptrs!(DisplayCardanoSignData);
impl_c_ptrs!(DisplayCardanoSignTxHash);
impl Free for DisplayCardanoSignData {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.payload);
free_str_ptr!(self.derivation_path);
free_str_ptr!(self.message_hash);
@@ -168,7 +166,7 @@ impl Free for DisplayCardanoSignData {
}
impl Free for DisplayCardanoCatalyst {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.nonce);
free_str_ptr!(self.stake_key);
free_str_ptr!(self.rewards);
@@ -177,7 +175,7 @@ impl Free for DisplayCardanoCatalyst {
}
impl Free for DisplayCardanoSignTxHash {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.network);
free_vec!(self.path);
free_str_ptr!(self.tx_hash);
@@ -186,28 +184,26 @@ impl Free for DisplayCardanoSignTxHash {
}
impl Free for DisplayCardanoTx {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(self.from);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
- let x = Box::from_raw(self.to);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| {
- v.free();
- });
- free_vec!(self.withdrawals);
- free_vec!(self.certificates);
- free_vec!(self.voting_procedures);
- free_vec!(self.voting_proposals);
-
- free_ptr_string(self.total_input);
- free_ptr_string(self.total_output);
- free_ptr_string(self.fee);
- free_ptr_string(self.network);
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(self.from);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+ let x = Box::from_raw(self.to);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| {
+ v.free();
+ });
+ free_vec!(self.withdrawals);
+ free_vec!(self.certificates);
+ free_vec!(self.voting_procedures);
+ free_vec!(self.voting_proposals);
+
+ free_str_ptr!(self.total_input);
+ free_str_ptr!(self.total_output);
+ free_str_ptr!(self.fee);
+ free_str_ptr!(self.network);
}
}
@@ -308,7 +304,7 @@ impl From<&CardanoFrom> for DisplayCardanoFrom {
}
impl Free for DisplayCardanoTo {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.assets_text);
free_str_ptr!(self.address);
free_str_ptr!(self.amount);
@@ -316,7 +312,7 @@ impl Free for DisplayCardanoTo {
}
impl Free for DisplayCardanoFrom {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.path);
free_str_ptr!(self.amount);
free_str_ptr!(self.address);
@@ -376,14 +372,14 @@ impl From<&CardanoCertificate> for DisplayCardanoCertificate {
}
impl Free for DisplayCardanoCertificate {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.cert_type);
free_vec!(self.fields);
}
}
impl Free for DisplayVotingProcedure {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.voter);
free_str_ptr!(self.transaction_id);
free_str_ptr!(self.index);
@@ -392,7 +388,7 @@ impl Free for DisplayVotingProcedure {
}
impl Free for DisplayVotingProposal {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.anchor);
}
}
@@ -407,14 +403,14 @@ impl From<&CardanoWithdrawal> for DisplayCardanoWithdrawal {
}
impl Free for DisplayCardanoWithdrawal {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.address);
free_str_ptr!(self.amount);
}
}
impl Free for DisplayCertField {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.label);
free_str_ptr!(self.value);
}
diff --git a/rust/rust_c/src/common/errors.rs b/rust/rust_c/src/common/errors.rs
index 0c1699a..89a131e 100644
--- a/rust/rust_c/src/common/errors.rs
+++ b/rust/rust_c/src/common/errors.rs
@@ -588,9 +588,7 @@ impl From<&ZcashError> for ErrorCodes {
#[cfg(feature = "monero")]
impl From<&MoneroError> for ErrorCodes {
fn from(value: &MoneroError) -> Self {
- match value {
- _ => Self::MoneroUnknownError,
- }
+ Self::MoneroUnknownError
}
}
diff --git a/rust/rust_c/src/common/ffi.rs b/rust/rust_c/src/common/ffi.rs
index cc992dc..b620304 100644
--- a/rust/rust_c/src/common/ffi.rs
+++ b/rust/rust_c/src/common/ffi.rs
@@ -28,27 +28,23 @@ impl<T> From<Vec<T>> for VecFFI<T> {
impl_simple_free!(u8);
impl<T: SimpleFree> SimpleFree for VecFFI<T> {
- fn free(&self) {
+ unsafe fn free(&self) {
if self.data.is_null() {
return;
}
- unsafe {
- let _x = Vec::from_raw_parts(self.data, self.size, self.cap);
- }
+ let _x = Vec::from_raw_parts(self.data, self.size, self.cap);
}
}
impl<T: Free> Free for VecFFI<T> {
- fn free(&self) {
+ unsafe fn free(&self) {
if self.data.is_null() {
return;
}
- unsafe {
- let x = Vec::from_raw_parts(self.data, self.size, self.cap);
- x.iter().for_each(|v| {
- v.free();
- });
- }
+ let x = Vec::from_raw_parts(self.data, self.size, self.cap);
+ x.iter().for_each(|v| {
+ v.free();
+ });
}
}
diff --git a/rust/rust_c/src/common/free.rs b/rust/rust_c/src/common/free.rs
index b9bd388..816f7f3 100644
--- a/rust/rust_c/src/common/free.rs
+++ b/rust/rust_c/src/common/free.rs
@@ -7,11 +7,11 @@ use alloc::boxed::Box;
use cty::{c_char, c_void};
pub trait Free {
- fn free(&self);
+ unsafe fn free(&self);
}
pub trait SimpleFree {
- fn free(&self);
+ unsafe fn free(&self);
}
#[macro_export]
@@ -20,10 +20,8 @@ macro_rules! check_and_free_ptr {
if $p.is_null() {
return;
} else {
- unsafe {
- let x = alloc::boxed::Box::from_raw($p);
- x.free()
- }
+ let x = alloc::boxed::Box::from_raw($p);
+ x.free()
}
};
}
@@ -32,9 +30,7 @@ macro_rules! check_and_free_ptr {
macro_rules! free_str_ptr {
($p: expr) => {
if !$p.is_null() {
- unsafe {
- cstr_core::CString::from_raw($p);
- }
+ cstr_core::CString::from_raw($p);
}
};
}
@@ -43,11 +39,9 @@ macro_rules! free_str_ptr {
macro_rules! free_vec {
($p: expr) => {
if !$p.is_null() {
- unsafe {
- let x = alloc::boxed::Box::from_raw($p);
- let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
- ve.iter().for_each(|v| v.free())
- }
+ let x = alloc::boxed::Box::from_raw($p);
+ let ve = Vec::from_raw_parts(x.data, x.size, x.cap);
+ ve.iter().for_each(|v| v.free())
}
};
}
@@ -56,11 +50,9 @@ macro_rules! free_vec {
macro_rules! free_ptr_with_type {
($x: expr, $name: ident) => {
if (!$x.is_null()) {
- unsafe {
- let x = $crate::extract_ptr_with_type!($x, $name);
- let _b = alloc::boxed::Box::from_raw(x);
- // drop(b);
- }
+ let x = $crate::extract_ptr_with_type!($x, $name);
+ let _b = alloc::boxed::Box::from_raw(x);
+ // drop(b);
}
};
}
@@ -94,48 +86,46 @@ macro_rules! free_ptr_with_type {
// }
#[no_mangle]
-pub extern "C" fn free_ur_parse_result(ur_parse_result: PtrT<URParseResult>) {
+pub unsafe extern "C" fn free_ur_parse_result(ur_parse_result: PtrT<URParseResult>) {
check_and_free_ptr!(ur_parse_result);
}
#[no_mangle]
-pub extern "C" fn free_ur_parse_multi_result(ptr: PtrT<URParseMultiResult>) {
+pub unsafe extern "C" fn free_ur_parse_multi_result(ptr: PtrT<URParseMultiResult>) {
check_and_free_ptr!(ptr)
}
#[no_mangle]
-pub extern "C" fn free_ur_encode_result(ptr: PtrT<UREncodeResult>) {
+pub unsafe extern "C" fn free_ur_encode_result(ptr: PtrT<UREncodeResult>) {
check_and_free_ptr!(ptr);
}
#[no_mangle]
-pub extern "C" fn free_ur_encode_muilt_result(ptr: PtrT<UREncodeMultiResult>) {
+pub unsafe extern "C" fn free_ur_encode_muilt_result(ptr: PtrT<UREncodeMultiResult>) {
check_and_free_ptr!(ptr);
}
#[no_mangle]
-pub extern "C" fn free_simple_response_u8(ptr: PtrT<SimpleResponse<u8>>) {
+pub unsafe extern "C" fn free_simple_response_u8(ptr: PtrT<SimpleResponse<u8>>) {
check_and_free_ptr!(ptr);
}
#[no_mangle]
-pub extern "C" fn free_simple_response_c_char(ptr: PtrT<SimpleResponse<c_char>>) {
+pub unsafe extern "C" fn free_simple_response_c_char(ptr: PtrT<SimpleResponse<c_char>>) {
check_and_free_ptr!(ptr);
}
#[no_mangle]
-pub extern "C" fn free_ptr_string(ptr: PtrString) {
+pub unsafe extern "C" fn free_ptr_string(ptr: PtrString) {
free_str_ptr!(ptr);
}
#[no_mangle]
-pub extern "C" fn free_rust_value(any_ptr: *mut c_void) {
+pub unsafe extern "C" fn free_rust_value(any_ptr: *mut c_void) {
if any_ptr.is_null() {
return;
}
- unsafe {
- drop(Box::from_raw(any_ptr));
- }
+ drop(Box::from_raw(any_ptr));
}
// make_free_method!(Response<DisplayContractData>);
diff --git a/rust/rust_c/src/common/keystone.rs b/rust/rust_c/src/common/keystone.rs
index 9d38f75..646af70 100644
--- a/rust/rust_c/src/common/keystone.rs
+++ b/rust/rust_c/src/common/keystone.rs
@@ -3,7 +3,7 @@ use super::structs::TransactionCheckResult;
use super::types::{PtrBytes, PtrString, PtrT, PtrUR};
use super::ur::{QRCodeType, UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use super::utils::recover_c_char;
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::{String, ToString};
@@ -24,7 +24,7 @@ use ur_registry::pb::protoc::payload::Type as PbType;
use ur_registry::pb::protoc::{payload, Base, Payload, SignTransactionResult};
use ur_registry::traits::RegistryItem;
-pub fn build_payload(ptr: PtrUR, ur_type: QRCodeType) -> Result<Payload, KeystoneError> {
+pub unsafe fn build_payload(ptr: PtrUR, ur_type: QRCodeType) -> Result<Payload, KeystoneError> {
let bytes = match ur_type {
#[cfg(feature = "multi-coins")]
QRCodeType::KeystoneSignRequest => {
@@ -44,18 +44,18 @@ pub fn build_payload(ptr: PtrUR, ur_type: QRCodeType) -> Result<Payload, Keyston
.ok_or(KeystoneError::ProtobufError("empty payload".to_string()))
}
-pub fn build_parse_context(
+pub unsafe fn build_parse_context(
master_fingerprint: PtrBytes,
x_pub: PtrString,
) -> Result<app_utils::keystone::ParseContext, KeystoneError> {
- let mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let x_pub = recover_c_char(x_pub);
let xpub_str = convert_version(x_pub.as_str(), &Version::Xpub)
.map_err(|e| KeystoneError::InvalidParseContext(e.to_string()))?;
let master_fingerprint = bitcoin::bip32::Fingerprint::from_str(hex::encode(mfp).as_str())
.map_err(|_| KeystoneError::InvalidParseContext("invalid mfp".to_string()))?;
let extended_pubkey = bitcoin::bip32::Xpub::from_str(&xpub_str).map_err(|_| {
- KeystoneError::InvalidParseContext(format!("invalid extended pub key {}", x_pub))
+ KeystoneError::InvalidParseContext(format!("invalid extended pub key {x_pub}"))
})?;
Ok(app_utils::keystone::ParseContext::new(
master_fingerprint,
@@ -63,7 +63,7 @@ pub fn build_parse_context(
))
}
-fn get_signed_tx(
+unsafe fn get_signed_tx(
coin_code: String,
payload: Payload,
master_fingerprint: PtrBytes,
@@ -81,14 +81,13 @@ fn get_signed_tx(
"TRON" => app_tron::sign_raw_tx(payload, context, seed)
.map_err(|e| KeystoneError::SignTxFailed(e.to_string())),
_ => Err(KeystoneError::SignTxFailed(format!(
- "chain is not supported {}",
- coin_code
+ "chain is not supported {coin_code}"
))),
}
})
}
-pub fn build_check_result(
+pub unsafe fn build_check_result(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -123,7 +122,7 @@ pub fn build_check_result(
}
}
-pub fn build_sign_result(
+pub unsafe fn build_sign_result(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -167,7 +166,7 @@ pub fn build_sign_result(
}
}
-pub fn check(
+pub unsafe fn check(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -184,7 +183,7 @@ pub fn check(
}
}
-pub fn sign(
+pub unsafe fn sign(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
diff --git a/rust/rust_c/src/common/macros.rs b/rust/rust_c/src/common/macros.rs
index 9aa2955..514702f 100644
--- a/rust/rust_c/src/common/macros.rs
+++ b/rust/rust_c/src/common/macros.rs
@@ -471,12 +471,12 @@ macro_rules! impl_simple_new_error {
macro_rules! extract_ptr_with_type {
($x: expr, $name: ident) => {{
let ptr = $x as *mut $name;
- let result: &mut $name = unsafe { &mut *ptr };
+ let result: &mut $name = &mut *ptr;
result
}};
($x: expr, $name: ident<$t: ident>) => {{
let ptr = $x as *mut $name<$t>;
- let result: &mut $name<$t> = unsafe { &mut *ptr };
+ let result: &mut $name<$t> = &mut *ptr;
result
}};
}
@@ -485,7 +485,7 @@ macro_rules! extract_ptr_with_type {
macro_rules! extract_array {
($x: expr, $name: ident, $length: expr) => {{
let ptr = $x as *mut $name;
- let result: &[$name] = unsafe { core::slice::from_raw_parts(ptr, $length as usize) };
+ let result: &[$name] = core::slice::from_raw_parts(ptr, $length as usize);
result
}};
}
@@ -520,7 +520,7 @@ macro_rules! impl_c_ptrs {
macro_rules! impl_simple_free {
($($name: ident), *) => {
$(
- impl SimpleFree for $name {fn free(&self){}}
+ impl SimpleFree for $name {unsafe fn free(&self){}}
)*
};
}
@@ -530,7 +530,7 @@ macro_rules! make_free_method {
($t: ident) => {
app_utils::paste::item! {
#[no_mangle]
- pub extern "C" fn [<free_ $t>](ptr: PtrT<$t>) {
+ pub unsafe extern "C" fn [<free_ $t>](ptr: PtrT<$t>) {
$crate::check_and_free_ptr!(ptr)
}
}
@@ -538,7 +538,7 @@ macro_rules! make_free_method {
($t1:ident<$t2:ident>) => {
app_utils::paste::item! {
#[no_mangle]
- pub extern "C" fn [<free_ $t1 _ $t2>](ptr: PtrT<$t1<$t2>>) {
+ pub unsafe extern "C" fn [<free_ $t1 _ $t2>](ptr: PtrT<$t1<$t2>>) {
$crate::check_and_free_ptr!(ptr)
}
}
diff --git a/rust/rust_c/src/common/mod.rs b/rust/rust_c/src/common/mod.rs
index ea7b66b..1880268 100644
--- a/rust/rust_c/src/common/mod.rs
+++ b/rust/rust_c/src/common/mod.rs
@@ -23,6 +23,8 @@ use structs::SimpleResponse;
use types::{PtrBytes, PtrString};
use utils::{convert_c_char, recover_c_char};
+use crate::extract_array;
+
pub mod errors;
pub mod ffi;
pub mod free;
@@ -56,7 +58,7 @@ pub extern "C" fn dummy_function_to_export_error_codes() -> ErrorCodes {
}
#[no_mangle]
-pub extern "C" fn format_value_with_decimals(
+pub unsafe extern "C" fn format_value_with_decimals(
value: PtrString,
decimals: u32,
) -> *mut SimpleResponse<c_char> {
@@ -87,13 +89,13 @@ pub extern "C" fn format_value_with_decimals(
}
#[no_mangle]
-pub extern "C" fn get_extended_pubkey_by_seed(
+pub unsafe extern "C" fn get_extended_pubkey_by_seed(
seed: PtrBytes,
seed_len: u32,
path: PtrString,
) -> *mut SimpleResponse<c_char> {
let path = recover_c_char(path);
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let extended_key =
keystore::algorithms::secp256k1::get_extended_public_key_by_seed(seed, &path);
match extended_key {
@@ -103,13 +105,13 @@ pub extern "C" fn get_extended_pubkey_by_seed(
}
#[no_mangle]
-pub extern "C" fn get_extended_pubkey_bytes_by_seed(
+pub unsafe extern "C" fn get_extended_pubkey_bytes_by_seed(
seed: PtrBytes,
seed_len: u32,
path: PtrString,
) -> *mut SimpleResponse<c_char> {
let path = recover_c_char(path);
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let extended_key =
keystore::algorithms::secp256k1::get_extended_public_key_by_seed(seed, &path);
match extended_key {
@@ -122,12 +124,12 @@ pub extern "C" fn get_extended_pubkey_bytes_by_seed(
}
#[no_mangle]
-pub extern "C" fn get_ed25519_pubkey_by_seed(
+pub unsafe extern "C" fn get_ed25519_pubkey_by_seed(
seed: PtrBytes,
seed_len: u32,
path: PtrString,
) -> *mut SimpleResponse<c_char> {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let path = recover_c_char(path);
let extended_key =
keystore::algorithms::ed25519::slip10_ed25519::get_public_key_by_seed(seed, &path);
@@ -138,8 +140,11 @@ pub extern "C" fn get_ed25519_pubkey_by_seed(
}
#[no_mangle]
-pub extern "C" fn get_rsa_pubkey_by_seed(seed: PtrBytes, seed_len: u32) -> *mut SimpleResponse<u8> {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+pub unsafe extern "C" fn get_rsa_pubkey_by_seed(
+ seed: PtrBytes,
+ seed_len: u32,
+) -> *mut SimpleResponse<u8> {
+ let seed = extract_array!(seed, u8, seed_len as usize);
let public_key = keystore::algorithms::rsa::get_rsa_pubkey_by_seed(seed);
match public_key {
Ok(result) => {
@@ -150,13 +155,13 @@ pub extern "C" fn get_rsa_pubkey_by_seed(seed: PtrBytes, seed_len: u32) -> *mut
}
#[no_mangle]
-pub extern "C" fn get_bip32_ed25519_extended_pubkey(
+pub unsafe extern "C" fn get_bip32_ed25519_extended_pubkey(
entropy: PtrBytes,
entropy_len: u32,
passphrase: PtrString,
path: PtrString,
) -> *mut SimpleResponse<c_char> {
- let entropy = unsafe { slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let path = recover_c_char(path);
let passphrase = recover_c_char(passphrase);
let extended_key =
@@ -172,7 +177,7 @@ pub extern "C" fn get_bip32_ed25519_extended_pubkey(
}
#[no_mangle]
-pub extern "C" fn get_ledger_bitbox02_master_key(
+pub unsafe extern "C" fn get_ledger_bitbox02_master_key(
mnemonic: PtrString,
passphrase: PtrString,
) -> *mut SimpleResponse<c_char> {
@@ -190,12 +195,12 @@ pub extern "C" fn get_ledger_bitbox02_master_key(
}
#[no_mangle]
-pub extern "C" fn get_icarus_master_key(
+pub unsafe extern "C" fn get_icarus_master_key(
entropy: PtrBytes,
entropy_len: u32,
passphrase: PtrString,
) -> *mut SimpleResponse<c_char> {
- let entropy = unsafe { slice::from_raw_parts(entropy, entropy_len as usize) };
+ let entropy = extract_array!(entropy, u8, entropy_len as usize);
let passphrase = recover_c_char(passphrase);
let master_key = keystore::algorithms::ed25519::bip32_ed25519::get_icarus_master_key_by_entropy(
entropy,
@@ -208,7 +213,7 @@ pub extern "C" fn get_icarus_master_key(
}
#[no_mangle]
-pub extern "C" fn derive_bip32_ed25519_extended_pubkey(
+pub unsafe extern "C" fn derive_bip32_ed25519_extended_pubkey(
master_key: PtrString,
path: PtrString,
) -> *mut SimpleResponse<c_char> {
@@ -230,12 +235,12 @@ pub extern "C" fn derive_bip32_ed25519_extended_pubkey(
}
#[no_mangle]
-pub extern "C" fn k1_sign_message_hash_by_private_key(
+pub unsafe extern "C" fn k1_sign_message_hash_by_private_key(
private_key: PtrBytes,
message_hash: PtrBytes,
) -> *mut SimpleResponse<c_char> {
- let private_key_bytes = unsafe { slice::from_raw_parts(private_key, 32) };
- let message_hash_bytes = unsafe { slice::from_raw_parts(message_hash, 32) };
+ let private_key_bytes = extract_array!(private_key, u8, 32);
+ let message_hash_bytes = extract_array!(message_hash, u8, 32);
let signature = keystore::algorithms::secp256k1::sign_message_hash_by_private_key(
message_hash_bytes,
private_key_bytes,
@@ -247,34 +252,31 @@ pub extern "C" fn k1_sign_message_hash_by_private_key(
}
#[no_mangle]
-pub extern "C" fn k1_verify_signature(
+pub unsafe extern "C" fn k1_verify_signature(
signature: PtrBytes,
message_hash: PtrBytes,
public_key: PtrBytes,
) -> bool {
- let signature_bytes = unsafe { slice::from_raw_parts(signature, 64) };
- let message_hash_bytes = unsafe { slice::from_raw_parts(message_hash, 32) };
- let public_key_bytes = unsafe { slice::from_raw_parts(public_key, 65) };
+ let signature_bytes = extract_array!(signature, u8, 64);
+ let message_hash_bytes = extract_array!(message_hash, u8, 32);
+ let public_key_bytes = extract_array!(public_key, u8, 65);
let result = keystore::algorithms::secp256k1::verify_signature(
signature_bytes,
message_hash_bytes,
public_key_bytes,
);
- match result {
- Ok(data) => data,
- Err(_e) => false,
- }
+ result.unwrap_or_default()
}
#[no_mangle]
-pub extern "C" fn k1_generate_ecdh_sharekey(
+pub unsafe extern "C" fn k1_generate_ecdh_sharekey(
privkey: PtrBytes,
privkey_len: u32,
pubkey: PtrBytes,
pubkey_len: u32,
) -> *mut SimpleResponse<u8> {
- let private_key = unsafe { slice::from_raw_parts(privkey, privkey_len as usize) };
- let public_key = unsafe { slice::from_raw_parts(pubkey, pubkey_len as usize) };
+ let private_key = extract_array!(privkey, u8, privkey_len as usize);
+ let public_key = extract_array!(pubkey, u8, pubkey_len as usize);
let result = keystore::algorithms::secp256k1::get_share_key(private_key, public_key);
match result {
Ok(share_key) => {
@@ -285,11 +287,11 @@ pub extern "C" fn k1_generate_ecdh_sharekey(
}
#[no_mangle]
-pub extern "C" fn k1_generate_pubkey_by_privkey(
+pub unsafe extern "C" fn k1_generate_pubkey_by_privkey(
privkey: PtrBytes,
privkey_len: u32,
) -> *mut SimpleResponse<u8> {
- let private_key = unsafe { slice::from_raw_parts(privkey, privkey_len as usize) };
+ let private_key = extract_array!(privkey, u8, privkey_len as usize);
let result = keystore::algorithms::secp256k1::get_public_key(private_key);
match result {
Ok(pubkey) => {
@@ -300,25 +302,25 @@ pub extern "C" fn k1_generate_pubkey_by_privkey(
}
#[no_mangle]
-pub extern "C" fn pbkdf2_rust(
+pub unsafe extern "C" fn pbkdf2_rust(
password: PtrBytes,
salt: PtrBytes,
iterations: u32,
) -> *mut SimpleResponse<u8> {
- let password_bytes = unsafe { slice::from_raw_parts(password, 32) };
- let salt_bytes = unsafe { slice::from_raw_parts(salt, 32) };
+ let password_bytes = extract_array!(password, u8, 32);
+ let salt_bytes = extract_array!(salt, u8, 32);
let output = keystore::algorithms::crypto::hkdf(password_bytes, salt_bytes, iterations);
SimpleResponse::success(Box::into_raw(Box::new(output)) as *mut u8).simple_c_ptr()
}
#[no_mangle]
-pub extern "C" fn pbkdf2_rust_64(
+pub unsafe extern "C" fn pbkdf2_rust_64(
password: PtrBytes,
salt: PtrBytes,
iterations: u32,
) -> *mut SimpleResponse<u8> {
- let password_bytes = unsafe { slice::from_raw_parts(password, 64) };
- let salt_bytes = unsafe { slice::from_raw_parts(salt, 64) };
+ let password_bytes = extract_array!(password, u8, 64);
+ let salt_bytes = extract_array!(salt, u8, 64);
let output = keystore::algorithms::crypto::hkdf64(password_bytes, salt_bytes, iterations);
SimpleResponse::success(Box::into_raw(Box::new(output)) as *mut u8).simple_c_ptr()
}
diff --git a/rust/rust_c/src/common/qrcode/mod.rs b/rust/rust_c/src/common/qrcode/mod.rs
index 4b071e2..3e3f150 100644
--- a/rust/rust_c/src/common/qrcode/mod.rs
+++ b/rust/rust_c/src/common/qrcode/mod.rs
@@ -17,7 +17,7 @@ pub enum QRProtocol {
}
#[no_mangle]
-pub extern "C" fn infer_qrcode_type(qrcode: PtrString) -> QRProtocol {
+pub unsafe extern "C" fn infer_qrcode_type(qrcode: PtrString) -> QRProtocol {
let value = recover_c_char(qrcode);
if value.to_uppercase().starts_with("UR:") {
QRProtocol::QRCodeTypeUR
@@ -27,7 +27,7 @@ pub extern "C" fn infer_qrcode_type(qrcode: PtrString) -> QRProtocol {
}
#[no_mangle]
-pub extern "C" fn parse_qrcode_text(qr: PtrString) -> Ptr<URParseResult> {
+pub unsafe extern "C" fn parse_qrcode_text(qr: PtrString) -> Ptr<URParseResult> {
let value = recover_c_char(qr);
if value.to_lowercase().starts_with("signmessage") {
let mut headers_and_message = value.split(':');
@@ -55,8 +55,7 @@ pub extern "C" fn parse_qrcode_text(qr: PtrString) -> Ptr<URParseResult> {
}
_ => {
return URParseResult::from(RustCError::UnsupportedTransaction(format!(
- "message encode not supported: {}",
- encode
+ "message encode not supported: {encode}"
)))
.c_ptr()
}
diff --git a/rust/rust_c/src/common/structs.rs b/rust/rust_c/src/common/structs.rs
index 8e1d32a..d97cbc2 100644
--- a/rust/rust_c/src/common/structs.rs
+++ b/rust/rust_c/src/common/structs.rs
@@ -12,7 +12,7 @@ use ur_registry::error::URError;
use super::free::Free;
use super::types::{PtrString, PtrT};
use crate::{
- check_and_free_ptr, free_str_ptr, impl_c_ptr, impl_new_error, impl_response, impl_simple_c_ptr,
+ free_str_ptr, impl_c_ptr, impl_new_error, impl_response, impl_simple_c_ptr,
impl_simple_new_error, make_free_method,
};
@@ -38,15 +38,13 @@ impl<T> TransactionParseResult<T> {
}
impl<T: Free> Free for TransactionParseResult<T> {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.error_message);
if self.data.is_null() {
return;
}
- unsafe {
- let x = Box::from_raw(self.data);
- x.free()
- }
+ let x = Box::from_raw(self.data);
+ x.free()
}
}
@@ -68,7 +66,7 @@ impl TransactionCheckResult {
}
impl Free for TransactionCheckResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.error_message);
}
}
@@ -99,22 +97,18 @@ impl<T> SimpleResponse<T> {
}
impl Free for SimpleResponse<u8> {
- fn free(&self) {
- unsafe {
- if !self.data.is_null() {
- let _x = Box::from_raw(self.data);
- }
+ unsafe fn free(&self) {
+ if !self.data.is_null() {
+ let _x = Box::from_raw(self.data);
}
free_str_ptr!(self.error_message);
}
}
impl Free for SimpleResponse<i8> {
- fn free(&self) {
- unsafe {
- if !self.data.is_null() {
- let _x = Box::from_raw(self.data);
- }
+ unsafe fn free(&self) {
+ if !self.data.is_null() {
+ let _x = Box::from_raw(self.data);
}
free_str_ptr!(self.error_message);
}
@@ -150,15 +144,13 @@ impl<T> Response<T> {
}
impl<T: Free> Free for Response<T> {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.error_message);
if self.data.is_null() {
return;
}
- unsafe {
- let x = Box::from_raw(self.data);
- x.free()
- }
+ let x = Box::from_raw(self.data);
+ x.free()
}
}
@@ -173,18 +165,16 @@ pub struct ExtendedPublicKey {
impl_c_ptr!(ExtendedPublicKey);
impl Free for ExtendedPublicKey {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.path);
free_str_ptr!(self.xpub);
}
}
impl Free for PtrT<ExtendedPublicKey> {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(*self);
- x.free()
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(*self);
+ x.free()
}
}
@@ -198,17 +188,15 @@ pub struct ZcashKey {
impl_c_ptr!(ZcashKey);
impl Free for ZcashKey {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.key_text);
free_str_ptr!(self.key_name);
}
}
impl Free for PtrT<ZcashKey> {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(*self);
- x.free()
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(*self);
+ x.free()
}
}
diff --git a/rust/rust_c/src/common/types.rs b/rust/rust_c/src/common/types.rs
index 3c5c0b3..041b3b6 100644
--- a/rust/rust_c/src/common/types.rs
+++ b/rust/rust_c/src/common/types.rs
@@ -16,9 +16,7 @@ pub type PtrT<T> = *mut T;
pub type Ptr<T> = *mut T;
impl Free for PtrString {
- fn free(&self) {
- unsafe {
- let _ = Box::from_raw(*self);
- }
+ unsafe fn free(&self) {
+ let _ = Box::from_raw(*self);
}
}
diff --git a/rust/rust_c/src/common/ur.rs b/rust/rust_c/src/common/ur.rs
index 3620ff8..ed1b66b 100644
--- a/rust/rust_c/src/common/ur.rs
+++ b/rust/rust_c/src/common/ur.rs
@@ -151,12 +151,10 @@ impl UREncodeResult {
}
impl Free for UREncodeResult {
- fn free(&self) {
- unsafe {
- free_str_ptr!(self.data);
- free_str_ptr!(self.error_message);
- free_ptr_with_type!(self.encoder, KeystoneUREncoder);
- }
+ unsafe fn free(&self) {
+ free_str_ptr!(self.data);
+ free_str_ptr!(self.error_message);
+ free_ptr_with_type!(self.encoder, KeystoneUREncoder);
}
}
@@ -186,7 +184,7 @@ impl UREncodeMultiResult {
}
impl Free for UREncodeMultiResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.data);
free_str_ptr!(self.error_message);
}
@@ -489,14 +487,14 @@ impl URParseResult {
}
impl Free for URParseResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.error_message);
free_ptr_with_type!(self.decoder, KeystoneURDecoder);
free_ur(&self.ur_type, self.data);
}
}
-fn free_ur(ur_type: &QRCodeType, data: PtrUR) {
+unsafe fn free_ur(ur_type: &QRCodeType, data: PtrUR) {
match ur_type {
#[cfg(feature = "bitcoin")]
QRCodeType::CryptoPSBT => {
@@ -660,7 +658,7 @@ impl URParseMultiResult {
}
impl Free for URParseMultiResult {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.error_message);
free_ur(&self.ur_type, self.data);
}
@@ -912,12 +910,12 @@ pub extern "C" fn get_next_cyclic_part(ptr: PtrEncoder) -> *mut UREncodeMultiRes
}
#[no_mangle]
-pub extern "C" fn parse_ur(ur: PtrString) -> *mut URParseResult {
+pub unsafe extern "C" fn parse_ur(ur: PtrString) -> *mut URParseResult {
decode_ur(recover_c_char(ur)).c_ptr()
}
#[no_mangle]
-pub extern "C" fn receive(ur: PtrString, decoder: PtrDecoder) -> *mut URParseMultiResult {
+pub unsafe extern "C" fn receive(ur: PtrString, decoder: PtrDecoder) -> *mut URParseMultiResult {
let decoder = extract_ptr_with_type!(decoder, KeystoneURDecoder);
receive_ur(recover_c_char(ur), decoder).c_ptr()
}
diff --git a/rust/rust_c/src/common/ur_ext.rs b/rust/rust_c/src/common/ur_ext.rs
index 6fd5989..3e4fa1b 100644
--- a/rust/rust_c/src/common/ur_ext.rs
+++ b/rust/rust_c/src/common/ur_ext.rs
@@ -274,7 +274,7 @@ impl InferViewType for Bytes {
Ok(_v) => {
if let Some(_type) = _v.pointer("/data/type") {
let contract_name: String = from_value(_type.clone())
- .map_err(|e| URError::UrDecodeError(format!("invalid data, {}", e)))?;
+ .map_err(|e| URError::UrDecodeError(format!("invalid data, {e}")))?;
if contract_name.eq("webAuth") {
return Ok(ViewType::WebAuthResult);
}
@@ -282,7 +282,7 @@ impl InferViewType for Bytes {
#[cfg(feature = "xrp")]
return Ok(ViewType::XRPTx);
#[cfg(not(feature = "xrp"))]
- return Err(URError::UrDecodeError(format!("invalid data")));
+ return Err(URError::UrDecodeError("invalid data".to_string()));
}
#[cfg(feature = "multi-coins")]
Err(_e) => get_view_type_from_keystone(self.get_bytes()),
@@ -297,7 +297,7 @@ impl InferViewType for Bytes {
get_view_type_from_keystone(self.get_bytes())
}
#[cfg(not(any(feature = "btc-only", feature = "multi-coins")))]
- Err(_e) => return Err(URError::UrDecodeError(format!("invalid data"))),
+ Err(_e) => Err(URError::UrDecodeError("invalid data".to_string())),
}
}
}
diff --git a/rust/rust_c/src/common/utils.rs b/rust/rust_c/src/common/utils.rs
index c0cc666..9d5f711 100644
--- a/rust/rust_c/src/common/utils.rs
+++ b/rust/rust_c/src/common/utils.rs
@@ -3,7 +3,7 @@ use core::slice;
use super::ffi::CSliceFFI;
use super::free::Free;
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use cstr_core::{CStr, CString};
use cty::c_char;
@@ -13,11 +13,11 @@ pub fn convert_c_char(s: String) -> PtrString {
CString::new(s).unwrap().into_raw()
}
-pub fn recover_c_char(s: *mut c_char) -> String {
- unsafe { CStr::from_ptr(s).to_str().unwrap().to_string() }
+pub unsafe fn recover_c_char(s: *mut c_char) -> String {
+ CStr::from_ptr(s).to_str().unwrap().to_string()
}
pub unsafe fn recover_c_array<'a, T: Free>(s: PtrT<CSliceFFI<T>>) -> &'a [T] {
let boxed_keys = extract_ptr_with_type!(s, CSliceFFI<T>);
- slice::from_raw_parts(boxed_keys.data, boxed_keys.size)
+ extract_array!(boxed_keys.data, T, boxed_keys.size)
}
diff --git a/rust/rust_c/src/common/web_auth.rs b/rust/rust_c/src/common/web_auth.rs
index 4e9c87f..eb3e6e5 100644
--- a/rust/rust_c/src/common/web_auth.rs
+++ b/rust/rust_c/src/common/web_auth.rs
@@ -1,5 +1,5 @@
use alloc::{
- format, slice,
+ format,
string::{String, ToString},
vec,
};
@@ -10,7 +10,7 @@ use {
ur_registry::bytes::Bytes,
};
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use super::{
errors::RustCError,
@@ -21,7 +21,7 @@ use super::{
use sha1::Sha1;
#[no_mangle]
-pub extern "C" fn calculate_auth_code(
+pub unsafe extern "C" fn calculate_auth_code(
web_auth_data: ConstPtrUR,
rsa_key_n: PtrBytes,
rsa_key_n_len: u32,
@@ -38,23 +38,23 @@ pub extern "C" fn calculate_auth_code(
Ok(_hex) => match base64::decode(&_hex) {
Ok(_value) => unsafe {
let rsa_key_n =
- slice::from_raw_parts(rsa_key_n, rsa_key_n_len as usize);
+ extract_array!(rsa_key_n, u8, rsa_key_n_len as usize);
let rsa_key_d =
- slice::from_raw_parts(rsa_key_d, rsa_key_d_len as usize);
+ extract_array!(rsa_key_d, u8, rsa_key_d_len as usize);
match _calculate_auth_code(&_value, rsa_key_n, rsa_key_d) {
Ok(_result) => Ok(_result),
- Err(_err) => Err(RustCError::WebAuthFailed(format!("{}", _err))),
+ Err(_err) => Err(RustCError::WebAuthFailed(format!("{_err}"))),
}
},
- Err(_err) => Err(RustCError::WebAuthFailed(format!("{}", _err))),
+ Err(_err) => Err(RustCError::WebAuthFailed(format!("{_err}"))),
},
- Err(_err) => Err(RustCError::WebAuthFailed(format!("{}", _err))),
+ Err(_err) => Err(RustCError::WebAuthFailed(format!("{_err}"))),
}
} else {
Err(RustCError::WebAuthFailed("invalid json".to_string()))
}
}
- Err(_err) => Err(RustCError::WebAuthFailed(format!("{}", _err))),
+ Err(_err) => Err(RustCError::WebAuthFailed(format!("{_err}"))),
};
match result {
Ok(_value) => convert_c_char(_value),
@@ -96,13 +96,11 @@ fn _calculate_auth_code(
))
}),
Err(_err) => Err(RustCError::WebAuthFailed(format!(
- "RSA decryption failed: {}",
- _err
+ "RSA decryption failed: {_err}"
))),
},
Err(_err) => Err(RustCError::WebAuthFailed(format!(
- "RSA key recovery error: {}",
- _err
+ "RSA key recovery error: {_err}"
))),
}
},
diff --git a/rust/rust_c/src/cosmos/mod.rs b/rust/rust_c/src/cosmos/mod.rs
index 6252236..9cf0df3 100644
--- a/rust/rust_c/src/cosmos/mod.rs
+++ b/rust/rust_c/src/cosmos/mod.rs
@@ -5,6 +5,7 @@ use crate::common::structs::{SimpleResponse, TransactionCheckResult, Transaction
use crate::common::types::{PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{QRCodeType, UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use crate::common::utils::{convert_c_char, recover_c_char};
+use crate::extract_array;
use crate::extract_ptr_with_type;
use alloc::format;
use alloc::string::{String, ToString};
@@ -12,7 +13,6 @@ use alloc::vec::Vec;
use app_cosmos::errors::CosmosError;
use app_cosmos::transaction::structs::SignMode;
use app_utils::normalize_path;
-use core::slice;
use cty::c_char;
use either::Either;
use structs::DisplayCosmosTx;
@@ -30,15 +30,14 @@ fn get_public_key(seed: &[u8], path: &String) -> Result<Vec<u8>, CosmosError> {
Ok(xpub) => xpub.public_key,
Err(e) => {
return Err(CosmosError::SignFailure(format!(
- "derive public key failed {:?}",
- e
+ "derive public key failed {e:?}"
)))
}
};
Ok(public_key.serialize().to_vec())
}
-fn build_sign_result(
+unsafe fn build_sign_result(
ptr: PtrUR,
ur_type: QRCodeType,
seed: &[u8],
@@ -86,7 +85,7 @@ fn build_sign_result(
}
#[no_mangle]
-pub extern "C" fn cosmos_check_tx(
+pub unsafe extern "C" fn cosmos_check_tx(
ptr: PtrUR,
ur_type: QRCodeType,
master_fingerprint: PtrBytes,
@@ -95,7 +94,7 @@ pub extern "C" fn cosmos_check_tx(
if length != 4 {
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
- let mfp = unsafe { slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let ur_mfp = match ur_type {
QRCodeType::CosmosSignRequest => {
let sign_request = extract_ptr_with_type!(ptr, CosmosSignRequest);
@@ -128,7 +127,7 @@ pub extern "C" fn cosmos_check_tx(
}
#[no_mangle]
-pub extern "C" fn cosmos_get_address(
+pub unsafe extern "C" fn cosmos_get_address(
hd_path: PtrString,
root_x_pub: PtrString,
root_path: PtrString,
@@ -140,8 +139,7 @@ pub extern "C" fn cosmos_get_address(
let prefix = recover_c_char(prefix);
if !hd_path.starts_with(root_path.as_str()) {
return SimpleResponse::from(CosmosError::InvalidHDPath(format!(
- "{} does not match {}",
- hd_path, root_path
+ "{hd_path} does not match {root_path}"
)))
.simple_c_ptr();
}
@@ -153,13 +151,13 @@ pub extern "C" fn cosmos_get_address(
}
#[no_mangle]
-pub extern "C" fn cosmos_sign_tx(
+pub unsafe extern "C" fn cosmos_sign_tx(
ptr: PtrUR,
ur_type: QRCodeType,
seed: PtrBytes,
seed_len: u32,
) -> PtrT<UREncodeResult> {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let ur_tag = match ur_type {
QRCodeType::CosmosSignRequest => CosmosSignature::get_registry_type().get_type(),
QRCodeType::EvmSignRequest => EvmSignature::get_registry_type().get_type(),
@@ -189,7 +187,7 @@ pub extern "C" fn cosmos_sign_tx(
}
#[no_mangle]
-pub extern "C" fn cosmos_parse_tx(
+pub unsafe extern "C" fn cosmos_parse_tx(
ptr: PtrUR,
ur_type: QRCodeType,
) -> PtrT<TransactionParseResult<DisplayCosmosTx>> {
diff --git a/rust/rust_c/src/cosmos/structs.rs b/rust/rust_c/src/cosmos/structs.rs
index d2d2fb4..415a580 100644
--- a/rust/rust_c/src/cosmos/structs.rs
+++ b/rust/rust_c/src/cosmos/structs.rs
@@ -4,11 +4,11 @@ use app_cosmos::transaction::structs::{CosmosTxDisplayType, ParsedCosmosTx};
use core::ptr::null_mut;
use serde_json;
-use crate::common::free::{free_ptr_string, Free};
+use crate::common::free::Free;
use crate::common::structs::TransactionParseResult;
use crate::common::types::{PtrString, PtrT};
use crate::common::utils::convert_c_char;
-use crate::{check_and_free_ptr, impl_c_ptr, make_free_method};
+use crate::{check_and_free_ptr, impl_c_ptr, make_free_method, free_str_ptr};
#[repr(C)]
pub struct DisplayCosmosTx {
@@ -89,37 +89,37 @@ impl Default for DisplayCosmosTxOverview {
}
impl Free for DisplayCosmosTx {
- fn free(&self) {
+ unsafe fn free(&self) {
check_and_free_ptr!(self.overview);
- free_ptr_string(self.detail);
+ free_str_ptr!(self.detail);
}
}
impl Free for DisplayCosmosTxOverview {
- fn free(&self) {
- free_ptr_string(self.display_type);
- free_ptr_string(self.method);
- free_ptr_string(self.network);
- free_ptr_string(self.send_value);
- free_ptr_string(self.send_from);
- free_ptr_string(self.send_to);
- free_ptr_string(self.delegate_value);
- free_ptr_string(self.delegate_from);
- free_ptr_string(self.delegate_to);
- free_ptr_string(self.undelegate_value);
- free_ptr_string(self.undelegate_to);
- free_ptr_string(self.undelegate_validator);
- free_ptr_string(self.redelegate_value);
- free_ptr_string(self.redelegate_to);
- free_ptr_string(self.redelegate_new_validator);
- free_ptr_string(self.withdraw_reward_to);
- free_ptr_string(self.withdraw_reward_validator);
- free_ptr_string(self.transfer_from);
- free_ptr_string(self.transfer_to);
- free_ptr_string(self.transfer_value);
- free_ptr_string(self.vote_voted);
- free_ptr_string(self.vote_proposal);
- free_ptr_string(self.vote_voter);
- free_ptr_string(self.overview_list);
+ unsafe fn free(&self) {
+ free_str_ptr!(self.display_type);
+ free_str_ptr!(self.method);
+ free_str_ptr!(self.network);
+ free_str_ptr!(self.send_value);
+ free_str_ptr!(self.send_from);
+ free_str_ptr!(self.send_to);
+ free_str_ptr!(self.delegate_value);
+ free_str_ptr!(self.delegate_from);
+ free_str_ptr!(self.delegate_to);
+ free_str_ptr!(self.undelegate_value);
+ free_str_ptr!(self.undelegate_to);
+ free_str_ptr!(self.undelegate_validator);
+ free_str_ptr!(self.redelegate_value);
+ free_str_ptr!(self.redelegate_to);
+ free_str_ptr!(self.redelegate_new_validator);
+ free_str_ptr!(self.withdraw_reward_to);
+ free_str_ptr!(self.withdraw_reward_validator);
+ free_str_ptr!(self.transfer_from);
+ free_str_ptr!(self.transfer_to);
+ free_str_ptr!(self.transfer_value);
+ free_str_ptr!(self.vote_voted);
+ free_str_ptr!(self.vote_proposal);
+ free_str_ptr!(self.vote_voter);
+ free_str_ptr!(self.overview_list);
}
}
diff --git a/rust/rust_c/src/ethereum/abi.rs b/rust/rust_c/src/ethereum/abi.rs
index ffeaa58..96263db 100644
--- a/rust/rust_c/src/ethereum/abi.rs
+++ b/rust/rust_c/src/ethereum/abi.rs
@@ -5,7 +5,7 @@ use crate::common::types::{Ptr, PtrString};
use crate::common::utils::recover_c_char;
#[no_mangle]
-pub extern "C" fn eth_parse_contract_data(
+pub unsafe extern "C" fn eth_parse_contract_data(
input_data: PtrString,
contract_json: PtrString,
) -> Ptr<Response<DisplayContractData>> {
@@ -26,7 +26,7 @@ pub extern "C" fn eth_parse_contract_data(
}
#[no_mangle]
-pub extern "C" fn eth_parse_swapkit_contract(
+pub unsafe extern "C" fn eth_parse_swapkit_contract(
input_data: PtrString,
contract_json: PtrString,
) -> Ptr<Response<DisplaySwapkitContractData>> {
@@ -47,7 +47,7 @@ pub extern "C" fn eth_parse_swapkit_contract(
}
#[no_mangle]
-pub extern "C" fn eth_parse_contract_data_by_method(
+pub unsafe extern "C" fn eth_parse_contract_data_by_method(
input_data: PtrString,
contract_name: PtrString,
contract_method_json: PtrString,
diff --git a/rust/rust_c/src/ethereum/address.rs b/rust/rust_c/src/ethereum/address.rs
index 56deddb..878df53 100644
--- a/rust/rust_c/src/ethereum/address.rs
+++ b/rust/rust_c/src/ethereum/address.rs
@@ -8,7 +8,7 @@ use crate::common::utils::{convert_c_char, recover_c_char};
use app_ethereum::errors::EthereumError;
#[no_mangle]
-pub extern "C" fn eth_get_address(
+pub unsafe extern "C" fn eth_get_address(
hd_path: PtrString,
root_x_pub: PtrString,
root_path: PtrString,
@@ -18,8 +18,7 @@ pub extern "C" fn eth_get_address(
let root_path = recover_c_char(root_path);
if !hd_path.starts_with(root_path.as_str()) {
return SimpleResponse::from(EthereumError::InvalidHDPath(format!(
- "{} does not match {}",
- hd_path, root_path
+ "{hd_path} does not match {root_path}"
)))
.simple_c_ptr();
}
diff --git a/rust/rust_c/src/ethereum/mod.rs b/rust/rust_c/src/ethereum/mod.rs
index e0e6305..7091ab1 100644
--- a/rust/rust_c/src/ethereum/mod.rs
+++ b/rust/rust_c/src/ethereum/mod.rs
@@ -32,7 +32,7 @@ use crate::common::ur::{
};
use crate::common::utils::{convert_c_char, recover_c_char};
use crate::common::KEYSTONE;
-use crate::extract_ptr_with_type;
+use crate::{extract_array, extract_ptr_with_type};
use structs::{
DisplayETH, DisplayETHBatchTx, DisplayETHPersonalMessage, DisplayETHTypedData,
@@ -45,7 +45,7 @@ pub mod structs;
pub(crate) mod util;
#[no_mangle]
-pub extern "C" fn eth_check_ur_bytes(
+pub unsafe extern "C" fn eth_check_ur_bytes(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -57,7 +57,7 @@ pub extern "C" fn eth_check_ur_bytes(
let payload = build_payload(ptr, ur_type);
match payload {
Ok(payload) => {
- let mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let mfp: [u8; 4] = mfp.to_vec().try_into().unwrap();
let xfp = payload.xfp;
@@ -73,7 +73,7 @@ pub extern "C" fn eth_check_ur_bytes(
}
#[no_mangle]
-pub extern "C" fn eth_check(
+pub unsafe extern "C" fn eth_check(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -82,7 +82,7 @@ pub extern "C" fn eth_check(
return TransactionCheckResult::from(RustCError::InvalidMasterFingerprint).c_ptr();
}
let eth_sign_request = extract_ptr_with_type!(ptr, EthSignRequest);
- let mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let mfp: [u8; 4] = match mfp.try_into() {
Ok(mfp) => mfp,
Err(_) => {
@@ -108,7 +108,7 @@ pub extern "C" fn eth_check(
}
#[no_mangle]
-pub extern "C" fn eth_get_root_path_bytes(ptr: PtrUR) -> PtrString {
+pub unsafe extern "C" fn eth_get_root_path_bytes(ptr: PtrUR) -> PtrString {
let payload = build_payload(ptr, QRCodeType::Bytes).unwrap();
let content = payload.content.unwrap();
let sign_tx = match content {
@@ -129,7 +129,7 @@ pub extern "C" fn eth_get_root_path_bytes(ptr: PtrUR) -> PtrString {
}
#[no_mangle]
-pub extern "C" fn eth_get_root_path(ptr: PtrUR) -> PtrString {
+pub unsafe extern "C" fn eth_get_root_path(ptr: PtrUR) -> PtrString {
let eth_sign_request = extract_ptr_with_type!(ptr, EthSignRequest);
let derivation_path: ur_registry::crypto_key_path::CryptoKeyPath =
eth_sign_request.get_derivation_path();
@@ -147,7 +147,7 @@ fn parse_eth_root_path(path: String) -> Option<String> {
Some(path) => {
if let Some(index) = path.find('/') {
let sub_path = &path[..index];
- Some(format!("{}{}", root_path, sub_path))
+ Some(format!("{root_path}{sub_path}"))
} else {
None
}
@@ -173,7 +173,7 @@ fn try_get_eth_public_key(
Some(path) => {
let _path = path.clone();
if let Some(sub_path) = parse_eth_sub_path(_path) {
- derive_public_key(&xpub, &format!("m/{}", sub_path)).map_err(|_e| {
+ derive_public_key(&xpub, &format!("m/{sub_path}")).map_err(|_e| {
RustCError::UnexpectedError("unable to derive pubkey".to_string())
})
} else {
@@ -184,7 +184,7 @@ fn try_get_eth_public_key(
}
#[no_mangle]
-pub extern "C" fn eth_parse_bytes_data(
+pub unsafe extern "C" fn eth_parse_bytes_data(
ptr: PtrUR,
xpub: PtrString,
) -> PtrT<TransactionParseResult<DisplayETH>> {
@@ -229,16 +229,13 @@ pub extern "C" fn eth_parse_bytes_data(
}
#[no_mangle]
-pub extern "C" fn eth_parse(
+pub unsafe extern "C" fn eth_parse(
ptr: PtrUR,
xpub: PtrString,
) -> PtrT<TransactionParseResult<DisplayETH>> {
let crypto_eth = extract_ptr_with_type!(ptr, EthSignRequest);
let xpub = recover_c_char(xpub);
- let pubkey = match try_get_eth_public_key(xpub, &crypto_eth) {
- Ok(key) => Some(key),
- Err(e) => None,
- };
+ let pubkey = try_get_eth_public_key(xpub, crypto_eth).ok();
let transaction_type = TransactionType::from(crypto_eth.get_data_type());
match transaction_type {
TransactionType::Legacy => {
@@ -250,7 +247,7 @@ pub extern "C" fn eth_parse(
}
TransactionType::TypedTransaction => {
match crypto_eth.get_sign_data().first() {
- Some(02) => {
+ Some(0x02) => {
//remove envelop
let payload = &crypto_eth.get_sign_data()[1..];
let tx = parse_fee_market_tx(payload, pubkey);
@@ -262,7 +259,7 @@ pub extern "C" fn eth_parse(
}
}
Some(x) => TransactionParseResult::from(RustCError::UnsupportedTransaction(
- format!("ethereum tx type:{}", x),
+ format!("ethereum tx type:{x}"),
))
.c_ptr(),
None => TransactionParseResult::from(EthereumError::InvalidTransaction).c_ptr(),
@@ -276,16 +273,13 @@ pub extern "C" fn eth_parse(
}
#[no_mangle]
-pub extern "C" fn eth_parse_personal_message(
+pub unsafe extern "C" fn eth_parse_personal_message(
ptr: PtrUR,
xpub: PtrString,
) -> PtrT<TransactionParseResult<DisplayETHPersonalMessage>> {
let crypto_eth = extract_ptr_with_type!(ptr, EthSignRequest);
let xpub = recover_c_char(xpub);
- let pubkey = match try_get_eth_public_key(xpub, &crypto_eth) {
- Ok(key) => Some(key),
- Err(e) => None,
- };
+ let pubkey = try_get_eth_public_key(xpub, crypto_eth).ok();
let transaction_type = TransactionType::from(crypto_eth.get_data_type());
match transaction_type {
@@ -305,7 +299,7 @@ pub extern "C" fn eth_parse_personal_message(
}
}
-fn eth_check_batch_tx(
+unsafe fn eth_check_batch_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
length: u32,
@@ -314,7 +308,7 @@ fn eth_check_batch_tx(
return Err(RustCError::InvalidMasterFingerprint);
}
let batch_transaction = extract_ptr_with_type!(ptr, EthBatchSignRequest);
- let mfp = unsafe { core::slice::from_raw_parts(master_fingerprint, 4) };
+ let mfp = extract_array!(master_fingerprint, u8, 4);
let mfp: [u8; 4] = match mfp.try_into() {
Ok(mfp) => mfp,
Err(_) => {
@@ -363,7 +357,7 @@ fn eth_check_batch_tx(
}
#[no_mangle]
-pub extern "C" fn eth_check_then_parse_batch_tx(
+pub unsafe extern "C" fn eth_check_then_parse_batch_tx(
ptr: PtrUR,
master_fingerprint: PtrBytes,
mfp_length: u32,
@@ -381,7 +375,7 @@ pub extern "C" fn eth_check_then_parse_batch_tx(
let mut result = Vec::new();
for request in requests {
let request_type = request.get_data_type();
- let pubkey = match try_get_eth_public_key(xpub.clone(), &request) {
+ let pubkey = match try_get_eth_public_key(xpub.clone(), request) {
Ok(key) => Some(key),
Err(e) => return TransactionParseResult::from(e).c_ptr(),
};
@@ -398,7 +392,7 @@ pub extern "C" fn eth_check_then_parse_batch_tx(
}
TransactionType::TypedTransaction => {
match request.get_sign_data().first() {
- Some(02) => {
+ Some(0x02) => {
//remove envelop
let payload = &request.get_sign_data()[1..];
let tx = parse_fee_market_tx(payload, pubkey);
@@ -409,7 +403,7 @@ pub extern "C" fn eth_check_then_parse_batch_tx(
}
Some(x) => {
return TransactionParseResult::from(RustCError::UnsupportedTransaction(
- format!("ethereum tx type:{}", x),
+ format!("ethereum tx type:{x}"),
))
.c_ptr()
}
@@ -435,22 +429,20 @@ pub extern "C" fn eth_check_then_parse_batch_tx(
.map(|t| DisplayETH::from(t.clone()))
.collect::<Vec<DisplayETH>>();
let display_eth_batch_tx = DisplayETHBatchTx::from(display_result);
- return TransactionParseResult::success(display_eth_batch_tx.c_ptr()).c_ptr();
- }
- Err(e) => {
- return TransactionParseResult::from(e).c_ptr();
+ TransactionParseResult::success(display_eth_batch_tx.c_ptr()).c_ptr()
}
+ Err(e) => TransactionParseResult::from(e).c_ptr(),
}
}
#[no_mangle]
-pub extern "C" fn eth_sign_batch_tx(
+pub unsafe extern "C" fn eth_sign_batch_tx(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
) -> PtrT<UREncodeResult> {
let batch_transaction = extract_ptr_with_type!(ptr, EthBatchSignRequest);
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let mut result = Vec::new();
for request in batch_transaction.get_requests() {
let mut path = match request.get_derivation_path().get_path() {
@@ -458,7 +450,7 @@ pub extern "C" fn eth_sign_batch_tx(
None => return UREncodeResult::from(EthereumError::InvalidTransaction).c_ptr(),
};
if !path.starts_with("m/") {
- path = format!("m/{}", path);
+ path = format!("m/{path}");
}
let signature = match TransactionType::from(request.get_data_type()) {
@@ -471,8 +463,7 @@ pub extern "C" fn eth_sign_batch_tx(
}
Some(x) => {
return UREncodeResult::from(RustCError::UnsupportedTransaction(format!(
- "ethereum tx type: {}",
- x
+ "ethereum tx type: {x}"
)))
.c_ptr();
}
@@ -516,16 +507,13 @@ pub extern "C" fn eth_sign_batch_tx(
}
#[no_mangle]
-pub extern "C" fn eth_parse_typed_data(
+pub unsafe extern "C" fn eth_parse_typed_data(
ptr: PtrUR,
xpub: PtrString,
) -> PtrT<TransactionParseResult<DisplayETHTypedData>> {
let crypto_eth = extract_ptr_with_type!(ptr, EthSignRequest);
let xpub = recover_c_char(xpub);
- let pubkey = match try_get_eth_public_key(xpub, &crypto_eth) {
- Ok(key) => Some(key),
- Err(e) => None,
- };
+ let pubkey = try_get_eth_public_key(xpub, crypto_eth).ok();
let transaction_type = TransactionType::from(crypto_eth.get_data_type());
match transaction_type {
@@ -546,20 +534,20 @@ pub extern "C" fn eth_parse_typed_data(
}
#[no_mangle]
-pub extern "C" fn eth_sign_tx_dynamic(
+pub unsafe extern "C" fn eth_sign_tx_dynamic(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
fragment_length: usize,
) -> PtrT<UREncodeResult> {
let crypto_eth = extract_ptr_with_type!(ptr, EthSignRequest);
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let mut path = match crypto_eth.get_derivation_path().get_path() {
Some(v) => v,
None => return UREncodeResult::from(EthereumError::InvalidTransaction).c_ptr(),
};
if !path.starts_with("m/") {
- path = format!("m/{}", path);
+ path = format!("m/{path}");
}
let signature = match TransactionType::from(crypto_eth.get_data_type()) {
@@ -572,8 +560,7 @@ pub extern "C" fn eth_sign_tx_dynamic(
}
Some(x) => {
return UREncodeResult::from(RustCError::UnsupportedTransaction(format!(
- "ethereum tx type: {}",
- x
+ "ethereum tx type: {x}"
)))
.c_ptr();
}
@@ -610,7 +597,7 @@ pub extern "C" fn eth_sign_tx_dynamic(
}
#[no_mangle]
-pub extern "C" fn eth_sign_tx_bytes(
+pub unsafe extern "C" fn eth_sign_tx_bytes(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -641,8 +628,8 @@ pub extern "C" fn eth_sign_tx_bytes(
let legacy_transaction = LegacyTransaction::try_from(eth_tx).unwrap();
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
- let mfp = unsafe { slice::from_raw_parts(mfp, mfp_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
+ let mfp = extract_array!(mfp, u8, mfp_len as usize);
let signature = app_ethereum::sign_legacy_tx_v2(
legacy_transaction.encode_raw().to_vec(),
@@ -690,13 +677,17 @@ pub extern "C" fn eth_sign_tx_bytes(
}
#[no_mangle]
-pub extern "C" fn eth_sign_tx(ptr: PtrUR, seed: PtrBytes, seed_len: u32) -> PtrT<UREncodeResult> {
+pub unsafe extern "C" fn eth_sign_tx(
+ ptr: PtrUR,
+ seed: PtrBytes,
+ seed_len: u32,
+) -> PtrT<UREncodeResult> {
eth_sign_tx_dynamic(ptr, seed, seed_len, FRAGMENT_MAX_LENGTH_DEFAULT)
}
// _unlimited
#[no_mangle]
-pub extern "C" fn eth_sign_tx_unlimited(
+pub unsafe extern "C" fn eth_sign_tx_unlimited(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
@@ -705,7 +696,7 @@ pub extern "C" fn eth_sign_tx_unlimited(
}
#[no_mangle]
-pub extern "C" fn eth_parse_erc20(
+pub unsafe extern "C" fn eth_parse_erc20(
input: PtrString,
decimal: u32,
) -> PtrT<TransactionParseResult<EthParsedErc20Transaction>> {
@@ -723,7 +714,7 @@ pub extern "C" fn eth_parse_erc20(
}
#[no_mangle]
-pub extern "C" fn eth_parse_erc20_approval(
+pub unsafe extern "C" fn eth_parse_erc20_approval(
input: PtrString,
decimal: u32,
) -> PtrT<Response<EthParsedErc20Approval>> {
diff --git a/rust/rust_c/src/ethereum/structs.rs b/rust/rust_c/src/ethereum/structs.rs
index 0957a96..aa63bf4 100644
--- a/rust/rust_c/src/ethereum/structs.rs
+++ b/rust/rust_c/src/ethereum/structs.rs
@@ -7,7 +7,7 @@ use crate::common::free::Free;
use crate::common::structs::{Response, TransactionParseResult};
use crate::common::types::{Ptr, PtrString, PtrT};
use crate::common::utils::convert_c_char;
-use crate::{check_and_free_ptr, free_str_ptr, free_vec, impl_c_ptr, make_free_method};
+use crate::{free_str_ptr, free_vec, impl_c_ptr, make_free_method};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use app_ethereum::abi::{ContractData, ContractMethodParam};
@@ -145,7 +145,7 @@ pub struct DisplayETHOverview {
impl_c_ptr!(DisplayETHOverview);
impl Free for DisplayETHOverview {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.value);
free_str_ptr!(self.max_txn_fee);
free_str_ptr!(self.gas_price);
@@ -181,7 +181,7 @@ pub struct DisplayETHDetail {
impl_c_ptr!(DisplayETHDetail);
impl Free for DisplayETHDetail {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.value);
free_str_ptr!(self.max_txn_fee);
free_str_ptr!(self.gas_price);
@@ -198,14 +198,12 @@ impl Free for DisplayETHDetail {
}
impl Free for DisplayETH {
- fn free(&self) {
- unsafe {
- let x = Box::from_raw(self.overview);
- x.free();
- free_str_ptr!(self.tx_type);
- let y = Box::from_raw(self.detail);
- y.free();
- }
+ unsafe fn free(&self) {
+ let x = Box::from_raw(self.overview);
+ x.free();
+ free_str_ptr!(self.tx_type);
+ let y = Box::from_raw(self.detail);
+ y.free()
}
}
@@ -285,7 +283,7 @@ impl From<PersonalMessage> for DisplayETHPersonalMessage {
impl_c_ptr!(DisplayETHPersonalMessage);
impl Free for DisplayETHPersonalMessage {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.raw_message);
free_str_ptr!(self.utf8_message);
free_str_ptr!(self.from);
@@ -338,7 +336,7 @@ impl From<TypedData> for DisplayETHTypedData {
impl_c_ptr!(DisplayETHTypedData);
impl Free for DisplayETHTypedData {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.name);
free_str_ptr!(self.version);
free_str_ptr!(self.chain_id);
@@ -398,15 +396,13 @@ impl From<ContractData> for DisplayContractData {
}
impl Free for DisplayContractData {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.method_name);
free_str_ptr!(self.contract_name);
- unsafe {
- let x = Box::from_raw(self.params);
- let v = Vec::from_raw_parts(x.data, x.size, x.cap);
- for x in v {
- x.free()
- }
+ let x = Box::from_raw(self.params);
+ let v = Vec::from_raw_parts(x.data, x.size, x.cap);
+ for x in v {
+ x.free()
}
}
}
@@ -429,7 +425,7 @@ impl From<&ContractMethodParam> for DisplayContractParam {
}
impl Free for DisplayContractParam {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.name);
free_str_ptr!(self.value);
}
@@ -453,7 +449,7 @@ impl From<app_ethereum::erc20::ParsedErc20Transaction> for EthParsedErc20Transac
}
impl Free for EthParsedErc20Transaction {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.to);
free_str_ptr!(self.value);
}
@@ -479,7 +475,7 @@ impl From<app_ethereum::erc20::ParsedErc20Approval> for EthParsedErc20Approval {
}
impl Free for EthParsedErc20Approval {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.spender);
free_str_ptr!(self.value);
}
@@ -499,10 +495,8 @@ impl From<Vec<DisplayETH>> for DisplayETHBatchTx {
}
impl Free for DisplayETHBatchTx {
- fn free(&self) {
- unsafe {
- free_vec!(self.txs);
- }
+ unsafe fn free(&self) {
+ free_vec!(self.txs);
}
}
@@ -537,7 +531,7 @@ impl From<app_ethereum::swap::SwapkitContractData> for DisplaySwapkitContractDat
impl_c_ptr!(DisplaySwapkitContractData);
impl Free for DisplaySwapkitContractData {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.vault);
free_str_ptr!(self.swap_in_asset);
free_str_ptr!(self.swap_in_amount);
diff --git a/rust/rust_c/src/ethereum/util.rs b/rust/rust_c/src/ethereum/util.rs
index 9812c13..1c29908 100644
--- a/rust/rust_c/src/ethereum/util.rs
+++ b/rust/rust_c/src/ethereum/util.rs
@@ -5,7 +5,7 @@ use alloc::string::String;
pub fn convert_wei_to_eth(wei: &str) -> String {
let wei = wei.parse::<f64>().unwrap();
let eth = wei / 1_000_000_000_000_000_000.0;
- format!("{:.6}", eth)
+ format!("{eth:.6}")
}
/// calculate the max_txn_fee = gas_price * gas_limit
@@ -13,5 +13,5 @@ pub fn calculate_max_txn_fee(gase_price: &str, gas_limit: &str) -> String {
let gas_price = gase_price.parse::<f64>().unwrap();
let gas_limit = gas_limit.parse::<f64>().unwrap();
let max_txn_fee = gas_price * gas_limit;
- format!("{:.6}", max_txn_fee)
+ format!("{max_txn_fee:.6}")
}
diff --git a/rust/rust_c/src/iota/mod.rs b/rust/rust_c/src/iota/mod.rs
index 40477c0..e6fe7d3 100644
--- a/rust/rust_c/src/iota/mod.rs
+++ b/rust/rust_c/src/iota/mod.rs
@@ -3,10 +3,11 @@ use crate::common::structs::{TransactionCheckResult, TransactionParseResult};
use crate::common::types::{PtrBytes, PtrString, PtrT, PtrUR};
use crate::common::ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use crate::common::utils::{convert_c_char, recover_c_char};
+use crate::extract_array;
use crate::extract_ptr_with_type;
use crate::sui::get_public_key;
use alloc::vec::Vec;
-use alloc::{format, slice};
+use alloc::{format};
use alloc::{
string::{String, ToString},
vec,
@@ -27,7 +28,9 @@ use ur_registry::traits::RegistryItem;
pub mod structs;
#[no_mangle]
-pub extern "C" fn iota_get_address_from_pubkey(xpub: PtrString) -> *mut SimpleResponse<c_char> {
+pub unsafe extern "C" fn iota_get_address_from_pubkey(
+ xpub: PtrString,
+) -> *mut SimpleResponse<c_char> {
let xpub = recover_c_char(xpub);
match app_iota::address::get_address_from_pubkey(xpub) {
Ok(result) => SimpleResponse::success(convert_c_char(result)).simple_c_ptr(),
@@ -36,7 +39,7 @@ pub extern "C" fn iota_get_address_from_pubkey(xpub: PtrString) -> *mut SimpleRe
}
#[no_mangle]
-pub extern "C" fn iota_parse_intent(
+pub unsafe extern "C" fn iota_parse_intent(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayIotaIntentData>> {
let sign_request = extract_ptr_with_type!(ptr, IotaSignRequest);
@@ -65,7 +68,7 @@ pub extern "C" fn iota_parse_intent(
}
#[no_mangle]
-pub extern "C" fn iota_parse_sign_message_hash(
+pub unsafe extern "C" fn iota_parse_sign_message_hash(
ptr: PtrUR,
) -> PtrT<TransactionParseResult<DisplayIotaSignMessageHash>> {
let sign_hash_request = extract_ptr_with_type!(ptr, IotaSignHashRequest);
@@ -86,12 +89,12 @@ pub extern "C" fn iota_parse_sign_message_hash(
}
#[no_mangle]
-pub extern "C" fn iota_sign_hash(
+pub unsafe extern "C" fn iota_sign_hash(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
) -> PtrT<UREncodeResult> {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let sign_request = extract_ptr_with_type!(ptr, IotaSignHashRequest);
let hash = sign_request.get_message_hash();
let path = match sign_request.get_derivation_paths()[0].get_path() {
@@ -129,12 +132,12 @@ pub extern "C" fn iota_sign_hash(
}
#[no_mangle]
-pub extern "C" fn iota_sign_intent(
+pub unsafe extern "C" fn iota_sign_intent(
ptr: PtrUR,
seed: PtrBytes,
seed_len: u32,
) -> PtrT<UREncodeResult> {
- let seed = unsafe { slice::from_raw_parts(seed, seed_len as usize) };
+ let seed = extract_array!(seed, u8, seed_len as usize);
let sign_request = extract_ptr_with_type!(ptr, IotaSignRequest);
let sign_data = sign_request.get_intent_message();
let path = match sign_request.get_derivation_paths()[0].get_path() {
diff --git a/rust/rust_c/src/iota/structs.rs b/rust/rust_c/src/iota/structs.rs
index bc6bd0f..7a3ef10 100644
--- a/rust/rust_c/src/iota/structs.rs
+++ b/rust/rust_c/src/iota/structs.rs
@@ -16,7 +16,7 @@ use crate::common::structs::TransactionParseResult;
use crate::common::types::{Ptr, PtrString, PtrT};
use crate::common::utils::convert_c_char;
use crate::{
- check_and_free_ptr, free_str_ptr, free_vec, impl_c_ptr, impl_c_ptrs, make_free_method,
+ free_str_ptr, free_vec, impl_c_ptr, impl_c_ptrs, make_free_method,
};
use app_ethereum::address::checksum_address;
use app_sui::Intent;
@@ -147,9 +147,9 @@ fn extract_transaction_params(
let max_amount = amounts.iter().max().unwrap_or(&0);
let min_amount = amounts.iter().min().unwrap_or(&0);
let net_amount = max_amount - min_amount;
- convert_c_char(format!("{} IOTA", net_amount as f64 / 1000_000_000.0))
+ convert_c_char(format!("{} IOTA", net_amount as f64 / 1_000_000_000.0))
} else if amounts.len() == 1 {
- convert_c_char(format!("{} IOTA", amounts[0] as f64 / 1000_000_000.0))
+ convert_c_char(format!("{} IOTA", amounts[0] as f64 / 1_000_000_000.0))
} else {
let has_transfer_gas_coin = commands.iter().any(|command| {
if let Command::TransferObjects(objects, target) = command {
@@ -249,7 +249,7 @@ impl DisplayIotaSignMessageHash {
impl_c_ptr!(DisplayIotaSignMessageHash);
impl Free for DisplayIotaSignMessageHash {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.network);
free_str_ptr!(self.path);
free_str_ptr!(self.message);
@@ -260,7 +260,7 @@ impl Free for DisplayIotaSignMessageHash {
make_free_method!(DisplayIotaSignMessageHash);
impl Free for DisplayIotaIntentData {
- fn free(&self) {
+ unsafe fn free(&self) {
free_str_ptr!(self.network);
free_str_ptr!(self.sender);
free_str_ptr!(self.recipient);
diff --git a/rust/rust_c/src/monero/mod.rs b/rust/rust_c/src/monero/mod.rs
index 1ff2cae..00bc1b7 100644
--- a/rust/rust_c/src/monero/mod.rs
+++ b/rust/rust_c/src/monero/mod.rs
@@ -5,7 +5,6 @@ use crate::common::errors::RustCError;
use crate::common::structs::{SimpleResponse, TransactionCheckResult, TransactionParseResult};
use crate::common::ur::{UREncodeResult, FRAGMENT_MAX_LENGTH_DEFAULT};
use alloc::boxed::Box;
-use alloc::slice;
use alloc::string::ToString;
use app_monero::address::Address;
use app_monero::key::Why this scored 34/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.