summaryrefslogtreecommitdiff
path: root/nostr
diff options
context:
space:
mode:
authorYuval Adam <_@yuv.al>2022-01-17 15:16:13 +0200
committerYuval Adam <_@yuv.al>2022-01-17 15:16:13 +0200
commitfcfc9410654d366640dac7b6b1c612c8eda2beba (patch)
treeff68c30fa063c600f6a7bc546a5ec6251af59f50 /nostr
parent8b7b67e0381bb11fae7691cca134627d26933d57 (diff)
Initial bip340 reference code copy pasta
Diffstat (limited to 'nostr')
-rw-r--r--nostr/bip340.py170
-rw-r--r--nostr/event.py4
-rw-r--r--nostr/keys.py0
3 files changed, 174 insertions, 0 deletions
diff --git a/nostr/bip340.py b/nostr/bip340.py
new file mode 100644
index 0000000..7712500
--- /dev/null
+++ b/nostr/bip340.py
@@ -0,0 +1,170 @@
+### Reference implementatoin copy pasta from https://github.com/bitcoin/bips/blob/02de475efc528058bd04a0c4ad31b6422aed5f5f/bip-0340/reference.py
+
+from typing import Tuple, Optional, Any
+import hashlib
+import binascii
+
+# Set DEBUG to True to get a detailed debug output including
+# intermediate values during key generation, signing, and
+# verification. This is implemented via calls to the
+# debug_print_vars() function.
+#
+# If you want to print values on an individual basis, use
+# the pretty() function, e.g., print(pretty(foo)).
+DEBUG = False
+
+p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
+n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
+
+# Points are tuples of X and Y coordinates and the point at infinity is
+# represented by the None keyword.
+G = (
+ 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
+ 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
+)
+
+Point = Tuple[int, int]
+
+# This implementation can be sped up by storing the midstate after hashing
+# tag_hash instead of rehashing it all the time.
+def tagged_hash(tag: str, msg: bytes) -> bytes:
+ tag_hash = hashlib.sha256(tag.encode()).digest()
+ return hashlib.sha256(tag_hash + tag_hash + msg).digest()
+
+
+def is_infinite(P: Optional[Point]) -> bool:
+ return P is None
+
+
+def x(P: Point) -> int:
+ assert not is_infinite(P)
+ return P[0]
+
+
+def y(P: Point) -> int:
+ assert not is_infinite(P)
+ return P[1]
+
+
+def point_add(P1: Optional[Point], P2: Optional[Point]) -> Optional[Point]:
+ if P1 is None:
+ return P2
+ if P2 is None:
+ return P1
+ if (x(P1) == x(P2)) and (y(P1) != y(P2)):
+ return None
+ if P1 == P2:
+ lam = (3 * x(P1) * x(P1) * pow(2 * y(P1), p - 2, p)) % p
+ else:
+ lam = ((y(P2) - y(P1)) * pow(x(P2) - x(P1), p - 2, p)) % p
+ x3 = (lam * lam - x(P1) - x(P2)) % p
+ return (x3, (lam * (x(P1) - x3) - y(P1)) % p)
+
+
+def point_mul(P: Optional[Point], n: int) -> Optional[Point]:
+ R = None
+ for i in range(256):
+ if (n >> i) & 1:
+ R = point_add(R, P)
+ P = point_add(P, P)
+ return R
+
+
+def bytes_from_int(x: int) -> bytes:
+ return x.to_bytes(32, byteorder="big")
+
+
+def bytes_from_point(P: Point) -> bytes:
+ return bytes_from_int(x(P))
+
+
+def xor_bytes(b0: bytes, b1: bytes) -> bytes:
+ return bytes(x ^ y for (x, y) in zip(b0, b1))
+
+
+def lift_x(b: bytes) -> Optional[Point]:
+ x = int_from_bytes(b)
+ if x >= p:
+ return None
+ y_sq = (pow(x, 3, p) + 7) % p
+ y = pow(y_sq, (p + 1) // 4, p)
+ if pow(y, 2, p) != y_sq:
+ return None
+ return (x, y if y & 1 == 0 else p - y)
+
+
+def int_from_bytes(b: bytes) -> int:
+ return int.from_bytes(b, byteorder="big")
+
+
+def hash_sha256(b: bytes) -> bytes:
+ return hashlib.sha256(b).digest()
+
+
+def has_even_y(P: Point) -> bool:
+ assert not is_infinite(P)
+ return y(P) % 2 == 0
+
+
+def pubkey_gen(seckey: bytes) -> bytes:
+ d0 = int_from_bytes(seckey)
+ if not (1 <= d0 <= n - 1):
+ raise ValueError("The secret key must be an integer in the range 1..n-1.")
+ P = point_mul(G, d0)
+ assert P is not None
+ return bytes_from_point(P)
+
+
+def schnorr_sign(msg: bytes, seckey: bytes, aux_rand: bytes) -> bytes:
+ if len(msg) != 32:
+ raise ValueError("The message must be a 32-byte array.")
+ d0 = int_from_bytes(seckey)
+ if not (1 <= d0 <= n - 1):
+ raise ValueError("The secret key must be an integer in the range 1..n-1.")
+ if len(aux_rand) != 32:
+ raise ValueError("aux_rand must be 32 bytes instead of %i." % len(aux_rand))
+ P = point_mul(G, d0)
+ assert P is not None
+ d = d0 if has_even_y(P) else n - d0
+ t = xor_bytes(bytes_from_int(d), tagged_hash("BIP0340/aux", aux_rand))
+ k0 = int_from_bytes(tagged_hash("BIP0340/nonce", t + bytes_from_point(P) + msg)) % n
+ if k0 == 0:
+ raise RuntimeError("Failure. This happens only with negligible probability.")
+ R = point_mul(G, k0)
+ assert R is not None
+ k = n - k0 if not has_even_y(R) else k0
+ e = (
+ int_from_bytes(
+ tagged_hash(
+ "BIP0340/challenge", bytes_from_point(R) + bytes_from_point(P) + msg
+ )
+ )
+ % n
+ )
+ sig = bytes_from_point(R) + bytes_from_int((k + e * d) % n)
+ debug_print_vars()
+ if not schnorr_verify(msg, bytes_from_point(P), sig):
+ raise RuntimeError("The created signature does not pass verification.")
+ return sig
+
+
+def schnorr_verify(msg: bytes, pubkey: bytes, sig: bytes) -> bool:
+ if len(msg) != 32:
+ raise ValueError("The message must be a 32-byte array.")
+ if len(pubkey) != 32:
+ raise ValueError("The public key must be a 32-byte array.")
+ if len(sig) != 64:
+ raise ValueError("The signature must be a 64-byte array.")
+ P = lift_x(pubkey)
+ r = int_from_bytes(sig[0:32])
+ s = int_from_bytes(sig[32:64])
+ if (P is None) or (r >= p) or (s >= n):
+ debug_print_vars()
+ return False
+ e = int_from_bytes(tagged_hash("BIP0340/challenge", sig[0:32] + pubkey + msg)) % n
+ R = point_add(point_mul(G, s), point_mul(P, n - e))
+ if (R is None) or (not has_even_y(R)) or (x(R) != r):
+ debug_print_vars()
+ return False
+ debug_print_vars()
+ return True
diff --git a/nostr/event.py b/nostr/event.py
index 9cf363a..3dfe638 100644
--- a/nostr/event.py
+++ b/nostr/event.py
@@ -9,6 +9,9 @@ class EventKind(Enum):
SET_METADATA = 0
TEXT_NOTE = 1
RECOMMEND_SERVER = 2
+ CONTACT_LIST = 3
+ ENCRYPTED_DIRECT_MESSAGE = 4
+ DELETION = 5
class Event:
@@ -24,4 +27,5 @@ class Event:
def id(self):
data = [0, self.pubkey, self.created_at, self.kind, self.tags, self.content]
jd = json.dumps(data).encode("utf-8")
+ print(jd)
return hashlib.sha256(jd).hexdigest()
diff --git a/nostr/keys.py b/nostr/keys.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/nostr/keys.py