What is Nostr?
chaoticalHeavy /
npub1g8g…k7um
2024-01-09 20:11:31

chaoticalHeavy on Nostr: (Tutorial) Nostr for Dummies: How to implement NOSTR Protocol from scratch with ...




(Tutorial) Nostr for Dummies: How to implement NOSTR Protocol from scratch with Python (NIP-01)
https://stacker.news/items/382246/r/chaoticalHeavy

# Package installation on Jupyter Notebook environment (uncomment if you are using the Jupyter Notebook)
# ! pip install websockets # Connect you with the Relay
# ! pip install secp256k1 # Generate the private key and public key
# ! pip install sha256 # Generate needed hash




# package importation
import asyncio
import websockets
import secrets
import secp256k1
import time
import json
from hashlib import sha256
from time import time


# The custom content of note that will be publish in this tutorial
content = "Hello, world!" #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 = 0
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.geekiam.services"


# Connect to the Relay using Socket and send the note
async with websockets.connect(relay) as websocket:

await websocket.send(note)
print(f">>> {note}")

greeting = await websocket.recv()
print(f"<<< {greeting}")

Author Public Key
npub1g8g2w9gl88r3z6a0tcsgngqwe5f225n4j5wg3cpzw26pp9enc5fqmmk7um