From 2e3dcf50bd179b1a888f8b320144429b23bb7ad6 Mon Sep 17 00:00:00 2001 From: trantorian <114066155+Trantorian1@users.noreply.github.com> Date: Wed, 9 Oct 2024 18:11:26 +0200 Subject: [PATCH] feat(zeroize): added zeorizing to `Felt` This is feature-gated behind the `zeroing` flag --- crates/starknet-types-core/Cargo.toml | 7 +++++-- crates/starknet-types-core/src/felt/mod.rs | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/starknet-types-core/Cargo.toml b/crates/starknet-types-core/Cargo.toml index 70946ea..55476ec 100644 --- a/crates/starknet-types-core/Cargo.toml +++ b/crates/starknet-types-core/Cargo.toml @@ -24,9 +24,10 @@ serde = { version = "1", optional = true, default-features = false, features = [ lambdaworks-crypto = { version = "0.10.0", default-features = false, optional = true } parity-scale-codec = { version = "3.6", default-features = false, optional = true } lazy_static = { version = "1.5", default-features = false, optional = true } +zeroize = { version = "1.8.1", default-features = false, optional = true } [features] -default = ["std", "serde", "curve", "num-traits"] +default = ["std", "serde", "curve", "num-traits", "zeroing"] std = [ "lambdaworks-math/std", "num-traits/std", @@ -34,8 +35,9 @@ std = [ "num-integer/std", "serde?/std", "lambdaworks-crypto?/std", + "zeroize?/std", ] -alloc = [] +alloc = ["zeroize?/alloc"] curve = [] hash = ["dep:lambdaworks-crypto"] arbitrary = ["std", "dep:arbitrary"] @@ -44,6 +46,7 @@ serde = ["alloc", "dep:serde"] prime-bigint = ["dep:lazy_static"] num-traits = [] papyrus-serialization = ["std"] +zeroing = ["zeroize"] [dev-dependencies] proptest = "1.5" diff --git a/crates/starknet-types-core/src/felt/mod.rs b/crates/starknet-types-core/src/felt/mod.rs index 11d99b9..04b9284 100644 --- a/crates/starknet-types-core/src/felt/mod.rs +++ b/crates/starknet-types-core/src/felt/mod.rs @@ -1062,6 +1062,18 @@ mod errors { } } +mod zeroing { + use super::*; + + #[cfg(feature = "zeroing")] + impl zeroize::Zeroize for Felt { + fn zeroize(&mut self) { + core::mem::take(self); + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); + } + } +} + #[cfg(test)] mod test { use super::alloc::{format, string::String, vec::Vec}; @@ -1844,4 +1856,14 @@ mod test { assert_eq!(Felt::from_bytes_be(&bytes), d); } } + + #[cfg(feature = "zeroing")] + #[test] + fn zeroing_felt() { + use zeroize::Zeroize; + + let mut felt = Felt::from_hex_unchecked("0x01"); + felt.zeroize(); + assert_eq!(felt, Felt::ZERO); + } }