-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
354 lines (314 loc) · 10.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package libkarai
import (
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"fmt"
"net/url"
"os"
"runtime"
"strings"
"github.com/gorilla/websocket"
)
const (
appName = "libkarai-go"
appDev = "RockSteadyTC"
appDescription = appName + " a Go library for interacting with Karai"
appLicense = "https://choosealicense.com/licenses/mit/"
appRepository = "https://github.com/karai/libkarai-go"
appURL = "https://karai.io"
)
var nc = "\033[0m"
// File & folder constants
const (
configDir = "./config"
configKeyDir = configDir + "/keys"
configHostsDir = configDir + "/hosts"
configTxDir = configDir + "/transactions"
configTxArchiveDir = configTxDir + "/archived/"
pubKeyFilePath = configKeyDir + "/" + "pub.key"
privKeyFilePath = configKeyDir + "/" + "priv.key"
signedKeyFilePath = configKeyDir + "/" + "signed.key"
selfCertFilePath = configKeyDir + "/" + "self.cert"
)
var (
isFirstTime bool
isTrusted bool
)
// Coordinator values
var (
joinMsg []byte = []byte("JOIN")
ncasMsg []byte = []byte("NCAS")
capkMsg []byte = []byte("CAPK")
certMsg []byte = []byte("CERT")
peerMsg []byte = []byte("PEER")
pubkMsg []byte = []byte("PUBK")
nsigMsg []byte = []byte("NSIG")
sendMsg []byte = []byte("SEND")
conn *websocket.Conn
upgrader = websocket.Upgrader{
EnableCompression: true,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
var (
brightblack = "\033[1;30m"
brightred = "\033[1;31m"
brightgreen = "\033[1;32m"
brightyellow = "\033[1;33m"
brightpurple = "\033[1;34m"
brightmagenta = "\033[1;35m"
brightcyan = "\033[1;36m"
brightwhite = "\033[1;37m"
black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
purple = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
)
// OSCheck Check for the OS
func OSCheck() {
if runtime.GOOS == "windows" {
nc = ""
brightblack = ""
brightred = ""
brightgreen = ""
brightyellow = ""
brightpurple = ""
brightmagenta = ""
brightcyan = ""
brightwhite = ""
black = ""
red = ""
green = ""
yellow = ""
purple = ""
magenta = ""
cyan = ""
white = ""
}
}
// ED25519Keys This is a struct for holding keys and a signature.
type ED25519Keys struct {
publicKey string
privateKey string
signedKey string
selfCert string
}
// Version Prints the semver of libkarai-go as string
func Version() string {
var major, minor, patch, version string
major = "0"
minor = "1"
patch = "2"
version = major + "." + minor + "." + patch
return version
}
// Send Takes a data string and a websocket connection
func Send(msg string, conn *websocket.Conn) error {
err := conn.WriteMessage(1, []byte("send "+msg))
handle("There was a problem sending your transaction ", err)
return err
}
// JoinChannel Takes a ktx address with port, boolean for new or returning, and keys. Outputs a websocket and CA cert
func JoinChannel(ktx, pubKey, signedKey, ktxCertFileName string, keyCollection *ED25519Keys) *websocket.Conn {
// request a websocket connection
conn := requestSocket(ktx, "1")
// using that connection, attempt to join the channel
joinedChannel := handShake(conn, pubKey)
// parse channel messages
socketMsgParser(ktx, pubKey, signedKey, joinedChannel, keyCollection)
// return the connection
return conn
}
func handShake(conn *websocket.Conn, pubKey string) *websocket.Conn {
// new users should send JOIN with the pubkey
if isFirstTime {
joinReq := "JOIN " + pubKey
_ = conn.WriteMessage(1, []byte(joinReq))
}
// returning users should send RTRN and the signed CA cert
if !isFirstTime {
certString := readFile(selfCertFilePath)
rtrnReq := "RTRN " + pubKey + " " + certString
_ = conn.WriteMessage(1, []byte(rtrnReq))
}
return conn
}
// func JoinChannel(ktx string, isNew bool, keyCollection *ED25519Keys) (*websocket.Conn, string) {
// // request a websocket connection
// var conn = requestSocket(ktx, "1")
// // using that connection, attempt to join the channel
// var joinedChannel = joinStatement(conn, isNew, keyCollection)
// // parse channel messages
// cert := socketMsgParser(ktx, joinedChannel, keyCollection)
// // return the connection
// return conn, cert
// }
func joinStatement(conn *websocket.Conn, isNew bool, keyCollection *ED25519Keys) *websocket.Conn {
// new users should send JOIN with the pubkey
if isNew {
joinReq := "JOIN " + keyCollection.publicKey[:64]
_ = conn.WriteMessage(1, []byte(joinReq))
}
// returning users should send RTRN and the signed CA cert
if !isNew {
rtrnReq := "RTRN " + keyCollection.publicKey[:64] + " " + keyCollection.selfCert
_ = conn.WriteMessage(1, []byte(rtrnReq))
}
return conn
}
func returnMessage(conn *websocket.Conn, pubKey string, keyCollection *ED25519Keys) *websocket.Conn {
if !isNew {
rtrnReq := "RTRN " + pubKey[:64] + " " + keyCollection.selfCert
_ = conn.WriteMessage(1, []byte(rtrnReq))
}
return conn
}
func requestSocket(ktx, protocolVersion string) *websocket.Conn {
urlConnection := url.URL{Scheme: "ws", Host: ktx, Path: "/api/v" + protocolVersion + "/channel"}
conn, _, err := websocket.DefaultDialer.Dial(urlConnection.String(), nil)
handle("There was a problem connecting to the channel: ", err)
return conn
}
// handle Ye Olde Error Handler takes a message and an error code
func handle(msg string, err error) {
if err != nil {
fmt.Printf(brightred+"\n%s: %s"+white, msg, err)
}
}
// createFile Generic file handler
func createFile(filename string) {
var _, err = os.Stat(filename)
if os.IsNotExist(err) {
var file, err = os.Create(filename)
handle("", err)
defer file.Close()
}
}
// writeFile Generic file handler
func writeFile(filename, textToWrite string) {
var file, err = os.OpenFile(filename, os.O_RDWR, 0644)
handle("", err)
defer file.Close()
_, err = file.WriteString(textToWrite)
err = file.Sync()
handle("", err)
}
// SignKey Takes a key set and an ed25519 public key string parameter to sign a key. Returns a signature of the key signed with the key set.
func SignKey(keyCollection *ED25519Keys, publicKey string) string {
messageBytes, err := hex.DecodeString(publicKey)
if err != nil {
panic(err)
}
privateKey, err := hex.DecodeString(keyCollection.privateKey)
if err != nil {
panic(err)
}
pubKey, err := hex.DecodeString(keyCollection.publicKey)
if err != nil {
panic(err)
}
privateKey = append(privateKey, pubKey...)
signature := ed25519.Sign(privateKey, messageBytes)
return hex.EncodeToString(signature)
}
func socketMsgParser(ktx, pubKey, signedKey string, conn *websocket.Conn, keyCollection *ED25519Keys) {
_, joinResponse, err := conn.ReadMessage()
handle("There was a problem reading the socket: ", err)
if strings.HasPrefix(string(joinResponse), "WCBK") {
isTrusted = true
isFirstTime = false
fmt.Printf(brightgreen + " ✔️\nConnected!\n" + white)
fmt.Printf("\nType `"+brightpurple+"send %s filename.json"+white+"` where filename.json is a file in %s to send a JSON object in a transaction.\n\n", ktx, configTxDir)
}
if strings.Contains(string(joinResponse), string(capkMsg)) {
convertjoinResponseString := string(joinResponse)
trimNewLinejoinResponse := strings.TrimRight(convertjoinResponseString, "\n")
trimCmdPrefix := strings.TrimPrefix(trimNewLinejoinResponse, "CAPK ")
ncasMsgtring := signKey(keyCollection, trimCmdPrefix[:64])
composedNcasMsgtring := string(ncasMsg) + " " + ncasMsgtring
_ = conn.WriteMessage(1, []byte(composedNcasMsgtring))
_, certResponse, err := conn.ReadMessage()
isFirstTime = false
convertStringcertResponse := string(certResponse) // keys := generateKeys()
trimNewLinecertResponse := strings.TrimRight(convertStringcertResponse, "\n")
trimCmdPrefixcertResponse := strings.TrimPrefix(trimNewLinecertResponse, "CERT ")
handle("There was an error receiving the certificate: ", err)
ktxCertFileName := configHostsDir + "/" + ktx + ".cert"
createFile(ktxCertFileName)
writeFile(ktxCertFileName, trimCmdPrefixcertResponse[:192])
fmt.Printf(brightgreen + "\nCert Name: ")
fmt.Printf(white+"%s", ktxCertFileName)
fmt.Printf(brightgreen + "\nCert Body: ")
fmt.Printf(white+"%s\n", trimCmdPrefixcertResponse[:192])
}
}
// GenerateKeys Generates ed25519 keyset as strings
func GenerateKeys() *ED25519Keys {
keys := ED25519Keys{}
pubKey, privKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
handle("error: ", err)
}
keys.privateKey = hex.EncodeToString(privKey[0:32])
keys.publicKey = hex.EncodeToString(pubKey)
signedKey := ed25519.Sign(privKey, pubKey)
keys.signedKey = hex.EncodeToString(signedKey)
keys.selfCert = keys.publicKey + keys.signedKey
return &keys
}
// // handle Ye Olde Error Handler takes a message and an error code
// func handle(msg string, err error) {
// if err != nil {
// fmt.Printf("\n%s: %s", msg, err)
// }
// }
// Sign Takes keys and a message to sign
func Sign(keyCollection *ED25519Keys, msg string) string {
messageBytes := []byte(msg)
privateKey, err := hex.DecodeString(keyCollection.privateKey)
if err != nil {
panic(err)
}
publicKey, err := hex.DecodeString(keyCollection.publicKey)
if err != nil {
panic(err)
}
privateKey = append(privateKey, publicKey...)
signature := ed25519.Sign(privateKey, messageBytes)
return hex.EncodeToString(signature)
}
// VerifySignature Takes a public key, a message, and a signature. This will return true if it verifies correctly.
func VerifySignature(publicKey string, msg, signature string) bool {
pubKey, err := hex.DecodeString(publicKey)
if err != nil {
panic(err)
}
messageBytes := []byte(msg)
sig, err := hex.DecodeString(signature)
if err != nil {
panic(err)
}
return ed25519.Verify(pubKey, messageBytes, sig)
}
// VerifySignedKey Takes a public key, a public signing key, and a signature. This will return true if it verifies correctly.
func VerifySignedKey(publicKey string, publicSigningKey string, signature string) bool {
pubKey, err := hex.DecodeString(publicKey)
if err != nil {
panic(err)
}
pubSignKey, err := hex.DecodeString(publicSigningKey)
if err != nil {
panic(err)
}
sig, err := hex.DecodeString(signature)
if err != nil {
panic(err)
}
return ed25519.Verify(pubSignKey, pubKey, sig)
}