aionwc 0.1.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.
- aionwc-0.1.0/LICENSE +22 -0
- aionwc-0.1.0/PKG-INFO +132 -0
- aionwc-0.1.0/README.md +111 -0
- aionwc-0.1.0/pyproject.toml +59 -0
- aionwc-0.1.0/src/aionwc/__init__.py +21 -0
- aionwc-0.1.0/src/aionwc/_encryption.py +157 -0
- aionwc-0.1.0/src/aionwc/_libcrypto.py +85 -0
- aionwc-0.1.0/src/aionwc/_native_secp256k1.py +225 -0
- aionwc-0.1.0/src/aionwc/_protocol.py +193 -0
- aionwc-0.1.0/src/aionwc/_secp256k1.py +156 -0
- aionwc-0.1.0/src/aionwc/client.py +303 -0
- aionwc-0.1.0/src/aionwc/errors.py +41 -0
- aionwc-0.1.0/src/aionwc/py.typed +0 -0
aionwc-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sats-Lottu
|
|
4
|
+
Copyright (c) 2026 eddieoz (portions derived from nwc-agent)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
aionwc-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aionwc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python client for Lightning wallets using Nostr Wallet Connect
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: nostr,nwc,lightning,bitcoin,asyncio
|
|
8
|
+
Author: Sats-Lottu
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Provides-Extra: nip04-fallback
|
|
15
|
+
Requires-Dist: pyaes (>=1.6.1,<2) ; extra == "nip04-fallback"
|
|
16
|
+
Requires-Dist: websockets (>=15,<17)
|
|
17
|
+
Project-URL: Issues, https://github.com/Sats-Lottu/aionwc/issues
|
|
18
|
+
Project-URL: Repository, https://github.com/Sats-Lottu/aionwc
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# aionwc
|
|
22
|
+
|
|
23
|
+
`aionwc` is an asyncio client for Lightning wallets that expose
|
|
24
|
+
[Nostr Wallet Connect (NIP-47)](https://github.com/nostr-protocol/nips/blob/master/47.md).
|
|
25
|
+
It requires Python 3.11 or later and a wallet-generated
|
|
26
|
+
`nostr+walletconnect://` URI. The URI contains a private key. Store it as a
|
|
27
|
+
secret and keep it out of logs and source control.
|
|
28
|
+
|
|
29
|
+
The package depends on `websockets` for async relay transport. For legacy
|
|
30
|
+
NIP-04, it uses AES-256-CBC from OpenSSL's `libcrypto`. Install the
|
|
31
|
+
`nip04-fallback` extra to provide `pyaes` on systems where OpenSSL AES
|
|
32
|
+
is unavailable. NIP-44 works independently of both AES backends.
|
|
33
|
+
|
|
34
|
+
For secp256k1, the client prefers the system's `libsecp256k1` with ECDH,
|
|
35
|
+
extrakeys and Schnorr support. The next choice is OpenSSL's `libcrypto`,
|
|
36
|
+
which performs the curve operations in ECDH and the Python BIP340
|
|
37
|
+
implementation. The client can fall back to Python curve arithmetic when
|
|
38
|
+
neither shared library is available. The Python arithmetic uses variable
|
|
39
|
+
execution time. On Windows, the client looks for `secp256k1.dll` or
|
|
40
|
+
`libsecp256k1.dll` on the system search path and can use the OpenSSL DLL
|
|
41
|
+
bundled with CPython.
|
|
42
|
+
|
|
43
|
+
To install a local build, run `poetry build` followed by
|
|
44
|
+
`pip install dist/aionwc-0.1.0-py3-none-any.whl`. To include the fallback,
|
|
45
|
+
use `pip install "dist/aionwc-0.1.0-py3-none-any.whl[nip04-fallback]"`.
|
|
46
|
+
|
|
47
|
+
## Documentation
|
|
48
|
+
|
|
49
|
+
The [documentation source](https://github.com/Sats-Lottu/aionwc/tree/main/docs) includes a quickstart, wallet
|
|
50
|
+
operations, encryption compatibility, and a generated API reference.
|
|
51
|
+
The [development guide](https://github.com/Sats-Lottu/aionwc/blob/main/docs/development.rst) covers publishing it on
|
|
52
|
+
Read the Docs Community.
|
|
53
|
+
|
|
54
|
+
```console
|
|
55
|
+
poetry install --with docs
|
|
56
|
+
poetry run sphinx-build -M html docs docs/_build -W --keep-going
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Open `docs/_build/html/index.html` to preview the generated site.
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
import os
|
|
66
|
+
|
|
67
|
+
from aionwc import NWCClient
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def main():
|
|
71
|
+
wallet = NWCClient(os.environ["NWC_URI"])
|
|
72
|
+
info, balance_msat = await asyncio.gather(
|
|
73
|
+
wallet.get_info(),
|
|
74
|
+
wallet.get_balance(),
|
|
75
|
+
)
|
|
76
|
+
print(info.get("alias"), balance_msat)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
asyncio.run(main())
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- `get_info()` returns wallet metadata and the available methods.
|
|
83
|
+
- `get_balance()` returns the balance as an integer in millisatoshis.
|
|
84
|
+
- `make_invoice(amount_msat, description="...")` creates a BOLT11 invoice.
|
|
85
|
+
- `pay_invoice(invoice)` pays a BOLT11 invoice and returns the wallet's confirmation.
|
|
86
|
+
- `lookup_invoice(payment_hash=...)` or `lookup_invoice(invoice=...)` returns invoice details.
|
|
87
|
+
- `list_transactions(transaction_type="incoming", limit=10)` returns a list of transactions.
|
|
88
|
+
- `request(method, params)` calls an additional method supported by the wallet.
|
|
89
|
+
|
|
90
|
+
Invoice and payment methods return the wallet's result dictionary. Each call
|
|
91
|
+
opens and closes its own WebSocket. The default timeout is 30 seconds for the
|
|
92
|
+
entire call. The client prefers NIP-44 v2 when the wallet advertises it and
|
|
93
|
+
uses NIP-04 when it receives no valid wallet information event or the event
|
|
94
|
+
has no encryption tag. To require NIP-44, set
|
|
95
|
+
`NWCClient(uri, encryption="nip44_v2")`.
|
|
96
|
+
|
|
97
|
+
`NWCWalletError` exposes the wallet's `code` and `message`.
|
|
98
|
+
`NWCRelayError` and its subclass `NWCTimeoutError` can carry the signed
|
|
99
|
+
`request_id` if publication was attempted. Requests can move to another relay
|
|
100
|
+
before publication. If a payment times out or the connection drops after
|
|
101
|
+
publication, check its state with `lookup_invoice` before attempting it again.
|
|
102
|
+
|
|
103
|
+
## Development
|
|
104
|
+
|
|
105
|
+
```console
|
|
106
|
+
poetry install --extras nip04-fallback
|
|
107
|
+
poetry run pytest --cov=aionwc --cov-report=term-missing
|
|
108
|
+
poetry check --lock
|
|
109
|
+
poetry build
|
|
110
|
+
poetry run twine check --strict dist/*
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
To run the integration test, start Docker and install the integration
|
|
114
|
+
dependency group. Testcontainers starts LNbits and a local Nostr relay with
|
|
115
|
+
fresh test wallets and LNbits' `FakeWallet` funding source. The setup pulls
|
|
116
|
+
container images and downloads the LNbits NWC Provider extension on first use.
|
|
117
|
+
|
|
118
|
+
```console
|
|
119
|
+
poetry install --with integration
|
|
120
|
+
poetry run pytest -m integration
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The [release guide](https://github.com/Sats-Lottu/aionwc/blob/main/.github/RELEASING.md)
|
|
124
|
+
covers Trusted Publishing and how to validate and publish distributions to PyPI.
|
|
125
|
+
|
|
126
|
+
## Credits
|
|
127
|
+
|
|
128
|
+
`aionwc` is maintained by Sats-Lottu and inspired by eddieoz's
|
|
129
|
+
[nwc-agent](https://github.com/eddieoz/nwc-agent). Portions adapted from
|
|
130
|
+
`nwc-agent` retain their MIT attribution in the license.
|
|
131
|
+
|
|
132
|
+
|
aionwc-0.1.0/README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# aionwc
|
|
2
|
+
|
|
3
|
+
`aionwc` is an asyncio client for Lightning wallets that expose
|
|
4
|
+
[Nostr Wallet Connect (NIP-47)](https://github.com/nostr-protocol/nips/blob/master/47.md).
|
|
5
|
+
It requires Python 3.11 or later and a wallet-generated
|
|
6
|
+
`nostr+walletconnect://` URI. The URI contains a private key. Store it as a
|
|
7
|
+
secret and keep it out of logs and source control.
|
|
8
|
+
|
|
9
|
+
The package depends on `websockets` for async relay transport. For legacy
|
|
10
|
+
NIP-04, it uses AES-256-CBC from OpenSSL's `libcrypto`. Install the
|
|
11
|
+
`nip04-fallback` extra to provide `pyaes` on systems where OpenSSL AES
|
|
12
|
+
is unavailable. NIP-44 works independently of both AES backends.
|
|
13
|
+
|
|
14
|
+
For secp256k1, the client prefers the system's `libsecp256k1` with ECDH,
|
|
15
|
+
extrakeys and Schnorr support. The next choice is OpenSSL's `libcrypto`,
|
|
16
|
+
which performs the curve operations in ECDH and the Python BIP340
|
|
17
|
+
implementation. The client can fall back to Python curve arithmetic when
|
|
18
|
+
neither shared library is available. The Python arithmetic uses variable
|
|
19
|
+
execution time. On Windows, the client looks for `secp256k1.dll` or
|
|
20
|
+
`libsecp256k1.dll` on the system search path and can use the OpenSSL DLL
|
|
21
|
+
bundled with CPython.
|
|
22
|
+
|
|
23
|
+
To install a local build, run `poetry build` followed by
|
|
24
|
+
`pip install dist/aionwc-0.1.0-py3-none-any.whl`. To include the fallback,
|
|
25
|
+
use `pip install "dist/aionwc-0.1.0-py3-none-any.whl[nip04-fallback]"`.
|
|
26
|
+
|
|
27
|
+
## Documentation
|
|
28
|
+
|
|
29
|
+
The [documentation source](https://github.com/Sats-Lottu/aionwc/tree/main/docs) includes a quickstart, wallet
|
|
30
|
+
operations, encryption compatibility, and a generated API reference.
|
|
31
|
+
The [development guide](https://github.com/Sats-Lottu/aionwc/blob/main/docs/development.rst) covers publishing it on
|
|
32
|
+
Read the Docs Community.
|
|
33
|
+
|
|
34
|
+
```console
|
|
35
|
+
poetry install --with docs
|
|
36
|
+
poetry run sphinx-build -M html docs docs/_build -W --keep-going
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Open `docs/_build/html/index.html` to preview the generated site.
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
import os
|
|
46
|
+
|
|
47
|
+
from aionwc import NWCClient
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def main():
|
|
51
|
+
wallet = NWCClient(os.environ["NWC_URI"])
|
|
52
|
+
info, balance_msat = await asyncio.gather(
|
|
53
|
+
wallet.get_info(),
|
|
54
|
+
wallet.get_balance(),
|
|
55
|
+
)
|
|
56
|
+
print(info.get("alias"), balance_msat)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
asyncio.run(main())
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- `get_info()` returns wallet metadata and the available methods.
|
|
63
|
+
- `get_balance()` returns the balance as an integer in millisatoshis.
|
|
64
|
+
- `make_invoice(amount_msat, description="...")` creates a BOLT11 invoice.
|
|
65
|
+
- `pay_invoice(invoice)` pays a BOLT11 invoice and returns the wallet's confirmation.
|
|
66
|
+
- `lookup_invoice(payment_hash=...)` or `lookup_invoice(invoice=...)` returns invoice details.
|
|
67
|
+
- `list_transactions(transaction_type="incoming", limit=10)` returns a list of transactions.
|
|
68
|
+
- `request(method, params)` calls an additional method supported by the wallet.
|
|
69
|
+
|
|
70
|
+
Invoice and payment methods return the wallet's result dictionary. Each call
|
|
71
|
+
opens and closes its own WebSocket. The default timeout is 30 seconds for the
|
|
72
|
+
entire call. The client prefers NIP-44 v2 when the wallet advertises it and
|
|
73
|
+
uses NIP-04 when it receives no valid wallet information event or the event
|
|
74
|
+
has no encryption tag. To require NIP-44, set
|
|
75
|
+
`NWCClient(uri, encryption="nip44_v2")`.
|
|
76
|
+
|
|
77
|
+
`NWCWalletError` exposes the wallet's `code` and `message`.
|
|
78
|
+
`NWCRelayError` and its subclass `NWCTimeoutError` can carry the signed
|
|
79
|
+
`request_id` if publication was attempted. Requests can move to another relay
|
|
80
|
+
before publication. If a payment times out or the connection drops after
|
|
81
|
+
publication, check its state with `lookup_invoice` before attempting it again.
|
|
82
|
+
|
|
83
|
+
## Development
|
|
84
|
+
|
|
85
|
+
```console
|
|
86
|
+
poetry install --extras nip04-fallback
|
|
87
|
+
poetry run pytest --cov=aionwc --cov-report=term-missing
|
|
88
|
+
poetry check --lock
|
|
89
|
+
poetry build
|
|
90
|
+
poetry run twine check --strict dist/*
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
To run the integration test, start Docker and install the integration
|
|
94
|
+
dependency group. Testcontainers starts LNbits and a local Nostr relay with
|
|
95
|
+
fresh test wallets and LNbits' `FakeWallet` funding source. The setup pulls
|
|
96
|
+
container images and downloads the LNbits NWC Provider extension on first use.
|
|
97
|
+
|
|
98
|
+
```console
|
|
99
|
+
poetry install --with integration
|
|
100
|
+
poetry run pytest -m integration
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The [release guide](https://github.com/Sats-Lottu/aionwc/blob/main/.github/RELEASING.md)
|
|
104
|
+
covers Trusted Publishing and how to validate and publish distributions to PyPI.
|
|
105
|
+
|
|
106
|
+
## Credits
|
|
107
|
+
|
|
108
|
+
`aionwc` is maintained by Sats-Lottu and inspired by eddieoz's
|
|
109
|
+
[nwc-agent](https://github.com/eddieoz/nwc-agent). Portions adapted from
|
|
110
|
+
`nwc-agent` retain their MIT attribution in the license.
|
|
111
|
+
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "aionwc"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Async Python client for Lightning wallets using Nostr Wallet Connect"
|
|
5
|
+
authors = [{ name = "Sats-Lottu" }]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = ["nostr", "nwc", "lightning", "bitcoin", "asyncio"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Framework :: AsyncIO",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Typing :: Typed",
|
|
16
|
+
]
|
|
17
|
+
dependencies = [
|
|
18
|
+
"websockets>=15,<17",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
nip04-fallback = ["pyaes>=1.6.1,<2"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Repository = "https://github.com/Sats-Lottu/aionwc"
|
|
26
|
+
Issues = "https://github.com/Sats-Lottu/aionwc/issues"
|
|
27
|
+
|
|
28
|
+
[tool.poetry]
|
|
29
|
+
packages = [{ include = "aionwc", from = "src" }]
|
|
30
|
+
|
|
31
|
+
[tool.poetry.group.dev.dependencies]
|
|
32
|
+
pytest = "^8.4"
|
|
33
|
+
pytest-asyncio = "^1.0"
|
|
34
|
+
twine = "^6.2"
|
|
35
|
+
pytest-cov = "^7.1.0"
|
|
36
|
+
|
|
37
|
+
[tool.poetry.group.docs]
|
|
38
|
+
optional = true
|
|
39
|
+
|
|
40
|
+
[tool.poetry.group.docs.dependencies]
|
|
41
|
+
sphinx = "^8.2.3"
|
|
42
|
+
furo = "^2025.12.19"
|
|
43
|
+
|
|
44
|
+
[tool.poetry.group.integration]
|
|
45
|
+
optional = true
|
|
46
|
+
|
|
47
|
+
[tool.poetry.group.integration.dependencies]
|
|
48
|
+
testcontainers = "^4.14"
|
|
49
|
+
httpx = "^0.28"
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
asyncio_mode = "auto"
|
|
53
|
+
testpaths = ["tests"]
|
|
54
|
+
markers = ["integration: exercises LNbits and a Nostr relay in Docker"]
|
|
55
|
+
addopts = "-m 'not integration'"
|
|
56
|
+
|
|
57
|
+
[build-system]
|
|
58
|
+
requires = ["poetry-core>=2.0,<3.0"]
|
|
59
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Async Nostr Wallet Connect client."""
|
|
2
|
+
|
|
3
|
+
from .client import NWCClient
|
|
4
|
+
from .errors import (
|
|
5
|
+
NWCError,
|
|
6
|
+
NWCProtocolError,
|
|
7
|
+
NWCRelayError,
|
|
8
|
+
NWCTimeoutError,
|
|
9
|
+
NWCURIError,
|
|
10
|
+
NWCWalletError,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"NWCClient",
|
|
15
|
+
"NWCError",
|
|
16
|
+
"NWCProtocolError",
|
|
17
|
+
"NWCRelayError",
|
|
18
|
+
"NWCTimeoutError",
|
|
19
|
+
"NWCURIError",
|
|
20
|
+
"NWCWalletError",
|
|
21
|
+
]
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""NIP-04 and NIP-44 v2 payload encryption, based on nwc-agent."""
|
|
2
|
+
|
|
3
|
+
import hmac
|
|
4
|
+
from base64 import b64decode, b64encode
|
|
5
|
+
from secrets import token_bytes
|
|
6
|
+
from struct import pack, unpack
|
|
7
|
+
|
|
8
|
+
from .errors import NWCProtocolError
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from ._libcrypto import OpenSSLAES256CBC, load_libcrypto
|
|
12
|
+
except ImportError:
|
|
13
|
+
# Some Python builds omit the optional ctypes module.
|
|
14
|
+
_OPENSSL_AES = None
|
|
15
|
+
else:
|
|
16
|
+
_OPENSSL_AES = load_libcrypto(OpenSSLAES256CBC)
|
|
17
|
+
|
|
18
|
+
AES_BLOCK_SIZE = 16
|
|
19
|
+
CHACHA_MASK = 0xFFFFFFFF
|
|
20
|
+
CHACHA_CONSTANTS = unpack("<4I", b"expand 32-byte k")
|
|
21
|
+
CHACHA_ROUND = (
|
|
22
|
+
(0, 4, 8, 12), (1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15),
|
|
23
|
+
(0, 5, 10, 15), (1, 6, 11, 12), (2, 7, 8, 13), (3, 4, 9, 14),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _aes_cbc(key: bytes, iv: bytes, data: bytes, *, encrypt: bool) -> bytes:
|
|
28
|
+
if len(key) != 32:
|
|
29
|
+
raise ValueError("NIP-04 requires a 32-byte AES key")
|
|
30
|
+
if _OPENSSL_AES is not None:
|
|
31
|
+
return _OPENSSL_AES.crypt(key, iv, data, encrypt=encrypt)
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from pyaes import AESModeOfOperationCBC
|
|
35
|
+
except ImportError:
|
|
36
|
+
raise NWCProtocolError(
|
|
37
|
+
"NIP-04 requires OpenSSL AES-256-CBC or the aionwc[nip04-fallback] extra"
|
|
38
|
+
) from None
|
|
39
|
+
|
|
40
|
+
aes = AESModeOfOperationCBC(key, iv)
|
|
41
|
+
if encrypt:
|
|
42
|
+
padding = AES_BLOCK_SIZE - len(data) % AES_BLOCK_SIZE
|
|
43
|
+
data += bytes([padding]) * padding
|
|
44
|
+
crypt_block = aes.encrypt if encrypt else aes.decrypt
|
|
45
|
+
result = b"".join(
|
|
46
|
+
crypt_block(data[offset:offset + AES_BLOCK_SIZE])
|
|
47
|
+
for offset in range(0, len(data), AES_BLOCK_SIZE)
|
|
48
|
+
)
|
|
49
|
+
if encrypt:
|
|
50
|
+
return result
|
|
51
|
+
padding = result[-1]
|
|
52
|
+
if not 1 <= padding <= AES_BLOCK_SIZE or result[-padding:] != bytes([padding]) * padding:
|
|
53
|
+
raise ValueError("Invalid NIP-04 padding")
|
|
54
|
+
return result[:-padding]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def nip04_encrypt(key: bytes, plaintext: str) -> str:
|
|
58
|
+
iv = token_bytes(AES_BLOCK_SIZE)
|
|
59
|
+
ciphertext = _aes_cbc(key, iv, plaintext.encode(), encrypt=True)
|
|
60
|
+
return f"{b64encode(ciphertext).decode()}?iv={b64encode(iv).decode()}"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def nip04_decrypt(key: bytes, payload: str) -> str:
|
|
64
|
+
encoded, separator, encoded_iv = payload.partition("?iv=")
|
|
65
|
+
if not separator:
|
|
66
|
+
raise ValueError("Missing NIP-04 initialization vector")
|
|
67
|
+
ciphertext = b64decode(encoded, validate=True)
|
|
68
|
+
iv = b64decode(encoded_iv, validate=True)
|
|
69
|
+
if len(iv) != AES_BLOCK_SIZE or not ciphertext or len(ciphertext) % AES_BLOCK_SIZE:
|
|
70
|
+
raise ValueError("Invalid NIP-04 payload length")
|
|
71
|
+
return _aes_cbc(key, iv, ciphertext, encrypt=False).decode()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _rotate(value: int, bits: int) -> int:
|
|
75
|
+
return ((value << bits) | (value >> (32 - bits))) & CHACHA_MASK
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _quarter_round(state: list[int], a: int, b: int, c: int, d: int) -> None:
|
|
79
|
+
state[a] = (state[a] + state[b]) & CHACHA_MASK
|
|
80
|
+
state[d] = _rotate(state[d] ^ state[a], 16)
|
|
81
|
+
state[c] = (state[c] + state[d]) & CHACHA_MASK
|
|
82
|
+
state[b] = _rotate(state[b] ^ state[c], 12)
|
|
83
|
+
state[a] = (state[a] + state[b]) & CHACHA_MASK
|
|
84
|
+
state[d] = _rotate(state[d] ^ state[a], 8)
|
|
85
|
+
state[c] = (state[c] + state[d]) & CHACHA_MASK
|
|
86
|
+
state[b] = _rotate(state[b] ^ state[c], 7)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _chacha20_xor(key: bytes, nonce: bytes, data: bytes) -> bytes:
|
|
90
|
+
key_words = unpack("<8I", key)
|
|
91
|
+
nonce_words = unpack("<3I", nonce)
|
|
92
|
+
result = bytearray()
|
|
93
|
+
for counter, start in enumerate(range(0, len(data), 64)):
|
|
94
|
+
state = (*CHACHA_CONSTANTS, *key_words, counter, *nonce_words)
|
|
95
|
+
working = list(state)
|
|
96
|
+
for _ in range(10):
|
|
97
|
+
for indices in CHACHA_ROUND:
|
|
98
|
+
_quarter_round(working, *indices)
|
|
99
|
+
block = pack("<16I", *((a + b) & CHACHA_MASK for a, b in zip(working, state)))
|
|
100
|
+
result.extend(a ^ b for a, b in zip(data[start:start + 64], block))
|
|
101
|
+
return bytes(result)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _message_keys(shared_key: bytes, nonce: bytes) -> tuple[bytes, bytes, bytes]:
|
|
105
|
+
conversation_key = hmac.digest(b"nip44-v2", shared_key, "sha256")
|
|
106
|
+
blocks = []
|
|
107
|
+
previous = b""
|
|
108
|
+
for counter in range(1, 4):
|
|
109
|
+
previous = hmac.digest(conversation_key, previous + nonce + bytes([counter]), "sha256")
|
|
110
|
+
blocks.append(previous)
|
|
111
|
+
keys = b"".join(blocks)
|
|
112
|
+
return keys[:32], keys[32:44], keys[44:76]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _padded_length(length: int) -> int:
|
|
116
|
+
if length <= 32:
|
|
117
|
+
return 32
|
|
118
|
+
next_power = 1 << (length - 1).bit_length()
|
|
119
|
+
chunk = 32 if next_power <= 256 else next_power // 8
|
|
120
|
+
return chunk * ((length + chunk - 1) // chunk)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def nip44_encrypt(key: bytes, plaintext: str, *, nonce: bytes | None = None) -> str:
|
|
124
|
+
data = plaintext.encode()
|
|
125
|
+
length = len(data)
|
|
126
|
+
if not 1 <= length <= 0xFFFFFFFF:
|
|
127
|
+
raise ValueError("Invalid NIP-44 plaintext length")
|
|
128
|
+
nonce = token_bytes(32) if nonce is None else nonce
|
|
129
|
+
if len(nonce) != 32:
|
|
130
|
+
raise ValueError("NIP-44 nonce must be 32 bytes")
|
|
131
|
+
prefix = pack(">H", length) if length < 65536 else b"\x00\x00" + pack(">I", length)
|
|
132
|
+
padded = prefix + data + bytes(_padded_length(length) - length)
|
|
133
|
+
cipher_key, cipher_nonce, mac_key = _message_keys(key, nonce)
|
|
134
|
+
ciphertext = _chacha20_xor(cipher_key, cipher_nonce, padded)
|
|
135
|
+
mac = hmac.digest(mac_key, nonce + ciphertext, "sha256")
|
|
136
|
+
return b64encode(b"\x02" + nonce + ciphertext + mac).decode()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def nip44_decrypt(key: bytes, payload: str) -> str:
|
|
140
|
+
raw = b64decode(payload, validate=True)
|
|
141
|
+
if len(raw) < 99 or raw[0] != 2:
|
|
142
|
+
raise ValueError("Invalid NIP-44 v2 payload")
|
|
143
|
+
nonce, ciphertext, mac = raw[1:33], raw[33:-32], raw[-32:]
|
|
144
|
+
cipher_key, cipher_nonce, mac_key = _message_keys(key, nonce)
|
|
145
|
+
if not hmac.compare_digest(mac, hmac.digest(mac_key, nonce + ciphertext, "sha256")):
|
|
146
|
+
raise ValueError("Invalid NIP-44 authentication code")
|
|
147
|
+
padded = _chacha20_xor(cipher_key, cipher_nonce, ciphertext)
|
|
148
|
+
length = int.from_bytes(padded[:2], "big")
|
|
149
|
+
prefix_size = 2
|
|
150
|
+
if length == 0:
|
|
151
|
+
length = int.from_bytes(padded[2:6], "big")
|
|
152
|
+
prefix_size = 6
|
|
153
|
+
if length < 65536:
|
|
154
|
+
raise ValueError("Invalid NIP-44 extended length")
|
|
155
|
+
if len(padded) != prefix_size + _padded_length(length):
|
|
156
|
+
raise ValueError("Invalid NIP-44 padding")
|
|
157
|
+
return padded[prefix_size:prefix_size + length].decode()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Discovery and bindings for the system OpenSSL shared library."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Callable, Iterator
|
|
5
|
+
from ctypes import CDLL, POINTER, byref, c_int, c_ubyte, c_void_p, memset, string_at
|
|
6
|
+
from ctypes.util import find_library
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TypeVar
|
|
9
|
+
|
|
10
|
+
AES_BLOCK_SIZE = 16
|
|
11
|
+
Backend = TypeVar("Backend")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def bind(library, name, restype, *argtypes):
|
|
15
|
+
function = getattr(library, name)
|
|
16
|
+
function.restype = restype
|
|
17
|
+
function.argtypes = argtypes
|
|
18
|
+
return function
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _libcrypto_paths() -> Iterator[str | Path]:
|
|
22
|
+
if sys.platform == "win32":
|
|
23
|
+
for version in ("4", "3"):
|
|
24
|
+
for suffix in ("-x64", "-arm64", ""):
|
|
25
|
+
name = f"libcrypto-{version}{suffix}"
|
|
26
|
+
if (path := find_library(name)) and Path(path).is_absolute():
|
|
27
|
+
yield path
|
|
28
|
+
bundled = Path(sys.base_prefix) / "DLLs" / f"{name}.dll"
|
|
29
|
+
if bundled.is_file():
|
|
30
|
+
yield bundled
|
|
31
|
+
elif path := find_library("crypto"):
|
|
32
|
+
yield path
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_libcrypto(create_backend: Callable[[CDLL], Backend]) -> Backend | None:
|
|
36
|
+
for path in _libcrypto_paths():
|
|
37
|
+
try:
|
|
38
|
+
return create_backend(CDLL(str(path)))
|
|
39
|
+
except (OSError, AttributeError, ValueError):
|
|
40
|
+
continue
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class OpenSSLAES256CBC:
|
|
45
|
+
"""AES-256-CBC with OpenSSL's standard PKCS#7 padding."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, library: CDLL) -> None:
|
|
48
|
+
self._create = bind(library, "EVP_CIPHER_CTX_new", c_void_p)
|
|
49
|
+
self._free = bind(library, "EVP_CIPHER_CTX_free", None, c_void_p)
|
|
50
|
+
self._init = bind(
|
|
51
|
+
library, "EVP_CipherInit_ex", c_int,
|
|
52
|
+
c_void_p, c_void_p, c_void_p, c_void_p, c_void_p, c_int,
|
|
53
|
+
)
|
|
54
|
+
self._update = bind(
|
|
55
|
+
library, "EVP_CipherUpdate", c_int,
|
|
56
|
+
c_void_p, c_void_p, POINTER(c_int), c_void_p, c_int,
|
|
57
|
+
)
|
|
58
|
+
self._final = bind(library, "EVP_CipherFinal_ex", c_int, c_void_p, c_void_p, POINTER(c_int))
|
|
59
|
+
self._cipher = bind(library, "EVP_aes_256_cbc", c_void_p)()
|
|
60
|
+
if not self._cipher:
|
|
61
|
+
raise ValueError("OpenSSL does not provide AES-256-CBC")
|
|
62
|
+
# OpenSSL can expose this cipher while the active providers cannot initialize it.
|
|
63
|
+
self.crypt(bytes(32), bytes(AES_BLOCK_SIZE), b"", encrypt=True)
|
|
64
|
+
|
|
65
|
+
def crypt(self, key: bytes, iv: bytes, data: bytes, *, encrypt: bool) -> bytes:
|
|
66
|
+
if len(key) != 32 or len(iv) != AES_BLOCK_SIZE:
|
|
67
|
+
raise ValueError("Invalid AES-256-CBC key or IV length")
|
|
68
|
+
if len(data) > (1 << 31) - 1 - AES_BLOCK_SIZE:
|
|
69
|
+
raise ValueError("AES-256-CBC input exceeds the EVP length limit")
|
|
70
|
+
output = (c_ubyte * (len(data) + 2 * AES_BLOCK_SIZE))()
|
|
71
|
+
written, final_size = c_int(), c_int()
|
|
72
|
+
context = self._create()
|
|
73
|
+
if not context:
|
|
74
|
+
raise ValueError("Cannot allocate OpenSSL cipher context")
|
|
75
|
+
try:
|
|
76
|
+
if not self._init(context, self._cipher, None, key, iv, encrypt):
|
|
77
|
+
raise ValueError("Cannot initialize AES-256-CBC")
|
|
78
|
+
if not self._update(context, output, byref(written), data, len(data)):
|
|
79
|
+
raise ValueError("Cannot process AES-256-CBC data")
|
|
80
|
+
if not self._final(context, byref(output, written.value), byref(final_size)):
|
|
81
|
+
raise ValueError("Cannot finalize AES-256-CBC data")
|
|
82
|
+
return string_at(output, written.value + final_size.value)
|
|
83
|
+
finally:
|
|
84
|
+
self._free(context)
|
|
85
|
+
memset(output, 0, len(output))
|