aionwc 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aionwc/__init__.py +21 -0
- aionwc/_encryption.py +157 -0
- aionwc/_libcrypto.py +85 -0
- aionwc/_native_secp256k1.py +225 -0
- aionwc/_protocol.py +193 -0
- aionwc/_secp256k1.py +156 -0
- aionwc/client.py +303 -0
- aionwc/errors.py +41 -0
- aionwc/py.typed +0 -0
- aionwc-0.1.0.dist-info/METADATA +132 -0
- aionwc-0.1.0.dist-info/RECORD +13 -0
- aionwc-0.1.0.dist-info/WHEEL +4 -0
- aionwc-0.1.0.dist-info/licenses/LICENSE +22 -0
aionwc/__init__.py
ADDED
|
@@ -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
|
+
]
|
aionwc/_encryption.py
ADDED
|
@@ -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()
|
aionwc/_libcrypto.py
ADDED
|
@@ -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))
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Bindings to optional system implementations of secp256k1."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from contextlib import ExitStack
|
|
5
|
+
from ctypes import (
|
|
6
|
+
CDLL,
|
|
7
|
+
CFUNCTYPE,
|
|
8
|
+
Structure,
|
|
9
|
+
byref,
|
|
10
|
+
c_char_p,
|
|
11
|
+
c_int,
|
|
12
|
+
c_size_t,
|
|
13
|
+
c_ubyte,
|
|
14
|
+
c_uint,
|
|
15
|
+
c_void_p,
|
|
16
|
+
memmove,
|
|
17
|
+
memset,
|
|
18
|
+
)
|
|
19
|
+
from ctypes.util import find_library
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from secrets import token_bytes
|
|
22
|
+
from weakref import finalize
|
|
23
|
+
|
|
24
|
+
from ._libcrypto import bind as _bind
|
|
25
|
+
from ._libcrypto import load_libcrypto
|
|
26
|
+
|
|
27
|
+
_CONTEXT_NONE = 1
|
|
28
|
+
_POINT_CONVERSION_COMPRESSED = 2
|
|
29
|
+
_ECDH_HASH = CFUNCTYPE(c_int, c_void_p, c_void_p, c_void_p, c_void_p)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@_ECDH_HASH
|
|
33
|
+
def _copy_x(output, x, _y, _data):
|
|
34
|
+
# NIP-04 and NIP-44 use the shared point's X coordinate directly.
|
|
35
|
+
memmove(output, x, 32)
|
|
36
|
+
return 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _SchnorrParameters(Structure):
|
|
40
|
+
_fields_ = [
|
|
41
|
+
("magic", c_ubyte * 4),
|
|
42
|
+
("nonce_function", c_void_p),
|
|
43
|
+
("nonce_data", c_char_p),
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class LibSecp256k1:
|
|
48
|
+
def __init__(self, library: CDLL) -> None:
|
|
49
|
+
self._keypair = _bind(
|
|
50
|
+
library, "secp256k1_keypair_create", c_int, c_void_p, c_void_p, c_void_p
|
|
51
|
+
)
|
|
52
|
+
self._keypair_x = _bind(
|
|
53
|
+
library, "secp256k1_keypair_xonly_pub", c_int, c_void_p, c_void_p, c_void_p, c_void_p
|
|
54
|
+
)
|
|
55
|
+
self._x_serialize = _bind(
|
|
56
|
+
library, "secp256k1_xonly_pubkey_serialize", c_int, c_void_p, c_void_p, c_void_p
|
|
57
|
+
)
|
|
58
|
+
self._x_parse = _bind(
|
|
59
|
+
library, "secp256k1_xonly_pubkey_parse", c_int, c_void_p, c_void_p, c_void_p
|
|
60
|
+
)
|
|
61
|
+
self._parse = _bind(
|
|
62
|
+
library, "secp256k1_ec_pubkey_parse", c_int, c_void_p, c_void_p, c_void_p, c_size_t
|
|
63
|
+
)
|
|
64
|
+
self._ecdh = _bind(
|
|
65
|
+
library, "secp256k1_ecdh", c_int, c_void_p, c_void_p, c_void_p, c_void_p,
|
|
66
|
+
_ECDH_HASH, c_void_p,
|
|
67
|
+
)
|
|
68
|
+
self._sign = _bind(
|
|
69
|
+
library, "secp256k1_schnorrsig_sign_custom", c_int,
|
|
70
|
+
c_void_p, c_void_p, c_void_p, c_size_t, c_void_p, c_void_p,
|
|
71
|
+
)
|
|
72
|
+
self._verify = _bind(
|
|
73
|
+
library, "secp256k1_schnorrsig_verify", c_int,
|
|
74
|
+
c_void_p, c_void_p, c_void_p, c_size_t, c_void_p,
|
|
75
|
+
)
|
|
76
|
+
create = _bind(library, "secp256k1_context_create", c_void_p, c_uint)
|
|
77
|
+
destroy = _bind(library, "secp256k1_context_destroy", None, c_void_p)
|
|
78
|
+
randomize = _bind(library, "secp256k1_context_randomize", c_int, c_void_p, c_void_p)
|
|
79
|
+
self._context = create(_CONTEXT_NONE)
|
|
80
|
+
if not self._context:
|
|
81
|
+
raise OSError("Cannot create libsecp256k1 context")
|
|
82
|
+
cleanup = finalize(self, destroy, self._context)
|
|
83
|
+
if not randomize(self._context, token_bytes(32)):
|
|
84
|
+
cleanup()
|
|
85
|
+
raise OSError("Cannot randomize libsecp256k1 context")
|
|
86
|
+
|
|
87
|
+
def public_key(self, secret: bytes) -> bytes:
|
|
88
|
+
keypair = (c_ubyte * 96)()
|
|
89
|
+
point, output = (c_ubyte * 64)(), (c_ubyte * 32)()
|
|
90
|
+
try:
|
|
91
|
+
if not self._keypair(self._context, keypair, secret):
|
|
92
|
+
raise ValueError("Invalid private key")
|
|
93
|
+
self._keypair_x(self._context, point, None, keypair)
|
|
94
|
+
self._x_serialize(self._context, output, point)
|
|
95
|
+
return bytes(output)
|
|
96
|
+
finally:
|
|
97
|
+
memset(keypair, 0, len(keypair))
|
|
98
|
+
|
|
99
|
+
def shared_secret(self, secret: bytes, peer: bytes) -> bytes:
|
|
100
|
+
point, output = (c_ubyte * 64)(), (c_ubyte * 32)()
|
|
101
|
+
encoded = b"\x02" + peer
|
|
102
|
+
if not self._parse(self._context, point, encoded, len(encoded)):
|
|
103
|
+
raise ValueError("Invalid public key")
|
|
104
|
+
try:
|
|
105
|
+
if not self._ecdh(self._context, output, point, secret, _copy_x, None):
|
|
106
|
+
raise ValueError("Cannot derive shared secret")
|
|
107
|
+
return bytes(output)
|
|
108
|
+
finally:
|
|
109
|
+
memset(output, 0, len(output))
|
|
110
|
+
|
|
111
|
+
def sign(self, secret: bytes, message: bytes, aux: bytes) -> bytes:
|
|
112
|
+
keypair, signature = (c_ubyte * 96)(), (c_ubyte * 64)()
|
|
113
|
+
params = _SchnorrParameters((0xDA, 0x6F, 0xB3, 0x8C), None, aux)
|
|
114
|
+
try:
|
|
115
|
+
if not self._keypair(self._context, keypair, secret):
|
|
116
|
+
raise ValueError("Invalid private key")
|
|
117
|
+
if not self._sign(self._context, signature, message, len(message), keypair, byref(params)):
|
|
118
|
+
raise ValueError("Cannot sign Schnorr message")
|
|
119
|
+
return bytes(signature)
|
|
120
|
+
finally:
|
|
121
|
+
memset(keypair, 0, len(keypair))
|
|
122
|
+
|
|
123
|
+
def verify(self, pubkey: bytes, message: bytes, signature: bytes) -> bool:
|
|
124
|
+
point = (c_ubyte * 64)()
|
|
125
|
+
if not self._x_parse(self._context, point, pubkey):
|
|
126
|
+
return False
|
|
127
|
+
return bool(self._verify(self._context, signature, message, len(message), point))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _allocate(stack, create, release, *args):
|
|
131
|
+
handle = create(*args)
|
|
132
|
+
if not handle:
|
|
133
|
+
raise ValueError("Cannot allocate OpenSSL secp256k1 data")
|
|
134
|
+
stack.callback(release, handle)
|
|
135
|
+
return handle
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class OpenSSLCurve:
|
|
139
|
+
def __init__(self, library: CDLL) -> None:
|
|
140
|
+
nid = _bind(library, "OBJ_txt2nid", c_int, c_char_p)
|
|
141
|
+
self._curve = nid(b"secp256k1")
|
|
142
|
+
self._group_new = _bind(library, "EC_GROUP_new_by_curve_name", c_void_p, c_int)
|
|
143
|
+
self._group_free = _bind(library, "EC_GROUP_free", None, c_void_p)
|
|
144
|
+
self._point_new = _bind(library, "EC_POINT_new", c_void_p, c_void_p)
|
|
145
|
+
self._point_free = _bind(library, "EC_POINT_clear_free", None, c_void_p)
|
|
146
|
+
self._bn_new = _bind(library, "BN_bin2bn", c_void_p, c_void_p, c_int, c_void_p)
|
|
147
|
+
self._bn_free = _bind(library, "BN_clear_free", None, c_void_p)
|
|
148
|
+
self._ctx_new = _bind(library, "BN_CTX_new", c_void_p)
|
|
149
|
+
self._ctx_free = _bind(library, "BN_CTX_free", None, c_void_p)
|
|
150
|
+
self._parse = _bind(
|
|
151
|
+
library, "EC_POINT_oct2point", c_int, c_void_p, c_void_p, c_void_p, c_size_t, c_void_p,
|
|
152
|
+
)
|
|
153
|
+
self._mul = _bind(
|
|
154
|
+
library, "EC_POINT_mul", c_int, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p,
|
|
155
|
+
c_void_p,
|
|
156
|
+
)
|
|
157
|
+
self._serialize = _bind(
|
|
158
|
+
library, "EC_POINT_point2oct", c_size_t, c_void_p, c_void_p, c_int,
|
|
159
|
+
c_void_p, c_size_t, c_void_p,
|
|
160
|
+
)
|
|
161
|
+
# A system libcrypto may have been built without this curve.
|
|
162
|
+
if not self._curve or self.multiply(generator_scalar=(1).to_bytes(32, "big")) is None:
|
|
163
|
+
raise ValueError("OpenSSL does not provide secp256k1")
|
|
164
|
+
|
|
165
|
+
def multiply(
|
|
166
|
+
self,
|
|
167
|
+
*,
|
|
168
|
+
generator_scalar: bytes | None = None,
|
|
169
|
+
peer: bytes | None = None,
|
|
170
|
+
peer_scalar: bytes | None = None,
|
|
171
|
+
) -> tuple[bytes, int] | None:
|
|
172
|
+
"""Return the X coordinate and Y parity for s*G + t*P."""
|
|
173
|
+
with ExitStack() as stack:
|
|
174
|
+
group = _allocate(stack, self._group_new, self._group_free, self._curve)
|
|
175
|
+
context = _allocate(stack, self._ctx_new, self._ctx_free)
|
|
176
|
+
result = _allocate(stack, self._point_new, self._point_free, group)
|
|
177
|
+
base = scalar = point = None
|
|
178
|
+
if generator_scalar is not None:
|
|
179
|
+
base = _allocate(
|
|
180
|
+
stack, self._bn_new, self._bn_free, generator_scalar, len(generator_scalar), None
|
|
181
|
+
)
|
|
182
|
+
if peer is not None:
|
|
183
|
+
if peer_scalar is None:
|
|
184
|
+
raise ValueError("Missing OpenSSL peer scalar")
|
|
185
|
+
point = _allocate(stack, self._point_new, self._point_free, group)
|
|
186
|
+
encoded = b"\x02" + peer
|
|
187
|
+
if not self._parse(group, point, encoded, len(encoded), context):
|
|
188
|
+
raise ValueError("Invalid public key")
|
|
189
|
+
scalar = _allocate(
|
|
190
|
+
stack, self._bn_new, self._bn_free, peer_scalar, len(peer_scalar), None
|
|
191
|
+
)
|
|
192
|
+
if not self._mul(group, result, base, point, scalar, context):
|
|
193
|
+
raise ValueError("OpenSSL secp256k1 multiplication failed")
|
|
194
|
+
output = (c_ubyte * 33)()
|
|
195
|
+
try:
|
|
196
|
+
size = self._serialize(
|
|
197
|
+
group, result, _POINT_CONVERSION_COMPRESSED, output, len(output), context
|
|
198
|
+
)
|
|
199
|
+
if size == 1 and output[0] == 0:
|
|
200
|
+
return None
|
|
201
|
+
if size != 33:
|
|
202
|
+
raise ValueError("Cannot serialize OpenSSL secp256k1 point")
|
|
203
|
+
return bytes(output)[1:], output[0] & 1
|
|
204
|
+
finally:
|
|
205
|
+
memset(output, 0, len(output))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def load_libsecp256k1() -> LibSecp256k1 | None:
|
|
209
|
+
paths = [find_library("secp256k1")]
|
|
210
|
+
if sys.platform == "win32":
|
|
211
|
+
paths.append(find_library("libsecp256k1"))
|
|
212
|
+
if sys.platform == "darwin":
|
|
213
|
+
paths.append("/opt/homebrew/lib/libsecp256k1.dylib")
|
|
214
|
+
for path in paths:
|
|
215
|
+
if not path or (sys.platform == "win32" and not Path(path).is_absolute()):
|
|
216
|
+
continue
|
|
217
|
+
try:
|
|
218
|
+
return LibSecp256k1(CDLL(path))
|
|
219
|
+
except (OSError, AttributeError):
|
|
220
|
+
continue
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def load_openssl() -> OpenSSLCurve | None:
|
|
225
|
+
return load_libcrypto(OpenSSLCurve)
|
aionwc/_protocol.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""NIP-47 event and payload handling adapted from nwc-agent's nwc_wallet.py."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from hashlib import sha256
|
|
8
|
+
from typing import Any, Literal, TypedDict, cast
|
|
9
|
+
from urllib.parse import parse_qs, urlsplit
|
|
10
|
+
|
|
11
|
+
from ._encryption import nip04_decrypt, nip04_encrypt, nip44_decrypt, nip44_encrypt
|
|
12
|
+
from ._secp256k1 import public_key, schnorr_sign, schnorr_verify, shared_secret
|
|
13
|
+
from .errors import NWCProtocolError, NWCURIError, NWCWalletError
|
|
14
|
+
|
|
15
|
+
INFO_KIND = 13194
|
|
16
|
+
REQUEST_KIND = 23194
|
|
17
|
+
RESPONSE_KIND = 23195
|
|
18
|
+
Encryption = Literal["nip04", "nip44_v2"]
|
|
19
|
+
JsonObject = dict[str, Any]
|
|
20
|
+
_HEX_KEY = re.compile(r"[0-9a-fA-F]{64}")
|
|
21
|
+
_HEX_SIGNATURE = re.compile(r"[0-9a-f]{128}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Event(TypedDict):
|
|
25
|
+
id: str
|
|
26
|
+
pubkey: str
|
|
27
|
+
created_at: int
|
|
28
|
+
kind: int
|
|
29
|
+
tags: list[list[str]]
|
|
30
|
+
content: str
|
|
31
|
+
sig: str
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _valid_relay(url: str) -> bool:
|
|
35
|
+
parsed = urlsplit(url)
|
|
36
|
+
return (
|
|
37
|
+
parsed.scheme in {"ws", "wss"}
|
|
38
|
+
and bool(parsed.hostname)
|
|
39
|
+
and parsed.port != 0
|
|
40
|
+
and parsed.username is None
|
|
41
|
+
and "#" not in url
|
|
42
|
+
and not any(character.isspace() or ord(character) < 32 for character in url)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Connection:
|
|
48
|
+
wallet: str
|
|
49
|
+
pubkey: str
|
|
50
|
+
secret: int = field(repr=False)
|
|
51
|
+
shared_key: bytes = field(repr=False)
|
|
52
|
+
relays: tuple[str, ...] = field(repr=False)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_uri(cls, uri: str) -> "Connection":
|
|
56
|
+
try:
|
|
57
|
+
parsed = urlsplit(uri)
|
|
58
|
+
params = parse_qs(parsed.query, keep_blank_values=True)
|
|
59
|
+
secrets = params.get("secret", [])
|
|
60
|
+
relays = tuple(dict.fromkeys(params.get("relay", [])))
|
|
61
|
+
if (
|
|
62
|
+
parsed.scheme != "nostr+walletconnect"
|
|
63
|
+
or parsed.path not in {"", "/"}
|
|
64
|
+
or "#" in uri
|
|
65
|
+
or not _HEX_KEY.fullmatch(parsed.netloc)
|
|
66
|
+
or len(secrets) != 1
|
|
67
|
+
or not _HEX_KEY.fullmatch(secrets[0])
|
|
68
|
+
or not relays
|
|
69
|
+
or not all(_valid_relay(relay) for relay in relays)
|
|
70
|
+
):
|
|
71
|
+
raise ValueError
|
|
72
|
+
wallet = parsed.netloc.lower()
|
|
73
|
+
secret = int(secrets[0], 16)
|
|
74
|
+
shared_key = shared_secret(secret, bytes.fromhex(wallet))
|
|
75
|
+
return cls(wallet, public_key(secret).hex(), secret, shared_key, relays)
|
|
76
|
+
except ValueError:
|
|
77
|
+
raise NWCURIError("Invalid Nostr Wallet Connect URI") from None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _event_id(
|
|
81
|
+
pubkey: str, created_at: int, kind: int, tags: list[list[str]], content: str
|
|
82
|
+
) -> bytes:
|
|
83
|
+
event = [0, pubkey, created_at, kind, tags, content]
|
|
84
|
+
encoded = json.dumps(event, ensure_ascii=False, separators=(",", ":")).encode()
|
|
85
|
+
return sha256(encoded).digest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def create_event(
|
|
89
|
+
secret: int, pubkey: str, kind: int, tags: list[list[str]], content: str
|
|
90
|
+
) -> Event:
|
|
91
|
+
created_at = int(time.time())
|
|
92
|
+
event_id = _event_id(pubkey, created_at, kind, tags, content)
|
|
93
|
+
return Event(
|
|
94
|
+
id=event_id.hex(),
|
|
95
|
+
pubkey=pubkey,
|
|
96
|
+
created_at=created_at,
|
|
97
|
+
kind=kind,
|
|
98
|
+
tags=tags,
|
|
99
|
+
content=content,
|
|
100
|
+
sig=schnorr_sign(secret, event_id).hex(),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def signed_event(data: Any, *, kind: int, author: str) -> Event | None:
|
|
105
|
+
if (
|
|
106
|
+
not isinstance(data, dict)
|
|
107
|
+
or type(data.get("kind")) is not int
|
|
108
|
+
or data.get("kind") != kind
|
|
109
|
+
or data.get("pubkey") != author
|
|
110
|
+
or type(data.get("created_at")) is not int
|
|
111
|
+
or not isinstance(data.get("content"), str)
|
|
112
|
+
or not isinstance(data.get("tags"), list)
|
|
113
|
+
or not isinstance(data.get("sig"), str)
|
|
114
|
+
or not _HEX_SIGNATURE.fullmatch(data["sig"])
|
|
115
|
+
or any(
|
|
116
|
+
not isinstance(tag, list) or any(not isinstance(value, str) for value in tag)
|
|
117
|
+
for tag in data["tags"]
|
|
118
|
+
)
|
|
119
|
+
):
|
|
120
|
+
return None
|
|
121
|
+
try:
|
|
122
|
+
actual_id = _event_id(author, data["created_at"], kind, data["tags"], data["content"])
|
|
123
|
+
except UnicodeError:
|
|
124
|
+
return None
|
|
125
|
+
if data.get("id") != actual_id.hex():
|
|
126
|
+
return None
|
|
127
|
+
if not schnorr_verify(bytes.fromhex(author), actual_id, bytes.fromhex(data["sig"])):
|
|
128
|
+
return None
|
|
129
|
+
return cast(Event, data)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def tag_values(event: Event, name: str) -> set[str]:
|
|
133
|
+
return {tag[1] for tag in event["tags"] if len(tag) >= 2 and tag[0] == name}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def preferred_encryption(info: Event) -> Encryption:
|
|
137
|
+
advertised = tag_values(info, "encryption")
|
|
138
|
+
schemes = {scheme for tag in advertised for scheme in tag.split()}
|
|
139
|
+
if "nip44_v2" in schemes:
|
|
140
|
+
return "nip44_v2"
|
|
141
|
+
if not advertised or "nip04" in schemes:
|
|
142
|
+
return "nip04"
|
|
143
|
+
raise NWCProtocolError("Wallet advertises no supported encryption")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def request_event(
|
|
147
|
+
connection: Connection,
|
|
148
|
+
method: str,
|
|
149
|
+
params: JsonObject,
|
|
150
|
+
encryption: Encryption,
|
|
151
|
+
expires_at: int,
|
|
152
|
+
) -> Event:
|
|
153
|
+
plaintext = json.dumps({"method": method, "params": params}, allow_nan=False)
|
|
154
|
+
tags = [["p", connection.wallet], ["expiration", str(expires_at)]]
|
|
155
|
+
try:
|
|
156
|
+
if encryption == "nip44_v2":
|
|
157
|
+
content = nip44_encrypt(connection.shared_key, plaintext)
|
|
158
|
+
tags.append(["encryption", encryption])
|
|
159
|
+
else:
|
|
160
|
+
content = nip04_encrypt(connection.shared_key, plaintext)
|
|
161
|
+
return create_event(connection.secret, connection.pubkey, REQUEST_KIND, tags, content)
|
|
162
|
+
except ValueError:
|
|
163
|
+
raise NWCProtocolError("Cannot encrypt or sign the wallet request") from None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def response_result(
|
|
167
|
+
connection: Connection,
|
|
168
|
+
event: Event,
|
|
169
|
+
method: str,
|
|
170
|
+
encryption: Encryption,
|
|
171
|
+
) -> JsonObject:
|
|
172
|
+
decrypt = nip44_decrypt if encryption == "nip44_v2" else nip04_decrypt
|
|
173
|
+
try:
|
|
174
|
+
payload = json.loads(decrypt(connection.shared_key, event["content"]))
|
|
175
|
+
except (ValueError, RecursionError):
|
|
176
|
+
raise NWCProtocolError("Cannot decode the wallet response") from None
|
|
177
|
+
|
|
178
|
+
if not isinstance(payload, dict) or payload.get("result_type") != method:
|
|
179
|
+
raise NWCProtocolError("Wallet response has an unexpected result type")
|
|
180
|
+
error = payload.get("error")
|
|
181
|
+
result = payload.get("result")
|
|
182
|
+
if error is not None:
|
|
183
|
+
if (
|
|
184
|
+
result is not None
|
|
185
|
+
or not isinstance(error, dict)
|
|
186
|
+
or not isinstance(error.get("code"), str)
|
|
187
|
+
or not isinstance(error.get("message"), str)
|
|
188
|
+
):
|
|
189
|
+
raise NWCProtocolError("Wallet response has a malformed error")
|
|
190
|
+
raise NWCWalletError(error["code"], error["message"])
|
|
191
|
+
if not isinstance(result, dict):
|
|
192
|
+
raise NWCProtocolError("Wallet response has no result object")
|
|
193
|
+
return result
|
aionwc/_secp256k1.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Nostr key agreement and BIP340 signatures, based on nwc-agent."""
|
|
2
|
+
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
from secrets import token_bytes
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from ._native_secp256k1 import load_libsecp256k1, load_openssl
|
|
8
|
+
except ImportError:
|
|
9
|
+
# Some Python builds omit the optional ctypes module.
|
|
10
|
+
_LIBSECP256K1 = _OPENSSL = None
|
|
11
|
+
else:
|
|
12
|
+
_LIBSECP256K1 = load_libsecp256k1()
|
|
13
|
+
_OPENSSL = load_openssl() if _LIBSECP256K1 is None else None
|
|
14
|
+
|
|
15
|
+
FIELD = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
|
|
16
|
+
ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
|
|
17
|
+
GENERATOR = (
|
|
18
|
+
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
|
|
19
|
+
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
|
|
20
|
+
)
|
|
21
|
+
Point = tuple[int, int] | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _point_add(left: Point, right: Point) -> Point:
|
|
25
|
+
if left is None:
|
|
26
|
+
return right
|
|
27
|
+
if right is None:
|
|
28
|
+
return left
|
|
29
|
+
x1, y1 = left
|
|
30
|
+
x2, y2 = right
|
|
31
|
+
if x1 == x2:
|
|
32
|
+
if (y1 + y2) % FIELD == 0:
|
|
33
|
+
return None
|
|
34
|
+
slope = (3 * x1 * x1) * pow(2 * y1, -1, FIELD)
|
|
35
|
+
else:
|
|
36
|
+
slope = (y2 - y1) * pow(x2 - x1, -1, FIELD)
|
|
37
|
+
slope %= FIELD
|
|
38
|
+
x = (slope * slope - x1 - x2) % FIELD
|
|
39
|
+
return x, (slope * (x1 - x) - y1) % FIELD
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _point_mul(scalar: int, point: Point) -> Point:
|
|
43
|
+
result = None
|
|
44
|
+
while scalar:
|
|
45
|
+
if scalar & 1:
|
|
46
|
+
result = _point_add(result, point)
|
|
47
|
+
point = _point_add(point, point)
|
|
48
|
+
scalar >>= 1
|
|
49
|
+
return result
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _lift_x(pubkey: bytes) -> tuple[int, int]:
|
|
53
|
+
if len(pubkey) != 32:
|
|
54
|
+
raise ValueError("Public key must be 32 bytes")
|
|
55
|
+
x = int.from_bytes(pubkey, "big")
|
|
56
|
+
if x >= FIELD:
|
|
57
|
+
raise ValueError("Public key is outside the curve field")
|
|
58
|
+
square = (pow(x, 3, FIELD) + 7) % FIELD
|
|
59
|
+
y = pow(square, (FIELD + 1) // 4, FIELD)
|
|
60
|
+
if pow(y, 2, FIELD) != square:
|
|
61
|
+
raise ValueError("Public key is not on secp256k1")
|
|
62
|
+
return x, FIELD - y if y % 2 else y
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _secret_bytes(secret: int) -> bytes:
|
|
66
|
+
if not 1 <= secret < ORDER:
|
|
67
|
+
raise ValueError("Private key is outside the scalar range")
|
|
68
|
+
return secret.to_bytes(32, "big")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _private_coordinates(secret: int, peer: bytes | None = None) -> tuple[bytes, int]:
|
|
72
|
+
encoded = _secret_bytes(secret)
|
|
73
|
+
if _OPENSSL is not None:
|
|
74
|
+
coordinates = (
|
|
75
|
+
_OPENSSL.multiply(generator_scalar=encoded)
|
|
76
|
+
if peer is None
|
|
77
|
+
else _OPENSSL.multiply(peer=peer, peer_scalar=encoded)
|
|
78
|
+
)
|
|
79
|
+
if coordinates is not None:
|
|
80
|
+
return coordinates
|
|
81
|
+
else:
|
|
82
|
+
point = _point_mul(secret, GENERATOR if peer is None else _lift_x(peer))
|
|
83
|
+
if point is not None:
|
|
84
|
+
return point[0].to_bytes(32, "big"), point[1] & 1
|
|
85
|
+
raise ValueError("Invalid curve point")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def public_key(secret: int) -> bytes:
|
|
89
|
+
if _LIBSECP256K1 is not None:
|
|
90
|
+
return _LIBSECP256K1.public_key(_secret_bytes(secret))
|
|
91
|
+
return _private_coordinates(secret)[0]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def shared_secret(secret: int, peer: bytes) -> bytes:
|
|
95
|
+
if len(peer) != 32:
|
|
96
|
+
raise ValueError("Public key must be 32 bytes")
|
|
97
|
+
if _LIBSECP256K1 is not None:
|
|
98
|
+
return _LIBSECP256K1.shared_secret(_secret_bytes(secret), peer)
|
|
99
|
+
return _private_coordinates(secret, peer)[0]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _tagged_hash(tag: bytes, data: bytes) -> bytes:
|
|
103
|
+
digest = sha256(tag).digest()
|
|
104
|
+
return sha256(digest + digest + data).digest()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _challenge(rx: bytes, pubkey: bytes, message: bytes) -> int:
|
|
108
|
+
return int.from_bytes(
|
|
109
|
+
_tagged_hash(b"BIP0340/challenge", rx + pubkey + message), "big"
|
|
110
|
+
) % ORDER
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def schnorr_sign(secret: int, message: bytes, *, aux: bytes | None = None) -> bytes:
|
|
114
|
+
aux = token_bytes(32) if aux is None else aux
|
|
115
|
+
if len(aux) != 32:
|
|
116
|
+
raise ValueError("Auxiliary randomness must be 32 bytes")
|
|
117
|
+
if _LIBSECP256K1 is not None:
|
|
118
|
+
return _LIBSECP256K1.sign(_secret_bytes(secret), message, aux)
|
|
119
|
+
pubkey, parity = _private_coordinates(secret)
|
|
120
|
+
normalized = ORDER - secret if parity else secret
|
|
121
|
+
hidden = normalized ^ int.from_bytes(_tagged_hash(b"BIP0340/aux", aux), "big")
|
|
122
|
+
nonce = int.from_bytes(
|
|
123
|
+
_tagged_hash(b"BIP0340/nonce", hidden.to_bytes(32, "big") + pubkey + message), "big"
|
|
124
|
+
) % ORDER
|
|
125
|
+
r, parity = _private_coordinates(nonce)
|
|
126
|
+
normalized_nonce = ORDER - nonce if parity else nonce
|
|
127
|
+
s = (normalized_nonce + _challenge(r, pubkey, message) * normalized) % ORDER
|
|
128
|
+
return r + s.to_bytes(32, "big")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def schnorr_verify(pubkey: bytes, message: bytes, signature: bytes) -> bool:
|
|
132
|
+
if len(pubkey) != 32 or len(signature) != 64:
|
|
133
|
+
return False
|
|
134
|
+
if _LIBSECP256K1 is not None:
|
|
135
|
+
return _LIBSECP256K1.verify(pubkey, message, signature)
|
|
136
|
+
r = signature[:32]
|
|
137
|
+
x = int.from_bytes(r, "big")
|
|
138
|
+
s = int.from_bytes(signature[32:], "big")
|
|
139
|
+
if x >= FIELD or s >= ORDER:
|
|
140
|
+
return False
|
|
141
|
+
inverse_challenge = (-_challenge(r, pubkey, message)) % ORDER
|
|
142
|
+
try:
|
|
143
|
+
if _OPENSSL is not None:
|
|
144
|
+
return _OPENSSL.multiply(
|
|
145
|
+
generator_scalar=signature[32:],
|
|
146
|
+
peer=pubkey,
|
|
147
|
+
peer_scalar=inverse_challenge.to_bytes(32, "big"),
|
|
148
|
+
) == (r, 0)
|
|
149
|
+
point = _lift_x(pubkey)
|
|
150
|
+
except ValueError:
|
|
151
|
+
return False
|
|
152
|
+
expected = _point_add(
|
|
153
|
+
_point_mul(s, GENERATOR),
|
|
154
|
+
_point_mul(inverse_challenge, point),
|
|
155
|
+
)
|
|
156
|
+
return expected is not None and expected[0] == x and expected[1] % 2 == 0
|
aionwc/client.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Async NIP-47 request and response API."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from websockets.asyncio.client import ClientConnection, connect
|
|
12
|
+
from websockets.exceptions import WebSocketException
|
|
13
|
+
|
|
14
|
+
from ._protocol import (
|
|
15
|
+
INFO_KIND,
|
|
16
|
+
RESPONSE_KIND,
|
|
17
|
+
Connection,
|
|
18
|
+
Encryption,
|
|
19
|
+
JsonObject,
|
|
20
|
+
preferred_encryption,
|
|
21
|
+
request_event,
|
|
22
|
+
response_result,
|
|
23
|
+
signed_event,
|
|
24
|
+
tag_values,
|
|
25
|
+
)
|
|
26
|
+
from .errors import NWCProtocolError, NWCRelayError, NWCTimeoutError
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def _send(socket: ClientConnection, *parts: Any) -> None:
|
|
30
|
+
await socket.send(json.dumps(parts, separators=(",", ":")))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def _receive(socket: ClientConnection) -> list[Any]:
|
|
34
|
+
while True:
|
|
35
|
+
try:
|
|
36
|
+
frame = json.loads(await socket.recv())
|
|
37
|
+
except (ValueError, RecursionError):
|
|
38
|
+
continue
|
|
39
|
+
if isinstance(frame, list) and len(frame) >= 2:
|
|
40
|
+
return frame
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def _negotiate(socket: ClientConnection, wallet: str) -> Encryption:
|
|
44
|
+
subscription = uuid4().hex
|
|
45
|
+
await _send(socket, "REQ", subscription, {"kinds": [INFO_KIND], "authors": [wallet], "limit": 1})
|
|
46
|
+
try:
|
|
47
|
+
async with asyncio.timeout(1.0):
|
|
48
|
+
while True:
|
|
49
|
+
frame = await _receive(socket)
|
|
50
|
+
if frame[1] != subscription:
|
|
51
|
+
continue
|
|
52
|
+
if frame[0] in ("EOSE", "CLOSED"):
|
|
53
|
+
return "nip04"
|
|
54
|
+
if frame[0] == "EVENT" and len(frame) == 3:
|
|
55
|
+
info = await asyncio.to_thread(
|
|
56
|
+
signed_event, frame[2], kind=INFO_KIND, author=wallet
|
|
57
|
+
)
|
|
58
|
+
if info is not None:
|
|
59
|
+
return preferred_encryption(info)
|
|
60
|
+
except TimeoutError:
|
|
61
|
+
return "nip04"
|
|
62
|
+
finally:
|
|
63
|
+
await _send(socket, "CLOSE", subscription)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class NWCClient:
|
|
67
|
+
"""Send async NIP-47 requests using a wallet connection URI.
|
|
68
|
+
|
|
69
|
+
Each request owns its WebSocket and can run concurrently with other
|
|
70
|
+
requests. The timeout is a total deadline in seconds, including relay
|
|
71
|
+
connection and encryption discovery.
|
|
72
|
+
|
|
73
|
+
:param uri: Wallet-issued connection URI containing the client secret.
|
|
74
|
+
:param timeout: Positive, finite deadline in seconds per operation.
|
|
75
|
+
:param encryption: Select automatically, require NIP-44 v2, or use NIP-04.
|
|
76
|
+
:raises NWCURIError: If the connection URI is invalid.
|
|
77
|
+
:raises ValueError: If the deadline or encryption mode is invalid.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
uri: str,
|
|
83
|
+
*,
|
|
84
|
+
timeout: float = 30.0,
|
|
85
|
+
encryption: Literal["auto", "nip04", "nip44_v2"] = "auto",
|
|
86
|
+
) -> None:
|
|
87
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
88
|
+
raise ValueError("timeout must be finite and positive")
|
|
89
|
+
if encryption not in ("auto", "nip04", "nip44_v2"):
|
|
90
|
+
raise ValueError("encryption must be auto, nip04, or nip44_v2")
|
|
91
|
+
self._connection = Connection.from_uri(uri)
|
|
92
|
+
self._timeout = timeout
|
|
93
|
+
self._encryption = encryption
|
|
94
|
+
|
|
95
|
+
async def request(
|
|
96
|
+
self, method: str, params: Mapping[str, Any] | None = None
|
|
97
|
+
) -> JsonObject:
|
|
98
|
+
"""Send a NIP-47 command and return its result object.
|
|
99
|
+
|
|
100
|
+
:param method: Command supported by the connected wallet.
|
|
101
|
+
:param params: JSON-serializable command arguments.
|
|
102
|
+
:raises NWCWalletError: If the wallet replies with a NIP-47 error.
|
|
103
|
+
:raises NWCProtocolError: If the response is invalid or the encryption mode is unavailable.
|
|
104
|
+
:raises NWCRelayError: If the relay cannot deliver the request or response.
|
|
105
|
+
:raises NWCTimeoutError: If the operation exceeds the deadline.
|
|
106
|
+
"""
|
|
107
|
+
if not isinstance(method, str) or not method.strip():
|
|
108
|
+
raise ValueError("method must be a non-empty string")
|
|
109
|
+
arguments = {} if params is None else dict(params)
|
|
110
|
+
connection = self._connection
|
|
111
|
+
wallet = connection.wallet
|
|
112
|
+
client = connection.pubkey
|
|
113
|
+
expires_at = math.ceil(time.time() + self._timeout)
|
|
114
|
+
request_id = None
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
async with asyncio.timeout(self._timeout):
|
|
118
|
+
open_timeout = min(5.0, self._timeout / len(connection.relays))
|
|
119
|
+
for relay in connection.relays:
|
|
120
|
+
try:
|
|
121
|
+
async with connect(
|
|
122
|
+
relay, open_timeout=open_timeout, close_timeout=1
|
|
123
|
+
) as socket:
|
|
124
|
+
encryption = self._encryption
|
|
125
|
+
if encryption == "auto":
|
|
126
|
+
encryption = await _negotiate(socket, wallet)
|
|
127
|
+
|
|
128
|
+
event = await asyncio.to_thread(
|
|
129
|
+
request_event, connection, method, arguments, encryption, expires_at
|
|
130
|
+
)
|
|
131
|
+
event_id = event["id"]
|
|
132
|
+
subscription = uuid4().hex
|
|
133
|
+
await _send(
|
|
134
|
+
socket,
|
|
135
|
+
"REQ",
|
|
136
|
+
subscription,
|
|
137
|
+
{
|
|
138
|
+
"authors": [wallet],
|
|
139
|
+
"kinds": [RESPONSE_KIND],
|
|
140
|
+
"#p": [client],
|
|
141
|
+
"#e": [event_id],
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
# A failed send can still have reached the relay.
|
|
145
|
+
request_id = event_id
|
|
146
|
+
await _send(socket, "EVENT", event)
|
|
147
|
+
return await self._wait_response(
|
|
148
|
+
socket, subscription, request_id, method, encryption
|
|
149
|
+
)
|
|
150
|
+
except (OSError, WebSocketException):
|
|
151
|
+
if request_id is not None:
|
|
152
|
+
raise NWCRelayError(
|
|
153
|
+
"Relay disconnected before the wallet responded",
|
|
154
|
+
request_id=request_id,
|
|
155
|
+
) from None
|
|
156
|
+
raise NWCRelayError("Unable to send the request to any configured relay")
|
|
157
|
+
except TimeoutError:
|
|
158
|
+
raise NWCTimeoutError(
|
|
159
|
+
"Timed out waiting for the wallet response", request_id=request_id
|
|
160
|
+
) from None
|
|
161
|
+
|
|
162
|
+
async def _wait_response(
|
|
163
|
+
self,
|
|
164
|
+
socket: ClientConnection,
|
|
165
|
+
subscription: str,
|
|
166
|
+
request_id: str,
|
|
167
|
+
method: str,
|
|
168
|
+
encryption: Encryption,
|
|
169
|
+
) -> JsonObject:
|
|
170
|
+
connection = self._connection
|
|
171
|
+
wallet = connection.wallet
|
|
172
|
+
client = connection.pubkey
|
|
173
|
+
while True:
|
|
174
|
+
frame = await _receive(socket)
|
|
175
|
+
if (
|
|
176
|
+
frame[0] == "OK"
|
|
177
|
+
and len(frame) >= 3
|
|
178
|
+
and frame[1] == request_id
|
|
179
|
+
and frame[2] is False
|
|
180
|
+
):
|
|
181
|
+
raise NWCRelayError("Relay rejected the request", request_id=request_id)
|
|
182
|
+
if frame[0] == "CLOSED" and frame[1] == subscription:
|
|
183
|
+
raise NWCRelayError(
|
|
184
|
+
"Relay closed the response subscription", request_id=request_id
|
|
185
|
+
)
|
|
186
|
+
if frame[0] != "EVENT" or frame[1] != subscription or len(frame) != 3:
|
|
187
|
+
continue
|
|
188
|
+
event = await asyncio.to_thread(
|
|
189
|
+
signed_event, frame[2], kind=RESPONSE_KIND, author=wallet
|
|
190
|
+
)
|
|
191
|
+
if event is None:
|
|
192
|
+
continue
|
|
193
|
+
if client in tag_values(event, "p") and request_id in tag_values(event, "e"):
|
|
194
|
+
return await asyncio.to_thread(
|
|
195
|
+
response_result, connection, event, method, encryption
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
async def get_info(self) -> JsonObject:
|
|
199
|
+
"""Return wallet metadata and supported methods."""
|
|
200
|
+
return await self.request("get_info")
|
|
201
|
+
|
|
202
|
+
async def get_balance(self) -> int:
|
|
203
|
+
"""Return the wallet balance in millisatoshis."""
|
|
204
|
+
result = await self.request("get_balance")
|
|
205
|
+
balance = result.get("balance")
|
|
206
|
+
if type(balance) is not int or balance < 0:
|
|
207
|
+
raise NWCProtocolError("Wallet response has an invalid balance")
|
|
208
|
+
return balance
|
|
209
|
+
|
|
210
|
+
async def make_invoice(
|
|
211
|
+
self,
|
|
212
|
+
amount_msat: int,
|
|
213
|
+
*,
|
|
214
|
+
description: str | None = None,
|
|
215
|
+
description_hash: str | None = None,
|
|
216
|
+
expiry: int | None = None,
|
|
217
|
+
) -> JsonObject:
|
|
218
|
+
"""Create a BOLT11 invoice and return the wallet's result object.
|
|
219
|
+
|
|
220
|
+
:param amount_msat: Invoice amount as a positive integer in millisatoshis.
|
|
221
|
+
:param description: Optional invoice description.
|
|
222
|
+
:param description_hash: Optional description hash used in place of a description.
|
|
223
|
+
:param expiry: Optional positive lifetime in seconds.
|
|
224
|
+
"""
|
|
225
|
+
if type(amount_msat) is not int or amount_msat <= 0:
|
|
226
|
+
raise ValueError("amount_msat must be a positive integer")
|
|
227
|
+
if description is not None and description_hash is not None:
|
|
228
|
+
raise ValueError("Provide only one of description and description_hash")
|
|
229
|
+
if expiry is not None and (type(expiry) is not int or expiry <= 0):
|
|
230
|
+
raise ValueError("expiry must be a positive number of seconds")
|
|
231
|
+
params: JsonObject = {"amount": amount_msat}
|
|
232
|
+
if description is not None:
|
|
233
|
+
params["description"] = description
|
|
234
|
+
if description_hash is not None:
|
|
235
|
+
params["description_hash"] = description_hash
|
|
236
|
+
if expiry is not None:
|
|
237
|
+
params["expiry"] = expiry
|
|
238
|
+
return await self.request("make_invoice", params)
|
|
239
|
+
|
|
240
|
+
async def pay_invoice(
|
|
241
|
+
self, invoice: str, *, amount_msat: int | None = None
|
|
242
|
+
) -> JsonObject:
|
|
243
|
+
"""Pay a BOLT11 invoice and return the wallet's confirmation.
|
|
244
|
+
|
|
245
|
+
:param invoice: Recipient's BOLT11 invoice.
|
|
246
|
+
:param amount_msat: Optional positive amount in millisatoshis for an amountless invoice.
|
|
247
|
+
"""
|
|
248
|
+
params: JsonObject = {"invoice": invoice}
|
|
249
|
+
if amount_msat is not None:
|
|
250
|
+
if type(amount_msat) is not int or amount_msat <= 0:
|
|
251
|
+
raise ValueError("amount_msat must be a positive integer")
|
|
252
|
+
params["amount"] = amount_msat
|
|
253
|
+
return await self.request("pay_invoice", params)
|
|
254
|
+
|
|
255
|
+
async def lookup_invoice(
|
|
256
|
+
self, *, payment_hash: str | None = None, invoice: str | None = None
|
|
257
|
+
) -> JsonObject:
|
|
258
|
+
"""Find an invoice by supplying exactly one of the two identifiers.
|
|
259
|
+
|
|
260
|
+
:param payment_hash: Payment hash of the invoice.
|
|
261
|
+
:param invoice: Complete BOLT11 invoice.
|
|
262
|
+
"""
|
|
263
|
+
if (payment_hash is None) == (invoice is None):
|
|
264
|
+
raise ValueError("Provide either payment_hash or invoice")
|
|
265
|
+
params = {"payment_hash": payment_hash} if invoice is None else {"invoice": invoice}
|
|
266
|
+
return await self.request("lookup_invoice", params)
|
|
267
|
+
|
|
268
|
+
async def list_transactions(
|
|
269
|
+
self,
|
|
270
|
+
*,
|
|
271
|
+
transaction_type: Literal["incoming", "outgoing"] | None = None,
|
|
272
|
+
limit: int | None = None,
|
|
273
|
+
offset: int | None = None,
|
|
274
|
+
from_timestamp: int | None = None,
|
|
275
|
+
until_timestamp: int | None = None,
|
|
276
|
+
unpaid: bool | None = None,
|
|
277
|
+
) -> list[JsonObject]:
|
|
278
|
+
"""List transactions matching optional filters and pagination.
|
|
279
|
+
|
|
280
|
+
:param transaction_type: Filter for incoming or outgoing transactions.
|
|
281
|
+
:param limit: Maximum number of records requested.
|
|
282
|
+
:param offset: Number of records to skip.
|
|
283
|
+
:param from_timestamp: Lower time bound as a Unix timestamp in seconds.
|
|
284
|
+
:param until_timestamp: Upper time bound as a Unix timestamp in seconds.
|
|
285
|
+
:param unpaid: Wallet filter for unpaid invoices.
|
|
286
|
+
"""
|
|
287
|
+
filters = {
|
|
288
|
+
"type": transaction_type,
|
|
289
|
+
"limit": limit,
|
|
290
|
+
"offset": offset,
|
|
291
|
+
"from": from_timestamp,
|
|
292
|
+
"until": until_timestamp,
|
|
293
|
+
"unpaid": unpaid,
|
|
294
|
+
}
|
|
295
|
+
result = await self.request(
|
|
296
|
+
"list_transactions", {key: value for key, value in filters.items() if value is not None}
|
|
297
|
+
)
|
|
298
|
+
transactions = result.get("transactions")
|
|
299
|
+
if not isinstance(transactions, list) or any(
|
|
300
|
+
not isinstance(item, dict) for item in transactions
|
|
301
|
+
):
|
|
302
|
+
raise NWCProtocolError("Wallet response has an invalid transaction list")
|
|
303
|
+
return transactions
|
aionwc/errors.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Errors raised by the Nostr Wallet Connect client."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class NWCError(Exception):
|
|
5
|
+
"""Base class for NWC client errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NWCURIError(NWCError, ValueError):
|
|
9
|
+
"""The wallet connection URI is invalid."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NWCProtocolError(NWCError):
|
|
13
|
+
"""The wallet returned invalid protocol data or the client cannot use a protocol mode."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NWCRelayError(NWCError):
|
|
17
|
+
"""A relay could not deliver the request or its response.
|
|
18
|
+
|
|
19
|
+
:ivar request_id: Signed event ID if the client attempted to publish the request.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message: str, *, request_id: str | None = None) -> None:
|
|
23
|
+
self.request_id = request_id
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NWCTimeoutError(NWCRelayError, TimeoutError):
|
|
28
|
+
"""The request deadline passed before the wallet responded."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class NWCWalletError(NWCError):
|
|
32
|
+
"""The wallet returned a NIP-47 error.
|
|
33
|
+
|
|
34
|
+
:ivar code: Protocol error code supplied by the wallet.
|
|
35
|
+
:ivar message: Human-readable wallet error message.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, code: str, message: str) -> None:
|
|
39
|
+
self.code = code
|
|
40
|
+
self.message = message
|
|
41
|
+
super().__init__(f"{code}: {message}")
|
aionwc/py.typed
ADDED
|
File without changes
|
|
@@ -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
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
aionwc/__init__.py,sha256=myvqRK7RkvPibwgTd9M0BhmmyjsCKDUdTXr8aIQ4mmU,366
|
|
2
|
+
aionwc/_encryption.py,sha256=iotFubG6qaszKyvuiht_KKKZ95OmWSAfcQAk0go4Pkw,6172
|
|
3
|
+
aionwc/_libcrypto.py,sha256=TMcU6ojZjdltjY9L63LLH5WLwtfJ5EO9CgvXenjMr98,3557
|
|
4
|
+
aionwc/_native_secp256k1.py,sha256=iSbckuT2rqJ6Fs-YXe_JwPzKNNQBCZfOih-DPGWEW6Y,9004
|
|
5
|
+
aionwc/_protocol.py,sha256=FgXG86pYGeqJ6liZuoxTo1sdwhjNdDuogtZiE4nLFA4,6630
|
|
6
|
+
aionwc/_secp256k1.py,sha256=vNO_DIDTKhIpEfB-mjSdRH1_-xobzbPtq1i8JlXlsjU,5425
|
|
7
|
+
aionwc/client.py,sha256=CLMWIPUNNjWnciGfdjbvKsIc6mCxzNUdHcM4rzd1b8c,12523
|
|
8
|
+
aionwc/errors.py,sha256=E5fM660wtHbhcEQVRWhEMRyvJGm11C6kEIicCzgHJfs,1176
|
|
9
|
+
aionwc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
aionwc-0.1.0.dist-info/METADATA,sha256=cSRYUh9nDCsnebwCtvhl1-0bBn-dcUH-Zj9-9rYByPI,5192
|
|
11
|
+
aionwc-0.1.0.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
|
|
12
|
+
aionwc-0.1.0.dist-info/licenses/LICENSE,sha256=27eJCUHGuO4Ukd8tbAMS7PogLV8cVjTZV_FAiJVtJDU,1128
|
|
13
|
+
aionwc-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|