1
1
use rand_chacha:: ChaChaRng ;
2
- use rand_core:: { RngCore , SeedableRng } ;
2
+ use rand_core:: { CryptoRng , RngCore , SeedableRng } ;
3
3
use sha2:: { Digest , Sha256 } ;
4
4
5
- pub struct Prng {
5
+ use cosmwasm_std:: Env ;
6
+
7
+ pub struct ContractPrng {
6
8
pub rng : ChaChaRng ,
7
9
}
8
10
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
+
10
19
pub fn new ( seed : & [ u8 ] , entropy : & [ u8 ] ) -> Self {
11
20
let mut hasher = Sha256 :: new ( ) ;
12
21
@@ -35,6 +44,26 @@ impl Prng {
35
44
}
36
45
}
37
46
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
+
38
67
#[ cfg( test) ]
39
68
mod tests {
40
69
use super :: * ;
@@ -43,7 +72,7 @@ mod tests {
43
72
/// different random bytes every time it is called.
44
73
#[ test]
45
74
fn test_rng ( ) {
46
- let mut rng = Prng :: new ( b"foo" , b"bar!" ) ;
75
+ let mut rng = ContractPrng :: new ( b"foo" , b"bar!" ) ;
47
76
let r1: [ u8 ; 32 ] = [
48
77
155 , 11 , 21 , 97 , 252 , 65 , 160 , 190 , 100 , 126 , 85 , 251 , 47 , 73 , 160 , 49 , 216 , 182 , 93 ,
49
78
30 , 185 , 67 , 166 , 22 , 34 , 10 , 213 , 112 , 21 , 136 , 49 , 214 ,
@@ -68,7 +97,7 @@ mod tests {
68
97
69
98
#[ test]
70
99
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" ) ;
72
101
73
102
let r1: [ u8 ; 32 ] = [
74
103
114 , 227 , 179 , 76 , 120 , 34 , 236 , 42 , 204 , 27 , 153 , 74 , 44 , 29 , 158 , 162 , 180 , 202 , 165 ,
0 commit comments