add compute_id method to event class

This commit is contained in:
jeffthibault
2022-11-01 18:37:51 -04:00
parent 66d95a5a8c
commit 033e1f16a2

View File

@@ -25,7 +25,7 @@ class Event():
if not isinstance(content, str): if not isinstance(content, str):
raise TypeError("Argument 'content' must be of type str") raise TypeError("Argument 'content' must be of type str")
self.id = id if id != None else sha256(Event.serialize(public_key, created_at, kind, tags, content)).hexdigest() self.id = id if not id is None else Event.compute_id(public_key, created_at, kind, tags, content)
self.public_key = public_key self.public_key = public_key
self.content = content self.content = content
self.created_at = created_at self.created_at = created_at
@@ -39,14 +39,19 @@ class Event():
data_str = json.dumps(data, separators=(',', ':')) data_str = json.dumps(data, separators=(',', ':'))
return data_str.encode() return data_str.encode()
def sign(self, sk: str) -> None: @staticmethod
private_key = PrivateKey(bytes.fromhex(sk)) def compute_id(public_key: str, created_at: int, kind: int, tags: "list[list[str]]", content: str) -> str:
sig = private_key.schnorr_sign(bytes.fromhex(self.id), None, raw=True) return sha256(Event.serialize(public_key, created_at, kind, tags, content)).hexdigest()
def sign(self, private_key_hex: str) -> None:
sk = PrivateKey(bytes.fromhex(private_key_hex))
sig = sk.schnorr_sign(bytes.fromhex(self.id), None, raw=True)
self.signature = sig.hex() self.signature = sig.hex()
def verify(self) -> bool: def verify(self) -> bool:
pub_key = PublicKey(bytes.fromhex("02" + self.public_key), True) # add 02 for schnorr (bip340) pub_key = PublicKey(bytes.fromhex("02" + self.public_key), True) # add 02 for schnorr (bip340)
return pub_key.schnorr_verify(bytes.fromhex(self.id), bytes.fromhex(self.signature), None, raw=True) event_id = Event.compute_id(self.public_key, self.created_at, self.kind, self.tags, self.content)
return pub_key.schnorr_verify(event_id, bytes.fromhex(self.signature), None, raw=True)
def to_json_object(self) -> dict: def to_json_object(self) -> dict:
return { return {