@bcts/rand 1.0.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +48 -0
- package/README.md +13 -0
- package/dist/index.cjs +506 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +315 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +315 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.iife.js +510 -0
- package/dist/index.iife.js.map +1 -0
- package/dist/index.mjs +478 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +69 -0
- package/src/index.ts +57 -0
- package/src/magnitude.ts +75 -0
- package/src/random-number-generator.ts +279 -0
- package/src/secure-random.ts +97 -0
- package/src/seeded-random.ts +171 -0
- package/src/widening.ts +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Copyright © 2023 Blockchain Commons, LLC
|
|
2
|
+
Copyright © 2025 Leonardo Amoroso Custodio
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without modification,
|
|
5
|
+
are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
8
|
+
this list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
Subject to the terms and conditions of this license, each copyright holder and
|
|
15
|
+
contributor hereby grants to those receiving rights under this license a
|
|
16
|
+
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
17
|
+
(except for failure to satisfy the conditions of this license) patent license to
|
|
18
|
+
make, have made, use, offer to sell, sell, import, and otherwise transfer this
|
|
19
|
+
software, where such license applies only to those patent claims, already
|
|
20
|
+
acquired or hereafter acquired, licensable by such copyright holder or
|
|
21
|
+
contributor that are necessarily infringed by:
|
|
22
|
+
|
|
23
|
+
(a) their Contribution(s) (the licensed copyrights of copyright holders and
|
|
24
|
+
non-copyrightable additions of contributors, in source or binary form)
|
|
25
|
+
alone; or
|
|
26
|
+
|
|
27
|
+
(b) combination of their Contribution(s) with the work of authorship to
|
|
28
|
+
which such Contribution(s) was added by such copyright holder or
|
|
29
|
+
contributor, if, at the time the Contribution is added, such addition causes
|
|
30
|
+
such combination to be necessarily infringed. The patent license shall not
|
|
31
|
+
apply to any other combinations which include the Contribution.
|
|
32
|
+
|
|
33
|
+
Except as expressly stated above, no rights or licenses from any copyright
|
|
34
|
+
holder or contributor is granted under this license, whether expressly, by
|
|
35
|
+
implication, estoppel or otherwise.
|
|
36
|
+
|
|
37
|
+
DISCLAIMER
|
|
38
|
+
|
|
39
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
40
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
41
|
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
42
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
|
|
43
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
44
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
45
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
46
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
|
47
|
+
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
|
48
|
+
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Blockchain Commons Random Number Utilities for TypeScript
|
|
2
|
+
|
|
3
|
+
> Disclaimer: This package is under active development and APIs may change.
|
|
4
|
+
|
|
5
|
+
## Introduction
|
|
6
|
+
|
|
7
|
+
`rand` exposes a uniform API for the random number primitives used in higher-level [Blockchain Commons](https://blockchaincommons.com) projects, including a cryptographically strong random number generator and a deterministic random number generator.
|
|
8
|
+
|
|
9
|
+
The crate also includes several convenience functions for generating secure and deterministic random numbers.
|
|
10
|
+
|
|
11
|
+
## Rust Reference Implementation
|
|
12
|
+
|
|
13
|
+
This TypeScript implementation is based on [bc-rand-rust](https://github.com/BlockchainCommons/bc-rand-rust) **v0.5.0** ([commit](https://github.com/BlockchainCommons/bc-rand-rust/tree/8f53717e35300933e9ca1bc6c51bddc0854cfb9e)).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/widening.ts
|
|
3
|
+
/**
|
|
4
|
+
* Performs wide multiplication for unsigned integers.
|
|
5
|
+
* Returns (low, high) parts of the full-width result.
|
|
6
|
+
*
|
|
7
|
+
* This is equivalent to Rust's widening_mul for unsigned types.
|
|
8
|
+
*/
|
|
9
|
+
function wideMul(a, b, bits) {
|
|
10
|
+
const mask = (1n << BigInt(bits)) - 1n;
|
|
11
|
+
const wide = (a & mask) * (b & mask);
|
|
12
|
+
return [wide & mask, wide >> BigInt(bits)];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Wide multiplication for 8-bit unsigned integers.
|
|
16
|
+
* @param a - First 8-bit value
|
|
17
|
+
* @param b - Second 8-bit value
|
|
18
|
+
* @returns Tuple of (low 8 bits, high 8 bits)
|
|
19
|
+
*/
|
|
20
|
+
function wideMulU8(a, b) {
|
|
21
|
+
const wide = (a & 255) * (b & 255);
|
|
22
|
+
return [wide & 255, wide >> 8 & 255];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Wide multiplication for 16-bit unsigned integers.
|
|
26
|
+
* @param a - First 16-bit value
|
|
27
|
+
* @param b - Second 16-bit value
|
|
28
|
+
* @returns Tuple of (low 16 bits, high 16 bits)
|
|
29
|
+
*/
|
|
30
|
+
function wideMulU16(a, b) {
|
|
31
|
+
const wide = (a & 65535) * (b & 65535);
|
|
32
|
+
return [wide & 65535, wide >>> 16 & 65535];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Wide multiplication for 32-bit unsigned integers.
|
|
36
|
+
* @param a - First 32-bit value
|
|
37
|
+
* @param b - Second 32-bit value
|
|
38
|
+
* @returns Tuple of (low 32 bits, high 32 bits) as bigints
|
|
39
|
+
*/
|
|
40
|
+
function wideMulU32(a, b) {
|
|
41
|
+
const wide = BigInt(a >>> 0) * BigInt(b >>> 0);
|
|
42
|
+
return [wide & 4294967295n, wide >> 32n];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Wide multiplication for 64-bit unsigned integers.
|
|
46
|
+
* @param a - First 64-bit value as bigint
|
|
47
|
+
* @param b - Second 64-bit value as bigint
|
|
48
|
+
* @returns Tuple of (low 64 bits, high 64 bits) as bigints
|
|
49
|
+
*/
|
|
50
|
+
function wideMulU64(a, b) {
|
|
51
|
+
const mask64 = 18446744073709551615n;
|
|
52
|
+
const wide = (a & mask64) * (b & mask64);
|
|
53
|
+
return [wide & mask64, wide >> 64n];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/magnitude.ts
|
|
58
|
+
/**
|
|
59
|
+
* Converts a signed integer to its unsigned magnitude.
|
|
60
|
+
* For positive numbers, returns the number unchanged.
|
|
61
|
+
* For negative numbers, returns the absolute value (wrapping for MIN values).
|
|
62
|
+
*
|
|
63
|
+
* This matches Rust's wrapping_abs() behavior.
|
|
64
|
+
*/
|
|
65
|
+
function toMagnitude(value, bits) {
|
|
66
|
+
switch (bits) {
|
|
67
|
+
case 8: {
|
|
68
|
+
const i8Value = value << 24 >> 24;
|
|
69
|
+
return Math.abs(i8Value) & 255;
|
|
70
|
+
}
|
|
71
|
+
case 16: {
|
|
72
|
+
const i16Value = value << 16 >> 16;
|
|
73
|
+
return Math.abs(i16Value) & 65535;
|
|
74
|
+
}
|
|
75
|
+
case 32: {
|
|
76
|
+
const i32Value = value | 0;
|
|
77
|
+
if (i32Value === -2147483648) return 2147483648;
|
|
78
|
+
return Math.abs(i32Value) >>> 0;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Converts a signed bigint to its unsigned magnitude for 64-bit values.
|
|
84
|
+
*/
|
|
85
|
+
function toMagnitude64(value) {
|
|
86
|
+
const mask = 18446744073709551615n;
|
|
87
|
+
if (value < 0n) return -value & mask;
|
|
88
|
+
return value & mask;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Converts an unsigned magnitude back to a signed value.
|
|
92
|
+
* Simply reinterprets the bits.
|
|
93
|
+
*/
|
|
94
|
+
function fromMagnitude(magnitude, bits) {
|
|
95
|
+
switch (bits) {
|
|
96
|
+
case 8: return magnitude << 24 >> 24;
|
|
97
|
+
case 16: return magnitude << 16 >> 16;
|
|
98
|
+
case 32: return magnitude | 0;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Converts an unsigned 64-bit magnitude back to a signed bigint.
|
|
103
|
+
*/
|
|
104
|
+
function fromMagnitude64(magnitude) {
|
|
105
|
+
const mask = 18446744073709551615n;
|
|
106
|
+
const signBit = 1n << 63n;
|
|
107
|
+
const maskedMag = magnitude & mask;
|
|
108
|
+
if ((maskedMag & signBit) !== 0n) return maskedMag - (1n << 64n);
|
|
109
|
+
return maskedMag;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/random-number-generator.ts
|
|
114
|
+
/**
|
|
115
|
+
* Returns a Uint8Array of random bytes of the given size.
|
|
116
|
+
*/
|
|
117
|
+
function rngRandomData(rng, size) {
|
|
118
|
+
const data = new Uint8Array(size);
|
|
119
|
+
rng.fillRandomData(data);
|
|
120
|
+
return data;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Fills the given Uint8Array with random bytes.
|
|
124
|
+
*/
|
|
125
|
+
function rngFillRandomData(rng, data) {
|
|
126
|
+
rng.fillRandomData(data);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Returns a random value that is less than the given upper bound.
|
|
130
|
+
*
|
|
131
|
+
* Uses Lemire's "nearly divisionless" method for generating random
|
|
132
|
+
* integers in an interval. For a detailed explanation, see:
|
|
133
|
+
* https://arxiv.org/abs/1805.10941
|
|
134
|
+
*
|
|
135
|
+
* @param rng - The random number generator to use
|
|
136
|
+
* @param upperBound - The upper bound for the randomly generated value. Must be non-zero.
|
|
137
|
+
* @returns A random value in the range [0, upperBound). Every value in the range is equally likely.
|
|
138
|
+
*/
|
|
139
|
+
function rngNextWithUpperBound(rng, upperBound) {
|
|
140
|
+
if (upperBound === 0n) throw new Error("upperBound must be non-zero");
|
|
141
|
+
const bitmask = 18446744073709551615n;
|
|
142
|
+
let random = rng.nextU64() & bitmask;
|
|
143
|
+
let m = wideMulU64(random, upperBound);
|
|
144
|
+
if (m[0] < upperBound) {
|
|
145
|
+
const t = (bitmask + 1n - upperBound & bitmask) % upperBound;
|
|
146
|
+
while (m[0] < t) {
|
|
147
|
+
random = rng.nextU64() & bitmask;
|
|
148
|
+
m = wideMulU64(random, upperBound);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return m[1];
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Returns a random 32-bit value that is less than the given upper bound.
|
|
155
|
+
* This matches Rust's behavior when called with u32 type.
|
|
156
|
+
*
|
|
157
|
+
* Uses Lemire's "nearly divisionless" method with 32-bit arithmetic.
|
|
158
|
+
*
|
|
159
|
+
* @param rng - The random number generator to use
|
|
160
|
+
* @param upperBound - The upper bound for the randomly generated value. Must be non-zero and fit in u32.
|
|
161
|
+
* @returns A random u32 value in the range [0, upperBound).
|
|
162
|
+
*/
|
|
163
|
+
function rngNextWithUpperBoundU32(rng, upperBound) {
|
|
164
|
+
if (upperBound === 0) throw new Error("upperBound must be non-zero");
|
|
165
|
+
const upperBoundU32 = upperBound >>> 0;
|
|
166
|
+
const bitmask = 4294967295;
|
|
167
|
+
let random = Number(rng.nextU64() & BigInt(bitmask));
|
|
168
|
+
let m = wideMulU32(random, upperBoundU32);
|
|
169
|
+
if (Number(m[0]) < upperBoundU32) {
|
|
170
|
+
const t = (bitmask + 1 - upperBoundU32 >>> 0) % upperBoundU32;
|
|
171
|
+
while (Number(m[0]) < t) {
|
|
172
|
+
random = Number(rng.nextU64() & BigInt(bitmask));
|
|
173
|
+
m = wideMulU32(random, upperBoundU32);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return Number(m[1]);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Returns a random value within the specified range [start, end) using 32-bit arithmetic.
|
|
180
|
+
* This matches Rust's behavior when called with i32 types.
|
|
181
|
+
*
|
|
182
|
+
* @param rng - The random number generator to use
|
|
183
|
+
* @param start - The lower bound (inclusive) as i32
|
|
184
|
+
* @param end - The upper bound (exclusive) as i32
|
|
185
|
+
* @returns A random i32 value within the bounds
|
|
186
|
+
*/
|
|
187
|
+
function rngNextInRangeI32(rng, start, end) {
|
|
188
|
+
if (start >= end) throw new Error("start must be less than end");
|
|
189
|
+
const startI32 = start | 0;
|
|
190
|
+
const delta = toMagnitude((end | 0) - startI32, 32);
|
|
191
|
+
if (delta === 4294967295) return rng.nextU32() | 0;
|
|
192
|
+
return startI32 + rngNextWithUpperBoundU32(rng, delta) | 0;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Returns a random value within the specified range [start, end).
|
|
196
|
+
*
|
|
197
|
+
* @param rng - The random number generator to use
|
|
198
|
+
* @param start - The lower bound (inclusive)
|
|
199
|
+
* @param end - The upper bound (exclusive)
|
|
200
|
+
* @returns A random value within the bounds of the range
|
|
201
|
+
*/
|
|
202
|
+
function rngNextInRange(rng, start, end) {
|
|
203
|
+
if (start >= end) throw new Error("start must be less than end");
|
|
204
|
+
const delta = end - start;
|
|
205
|
+
if (delta === 18446744073709551615n) return rng.nextU64();
|
|
206
|
+
return start + rngNextWithUpperBound(rng, delta);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Returns a random value within the specified closed range [start, end].
|
|
210
|
+
*
|
|
211
|
+
* @param rng - The random number generator to use
|
|
212
|
+
* @param start - The lower bound (inclusive)
|
|
213
|
+
* @param end - The upper bound (inclusive)
|
|
214
|
+
* @returns A random value within the bounds of the range
|
|
215
|
+
*/
|
|
216
|
+
function rngNextInClosedRange(rng, start, end) {
|
|
217
|
+
if (start > end) throw new Error("start must be less than or equal to end");
|
|
218
|
+
const delta = end - start;
|
|
219
|
+
if (delta === 18446744073709551615n) return rng.nextU64();
|
|
220
|
+
return start + rngNextWithUpperBound(rng, delta + 1n);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Returns a random value within the specified closed range [start, end] for i32 values.
|
|
224
|
+
* Convenience function that handles signed 32-bit integers.
|
|
225
|
+
*
|
|
226
|
+
* @param rng - The random number generator to use
|
|
227
|
+
* @param start - The lower bound (inclusive) as i32
|
|
228
|
+
* @param end - The upper bound (inclusive) as i32
|
|
229
|
+
* @returns A random i32 value within the bounds of the range
|
|
230
|
+
*/
|
|
231
|
+
function rngNextInClosedRangeI32(rng, start, end) {
|
|
232
|
+
if (start > end) throw new Error("start must be less than or equal to end");
|
|
233
|
+
const startI32 = start | 0;
|
|
234
|
+
const delta = toMagnitude((end | 0) - startI32, 32);
|
|
235
|
+
if (delta === 4294967295) return rng.nextU32() | 0;
|
|
236
|
+
return startI32 + rngNextWithUpperBoundU32(rng, delta + 1) | 0;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Returns a fixed-size array of random bytes.
|
|
240
|
+
*
|
|
241
|
+
* @param rng - The random number generator to use
|
|
242
|
+
* @param size - The size of the array to return
|
|
243
|
+
* @returns A Uint8Array of the specified size filled with random bytes
|
|
244
|
+
*/
|
|
245
|
+
function rngRandomArray(rng, size) {
|
|
246
|
+
const data = new Uint8Array(size);
|
|
247
|
+
rng.fillRandomData(data);
|
|
248
|
+
return data;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Returns a random boolean value.
|
|
252
|
+
*
|
|
253
|
+
* @param rng - The random number generator to use
|
|
254
|
+
* @returns A random boolean
|
|
255
|
+
*/
|
|
256
|
+
function rngRandomBool(rng) {
|
|
257
|
+
return (rng.nextU32() & 1) === 0;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Returns a random 32-bit unsigned integer.
|
|
261
|
+
*
|
|
262
|
+
* @param rng - The random number generator to use
|
|
263
|
+
* @returns A random u32 value
|
|
264
|
+
*/
|
|
265
|
+
function rngRandomU32(rng) {
|
|
266
|
+
return rng.nextU32();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
//#endregion
|
|
270
|
+
//#region src/secure-random.ts
|
|
271
|
+
/**
|
|
272
|
+
* Detects the crypto API available in the current environment.
|
|
273
|
+
* Works in both Node.js and browser environments.
|
|
274
|
+
*/
|
|
275
|
+
function getCrypto() {
|
|
276
|
+
if (typeof globalThis !== "undefined" && globalThis.crypto !== null && globalThis.crypto !== void 0) return globalThis.crypto;
|
|
277
|
+
if (typeof globalThis.crypto !== "undefined") return globalThis.crypto;
|
|
278
|
+
throw new Error("No crypto API available in this environment");
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Generate a Uint8Array of cryptographically strong random bytes of the given size.
|
|
282
|
+
*/
|
|
283
|
+
function randomData(size) {
|
|
284
|
+
const data = new Uint8Array(size);
|
|
285
|
+
fillRandomData(data);
|
|
286
|
+
return data;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Fill the given Uint8Array with cryptographically strong random bytes.
|
|
290
|
+
*/
|
|
291
|
+
function fillRandomData(data) {
|
|
292
|
+
getCrypto().getRandomValues(data);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Returns the next cryptographically strong random 64-bit unsigned integer.
|
|
296
|
+
*/
|
|
297
|
+
function nextU64() {
|
|
298
|
+
const data = new Uint8Array(8);
|
|
299
|
+
fillRandomData(data);
|
|
300
|
+
return new DataView(data.buffer).getBigUint64(0, true);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* A random number generator that can be used as a source of
|
|
304
|
+
* cryptographically-strong randomness.
|
|
305
|
+
*
|
|
306
|
+
* Uses the Web Crypto API (crypto.getRandomValues) which is available
|
|
307
|
+
* in both browsers and Node.js >= 15.
|
|
308
|
+
*/
|
|
309
|
+
var SecureRandomNumberGenerator = class {
|
|
310
|
+
/**
|
|
311
|
+
* Returns the next random 32-bit unsigned integer.
|
|
312
|
+
*/
|
|
313
|
+
nextU32() {
|
|
314
|
+
const data = new Uint8Array(4);
|
|
315
|
+
fillRandomData(data);
|
|
316
|
+
return new DataView(data.buffer).getUint32(0, true) >>> 0;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Returns the next random 64-bit unsigned integer as a bigint.
|
|
320
|
+
*/
|
|
321
|
+
nextU64() {
|
|
322
|
+
return nextU64();
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Fills the given Uint8Array with random bytes.
|
|
326
|
+
*/
|
|
327
|
+
fillBytes(dest) {
|
|
328
|
+
fillRandomData(dest);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Returns a Uint8Array of random bytes of the given size.
|
|
332
|
+
*/
|
|
333
|
+
randomData(size) {
|
|
334
|
+
return randomData(size);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Fills the given Uint8Array with random bytes.
|
|
338
|
+
*/
|
|
339
|
+
fillRandomData(data) {
|
|
340
|
+
fillRandomData(data);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/seeded-random.ts
|
|
346
|
+
/**
|
|
347
|
+
* Rotate left for 64-bit bigint
|
|
348
|
+
*/
|
|
349
|
+
function rotl(x, k) {
|
|
350
|
+
return (x << BigInt(k) | x >> BigInt(64 - k)) & 18446744073709551615n;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Xoshiro256** PRNG implementation
|
|
354
|
+
* This is the same algorithm used by rand_xoshiro in Rust
|
|
355
|
+
*/
|
|
356
|
+
function xoshiro256StarStar(state) {
|
|
357
|
+
const mask = 18446744073709551615n;
|
|
358
|
+
const result = rotl(state.s1 * 5n & mask, 7) * 9n & mask;
|
|
359
|
+
const t = state.s1 << 17n & mask;
|
|
360
|
+
state.s2 ^= state.s0;
|
|
361
|
+
state.s3 ^= state.s1;
|
|
362
|
+
state.s1 ^= state.s2;
|
|
363
|
+
state.s0 ^= state.s3;
|
|
364
|
+
state.s2 ^= t;
|
|
365
|
+
state.s3 = rotl(state.s3, 45);
|
|
366
|
+
return result;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* A random number generator that can be used as a source of deterministic
|
|
370
|
+
* pseudo-randomness for testing purposes.
|
|
371
|
+
*
|
|
372
|
+
* Uses the Xoshiro256** algorithm, which is the same algorithm used by
|
|
373
|
+
* rand_xoshiro in Rust. This ensures cross-platform compatibility with
|
|
374
|
+
* the Rust implementation.
|
|
375
|
+
*
|
|
376
|
+
* WARNING: This is NOT cryptographically secure and should only be used
|
|
377
|
+
* for testing purposes.
|
|
378
|
+
*/
|
|
379
|
+
var SeededRandomNumberGenerator = class SeededRandomNumberGenerator {
|
|
380
|
+
state;
|
|
381
|
+
/**
|
|
382
|
+
* Creates a new seeded random number generator.
|
|
383
|
+
*
|
|
384
|
+
* The seed should be a 256-bit value, represented as an array of 4 64-bit
|
|
385
|
+
* integers (as bigints). For the output distribution to look random, the seed
|
|
386
|
+
* should not have any obvious patterns, like all zeroes or all ones.
|
|
387
|
+
*
|
|
388
|
+
* This is not cryptographically secure, and should only be used for
|
|
389
|
+
* testing purposes.
|
|
390
|
+
*
|
|
391
|
+
* @param seed - Array of 4 64-bit unsigned integers as bigints
|
|
392
|
+
*/
|
|
393
|
+
constructor(seed) {
|
|
394
|
+
this.state = {
|
|
395
|
+
s0: seed[0] & 18446744073709551615n,
|
|
396
|
+
s1: seed[1] & 18446744073709551615n,
|
|
397
|
+
s2: seed[2] & 18446744073709551615n,
|
|
398
|
+
s3: seed[3] & 18446744073709551615n
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Creates a new seeded random number generator from a seed array.
|
|
403
|
+
* Convenience method that accepts numbers and converts to bigints.
|
|
404
|
+
*
|
|
405
|
+
* @param seed - Array of 4 64-bit unsigned integers
|
|
406
|
+
*/
|
|
407
|
+
static fromSeed(seed) {
|
|
408
|
+
return new SeededRandomNumberGenerator(seed);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Returns the next random 64-bit unsigned integer as a bigint.
|
|
412
|
+
*/
|
|
413
|
+
nextU64() {
|
|
414
|
+
return xoshiro256StarStar(this.state);
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Returns the next random 32-bit unsigned integer.
|
|
418
|
+
*/
|
|
419
|
+
nextU32() {
|
|
420
|
+
return Number(this.nextU64() & 4294967295n) >>> 0;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Fills the given Uint8Array with random bytes.
|
|
424
|
+
*
|
|
425
|
+
* Note: This implementation matches the Rust behavior exactly -
|
|
426
|
+
* it uses one nextU64() call per byte (taking only the low byte),
|
|
427
|
+
* which matches the Swift version's behavior.
|
|
428
|
+
*/
|
|
429
|
+
fillBytes(dest) {
|
|
430
|
+
for (let i = 0; i < dest.length; i++) dest[i] = Number(this.nextU64() & 255n);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Returns a Uint8Array of random bytes of the given size.
|
|
434
|
+
*
|
|
435
|
+
* This might not be the most efficient implementation,
|
|
436
|
+
* but it works the same as the Swift version.
|
|
437
|
+
*/
|
|
438
|
+
randomData(size) {
|
|
439
|
+
const data = new Uint8Array(size);
|
|
440
|
+
for (let i = 0; i < size; i++) data[i] = Number(this.nextU64() & 255n);
|
|
441
|
+
return data;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Fills the given Uint8Array with random bytes.
|
|
445
|
+
*/
|
|
446
|
+
fillRandomData(data) {
|
|
447
|
+
this.fillBytes(data);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
/**
|
|
451
|
+
* The standard test seed used across all Blockchain Commons implementations.
|
|
452
|
+
*/
|
|
453
|
+
const TEST_SEED = [
|
|
454
|
+
17295166580085024720n,
|
|
455
|
+
422929670265678780n,
|
|
456
|
+
5577237070365765850n,
|
|
457
|
+
7953171132032326923n
|
|
458
|
+
];
|
|
459
|
+
/**
|
|
460
|
+
* Creates a seeded random number generator with a fixed seed.
|
|
461
|
+
* This is useful for reproducible testing across different platforms.
|
|
462
|
+
*/
|
|
463
|
+
function makeFakeRandomNumberGenerator() {
|
|
464
|
+
return new SeededRandomNumberGenerator(TEST_SEED);
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Creates a Uint8Array of random data with a fixed seed.
|
|
468
|
+
* This is useful for reproducible testing.
|
|
469
|
+
*
|
|
470
|
+
* @param size - The number of bytes to generate
|
|
471
|
+
* @returns A Uint8Array of pseudo-random bytes
|
|
472
|
+
*/
|
|
473
|
+
function fakeRandomData(size) {
|
|
474
|
+
return makeFakeRandomNumberGenerator().randomData(size);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
//#endregion
|
|
478
|
+
exports.SecureRandomNumberGenerator = SecureRandomNumberGenerator;
|
|
479
|
+
exports.SeededRandomNumberGenerator = SeededRandomNumberGenerator;
|
|
480
|
+
exports.TEST_SEED = TEST_SEED;
|
|
481
|
+
exports.fakeRandomData = fakeRandomData;
|
|
482
|
+
exports.fillRandomData = fillRandomData;
|
|
483
|
+
exports.fromMagnitude = fromMagnitude;
|
|
484
|
+
exports.fromMagnitude64 = fromMagnitude64;
|
|
485
|
+
exports.makeFakeRandomNumberGenerator = makeFakeRandomNumberGenerator;
|
|
486
|
+
exports.nextU64 = nextU64;
|
|
487
|
+
exports.randomData = randomData;
|
|
488
|
+
exports.rngFillRandomData = rngFillRandomData;
|
|
489
|
+
exports.rngNextInClosedRange = rngNextInClosedRange;
|
|
490
|
+
exports.rngNextInClosedRangeI32 = rngNextInClosedRangeI32;
|
|
491
|
+
exports.rngNextInRange = rngNextInRange;
|
|
492
|
+
exports.rngNextInRangeI32 = rngNextInRangeI32;
|
|
493
|
+
exports.rngNextWithUpperBound = rngNextWithUpperBound;
|
|
494
|
+
exports.rngNextWithUpperBoundU32 = rngNextWithUpperBoundU32;
|
|
495
|
+
exports.rngRandomArray = rngRandomArray;
|
|
496
|
+
exports.rngRandomBool = rngRandomBool;
|
|
497
|
+
exports.rngRandomData = rngRandomData;
|
|
498
|
+
exports.rngRandomU32 = rngRandomU32;
|
|
499
|
+
exports.toMagnitude = toMagnitude;
|
|
500
|
+
exports.toMagnitude64 = toMagnitude64;
|
|
501
|
+
exports.wideMul = wideMul;
|
|
502
|
+
exports.wideMulU16 = wideMulU16;
|
|
503
|
+
exports.wideMulU32 = wideMulU32;
|
|
504
|
+
exports.wideMulU64 = wideMulU64;
|
|
505
|
+
exports.wideMulU8 = wideMulU8;
|
|
506
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TEST_SEED: [bigint, bigint, bigint, bigint]"],"sources":["../src/widening.ts","../src/magnitude.ts","../src/random-number-generator.ts","../src/secure-random.ts","../src/seeded-random.ts"],"sourcesContent":["// The below is so we don't have to use #![feature(bigint_helper_methods)]\n// Ported from bc-rand-rust/src/widening.rs\n\n/**\n * Wide multiplication result type - returns (low, high) parts.\n * For a multiplication of two N-bit values, the result is 2N bits\n * split into two N-bit parts.\n */\nexport type WideMulResult = [bigint, bigint];\n\n/**\n * Performs wide multiplication for unsigned integers.\n * Returns (low, high) parts of the full-width result.\n *\n * This is equivalent to Rust's widening_mul for unsigned types.\n */\nexport function wideMul(a: bigint, b: bigint, bits: number): WideMulResult {\n const mask = (1n << BigInt(bits)) - 1n;\n const wide = (a & mask) * (b & mask);\n const low = wide & mask;\n const high = wide >> BigInt(bits);\n return [low, high];\n}\n\n/**\n * Wide multiplication for 8-bit unsigned integers.\n * @param a - First 8-bit value\n * @param b - Second 8-bit value\n * @returns Tuple of (low 8 bits, high 8 bits)\n */\nexport function wideMulU8(a: number, b: number): [number, number] {\n const wide = (a & 0xff) * (b & 0xff);\n return [wide & 0xff, (wide >> 8) & 0xff];\n}\n\n/**\n * Wide multiplication for 16-bit unsigned integers.\n * @param a - First 16-bit value\n * @param b - Second 16-bit value\n * @returns Tuple of (low 16 bits, high 16 bits)\n */\nexport function wideMulU16(a: number, b: number): [number, number] {\n const wide = (a & 0xffff) * (b & 0xffff);\n return [wide & 0xffff, (wide >>> 16) & 0xffff];\n}\n\n/**\n * Wide multiplication for 32-bit unsigned integers.\n * @param a - First 32-bit value\n * @param b - Second 32-bit value\n * @returns Tuple of (low 32 bits, high 32 bits) as bigints\n */\nexport function wideMulU32(a: number, b: number): [bigint, bigint] {\n const aBig = BigInt(a >>> 0);\n const bBig = BigInt(b >>> 0);\n const wide = aBig * bBig;\n return [wide & 0xffffffffn, wide >> 32n];\n}\n\n/**\n * Wide multiplication for 64-bit unsigned integers.\n * @param a - First 64-bit value as bigint\n * @param b - Second 64-bit value as bigint\n * @returns Tuple of (low 64 bits, high 64 bits) as bigints\n */\nexport function wideMulU64(a: bigint, b: bigint): [bigint, bigint] {\n const mask64 = 0xffffffffffffffffn;\n const wide = (a & mask64) * (b & mask64);\n return [wide & mask64, wide >> 64n];\n}\n","// Ported from bc-rand-rust/src/magnitude.rs\n\n/**\n * Converts a signed integer to its unsigned magnitude.\n * For positive numbers, returns the number unchanged.\n * For negative numbers, returns the absolute value (wrapping for MIN values).\n *\n * This matches Rust's wrapping_abs() behavior.\n */\nexport function toMagnitude(value: number, bits: 8 | 16 | 32): number {\n switch (bits) {\n case 8: {\n // i8 to u8: wrapping_abs\n const i8Value = (value << 24) >> 24; // Sign extend to i8\n return Math.abs(i8Value) & 0xff;\n }\n case 16: {\n // i16 to u16: wrapping_abs\n const i16Value = (value << 16) >> 16; // Sign extend to i16\n return Math.abs(i16Value) & 0xffff;\n }\n case 32: {\n // i32 to u32: wrapping_abs\n const i32Value = value | 0; // Force to i32\n // Handle MIN_VALUE specially (wrapping behavior)\n if (i32Value === -2147483648) {\n return 2147483648; // Returns as positive\n }\n return Math.abs(i32Value) >>> 0; // Convert to unsigned\n }\n }\n}\n\n/**\n * Converts a signed bigint to its unsigned magnitude for 64-bit values.\n */\nexport function toMagnitude64(value: bigint): bigint {\n const mask = 0xffffffffffffffffn;\n // Handle negative values\n if (value < 0n) {\n // Wrapping absolute value\n const absValue = -value;\n return absValue & mask;\n }\n return value & mask;\n}\n\n/**\n * Converts an unsigned magnitude back to a signed value.\n * Simply reinterprets the bits.\n */\nexport function fromMagnitude(magnitude: number, bits: 8 | 16 | 32): number {\n switch (bits) {\n case 8:\n return (magnitude << 24) >> 24; // Sign extend from u8 to i8\n case 16:\n return (magnitude << 16) >> 16; // Sign extend from u16 to i16\n case 32:\n return magnitude | 0; // Reinterpret as i32\n }\n}\n\n/**\n * Converts an unsigned 64-bit magnitude back to a signed bigint.\n */\nexport function fromMagnitude64(magnitude: bigint): bigint {\n const mask = 0xffffffffffffffffn;\n const signBit = 1n << 63n;\n const maskedMag = magnitude & mask;\n if ((maskedMag & signBit) !== 0n) {\n // Negative value - convert from two's complement\n return maskedMag - (1n << 64n);\n }\n return maskedMag;\n}\n","// Ported from bc-rand-rust/src/random_number_generator.rs\n\nimport { wideMulU32, wideMulU64 } from \"./widening.js\";\nimport {\n toMagnitude,\n toMagnitude64 as _toMagnitude64,\n fromMagnitude as _fromMagnitude,\n fromMagnitude64 as _fromMagnitude64,\n} from \"./magnitude.js\";\n\n/**\n * Interface for random number generators.\n * This is the TypeScript equivalent of Rust's RandomNumberGenerator trait\n * which extends RngCore + CryptoRng.\n *\n * This is compatible with the RandomNumberGenerator Swift protocol used\n * in MacOS and iOS, which is important for cross-platform testing.\n */\nexport interface RandomNumberGenerator {\n /**\n * Returns the next random 32-bit unsigned integer.\n */\n nextU32(): number;\n\n /**\n * Returns the next random 64-bit unsigned integer as a bigint.\n */\n nextU64(): bigint;\n\n /**\n * Fills the given Uint8Array with random bytes.\n */\n fillBytes(dest: Uint8Array): void;\n\n /**\n * Returns a Uint8Array of random bytes of the given size.\n */\n randomData(size: number): Uint8Array;\n\n /**\n * Fills the given Uint8Array with random bytes.\n * Alias for fillBytes for compatibility.\n */\n fillRandomData(data: Uint8Array): void;\n}\n\n/**\n * Returns a Uint8Array of random bytes of the given size.\n */\nexport function rngRandomData(rng: RandomNumberGenerator, size: number): Uint8Array {\n const data = new Uint8Array(size);\n rng.fillRandomData(data);\n return data;\n}\n\n/**\n * Fills the given Uint8Array with random bytes.\n */\nexport function rngFillRandomData(rng: RandomNumberGenerator, data: Uint8Array): void {\n rng.fillRandomData(data);\n}\n\n/**\n * Returns a random value that is less than the given upper bound.\n *\n * Uses Lemire's \"nearly divisionless\" method for generating random\n * integers in an interval. For a detailed explanation, see:\n * https://arxiv.org/abs/1805.10941\n *\n * @param rng - The random number generator to use\n * @param upperBound - The upper bound for the randomly generated value. Must be non-zero.\n * @returns A random value in the range [0, upperBound). Every value in the range is equally likely.\n */\nexport function rngNextWithUpperBound(rng: RandomNumberGenerator, upperBound: bigint): bigint {\n if (upperBound === 0n) {\n throw new Error(\"upperBound must be non-zero\");\n }\n\n // We use Lemire's \"nearly divisionless\" method for generating random\n // integers in an interval. For a detailed explanation, see:\n // https://arxiv.org/abs/1805.10941\n\n const bitmask = 0xffffffffffffffffn; // u64 max\n let random = rng.nextU64() & bitmask;\n let m = wideMulU64(random, upperBound);\n\n if (m[0] < upperBound) {\n // t = (0 - upperBound) % upperBound\n const negUpperBound = (bitmask + 1n - upperBound) & bitmask;\n const t = negUpperBound % upperBound;\n while (m[0] < t) {\n random = rng.nextU64() & bitmask;\n m = wideMulU64(random, upperBound);\n }\n }\n\n return m[1];\n}\n\n/**\n * Returns a random 32-bit value that is less than the given upper bound.\n * This matches Rust's behavior when called with u32 type.\n *\n * Uses Lemire's \"nearly divisionless\" method with 32-bit arithmetic.\n *\n * @param rng - The random number generator to use\n * @param upperBound - The upper bound for the randomly generated value. Must be non-zero and fit in u32.\n * @returns A random u32 value in the range [0, upperBound).\n */\nexport function rngNextWithUpperBoundU32(rng: RandomNumberGenerator, upperBound: number): number {\n if (upperBound === 0) {\n throw new Error(\"upperBound must be non-zero\");\n }\n\n const upperBoundU32 = upperBound >>> 0;\n const bitmask = 0xffffffff;\n\n // Get random and mask to 32 bits (matches Rust behavior)\n let random = Number(rng.nextU64() & BigInt(bitmask));\n let m = wideMulU32(random, upperBoundU32);\n\n if (Number(m[0]) < upperBoundU32) {\n // t = (0 - upperBound) % upperBound (wrapping subtraction)\n const t = ((bitmask + 1 - upperBoundU32) >>> 0) % upperBoundU32;\n while (Number(m[0]) < t) {\n random = Number(rng.nextU64() & BigInt(bitmask));\n m = wideMulU32(random, upperBoundU32);\n }\n }\n\n return Number(m[1]);\n}\n\n/**\n * Returns a random value within the specified range [start, end) using 32-bit arithmetic.\n * This matches Rust's behavior when called with i32 types.\n *\n * @param rng - The random number generator to use\n * @param start - The lower bound (inclusive) as i32\n * @param end - The upper bound (exclusive) as i32\n * @returns A random i32 value within the bounds\n */\nexport function rngNextInRangeI32(rng: RandomNumberGenerator, start: number, end: number): number {\n if (start >= end) {\n throw new Error(\"start must be less than end\");\n }\n\n const startI32 = start | 0;\n const endI32 = end | 0;\n const delta = toMagnitude(endI32 - startI32, 32);\n\n if (delta === 0xffffffff) {\n return rng.nextU32() | 0;\n }\n\n const random = rngNextWithUpperBoundU32(rng, delta);\n return (startI32 + random) | 0;\n}\n\n/**\n * Returns a random value within the specified range [start, end).\n *\n * @param rng - The random number generator to use\n * @param start - The lower bound (inclusive)\n * @param end - The upper bound (exclusive)\n * @returns A random value within the bounds of the range\n */\nexport function rngNextInRange(rng: RandomNumberGenerator, start: bigint, end: bigint): bigint {\n if (start >= end) {\n throw new Error(\"start must be less than end\");\n }\n\n const delta = end - start;\n\n // If delta covers the entire range, just return a random value\n const maxU64 = 0xffffffffffffffffn;\n if (delta === maxU64) {\n return rng.nextU64();\n }\n\n const random = rngNextWithUpperBound(rng, delta);\n return start + random;\n}\n\n/**\n * Returns a random value within the specified closed range [start, end].\n *\n * @param rng - The random number generator to use\n * @param start - The lower bound (inclusive)\n * @param end - The upper bound (inclusive)\n * @returns A random value within the bounds of the range\n */\nexport function rngNextInClosedRange(\n rng: RandomNumberGenerator,\n start: bigint,\n end: bigint,\n): bigint {\n if (start > end) {\n throw new Error(\"start must be less than or equal to end\");\n }\n\n const delta = end - start;\n\n // If delta covers the entire range, just return a random value\n const maxU64 = 0xffffffffffffffffn;\n if (delta === maxU64) {\n return rng.nextU64();\n }\n\n const random = rngNextWithUpperBound(rng, delta + 1n);\n return start + random;\n}\n\n/**\n * Returns a random value within the specified closed range [start, end] for i32 values.\n * Convenience function that handles signed 32-bit integers.\n *\n * @param rng - The random number generator to use\n * @param start - The lower bound (inclusive) as i32\n * @param end - The upper bound (inclusive) as i32\n * @returns A random i32 value within the bounds of the range\n */\nexport function rngNextInClosedRangeI32(\n rng: RandomNumberGenerator,\n start: number,\n end: number,\n): number {\n if (start > end) {\n throw new Error(\"start must be less than or equal to end\");\n }\n\n // Convert to i32\n const startI32 = start | 0;\n const endI32 = end | 0;\n\n // Calculate delta as u32 magnitude\n const delta = toMagnitude(endI32 - startI32, 32);\n\n // If delta covers the entire u32 range, just return a random value\n if (delta === 0xffffffff) {\n return rng.nextU32() | 0;\n }\n\n const random = rngNextWithUpperBoundU32(rng, delta + 1);\n return (startI32 + random) | 0;\n}\n\n/**\n * Returns a fixed-size array of random bytes.\n *\n * @param rng - The random number generator to use\n * @param size - The size of the array to return\n * @returns A Uint8Array of the specified size filled with random bytes\n */\nexport function rngRandomArray(rng: RandomNumberGenerator, size: number): Uint8Array {\n const data = new Uint8Array(size);\n rng.fillRandomData(data);\n return data;\n}\n\n/**\n * Returns a random boolean value.\n *\n * @param rng - The random number generator to use\n * @returns A random boolean\n */\nexport function rngRandomBool(rng: RandomNumberGenerator): boolean {\n return (rng.nextU32() & 1) === 0;\n}\n\n/**\n * Returns a random 32-bit unsigned integer.\n *\n * @param rng - The random number generator to use\n * @returns A random u32 value\n */\nexport function rngRandomU32(rng: RandomNumberGenerator): number {\n return rng.nextU32();\n}\n","// Ported from bc-rand-rust/src/secure_random.rs\n\nimport type { RandomNumberGenerator } from \"./random-number-generator.js\";\n\n/**\n * Detects the crypto API available in the current environment.\n * Works in both Node.js and browser environments.\n */\nfunction getCrypto(): Crypto {\n // Browser environment\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto !== null &&\n globalThis.crypto !== undefined\n ) {\n return globalThis.crypto;\n }\n // Node.js environment - globalThis.crypto is also available in Node.js >= 15\n if (typeof globalThis.crypto !== \"undefined\") {\n return globalThis.crypto;\n }\n throw new Error(\"No crypto API available in this environment\");\n}\n\n/**\n * Generate a Uint8Array of cryptographically strong random bytes of the given size.\n */\nexport function randomData(size: number): Uint8Array {\n const data = new Uint8Array(size);\n fillRandomData(data);\n return data;\n}\n\n/**\n * Fill the given Uint8Array with cryptographically strong random bytes.\n */\nexport function fillRandomData(data: Uint8Array): void {\n const crypto = getCrypto();\n crypto.getRandomValues(data);\n}\n\n/**\n * Returns the next cryptographically strong random 64-bit unsigned integer.\n */\nexport function nextU64(): bigint {\n const data = new Uint8Array(8);\n fillRandomData(data);\n const view = new DataView(data.buffer);\n return view.getBigUint64(0, true); // little-endian\n}\n\n/**\n * A random number generator that can be used as a source of\n * cryptographically-strong randomness.\n *\n * Uses the Web Crypto API (crypto.getRandomValues) which is available\n * in both browsers and Node.js >= 15.\n */\nexport class SecureRandomNumberGenerator implements RandomNumberGenerator {\n /**\n * Returns the next random 32-bit unsigned integer.\n */\n nextU32(): number {\n const data = new Uint8Array(4);\n fillRandomData(data);\n const view = new DataView(data.buffer);\n return view.getUint32(0, true) >>> 0; // little-endian, unsigned\n }\n\n /**\n * Returns the next random 64-bit unsigned integer as a bigint.\n */\n nextU64(): bigint {\n return nextU64();\n }\n\n /**\n * Fills the given Uint8Array with random bytes.\n */\n fillBytes(dest: Uint8Array): void {\n fillRandomData(dest);\n }\n\n /**\n * Returns a Uint8Array of random bytes of the given size.\n */\n randomData(size: number): Uint8Array {\n return randomData(size);\n }\n\n /**\n * Fills the given Uint8Array with random bytes.\n */\n fillRandomData(data: Uint8Array): void {\n fillRandomData(data);\n }\n}\n","// Ported from bc-rand-rust/src/seeded_random.rs\n\nimport type { RandomNumberGenerator } from \"./random-number-generator.js\";\n\n/**\n * Xoshiro256** state\n * Based on xoshiro256** 1.0 by David Blackman and Sebastiano Vigna\n * https://prng.di.unimi.it/\n */\ninterface Xoshiro256State {\n s0: bigint;\n s1: bigint;\n s2: bigint;\n s3: bigint;\n}\n\n/**\n * Rotate left for 64-bit bigint\n */\nfunction rotl(x: bigint, k: number): bigint {\n const mask = 0xffffffffffffffffn;\n return ((x << BigInt(k)) | (x >> BigInt(64 - k))) & mask;\n}\n\n/**\n * Xoshiro256** PRNG implementation\n * This is the same algorithm used by rand_xoshiro in Rust\n */\nfunction xoshiro256StarStar(state: Xoshiro256State): bigint {\n const mask = 0xffffffffffffffffn;\n\n // result = rotl(s1 * 5, 7) * 9\n const result = (rotl((state.s1 * 5n) & mask, 7) * 9n) & mask;\n\n // t = s1 << 17\n const t = (state.s1 << 17n) & mask;\n\n // Update state\n state.s2 ^= state.s0;\n state.s3 ^= state.s1;\n state.s1 ^= state.s2;\n state.s0 ^= state.s3;\n\n state.s2 ^= t;\n state.s3 = rotl(state.s3, 45);\n\n return result;\n}\n\n/**\n * A random number generator that can be used as a source of deterministic\n * pseudo-randomness for testing purposes.\n *\n * Uses the Xoshiro256** algorithm, which is the same algorithm used by\n * rand_xoshiro in Rust. This ensures cross-platform compatibility with\n * the Rust implementation.\n *\n * WARNING: This is NOT cryptographically secure and should only be used\n * for testing purposes.\n */\nexport class SeededRandomNumberGenerator implements RandomNumberGenerator {\n private readonly state: Xoshiro256State;\n\n /**\n * Creates a new seeded random number generator.\n *\n * The seed should be a 256-bit value, represented as an array of 4 64-bit\n * integers (as bigints). For the output distribution to look random, the seed\n * should not have any obvious patterns, like all zeroes or all ones.\n *\n * This is not cryptographically secure, and should only be used for\n * testing purposes.\n *\n * @param seed - Array of 4 64-bit unsigned integers as bigints\n */\n constructor(seed: [bigint, bigint, bigint, bigint]) {\n this.state = {\n s0: seed[0] & 0xffffffffffffffffn,\n s1: seed[1] & 0xffffffffffffffffn,\n s2: seed[2] & 0xffffffffffffffffn,\n s3: seed[3] & 0xffffffffffffffffn,\n };\n }\n\n /**\n * Creates a new seeded random number generator from a seed array.\n * Convenience method that accepts numbers and converts to bigints.\n *\n * @param seed - Array of 4 64-bit unsigned integers\n */\n static fromSeed(seed: [bigint, bigint, bigint, bigint]): SeededRandomNumberGenerator {\n return new SeededRandomNumberGenerator(seed);\n }\n\n /**\n * Returns the next random 64-bit unsigned integer as a bigint.\n */\n nextU64(): bigint {\n return xoshiro256StarStar(this.state);\n }\n\n /**\n * Returns the next random 32-bit unsigned integer.\n */\n nextU32(): number {\n return Number(this.nextU64() & 0xffffffffn) >>> 0;\n }\n\n /**\n * Fills the given Uint8Array with random bytes.\n *\n * Note: This implementation matches the Rust behavior exactly -\n * it uses one nextU64() call per byte (taking only the low byte),\n * which matches the Swift version's behavior.\n */\n fillBytes(dest: Uint8Array): void {\n for (let i = 0; i < dest.length; i++) {\n dest[i] = Number(this.nextU64() & 0xffn);\n }\n }\n\n /**\n * Returns a Uint8Array of random bytes of the given size.\n *\n * This might not be the most efficient implementation,\n * but it works the same as the Swift version.\n */\n randomData(size: number): Uint8Array {\n const data = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n data[i] = Number(this.nextU64() & 0xffn);\n }\n return data;\n }\n\n /**\n * Fills the given Uint8Array with random bytes.\n */\n fillRandomData(data: Uint8Array): void {\n this.fillBytes(data);\n }\n}\n\n/**\n * The standard test seed used across all Blockchain Commons implementations.\n */\nexport const TEST_SEED: [bigint, bigint, bigint, bigint] = [\n 17295166580085024720n,\n 422929670265678780n,\n 5577237070365765850n,\n 7953171132032326923n,\n];\n\n/**\n * Creates a seeded random number generator with a fixed seed.\n * This is useful for reproducible testing across different platforms.\n */\nexport function makeFakeRandomNumberGenerator(): SeededRandomNumberGenerator {\n return new SeededRandomNumberGenerator(TEST_SEED);\n}\n\n/**\n * Creates a Uint8Array of random data with a fixed seed.\n * This is useful for reproducible testing.\n *\n * @param size - The number of bytes to generate\n * @returns A Uint8Array of pseudo-random bytes\n */\nexport function fakeRandomData(size: number): Uint8Array {\n return makeFakeRandomNumberGenerator().randomData(size);\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,QAAQ,GAAW,GAAW,MAA6B;CACzE,MAAM,QAAQ,MAAM,OAAO,KAAK,IAAI;CACpC,MAAM,QAAQ,IAAI,SAAS,IAAI;AAG/B,QAAO,CAFK,OAAO,MACN,QAAQ,OAAO,KAAK,CACf;;;;;;;;AASpB,SAAgB,UAAU,GAAW,GAA6B;CAChE,MAAM,QAAQ,IAAI,QAAS,IAAI;AAC/B,QAAO,CAAC,OAAO,KAAO,QAAQ,IAAK,IAAK;;;;;;;;AAS1C,SAAgB,WAAW,GAAW,GAA6B;CACjE,MAAM,QAAQ,IAAI,UAAW,IAAI;AACjC,QAAO,CAAC,OAAO,OAAS,SAAS,KAAM,MAAO;;;;;;;;AAShD,SAA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