quantumrandom 2.0.0__py3-none-any.whl
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.
- quantumrandom/__init__.py +332 -0
- quantumrandom/cmd.py +102 -0
- quantumrandom-2.0.0.dist-info/METADATA +289 -0
- quantumrandom-2.0.0.dist-info/RECORD +8 -0
- quantumrandom-2.0.0.dist-info/WHEEL +5 -0
- quantumrandom-2.0.0.dist-info/entry_points.txt +2 -0
- quantumrandom-2.0.0.dist-info/licenses/LICENSE +19 -0
- quantumrandom-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
# Copyright (c) 2012-2013 Luke Macken <lmacken@redhat.com>
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
# in the Software without restriction, including without limitation the rights
|
|
6
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
# furnished to do so, subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in
|
|
11
|
+
# all copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
# SOFTWARE.
|
|
20
|
+
"""
|
|
21
|
+
A Python interface to the ANU Quantum Numbers (AQN) API.
|
|
22
|
+
|
|
23
|
+
https://quantumnumbers.anu.edu.au
|
|
24
|
+
|
|
25
|
+
Every request needs an API key, which is free to create. Provide it with the
|
|
26
|
+
``QUANTUMRANDOM_API_KEY`` environment variable, :func:`set_api_key`, or the
|
|
27
|
+
``api_key`` argument that the functions here accept.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import binascii
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import random as _random
|
|
34
|
+
import threading
|
|
35
|
+
import time
|
|
36
|
+
from urllib.error import HTTPError
|
|
37
|
+
from urllib.parse import urlencode
|
|
38
|
+
from urllib.request import Request, urlopen
|
|
39
|
+
|
|
40
|
+
VERSION = __version__ = '2.0.0'
|
|
41
|
+
URL = 'https://api.quantumnumbers.anu.edu.au/'
|
|
42
|
+
API_KEY_ENV = 'QUANTUMRANDOM_API_KEY'
|
|
43
|
+
DATA_TYPES = ['uint8', 'uint16', 'hex8', 'hex16']
|
|
44
|
+
MAX_LEN = 1024
|
|
45
|
+
MAX_BLOCK_SIZE = 10
|
|
46
|
+
INT_BITS = 16
|
|
47
|
+
TIMEOUT = 30 # seconds to wait on the API when no timeout is given
|
|
48
|
+
MAX_RETRIES = 3 # times to retry a request that was rate limited
|
|
49
|
+
|
|
50
|
+
_api_key = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class QuantumRandomError(Exception):
|
|
54
|
+
"""Something went wrong fetching data from the ANU Quantum Numbers API"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class APIKeyError(QuantumRandomError):
|
|
58
|
+
"""No API key was provided, or the API rejected it"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RateLimitError(QuantumRandomError):
|
|
62
|
+
"""Requests were made faster than the API key's plan allows"""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class QuotaExceededError(QuantumRandomError):
|
|
66
|
+
"""The API key has used up its request quota"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def set_api_key(api_key):
|
|
70
|
+
"""Set the API key to use when one is not passed in explicitly.
|
|
71
|
+
|
|
72
|
+
This takes precedence over the QUANTUMRANDOM_API_KEY environment variable.
|
|
73
|
+
"""
|
|
74
|
+
global _api_key
|
|
75
|
+
_api_key = api_key
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _resolve_api_key(api_key=None):
|
|
79
|
+
key = api_key or _api_key or os.environ.get(API_KEY_ENV)
|
|
80
|
+
if not key or not key.strip():
|
|
81
|
+
raise APIKeyError(
|
|
82
|
+
"No API key found. Create a free one at "
|
|
83
|
+
"https://quantumnumbers.anu.edu.au and then set the %s "
|
|
84
|
+
"environment variable, call quantumrandom.set_api_key(), or "
|
|
85
|
+
"pass api_key=" % API_KEY_ENV)
|
|
86
|
+
key = key.strip()
|
|
87
|
+
if not (key.isascii() and key.isprintable()) or ' ' in key:
|
|
88
|
+
# Catch this here, as the errors that an unusable HTTP header leads
|
|
89
|
+
# to further down would have the key itself in them.
|
|
90
|
+
raise APIKeyError(
|
|
91
|
+
"The API key is malformed. It should be a single line, without "
|
|
92
|
+
"any spaces.")
|
|
93
|
+
return key
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _describe(http_error):
|
|
97
|
+
"""Return the (error type, message) that the API sent with an error"""
|
|
98
|
+
kind = ''
|
|
99
|
+
if http_error.headers:
|
|
100
|
+
kind = http_error.headers.get('x-amzn-errortype') or ''
|
|
101
|
+
try:
|
|
102
|
+
message = json.loads(http_error.read().decode('utf-8'))['message']
|
|
103
|
+
except Exception:
|
|
104
|
+
message = http_error.reason
|
|
105
|
+
return kind, str(message)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _retry_delay(http_error, attempt):
|
|
109
|
+
"""Seconds to wait before retrying a rate limited request"""
|
|
110
|
+
try:
|
|
111
|
+
return float(http_error.headers.get('Retry-After'))
|
|
112
|
+
except (AttributeError, TypeError, ValueError):
|
|
113
|
+
return float(2 ** (attempt - 1))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _fetch(params, api_key, timeout):
|
|
117
|
+
"""Query the API, returning its decoded JSON response"""
|
|
118
|
+
request = Request(URL + '?' + urlencode(params), headers={
|
|
119
|
+
'x-api-key': api_key,
|
|
120
|
+
'Accept': 'application/json',
|
|
121
|
+
'User-Agent': 'quantumrandom/%s' % VERSION,
|
|
122
|
+
})
|
|
123
|
+
retries = 0
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
with urlopen(request, timeout=timeout) as response:
|
|
127
|
+
return json.loads(response.read().decode('utf-8'))
|
|
128
|
+
except HTTPError as e:
|
|
129
|
+
kind, message = _describe(e)
|
|
130
|
+
if e.code == 403:
|
|
131
|
+
raise APIKeyError(
|
|
132
|
+
"The API rejected the API key (HTTP 403: %s). Check it "
|
|
133
|
+
"at https://quantumnumbers.anu.edu.au" % message) from e
|
|
134
|
+
if e.code == 429:
|
|
135
|
+
# The API sits behind AWS API Gateway, which answers 429 both
|
|
136
|
+
# when the monthly quota runs out ("Limit Exceeded") and when
|
|
137
|
+
# requests arrive too quickly ("Too Many Requests"). Only the
|
|
138
|
+
# latter is worth waiting out.
|
|
139
|
+
if 'limitexceeded' in (kind + message).replace(' ', '').lower():
|
|
140
|
+
raise QuotaExceededError(
|
|
141
|
+
"The API key has used up its request quota "
|
|
142
|
+
"(HTTP 429: %s)" % message) from e
|
|
143
|
+
if retries < MAX_RETRIES:
|
|
144
|
+
retries += 1
|
|
145
|
+
time.sleep(_retry_delay(e, retries))
|
|
146
|
+
continue
|
|
147
|
+
raise RateLimitError(
|
|
148
|
+
"Still rate limited after %d retries (HTTP 429: %s)"
|
|
149
|
+
% (retries, message)) from e
|
|
150
|
+
raise QuantumRandomError(
|
|
151
|
+
"The API returned HTTP %s: %s" % (e.code, message)) from e
|
|
152
|
+
except (OSError, ValueError) as e:
|
|
153
|
+
raise QuantumRandomError(
|
|
154
|
+
"Unable to fetch data from %s: %s" % (URL, e)) from e
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def get_data(data_type='uint16', array_length=1, block_size=1, api_key=None,
|
|
158
|
+
timeout=None):
|
|
159
|
+
"""Fetch data from the ANU Quantum Numbers JSON API.
|
|
160
|
+
|
|
161
|
+
Each call makes one API request and returns a list of ``array_length``
|
|
162
|
+
items. ``block_size`` only applies to the hex data types, where it sets
|
|
163
|
+
how many 8 or 16 bit values make up each item.
|
|
164
|
+
"""
|
|
165
|
+
if data_type not in DATA_TYPES:
|
|
166
|
+
raise ValueError("data_type must be one of %s" % DATA_TYPES)
|
|
167
|
+
if not 1 <= array_length <= MAX_LEN:
|
|
168
|
+
raise ValueError("array_length must be between 1 and %s" % MAX_LEN)
|
|
169
|
+
params = {'length': array_length, 'type': data_type}
|
|
170
|
+
if data_type.startswith('hex'):
|
|
171
|
+
if not 1 <= block_size <= MAX_BLOCK_SIZE:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
"block_size must be between 1 and %s" % MAX_BLOCK_SIZE)
|
|
174
|
+
params['size'] = block_size
|
|
175
|
+
response = _fetch(params, _resolve_api_key(api_key),
|
|
176
|
+
TIMEOUT if timeout is None else timeout)
|
|
177
|
+
if not isinstance(response, dict) or response.get('success') is not True:
|
|
178
|
+
message = None
|
|
179
|
+
if isinstance(response, dict):
|
|
180
|
+
message = response.get('message')
|
|
181
|
+
raise QuantumRandomError(
|
|
182
|
+
"The API request failed: %s" % (message or response))
|
|
183
|
+
data = response.get('data')
|
|
184
|
+
if not isinstance(data, list) or len(data) != array_length:
|
|
185
|
+
raise QuantumRandomError(
|
|
186
|
+
"Asked the API for %d items but got: %r" % (array_length, data))
|
|
187
|
+
return data
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def binary(array_length=MAX_LEN, block_size=MAX_BLOCK_SIZE, api_key=None,
|
|
191
|
+
timeout=None):
|
|
192
|
+
"""Return a chunk of binary data.
|
|
193
|
+
|
|
194
|
+
The chunk is ``array_length * block_size * 2`` bytes long, which by
|
|
195
|
+
default is 20480 bytes: the most that a single API request can return.
|
|
196
|
+
"""
|
|
197
|
+
return binascii.unhexlify(hex(array_length, block_size, api_key, timeout))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def hex(array_length=MAX_LEN, block_size=MAX_BLOCK_SIZE, api_key=None,
|
|
201
|
+
timeout=None):
|
|
202
|
+
"""Return a chunk of hex, twice as long as the equivalent binary()"""
|
|
203
|
+
return ''.join(
|
|
204
|
+
get_data('hex16', array_length, block_size, api_key, timeout))
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def randint(min=0, max=10, generator=None):
|
|
208
|
+
"""Return a random int N such that min <= N <= max.
|
|
209
|
+
|
|
210
|
+
Both ends are included, just like random.randint().
|
|
211
|
+
|
|
212
|
+
Numbers are drawn from a shared buffer that is refilled with one API
|
|
213
|
+
request whenever it runs dry, so that calling this repeatedly does not
|
|
214
|
+
spend a request each time. If a generator of uint16 values is given, such
|
|
215
|
+
as a cached_generator() instance, numbers are taken from that instead.
|
|
216
|
+
"""
|
|
217
|
+
span = max - min + 1
|
|
218
|
+
if span < 1:
|
|
219
|
+
raise ValueError("max (%r) cannot be less than min (%r)" % (max, min))
|
|
220
|
+
if span == 1:
|
|
221
|
+
return min # no need to spend random data on this
|
|
222
|
+
if generator is None:
|
|
223
|
+
return _shared.randint(min, max)
|
|
224
|
+
# Draw just enough bits to cover the range and throw away any value that
|
|
225
|
+
# lands outside of it. This keeps the result uniform, which taking a
|
|
226
|
+
# modulus would not.
|
|
227
|
+
bits = (span - 1).bit_length()
|
|
228
|
+
words = (bits + INT_BITS - 1) // INT_BITS
|
|
229
|
+
while True:
|
|
230
|
+
num = 0
|
|
231
|
+
for _ in range(words):
|
|
232
|
+
num = (num << INT_BITS) | next(generator)
|
|
233
|
+
num >>= words * INT_BITS - bits
|
|
234
|
+
if num < span:
|
|
235
|
+
return min + num
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def uint16(array_length=100, api_key=None, timeout=None):
|
|
239
|
+
"""Return a numpy array of uint16 numbers"""
|
|
240
|
+
import numpy
|
|
241
|
+
return numpy.array(
|
|
242
|
+
get_data('uint16', array_length, api_key=api_key, timeout=timeout),
|
|
243
|
+
dtype=numpy.uint16)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def cached_generator(data_type='uint16', cache_size=1024, block_size=1,
|
|
247
|
+
api_key=None, timeout=None):
|
|
248
|
+
"""Returns numbers. Caches numbers to avoid latency.
|
|
249
|
+
|
|
250
|
+
One API request is made for every ``cache_size`` numbers.
|
|
251
|
+
"""
|
|
252
|
+
while 1:
|
|
253
|
+
for n in get_data(data_type, cache_size, block_size, api_key, timeout):
|
|
254
|
+
yield n
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class QuantumRandom(_random.Random):
|
|
258
|
+
"""A drop-in for random.Random that is backed by quantum random numbers.
|
|
259
|
+
|
|
260
|
+
All of the usual methods are available: random(), randint(), randrange(),
|
|
261
|
+
choice(), shuffle(), sample(), uniform(), gauss(), and so on.
|
|
262
|
+
|
|
263
|
+
Random data is fetched 20480 bytes at a time, the most that one API
|
|
264
|
+
request can return, and handed out from a local buffer. A new request is
|
|
265
|
+
only made once the buffer runs dry, and no byte is ever used twice.
|
|
266
|
+
|
|
267
|
+
Like random.SystemRandom, this does not rely on software state, so
|
|
268
|
+
sequences are not reproducible: seed() does nothing, and getstate() and
|
|
269
|
+
setstate() are not implemented.
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
def __init__(self, *, api_key=None, timeout=None):
|
|
273
|
+
self._api_key = api_key
|
|
274
|
+
self._timeout = timeout
|
|
275
|
+
self._buffer = b''
|
|
276
|
+
self._pos = 0
|
|
277
|
+
self._pid = os.getpid()
|
|
278
|
+
self._lock = threading.Lock()
|
|
279
|
+
super().__init__()
|
|
280
|
+
|
|
281
|
+
def _read(self, n):
|
|
282
|
+
"""Take n bytes from the buffer, refilling it as needed"""
|
|
283
|
+
chunks = []
|
|
284
|
+
with self._lock:
|
|
285
|
+
if self._pid != os.getpid():
|
|
286
|
+
# A forked child must not hand out the same bytes as its
|
|
287
|
+
# parent, so drop what was inherited.
|
|
288
|
+
self._buffer, self._pos, self._pid = b'', 0, os.getpid()
|
|
289
|
+
while n > 0:
|
|
290
|
+
if self._pos >= len(self._buffer):
|
|
291
|
+
self._buffer = binary(api_key=self._api_key,
|
|
292
|
+
timeout=self._timeout)
|
|
293
|
+
self._pos = 0
|
|
294
|
+
chunk = self._buffer[self._pos:self._pos + n]
|
|
295
|
+
self._pos += len(chunk)
|
|
296
|
+
n -= len(chunk)
|
|
297
|
+
chunks.append(chunk)
|
|
298
|
+
return b''.join(chunks)
|
|
299
|
+
|
|
300
|
+
def random(self):
|
|
301
|
+
"""Get the next random number in the range 0.0 <= X < 1.0"""
|
|
302
|
+
return (int.from_bytes(self._read(7), 'big') >> 3) * 2.0 ** -53
|
|
303
|
+
|
|
304
|
+
def getrandbits(self, k):
|
|
305
|
+
"""getrandbits(k) -> x. Generates an int with k random bits."""
|
|
306
|
+
if k < 0:
|
|
307
|
+
raise ValueError('number of bits must be non-negative')
|
|
308
|
+
numbytes = (k + 7) // 8
|
|
309
|
+
x = int.from_bytes(self._read(numbytes), 'big')
|
|
310
|
+
return x >> (numbytes * 8 - k)
|
|
311
|
+
|
|
312
|
+
def randbytes(self, n):
|
|
313
|
+
"""Generate n random bytes"""
|
|
314
|
+
return self._read(n)
|
|
315
|
+
|
|
316
|
+
def seed(self, *args, **kwds):
|
|
317
|
+
"""Does nothing: there is no state to seed"""
|
|
318
|
+
return None
|
|
319
|
+
|
|
320
|
+
def _notimplemented(self, *args, **kwds):
|
|
321
|
+
"""Method should not be called for a quantum random number generator"""
|
|
322
|
+
raise NotImplementedError('Quantum entropy source does not have state.')
|
|
323
|
+
|
|
324
|
+
getstate = setstate = _notimplemented
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
_shared = QuantumRandom()
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
__all__ = ['get_data', 'binary', 'hex', 'uint16', 'cached_generator',
|
|
331
|
+
'randint', 'set_api_key', 'QuantumRandom', 'QuantumRandomError',
|
|
332
|
+
'APIKeyError', 'RateLimitError', 'QuotaExceededError']
|
quantumrandom/cmd.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Copyright (c) 2012-2013 Luke Macken <lmacken@redhat.com>
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
# in the Software without restriction, including without limitation the rights
|
|
6
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
# furnished to do so, subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in
|
|
11
|
+
# all copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
# SOFTWARE.
|
|
20
|
+
"""
|
|
21
|
+
A tool for printing random data from the ANU Quantum Random Number Generator
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import itertools
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
|
|
29
|
+
import quantumrandom
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_args(argv=None):
|
|
33
|
+
parser = argparse.ArgumentParser(
|
|
34
|
+
prog='qrandom',
|
|
35
|
+
description="Print random data from the ANU Quantum Random Number "
|
|
36
|
+
"Generator.",
|
|
37
|
+
epilog="An API key is required. Create a free one at "
|
|
38
|
+
"https://quantumnumbers.anu.edu.au and export it as %s. "
|
|
39
|
+
"Each block of --hex or --binary output costs one API request, "
|
|
40
|
+
"while --int gets thousands of numbers out of each request."
|
|
41
|
+
% quantumrandom.API_KEY_ENV)
|
|
42
|
+
mode = parser.add_mutually_exclusive_group(required=True)
|
|
43
|
+
mode.add_argument('-i', '--int', action='store_true',
|
|
44
|
+
help="print an integer between --min and --max, "
|
|
45
|
+
"inclusive")
|
|
46
|
+
mode.add_argument('-x', '--hex', action='store_true',
|
|
47
|
+
help="print blocks of 40960 hex characters")
|
|
48
|
+
mode.add_argument('-b', '--binary', action='store_true',
|
|
49
|
+
help="write blocks of 20480 raw bytes")
|
|
50
|
+
parser.add_argument('--min', type=int, default=0,
|
|
51
|
+
help="smallest integer to print with --int "
|
|
52
|
+
"(default: %(default)s)")
|
|
53
|
+
parser.add_argument('--max', type=int, default=10,
|
|
54
|
+
help="largest integer to print with --int "
|
|
55
|
+
"(default: %(default)s)")
|
|
56
|
+
parser.add_argument('-c', '--count', type=int, default=1, metavar='N',
|
|
57
|
+
help="how many integers or blocks to output, or 0 to "
|
|
58
|
+
"keep going until interrupted "
|
|
59
|
+
"(default: %(default)s)")
|
|
60
|
+
parser.add_argument('-k', '--api-key', metavar='KEY',
|
|
61
|
+
help="API key to use instead of $%s. Note that other "
|
|
62
|
+
"users on this machine can see command-line "
|
|
63
|
+
"arguments." % quantumrandom.API_KEY_ENV)
|
|
64
|
+
parser.add_argument('--version', action='version',
|
|
65
|
+
version='%(prog)s ' + quantumrandom.VERSION)
|
|
66
|
+
args = parser.parse_args(argv)
|
|
67
|
+
if args.count < 0:
|
|
68
|
+
parser.error("--count cannot be negative")
|
|
69
|
+
if args.max < args.min:
|
|
70
|
+
parser.error("--max cannot be less than --min")
|
|
71
|
+
return args
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main(argv=None):
|
|
75
|
+
args = parse_args(argv)
|
|
76
|
+
if args.api_key:
|
|
77
|
+
quantumrandom.set_api_key(args.api_key)
|
|
78
|
+
try:
|
|
79
|
+
for _ in range(args.count) if args.count else itertools.count():
|
|
80
|
+
if args.int:
|
|
81
|
+
print(quantumrandom.randint(args.min, args.max))
|
|
82
|
+
elif args.hex:
|
|
83
|
+
print(quantumrandom.hex())
|
|
84
|
+
else:
|
|
85
|
+
sys.stdout.buffer.write(quantumrandom.binary())
|
|
86
|
+
sys.stdout.flush()
|
|
87
|
+
except quantumrandom.QuantumRandomError as e:
|
|
88
|
+
sys.stderr.write("qrandom: %s\n" % e)
|
|
89
|
+
return 1
|
|
90
|
+
except KeyboardInterrupt:
|
|
91
|
+
return 130
|
|
92
|
+
except BrokenPipeError:
|
|
93
|
+
# Whatever we were piped into stopped reading. Point stdout at
|
|
94
|
+
# /dev/null so that the interpreter does not complain about not being
|
|
95
|
+
# able to flush it on the way out.
|
|
96
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
97
|
+
return 1
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == '__main__':
|
|
102
|
+
sys.exit(main())
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quantumrandom
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: A Python interface to the ANU Quantum Random Numbers Server
|
|
5
|
+
Author-email: Luke Macken <luke@phorex.org>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/lmacken/quantumrandom
|
|
8
|
+
Project-URL: Issues, https://github.com/lmacken/quantumrandom/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/lmacken/quantumrandom/blob/develop/CHANGELOG.rst
|
|
10
|
+
Keywords: quantum,random,qrng,anu
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
24
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/x-rst
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Provides-Extra: numpy
|
|
29
|
+
Requires-Dist: numpy; extra == "numpy"
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
Tools for utilizing the ANU Quantum Random Numbers Server
|
|
35
|
+
=========================================================
|
|
36
|
+
|
|
37
|
+
.. image:: https://github.com/lmacken/quantumrandom/actions/workflows/tests.yml/badge.svg?branch=develop
|
|
38
|
+
:target: https://github.com/lmacken/quantumrandom/actions/workflows/tests.yml
|
|
39
|
+
.. image:: https://img.shields.io/pypi/v/quantumrandom.svg
|
|
40
|
+
:target: https://pypi.org/project/quantumrandom/
|
|
41
|
+
.. image:: https://img.shields.io/pypi/dm/quantumrandom.svg
|
|
42
|
+
:target: https://pypi.org/project/quantumrandom/
|
|
43
|
+
|
|
44
|
+
This project provides tools for interacting with The ANU Quantum Random
|
|
45
|
+
Number Generator (`quantumnumbers.anu.edu.au
|
|
46
|
+
<https://quantumnumbers.anu.edu.au>`_), which generates true random numbers in
|
|
47
|
+
real time by measuring the quantum fluctuations of the vacuum. It communicates
|
|
48
|
+
with their JSON API and provides a ``qrandom`` command-line tool and a Python
|
|
49
|
+
API, including a drop-in replacement for Python's own ``random.Random``.
|
|
50
|
+
|
|
51
|
+
quantumrandom works on Python 3.9 and newer, and has no dependencies.
|
|
52
|
+
|
|
53
|
+
.. note:: As of version 2.0, quantumrandom uses ANU's new API, which requires
|
|
54
|
+
an API key. The ``qrng.anu.edu.au`` service that earlier versions talked to
|
|
55
|
+
has been shut down, so those versions no longer work. There are a few
|
|
56
|
+
other changes to be aware of when upgrading, which are listed in the
|
|
57
|
+
`changelog
|
|
58
|
+
<https://github.com/lmacken/quantumrandom/blob/develop/CHANGELOG.rst>`_.
|
|
59
|
+
|
|
60
|
+
Installing
|
|
61
|
+
----------
|
|
62
|
+
|
|
63
|
+
::
|
|
64
|
+
|
|
65
|
+
pip install quantumrandom
|
|
66
|
+
|
|
67
|
+
Getting an API key
|
|
68
|
+
------------------
|
|
69
|
+
|
|
70
|
+
Sign up at `quantumnumbers.anu.edu.au <https://quantumnumbers.anu.edu.au>`_ to
|
|
71
|
+
create an API key. At the time of writing the free plan allows 100 requests
|
|
72
|
+
per month, at up to 1 request per second. A paid plan, billed per request
|
|
73
|
+
through the AWS Marketplace, has no monthly limit and allows 100 requests per
|
|
74
|
+
second. See their `pricing <https://quantumnumbers.anu.edu.au/pricing>`_ for
|
|
75
|
+
the details. quantumrandom works the same way with a key from any plan.
|
|
76
|
+
|
|
77
|
+
The easiest way to provide your key is with an environment variable, which
|
|
78
|
+
both the Python API and the ``qrandom`` command will pick up::
|
|
79
|
+
|
|
80
|
+
export QUANTUMRANDOM_API_KEY=your-api-key
|
|
81
|
+
|
|
82
|
+
You can also set it from Python, which takes precedence over the environment::
|
|
83
|
+
|
|
84
|
+
>>> import quantumrandom
|
|
85
|
+
>>> quantumrandom.set_api_key('your-api-key')
|
|
86
|
+
|
|
87
|
+
Lastly, anything that makes API requests accepts an ``api_key`` argument, for
|
|
88
|
+
when you need to use more than one key.
|
|
89
|
+
|
|
90
|
+
Making the most of your requests
|
|
91
|
+
--------------------------------
|
|
92
|
+
|
|
93
|
+
ANU counts requests, not the amount of data that they return, and a single
|
|
94
|
+
request can return anything up to 20480 bytes. quantumrandom is designed
|
|
95
|
+
around this: it asks for as much as it can at a time, and keeps what you have
|
|
96
|
+
not used yet in memory so that it does not need to ask again until it runs
|
|
97
|
+
out. For example, rolling a die a thousand times with
|
|
98
|
+
``quantumrandom.randint(1, 6)`` costs one request, not a thousand.
|
|
99
|
+
|
|
100
|
+
Random data is only ever handed out once, and the buffered data lasts only as
|
|
101
|
+
long as your Python process does.
|
|
102
|
+
|
|
103
|
+
If a request is rate limited it is retried automatically, after a short
|
|
104
|
+
pause, up to ``quantumrandom.MAX_RETRIES`` (3) times.
|
|
105
|
+
|
|
106
|
+
Command-line tool
|
|
107
|
+
-----------------
|
|
108
|
+
|
|
109
|
+
::
|
|
110
|
+
|
|
111
|
+
$ qrandom --int --min 5 --max 15
|
|
112
|
+
7
|
|
113
|
+
$ qrandom --int --min 1 --max 6 --count 5
|
|
114
|
+
5
|
|
115
|
+
6
|
|
116
|
+
4
|
|
117
|
+
4
|
|
118
|
+
1
|
|
119
|
+
$ qrandom --hex
|
|
120
|
+
1dc59fde43b5045120453186d45653dd455bd8e6fc7d8c591f0018fa9261ab2835eb210e8
|
|
121
|
+
e267cf35a54c02ce2a93b3ec448c4c7aa84fdedb61c7b0d87c9e7acf8e9fdadc8d68bcaa5a
|
|
122
|
+
...
|
|
123
|
+
$ qrandom --binary > data
|
|
124
|
+
$ ls -l data
|
|
125
|
+
-rw-r--r-- 1 user user 20480 Nov 24 12:00 data
|
|
126
|
+
|
|
127
|
+
``--hex`` and ``--binary`` output one block of 20480 bytes, at the cost of one
|
|
128
|
+
API request. Use ``--count`` to ask for more than one block (or more than one
|
|
129
|
+
integer), or ``--count 0`` to keep going until interrupted::
|
|
130
|
+
|
|
131
|
+
$ qrandom --binary --count 0 | dd of=data
|
|
132
|
+
|
|
133
|
+
.. warning:: ``--count 0`` makes one API request after another for as long as
|
|
134
|
+
it runs. On the free plan that will use up your month's requests in a
|
|
135
|
+
couple of minutes.
|
|
136
|
+
|
|
137
|
+
Run ``qrandom --help`` for the full list of options.
|
|
138
|
+
|
|
139
|
+
Python API
|
|
140
|
+
----------
|
|
141
|
+
|
|
142
|
+
The simplest way to get going is with ``quantumrandom.QuantumRandom``, which
|
|
143
|
+
is a subclass of `random.Random
|
|
144
|
+
<https://docs.python.org/3/library/random.html>`_ that gets its randomness
|
|
145
|
+
from the quantum random number generator. It supports everything that the
|
|
146
|
+
``random`` module does.
|
|
147
|
+
|
|
148
|
+
::
|
|
149
|
+
|
|
150
|
+
>>> import quantumrandom
|
|
151
|
+
>>> qr = quantumrandom.QuantumRandom()
|
|
152
|
+
>>> qr.random()
|
|
153
|
+
0.794368699495203
|
|
154
|
+
>>> qr.randint(1, 6)
|
|
155
|
+
4
|
|
156
|
+
>>> qr.choice(['heads', 'tails'])
|
|
157
|
+
'tails'
|
|
158
|
+
>>> qr.sample(range(1, 50), 6)
|
|
159
|
+
[12, 49, 36, 43, 31, 25]
|
|
160
|
+
>>> deck = list(range(52))
|
|
161
|
+
>>> qr.shuffle(deck)
|
|
162
|
+
>>> qr.randbytes(16).hex()
|
|
163
|
+
'e686697890ac68804bd8075067edd33d'
|
|
164
|
+
|
|
165
|
+
Just like ``random.SystemRandom``, it has no state to seed or save, so
|
|
166
|
+
sequences cannot be reproduced. Each instance keeps its own buffer of random
|
|
167
|
+
data, and can be given its own ``api_key``.
|
|
168
|
+
|
|
169
|
+
There is also a ``randint`` function at the top level, for convenience. It
|
|
170
|
+
draws from a buffer that is shared by the whole process.
|
|
171
|
+
|
|
172
|
+
::
|
|
173
|
+
|
|
174
|
+
>>> quantumrandom.randint(0, 20)
|
|
175
|
+
5
|
|
176
|
+
|
|
177
|
+
.. note:: As of version 2.0, ``randint(min, max)`` can return ``max``, just
|
|
178
|
+
like ``random.randint`` does. Earlier versions never did.
|
|
179
|
+
|
|
180
|
+
The low-level ``get_data`` function is modelled after the ANU Quantum Random
|
|
181
|
+
Number Generator's JSON API. It makes one request, and returns a list of
|
|
182
|
+
``uint8`` or ``uint16`` integers, or ``hex8`` or ``hex16`` strings.
|
|
183
|
+
|
|
184
|
+
::
|
|
185
|
+
|
|
186
|
+
>>> quantumrandom.get_data()
|
|
187
|
+
[26646]
|
|
188
|
+
>>> quantumrandom.get_data(data_type='uint16', array_length=5)
|
|
189
|
+
[22546, 58383, 55100, 9936, 55159]
|
|
190
|
+
>>> quantumrandom.get_data(data_type='hex8', array_length=3, block_size=2)
|
|
191
|
+
['8350', 'df68', 'ae1f']
|
|
192
|
+
>>> quantumrandom.get_data(data_type='hex16', array_length=2, block_size=3)
|
|
193
|
+
['8ba57d8c7d1e', 'bc54a2eb5a07']
|
|
194
|
+
|
|
195
|
+
The ``array_length`` cannot be larger than ``1024``. The ``block_size`` only
|
|
196
|
+
applies to the hex data types, where it is the number of 8 or 16 bit values
|
|
197
|
+
in each string, and cannot be larger than ``10``.
|
|
198
|
+
|
|
199
|
+
Based on this ``get_data`` function, quantumrandom also provides a few
|
|
200
|
+
higher-level helper functions. Each of these makes one request when called.
|
|
201
|
+
|
|
202
|
+
::
|
|
203
|
+
|
|
204
|
+
>>> quantumrandom.hex()[:10]
|
|
205
|
+
'8272613343'
|
|
206
|
+
>>> len(quantumrandom.binary())
|
|
207
|
+
20480
|
|
208
|
+
>>> quantumrandom.binary(array_length=8, block_size=1)
|
|
209
|
+
b'\x07kE\xbb\x7f\xf8\x12\x83\xd5\xc6\xa2\xd17\x8e\x03\x17'
|
|
210
|
+
>>> quantumrandom.uint16()
|
|
211
|
+
array([24094, 13944, 22109, 22908, 34878, 33797, 47221, 21485, 37930, ...], dtype=uint16)
|
|
212
|
+
|
|
213
|
+
``uint16`` requires `NumPy <https://numpy.org>`_, which you can install along
|
|
214
|
+
with quantumrandom by running ``pip install quantumrandom[numpy]``.
|
|
215
|
+
|
|
216
|
+
``cached_generator`` returns a generator that yields numbers forever, making
|
|
217
|
+
a request for 1024 more each time it runs out. One can be passed to
|
|
218
|
+
``randint`` to have it take its numbers from there instead.
|
|
219
|
+
|
|
220
|
+
::
|
|
221
|
+
|
|
222
|
+
>>> generator = quantumrandom.cached_generator()
|
|
223
|
+
>>> next(generator)
|
|
224
|
+
48013
|
|
225
|
+
>>> quantumrandom.randint(1, 6, generator)
|
|
226
|
+
2
|
|
227
|
+
|
|
228
|
+
Handling errors
|
|
229
|
+
---------------
|
|
230
|
+
|
|
231
|
+
Everything that can go wrong while talking to the API raises a subclass of
|
|
232
|
+
``quantumrandom.QuantumRandomError``:
|
|
233
|
+
|
|
234
|
+
* ``APIKeyError`` if no API key was found, or the API rejected it.
|
|
235
|
+
* ``QuotaExceededError`` if your API key has used up its requests.
|
|
236
|
+
* ``RateLimitError`` if a request was still being rate limited after being
|
|
237
|
+
retried.
|
|
238
|
+
* ``QuantumRandomError`` itself for anything else, such as the API being
|
|
239
|
+
unreachable, timing out (after ``quantumrandom.TIMEOUT`` seconds, 30 by
|
|
240
|
+
default, or the ``timeout`` that you passed in), or returning something
|
|
241
|
+
unexpected.
|
|
242
|
+
|
|
243
|
+
Invalid arguments raise a ``ValueError`` without making a request.
|
|
244
|
+
|
|
245
|
+
What happened to /dev/qrandom?
|
|
246
|
+
------------------------------
|
|
247
|
+
|
|
248
|
+
Earlier versions came with ``qrandom-dev``, which created a ``/dev/qrandom``
|
|
249
|
+
character device that could be used to feed the Linux entropy pool. It was
|
|
250
|
+
removed in version 2.0. The library that it was built upon (cusepy) only ever
|
|
251
|
+
supported Python 2 and is no longer available, and a device that makes API
|
|
252
|
+
requests in the background for as long as something reads from it is a poor
|
|
253
|
+
fit for an API that is metered by the request. If all you need is a stream of
|
|
254
|
+
bytes, ``qrandom --binary`` can be piped into whatever needs it.
|
|
255
|
+
|
|
256
|
+
Development
|
|
257
|
+
-----------
|
|
258
|
+
|
|
259
|
+
::
|
|
260
|
+
|
|
261
|
+
pip install -e .[test,numpy]
|
|
262
|
+
pytest
|
|
263
|
+
|
|
264
|
+
The tests do not use the network or need an API key. One additional test
|
|
265
|
+
makes a single request to the real API, and only runs if you ask it to::
|
|
266
|
+
|
|
267
|
+
QUANTUMRANDOM_LIVE_TEST=1 QUANTUMRANDOM_API_KEY=your-api-key pytest tests/test_live.py
|
|
268
|
+
|
|
269
|
+
Releasing
|
|
270
|
+
---------
|
|
271
|
+
|
|
272
|
+
1. Update ``VERSION`` in ``quantumrandom/__init__.py``, and add the release to
|
|
273
|
+
``CHANGELOG.rst``.
|
|
274
|
+
2. Commit, tag, and push the release. Pushing a tag that starts with a digit
|
|
275
|
+
runs ``.github/workflows/publish.yml``, which builds the distributions and
|
|
276
|
+
publishes them to PyPI::
|
|
277
|
+
|
|
278
|
+
git tag -a 2.0.0 -m "quantumrandom 2.0.0"
|
|
279
|
+
git push origin develop 2.0.0
|
|
280
|
+
|
|
281
|
+
Publishing relies on PyPI's `trusted publishing
|
|
282
|
+
<https://docs.pypi.org/trusted-publishers/>`_, which has to be set up once. On
|
|
283
|
+
PyPI, add a trusted publisher for the project with owner ``lmacken``,
|
|
284
|
+
repository ``quantumrandom``, workflow ``publish.yml``, and environment
|
|
285
|
+
``pypi``.
|
|
286
|
+
|
|
287
|
+
To rehearse a release on TestPyPI first, which is optional, add the same
|
|
288
|
+
publisher there with environment ``testpypi``, and then run the **Publish**
|
|
289
|
+
workflow manually.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
quantumrandom/__init__.py,sha256=5MM_Au-5ko9hYl7CMTppV5tGDsb5o9OA2d2hmQMt3Xc,12882
|
|
2
|
+
quantumrandom/cmd.py,sha256=tdvf-Jzv15dlCPij2pOBO5ioJi9yjdKh_-JhsROb0hs,4545
|
|
3
|
+
quantumrandom-2.0.0.dist-info/licenses/LICENSE,sha256=_BRvW3T6LoA0HO3qUspTg3w9rGGVV5dXnXLB8Ws-jHM,1060
|
|
4
|
+
quantumrandom-2.0.0.dist-info/METADATA,sha256=V2yHCGwqfkSuPGHLboM3wyHsNrUTUfVNm4XPo8RYibo,10915
|
|
5
|
+
quantumrandom-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
quantumrandom-2.0.0.dist-info/entry_points.txt,sha256=BcApLs3gJ_rR2BMZR4hedy_il-pEmqqyYDdpozObG64,51
|
|
7
|
+
quantumrandom-2.0.0.dist-info/top_level.txt,sha256=VLA4YmHU7K1vPe32dliMZl4-YoUjBRGbgYhEh0jQe_Q,14
|
|
8
|
+
quantumrandom-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2012-2026 Luke Macken
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quantumrandom
|