fairdice 1.1.0__tar.gz

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.
fairdice-1.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 fairdice.ir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: fairdice
3
+ Version: 1.1.0
4
+ Summary: Provably fair, seed-based dice, cards and lottery draws for game servers and player apps, verifiable at fairdice.ir
5
+ Author: fairdice.ir
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://fairdice.ir
8
+ Project-URL: Documentation, https://fairdice.ir/docs
9
+ Project-URL: Source, https://github.com/Ahmadrezadl/fair-dice-ir
10
+ Project-URL: Issues, https://github.com/Ahmadrezadl/fair-dice-ir/issues
11
+ Keywords: provably fair,dice,rng,backgammon,cards,shuffle,lottery,commit-reveal,verifiable,game
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Security :: Cryptography
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # fairdice
24
+
25
+ Provably fair, seed-based dice, cards and lottery draws for Python game servers and player apps.
26
+ Standard library only, works offline, and every match can be verified by anyone at
27
+ [fairdice.ir](https://fairdice.ir). Results are identical to the JavaScript (`npm install fairdice-ir`)
28
+ and .NET (`dotnet add package FairDice`) SDKs.
29
+
30
+ ```sh
31
+ pip install fairdice
32
+ ```
33
+
34
+ ## Game server
35
+
36
+ ```python
37
+ from fairdice import FairDice
38
+
39
+ fd = FairDice(dice="2d6", game="Backgammon") # or FairDice(preset="yatzy"), ...
40
+ send_to_apps(fd.commitment) # match start: the apps keep it, players never see it
41
+ fd.add_player_seed(seed_from_alice) # each app answers with FairDicePlayer.join()
42
+ fd.add_player_seed(seed_from_bob)
43
+
44
+ fd.roll() # [3, 5] - computed locally, no network
45
+ fd.shuffle("std52") # ['7H', 'KS', ...]
46
+ fd.lotto(6, 49) # [4, 11, 23, 30, 38, 45]
47
+
48
+ send_to_apps(fd.url()) # after the match: https://fairdice.ir/v/<token>
49
+ ```
50
+
51
+ The server seed is locked before any player seed arrives, so the server cannot search for a lucky seed,
52
+ and the player seeds are listed in the proof, so it cannot drop one.
53
+
54
+ ## Player app
55
+
56
+ ```python
57
+ from fairdice import FairDicePlayer
58
+
59
+ me = FairDicePlayer()
60
+ send_to_server(me.join(commitment_from_server)) # at match start
61
+ me.saw(roll) # optional: every result the game showed
62
+ check = me.check(proof_url, complete=True) # after the match, offline
63
+ show_badge("Fair dice, verified" if check["ok"] else "Could not verify", check["url"])
64
+ ```
65
+
66
+ ## No player apps?
67
+
68
+ `fd.use_beacon()` timestamps the commitment on fairdice.ir and mixes in the first
69
+ [public beacon](https://fairdice.ir/beacon) round published after it (waits up to a minute).
70
+
71
+ Persist a running match with `fd.state()` and continue with `FairDice.restore(state)`.
72
+ `verify(url_or_token)` recomputes any proof.
73
+
74
+ Docs: <https://fairdice.ir/docs> · Source: <https://github.com/Ahmadrezadl/fair-dice-ir>
@@ -0,0 +1,52 @@
1
+ # fairdice
2
+
3
+ Provably fair, seed-based dice, cards and lottery draws for Python game servers and player apps.
4
+ Standard library only, works offline, and every match can be verified by anyone at
5
+ [fairdice.ir](https://fairdice.ir). Results are identical to the JavaScript (`npm install fairdice-ir`)
6
+ and .NET (`dotnet add package FairDice`) SDKs.
7
+
8
+ ```sh
9
+ pip install fairdice
10
+ ```
11
+
12
+ ## Game server
13
+
14
+ ```python
15
+ from fairdice import FairDice
16
+
17
+ fd = FairDice(dice="2d6", game="Backgammon") # or FairDice(preset="yatzy"), ...
18
+ send_to_apps(fd.commitment) # match start: the apps keep it, players never see it
19
+ fd.add_player_seed(seed_from_alice) # each app answers with FairDicePlayer.join()
20
+ fd.add_player_seed(seed_from_bob)
21
+
22
+ fd.roll() # [3, 5] - computed locally, no network
23
+ fd.shuffle("std52") # ['7H', 'KS', ...]
24
+ fd.lotto(6, 49) # [4, 11, 23, 30, 38, 45]
25
+
26
+ send_to_apps(fd.url()) # after the match: https://fairdice.ir/v/<token>
27
+ ```
28
+
29
+ The server seed is locked before any player seed arrives, so the server cannot search for a lucky seed,
30
+ and the player seeds are listed in the proof, so it cannot drop one.
31
+
32
+ ## Player app
33
+
34
+ ```python
35
+ from fairdice import FairDicePlayer
36
+
37
+ me = FairDicePlayer()
38
+ send_to_server(me.join(commitment_from_server)) # at match start
39
+ me.saw(roll) # optional: every result the game showed
40
+ check = me.check(proof_url, complete=True) # after the match, offline
41
+ show_badge("Fair dice, verified" if check["ok"] else "Could not verify", check["url"])
42
+ ```
43
+
44
+ ## No player apps?
45
+
46
+ `fd.use_beacon()` timestamps the commitment on fairdice.ir and mixes in the first
47
+ [public beacon](https://fairdice.ir/beacon) round published after it (waits up to a minute).
48
+
49
+ Persist a running match with `fd.state()` and continue with `FairDice.restore(state)`.
50
+ `verify(url_or_token)` recomputes any proof.
51
+
52
+ Docs: <https://fairdice.ir/docs> · Source: <https://github.com/Ahmadrezadl/fair-dice-ir>
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: fairdice
3
+ Version: 1.1.0
4
+ Summary: Provably fair, seed-based dice, cards and lottery draws for game servers and player apps, verifiable at fairdice.ir
5
+ Author: fairdice.ir
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://fairdice.ir
8
+ Project-URL: Documentation, https://fairdice.ir/docs
9
+ Project-URL: Source, https://github.com/Ahmadrezadl/fair-dice-ir
10
+ Project-URL: Issues, https://github.com/Ahmadrezadl/fair-dice-ir/issues
11
+ Keywords: provably fair,dice,rng,backgammon,cards,shuffle,lottery,commit-reveal,verifiable,game
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Games/Entertainment
17
+ Classifier: Topic :: Security :: Cryptography
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # fairdice
24
+
25
+ Provably fair, seed-based dice, cards and lottery draws for Python game servers and player apps.
26
+ Standard library only, works offline, and every match can be verified by anyone at
27
+ [fairdice.ir](https://fairdice.ir). Results are identical to the JavaScript (`npm install fairdice-ir`)
28
+ and .NET (`dotnet add package FairDice`) SDKs.
29
+
30
+ ```sh
31
+ pip install fairdice
32
+ ```
33
+
34
+ ## Game server
35
+
36
+ ```python
37
+ from fairdice import FairDice
38
+
39
+ fd = FairDice(dice="2d6", game="Backgammon") # or FairDice(preset="yatzy"), ...
40
+ send_to_apps(fd.commitment) # match start: the apps keep it, players never see it
41
+ fd.add_player_seed(seed_from_alice) # each app answers with FairDicePlayer.join()
42
+ fd.add_player_seed(seed_from_bob)
43
+
44
+ fd.roll() # [3, 5] - computed locally, no network
45
+ fd.shuffle("std52") # ['7H', 'KS', ...]
46
+ fd.lotto(6, 49) # [4, 11, 23, 30, 38, 45]
47
+
48
+ send_to_apps(fd.url()) # after the match: https://fairdice.ir/v/<token>
49
+ ```
50
+
51
+ The server seed is locked before any player seed arrives, so the server cannot search for a lucky seed,
52
+ and the player seeds are listed in the proof, so it cannot drop one.
53
+
54
+ ## Player app
55
+
56
+ ```python
57
+ from fairdice import FairDicePlayer
58
+
59
+ me = FairDicePlayer()
60
+ send_to_server(me.join(commitment_from_server)) # at match start
61
+ me.saw(roll) # optional: every result the game showed
62
+ check = me.check(proof_url, complete=True) # after the match, offline
63
+ show_badge("Fair dice, verified" if check["ok"] else "Could not verify", check["url"])
64
+ ```
65
+
66
+ ## No player apps?
67
+
68
+ `fd.use_beacon()` timestamps the commitment on fairdice.ir and mixes in the first
69
+ [public beacon](https://fairdice.ir/beacon) round published after it (waits up to a minute).
70
+
71
+ Persist a running match with `fd.state()` and continue with `FairDice.restore(state)`.
72
+ `verify(url_or_token)` recomputes any proof.
73
+
74
+ Docs: <https://fairdice.ir/docs> · Source: <https://github.com/Ahmadrezadl/fair-dice-ir>
@@ -0,0 +1,8 @@
1
+ LICENSE
2
+ README.md
3
+ fairdice.py
4
+ pyproject.toml
5
+ fairdice.egg-info/PKG-INFO
6
+ fairdice.egg-info/SOURCES.txt
7
+ fairdice.egg-info/dependency_links.txt
8
+ fairdice.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ fairdice
@@ -0,0 +1,749 @@
1
+ """
2
+ fairdice - provably fair, seed-based randomness (FairDice protocol v1).
3
+
4
+ Python reference implementation, standard library only. Produces exactly the
5
+ same results as the JavaScript and C# SDKs (see spec/test-vectors.json), so
6
+ proofs made here verify on https://fairdice.ir and vice versa.
7
+
8
+ from fairdice import FairDice
9
+
10
+ fd = FairDice(dice="2d6", game="Backgammon")
11
+ send_to_apps(fd.commitment) # silently, at match start
12
+ fd.add_player_seed(seed_from_app) # FairDicePlayer.join() in each player's app
13
+ fd.roll() # [3, 5] - offline, no API calls
14
+ ...
15
+ print(fd.url()) # https://fairdice.ir/v/<token> (reveals the seed)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import hashlib
22
+ import hmac
23
+ import json
24
+ import re
25
+ import secrets
26
+ import time
27
+ import urllib.error
28
+ import urllib.request
29
+ from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union
30
+
31
+ __all__ = [
32
+ "FairDice", "FairDicePlayer", "ByteStream", "commitment_of", "compute_draw", "build_deck",
33
+ "mix_client_seed", "encode_token", "decode_token", "verify", "replay", "PRESETS",
34
+ "register_commitment", "get_beacon", "wait_for_beacon", "beacon_round_after",
35
+ ]
36
+ __version__ = "1.1.0"
37
+
38
+ DEFAULT_BASE_URL = "https://fairdice.ir"
39
+ TWO_32 = 4294967296
40
+ MAX_COUNT = 10000
41
+ MAX_DECK = 100000
42
+ MAX_PICK = 100000
43
+ SEED_RE = re.compile(r"^[0-9a-f]{64}$")
44
+ MAX_PLAYER_SEEDS = 64
45
+ BEACON_ROUND_SECONDS = 60
46
+
47
+ Item = Union[str, int]
48
+
49
+
50
+ # --------------------------------------------------------------------- stream
51
+
52
+ class ByteStream:
53
+ """HMAC-SHA256(key=serverSeed, msg=f"{clientSeed}:{nonce}:{block}") for block = 0, 1, 2..."""
54
+
55
+ def __init__(self, server_seed: str, client_seed: str, nonce: int):
56
+ self._key = server_seed.encode("utf-8")
57
+ self._prefix = f"{client_seed}:{nonce}:"
58
+ self._block = 0
59
+ self._buf = b""
60
+ self._pos = 0
61
+
62
+ def byte(self) -> int:
63
+ if self._pos >= len(self._buf):
64
+ self._buf = hmac.new(self._key, (self._prefix + str(self._block)).encode("utf-8"), hashlib.sha256).digest()
65
+ self._block += 1
66
+ self._pos = 0
67
+ b = self._buf[self._pos]
68
+ self._pos += 1
69
+ return b
70
+
71
+ def uint32(self) -> int:
72
+ return (self.byte() << 24) | (self.byte() << 16) | (self.byte() << 8) | self.byte()
73
+
74
+ def int(self, n: int) -> int:
75
+ """Uniform integer in [0, n) by rejection sampling (no modulo bias)."""
76
+ if not isinstance(n, int) or n < 1 or n > TWO_32:
77
+ raise ValueError("n must be an integer in [1, 2^32]")
78
+ if n == 1:
79
+ return 0
80
+ limit = TWO_32 - (TWO_32 % n)
81
+ while True:
82
+ x = self.uint32()
83
+ if x < limit:
84
+ return x % n
85
+
86
+ def float(self) -> float:
87
+ a = self.uint32() >> 5
88
+ b = self.uint32() >> 6
89
+ return (a * 67108864 + b) / 9007199254740992
90
+
91
+
92
+ # --------------------------------------------------------------------- decks
93
+
94
+ SUITS = ["S", "H", "D", "C"]
95
+ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]
96
+
97
+
98
+ def _cards(ranks: Sequence[str]) -> List[str]:
99
+ return [r + s for s in SUITS for r in ranks]
100
+
101
+
102
+ def _dominoes(mx: int) -> List[str]:
103
+ return [f"{a}-{b}" for a in range(mx + 1) for b in range(a, mx + 1)]
104
+
105
+
106
+ def build_deck(spec: str) -> List[Item]:
107
+ fixed = {
108
+ "std52": lambda: _cards(RANKS),
109
+ "std54": lambda: _cards(RANKS) + ["XR", "XB"],
110
+ "std36": lambda: _cards(["A", "6", "7", "8", "9", "T", "J", "Q", "K"]),
111
+ "std32": lambda: _cards(["A", "7", "8", "9", "T", "J", "Q", "K"]),
112
+ "dom6": lambda: _dominoes(6),
113
+ "dom9": lambda: _dominoes(9),
114
+ "dom12": lambda: _dominoes(12),
115
+ }
116
+ if spec in fixed:
117
+ return list(fixed[spec]())
118
+ m = re.fullmatch(r"shoe:(\d{1,2})", spec)
119
+ if m:
120
+ k = int(m.group(1))
121
+ if not 1 <= k <= 16:
122
+ raise ValueError("shoe:N supports 1..16 decks")
123
+ return _cards(RANKS) * k
124
+ m = re.fullmatch(r"n:(\d{1,6})", spec)
125
+ if m:
126
+ n = int(m.group(1))
127
+ if not 1 <= n <= MAX_DECK:
128
+ raise ValueError(f"n:N supports 1..{MAX_DECK}")
129
+ return list(range(1, n + 1))
130
+ raise ValueError(f'Unknown deck spec "{spec}"')
131
+
132
+
133
+ # --------------------------------------------------------------------- ops
134
+
135
+ def _is_int(x: Any) -> bool:
136
+ return isinstance(x, int) and not isinstance(x, bool) and abs(x) <= 9007199254740991
137
+
138
+
139
+ def _int_in(x: Any, lo: int, hi: int, name: str) -> int:
140
+ if not _is_int(x) or x < lo or x > hi:
141
+ raise ValueError(f"{name} must be an integer in [{lo}, {hi}]")
142
+ return x
143
+
144
+
145
+ def validate_op(code: str, params: list) -> None:
146
+ def arity(n: int) -> None:
147
+ if not isinstance(params, list) or len(params) != n:
148
+ raise ValueError(f'op "{code}" expects {n} params')
149
+
150
+ if code == "d":
151
+ arity(2); _int_in(params[0], 2, 1_000_000_000, "sides"); _int_in(params[1], 1, MAX_COUNT, "count")
152
+ elif code in ("c", "f"):
153
+ arity(1); _int_in(params[0], 1, MAX_COUNT, "count")
154
+ elif code == "i":
155
+ arity(3)
156
+ mn, mx = params[0], params[1]
157
+ if not _is_int(mn) or not _is_int(mx) or mx < mn:
158
+ raise ValueError("min/max must be integers with min <= max")
159
+ if mx - mn + 1 > TWO_32:
160
+ raise ValueError("range must be <= 2^32")
161
+ _int_in(params[2], 1, MAX_COUNT, "count")
162
+ elif code == "s":
163
+ arity(1); build_deck(params[0])
164
+ elif code == "dl":
165
+ arity(3)
166
+ size = len(build_deck(params[0]))
167
+ hands = _int_in(params[1], 1, 1000, "hands")
168
+ per = _int_in(params[2], 1, MAX_DECK, "perHand")
169
+ if hands * per > size:
170
+ raise ValueError(f"cannot deal {hands}x{per} from a deck of {size}")
171
+ elif code == "p":
172
+ arity(3)
173
+ n = _int_in(params[0], 1, TWO_32, "n")
174
+ _int_in(params[1], 1, min(n, MAX_PICK), "k")
175
+ _int_in(params[2], -9007199254740991 + TWO_32, 9007199254740991 - TWO_32, "offset")
176
+ elif code == "w":
177
+ arity(2)
178
+ ws = params[0]
179
+ if not isinstance(ws, list) or not 1 <= len(ws) <= 10000:
180
+ raise ValueError("weights must be a list of 1..10000 integers")
181
+ total = sum(_int_in(w, 0, TWO_32, "weight") for w in ws)
182
+ if not 1 <= total <= TWO_32:
183
+ raise ValueError("sum of weights must be in [1, 2^32]")
184
+ _int_in(params[1], 1, MAX_COUNT, "count")
185
+ elif code == "r":
186
+ arity(2)
187
+ if params[0] not in ("eu", "us"):
188
+ raise ValueError('roulette variant must be "eu" or "us"')
189
+ _int_in(params[1], 1, MAX_COUNT, "count")
190
+ elif code == "b":
191
+ arity(1); _int_in(params[0], 1, 4096, "length")
192
+ else:
193
+ raise ValueError(f'Unknown op code "{code}"')
194
+
195
+
196
+ def pick_indices(stream: ByteStream, n: int, k: int) -> List[int]:
197
+ """Sparse forward Fisher-Yates: step i swaps i with j = i + int(n - i)."""
198
+ moved: Dict[int, int] = {}
199
+ out = []
200
+ for i in range(k):
201
+ j = i + stream.int(n - i)
202
+ at_i = moved.get(i, i)
203
+ at_j = moved.get(j, j)
204
+ moved[j] = at_i
205
+ moved.pop(i, None)
206
+ out.append(at_j)
207
+ return out
208
+
209
+
210
+ def execute_op(stream: ByteStream, code: str, params: list) -> Any:
211
+ if code == "d":
212
+ sides, count = params
213
+ return [1 + stream.int(sides) for _ in range(count)]
214
+ if code == "c":
215
+ return ["H" if stream.int(2) == 0 else "T" for _ in range(params[0])]
216
+ if code == "i":
217
+ mn, mx, count = params
218
+ return [mn + stream.int(mx - mn + 1) for _ in range(count)]
219
+ if code == "f":
220
+ return [stream.float() for _ in range(params[0])]
221
+ if code == "s":
222
+ deck = build_deck(params[0])
223
+ return [deck[i] for i in pick_indices(stream, len(deck), len(deck))]
224
+ if code == "dl":
225
+ deck = build_deck(params[0])
226
+ hands, per = params[1], params[2]
227
+ sh = [deck[i] for i in pick_indices(stream, len(deck), len(deck))]
228
+ return {"hands": [sh[h * per:(h + 1) * per] for h in range(hands)], "rest": sh[hands * per:]}
229
+ if code == "p":
230
+ n, k, offset = params
231
+ return [i + offset for i in pick_indices(stream, n, k)]
232
+ if code == "w":
233
+ ws, count = params
234
+ total = sum(ws)
235
+ out = []
236
+ for _ in range(count):
237
+ r = stream.int(total)
238
+ idx = 0
239
+ while r >= ws[idx]:
240
+ r -= ws[idx]
241
+ idx += 1
242
+ out.append(idx)
243
+ return out
244
+ if code == "r":
245
+ us = params[0] == "us"
246
+ out: List[Item] = []
247
+ for _ in range(params[1]):
248
+ x = stream.int(38 if us else 37)
249
+ out.append("00" if x == 37 else x)
250
+ return out
251
+ if code == "b":
252
+ return "".join(f"{stream.byte():02x}" for _ in range(params[0]))
253
+ raise ValueError(f'Unknown op code "{code}"')
254
+
255
+
256
+ def parse_dice(notation: str) -> Tuple[int, int]:
257
+ m = re.fullmatch(r"\s*(\d*)\s*[dD]\s*(\d+)\s*", notation)
258
+ if not m:
259
+ raise ValueError(f'Invalid dice notation "{notation}"')
260
+ count = int(m.group(1)) if m.group(1) else 1
261
+ sides = int(m.group(2))
262
+ validate_op("d", [sides, count])
263
+ return sides, count
264
+
265
+
266
+ # --------------------------------------------------------------------- proof
267
+
268
+ def commitment_of(server_seed: str) -> str:
269
+ return hashlib.sha256(server_seed.encode("utf-8")).hexdigest()
270
+
271
+
272
+ def _check_client_seed(seed: Any, name: str = "client seed") -> None:
273
+ if not isinstance(seed, str) or not 1 <= len(seed) <= 256:
274
+ raise ValueError(f"{name} must be a 1..256 char string")
275
+
276
+
277
+ def _check_beacon_ref(b: Any) -> None:
278
+ if (not isinstance(b, (list, tuple)) or len(b) != 2 or not _is_int(b[0]) or b[0] < 0
279
+ or not isinstance(b[1], str) or not SEED_RE.match(b[1])):
280
+ raise ValueError("b must be [round, 64-hex beacon output]")
281
+
282
+
283
+ def mix_client_seed(player_seeds: Sequence[str], beacon: Optional[Sequence[Any]] = None) -> str:
284
+ """Combine player seeds and an optional beacon round [round, output] into one client seed.
285
+
286
+ hashes = sorted(sha256_hex(seed) for seed in player_seeds)
287
+ "mix:" + sha256_hex("fairdice-mix-v1|" + ",".join(hashes) + "|" + (f"{round}:{output}" if beacon else ""))
288
+ """
289
+ if len(player_seeds) > MAX_PLAYER_SEEDS:
290
+ raise ValueError(f"at most {MAX_PLAYER_SEEDS} player seeds")
291
+ for x in player_seeds:
292
+ _check_client_seed(x, "player seed")
293
+ if beacon is not None:
294
+ _check_beacon_ref(beacon)
295
+ hashes = sorted(hashlib.sha256(x.encode("utf-8")).hexdigest() for x in player_seeds)
296
+ tail = f"{beacon[0]}:{beacon[1]}" if beacon is not None else ""
297
+ return "mix:" + hashlib.sha256(f"fairdice-mix-v1|{','.join(hashes)}|{tail}".encode("utf-8")).hexdigest()
298
+
299
+
300
+ def compute_draw(server_seed: str, client_seed: str, nonce: int, code: str, params: list) -> Any:
301
+ validate_op(code, params)
302
+ return execute_op(ByteStream(server_seed, client_seed, nonce), code, params)
303
+
304
+
305
+ def _b64url(b: bytes) -> str:
306
+ return base64.urlsafe_b64encode(b).decode("ascii").rstrip("=")
307
+
308
+
309
+ def _unb64url(s: str) -> bytes:
310
+ s = s.strip().replace("+", "-").replace("/", "_").rstrip("=")
311
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
312
+
313
+
314
+ def encode_token(proof: dict) -> str:
315
+ return _b64url(json.dumps(proof, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))
316
+
317
+
318
+ def decode_token(token_or_url: str) -> dict:
319
+ s = token_or_url.strip()
320
+ m = re.search(r"/v/([A-Za-z0-9_\-+/=]+)", s) or re.search(r"#([A-Za-z0-9_\-+/=]+)$", s)
321
+ if m:
322
+ s = m.group(1)
323
+ proof = json.loads(_unb64url(s).decode("utf-8"))
324
+ validate_proof(proof)
325
+ return proof
326
+
327
+
328
+ def validate_proof(p: dict) -> None:
329
+ if not isinstance(p, dict) or p.get("v") != 1:
330
+ raise ValueError("unsupported proof version")
331
+ if not isinstance(p.get("s"), str) or not SEED_RE.match(p["s"]):
332
+ raise ValueError("s must be 64 lowercase hex chars")
333
+ if not isinstance(p.get("c"), str) or not 1 <= len(p["c"]) <= 256:
334
+ raise ValueError("c must be a 1..256 char string")
335
+ if not _is_int(p.get("n")) or p["n"] < 0:
336
+ raise ValueError("n must be a non-negative integer")
337
+ if not isinstance(p.get("o"), list):
338
+ raise ValueError("o must be a list")
339
+ for e in p["o"]:
340
+ if not isinstance(e, list) or len(e) != 3 or not _is_int(e[2]) or e[2] < 1:
341
+ raise ValueError("op log entries must be [code, params, times]")
342
+ validate_op(e[0], e[1])
343
+ if "p" in p:
344
+ if not isinstance(p["p"], list) or not 1 <= len(p["p"]) <= MAX_PLAYER_SEEDS:
345
+ raise ValueError(f"p must be a list of 1..{MAX_PLAYER_SEEDS} player seeds")
346
+ for x in p["p"]:
347
+ _check_client_seed(x, "player seed")
348
+ if "b" in p:
349
+ _check_beacon_ref(p["b"])
350
+ if ("p" in p or "b" in p) and p["c"] != mix_client_seed(p.get("p", []), p.get("b")):
351
+ raise ValueError("c does not match the player seeds and beacon round in the proof")
352
+
353
+
354
+ def replay(proof: dict) -> Iterator[dict]:
355
+ index = 0
356
+ for code, params, times in proof["o"]:
357
+ for _ in range(times):
358
+ nonce = proof["n"] + index
359
+ yield {"index": index, "nonce": nonce, "code": code, "params": params,
360
+ "result": execute_op(ByteStream(proof["s"], proof["c"], nonce), code, params)}
361
+ index += 1
362
+
363
+
364
+ def verify(token_or_proof: Union[str, dict], expected_commitment: Optional[str] = None) -> dict:
365
+ proof = decode_token(token_or_proof) if isinstance(token_or_proof, str) else token_or_proof
366
+ validate_proof(proof)
367
+ commitment = commitment_of(proof["s"])
368
+ draws = list(replay(proof))
369
+ return {
370
+ "proof": proof,
371
+ "commitment": commitment,
372
+ "commitment_matches": None if expected_commitment is None else expected_commitment.strip().lower() == commitment,
373
+ "count": len(draws),
374
+ "draws": draws,
375
+ "player_seeds": list(proof.get("p", [])),
376
+ "beacon": {"round": proof["b"][0], "output": proof["b"][1]} if "b" in proof else None,
377
+ }
378
+
379
+
380
+ # --------------------------------------------------------------------- online helpers (optional)
381
+
382
+ def _http(base_url: str, path: str, body: Optional[dict] = None, timeout: float = 15) -> Tuple[int, dict]:
383
+ data = None if body is None else json.dumps(body).encode("utf-8")
384
+ req = urllib.request.Request(base_url.rstrip("/") + path, data=data, method="POST" if body is not None else "GET",
385
+ headers={"content-type": "application/json", "user-agent": f"fairdice-python/{__version__}"})
386
+ try:
387
+ with urllib.request.urlopen(req, timeout=timeout) as r:
388
+ return r.status, json.loads(r.read().decode("utf-8") or "{}")
389
+ except urllib.error.HTTPError as e:
390
+ try:
391
+ return e.code, json.loads(e.read().decode("utf-8") or "{}")
392
+ except ValueError:
393
+ return e.code, {}
394
+
395
+
396
+ def _ok(status: int, body: dict) -> dict:
397
+ if status >= 400:
398
+ raise RuntimeError(body.get("error") or f"fairdice.ir request failed ({status})")
399
+ return body
400
+
401
+
402
+ def register_commitment(commitment: str, label: Optional[str] = None, base_url: str = DEFAULT_BASE_URL) -> dict:
403
+ """Timestamp a commitment on the fairdice.ir notary (idempotent)."""
404
+ return _ok(*_http(base_url, "/api/commitments", {"hash": commitment, "label": label}))
405
+
406
+
407
+ def get_beacon(round_: Union[int, str] = "latest", base_url: str = DEFAULT_BASE_URL) -> dict:
408
+ return _ok(*_http(base_url, f"/api/beacon/{round_}"))
409
+
410
+
411
+ def beacon_round_after(iso_time: str) -> int:
412
+ """First beacon round strictly after an ISO time (round r is due at unix r*60)."""
413
+ from datetime import datetime
414
+ ts = datetime.fromisoformat(iso_time.replace("Z", "+00:00")).timestamp()
415
+ return int(ts // BEACON_ROUND_SECONDS) + 1
416
+
417
+
418
+ def wait_for_beacon(round_: int, base_url: str = DEFAULT_BASE_URL, timeout: float = 90, poll: float = 2) -> dict:
419
+ """Wait until a beacon round is published (due at round*60 s) and return it."""
420
+ due = round_ * BEACON_ROUND_SECONDS
421
+ deadline = max(time.time(), due) + timeout
422
+ while True:
423
+ if time.time() < due:
424
+ time.sleep(min(due - time.time() + 0.5, max(0.0, deadline - time.time())))
425
+ status, body = _http(base_url, f"/api/beacon/{round_}")
426
+ if status < 400:
427
+ return body
428
+ if status != 404:
429
+ _ok(status, body)
430
+ if time.time() >= deadline:
431
+ raise TimeoutError(f"beacon round {round_} was not published in time")
432
+ time.sleep(poll)
433
+
434
+
435
+ PRESETS: Dict[str, Tuple[str, list]] = {
436
+ "backgammon": ("d", [6, 2]), "yatzy": ("d", [6, 5]), "ludo": ("d", [6, 1]),
437
+ "d20": ("d", [20, 1]), "coin": ("c", [1]), "hokm": ("dl", ["std52", 4, 13]),
438
+ "poker": ("s", ["std52"]), "blackjack": ("s", ["shoe:6"]), "roulette": ("r", ["eu", 1]),
439
+ "lotto649": ("p", [49, 6, 1]), "bingo75": ("p", [75, 75, 1]), "mapseed": ("b", [32]),
440
+ }
441
+
442
+
443
+ # --------------------------------------------------------------------- session
444
+
445
+ class FairDice:
446
+ """One provably fair session (a match, a table, a round of a game)."""
447
+
448
+ def __init__(self, server_seed: Optional[str] = None, client_seed: Optional[str] = None, nonce: int = 0,
449
+ dice: Optional[str] = None, preset: Optional[str] = None, game: Optional[str] = None,
450
+ meta: Optional[dict] = None, base_url: str = DEFAULT_BASE_URL,
451
+ player_seeds: Optional[Sequence[str]] = None, beacon: Optional[Sequence[Any]] = None):
452
+ self.server_seed = (server_seed or secrets.token_hex(32)).lower()
453
+ if not SEED_RE.match(self.server_seed):
454
+ raise ValueError("server_seed must be 64 hex chars")
455
+ self._client_seed = client_seed if client_seed is not None else secrets.token_hex(8)
456
+ _check_client_seed(self._client_seed)
457
+ self._players: List[str] = list(player_seeds or [])
458
+ self._beacon: Optional[List[Any]] = [beacon[0], beacon[1]] if beacon is not None else None
459
+ self._receipt: Optional[dict] = None
460
+ if player_seeds is not None or beacon is not None:
461
+ mixed = mix_client_seed(self._players, self._beacon)
462
+ if client_seed is not None and client_seed != mixed:
463
+ raise ValueError("client_seed does not match player_seeds/beacon")
464
+ self._client_seed = mixed
465
+ self.first_nonce = nonce
466
+ self.commitment = commitment_of(self.server_seed)
467
+ self.game = game
468
+ self.meta = meta
469
+ self.base_url = base_url.rstrip("/")
470
+ self.created_at = int(time.time())
471
+ self.history: List[dict] = []
472
+ self._log: List[list] = []
473
+ self._count = 0
474
+ self._revealed = False
475
+ self._default: Optional[Tuple[str, list]] = None
476
+ if dice:
477
+ self._default = ("d", list(parse_dice(dice)))
478
+ elif preset:
479
+ self._default = PRESETS[preset]
480
+ self.game = self.game or preset.capitalize()
481
+
482
+ @property
483
+ def client_seed(self) -> str:
484
+ return self._client_seed
485
+
486
+ @property
487
+ def count(self) -> int:
488
+ return self._count
489
+
490
+ @property
491
+ def nonce(self) -> int:
492
+ return self.first_nonce + self._count
493
+
494
+ @property
495
+ def player_seeds(self) -> List[str]:
496
+ return list(self._players)
497
+
498
+ @property
499
+ def beacon(self) -> Optional[dict]:
500
+ return {"round": self._beacon[0], "output": self._beacon[1]} if self._beacon else None
501
+
502
+ def _no_draws(self, what: str) -> None:
503
+ if self._count:
504
+ raise RuntimeError(f"{what} must be called before the first draw")
505
+
506
+ def set_client_seed(self, seed: str) -> "FairDice":
507
+ """Replace the client seed with a raw value (drops player seeds and beacon)."""
508
+ self._no_draws("set_client_seed()")
509
+ _check_client_seed(seed)
510
+ self._players, self._beacon = [], None
511
+ self._client_seed = seed
512
+ return self
513
+
514
+ def set_player_seeds(self, seeds: Sequence[str]) -> "FairDice":
515
+ """Mix the seeds the players' apps sent (after receiving the commitment) into the client seed."""
516
+ self._no_draws("set_player_seeds()")
517
+ nxt = [str(x) for x in seeds]
518
+ self._client_seed = mix_client_seed(nxt, self._beacon)
519
+ self._players = nxt
520
+ return self
521
+
522
+ def add_player_seed(self, seed: str) -> "FairDice":
523
+ return self.set_player_seeds(self._players + [seed])
524
+
525
+ def draw(self, code: str, params: list) -> Any:
526
+ if self._revealed:
527
+ raise RuntimeError("session was revealed; start a new FairDice")
528
+ validate_op(code, params)
529
+ nonce = self.nonce
530
+ result = execute_op(ByteStream(self.server_seed, self._client_seed, nonce), code, params)
531
+ if self._log and self._log[-1][0] == code and self._log[-1][1] == params:
532
+ self._log[-1][2] += 1
533
+ else:
534
+ self._log.append([code, json.loads(json.dumps(params)), 1])
535
+ self.history.append({"index": self._count, "nonce": nonce, "code": code, "params": params, "result": result})
536
+ self._count += 1
537
+ return result
538
+
539
+ def roll(self) -> Any:
540
+ if not self._default:
541
+ raise RuntimeError('no default op; pass dice="2d6" or preset=...')
542
+ return self.draw(self._default[0], list(self._default[1]))
543
+
544
+ def dice(self, sides: int = 6, count: int = 1) -> List[int]:
545
+ return self.draw("d", [sides, count])
546
+
547
+ def coin(self) -> str:
548
+ return self.draw("c", [1])[0]
549
+
550
+ def int(self, mn: int, mx: int) -> int:
551
+ return self.draw("i", [mn, mx, 1])[0]
552
+
553
+ def float(self) -> float:
554
+ return self.draw("f", [1])[0]
555
+
556
+ def shuffle(self, deck: str = "std52") -> List[Item]:
557
+ return self.draw("s", [deck])
558
+
559
+ def deal(self, deck: str, hands: int, per_hand: int) -> dict:
560
+ return self.draw("dl", [deck, hands, per_hand])
561
+
562
+ def sample(self, n: int, k: int, offset: int = 1) -> List[int]:
563
+ return self.draw("p", [n, k, offset])
564
+
565
+ def lotto(self, k: int, n: int) -> List[int]:
566
+ return self.sample(n, k, 1)
567
+
568
+ def pick(self, items: Sequence[Any]) -> Any:
569
+ return items[self.sample(len(items), 1, 0)[0]]
570
+
571
+ def weighted(self, weights: List[int]) -> int:
572
+ return self.draw("w", [weights, 1])[0]
573
+
574
+ def roulette(self, variant: str = "eu") -> Item:
575
+ return self.draw("r", [variant, 1])[0]
576
+
577
+ def bytes(self, length: int = 32) -> str:
578
+ return self.draw("b", [length])
579
+
580
+ def state(self) -> dict:
581
+ p: Dict[str, Any] = {"v": 1, "s": self.server_seed, "c": self._client_seed, "n": self.first_nonce,
582
+ "o": [[c, prm, t] for c, prm, t in self._log]}
583
+ if self.game:
584
+ p["g"] = self.game
585
+ if self.meta:
586
+ p["m"] = self.meta
587
+ p["t"] = self.created_at
588
+ if self._players:
589
+ p["p"] = list(self._players)
590
+ if self._beacon:
591
+ p["b"] = [self._beacon[0], self._beacon[1]]
592
+ return p
593
+
594
+ @classmethod
595
+ def restore(cls, state: dict, dice: Optional[str] = None, preset: Optional[str] = None,
596
+ base_url: str = DEFAULT_BASE_URL) -> "FairDice":
597
+ """Resume a session from state() (e.g. after a server restart)."""
598
+ validate_proof(state)
599
+ fd = cls(server_seed=state["s"], client_seed=state["c"], nonce=state["n"], dice=dice, preset=preset,
600
+ game=state.get("g"), meta=state.get("m"), base_url=base_url,
601
+ player_seeds=state.get("p"), beacon=state.get("b"))
602
+ for code, params, times in state["o"]:
603
+ for _ in range(times):
604
+ fd.draw(code, params)
605
+ if "t" in state:
606
+ fd.created_at = state["t"]
607
+ return fd
608
+
609
+ def reveal(self) -> dict:
610
+ proof = self.state()
611
+ token = encode_token(proof)
612
+ self._revealed = True
613
+ return {"proof": proof, "token": token, "url": f"{self.base_url}/v/{token}",
614
+ "commitment": self.commitment, "count": self._count}
615
+
616
+ def token(self) -> str:
617
+ return self.reveal()["token"]
618
+
619
+ def url(self) -> str:
620
+ return self.reveal()["url"]
621
+
622
+ def commit_url(self) -> str:
623
+ return f"{self.base_url}/c/{self.commitment}"
624
+
625
+ # ---------------------------------------------------------------- optional online helpers
626
+
627
+ def register(self, label: Optional[str] = None) -> dict:
628
+ """Timestamp the commitment on fairdice.ir (proves when the seed was locked). Idempotent."""
629
+ if self._receipt is None:
630
+ self._receipt = register_commitment(self.commitment, label or self.game, self.base_url)
631
+ return self._receipt
632
+
633
+ def use_beacon(self, round_: Union[int, str] = "next") -> dict:
634
+ """Mix the first public beacon round after the commitment's timestamp into the client seed.
635
+
636
+ Registers the commitment, then waits (up to ~60 s) for that round. Call after
637
+ set_player_seeds(), before the first draw.
638
+ """
639
+ self._no_draws("use_beacon()")
640
+ receipt = self.register()
641
+ first = beacon_round_after(receipt["registeredAt"])
642
+ target = first if round_ == "next" else int(round_)
643
+ if target < first:
644
+ raise ValueError(f"beacon round {target} is not after the commitment was registered")
645
+ b = wait_for_beacon(target, self.base_url)
646
+ self._no_draws("use_beacon()")
647
+ self._beacon = [b["round"], b["output"]]
648
+ self._client_seed = mix_client_seed(self._players, self._beacon)
649
+ return b
650
+
651
+ def short_url(self) -> str:
652
+ """Reveal and store the proof on fairdice.ir; returns a short link."""
653
+ token = self.reveal()["token"]
654
+ return _ok(*_http(self.base_url, "/api/proofs", {"token": token}))["url"]
655
+
656
+
657
+ # --------------------------------------------------------------------- player side
658
+
659
+ def _same(a: Any, b: Any) -> bool:
660
+ if isinstance(a, list) and isinstance(b, list):
661
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
662
+ if isinstance(a, dict) and isinstance(b, dict):
663
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
664
+ if isinstance(a, (list, dict)) or isinstance(b, (list, dict)):
665
+ return False
666
+ return a == b
667
+
668
+
669
+ class FairDicePlayer:
670
+ """The player's side of a match: runs in the game app so the player never sees hashes.
671
+
672
+ me = FairDicePlayer()
673
+ seed = me.join(commitment_from_server) # send seed back to the server
674
+ me.saw([3, 5]) # optional, each result shown
675
+ check = me.check(proof_url) # after the match, offline
676
+ check["ok"]
677
+ """
678
+
679
+ def __init__(self, seed: Optional[str] = None, base_url: str = DEFAULT_BASE_URL):
680
+ self.seed = seed if seed is not None else secrets.token_hex(16)
681
+ _check_client_seed(self.seed, "seed")
682
+ self.base_url = base_url.rstrip("/")
683
+ self._commitment: Optional[str] = None
684
+ self._seen: List[List[Any]] = []
685
+
686
+ @property
687
+ def commitment(self) -> Optional[str]:
688
+ return self._commitment
689
+
690
+ def join(self, commitment: str) -> str:
691
+ c = str(commitment).strip().lower()
692
+ if not SEED_RE.match(c):
693
+ raise ValueError("commitment must be 64 hex characters")
694
+ if self._commitment and self._commitment != c:
695
+ raise RuntimeError("this FairDicePlayer already joined another match; create a new one per match")
696
+ self._commitment = c
697
+ return self.seed
698
+
699
+ def saw(self, result: Any, index: Optional[int] = None) -> None:
700
+ i = index if index is not None else (self._seen[-1][0] + 1 if self._seen else 0)
701
+ if not _is_int(i) or i < 0:
702
+ raise ValueError("index must be a non-negative integer")
703
+ self._seen.append([i, json.loads(json.dumps(result))])
704
+
705
+ def check(self, url_or_token: str, complete: bool = False) -> dict:
706
+ problems: List[str] = []
707
+ token, result = "", None
708
+ try:
709
+ s = url_or_token.strip()
710
+ m = re.search(r"/v/([A-Za-z0-9_\-+/=]+)", s) or re.search(r"#([A-Za-z0-9_\-+/=]+)$", s)
711
+ token = m.group(1) if m else s
712
+ result = verify(token)
713
+ except Exception as e: # noqa: BLE001 - any parse failure means "not a valid proof"
714
+ problems.append(f"not a valid proof: {e}")
715
+ url = f"{self.base_url}/v/{token}" if token else ""
716
+ if result is None:
717
+ return {"ok": False, "commitment_ok": False, "seed_included": False, "draws_ok": None,
718
+ "problems": problems, "url": url, "result": None}
719
+ commitment_ok = self._commitment is not None and result["commitment"] == self._commitment
720
+ if self._commitment is None:
721
+ problems.append("join() was never called, so there is no fingerprint to compare with")
722
+ elif not commitment_ok:
723
+ problems.append("the revealed seed does not match the fingerprint received before the match")
724
+ seed_included = self.seed in result["player_seeds"]
725
+ if not seed_included:
726
+ problems.append("this player's seed was not mixed into the dice")
727
+ draws_ok = None
728
+ if self._seen:
729
+ draws = result["draws"]
730
+ draws_ok = all(i < len(draws) and _same(draws[i]["result"], r) for i, r in self._seen)
731
+ if not draws_ok:
732
+ problems.append("some results shown in the game differ from the proof")
733
+ if complete and result["count"] != len(self._seen):
734
+ draws_ok = False
735
+ problems.append(f"the proof has {result['count']} draws but the game showed {len(self._seen)}")
736
+ return {"ok": not problems, "commitment_ok": commitment_ok, "seed_included": seed_included,
737
+ "draws_ok": draws_ok, "problems": problems, "url": url, "result": result}
738
+
739
+ def to_dict(self) -> dict:
740
+ return {"seed": self.seed, "commitment": self._commitment, "seen": [list(x) for x in self._seen]}
741
+
742
+ @classmethod
743
+ def restore(cls, state: dict, base_url: str = DEFAULT_BASE_URL) -> "FairDicePlayer":
744
+ p = cls(seed=state["seed"], base_url=base_url)
745
+ if state.get("commitment"):
746
+ p.join(state["commitment"])
747
+ for i, r in state.get("seen", []):
748
+ p.saw(r, i)
749
+ return p
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fairdice"
7
+ version = "1.1.0"
8
+ description = "Provably fair, seed-based dice, cards and lottery draws for game servers and player apps, verifiable at fairdice.ir"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "fairdice.ir" }]
14
+ keywords = ["provably fair", "dice", "rng", "backgammon", "cards", "shuffle", "lottery", "commit-reveal", "verifiable", "game"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Games/Entertainment",
21
+ "Topic :: Security :: Cryptography",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.urls]
26
+ Homepage = "https://fairdice.ir"
27
+ Documentation = "https://fairdice.ir/docs"
28
+ Source = "https://github.com/Ahmadrezadl/fair-dice-ir"
29
+ Issues = "https://github.com/Ahmadrezadl/fair-dice-ir/issues"
30
+
31
+ [tool.setuptools]
32
+ py-modules = ["fairdice"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+