astreum 0.2.41__py3-none-any.whl → 0.3.1__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.
- astreum/__init__.py +16 -7
- astreum/{_communication → communication}/__init__.py +3 -3
- astreum/communication/handlers/handshake.py +83 -0
- astreum/communication/handlers/ping.py +48 -0
- astreum/communication/handlers/storage_request.py +81 -0
- astreum/communication/models/__init__.py +0 -0
- astreum/{_communication → communication/models}/message.py +1 -0
- astreum/communication/models/peer.py +23 -0
- astreum/{_communication → communication/models}/route.py +45 -8
- astreum/{_communication → communication}/setup.py +46 -95
- astreum/communication/start.py +38 -0
- astreum/consensus/__init__.py +20 -0
- astreum/consensus/genesis.py +66 -0
- astreum/consensus/models/__init__.py +0 -0
- astreum/consensus/models/account.py +84 -0
- astreum/consensus/models/accounts.py +72 -0
- astreum/consensus/models/block.py +364 -0
- astreum/{_consensus → consensus/models}/chain.py +7 -7
- astreum/{_consensus → consensus/models}/fork.py +8 -8
- astreum/consensus/models/receipt.py +98 -0
- astreum/consensus/models/transaction.py +213 -0
- astreum/{_consensus → consensus}/setup.py +26 -11
- astreum/consensus/start.py +68 -0
- astreum/consensus/validator.py +95 -0
- astreum/{_consensus → consensus}/workers/discovery.py +20 -1
- astreum/consensus/workers/validation.py +291 -0
- astreum/{_consensus → consensus}/workers/verify.py +32 -3
- astreum/machine/__init__.py +20 -0
- astreum/machine/evaluations/__init__.py +0 -0
- astreum/machine/evaluations/high_evaluation.py +237 -0
- astreum/machine/evaluations/low_evaluation.py +281 -0
- astreum/machine/evaluations/script_evaluation.py +27 -0
- astreum/machine/models/__init__.py +0 -0
- astreum/machine/models/environment.py +31 -0
- astreum/machine/models/expression.py +218 -0
- astreum/{_lispeum → machine}/parser.py +26 -31
- astreum/machine/tokenizer.py +90 -0
- astreum/node.py +73 -781
- astreum/storage/__init__.py +7 -0
- astreum/storage/actions/get.py +69 -0
- astreum/storage/actions/set.py +132 -0
- astreum/storage/models/atom.py +107 -0
- astreum/{_storage/patricia.py → storage/models/trie.py} +236 -177
- astreum/storage/setup.py +44 -15
- astreum/utils/bytes.py +24 -0
- astreum/utils/integer.py +25 -0
- astreum/utils/logging.py +219 -0
- astreum-0.3.1.dist-info/METADATA +160 -0
- astreum-0.3.1.dist-info/RECORD +62 -0
- astreum/_communication/peer.py +0 -11
- astreum/_consensus/__init__.py +0 -20
- astreum/_consensus/account.py +0 -170
- astreum/_consensus/accounts.py +0 -67
- astreum/_consensus/block.py +0 -328
- astreum/_consensus/genesis.py +0 -141
- astreum/_consensus/receipt.py +0 -177
- astreum/_consensus/transaction.py +0 -192
- astreum/_consensus/workers/validation.py +0 -122
- astreum/_lispeum/__init__.py +0 -16
- astreum/_lispeum/environment.py +0 -13
- astreum/_lispeum/expression.py +0 -37
- astreum/_lispeum/high_evaluation.py +0 -177
- astreum/_lispeum/low_evaluation.py +0 -123
- astreum/_lispeum/tokenizer.py +0 -22
- astreum/_node.py +0 -58
- astreum/_storage/__init__.py +0 -5
- astreum/_storage/atom.py +0 -117
- astreum/format.py +0 -75
- astreum/models/block.py +0 -441
- astreum/models/merkle.py +0 -205
- astreum/models/patricia.py +0 -393
- astreum/storage/object.py +0 -68
- astreum-0.2.41.dist-info/METADATA +0 -146
- astreum-0.2.41.dist-info/RECORD +0 -53
- /astreum/{models → communication/handlers}/__init__.py +0 -0
- /astreum/{_communication → communication/models}/ping.py +0 -0
- /astreum/{_communication → communication}/util.py +0 -0
- /astreum/{_consensus → consensus}/workers/__init__.py +0 -0
- /astreum/{_lispeum → machine/models}/meter.py +0 -0
- {astreum-0.2.41.dist-info → astreum-0.3.1.dist-info}/WHEEL +0 -0
- {astreum-0.2.41.dist-info → astreum-0.3.1.dist-info}/licenses/LICENSE +0 -0
- {astreum-0.2.41.dist-info → astreum-0.3.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, List, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
from ...storage.models.atom import Atom, AtomKind, ZERO32
|
|
6
|
+
|
|
7
|
+
STATUS_SUCCESS = 0
|
|
8
|
+
STATUS_FAILED = 1
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _int_to_be_bytes(value: Optional[int]) -> bytes:
|
|
12
|
+
if value is None:
|
|
13
|
+
return b""
|
|
14
|
+
value = int(value)
|
|
15
|
+
if value == 0:
|
|
16
|
+
return b"\x00"
|
|
17
|
+
size = (value.bit_length() + 7) // 8
|
|
18
|
+
return value.to_bytes(size, "big")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _be_bytes_to_int(data: Optional[bytes]) -> int:
|
|
22
|
+
if not data:
|
|
23
|
+
return 0
|
|
24
|
+
return int.from_bytes(data, "big")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Receipt:
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
transaction_hash: bytes,
|
|
31
|
+
cost: int,
|
|
32
|
+
status: int,
|
|
33
|
+
logs_hash: bytes = ZERO32,
|
|
34
|
+
) -> None:
|
|
35
|
+
self.transaction_hash = bytes(transaction_hash)
|
|
36
|
+
self.cost = int(cost)
|
|
37
|
+
self.logs_hash = bytes(logs_hash)
|
|
38
|
+
self.status = int(status)
|
|
39
|
+
self.atom_hash = ZERO32
|
|
40
|
+
self.atoms: List[Atom] = []
|
|
41
|
+
|
|
42
|
+
def to_atom(self) -> Tuple[bytes, List[Atom]]:
|
|
43
|
+
if self.status not in (STATUS_SUCCESS, STATUS_FAILED):
|
|
44
|
+
raise ValueError("unsupported receipt status")
|
|
45
|
+
|
|
46
|
+
detail_specs = [
|
|
47
|
+
(bytes(self.transaction_hash), AtomKind.LIST),
|
|
48
|
+
(_int_to_be_bytes(self.status), AtomKind.BYTES),
|
|
49
|
+
(_int_to_be_bytes(self.cost), AtomKind.BYTES),
|
|
50
|
+
(bytes(self.logs_hash), AtomKind.LIST),
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
detail_atoms: List[Atom] = []
|
|
54
|
+
next_hash = ZERO32
|
|
55
|
+
for payload, kind in reversed(detail_specs):
|
|
56
|
+
atom = Atom(data=payload, next_id=next_hash, kind=kind)
|
|
57
|
+
detail_atoms.append(atom)
|
|
58
|
+
next_hash = atom.object_id()
|
|
59
|
+
detail_atoms.reverse()
|
|
60
|
+
|
|
61
|
+
type_atom = Atom(data=b"receipt", next_id=next_hash, kind=AtomKind.SYMBOL)
|
|
62
|
+
|
|
63
|
+
atoms = detail_atoms + [type_atom]
|
|
64
|
+
receipt_id = type_atom.object_id()
|
|
65
|
+
return receipt_id, atoms
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_atom(cls, node: Any, receipt_id: bytes) -> Receipt:
|
|
69
|
+
atom_chain = node.get_atom_list_from_storage(receipt_id)
|
|
70
|
+
if atom_chain is None or len(atom_chain) != 5:
|
|
71
|
+
raise ValueError("malformed receipt atom chain")
|
|
72
|
+
|
|
73
|
+
type_atom, tx_atom, status_atom, cost_atom, logs_atom = atom_chain
|
|
74
|
+
if type_atom.kind is not AtomKind.SYMBOL or type_atom.data != b"receipt":
|
|
75
|
+
raise ValueError("not a receipt (type atom)")
|
|
76
|
+
if tx_atom.kind is not AtomKind.LIST:
|
|
77
|
+
raise ValueError("receipt transaction hash must be list-kind")
|
|
78
|
+
if status_atom.kind is not AtomKind.BYTES or cost_atom.kind is not AtomKind.BYTES or logs_atom.kind is not AtomKind.LIST:
|
|
79
|
+
raise ValueError("receipt detail atoms must be bytes-kind")
|
|
80
|
+
|
|
81
|
+
transaction_hash_bytes = tx_atom.data
|
|
82
|
+
status_bytes = status_atom.data
|
|
83
|
+
cost_bytes = cost_atom.data
|
|
84
|
+
logs_bytes = logs_atom.data
|
|
85
|
+
|
|
86
|
+
status_value = _be_bytes_to_int(status_bytes)
|
|
87
|
+
if status_value not in (STATUS_SUCCESS, STATUS_FAILED):
|
|
88
|
+
raise ValueError("unsupported receipt status")
|
|
89
|
+
|
|
90
|
+
receipt = cls(
|
|
91
|
+
transaction_hash=transaction_hash_bytes,
|
|
92
|
+
cost=_be_bytes_to_int(cost_bytes),
|
|
93
|
+
logs_hash=logs_bytes,
|
|
94
|
+
status=status_value,
|
|
95
|
+
)
|
|
96
|
+
receipt.atom_hash = bytes(receipt_id)
|
|
97
|
+
receipt.atoms = atom_chain
|
|
98
|
+
return receipt
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, List, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
from ...storage.models.atom import Atom, AtomKind, ZERO32
|
|
7
|
+
from ...utils.integer import bytes_to_int, int_to_bytes
|
|
8
|
+
from .account import Account
|
|
9
|
+
from ..genesis import TREASURY_ADDRESS
|
|
10
|
+
from .receipt import STATUS_FAILED, Receipt, STATUS_SUCCESS
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Transaction:
|
|
14
|
+
chain_id: int
|
|
15
|
+
amount: int
|
|
16
|
+
counter: int
|
|
17
|
+
data: bytes = b""
|
|
18
|
+
recipient: bytes = b""
|
|
19
|
+
sender: bytes = b""
|
|
20
|
+
signature: bytes = b""
|
|
21
|
+
hash: bytes = ZERO32
|
|
22
|
+
|
|
23
|
+
def to_atom(self) -> Tuple[bytes, List[Atom]]:
|
|
24
|
+
"""Serialise the transaction, returning (object_id, atoms)."""
|
|
25
|
+
detail_payloads: List[bytes] = []
|
|
26
|
+
acc: List[Atom] = []
|
|
27
|
+
|
|
28
|
+
def emit(payload: bytes) -> None:
|
|
29
|
+
detail_payloads.append(payload)
|
|
30
|
+
|
|
31
|
+
emit(int_to_bytes(self.chain_id))
|
|
32
|
+
emit(int_to_bytes(self.amount))
|
|
33
|
+
emit(int_to_bytes(self.counter))
|
|
34
|
+
emit(bytes(self.data))
|
|
35
|
+
emit(bytes(self.recipient))
|
|
36
|
+
emit(bytes(self.sender))
|
|
37
|
+
|
|
38
|
+
body_head = ZERO32
|
|
39
|
+
detail_atoms: List[Atom] = []
|
|
40
|
+
for payload in reversed(detail_payloads):
|
|
41
|
+
atom = Atom(data=payload, next_id=body_head, kind=AtomKind.BYTES)
|
|
42
|
+
detail_atoms.append(atom)
|
|
43
|
+
body_head = atom.object_id()
|
|
44
|
+
detail_atoms.reverse()
|
|
45
|
+
acc.extend(detail_atoms)
|
|
46
|
+
|
|
47
|
+
body_list_atom = Atom(data=body_head, kind=AtomKind.LIST)
|
|
48
|
+
acc.append(body_list_atom)
|
|
49
|
+
body_list_id = body_list_atom.object_id()
|
|
50
|
+
|
|
51
|
+
signature_atom = Atom(
|
|
52
|
+
data=bytes(self.signature),
|
|
53
|
+
next_id=body_list_id,
|
|
54
|
+
kind=AtomKind.BYTES,
|
|
55
|
+
)
|
|
56
|
+
type_atom = Atom(
|
|
57
|
+
data=b"transaction",
|
|
58
|
+
next_id=signature_atom.object_id(),
|
|
59
|
+
kind=AtomKind.SYMBOL,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
acc.append(signature_atom)
|
|
63
|
+
acc.append(type_atom)
|
|
64
|
+
|
|
65
|
+
self.hash = type_atom.object_id()
|
|
66
|
+
return self.hash, acc
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_atom(
|
|
70
|
+
cls,
|
|
71
|
+
node: Any,
|
|
72
|
+
transaction_id: bytes,
|
|
73
|
+
) -> Transaction:
|
|
74
|
+
storage_get = getattr(node, "storage_get", None)
|
|
75
|
+
if not callable(storage_get):
|
|
76
|
+
raise NotImplementedError("node does not expose a storage getter")
|
|
77
|
+
|
|
78
|
+
def _atom_kind(atom: Optional[Atom]) -> Optional[AtomKind]:
|
|
79
|
+
kind_value = getattr(atom, "kind", None)
|
|
80
|
+
if isinstance(kind_value, AtomKind):
|
|
81
|
+
return kind_value
|
|
82
|
+
if isinstance(kind_value, int):
|
|
83
|
+
try:
|
|
84
|
+
return AtomKind(kind_value)
|
|
85
|
+
except ValueError:
|
|
86
|
+
return None
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
def _require_atom(
|
|
90
|
+
atom_id: Optional[bytes],
|
|
91
|
+
context: str,
|
|
92
|
+
expected_kind: Optional[AtomKind] = None,
|
|
93
|
+
) -> Atom:
|
|
94
|
+
if not atom_id or atom_id == ZERO32:
|
|
95
|
+
raise ValueError(f"missing {context}")
|
|
96
|
+
atom = storage_get(atom_id)
|
|
97
|
+
if atom is None:
|
|
98
|
+
raise ValueError(f"missing {context}")
|
|
99
|
+
if expected_kind is not None:
|
|
100
|
+
kind = _atom_kind(atom)
|
|
101
|
+
if kind is not expected_kind:
|
|
102
|
+
raise ValueError(f"malformed {context}")
|
|
103
|
+
return atom
|
|
104
|
+
|
|
105
|
+
type_atom = _require_atom(transaction_id, "transaction type atom", AtomKind.SYMBOL)
|
|
106
|
+
if type_atom.data != b"transaction":
|
|
107
|
+
raise ValueError("not a transaction (type atom payload)")
|
|
108
|
+
|
|
109
|
+
signature_atom = _require_atom(type_atom.next_id, "transaction signature atom", AtomKind.BYTES)
|
|
110
|
+
body_list_atom = _require_atom(signature_atom.next_id, "transaction body list atom", AtomKind.LIST)
|
|
111
|
+
if body_list_atom.next_id and body_list_atom.next_id != ZERO32:
|
|
112
|
+
raise ValueError("malformed transaction (body list tail)")
|
|
113
|
+
|
|
114
|
+
detail_atoms = node.get_atom_list_from_storage(body_list_atom.data)
|
|
115
|
+
if detail_atoms is None:
|
|
116
|
+
raise ValueError("missing transaction body list nodes")
|
|
117
|
+
if len(detail_atoms) != 6:
|
|
118
|
+
raise ValueError("transaction body must contain exactly 6 detail entries")
|
|
119
|
+
|
|
120
|
+
detail_values: List[bytes] = []
|
|
121
|
+
for detail_atom in detail_atoms:
|
|
122
|
+
if detail_atom.kind is not AtomKind.BYTES:
|
|
123
|
+
raise ValueError("transaction detail atoms must be bytes")
|
|
124
|
+
detail_values.append(detail_atom.data)
|
|
125
|
+
|
|
126
|
+
(
|
|
127
|
+
chain_id_bytes,
|
|
128
|
+
amount_bytes,
|
|
129
|
+
counter_bytes,
|
|
130
|
+
data_bytes,
|
|
131
|
+
recipient_bytes,
|
|
132
|
+
sender_bytes,
|
|
133
|
+
) = detail_values
|
|
134
|
+
|
|
135
|
+
return cls(
|
|
136
|
+
chain_id=bytes_to_int(chain_id_bytes),
|
|
137
|
+
amount=bytes_to_int(amount_bytes),
|
|
138
|
+
counter=bytes_to_int(counter_bytes),
|
|
139
|
+
data=data_bytes,
|
|
140
|
+
recipient=recipient_bytes,
|
|
141
|
+
sender=sender_bytes,
|
|
142
|
+
signature=signature_atom.data,
|
|
143
|
+
hash=bytes(transaction_id),
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def apply_transaction(node: Any, block: object, transaction_hash: bytes) -> int:
|
|
148
|
+
"""Apply transaction to the candidate block and return the collected fee."""
|
|
149
|
+
transaction = Transaction.from_atom(node, transaction_hash)
|
|
150
|
+
|
|
151
|
+
block_chain = getattr(block, "chain_id", None)
|
|
152
|
+
if block_chain is not None and transaction.chain_id != block_chain:
|
|
153
|
+
return 0
|
|
154
|
+
|
|
155
|
+
accounts = getattr(block, "accounts", None)
|
|
156
|
+
if accounts is None:
|
|
157
|
+
raise ValueError("block missing accounts snapshot for transaction application")
|
|
158
|
+
|
|
159
|
+
sender_account = accounts.get_account(address=transaction.sender, node=node)
|
|
160
|
+
if sender_account is None:
|
|
161
|
+
return 0
|
|
162
|
+
|
|
163
|
+
tx_fee = 1
|
|
164
|
+
tx_cost = tx_fee + transaction.amount
|
|
165
|
+
|
|
166
|
+
if sender_account.balance < tx_cost:
|
|
167
|
+
low_sender_balance_receipt = Receipt(
|
|
168
|
+
transaction_hash=bytes(transaction_hash),
|
|
169
|
+
cost=0,
|
|
170
|
+
status=STATUS_FAILED,
|
|
171
|
+
)
|
|
172
|
+
low_sender_balance_receipt.to_atom()
|
|
173
|
+
if block.receipts is None:
|
|
174
|
+
block.receipts = []
|
|
175
|
+
block.receipts.append(low_sender_balance_receipt)
|
|
176
|
+
if block.transactions is None:
|
|
177
|
+
block.transactions = []
|
|
178
|
+
block.transactions.append(transaction)
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
recipient_account = accounts.get_account(address=transaction.recipient, node=node)
|
|
182
|
+
if recipient_account is None:
|
|
183
|
+
recipient_account = Account.create()
|
|
184
|
+
|
|
185
|
+
if transaction.recipient == TREASURY_ADDRESS:
|
|
186
|
+
stake_trie = recipient_account.data
|
|
187
|
+
existing_stake = stake_trie.get(node, transaction.sender)
|
|
188
|
+
current_stake = bytes_to_int(existing_stake)
|
|
189
|
+
new_stake = current_stake + transaction.amount
|
|
190
|
+
stake_trie.put(node, transaction.sender, int_to_bytes(new_stake))
|
|
191
|
+
recipient_account.data_hash = stake_trie.root_hash or ZERO32
|
|
192
|
+
recipient_account.balance += transaction.amount
|
|
193
|
+
else:
|
|
194
|
+
recipient_account.balance += transaction.amount
|
|
195
|
+
|
|
196
|
+
sender_account.balance -= tx_cost
|
|
197
|
+
accounts.set_account(transaction.sender, sender_account)
|
|
198
|
+
accounts.set_account(transaction.recipient, recipient_account)
|
|
199
|
+
|
|
200
|
+
if block.transactions is None:
|
|
201
|
+
block.transactions = []
|
|
202
|
+
block.transactions.append(transaction)
|
|
203
|
+
|
|
204
|
+
receipt = Receipt(
|
|
205
|
+
transaction_hash=bytes(transaction_hash),
|
|
206
|
+
cost=tx_fee,
|
|
207
|
+
status=STATUS_SUCCESS,
|
|
208
|
+
)
|
|
209
|
+
receipt.to_atom()
|
|
210
|
+
if block.receipts is None:
|
|
211
|
+
block.receipts = []
|
|
212
|
+
block.receipts.append(receipt)
|
|
213
|
+
return tx_fee
|
|
@@ -2,21 +2,21 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import threading
|
|
4
4
|
from queue import Queue
|
|
5
|
-
from typing import Any
|
|
5
|
+
from typing import Any, Optional
|
|
6
6
|
|
|
7
|
+
from .validator import current_validator # re-exported for compatibility
|
|
7
8
|
from .workers import (
|
|
8
9
|
make_discovery_worker,
|
|
9
10
|
make_validation_worker,
|
|
10
11
|
make_verify_worker,
|
|
11
12
|
)
|
|
13
|
+
from ..utils.bytes import hex_to_bytes
|
|
12
14
|
|
|
13
15
|
|
|
14
|
-
def
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
def consensus_setup(node: Any, config: Optional[dict] = None) -> None:
|
|
17
|
+
config = config or {}
|
|
18
|
+
node.logger.info("Setting up node consensus")
|
|
17
19
|
|
|
18
|
-
|
|
19
|
-
def consensus_setup(node: Any) -> None:
|
|
20
20
|
# Shared state
|
|
21
21
|
node.validation_lock = getattr(node, "validation_lock", threading.RLock())
|
|
22
22
|
|
|
@@ -25,6 +25,22 @@ def consensus_setup(node: Any) -> None:
|
|
|
25
25
|
# - forks: Dict[head, Fork]
|
|
26
26
|
node.chains = getattr(node, "chains", {})
|
|
27
27
|
node.forks = getattr(node, "forks", {})
|
|
28
|
+
node.logger.info(
|
|
29
|
+
"Consensus maps initialized (chains=%s, forks=%s)",
|
|
30
|
+
len(node.chains),
|
|
31
|
+
len(node.forks),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
latest_block_hex = config.get("latest_block_hash")
|
|
35
|
+
if latest_block_hex is not None:
|
|
36
|
+
node.latest_block_hash = hex_to_bytes(latest_block_hex, expected_length=32)
|
|
37
|
+
|
|
38
|
+
node.latest_block_hash = getattr(node, "latest_block_hash", None)
|
|
39
|
+
node.latest_block = getattr(node, "latest_block", None)
|
|
40
|
+
node.logger.info(
|
|
41
|
+
"Consensus latest_block_hash preset: %s",
|
|
42
|
+
node.latest_block_hash.hex() if isinstance(node.latest_block_hash, bytes) else node.latest_block_hash,
|
|
43
|
+
)
|
|
28
44
|
|
|
29
45
|
# Pending transactions queue (hash-only entries)
|
|
30
46
|
node._validation_transaction_queue = getattr(
|
|
@@ -47,9 +63,7 @@ def consensus_setup(node: Any) -> None:
|
|
|
47
63
|
node.enqueue_transaction_hash = enqueue_transaction_hash
|
|
48
64
|
|
|
49
65
|
verify_worker = make_verify_worker(node)
|
|
50
|
-
validation_worker = make_validation_worker(
|
|
51
|
-
node, current_validator=current_validator
|
|
52
|
-
)
|
|
66
|
+
validation_worker = make_validation_worker(node)
|
|
53
67
|
|
|
54
68
|
# Start workers as daemons
|
|
55
69
|
discovery_worker = make_discovery_worker(node)
|
|
@@ -63,6 +77,7 @@ def consensus_setup(node: Any) -> None:
|
|
|
63
77
|
target=validation_worker, daemon=True, name="consensus-validation"
|
|
64
78
|
)
|
|
65
79
|
node.consensus_discovery_thread.start()
|
|
80
|
+
node.logger.info("Started consensus discovery thread (%s)", node.consensus_discovery_thread.name)
|
|
66
81
|
node.consensus_verify_thread.start()
|
|
67
|
-
|
|
68
|
-
|
|
82
|
+
node.logger.info("Started consensus verify thread (%s)", node.consensus_verify_thread.name)
|
|
83
|
+
node.logger.info("Consensus setup ready")
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from cryptography.hazmat.primitives import serialization
|
|
2
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
3
|
+
|
|
4
|
+
from astreum.consensus.genesis import create_genesis_block
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def process_blocks_and_transactions(self, validator_secret_key: Ed25519PrivateKey):
|
|
8
|
+
"""Initialize validator keys, ensure genesis exists, then start validation thread."""
|
|
9
|
+
node_logger = self.logger
|
|
10
|
+
node_logger.info(
|
|
11
|
+
"Initializing block and transaction processing for chain %s",
|
|
12
|
+
getattr(self, "chain", "unknown"),
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
self.validation_secret_key = validator_secret_key
|
|
16
|
+
validator_public_key_obj = self.validation_secret_key.public_key()
|
|
17
|
+
validator_public_key_bytes = validator_public_key_obj.public_bytes(
|
|
18
|
+
encoding=serialization.Encoding.Raw,
|
|
19
|
+
format=serialization.PublicFormat.Raw,
|
|
20
|
+
)
|
|
21
|
+
self.validation_public_key = validator_public_key_bytes
|
|
22
|
+
node_logger.debug(
|
|
23
|
+
"Derived validator public key %s", validator_public_key_bytes.hex()
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
if self.latest_block_hash is None:
|
|
27
|
+
genesis_block = create_genesis_block(
|
|
28
|
+
self,
|
|
29
|
+
validator_public_key=validator_public_key_bytes,
|
|
30
|
+
chain_id=self.chain,
|
|
31
|
+
)
|
|
32
|
+
account_atoms = genesis_block.accounts.update_trie(self) if genesis_block.accounts else []
|
|
33
|
+
|
|
34
|
+
genesis_hash, genesis_atoms = genesis_block.to_atom()
|
|
35
|
+
node_logger.debug(
|
|
36
|
+
"Genesis block created with %s atoms (%s account atoms)",
|
|
37
|
+
len(genesis_atoms),
|
|
38
|
+
len(account_atoms),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
for atom in account_atoms + genesis_atoms:
|
|
42
|
+
try:
|
|
43
|
+
self._hot_storage_set(key=atom.object_id(), value=atom)
|
|
44
|
+
except Exception as exc:
|
|
45
|
+
node_logger.warning(
|
|
46
|
+
"Unable to persist genesis atom %s: %s",
|
|
47
|
+
atom.object_id(),
|
|
48
|
+
exc,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
self.latest_block_hash = genesis_hash
|
|
52
|
+
self.latest_block = genesis_block
|
|
53
|
+
node_logger.info("Genesis block stored with hash %s", genesis_hash.hex())
|
|
54
|
+
else:
|
|
55
|
+
node_logger.debug(
|
|
56
|
+
"latest_block_hash already set to %s; skipping genesis creation",
|
|
57
|
+
self.latest_block_hash.hex()
|
|
58
|
+
if isinstance(self.latest_block_hash, (bytes, bytearray))
|
|
59
|
+
else self.latest_block_hash,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
node_logger.info(
|
|
63
|
+
"Starting consensus validation thread (%s)",
|
|
64
|
+
self.consensus_validation_thread.name,
|
|
65
|
+
)
|
|
66
|
+
self.consensus_validation_thread.start()
|
|
67
|
+
|
|
68
|
+
# ping all peers to announce validation capability
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
from typing import Any, Dict, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
from .genesis import TREASURY_ADDRESS
|
|
7
|
+
from .models.account import Account
|
|
8
|
+
from .models.accounts import Accounts
|
|
9
|
+
from .models.block import Block
|
|
10
|
+
from ..storage.models.atom import ZERO32
|
|
11
|
+
from ..utils.integer import bytes_to_int, int_to_bytes
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def current_validator(
|
|
15
|
+
node: Any,
|
|
16
|
+
block_hash: bytes,
|
|
17
|
+
target_time: Optional[int] = None,
|
|
18
|
+
) -> Tuple[bytes, Accounts]:
|
|
19
|
+
"""
|
|
20
|
+
Determine the validator for the requested target_time, halving stakes each second
|
|
21
|
+
between the referenced block and the target time. Returns the validator key and
|
|
22
|
+
the updated accounts snapshot reflecting stake and balance adjustments.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
block = Block.from_atom(node, block_hash)
|
|
26
|
+
|
|
27
|
+
if block.timestamp is None:
|
|
28
|
+
raise ValueError("block timestamp missing")
|
|
29
|
+
|
|
30
|
+
block_timestamp = block.timestamp
|
|
31
|
+
target_timestamp = int(target_time) if target_time is not None else block_timestamp + 1
|
|
32
|
+
if target_timestamp <= block_timestamp:
|
|
33
|
+
target_timestamp = block_timestamp + 1
|
|
34
|
+
|
|
35
|
+
accounts_hash = getattr(block, "accounts_hash", None)
|
|
36
|
+
if not accounts_hash:
|
|
37
|
+
raise ValueError("block missing accounts hash")
|
|
38
|
+
accounts = Accounts(root_hash=accounts_hash)
|
|
39
|
+
|
|
40
|
+
treasury_account = accounts.get_account(TREASURY_ADDRESS, node)
|
|
41
|
+
if treasury_account is None:
|
|
42
|
+
raise ValueError("treasury account missing from accounts trie")
|
|
43
|
+
|
|
44
|
+
stake_trie = treasury_account.data
|
|
45
|
+
|
|
46
|
+
stakes: Dict[bytes, int] = {}
|
|
47
|
+
for account_key, stake_amount in stake_trie.get_all(node).items():
|
|
48
|
+
if not account_key:
|
|
49
|
+
continue
|
|
50
|
+
stakes[account_key] = bytes_to_int(stake_amount)
|
|
51
|
+
|
|
52
|
+
if not stakes:
|
|
53
|
+
raise ValueError("no validator stakes found in treasury trie")
|
|
54
|
+
|
|
55
|
+
seed_source = block_hash or getattr(block, "previous_block_hash", ZERO32)
|
|
56
|
+
seed_value = int.from_bytes(bytes(seed_source), "big", signed=False)
|
|
57
|
+
rng = random.Random(seed_value)
|
|
58
|
+
|
|
59
|
+
def pick_validator() -> bytes:
|
|
60
|
+
positive_weights = [(key, weight) for key, weight in stakes.items() if weight > 0]
|
|
61
|
+
if not positive_weights:
|
|
62
|
+
raise ValueError("no validators with positive stake")
|
|
63
|
+
total_weight = sum(weight for _, weight in positive_weights)
|
|
64
|
+
choice = rng.randrange(total_weight)
|
|
65
|
+
cumulative = 0
|
|
66
|
+
for key, weight in sorted(positive_weights, key=lambda item: item[0]):
|
|
67
|
+
cumulative += weight
|
|
68
|
+
if choice < cumulative:
|
|
69
|
+
return key
|
|
70
|
+
return positive_weights[-1][0]
|
|
71
|
+
|
|
72
|
+
def halve_stake(validator_key: bytes) -> None:
|
|
73
|
+
current_amount = stakes.get(validator_key, 0)
|
|
74
|
+
if current_amount <= 0:
|
|
75
|
+
raise ValueError("validator stake must be positive")
|
|
76
|
+
new_amount = current_amount // 2
|
|
77
|
+
returned_amount = current_amount - new_amount
|
|
78
|
+
stakes[validator_key] = new_amount
|
|
79
|
+
stake_trie.put(node, validator_key, int_to_bytes(new_amount))
|
|
80
|
+
treasury_account.data_hash = stake_trie.root_hash or ZERO32
|
|
81
|
+
|
|
82
|
+
validator_account = accounts.get_account(validator_key, node)
|
|
83
|
+
if validator_account is None:
|
|
84
|
+
validator_account = Account.create()
|
|
85
|
+
validator_account.balance += returned_amount
|
|
86
|
+
accounts.set_account(validator_key, validator_account)
|
|
87
|
+
accounts.set_account(TREASURY_ADDRESS, treasury_account)
|
|
88
|
+
|
|
89
|
+
iteration_target = block_timestamp + 1
|
|
90
|
+
while True:
|
|
91
|
+
selected_validator = pick_validator()
|
|
92
|
+
halve_stake(selected_validator)
|
|
93
|
+
if iteration_target == target_timestamp:
|
|
94
|
+
return selected_validator, accounts
|
|
95
|
+
iteration_target += 1
|
|
@@ -13,6 +13,8 @@ def make_discovery_worker(node: Any):
|
|
|
13
13
|
"""
|
|
14
14
|
|
|
15
15
|
def _discovery_worker() -> None:
|
|
16
|
+
node_logger = node.logger
|
|
17
|
+
node_logger.info("Discovery worker started")
|
|
16
18
|
stop = node._validation_stop_event
|
|
17
19
|
while not stop.is_set():
|
|
18
20
|
try:
|
|
@@ -33,6 +35,16 @@ def make_discovery_worker(node: Any):
|
|
|
33
35
|
for hb in latest_keys
|
|
34
36
|
}
|
|
35
37
|
|
|
38
|
+
if not pairs:
|
|
39
|
+
node_logger.debug("No peers reported latest blocks; skipping queue update")
|
|
40
|
+
continue
|
|
41
|
+
|
|
42
|
+
node_logger.debug(
|
|
43
|
+
"Discovery grouped %d block hashes from %d peers",
|
|
44
|
+
len(grouped),
|
|
45
|
+
len(pairs),
|
|
46
|
+
)
|
|
47
|
+
|
|
36
48
|
try:
|
|
37
49
|
while True:
|
|
38
50
|
node._validation_verify_queue.get_nowait()
|
|
@@ -40,9 +52,16 @@ def make_discovery_worker(node: Any):
|
|
|
40
52
|
pass
|
|
41
53
|
for latest_b, peer_set in grouped.items():
|
|
42
54
|
node._validation_verify_queue.put((latest_b, peer_set))
|
|
55
|
+
node_logger.debug(
|
|
56
|
+
"Queued %d peers for validation of block %s",
|
|
57
|
+
len(peer_set),
|
|
58
|
+
latest_b.hex(),
|
|
59
|
+
)
|
|
43
60
|
except Exception:
|
|
44
|
-
|
|
61
|
+
node_logger.exception("Discovery worker iteration failed")
|
|
45
62
|
finally:
|
|
46
63
|
time.sleep(0.5)
|
|
47
64
|
|
|
65
|
+
node_logger.info("Discovery worker stopped")
|
|
66
|
+
|
|
48
67
|
return _discovery_worker
|