Skip to content

Commit ea821ca

Browse files
committed
keep generation.py ruff formatted.
1 parent c377003 commit ea821ca

1 file changed

Lines changed: 71 additions & 24 deletions

File tree

‎src/codex32/generation.py‎

Lines changed: 71 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
"""Electronic generation for ``ms`` and Core Lightning share sets."""
22

3-
# ruff: noqa: I001
43
from __future__ import annotations
4+
55
import secrets
6-
from collections.abc import Sequence, Set as AbstractSet
6+
from collections.abc import Sequence
7+
from collections.abc import Set as AbstractSet
78
from dataclasses import dataclass
89
from typing import Never, SupportsIndex, cast
10+
911
from codex32.bech32 import CHARSET, _u5_to_chars, convertbits
1012
from codex32.bip93 import (
1113
IDX_SORT,
@@ -29,17 +31,21 @@
2931
from codex32.profiles.cl32 import PAYLOAD_LENGTH as CL_PAYLOAD_LENGTH
3032
from codex32.profiles.cl32 import (
3133
CoreLightningSecret,
32-
_has_generation_padding as _cl_padding,
3334
_secret_from_bytes,
3435
)
36+
from codex32.profiles.cl32 import (
37+
_has_generation_padding as _cl_padding,
38+
)
3539
from codex32.profiles.ms32 import (
3640
DEFAULT_SEED_BYTES,
3741
SEED_BYTE_LENGTHS,
3842
MasterSeed,
3943
_fingerprint_from_seed,
40-
_has_generation_padding as _ms_padding,
4144
_payload_length,
4245
)
46+
from codex32.profiles.ms32 import (
47+
_has_generation_padding as _ms_padding,
48+
)
4349

4450
ORDINARY_INDICES = tuple(IDX_SORT[1:])
4551

@@ -56,7 +62,9 @@ def _threshold(value: object, *, allow_zero: bool = True) -> int:
5662
if isinstance(value, bool) or not isinstance(value, int):
5763
raise InvalidThreshold("threshold must be an integer")
5864
if value not in ((0, *range(2, 10)) if allow_zero else tuple(range(2, 10))):
59-
raise InvalidThreshold(f"threshold must be {'0 or ' if allow_zero else ''}2 through 9")
65+
raise InvalidThreshold(
66+
f"threshold must be {'0 or ' if allow_zero else ''}2 through 9"
67+
)
6068
return value
6169

6270

@@ -79,25 +87,33 @@ def _index(value: object) -> str:
7987

8088

8189
def _indices(values: Sequence[str] | str) -> tuple[str, ...]:
82-
if not isinstance(values, str) and (isinstance(values, AbstractSet) or not isinstance(values, Sequence)):
90+
if not isinstance(values, str) and (
91+
isinstance(values, AbstractSet) or not isinstance(values, Sequence)
92+
):
8393
raise TypeError("indices must be an ordered sequence")
8494
if len(values) > 31:
8595
raise InvalidShareSelection("at most 31 shares may be requested")
86-
copied: tuple[object, ...] = tuple(values[position] for position in range(len(values)))
96+
copied: tuple[object, ...] = tuple(
97+
values[position] for position in range(len(values))
98+
)
8799
normalized = tuple(_index(value) for value in copied)
88100
if len(set(normalized)) != len(normalized):
89101
raise InvalidShareSelection("output indices must be distinct")
90102
return normalized
91103

92104

93-
def _selection(threshold: int, share_count: object, indices: Sequence[str] | str | None) -> tuple[str, ...]:
105+
def _selection(
106+
threshold: int, share_count: object, indices: Sequence[str] | str | None
107+
) -> tuple[str, ...]:
94108
if (share_count is None) == (indices is None):
95109
raise InvalidShareSelection("choose exactly one of share_count or indices")
96110
if share_count is not None:
97111
if isinstance(share_count, bool) or not isinstance(share_count, int):
98112
raise InvalidShareSelection("share_count must be an integer")
99113
if not threshold <= share_count <= 31:
100-
raise InvalidShareSelection(f"share_count must be from threshold {threshold} through 31")
114+
raise InvalidShareSelection(
115+
f"share_count must be from threshold {threshold} through 31"
116+
)
101117
return tuple(secrets.SystemRandom().sample(ORDINARY_INDICES, share_count))
102118
assert indices is not None
103119
selected = _indices(indices)
@@ -111,27 +127,39 @@ def _random_identifier() -> str:
111127

112128

113129
def _fingerprint_identifier(seed: bytes) -> str:
114-
return _u5_to_chars(tuple(convertbits(_fingerprint_from_seed(seed), 8, 5, pad=True)[:4]))
130+
return _u5_to_chars(
131+
tuple(convertbits(_fingerprint_from_seed(seed), 8, 5, pad=True)[:4])
132+
)
115133

116134

117-
def _random_share(profile: Profile, threshold: int, identifier: str, index: str, length: int) -> Share:
135+
def _random_share(
136+
profile: Profile, threshold: int, identifier: str, index: str, length: int
137+
) -> Share:
118138
symbols = tuple(value & 31 for value in secrets.token_bytes(length))
119139
artifact = _from_parts(profile, Header(threshold, identifier, index), symbols)
120140
assert isinstance(artifact, Share)
121141
return artifact
122142

123143

124-
def _seed_input(seed_bytes: bytes | None, byte_length: int | None) -> tuple[bytes | None, int]:
144+
def _seed_input(
145+
seed_bytes: bytes | None, byte_length: int | None
146+
) -> tuple[bytes | None, int]:
125147
if seed_bytes is not None:
126148
if not isinstance(seed_bytes, bytes):
127149
raise TypeError("seed_bytes must be bytes")
128150
if byte_length is not None:
129151
raise InvalidLength("byte_length cannot accompany seed_bytes")
130152
if len(seed_bytes) not in SEED_BYTE_LENGTHS:
131-
raise InvalidLength("master seed must contain 16, 20, 24, 28, 32, or 64 bytes")
153+
raise InvalidLength(
154+
"master seed must contain 16, 20, 24, 28, 32, or 64 bytes"
155+
)
132156
return seed_bytes, len(seed_bytes)
133157
length = DEFAULT_SEED_BYTES if byte_length is None else byte_length
134-
if isinstance(length, bool) or not isinstance(length, int) or length not in SEED_BYTE_LENGTHS:
158+
if (
159+
isinstance(length, bool)
160+
or not isinstance(length, int)
161+
or length not in SEED_BYTE_LENGTHS
162+
):
135163
raise InvalidLength("byte_length must be 16, 20, 24, 28, 32, or 64")
136164
return None, length
137165

@@ -145,15 +173,19 @@ def generate_master_seed(
145173
"""Generate or encode one unshared ``ms`` secret."""
146174
supplied, length = _seed_input(seed_bytes, byte_length)
147175
if supplied is not None:
148-
identifier = _random_identifier() if identifier is None else _identifier(identifier)
176+
identifier = (
177+
_random_identifier() if identifier is None else _identifier(identifier)
178+
)
149179
return MasterSeed.from_seed(supplied, identifier=identifier)
150180
while True:
151181
fresh = secrets.token_bytes(length)
152182
try:
153183
default_identifier = _fingerprint_identifier(fresh)
154184
except CodexError:
155185
continue
156-
identifier = default_identifier if identifier is None else _identifier(identifier)
186+
identifier = (
187+
default_identifier if identifier is None else _identifier(identifier)
188+
)
157189
return MasterSeed.from_seed(fresh, identifier=identifier)
158190

159191

@@ -162,7 +194,9 @@ def generate_core_lightning_secret(
162194
) -> CoreLightningSecret:
163195
"""Generate or encode one unshared Core Lightning HSM secret."""
164196
identifier = _random_identifier() if identifier is None else _identifier(identifier)
165-
return _secret_from_bytes(secrets.token_bytes(32) if secret_bytes is None else secret_bytes, identifier)
197+
return _secret_from_bytes(
198+
secrets.token_bytes(32) if secret_bytes is None else secret_bytes, identifier
199+
)
166200

167201

168202
class CreationCeremony:
@@ -205,7 +239,9 @@ def _start(
205239
if secret is None:
206240
self._secret, self._basis, self._direct_count = None, [], threshold
207241
else:
208-
reheadered = _from_parts(profile, Header(threshold, identifier, "s"), secret.payload_symbols)
242+
reheadered = _from_parts(
243+
profile, Header(threshold, identifier, "s"), secret.payload_symbols
244+
)
209245
assert isinstance(reheadered, (MasterSeed, CoreLightningSecret))
210246
self._secret, self._basis, self._direct_count = (
211247
reheadered,
@@ -227,7 +263,9 @@ def master_seed(
227263
"""Start a ceremony for a fresh shared Bitcoin master seed."""
228264
threshold = _threshold(threshold, allow_zero=False)
229265
_supplied, byte_length = _seed_input(None, byte_length)
230-
identifier = _random_identifier() if identifier is None else _identifier(identifier)
266+
identifier = (
267+
_random_identifier() if identifier is None else _identifier(identifier)
268+
)
231269
return cls._start(
232270
Profile.MS,
233271
_payload_length(byte_length),
@@ -249,7 +287,9 @@ def core_lightning(
249287
) -> CreationCeremony:
250288
"""Start a ceremony for a fresh shared Core Lightning secret."""
251289
threshold = _threshold(threshold, allow_zero=False)
252-
identifier = _random_identifier() if identifier is None else _identifier(identifier)
290+
identifier = (
291+
_random_identifier() if identifier is None else _identifier(identifier)
292+
)
253293
return cls._start(
254294
Profile.CL,
255295
CL_PAYLOAD_LENGTH,
@@ -272,10 +312,14 @@ def from_secret(
272312
) -> CreationCeremony:
273313
"""Start a ceremony that shares an existing validated secret."""
274314
if not isinstance(secret, (MasterSeed, CoreLightningSecret)):
275-
raise TypeError("from_secret accepts only MasterSeed or CoreLightningSecret")
315+
raise TypeError(
316+
"from_secret accepts only MasterSeed or CoreLightningSecret"
317+
)
276318
threshold = _threshold(threshold, allow_zero=False)
277319
random_identifier = identifier is None
278-
identifier = _random_identifier() if random_identifier else _identifier(identifier)
320+
identifier = (
321+
_random_identifier() if random_identifier else _identifier(identifier)
322+
)
279323
while (threshold, identifier) == (
280324
secret.header.threshold,
281325
secret.header.identifier,
@@ -307,7 +351,9 @@ def next_share(self) -> Share:
307351
if self._finished:
308352
raise CeremonyStateError("this creation ceremony is finished")
309353
if self._pending is not None:
310-
raise CeremonyStateError("confirm the pending card before requesting another")
354+
raise CeremonyStateError(
355+
"confirm the pending card before requesting another"
356+
)
311357
if self._position == len(self._indices):
312358
raise CeremonyStateError("all cards are confirmed; finish the ceremony")
313359
index = self._indices[self._position]
@@ -345,7 +391,8 @@ def confirm(self, text: str) -> ConfirmationResult:
345391
mismatched = tuple(
346392
group + 1
347393
for group in range((max(len(observed), len(expected)) + 3) // 4)
348-
if observed[group * 4 : group * 4 + 4] != expected[group * 4 : group * 4 + 4]
394+
if observed[group * 4 : group * 4 + 4]
395+
!= expected[group * 4 : group * 4 + 4]
349396
)
350397
if mismatched:
351398
return ConfirmationResult(False, mismatched)

0 commit comments

Comments
 (0)