orangecheck 2.3.1__tar.gz → 2.5.0__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.
Files changed (72) hide show
  1. {orangecheck-2.3.1 → orangecheck-2.5.0}/CHANGELOG.md +47 -0
  2. {orangecheck-2.3.1 → orangecheck-2.5.0}/PKG-INFO +1 -1
  3. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/__init__.py +7 -1
  4. orangecheck-2.5.0/orangecheck/address.py +130 -0
  5. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/bond.py +3 -77
  6. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/integrator.py +3 -1
  7. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/__init__.py +2 -0
  8. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/envelopes.py +79 -2
  9. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/state.py +15 -4
  10. orangecheck-2.5.0/orangecheck/verify_sig.py +280 -0
  11. {orangecheck-2.3.1 → orangecheck-2.5.0}/pyproject.toml +1 -1
  12. orangecheck-2.5.0/tests/fixtures/bip137-parity.json +1082 -0
  13. orangecheck-2.5.0/tests/fixtures/bip322-js-6.1.8.json +1 -0
  14. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/pledge/test_authority.py +22 -0
  15. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/pledge/test_delegation.py +82 -0
  16. orangecheck-2.5.0/tests/test_address.py +74 -0
  17. orangecheck-2.5.0/tests/test_ripemd160.py +29 -0
  18. orangecheck-2.5.0/tests/test_signature_parity.py +62 -0
  19. orangecheck-2.3.1/orangecheck/verify_sig.py +0 -68
  20. orangecheck-2.3.1/tests/test_bond_address.py +0 -34
  21. {orangecheck-2.3.1 → orangecheck-2.5.0}/.gitignore +0 -0
  22. {orangecheck-2.3.1 → orangecheck-2.5.0}/README.md +0 -0
  23. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/__main__.py +0 -0
  24. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/canonical.py +0 -0
  25. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/client.py +0 -0
  26. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/errors.py +0 -0
  27. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/bond.py +0 -0
  28. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/canonical.py +0 -0
  29. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/delegation.py +0 -0
  30. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/pledge/resolution.py +0 -0
  31. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/py.typed +0 -0
  32. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/top_level.py +0 -0
  33. {orangecheck-2.3.1 → orangecheck-2.5.0}/orangecheck/types.py +0 -0
  34. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/fixtures/bip322-official-basic.json +0 -0
  35. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/fixtures/bip322-official-generated.json +0 -0
  36. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/pledge/__init__.py +0 -0
  37. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/pledge/test_vectors.py +0 -0
  38. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/pledge/test_wrap.py +0 -0
  39. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/test_bip322_official.py +0 -0
  40. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/test_client.py +0 -0
  41. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/test_client_failure_modes.py +0 -0
  42. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/test_conformance.py +0 -0
  43. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/test_integrator_vectors.py +0 -0
  44. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/index.json +0 -0
  45. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv01.json +0 -0
  46. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv02.json +0 -0
  47. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv03.json +0 -0
  48. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv04.json +0 -0
  49. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv05.json +0 -0
  50. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv06.json +0 -0
  51. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv07.json +0 -0
  52. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv08.json +0 -0
  53. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv09.json +0 -0
  54. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv10.json +0 -0
  55. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv11.json +0 -0
  56. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv12.json +0 -0
  57. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv13.json +0 -0
  58. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv14.json +0 -0
  59. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv15.json +0 -0
  60. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv16.json +0 -0
  61. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv17.json +0 -0
  62. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv18.json +0 -0
  63. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv19.json +0 -0
  64. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv20.json +0 -0
  65. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv21.json +0 -0
  66. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv22.json +0 -0
  67. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv23.json +0 -0
  68. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv24.json +0 -0
  69. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv25.json +0 -0
  70. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv26.json +0 -0
  71. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv27.json +0 -0
  72. {orangecheck-2.3.1 → orangecheck-2.5.0}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,53 @@ All notable changes to the **`orangecheck`** Python package. Follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [2.5.0] — 2026-10-22
8
+
9
+ ### Fixed — legacy signatures, as @orangecheck/bip322 verifies them
10
+
11
+ - `verify_bip322_signature` verifies a 65-byte legacy BIP-137 `signmessage`
12
+ signature on every address it can stand for: P2PKH (compressed or
13
+ uncompressed key), P2SH-P2WPKH, P2WPKH and P2TR, under any header flag
14
+ (27–42). Before, it refused every legacy signature, P2PKH included. The
15
+ signature's bytes decide: 65 bytes is BIP-137, anything else BIP-322
16
+ simple. It now agrees with `@orangecheck/bip322` on the bip322-js corpus
17
+ that package is held to and on BIP-137 cases across every header range
18
+ and recovery-id parity.
19
+ - BIP-137 recovers the key with integer arithmetic over public values, and
20
+ `cryptography` checks the signature against it. RIPEMD-160 comes from
21
+ hashlib, or a pure-Python fallback where hashlib lacks it.
22
+
23
+ ### Changed — one spelling per address
24
+
25
+ - `verify_bip322_signature` refuses a bech32 address that is not lowercase,
26
+ as `@orangecheck/bip322` does, so one key has one address that verifies.
27
+
28
+ ### Added
29
+
30
+ - `normalize_address(text)`: the canonical spelling of an address a person
31
+ typed or scanned (whitespace dropped, all-capitals bech32 lowercased, base58
32
+ unchanged), or None. Key and compare addresses in this form.
33
+ - `decode_address(address)` returns its type, network and program, or None.
34
+ Bonds read addresses through it.
35
+
36
+ ## [2.4.0] — 2026-10-22
37
+
38
+ ### Changed — an agent pledge is checked as of the time of verification
39
+
40
+ As `@orangecheck/pledge-core` 3.2.0 (SPEC §7.3, §11.12, §4.4).
41
+
42
+ - `verify_pledge` takes `now` (default: the current time). The delegation
43
+ lookup is asked as of `now`, not as of `sworn_at`, and the delegation must
44
+ still be unexpired then. `VerifyOk.as_of` is `{"basis": "now", "now": …}`.
45
+ - `classify_state` leaves out an outcome, or a contradicting one, whose
46
+ `resolved_at` is later than `now`.
47
+
48
+ ### Added
49
+
50
+ - `verify_pledge_as_of_sworn_at` checks a past pledge as of its own
51
+ `sworn_at`, for a history. `as_of` is
52
+ `{"basis": "sworn_at", "sworn_at": …, "anchored": False}`.
53
+
7
54
  ## [2.3.1] — 2026-10-21
8
55
 
9
56
  ### Fixed — signatures from wallets that follow the finalized BIP-322
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 2.3.1
3
+ Version: 2.5.0
4
4
  Summary: Python SDK for OrangeCheck — proof of Bitcoin stake, the OC Pledge primitive, and ochk.app sign-in for your backend.
5
5
  Project-URL: Homepage, https://ochk.io
6
6
  Project-URL: Documentation, https://ochk.io/docs
@@ -40,6 +40,8 @@ from .canonical import (
40
40
  score_v0,
41
41
  )
42
42
 
43
+ from .address import DecodedAddress, decode_address, normalize_address
44
+
43
45
  # Local BIP-322 verification is optional (requires the `bip322` extra).
44
46
  # Expose the function when available; absent otherwise.
45
47
  try:
@@ -97,6 +99,10 @@ __all__ = [
97
99
  "random_nonce",
98
100
  "score_v0",
99
101
  "CanonicalIdentityBinding",
102
+ # Addresses in the one spelling the family verifies and keys by
103
+ "decode_address",
104
+ "normalize_address",
105
+ "DecodedAddress",
100
106
  # Local BIP-322 verification (requires the `[verify]` extra at install time;
101
107
  # the name is re-exported as None when the extra isn't installed so callers
102
108
  # can check `if verify_bip322_signature is not None`).
@@ -133,7 +139,7 @@ __all__ = [
133
139
  "VerificationError",
134
140
  ]
135
141
 
136
- __version__ = "2.3.1"
142
+ __version__ = "2.5.0"
137
143
 
138
144
  # OC Pledge submodule — sibling primitive for forward-looking commitments
139
145
  # bound to a Bitcoin address. Imported here so consumers can write:
@@ -0,0 +1,130 @@
1
+ """
2
+ Bitcoin addresses in the one spelling the family verifies and keys by.
3
+
4
+ ``decode_address`` reads what @orangecheck/bip322's ``decodeAddress`` reads:
5
+ lowercase bech32 (witness versions 0 and 1) and base58 P2PKH/P2SH, on
6
+ mainnet, testnet/signet and regtest. ``normalize_address`` turns what a
7
+ person typed or scanned into that spelling.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import re
14
+ from dataclasses import dataclass
15
+ from typing import Optional
16
+
17
+ _BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
18
+ _BECH32M_CONST = 0x2BC830A3
19
+ _B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
20
+ # Base58 regtest addresses share testnet's version bytes, so they report testnet.
21
+ _B58_VERSIONS = {
22
+ 0x00: ("p2pkh", "mainnet"),
23
+ 0x05: ("p2sh", "mainnet"),
24
+ 0x6F: ("p2pkh", "testnet"),
25
+ 0xC4: ("p2sh", "testnet"),
26
+ }
27
+ _HRP_NETWORKS = {"bc": "mainnet", "tb": "testnet", "bcrt": "regtest"}
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class DecodedAddress:
32
+ #: ``p2pkh``, ``p2sh``, ``p2wpkh``, ``p2wsh`` or ``p2tr``.
33
+ type: str
34
+ #: ``mainnet``, ``testnet`` or ``regtest``.
35
+ network: str
36
+ #: The pubkey hash, script hash, witness program or x-only output key.
37
+ program: bytes
38
+
39
+
40
+ def _polymod(values: list[int]) -> int:
41
+ gen = (0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)
42
+ chk = 1
43
+ for v in values:
44
+ top = chk >> 25
45
+ chk = (chk & 0x1FFFFFF) << 5 ^ v
46
+ for i in range(5):
47
+ chk ^= gen[i] if ((top >> i) & 1) else 0
48
+ return chk
49
+
50
+
51
+ def _five_to_eight(words: list[int]) -> Optional[bytes]:
52
+ """BIP-173 regrouping with strict padding: None when the padding is wrong."""
53
+ acc = bits = 0
54
+ out = bytearray()
55
+ for w in words:
56
+ acc = (acc << 5) | w
57
+ bits += 5
58
+ while bits >= 8:
59
+ bits -= 8
60
+ out.append((acc >> bits) & 0xFF)
61
+ if bits >= 5 or (acc << (8 - bits)) & 0xFF:
62
+ return None
63
+ return bytes(out)
64
+
65
+
66
+ def _decode_segwit(address: str, hrp: str) -> Optional[DecodedAddress]:
67
+ if len(address) > 90 or address.lower() != address:
68
+ return None
69
+ sep = address.rfind("1")
70
+ if address[:sep] != hrp or len(address) - sep < 8:
71
+ return None
72
+ try:
73
+ data = [_BECH32.index(c) for c in address[sep + 1 :]]
74
+ except ValueError:
75
+ return None
76
+ const = _polymod([ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp] + data)
77
+ words = data[:-6]
78
+ if not words:
79
+ return None
80
+ program = _five_to_eight(words[1:])
81
+ if program is None:
82
+ return None
83
+ network = _HRP_NETWORKS[hrp]
84
+ if words[0] == 0 and const == 1 and len(program) in (20, 32):
85
+ return DecodedAddress("p2wpkh" if len(program) == 20 else "p2wsh", network, program)
86
+ if words[0] == 1 and const == _BECH32M_CONST and len(program) == 32:
87
+ return DecodedAddress("p2tr", network, program)
88
+ return None
89
+
90
+
91
+ def _decode_base58(address: str) -> Optional[DecodedAddress]:
92
+ n = 0
93
+ for c in address:
94
+ i = _B58.find(c)
95
+ if i < 0:
96
+ return None
97
+ n = n * 58 + i
98
+ raw = b"\0" * (len(address) - len(address.lstrip("1"))) + n.to_bytes((n.bit_length() + 7) // 8, "big")
99
+ payload, check = raw[:-4], raw[-4:]
100
+ if len(payload) != 21 or payload[0] not in _B58_VERSIONS:
101
+ return None
102
+ if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != check:
103
+ return None
104
+ kind, network = _B58_VERSIONS[payload[0]]
105
+ return DecodedAddress(kind, network, payload[1:])
106
+
107
+
108
+ def decode_address(address: str) -> Optional[DecodedAddress]:
109
+ """
110
+ Decode an address in its canonical spelling, checksum included: bech32
111
+ lowercase only, so one key never has two addresses that verify. None for
112
+ anything else, uppercase bech32 included; pass what a person typed or
113
+ scanned through ``normalize_address`` first.
114
+ """
115
+ m = re.match(r"^(bc|tb|bcrt)1", address)
116
+ return _decode_segwit(address, m.group(1)) if m else _decode_base58(address)
117
+
118
+
119
+ def normalize_address(text: str) -> Optional[str]:
120
+ """
121
+ The canonical spelling of an address a person typed or scanned:
122
+ surrounding whitespace dropped, all-capitals bech32 lowercased (QR codes
123
+ carry it that way, which BIP-173 allows), base58 unchanged. None when the
124
+ result is not an address ``decode_address`` reads, mixed-case bech32
125
+ included. Store, key and compare addresses in this form only.
126
+ """
127
+ address = text.strip()
128
+ if re.fullmatch(r"(BC|TB|BCRT)1[^a-z]*", address):
129
+ address = address.lower()
130
+ return address if decode_address(address) else None
@@ -19,6 +19,8 @@ from dataclasses import dataclass
19
19
  from datetime import datetime, timezone
20
20
  from typing import Optional
21
21
 
22
+ from .address import decode_address
23
+
22
24
  HEADER = "orangecheck-bond"
23
25
  ACK = "I back this subject with this coin. It stays in my wallet."
24
26
  FIELDS = ("address", "outpoint", "subject", "nonce", "issued_at", "expires_at")
@@ -35,82 +37,6 @@ _NONCE = re.compile(r"^[0-9a-f]{32}$")
35
37
  _TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
36
38
  _SUBJECT = re.compile(r"^[\x21-\x7e]{1,256}$")
37
39
 
38
- _BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
39
- _BECH32M_CONST = 0x2BC830A3
40
- _B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
41
- _B58_VERSIONS = (0x00, 0x05, 0x6F, 0xC4)
42
-
43
-
44
- def _polymod(values: list[int]) -> int:
45
- gen = (0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)
46
- chk = 1
47
- for v in values:
48
- top = chk >> 25
49
- chk = (chk & 0x1FFFFFF) << 5 ^ v
50
- for i in range(5):
51
- chk ^= gen[i] if ((top >> i) & 1) else 0
52
- return chk
53
-
54
-
55
- def _five_to_eight(words: list[int]) -> Optional[bytes]:
56
- """BIP-173 regrouping with strict padding: None when the padding is wrong."""
57
- acc = bits = 0
58
- out = bytearray()
59
- for w in words:
60
- acc = (acc << 5) | w
61
- bits += 5
62
- while bits >= 8:
63
- bits -= 8
64
- out.append((acc >> bits) & 0xFF)
65
- if bits >= 5 or (acc << (8 - bits)) & 0xFF:
66
- return None
67
- return bytes(out)
68
-
69
-
70
- def _segwit_ok(address: str, hrp: str) -> bool:
71
- if len(address) > 90 or address.lower() != address:
72
- return False
73
- sep = address.rfind("1")
74
- if address[:sep] != hrp or len(address) - sep < 8:
75
- return False
76
- try:
77
- data = [_BECH32.index(c) for c in address[sep + 1 :]]
78
- except ValueError:
79
- return False
80
- const = _polymod([ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp] + data)
81
- words = data[:-6]
82
- if not words:
83
- return False
84
- program = _five_to_eight(words[1:])
85
- if program is None:
86
- return False
87
- if words[0] == 0:
88
- return const == 1 and len(program) in (20, 32)
89
- if words[0] == 1:
90
- return const == _BECH32M_CONST and len(program) == 32
91
- return False
92
-
93
-
94
- def _base58_ok(address: str) -> bool:
95
- n = 0
96
- for c in address:
97
- i = _B58.find(c)
98
- if i < 0:
99
- return False
100
- n = n * 58 + i
101
- raw = b"\0" * (len(address) - len(address.lstrip("1"))) + n.to_bytes((n.bit_length() + 7) // 8, "big")
102
- payload, check = raw[:-4], raw[-4:]
103
- if len(payload) != 21 or payload[0] not in _B58_VERSIONS:
104
- return False
105
- return hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] == check
106
-
107
-
108
- def _address_ok(address: str) -> bool:
109
- """An address @orangecheck/bip322's decodeAddress accepts, checksum included."""
110
- m = re.match(r"^(bc|tb|bcrt)1", address)
111
- return _segwit_ok(address, m.group(1)) if m else _base58_ok(address)
112
-
113
-
114
40
  @dataclass(frozen=True)
115
41
  class BondFields:
116
42
  address: str
@@ -128,7 +54,7 @@ def _when(s: str) -> datetime:
128
54
 
129
55
  def _well_formed(f: BondFields) -> bool:
130
56
  return bool(
131
- _address_ok(f.address)
57
+ decode_address(f.address)
132
58
  and _OUTPOINT.match(f.outpoint)
133
59
  and _SUBJECT.match(f.subject)
134
60
  and _NONCE.match(f.nonce)
@@ -245,7 +245,9 @@ def sign_event(
245
245
  ``body`` must be the exact bytes you send; serialise once and send that
246
246
  string. The key is the signing secret's text as UTF-8 (it is not
247
247
  hex-decoded), and the MAC covers ``f"{t}.{body}"``. me.ochk.io refuses a
248
- timestamp more than 300 seconds from its clock.
248
+ timestamp more than 300 seconds behind its clock or 60 seconds ahead, and
249
+ processes the same signed bytes once: sending them again returns the first
250
+ event, whatever ``Idempotency-Key`` they carry.
249
251
 
250
252
  body = json.dumps({"project_key": key, "subtype": "account_created",
251
253
  "user_address": session.did_oc})
@@ -90,6 +90,7 @@ from .envelopes import (
90
90
  verify_abandonment,
91
91
  verify_outcome,
92
92
  verify_pledge,
93
+ verify_pledge_as_of_sworn_at,
93
94
  wrap_abandonment_envelope,
94
95
  wrap_outcome_envelope,
95
96
  wrap_pledge_envelope,
@@ -139,6 +140,7 @@ __all__ = [
139
140
  # Build / verify
140
141
  "create_pledge",
141
142
  "verify_pledge",
143
+ "verify_pledge_as_of_sworn_at",
142
144
  "create_outcome",
143
145
  "verify_outcome",
144
146
  "create_abandonment",
@@ -11,6 +11,7 @@ or any other adapter of choice.
11
11
  from __future__ import annotations
12
12
 
13
13
  from dataclasses import dataclass
14
+ from datetime import datetime, timezone
14
15
  from typing import Any, Callable, Literal, Optional, Protocol, Union
15
16
 
16
17
  from .canonical import (
@@ -100,6 +101,10 @@ class VerifyOk:
100
101
  # True for an unsigned deterministic outcome: the envelope is a claim, and
101
102
  # the caller must re-evaluate the mechanism against public state (§11.4).
102
103
  recompute_required: bool = False
104
+ # For a pledge, the time the verdict holds for: {"basis": "now", "now": ...}
105
+ # from verify_pledge, {"basis": "sworn_at", "sworn_at": ..., "anchored": False}
106
+ # from verify_pledge_as_of_sworn_at. None for outcomes and abandonments.
107
+ as_of: Optional[dict[str, Any]] = None
103
108
 
104
109
 
105
110
  @dataclass(frozen=True)
@@ -260,6 +265,7 @@ def verify_pledge(
260
265
  delegation_lookup: Optional[Callable[[str, str], Any]] = None,
261
266
  *,
262
267
  skip_delegation_verification: bool = False,
268
+ now: Optional[datetime] = None,
263
269
  ) -> VerifyResult:
264
270
  """
265
271
  Envelope-only verify per SPEC §9.1 steps 1–4.
@@ -275,7 +281,62 @@ def verify_pledge(
275
281
  An agent pledge (``via_delegation``) is refused without a
276
282
  ``delegation_lookup`` unless ``skip_delegation_verification=True`` states
277
283
  that the delegation is not being checked.
284
+
285
+ An agent pledge is checked as of ``now`` (default: the current time): its
286
+ delegation must be in force then. The agent chooses ``sworn_at``, so a
287
+ delegation that has since expired or been revoked cannot date a pledge
288
+ back into its window. ``verify_pledge_as_of_sworn_at`` audits a past
289
+ pledge as of its own ``sworn_at``.
290
+ """
291
+ return _verify_pledge_at(
292
+ envelope,
293
+ verify_bip322,
294
+ skip_signature_verification,
295
+ delegation_lookup,
296
+ skip_delegation_verification,
297
+ now if now is not None else datetime.now(timezone.utc),
298
+ )
299
+
300
+
301
+ def verify_pledge_as_of_sworn_at(
302
+ envelope: dict[str, Any],
303
+ verify_bip322: Optional[VerifyBip322] = None,
304
+ skip_signature_verification: bool = False,
305
+ delegation_lookup: Optional[Callable[[str, str], Any]] = None,
306
+ *,
307
+ skip_delegation_verification: bool = False,
308
+ ) -> VerifyResult:
309
+ """
310
+ Verify a past pledge as of its own ``sworn_at``, for an audit or a
311
+ history. Its signer chose that time, so the verdict holds only if the
312
+ claim is true: ``as_of["anchored"]`` is False, since a v1 pledge carries
313
+ no anchor that fixes it. Never use this to decide whether a pledge counts now.
278
314
  """
315
+ return _verify_pledge_at(
316
+ envelope,
317
+ verify_bip322,
318
+ skip_signature_verification,
319
+ delegation_lookup,
320
+ skip_delegation_verification,
321
+ None,
322
+ )
323
+
324
+
325
+ def _iso_seconds(t: datetime) -> str:
326
+ if t.tzinfo is None:
327
+ t = t.replace(tzinfo=timezone.utc)
328
+ return t.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
329
+
330
+
331
+ def _verify_pledge_at(
332
+ envelope: dict[str, Any],
333
+ verify_bip322: Optional[VerifyBip322],
334
+ skip_signature_verification: bool,
335
+ delegation_lookup: Optional[Callable[[str, str], Any]],
336
+ skip_delegation_verification: bool,
337
+ now: Optional[datetime],
338
+ ) -> VerifyResult:
339
+ """``now`` None: the audit form, checked as of the pledge's own sworn_at."""
279
340
  if envelope.get("v") != ENVELOPE_VERSION:
280
341
  return _err("E_UNSUPPORTED_VERSION", f"pledge envelope v={envelope.get('v')!r} not supported")
281
342
 
@@ -338,7 +399,9 @@ def verify_pledge(
338
399
  )
339
400
  import inspect
340
401
 
341
- result = delegation_lookup(envelope["via_delegation"], envelope["sworn_at"])
402
+ # The lookup checks the delegation, and any revocation of it, as of `at`.
403
+ at = envelope["sworn_at"] if now is None else _iso_seconds(now)
404
+ result = delegation_lookup(envelope["via_delegation"], at)
342
405
  if inspect.isawaitable(result):
343
406
  # Async lookup not supported here (verify_pledge is sync). Wrap
344
407
  # in your event loop or pre-resolve before calling. We surface a
@@ -369,12 +432,26 @@ def verify_pledge(
369
432
  "E_DELEGATION_EXPIRED",
370
433
  f"delegation.expires_at ({delegation.expires_at}) <= pledge.sworn_at ({envelope['sworn_at']})",
371
434
  )
435
+ if now is not None and not iso_utc_greater_than(delegation.expires_at, at):
436
+ return _err(
437
+ "E_DELEGATION_EXPIRED",
438
+ f"delegation.expires_at ({delegation.expires_at}) <= now ({at})",
439
+ )
372
440
  scope_check = check_pledge_create_scope(envelope, delegation)
373
441
  if not scope_check.ok:
374
442
  return _err(scope_check.code, scope_check.reason)
375
443
 
444
+ as_of: dict[str, Any] = (
445
+ {"basis": "sworn_at", "sworn_at": envelope["sworn_at"], "anchored": False}
446
+ if now is None
447
+ else {"basis": "now", "now": _iso_seconds(now)}
448
+ )
376
449
  return VerifyOk(
377
- ok=True, envelope=envelope, canonical_message=canonical_message, id=declared_id
450
+ ok=True,
451
+ envelope=envelope,
452
+ canonical_message=canonical_message,
453
+ id=declared_id,
454
+ as_of=as_of,
378
455
  )
379
456
 
380
457
 
@@ -58,7 +58,12 @@ def classify_state(
58
58
  # verify_abandonment()/verify_outcome() with the pledge supplied.
59
59
  pledge_id = pledge.get("id")
60
60
  swearer = (pledge.get("swearer") or {}).get("address")
61
- if outcome is not None and outcome.get("pledge_id") != pledge_id:
61
+ # An outcome dated after `now` describes a resolution that has not happened
62
+ # yet, so it does not classify the pledge until then.
63
+ def in_force(o: dict[str, Any]) -> bool:
64
+ return o.get("pledge_id") == pledge_id and not _dated_after(o.get("resolved_at"), now_ms)
65
+
66
+ if outcome is not None and not in_force(outcome):
62
67
  outcome = None
63
68
  if abandonment is not None and (
64
69
  abandonment.get("pledge_id") != pledge_id
@@ -73,9 +78,7 @@ def classify_state(
73
78
  # Contradictory outcome envelopes from authorized resolvers → disputed.
74
79
  if outcome is not None and contradictory_outcomes:
75
80
  for other in contradictory_outcomes:
76
- if other.get("pledge_id") == pledge_id and other.get("outcome") != outcome.get(
77
- "outcome"
78
- ):
81
+ if in_force(other) and other.get("outcome") != outcome.get("outcome"):
79
82
  return "disputed"
80
83
 
81
84
  if outcome is not None:
@@ -111,6 +114,14 @@ def _normalize_resolves_at(
111
114
  return None
112
115
 
113
116
 
117
+ def _dated_after(iso: Any, now_ms: int) -> bool:
118
+ """True when ``iso`` is later than ``now_ms``, or not a timestamp at all."""
119
+ try:
120
+ return _parse_utc(iso) > now_ms
121
+ except (TypeError, ValueError):
122
+ return True
123
+
124
+
114
125
  def _parse_utc(s: str) -> int:
115
126
  """Parse strict ISO 8601 UTC (YYYY-MM-DDTHH:MM:SSZ) into epoch ms.
116
127