orangecheck 2.4.0__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.4.0 → orangecheck-2.5.0}/CHANGELOG.md +29 -0
  2. {orangecheck-2.4.0 → orangecheck-2.5.0}/PKG-INFO +1 -1
  3. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/__init__.py +7 -1
  4. orangecheck-2.5.0/orangecheck/address.py +130 -0
  5. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/bond.py +3 -77
  6. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/integrator.py +3 -1
  7. orangecheck-2.5.0/orangecheck/verify_sig.py +280 -0
  8. {orangecheck-2.4.0 → orangecheck-2.5.0}/pyproject.toml +1 -1
  9. orangecheck-2.5.0/tests/fixtures/bip137-parity.json +1082 -0
  10. orangecheck-2.5.0/tests/fixtures/bip322-js-6.1.8.json +1 -0
  11. orangecheck-2.5.0/tests/test_address.py +74 -0
  12. orangecheck-2.5.0/tests/test_ripemd160.py +29 -0
  13. orangecheck-2.5.0/tests/test_signature_parity.py +62 -0
  14. orangecheck-2.4.0/orangecheck/verify_sig.py +0 -68
  15. orangecheck-2.4.0/tests/test_bond_address.py +0 -34
  16. {orangecheck-2.4.0 → orangecheck-2.5.0}/.gitignore +0 -0
  17. {orangecheck-2.4.0 → orangecheck-2.5.0}/README.md +0 -0
  18. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/__main__.py +0 -0
  19. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/canonical.py +0 -0
  20. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/client.py +0 -0
  21. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/errors.py +0 -0
  22. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/__init__.py +0 -0
  23. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/bond.py +0 -0
  24. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/canonical.py +0 -0
  25. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/delegation.py +0 -0
  26. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/envelopes.py +0 -0
  27. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/resolution.py +0 -0
  28. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/pledge/state.py +0 -0
  29. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/py.typed +0 -0
  30. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/top_level.py +0 -0
  31. {orangecheck-2.4.0 → orangecheck-2.5.0}/orangecheck/types.py +0 -0
  32. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/fixtures/bip322-official-basic.json +0 -0
  33. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/fixtures/bip322-official-generated.json +0 -0
  34. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/pledge/__init__.py +0 -0
  35. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/pledge/test_authority.py +0 -0
  36. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/pledge/test_delegation.py +0 -0
  37. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/pledge/test_vectors.py +0 -0
  38. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/pledge/test_wrap.py +0 -0
  39. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/test_bip322_official.py +0 -0
  40. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/test_client.py +0 -0
  41. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/test_client_failure_modes.py +0 -0
  42. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/test_conformance.py +0 -0
  43. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/test_integrator_vectors.py +0 -0
  44. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/index.json +0 -0
  45. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv01.json +0 -0
  46. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv02.json +0 -0
  47. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv03.json +0 -0
  48. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv04.json +0 -0
  49. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv05.json +0 -0
  50. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv06.json +0 -0
  51. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv07.json +0 -0
  52. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv08.json +0 -0
  53. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv09.json +0 -0
  54. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv10.json +0 -0
  55. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv11.json +0 -0
  56. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv12.json +0 -0
  57. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv13.json +0 -0
  58. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv14.json +0 -0
  59. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv15.json +0 -0
  60. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv16.json +0 -0
  61. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv17.json +0 -0
  62. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv18.json +0 -0
  63. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv19.json +0 -0
  64. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv20.json +0 -0
  65. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv21.json +0 -0
  66. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv22.json +0 -0
  67. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv23.json +0 -0
  68. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv24.json +0 -0
  69. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv25.json +0 -0
  70. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv26.json +0 -0
  71. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv27.json +0 -0
  72. {orangecheck-2.4.0 → orangecheck-2.5.0}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,35 @@ 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
+
7
36
  ## [2.4.0] — 2026-10-22
8
37
 
9
38
  ### Changed — an agent pledge is checked as of the time of verification
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 2.4.0
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.4.0"
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})
@@ -0,0 +1,280 @@
1
+ """
2
+ Local Bitcoin message-signature verification, by the rule
3
+ ``@orangecheck/bip322`` verifies by.
4
+
5
+ Opt-in: requires the ``bip322`` package (install via ``pip install
6
+ orangecheck[verify]``), which wraps the Rust ``bitcoin`` / ``secp256k1``
7
+ crates for BIP-322.
8
+
9
+ ``verify_bip322_signature(address, message, signature)`` returns ``True``
10
+ when ``signature`` signs ``message`` for ``address``, ``False`` otherwise.
11
+ Never raises for cryptographic failures — only for a missing optional
12
+ dependency (at import time).
13
+
14
+ - The signature's bytes decide how it is checked. 65 bytes is a legacy
15
+ BIP-137 ``signmessage`` signature, on any address it can stand for
16
+ (P2PKH, P2SH-P2WPKH, P2WPKH, P2TR), whatever its header flag says;
17
+ anything else is BIP-322 simple, with or without the finalized BIP's
18
+ ``smp`` prefix. A ``ful`` or ``pof`` signature is not supported.
19
+ - Bech32 addresses verify only in their canonical lowercase spelling; pass
20
+ what a person typed or scanned through
21
+ ``orangecheck.address.normalize_address`` first.
22
+ - BIP-137 recovers the signer's key with integer arithmetic over public
23
+ values, then ``cryptography`` (OpenSSL) checks the signature against that
24
+ key, so a mistake in the recovery can only refuse.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import base64
30
+ import hashlib
31
+ import re
32
+ from typing import Optional, Tuple
33
+
34
+ from cryptography.exceptions import InvalidSignature
35
+ from cryptography.hazmat.primitives import hashes
36
+ from cryptography.hazmat.primitives.asymmetric import ec
37
+ from cryptography.hazmat.primitives.asymmetric.utils import Prehashed, encode_dss_signature
38
+
39
+ from .address import DecodedAddress, decode_address
40
+
41
+ try:
42
+ import bip322 as _bip322
43
+ except ImportError as e: # pragma: no cover - optional-dep path
44
+ raise ImportError(
45
+ "orangecheck.verify_sig requires the `bip322` package. "
46
+ "Install with `pip install orangecheck[verify]`."
47
+ ) from e
48
+
49
+ _P = 2**256 - 2**32 - 977
50
+ _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
51
+ _G = (
52
+ 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
53
+ 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
54
+ )
55
+ Point = Optional[Tuple[int, int]]
56
+
57
+
58
+ def _add(a: Point, b: Point) -> Point:
59
+ if a is None:
60
+ return b
61
+ if b is None:
62
+ return a
63
+ if a[0] == b[0] and (a[1] + b[1]) % _P == 0:
64
+ return None
65
+ if a == b:
66
+ lam = 3 * a[0] * a[0] * pow(2 * a[1], -1, _P)
67
+ else:
68
+ lam = (b[1] - a[1]) * pow(b[0] - a[0], -1, _P)
69
+ x = (lam * lam - a[0] - b[0]) % _P
70
+ return (x, (lam * (a[0] - x) - a[1]) % _P)
71
+
72
+
73
+ def _mul(k: int, point: Point) -> Point:
74
+ out: Point = None
75
+ while k:
76
+ if k & 1:
77
+ out = _add(out, point)
78
+ point = _add(point, point)
79
+ k >>= 1
80
+ return out
81
+
82
+
83
+ def _lift_x(x: int, odd: int) -> Point:
84
+ if x >= _P:
85
+ return None
86
+ y2 = (pow(x, 3, _P) + 7) % _P
87
+ y = pow(y2, (_P + 1) // 4, _P)
88
+ if y * y % _P != y2:
89
+ return None
90
+ return (x, y if y & 1 == odd else _P - y)
91
+
92
+
93
+ def _sec(point: Tuple[int, int], compressed: bool = True) -> bytes:
94
+ x = point[0].to_bytes(32, "big")
95
+ if compressed:
96
+ return bytes([2 + (point[1] & 1)]) + x
97
+ return b"\x04" + x + point[1].to_bytes(32, "big")
98
+
99
+
100
+ # RIPEMD-160 for hashlib builds without it (OpenSSL 3.0.0–3.0.6 dropped it).
101
+ _RL = [
102
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
103
+ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
104
+ 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
105
+ 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
106
+ 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13,
107
+ ] # fmt: skip
108
+ _RR = [
109
+ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
110
+ 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
111
+ 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
112
+ 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
113
+ 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11,
114
+ ] # fmt: skip
115
+ _SL = [
116
+ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
117
+ 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
118
+ 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
119
+ 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
120
+ 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6,
121
+ ] # fmt: skip
122
+ _SR = [
123
+ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
124
+ 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
125
+ 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
126
+ 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
127
+ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11,
128
+ ] # fmt: skip
129
+ _KL = (0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E)
130
+ _KR = (0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000)
131
+ _M = 0xFFFFFFFF
132
+
133
+
134
+ def _ripemd160_py(data: bytes) -> bytes:
135
+ def f(j: int, x: int, y: int, z: int) -> int:
136
+ if j < 16:
137
+ return x ^ y ^ z
138
+ if j < 32:
139
+ return (x & y) | (~x & z)
140
+ if j < 48:
141
+ return (x | ~y) ^ z
142
+ if j < 64:
143
+ return (x & z) | (y & ~z)
144
+ return x ^ (y | ~z)
145
+
146
+ def rol(x: int, n: int) -> int:
147
+ return ((x << n) | (x >> (32 - n))) & _M
148
+
149
+ msg = data + b"\x80" + b"\0" * ((55 - len(data)) % 64) + (8 * len(data)).to_bytes(8, "little")
150
+ h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
151
+ for block in range(0, len(msg), 64):
152
+ x = [int.from_bytes(msg[block + 4 * i : block + 4 * i + 4], "little") for i in range(16)]
153
+ al, bl, cl, dl, el = h
154
+ ar, br, cr, dr, er = h
155
+ for j in range(80):
156
+ t = (rol((al + (f(j, bl, cl, dl) & _M) + x[_RL[j]] + _KL[j // 16]) & _M, _SL[j]) + el) & _M
157
+ al, el, dl, cl, bl = el, dl, rol(cl, 10), bl, t
158
+ t = (rol((ar + (f(79 - j, br, cr, dr) & _M) + x[_RR[j]] + _KR[j // 16]) & _M, _SR[j]) + er) & _M
159
+ ar, er, dr, cr, br = er, dr, rol(cr, 10), br, t
160
+ h = [
161
+ (h[1] + cl + dr) & _M,
162
+ (h[2] + dl + er) & _M,
163
+ (h[3] + el + ar) & _M,
164
+ (h[4] + al + br) & _M,
165
+ (h[0] + bl + cr) & _M,
166
+ ]
167
+ return b"".join(v.to_bytes(4, "little") for v in h)
168
+
169
+
170
+ def _hash160(data: bytes) -> bytes:
171
+ sha = hashlib.sha256(data).digest()
172
+ try:
173
+ return hashlib.new("ripemd160", sha).digest()
174
+ except ValueError:
175
+ return _ripemd160_py(sha)
176
+
177
+
178
+ def _bip86_output_key(point: Tuple[int, int]) -> bytes:
179
+ x = point[0].to_bytes(32, "big")
180
+ tag = hashlib.sha256(b"TapTweak").digest()
181
+ tweak = int.from_bytes(hashlib.sha256(tag + tag + x).digest(), "big")
182
+ out = _add(_lift_x(point[0], 0), _mul(tweak, _G))
183
+ return out[0].to_bytes(32, "big") if out and tweak < _N else b""
184
+
185
+
186
+ def _compact_size(n: int) -> bytes:
187
+ if n < 0xFD:
188
+ return bytes([n])
189
+ if n <= 0xFFFF:
190
+ return b"\xfd" + n.to_bytes(2, "little")
191
+ return b"\xfe" + n.to_bytes(4, "little")
192
+
193
+
194
+ def _decode_base64(s: str) -> bytes:
195
+ """Standard or URL-safe, padded or not; empty when it is not base64."""
196
+ clean = re.sub(r"\s+", "", s).replace("-", "+").replace("_", "/").rstrip("=")
197
+ if not re.fullmatch(r"[A-Za-z0-9+/]*", clean) or len(clean) % 4 == 1:
198
+ return b""
199
+ return base64.b64decode(clean + "=" * (-len(clean) % 4))
200
+
201
+
202
+ def _verify_bip137(addr: DecodedAddress, message: str, sig: bytes) -> bool:
203
+ flag = sig[0] - 27
204
+ if not 0 <= flag <= 15:
205
+ return False
206
+ msg = message.encode("utf-8")
207
+ digest = hashlib.sha256(
208
+ hashlib.sha256(b"\x18Bitcoin Signed Message:\n" + _compact_size(len(msg)) + msg).digest()
209
+ ).digest()
210
+ r = int.from_bytes(sig[1:33], "big")
211
+ s = int.from_bytes(sig[33:65], "big")
212
+ if not (0 < r < _N and 0 < s < _N):
213
+ return False
214
+ big_r = _lift_x(r + (_N if flag & 2 else 0), flag & 1)
215
+ if big_r is None:
216
+ return False
217
+ rinv = pow(r, -1, _N)
218
+ z = int.from_bytes(digest, "big")
219
+ key = _add(_mul(s * rinv % _N, big_r), _mul(-z * rinv % _N, _G))
220
+ if key is None:
221
+ return False
222
+ try:
223
+ public = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), _sec(key))
224
+ public.verify(encode_dss_signature(r, s), digest, ec.ECDSA(Prehashed(hashes.SHA256())))
225
+ except (InvalidSignature, ValueError):
226
+ return False
227
+ compressed = _sec(key)
228
+ if addr.type == "p2pkh":
229
+ return addr.program in (_hash160(compressed), _hash160(_sec(key, compressed=False)))
230
+ if addr.type == "p2sh":
231
+ return _hash160(b"\x00\x14" + _hash160(compressed)) == addr.program
232
+ if addr.type == "p2wpkh":
233
+ return _hash160(compressed) == addr.program
234
+ if addr.type == "p2tr":
235
+ return _bip86_output_key(key) == addr.program
236
+ return False
237
+
238
+
239
+ def verify_bip322_signature(address: str, message: str, signature: str) -> bool:
240
+ """
241
+ Verify a Bitcoin message signature: BIP-322 simple or legacy BIP-137.
242
+
243
+ Parameters
244
+ ----------
245
+ address:
246
+ Bitcoin address the signature claims to be from, in its canonical
247
+ spelling (bech32 lowercase).
248
+ message:
249
+ The exact bytes (as UTF-8 string) that were signed. For OrangeCheck
250
+ attestations this is the canonical message produced by
251
+ ``build_canonical_message``.
252
+ signature:
253
+ Base64, standard or URL-safe: a BIP-322 simple signature, with or
254
+ without the finalized BIP's ``smp`` prefix, or a 65-byte BIP-137
255
+ signature. Hex is NOT accepted — normalize to base64 before calling.
256
+
257
+ Returns
258
+ -------
259
+ True if the signature verifies; False otherwise. Never raises for
260
+ invalid / malformed signatures.
261
+ """
262
+ addr = decode_address(address)
263
+ if addr is None or signature.startswith(("ful", "pof")):
264
+ return False
265
+ prefixed = signature.startswith("smp")
266
+ sig = _decode_base64(signature[3:] if prefixed else signature)
267
+ if not sig:
268
+ return False
269
+ # No valid witness serializes to 65 bytes, so a 65-byte blob is BIP-137.
270
+ if not prefixed and (addr.type == "p2pkh" or len(sig) == 65):
271
+ return _verify_bip137(addr, message, sig)
272
+ try:
273
+ _bip322.verify_simple_encoded(address, message, base64.b64encode(sig).decode("ascii"))
274
+ except _bip322.VerificationError:
275
+ return False
276
+ except Exception:
277
+ # Any other surprise (unusual address shape, a witness the bridge
278
+ # cannot parse) counts as "not a valid sig" for our purposes.
279
+ return False
280
+ return True
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "orangecheck"
7
- version = "2.4.0"
7
+ version = "2.5.0"
8
8
  description = "Python SDK for OrangeCheck — proof of Bitcoin stake, the OC Pledge primitive, and ochk.app sign-in for your backend."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }