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.
@@ -0,0 +1,150 @@
1
+ from typing import Any
2
+
3
+
4
+ class Error(Exception):
5
+ pass
6
+
7
+
8
+ class MultiaddrLookupError(LookupError, Error):
9
+ pass
10
+
11
+
12
+ class ProtocolLookupError(MultiaddrLookupError):
13
+ """
14
+ MultiAddr did not contain a protocol with the requested code
15
+ """
16
+
17
+ def __init__(self, proto: Any, string: str) -> None:
18
+ self.proto = proto
19
+ self.string = string
20
+
21
+ super().__init__(f"MultiAddr {string!r} does not contain protocol {proto}")
22
+
23
+
24
+ class ParseError(ValueError, Error):
25
+ pass
26
+
27
+
28
+ class StringParseError(ParseError):
29
+ """
30
+ MultiAddr string representation could not be parsed
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ message: str,
36
+ string: str,
37
+ protocol: str | None = None,
38
+ original: Exception | None = None,
39
+ ) -> None:
40
+ self.message = message
41
+ self.string = string
42
+ self.protocol = protocol
43
+ self.original = original
44
+
45
+ if protocol:
46
+ message = f"Invalid MultiAddr {string!r} protocol {protocol}: {message}"
47
+ else:
48
+ message = f"Invalid MultiAddr {string!r}: {message}"
49
+
50
+ super().__init__(message)
51
+
52
+ def __str__(self) -> str:
53
+ base = super().__str__()
54
+ if self.protocol is not None:
55
+ base += f" (protocol: {self.protocol})"
56
+ if self.string is not None:
57
+ base += f" (string: {self.string})"
58
+ if self.original is not None:
59
+ base += f" (cause: {self.original})"
60
+ return base
61
+
62
+
63
+ class BinaryParseError(ParseError):
64
+ """
65
+ MultiAddr binary representation could not be parsed
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ message: str,
71
+ binary: bytes,
72
+ protocol: str | int,
73
+ original: Exception | None = None,
74
+ ) -> None:
75
+ self.message = message
76
+ self.binary = binary
77
+ self.protocol = protocol
78
+ self.original = original
79
+
80
+ message = f"Invalid binary MultiAddr protocol {protocol}: {message}"
81
+
82
+ super().__init__(message)
83
+
84
+ def __str__(self) -> str:
85
+ base = super().__str__()
86
+ if self.protocol is not None:
87
+ base += f" (protocol: {self.protocol})"
88
+ if self.binary is not None:
89
+ base += f" (binary: {self.binary!r})"
90
+ if self.original is not None:
91
+ base += f" (cause: {self.original})"
92
+ return base
93
+
94
+
95
+ class ProtocolRegistryError(Error):
96
+ pass
97
+
98
+
99
+ ProtocolManagerError = ProtocolRegistryError
100
+
101
+
102
+ class ProtocolRegistryLocked(Error):
103
+ """Protocol registry was locked and doesn't allow any further additions"""
104
+
105
+ def __init__(self) -> None:
106
+ super().__init__("Protocol registry is locked and does not accept any new values")
107
+
108
+
109
+ class ProtocolExistsError(ProtocolRegistryError):
110
+ """Protocol with the given name or code already exists"""
111
+
112
+ def __init__(self, proto: Any, kind: str = "name") -> None:
113
+ self.proto = proto
114
+ self.kind = kind
115
+
116
+ super().__init__(f"Protocol with {kind} {getattr(proto, kind)!r} already exists")
117
+
118
+
119
+ class ProtocolNotFoundError(ProtocolRegistryError):
120
+ """No protocol with the given name or code found"""
121
+
122
+ def __init__(self, value: str | int, kind: str = "name") -> None:
123
+ self.value = value
124
+ self.kind = kind
125
+
126
+ super().__init__(f"No protocol with {kind} {value!r} found")
127
+
128
+
129
+ class MultiaddrError(Exception):
130
+ """Base exception for multiaddr errors."""
131
+
132
+ def __init__(self, message: str = "Multiaddr error"):
133
+ super().__init__(message)
134
+ self.name = "MultiaddrError"
135
+
136
+
137
+ class ResolutionError(MultiaddrError):
138
+ """Raised when resolution fails."""
139
+
140
+ def __init__(self, message: str = "Resolution failed"):
141
+ super().__init__(message)
142
+ self.name = "ResolutionError"
143
+
144
+
145
+ class RecursionLimitError(ResolutionError):
146
+ """Raised when the maximum recursive depth is reached."""
147
+
148
+ def __init__(self, message: str = "Max recursive depth reached"):
149
+ super().__init__(message)
150
+ self.name = "RecursionLimitError"
multiaddr/multiaddr.py ADDED
@@ -0,0 +1,504 @@
1
+ import collections.abc
2
+ from collections.abc import Iterator, Sequence
3
+ from typing import Any, TypeVar, Union, overload
4
+
5
+ import varint
6
+
7
+ from . import exceptions, protocols
8
+ from .codecs import codec_by_name
9
+ from .protocols import protocol_with_name
10
+ from .transforms import bytes_iter, bytes_to_string
11
+
12
+ __all__ = ("Multiaddr",)
13
+
14
+
15
+ T = TypeVar("T")
16
+
17
+
18
+ class MultiAddrKeys(collections.abc.KeysView[Any], collections.abc.Sequence[Any]):
19
+ def __init__(self, mapping: "Multiaddr") -> None:
20
+ self._mapping = mapping
21
+ super().__init__(mapping)
22
+
23
+ def __contains__(self, proto: object) -> bool:
24
+ proto = self._mapping.registry.find(proto)
25
+ return collections.abc.Sequence.__contains__(self, proto)
26
+
27
+ def __getitem__(self, idx: int | slice) -> Any | Sequence[Any]:
28
+ if isinstance(idx, slice):
29
+ return list(self)[idx]
30
+ if idx < 0:
31
+ idx = len(self) + idx
32
+ for idx2, proto in enumerate(self):
33
+ if idx2 == idx:
34
+ return proto
35
+ raise IndexError("Protocol list index out of range")
36
+
37
+ def __hash__(self) -> int:
38
+ return hash(tuple(self))
39
+
40
+ def __iter__(self) -> Iterator[Any]:
41
+ for _, proto, _, _ in bytes_iter(self._mapping.to_bytes()):
42
+ yield proto
43
+
44
+
45
+ class MultiAddrItems(
46
+ collections.abc.ItemsView[Any, Any], collections.abc.Sequence[tuple[Any, Any]]
47
+ ):
48
+ def __init__(self, mapping: "Multiaddr") -> None:
49
+ self._mapping = mapping
50
+ super().__init__(mapping)
51
+
52
+ def __contains__(self, item: object) -> bool:
53
+ if not isinstance(item, tuple) or len(item) != 2:
54
+ return False
55
+ proto, value = item
56
+ proto = self._mapping.registry.find(proto)
57
+ return collections.abc.Sequence.__contains__(self, (proto, value))
58
+
59
+ @overload
60
+ def __getitem__(self, idx: int) -> tuple[Any, Any]: ...
61
+
62
+ @overload
63
+ def __getitem__(self, idx: slice) -> Sequence[tuple[Any, Any]]: ...
64
+
65
+ def __getitem__(self, idx: int | slice) -> tuple[Any, Any] | Sequence[tuple[Any, Any]]:
66
+ if isinstance(idx, slice):
67
+ return list(self)[idx]
68
+ if idx < 0:
69
+ idx = len(self) + idx
70
+ for idx2, item in enumerate(self):
71
+ if idx2 == idx:
72
+ return item
73
+ raise IndexError("Protocol item list index out of range")
74
+
75
+ def __iter__(self) -> Iterator[tuple[Any, Any]]:
76
+ for _, proto, codec, part in bytes_iter(self._mapping.to_bytes()):
77
+ if codec.SIZE != 0:
78
+ try:
79
+ # If we have an address, return it
80
+ yield proto, codec.to_string(proto, part)
81
+ except Exception as exc:
82
+ raise exceptions.BinaryParseError(
83
+ str(exc),
84
+ self._mapping.to_bytes(),
85
+ proto.name,
86
+ exc,
87
+ ) from exc
88
+ else:
89
+ # We were given something like '/utp', which doesn't have
90
+ # an address, so return None
91
+ yield proto, None
92
+
93
+
94
+ class MultiAddrValues(collections.abc.ValuesView[Any], collections.abc.Sequence[Any]):
95
+ def __init__(self, mapping: "Multiaddr") -> None:
96
+ self._mapping = mapping
97
+ super().__init__(mapping)
98
+
99
+ def __contains__(self, value: object) -> bool:
100
+ return collections.abc.Sequence.__contains__(self, value)
101
+
102
+ def __getitem__(self, idx: int | slice) -> Any | Sequence[Any]:
103
+ if isinstance(idx, slice):
104
+ return list(self)[idx]
105
+ if idx < 0:
106
+ idx = len(self) + idx
107
+ for idx2, value in enumerate(self):
108
+ if idx2 == idx:
109
+ return value
110
+ raise IndexError("Protocol value list index out of range")
111
+
112
+ def __iter__(self) -> Iterator[Any]:
113
+ for _, value in MultiAddrItems(self._mapping):
114
+ yield value
115
+
116
+
117
+ class Multiaddr(collections.abc.Mapping[Any, Any]):
118
+ """Multiaddr is a representation of multiple nested internet addresses.
119
+
120
+ Multiaddr is a cross-protocol, cross-platform format for representing
121
+ internet addresses. It emphasizes explicitness and self-description.
122
+
123
+ Learn more here: https://multiformats.io/multiaddr/
124
+
125
+ Multiaddrs have both a binary and string representation.
126
+
127
+ >>> from multiaddr import Multiaddr
128
+ >>> addr = Multiaddr("/ip4/1.2.3.4/tcp/80")
129
+
130
+ Multiaddr objects are immutable, so `encapsulate` and `decapsulate`
131
+ return new objects rather than modify internal state.
132
+ """
133
+
134
+ __slots__ = ("_bytes", "registry")
135
+
136
+ def __init__(
137
+ self, addr: Union[str, bytes, "Multiaddr"], *, registry: Any = protocols.REGISTRY
138
+ ) -> None:
139
+ """Instantiate a new Multiaddr.
140
+
141
+ Args:
142
+ addr : A string-encoded or a byte-encoded Multiaddr
143
+
144
+ """
145
+ self.registry = registry
146
+ if isinstance(addr, str):
147
+ self._from_string(addr)
148
+ elif isinstance(addr, bytes):
149
+ self._from_bytes(addr)
150
+ elif isinstance(addr, Multiaddr):
151
+ self._bytes = addr.to_bytes()
152
+ else:
153
+ raise TypeError("MultiAddr must be bytes, str or another MultiAddr instance")
154
+
155
+ @classmethod
156
+ def join(cls, *addrs: Union[str, bytes, "Multiaddr"]) -> "Multiaddr":
157
+ """Concatenate the values of the given MultiAddr strings or objects,
158
+ encapsulating each successive MultiAddr value with the previous ones."""
159
+ return cls(b"".join(map(lambda a: cls(a).to_bytes(), addrs)))
160
+
161
+ def __eq__(self, other: Any) -> bool:
162
+ """Checks if two Multiaddr objects are exactly equal."""
163
+ if not isinstance(other, Multiaddr):
164
+ return NotImplemented
165
+ return self._bytes == other._bytes
166
+
167
+ def __str__(self) -> str:
168
+ """Return the string representation of this Multiaddr.
169
+
170
+ May raise a :class:`~multiaddr.exceptions.BinaryParseError` if the
171
+ stored MultiAddr binary representation is invalid."""
172
+ return bytes_to_string(self._bytes)
173
+
174
+ def __contains__(self, proto: object) -> bool:
175
+ return proto in MultiAddrKeys(self)
176
+
177
+ def __iter__(self) -> Iterator[Any]:
178
+ return iter(MultiAddrKeys(self))
179
+
180
+ def __len__(self) -> int:
181
+ return sum(1 for _ in bytes_iter(self.to_bytes()))
182
+
183
+ def __repr__(self) -> str:
184
+ return "<Multiaddr %s>" % str(self)
185
+
186
+ def __hash__(self) -> int:
187
+ return self._bytes.__hash__()
188
+
189
+ def to_bytes(self) -> bytes:
190
+ """Returns the byte array representation of this Multiaddr."""
191
+ return self._bytes
192
+
193
+ __bytes__ = to_bytes
194
+
195
+ def protocols(self) -> MultiAddrKeys:
196
+ """Returns a list of Protocols this Multiaddr includes."""
197
+ return MultiAddrKeys(self)
198
+
199
+ def split(self, maxsplit: int = -1) -> list["Multiaddr"]:
200
+ """Returns the list of individual path components this MultiAddr is made
201
+ up of."""
202
+ final_split_offset = -1
203
+ results = []
204
+ for idx, (offset, proto, codec, part_value) in enumerate(bytes_iter(self._bytes)):
205
+ # Split at most `maxplit` times
206
+ if idx == maxsplit:
207
+ final_split_offset = offset
208
+ break
209
+
210
+ # Re-assemble binary MultiAddr representation
211
+ part_size = varint.encode(len(part_value)) if codec.SIZE < 0 else b""
212
+ part = b"".join((proto.vcode, part_size, part_value))
213
+
214
+ # Add MultiAddr with the given value
215
+ results.append(self.__class__(part))
216
+ # Add final item with remainder of MultiAddr if there is anything left
217
+ if final_split_offset >= 0:
218
+ results.append(self.__class__(self._bytes[final_split_offset:]))
219
+ return results
220
+
221
+ keys = protocols
222
+
223
+ def items(self) -> MultiAddrItems:
224
+ return MultiAddrItems(self)
225
+
226
+ def values(self) -> MultiAddrValues:
227
+ return MultiAddrValues(self)
228
+
229
+ def encapsulate(self, other: Union[str, bytes, "Multiaddr"]) -> "Multiaddr":
230
+ """Wrap this Multiaddr around another.
231
+
232
+ For example:
233
+ /ip4/1.2.3.4 encapsulate /tcp/80 = /ip4/1.2.3.4/tcp/80
234
+ """
235
+ return self.__class__.join(self, other)
236
+
237
+ def decapsulate(self, addr: Union["Multiaddr", str]) -> "Multiaddr":
238
+ """Remove a Multiaddr wrapping.
239
+
240
+ For example:
241
+ /ip4/1.2.3.4/tcp/80 decapsulate /ip4/1.2.3.4 = /tcp/80
242
+ """
243
+ addr_str = str(addr)
244
+ s = str(self)
245
+ i = s.rindex(addr_str)
246
+ if i < 0:
247
+ raise ValueError(f"Address {s} does not contain subaddress: {addr_str}")
248
+ return Multiaddr(s[:i])
249
+
250
+ def decapsulate_code(self, code: int) -> "Multiaddr":
251
+ """
252
+ Remove the last occurrence of the protocol with the given code and everything after it.
253
+ If the protocol code is not present, return the original multiaddr.
254
+ """
255
+ # Find all protocol codes and their offsets
256
+ offsets = []
257
+ for offset, proto, codec, part_value in bytes_iter(self._bytes):
258
+ offsets.append((offset, proto.code))
259
+ # Find the last occurrence of the code
260
+ last_index = -1
261
+ for i, (offset, proto_code) in enumerate(offsets):
262
+ if proto_code == code:
263
+ last_index = i
264
+ if last_index == -1:
265
+ # Protocol code not found, return original
266
+ return self
267
+ # Get the offset to slice up to
268
+ cut_offset = offsets[last_index][0]
269
+ if cut_offset == 0:
270
+ return self.__class__("")
271
+ return self.__class__(self._bytes[:cut_offset])
272
+
273
+ def value_for_protocol(self, proto: Any) -> Any | None:
274
+ """Return the value (if any) following the specified protocol
275
+
276
+ Returns
277
+ -------
278
+ Union[object, NoneType]
279
+ The parsed protocol value for the given protocol code or ``None``
280
+ if the given protocol does not require any value
281
+
282
+ Raises
283
+ ------
284
+ ~multiaddr.exceptions.BinaryParseError
285
+ The stored MultiAddr binary representation is invalid
286
+ ~multiaddr.exceptions.ProtocolLookupError
287
+ MultiAddr does not contain any instance of this protocol
288
+ """
289
+ proto = self.registry.find(proto)
290
+ for proto2, value in self.items():
291
+ if proto2 is proto or proto2 == proto:
292
+ return value
293
+ raise exceptions.ProtocolLookupError(proto, str(self))
294
+
295
+ def __getitem__(self, proto: Any) -> Any:
296
+ """Returns the value for the given protocol.
297
+
298
+ Raises
299
+ ------
300
+ ~multiaddr.exceptions.ProtocolLookupError
301
+ If the protocol is not found in this Multiaddr.
302
+ ~multiaddr.exceptions.BinaryParseError
303
+ If the protocol value is invalid.
304
+ """
305
+ proto = self.registry.find(proto)
306
+ for _, p, codec, part in bytes_iter(self._bytes):
307
+ if p == proto:
308
+ if codec.SIZE == 0:
309
+ return None
310
+ try:
311
+ return codec.to_string(proto, part)
312
+ except Exception as exc:
313
+ raise exceptions.BinaryParseError(
314
+ str(exc),
315
+ self._bytes,
316
+ proto.name,
317
+ exc,
318
+ ) from exc
319
+ raise exceptions.ProtocolLookupError(proto, str(self))
320
+
321
+ async def resolve(self) -> list["Multiaddr"]:
322
+ """Resolve this multiaddr if it contains a resolvable protocol.
323
+
324
+ Returns:
325
+ A list of resolved multiaddrs
326
+ """
327
+ from .resolvers.dns import DNSResolver
328
+
329
+ resolver: DNSResolver = DNSResolver()
330
+ return await resolver.resolve(self)
331
+
332
+ def _from_string(self, addr: str) -> None:
333
+ """Parse a string multiaddr.
334
+
335
+ Args:
336
+ addr: The multiaddr string to parse.
337
+
338
+ Raises:
339
+ StringParseError: If the string multiaddr is invalid.
340
+ """
341
+ if not addr:
342
+ # Allow empty multiaddrs (like JavaScript implementation)
343
+ self._bytes = b""
344
+ return
345
+
346
+ # Handle other protocols
347
+ parts = iter(addr.strip("/").split("/"))
348
+ if not parts:
349
+ raise exceptions.StringParseError("empty multiaddr", addr)
350
+
351
+ self._bytes = b""
352
+ for part in parts:
353
+ if not part:
354
+ continue
355
+
356
+ # Special handling for unix paths
357
+ if part == "unix":
358
+ try:
359
+ # Get the next part as the path value
360
+ unix_path_value = next(parts)
361
+ if not unix_path_value:
362
+ raise exceptions.StringParseError("empty unix path", addr)
363
+
364
+ # Join any remaining parts as part of the path
365
+ remaining_parts = []
366
+ while True:
367
+ try:
368
+ next_part = next(parts)
369
+ if not next_part:
370
+ continue
371
+ remaining_parts.append(next_part)
372
+ except StopIteration:
373
+ break
374
+
375
+ if remaining_parts:
376
+ unix_path_value = unix_path_value + "/" + "/".join(remaining_parts)
377
+
378
+ proto = protocol_with_name("unix")
379
+ codec = codec_by_name(proto.codec)
380
+ if not codec:
381
+ raise exceptions.StringParseError(f"unknown codec: {proto.codec}", addr)
382
+
383
+ try:
384
+ self._bytes += varint.encode(proto.code)
385
+ buf = codec.to_bytes(proto, unix_path_value)
386
+ # Add length prefix for variable-sized or zero-sized codecs
387
+ if codec.SIZE <= 0:
388
+ self._bytes += varint.encode(len(buf))
389
+ if buf: # Only append buffer if it's not empty
390
+ self._bytes += buf
391
+ except Exception as e:
392
+ raise exceptions.StringParseError(str(e), addr) from e
393
+ continue
394
+ except StopIteration:
395
+ raise exceptions.StringParseError("missing value for unix protocol", addr)
396
+
397
+ # Handle other protocols
398
+ # Split protocol name and value if present
399
+ protocol_value: str | None = None
400
+ if "=" in part:
401
+ proto_name, protocol_value = part.split("=", 1)
402
+ else:
403
+ proto_name = part
404
+
405
+ try:
406
+ proto = protocol_with_name(proto_name)
407
+ except Exception as exc:
408
+ raise exceptions.StringParseError(f"unknown protocol: {proto_name}", addr) from exc
409
+
410
+ # If the protocol expects a value, get it
411
+ if proto.codec is not None:
412
+ if protocol_value is None:
413
+ try:
414
+ protocol_value = next(parts)
415
+ except StopIteration:
416
+ raise exceptions.StringParseError(
417
+ f"missing value for protocol: {proto_name}", addr
418
+ )
419
+ # Validate value (optional: could add more checks here)
420
+ # If value looks like a protocol name, that's an error
421
+ if protocol_value is not None:
422
+ try:
423
+ protocol_with_name(protocol_value)
424
+ # If no exception, value is a protocol name, which is not allowed here
425
+ raise exceptions.StringParseError(
426
+ f"expected value for protocol {proto_name}, "
427
+ f"got protocol name {protocol_value}",
428
+ addr,
429
+ )
430
+ except exceptions.ProtocolNotFoundError:
431
+ pass # value is not a protocol name, so it's valid as a value
432
+
433
+ codec = codec_by_name(proto.codec)
434
+ if not codec:
435
+ raise exceptions.StringParseError(f"unknown codec: {proto.codec}", addr)
436
+
437
+ try:
438
+ self._bytes += varint.encode(proto.code)
439
+
440
+ # Special case: protocols with codec=None are flag protocols
441
+ # (no value, no length prefix, no buffer)
442
+ if proto.codec is None:
443
+ continue
444
+
445
+ buf = codec.to_bytes(proto, protocol_value or "")
446
+ if codec.SIZE <= 0: # Add length prefix for variable-sized or zero-sized codecs
447
+ self._bytes += varint.encode(len(buf))
448
+ if buf: # Only append buffer if it's not empty
449
+ self._bytes += buf
450
+ except Exception as e:
451
+ raise exceptions.StringParseError(str(e), addr) from e
452
+
453
+ def _from_bytes(self, addr: bytes) -> None:
454
+ """Parse a binary multiaddr.
455
+
456
+ Args:
457
+ addr: The multiaddr bytes to parse.
458
+
459
+ Raises:
460
+ BinaryParseError: If the binary multiaddr is invalid.
461
+ """
462
+ if not addr:
463
+ # Allow empty multiaddrs (like JavaScript implementation)
464
+ self._bytes = b""
465
+ return
466
+
467
+ self._bytes = addr
468
+
469
+ def get_peer_id(self) -> str | None:
470
+ """Get the peer ID from the multiaddr.
471
+
472
+ For circuit addresses, returns the target peer ID, not the relay peer ID.
473
+
474
+ Returns:
475
+ The peer ID if found, None otherwise.
476
+
477
+ Raises:
478
+ BinaryParseError: If the binary multiaddr is invalid.
479
+ """
480
+ try:
481
+ tuples = []
482
+
483
+ for _, proto, codec, part in bytes_iter(self._bytes):
484
+ if proto.name == "p2p":
485
+ tuples.append((proto, part))
486
+
487
+ # If this is a p2p-circuit address, reset tuples to get target peer id
488
+ # not the peer id of the relay
489
+ if proto.name == "p2p-circuit":
490
+ tuples = []
491
+
492
+ # Get the last p2p tuple (target peer ID for circuits)
493
+ if tuples:
494
+ last_tuple = tuples[-1]
495
+ proto, part = last_tuple
496
+ # Get the codec for this specific protocol
497
+ codec = codec_by_name(proto.codec)
498
+ # Handle both fixed-size and variable-sized codecs
499
+ if codec is not None and codec.SIZE != 0:
500
+ return codec.to_string(proto, part)
501
+
502
+ return None
503
+ except Exception:
504
+ return None