stellar-strkey 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.
- stellar_strkey/__init__.py +58 -0
- stellar_strkey/_codec.py +82 -0
- stellar_strkey/_errors.py +69 -0
- stellar_strkey/_keys.py +526 -0
- stellar_strkey/py.typed +0 -0
- stellar_strkey-0.1.0.dist-info/METADATA +165 -0
- stellar_strkey-0.1.0.dist-info/RECORD +9 -0
- stellar_strkey-0.1.0.dist-info/WHEEL +4 -0
- stellar_strkey-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Encode and decode Stellar strkeys as defined by SEP-23.
|
|
2
|
+
|
|
3
|
+
Every strkey type has its own immutable class. Use `parse` when the type is not known
|
|
4
|
+
in advance. See https://stellar-strkey.readthedocs.io/ for the guide.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._errors import (
|
|
8
|
+
ChecksumMismatchError,
|
|
9
|
+
MalformedStrkeyError,
|
|
10
|
+
StrkeyError,
|
|
11
|
+
UnsupportedVersionError,
|
|
12
|
+
WrongStrkeyTypeError,
|
|
13
|
+
)
|
|
14
|
+
from ._keys import (
|
|
15
|
+
ClaimableBalance,
|
|
16
|
+
Contract,
|
|
17
|
+
Ed25519PrivateKey,
|
|
18
|
+
Ed25519PublicKey,
|
|
19
|
+
Ed25519SignedPayload,
|
|
20
|
+
HashX,
|
|
21
|
+
LiquidityPool,
|
|
22
|
+
MuxedContract,
|
|
23
|
+
MuxedEd25519Account,
|
|
24
|
+
PreAuthTx,
|
|
25
|
+
Strkey,
|
|
26
|
+
parse,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"ChecksumMismatchError",
|
|
31
|
+
"ClaimableBalance",
|
|
32
|
+
"Contract",
|
|
33
|
+
"Ed25519PrivateKey",
|
|
34
|
+
"Ed25519PublicKey",
|
|
35
|
+
"Ed25519SignedPayload",
|
|
36
|
+
"HashX",
|
|
37
|
+
"LiquidityPool",
|
|
38
|
+
"MalformedStrkeyError",
|
|
39
|
+
"MuxedContract",
|
|
40
|
+
"MuxedEd25519Account",
|
|
41
|
+
"PreAuthTx",
|
|
42
|
+
"Strkey",
|
|
43
|
+
"StrkeyError",
|
|
44
|
+
"UnsupportedVersionError",
|
|
45
|
+
"WrongStrkeyTypeError",
|
|
46
|
+
"parse",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
# Show the public path in tracebacks and pickles, so that old pickles stay loadable when
|
|
50
|
+
# the private modules are reorganized. A union alias has no `__module__` to set.
|
|
51
|
+
#
|
|
52
|
+
# The cost is that inspect.getsource() can't find the classes, so tools that read the
|
|
53
|
+
# source at run time, such as IPython's `??` and Sphinx's viewcode, can't show it. IDEs
|
|
54
|
+
# and mkdocstrings read the files directly and are not affected.
|
|
55
|
+
for _name in __all__:
|
|
56
|
+
if _name != "Strkey":
|
|
57
|
+
globals()[_name].__module__ = __name__
|
|
58
|
+
del _name # pyright: ignore[reportPossiblyUnboundVariable]
|
stellar_strkey/_codec.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""The strkey wire format: `base32(version || payload || crc16-xmodem)`."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
from ._errors import ChecksumMismatchError, MalformedStrkeyError
|
|
8
|
+
|
|
9
|
+
_VERSION_LEN: Final = 1
|
|
10
|
+
_CHECKSUM_LEN: Final = 2
|
|
11
|
+
_BASE32_BLOCK_LEN: Final = 8
|
|
12
|
+
|
|
13
|
+
# The length is checked before decoding, so that hostile input is rejected without being
|
|
14
|
+
# decoded. The cost is that a future strkey type with a longer payload would be reported
|
|
15
|
+
# as malformed rather than as an unsupported version until this limit is raised for it.
|
|
16
|
+
MAX_PAYLOAD_LEN: Final = 100
|
|
17
|
+
"""The largest payload of any type: a signed payload with a 64-byte inner payload."""
|
|
18
|
+
|
|
19
|
+
# The padding standard base32 needs for each valid remainder of the encoded length.
|
|
20
|
+
# Lengths congruent to 1, 3 or 6 mod 8 cannot be produced by any byte sequence.
|
|
21
|
+
_PADDING_BY_REMAINDER: Final = {0: 0, 2: 6, 4: 4, 5: 3, 7: 1}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _checksum(data: bytes) -> bytes:
|
|
25
|
+
return binascii.crc_hqx(data, 0).to_bytes(_CHECKSUM_LEN, "little")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def encode(version: int, payload: bytes) -> str:
|
|
29
|
+
"""Encode a version byte and a payload into a strkey."""
|
|
30
|
+
data = bytes((version,)) + payload
|
|
31
|
+
return base64.b32encode(data + _checksum(data)).rstrip(b"=").decode("ascii")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def decode(value: str) -> tuple[int, bytes]:
|
|
35
|
+
"""Decode a strkey into its version byte and payload.
|
|
36
|
+
|
|
37
|
+
The length is checked before any decoding happens, which bounds the work done
|
|
38
|
+
on hostile input. SEP-23 only accepts a strkey that re-encodes to exactly the
|
|
39
|
+
same string, which also rejects padding, lower case and non-zero trailing bits.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
value: The strkey to decode.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
The version byte and the payload.
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
TypeError: If `value` is not a `str`.
|
|
49
|
+
MalformedStrkeyError: If `value` is not a well-formed strkey.
|
|
50
|
+
"""
|
|
51
|
+
if not isinstance(value, str): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
52
|
+
raise TypeError(f"strkey must be str, got {type(value).__name__}")
|
|
53
|
+
# A str subclass can override __len__ or encode and so get past the length check
|
|
54
|
+
# that bounds the work done on hostile input. str.__str__ is implemented in C and
|
|
55
|
+
# always returns an exact str with the real content, without copying an exact str.
|
|
56
|
+
value = str.__str__(value)
|
|
57
|
+
|
|
58
|
+
padding = _PADDING_BY_REMAINDER.get(len(value) % _BASE32_BLOCK_LEN)
|
|
59
|
+
if padding is None:
|
|
60
|
+
raise MalformedStrkeyError("strkey has an impossible base32 length")
|
|
61
|
+
|
|
62
|
+
data_len = len(value) * 5 // 8
|
|
63
|
+
if data_len < _VERSION_LEN + _CHECKSUM_LEN:
|
|
64
|
+
raise MalformedStrkeyError(
|
|
65
|
+
"strkey is too short to hold a version and a checksum"
|
|
66
|
+
)
|
|
67
|
+
if data_len > _VERSION_LEN + MAX_PAYLOAD_LEN + _CHECKSUM_LEN:
|
|
68
|
+
raise MalformedStrkeyError(
|
|
69
|
+
f"strkey payload exceeds {MAX_PAYLOAD_LEN} bytes, the most of any type"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
encoded = value.encode("ascii")
|
|
74
|
+
data = base64.b32decode(encoded + b"=" * padding)
|
|
75
|
+
except ValueError: # UnicodeEncodeError and binascii.Error
|
|
76
|
+
raise MalformedStrkeyError("strkey is not valid base32") from None
|
|
77
|
+
if base64.b32encode(data).rstrip(b"=") != encoded:
|
|
78
|
+
raise MalformedStrkeyError("strkey is not canonical base32")
|
|
79
|
+
|
|
80
|
+
if _checksum(data[:-_CHECKSUM_LEN]) != data[-_CHECKSUM_LEN:]:
|
|
81
|
+
raise ChecksumMismatchError("strkey checksum does not match")
|
|
82
|
+
return data[0], data[_VERSION_LEN:-_CHECKSUM_LEN]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Exceptions raised when a string is not an acceptable strkey.
|
|
2
|
+
|
|
3
|
+
Only `from_string` and `parse` raise these, with one exception:
|
|
4
|
+
`ClaimableBalance.from_bytes` raises `UnsupportedVersionError` for an unknown claimable
|
|
5
|
+
balance version, because that is a protocol version problem rather than bad key
|
|
6
|
+
material. Constructors and `from_bytes` otherwise raise a plain `ValueError`, as
|
|
7
|
+
Python's own constructors do, because no strkey is involved there.
|
|
8
|
+
|
|
9
|
+
Messages never contain the strkey or key material being processed, because the input
|
|
10
|
+
may be a secret seed and exception messages tend to end up in logs.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class StrkeyError(ValueError):
|
|
15
|
+
"""Base class of the errors raised when a string is not an acceptable strkey."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class MalformedStrkeyError(StrkeyError):
|
|
19
|
+
"""The string is not a well-formed strkey.
|
|
20
|
+
|
|
21
|
+
For example, it isn't canonical base32, or it has the wrong length or structure for
|
|
22
|
+
its type. The message says what is wrong.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ChecksumMismatchError(MalformedStrkeyError):
|
|
27
|
+
"""The checksum does not match, which usually means the strkey was mistyped."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class UnsupportedVersionError(StrkeyError):
|
|
31
|
+
"""The strkey's version is not one this package knows.
|
|
32
|
+
|
|
33
|
+
Either its version byte is unknown, or it is a claimable balance of an unknown
|
|
34
|
+
version. It may be a strkey type introduced after this release of the package.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class WrongStrkeyTypeError(StrkeyError):
|
|
39
|
+
"""The string is a strkey of another type than the one that was asked for.
|
|
40
|
+
|
|
41
|
+
Only its encoding, checksum and version byte are checked. The rest is not, since the
|
|
42
|
+
strkey would be rejected anyway.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
expected: The type that was asked for, or `None` when
|
|
46
|
+
[`parse`][stellar_strkey.parse] refused a private key, since it would have
|
|
47
|
+
accepted any other type.
|
|
48
|
+
found: The type of the strkey that was given.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
expected: type[object] | None
|
|
52
|
+
found: type[object]
|
|
53
|
+
|
|
54
|
+
def __init__(self, expected: type[object] | None, found: type[object]) -> None:
|
|
55
|
+
# Passing the attributes to the base class keeps the exception picklable.
|
|
56
|
+
super().__init__(expected, found)
|
|
57
|
+
self.expected = expected
|
|
58
|
+
self.found = found
|
|
59
|
+
|
|
60
|
+
def __str__(self) -> str:
|
|
61
|
+
if self.expected is None:
|
|
62
|
+
return (
|
|
63
|
+
"parse() does not return private keys; "
|
|
64
|
+
f"use {self.found.__name__}.from_string"
|
|
65
|
+
)
|
|
66
|
+
return (
|
|
67
|
+
f"expected a strkey of type {self.expected.__name__}, "
|
|
68
|
+
f"got one of type {self.found.__name__}"
|
|
69
|
+
)
|
stellar_strkey/_keys.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""One immutable class per strkey type, plus `parse` for unknown input."""
|
|
2
|
+
|
|
3
|
+
import hmac
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from dataclasses import FrozenInstanceError, dataclass
|
|
6
|
+
from typing import ClassVar, Final, NoReturn, Self, SupportsIndex, TypeAlias, TypeVar
|
|
7
|
+
|
|
8
|
+
from ._codec import MAX_PAYLOAD_LEN as _MAX_ANY_PAYLOAD_LEN
|
|
9
|
+
from ._codec import decode, encode
|
|
10
|
+
from ._errors import (
|
|
11
|
+
MalformedStrkeyError,
|
|
12
|
+
StrkeyError,
|
|
13
|
+
UnsupportedVersionError,
|
|
14
|
+
WrongStrkeyTypeError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
_KEY_LEN: Final = 32
|
|
18
|
+
_ID_LEN: Final = 8
|
|
19
|
+
_LENGTH_PREFIX_LEN: Final = 4
|
|
20
|
+
_XDR_ALIGNMENT: Final = 4
|
|
21
|
+
_MAX_ID: Final = 2**64 - 1
|
|
22
|
+
_MIN_INNER_PAYLOAD_LEN: Final = 1
|
|
23
|
+
_MAX_INNER_PAYLOAD_LEN: Final = 64
|
|
24
|
+
_MUXED_PAYLOAD_LEN: Final = _KEY_LEN + _ID_LEN
|
|
25
|
+
_CLAIMABLE_BALANCE_V0: Final = b"\x00"
|
|
26
|
+
|
|
27
|
+
# SEP-23 version bytes: the key type in the top five bits, the algorithm in the rest.
|
|
28
|
+
_PUBLIC_KEY: Final = 6 << 3
|
|
29
|
+
_PRIVATE_KEY: Final = 18 << 3
|
|
30
|
+
_MUXED_ACCOUNT: Final = 12 << 3
|
|
31
|
+
_SIGNED_PAYLOAD: Final = 15 << 3
|
|
32
|
+
_PRE_AUTH_TX: Final = 19 << 3
|
|
33
|
+
_HASH_X: Final = 23 << 3
|
|
34
|
+
_CONTRACT: Final = 2 << 3
|
|
35
|
+
_LIQUIDITY_POOL: Final = 11 << 3
|
|
36
|
+
_CLAIMABLE_BALANCE: Final = 1 << 3
|
|
37
|
+
_MUXED_CONTRACT: Final = 22 << 3
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _require_bytes(name: str, value: bytes) -> bytes:
|
|
41
|
+
"""Return `value` as exact `bytes`, or raise `TypeError` if it isn't bytes."""
|
|
42
|
+
# Coercing with bytes() would turn the integer 32 into 32 zero bytes.
|
|
43
|
+
if not isinstance(value, bytes): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
44
|
+
raise TypeError(f"{name} must be bytes, got {type(value).__name__}")
|
|
45
|
+
# A bytes subclass can override __len__, __bool__ or __bytes__ and so get past the
|
|
46
|
+
# checks below, so its real content is copied out through the buffer protocol,
|
|
47
|
+
# which Python code can't override. Exact bytes, the usual case, aren't copied.
|
|
48
|
+
return value if type(value) is bytes else memoryview(value).tobytes()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _require_len(name: str, value: bytes, length: int) -> bytes:
|
|
52
|
+
value = _require_bytes(name, value)
|
|
53
|
+
if len(value) != length:
|
|
54
|
+
raise ValueError(f"{name} must be {length} bytes, got {len(value)}")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _require_id(value: int) -> None:
|
|
59
|
+
if not isinstance(value, int) or isinstance(value, bool): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
60
|
+
raise TypeError(f"id must be int, got {type(value).__name__}")
|
|
61
|
+
if not 0 <= value <= _MAX_ID:
|
|
62
|
+
raise ValueError("id must fit in an unsigned 64-bit integer")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _xdr_padding_len(length: int) -> int:
|
|
66
|
+
return -length % _XDR_ALIGNMENT
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_T = TypeVar("_T", bound="_Strkey")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _from_payload(strkey_type: type[_T], payload: bytes) -> _T:
|
|
73
|
+
try:
|
|
74
|
+
return strkey_type.from_bytes(payload)
|
|
75
|
+
except StrkeyError:
|
|
76
|
+
raise
|
|
77
|
+
except ValueError as error:
|
|
78
|
+
# Invalid key material is a plain ValueError, but inside a strkey it means that
|
|
79
|
+
# the strkey is malformed. The message never contains the input.
|
|
80
|
+
raise MalformedStrkeyError(str(error)) from None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _Strkey(ABC):
|
|
84
|
+
"""The operations shared by every strkey type."""
|
|
85
|
+
|
|
86
|
+
__slots__ = ()
|
|
87
|
+
|
|
88
|
+
_VERSION_BYTE: ClassVar[int]
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
@abstractmethod
|
|
92
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
93
|
+
"""Build an instance from the binary form of the strkey.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
data: The binary form, in the layout `to_bytes` returns.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
TypeError: If `data` is not `bytes`.
|
|
100
|
+
ValueError: If `data` is not a valid binary form for this type.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
@abstractmethod
|
|
104
|
+
def to_bytes(self) -> bytes:
|
|
105
|
+
"""Return the binary form of the strkey, without version byte and checksum."""
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_string(cls, value: str) -> Self:
|
|
109
|
+
"""Decode a strkey of exactly this type.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
value: The strkey to decode.
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
TypeError: If `value` is not a `str`.
|
|
116
|
+
MalformedStrkeyError: If `value` is not a well-formed strkey.
|
|
117
|
+
WrongStrkeyTypeError: If `value` is a strkey of another type.
|
|
118
|
+
UnsupportedVersionError: If the version of `value` is unknown.
|
|
119
|
+
"""
|
|
120
|
+
# The type is checked before its length, so an `M...` address given to a
|
|
121
|
+
# `G...` parser is reported as the wrong type rather than as too long.
|
|
122
|
+
version, payload = decode(value)
|
|
123
|
+
if version != cls._VERSION_BYTE:
|
|
124
|
+
found = _TYPES_BY_VERSION_BYTE.get(version)
|
|
125
|
+
if found is None:
|
|
126
|
+
raise UnsupportedVersionError(
|
|
127
|
+
f"unsupported version byte {version:#04x}"
|
|
128
|
+
)
|
|
129
|
+
raise WrongStrkeyTypeError(cls, found)
|
|
130
|
+
return _from_payload(cls, payload)
|
|
131
|
+
|
|
132
|
+
@classmethod
|
|
133
|
+
def is_valid(cls, value: object) -> bool:
|
|
134
|
+
"""Return whether `value` is a valid strkey of exactly this type."""
|
|
135
|
+
if not isinstance(value, str):
|
|
136
|
+
return False
|
|
137
|
+
try:
|
|
138
|
+
cls.from_string(value)
|
|
139
|
+
except StrkeyError:
|
|
140
|
+
return False
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
def __str__(self) -> str:
|
|
144
|
+
return encode(self._VERSION_BYTE, self.to_bytes())
|
|
145
|
+
|
|
146
|
+
def __repr__(self) -> str:
|
|
147
|
+
return f"{type(self).__name__}.from_string({str(self)!r})"
|
|
148
|
+
|
|
149
|
+
def __format__(self, format_spec: str) -> str:
|
|
150
|
+
return format(str(self), format_spec)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
154
|
+
class _Hash(_Strkey):
|
|
155
|
+
"""A strkey whose binary form is a single 32-byte hash."""
|
|
156
|
+
|
|
157
|
+
hash: bytes
|
|
158
|
+
"""The 32-byte hash."""
|
|
159
|
+
|
|
160
|
+
def __post_init__(self) -> None:
|
|
161
|
+
object.__setattr__(self, "hash", _require_len("hash", self.hash, _KEY_LEN))
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
165
|
+
"""Build an instance from a 32-byte hash."""
|
|
166
|
+
return cls(data)
|
|
167
|
+
|
|
168
|
+
def to_bytes(self) -> bytes:
|
|
169
|
+
"""Return the 32-byte hash."""
|
|
170
|
+
return self.hash
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
174
|
+
class Ed25519PublicKey(_Strkey):
|
|
175
|
+
"""An ed25519 public key (`G...`)."""
|
|
176
|
+
|
|
177
|
+
_VERSION_BYTE: ClassVar[int] = _PUBLIC_KEY
|
|
178
|
+
|
|
179
|
+
key: bytes
|
|
180
|
+
"""The 32-byte public key."""
|
|
181
|
+
|
|
182
|
+
def __post_init__(self) -> None:
|
|
183
|
+
object.__setattr__(self, "key", _require_len("key", self.key, _KEY_LEN))
|
|
184
|
+
|
|
185
|
+
@classmethod
|
|
186
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
187
|
+
"""Build an instance from a 32-byte public key."""
|
|
188
|
+
return cls(data)
|
|
189
|
+
|
|
190
|
+
def to_bytes(self) -> bytes:
|
|
191
|
+
"""Return the 32-byte public key."""
|
|
192
|
+
return self.key
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_NOT_PICKLABLE: Final = (
|
|
196
|
+
"cannot pickle Ed25519PrivateKey; use reveal() to store or send it explicitly"
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class Ed25519PrivateKey(_Strkey):
|
|
201
|
+
"""An ed25519 private key seed (`S...`).
|
|
202
|
+
|
|
203
|
+
`str()`, `repr()` and f-strings are redacted, so a key cannot leak through logging
|
|
204
|
+
by accident. Call [`reveal`][stellar_strkey.Ed25519PrivateKey.reveal] to get the
|
|
205
|
+
strkey. Instances are immutable, compare in constant time and are unhashable.
|
|
206
|
+
|
|
207
|
+
Unlike the other types, this is not a dataclass and cannot be pickled, so tools
|
|
208
|
+
that serialize objects generically, such as `dataclasses.asdict`, msgspec, pydantic
|
|
209
|
+
and pickle, cannot write the seed out. To store or send a key, use `reveal`.
|
|
210
|
+
`copy.copy` and `copy.deepcopy` return the key itself. Only `seed` and `to_bytes`
|
|
211
|
+
return the raw seed, so don't log those. Python cannot erase `bytes` from memory, so
|
|
212
|
+
this class does not protect against an attacker who can read process memory.
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
# This class is written by hand rather than as a dataclass on purpose. Generic
|
|
216
|
+
# serializers (dataclasses.asdict, msgspec, pydantic and others) treat a dataclass
|
|
217
|
+
# as plain data and would write out its fields, including the seed, even when the
|
|
218
|
+
# key is nested inside the caller's own dataclass. As a plain class it is opaque to
|
|
219
|
+
# them: asdict keeps the redacted object, and msgspec and pydantic refuse it.
|
|
220
|
+
__slots__ = ("_seed",)
|
|
221
|
+
__match_args__ = ("seed",)
|
|
222
|
+
|
|
223
|
+
_VERSION_BYTE: ClassVar[int] = _PRIVATE_KEY
|
|
224
|
+
_seed: bytes
|
|
225
|
+
|
|
226
|
+
def __init__(self, seed: bytes) -> None:
|
|
227
|
+
object.__setattr__(self, "_seed", _require_len("seed", seed, _KEY_LEN))
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def seed(self) -> bytes:
|
|
231
|
+
"""The 32-byte seed."""
|
|
232
|
+
return self._seed
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
236
|
+
"""Build an instance from a 32-byte seed."""
|
|
237
|
+
return cls(data)
|
|
238
|
+
|
|
239
|
+
def to_bytes(self) -> bytes:
|
|
240
|
+
"""Return the 32-byte seed."""
|
|
241
|
+
return self._seed
|
|
242
|
+
|
|
243
|
+
def reveal(self) -> str:
|
|
244
|
+
"""Return the secret `S...` strkey."""
|
|
245
|
+
return encode(self._VERSION_BYTE, self._seed)
|
|
246
|
+
|
|
247
|
+
def __str__(self) -> str:
|
|
248
|
+
return "<redacted>"
|
|
249
|
+
|
|
250
|
+
def __repr__(self) -> str:
|
|
251
|
+
return f"{type(self).__name__}(<redacted>)"
|
|
252
|
+
|
|
253
|
+
def __eq__(self, other: object) -> bool:
|
|
254
|
+
if not isinstance(other, Ed25519PrivateKey):
|
|
255
|
+
return NotImplemented
|
|
256
|
+
return hmac.compare_digest(self._seed, other._seed)
|
|
257
|
+
|
|
258
|
+
# Defining __eq__ already makes the class unhashable; this tells type checkers.
|
|
259
|
+
__hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride]
|
|
260
|
+
|
|
261
|
+
# Immutable like the other types, which are frozen dataclasses, so the same
|
|
262
|
+
# exception is raised.
|
|
263
|
+
def __setattr__(self, name: str, _value: object, /) -> NoReturn:
|
|
264
|
+
raise FrozenInstanceError(f"cannot assign to field {name!r}")
|
|
265
|
+
|
|
266
|
+
def __delattr__(self, name: str, /) -> NoReturn:
|
|
267
|
+
raise FrozenInstanceError(f"cannot delete field {name!r}")
|
|
268
|
+
|
|
269
|
+
# Pickling is refused because a pickle carries the seed to wherever it goes, such as
|
|
270
|
+
# a cache, a task queue or a file, without the caller asking for that. cryptography
|
|
271
|
+
# and pycryptodome also refuse to pickle private keys. Refusing can be relaxed later
|
|
272
|
+
# without breaking anyone, while allowing it couldn't be taken back. To store or
|
|
273
|
+
# send a key, use reveal().
|
|
274
|
+
#
|
|
275
|
+
# __getstate__ is refused as well because some serializers, such as jsonpickle,
|
|
276
|
+
# call it directly instead of going through pickle.
|
|
277
|
+
def __reduce_ex__(self, _protocol: SupportsIndex, /) -> NoReturn:
|
|
278
|
+
raise TypeError(_NOT_PICKLABLE)
|
|
279
|
+
|
|
280
|
+
def __getstate__(self) -> NoReturn:
|
|
281
|
+
raise TypeError(_NOT_PICKLABLE)
|
|
282
|
+
|
|
283
|
+
# copy and deepcopy would otherwise go through __reduce_ex__ and fail. The key is
|
|
284
|
+
# immutable, so returning it unchanged is a correct copy. This keeps copying
|
|
285
|
+
# containers that hold a key working, including dataclasses.asdict, which deep
|
|
286
|
+
# copies the values it doesn't recurse into.
|
|
287
|
+
def __copy__(self) -> Self:
|
|
288
|
+
return self
|
|
289
|
+
|
|
290
|
+
def __deepcopy__(self, _memo: dict[int, object], /) -> Self:
|
|
291
|
+
return self
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
295
|
+
class MuxedEd25519Account(_Strkey):
|
|
296
|
+
"""A multiplexed ed25519 account (`M...`)."""
|
|
297
|
+
|
|
298
|
+
_VERSION_BYTE: ClassVar[int] = _MUXED_ACCOUNT
|
|
299
|
+
|
|
300
|
+
key: bytes
|
|
301
|
+
"""The 32-byte public key of the underlying account."""
|
|
302
|
+
|
|
303
|
+
id: int
|
|
304
|
+
"""The unsigned 64-bit multiplexing ID."""
|
|
305
|
+
|
|
306
|
+
def __post_init__(self) -> None:
|
|
307
|
+
object.__setattr__(self, "key", _require_len("key", self.key, _KEY_LEN))
|
|
308
|
+
_require_id(self.id)
|
|
309
|
+
|
|
310
|
+
@classmethod
|
|
311
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
312
|
+
"""Build an instance from a public key followed by a big-endian ID."""
|
|
313
|
+
data = _require_len("muxed account", data, _MUXED_PAYLOAD_LEN)
|
|
314
|
+
return cls(data[:_KEY_LEN], int.from_bytes(data[_KEY_LEN:], "big"))
|
|
315
|
+
|
|
316
|
+
def to_bytes(self) -> bytes:
|
|
317
|
+
"""Return the public key followed by the big-endian ID."""
|
|
318
|
+
return self.key + self.id.to_bytes(_ID_LEN, "big")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
322
|
+
class Ed25519SignedPayload(_Strkey):
|
|
323
|
+
"""An ed25519 signed payload signer (`P...`, CAP-40)."""
|
|
324
|
+
|
|
325
|
+
_VERSION_BYTE: ClassVar[int] = _SIGNED_PAYLOAD
|
|
326
|
+
|
|
327
|
+
key: bytes
|
|
328
|
+
"""The 32-byte public key that has to sign the payload."""
|
|
329
|
+
|
|
330
|
+
payload: bytes
|
|
331
|
+
"""The payload to sign, 1 to 64 bytes without padding."""
|
|
332
|
+
|
|
333
|
+
def __post_init__(self) -> None:
|
|
334
|
+
object.__setattr__(self, "key", _require_len("key", self.key, _KEY_LEN))
|
|
335
|
+
object.__setattr__(self, "payload", _require_bytes("payload", self.payload))
|
|
336
|
+
# stellar-core rejects empty payloads with SET_OPTIONS_BAD_SIGNER.
|
|
337
|
+
if not _MIN_INNER_PAYLOAD_LEN <= len(self.payload) <= _MAX_INNER_PAYLOAD_LEN:
|
|
338
|
+
raise ValueError(
|
|
339
|
+
f"payload must be {_MIN_INNER_PAYLOAD_LEN} to "
|
|
340
|
+
f"{_MAX_INNER_PAYLOAD_LEN} bytes, got {len(self.payload)}"
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
@classmethod
|
|
344
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
345
|
+
"""Build an instance from a public key and an XDR-encoded payload."""
|
|
346
|
+
data = _require_bytes("signed payload", data)
|
|
347
|
+
payload_start = _KEY_LEN + _LENGTH_PREFIX_LEN
|
|
348
|
+
if not payload_start + _XDR_ALIGNMENT <= len(data) <= _MAX_ANY_PAYLOAD_LEN:
|
|
349
|
+
raise ValueError(
|
|
350
|
+
f"signed payload must be {payload_start + _XDR_ALIGNMENT} to "
|
|
351
|
+
f"{_MAX_ANY_PAYLOAD_LEN} bytes, got {len(data)}"
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
payload_len = int.from_bytes(data[_KEY_LEN:payload_start], "big")
|
|
355
|
+
padding_start = payload_start + payload_len
|
|
356
|
+
padding_end = padding_start + _xdr_padding_len(payload_len)
|
|
357
|
+
mismatch = "signed payload length prefix does not match the data"
|
|
358
|
+
if padding_end > len(data):
|
|
359
|
+
raise ValueError(mismatch)
|
|
360
|
+
if any(data[padding_start:padding_end]):
|
|
361
|
+
raise ValueError("signed payload padding must be zero")
|
|
362
|
+
if padding_end != len(data):
|
|
363
|
+
raise ValueError(mismatch)
|
|
364
|
+
return cls(data[:_KEY_LEN], data[payload_start:padding_start])
|
|
365
|
+
|
|
366
|
+
def to_bytes(self) -> bytes:
|
|
367
|
+
"""Return the public key followed by the XDR-encoded payload."""
|
|
368
|
+
length = len(self.payload)
|
|
369
|
+
return b"".join(
|
|
370
|
+
(
|
|
371
|
+
self.key,
|
|
372
|
+
length.to_bytes(_LENGTH_PREFIX_LEN, "big"),
|
|
373
|
+
self.payload,
|
|
374
|
+
bytes(_xdr_padding_len(length)),
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class PreAuthTx(_Hash):
|
|
380
|
+
"""A pre-authorized transaction hash signer (`T...`)."""
|
|
381
|
+
|
|
382
|
+
__slots__ = ()
|
|
383
|
+
_VERSION_BYTE: ClassVar[int] = _PRE_AUTH_TX
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class HashX(_Hash):
|
|
387
|
+
"""A SHA-256 hash signer, satisfied by revealing its preimage (`X...`)."""
|
|
388
|
+
|
|
389
|
+
__slots__ = ()
|
|
390
|
+
_VERSION_BYTE: ClassVar[int] = _HASH_X
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class Contract(_Hash):
|
|
394
|
+
"""A smart contract address (`C...`)."""
|
|
395
|
+
|
|
396
|
+
__slots__ = ()
|
|
397
|
+
_VERSION_BYTE: ClassVar[int] = _CONTRACT
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class LiquidityPool(_Hash):
|
|
401
|
+
"""A liquidity pool ID (`L...`)."""
|
|
402
|
+
|
|
403
|
+
__slots__ = ()
|
|
404
|
+
_VERSION_BYTE: ClassVar[int] = _LIQUIDITY_POOL
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
408
|
+
class ClaimableBalance(_Strkey):
|
|
409
|
+
"""A version 0 claimable balance ID (`B...`)."""
|
|
410
|
+
|
|
411
|
+
_VERSION_BYTE: ClassVar[int] = _CLAIMABLE_BALANCE
|
|
412
|
+
|
|
413
|
+
hash: bytes
|
|
414
|
+
"""The 32-byte hash."""
|
|
415
|
+
|
|
416
|
+
def __post_init__(self) -> None:
|
|
417
|
+
object.__setattr__(self, "hash", _require_len("hash", self.hash, _KEY_LEN))
|
|
418
|
+
|
|
419
|
+
@classmethod
|
|
420
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
421
|
+
"""Build an instance from a version byte followed by a 32-byte hash.
|
|
422
|
+
|
|
423
|
+
Raises:
|
|
424
|
+
TypeError: If `data` is not `bytes`.
|
|
425
|
+
UnsupportedVersionError: If the version byte is not 0.
|
|
426
|
+
ValueError: If `data` is not 33 bytes long.
|
|
427
|
+
"""
|
|
428
|
+
data = _require_bytes("claimable balance", data)
|
|
429
|
+
if len(data) > 0 and data[:1] != _CLAIMABLE_BALANCE_V0:
|
|
430
|
+
raise UnsupportedVersionError(
|
|
431
|
+
f"unsupported claimable balance version {data[0]:#04x}"
|
|
432
|
+
)
|
|
433
|
+
data = _require_len(
|
|
434
|
+
"claimable balance", data, len(_CLAIMABLE_BALANCE_V0) + _KEY_LEN
|
|
435
|
+
)
|
|
436
|
+
return cls(data[1:])
|
|
437
|
+
|
|
438
|
+
def to_bytes(self) -> bytes:
|
|
439
|
+
"""Return the version byte followed by the 32-byte hash."""
|
|
440
|
+
return _CLAIMABLE_BALANCE_V0 + self.hash
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
444
|
+
class MuxedContract(_Strkey):
|
|
445
|
+
"""A multiplexed smart contract address (`W...`, CAP-84)."""
|
|
446
|
+
|
|
447
|
+
_VERSION_BYTE: ClassVar[int] = _MUXED_CONTRACT
|
|
448
|
+
|
|
449
|
+
hash: bytes
|
|
450
|
+
"""The 32-byte hash of the underlying contract."""
|
|
451
|
+
|
|
452
|
+
id: int
|
|
453
|
+
"""The unsigned 64-bit multiplexing ID."""
|
|
454
|
+
|
|
455
|
+
def __post_init__(self) -> None:
|
|
456
|
+
object.__setattr__(self, "hash", _require_len("hash", self.hash, _KEY_LEN))
|
|
457
|
+
_require_id(self.id)
|
|
458
|
+
|
|
459
|
+
@classmethod
|
|
460
|
+
def from_bytes(cls, data: bytes) -> Self:
|
|
461
|
+
"""Build an instance from a contract hash followed by a big-endian ID."""
|
|
462
|
+
data = _require_len("muxed contract", data, _MUXED_PAYLOAD_LEN)
|
|
463
|
+
return cls(data[:_KEY_LEN], int.from_bytes(data[_KEY_LEN:], "big"))
|
|
464
|
+
|
|
465
|
+
def to_bytes(self) -> bytes:
|
|
466
|
+
"""Return the contract hash followed by the big-endian ID."""
|
|
467
|
+
return self.hash + self.id.to_bytes(_ID_LEN, "big")
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
Strkey: TypeAlias = (
|
|
471
|
+
Ed25519PublicKey
|
|
472
|
+
| MuxedEd25519Account
|
|
473
|
+
| Ed25519SignedPayload
|
|
474
|
+
| PreAuthTx
|
|
475
|
+
| HashX
|
|
476
|
+
| Contract
|
|
477
|
+
| LiquidityPool
|
|
478
|
+
| ClaimableBalance
|
|
479
|
+
| MuxedContract
|
|
480
|
+
)
|
|
481
|
+
"""Every strkey type `parse` can return. Private keys are excluded on purpose.
|
|
482
|
+
|
|
483
|
+
`isinstance(value, Strkey)` works too.
|
|
484
|
+
"""
|
|
485
|
+
|
|
486
|
+
_TYPES_BY_VERSION_BYTE: Final[dict[int, type[Strkey | Ed25519PrivateKey]]] = {
|
|
487
|
+
_PUBLIC_KEY: Ed25519PublicKey,
|
|
488
|
+
_PRIVATE_KEY: Ed25519PrivateKey,
|
|
489
|
+
_MUXED_ACCOUNT: MuxedEd25519Account,
|
|
490
|
+
_SIGNED_PAYLOAD: Ed25519SignedPayload,
|
|
491
|
+
_PRE_AUTH_TX: PreAuthTx,
|
|
492
|
+
_HASH_X: HashX,
|
|
493
|
+
_CONTRACT: Contract,
|
|
494
|
+
_LIQUIDITY_POOL: LiquidityPool,
|
|
495
|
+
_CLAIMABLE_BALANCE: ClaimableBalance,
|
|
496
|
+
_MUXED_CONTRACT: MuxedContract,
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def parse(value: str) -> Strkey:
|
|
501
|
+
"""Decode a strkey whose type is not known in advance.
|
|
502
|
+
|
|
503
|
+
Private keys are refused, so input from an untrusted or generic source cannot
|
|
504
|
+
silently become a secret. Use
|
|
505
|
+
[`Ed25519PrivateKey.from_string`][stellar_strkey.Ed25519PrivateKey.from_string]
|
|
506
|
+
for those.
|
|
507
|
+
|
|
508
|
+
Args:
|
|
509
|
+
value: The strkey to decode.
|
|
510
|
+
|
|
511
|
+
Returns:
|
|
512
|
+
An instance of the class that matches the strkey's type.
|
|
513
|
+
|
|
514
|
+
Raises:
|
|
515
|
+
TypeError: If `value` is not a `str`.
|
|
516
|
+
MalformedStrkeyError: If `value` is not a well-formed strkey.
|
|
517
|
+
WrongStrkeyTypeError: If `value` is a private key.
|
|
518
|
+
UnsupportedVersionError: If the version of `value` is unknown.
|
|
519
|
+
"""
|
|
520
|
+
version, payload = decode(value)
|
|
521
|
+
strkey_type = _TYPES_BY_VERSION_BYTE.get(version)
|
|
522
|
+
if strkey_type is None:
|
|
523
|
+
raise UnsupportedVersionError(f"unsupported version byte {version:#04x}")
|
|
524
|
+
if issubclass(strkey_type, Ed25519PrivateKey):
|
|
525
|
+
raise WrongStrkeyTypeError(None, strkey_type)
|
|
526
|
+
return _from_payload(strkey_type, payload)
|
stellar_strkey/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stellar-strkey
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Strict, typed, dependency-free encoding and decoding of Stellar strkeys (SEP-23).
|
|
5
|
+
Keywords: stellar,strkey,sep-23,base32,soroban
|
|
6
|
+
Author: overcat
|
|
7
|
+
Author-email: overcat <hi@overcat.dev>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Project-URL: Homepage, https://github.com/lightsail-network/py-stellar-strkey
|
|
26
|
+
Project-URL: Documentation, https://stellar-strkey.readthedocs.io/
|
|
27
|
+
Project-URL: Repository, https://github.com/lightsail-network/py-stellar-strkey
|
|
28
|
+
Project-URL: Issues, https://github.com/lightsail-network/py-stellar-strkey/issues
|
|
29
|
+
Project-URL: Changelog, https://github.com/lightsail-network/py-stellar-strkey/blob/main/CHANGELOG.md
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# stellar-strkey
|
|
33
|
+
|
|
34
|
+
Encode and decode [Stellar strkeys](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0023.md),
|
|
35
|
+
the `G...`, `C...` and `M...` strings that identify accounts, contracts, signers and
|
|
36
|
+
other things on the Stellar network.
|
|
37
|
+
|
|
38
|
+
- **Complete.** Supports every strkey type defined by SEP-23.
|
|
39
|
+
- **Strict.** Accepts a strkey only in its one canonical form and rejects everything else
|
|
40
|
+
with a clear error, so invalid input never gets through.
|
|
41
|
+
- **Thoroughly tested.** Verified against the SEP-23 test cases and a shared set of test
|
|
42
|
+
vectors, with property-based tests and 100% branch coverage.
|
|
43
|
+
- **Safe with secrets.** Secret seeds are never printed or serialized by accident, and
|
|
44
|
+
error messages never include the input.
|
|
45
|
+
- **Lightweight.** Fully typed, pure Python, no dependencies.
|
|
46
|
+
|
|
47
|
+
The [documentation](https://stellar-strkey.readthedocs.io/) has the guide and the API
|
|
48
|
+
reference.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
```shell
|
|
53
|
+
pip install stellar-strkey
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from stellar_strkey import (
|
|
60
|
+
Contract,
|
|
61
|
+
Ed25519PublicKey,
|
|
62
|
+
MuxedEd25519Account,
|
|
63
|
+
StrkeyError,
|
|
64
|
+
parse,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# When you know the type, use its class. Anything else is rejected.
|
|
68
|
+
key = Ed25519PublicKey.from_string(
|
|
69
|
+
"GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ"
|
|
70
|
+
)
|
|
71
|
+
assert key.key.hex() == (
|
|
72
|
+
"3f0c34bf93ad0d9971d04ccc90f705511c838aad9734a4a2fb0d7a03fc7fe89a"
|
|
73
|
+
)
|
|
74
|
+
# The same 32 bytes as a contract give a different strkey.
|
|
75
|
+
assert str(Contract(key.key)) == (
|
|
76
|
+
"CA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUWDA"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# When you don't, parse() returns the matching class.
|
|
80
|
+
match parse("MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVAAAAAAAAAAAAAJLK"):
|
|
81
|
+
case Ed25519PublicKey(key):
|
|
82
|
+
description = f"account {key.hex()}"
|
|
83
|
+
case MuxedEd25519Account(key, id):
|
|
84
|
+
description = f"muxed account {key.hex()} with ID {id}"
|
|
85
|
+
case other:
|
|
86
|
+
description = f"something else: {other!r}"
|
|
87
|
+
assert description.endswith("with ID 9223372036854775808")
|
|
88
|
+
|
|
89
|
+
# Invalid input raises StrkeyError, which is a ValueError.
|
|
90
|
+
try:
|
|
91
|
+
parse("GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGA")
|
|
92
|
+
except StrkeyError as error:
|
|
93
|
+
message = str(error)
|
|
94
|
+
assert message == "strkey checksum does not match"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Secret seeds
|
|
98
|
+
|
|
99
|
+
Secret seeds (`S...`) have their own parser, and `parse()` refuses them, so code that
|
|
100
|
+
handles arbitrary addresses can't pick up a secret by accident:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from stellar_strkey import Ed25519PrivateKey, WrongStrkeyTypeError, parse
|
|
104
|
+
|
|
105
|
+
# In real code, load the secret from the environment or a secret store, never from
|
|
106
|
+
# source code. This is a well-known test seed.
|
|
107
|
+
secret = "SBU2RRGLXH3E5CQHTD3ODLDF2BWDCYUSSBLLZ5GNW7JXHDIYKXZWHOKR"
|
|
108
|
+
|
|
109
|
+
key = Ed25519PrivateKey.from_string(secret)
|
|
110
|
+
seed = key.seed # the raw 32 bytes, for example for an ed25519 signing library
|
|
111
|
+
assert len(seed) == 32
|
|
112
|
+
|
|
113
|
+
# Printing or logging the key never shows the seed.
|
|
114
|
+
assert str(key) == "<redacted>"
|
|
115
|
+
assert repr(key) == "Ed25519PrivateKey(<redacted>)"
|
|
116
|
+
|
|
117
|
+
# Get the strkey back only where you mean to.
|
|
118
|
+
assert key.reveal() == secret
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
parse(secret)
|
|
122
|
+
except WrongStrkeyTypeError as error:
|
|
123
|
+
refused = error.found
|
|
124
|
+
assert refused is Ed25519PrivateKey
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Types
|
|
128
|
+
|
|
129
|
+
| Prefix | Class | Fields | `to_bytes()` / `from_bytes()` layout |
|
|
130
|
+
| ------ | ---------------------- | ---------------- | ------------------------------------- |
|
|
131
|
+
| `G` | `Ed25519PublicKey` | `key` | 32-byte key |
|
|
132
|
+
| `S` | `Ed25519PrivateKey` | `seed` | 32-byte seed |
|
|
133
|
+
| `M` | `MuxedEd25519Account` | `key`, `id` | 32-byte key, 8-byte big-endian ID |
|
|
134
|
+
| `P` | `Ed25519SignedPayload` | `key`, `payload` | 32-byte key, XDR `opaque<64>` payload |
|
|
135
|
+
| `T` | `PreAuthTx` | `hash` | 32-byte hash |
|
|
136
|
+
| `X` | `HashX` | `hash` | 32-byte hash |
|
|
137
|
+
| `C` | `Contract` | `hash` | 32-byte hash |
|
|
138
|
+
| `L` | `LiquidityPool` | `hash` | 32-byte hash |
|
|
139
|
+
| `B` | `ClaimableBalance` | `hash` | `0x00` version byte, 32-byte hash |
|
|
140
|
+
| `W` | `MuxedContract` | `hash`, `id` | 32-byte hash, 8-byte big-endian ID |
|
|
141
|
+
|
|
142
|
+
See the guide for how to handle errors, and for what private keys are protected
|
|
143
|
+
against and what they aren't.
|
|
144
|
+
|
|
145
|
+
## Development
|
|
146
|
+
|
|
147
|
+
```shell
|
|
148
|
+
uv sync --all-groups # create the environment, including the docs tools
|
|
149
|
+
uv run prek install # optional: check before each commit
|
|
150
|
+
make check # format check, lint, type checks and tests with coverage
|
|
151
|
+
make docs-serve # preview the documentation
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`tests/vectors/strkeys.json` holds the shared test vectors in a language neutral form.
|
|
155
|
+
Add new cases there by hand, with the expected result that SEP-23 requires.
|
|
156
|
+
|
|
157
|
+
To release, run `make release-prep VERSION=<version>`, which sets the version and adds the
|
|
158
|
+
commits since the last release to `CHANGELOG.md`. Edit the new section where a commit
|
|
159
|
+
title isn't enough, commit it, then push a `v<version>` tag. The publish workflow verifies
|
|
160
|
+
that the tag matches the version and publishes to PyPI with trusted publishing, along with
|
|
161
|
+
PEP 740 attestations.
|
|
162
|
+
|
|
163
|
+
## License
|
|
164
|
+
|
|
165
|
+
[Apache-2.0](https://github.com/lightsail-network/py-stellar-strkey/blob/main/LICENSE)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
stellar_strkey/__init__.py,sha256=CWnAZKpsONAvnfei9D5g3skXqD-CCLEhx0hfNCj3tMc,1573
|
|
2
|
+
stellar_strkey/_codec.py,sha256=koubDz4CN6WvM-K5cygX3VNrNOYLDZIcjBKq_COhGUc,3399
|
|
3
|
+
stellar_strkey/_errors.py,sha256=ggJhtNwRolDpbSblbKSCnkSPPMrft63rU9bRaicaq1o,2575
|
|
4
|
+
stellar_strkey/_keys.py,sha256=mE4p1yFjHx33vEze4vifsw_RHE8ZDE2wGUKiiuu_xMc,18464
|
|
5
|
+
stellar_strkey/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
stellar_strkey-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
stellar_strkey-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
|
|
8
|
+
stellar_strkey-0.1.0.dist-info/METADATA,sha256=WbPyGrvFEYI1qIirUAYJozJnhDOH-vSjYsYQQkRQP1Q,6926
|
|
9
|
+
stellar_strkey-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|