-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
362 lines (272 loc) · 10.2 KB
/
common.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
355
356
357
358
359
360
361
362
package common
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"strings"
"time"
"github.com/SummerCash/ursa/compiler"
"github.com/SummerCash/ursa/vm"
)
var (
// ErrNilInput - error definition describing input of 0 char length
ErrNilInput = errors.New("nil input")
// ErrVerboseNotAllowed - error definition describing config preventing print call
ErrVerboseNotAllowed = errors.New("verbose output not allowed")
// DataDir - global data directory definition
DataDir = getDataDir()
// ConfigDir - global config directory definition
ConfigDir = filepath.FromSlash(fmt.Sprintf("%s/config", DataDir))
// PeerToPeerDir - global p2p directory definition.
PeerToPeerDir = filepath.FromSlash(fmt.Sprintf("%s/p2p", DataDir))
// DisableTimestamps - global declaration for timestamp format config
DisableTimestamps = false
// GeneralTLSConfig - general global GoP2P TLS Config
GeneralTLSConfig = &tls.Config{ // Init TLS config
Certificates: []tls.Certificate{getTLSCerts("general")},
InsecureSkipVerify: true,
ServerName: "localhost",
}
// BootstrapNodes - global definition for set of bootstrap nodes
BootstrapNodes = []string{
"108.41.124.60:3000", // Boot node 0
}
// Silent - silent config
Silent = false
// NodePort - global port definition
NodePort = 3000
// VMConfig - global virtual machine config
VMConfig = vm.Environment{
EnableJIT: false, // Disable JIT
DefaultMemoryPages: 128, // Set default mem pages
DefaultTableSize: 65536, // Set default table size
}
// GasPolicy - global gas policy
GasPolicy = &compiler.SimpleGasPolicy{ //TODO: better gas policy
GasPerInstruction: 1,
}
)
/* BEGIN EXPORTED METHODS */
/*
BEGIN TERMINAL METHODS
*/
// Log - fmt.Println wrapper
func Log(a ...interface{}) (int, error) {
if !Silent { // Check verbose allowed
return fmt.Println(a...) // Log
}
return 0, ErrVerboseNotAllowed // Return error
}
// Logf - fmt.Printf wrapper
func Logf(format string, a ...interface{}) (int, error) {
if !Silent { // Check verbose allowed
if !DisableTimestamps { // Check timestamps not disabled
if strings.Contains(format, "==") { // Check room for formatting
format = fmt.Sprintf("[%s] ", time.Now().UTC().Format("Jan 2 03:04:05PM 2006")) + format // Append current time
}
}
return fmt.Printf(format, a...) // Print
}
return 0, ErrVerboseNotAllowed // Return error
}
// ParseStringMethodCall - attempt to parse string as method call, returning receiver, method name and params
func ParseStringMethodCall(input string) (string, string, []string, error) {
if input == "" { // Check for errors
return "", "", []string{}, ErrNilInput // Return found error
} else if !strings.Contains(input, "(") || !strings.Contains(input, ")") {
input = input + "()" // Fetch receiver methods
}
if !strings.Contains(input, ".") { // Check for nil receiver
return "", "", []string{}, errors.New("invalid method " + input) // Return found error
}
method := strings.Split(strings.Split(input, "(")[0], ".")[1] // Fetch method
receiver := StringFetchCallReceiver(input) // Fetch receiver
params := []string{} // Init buffer
if strings.Contains(input, ",") || !strings.Contains(input, "()") { // Check for nil params
params, _ = ParseStringParams(input) // Fetch params
}
return receiver, method, params, nil // No error occurred, return parsed method+params
}
// ParseStringMethodCallNoReceiver - attempt to parse string as method call, returning method name and params
func ParseStringMethodCallNoReceiver(input string) (string, []string, error) {
if input == "" { // Check for errors
return "", []string{}, ErrNilInput // Return found error
} else if !strings.Contains(input, "(") || !strings.Contains(input, ")") {
input = input + "()" // Fetch receiver methods
}
method := strings.Split(input, "(")[0] // Fetch method
params := []string{} // Init buffer
if !strings.Contains(input, "()") { // Check for nil params
params, _ = ParseStringParams(input) // Fetch params
}
return method, params, nil // No error occurred, return parsed method+params
}
// ParseStringParams - attempt to fetch string parameters from (..., ..., ...) style call
func ParseStringParams(input string) ([]string, error) {
if input == "" { // Check for errors
return []string{}, ErrNilInput // Return found error
}
parenthesesStripped := StringStripReceiverCall(input) // Strip parentheses
params := strings.Split(parenthesesStripped, ", ") // Split by ', '
return params, nil // No error occurred, return split params
}
// StringStripReceiverCall - strip receiver from string method call
func StringStripReceiverCall(input string) string {
openParenthIndex := strings.Index(input, "(") // Get open parent index
closeParenthIndex := strings.LastIndex(input, ")") // Get close parent index
return input[openParenthIndex+1 : closeParenthIndex] // Strip receiver
}
// StringStripParentheses - strip parantheses from string
func StringStripParentheses(input string) string {
leftStripped := strings.Replace(input, "(", "", -1) // Strip left parent
return strings.Replace(leftStripped, ")", "", -1) // Return right stripped
}
// StringFetchCallReceiver - attempt to fetch receiver from string, as if it were an x.y(..., ..., ...) style method call
func StringFetchCallReceiver(input string) string {
return strings.Split(strings.Split(input, "(")[0], ".")[0] // Return split string
}
/*
END TERMINAL METHODS
*/
/*
BEGIN TLS METHODS
*/
// GenerateTLSCertificates - generate necessary TLS certificates, keys
func GenerateTLSCertificates(namePrefix string) error {
_, certErr := os.Stat(fmt.Sprintf("%sCert.pem", namePrefix)) // Check for error reading file
_, keyErr := os.Stat(fmt.Sprintf("%sKey.pem", namePrefix)) // Check for error reading file
if os.IsNotExist(certErr) || os.IsNotExist(keyErr) { // Check for does not exist error
privateKey, err := generateTLSKey(namePrefix) // Generate key
if err != nil { // Check for errors
return err // Return found error
}
err = generateTLSCert(privateKey, namePrefix) // Generate cert
if err != nil { // Check for errors
return err // Return found error
}
}
return nil // No error occurred, return nil
}
/*
END TLS METHODS
*/
/*
BEGIN MAIN METHODS
*/
// Forever - prevent thread from closing
func Forever() {
for {
time.Sleep(time.Second)
}
}
/*
END MAIN METHODS
*/
/* END EXPORTED METHODS */
/* BEGIN INTERNAL METHODS */
/*
BEGIN TLS METHODS
*/
// generateTLSKey - generates necessary TLS key
func generateTLSKey(namePrefix string) (*ecdsa.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // Generate private key
if err != nil { // Check for errors
return nil, err // Return found error
}
marshaledPrivateKey, err := x509.MarshalECPrivateKey(privateKey) // Marshal private key
if err != nil { // Check for errors
return nil, err // Return found error
}
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: marshaledPrivateKey}) // Encode to memory
err = ioutil.WriteFile(fmt.Sprintf("%sKey.pem", namePrefix), pemEncoded, 0644) // Write pem
if err != nil { // Check for errors
return nil, err // Return found error
}
return privateKey, nil // No error occurred, return nil
}
// generateTLSCert - generates necessary TLS cert
func generateTLSCert(privateKey *ecdsa.PrivateKey, namePrefix string) error {
notBefore := time.Now() // Fetch current time
notAfter := notBefore.Add(292 * (365 * (24 * time.Hour))) // Fetch 'deadline'
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) // Init limit
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) // Init serial number
if err != nil { // Check for errors
return err // Return found error
}
template := x509.Certificate{ // Init template
SerialNumber: serialNumber, // Generate w/serial number
Subject: pkix.Name{ // Generate w/subject
Organization: []string{"localhost"}, // Generate w/org
},
NotBefore: notBefore, // Generate w/not before
NotAfter: notAfter, // Generate w/not after
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, // Generate w/key usage
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, // Generate w/ext key
BasicConstraintsValid: true, // Generate w/basic constraints
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(privateKey), privateKey) // Generate certificate
if err != nil { // Check for errors
return err // Return found error
}
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) // Encode pem
err = ioutil.WriteFile(fmt.Sprintf("%sCert.pem", namePrefix), pemEncoded, 0644) // Write cert file
if err != nil { // Check for errors
return err // Return found error
}
return nil // No error occurred, return nil
}
// getTLSCert - attempt to read TLS cert from current dir
func getTLSCerts(certPrefix string) tls.Certificate {
GenerateTLSCertificates(certPrefix) // Generate certs
cert, err := tls.LoadX509KeyPair(fmt.Sprintf("%sCert.pem", certPrefix), fmt.Sprintf("%sKey.pem", certPrefix)) // Load key pair
if err != nil { // Check for errors
panic(err) // Panic
}
return cert // Return read certificates
}
// publicKey - cast to public key
func publicKey(privateKey interface{}) interface{} {
switch k := privateKey.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
/*
END TLS METHODS
*/
/*
BEGIN MISC METHODS
*/
// getNonNilInStringSlice - get non nil string in slice
func getNonNilInStringSlice(slice []string) (string, error) {
for _, entry := range slice { // Iterate through entries
if entry != "" { // Check for non-nil entry
return entry, nil // Return valid entry
}
}
return "", fmt.Errorf("couldn't find non-nil element in slice %v", slice) // Couldn't find valid address, return error
}
// getDataDir - get absolute data dir
func getDataDir() string {
abs, _ := filepath.Abs("./data") // Get absolute dir
return filepath.FromSlash(abs) // Match slashes
}
/*
END MISC METHODS
*/
/* END INTERNAL METHODS */