calculate proof of work on events

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2022-04-11 11:32:30 -07:00
parent 1f046ac021
commit e0059388e8
4 changed files with 101 additions and 0 deletions

View File

@@ -25,6 +25,7 @@ struct NostrEvent: Decodable, Identifiable {
let tags: [[String]]
let content: String
let sig: String
var pow: Int?
}
func decode_nostr_event(txt: String) -> NostrResponse? {

View File

@@ -25,6 +25,7 @@ enum NostrResponse: Decodable {
print(error)
throw error
}
ev.pow = count_hash_leading_zero_bits(ev.id)
self = .event(sub_id, ev)
return
} else if typ == "NOTICE" {

View File

@@ -0,0 +1,95 @@
//
// ProofOfWork.swift
// damus
//
// Created by William Casarin on 2022-04-11.
//
import Foundation
func zero_bits(_ argb: UInt8) -> Int
{
var b = argb
var n: Int = 0;
if b == 0 {
return 8;
}
while true {
b >>= 1;
if b != 0 {
n += 1;
} else {
break
}
}
return 7-n;
}
func count_hash_leading_zero_bits(_ hash: String) -> Int?
{
guard let decoded = hex_decode(hash) else {
return nil
}
return count_leading_zero_bits(decoded)
}
/* find the number of leading zero bits in a hash */
func count_leading_zero_bits(_ hash: [UInt8]) -> Int
{
var bits: Int = 0
var total: Int = 0
for c in hash {
bits = zero_bits(c)
total += bits
if (bits != 8) {
break
}
}
return total
}
func char_to_hex(_ c: UInt8) -> UInt8?
{
// 0 && 9
if (c >= 48 && c <= 57) {
return c - 48 // 0
}
// a && f
if (c >= 97 && c <= 102) {
return c - 97 + 10;
}
// A && F
if (c >= 65 && c <= 70) {
return c - 65 + 10;
}
return nil;
}
func hex_decode(_ str: String) -> [UInt8]?
{
var ret: [UInt8] = []
let chars = Array(str.utf8)
for c in zip(chars, chars[1...]) {
guard let c1 = char_to_hex(c.0) else {
return nil
}
guard let c2 = char_to_hex(c.1) else {
return nil
}
ret.append((c1 << 4) | c2)
}
return ret
}