-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmixin_snap.go
1337 lines (1240 loc) · 41.6 KB
/
mixin_snap.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strconv"
"time"
messenger "github.com/MooooonStar/mixin-sdk-go/messenger"
mixin "github.com/MooooonStar/mixin-sdk-go/network"
"github.com/gofrs/uuid"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
const (
userid = "3c5fd587-5ac3-4fb6-b294-423ba3473f7d"
sessionid = "82365995-4d86-4676-a632-4354f1a04954"
private_key = `-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQCIJJ+PfATaR3UDegG13fs0Rgx21+jpEB/aVOqrDNQUmuY5k/MC
GRicNeIa+J2gT6lzPfWDL8z5IABnlc6EgI4BKM1ok0UgeQy/DWvDAmik47vEMpjU
JjKwgwyarQA/yWl1R/9djt/cVOwxekOXJqNAjsfGzjArgUAzBZ3OYNr15wIDAQAB
AoGAL5kmVCMXCz3KcmG4sV4f0qHe/7nzC3EAwfPIa+87Qsz5Sw4n+wbNLOhF2gos
Cf1wEAOMj8YpkrwWiCC/KGJNwyGvCMWs166oA0KFPeMhpKMlqXE+DpNJQzit3mb1
nZf18MXSMHw2u8LFfMDjJb2QZTOMVvWjYKnVg1AchfcPbeECQQDtW26N9lMTlzXO
MxrtheenHuSEgm55wGRhKquxDpXbJNcalHAnIvfd5tGbuciMbVlEk01MF7ggEWID
IhSHXhvRAkEAktYRV2XetVvF13orMGMPag9akdCjCpnA8Yxn11S0HSGsM6nkrMKl
i7t+qDTjNUODsnOMzb34iJCNtaaHGL48NwJBAKiQ6Yfaaw+bsLObKcGL+oN+dg4B
T5IZ52/2TO62jAiRNk6DIs84j03BUhVFML9CHUaNUjT7F2F21uOgvXGRjTECQQCG
Uq2qddY1sa5aX7gCm5wOOd1wZpu/pseKMBcONL5Pp+4PlOtL3wPxv6Mt3LO8lfZz
2KCF1bL1usbn1V7gk6YhAkEAhegwxueVDfayjuOSX0yHKY6VAECELpCqpNy1YEon
9oKozCDe1Kg/ZLWGMP9cIayb/eyUjJeyUPP8dR2rfhFBkA==
-----END RSA PRIVATE KEY-----`
ADMIN_MessengerID = "31367"
)
type Snapshot struct {
Amount string `json:"amount"`
Asset struct {
AssetId string `json:"asset_id"`
} `json:"asset"`
AssetId string `json:"asset_id"`
CreatedAt time.Time `json:"created_at"`
SnapshotId string `json:"snapshot_id"`
Source string `json:"source"`
Type string `json:"type"`
//only available when http request include correct token
UserId string `json:"user_id"`
TraceId string `json:"trace_id"`
OpponentId string `json:"opponent_id"`
Sender string `json:"sender"`
Data string `json:"data"`
Transactionhash string `json:"transaction_hash"`
}
type Payment_Record struct {
Amount string
AssetId string
CreatedAt time.Time `json:"created_at"`
SnapshotId string `json:"snapshot_id"`
}
type Profile struct {
CreatedAt time.Time `json:"created_at"`
}
type DepositAddressResonse struct {
PublicKey string `json:"public_key"`
AccountName string `json:"account_name"`
AccountTag string `json:"account_tag"`
IconURL string `json:"icon_url"`
Confirmblock uint `json:"confirmations"`
Symbol string `json:"symbol"`
Name string `json:"name"`
Chainid string `json:"chain_id"`
Assetkey string `json:"asset_key"`
Assetid string `json:"asset_id"`
Priceusd string `json:"price_usd"`
Pricebtc string `json:"price_btc"`
}
type DepositNetResponse struct {
Error error
Accountid string
Assetid string
MixinResponse MixinDepositResponse
}
type MixinDepositResponse struct {
Data *DepositAddressResonse `json:"data"`
Error string `json:"error"`
}
type Snapshotindb struct {
gorm.Model
SnapshotId string `gorm:"primary_key"`
Amount string
AssetId string `gorm:"index"`
Source string `gorm:"index"`
SnapCreatedAt time.Time
UserId string `gorm:"index"`
TraceId string
OpponentId string
Data string
OPType string
}
type MixinAccountindb struct {
gorm.Model
Userid string `gorm:"primary_key"`
Sessionid string
Pintoken string
Privatekey string
Pin string
ClientReqid uint
Utccreated_at time.Time
}
type DepositAddressindb struct {
gorm.Model
Accountrecord_id uint
Assetid string
Publicaddress string
Accountname string
Accounttag string
Iconurl string
Confirmblock uint
}
type AssetInformationindb struct {
gorm.Model
Assetid string
Chainid string
Symbol string
Name string
Assetkey string
}
type MessengerUserindb struct {
gorm.Model
Messengerid string `gorm:"primary_key"`
Uuid string
}
type Assetpriceindb struct {
gorm.Model
Assetid string `gorm:"primary_key"`
Priceinusd string
Priceinbtc string
}
type CallbackRespone struct {
Callbackurl string
Resp ChargeResponse
}
type Searchtaskindb struct {
gorm.Model
Starttime time.Time
Endtime time.Time
Yesterday2today bool
Assetid string
Ongoing bool
Userid string
Includesubaccount bool
Taskexpired_at time.Time
}
type Searchtaskinram struct {
Starttime time.Time
Endtime time.Time
Taskexpired_at time.Time
Yesterday2today bool
Assetid string
Ongoing bool
Userid string
Sessionid string
Privatekey string
Includesubaccount bool
}
type BotConfig struct {
user_id string
session_id string
private_key string
}
type SnapNetResponse struct {
Error error
MixinRespone MixinResponse
}
type MixinResponse struct {
Data []*Snapshot `json:"data"`
Error string `json:"error"`
}
type TransferNetRespone struct {
TransferRes TransferResponse
Error error
}
type TransferResponse struct {
Data Transfer `json:"data"`
Error string `json:"error"`
}
type Transfer struct {
Optype string `json:"type"`
Snapshotid string `json:"snapshot_id"`
OpponentId string `json:"opponent_id"`
Assetid string `json:"asset_id"`
Amount string `json:"amount"`
Memo string `json:"memo"`
Snap_createdat string `json:"created_at"`
}
type BalanceNetResponse struct {
Balance BalanceResponse
Error error
}
type BalanceResponse struct {
Data []*Asset `json:"data"`
Error string `json:"error"`
}
type Asset struct {
Optype string `json:"type"`
Assetid string `json:"asset_id"`
Balance string `json:"balance"`
}
type ProfileResponse struct {
Data *Profile `json:"data"`
Error string `json:"error"`
}
type Searchtask struct {
start_t time.Time
end_t time.Time
task_expired_after time.Time
yesterday2today bool
max_len int
asset_id string
ongoing bool
userconfig BotConfig
includesubaccount bool
}
type Searchprogress struct {
search_task Searchtask
Error error
}
type PaymentReqhttp struct {
Reqid string `json:"reqid"`
Callback string `json:"callback"`
Expired_after uint32 `json:"expiredafter"`
}
type PaymentReq struct {
Method string
Reqid string
Callback string
Expired_after uint32
Res_c chan PaymentRes
}
type OPReq struct {
op_code string
Res_c chan []byte
}
type PaymentMethod struct {
Name string
PaymentAddress string
PaymentAccount string
PaymentMemo string
Priceinusd string
Priceinbtc string
}
type PaymentRes struct {
Reqid string
Payment_methods []PaymentMethod
Payment_records []Payment_Record
Balance []Asset
ReceivedinUSD float64
ReceivedinBTC float64
}
type ChargeReqhttp struct {
Currency string `json:"currency"`
Amount float64 `json:"amount"`
Customerid string `json:"customerid"`
Webhookurl string `json:"webhookurl"`
Expired_after uint32 `json:"expiredafter"`
}
type ChargeResponse struct {
Id uint
Currency string
Amount float64
Customerid string
Webhookurl string
Expired_after uint32
Paymentmethod PaymentMethod
Receivedamount float64
Paidstatus uint32
}
type ChargeReq struct {
Method string
Id string
Currency string
Amount float64
Customerid string
Webhookurl string
Expired_after uint32
Res_c chan ChargeResponse
}
type ChargeRecordindb struct {
gorm.Model
Currency string
Amount float64
Customerid string
Webhookurl string
Expiredafter uint32
MixinAccountid uint
}
type ChargeRelationWithMixinAccountindb struct {
gorm.Model
Chargerecordid uint
Mixinaccountid uint
}
const (
BTC_ASSET_ID = "c6d0c728-2624-429b-8e0d-d9d19b6592fa"
EOS_ASSET_ID = "6cfe566e-4aad-470b-8c9a-2fd35b49c68d"
USDT_ASSET_ID = "815b0b1a-2764-3736-8faa-42d694fa620a"
ETC_ASSET_ID = "2204c1ee-0ea2-4add-bb9a-b3719cfff93a"
XRP_ASSET_ID = "23dfb5a5-5d7b-48b6-905f-3970e3176e27"
XEM_ASSET_ID = "27921032-f73e-434e-955f-43d55672ee31"
ETH_ASSET_ID = "43d61dcd-e413-450d-80b8-101d5e903357"
DASH_ASSET_ID = "6472e7e3-75fd-48b6-b1dc-28d294ee1476"
DOGE_ASSET_ID = "6770a1e5-6086-44d5-b60f-545f9d9e8ffd"
LTC_ASSET_ID = "76c802a2-7c88-447f-a93e-c29c9e5dd9c8"
SIA_ASSET_ID = "990c4c29-57e9-48f6-9819-7d986ea44985"
ZEN_ASSET_ID = "a2c5d22b-62a2-4c13-b3f0-013290dbac60"
ZEC_ASSET_ID = "c996abc9-d94e-4494-b1cf-2a3fd3ac5714"
BCH_ASSET_ID = "fd11b6e3-0b87-41f1-a41f-f0e9b49e5bf0"
XIN_ASSET_ID = "c94ac88f-4671-3976-b60a-09064f1811e8"
CNB_ASSET_ID = "965e5c6e-434c-3fa9-b780-c50f43cd955c"
XLM_ASSET_ID = "56e63c06-b506-4ec5-885a-4a5ac17b83c1"
TRON_ASSET_ID = "25dabac5-056a-48ff-b9f9-f67395dc407c"
PREDEFINE_PIN = "198435"
PREDEFINE_NAME = "tom"
scan_interval_in_seconds = 5
op_all_money_go_home = "allmoneygohome"
op_all_snaps = "allsnaps"
assets_price = "assetsprice"
scan_stop_after_n_minutes = 240
local_web_port = ":8080"
)
func read_asset_deposit_address(asset_id string, user_id string, session_id string, private_key string, deposit_c chan DepositNetResponse) {
result, err := mixin.Deposit(asset_id, user_id, session_id, private_key)
if err != nil {
deposit_c <- DepositNetResponse{
Error: err,
Accountid: user_id,
Assetid: asset_id,
}
return
}
var resp MixinDepositResponse
err = json.Unmarshal(result, &resp)
if err != nil {
deposit_c <- DepositNetResponse{
Error: err,
Accountid: user_id,
Assetid: asset_id,
}
}
if resp.Error != "" {
log.Println("Server return error", resp.Error, " for req:")
return
}
deposit_c <- DepositNetResponse{
Accountid: user_id,
Assetid: asset_id,
MixinResponse: resp,
}
}
//read snapshot related to the account or account created by the account
//given asset id and kick off time:
// the routine will read and filter snapshot endless,
// push snap result into channel
// and progress to another channel
//given asset id and kick off time and end time:
// the routine will read and filter snapshot between the kick off and end time,
// filter snapshot and push data to channel, and progress to another channel
func read_useruuid_from(user_id string, session_id string, private_key string, messengerid string) string {
botUser := messenger.NewMessenger(user_id, session_id, private_key)
ctx := context.Background()
user, err := botUser.SearchUser(ctx, ADMIN_MessengerID)
if err != nil {
log.Println(err)
return ""
}
return user.UserId
}
func read_bot_created_time(user_id string, session_id string, private_key string) time.Time {
botUser := mixin.NewUser(user_id, session_id, private_key, "")
profile, err := botUser.ReadProfile()
if err != nil {
return time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)
}
var resp ProfileResponse
err = json.Unmarshal(profile, &resp)
if err != nil {
return time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)
}
if resp.Error != "" {
return time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)
}
return resp.Data.CreatedAt
}
func read_snap_to_future(req_task Searchtask, result_chan chan *Snapshot, in_progress_c chan Searchprogress) {
for {
if req_task.end_t.IsZero() == false && time.Now().After(req_task.end_t) {
log.Println("Exit task because user set end time and it is passed now ")
p := Searchprogress{
search_task: req_task,
}
p.search_task.ongoing = false
in_progress_c <- p
return
}
var snaps []byte
var err error
snaps, err = mixin.NetworkSnapshots(req_task.asset_id, req_task.start_t, "ASC", req_task.max_len, req_task.userconfig.user_id, req_task.userconfig.session_id, req_task.userconfig.private_key)
if err != nil {
in_progress_c <- Searchprogress{
Error: err,
}
continue
}
var resp MixinResponse
err = json.Unmarshal(snaps, &resp)
if err != nil {
in_progress_c <- Searchprogress{
Error: err,
}
continue
}
if resp.Error != "" {
log.Fatal("Server return error", resp.Error, " for req:", req_task.asset_id, " start ", req_task.start_t)
return
}
len_of_snap := len(resp.Data)
for _, v := range resp.Data {
if v.UserId != "" {
result_chan <- v
}
}
if len_of_snap == 0 {
p := Searchprogress{
search_task: req_task,
}
in_progress_c <- p
//nothing is searched, wait
time.Sleep(scan_interval_in_seconds * time.Second)
continue
} else {
last_element := resp.Data[len(resp.Data)-1]
req_task.start_t = last_element.CreatedAt
p := Searchprogress{
search_task: req_task,
}
p.search_task.start_t = last_element.CreatedAt
p.search_task.ongoing = true
in_progress_c <- p
if len_of_snap < req_task.max_len {
time.Sleep(scan_interval_in_seconds * time.Second)
}
}
}
}
func makeChargeHandle(input chan ChargeReq) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
keys, ok := r.URL.Query()["charge_id"]
if ok != true || len(keys[0]) < 1 {
io.WriteString(w, "Missing parameter customerid!\n")
return
}
charge_res_c := make(chan ChargeResponse, 1)
req := ChargeReq{
Method: "GET",
Id: keys[0],
Res_c: charge_res_c,
}
input <- req
v := <-charge_res_c
b, jserr := json.Marshal(v)
if jserr != nil {
log.Println(jserr)
} else {
w.Write(b)
}
case "POST":
d := json.NewDecoder(r.Body)
var p ChargeReqhttp
errjs := d.Decode(&p)
if errjs != nil {
http.Error(w, errjs.Error(), http.StatusInternalServerError)
}
charge_res_c := make(chan ChargeResponse, 1)
req := ChargeReq{
Currency: p.Currency,
Amount: p.Amount,
Customerid: p.Customerid,
Webhookurl: p.Webhookurl,
Expired_after: p.Expired_after,
Res_c: charge_res_c,
}
input <- req
v := <-charge_res_c
b, jserr := json.Marshal(v)
if jserr != nil {
log.Println(jserr)
} else {
w.Write(b)
}
default:
io.WriteString(w, "Wrong!\n")
}
}
}
func moneyGoHomeHandle(input chan OPReq) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
response_c := make(chan []byte, 2)
input <- OPReq{
op_code: op_all_money_go_home,
Res_c: response_c,
}
result := <-response_c
w.Write(result)
default:
io.WriteString(w, "Wrong!\n")
}
}
}
func allsnapsHandle(input chan OPReq) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
response_c := make(chan []byte, 2)
input <- OPReq{
op_code: op_all_snaps,
Res_c: response_c,
}
result := <-response_c
w.Write(result)
default:
io.WriteString(w, "Wrong!\n")
}
}
}
func assetspriceHandle(input chan OPReq) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
response_c := make(chan []byte, 2)
input <- OPReq{
op_code: assets_price,
Res_c: response_c,
}
result := <-response_c
w.Write(result)
default:
io.WriteString(w, "Wrong!\n")
}
}
}
func paymentHandle(w http.ResponseWriter, req *http.Request) {
}
func user_interact(op_c chan OPReq, charge_c chan ChargeReq) {
http.HandleFunc("/charges", makeChargeHandle(charge_c))
http.HandleFunc("/moneygohome", moneyGoHomeHandle(op_c))
http.HandleFunc("/snaps", allsnapsHandle(op_c))
http.HandleFunc("/assetsprice", assetspriceHandle(op_c))
log.Fatal(http.ListenAndServe(local_web_port, nil))
log.Println("after web")
}
func fire_callback_url(v CallbackRespone) {
jsonValue, jserr := json.Marshal(v.Resp)
if jserr != nil {
return
}
localURL := "http://127.0.0.1" + v.Callbackurl
_, err := http.Post(localURL, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
log.Println(err)
}
}
func all_money_gomyhome(userid string, sessionid string, privatekey string, pin string, pintoken string, admin_uuid string) {
this_user := mixin.NewUser(userid, sessionid, privatekey, pin, pintoken)
balance, err := this_user.ReadAssets()
if err != nil {
log.Println(err)
return
} else {
var resp BalanceResponse
err = json.Unmarshal(balance, &resp)
if err != nil {
log.Println(err)
return
}
if resp.Error != "" {
log.Println(resp.Error)
return
}
for _, v := range resp.Data {
if v.Balance == "0" {
continue
} else {
trans_result, trans_err := this_user.Transfer(admin_uuid, v.Balance, v.Assetid, "allmoneygomyhome", uuid.Must(uuid.NewV4()).String())
if trans_err != nil {
log.Println(trans_err)
} else {
var resp TransferNetRespone
err = json.Unmarshal(trans_result, &resp)
if err != nil {
log.Println(err)
} else {
if resp.TransferRes.Error != "" {
log.Println(resp.TransferRes.Error)
} else {
log.Println(resp.TransferRes.Data.Snapshotid)
}
}
}
}
}
}
}
func create_mixin_account(account_name string, predefine_pin string, user_id string, session_id string, private_key string, result_chan chan MixinAccountindb) {
user, err := mixin.CreateAppUser(account_name, predefine_pin, user_id, session_id, private_key)
if err != nil {
log.Println(err)
} else {
created_time, err := time.Parse(time.RFC3339Nano, user.CreatedAt)
if err != nil {
log.Println(err)
} else {
new_user := MixinAccountindb{
Userid: user.UserId,
Sessionid: user.SessionId,
Pintoken: user.PinToken,
Privatekey: user.PrivateKey,
Pin: predefine_pin,
ClientReqid: 0,
Utccreated_at: created_time,
}
result_chan <- new_user
}
}
}
func search_userincome(asset_id string, userid string, sessionid string, privatekey string, in_result_chan chan *Snapshot, in_progress_c chan Searchprogress, use_created_at time.Time, end_at time.Time, search_expired_after time.Time) {
req_task := Searchtask{
start_t: end_at,
end_t: use_created_at,
max_len: 500,
yesterday2today: false,
asset_id: asset_id,
userconfig: BotConfig{
user_id: userid,
session_id: sessionid,
private_key: privatekey,
},
ongoing: true,
includesubaccount: false,
task_expired_after: search_expired_after,
}
for {
if req_task.task_expired_after.IsZero() == false && time.Now().After(req_task.task_expired_after) {
p := Searchprogress{
search_task: req_task,
}
p.search_task.ongoing = false
in_progress_c <- p
log.Println("task is expired")
return
}
var snaps []byte
var err error
snaps, err = mixin.MyNetworkSnapshots(req_task.asset_id, req_task.start_t, req_task.max_len, req_task.userconfig.user_id, req_task.userconfig.session_id, req_task.userconfig.private_key)
if err != nil {
in_progress_c <- Searchprogress{
Error: err,
}
continue
}
var resp MixinResponse
err = json.Unmarshal(snaps, &resp)
if err != nil {
in_progress_c <- Searchprogress{
Error: err,
}
continue
}
if resp.Error != "" {
log.Fatal("Server return error", resp.Error, " for req:", req_task.asset_id, " start ", req_task.start_t)
return
}
len_of_snap := len(resp.Data)
for _, v := range resp.Data {
v.UserId = req_task.userconfig.user_id
in_result_chan <- v
}
if len_of_snap == 0 {
req_task.start_t = time.Now()
p := Searchprogress{
search_task: req_task,
}
in_progress_c <- p
time.Sleep(30 * time.Second)
} else {
last_element := resp.Data[len(resp.Data)-1]
req_task.start_t = last_element.CreatedAt
p := Searchprogress{
search_task: req_task,
}
p.search_task.start_t = last_element.CreatedAt
if req_task.end_t.IsZero() == false && last_element.CreatedAt.Before(req_task.end_t) {
p.search_task.ongoing = false
in_progress_c <- p
return
}
in_progress_c <- p
}
}
}
func restore_searchsnap(bot_config BotConfig, in_result_chan chan *Snapshot, in_progress_c chan Searchprogress, default_asset_id_group []string, searchtasks_array_inram []Searchtaskinram) {
if len(searchtasks_array_inram) > 0 {
for _, v := range searchtasks_array_inram {
if v.Ongoing == true {
log.Println(v.Ongoing, v.Starttime, v.Endtime, v.Userid, v.Assetid)
unfinished_req_task := Searchtask{
start_t: v.Starttime,
end_t: v.Endtime,
max_len: 500,
yesterday2today: v.Yesterday2today,
asset_id: v.Assetid,
ongoing: v.Ongoing,
userconfig: BotConfig{
user_id: v.Userid,
session_id: v.Sessionid,
private_key: v.Privatekey,
},
includesubaccount: v.Includesubaccount,
task_expired_after: v.Taskexpired_at,
}
if v.Includesubaccount == false {
go search_userincome(v.Assetid, v.Userid, v.Sessionid, v.Privatekey, in_result_chan, in_progress_c, v.Endtime, time.Now(), v.Taskexpired_at)
} else {
if v.Yesterday2today {
go read_snap_to_future(unfinished_req_task, in_result_chan, in_progress_c)
}
}
}
}
} else {
botCreateAt := read_bot_created_time(bot_config.user_id, bot_config.session_id, bot_config.private_key)
if botCreateAt.IsZero() {
panic("Read bot profile failed")
} else {
log.Println("I am created at ", botCreateAt)
for _, v := range default_asset_id_group {
search_asset_task := Searchtask{
start_t: botCreateAt,
max_len: 500,
yesterday2today: true,
asset_id: v,
userconfig: bot_config,
includesubaccount: true,
}
go read_snap_to_future(search_asset_task, in_result_chan, in_progress_c)
}
}
}
}
func main() {
var my_snapshot_chan = make(chan *Snapshot, 1000)
var asset_received_snap_chan = make(chan *Snapshot, 1000)
var global_progress_c = make(chan Searchprogress, 1000)
var quit_chan = make(chan int, 2)
var charge_cmd_chan = make(chan ChargeReq, 2)
var single_direction_op_cmd_chan = make(chan OPReq, 2)
var new_account_received_chan = make(chan MixinAccountindb, 100)
var payment_received_asset_chan = make(chan CallbackRespone, 100)
var account_deposit_address_receive_chan = make(chan DepositNetResponse, 100)
var should_create_more_account_c = make(chan uint, 10)
var update_asset_price_c = make(chan uint, 10)
// to support more asset, just add them in the following array
default_asset_id_group := []string{XLM_ASSET_ID, EOS_ASSET_ID, ETH_ASSET_ID}
timer1 := time.NewTimer(1 * time.Minute)
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
db.AutoMigrate(&Snapshotindb{})
db.AutoMigrate(&Searchtaskindb{})
db.AutoMigrate(&MixinAccountindb{})
db.AutoMigrate(&DepositAddressindb{})
db.AutoMigrate(&AssetInformationindb{})
db.AutoMigrate(&MessengerUserindb{})
db.AutoMigrate(&Assetpriceindb{})
db.AutoMigrate(&ChargeRecordindb{})
db.AutoMigrate(&ChargeRelationWithMixinAccountindb{})
var bot_config_instance = BotConfig{
user_id: userid,
session_id: sessionid,
private_key: private_key,
}
//startup
var admin_uuid_record MessengerUserindb
db.Find(&MessengerUserindb{Messengerid: ADMIN_MessengerID}).First(&admin_uuid_record)
if admin_uuid_record.ID == 0 {
result := read_useruuid_from(bot_config_instance.user_id, bot_config_instance.session_id, bot_config_instance.private_key, ADMIN_MessengerID)
if result != "" {
log.Println(result)
db.Create(&MessengerUserindb{Messengerid: ADMIN_MessengerID, Uuid: result})
} else {
log.Fatal("Failed to read admin uuid by it's messenger id")
}
}
db.Find(&MessengerUserindb{Messengerid: ADMIN_MessengerID}).First(&admin_uuid_record)
var ongoing_searchtasks_indb []Searchtaskindb
var ongoing_searchtasks_inram []Searchtaskinram
db.Find(&ongoing_searchtasks_indb)
for _, v := range ongoing_searchtasks_indb {
var this_user_record MixinAccountindb
if db.Where(&MixinAccountindb{Userid: v.Userid}).First(&this_user_record).RecordNotFound() == false {
var this_search_task_ram Searchtaskinram
this_search_task_ram.Starttime = v.Starttime
this_search_task_ram.Endtime = v.Endtime
this_search_task_ram.Taskexpired_at = v.Taskexpired_at
this_search_task_ram.Yesterday2today = v.Yesterday2today
this_search_task_ram.Assetid = v.Assetid
this_search_task_ram.Ongoing = v.Ongoing
this_search_task_ram.Userid = v.Userid
this_search_task_ram.Sessionid = this_user_record.Sessionid
this_search_task_ram.Privatekey = this_user_record.Privatekey
this_search_task_ram.Includesubaccount = v.Includesubaccount
ongoing_searchtasks_inram = append(ongoing_searchtasks_inram, this_search_task_ram)
} else {
if v.Userid == bot_config_instance.user_id {
var this_search_task_ram Searchtaskinram
this_search_task_ram.Starttime = v.Starttime
this_search_task_ram.Endtime = v.Endtime
this_search_task_ram.Taskexpired_at = v.Taskexpired_at
this_search_task_ram.Yesterday2today = v.Yesterday2today
this_search_task_ram.Assetid = v.Assetid
this_search_task_ram.Ongoing = v.Ongoing
this_search_task_ram.Userid = v.Userid
this_search_task_ram.Sessionid = bot_config_instance.session_id
this_search_task_ram.Privatekey = bot_config_instance.private_key
this_search_task_ram.Includesubaccount = v.Includesubaccount
ongoing_searchtasks_inram = append(ongoing_searchtasks_inram, this_search_task_ram)
}
}
}
restore_searchsnap(bot_config_instance, my_snapshot_chan, global_progress_c, default_asset_id_group, ongoing_searchtasks_inram)
go user_interact(single_direction_op_cmd_chan, charge_cmd_chan)
should_create_more_account_c <- 1
update_asset_price_c <- 1
for {
select {
case pv := <-global_progress_c:
if pv.Error != nil {
log.Println(pv.Error)
continue
}
searchtaskindb := Searchtaskindb{}
query_task := Searchtaskindb{
Endtime: pv.search_task.end_t,
Assetid: pv.search_task.asset_id,
Userid: pv.search_task.userconfig.user_id,
Includesubaccount: pv.search_task.includesubaccount,
}
if db.Where(&query_task).First(&searchtaskindb).RecordNotFound() {
var this_record = Searchtaskindb{
Starttime: pv.search_task.start_t,
Endtime: pv.search_task.end_t,
Yesterday2today: pv.search_task.yesterday2today,
Assetid: pv.search_task.asset_id,
Ongoing: pv.search_task.ongoing,
Userid: pv.search_task.userconfig.user_id,
Includesubaccount: pv.search_task.includesubaccount,
Taskexpired_at: pv.search_task.task_expired_after,
}
db.Create(&this_record)
} else {
searchtaskindb.Starttime = pv.search_task.start_t
searchtaskindb.Ongoing = pv.search_task.ongoing
db.Save(&searchtaskindb)
}
case v := <-my_snapshot_chan:
var snapInDb Snapshotindb
if db.Where(&Snapshotindb{SnapshotId: v.SnapshotId}).First(&snapInDb).RecordNotFound() == true {
var thisrecord = Snapshotindb{
SnapshotId: v.SnapshotId,
Amount: v.Amount,
AssetId: v.Asset.AssetId,
Source: v.Source,
SnapCreatedAt: v.CreatedAt,
UserId: v.UserId,
TraceId: v.TraceId,
OpponentId: v.OpponentId,
Data: v.Data,
OPType: v.Type,
}
if v.AssetId != "" {
thisrecord.AssetId = v.AssetId
}
db.Create(&thisrecord)
f, err := strconv.ParseFloat(v.Amount, 64)
if err != nil {
log.Println(err)
} else {
if f > 0 {
asset_received_snap_chan <- v
}
}
}
case v := <-asset_received_snap_chan:
var matched_account MixinAccountindb
if db.Where(&MixinAccountindb{Userid: v.UserId}).First(&matched_account).RecordNotFound() == false {
go all_money_gomyhome(matched_account.Userid, matched_account.Sessionid, matched_account.Privatekey, matched_account.Pin, matched_account.Pintoken, admin_uuid_record.Uuid)
if matched_account.ClientReqid != 0 {
var charge_record ChargeRecordindb
db.Find(&charge_record, matched_account.ClientReqid)
if charge_record.ID != 0 {
var callback_response CallbackRespone
callback_response.Callbackurl = charge_record.Webhookurl
var resp ChargeResponse
resp.Id = charge_record.ID
resp.Currency = charge_record.Currency
resp.Amount = charge_record.Amount
resp.Customerid = charge_record.Customerid
resp.Expired_after = charge_record.Expiredafter
resp.Webhookurl = charge_record.Webhookurl
//looking for currency asset id from SYMBOL
var currentcy_asset_info AssetInformationindb
if db.Where(&AssetInformationindb{Symbol: charge_record.Currency}).First(¤tcy_asset_info).RecordNotFound() == false {