astreum 0.2.36__py3-none-any.whl → 0.2.38__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.

Potentially problematic release.


This version of astreum might be problematic. Click here for more details.

astreum/__init__.py CHANGED
@@ -1 +1,9 @@
1
- from ._node import Node, Expr, Env, tokenize, parse
1
+ """Lightweight package initializer to avoid circular imports during tests.
2
+
3
+ Exports are intentionally minimal; import submodules directly as needed:
4
+ - Node, Expr, Env, tokenize, parse -> from astreum._node or astreum.lispeum
5
+ - Validation types -> from astreum._validation
6
+ - Storage types -> from astreum._storage
7
+ """
8
+
9
+ __all__: list[str] = []
@@ -0,0 +1,9 @@
1
+ from .peer import Peer
2
+ from .route import Route
3
+ from .setup import communication_setup
4
+
5
+ __all__ = [
6
+ "Peer",
7
+ "Route",
8
+ "communication_setup",
9
+ ]
@@ -0,0 +1,11 @@
1
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
2
+ from datetime import datetime, timezone
3
+
4
+ class Peer:
5
+ shared_key: bytes
6
+ timestamp: datetime
7
+ latest_block: bytes
8
+
9
+ def __init__(self, my_sec_key: X25519PrivateKey, peer_pub_key: X25519PublicKey):
10
+ self.shared_key = my_sec_key.exchange(peer_pub_key)
11
+ self.timestamp = datetime.now(timezone.utc)
@@ -0,0 +1,25 @@
1
+ from typing import Dict, List
2
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
3
+
4
+ class Route:
5
+ def __init__(self, relay_public_key: X25519PublicKey, bucket_size: int = 16):
6
+ self.relay_public_key_bytes = relay_public_key.public_bytes(encoding=Encoding.Raw, format=PublicFormat.Raw)
7
+ self.bucket_size = bucket_size
8
+ self.buckets: Dict[int, List[X25519PublicKey]] = {
9
+ i: [] for i in range(len(self.relay_public_key_bytes) * 8)
10
+ }
11
+ self.peers = {}
12
+
13
+ @staticmethod
14
+ def _matching_leading_bits(a: bytes, b: bytes) -> int:
15
+ for byte_index, (ba, bb) in enumerate(zip(a, b)):
16
+ diff = ba ^ bb
17
+ if diff:
18
+ return byte_index * 8 + (8 - diff.bit_length())
19
+ return len(a) * 8
20
+
21
+ def add_peer(self, peer_public_key: X25519PublicKey):
22
+ peer_public_key_bytes = peer_public_key.public_bytes(encoding=Encoding.Raw, format=PublicFormat.Raw)
23
+ bucket_idx = self._matching_leading_bits(self.relay_public_key_bytes, peer_public_key_bytes)
24
+ if len(self.buckets[bucket_idx]) < self.bucket_size:
25
+ self.buckets[bucket_idx].append(peer_public_key)
@@ -0,0 +1,113 @@
1
+ import socket, threading
2
+ from queue import Queue
3
+ from typing import Tuple, Optional
4
+ from cryptography.hazmat.primitives.asymmetric import ed25519
5
+ from cryptography.hazmat.primitives import serialization
6
+ from cryptography.hazmat.primitives.asymmetric.x25519 import (
7
+ X25519PrivateKey,
8
+ X25519PublicKey,
9
+ )
10
+
11
+ from typing import TYPE_CHECKING
12
+ if TYPE_CHECKING:
13
+ from .. import Node
14
+
15
+ from .import Route
16
+
17
+ def load_x25519(hex_key: Optional[str]) -> X25519PrivateKey:
18
+ """DH key for relaying (always X25519)."""
19
+ return
20
+
21
+ def load_ed25519(hex_key: Optional[str]) -> Optional[ed25519.Ed25519PrivateKey]:
22
+ """Signing key for validation (Ed25519), or None if absent."""
23
+ return ed25519.Ed25519PrivateKey.from_private_bytes(bytes.fromhex(hex_key)) \
24
+ if hex_key else None
25
+
26
+ def make_routes(
27
+ relay_pk: X25519PublicKey,
28
+ val_sk: Optional[ed25519.Ed25519PrivateKey]
29
+ ) -> Tuple[Route, Optional[Route]]:
30
+ """Peer route (DH pubkey) + optional validation route (ed pubkey)."""
31
+ peer_rt = Route(relay_pk)
32
+ val_rt = Route(val_sk.public_key()) if val_sk else None
33
+ return peer_rt, val_rt
34
+
35
+ def setup_udp(
36
+ bind_port: int,
37
+ use_ipv6: bool
38
+ ) -> Tuple[socket.socket, int, Queue, threading.Thread, threading.Thread]:
39
+ fam = socket.AF_INET6 if use_ipv6 else socket.AF_INET
40
+ sock = socket.socket(fam, socket.SOCK_DGRAM)
41
+ if use_ipv6:
42
+ sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
43
+ sock.bind(("::" if use_ipv6 else "0.0.0.0", bind_port or 0))
44
+ port = sock.getsockname()[1]
45
+
46
+ q = Queue()
47
+ pop = threading.Thread(target=lambda: None, daemon=True)
48
+ proc = threading.Thread(target=lambda: None, daemon=True)
49
+ pop.start(); proc.start()
50
+ return sock, port, q, pop, proc
51
+
52
+ def setup_outgoing(
53
+ use_ipv6: bool
54
+ ) -> Tuple[socket.socket, Queue, threading.Thread]:
55
+ fam = socket.AF_INET6 if use_ipv6 else socket.AF_INET
56
+ sock = socket.socket(fam, socket.SOCK_DGRAM)
57
+ q = Queue()
58
+ thr = threading.Thread(target=lambda: None, daemon=True)
59
+ thr.start()
60
+ return sock, q, thr
61
+
62
+ def make_maps():
63
+ """Empty lookup maps: peers and addresses."""
64
+ return
65
+
66
+ def communication_setup(node: "Node", config: dict):
67
+ node.use_ipv6 = config.get('use_ipv6', False)
68
+
69
+ # key loading
70
+ node.relay_secret_key = load_x25519(config.get('relay_secret_key'))
71
+ node.validation_secret_key = load_ed25519(config.get('validation_secret_key'))
72
+
73
+ # derive pubs + routes
74
+ node.relay_public_key = node.relay_secret_key.public_key()
75
+ node.validation_public_key = (
76
+ node.validation_secret_key.public_key().public_bytes(
77
+ encoding=serialization.Encoding.Raw,
78
+ format=serialization.PublicFormat.Raw,
79
+ )
80
+ if node.validation_secret_key
81
+ else None
82
+ )
83
+ node.peer_route, node.validation_route = make_routes(
84
+ node.relay_public_key,
85
+ node.validation_secret_key
86
+ )
87
+
88
+ # sockets + queues + threads
89
+ (node.incoming_socket,
90
+ node.incoming_port,
91
+ node.incoming_queue,
92
+ node.incoming_populate_thread,
93
+ node.incoming_process_thread
94
+ ) = setup_udp(config.get('incoming_port', 7373), node.use_ipv6)
95
+
96
+ (node.outgoing_socket,
97
+ node.outgoing_queue,
98
+ node.outgoing_thread
99
+ ) = setup_outgoing(node.use_ipv6)
100
+
101
+ # other workers & maps
102
+ node.object_request_queue = Queue()
103
+ node.peer_manager_thread = threading.Thread(
104
+ target=node._relay_peer_manager,
105
+ daemon=True
106
+ )
107
+ node.peer_manager_thread.start()
108
+
109
+ node.peers, node.addresses = {}, {} # peers: Dict[X25519PublicKey,Peer], addresses: Dict[(str,int),X25519PublicKey]
110
+
111
+ # bootstrap pings
112
+ for addr in config.get('bootstrap', []):
113
+ node._send_ping(addr)
@@ -2,7 +2,7 @@ from .expression import Expr
2
2
  from .environment import Env
3
3
  from .low_evaluation import low_eval
4
4
  from .meter import Meter
5
- from .parser import parse
5
+ from .parser import parse, ParseError
6
6
  from .tokenizer import tokenize
7
7
 
8
8
  __all__ = [
@@ -11,6 +11,6 @@ __all__ = [
11
11
  "low_eval",
12
12
  "Meter",
13
13
  "parse",
14
- "tokenize"
14
+ "tokenize",
15
+ "ParseError",
15
16
  ]
16
-
@@ -1,10 +1,13 @@
1
1
  from ast import Expr
2
2
  from typing import Dict, Optional
3
+ import uuid
3
4
 
4
5
 
5
6
  class Env:
6
7
  def __init__(
7
8
  self,
8
- data: Optional[Dict[str, Expr]] = None
9
+ data: Optional[Dict[str, Expr]] = None,
10
+ parent_id: Optional[uuid.UUID] = None,
9
11
  ):
10
- self.data: Dict[bytes, Expr] = {} if data is None else data
12
+ self.data: Dict[bytes, Expr] = {} if data is None else data
13
+ self.parent_id = parent_id
@@ -10,21 +10,21 @@ class Expr:
10
10
  if not self.elements:
11
11
  return "()"
12
12
  inner = " ".join(str(e) for e in self.elements)
13
- return f"({inner})"
13
+ return f"({inner} list)"
14
14
 
15
15
  class Symbol:
16
16
  def __init__(self, value: str):
17
17
  self.value = value
18
18
 
19
19
  def __repr__(self):
20
- return self.value
20
+ return f"({self.value} symbol)"
21
21
 
22
- class Byte:
23
- def __init__(self, value: int):
22
+ class Bytes:
23
+ def __init__(self, value: bytes):
24
24
  self.value = value
25
25
 
26
26
  def __repr__(self):
27
- return self.value
27
+ return f"({self.value} bytes)"
28
28
 
29
29
  class Error:
30
30
  def __init__(self, topic: str, origin: Optional['Expr'] = None):
@@ -33,5 +33,5 @@ class Expr:
33
33
 
34
34
  def __repr__(self):
35
35
  if self.origin is None:
36
- return f'({self.topic} err)'
37
- return f'({self.origin} {self.topic} err)'
36
+ return f'({self.topic} error)'
37
+ return f'({self.origin} {self.topic} error)'
@@ -1,7 +1,9 @@
1
- from typing import List, Union
2
- import uuid
3
-
4
- from src.astreum._lispeum import Env, Expr, Meter
1
+ from typing import List, Union
2
+ import uuid
3
+
4
+ from .environment import Env
5
+ from .expression import Expr
6
+ from .meter import Meter
5
7
 
6
8
 
7
9
  def high_eval(self, env_id: uuid.UUID, expr: Expr, meter = None) -> Expr:
@@ -125,9 +127,7 @@ def high_eval(self, env_id: uuid.UUID, expr: Expr, meter = None) -> Expr:
125
127
 
126
128
  # Execute low-level code built from sk-body using the caller's meter
127
129
  res = self.low_eval(code, meter=meter)
128
- if isinstance(res, Expr.Error):
129
- return res
130
- return Expr.ListExpr([Expr.Byte(b) for b in res])
130
+ return res
131
131
 
132
132
  # ---------- (... (body params fn)) HIGH-LEVEL CALL ----------
133
133
  if isinstance(tail, Expr.ListExpr):
@@ -174,4 +174,4 @@ def high_eval(self, env_id: uuid.UUID, expr: Expr, meter = None) -> Expr:
174
174
 
175
175
  # ---------- default: resolve each element and return list ----------
176
176
  resolved: List[Expr] = [self.high_eval(env_id, e, meter=meter) for e in expr.elements]
177
- return Expr.ListExpr(resolved)
177
+ return Expr.ListExpr(resolved)
@@ -1,5 +1,6 @@
1
- from typing import Dict, List, Union
2
- from src.astreum._lispeum import Expr, Meter
1
+ from typing import Dict, List, Union
2
+ from .expression import Expr
3
+ from .meter import Meter
3
4
 
4
5
  def tc_to_int(b: bytes) -> int:
5
6
  """bytes -> int using two's complement (width = len(b)*8)."""
@@ -34,18 +35,19 @@ def nand_bytes(a: bytes, b: bytes) -> bytes:
34
35
  resu = (~(au & bu)) & mask
35
36
  return resu.to_bytes(w, "big", signed=False)
36
37
 
37
- def low_eval(self, code: List[bytes], meter: Meter) -> Union[bytes, Expr.Error]:
38
+ def low_eval(self, code: List[bytes], meter: Meter) -> Expr:
38
39
 
39
40
  heap: Dict[bytes, bytes] = {}
40
41
 
41
42
  stack: List[bytes] = []
42
43
  pc = 0
43
44
 
44
- while True:
45
- if pc >= len(code):
46
- if len(stack) != 1:
47
- return Expr.Error("bad stack")
48
- return stack.pop()
45
+ while True:
46
+ if pc >= len(code):
47
+ if len(stack) != 1:
48
+ return Expr.Error("bad stack")
49
+ # wrap successful result as an Expr.Bytes
50
+ return Expr.Bytes(stack.pop())
49
51
 
50
52
  tok = code[pc]
51
53
  pc += 1
@@ -1,5 +1,5 @@
1
- from typing import List, Tuple
2
- from src.astreum._lispeum import Expr
1
+ from typing import List, Tuple
2
+ from src.astreum._lispeum import Expr
3
3
 
4
4
  class ParseError(Exception):
5
5
  pass
@@ -27,14 +27,30 @@ def _parse_one(tokens: List[str], pos: int = 0) -> Tuple[Expr, int]:
27
27
  if tok == ')':
28
28
  raise ParseError("unexpected ')'")
29
29
 
30
- # try integer → Byte
31
- try:
32
- n = int(tok)
33
- return Expr.Byte(n), pos + 1
34
- except ValueError:
35
- return Expr.Symbol(tok), pos + 1
30
+ # try integer → Bytes (variable-length two's complement)
31
+ try:
32
+ n = int(tok)
33
+ # encode as minimal-width signed two's complement, big-endian
34
+ def int_to_min_tc(v: int) -> bytes:
35
+ """Return the minimal-width signed two's complement big-endian
36
+ byte encoding of integer v. Width expands just enough so that
37
+ decoding with signed=True yields the same value and sign.
38
+ Example: 0 -> b"\x00", 127 -> b"\x7f", 128 -> b"\x00\x80".
39
+ """
40
+ if v == 0:
41
+ return b"\x00"
42
+ w = 1
43
+ while True:
44
+ try:
45
+ return v.to_bytes(w, "big", signed=True)
46
+ except OverflowError:
47
+ w += 1
48
+
49
+ return Expr.Bytes(int_to_min_tc(n)), pos + 1
50
+ except ValueError:
51
+ return Expr.Symbol(tok), pos + 1
36
52
 
37
53
  def parse(tokens: List[str]) -> Tuple[Expr, List[str]]:
38
54
  """Parse tokens into an Expr and return (expr, remaining_tokens)."""
39
55
  expr, next_pos = _parse_one(tokens, 0)
40
- return expr, tokens[next_pos:]
56
+ return expr, tokens[next_pos:]
astreum/_node.py CHANGED
@@ -1,126 +1,35 @@
1
1
  from __future__ import annotations
2
- from typing import Dict, List, Optional, Tuple, Union
2
+ from typing import Dict, Optional
3
3
  import uuid
4
4
  import threading
5
5
 
6
- from src.astreum._lispeum import Env, Expr, Meter, low_eval
6
+ from src.astreum._storage.atom import Atom
7
+ from src.astreum._lispeum import Env, Expr, low_eval, parse, tokenize, ParseError
7
8
 
8
9
  def bytes_touched(*vals: bytes) -> int:
9
10
  """For metering: how many bytes were manipulated (max of operands)."""
10
11
  return max((len(v) for v in vals), default=1)
11
12
 
12
- from blake3 import blake3
13
-
14
- ZERO32 = b"\x00"*32
15
-
16
- def u64_le(n: int) -> bytes:
17
- return int(n).to_bytes(8, "little", signed=False)
18
-
19
- def hash_bytes(b: bytes) -> bytes:
20
- return blake3(b).digest()
21
-
22
- class Atom:
23
- data: bytes
24
- next: bytes
25
- size: int
26
-
27
- def __init__(self, data: bytes, next: bytes = ZERO32, size: Optional[int] = None):
28
- self.data = data
29
- self.next = next
30
- self.size = len(data) if size is None else size
31
-
32
- @staticmethod
33
- def from_data(data: bytes, next_hash: bytes = ZERO32) -> "Atom":
34
- return Atom(data=data, next=next_hash, size=len(data))
35
-
36
- @staticmethod
37
- def object_id_from_parts(data_hash: bytes, next_hash: bytes, size: int) -> bytes:
38
- return blake3(data_hash + next_hash + u64_le(size)).digest()
39
-
40
- def data_hash(self) -> bytes:
41
- return hash_bytes(self.data)
42
-
43
- def object_id(self) -> bytes:
44
- return self.object_id_from_parts(self.data_hash(), self.next, self.size)
45
-
46
- @staticmethod
47
- def verify_metadata(object_id: bytes, size: int, next_hash: bytes, data_hash: bytes) -> bool:
48
- return object_id == blake3(data_hash + next_hash + u64_le(size)).digest()
49
-
50
- def to_bytes(self) -> bytes:
51
- if len(self.next) != len(ZERO32):
52
- raise ValueError("next must be 32 bytes")
53
- return self.next + self.data
54
-
55
- @staticmethod
56
- def from_bytes(buf: bytes) -> "Atom":
57
- if len(buf) < len(ZERO32):
58
- raise ValueError("buffer too short for Atom header")
59
- next_hash = buf[:len(ZERO32)]
60
- data = buf[len(ZERO32):]
61
- return Atom(data=data, next=next_hash, size=len(data))
62
-
63
- def u32_le(n: int) -> bytes:
64
- return int(n).to_bytes(4, "little", signed=False)
65
-
66
- def expr_to_atoms(e: Expr) -> Tuple[bytes, List[Atom]]:
67
- def sym(v: str) -> Tuple[bytes, List[Atom]]:
68
- val = v.encode("utf-8")
69
- val_atom = Atom.from_data(u32_le(len(val)) + val)
70
- typ_atom = Atom.from_data(b"symbol", val_atom.object_id())
71
- return typ_atom.object_id(), [val_atom, typ_atom]
72
-
73
- def byt(v: int) -> Tuple[bytes, List[Atom]]:
74
- val_atom = Atom.from_data(bytes([v & 0xFF]))
75
- typ_atom = Atom.from_data(b"byte", val_atom.object_id())
76
- return typ_atom.object_id(), [val_atom, typ_atom]
77
-
78
- def err(topic: str, origin: Optional[Expr]) -> Tuple[bytes, List[Atom]]:
79
- t = topic.encode("utf-8")
80
- origin_hash, acc = (ZERO32, [])
81
- if origin is not None:
82
- origin_hash, acc = expr_to_atoms(origin)
83
- val_atom = Atom.from_data(u32_le(len(t)) + t + origin_hash)
84
- typ_atom = Atom.from_data(b"error", val_atom.object_id())
85
- return typ_atom.object_id(), acc + [val_atom, typ_atom]
86
-
87
- def lst(items: List[Expr]) -> Tuple[bytes, List[Atom]]:
88
- acc: List[Atom] = []
89
- child_hashes: List[bytes] = []
90
- for it in items:
91
- h, atoms = expr_to_atoms(it)
92
- acc.extend(atoms)
93
- child_hashes.append(h)
94
- next_hash = ZERO32
95
- elem_atoms: List[Atom] = []
96
- for h in reversed(child_hashes):
97
- a = Atom.from_data(h, next_hash)
98
- next_hash = a.object_id()
99
- elem_atoms.append(a)
100
- elem_atoms.reverse()
101
- head = next_hash
102
- val_atom = Atom.from_data(u64_le(len(items)), head)
103
- typ_atom = Atom.from_data(b"list", val_atom.object_id())
104
- return typ_atom.object_id(), acc + elem_atoms + [val_atom, typ_atom]
105
-
106
- if isinstance(e, Expr.Symbol):
107
- return sym(e.value)
108
- if isinstance(e, Expr.Byte):
109
- return byt(e.value)
110
- if isinstance(e, Expr.Error):
111
- return err(e.topic, e.origin)
112
- if isinstance(e, Expr.ListExpr):
113
- return lst(e.elements)
114
- raise TypeError("unknown Expr variant")
115
-
116
13
  class Node:
117
- def __init__(self):
14
+ def __init__(self, config: dict):
118
15
  # Storage Setup
119
- self.in_memory_storage: Dict[bytes, bytes] = {}
16
+ self.in_memory_storage: Dict[bytes, Atom] = {}
17
+ self.in_memory_storage_lock = threading.RLock()
120
18
  # Lispeum Setup
121
19
  self.environments: Dict[uuid.UUID, Env] = {}
122
20
  self.machine_environments_lock = threading.RLock()
123
21
  self.low_eval = low_eval
22
+ # Communication and Validation Setup (import lazily to avoid heavy deps during parsing tests)
23
+ try:
24
+ from astreum._communication import communication_setup # type: ignore
25
+ communication_setup(node=self, config=config)
26
+ except Exception:
27
+ pass
28
+ try:
29
+ from astreum._validation import validation_setup # type: ignore
30
+ validation_setup(node=self)
31
+ except Exception:
32
+ pass
124
33
 
125
34
  # ---- Env helpers ----
126
35
  def env_get(self, env_id: uuid.UUID, key: bytes) -> Optional[Expr]:
@@ -139,9 +48,11 @@ class Node:
139
48
  env.data[key] = value
140
49
  return True
141
50
 
142
- # ---- Storage (persistent) ----
143
- def _local_get(self, key: bytes) -> Optional[bytes]:
144
- return self.in_memory_storage.get(key)
51
+ # Storage
52
+ def _local_get(self, key: bytes) -> Optional[Atom]:
53
+ with self.in_memory_storage_lock:
54
+ return self.in_memory_storage.get(key)
145
55
 
146
- def _local_set(self, key: bytes, value: bytes) -> None:
147
- self.in_memory_storage[key] = value
56
+ def _local_set(self, key: bytes, value: Atom) -> None:
57
+ with self.in_memory_storage_lock:
58
+ self.in_memory_storage[key] = value
@@ -0,0 +1,5 @@
1
+ from .atom import Atom
2
+
3
+ __all__ = [
4
+ "Atom",
5
+ ]
@@ -0,0 +1,100 @@
1
+
2
+
3
+ from typing import List, Optional, Tuple
4
+
5
+ from .._lispeum.expression import Expr
6
+ from blake3 import blake3
7
+
8
+ ZERO32 = b"\x00"*32
9
+
10
+ def u64_le(n: int) -> bytes:
11
+ return int(n).to_bytes(8, "little", signed=False)
12
+
13
+ def hash_bytes(b: bytes) -> bytes:
14
+ return blake3(b).digest()
15
+
16
+ class Atom:
17
+ data: bytes
18
+ next: bytes
19
+ size: int
20
+
21
+ def __init__(self, data: bytes, next: bytes = ZERO32, size: Optional[int] = None):
22
+ self.data = data
23
+ self.next = next
24
+ self.size = len(data) if size is None else size
25
+
26
+ @staticmethod
27
+ def from_data(data: bytes, next_hash: bytes = ZERO32) -> "Atom":
28
+ return Atom(data=data, next=next_hash, size=len(data))
29
+
30
+ @staticmethod
31
+ def object_id_from_parts(data_hash: bytes, next_hash: bytes, size: int) -> bytes:
32
+ return blake3(data_hash + next_hash + u64_le(size)).digest()
33
+
34
+ def data_hash(self) -> bytes:
35
+ return hash_bytes(self.data)
36
+
37
+ def object_id(self) -> bytes:
38
+ return self.object_id_from_parts(self.data_hash(), self.next, self.size)
39
+
40
+ @staticmethod
41
+ def verify_metadata(object_id: bytes, size: int, next_hash: bytes, data_hash: bytes) -> bool:
42
+ return object_id == blake3(data_hash + next_hash + u64_le(size)).digest()
43
+
44
+ def to_bytes(self) -> bytes:
45
+ return self.next + self.data
46
+
47
+ @staticmethod
48
+ def from_bytes(buf: bytes) -> "Atom":
49
+ if len(buf) < len(ZERO32):
50
+ raise ValueError("buffer too short for Atom header")
51
+ next_hash = buf[:len(ZERO32)]
52
+ data = buf[len(ZERO32):]
53
+ return Atom(data=data, next=next_hash, size=len(data))
54
+
55
+ def expr_to_atoms(e: Expr) -> Tuple[bytes, List[Atom]]:
56
+ def symbol(value: str) -> Tuple[bytes, List[Atom]]:
57
+ val = value.encode("utf-8")
58
+ val_atom = Atom.from_data(data=val)
59
+ typ_atom = Atom.from_data(b"symbol", val_atom.object_id())
60
+ return typ_atom.object_id(), [val_atom, typ_atom]
61
+
62
+ def bytes(data: bytes) -> Tuple[bytes, List[Atom]]:
63
+ val_atom = Atom.from_data(data=data)
64
+ typ_atom = Atom.from_data(b"byte", val_atom.object_id())
65
+ return typ_atom.object_id(), [val_atom, typ_atom]
66
+
67
+ def err(topic: str, origin: Optional[Expr]) -> Tuple[bytes, List[Atom]]:
68
+ topic_bytes = topic.encode("utf-8")
69
+ topic_atom = Atom.from_data(data=topic_bytes)
70
+ typ_atom = Atom.from_data(data=b"error", next_hash=topic_atom.object_id())
71
+ return typ_atom.object_id(), [topic_atom, typ_atom]
72
+
73
+ def lst(items: List[Expr]) -> Tuple[bytes, List[Atom]]:
74
+ acc: List[Atom] = []
75
+ child_hashes: List[bytes] = []
76
+ for it in items:
77
+ h, atoms = expr_to_atoms(it)
78
+ acc.extend(atoms)
79
+ child_hashes.append(h)
80
+ next_hash = ZERO32
81
+ elem_atoms: List[Atom] = []
82
+ for h in reversed(child_hashes):
83
+ a = Atom.from_data(h, next_hash)
84
+ next_hash = a.object_id()
85
+ elem_atoms.append(a)
86
+ elem_atoms.reverse()
87
+ head = next_hash
88
+ val_atom = Atom.from_data(data=u64_le(len(items)), next_hash=head)
89
+ typ_atom = Atom.from_data(data=b"list", next_hash=val_atom.object_id())
90
+ return typ_atom.object_id(), acc + elem_atoms + [val_atom, typ_atom]
91
+
92
+ if isinstance(e, Expr.Symbol):
93
+ return symbol(e.value)
94
+ if isinstance(e, Expr.Bytes):
95
+ return bytes(e.value)
96
+ if isinstance(e, Expr.Error):
97
+ return err(e.topic, e.origin)
98
+ if isinstance(e, Expr.ListExpr):
99
+ return lst(e.elements)
100
+ raise TypeError("unknown Expr variant")
@@ -0,0 +1,12 @@
1
+ from .block import Block
2
+ from .chain import Chain
3
+ from .fork import Fork
4
+ from .setup import validation_setup
5
+
6
+
7
+ __all__ = [
8
+ "Block",
9
+ "Chain",
10
+ "Fork",
11
+ "validation_setup",
12
+ ]