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

Commit c55dee5

Browse files
committed
add nip-13: proof of work
1 parent aa56d84 commit c55dee5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

nostr/pow.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import time
2+
from .event import Event
3+
4+
def zero_bits(b: int) -> int:
5+
n = 0
6+
7+
if b == 0:
8+
return 8
9+
10+
while b >> 1:
11+
b = b >> 1
12+
n += 1
13+
14+
return 7 - n
15+
16+
def count_leading_zero_bits(event_id: str) -> int:
17+
total = 0
18+
for i in range(0, len(event_id) - 2, 2):
19+
bits = zero_bits(int(event_id[i:i+2], 16))
20+
total += bits
21+
22+
if bits != 8:
23+
break
24+
25+
return total
26+
27+
def mine_event(content: str, difficulty: int, public_key: str, kind: int, tags: list=[]) -> Event:
28+
all_tags = [["nonce", "1", str(difficulty)]]
29+
all_tags.extend(tags)
30+
31+
created_at = int(time.time())
32+
event_id = Event.compute_id(public_key, created_at, kind, all_tags, content)
33+
num_leading_zero_bits = count_leading_zero_bits(event_id)
34+
35+
attempts = 1
36+
while num_leading_zero_bits < difficulty:
37+
attempts += 1
38+
all_tags[0][1] = str(attempts)
39+
created_at = int(time.time())
40+
event_id = Event.compute_id(public_key, created_at, kind, all_tags, content)
41+
num_leading_zero_bits = count_leading_zero_bits(event_id)
42+
43+
return Event(public_key, content, created_at, kind, all_tags, event_id)

0 commit comments

Comments
 (0)