Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose PRNG functions #1023

Merged
merged 17 commits into from
Sep 16, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 functions which provide pseudo-randomness.
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
#[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;
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
pub mod storage;
pub mod token;
mod vec;
Expand Down
48 changes: 48 additions & 0 deletions soroban-sdk/src/prng.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! Prng contains functions for pseudo-random functions.
use crate::{
env::internal, unwrap::UnwrapInfallible, Bytes, Env, IntoVal, TryIntoVal, Val,
Vec,
};

/// Prng provides access to pseudo-random functions.
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
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) {
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
let env = self.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 {
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
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>
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
leighmcculloch marked this conversation as resolved.
Show resolved Hide resolved
where
V: IntoVal<Env, Vec<Val>>,
{
let env = self.env();
let v_val = v.into_val(env);

internal::Env::prng_vec_shuffle(env, v_val.to_object())
.unwrap_infallible()
.try_into_val(env)
.unwrap_infallible()
}
}
2 changes: 2 additions & 0 deletions soroban-sdk/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ mod contract_udt_struct;
mod contract_udt_struct_tuple;
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
88 changes: 88 additions & 0 deletions soroban-sdk/src/tests/crypto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use crate::{self as soroban_sdk};
use crate::{bytes, bytesn, Bytes, BytesN, Env};
use soroban_sdk::{contract, contractimpl};

#[contract]
pub struct TestCryptoContract;

#[contractimpl]
impl TestCryptoContract {
pub fn sha256(env: Env, bytes: Bytes) -> BytesN<32> {
env.crypto().sha256(&bytes)
}

pub fn verify_sig_ed25519(
env: Env,
public_key: BytesN<32>,
message: Bytes,
signature: BytesN<64>,
) {
env.crypto()
.ed25519_verify(&public_key, &message, &signature);
}
}

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

let bytes = bytes!(&env, 0x01);

assert_eq!(
client.sha256(&bytes),
bytesn!(
&env,
0x4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a
)
);
}

#[test]
fn test_verify_sig_ed25519() {
let env = Env::default();
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
let public_key: BytesN<32> = bytes!(
&env,
0x3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c
)
.try_into()
.unwrap();
let signature = bytesn!(
&env,
0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00
);
let message = bytes!(&env, 0x72);

assert_eq!(
client.verify_sig_ed25519(&public_key, &message, &signature),
()
);
}

#[test]
#[should_panic]
fn test_verify_sig_ed25519_invalid_sig() {
let env = Env::default();
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
let public_key = bytesn!(
&env,
0x3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c
)
.try_into()
.unwrap();
let signature = bytesn!(
&env,
0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00
);
let message = bytes!(&env, 0x73);

client.verify_sig_ed25519(&public_key, &message, &signature);
}
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_prng_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_prng_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);
}