Skip to content
This repository was archived by the owner on May 22, 2024. It is now read-only.

Commit 629949d

Browse files
committed
add bech32 key encoding
1 parent 751c1a3 commit 629949d

File tree

2 files changed

+154
-0
lines changed

2 files changed

+154
-0
lines changed

nostr/bech32.py

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Copyright (c) 2017, 2020 Pieter Wuille
2+
#
3+
# Permission is hereby granted, free of charge, to any person obtaining a copy
4+
# of this software and associated documentation files (the "Software"), to deal
5+
# in the Software without restriction, including without limitation the rights
6+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
# copies of the Software, and to permit persons to whom the Software is
8+
# furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included in
11+
# all copies or substantial portions of the Software.
12+
#
13+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
# THE SOFTWARE.
20+
21+
"""Reference implementation for Bech32/Bech32m and segwit addresses."""
22+
23+
24+
from enum import Enum
25+
26+
class Encoding(Enum):
27+
"""Enumeration type to list the various supported encodings."""
28+
BECH32 = 1
29+
BECH32M = 2
30+
31+
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
32+
BECH32M_CONST = 0x2bc830a3
33+
34+
def bech32_polymod(values):
35+
"""Internal function that computes the Bech32 checksum."""
36+
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
37+
chk = 1
38+
for value in values:
39+
top = chk >> 25
40+
chk = (chk & 0x1ffffff) << 5 ^ value
41+
for i in range(5):
42+
chk ^= generator[i] if ((top >> i) & 1) else 0
43+
return chk
44+
45+
46+
def bech32_hrp_expand(hrp):
47+
"""Expand the HRP into values for checksum computation."""
48+
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
49+
50+
51+
def bech32_verify_checksum(hrp, data):
52+
"""Verify a checksum given HRP and converted data characters."""
53+
const = bech32_polymod(bech32_hrp_expand(hrp) + data)
54+
if const == 1:
55+
return Encoding.BECH32
56+
if const == BECH32M_CONST:
57+
return Encoding.BECH32M
58+
return None
59+
60+
def bech32_create_checksum(hrp, data, spec):
61+
"""Compute the checksum values given HRP and data."""
62+
values = bech32_hrp_expand(hrp) + data
63+
const = BECH32M_CONST if spec == Encoding.BECH32M else 1
64+
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
65+
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
66+
67+
68+
def bech32_encode(hrp, data, spec):
69+
"""Compute a Bech32 string given HRP and data values."""
70+
combined = data + bech32_create_checksum(hrp, data, spec)
71+
return hrp + '1' + ''.join([CHARSET[d] for d in combined])
72+
73+
def bech32_decode(bech):
74+
"""Validate a Bech32/Bech32m string, and determine HRP and data."""
75+
if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
76+
(bech.lower() != bech and bech.upper() != bech)):
77+
return (None, None, None)
78+
bech = bech.lower()
79+
pos = bech.rfind('1')
80+
if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
81+
return (None, None, None)
82+
if not all(x in CHARSET for x in bech[pos+1:]):
83+
return (None, None, None)
84+
hrp = bech[:pos]
85+
data = [CHARSET.find(x) for x in bech[pos+1:]]
86+
spec = bech32_verify_checksum(hrp, data)
87+
if spec is None:
88+
return (None, None, None)
89+
return (hrp, data[:-6], spec)
90+
91+
def convertbits(data, frombits, tobits, pad=True):
92+
"""General power-of-2 base conversion."""
93+
acc = 0
94+
bits = 0
95+
ret = []
96+
maxv = (1 << tobits) - 1
97+
max_acc = (1 << (frombits + tobits - 1)) - 1
98+
for value in data:
99+
if value < 0 or (value >> frombits):
100+
return None
101+
acc = ((acc << frombits) | value) & max_acc
102+
bits += frombits
103+
while bits >= tobits:
104+
bits -= tobits
105+
ret.append((acc >> bits) & maxv)
106+
if pad:
107+
if bits:
108+
ret.append((acc << (tobits - bits)) & maxv)
109+
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
110+
return None
111+
return ret
112+
113+
114+
def decode(hrp, addr):
115+
"""Decode a segwit address."""
116+
hrpgot, data, spec = bech32_decode(addr)
117+
if hrpgot != hrp:
118+
return (None, None)
119+
decoded = convertbits(data[1:], 5, 8, False)
120+
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
121+
return (None, None)
122+
if data[0] > 16:
123+
return (None, None)
124+
if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
125+
return (None, None)
126+
if data[0] == 0 and spec != Encoding.BECH32 or data[0] != 0 and spec != Encoding.BECH32M:
127+
return (None, None)
128+
return (data[0], decoded)
129+
130+
131+
def encode(hrp, witver, witprog):
132+
"""Encode a segwit address."""
133+
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
134+
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
135+
if decode(hrp, ret) == (None, None):
136+
return None
137+
return ret

nostr/key.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from secp256k1 import PrivateKey, PublicKey
55
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
66
from cryptography.hazmat.primitives import padding
7+
from . import bech32
78

89
def generate_private_key() -> str:
910
private_key = PrivateKey()
@@ -23,6 +24,22 @@ def get_key_pair() -> tuple:
2324
public_key = private_key.pubkey.serialize().hex()
2425
return (private_key.serialize(), public_key[2:])
2526

27+
def bech32_encode_private_key(private_key: str) -> str:
28+
converted_bits = bech32.convertbits(bytes.fromhex(private_key), 8, 5)
29+
return bech32.bech32_encode("nsec", converted_bits, bech32.Encoding.BECH32)
30+
31+
def bech32_decode_private_key(private_key_bech32: str) -> str:
32+
data = bech32.bech32_decode(private_key_bech32)[1]
33+
return bytes(bech32.convertbits(data, 5, 8, False)).hex()
34+
35+
def bech32_encode_public_key(public_key: str) -> str:
36+
converted_bits = bech32.convertbits(bytes.fromhex(public_key), 8, 5)
37+
return bech32.bech32_encode("npub", converted_bits, bech32.Encoding.BECH32)
38+
39+
def bech32_decode_public_key(public_key_bech32: str) -> str:
40+
data = bech32.bech32_decode(public_key_bech32)[1]
41+
return bytes(bech32.convertbits(data, 5, 8, False)).hex()
42+
2643
def tweak_add_private_key(private_key: str, scalar: bytes) -> str:
2744
sk = PrivateKey(bytes.fromhex(private_key))
2845
tweaked_secret = sk.tweak_add(scalar)

0 commit comments

Comments
 (0)