/
utils.go
1905 lines (1761 loc) · 50.5 KB
/
utils.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The go-daylight Authors
// This file is part of the go-daylight library.
//
// The go-daylight library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-daylight library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-daylight library. If not, see <http://www.gnu.org/licenses/>.
package utils
import (
"archive/zip"
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
// "crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"math"
"math/rand"
"net"
"net/http"
"github.com/EGaaS/go-egaas-mvp/packages/consts"
"github.com/EGaaS/go-egaas-mvp/packages/lib"
"github.com/EGaaS/go-egaas-mvp/packages/static"
"github.com/EGaaS/go-egaas-mvp/packages/textproc"
"github.com/kardianos/osext"
// _ "github.com/lib/pq"
"github.com/mcuadros/go-version"
"github.com/shopspring/decimal"
// "net/mail"
// "net/smtp"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
// BlockData is a structure of the block's header
type BlockData struct {
BlockId int64
Time int64
WalletId int64
StateID int64
Sign []byte
Hash []byte
}
// DaemonsChansType is a structure for deamons
type DaemonsChansType struct {
ChBreaker chan bool
ChAnswer chan string
}
var (
// FirstBlockDir is a folder where 1block file will be stored
FirstBlockDir = flag.String("firstBlockDir", "", "FirstBlockDir")
// FirstBlockPublicKey is the private key
FirstBlockPublicKey = flag.String("firstBlockPublicKey", "", "FirstBlockPublicKey")
// FirstBlockNodePublicKey is the node private key
FirstBlockNodePublicKey = flag.String("firstBlockNodePublicKey", "", "FirstBlockNodePublicKey")
// FirstBlockHost is the host of the first block
FirstBlockHost = flag.String("firstBlockHost", "", "FirstBlockHost")
// WalletAddress is a wallet address for forging
WalletAddress = flag.String("walletAddress", "", "walletAddress for forging ")
// TCPHost is the tcp host
TCPHost = flag.String("tcpHost", "", "tcpHost (e.g. 127.0.0.1)")
// ListenHTTPPort is HTTP port
ListenHTTPPort = flag.String("listenHttpPort", "7079", "ListenHTTPPort")
// GenerateFirstBlock show if the first block must be generated
GenerateFirstBlock = flag.Int64("generateFirstBlock", 0, "generateFirstBlock")
// OldVersion is the number of the old version
OldVersion = flag.String("oldVersion", "", "")
// TestRollBack equals 1 for testing rollback
TestRollBack = flag.Int64("testRollBack", 0, "testRollBack")
// Dir is EGAAS folder
Dir = flag.String("dir", GetCurrentDir(), "DayLight directory")
// OldFileName is the old file name
OldFileName = flag.String("oldFileName", "", "")
// LogLevel is the log level
LogLevel = flag.String("logLevel", "", "DayLight LogLevel")
// Console equals 1 for starting in console
Console = flag.Int64("console", 0, "Start from console")
// StartBlockID is the start block
StartBlockID = flag.Int64("startBlockId", 0, "Start block for blockCollection daemon")
// EndBlockID is the end block
EndBlockID = flag.Int64("endBlockId", 0, "End block for blockCollection daemon")
// RollbackToBlockID is the target block for rollback
RollbackToBlockID = flag.Int64("rollbackToBlockId", 0, "Rollback to block_id")
// TLS is a directory for .well-known and keys. It is required for https
TLS = flag.String("tls", "", "Support https. Specify directory for .well-known")
// DevTools switches on dev tools in thrust shell
DevTools = flag.Int64("devtools", 0, "Devtools in thrust-shell")
// BoltDir is the edir for BoltDb folder
BoltDir = flag.String("boltDir", GetCurrentDir(), "Bolt directory")
// BoltPsw is the password for BoltDB
BoltPsw = flag.String("boltPsw", "", "Bolt password")
// APIToken is an api token for exchange api
APIToken = flag.String("apiToken", "", "API Token")
// OneCountry is the country which is supported
OneCountry int64
// PrivCountry is protect system from registering
PrivCountry bool
// OutFile *os.File
// LogoExt is the extension of the logotype
LogoExt = `png`
// DltWalletID is the wallet identifier
DltWalletID = flag.Int64("dltWalletId", 0, "DltWalletID")
// DaemonsChans is a slice of DaemonsChansType
DaemonsChans []*DaemonsChansType
// Thrust is true for thrust shell
Thrust bool
)
func init() {
flag.Parse()
}
// IOS checks if the app runs on iOS
func IOS() bool {
if (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") && runtime.GOOS == "darwin" {
return true
}
return false
}
// Desktop checks if the app runs on the desktop with thrust_shell
func Desktop() bool {
thrustShell := "thrust_shell"
if runtime.GOOS == "windows" {
thrustShell = "thrust_shell.exe"
} else if runtime.GOOS == "darwin" {
thrustShell = "ThrustShell"
}
if _, err := os.Stat(*Dir + "/" + thrustShell); err == nil {
return true
}
return false
}
// Mobile checks if the app runs on Android or iOS
func Mobile() bool {
if IOS() || runtime.GOOS == "android" {
return true
}
return false
}
// Android checks if the app runs on Android
func Android() bool {
if runtime.GOOS == "android" {
return true
}
return false
}
// Sleep makes a pause during sec seconds
func Sleep(sec time.Duration) {
time.Sleep(sec * time.Second)
}
// ParseBlockHeader parses the header of the block
func ParseBlockHeader(binaryBlock *[]byte) *BlockData {
result := new(BlockData)
// Parse the heading of a block
/*
The heading
TYPE(0-block, 1-transaction)
BLOCK_ID 4
TIME 4
WALLET_ID 1-8
state_id 1
SIGN from 128 to 512 байт. Signature from TYPE, BLOCK_ID, PREV_BLOCK_HASH, TIME, WALLET_ID, state_id, MRKL_ROOT
Further is body block (transaction)
*/
result.BlockId = BinToDecBytesShift(binaryBlock, 4)
result.Time = BinToDecBytesShift(binaryBlock, 4)
result.WalletId, _ = lib.DecodeLenInt64(binaryBlock) //BytesToInt64(BytesShift(binaryBlock, DecodeLength(binaryBlock)))
// Delete after re-build blocks
/* if result.WalletId == 0x31 {
result.WalletId = 1
}*/
result.StateID = BinToDecBytesShift(binaryBlock, 1)
if result.BlockId > 1 {
signSize := DecodeLength(binaryBlock)
result.Sign = BytesShift(binaryBlock, signSize)
} else {
*binaryBlock = (*binaryBlock)[1:]
}
log.Debug("result.BlockId: %v / result.Time: %v / result.WalletId: %v / result.StateID: %v / result.Sign: %v", result.BlockId, result.Time, result.WalletId, result.StateID, result.Sign)
return result
}
/*
func Round(f float64, places int) (float64) {
if places==0 {
return math.Floor(f + .5)
} else {
shift := math.Pow(10, float64(places))
return math.Floor((f * shift)+.5) / shift;
}
}
*/
func round(num float64) int64 {
//log.Debug("num", num)
//num += ROUND_FIX
// return int(StrToFloat64(Float64ToStr(num)) + math.Copysign(0.5, num))
//log.Debug("num", num)
return int64(num + math.Copysign(0.5, num))
}
// Round rounds float64 value
func Round(num float64, precision int) float64 {
num += consts.ROUND_FIX
output := math.Pow(10, float64(precision))
return float64(round(num*output)) / output
}
// RandInt returns a random integer between min and max
func RandInt(min int, max int) int {
if max-min <= 0 {
return 1
}
return min + rand.Intn(max-min)
}
// CheckInputData checks the input data
func CheckInputData(idata interface{}, dataType string) bool {
var data string
switch idata.(type) {
case int:
data = IntToStr(idata.(int))
case int64:
data = Int64ToStr(idata.(int64))
case float64:
data = Float64ToStr(idata.(float64))
case string:
data = idata.(string)
case []byte:
data = string(idata.([]byte))
}
log.Debug("CheckInputData:" + data)
log.Debug("dataType:" + dataType)
switch dataType {
case "arbitration_trust_list":
if ok, _ := regexp.MatchString(`^\[[0-9]{1,10}(,[0-9]{1,10}){0,100}\]$`, data); ok {
return true
}
case "abuse_comment", "vote_comment":
if ok, _ := regexp.MatchString(`^(?i)[0-9a-z\,\s\.\-]{1,255}$`, data); ok {
return true
}
case "private_key":
if ok, _ := regexp.MatchString(`^[0-9a-fA-F]+$`, data); ok {
if len(data) == 64 {
return true
}
}
case "votes_comment", "cf_comment":
if ok, _ := regexp.MatchString(`^[\pL0-9\,\s\.\-\:\=\;\?\!\%\)\(\@\/\n\r]{1,140}$`, data); ok {
return true
}
case "type":
if ok, _ := regexp.MatchString(`^[\w]+$`, data); ok {
if StrToInt(data) <= 30 {
return true
}
}
case "word":
if ok, _ := regexp.MatchString(`^(?i)[a-z]+$`, data); ok {
if StrToInt(data) <= 1024 {
return true
}
}
case "currency_name", "state_name":
if ok, _ := regexp.MatchString(`^[\pL0-9\,\s\.\-\:\=\;\?\!\%\)\(\@\/\n\r]{1,20}$`, data); ok {
if StrToInt(data) <= 1024 {
return true
}
}
case "string":
if ok, _ := regexp.MatchString(`^[\w]+$`, data); ok {
if StrToInt(data) <= 1024 {
return true
}
}
case "referral":
if ok, _ := regexp.MatchString(`^[0-9]{1,2}$`, data); ok {
if StrToInt(data) <= 30 {
return true
}
}
case "currency_id":
if ok, _ := regexp.MatchString(`^[0-9]{1,3}$`, data); ok {
if StrToInt(data) <= 255 {
return true
}
}
case "system_commission":
if ok, _ := regexp.MatchString(`^[0-9]{1,3}$`, data); ok {
if StrToInt(data) <= 15 && StrToInt(data) >= 5 {
return true
}
}
case "tinyint":
if ok, _ := regexp.MatchString(`^[0-9]{1,3}$`, data); ok {
if StrToInt(data) <= 127 {
return true
}
}
case "smallint":
if ok, _ := regexp.MatchString(`^[0-9]{1,5}$`, data); ok {
if StrToInt(data) <= 65535 {
return true
}
}
case "column_type":
if ok, _ := regexp.MatchString(`^(text|int64|time|hash|money|double)$`, data); ok {
return true
}
case "avatar":
regex := `https?\:\/\/` // SCHEME
regex += `[\w-.]*\.[a-z]{2,4}` // Host or IP
regex += `(\:[0-9]{2,5})?` // Port
regex += `(\/[\w_-]+)*\/?` // Path
regex += `\.(png|jpg)` // Img
if ok, _ := regexp.MatchString(`^`+regex+`$`, data); ok {
if len(data) < 100 {
return true
}
}
case "img_url":
regex := `https?\:\/\/` // SCHEME
regex += `[\w-.]*\.[a-z]{2,4}` // Host or IP
regex += `(\:[0-9]{2,5})?` // Port
regex += `(\/[\w_-]+)*\/?` // Path
regex += `\.(png|jpg)` // Img
if ok, _ := regexp.MatchString(`^`+regex+`$`, data); ok {
if len(data) < 50 {
return true
}
}
case "ca_url", "arbitrator_url":
regex := `https?\:\/\/` // SCHEME
regex += `[\w-.]*\.[a-z]{2,4}` // Host or IP
regex += `(\:[0-9]{2,5})?` // Port
regex += `(\/[\w_-]+)*\/?` // Path
if ok, _ := regexp.MatchString(`^`+regex+`$`, data); ok {
if len(data) <= 30 {
return true
}
}
case "credit_pct", "pct":
if ok, _ := regexp.MatchString(`^[0-9]{1,3}(\.[0-9]{2})?$`, data); ok {
return true
}
case "user_name":
if ok, _ := regexp.MatchString(`^[\w\s]{1,30}$`, data); ok {
return true
}
case "admin_currency_list":
if ok, _ := regexp.MatchString(`^((\d{1,3}\,){0,9}\d{1,3}|ALL)$`, data); ok {
return true
}
case "users_ids":
if ok, _ := regexp.MatchString(`^([0-9]{1,12},){0,1000}[0-9]{1,12}$`, data); ok {
return true
}
case "version":
if ok, _ := regexp.MatchString(`^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}([a-z]{1,2}[0-9]{1,2})?$`, data); ok {
return true
}
case "soft_type":
if ok, _ := regexp.MatchString(`^[a-z]{3,10}$`, data); ok {
return true
}
case "currency_full_name":
if ok, _ := regexp.MatchString(`^[a-zA-Z\s]{3,50}$`, data); ok {
return true
}
case "currency_commission":
if ok, _ := regexp.MatchString(`^[0-9]{1,7}(\.[0-9]{1,2})?$`, data); ok {
return true
}
case "sell_rate":
if ok, _ := regexp.MatchString(`^[0-9]{0,10}(\.[0-9]{0,10})?$`, data); ok {
return true
}
case "amount":
if ok, _ := regexp.MatchString(`^[0-9]{0,10}(\.[0-9]{0,2})?$`, data); ok {
return true
}
case "amount_btc":
if ok, _ := regexp.MatchString(`^[0-9]{0,10}(\.[0-9]{0,5})?$`, data); ok {
return true
}
case "tpl_name":
if ok, _ := regexp.MatchString("^[\\w]{1,30}$", data); ok {
return true
}
case "example_spots":
r1 := `"\d{1,2}":\["\d{1,3}","\d{1,3}",(\[("[a-z_]{1,30}",?){0,20}\]|""),"\d{1,2}","\d{1,2}"\]`
reg := `^\{(\"(face|profile)\":\{(` + r1 + `,?){1,20}\},?){2}}$`
if ok, _ := regexp.MatchString(reg, data); ok {
return true
}
case "segments":
r1 := `"\d{1,2}":\["\d{1,2}","\d{1,2}"\]`
face := `"face":\{(` + r1 + `\,){1,20}` + r1 + `\}`
profile := `"profile":\{(` + r1 + `\,){1,20}` + r1 + `\}`
reg := `^\{` + face + `,` + profile + `\}$`
if ok, _ := regexp.MatchString(reg, data); ok {
return true
}
case "tolerances":
r1 := `"\d{1,2}":"0\.\d{1,2}"`
face := `"face":\{(` + r1 + `\,){1,50}` + r1 + `\}`
profile := `"profile":\{(` + r1 + `\,){1,50}` + r1 + `\}`
reg := `^\{` + face + `,` + profile + `\}$`
if ok, _ := regexp.MatchString(reg, data); ok {
return true
}
case "compatibility":
if ok, _ := regexp.MatchString(`^\[(\d{1,5},)*\d{1,5}\]$`, data); ok {
return true
}
case "race":
if ok, _ := regexp.MatchString("^[1-3]$", data); ok {
return true
}
case "country":
if ok, _ := regexp.MatchString("^[0-9]{1,3}$", data); ok {
return true
}
case "vote", "boolean":
if ok, _ := regexp.MatchString(`^0|1$`, data); ok {
return true
}
case "coordinate":
if ok, _ := regexp.MatchString(`^\-?[0-9]{1,3}(\.[0-9]{1,5})?$`, data); ok {
return true
}
case "cf_links":
regex := `\["https?\:\/\/(goo\.gl|bit\.ly|t\.co)\/[\w-]+",[0-9]+,[0-9]+,[0-9]+,[0-9]+\]`
if ok, _ := regexp.MatchString(`^\[`+regex+`(\,`+regex+`)*\]$`, data); ok {
if len(data) < 512 {
return true
}
}
case "http_host":
if ok, _ := regexp.MatchString(`^https?:\/\/[0-9a-z\_\.\-\/:]{1,100}[\/]$`, data); ok {
return true
}
case "e_host":
if ok, _ := regexp.MatchString(`^https?:\/\/[0-9a-z\_\.\-\/:]{1,100}[\/]$`, data); ok || data == "0" {
return true
}
case "host":
if ok, _ := regexp.MatchString(`^(?i)[0-9a-z\_\.\-]{1,100}$`, data); ok {
return true
}
case "tcp_host":
if ok, _ := regexp.MatchString(`^(?i)[0-9a-z\_\.\-]{1,100}:[0-9]+$`, data); ok {
return true
}
case "coords":
xy := `\[\d{1,3}\,\d{1,3}\]`
r := `^\[(` + xy + `\,){}` + xy + `\]$`
if ok, _ := regexp.MatchString(r, data); ok {
return true
}
case "lang":
if ok, _ := regexp.MatchString("^(en|ru)$", data); ok {
return true
}
case "payment_systems_ids":
if ok, _ := regexp.MatchString("^([0-9]{1,4},){0,4}[0-9]{1,4}$", data); ok {
return true
}
case "video_type":
if ok, _ := regexp.MatchString("^(youtube|vimeo|youku|null)$", data); ok {
return true
}
case "video_url_id", "sn_url_id":
if ok, _ := regexp.MatchString("^(?i)(null|[0-9a-z_\\-\\.]{2,32})$", data); ok {
return true
}
case "sn_type":
if ok, _ := regexp.MatchString("^(vk|fb|qq)$", data); ok {
return true
}
case "sha1":
if ok, _ := regexp.MatchString("^[0-9a-z]{40}$", data); ok {
return true
}
case "walletAddress":
if ok, _ := regexp.MatchString("^(?i)[0-9]{20}$", strings.Replace(data, `-`, ``, -1)); ok {
return true
}
case "photo_hash", "sha256":
if ok, _ := regexp.MatchString("^[0-9a-z]{64}$", data); ok {
return true
}
case "cash_code":
if ok, _ := regexp.MatchString("^[0-9a-z]{32}$", data); ok {
return true
}
case "alert":
if ok, _ := regexp.MatchString("^[\\pL0-9\\,\\s\\.\\-\\:\\=\\;\\?\\!\\%\\)\\(\\@\\/]{1,512}$", data); ok {
return true
}
case "int":
if ok, _ := regexp.MatchString("^[0-9]{1,10}$", data); ok {
return true
}
case "float":
if ok, _ := regexp.MatchString(`^[0-9]{1,5}(\.[0-9]{1,5})?$`, data); ok {
return true
}
case "sleep_var":
if ok, _ := regexp.MatchString(`^\{\"is_ready\"\:\[([0-9]{1,5},){1,100}[0-9]{1,5}\],\"generator\"\:\[([0-9]{1,5},){1,100}[0-9]{1,5}\]\}$`, data); ok {
return true
}
case "int64", "bigint", "user_id":
if ok, _ := regexp.MatchString("^-?[0-9]{1,20}$", data); ok {
return true
}
case "decimal": // 1.2345678e+25
if ok, _ := regexp.MatchString(`^([0-9]{1,30})|([0-9]+\.[0-9]+[e]\+\[0-9]+)$`, data); ok {
return true
}
case "level":
if StrToInt(data) >= 0 && StrToInt(data) <= 34 {
return true
}
case "comment":
if len(data) >= 1 && len(data) <= 512 {
return true
}
case "conditions":
if len(data) <= 1024 {
return true
}
case "hex_sign", "hex", "public_key":
if ok, _ := regexp.MatchString("^[0-9a-z]+$", data); ok {
if len(data) < 2048 {
return true
}
}
case "account":
if ok, _ := regexp.MatchString(`^[0-9a-zA-Z\-\s_\+\#\:]{1,50}$`, data); ok {
return true
}
case "method":
if ok, _ := regexp.MatchString(`^[0-9a-zA-Z\-\_]{1,30}$`, data); ok {
return true
}
}
return false
}
// Time returns th ecurrent Unix time
func Time() int64 {
return time.Now().Unix()
}
// ValidateEmail validates email
func ValidateEmail(email string) bool {
Re := regexp.MustCompile(`^(?i)[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return Re.MatchString(email)
}
// GetHTTPTextAnswer returns HTTP answer as a string
func GetHTTPTextAnswer(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
htmlData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode == 404 {
err = fmt.Errorf(`404`)
}
return string(htmlData), err
}
// StrToInt64 converts string to int64
func StrToInt64(s string) int64 {
int64, _ := strconv.ParseInt(s, 10, 64)
return int64
}
// BytesToInt64 converts []bytes to int64
func BytesToInt64(s []byte) int64 {
int64, _ := strconv.ParseInt(string(s), 10, 64)
return int64
}
// StrToUint64 converts string to the unsinged int64
func StrToUint64(s string) uint64 {
ret, _ := strconv.ParseUint(s, 10, 64)
return ret
}
// StrToInt converts string to integer
func StrToInt(s string) int {
i, _ := strconv.Atoi(s)
return i
}
// Float64ToStr converts float64 to string
func Float64ToStr(f float64) string {
return strconv.FormatFloat(f, 'f', 13, 64)
}
// StrToFloat64 converts string to float64
func StrToFloat64(s string) float64 {
Float64, _ := strconv.ParseFloat(s, 64)
return Float64
}
// BytesToFloat64 converts []byte to float64
func BytesToFloat64(s []byte) float64 {
Float64, _ := strconv.ParseFloat(string(s), 64)
return Float64
}
// BytesToInt converts []byte to integer
func BytesToInt(s []byte) int {
i, _ := strconv.Atoi(string(s))
return i
}
// StrToMoney rounds money string to float64
func StrToMoney(str string) float64 {
ind := strings.Index(str, ".")
new := ""
if ind != -1 {
end := 2
if len(str[ind+1:]) > 1 {
end = 3
}
new = str[:ind] + "." + str[ind+1:ind+end]
} else {
new = str
}
return StrToFloat64(new)
}
// GetEndBlockID returns the end block id
func GetEndBlockID() (int64, error) {
if _, err := os.Stat(*Dir + "/public/blockchain"); os.IsNotExist(err) {
return 0, nil
}
// size of a block recorded into the last 5 bytes of blockchain file
fname := *Dir + "/public/blockchain"
file, err := os.Open(fname)
if err != nil {
return 0, ErrInfo(err)
}
defer file.Close()
fi, err := file.Stat()
if err != nil {
log.Fatal(err)
}
if fi.Size() == 0 {
return 0, ErrInfo("/public/blockchain size=0")
}
// size of a block recorded into the last 5 bytes of blockchain file
_, err = file.Seek(-5, 2)
if err != nil {
return 0, ErrInfo(err)
}
buf := make([]byte, 5)
_, err = file.Read(buf)
if err != nil {
return 0, ErrInfo(err)
}
size := BinToDec(buf)
if size > consts.MAX_BLOCK_SIZE {
return 0, ErrInfo("size > conts.MAX_BLOCK_SIZE")
}
// block itself
_, err = file.Seek(-(size + 5), 2)
if err != nil {
return 0, ErrInfo(err)
}
dataBinary := make([]byte, size+5)
_, err = file.Read(dataBinary)
if err != nil {
return 0, ErrInfo(err)
}
// size (block id + body of a block)
BinToDecBytesShift(&dataBinary, 5)
return BinToDecBytesShift(&dataBinary, 5), nil
}
// DownloadToFile downloads and saves the specified file
func DownloadToFile(url, file string, timeoutSec int64, DaemonCh chan bool, AnswerDaemonCh chan string, GoroutineName string) (int64, error) {
f, err := os.Create(file)
if err != nil {
return 0, ErrInfo(err)
}
defer f.Close()
timeout := time.Duration(time.Duration(timeoutSec) * time.Second)
client := http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
if err != nil {
return 0, ErrInfo(err)
}
defer resp.Body.Close()
var offset int64
for {
if DaemonCh != nil {
select {
case <-DaemonCh:
if GoroutineName == "NodeVoting" {
DB.DbUnlock(GoroutineName)
}
AnswerDaemonCh <- GoroutineName
return offset, fmt.Errorf("daemons restart")
default:
}
}
data, err := ioutil.ReadAll(io.LimitReader(resp.Body, 10000))
if err != nil {
return offset, ErrInfo(err)
}
f.WriteAt(data, offset)
offset += int64(len(data))
if len(data) == 0 {
break
}
log.Debug("read %s", url)
}
return offset, nil
}
// ErrInfoFmt fomats the error message
func ErrInfoFmt(err string, a ...interface{}) error {
return fmt.Errorf("%s (%s)", fmt.Sprintf(err, a...), Caller(1))
}
// ErrInfo formats the error message
func ErrInfo(verr interface{}, additionally ...string) error {
var err error
switch verr.(type) {
case error:
err = verr.(error)
case string:
err = errors.New(verr.(string))
}
if err != nil {
if len(additionally) > 0 {
return fmt.Errorf("%s # %s (%s)", err, additionally, Caller(1))
}
return fmt.Errorf("%s (%s)", err, Caller(1))
}
return err
}
// CallMethod calls the function by its name
func CallMethod(i interface{}, methodName string) interface{} {
var ptr reflect.Value
var value reflect.Value
var finalMethod reflect.Value
value = reflect.ValueOf(i)
// if we start with a pointer, we need to get value pointed to
// if we start with a value, we need to get a pointer to that value
if value.Type().Kind() == reflect.Ptr {
ptr = value
value = ptr.Elem()
} else {
ptr = reflect.New(reflect.TypeOf(i))
temp := ptr.Elem()
temp.Set(value)
}
// check for method on value
method := value.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}
// check for method on pointer
method = ptr.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}
if finalMethod.IsValid() {
return finalMethod.Call([]reflect.Value{})[0].Interface()
}
// return or panic, method not found of either type
return fmt.Errorf("method %s not found", methodName)
}
// Caller returns the name of the latest function
func Caller(steps int) string {
name := "?"
if pc, _, num, ok := runtime.Caller(steps + 1); ok {
//fmt.Println(num)
name = fmt.Sprintf("%s : %d", filepath.Base(runtime.FuncForPC(pc).Name()), num)
}
return name
}
// InSliceString searches the string in the slice of strings
func InSliceString(search string, slice []string) bool {
for _, v := range slice {
if v == search {
return true
}
}
return false
}
// EncodeLengthPlusData encoding interface into []byte
func EncodeLengthPlusData(idata interface{}) []byte {
var data []byte
switch idata.(type) {
case int64:
data = Int64ToByte(idata.(int64))
case string:
data = []byte(idata.(string))
case []byte:
data = idata.([]byte)
}
//log.Debug("data: %x", data)
//log.Debug("len data: %d", len(data))
return append(lib.EncodeLength(int64(len(data))), data...)
}
// UInt32ToStr converts uint32 to string
func UInt32ToStr(num uint32) string {
return strconv.FormatInt(int64(num), 10)
}
// Int64ToStr converts int64 to string
func Int64ToStr(num int64) string {
return strconv.FormatInt(num, 10)
}
// Int64ToByte converts int64 to []byte
func Int64ToByte(num int64) []byte {
return []byte(strconv.FormatInt(num, 10))
}
// IntToStr converts integer to string
func IntToStr(num int) string {
return strconv.Itoa(num)
}
// DecToBin converts interface to []byte
func DecToBin(v interface{}, sizeBytes int64) []byte {
var dec int64
switch v.(type) {
case int:
dec = int64(v.(int))
case int64:
dec = v.(int64)
case string:
dec = StrToInt64(v.(string))
}
Hex := fmt.Sprintf("%0"+Int64ToStr(sizeBytes*2)+"x", dec)
return HexToBin([]byte(Hex))
}
// BinToHex converts interface to hex []byte
func BinToHex(v interface{}) []byte {
var bin []byte
switch v.(type) {
case []byte:
bin = v.([]byte)
case int64:
bin = Int64ToByte(v.(int64))
case string:
bin = []byte(v.(string))
}
return []byte(fmt.Sprintf("%x", bin))
}
// HexToBin converts hex interface to binary []byte
func HexToBin(ihexdata interface{}) []byte {
var hexdata string
switch ihexdata.(type) {
case []byte:
hexdata = string(ihexdata.([]byte))
case int64:
hexdata = Int64ToStr(ihexdata.(int64))
case string:
hexdata = ihexdata.(string)
}
var str []byte
str, err := hex.DecodeString(hexdata)
if err != nil {
log.Error("%v / %v", err, GetParent())
}
return str
}
// BinToDec converts input binary []byte to int64
func BinToDec(bin []byte) int64 {
var a uint64
l := len(bin)
for i, b := range bin {
shift := uint64((l - i - 1) * 8)
a |= uint64(b) << shift
}
return int64(a)
}
// BinToDecBytesShift converts the input binary []byte to int64 and shifts the input bin
func BinToDecBytesShift(bin *[]byte, num int64) int64 {
return BinToDec(BytesShift(bin, num))
}
// BytesShift returns the index bytes of the input []byte and shift str pointer
func BytesShift(str *[]byte, index int64) (ret []byte) {
if int64(len(*str)) < index || index == 0 {
*str = (*str)[:0]
return []byte{}
}
ret, *str = (*str)[:index], (*str)[index:]
return
}
// InterfaceToStr converts the interfaces to the string
func InterfaceToStr(v interface{}) string {
var str string
switch v.(type) {
case int:
str = IntToStr(v.(int))
case float64:
str = Float64ToStr(v.(float64))
case int64:
str = Int64ToStr(v.(int64))
case string:
str = v.(string)
case []byte:
str = string(v.([]byte))
default:
if reflect.TypeOf(v).String() == `decimal.Decimal` {
str = v.(decimal.Decimal).String()
}
}
return str
}
// InterfaceSliceToStr converts the slice of interfaces to the slice of strings
func InterfaceSliceToStr(i []interface{}) []string {
var str []string
for _, v := range i {
str = append(str, InterfaceToStr(v))
}
return str
}