multiaddr 0.0.11__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.
- multiaddr/__init__.py +5 -0
- multiaddr/codecs/__init__.py +43 -0
- multiaddr/codecs/cid.py +177 -0
- multiaddr/codecs/domain.py +52 -0
- multiaddr/codecs/fspath.py +73 -0
- multiaddr/codecs/ip4.py +23 -0
- multiaddr/codecs/ip6.py +19 -0
- multiaddr/codecs/memory.py +30 -0
- multiaddr/codecs/onion.py +54 -0
- multiaddr/codecs/onion3.py +56 -0
- multiaddr/codecs/uint16be.py +25 -0
- multiaddr/codecs/utf8.py +49 -0
- multiaddr/exceptions.py +150 -0
- multiaddr/multiaddr.py +504 -0
- multiaddr/protocols.py +491 -0
- multiaddr/resolvers/__init__.py +6 -0
- multiaddr/resolvers/base.py +29 -0
- multiaddr/resolvers/dns.py +408 -0
- multiaddr/transforms.py +174 -0
- multiaddr/utils.py +119 -0
- multiaddr-0.0.11.dist-info/METADATA +351 -0
- multiaddr-0.0.11.dist-info/RECORD +27 -0
- multiaddr-0.0.11.dist-info/WHEEL +5 -0
- multiaddr-0.0.11.dist-info/licenses/AUTHORS +18 -0
- multiaddr-0.0.11.dist-info/licenses/LICENSE-APACHE2 +7 -0
- multiaddr-0.0.11.dist-info/licenses/LICENSE-MIT +22 -0
- multiaddr-0.0.11.dist-info/top_level.txt +1 -0
multiaddr/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
# These are special sizes
|
|
5
|
+
LENGTH_PREFIXED_VAR_SIZE = -1
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CodecBase:
|
|
9
|
+
SIZE: int
|
|
10
|
+
IS_PATH: bool
|
|
11
|
+
|
|
12
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
13
|
+
raise NotImplementedError
|
|
14
|
+
|
|
15
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
16
|
+
raise NotImplementedError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class NoneCodec(CodecBase):
|
|
20
|
+
SIZE: int = 0
|
|
21
|
+
IS_PATH: bool = False
|
|
22
|
+
|
|
23
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
24
|
+
return ""
|
|
25
|
+
|
|
26
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
27
|
+
return b""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
CODEC_CACHE: dict[str, CodecBase] = {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def codec_by_name(name: str | None) -> CodecBase:
|
|
34
|
+
if name is None: # Special "do nothing - expect nothing" pseudo-codec
|
|
35
|
+
return NoneCodec()
|
|
36
|
+
codec = CODEC_CACHE.get(name)
|
|
37
|
+
if codec is None:
|
|
38
|
+
module = importlib.import_module(f".{name}", __name__)
|
|
39
|
+
codec_class = getattr(module, "Codec")
|
|
40
|
+
assert codec_class is not None, f"Codec {name} not found"
|
|
41
|
+
codec = codec_class()
|
|
42
|
+
CODEC_CACHE[name] = codec
|
|
43
|
+
return codec
|
multiaddr/codecs/cid.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import base58
|
|
5
|
+
import cid
|
|
6
|
+
|
|
7
|
+
from ..codecs import CodecBase
|
|
8
|
+
from ..exceptions import BinaryParseError
|
|
9
|
+
from . import LENGTH_PREFIXED_VAR_SIZE
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
SIZE = LENGTH_PREFIXED_VAR_SIZE
|
|
14
|
+
IS_PATH = False
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# Spec: https://github.com/libp2p/specs/blob/master/peer-ids/peer-ids.md#string-representation
|
|
18
|
+
CIDv0_PREFIX_TO_LENGTH: dict[str, list[int]] = {
|
|
19
|
+
# base58btc prefixes for valid lengths 1 - 42 with the identity "hash" function
|
|
20
|
+
"12": [5, 12, 19, 23, 30, 41, 52, 56],
|
|
21
|
+
"13": [9, 16, 34, 45],
|
|
22
|
+
"14": [27, 38, 49, 60],
|
|
23
|
+
"15": [3, 6, 20],
|
|
24
|
+
"16": [3, 6, 13, 20, 31, 42, 53],
|
|
25
|
+
"17": [3, 13, 42],
|
|
26
|
+
"18": [3],
|
|
27
|
+
"19": [3, 24, 57],
|
|
28
|
+
"1A": [24, 35, 46],
|
|
29
|
+
"1B": [35],
|
|
30
|
+
"1D": [17],
|
|
31
|
+
"1E": [10, 17],
|
|
32
|
+
"1F": [10],
|
|
33
|
+
"1G": [10, 28, 50],
|
|
34
|
+
"1H": [28, 39],
|
|
35
|
+
"1P": [21],
|
|
36
|
+
"1Q": [21],
|
|
37
|
+
"1R": [21, 54],
|
|
38
|
+
"1S": [54],
|
|
39
|
+
"1T": [7, 32, 43],
|
|
40
|
+
"1U": [7, 32, 43],
|
|
41
|
+
"1V": [7],
|
|
42
|
+
"1W": [7, 14],
|
|
43
|
+
"1X": [7, 14],
|
|
44
|
+
"1Y": [7, 14],
|
|
45
|
+
"1Z": [7, 14],
|
|
46
|
+
"1f": [4],
|
|
47
|
+
"1g": [4, 58],
|
|
48
|
+
"1h": [4, 25, 58],
|
|
49
|
+
"1i": [4, 25],
|
|
50
|
+
"1j": [4, 25],
|
|
51
|
+
"1k": [4, 25, 47],
|
|
52
|
+
"1m": [4, 36, 47],
|
|
53
|
+
"1n": [4, 36],
|
|
54
|
+
"1o": [4, 36],
|
|
55
|
+
"1p": [4],
|
|
56
|
+
"1q": [4],
|
|
57
|
+
"1r": [4],
|
|
58
|
+
"1s": [4],
|
|
59
|
+
"1t": [4],
|
|
60
|
+
"1u": [4],
|
|
61
|
+
"1v": [4],
|
|
62
|
+
"1w": [4],
|
|
63
|
+
"1x": [4],
|
|
64
|
+
"1y": [4],
|
|
65
|
+
"1z": [4, 18],
|
|
66
|
+
# base58btc prefix for length 42 with the sha256 hash function
|
|
67
|
+
"Qm": [46],
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
PROTO_NAME_TO_CIDv1_CODEC = {
|
|
71
|
+
"p2p": "libp2p-key",
|
|
72
|
+
"ipfs": "dag-pb",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_binary_cidv0_multihash(buf: bytes) -> bool:
|
|
77
|
+
"""Check if the given bytes represent a CIDv0 multihash."""
|
|
78
|
+
try:
|
|
79
|
+
# CIDv0 is just a base58btc encoded multihash
|
|
80
|
+
# The first byte is the hash function code, second byte is the length
|
|
81
|
+
if len(buf) < 2:
|
|
82
|
+
return False
|
|
83
|
+
hash_code = buf[0]
|
|
84
|
+
length = buf[1]
|
|
85
|
+
if len(buf) != length + 2: # +2 for the hash code and length bytes
|
|
86
|
+
return False
|
|
87
|
+
# For CIDv0, we only support sha2-256 (0x12) and identity (0x00)
|
|
88
|
+
return hash_code in (0x12, 0x00)
|
|
89
|
+
except Exception:
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Codec(CodecBase):
|
|
94
|
+
SIZE = SIZE
|
|
95
|
+
IS_PATH = IS_PATH
|
|
96
|
+
|
|
97
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
98
|
+
"""Convert a CID string to its binary representation."""
|
|
99
|
+
if not string:
|
|
100
|
+
raise ValueError("CID string cannot be empty")
|
|
101
|
+
|
|
102
|
+
logger.debug(f"[DEBUG CID to_bytes] Input value: {string}")
|
|
103
|
+
|
|
104
|
+
# First try to parse as CIDv0 (base58btc encoded multihash)
|
|
105
|
+
try:
|
|
106
|
+
decoded = base58.b58decode(string)
|
|
107
|
+
if _is_binary_cidv0_multihash(decoded):
|
|
108
|
+
logger.debug(f"[DEBUG CID to_bytes] Parsed as CIDv0: {decoded.hex()}")
|
|
109
|
+
# Do not add length prefix here; the framework handles it
|
|
110
|
+
return decoded
|
|
111
|
+
except Exception as e:
|
|
112
|
+
logger.debug(f"[DEBUG CID to_bytes] Failed to parse as CIDv0: {e}")
|
|
113
|
+
|
|
114
|
+
# If not CIDv0, try to parse as CIDv1
|
|
115
|
+
try:
|
|
116
|
+
parsed = cid.make_cid(string)
|
|
117
|
+
|
|
118
|
+
# Do not add length prefix here; the framework handles it
|
|
119
|
+
if not isinstance(parsed.buffer, bytes):
|
|
120
|
+
raise ValueError("CID buffer must be bytes")
|
|
121
|
+
return parsed.buffer
|
|
122
|
+
except ValueError as e:
|
|
123
|
+
logger.debug(f"[DEBUG CID to_bytes] Failed to parse as CIDv1: {e}")
|
|
124
|
+
raise ValueError(f"Invalid CID: {string}")
|
|
125
|
+
|
|
126
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
127
|
+
"""Convert a binary CID to its string representation."""
|
|
128
|
+
if not buf:
|
|
129
|
+
raise ValueError("CID buffer cannot be empty")
|
|
130
|
+
|
|
131
|
+
logger.debug(f"[DEBUG CID to_string] Input buffer: {buf.hex()}")
|
|
132
|
+
logger.debug(f"[DEBUG CID to_string] Protocol: {proto.name}")
|
|
133
|
+
|
|
134
|
+
expected_codec = PROTO_NAME_TO_CIDv1_CODEC.get(proto.name)
|
|
135
|
+
logger.debug(f"[DEBUG CID to_string] Expected codec: {expected_codec}")
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
# First try to parse as CIDv0
|
|
139
|
+
if _is_binary_cidv0_multihash(buf):
|
|
140
|
+
result = base58.b58encode(buf).decode("ascii")
|
|
141
|
+
logger.debug(f"[DEBUG CID to_string] Parsed as CIDv0: {result}")
|
|
142
|
+
return result
|
|
143
|
+
|
|
144
|
+
# If not CIDv0, try to parse as CIDv1
|
|
145
|
+
parsed = cid.from_bytes(buf)
|
|
146
|
+
logger.debug(f"[DEBUG CID to_string] Parsed as CIDv1: {parsed}")
|
|
147
|
+
|
|
148
|
+
# Ensure CID has correct codec for protocol
|
|
149
|
+
if expected_codec and parsed.codec != expected_codec:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
'"{}" multiaddr CIDs must use the "{}" multicodec'.format(
|
|
152
|
+
proto.name, expected_codec
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# For peer IDs (p2p/ipfs), always try to use CIDv0 format if possible
|
|
157
|
+
if expected_codec:
|
|
158
|
+
# Try to convert to CIDv0 format
|
|
159
|
+
try:
|
|
160
|
+
# Extract the multihash bytes
|
|
161
|
+
multihash = parsed.multihash
|
|
162
|
+
logger.debug(f"[DEBUG CID to_string] Extracted multihash: {multihash.hex()}")
|
|
163
|
+
# Check if it's a valid CIDv0 multihash
|
|
164
|
+
if _is_binary_cidv0_multihash(multihash):
|
|
165
|
+
result = base58.b58encode(multihash).decode("ascii")
|
|
166
|
+
logger.debug(f"[DEBUG CID to_string] Converted to CIDv0: {result}")
|
|
167
|
+
return result
|
|
168
|
+
except Exception as e:
|
|
169
|
+
logger.debug(f"[DEBUG CID to_string] Failed to convert to CIDv0: {e}")
|
|
170
|
+
|
|
171
|
+
# If we can't convert to CIDv0, use base32 CIDv1 format
|
|
172
|
+
result = parsed.encode("base32").decode("ascii")
|
|
173
|
+
logger.debug(f"[DEBUG CID to_string] Using CIDv1 format: {result}")
|
|
174
|
+
return result
|
|
175
|
+
except Exception as e:
|
|
176
|
+
logger.debug(f"[DEBUG CID to_string] Error: {e}")
|
|
177
|
+
raise BinaryParseError(str(e), buf, proto.name, e) from e
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
import idna
|
|
4
|
+
|
|
5
|
+
from ..exceptions import BinaryParseError
|
|
6
|
+
from . import LENGTH_PREFIXED_VAR_SIZE, CodecBase
|
|
7
|
+
|
|
8
|
+
SIZE = LENGTH_PREFIXED_VAR_SIZE # Variable size for length-prefixed values
|
|
9
|
+
IS_PATH = False
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Codec(CodecBase):
|
|
13
|
+
SIZE = SIZE
|
|
14
|
+
IS_PATH = IS_PATH
|
|
15
|
+
|
|
16
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
17
|
+
"""Convert a domain name string to its binary representation (UTF-8),
|
|
18
|
+
validating with IDNA."""
|
|
19
|
+
if not string:
|
|
20
|
+
raise ValueError("Domain name cannot be empty")
|
|
21
|
+
try:
|
|
22
|
+
# Validate using IDNA, but store as UTF-8
|
|
23
|
+
idna.encode(string, uts46=True)
|
|
24
|
+
return string.encode("utf-8")
|
|
25
|
+
except idna.IDNAError as e:
|
|
26
|
+
raise ValueError(f"Invalid domain name: {e!s}")
|
|
27
|
+
|
|
28
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
29
|
+
"""Convert a binary domain name to its string representation (UTF-8),
|
|
30
|
+
validating with IDNA."""
|
|
31
|
+
if not buf:
|
|
32
|
+
raise ValueError("Domain name buffer cannot be empty")
|
|
33
|
+
try:
|
|
34
|
+
value = buf.decode("utf-8")
|
|
35
|
+
# Validate using IDNA
|
|
36
|
+
idna.encode(value, uts46=True)
|
|
37
|
+
return value
|
|
38
|
+
except (UnicodeDecodeError, idna.IDNAError) as e:
|
|
39
|
+
raise BinaryParseError(f"Invalid domain name encoding: {e!s}", buf, proto.name, e)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def to_bytes(proto: Any, string: str) -> bytes:
|
|
43
|
+
# Validate using IDNA, but store as UTF-8
|
|
44
|
+
idna.encode(string, uts46=True)
|
|
45
|
+
return string.encode("utf-8")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def to_string(proto: Any, buf: bytes) -> str:
|
|
49
|
+
string = buf.decode("utf-8")
|
|
50
|
+
# Validate using IDNA
|
|
51
|
+
idna.encode(string, uts46=True)
|
|
52
|
+
return string
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import urllib.parse
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ..exceptions import BinaryParseError
|
|
6
|
+
from . import LENGTH_PREFIXED_VAR_SIZE, CodecBase
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
SIZE = LENGTH_PREFIXED_VAR_SIZE
|
|
11
|
+
IS_PATH = True
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Codec(CodecBase):
|
|
15
|
+
SIZE = SIZE
|
|
16
|
+
IS_PATH = IS_PATH
|
|
17
|
+
|
|
18
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
19
|
+
"""Convert a filesystem path to its binary representation."""
|
|
20
|
+
logger.debug(f"[DEBUG fspath.to_bytes] input value: {string}")
|
|
21
|
+
if not string:
|
|
22
|
+
raise ValueError("Path cannot be empty")
|
|
23
|
+
|
|
24
|
+
# Normalize path separators
|
|
25
|
+
string = string.replace("\\", "/")
|
|
26
|
+
|
|
27
|
+
# Remove leading/trailing slashes but preserve path components
|
|
28
|
+
string = string.strip("/")
|
|
29
|
+
|
|
30
|
+
# Handle empty path after normalization
|
|
31
|
+
if not string:
|
|
32
|
+
raise ValueError("Path cannot be empty after normalization")
|
|
33
|
+
|
|
34
|
+
# URL decode to handle special characters
|
|
35
|
+
string = urllib.parse.unquote(string)
|
|
36
|
+
|
|
37
|
+
# Encode as UTF-8
|
|
38
|
+
encoded = string.encode("utf-8")
|
|
39
|
+
logger.debug(f"[DEBUG fspath.to_bytes] encoded bytes: {encoded!r}")
|
|
40
|
+
return encoded
|
|
41
|
+
|
|
42
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
43
|
+
"""Convert a binary filesystem path to its string representation."""
|
|
44
|
+
logger.debug(f"[DEBUG fspath.to_string] input bytes: {buf!r}")
|
|
45
|
+
if not buf:
|
|
46
|
+
raise ValueError("Path buffer cannot be empty")
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
# Decode from UTF-8
|
|
50
|
+
value = buf.decode("utf-8")
|
|
51
|
+
logger.debug(f"[DEBUG fspath.to_string] decoded value: {value}")
|
|
52
|
+
|
|
53
|
+
# Normalize path separators
|
|
54
|
+
value = value.replace("\\", "/")
|
|
55
|
+
|
|
56
|
+
# Remove leading/trailing slashes but preserve path components
|
|
57
|
+
value = value.strip("/")
|
|
58
|
+
|
|
59
|
+
# Handle empty path after normalization
|
|
60
|
+
if not value:
|
|
61
|
+
raise ValueError("Path cannot be empty after normalization")
|
|
62
|
+
|
|
63
|
+
# URL encode special characters
|
|
64
|
+
result = urllib.parse.quote(value)
|
|
65
|
+
logger.debug(f"[DEBUG fspath.to_string] output string: {result}")
|
|
66
|
+
|
|
67
|
+
# Add leading slash for Unix socket paths
|
|
68
|
+
if proto.name == "unix":
|
|
69
|
+
result = "/" + result
|
|
70
|
+
|
|
71
|
+
return result
|
|
72
|
+
except UnicodeDecodeError as e:
|
|
73
|
+
raise BinaryParseError(f"Invalid UTF-8 encoding: {e!s}", buf, proto.name, e)
|
multiaddr/codecs/ip4.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
import netaddr
|
|
4
|
+
|
|
5
|
+
from ..codecs import CodecBase
|
|
6
|
+
from ..exceptions import BinaryParseError
|
|
7
|
+
|
|
8
|
+
SIZE = 32
|
|
9
|
+
IS_PATH = False
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Codec(CodecBase):
|
|
13
|
+
SIZE = SIZE
|
|
14
|
+
IS_PATH = IS_PATH
|
|
15
|
+
|
|
16
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
17
|
+
return netaddr.IPAddress(string, version=4).packed
|
|
18
|
+
|
|
19
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
20
|
+
try:
|
|
21
|
+
return str(netaddr.IPAddress(int.from_bytes(buf, byteorder="big"), version=4))
|
|
22
|
+
except (ValueError, netaddr.AddrFormatError):
|
|
23
|
+
raise BinaryParseError("Invalid IPv4 address bytes", buf, "ip4")
|
multiaddr/codecs/ip6.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
import netaddr
|
|
4
|
+
|
|
5
|
+
from ..codecs import CodecBase
|
|
6
|
+
|
|
7
|
+
SIZE = 128
|
|
8
|
+
IS_PATH = False
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Codec(CodecBase):
|
|
12
|
+
SIZE = SIZE
|
|
13
|
+
IS_PATH = IS_PATH
|
|
14
|
+
|
|
15
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
16
|
+
return netaddr.IPAddress(string, version=6).packed
|
|
17
|
+
|
|
18
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
19
|
+
return str(netaddr.IPAddress(int.from_bytes(buf, byteorder="big"), version=6))
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import struct
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from ..codecs import CodecBase
|
|
5
|
+
from ..exceptions import BinaryParseError
|
|
6
|
+
|
|
7
|
+
SIZE = 64
|
|
8
|
+
IS_PATH = False
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Codec(CodecBase):
|
|
12
|
+
SIZE = SIZE
|
|
13
|
+
IS_PATH = IS_PATH
|
|
14
|
+
|
|
15
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
16
|
+
# Parse as unsigned 64-bit int
|
|
17
|
+
value = int(string, 10)
|
|
18
|
+
if value < 0 or value > 0xFFFFFFFFFFFFFFFF:
|
|
19
|
+
raise ValueError("Value out of range for uint64")
|
|
20
|
+
return struct.pack(">Q", value) # big-endian uint64
|
|
21
|
+
|
|
22
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
23
|
+
if len(buf) != 8:
|
|
24
|
+
raise BinaryParseError("Expected 8 bytes for uint64", buf, "memory")
|
|
25
|
+
value = struct.unpack(">Q", buf)[0]
|
|
26
|
+
return str(value)
|
|
27
|
+
|
|
28
|
+
def memory_validate(self, b: bytes) -> None:
|
|
29
|
+
if len(b) != 8:
|
|
30
|
+
raise ValueError(f"Invalid length: must be exactly 8 bytes, got {len(b)}")
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import binascii
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ..codecs import CodecBase
|
|
6
|
+
from ..exceptions import BinaryParseError
|
|
7
|
+
|
|
8
|
+
SIZE = 96
|
|
9
|
+
IS_PATH = False
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Codec(CodecBase):
|
|
13
|
+
SIZE = SIZE
|
|
14
|
+
IS_PATH = IS_PATH
|
|
15
|
+
|
|
16
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
17
|
+
try:
|
|
18
|
+
addr, port = string.split(":", 1)
|
|
19
|
+
if addr.endswith(".onion"):
|
|
20
|
+
addr = addr[:-6]
|
|
21
|
+
if len(addr) != 16:
|
|
22
|
+
raise ValueError("Invalid onion address length")
|
|
23
|
+
if not port.isdigit():
|
|
24
|
+
raise ValueError("Invalid onion port")
|
|
25
|
+
port_num = int(port)
|
|
26
|
+
if not 1 <= port_num <= 65535:
|
|
27
|
+
raise ValueError("Invalid onion port range")
|
|
28
|
+
# onion address is standard base32 (lowercase, no padding)
|
|
29
|
+
addr_bytes = base64.b32decode(addr.upper())
|
|
30
|
+
if len(addr_bytes) != 10:
|
|
31
|
+
raise ValueError("Decoded onion address must be 10 bytes")
|
|
32
|
+
return addr_bytes + port_num.to_bytes(2, byteorder="big")
|
|
33
|
+
except (ValueError, UnicodeEncodeError, binascii.Error) as e:
|
|
34
|
+
raise BinaryParseError(str(e), string.encode(), proto)
|
|
35
|
+
|
|
36
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
37
|
+
try:
|
|
38
|
+
if len(buf) != 12: # 10 bytes for address + 2 bytes for port
|
|
39
|
+
raise ValueError("Invalid onion address length")
|
|
40
|
+
# Base32 encode the address
|
|
41
|
+
try:
|
|
42
|
+
addr = base64.b32encode(buf[:10]).decode("ascii").lower()
|
|
43
|
+
except binascii.Error:
|
|
44
|
+
raise ValueError("Invalid base32 encoding")
|
|
45
|
+
# Remove padding
|
|
46
|
+
addr = addr.rstrip("=")
|
|
47
|
+
if len(addr) != 16:
|
|
48
|
+
raise ValueError("Invalid onion address length")
|
|
49
|
+
port = str(int.from_bytes(buf[10:12], byteorder="big"))
|
|
50
|
+
if not 1 <= int(port) <= 65535:
|
|
51
|
+
raise ValueError("Invalid onion port range")
|
|
52
|
+
return f"{addr}:{port}"
|
|
53
|
+
except (ValueError, UnicodeDecodeError, binascii.Error) as e:
|
|
54
|
+
raise BinaryParseError(str(e), buf, proto)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import binascii
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ..codecs import CodecBase
|
|
6
|
+
from ..exceptions import BinaryParseError
|
|
7
|
+
|
|
8
|
+
SIZE = 296
|
|
9
|
+
IS_PATH = False
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Codec(CodecBase):
|
|
13
|
+
SIZE = SIZE
|
|
14
|
+
IS_PATH = IS_PATH
|
|
15
|
+
|
|
16
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
17
|
+
try:
|
|
18
|
+
addr, port = string.split(":", 1)
|
|
19
|
+
if addr.endswith(".onion"):
|
|
20
|
+
addr = addr[:-6]
|
|
21
|
+
if len(addr) != 56:
|
|
22
|
+
raise ValueError("Invalid onion3 address length")
|
|
23
|
+
if not port.isdigit():
|
|
24
|
+
raise ValueError("Invalid onion3 port")
|
|
25
|
+
port_num = int(port)
|
|
26
|
+
if not 1 <= port_num <= 65535:
|
|
27
|
+
raise ValueError("Invalid onion3 port range")
|
|
28
|
+
# onion3 address is standard base32 (lowercase, no padding)
|
|
29
|
+
try:
|
|
30
|
+
addr_bytes = base64.b32decode(addr.upper())
|
|
31
|
+
except binascii.Error:
|
|
32
|
+
raise ValueError("Invalid base32 encoding")
|
|
33
|
+
if len(addr_bytes) != 35:
|
|
34
|
+
raise ValueError("Decoded onion3 address must be 35 bytes")
|
|
35
|
+
return addr_bytes + port_num.to_bytes(2, byteorder="big")
|
|
36
|
+
except (ValueError, UnicodeEncodeError, binascii.Error) as e:
|
|
37
|
+
raise BinaryParseError(str(e), string.encode(), proto)
|
|
38
|
+
|
|
39
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
40
|
+
try:
|
|
41
|
+
if len(buf) != 37:
|
|
42
|
+
raise ValueError("Invalid onion3 address length")
|
|
43
|
+
try:
|
|
44
|
+
addr = base64.b32encode(buf[:35]).decode("ascii").lower()
|
|
45
|
+
except binascii.Error:
|
|
46
|
+
raise ValueError("Invalid base32 encoding")
|
|
47
|
+
# Remove padding
|
|
48
|
+
addr = addr.rstrip("=")
|
|
49
|
+
if len(addr) != 56:
|
|
50
|
+
raise ValueError("Invalid onion3 address length")
|
|
51
|
+
port = str(int.from_bytes(buf[35:], byteorder="big"))
|
|
52
|
+
if not 1 <= int(port) <= 65535:
|
|
53
|
+
raise ValueError("Invalid onion3 port range")
|
|
54
|
+
return f"{addr}:{port}"
|
|
55
|
+
except (ValueError, UnicodeDecodeError, binascii.Error) as e:
|
|
56
|
+
raise BinaryParseError(str(e), buf, proto)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from ..codecs import CodecBase
|
|
4
|
+
|
|
5
|
+
SIZE = 16
|
|
6
|
+
IS_PATH = False
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Codec(CodecBase):
|
|
10
|
+
SIZE = SIZE
|
|
11
|
+
IS_PATH = IS_PATH
|
|
12
|
+
|
|
13
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
14
|
+
try:
|
|
15
|
+
n = int(string, 10)
|
|
16
|
+
except ValueError:
|
|
17
|
+
raise ValueError("invalid base 10 integer")
|
|
18
|
+
if n < 0 or n >= 65536:
|
|
19
|
+
raise ValueError("integer not in range [0, 65536)")
|
|
20
|
+
return n.to_bytes(2, byteorder="big")
|
|
21
|
+
|
|
22
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
23
|
+
if len(buf) != 2:
|
|
24
|
+
raise ValueError("buffer length must be 2 bytes")
|
|
25
|
+
return str(int.from_bytes(buf, byteorder="big"))
|
multiaddr/codecs/utf8.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import urllib.parse
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from ..exceptions import BinaryParseError
|
|
5
|
+
from . import CodecBase
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Codec(CodecBase):
|
|
9
|
+
SIZE = 0 # Variable size
|
|
10
|
+
IS_PATH = False # Default to False, will be set to True for ip6zone protocol
|
|
11
|
+
|
|
12
|
+
def to_bytes(self, proto: Any, string: str) -> bytes:
|
|
13
|
+
"""Convert a UTF-8 string to its binary representation."""
|
|
14
|
+
if not string:
|
|
15
|
+
raise ValueError("String cannot be empty")
|
|
16
|
+
|
|
17
|
+
# For ip6zone, ensure no leading/trailing whitespace and don't URL encode
|
|
18
|
+
if proto.name == "ip6zone":
|
|
19
|
+
string = string.strip()
|
|
20
|
+
if not string:
|
|
21
|
+
raise ValueError("Zone identifier cannot be empty after stripping whitespace")
|
|
22
|
+
else:
|
|
23
|
+
# URL decode the string to handle special characters for other protocols
|
|
24
|
+
string = urllib.parse.unquote(string)
|
|
25
|
+
|
|
26
|
+
# Encode as UTF-8
|
|
27
|
+
encoded = string.encode("utf-8")
|
|
28
|
+
|
|
29
|
+
# Do not add varint length prefix here; the framework handles it
|
|
30
|
+
return encoded
|
|
31
|
+
|
|
32
|
+
def to_string(self, proto: Any, buf: bytes) -> str:
|
|
33
|
+
"""Convert a binary UTF-8 string to its string representation."""
|
|
34
|
+
if not buf:
|
|
35
|
+
raise ValueError("Buffer cannot be empty")
|
|
36
|
+
|
|
37
|
+
# Decode from UTF-8
|
|
38
|
+
try:
|
|
39
|
+
value = buf.decode("utf-8")
|
|
40
|
+
# For ip6zone, ensure no leading/trailing whitespace and don't URL encode
|
|
41
|
+
if proto.name == "ip6zone":
|
|
42
|
+
value = value.strip()
|
|
43
|
+
if not value:
|
|
44
|
+
raise ValueError("Zone identifier cannot be empty after stripping whitespace")
|
|
45
|
+
return value
|
|
46
|
+
# For other protocols, URL encode special characters
|
|
47
|
+
return urllib.parse.quote(value, safe="%")
|
|
48
|
+
except UnicodeDecodeError as e:
|
|
49
|
+
raise BinaryParseError(f"Invalid UTF-8 encoding: {e!s}", buf, proto.name, e)
|