nano-settlement-verify 2.0.0__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.
- nano_settlement_verify/__init__.py +607 -0
- nano_settlement_verify/claim.py +466 -0
- nano_settlement_verify/five_fields.py +444 -0
- nano_settlement_verify/funding.py +213 -0
- nano_settlement_verify/independence.py +257 -0
- nano_settlement_verify/links/__init__.py +0 -0
- nano_settlement_verify/links/public_check.py +177 -0
- nano_settlement_verify/node_set/NODES.json +22 -0
- nano_settlement_verify/node_set/__init__.py +43 -0
- nano_settlement_verify/node_set/probe.py +127 -0
- nano_settlement_verify/offline.py +225 -0
- nano_settlement_verify/payers.py +887 -0
- nano_settlement_verify/period_counts.py +210 -0
- nano_settlement_verify/quorum.py +2076 -0
- nano_settlement_verify/recount.py +249 -0
- nano_settlement_verify/stated_payer_test.py +699 -0
- nano_settlement_verify/terms.py +235 -0
- nano_settlement_verify/two_node.py +77 -0
- nano_settlement_verify-2.0.0.dist-info/METADATA +1166 -0
- nano_settlement_verify-2.0.0.dist-info/RECORD +23 -0
- nano_settlement_verify-2.0.0.dist-info/WHEEL +5 -0
- nano_settlement_verify-2.0.0.dist-info/licenses/LICENSE +21 -0
- nano_settlement_verify-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""Verify a Nano (XNO) settlement receipt.
|
|
2
|
+
|
|
3
|
+
Given the hash of a send block, ask a Nano node whether that block is confirmed,
|
|
4
|
+
whether it moved the amount that was quoted, and whether it paid the account the
|
|
5
|
+
seller expected. What comes back is a receipt a seller can keep.
|
|
6
|
+
|
|
7
|
+
Amounts are raw integers everywhere: 1 XNO is 10**30 raw, and a float loses the
|
|
8
|
+
low digits, so raw is parsed with int() and never with float().
|
|
9
|
+
|
|
10
|
+
Accounts are compared as accounts, not as the strings that spell them: one Nano
|
|
11
|
+
account has two spellings, the modern `nano_` form and the legacy `xrb_` form.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import numbers
|
|
20
|
+
import urllib.request
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from decimal import Decimal
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"Receipt",
|
|
27
|
+
"NotFound",
|
|
28
|
+
"Mismatch",
|
|
29
|
+
"Late",
|
|
30
|
+
"UnknownTime",
|
|
31
|
+
"NotANodeReply",
|
|
32
|
+
"verify",
|
|
33
|
+
"parse_not_after",
|
|
34
|
+
"TIME_SOURCE",
|
|
35
|
+
"post_json",
|
|
36
|
+
"is_valid_account",
|
|
37
|
+
"public_key_from_address",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
# The distribution's version (pyproject.toml says the same).
|
|
41
|
+
__version__ = "2.0.0"
|
|
42
|
+
|
|
43
|
+
# Seconds to wait on the node before giving up. Verification sits on a seller's
|
|
44
|
+
# request path; an unbounded wait there is an outage, not patience.
|
|
45
|
+
RPC_TIMEOUT_S = 30
|
|
46
|
+
|
|
47
|
+
# Sent on every node call. Cloudflare-fronted RPCs, rpc.nano.to among them, refuse
|
|
48
|
+
# urllib's default `Python-urllib/3.x` with 403 "error code: 1010" - a refusal
|
|
49
|
+
# indistinguishable from a bad node - so the call names itself instead.
|
|
50
|
+
USER_AGENT = "nano-settlement-verify/1.0 (+https://github.com/dhyabi2/nano-settlement-verify)"
|
|
51
|
+
|
|
52
|
+
# The operations a Nano block can name. A state block's contents.type is "state",
|
|
53
|
+
# which says nothing about what the block did, so it is deliberately absent here:
|
|
54
|
+
# a reply that carries no subtype and a contents.type of "state" names no
|
|
55
|
+
# operation, and must fail closed rather than be read as a send.
|
|
56
|
+
_OPERATIONS = frozenset({"send", "receive", "open", "change", "epoch"})
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class NotFound(Exception):
|
|
60
|
+
"""The node reports no block with this hash."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, block_hash: str) -> None:
|
|
63
|
+
super().__init__(f"no such block: {block_hash}")
|
|
64
|
+
self.block_hash = block_hash
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Mismatch(Exception):
|
|
68
|
+
"""The block is confirmed, but not for the amount or the account expected."""
|
|
69
|
+
|
|
70
|
+
def __init__(self, got, expected) -> None:
|
|
71
|
+
super().__init__(f"expected {expected!r}, got {got!r}")
|
|
72
|
+
self.got = got
|
|
73
|
+
self.expected = expected
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# Said in every receipt that carries a deadline, because it is the whole caveat.
|
|
77
|
+
TIME_SOURCE = (
|
|
78
|
+
"local_timestamp: when this node first saw the block, on its own clock; "
|
|
79
|
+
"not signed by the sender, and another node can differ by seconds - "
|
|
80
|
+
"read it on two nodes if seconds matter"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Late(Exception):
|
|
85
|
+
"""The block settled for the right amount and account, but was seen after not_after.
|
|
86
|
+
|
|
87
|
+
The money did arrive - `receipt` is the settled receipt, so a refund can
|
|
88
|
+
cite it - but not by the order's deadline, so the order is not paid on time.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(self, seen_at: int, not_after: int, receipt: "Receipt") -> None:
|
|
92
|
+
super().__init__(f"seen at {seen_at}, after the deadline {not_after}")
|
|
93
|
+
self.seen_at = seen_at
|
|
94
|
+
self.not_after = not_after
|
|
95
|
+
self.receipt = receipt
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class UnknownTime(Exception):
|
|
99
|
+
"""The block settled, but the node reports no time it saw it (missing or 0).
|
|
100
|
+
|
|
101
|
+
Very old blocks carry local_timestamp 0. With no time, on-time cannot be
|
|
102
|
+
shown, so this is never read as on time.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, not_after: int, receipt: "Receipt") -> None:
|
|
106
|
+
super().__init__(f"the node reports no local_timestamp; deadline {not_after} unchecked")
|
|
107
|
+
self.not_after = not_after
|
|
108
|
+
self.receipt = receipt
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class NotANodeReply(ValueError):
|
|
112
|
+
"""The endpoint answered with JSON that is not a node's block_info reply.
|
|
113
|
+
|
|
114
|
+
A public RPC behind a proxy answers 200 with its own JSON far more often
|
|
115
|
+
than it answers with HTML: a status page, a rate-limit envelope, an auth
|
|
116
|
+
complaint. None of them carry `confirmed`, so none of them says anything
|
|
117
|
+
about the payment.
|
|
118
|
+
|
|
119
|
+
This is a `ValueError` on purpose. It belongs with the transport failures,
|
|
120
|
+
not with `NotFound` or `Mismatch`: it means "we could not look", not "the
|
|
121
|
+
payment is bad". A seller catching `(OSError, ValueError)` around `verify` -
|
|
122
|
+
which is what the README tells it to do, because this sits on its request
|
|
123
|
+
path - holds the call and asks again, instead of taking an uncaught
|
|
124
|
+
exception. It used to be a bare `KeyError`, which escaped that arm.
|
|
125
|
+
|
|
126
|
+
It is never raised for a reply that IS a node reply: an `{"error": ...}`
|
|
127
|
+
body is still `NotFound`, and `"confirmed": "false"` is still an unsettled
|
|
128
|
+
receipt.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _required(reply: dict, field: str):
|
|
133
|
+
"""`reply[field]`, or `NotANodeReply` naming what was missing.
|
|
134
|
+
|
|
135
|
+
Every field a node's block_info reply must carry is read through here, so a
|
|
136
|
+
malformed reply is refused in the documented family rather than raising a
|
|
137
|
+
bare KeyError out of a seller's request path.
|
|
138
|
+
"""
|
|
139
|
+
try:
|
|
140
|
+
return reply[field]
|
|
141
|
+
except KeyError:
|
|
142
|
+
raise NotANodeReply(
|
|
143
|
+
"the endpoint's reply carries no %r, so it is not a node's "
|
|
144
|
+
"block_info reply and says nothing about this block; keys present: %s"
|
|
145
|
+
% (field, sorted(reply))
|
|
146
|
+
) from None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class Receipt:
|
|
151
|
+
"""What a seller can show to prove a payment settled."""
|
|
152
|
+
|
|
153
|
+
settled: bool
|
|
154
|
+
amount_raw: int
|
|
155
|
+
height: int
|
|
156
|
+
account: str
|
|
157
|
+
# Set only when verify() was given not_after; otherwise the receipt and its
|
|
158
|
+
# JSON are exactly what they were before deadlines existed.
|
|
159
|
+
seen_at: int | None = None
|
|
160
|
+
not_after: int | None = None
|
|
161
|
+
|
|
162
|
+
def to_json(self) -> str:
|
|
163
|
+
out = {
|
|
164
|
+
"settled": self.settled,
|
|
165
|
+
"amount_raw": self.amount_raw,
|
|
166
|
+
"height": self.height,
|
|
167
|
+
"account": self.account,
|
|
168
|
+
}
|
|
169
|
+
if self.not_after is not None:
|
|
170
|
+
out.update(seen_at=self.seen_at, not_after=self.not_after, time_source=TIME_SOURCE)
|
|
171
|
+
return json.dumps(out)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def parse_not_after(text: str) -> int:
|
|
175
|
+
"""A deadline as unix seconds, from unix seconds or ISO-8601 with a UTC offset.
|
|
176
|
+
|
|
177
|
+
`1790150110`, `2026-09-23T07:55:10Z` and `2026-09-23T07:55:10+00:00` are the
|
|
178
|
+
same instant. A time with no offset is refused (ValueError): whose clock it
|
|
179
|
+
means is a guess, and a guessed deadline decides real orders.
|
|
180
|
+
"""
|
|
181
|
+
text = str(text).strip()
|
|
182
|
+
if text.isdigit():
|
|
183
|
+
return int(text)
|
|
184
|
+
when = datetime.fromisoformat(text) # ValueError on anything unreadable
|
|
185
|
+
if when.tzinfo is None:
|
|
186
|
+
raise ValueError(f"deadline {text!r} has no UTC offset; add Z or +00:00")
|
|
187
|
+
return int(when.timestamp())
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _seen_at(reply: dict) -> int | None:
|
|
191
|
+
"""The node's local_timestamp as unix seconds, or None when it has none.
|
|
192
|
+
|
|
193
|
+
Missing, empty, unreadable and 0 all come back as None: 0 is what a node
|
|
194
|
+
reports for a block it has no record of seeing, not the epoch.
|
|
195
|
+
"""
|
|
196
|
+
try:
|
|
197
|
+
seen = int(str(reply.get("local_timestamp") or "0"))
|
|
198
|
+
except ValueError:
|
|
199
|
+
return None
|
|
200
|
+
return seen if seen > 0 else None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def post_json(rpc_url: str, payload: dict) -> dict:
|
|
204
|
+
"""POST payload as JSON to a Nano node's RPC endpoint and return its reply."""
|
|
205
|
+
request = urllib.request.Request(
|
|
206
|
+
rpc_url,
|
|
207
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
208
|
+
headers={"Content-Type": "application/json", "User-Agent": USER_AGENT},
|
|
209
|
+
method="POST",
|
|
210
|
+
)
|
|
211
|
+
# A seller calls this on its request path, so a node that accepts the
|
|
212
|
+
# connection and then goes quiet must not hang the sale indefinitely.
|
|
213
|
+
with urllib.request.urlopen(request, timeout=RPC_TIMEOUT_S) as response:
|
|
214
|
+
return json.loads(response.read().decode("utf-8"))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _contents(reply: dict) -> dict:
|
|
218
|
+
"""The block's contents, or an empty mapping when the node sent none.
|
|
219
|
+
|
|
220
|
+
A node that ignores json_block returns contents as an opaque string. There is
|
|
221
|
+
no link to read out of that, so it must read as absent, not raise.
|
|
222
|
+
"""
|
|
223
|
+
contents = reply.get("contents")
|
|
224
|
+
return contents if isinstance(contents, dict) else {}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _operation(reply: dict) -> str:
|
|
228
|
+
"""What the block did: "send", "receive", "open", "change" or "epoch".
|
|
229
|
+
|
|
230
|
+
A state block names it in the top-level subtype; a pre-state block names it in
|
|
231
|
+
contents.type. Anything else is unknown, and comes back as "".
|
|
232
|
+
"""
|
|
233
|
+
subtype = str(reply.get("subtype") or "")
|
|
234
|
+
if subtype:
|
|
235
|
+
return subtype
|
|
236
|
+
legacy = str(_contents(reply).get("type") or "")
|
|
237
|
+
return legacy if legacy in _OPERATIONS else ""
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# The two spellings of one Nano account. The address prefix was renamed from
|
|
241
|
+
# `xrb_` to `nano_`; the 60 characters after it are the same encoding of the same
|
|
242
|
+
# public key, and both forms are still in use and still accepted everywhere. So
|
|
243
|
+
# two addresses name the same account exactly when those 60 characters match.
|
|
244
|
+
_ACCOUNT_PREFIXES = ("nano_", "xrb_")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _account_body(address: object) -> str | None:
|
|
248
|
+
"""The part of an address that identifies the account, or None if it has none.
|
|
249
|
+
|
|
250
|
+
Everything after the `nano_`/`xrb_` prefix. Anything that is not a string
|
|
251
|
+
carrying one of those prefixes is not a Nano address, and comes back as None
|
|
252
|
+
so that it is refused rather than compared - an absent link reads as "", and
|
|
253
|
+
"" must never match. A caller who passes None for `account` still gets the
|
|
254
|
+
Mismatch it got before this function existed, not an AttributeError.
|
|
255
|
+
"""
|
|
256
|
+
if not isinstance(address, str):
|
|
257
|
+
return None
|
|
258
|
+
for prefix in _ACCOUNT_PREFIXES:
|
|
259
|
+
if address.startswith(prefix):
|
|
260
|
+
return address[len(prefix):]
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# A Nano address is its public key in base32 plus a 5-byte blake2b checksum of
|
|
265
|
+
# that key, so an address can be checked for being payable at all without
|
|
266
|
+
# asking anyone: 60 characters after the prefix, the first 52 carrying 4 zero
|
|
267
|
+
# padding bits and the 256-bit key, the last 8 carrying the checksum reversed.
|
|
268
|
+
# Nano's own base32 alphabet drops the characters that misread by hand.
|
|
269
|
+
_ACCOUNT_ALPHABET = "13456789abcdefghijkmnopqrstuwxyz"
|
|
270
|
+
_ACCOUNT_ALPHABET_INDEX = {c: i for i, c in enumerate(_ACCOUNT_ALPHABET)}
|
|
271
|
+
_ACCOUNT_BODY_LEN = 60
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _base32_to_int(chars: str) -> int | None:
|
|
275
|
+
"""The integer those base32 characters spell, or None if any is not one."""
|
|
276
|
+
value = 0
|
|
277
|
+
for char in chars:
|
|
278
|
+
index = _ACCOUNT_ALPHABET_INDEX.get(char)
|
|
279
|
+
if index is None:
|
|
280
|
+
return None
|
|
281
|
+
value = value * 32 + index
|
|
282
|
+
return value
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def public_key_from_address(address: object) -> bytes | None:
|
|
286
|
+
"""The 32-byte public key an address names, or None if it names none.
|
|
287
|
+
|
|
288
|
+
None means the string cannot be a Nano account at all: a wrong prefix, a
|
|
289
|
+
wrong length, a character outside Nano's base32 alphabet, non-zero padding
|
|
290
|
+
bits, or a checksum that does not match the key it is attached to. It never
|
|
291
|
+
means the account is empty or unknown to any node - this reads the address
|
|
292
|
+
itself and asks nobody.
|
|
293
|
+
"""
|
|
294
|
+
body = _account_body(address)
|
|
295
|
+
if body is None or len(body) != _ACCOUNT_BODY_LEN:
|
|
296
|
+
return None
|
|
297
|
+
key_value = _base32_to_int(body[:52])
|
|
298
|
+
check_value = _base32_to_int(body[52:])
|
|
299
|
+
if key_value is None or check_value is None:
|
|
300
|
+
return None
|
|
301
|
+
if key_value >> 256: # the 4 leading bits are padding and must be zero
|
|
302
|
+
return None
|
|
303
|
+
public_key = key_value.to_bytes(32, "big")
|
|
304
|
+
expected = hashlib.blake2b(public_key, digest_size=5).digest()[::-1]
|
|
305
|
+
if check_value.to_bytes(5, "big") != expected:
|
|
306
|
+
return None
|
|
307
|
+
return public_key
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def is_valid_account(address: object) -> bool:
|
|
311
|
+
"""Whether this string is an address XNO can actually be sent to.
|
|
312
|
+
|
|
313
|
+
The checksum is the whole point: a mistyped or truncated Nano address is
|
|
314
|
+
overwhelmingly likely to fail it, and a Nano send is irreversible, so an
|
|
315
|
+
address that fails this is money that leaves and never arrives.
|
|
316
|
+
"""
|
|
317
|
+
return public_key_from_address(address) is not None
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _same_account(left: object, right: object) -> bool:
|
|
321
|
+
"""Whether two addresses name one account, however each one is spelled.
|
|
322
|
+
|
|
323
|
+
A node always answers the modern `nano_` form, while a seller passes whatever
|
|
324
|
+
they have stored, which for older tooling is the `xrb_` form of the very same
|
|
325
|
+
account. Comparing the two strings refuses a payment that did arrive - and by
|
|
326
|
+
then the buyer's money has irreversibly moved, so the refusal costs the sale
|
|
327
|
+
and leaves the seller with no receipt for money they were paid.
|
|
328
|
+
"""
|
|
329
|
+
body = _account_body(left)
|
|
330
|
+
return body is not None and body == _account_body(right)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _paid_account(reply: dict) -> str:
|
|
334
|
+
"""The account the block paid: its link, not the chain it sits on.
|
|
335
|
+
|
|
336
|
+
A state block carries it as contents.link_as_account, a pre-state send block
|
|
337
|
+
as contents.destination. An absent link comes back as "".
|
|
338
|
+
"""
|
|
339
|
+
contents = _contents(reply)
|
|
340
|
+
return str(
|
|
341
|
+
contents.get("link_as_account")
|
|
342
|
+
or contents.get("destination")
|
|
343
|
+
or reply.get("link_as_account")
|
|
344
|
+
or reply.get("destination")
|
|
345
|
+
or ""
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _deadline(not_after: object) -> int | float:
|
|
350
|
+
"""`not_after` as an int or a float verify can compare and the receipt can print.
|
|
351
|
+
|
|
352
|
+
A ValueError, in the family `parse_not_after` uses, for anything else - so a
|
|
353
|
+
seller catching `(OSError, ValueError)` around verify holds the call.
|
|
354
|
+
|
|
355
|
+
Refused: a bool, a string or any other non-number, and a number that is not
|
|
356
|
+
finite. NaN compares False with everything, so `seen_at > NaN` was never
|
|
357
|
+
true and a payment an hour late verified as on time; +inf did the same by
|
|
358
|
+
being later than every time. `json.loads` reads both from an order record
|
|
359
|
+
(`NaN`, `Infinity`), and the receipt then printed them as JSON no parser
|
|
360
|
+
must accept.
|
|
361
|
+
|
|
362
|
+
Accepted and converted: a deadline that is a number but not an int or a
|
|
363
|
+
float - a Decimal from a database NUMERIC column, a numpy.int64 or
|
|
364
|
+
numpy.float64 from a dataframe, a Fraction. Those were refused by #24 on
|
|
365
|
+
every call, holding every paid order. An integral type becomes an int, a
|
|
366
|
+
float subclass a float, and any other real (a Decimal, a Fraction) its
|
|
367
|
+
floor: seen_at is whole seconds and the check is `seen_at > not_after`, so
|
|
368
|
+
the floor decides every payment exactly as the value itself would, where
|
|
369
|
+
float() could round 1790150109.9999999999 up across the second. The floor
|
|
370
|
+
is taken from the exact ratio where the type has one, so a numpy.longdouble
|
|
371
|
+
1790150109.9999999 is not rounded up through float() either.
|
|
372
|
+
|
|
373
|
+
Also refused, before any conversion: a numpy float narrower than float64
|
|
374
|
+
(a float32 is 128 seconds apart near a 2026 unix time, a float16 cannot hold
|
|
375
|
+
one at all), and a deadline whose magnitude is beyond 2**63 seconds -
|
|
376
|
+
no order expires there, and flooring Decimal('1E+1000000') would spend
|
|
377
|
+
seconds of CPU or run out of memory before it answered.
|
|
378
|
+
"""
|
|
379
|
+
if isinstance(not_after, bool) or not isinstance(not_after, (numbers.Real, Decimal)):
|
|
380
|
+
raise ValueError(
|
|
381
|
+
f"not_after must be unix seconds as an int or a float, got "
|
|
382
|
+
f"{type(not_after).__name__} ({not_after!r}); parse_not_after() reads "
|
|
383
|
+
f"a string deadline, in unix seconds or ISO-8601 with a UTC offset"
|
|
384
|
+
)
|
|
385
|
+
dtype = getattr(not_after, "dtype", None)
|
|
386
|
+
if (
|
|
387
|
+
not isinstance(not_after, numbers.Integral)
|
|
388
|
+
and getattr(dtype, "kind", None) == "f"
|
|
389
|
+
and getattr(dtype, "itemsize", 8) < 8
|
|
390
|
+
):
|
|
391
|
+
raise ValueError(
|
|
392
|
+
f"not_after is a {type(not_after).__name__} ({not_after!r}), which cannot "
|
|
393
|
+
f"hold a unix time to the second; pass an int, or a float64"
|
|
394
|
+
)
|
|
395
|
+
if isinstance(not_after, numbers.Integral):
|
|
396
|
+
not_after = int(not_after)
|
|
397
|
+
_within_deadline_bound(not_after)
|
|
398
|
+
return not_after
|
|
399
|
+
if isinstance(not_after, Decimal):
|
|
400
|
+
finite = not_after.is_finite()
|
|
401
|
+
else:
|
|
402
|
+
try:
|
|
403
|
+
finite = math.isfinite(not_after)
|
|
404
|
+
except OverflowError: # a Fraction too large for a float is still finite
|
|
405
|
+
finite = True
|
|
406
|
+
if not finite:
|
|
407
|
+
raise ValueError(
|
|
408
|
+
f"not_after must be a finite number of unix seconds, got {not_after!r}; "
|
|
409
|
+
f"a NaN or infinite deadline would let a late payment through as on time"
|
|
410
|
+
)
|
|
411
|
+
_within_deadline_bound(not_after)
|
|
412
|
+
if isinstance(not_after, float):
|
|
413
|
+
return float(not_after)
|
|
414
|
+
ratio = getattr(not_after, "as_integer_ratio", None)
|
|
415
|
+
if ratio is not None and not isinstance(not_after, Decimal):
|
|
416
|
+
numerator, denominator = ratio()
|
|
417
|
+
return int(numerator) // int(denominator)
|
|
418
|
+
return math.floor(not_after)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
_DEADLINE_BOUND = 2**63
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _within_deadline_bound(not_after: object) -> None:
|
|
425
|
+
"""ValueError for a finite deadline beyond 2**63 seconds either side of 1970.
|
|
426
|
+
|
|
427
|
+
The message names the type, not the value: repr() of an int past 4300 digits
|
|
428
|
+
itself raises ValueError, which would hide this one.
|
|
429
|
+
"""
|
|
430
|
+
if not -_DEADLINE_BOUND <= not_after <= _DEADLINE_BOUND: # no abs(): it rounds a Decimal
|
|
431
|
+
raise ValueError(
|
|
432
|
+
f"not_after must be within 2**63 unix seconds of 1970, got a "
|
|
433
|
+
f"{type(not_after).__name__} beyond that; pass None for no deadline"
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _raw_amount(reply: dict) -> int:
|
|
438
|
+
"""The reply's `amount` as an int of raw, or NotANodeReply.
|
|
439
|
+
|
|
440
|
+
A node sends raw as a decimal string. int() of a JSON number 1.9 is 1, and
|
|
441
|
+
int() of a JSON `true` is 1, so a reply carrying either would have matched an
|
|
442
|
+
expectation of 1 raw and settled on an amount nobody sent. A float or a bool
|
|
443
|
+
is not raw; it is refused in the family a seller holds on, like any other
|
|
444
|
+
reply that is not a node's block_info answer. Everything else reaches int()
|
|
445
|
+
as before: a string that is not an integer raises ValueError, an infinite
|
|
446
|
+
float OverflowError and a list or an object TypeError, which the skill's
|
|
447
|
+
CLI already names as a number too large to read and a field of the wrong
|
|
448
|
+
type.
|
|
449
|
+
"""
|
|
450
|
+
amount = _required(reply, "amount")
|
|
451
|
+
if isinstance(amount, bool) or (isinstance(amount, float) and math.isfinite(amount)):
|
|
452
|
+
raise NotANodeReply(
|
|
453
|
+
f"the reply's amount is {type(amount).__name__} ({amount!r}), not raw: "
|
|
454
|
+
f"a node sends raw as an integer string, and int() would read it as another number"
|
|
455
|
+
)
|
|
456
|
+
return int(amount)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def verify(
|
|
460
|
+
block_hash: str, expect_raw: int, account: str, rpc_url: str, not_after: int | None = None
|
|
461
|
+
) -> Receipt:
|
|
462
|
+
"""Prove a Nano send block settled for expect_raw to account.
|
|
463
|
+
|
|
464
|
+
Returns a settled Receipt when it did, and an unsettled one when the node
|
|
465
|
+
has the block but has not confirmed it yet.
|
|
466
|
+
|
|
467
|
+
Raises NotFound when the node has no such block, and Mismatch when the
|
|
468
|
+
amount differs, when the block names an operation other than "send", or when
|
|
469
|
+
it paid an account other than the one expected. `account` may be given in either the `nano_` or
|
|
470
|
+
the `xrb_` spelling; they are two names for one account. The receipt records
|
|
471
|
+
the account as the node spelled it, which is the canonical `nano_` form.
|
|
472
|
+
|
|
473
|
+
Raises TypeError when expect_raw is not an int, because raw is an integer
|
|
474
|
+
and a float expectation cannot be compared to one safely, and ValueError
|
|
475
|
+
when not_after is neither None nor a finite number of unix seconds - both before
|
|
476
|
+
the node is called. A string deadline goes through parse_not_after first.
|
|
477
|
+
|
|
478
|
+
Raises NotANodeReply - a ValueError - when the endpoint answers with JSON
|
|
479
|
+
that is not a node's block_info reply, which is what a proxy's status page
|
|
480
|
+
or a rate-limit envelope looks like. That lands with the transport failures
|
|
481
|
+
a seller is told to catch, rather than as a bare KeyError through its
|
|
482
|
+
request path. A reply that carries `confirmed` and an amount but names no
|
|
483
|
+
operation or no payee - a node that ignored json_block and sent `contents`
|
|
484
|
+
as a string, or dropped `subtype` - is the same family: nothing was read, so
|
|
485
|
+
nothing is claimed about the payment.
|
|
486
|
+
|
|
487
|
+
With `not_after` (unix seconds; see parse_not_after), a settled block must
|
|
488
|
+
also have been seen by this node at or before it - inclusive. Raises Late
|
|
489
|
+
when it was seen after, and UnknownTime when the node reports no time
|
|
490
|
+
(missing or 0). The time is the node's own local_timestamp: a Nano block
|
|
491
|
+
carries no sender-signed time, so the deadline is checked against the node
|
|
492
|
+
the caller chose, and another node can differ by seconds.
|
|
493
|
+
"""
|
|
494
|
+
if isinstance(expect_raw, bool) or not isinstance(expect_raw, int):
|
|
495
|
+
# A float expect_raw silently loses digits above 2**53, so 1 XNO written
|
|
496
|
+
# as 1e30 would "match" an amount 19884624838656 raw short of it. Refuse
|
|
497
|
+
# the comparison rather than settle on it.
|
|
498
|
+
raise TypeError(f"expect_raw must be an int of raw, got {type(expect_raw).__name__}")
|
|
499
|
+
# Checked here, beside expect_raw and before the node is called, because the
|
|
500
|
+
# comparison that uses it (`seen_at > not_after`) is the LAST thing verify
|
|
501
|
+
# does - after the block is confirmed and the amount and payee have matched.
|
|
502
|
+
# A deadline read back as a string from a JSON order record or a config file
|
|
503
|
+
# therefore raised `TypeError: '>' not supported between instances of 'int'
|
|
504
|
+
# and 'str'` only on payments that had actually arrived, and TypeError is
|
|
505
|
+
# neither OSError nor ValueError, so it escaped the arm the README tells a
|
|
506
|
+
# seller to wrap this call in and dropped a call the buyer had paid for.
|
|
507
|
+
# A ValueError holds instead, in the family `parse_not_after` already uses
|
|
508
|
+
# for a deadline it cannot read. A float is accepted: `time.time() + 300` is
|
|
509
|
+
# the ordinary way to write one, and unlike raw, a time is not an amount.
|
|
510
|
+
if not_after is not None:
|
|
511
|
+
not_after = _deadline(not_after)
|
|
512
|
+
reply = post_json(rpc_url, {"action": "block_info", "json_block": "true", "hash": block_hash})
|
|
513
|
+
return _receipt_of_reply(block_hash, expect_raw, account, reply, not_after)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _receipt_of_reply(
|
|
517
|
+
block_hash: str, expect_raw: int, account: str, reply: object, not_after=None
|
|
518
|
+
) -> Receipt:
|
|
519
|
+
"""`verify`'s verdict on a block_info reply already in hand.
|
|
520
|
+
|
|
521
|
+
Everything `verify` decides after the node has answered, unchanged. It is
|
|
522
|
+
split out so `nano_quorum` can read the same reply once and both reach this
|
|
523
|
+
verdict and check which block the reply is about; `not_after` must already
|
|
524
|
+
have been through `_deadline`, as `verify` does before it calls the node.
|
|
525
|
+
"""
|
|
526
|
+
# A node's block_info answer is a JSON object. Anything else is not an answer
|
|
527
|
+
# about this block, and it must not become one: the test below is `in`, which
|
|
528
|
+
# on a string is a substring test and on a list a membership test, so a
|
|
529
|
+
# proxy answering `"error"`, `"no error here"` or `["error"]` came out as
|
|
530
|
+
# NotFound -- "no such block", the one verdict a seller refuses a call on --
|
|
531
|
+
# from a reply that says nothing about the payment. A number or an object-less
|
|
532
|
+
# array instead reached `reply["confirmed"]` and raised TypeError, which is
|
|
533
|
+
# neither OSError nor ValueError and so escaped the `except (OSError,
|
|
534
|
+
# ValueError)` arm README.md's "Use it" example tells a seller to write. Both are the distinction #23 drew for an unreadable reply:
|
|
535
|
+
# "we could not look" is NotANodeReply and holds; only a readable answer may
|
|
536
|
+
# be a verdict. The skill bundle's CLI has no check of its own: through it
|
|
537
|
+
# this turns exit 3 (no_such_block) into exit 4 (node_unreachable), and a
|
|
538
|
+
# bare number, which used to crash it with a traceback, into exit 4 too. The
|
|
539
|
+
# same refusal reaches every caller that imports verify, which is what
|
|
540
|
+
# README.md documents first, and nano_quorum, where such an endpoint now
|
|
541
|
+
# counts as failed, not as answered. (nano_claim does not call verify; its
|
|
542
|
+
# own _call already refuses a reply that is not a dict.)
|
|
543
|
+
if not isinstance(reply, dict):
|
|
544
|
+
raise NotANodeReply(
|
|
545
|
+
"the endpoint's reply is %s, not a JSON object, so it is not a node's "
|
|
546
|
+
"block_info reply and says nothing about this block"
|
|
547
|
+
% type(reply).__name__
|
|
548
|
+
)
|
|
549
|
+
if "error" in reply:
|
|
550
|
+
raise NotFound(block_hash)
|
|
551
|
+
if _required(reply, "confirmed") != "true":
|
|
552
|
+
return Receipt(settled=False, amount_raw=0, height=0, account="")
|
|
553
|
+
# raw is an integer string; never parse it as a float
|
|
554
|
+
amount = _raw_amount(reply)
|
|
555
|
+
if amount != expect_raw:
|
|
556
|
+
raise Mismatch(amount, expect_raw)
|
|
557
|
+
# Only a send pays anyone. A receive or an open block sits on the account that
|
|
558
|
+
# was credited, so without this check the hash of any confirmed inbound block
|
|
559
|
+
# of the seller's own chain would verify with nothing paid for this call.
|
|
560
|
+
operation = _operation(reply)
|
|
561
|
+
# "" is not an answer about the block, it is the absence of one: a reply with
|
|
562
|
+
# no subtype and a contents.type of "state", or a contents the node sent as an
|
|
563
|
+
# opaque string because it ignored json_block. Reporting that as
|
|
564
|
+
# `Mismatch("", "send")` says "this block is not a send" - a verdict about the
|
|
565
|
+
# money, and the one arm the README tells a seller to refuse on - when the
|
|
566
|
+
# truth is "we could not look", which is what NotANodeReply is for. A real
|
|
567
|
+
# non-send names itself ("receive", "open", "change", "epoch") and is still a
|
|
568
|
+
# Mismatch below.
|
|
569
|
+
if not operation:
|
|
570
|
+
raise NotANodeReply(
|
|
571
|
+
f"the reply for {block_hash} names no operation: no subtype, and "
|
|
572
|
+
f"contents {'is not an object' if not isinstance(reply.get('contents'), dict) else 'names no type'}"
|
|
573
|
+
)
|
|
574
|
+
if operation != "send":
|
|
575
|
+
raise Mismatch(operation, "send")
|
|
576
|
+
# block_account is the account whose chain the block sits on - for a send, the
|
|
577
|
+
# payer. The account paid is the block's link.
|
|
578
|
+
paid = _paid_account(reply)
|
|
579
|
+
# Same distinction: every send names its payee, in one of the four places
|
|
580
|
+
# `_paid_account` looks, so "" means the reply carried none of them - not that
|
|
581
|
+
# the block paid somebody else. `Mismatch("", account)` told a seller whose
|
|
582
|
+
# buyer really had paid that it had been paid by nobody.
|
|
583
|
+
if not paid:
|
|
584
|
+
raise NotANodeReply(
|
|
585
|
+
f"the reply for {block_hash} names no payee: no link_as_account and no "
|
|
586
|
+
f"destination, in contents or at the top level"
|
|
587
|
+
)
|
|
588
|
+
if not _same_account(paid, account):
|
|
589
|
+
raise Mismatch(paid, account)
|
|
590
|
+
receipt = Receipt(
|
|
591
|
+
settled=True,
|
|
592
|
+
amount_raw=amount,
|
|
593
|
+
height=int(_required(reply, "height")),
|
|
594
|
+
account=paid,
|
|
595
|
+
)
|
|
596
|
+
if not_after is None:
|
|
597
|
+
return receipt
|
|
598
|
+
# The order's expiry. Checked last, so a wrong amount or payee is still a
|
|
599
|
+
# Mismatch whatever its time. Inclusive: seen exactly at not_after is on time.
|
|
600
|
+
seen_at = _seen_at(reply)
|
|
601
|
+
receipt = Receipt(receipt.settled, receipt.amount_raw, receipt.height, receipt.account,
|
|
602
|
+
seen_at=seen_at, not_after=not_after)
|
|
603
|
+
if seen_at is None:
|
|
604
|
+
raise UnknownTime(not_after, receipt)
|
|
605
|
+
if seen_at > not_after:
|
|
606
|
+
raise Late(seen_at, not_after, receipt)
|
|
607
|
+
return receipt
|