Skip to content

Commit

Permalink
Random ID should beginning with 1 (#1637)
Browse files Browse the repository at this point in the history
* Random ID should beginning with 1

* Make (and) first

* Enforce byte-order to big-endian

* Change MASK to let use native byte order

* Wrap value to 2**53 if 0

* Both MASK and random number using big-endian byte order

* Fix ID generator range error (#1637)
  • Loading branch information
SunFulong committed Apr 13, 2024
1 parent 1a7aaa9 commit f38f16b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
2 changes: 1 addition & 1 deletion autobahn/_version.py
Expand Up @@ -24,6 +24,6 @@
#
###############################################################################

__version__ = '24.4.1'
__version__ = '24.4.2'

__build__ = '00000000-0000000'
10 changes: 5 additions & 5 deletions autobahn/util.py
Expand Up @@ -278,13 +278,13 @@ def __next__(self):
#


# 8 byte mask with 53 LSBs set (WAMP requires IDs from [0, 2**53]
# 8 byte mask with 53 LSBs set (WAMP requires IDs from [1, 2**53]
_WAMP_ID_MASK = struct.unpack(">Q", b"\x00\x1f\xff\xff\xff\xff\xff\xff")[0]


def rid():
"""
Generate a new random integer ID from range **[0, 2**53]**.
Generate a new random integer ID from range **[1, 2**53]**.
The generated ID is uniformly distributed over the whole range, doesn't have
a period (no pseudo-random generator is used) and cryptographically strong.
Expand All @@ -298,13 +298,13 @@ def rid():
:returns: A random integer ID.
:rtype: int
"""
return struct.unpack("@Q", os.urandom(8))[0] & _WAMP_ID_MASK
return struct.unpack(">Q", os.urandom(8))[0] & _WAMP_ID_MASK or 2 ** 53


# noinspection PyShadowingBuiltins
def id():
"""
Generate a new random integer ID from range **[0, 2**53]**.
Generate a new random integer ID from range **[1, 2**53]**.
The generated ID is based on a pseudo-random number generator (Mersenne Twister,
which has a period of 2**19937-1). It is NOT cryptographically strong, and
Expand All @@ -319,7 +319,7 @@ def id():
:returns: A random integer ID.
:rtype: int
"""
return random.randint(0, 9007199254740992)
return random.randint(1, 9007199254740992)


def newid(length=16):
Expand Down
5 changes: 5 additions & 0 deletions docs/changelog.rst
Expand Up @@ -5,6 +5,11 @@
Changelog
=========

24.4.2
------

- fix: Ensure ID generator in range [1, 2 ** 53] (#1637)

24.4.1
------

Expand Down

0 comments on commit f38f16b

Please sign in to comment.