picoke 0.1.0rc2__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.
- picoke-0.1.0rc2/LICENSE +21 -0
- picoke-0.1.0rc2/MANIFEST.in +2 -0
- picoke-0.1.0rc2/PKG-INFO +133 -0
- picoke-0.1.0rc2/README.md +117 -0
- picoke-0.1.0rc2/pyproject.toml +32 -0
- picoke-0.1.0rc2/setup.cfg +4 -0
- picoke-0.1.0rc2/setup.py +20 -0
- picoke-0.1.0rc2/src/picoke/__init__.py +0 -0
- picoke-0.1.0rc2/src/picoke/crypto/__init__.py +33 -0
- picoke-0.1.0rc2/src/picoke/crypto/base64.pyi +4 -0
- picoke-0.1.0rc2/src/picoke/crypto/base64.pyx +185 -0
- picoke-0.1.0rc2/src/picoke/crypto/bip137.pyi +10 -0
- picoke-0.1.0rc2/src/picoke/crypto/bip137.pyx +144 -0
- picoke-0.1.0rc2/src/picoke/crypto/ed25519.pyi +3 -0
- picoke-0.1.0rc2/src/picoke/crypto/ed25519.pyx +130 -0
- picoke-0.1.0rc2/src/picoke/crypto/eip712.pyi +2 -0
- picoke-0.1.0rc2/src/picoke/crypto/eip712.pyx +290 -0
- picoke-0.1.0rc2/src/picoke/crypto/keccak.pyi +1 -0
- picoke-0.1.0rc2/src/picoke/crypto/keccak.pyx +102 -0
- picoke-0.1.0rc2/src/picoke/crypto/secp256k1.pyi +4 -0
- picoke-0.1.0rc2/src/picoke/crypto/secp256k1.pyx +77 -0
- picoke-0.1.0rc2/src/picoke/py.typed +0 -0
- picoke-0.1.0rc2/src/picoke/ratelimit.pyi +11 -0
- picoke-0.1.0rc2/src/picoke/ratelimit.pyx +171 -0
- picoke-0.1.0rc2/src/picoke.egg-info/PKG-INFO +133 -0
- picoke-0.1.0rc2/src/picoke.egg-info/SOURCES.txt +35 -0
- picoke-0.1.0rc2/src/picoke.egg-info/dependency_links.txt +1 -0
- picoke-0.1.0rc2/src/picoke.egg-info/requires.txt +5 -0
- picoke-0.1.0rc2/src/picoke.egg-info/top_level.txt +1 -0
- picoke-0.1.0rc2/tests/test_crypto_base64.py +360 -0
- picoke-0.1.0rc2/tests/test_crypto_bip137.py +185 -0
- picoke-0.1.0rc2/tests/test_crypto_ed25519.py +239 -0
- picoke-0.1.0rc2/tests/test_crypto_eip712.py +621 -0
- picoke-0.1.0rc2/tests/test_crypto_exports.py +23 -0
- picoke-0.1.0rc2/tests/test_crypto_keccak.py +69 -0
- picoke-0.1.0rc2/tests/test_crypto_secp256k1.py +153 -0
- picoke-0.1.0rc2/tests/test_ratelimit.py +348 -0
picoke-0.1.0rc2/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 picore contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
picoke-0.1.0rc2/PKG-INFO
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: picoke
|
|
3
|
+
Version: 0.1.0rc2
|
|
4
|
+
License-Expression: MIT
|
|
5
|
+
Project-URL: Repository, https://github.com/ckirua/picoke
|
|
6
|
+
Project-URL: Changelog, https://github.com/ckirua/picoke/blob/main/CHANGELOG.md
|
|
7
|
+
Requires-Python: >=3.14
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: picop<4,>=3.13
|
|
11
|
+
Requires-Dist: pybase64<1.6,>=1.5.2
|
|
12
|
+
Requires-Dist: pycryptodome<4,>=3.24.1
|
|
13
|
+
Requires-Dist: btclib-secp256k1<0.9,>=0.8.0.16
|
|
14
|
+
Requires-Dist: eth-account<0.15,>=0.14
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# picoke
|
|
18
|
+
|
|
19
|
+
picoke provides practical Python utilities. Its six Cython crypto extensions cover Base64, Keccak-256, Ed25519, recoverable secp256k1, EIP-712, and Bitcoin signed messages. The extensions use the CPython C API where needed and delegate underlying operations to OpenSSL libcrypto, pybase64, the standard library, PyCryptodome, btclib-secp256k1, and eth-account. [picop](https://github.com/ckirua/picop) is a runtime dependency. No independent security audit is implied.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
With CPython 3.15 (or 3.14), install from a checkout:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
python3.15 -m pip install .
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Source builds require a C compiler, the target interpreter's development
|
|
31
|
+
headers, and OpenSSL development headers (`openssl/evp.h`) and the libcrypto
|
|
32
|
+
library discoverable by the compiler and linker. The isolated build installs
|
|
33
|
+
Cython and picop's Cython declarations; it does not install these system
|
|
34
|
+
development dependencies. Base64 encoding and Keccak-256 link libcrypto;
|
|
35
|
+
dynamically linked builds need a compatible libcrypto shared library.
|
|
36
|
+
Large Base64 decodes use the `pybase64` runtime dependency on CPython 3.14
|
|
37
|
+
and 3.15; its libbase64 backend selects available SIMD implementations.
|
|
38
|
+
|
|
39
|
+
Wheels are specific to a CPython ABI and platform and include type stubs.
|
|
40
|
+
Cross-platform wheel compatibility and bundled OpenSSL libraries are not
|
|
41
|
+
claimed. There is no pure-Python fallback for the crypto extensions.
|
|
42
|
+
|
|
43
|
+
## Cryptography
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from picoke.crypto import (
|
|
47
|
+
b64decode, b64encode, ed25519_public_key, ed25519_sign,
|
|
48
|
+
ed25519_verify, keccak256,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
assert b64encode(b"foo") == b"Zm9v"
|
|
52
|
+
assert b64decode("Zm9v") == b"foo"
|
|
53
|
+
digest = keccak256(b"hello") # Keccak-256, not SHA3-256
|
|
54
|
+
seed = bytes.fromhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
|
|
55
|
+
public_key = ed25519_public_key(seed)
|
|
56
|
+
signature = ed25519_sign(b"message", seed)
|
|
57
|
+
assert ed25519_verify(b"message", signature, public_key)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Generate production seeds with a cryptographically secure random source; the fixed seed above is only an example. Python `bytes` cannot be guaranteed erased from memory. Signing and key APIs accept bytes; seeds and public keys are 32 bytes, and signatures are 64 bytes. Verification returns `False` for invalid signatures, malformed or noncanonical point encodings, noncanonical scalars and small-order public keys; `TypeError` is raised for non-bytes arguments. Invalid seed lengths raise `ValueError`. Remaining verification follows PyCryptodome's cofactored RFC 8032 behavior; applications must authenticate public keys independently.
|
|
61
|
+
|
|
62
|
+
`b64encode_ascii` returns a `str`; `b64encode` returns `bytes`. Both decoders, `b64decode` and `b64decode_ascii`, accept ASCII `str` and return `bytes`. Decoding follows `base64.b64decode(..., validate=True)` semantics, raising `ValueError` or `binascii.Error` for non-ASCII text, invalid alphabet or rejected padding. Excess-padding behavior follows the running Python version. Base64 is an encoding, not encryption.
|
|
63
|
+
|
|
64
|
+
Short Base64 decodes combine validation and decoding in one native pass.
|
|
65
|
+
Keccak-256 uses the OpenSSL `KECCAK-256` provider for exact `bytes` when
|
|
66
|
+
available, and PyCryptodome otherwise, including for bytes subclasses.
|
|
67
|
+
|
|
68
|
+
### secp256k1 and Bitcoin messages
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from picoke.crypto import (
|
|
72
|
+
bip137_sign_message, bip137_verify_message, privkey_to_address,
|
|
73
|
+
privkey_to_pubkey, recover_pubkey, sign_recoverable,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
private_key = (1).to_bytes(32, "big") # Example only; never use as a real key.
|
|
77
|
+
public_key = privkey_to_pubkey(private_key) # 65-byte uncompressed SEC key
|
|
78
|
+
address = privkey_to_address(private_key) # lowercase Ethereum address
|
|
79
|
+
message = b"example"
|
|
80
|
+
signature = bip137_sign_message(private_key, message)
|
|
81
|
+
assert bip137_verify_message(message, signature, public_key)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`sign_recoverable(private_key, digest)` accepts a 32-byte digest and returns `(r, s, v)` with `v = 27 + recovery_id`; `recover_pubkey(digest, r, s, recovery_id)` accepts IDs 0–3. Bitcoin signing accepts the `address_type` keyword: `p2pkh-uncompressed` (default), `p2pkh`, `p2sh-p2wpkh`, or `p2wpkh`. Verification checks the recovered public key and header/key compression; it does **not** validate a Bitcoin address or prove that the header matches an address.
|
|
85
|
+
|
|
86
|
+
Bitcoin messages use the standard framed, double-SHA-256 digest. This deliberately differs from the legacy function of the same name, which hashes raw input once. Legacy Ethereum addresses also differ: legacy hashed the `0x04` SEC prefix; picoke hashes the 64-byte coordinates as Ethereum requires.
|
|
87
|
+
|
|
88
|
+
### EIP-712
|
|
89
|
+
|
|
90
|
+
`eip712_hash_full_message(full_message)` hashes an EIP-712 envelope with `types`, `primaryType`, `domain` and `message`; `eip712_hash_agent_message(domain, source, connection_id)` uses the legacy Agent schema but requires exactly 32 bytes for `connection_id`. Array values may be lists or tuples. `EIP712Domain` fields must be unique and in canonical order (`name`, `version`, `chainId`, `verifyingContract`, `salt`, omitting absent fields). Canonical Agent inputs use a fixed-schema Cython encoder; other Agent inputs and generic envelopes use eth-account. Mutually recursive type graphs that eth-account cannot resolve remain unsupported. Check the typed data and authenticate the domain before signing: a digest alone does not establish trust.
|
|
91
|
+
|
|
92
|
+
`eth-account` loads on the first call that needs the generic encoder, after picoke validates the input. Importing `picoke.crypto` or hashing a canonical Agent message does not load it.
|
|
93
|
+
|
|
94
|
+
`eth-account` currently constrains PyCryptodome to the 3.x series via `eth-keyfile`; picoke therefore requires PyCryptodome 3.24.1 or newer, below 4. This increases the dependency footprint and differs from the earlier 4.5 baseline; see the [benchmark notes](bench/README.md).
|
|
95
|
+
|
|
96
|
+
## Rate limiting
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from picoke.ratelimit import TokenBucket
|
|
100
|
+
|
|
101
|
+
# Allow a burst of 20 tokens, then refill continuously at 10 tokens per second.
|
|
102
|
+
bucket = TokenBucket(20, refill_amount=10)
|
|
103
|
+
|
|
104
|
+
async def handle_batch() -> None:
|
|
105
|
+
await bucket.acquire(3)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`TokenBucket(capacity, *, refill_amount=1, refill_period_ns=1_000_000_000)` starts
|
|
109
|
+
full and uses a monotonic clock. Constructor settings are exact `int` values in
|
|
110
|
+
`1..2**63 - 1`; acquisition costs are exact `int` values in `1..capacity`.
|
|
111
|
+
Requests are served FIFO, so a large head request can delay smaller ones.
|
|
112
|
+
Cancellation while waiting does not consume tokens; use `asyncio.timeout()` to
|
|
113
|
+
bound a wait. Construct the bucket anywhere, but use it from one asyncio event
|
|
114
|
+
loop only. Importing `picoke.ratelimit` does not load the crypto providers.
|
|
115
|
+
|
|
116
|
+
The Cython implementation uses picop's native nanosecond clock and fixed-width
|
|
117
|
+
arithmetic when scaled capacity fits in 64 bits. Larger settings retain exact
|
|
118
|
+
integer arithmetic. It only allocates a lock when an acquisition has to wait.
|
|
119
|
+
See the [rate-limit benchmarks](bench/README.md#async-token-bucket) for
|
|
120
|
+
workloads and measured tradeoffs.
|
|
121
|
+
|
|
122
|
+
## Python support
|
|
123
|
+
|
|
124
|
+
Target CPython **3.14 and newer**, with **3.15 as the default** for development
|
|
125
|
+
and primary validation. Python versions below 3.14 are out of scope. The initial
|
|
126
|
+
compatibility matrix includes 3.14 and 3.15; newer versions need their own
|
|
127
|
+
validation. Free-threaded support is a goal, not a claim until tested.
|
|
128
|
+
|
|
129
|
+
## Documentation
|
|
130
|
+
|
|
131
|
+
- [Documentation index](docs/README.md)
|
|
132
|
+
- [Project plan](docs/PLAN.md)
|
|
133
|
+
- [Agent guidance](AGENTS.md)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# picoke
|
|
2
|
+
|
|
3
|
+
picoke provides practical Python utilities. Its six Cython crypto extensions cover Base64, Keccak-256, Ed25519, recoverable secp256k1, EIP-712, and Bitcoin signed messages. The extensions use the CPython C API where needed and delegate underlying operations to OpenSSL libcrypto, pybase64, the standard library, PyCryptodome, btclib-secp256k1, and eth-account. [picop](https://github.com/ckirua/picop) is a runtime dependency. No independent security audit is implied.
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Installation
|
|
7
|
+
|
|
8
|
+
With CPython 3.15 (or 3.14), install from a checkout:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
python3.15 -m pip install .
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Source builds require a C compiler, the target interpreter's development
|
|
15
|
+
headers, and OpenSSL development headers (`openssl/evp.h`) and the libcrypto
|
|
16
|
+
library discoverable by the compiler and linker. The isolated build installs
|
|
17
|
+
Cython and picop's Cython declarations; it does not install these system
|
|
18
|
+
development dependencies. Base64 encoding and Keccak-256 link libcrypto;
|
|
19
|
+
dynamically linked builds need a compatible libcrypto shared library.
|
|
20
|
+
Large Base64 decodes use the `pybase64` runtime dependency on CPython 3.14
|
|
21
|
+
and 3.15; its libbase64 backend selects available SIMD implementations.
|
|
22
|
+
|
|
23
|
+
Wheels are specific to a CPython ABI and platform and include type stubs.
|
|
24
|
+
Cross-platform wheel compatibility and bundled OpenSSL libraries are not
|
|
25
|
+
claimed. There is no pure-Python fallback for the crypto extensions.
|
|
26
|
+
|
|
27
|
+
## Cryptography
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from picoke.crypto import (
|
|
31
|
+
b64decode, b64encode, ed25519_public_key, ed25519_sign,
|
|
32
|
+
ed25519_verify, keccak256,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
assert b64encode(b"foo") == b"Zm9v"
|
|
36
|
+
assert b64decode("Zm9v") == b"foo"
|
|
37
|
+
digest = keccak256(b"hello") # Keccak-256, not SHA3-256
|
|
38
|
+
seed = bytes.fromhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
|
|
39
|
+
public_key = ed25519_public_key(seed)
|
|
40
|
+
signature = ed25519_sign(b"message", seed)
|
|
41
|
+
assert ed25519_verify(b"message", signature, public_key)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Generate production seeds with a cryptographically secure random source; the fixed seed above is only an example. Python `bytes` cannot be guaranteed erased from memory. Signing and key APIs accept bytes; seeds and public keys are 32 bytes, and signatures are 64 bytes. Verification returns `False` for invalid signatures, malformed or noncanonical point encodings, noncanonical scalars and small-order public keys; `TypeError` is raised for non-bytes arguments. Invalid seed lengths raise `ValueError`. Remaining verification follows PyCryptodome's cofactored RFC 8032 behavior; applications must authenticate public keys independently.
|
|
45
|
+
|
|
46
|
+
`b64encode_ascii` returns a `str`; `b64encode` returns `bytes`. Both decoders, `b64decode` and `b64decode_ascii`, accept ASCII `str` and return `bytes`. Decoding follows `base64.b64decode(..., validate=True)` semantics, raising `ValueError` or `binascii.Error` for non-ASCII text, invalid alphabet or rejected padding. Excess-padding behavior follows the running Python version. Base64 is an encoding, not encryption.
|
|
47
|
+
|
|
48
|
+
Short Base64 decodes combine validation and decoding in one native pass.
|
|
49
|
+
Keccak-256 uses the OpenSSL `KECCAK-256` provider for exact `bytes` when
|
|
50
|
+
available, and PyCryptodome otherwise, including for bytes subclasses.
|
|
51
|
+
|
|
52
|
+
### secp256k1 and Bitcoin messages
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from picoke.crypto import (
|
|
56
|
+
bip137_sign_message, bip137_verify_message, privkey_to_address,
|
|
57
|
+
privkey_to_pubkey, recover_pubkey, sign_recoverable,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
private_key = (1).to_bytes(32, "big") # Example only; never use as a real key.
|
|
61
|
+
public_key = privkey_to_pubkey(private_key) # 65-byte uncompressed SEC key
|
|
62
|
+
address = privkey_to_address(private_key) # lowercase Ethereum address
|
|
63
|
+
message = b"example"
|
|
64
|
+
signature = bip137_sign_message(private_key, message)
|
|
65
|
+
assert bip137_verify_message(message, signature, public_key)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`sign_recoverable(private_key, digest)` accepts a 32-byte digest and returns `(r, s, v)` with `v = 27 + recovery_id`; `recover_pubkey(digest, r, s, recovery_id)` accepts IDs 0–3. Bitcoin signing accepts the `address_type` keyword: `p2pkh-uncompressed` (default), `p2pkh`, `p2sh-p2wpkh`, or `p2wpkh`. Verification checks the recovered public key and header/key compression; it does **not** validate a Bitcoin address or prove that the header matches an address.
|
|
69
|
+
|
|
70
|
+
Bitcoin messages use the standard framed, double-SHA-256 digest. This deliberately differs from the legacy function of the same name, which hashes raw input once. Legacy Ethereum addresses also differ: legacy hashed the `0x04` SEC prefix; picoke hashes the 64-byte coordinates as Ethereum requires.
|
|
71
|
+
|
|
72
|
+
### EIP-712
|
|
73
|
+
|
|
74
|
+
`eip712_hash_full_message(full_message)` hashes an EIP-712 envelope with `types`, `primaryType`, `domain` and `message`; `eip712_hash_agent_message(domain, source, connection_id)` uses the legacy Agent schema but requires exactly 32 bytes for `connection_id`. Array values may be lists or tuples. `EIP712Domain` fields must be unique and in canonical order (`name`, `version`, `chainId`, `verifyingContract`, `salt`, omitting absent fields). Canonical Agent inputs use a fixed-schema Cython encoder; other Agent inputs and generic envelopes use eth-account. Mutually recursive type graphs that eth-account cannot resolve remain unsupported. Check the typed data and authenticate the domain before signing: a digest alone does not establish trust.
|
|
75
|
+
|
|
76
|
+
`eth-account` loads on the first call that needs the generic encoder, after picoke validates the input. Importing `picoke.crypto` or hashing a canonical Agent message does not load it.
|
|
77
|
+
|
|
78
|
+
`eth-account` currently constrains PyCryptodome to the 3.x series via `eth-keyfile`; picoke therefore requires PyCryptodome 3.24.1 or newer, below 4. This increases the dependency footprint and differs from the earlier 4.5 baseline; see the [benchmark notes](bench/README.md).
|
|
79
|
+
|
|
80
|
+
## Rate limiting
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from picoke.ratelimit import TokenBucket
|
|
84
|
+
|
|
85
|
+
# Allow a burst of 20 tokens, then refill continuously at 10 tokens per second.
|
|
86
|
+
bucket = TokenBucket(20, refill_amount=10)
|
|
87
|
+
|
|
88
|
+
async def handle_batch() -> None:
|
|
89
|
+
await bucket.acquire(3)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`TokenBucket(capacity, *, refill_amount=1, refill_period_ns=1_000_000_000)` starts
|
|
93
|
+
full and uses a monotonic clock. Constructor settings are exact `int` values in
|
|
94
|
+
`1..2**63 - 1`; acquisition costs are exact `int` values in `1..capacity`.
|
|
95
|
+
Requests are served FIFO, so a large head request can delay smaller ones.
|
|
96
|
+
Cancellation while waiting does not consume tokens; use `asyncio.timeout()` to
|
|
97
|
+
bound a wait. Construct the bucket anywhere, but use it from one asyncio event
|
|
98
|
+
loop only. Importing `picoke.ratelimit` does not load the crypto providers.
|
|
99
|
+
|
|
100
|
+
The Cython implementation uses picop's native nanosecond clock and fixed-width
|
|
101
|
+
arithmetic when scaled capacity fits in 64 bits. Larger settings retain exact
|
|
102
|
+
integer arithmetic. It only allocates a lock when an acquisition has to wait.
|
|
103
|
+
See the [rate-limit benchmarks](bench/README.md#async-token-bucket) for
|
|
104
|
+
workloads and measured tradeoffs.
|
|
105
|
+
|
|
106
|
+
## Python support
|
|
107
|
+
|
|
108
|
+
Target CPython **3.14 and newer**, with **3.15 as the default** for development
|
|
109
|
+
and primary validation. Python versions below 3.14 are out of scope. The initial
|
|
110
|
+
compatibility matrix includes 3.14 and 3.15; newer versions need their own
|
|
111
|
+
validation. Free-threaded support is a goal, not a claim until tested.
|
|
112
|
+
|
|
113
|
+
## Documentation
|
|
114
|
+
|
|
115
|
+
- [Documentation index](docs/README.md)
|
|
116
|
+
- [Project plan](docs/PLAN.md)
|
|
117
|
+
- [Agent guidance](AGENTS.md)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "Cython>=3.3.1,<4", "picop>=3.13,<4"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "picoke"
|
|
7
|
+
version = "0.1.0rc2"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
dependencies = [
|
|
13
|
+
"picop>=3.13,<4",
|
|
14
|
+
"pybase64>=1.5.2,<1.6",
|
|
15
|
+
"pycryptodome>=3.24.1,<4",
|
|
16
|
+
"btclib-secp256k1>=0.8.0.16,<0.9",
|
|
17
|
+
"eth-account>=0.14,<0.15",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Repository = "https://github.com/ckirua/picoke"
|
|
22
|
+
Changelog = "https://github.com/ckirua/picoke/blob/main/CHANGELOG.md"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
include-package-data = false
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
where = ["src"]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.package-data]
|
|
31
|
+
picoke = ["py.typed", "*.pyi"]
|
|
32
|
+
"picoke.crypto" = ["*.pyi"]
|
picoke-0.1.0rc2/setup.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Build picoke's extensions from Cython source."""
|
|
2
|
+
|
|
3
|
+
from Cython.Build import cythonize
|
|
4
|
+
from setuptools import Extension, setup
|
|
5
|
+
|
|
6
|
+
modules = ("base64", "keccak", "ed25519", "secp256k1", "eip712", "bip137")
|
|
7
|
+
setup(
|
|
8
|
+
ext_modules=cythonize(
|
|
9
|
+
[Extension("picoke.ratelimit", ["src/picoke/ratelimit.pyx"])] + [
|
|
10
|
+
Extension(
|
|
11
|
+
f"picoke.crypto.{module}",
|
|
12
|
+
[f"src/picoke/crypto/{module}.pyx"],
|
|
13
|
+
libraries=["crypto"] if module in ("base64", "keccak") else [],
|
|
14
|
+
)
|
|
15
|
+
for module in modules
|
|
16
|
+
],
|
|
17
|
+
build_dir="build/cython",
|
|
18
|
+
compiler_directives={"language_level": 3, "annotation_typing": False},
|
|
19
|
+
),
|
|
20
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Encoding, hashing, and signing utilities."""
|
|
2
|
+
|
|
3
|
+
from .base64 import b64decode, b64decode_ascii, b64encode, b64encode_ascii
|
|
4
|
+
from .bip137 import bip137_signed_message_hash, bip137_sign_message, bip137_verify_message
|
|
5
|
+
from .eip712 import eip712_hash_agent_message, eip712_hash_full_message
|
|
6
|
+
from .ed25519 import ed25519_public_key, ed25519_sign, ed25519_verify
|
|
7
|
+
from .keccak import keccak256
|
|
8
|
+
from .secp256k1 import (
|
|
9
|
+
privkey_to_address,
|
|
10
|
+
privkey_to_pubkey,
|
|
11
|
+
recover_pubkey,
|
|
12
|
+
sign_recoverable,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"b64encode",
|
|
17
|
+
"b64encode_ascii",
|
|
18
|
+
"b64decode",
|
|
19
|
+
"b64decode_ascii",
|
|
20
|
+
"keccak256",
|
|
21
|
+
"ed25519_public_key",
|
|
22
|
+
"ed25519_sign",
|
|
23
|
+
"ed25519_verify",
|
|
24
|
+
"privkey_to_address",
|
|
25
|
+
"privkey_to_pubkey",
|
|
26
|
+
"recover_pubkey",
|
|
27
|
+
"sign_recoverable",
|
|
28
|
+
"eip712_hash_agent_message",
|
|
29
|
+
"eip712_hash_full_message",
|
|
30
|
+
"bip137_signed_message_hash",
|
|
31
|
+
"bip137_sign_message",
|
|
32
|
+
"bip137_verify_message",
|
|
33
|
+
]
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Strict standard Base64 encoding and decoding helpers."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import pybase64
|
|
6
|
+
|
|
7
|
+
from cpython.bytes cimport (
|
|
8
|
+
PyBytes_AS_STRING, PyBytes_CheckExact, PyBytes_FromStringAndSize,
|
|
9
|
+
PyBytes_GET_SIZE,
|
|
10
|
+
)
|
|
11
|
+
from cpython.object cimport PyObject_IsInstance
|
|
12
|
+
from cpython.unicode cimport PyUnicode_DecodeASCII, PyUnicode_GET_LENGTH
|
|
13
|
+
from libc.limits cimport INT_MAX
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
cdef extern from "Python.h":
|
|
17
|
+
int PY_VERSION_HEX
|
|
18
|
+
bint PyUnicode_IS_ASCII(object text)
|
|
19
|
+
unsigned char *PyUnicode_1BYTE_DATA(object text)
|
|
20
|
+
object PyUnicode_New(Py_ssize_t size, unsigned int maxchar)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
cdef extern from "openssl/evp.h":
|
|
24
|
+
int EVP_EncodeBlock(unsigned char *out, const unsigned char *data, int size)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
cdef extern from *:
|
|
28
|
+
"""
|
|
29
|
+
/* Compact ASCII only, with a nonempty multiple of four bytes. */
|
|
30
|
+
static int picoke_decode_quartets(const unsigned char *src, Py_ssize_t n,
|
|
31
|
+
int pad, unsigned char *out) {
|
|
32
|
+
static const unsigned char sextet[128] = {
|
|
33
|
+
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
|
|
34
|
+
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
|
|
35
|
+
255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
|
|
36
|
+
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,255,255,255,
|
|
37
|
+
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
|
38
|
+
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
|
|
39
|
+
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
|
|
40
|
+
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255
|
|
41
|
+
};
|
|
42
|
+
const unsigned char *end = src + n - (pad ? 4 : 0);
|
|
43
|
+
for (; src < end; src += 4, out += 3) {
|
|
44
|
+
unsigned a = sextet[src[0]], b = sextet[src[1]];
|
|
45
|
+
unsigned c = sextet[src[2]], d = sextet[src[3]];
|
|
46
|
+
if ((a | b | c | d) & 128) return 0;
|
|
47
|
+
out[0] = (unsigned char)((a << 2) | (b >> 4));
|
|
48
|
+
out[1] = (unsigned char)((b << 4) | (c >> 2));
|
|
49
|
+
out[2] = (unsigned char)((c << 6) | d);
|
|
50
|
+
}
|
|
51
|
+
if (pad) {
|
|
52
|
+
unsigned a = sextet[src[0]], b = sextet[src[1]];
|
|
53
|
+
unsigned c = pad == 1 ? sextet[src[2]] : 0;
|
|
54
|
+
if ((a | b | c) & 128) return 0;
|
|
55
|
+
out[0] = (unsigned char)((a << 2) | (b >> 4));
|
|
56
|
+
if (pad == 1) out[1] = (unsigned char)((b << 4) | (c >> 2));
|
|
57
|
+
}
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
"""
|
|
61
|
+
bint picoke_decode_quartets(const unsigned char *, Py_ssize_t, int, unsigned char *) noexcept
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
cdef object _encode_exact(bytes data, bint ascii_result):
|
|
65
|
+
cdef Py_ssize_t size = PyBytes_GET_SIZE(data)
|
|
66
|
+
cdef Py_ssize_t output_size
|
|
67
|
+
cdef object result
|
|
68
|
+
cdef unsigned char *out
|
|
69
|
+
cdef int written
|
|
70
|
+
|
|
71
|
+
if size == 0:
|
|
72
|
+
return "" if ascii_result else b""
|
|
73
|
+
|
|
74
|
+
# Host-specific measurements showed stdlib wins for large bytes outputs
|
|
75
|
+
# on CPython 3.15. Avoid assuming this crossover on earlier releases;
|
|
76
|
+
# future runtimes conservatively retain their own optimized stdlib path.
|
|
77
|
+
if (PY_VERSION_HEX >= 0x03100000 or
|
|
78
|
+
(PY_VERSION_HEX >= 0x030F0000 and not ascii_result and size >= 2048)):
|
|
79
|
+
result = base64.b64encode(data)
|
|
80
|
+
return result.decode("ascii") if ascii_result else result
|
|
81
|
+
# The return value as well as the input length must fit an EVP int.
|
|
82
|
+
# Delegation also leaves allocation-overflow behavior to the stdlib for
|
|
83
|
+
# inputs outside this native range, without imposing a new size limit.
|
|
84
|
+
if size > (INT_MAX // 4) * 3:
|
|
85
|
+
result = base64.b64encode(data)
|
|
86
|
+
return result.decode("ascii") if ascii_result else result
|
|
87
|
+
output_size = ((size + 2) // 3) * 4
|
|
88
|
+
if ascii_result:
|
|
89
|
+
result = PyUnicode_New(output_size, 127)
|
|
90
|
+
out = PyUnicode_1BYTE_DATA(result)
|
|
91
|
+
else:
|
|
92
|
+
result = PyBytes_FromStringAndSize(NULL, output_size)
|
|
93
|
+
out = <unsigned char *>PyBytes_AS_STRING(result)
|
|
94
|
+
# Both CPython allocations include the trailing NUL slot EVP writes.
|
|
95
|
+
written = EVP_EncodeBlock(
|
|
96
|
+
out, <const unsigned char *>PyBytes_AS_STRING(data), <int>size
|
|
97
|
+
)
|
|
98
|
+
if written != output_size:
|
|
99
|
+
raise RuntimeError("OpenSSL Base64 encoding failed")
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
cdef object _decode_exact(object text):
|
|
104
|
+
cdef Py_ssize_t size
|
|
105
|
+
cdef Py_ssize_t output_size
|
|
106
|
+
cdef int padding = 0
|
|
107
|
+
cdef const unsigned char *source
|
|
108
|
+
cdef unsigned char *out
|
|
109
|
+
cdef object result
|
|
110
|
+
|
|
111
|
+
# libbase64's runtime-selected SIMD path combines validation and decoding.
|
|
112
|
+
# Leave unusual or invalid inputs to binascii for its exact error policy.
|
|
113
|
+
# The crossover is workload/CPU dependent; retain the previous path for
|
|
114
|
+
# short strings and unmeasured future CPython releases.
|
|
115
|
+
if (PY_VERSION_HEX < 0x03100000 and
|
|
116
|
+
PyUnicode_GET_LENGTH(text) >= 2048):
|
|
117
|
+
try:
|
|
118
|
+
return pybase64.b64decode(text, validate=True)
|
|
119
|
+
except binascii.Error:
|
|
120
|
+
return binascii.a2b_base64(text, strict_mode=True)
|
|
121
|
+
|
|
122
|
+
# Host-specific measurements showed stdlib wins at this size on 3.15;
|
|
123
|
+
# use it conservatively for all future interpreter versions.
|
|
124
|
+
if (PY_VERSION_HEX >= 0x03100000 or
|
|
125
|
+
(PY_VERSION_HEX >= 0x030F0000 and
|
|
126
|
+
PyUnicode_GET_LENGTH(text) >= 64)):
|
|
127
|
+
return binascii.a2b_base64(text, strict_mode=True)
|
|
128
|
+
if not PyUnicode_IS_ASCII(text):
|
|
129
|
+
return binascii.a2b_base64(text, strict_mode=True)
|
|
130
|
+
size = PyUnicode_GET_LENGTH(text)
|
|
131
|
+
if size == 0:
|
|
132
|
+
return b""
|
|
133
|
+
if size > INT_MAX or size % 4:
|
|
134
|
+
return binascii.a2b_base64(text, strict_mode=True)
|
|
135
|
+
source = PyUnicode_1BYTE_DATA(text)
|
|
136
|
+
if source[size - 1] == 61:
|
|
137
|
+
padding = 1
|
|
138
|
+
if source[size - 2] == 61:
|
|
139
|
+
padding = 2
|
|
140
|
+
output_size = (size // 4) * 3 - padding
|
|
141
|
+
result = PyBytes_FromStringAndSize(NULL, output_size)
|
|
142
|
+
out = <unsigned char *>PyBytes_AS_STRING(result)
|
|
143
|
+
# No intermediate pad bytes or second validation pass. Delegate unusual
|
|
144
|
+
# input to binascii so its version-specific strict error policy stays intact.
|
|
145
|
+
if not picoke_decode_quartets(source, size, padding, out):
|
|
146
|
+
return binascii.a2b_base64(text, strict_mode=True)
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def b64encode(data: bytes) -> bytes:
|
|
151
|
+
"""Encode bytes using the standard Base64 alphabet and padding."""
|
|
152
|
+
if PyBytes_CheckExact(data):
|
|
153
|
+
return _encode_exact(data, False)
|
|
154
|
+
if not PyObject_IsInstance(data, bytes):
|
|
155
|
+
raise TypeError("data must be bytes")
|
|
156
|
+
return base64.b64encode(data)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def b64encode_ascii(data: bytes) -> str:
|
|
160
|
+
"""Encode bytes to a standard Base64 ASCII string."""
|
|
161
|
+
cdef object encoded
|
|
162
|
+
cdef bytes exact_encoded
|
|
163
|
+
if PyBytes_CheckExact(data):
|
|
164
|
+
return _encode_exact(data, True)
|
|
165
|
+
encoded = b64encode(data)
|
|
166
|
+
if PyBytes_CheckExact(encoded):
|
|
167
|
+
exact_encoded = encoded
|
|
168
|
+
return <str>PyUnicode_DecodeASCII(
|
|
169
|
+
PyBytes_AS_STRING(exact_encoded), PyBytes_GET_SIZE(exact_encoded), NULL
|
|
170
|
+
)
|
|
171
|
+
return encoded.decode("ascii")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def b64decode(text: str) -> bytes:
|
|
175
|
+
"""Strictly decode a standard Base64 string."""
|
|
176
|
+
if type(text) is str:
|
|
177
|
+
return _decode_exact(text)
|
|
178
|
+
if not PyObject_IsInstance(text, str):
|
|
179
|
+
raise TypeError("text must be str")
|
|
180
|
+
return base64.b64decode(text, validate=True)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def b64decode_ascii(text: str) -> bytes:
|
|
184
|
+
"""Strictly decode a standard Base64 string (legacy API spelling)."""
|
|
185
|
+
return b64decode(text)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
def bip137_signed_message_hash(message: bytes) -> bytes: ...
|
|
4
|
+
def bip137_sign_message(
|
|
5
|
+
privkey: bytes,
|
|
6
|
+
message: bytes,
|
|
7
|
+
*,
|
|
8
|
+
address_type: Literal["p2pkh-uncompressed", "p2pkh", "p2sh-p2wpkh", "p2wpkh"] = "p2pkh-uncompressed",
|
|
9
|
+
) -> bytes: ...
|
|
10
|
+
def bip137_verify_message(message: bytes, signature_b64: bytes | str, pubkey: bytes) -> bool: ...
|