fwid 0.1.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.
- fwid/__init__.py +3 -0
- fwid/__main__.py +3 -0
- fwid/cli.py +107 -0
- fwid/helpers/__init__.py +5 -0
- fwid/helpers/base32crockford.py +43 -0
- fwid/helpers/base32hex.py +42 -0
- fwid/helpers/base62.py +37 -0
- fwid/lib.py +174 -0
- fwid-0.1.0.dist-info/METADATA +44 -0
- fwid-0.1.0.dist-info/RECORD +12 -0
- fwid-0.1.0.dist-info/WHEEL +4 -0
- fwid-0.1.0.dist-info/entry_points.txt +3 -0
fwid/__init__.py
ADDED
fwid/__main__.py
ADDED
fwid/cli.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Optional, Sequence
|
|
7
|
+
|
|
8
|
+
from .lib import FWID, FWIDFormat
|
|
9
|
+
|
|
10
|
+
class CLI:
|
|
11
|
+
FORMATS = {
|
|
12
|
+
"standard": FWIDFormat.STANDARD_TEXT,
|
|
13
|
+
"readable": FWIDFormat.READABLE_TEXT,
|
|
14
|
+
"compact": FWIDFormat.COMPACT_TEXT,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@staticmethod
|
|
18
|
+
def parse_datetime(text: str) -> datetime:
|
|
19
|
+
try:
|
|
20
|
+
dt = datetime.fromisoformat(text[:-1] + "+00:00" if text.endswith(("Z", "z")) else text)
|
|
21
|
+
except ValueError:
|
|
22
|
+
raise argparse.ArgumentTypeError(f"invalid ISO 8601 datetime: {text!r}")
|
|
23
|
+
if dt.tzinfo is None:
|
|
24
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
25
|
+
return dt
|
|
26
|
+
|
|
27
|
+
@staticmethod
|
|
28
|
+
def positive_int(text: str) -> int:
|
|
29
|
+
try:
|
|
30
|
+
value = int(text)
|
|
31
|
+
except ValueError:
|
|
32
|
+
raise argparse.ArgumentTypeError(f"invalid integer: {text!r}")
|
|
33
|
+
if value < 1:
|
|
34
|
+
raise argparse.ArgumentTypeError("must be 1 or greater")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def parser() -> argparse.ArgumentParser:
|
|
39
|
+
parser = argparse.ArgumentParser(prog="fwid", description="Generate and inspect FWIDs (FourWord Identifiers).")
|
|
40
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
41
|
+
sub.required = True
|
|
42
|
+
|
|
43
|
+
gen = sub.add_parser("generate", aliases=("g",), help="generate FWIDs")
|
|
44
|
+
gen.add_argument("-b", "--bits", type=CLI.positive_int, default=None,
|
|
45
|
+
help="total bit length, a multiple of %d (default: the smallest that fits the timestamp)" % FWID.BITS_ALIGN)
|
|
46
|
+
gen.add_argument("-f", "--format", choices=sorted(CLI.FORMATS), default="standard",
|
|
47
|
+
help="output format (default: standard)")
|
|
48
|
+
gen.add_argument("-n", "--count", type=CLI.positive_int, default=1,
|
|
49
|
+
help="number of FWIDs to generate (default: 1)")
|
|
50
|
+
gen.add_argument("-t", "--time", type=CLI.parse_datetime, default=None, metavar="DATETIME",
|
|
51
|
+
help="ISO 8601 timestamp to embed; naive values are UTC (default: now)")
|
|
52
|
+
gen.set_defaults(run=CLI.generate)
|
|
53
|
+
|
|
54
|
+
ins = sub.add_parser("inspect", aliases=("i",), help="show the contents of FWIDs")
|
|
55
|
+
ins.add_argument("ids", nargs="*", metavar="FWID",
|
|
56
|
+
help="FWIDs in any text format; read from standard input, one per line, if omitted or '-'")
|
|
57
|
+
ins.set_defaults(run=CLI.inspect)
|
|
58
|
+
return parser
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def generate(args: argparse.Namespace) -> int:
|
|
62
|
+
fmt = CLI.FORMATS[args.format]
|
|
63
|
+
for _ in range(args.count):
|
|
64
|
+
print(FWID(args.bits, args.time).text(fmt))
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def inspect(args: argparse.Namespace) -> int:
|
|
69
|
+
if not args.ids or args.ids == ["-"]:
|
|
70
|
+
texts = [line.strip() for line in sys.stdin if line.strip()]
|
|
71
|
+
else:
|
|
72
|
+
texts = args.ids
|
|
73
|
+
status = 0
|
|
74
|
+
for i, text in enumerate(texts):
|
|
75
|
+
if i > 0:
|
|
76
|
+
print()
|
|
77
|
+
try:
|
|
78
|
+
fmt = FWIDFormat.detect(text)
|
|
79
|
+
fwid = FWID.from_text(text)
|
|
80
|
+
timestamp = fwid.timestamp.isoformat(timespec="milliseconds")
|
|
81
|
+
except ValueError as e:
|
|
82
|
+
print(f"fwid: {text}: {e}", file=sys.stderr)
|
|
83
|
+
status = 1
|
|
84
|
+
continue
|
|
85
|
+
print(f"Format: {fmt.value}")
|
|
86
|
+
print(f"Bits: {fwid.bits} (timestamp {fwid.bits_timestamp}, random {fwid.bits_random})")
|
|
87
|
+
print(f"Timestamp: {timestamp} ({fwid.timestamp_ms} ms)")
|
|
88
|
+
print(f"Hex: {fwid.raw.hex()}")
|
|
89
|
+
print(f"Standard: {fwid.standard_text}")
|
|
90
|
+
print(f"Readable: {fwid.readable_text}")
|
|
91
|
+
print(f"Compact: {fwid.compact_text}")
|
|
92
|
+
return status
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def main(argv: Optional[Sequence[str]] = None) -> None:
|
|
96
|
+
args = CLI.parser().parse_args(argv)
|
|
97
|
+
try:
|
|
98
|
+
code = args.run(args)
|
|
99
|
+
except ValueError as e:
|
|
100
|
+
print(f"fwid: {e}", file=sys.stderr)
|
|
101
|
+
code = 1
|
|
102
|
+
except BrokenPipeError:
|
|
103
|
+
code = 1
|
|
104
|
+
sys.exit(code)
|
|
105
|
+
|
|
106
|
+
def main(argv: Optional[Sequence[str]] = None) -> None:
|
|
107
|
+
CLI.main(argv)
|
fwid/helpers/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
class Base32Crockford:
|
|
2
|
+
"""Crockford's Base32 without check symbols and without padding.
|
|
3
|
+
|
|
4
|
+
Encoding emits uppercase symbols. Decoding is case-insensitive and maps
|
|
5
|
+
the look-alike symbols I and L to 1 and O to 0, as Crockford specifies.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
9
|
+
# ASCII only: str.upper() maps some non-ASCII characters (e.g. U+017F) onto ASCII letters.
|
|
10
|
+
VALUES = dict(zip(ALPHABET + ALPHABET.lower(), list(range(32)) * 2))
|
|
11
|
+
VALUES.update({"I": 1, "L": 1, "O": 0, "i": 1, "l": 1, "o": 0})
|
|
12
|
+
BYTES_FROM_CHARS = {8: 5, 7: 4, 5: 3, 4: 2, 2: 1, 0: 0}
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def encode(cls, data: bytes) -> str:
|
|
16
|
+
out = []
|
|
17
|
+
for i in range(0, len(data), 5):
|
|
18
|
+
chunk = data[i:i + 5]
|
|
19
|
+
n = len(chunk)
|
|
20
|
+
value = int.from_bytes(chunk, "big") << (8 * (5 - n))
|
|
21
|
+
chars = (n * 8 + 4) // 5
|
|
22
|
+
out.extend(cls.ALPHABET[(value >> (35 - 5 * j)) & 31] for j in range(chars))
|
|
23
|
+
return "".join(out)
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def decode(cls, text: str) -> bytes:
|
|
27
|
+
out = bytearray()
|
|
28
|
+
for i in range(0, len(text), 8):
|
|
29
|
+
block = text[i:i + 8]
|
|
30
|
+
n = cls.BYTES_FROM_CHARS.get(len(block))
|
|
31
|
+
if n is None:
|
|
32
|
+
raise ValueError("Invalid Base32Crockford length")
|
|
33
|
+
value = 0
|
|
34
|
+
for ch in block:
|
|
35
|
+
index = cls.VALUES.get(ch)
|
|
36
|
+
if index is None:
|
|
37
|
+
raise ValueError(f"Invalid character: {ch!r}")
|
|
38
|
+
value = (value << 5) | index
|
|
39
|
+
extra = len(block) * 5 - n * 8
|
|
40
|
+
if value & ((1 << extra) - 1):
|
|
41
|
+
raise ValueError("Non-zero trailing bits")
|
|
42
|
+
out += (value >> extra).to_bytes(n, "big")
|
|
43
|
+
return bytes(out)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
class Base32Hex:
|
|
2
|
+
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUV"
|
|
3
|
+
PAD = "Z"
|
|
4
|
+
BYTES_FROM_CHARS = {8: 5, 7: 4, 5: 3, 4: 2, 2: 1}
|
|
5
|
+
|
|
6
|
+
@classmethod
|
|
7
|
+
def encode(cls, data: bytes) -> str:
|
|
8
|
+
out = []
|
|
9
|
+
for i in range(0, len(data), 5):
|
|
10
|
+
chunk = data[i:i + 5]
|
|
11
|
+
n = len(chunk)
|
|
12
|
+
value = int.from_bytes(chunk, "big") << (8 * (5 - n))
|
|
13
|
+
chars = (n * 8 + 4) // 5
|
|
14
|
+
out.extend(cls.ALPHABET[(value >> (35 - 5 * j)) & 31] for j in range(chars))
|
|
15
|
+
out.append(cls.PAD * (8 - chars))
|
|
16
|
+
return "".join(out)
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def decode(cls, text: str) -> bytes:
|
|
20
|
+
if len(text) % 8 != 0:
|
|
21
|
+
raise ValueError("Base32Hex length must be a multiple of 8")
|
|
22
|
+
out = bytearray()
|
|
23
|
+
blocks = len(text) // 8
|
|
24
|
+
for b in range(blocks):
|
|
25
|
+
block = text[b * 8:(b + 1) * 8]
|
|
26
|
+
body = block.rstrip(cls.PAD)
|
|
27
|
+
if body != block and b != blocks - 1:
|
|
28
|
+
raise ValueError("Padding is only allowed in the last block")
|
|
29
|
+
n = cls.BYTES_FROM_CHARS.get(len(body))
|
|
30
|
+
if n is None:
|
|
31
|
+
raise ValueError("Invalid padding length")
|
|
32
|
+
value = 0
|
|
33
|
+
for ch in body:
|
|
34
|
+
index = cls.ALPHABET.find(ch)
|
|
35
|
+
if index < 0:
|
|
36
|
+
raise ValueError(f"Invalid character: {ch!r}")
|
|
37
|
+
value = (value << 5) | index
|
|
38
|
+
extra = len(body) * 5 - n * 8
|
|
39
|
+
if value & ((1 << extra) - 1):
|
|
40
|
+
raise ValueError("Non-zero trailing bits")
|
|
41
|
+
out += (value >> extra).to_bytes(n, "big")
|
|
42
|
+
return bytes(out)
|
fwid/helpers/base62.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
class Base62:
|
|
2
|
+
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
3
|
+
|
|
4
|
+
@classmethod
|
|
5
|
+
def length(cls, size: int) -> int:
|
|
6
|
+
limit = 256 ** size
|
|
7
|
+
chars, capacity = 0, 1
|
|
8
|
+
while capacity < limit:
|
|
9
|
+
capacity *= 62
|
|
10
|
+
chars += 1
|
|
11
|
+
return chars
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def encode(cls, data: bytes) -> str:
|
|
15
|
+
value = int.from_bytes(data, "big")
|
|
16
|
+
out = []
|
|
17
|
+
for _ in range(cls.length(len(data))):
|
|
18
|
+
value, rem = divmod(value, 62)
|
|
19
|
+
out.append(cls.ALPHABET[rem])
|
|
20
|
+
return "".join(reversed(out))
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def decode(cls, text: str) -> bytes:
|
|
24
|
+
size = 0
|
|
25
|
+
while cls.length(size) < len(text):
|
|
26
|
+
size += 1
|
|
27
|
+
if cls.length(size) != len(text):
|
|
28
|
+
raise ValueError("Invalid Base62 length")
|
|
29
|
+
value = 0
|
|
30
|
+
for ch in text:
|
|
31
|
+
index = cls.ALPHABET.find(ch)
|
|
32
|
+
if index < 0:
|
|
33
|
+
raise ValueError(f"Invalid character: {ch!r}")
|
|
34
|
+
value = value * 62 + index
|
|
35
|
+
if value >= 256 ** size:
|
|
36
|
+
raise ValueError("Value out of range")
|
|
37
|
+
return value.to_bytes(size, "big")
|
fwid/lib.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Optional, Union
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
|
|
8
|
+
from .helpers import Base32Crockford, Base32Hex, Base62
|
|
9
|
+
|
|
10
|
+
class FWIDFormat(Enum):
|
|
11
|
+
UNFORMATTED = "Unformatted"
|
|
12
|
+
# Text
|
|
13
|
+
STANDARD_TEXT = "Standard Text"
|
|
14
|
+
READABLE_TEXT = "Readable Text"
|
|
15
|
+
COMPACT_TEXT = "Compact Text"
|
|
16
|
+
|
|
17
|
+
@staticmethod
|
|
18
|
+
def detect(arg: Union[bytes, str]) -> FWIDFormat:
|
|
19
|
+
if isinstance(arg, bytes):
|
|
20
|
+
return FWIDFormat.UNFORMATTED
|
|
21
|
+
elif isinstance(arg, str):
|
|
22
|
+
parsers = (
|
|
23
|
+
(FWIDFormat.STANDARD_TEXT, FWID.from_standard_text),
|
|
24
|
+
(FWIDFormat.READABLE_TEXT, FWID.from_readable_text),
|
|
25
|
+
(FWIDFormat.COMPACT_TEXT, FWID.from_compact_text),
|
|
26
|
+
)
|
|
27
|
+
for fmt, parse in parsers:
|
|
28
|
+
try:
|
|
29
|
+
parse(arg)
|
|
30
|
+
except ValueError:
|
|
31
|
+
continue
|
|
32
|
+
return fmt
|
|
33
|
+
raise ValueError("Unknown Format")
|
|
34
|
+
|
|
35
|
+
class FWID:
|
|
36
|
+
EPOCH = datetime(2001, 1, 1, tzinfo=timezone.utc)
|
|
37
|
+
BITS_ALIGN = 32
|
|
38
|
+
__slots__ = ("raw",)
|
|
39
|
+
|
|
40
|
+
def __init__(self, arg: Optional[Union[bytes, str, int]] = None, dt: Optional[datetime] = None):
|
|
41
|
+
if arg is None:
|
|
42
|
+
self.raw = FWID.generate(dt=dt)
|
|
43
|
+
elif isinstance(arg, bytes):
|
|
44
|
+
FWID.check_bits(len(arg) * 8)
|
|
45
|
+
self.raw = arg
|
|
46
|
+
elif isinstance(arg, str):
|
|
47
|
+
self.raw = FWID.from_text(arg).raw
|
|
48
|
+
elif isinstance(arg, int):
|
|
49
|
+
self.raw = FWID.generate(arg, dt)
|
|
50
|
+
else:
|
|
51
|
+
raise TypeError(f"Unsupported argument type: {type(arg).__name__}")
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def check_bits(bits: int) -> None:
|
|
55
|
+
if bits < FWID.BITS_ALIGN or bits % FWID.BITS_ALIGN != 0:
|
|
56
|
+
raise ValueError(f"Bits must be a positive multiple of {FWID.BITS_ALIGN}")
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def epoch_ms(dt: Optional[datetime] = None) -> int:
|
|
60
|
+
if dt is None:
|
|
61
|
+
dt = datetime.now(timezone.utc)
|
|
62
|
+
elif dt.tzinfo is None or dt.utcoffset() is None:
|
|
63
|
+
raise ValueError("datetime must be timezone-aware")
|
|
64
|
+
ms = (dt - FWID.EPOCH) // timedelta(milliseconds=1)
|
|
65
|
+
if ms < 0:
|
|
66
|
+
raise ValueError("datetime must not be before the FWID epoch (2001-01-01 00:00:00 UTC)")
|
|
67
|
+
return ms
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def from_text(text: str) -> "FWID":
|
|
71
|
+
for parse in (FWID.from_standard_text, FWID.from_readable_text, FWID.from_compact_text):
|
|
72
|
+
try:
|
|
73
|
+
return parse(text)
|
|
74
|
+
except ValueError:
|
|
75
|
+
continue
|
|
76
|
+
raise ValueError("Unknown Format")
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def from_standard_text(text: str) -> "FWID":
|
|
80
|
+
return FWID(Base32Hex.decode(text))
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def from_readable_text(text: str) -> "FWID":
|
|
84
|
+
if text != text.lower():
|
|
85
|
+
raise ValueError("Readable Text must be lowercase")
|
|
86
|
+
groups = text.split("-")
|
|
87
|
+
if any(len(group) != 8 for group in groups[:-1]) or not 1 <= len(groups[-1]) <= 8:
|
|
88
|
+
raise ValueError("Readable Text must be split into groups of 8 characters (the last may be shorter)")
|
|
89
|
+
return FWID(Base32Crockford.decode("".join(groups)))
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def from_compact_text(text: str) -> "FWID":
|
|
93
|
+
return FWID(Base62.decode(text))
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def min_bits_for_ms(ms: int) -> int:
|
|
97
|
+
return max(1, (ms.bit_length() + 7) // 8) * FWID.BITS_ALIGN
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def min_bits(dt: Optional[datetime] = None) -> int:
|
|
101
|
+
return FWID.min_bits_for_ms(FWID.epoch_ms(dt))
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def generate(bits: Optional[int] = None, dt: Optional[datetime] = None) -> bytes:
|
|
105
|
+
ms = FWID.epoch_ms(dt)
|
|
106
|
+
required = FWID.min_bits_for_ms(ms)
|
|
107
|
+
if bits is None:
|
|
108
|
+
bits = required
|
|
109
|
+
FWID.check_bits(bits)
|
|
110
|
+
if ms.bit_length() > bits // 4:
|
|
111
|
+
raise ValueError(f"{bits} bits is too small for this timestamp (need at least {required})")
|
|
112
|
+
return ms.to_bytes(bits // 32, "big") + secrets.token_bytes(bits // 32 * 3)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def bits(self) -> int:
|
|
116
|
+
return len(self.raw) * 8
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def bits_timestamp(self) -> int:
|
|
120
|
+
return self.bits // 4
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def bits_random(self) -> int:
|
|
124
|
+
return (self.bits // 4) * 3
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def timestamp_ms(self) -> int:
|
|
128
|
+
return int.from_bytes(self.raw[:self.bits_timestamp // 8], "big")
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def timestamp(self) -> datetime:
|
|
132
|
+
try:
|
|
133
|
+
return FWID.EPOCH + timedelta(milliseconds=self.timestamp_ms)
|
|
134
|
+
except OverflowError:
|
|
135
|
+
raise ValueError("timestamp is out of the range of datetime") from None
|
|
136
|
+
|
|
137
|
+
def text(self, format: FWIDFormat = FWIDFormat.STANDARD_TEXT) -> str:
|
|
138
|
+
if format == FWIDFormat.STANDARD_TEXT:
|
|
139
|
+
return self.standard_text
|
|
140
|
+
if format == FWIDFormat.READABLE_TEXT:
|
|
141
|
+
return self.readable_text
|
|
142
|
+
if format == FWIDFormat.COMPACT_TEXT:
|
|
143
|
+
return self.compact_text
|
|
144
|
+
raise ValueError(f"Format '{format.value}' is not Text-based Format")
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def standard_text(self) -> str:
|
|
148
|
+
return Base32Hex.encode(self.raw)
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def readable_text(self) -> str:
|
|
152
|
+
standard = Base32Crockford.encode(self.raw).lower()
|
|
153
|
+
return "-".join(standard[i:i + 8] for i in range(0, len(standard), 8))
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def compact_text(self) -> str:
|
|
157
|
+
return Base62.encode(self.raw)
|
|
158
|
+
|
|
159
|
+
def __bytes__(self) -> bytes:
|
|
160
|
+
return self.raw
|
|
161
|
+
|
|
162
|
+
def __str__(self) -> str:
|
|
163
|
+
return self.text()
|
|
164
|
+
|
|
165
|
+
def __repr__(self) -> str:
|
|
166
|
+
return f"FWID({self.standard_text!r})"
|
|
167
|
+
|
|
168
|
+
def __eq__(self, other: object) -> bool:
|
|
169
|
+
if not isinstance(other, FWID):
|
|
170
|
+
return NotImplemented
|
|
171
|
+
return self.raw == other.raw
|
|
172
|
+
|
|
173
|
+
def __hash__(self) -> int:
|
|
174
|
+
return hash(self.raw)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: fwid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Requires-Python: >=3.8
|
|
5
|
+
Project-URL: GitHub, https://github.com/nercone-dev/fwid/
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
|
|
8
|
+
[[Japanese/日本語](README.ja.md)]
|
|
9
|
+
|
|
10
|
+
# FWID (FourWord Identifier)
|
|
11
|
+
A novel random identifier generation method with time-series sortability.
|
|
12
|
+
|
|
13
|
+
## Overview
|
|
14
|
+
FWID is a random identifier designed for use cases such as database primary keys.
|
|
15
|
+
|
|
16
|
+
The length is variable: any multiple of 32 bits. As of 2026-11-04, the recommended length is 192 bits.
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
[ timestamp: total bits / 4 ] + [ CSPRNG output: total bits / 4 × 3 ]
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The timestamp is the number of milliseconds since 2001-01-01 00:00:00 UTC. Because it occupies a quarter of the total length instead of a fixed width, a longer identifier also lasts longer before its timestamp overflows. The trade-off is more leading zeros in the timestamp.
|
|
23
|
+
|
|
24
|
+
## Formats
|
|
25
|
+
|
|
26
|
+
| Format | Encoding | Example (192 bits) |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| Standard Text | Base32 Hex, `Z` as padding | `00NNTHJS00TETRA0QEQOA000000000001LISHPGZ` |
|
|
29
|
+
| Readable Text | Crockford's Base32, lowercase, no padding, hyphen every 8 characters | `00qqxhkw-00xexva0-tetra000-00000000-1njwhsg` |
|
|
30
|
+
| Compact Text | Base62, fixed length | `007h3WQ0lRIoEEs6MANGd9PJQhKTtetra` |
|
|
31
|
+
|
|
32
|
+
See [SPEC.md](SPEC.md) for the full specification: bit lengths, layout, overflow rules, text formats and their parsing rules, collision probability and overflow times.
|
|
33
|
+
|
|
34
|
+
## Etymology
|
|
35
|
+
The name "Four" comes from the fact that the timestamp occupies 1/4 of the bit length.
|
|
36
|
+
It is also a wordplay on the word "Forward".
|
|
37
|
+
|
|
38
|
+
## Implementations
|
|
39
|
+
Implementations for Python (this package, in `src/fwid`), Rust, Go, Swift, JavaScript and Lython Compiler are included, each with the same command line tool. See [docs/implementations.md](docs/implementations.md).
|
|
40
|
+
|
|
41
|
+
## License
|
|
42
|
+
The source code and libraries in this repository are freely available under the MIT License.
|
|
43
|
+
|
|
44
|
+
No attribution is required for software that utilizes the FWID specification itself or for data generated using FWID.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
fwid/__init__.py,sha256=8L_7eUmGMpv-kHWfABccBIee5R5gyG-eiXwe-BHvvH4,42
|
|
2
|
+
fwid/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
3
|
+
fwid/cli.py,sha256=w7J1L2_MS2zR5Hh6riGKnMGj2C_5STosmjM5HoS3m1g,4284
|
|
4
|
+
fwid/helpers/__init__.py,sha256=Cjd1iwxLu21QvrdqO0Li5e_UFPBJDPfVO9L20PXwQr4,159
|
|
5
|
+
fwid/helpers/base32crockford.py,sha256=QaP2C2igBfzh9Xkt_JwA4IKhZAEM5dXe7gQem_mwHd0,1770
|
|
6
|
+
fwid/helpers/base32hex.py,sha256=LseL79h1vEhHyIoIq4VLz9zWdAuSb2pT0eG8iRibXRc,1645
|
|
7
|
+
fwid/helpers/base62.py,sha256=aVZ79LAdVeEvAiBTTuBBm14Ol8-9EyJb4O_IKma439M,1180
|
|
8
|
+
fwid/lib.py,sha256=ZVFnvgwbV0uZa9KwlMRaq0FzSVGJi6wxZ9pYeVmZdq8,5914
|
|
9
|
+
fwid-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
10
|
+
fwid-0.1.0.dist-info/entry_points.txt,sha256=Og3nAFvRfOnLE7s61c9w9yK2TJfva_J-n1ZTvRBcFJM,40
|
|
11
|
+
fwid-0.1.0.dist-info/METADATA,sha256=jcEFmjyksiGZBGsB3jntyxbaTG-IOvxJMfoaq_Kp6ks,2016
|
|
12
|
+
fwid-0.1.0.dist-info/RECORD,,
|