11use rand_chacha:: ChaChaRng ;
2- use rand_core:: { RngCore , SeedableRng } ;
2+ use rand_core:: { CryptoRng , RngCore , SeedableRng } ;
33use sha2:: { Digest , Sha256 } ;
44
5- pub struct Prng {
5+ use cosmwasm_std:: Env ;
6+
7+ pub struct ContractPrng {
68 pub rng : ChaChaRng ,
79}
810
9- impl Prng {
11+ impl ContractPrng {
12+
13+ pub fn from_env ( env : & Env ) -> Self {
14+ let seed = env. block . random . as_ref ( ) . unwrap ( ) ;
15+
16+ Self :: new ( seed. as_slice ( ) , & [ ] )
17+ }
18+
1019 pub fn new ( seed : & [ u8 ] , entropy : & [ u8 ] ) -> Self {
1120 let mut hasher = Sha256 :: new ( ) ;
1221
@@ -35,6 +44,26 @@ impl Prng {
3544 }
3645}
3746
47+ impl RngCore for ContractPrng {
48+ fn next_u32 ( & mut self ) -> u32 {
49+ self . rng . next_u32 ( )
50+ }
51+
52+ fn next_u64 ( & mut self ) -> u64 {
53+ self . rng . next_u64 ( )
54+ }
55+
56+ fn fill_bytes ( & mut self , dest : & mut [ u8 ] ) {
57+ self . rng . fill_bytes ( dest)
58+ }
59+
60+ fn try_fill_bytes ( & mut self , dest : & mut [ u8 ] ) -> Result < ( ) , rand_core:: Error > {
61+ self . rng . try_fill_bytes ( dest)
62+ }
63+ }
64+
65+ impl CryptoRng for ContractPrng { }
66+
3867#[ cfg( test) ]
3968mod tests {
4069 use super :: * ;
@@ -43,7 +72,7 @@ mod tests {
4372 /// different random bytes every time it is called.
4473 #[ test]
4574 fn test_rng ( ) {
46- let mut rng = Prng :: new ( b"foo" , b"bar!" ) ;
75+ let mut rng = ContractPrng :: new ( b"foo" , b"bar!" ) ;
4776 let r1: [ u8 ; 32 ] = [
4877 155 , 11 , 21 , 97 , 252 , 65 , 160 , 190 , 100 , 126 , 85 , 251 , 47 , 73 , 160 , 49 , 216 , 182 , 93 ,
4978 30 , 185 , 67 , 166 , 22 , 34 , 10 , 213 , 112 , 21 , 136 , 49 , 214 ,
@@ -68,7 +97,7 @@ mod tests {
6897
6998 #[ test]
7099 fn test_rand_bytes_counter ( ) {
71- let mut rng = Prng :: new ( b"foo" , b"bar" ) ;
100+ let mut rng = ContractPrng :: new ( b"foo" , b"bar" ) ;
72101
73102 let r1: [ u8 ; 32 ] = [
74103 114 , 227 , 179 , 76 , 120 , 34 , 236 , 42 , 204 , 27 , 153 , 74 , 44 , 29 , 158 , 162 , 180 , 202 , 165 ,
0 commit comments