LNSocket.swift (1808B)
1 2 import Foundation 3 4 public class LNSocket { 5 var ln: OpaquePointer! 6 7 init() { 8 self.ln = lnsocket_create() 9 } 10 11 func genkey() { 12 lnsocket_genkey(self.ln) 13 } 14 15 func connect_and_init(node_id: String, host: String) -> Bool { 16 17 self.genkey() 18 19 guard self.connect(node_id: node_id, host: host) else { 20 return false 21 } 22 23 guard self.perform_init() else { 24 return false 25 } 26 27 return true 28 } 29 30 func connect(node_id: String, host: String) -> Bool { 31 node_id.withCString { p_node_id in 32 host.withCString { p_host in 33 return lnsocket_connect(self.ln, p_node_id, p_host) != 0 34 } 35 } 36 } 37 38 func write(_ data: Data) -> Bool { 39 var msg = Array(data) 40 return lnsocket_write(self.ln, &msg, UInt16(data.count)) != 0 41 } 42 43 func fd() -> Int32 { 44 var sock: Int32 = 0 45 lnsocket_fd(self.ln, &sock) 46 return sock 47 } 48 49 func recv() -> (UInt16, Data)? { 50 var msgtype: UInt16 = 0 51 var mpayload = UnsafeMutablePointer<UInt8>(nil) 52 var payload_len: UInt16 = 0 53 54 guard lnsocket_recv(self.ln, &msgtype, &mpayload, &payload_len) != 0 else { 55 return nil 56 } 57 58 guard let payload = mpayload else { 59 return nil 60 } 61 62 let data = Data(bytes: payload, count: Int(payload_len)) 63 64 return (msgtype, data) 65 } 66 67 func pong(ping: Data) { 68 var ping_ptr = Array(ping) 69 lnsocket_pong(self.ln, &ping_ptr, UInt16(ping.count)) 70 } 71 72 func perform_init() -> Bool { 73 return lnsocket_perform_init(self.ln) != 0 74 } 75 76 func print_errors() { 77 lnsocket_print_errors(self.ln) 78 } 79 80 deinit { 81 lnsocket_destroy(self.ln) 82 } 83 }