Skip to content

Commit

Permalink
Move PRNG functions to a new Prng module
Browse files Browse the repository at this point in the history
These functions  do not provide cryptographically strong randomness of the sort cryptographic applications need. Therefore they should not be in the crypto module.
  • Loading branch information
masonforest committed Sep 9, 2023
1 parent 79cb165 commit 2121193
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 93 deletions.
32 changes: 1 addition & 31 deletions soroban-sdk/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Crypto contains functions for cryptographic functions.
use crate::{
env::internal, unwrap::UnwrapInfallible, Bytes, BytesN, Env, EnvBase, IntoVal, TryIntoVal, Val,
Vec,
env::internal, unwrap::UnwrapInfallible, Bytes, BytesN, Env, EnvBase,
};

/// Crypto provides access to cryptographic functions.
Expand All @@ -26,35 +25,6 @@ impl Crypto {
unsafe { BytesN::unchecked_new(env.clone(), bin) }
}

// Reseeds the pseudorandom number generator (PRNG) with the provided `seed` value.
pub fn prng_reseed(&self, seed: &Bytes) {
let env = self.env();
env.check_same_env(seed.env());
internal::Env::prng_reseed(env, seed.into()).unwrap_infallible();
}

// Returns a random u64 in the range between `lower` and `upper` inclusive.
pub fn u64_in_inclusive_range(&self, lower: u64, upper: u64) -> u64 {
let env = self.env();
internal::Env::prng_u64_in_inclusive_range(env, lower.into(), upper.into())
.unwrap_infallible()
.into()
}

// Shuffles a given vector v using the Fisher-Yates algorithm.
pub fn vec_shuffle<V>(&self, v: V) -> Vec<Val>
where
V: IntoVal<Env, Vec<Val>>,
{
let env = self.env();
let v_val = v.into_val(env);
env.check_same_env(v_val.env());

internal::Env::prng_vec_shuffle(env, v_val.to_object())
.unwrap_infallible()
.try_into_val(env)
.unwrap_infallible()
}
/// Verifies an ed25519 signature.
///
/// The signature is verified as a valid signature of the message by the
Expand Down
10 changes: 8 additions & 2 deletions soroban-sdk/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ use crate::auth::InvokerContractAuthEntry;
use crate::unwrap::UnwrapInfallible;
use crate::unwrap::UnwrapOptimized;
use crate::{
crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logs::Logs, storage::Storage,
Address, Vec,
crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logs::Logs, prng::Prng,
storage::Storage, Address, Vec,
};
use internal::{
AddressObject, Bool, BytesObject, DurationObject, I128Object, I256Object, I256Val, I64Object,
Expand Down Expand Up @@ -300,6 +300,12 @@ impl Env {
Crypto::new(self)
}

/// Get a [Prng] for accessing the current pseudo-random functions.
#[inline(always)]
pub fn prng(&self) -> Prng {
Prng::new(self)
}

/// Get the Address object corresponding to the current executing contract.
pub fn current_contract_address(&self) -> Address {
let address = internal::Env::get_current_contract_address(self).unwrap_infallible();
Expand Down
1 change: 1 addition & 0 deletions soroban-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,7 @@ pub mod iter;
pub mod ledger;
pub mod logs;
mod map;
pub mod prng;
pub mod storage;
pub mod token;
mod vec;
Expand Down
70 changes: 70 additions & 0 deletions soroban-sdk/src/prng.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! Prng contains functions for pseudo-random functions.
use crate::{
env::internal, unwrap::UnwrapInfallible, Bytes, BytesN, Env, EnvBase, IntoVal, TryIntoVal, Val,
Vec,
};

/// Prng provides access to pseudo-random functions.
pub struct Prng {
env: Env,
}

impl Prng {
pub(crate) fn new(env: &Env) -> Prng {
Prng { env: env.clone() }
}

pub fn env(&self) -> &Env {
&self.env
}

// Reseeds the pseudorandom number generator (PRNG) with the provided `seed` value.
pub fn prng_reseed(&self, seed: &Bytes) {
let env = self.env();
env.check_same_env(seed.env());
internal::Env::prng_reseed(env, seed.into()).unwrap_infallible();
}

// Returns a random u64 in the range between `lower` and `upper` inclusive.
pub fn prng_u64_in_inclusive_range(&self, lower: u64, upper: u64) -> u64 {
let env = self.env();
internal::Env::prng_u64_in_inclusive_range(env, lower.into(), upper.into())
.unwrap_infallible()
.into()
}

// Shuffles a given vector v using the Fisher-Yates algorithm.
pub fn prng_vec_shuffle<V>(&self, v: V) -> Vec<Val>
where
V: IntoVal<Env, Vec<Val>>,
{
let env = self.env();
let v_val = v.into_val(env);
env.check_same_env(v_val.env());

internal::Env::prng_vec_shuffle(env, v_val.to_object())
.unwrap_infallible()
.try_into_val(env)
.unwrap_infallible()
}
/// Verifies an ed25519 signature.
///
/// The signature is verified as a valid signature of the message by the
/// ed25519 public key.
///
/// ### Panics
///
/// If the signature verification fails.
pub fn ed25519_verify(&self, public_key: &BytesN<32>, message: &Bytes, signature: &BytesN<64>) {
let env = self.env();
env.check_same_env(public_key.env());
env.check_same_env(message.env());
env.check_same_env(signature.env());
let _ = internal::Env::verify_sig_ed25519(
env,
public_key.to_object(),
message.to_object(),
signature.to_object(),
);
}
}
1 change: 1 addition & 0 deletions soroban-sdk/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod contractimport;
mod contractimport_with_error;
mod crypto;
mod env;
mod prng;
mod proptest_scval_cmp;
mod proptest_val_cmp;
mod token_client;
Expand Down
63 changes: 3 additions & 60 deletions soroban-sdk/src/tests/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{self as soroban_sdk};
use crate::{bytes, bytesn, vec, Bytes, BytesN, Env, IntoVal, Val, Vec};
use crate::{bytes, bytesn, Bytes, BytesN, Env};
use soroban_sdk::{contract, contractimpl};

#[contract]
Expand All @@ -11,20 +11,6 @@ impl TestCryptoContract {
env.crypto().sha256(&bytes)
}

pub fn prng_reseed(env: Env, bytes: Bytes) {
env.crypto().prng_reseed(&bytes);
}

pub fn u64_in_inclusive_range(env: Env, min: u64, max: u64) -> u64 {
env.crypto().u64_in_inclusive_range(min, max)
}

pub fn vec_shuffle(env: Env, vec: Vec<u32>) -> Vec<Val> {
env.crypto()
.vec_shuffle::<Vec<u32>>(vec.into())
.into_val(&env)
}

pub fn verify_sig_ed25519(
env: Env,
public_key: BytesN<32>,
Expand All @@ -36,24 +22,6 @@ impl TestCryptoContract {
}
}

#[test]
fn test_prng_reseed() {
let env = Env::default();
let contract_id = env.register_contract(None, TestCryptoContract);
env.host().set_base_prng_seed([0; 32]);
let client = TestCryptoContractClient::new(&env, &contract_id);

let seed = bytes!(
&env,
0x0000000000000000000000000000000000000000000000000000000000000001
);
assert_eq!(client.u64_in_inclusive_range(&0, &9), 6);

client.prng_reseed(&seed);

assert_eq!(client.u64_in_inclusive_range(&0, &9), 8);
}

#[test]
fn test_sha256() {
let env = Env::default();
Expand All @@ -71,35 +39,10 @@ fn test_sha256() {
);
}

#[test]
fn test_vec_shuffle() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]);
let contract_id = env.register_contract(None, TestCryptoContract);
let client = TestCryptoContractClient::new(&env, &contract_id);

let vec = vec![&env, 1, 2, 3];

assert_eq!(
client.vec_shuffle(&vec),
vec![&env, Val::from(2u32), Val::from(3u32), Val::from(1u32)]
);
}

#[test]
fn test_u64_in_inclusive_range() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]);
let contract_id = env.register_contract(None, TestCryptoContract);
let client = TestCryptoContractClient::new(&env, &contract_id);

assert_eq!(client.u64_in_inclusive_range(&0, &9), 6);
}

#[test]
fn test_verify_sig_ed25519() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]);
env.host().set_base_prng_seed([0; 32]).unwrap();
let contract_id = env.register_contract(None, TestCryptoContract);
let client = TestCryptoContractClient::new(&env, &contract_id);
// From https://datatracker.ietf.org/doc/html/rfc8032#section-7.1
Expand All @@ -125,7 +68,7 @@ fn test_verify_sig_ed25519() {
#[should_panic]
fn test_verify_sig_ed25519_invalid_sig() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]);
env.host().set_base_prng_seed([0; 32]).unwrap();
let contract_id = env.register_contract(None, TestCryptoContract);
let client = TestCryptoContractClient::new(&env, &contract_id);
// From https://datatracker.ietf.org/doc/html/rfc8032#section-7.1
Expand Down
64 changes: 64 additions & 0 deletions soroban-sdk/src/tests/prng.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use crate::{self as soroban_sdk};
use crate::{bytes, vec, Bytes, Env, Val, Vec};
use soroban_sdk::{contract, contractimpl};

#[contract]
pub struct TestPrngContract;

#[contractimpl]
impl TestPrngContract {
pub fn prng_reseed(env: Env, bytes: Bytes) {
env.prng().prng_reseed(&bytes);
}

pub fn prng_u64_in_inclusive_range(env: Env, min: u64, max: u64) -> u64 {
env.prng().prng_u64_in_inclusive_range(min, max)
}

pub fn prng_vec_shuffle(env: Env, vec: Vec<u32>) -> Vec<Val> {
env.prng().prng_vec_shuffle::<Vec<u32>>(vec.into())
}
}

#[test]
fn test_prng_reseed() {
let env = Env::default();
let contract_id = env.register_contract(None, TestPrngContract);
env.host().set_base_prng_seed([0; 32]).unwrap();
let client = TestPrngContractClient::new(&env, &contract_id);

let seed = bytes!(
&env,
0x0000000000000000000000000000000000000000000000000000000000000001
);
assert_eq!(client.prng_u64_in_inclusive_range(&0, &9), 6);

client.prng_reseed(&seed);

assert_eq!(client.prng_u64_in_inclusive_range(&0, &9), 8);
}

#[test]
fn test_vec_shuffle() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]).unwrap();
let contract_id = env.register_contract(None, TestPrngContract);
let client = TestPrngContractClient::new(&env, &contract_id);

let vec = vec![&env, 1, 2, 3];

assert_eq!(
client.prng_vec_shuffle(&vec),
vec![&env, Val::from(2u32), Val::from(3u32), Val::from(1u32)]
);
}

#[test]
fn test_u64_in_inclusive_range() {
let env = Env::default();
env.host().set_base_prng_seed([0; 32]).unwrap();
let contract_id = env.register_contract(None, TestPrngContract);
let client = TestPrngContractClient::new(&env, &contract_id);

assert_eq!(client.prng_u64_in_inclusive_range(&0, &9), 6);
}

0 comments on commit 2121193

Please sign in to comment.