#nostr protocol from scratch using Python
##########################################
# package importation
import asyncio, websockets, secrets,secp256k1
import time, json
from hashlib import sha256
from time import time
# The custom content of note that will be publish in this tutorial
content = input("What's your message to the world?")
# Token applied to generate public-private keypair
secrets_token_32bit = secrets.token_bytes(32)
# User's private key (use print(private_key.hex()) to print)
private_key = secp256k1.PrivateKey(secrets_token_32bit)
# User's public key
public_key = private_key.pubkey.serialize()[1:].hex()
# Definition of required elements according to NIP-01
tags = []
kind = 1
timestamp = int(time()) # timestamp in SECONDS
# Define the property "event_id"
event_id = sha256(
json.dumps([
0, # ZERO is a CONSTANT, don't confuse with kind
public_key,
timestamp,
kind,
tags,
content], separators=(',', ':'))
.encode('utf-8')).hexdigest()
# Define the property "sig"
sig = private_key.schnorr_sign(bytes.fromhex(event_id), None, raw=True).hex()
# Define the note to send to Relays
note = json.dumps(["EVENT", {
"id": event_id,
"pubkey": public_key,
"created_at": timestamp,
"kind": kind,
"tags": tags,
"content": content,
"sig": sig
}], separators=(',', ':'))
# Define the Relay for this tutorial (only for example)
relay : str = "wss://relay.damus.io"
# Connect to the Relay using Socket and send the note
async def main_program():
async with websockets.connect(relay) as websocket:
await websocket.send(note)
print(f">>> {note}")
greeting = await websocket.recv()
print(f"<<< {greeting}")
asyncio.run(main_program())