ProofOfWork.swift (1398B)
1 // 2 // ProofOfWork.swift 3 // damus 4 // 5 // Created by William Casarin on 2022-04-11. 6 // 7 8 import Foundation 9 10 func char_to_hex(_ c: UInt8) -> UInt8? 11 { 12 // 0 && 9 13 if (c >= 48 && c <= 57) { 14 return c - 48 // 0 15 } 16 // a && f 17 if (c >= 97 && c <= 102) { 18 return c - 97 + 10; 19 } 20 // A && F 21 if (c >= 65 && c <= 70) { 22 return c - 65 + 10; 23 } 24 return nil; 25 } 26 27 @discardableResult 28 func hex_decode(_ str: String) -> [UInt8]? 29 { 30 if str.count == 0 { 31 return nil 32 } 33 var ret: [UInt8] = [] 34 let chars = Array(str.utf8) 35 var i: Int = 0 36 for c in zip(chars, chars[1...]) { 37 i += 1 38 39 if i % 2 == 0 { 40 continue 41 } 42 43 guard let c1 = char_to_hex(c.0) else { 44 return nil 45 } 46 47 guard let c2 = char_to_hex(c.1) else { 48 return nil 49 } 50 51 ret.append((c1 << 4) | c2) 52 } 53 54 return ret 55 } 56 57 58 func hex_decode_id(_ str: String) -> Data? { 59 guard str.utf8.count == 64, let decoded = hex_decode(str) else { 60 return nil 61 } 62 63 return Data(decoded) 64 } 65 66 func hex_decode_noteid(_ str: String) -> NoteId? { 67 return hex_decode_id(str).map(NoteId.init) 68 } 69 70 func hex_decode_pubkey(_ str: String) -> Pubkey? { 71 return hex_decode_id(str).map(Pubkey.init) 72 } 73 74 func hex_decode_privkey(_ str: String) -> Privkey? { 75 return hex_decode_id(str).map(Privkey.init) 76 }