astreum 0.2.37__tar.gz → 0.2.53__tar.gz
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.
- {astreum-0.2.37/src/astreum.egg-info → astreum-0.2.53}/PKG-INFO +14 -1
- {astreum-0.2.37 → astreum-0.2.53}/README.md +13 -0
- {astreum-0.2.37 → astreum-0.2.53}/pyproject.toml +1 -1
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_communication/__init__.py +2 -0
- {astreum-0.2.37/src/astreum/models → astreum-0.2.53/src/astreum/_communication}/message.py +101 -64
- astreum-0.2.53/src/astreum/_communication/peer.py +23 -0
- astreum-0.2.53/src/astreum/_communication/ping.py +33 -0
- astreum-0.2.53/src/astreum/_communication/route.py +95 -0
- astreum-0.2.53/src/astreum/_communication/setup.py +322 -0
- astreum-0.2.53/src/astreum/_communication/util.py +42 -0
- astreum-0.2.53/src/astreum/_consensus/__init__.py +20 -0
- astreum-0.2.53/src/astreum/_consensus/account.py +95 -0
- astreum-0.2.53/src/astreum/_consensus/accounts.py +38 -0
- astreum-0.2.53/src/astreum/_consensus/block.py +311 -0
- {astreum-0.2.37/src/astreum/_validation → astreum-0.2.53/src/astreum/_consensus}/chain.py +65 -62
- {astreum-0.2.37/src/astreum/_validation → astreum-0.2.53/src/astreum/_consensus}/fork.py +99 -97
- astreum-0.2.53/src/astreum/_consensus/genesis.py +72 -0
- astreum-0.2.53/src/astreum/_consensus/receipt.py +177 -0
- astreum-0.2.53/src/astreum/_consensus/setup.py +115 -0
- astreum-0.2.53/src/astreum/_consensus/transaction.py +215 -0
- astreum-0.2.53/src/astreum/_consensus/workers/__init__.py +9 -0
- astreum-0.2.53/src/astreum/_consensus/workers/discovery.py +48 -0
- astreum-0.2.53/src/astreum/_consensus/workers/validation.py +125 -0
- astreum-0.2.53/src/astreum/_consensus/workers/verify.py +63 -0
- astreum-0.2.53/src/astreum/_lispeum/expression.py +181 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/high_evaluation.py +47 -34
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/low_evaluation.py +21 -21
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/parser.py +26 -31
- astreum-0.2.53/src/astreum/_node.py +163 -0
- astreum-0.2.53/src/astreum/_storage/__init__.py +7 -0
- astreum-0.2.53/src/astreum/_storage/atom.py +109 -0
- astreum-0.2.53/src/astreum/_storage/patricia.py +443 -0
- astreum-0.2.53/src/astreum/_storage/setup.py +35 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/models/block.py +30 -30
- astreum-0.2.53/src/astreum/node.py +781 -0
- astreum-0.2.53/src/astreum/utils/bytes.py +24 -0
- astreum-0.2.53/src/astreum/utils/integer.py +25 -0
- astreum-0.2.53/src/astreum/utils/logging.py +219 -0
- {astreum-0.2.37 → astreum-0.2.53/src/astreum.egg-info}/PKG-INFO +14 -1
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum.egg-info/SOURCES.txt +23 -20
- astreum-0.2.37/src/astreum/_communication/peer.py +0 -11
- astreum-0.2.37/src/astreum/_communication/route.py +0 -25
- astreum-0.2.37/src/astreum/_communication/setup.py +0 -104
- astreum-0.2.37/src/astreum/_lispeum/expression.py +0 -37
- astreum-0.2.37/src/astreum/_node.py +0 -58
- astreum-0.2.37/src/astreum/_storage/__init__.py +0 -5
- astreum-0.2.37/src/astreum/_storage/atom.py +0 -100
- astreum-0.2.37/src/astreum/_validation/__init__.py +0 -12
- astreum-0.2.37/src/astreum/_validation/block.py +0 -296
- astreum-0.2.37/src/astreum/_validation/genesis.py +0 -0
- astreum-0.2.37/src/astreum/_validation/setup.py +0 -141
- astreum-0.2.37/src/astreum/lispeum/environment.py +0 -40
- astreum-0.2.37/src/astreum/lispeum/expression.py +0 -86
- astreum-0.2.37/src/astreum/lispeum/parser.py +0 -41
- astreum-0.2.37/src/astreum/lispeum/tokenizer.py +0 -52
- astreum-0.2.37/src/astreum/models/account.py +0 -91
- astreum-0.2.37/src/astreum/models/accounts.py +0 -34
- astreum-0.2.37/src/astreum/models/transaction.py +0 -106
- astreum-0.2.37/src/astreum/node.py +0 -779
- astreum-0.2.37/src/astreum/relay/__init__.py +0 -0
- astreum-0.2.37/src/astreum/relay/peer.py +0 -9
- astreum-0.2.37/src/astreum/relay/route.py +0 -25
- astreum-0.2.37/src/astreum/relay/setup.py +0 -58
- astreum-0.2.37/src/astreum/storage/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/LICENSE +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/setup.cfg +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/environment.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/meter.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/_lispeum/tokenizer.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/crypto/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/crypto/ed25519.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/crypto/quadratic_form.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/crypto/wesolowski.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/crypto/x25519.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/format.py +0 -0
- {astreum-0.2.37/src/astreum/lispeum → astreum-0.2.53/src/astreum/models}/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/models/merkle.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/models/patricia.py +0 -0
- {astreum-0.2.37/src/astreum/models → astreum-0.2.53/src/astreum/storage}/__init__.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/storage/object.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum/storage/setup.py +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum.egg-info/dependency_links.txt +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum.egg-info/requires.txt +0 -0
- {astreum-0.2.37 → astreum-0.2.53}/src/astreum.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: astreum
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.53
|
|
4
4
|
Summary: Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
|
|
5
5
|
Author-email: "Roy R. O. Okello" <roy@stelar.xyz>
|
|
6
6
|
Project-URL: Homepage, https://github.com/astreum/lib
|
|
@@ -35,6 +35,8 @@ When initializing an `astreum.Node`, pass a dictionary with any of the options b
|
|
|
35
35
|
| `validation_secret_key` | hex string | `None` | X25519 private key that lets the node participate in the validation route. Leave unset for a non‑validator node. |
|
|
36
36
|
| `storage_path` | string | `None` | Directory where objects are persisted. If *None*, the node uses an in‑memory store. |
|
|
37
37
|
| `storage_get_relay_timeout` | float | `5` | Seconds to wait for an object requested from peers before timing‑out. |
|
|
38
|
+
| `logging_retention` | int | `90` | Number of days to keep rotated log files (daily gzip). |
|
|
39
|
+
| `verbose` | bool | `False` | When **True**, also mirror JSON logs to stdout with a human-readable format. |
|
|
38
40
|
|
|
39
41
|
### Networking
|
|
40
42
|
|
|
@@ -136,6 +138,17 @@ except ParseError as e:
|
|
|
136
138
|
|
|
137
139
|
---
|
|
138
140
|
|
|
141
|
+
|
|
142
|
+
## Logging
|
|
143
|
+
|
|
144
|
+
Every `Node` instance wires up structured logging automatically:
|
|
145
|
+
|
|
146
|
+
- Logs land in per-instance files named `node.log` under `%LOCALAPPDATA%\Astreum\lib-py\logs/<instance_id>` on Windows and `$XDG_STATE_HOME` (or `~/.local/state`)/`Astreum/lib-py/logs/<instance_id>` on other platforms. The `<instance_id>` is the first 16 hex characters of a BLAKE3 hash of the caller's file path, so running the node from different entry points keeps their logs isolated.
|
|
147
|
+
- Files rotate at midnight UTC with gzip compression (`node-YYYY-MM-DD.log.gz`) and retain 90 days by default. Override via `config["logging_retention"]`.
|
|
148
|
+
- Each event is a single JSON line containing timestamp, level, logger, message, process/thread info, module/function, and the derived `instance_id`.
|
|
149
|
+
- Set `config["verbose"] = True` to mirror logs to stdout in a human-friendly format like `[2025-04-13-42-59] [info] Starting Astreum Node`.
|
|
150
|
+
- The very first entry emitted is the banner `Starting Astreum Node`, signalling that the logging pipeline is live before other subsystems spin up.
|
|
151
|
+
|
|
139
152
|
## Testing
|
|
140
153
|
|
|
141
154
|
```bash
|
|
@@ -17,6 +17,8 @@ When initializing an `astreum.Node`, pass a dictionary with any of the options b
|
|
|
17
17
|
| `validation_secret_key` | hex string | `None` | X25519 private key that lets the node participate in the validation route. Leave unset for a non‑validator node. |
|
|
18
18
|
| `storage_path` | string | `None` | Directory where objects are persisted. If *None*, the node uses an in‑memory store. |
|
|
19
19
|
| `storage_get_relay_timeout` | float | `5` | Seconds to wait for an object requested from peers before timing‑out. |
|
|
20
|
+
| `logging_retention` | int | `90` | Number of days to keep rotated log files (daily gzip). |
|
|
21
|
+
| `verbose` | bool | `False` | When **True**, also mirror JSON logs to stdout with a human-readable format. |
|
|
20
22
|
|
|
21
23
|
### Networking
|
|
22
24
|
|
|
@@ -118,6 +120,17 @@ except ParseError as e:
|
|
|
118
120
|
|
|
119
121
|
---
|
|
120
122
|
|
|
123
|
+
|
|
124
|
+
## Logging
|
|
125
|
+
|
|
126
|
+
Every `Node` instance wires up structured logging automatically:
|
|
127
|
+
|
|
128
|
+
- Logs land in per-instance files named `node.log` under `%LOCALAPPDATA%\Astreum\lib-py\logs/<instance_id>` on Windows and `$XDG_STATE_HOME` (or `~/.local/state`)/`Astreum/lib-py/logs/<instance_id>` on other platforms. The `<instance_id>` is the first 16 hex characters of a BLAKE3 hash of the caller's file path, so running the node from different entry points keeps their logs isolated.
|
|
129
|
+
- Files rotate at midnight UTC with gzip compression (`node-YYYY-MM-DD.log.gz`) and retain 90 days by default. Override via `config["logging_retention"]`.
|
|
130
|
+
- Each event is a single JSON line containing timestamp, level, logger, message, process/thread info, module/function, and the derived `instance_id`.
|
|
131
|
+
- Set `config["verbose"] = True` to mirror logs to stdout in a human-friendly format like `[2025-04-13-42-59] [info] Starting Astreum Node`.
|
|
132
|
+
- The very first entry emitted is the banner `Starting Astreum Node`, signalling that the logging pipeline is live before other subsystems spin up.
|
|
133
|
+
|
|
121
134
|
## Testing
|
|
122
135
|
|
|
123
136
|
```bash
|
|
@@ -1,64 +1,101 @@
|
|
|
1
|
-
from enum import IntEnum
|
|
2
|
-
from
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
1
|
+
from enum import IntEnum
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from cryptography.hazmat.primitives import serialization
|
|
4
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey
|
|
5
|
+
|
|
6
|
+
class MessageTopic(IntEnum):
|
|
7
|
+
PING = 0
|
|
8
|
+
OBJECT_REQUEST = 1
|
|
9
|
+
OBJECT_RESPONSE = 2
|
|
10
|
+
ROUTE_REQUEST = 3
|
|
11
|
+
ROUTE_RESPONSE = 4
|
|
12
|
+
TRANSACTION = 5
|
|
13
|
+
STORAGE_REQUEST = 6
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Message:
|
|
17
|
+
handshake: bool
|
|
18
|
+
sender: Optional[X25519PublicKey]
|
|
19
|
+
|
|
20
|
+
topic: Optional[MessageTopic]
|
|
21
|
+
content: bytes
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
*,
|
|
26
|
+
handshake: bool = False,
|
|
27
|
+
sender: Optional[X25519PublicKey] = None,
|
|
28
|
+
topic: Optional[MessageTopic] = None,
|
|
29
|
+
content: bytes = b"",
|
|
30
|
+
body: Optional[bytes] = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
if body is not None:
|
|
33
|
+
if content and content != b"":
|
|
34
|
+
raise ValueError("specify only one of 'content' or 'body'")
|
|
35
|
+
content = body
|
|
36
|
+
|
|
37
|
+
self.handshake = handshake
|
|
38
|
+
self.sender = sender
|
|
39
|
+
self.topic = topic
|
|
40
|
+
self.content = content or b""
|
|
41
|
+
|
|
42
|
+
if self.handshake:
|
|
43
|
+
if self.sender is None:
|
|
44
|
+
raise ValueError("handshake Message requires a sender public key")
|
|
45
|
+
self.topic = None
|
|
46
|
+
self.content = b""
|
|
47
|
+
else:
|
|
48
|
+
if self.topic is None:
|
|
49
|
+
raise ValueError("non-handshake Message requires a topic")
|
|
50
|
+
|
|
51
|
+
def to_bytes(self):
|
|
52
|
+
if self.handshake:
|
|
53
|
+
# handshake byte (1) + raw public key bytes
|
|
54
|
+
return bytes([1]) + self.sender.public_bytes(
|
|
55
|
+
encoding=serialization.Encoding.Raw,
|
|
56
|
+
format=serialization.PublicFormat.Raw
|
|
57
|
+
)
|
|
58
|
+
else:
|
|
59
|
+
# normal message: 0 + topic + content
|
|
60
|
+
return bytes([0, self.topic.value]) + self.content
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_bytes(cls, data: bytes) -> "Message":
|
|
64
|
+
if len(data) < 1:
|
|
65
|
+
raise ValueError("Cannot parse Message: no data")
|
|
66
|
+
flag = data[0]
|
|
67
|
+
# create empty instance
|
|
68
|
+
msg = cls.__new__(cls)
|
|
69
|
+
|
|
70
|
+
if flag == 1:
|
|
71
|
+
# handshake message: the rest is the peer’s public key
|
|
72
|
+
key_bytes = data[1:]
|
|
73
|
+
if not key_bytes:
|
|
74
|
+
raise ValueError("Handshake message missing sender public key bytes")
|
|
75
|
+
try:
|
|
76
|
+
sender = X25519PublicKey.from_public_bytes(key_bytes)
|
|
77
|
+
except ValueError:
|
|
78
|
+
raise ValueError("Invalid public key bytes")
|
|
79
|
+
if sender is None:
|
|
80
|
+
raise ValueError("Handshake message missing sender public key")
|
|
81
|
+
msg.handshake = True
|
|
82
|
+
msg.sender = sender
|
|
83
|
+
msg.topic = None
|
|
84
|
+
msg.content = b''
|
|
85
|
+
elif flag == 0:
|
|
86
|
+
# normal message: next byte is topic, rest is content
|
|
87
|
+
if len(data) < 2:
|
|
88
|
+
raise ValueError("Cannot parse Message: missing topic byte")
|
|
89
|
+
topic_val = data[1]
|
|
90
|
+
try:
|
|
91
|
+
topic = MessageTopic(topic_val)
|
|
92
|
+
except ValueError:
|
|
93
|
+
raise ValueError(f"Unknown MessageTopic: {topic_val}")
|
|
94
|
+
msg.handshake = False
|
|
95
|
+
msg.sender = None
|
|
96
|
+
msg.topic = topic
|
|
97
|
+
msg.content = data[2:]
|
|
98
|
+
else:
|
|
99
|
+
raise ValueError(f"Invalid handshake flag: {flag}")
|
|
100
|
+
|
|
101
|
+
return msg
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
|
2
|
+
from cryptography.hazmat.primitives import serialization
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Optional, Tuple
|
|
5
|
+
|
|
6
|
+
class Peer:
|
|
7
|
+
shared_key: bytes
|
|
8
|
+
timestamp: datetime
|
|
9
|
+
latest_block: bytes
|
|
10
|
+
address: Optional[Tuple[str, int]]
|
|
11
|
+
public_key: X25519PublicKey
|
|
12
|
+
public_key_bytes: bytes
|
|
13
|
+
|
|
14
|
+
def __init__(self, my_sec_key: X25519PrivateKey, peer_pub_key: X25519PublicKey):
|
|
15
|
+
self.shared_key = my_sec_key.exchange(peer_pub_key)
|
|
16
|
+
self.timestamp = datetime.now(timezone.utc)
|
|
17
|
+
self.latest_block = b""
|
|
18
|
+
self.address = None
|
|
19
|
+
self.public_key = peer_pub_key
|
|
20
|
+
self.public_key_bytes = peer_pub_key.public_bytes(
|
|
21
|
+
encoding=serialization.Encoding.Raw,
|
|
22
|
+
format=serialization.PublicFormat.Raw,
|
|
23
|
+
)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PingFormatError(ValueError):
|
|
7
|
+
"""Raised when ping payload bytes are invalid."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Ping:
|
|
12
|
+
is_validator: bool
|
|
13
|
+
latest_block: bytes
|
|
14
|
+
|
|
15
|
+
PAYLOAD_SIZE = 33
|
|
16
|
+
|
|
17
|
+
def __post_init__(self) -> None:
|
|
18
|
+
lb = bytes(self.latest_block or b"")
|
|
19
|
+
if len(lb) != 32:
|
|
20
|
+
raise ValueError("latest_block must be exactly 32 bytes")
|
|
21
|
+
self.latest_block = lb
|
|
22
|
+
|
|
23
|
+
def to_bytes(self) -> bytes:
|
|
24
|
+
return (b"\x01" if self.is_validator else b"\x00") + self.latest_block
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def from_bytes(cls, data: bytes) -> "Ping":
|
|
28
|
+
if len(data) != cls.PAYLOAD_SIZE:
|
|
29
|
+
raise PingFormatError("ping payload must be exactly 33 bytes")
|
|
30
|
+
flag = data[0]
|
|
31
|
+
if flag not in (0, 1):
|
|
32
|
+
raise PingFormatError("ping validator flag must be 0 or 1")
|
|
33
|
+
return cls(is_validator=bool(flag), latest_block=data[1:])
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from typing import Dict, List, Optional, Union
|
|
2
|
+
from cryptography.hazmat.primitives import serialization
|
|
3
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey
|
|
4
|
+
from .peer import Peer
|
|
5
|
+
|
|
6
|
+
PeerKey = Union[X25519PublicKey, bytes, bytearray]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Route:
|
|
10
|
+
def __init__(self, relay_public_key: X25519PublicKey, bucket_size: int = 16):
|
|
11
|
+
self.relay_public_key_bytes = relay_public_key.public_bytes(
|
|
12
|
+
encoding=serialization.Encoding.Raw,
|
|
13
|
+
format=serialization.PublicFormat.Raw,
|
|
14
|
+
)
|
|
15
|
+
self.bucket_size = bucket_size
|
|
16
|
+
self.buckets: Dict[int, List[bytes]] = {
|
|
17
|
+
i: [] for i in range(len(self.relay_public_key_bytes) * 8)
|
|
18
|
+
}
|
|
19
|
+
self.peers: Dict[bytes, Peer] = {}
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def _matching_leading_bits(a: bytes, b: bytes) -> int:
|
|
23
|
+
for byte_index, (ba, bb) in enumerate(zip(a, b)):
|
|
24
|
+
diff = ba ^ bb
|
|
25
|
+
if diff:
|
|
26
|
+
return byte_index * 8 + (8 - diff.bit_length())
|
|
27
|
+
return len(a) * 8
|
|
28
|
+
|
|
29
|
+
def _normalize_peer_key(self, peer_public_key: PeerKey) -> bytes:
|
|
30
|
+
if isinstance(peer_public_key, X25519PublicKey):
|
|
31
|
+
return peer_public_key.public_bytes(
|
|
32
|
+
encoding=serialization.Encoding.Raw,
|
|
33
|
+
format=serialization.PublicFormat.Raw,
|
|
34
|
+
)
|
|
35
|
+
if isinstance(peer_public_key, (bytes, bytearray)):
|
|
36
|
+
key_bytes = bytes(peer_public_key)
|
|
37
|
+
if len(key_bytes) != len(self.relay_public_key_bytes):
|
|
38
|
+
raise ValueError("peer key must be raw 32-byte public key")
|
|
39
|
+
return key_bytes
|
|
40
|
+
raise TypeError("peer_public_key must be raw bytes or X25519PublicKey")
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def _xor_distance(a: bytes, b: bytes) -> int:
|
|
44
|
+
if len(a) != len(b):
|
|
45
|
+
raise ValueError("xor distance requires equal-length operands")
|
|
46
|
+
return int.from_bytes(bytes(x ^ y for x, y in zip(a, b)), "big", signed=False)
|
|
47
|
+
|
|
48
|
+
def add_peer(self, peer_public_key: PeerKey, peer: Optional[Peer] = None):
|
|
49
|
+
peer_public_key_bytes = self._normalize_peer_key(peer_public_key)
|
|
50
|
+
bucket_idx = self._matching_leading_bits(self.relay_public_key_bytes, peer_public_key_bytes)
|
|
51
|
+
if len(self.buckets[bucket_idx]) < self.bucket_size:
|
|
52
|
+
bucket = self.buckets[bucket_idx]
|
|
53
|
+
if peer_public_key_bytes not in bucket:
|
|
54
|
+
bucket.append(peer_public_key_bytes)
|
|
55
|
+
if peer is not None:
|
|
56
|
+
self.peers[peer_public_key_bytes] = peer
|
|
57
|
+
|
|
58
|
+
def remove_peer(self, peer_public_key: PeerKey):
|
|
59
|
+
peer_public_key_bytes = self._normalize_peer_key(peer_public_key)
|
|
60
|
+
bucket_idx = self._matching_leading_bits(self.relay_public_key_bytes, peer_public_key_bytes)
|
|
61
|
+
bucket = self.buckets.get(bucket_idx)
|
|
62
|
+
if not bucket:
|
|
63
|
+
return
|
|
64
|
+
try:
|
|
65
|
+
bucket.remove(peer_public_key_bytes)
|
|
66
|
+
except ValueError:
|
|
67
|
+
pass
|
|
68
|
+
self.peers.pop(peer_public_key_bytes, None)
|
|
69
|
+
|
|
70
|
+
def closest_peer_for_hash(self, target_hash: bytes) -> Optional[Peer]:
|
|
71
|
+
"""Return the peer with the minimal XOR distance to ``target_hash``."""
|
|
72
|
+
if not isinstance(target_hash, (bytes, bytearray)):
|
|
73
|
+
raise TypeError("target_hash must be bytes-like")
|
|
74
|
+
|
|
75
|
+
target = bytes(target_hash)
|
|
76
|
+
if len(target) != len(self.relay_public_key_bytes):
|
|
77
|
+
raise ValueError("target_hash must match peer key length (32 bytes)")
|
|
78
|
+
|
|
79
|
+
closest_key: Optional[bytes] = None
|
|
80
|
+
closest_distance: Optional[int] = None
|
|
81
|
+
|
|
82
|
+
for bucket in self.buckets.values():
|
|
83
|
+
for peer_key in bucket:
|
|
84
|
+
try:
|
|
85
|
+
distance = self._xor_distance(target, peer_key)
|
|
86
|
+
except ValueError:
|
|
87
|
+
continue
|
|
88
|
+
if closest_distance is None or distance < closest_distance:
|
|
89
|
+
closest_distance = distance
|
|
90
|
+
closest_key = peer_key
|
|
91
|
+
|
|
92
|
+
if closest_key is None:
|
|
93
|
+
return None
|
|
94
|
+
peer = self.peers.get(closest_key)
|
|
95
|
+
return peer
|