soroban_sdk/
prng.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Prng contains a pseudo-random number generator.
//!
//! ## Warning
//!
//! Do not use the PRNG in this module without a clear understanding of two
//! major limitations in the way it is deployed in the Stellar network:
//!
//!   1. The PRNG is seeded with data that is public as soon as each ledger is
//!      nominated. Therefore it **should never be used to generate secrets**.
//!
//!   2. The PRNG is seeded with data that is under the control of validators.
//!      Therefore it **should only be used in applications where the risk of
//!      validator influence is acceptable**.
//!
//! The PRNG in this module is a strong CSPRNG (ChaCha20) and can be manually
//! re-seeded by contracts, in order to support commit/reveal schemes, oracles,
//! or similar advanced types of pseudo-random contract behaviour. Any PRNG is
//! however only as strong as its seed.
//!
//! The network runs in strict consensus, so every node in the network seeds its
//! PRNG with a consensus value, **not a random entropy source**. It uses data
//! that is generally difficult to predict in advance, and generally difficult
//! for network **users** to bias to a specific value: the seed is derived from
//! the overall transaction-set hash and the hash-sorted position number of each
//! transaction within it. But this seed is **not secret** and **not
//! cryptographically hard to bias** if a corrupt **validator** were to choose
//! to do so (similar to the way a corrupt validator can bias overall
//! transaction admission in the network).
//!
//! In other words the network will provide a stronger seed than a contract
//! could likely derive on-chain using any other public data visible to it (eg.
//! better than using a timestamp, ledger number, counter, or a similarly weak
//! seed) but weaker than a contract could acquire using a commit/reveal scheme
//! with an off-chain source of trusted random entropy.
//!
//! You should carefully consider whether these limitations are acceptable for
//! your application before using this module.
//!
//! ## Operation
//!
//! The host has a single hidden "base" PRNG that is seeded by the network. The
//! base PRNG is then used to seed separate, independent "local" PRNGs for each
//! contract invocation. This independence has the following characteristics:
//!
//!   - Contract invocations can only access (use or reseed) their local PRNG.
//!   - Contract invocations cannot influence any other invocation's local PRNG,
//!     except by influencing the other invocation to make a call to its PRNG.
//!   - Contracts cannot influence the base PRNG that seeds local PRNGs, except
//!     by making calls and thereby creating new local PRNGs with new seeds.
//!   - A contract invocation's local PRNG maintains state through the life of
//!     the invocation.
//!   - That state is advanced by each call from the invocation to a PRNG
//!     function in this module.
//!   - A contract invocation's local PRNG is destroyed after the invocation.
//!   - Any re-entry of a contract counts as a separate invocation.
//!
//! ## Testing
//!
//! In local tests, the base PRNG of each host is seeded to zero when the host
//! is constructed, so each contract invocation's local PRNG seed (and all its
//! PRNG-derived calls) will be determined strictly by its order of invocation
//! in the test. Assuming this order is stable, each test run should see stable
//! output from the local PRNG.
use core::ops::{Bound, RangeBounds};

use crate::{
    env::internal,
    unwrap::{UnwrapInfallible, UnwrapOptimized},
    Bytes, BytesN, Env, IntoVal, Vec,
};

/// Prng is a pseudo-random generator.
///
/// # Warning
///
/// **The PRNG is unsuitable for generating secrets or use in applications with
/// low risk tolerance, see the module-level comment.**
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 PRNG with the provided value.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    pub fn seed(&self, seed: Bytes) {
        let env = self.env();
        assert_in_contract!(env);
        internal::Env::prng_reseed(env, seed.into()).unwrap_infallible();
    }

    /// Fills the type with a random value.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    ///
    /// # Examples
    ///
    /// ## `u64`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// let mut value: u64 = 0;
    /// env.prng().fill(&mut value);
    /// assert_eq!(value, 8478755077819529274);
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    ///
    /// ## `[u8]`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// let mut value = [0u8; 32];
    /// env.prng().fill(&mut value);
    /// assert_eq!(
    ///   value,
    ///   [
    ///     58, 248, 248, 38, 210, 150, 170, 117, 122, 110, 9, 101, 244, 57,
    ///     221, 102, 164, 48, 43, 104, 222, 229, 242, 29, 25, 148, 88, 204,
    ///     130, 148, 2, 66
    ///   ],
    /// );
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    pub fn fill<T>(&self, v: &mut T)
    where
        T: Fill + ?Sized,
    {
        v.fill(self);
    }

    /// Returns a random value of the given type.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    ///
    /// # Examples
    ///
    /// ## `u64`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// let value: u64 = env.prng().gen();
    /// assert_eq!(value, 8478755077819529274);
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    ///
    /// ## `[u8; N]`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// let value: [u8; 32] = env.prng().gen();
    /// assert_eq!(
    ///   value,
    ///   [
    ///     58, 248, 248, 38, 210, 150, 170, 117, 122, 110, 9, 101, 244, 57,
    ///     221, 102, 164, 48, 43, 104, 222, 229, 242, 29, 25, 148, 88, 204,
    ///     130, 148, 2, 66
    ///   ],
    /// );
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    pub fn gen<T>(&self) -> T
    where
        T: Gen,
    {
        T::gen(self)
    }

    /// Returns a random value of the given type with the given length.
    ///
    /// # Panics
    ///
    /// If the length is greater than u32::MAX.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    ///
    /// # Examples
    ///
    /// ## `Bytes`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// // Get a value of length 32 bytes.
    /// let value: Bytes = env.prng().gen_len(32);
    /// assert_eq!(value, Bytes::from_slice(
    ///   &env,
    ///   &[
    ///     58, 248, 248, 38, 210, 150, 170, 117, 122, 110, 9, 101, 244, 57,
    ///     221, 102, 164, 48, 43, 104, 222, 229, 242, 29, 25, 148, 88, 204,
    ///     130, 148, 2, 66
    ///   ],
    /// ));
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    pub fn gen_len<T>(&self, len: T::Len) -> T
    where
        T: GenLen,
    {
        T::gen_len(self, len)
    }

    /// Returns a random value of the given type in the range specified.
    ///
    /// # Panics
    ///
    /// If the start of the range is greater than the end.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    ///
    /// # Examples
    ///
    /// ## `u64`
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// // Get a value in the range of 1 to 100, inclusive.
    /// let value: u64 = env.prng().gen_range(1..=100);
    /// assert_eq!(value, 46);
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    pub fn gen_range<T>(&self, r: impl RangeBounds<T::RangeBound>) -> T
    where
        T: GenRange,
    {
        T::gen_range(self, r)
    }

    /// Returns a random u64 in the range specified.
    ///
    /// # Panics
    ///
    /// If the range is empty.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    ///
    /// # Examples
    ///
    /// ```
    /// # use soroban_sdk::{Env, contract, contractimpl, symbol_short, Bytes};
    /// #
    /// # #[contract]
    /// # pub struct Contract;
    /// #
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    /// #     let env = Env::default();
    /// #     let contract_id = env.register(Contract, ());
    /// #     env.as_contract(&contract_id, || {
    /// #         env.prng().seed(Bytes::from_array(&env, &[1; 32]));
    /// // Get a value in the range of 1 to 100, inclusive.
    /// let value = env.prng().u64_in_range(1..=100);
    /// assert_eq!(value, 46);
    /// #     })
    /// # }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    #[deprecated(note = "use env.prng().gen_range(...)")]
    pub fn u64_in_range(&self, r: impl RangeBounds<u64>) -> u64 {
        self.gen_range(r)
    }

    /// Shuffles a value using the Fisher-Yates algorithm.
    ///
    /// # Warning
    ///
    /// **The PRNG is unsuitable for generating secrets or use in applications with
    /// low risk tolerance, see the module-level comment.**
    pub fn shuffle<T>(&self, v: &mut T)
    where
        T: Shuffle,
    {
        v.shuffle(self);
    }
}

impl<T> Shuffle for Vec<T> {
    fn shuffle(&mut self, prng: &Prng) {
        let env = prng.env();
        assert_in_contract!(env);
        let obj = internal::Env::prng_vec_shuffle(env, self.to_object()).unwrap_infallible();
        *self = unsafe { Self::unchecked_new(env.clone(), obj) };
    }
}

/// Implemented by types that support being filled by a Prng.
pub trait Fill {
    /// Fills the given value with the Prng.
    fn fill(&mut self, prng: &Prng);
}

/// Implemented by types that support being generated by a Prng.
pub trait Gen {
    /// Generates a value of the implementing type with the Prng.
    fn gen(prng: &Prng) -> Self;
}

/// Implemented by types that support being generated of specific length by a
/// Prng.
pub trait GenLen {
    type Len;

    /// Generates a value of the given implementing type with length with the
    /// Prng.
    ///
    /// # Panics
    ///
    /// If the length is greater than u32::MAX.
    fn gen_len(prng: &Prng, len: Self::Len) -> Self;
}

/// Implemented by types that support being generated in a specific range by a
/// Prng.
pub trait GenRange {
    type RangeBound;

    /// Generates a value of the implementing type with the Prng in the
    /// specified range.
    ///
    /// # Panics
    ///
    /// If the range is empty.
    fn gen_range(prng: &Prng, r: impl RangeBounds<Self::RangeBound>) -> Self;
}

/// Implemented by types that support being shuffled by a Prng.
pub trait Shuffle {
    /// Shuffles the value with the Prng.
    fn shuffle(&mut self, prng: &Prng);
}

/// Implemented by types that support being shuffled by a Prng.
pub trait ToShuffled {
    type Shuffled;
    fn to_shuffled(&self, prng: &Prng) -> Self::Shuffled;
}

impl<T: Shuffle + Clone> ToShuffled for T {
    type Shuffled = Self;
    fn to_shuffled(&self, prng: &Prng) -> Self {
        let mut copy = self.clone();
        copy.shuffle(prng);
        copy
    }
}

impl Fill for u64 {
    fn fill(&mut self, prng: &Prng) {
        *self = Self::gen(prng);
    }
}

impl Gen for u64 {
    fn gen(prng: &Prng) -> Self {
        let env = prng.env();
        assert_in_contract!(env);
        internal::Env::prng_u64_in_inclusive_range(env, u64::MIN, u64::MAX).unwrap_infallible()
    }
}

impl GenRange for u64 {
    type RangeBound = u64;

    fn gen_range(prng: &Prng, r: impl RangeBounds<Self::RangeBound>) -> Self {
        let env = prng.env();
        assert_in_contract!(env);
        let start_bound = match r.start_bound() {
            Bound::Included(b) => *b,
            Bound::Excluded(b) => *b + 1,
            Bound::Unbounded => u64::MIN,
        };
        let end_bound = match r.end_bound() {
            Bound::Included(b) => *b,
            Bound::Excluded(b) => *b - 1,
            Bound::Unbounded => u64::MAX,
        };
        internal::Env::prng_u64_in_inclusive_range(env, start_bound, end_bound).unwrap_infallible()
    }
}

impl Fill for Bytes {
    /// Fills the Bytes with the Prng.
    ///
    /// # Panics
    ///
    /// If the length of Bytes is greater than u32::MAX in length.
    fn fill(&mut self, prng: &Prng) {
        let env = prng.env();
        assert_in_contract!(env);
        let len: u32 = self.len();
        let obj = internal::Env::prng_bytes_new(env, len.into()).unwrap_infallible();
        *self = unsafe { Bytes::unchecked_new(env.clone(), obj) };
    }
}

impl GenLen for Bytes {
    type Len = u32;
    /// Generates the Bytes with the Prng of the given length.
    fn gen_len(prng: &Prng, len: u32) -> Self {
        let env = prng.env();
        assert_in_contract!(env);
        let obj = internal::Env::prng_bytes_new(env, len.into()).unwrap_infallible();
        unsafe { Bytes::unchecked_new(env.clone(), obj) }
    }
}

impl<const N: usize> Fill for BytesN<N> {
    /// Fills the BytesN with the Prng.
    ///
    /// # Panics
    ///
    /// If the length of BytesN is greater than u32::MAX in length.
    fn fill(&mut self, prng: &Prng) {
        let bytesn = Self::gen(prng);
        *self = bytesn;
    }
}

impl<const N: usize> Gen for BytesN<N> {
    /// Generates the BytesN with the Prng.
    ///
    /// # Panics
    ///
    /// If the length of BytesN is greater than u32::MAX in length.
    fn gen(prng: &Prng) -> Self {
        let env = prng.env();
        assert_in_contract!(env);
        let len: u32 = N.try_into().unwrap_optimized();
        let obj = internal::Env::prng_bytes_new(env, len.into()).unwrap_infallible();
        unsafe { BytesN::unchecked_new(env.clone(), obj) }
    }
}

impl Fill for [u8] {
    /// Fills the slice with the Prng.
    ///
    /// # Panics
    ///
    /// If the slice is greater than u32::MAX in length.
    fn fill(&mut self, prng: &Prng) {
        let env = prng.env();
        assert_in_contract!(env);
        let len: u32 = self.len().try_into().unwrap_optimized();
        let bytes: Bytes = internal::Env::prng_bytes_new(env, len.into())
            .unwrap_infallible()
            .into_val(env);
        bytes.copy_into_slice(self);
    }
}

impl<const N: usize> Fill for [u8; N] {
    /// Fills the array with the Prng.
    ///
    /// # Panics
    ///
    /// If the array is greater than u32::MAX in length.
    fn fill(&mut self, prng: &Prng) {
        let env = prng.env();
        assert_in_contract!(env);
        let len: u32 = N.try_into().unwrap_optimized();
        let bytes: Bytes = internal::Env::prng_bytes_new(env, len.into())
            .unwrap_infallible()
            .into_val(env);
        bytes.copy_into_slice(self);
    }
}

impl<const N: usize> Gen for [u8; N] {
    /// Generates the array with the Prng.
    ///
    /// # Panics
    ///
    /// If the array is greater than u32::MAX in length.
    fn gen(prng: &Prng) -> Self {
        let mut v = [0u8; N];
        v.fill(prng);
        v
    }
}