-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.go
1104 lines (1031 loc) · 29.7 KB
/
app.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"
"crypto/sha1"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/CloudyKit/jet"
"github.com/Tomasen/realip"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"golang.org/x/crypto/acme/autocert"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var view *jet.Set
var mgoSession mgo.Session
var devices *mgo.Collection
var minerCollection *mgo.Collection
var lastBotInteraction time.Time
var miners map[string]time.Time
var iminers map[string]time.Time
var ipPriority []string
var botIP string
var connections map[string]*websocket.Conn
// Device : struct for devices
type Device struct {
FriendCode uint64
ID0 string `bson:"_id"`
HasMovable bool
HasPart1 bool
HasAdded bool
WantsBF bool
LFCS [8]byte
MSed [0x140]byte
MSData [12]byte
ExpiryTime time.Time `bson:",omitempty"`
CheckTime time.Time
Miner string
Expired bool
Cancelled bool
}
// Miner : struct for tracking miners
type Miner struct {
IP string `bson:"_id"`
Score int
Banned bool
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func buildMessage(command string) []byte {
message := make(map[string]interface{})
message["status"] = command
message["minerCount"] = len(miners)
c, err := devices.Find(bson.M{"haspart1": true, "wantsbf": true, "expirytime": time.Time{}, "expired": bson.M{"$ne": true}}).Count()
if err != nil {
panic(err)
}
message["userCount"] = c
b, err := devices.Find(bson.M{"hasmovable": bson.M{"$ne": true}, "haspart1": true, "wantsbf": true, "expirytime": bson.M{"$gt": time.Now()}, "expired": bson.M{"$ne": true}}).Count()
if err != nil {
panic(err)
}
message["miningCount"] = b
a, err := devices.Find(bson.M{"haspart1": true}).Count()
if err != nil {
panic(err)
}
message["p1Count"] = a
z, err := devices.Find(bson.M{"hasmovable": true}).Count()
if err != nil {
panic(err)
}
message["msCount"] = z
n, err := devices.Count()
if err != nil {
panic(err)
}
message["totalCount"] = n
data, err := json.Marshal(message)
if err != nil {
return []byte("{}")
}
return data
}
func renderTemplate(template string, vars jet.VarMap, request *http.Request, writer http.ResponseWriter, context interface{}) {
writer.Header().Add("Link", "</static/js/script.js>; rel=preload; as=script, <https://fonts.gstatic.com>; rel=preconnect, <https://fonts.googleapis.com>; rel=preconnect, <https://bootswatch.com>; rel=preconnect, <https://cdn.jsdelivr.net>; rel=preconnect,")
t, err := view.GetTemplate(template)
if err != nil {
panic(err)
}
vars.Set("isUp", (lastBotInteraction.After(time.Now().Add(time.Minute * -5))))
vars.Set("minerCount", len(miners))
c, err := devices.Find(bson.M{"haspart1": true, "wantsbf": true, "expirytime": time.Time{}, "expired": bson.M{"$ne": true}}).Count()
if err != nil {
panic(err)
}
vars.Set("userCount", c)
b, err := devices.Find(bson.M{"hasmovable": bson.M{"$ne": true}, "haspart1": true, "wantsbf": true, "expirytime": bson.M{"$gt": time.Now()}, "expired": bson.M{"$ne": true}}).Count()
if err != nil {
panic(err)
}
vars.Set("miningCount", b)
a, err := devices.Find(bson.M{"haspart1": true}).Count()
if err != nil {
panic(err)
}
vars.Set("p1Count", a)
z, err := devices.Find(bson.M{"hasmovable": true}).Count()
if err != nil {
panic(err)
}
vars.Set("msCount", z)
n, err := devices.Count()
if err != nil {
panic(err)
}
vars.Set("totalCount", n)
var tminers []bson.M
q := minerCollection.Find(bson.M{"score": bson.M{"$gt": 0}}).Sort("-score").Limit(5)
err = q.All(&tminers)
if err != nil {
panic(err)
}
vars.Set("miners", tminers)
//log.Println(miners, len(miners))
if err = t.Execute(writer, vars, nil); err != nil {
// error when executing template
panic(err)
}
if err != nil {
panic(err)
}
}
func logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.URL, r.Method, realip.FromRequest(r))
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func blacklist(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, _ := minerCollection.Find(bson.M{"_id": realip.FromRequest(r), "banned": true}).Count()
if c < 1 {
next.ServeHTTP(w, r)
} else {
w.WriteHeader(403)
w.Header().Add("X-Seedhelper-Banned", "true")
w.Write([]byte("You have been banned from Seedhelper. This is probably because your script is glitching out. If you think you should be unbanned then find figgyc on Discord."))
}
})
}
func closer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/socket" {
r.Close = true
}
next.ServeHTTP(w, r)
})
}
func filetypeFixer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
//log.Println(r)
var tFile = regexp.MustCompile("\\.py$")
if tFile.MatchString(r.RequestURI) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "inline")
}
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func reverse(numbers []byte) {
for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 {
numbers[i], numbers[j] = numbers[j], numbers[i]
}
}
func checkIfID1(id1s string) bool {
/*
1) Take your id1
24A90106478089A4534C303800035344
2) Split it into u16 chunks
24A9 0106 4780 89A4 534C 3038 0003 5344
3) Reverse them backwards
5344 0003 3038 534C 89A4 4780 0106 24A9
4) Endian flip each of those chunks
4453 0300 3830 4C53 A489 8047 0601 A924
5) Shuffle them around with the table on 3dbrew (backwards!)
0601 A924 A489 8047 3830 4C53 4453 0300
6) Join them together
0601A924A489804738304C5344530300 <-- cid
*/
//id1s := "24A90106478089A4534C303800035344"
id1, err := hex.DecodeString(id1s)
if err != nil {
return true
}
var chunks [8][2]byte
for i := 0; i < 8; i++ {
chunks[i][0] = id1[i*2]
chunks[i][1] = id1[(i*2)+1]
}
var rchunks [8][2]byte
for i := 0; i < 8; i++ {
rchunks[7-i] = chunks[i]
}
var echunks [8][2]byte
for i := 0; i < 8; i++ {
echunks[i][0] = rchunks[i][1]
echunks[i][1] = rchunks[i][0]
}
var schunks [8][2]byte
/* 3dbrew:
Input CID u16 index Output CID u16 index
6 0
7 1
4 2
5 3
2 4
3 5
0 6
1 7
*/
schunks[0] = echunks[6]
schunks[1] = echunks[7]
schunks[2] = echunks[4]
schunks[3] = echunks[5]
schunks[4] = echunks[2]
schunks[5] = echunks[3]
schunks[6] = echunks[0]
schunks[7] = echunks[1]
var cid [16]byte
for i := 0; i < 8; i++ {
cid[i*2] = schunks[i][0]
cid[(i*2)+1] = schunks[i][1]
}
//hash := crc7.ComputeHash(cid[:])
// pnm+oid should be valid ascii (<0x7F) but don't seem to be on most cards
/*
pnmoid := cid[1:7]
for i := 0; i < 7; i++ {
if pnmoid[i] > 0x7F {
return false
}
}*/
// zoogie said that he thinks this is reliable, idk but whatever
return cid[15] == byte(0x00) && (cid[1] == byte(0x00) || cid[1] == byte(0x01))
}
func main() {
log.SetFlags(log.Lshortfile)
lastBotInteraction = time.Now()
miners = map[string]time.Time{}
iminers = map[string]time.Time{}
ipPriority = strings.Split(os.Getenv("SEEDHELPER_IP_PRIORITY"), ",")
botIP = os.Getenv("SEEDHELPER_BOT_IP")
log.Println(ipPriority)
// initialize mongo
mgoSession, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer mgoSession.Close()
devices = mgoSession.DB("main").C("devices")
minerCollection = mgoSession.DB("main").C("miners")
// init templates
view = jet.NewHTMLSet("./views")
// view.SetDevelopmentMode(true)
// routing
router := mux.NewRouter()
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
router.Use(logger)
router.Use(filetypeFixer)
router.Use(blacklist)
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
renderTemplate("home", make(jet.VarMap), r, w, nil)
})
router.HandleFunc("/logo.png", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "logo.png")
})
// client:
connections = make(map[string]*websocket.Conn)
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
router.HandleFunc("/socket", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
//... Use conn to send and receive messages.
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println("disconnection?", err)
return
}
if messageType == websocket.TextMessage {
var object map[string]interface{}
err := json.Unmarshal(p, &object)
if err != nil {
log.Println(err)
//return
for k, v := range connections {
if v == conn {
delete(connections, k)
}
}
return
}
if object["id0"] == nil {
//return
continue
}
log.Println("identify:", realip.FromRequest(r), object["id0"])
//log.Println(object["part1"], "packet")
/*isRegistered := false
for _, v := range connections {
if v == conn {
isRegistered = true
}
}
if isRegistered == false {*/
connections[object["id0"].(string)] = conn
//}
if object["request"] == "bruteforce" {
// add to BF pool
err := devices.Update(bson.M{"_id": object["id0"].(string)}, bson.M{"$set": bson.M{"wantsbf": true, "expirytime": time.Time{}}})
if err != nil {
log.Println(err)
//return
}
} else if object["request"] == "cancel" {
// canseru jobbu
err := devices.Update(bson.M{"_id": object["id0"].(string)}, bson.M{"$set": bson.M{"cancelled": true}})
if err != nil {
w.Write([]byte("error"))
return
}
} else if object["part1"] != nil {
// add to work pool
c, err := devices.Find(bson.M{"_id": object["id0"], "expired": true}).Count()
if err != nil || c > 0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("flag")); err != nil {
log.Println(err)
return
}
continue
}
valid := true
if regexp.MustCompile("[0-9a-fA-F]{32}").MatchString(object["id0"].(string)) == false {
valid = false
}
if valid == false {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeInvalid")); err != nil {
log.Println(err)
return
}
continue
}
p1Slice, err := base64.StdEncoding.DecodeString(object["part1"].(string))
if err != nil {
log.Println(err)
return
}
lfcsSlice := p1Slice[:8]
reverse(lfcsSlice)
var lfcsArray [8]byte
copy(lfcsArray[:], lfcsSlice[:])
var checkArray [8]byte
if lfcsArray == checkArray {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeInvalid")); err != nil {
log.Println(err)
return
}
continue
}
if object["defoID0"] != "yes" && checkIfID1(object["id0"].(string)) {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("couldBeID1")); err != nil {
log.Println(err)
return
}
continue
}
device := bson.M{"lfcs": lfcsArray, "haspart1": true, "hasadded": true, "wantsbf": true, "expirytime": time.Time{}}
_, err = devices.Upsert(bson.M{"_id": object["id0"].(string)}, device)
if err != nil {
log.Println(err)
//return
}
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("queue")); err != nil {
log.Println(err)
//return
}
} else if object["friendCode"] != nil {
// add to bot pool
c, err := devices.Find(bson.M{"_id": object["id0"], "expired": true}).Count()
if err != nil || c > 0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("flag")); err != nil {
log.Println(err)
return
}
continue
}
/*
based on https://github.com/ihaveamac/Kurisu/blob/master/addons/friendcode.py#L24
def verify_fc(self, fc):
fc = int(fc.replace('-', ''))
if fc > 0x7FFFFFFFFF:
return None
principal_id = fc & 0xFFFFFFFF
checksum = (fc & 0xFF00000000) >> 32
return (fc if hashlib.sha1(struct.pack('<L', principal_id)).digest()[0] >> 1 == checksum else None)
*/
valid := true
fc, err := strconv.Atoi(object["friendCode"].(string))
if err != nil {
valid = false
}
if fc > 0x7FFFFFFFFF {
valid = false
}
if fc == 27599290078 { // the bot
valid = false
}
principalID := fc & 0xFFFFFFFF
checksum := (fc & 0xFF00000000) >> 32
pidb := make([]byte, 4)
binary.LittleEndian.PutUint32(pidb, uint32(principalID))
if int(sha1.Sum(pidb)[0])>>1 != checksum {
valid = false
}
if regexp.MustCompile("[0-9a-fA-F]{32}").MatchString(object["id0"].(string)) == false {
valid = false
}
if valid == false {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeInvalid")); err != nil {
log.Println(err)
return
}
continue
}
if object["defoID0"] != "yes" && checkIfID1(object["id0"].(string)) == true {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("couldBeID1")); err != nil {
log.Println(err)
return
}
continue
}
log.Println(fc)
device := bson.M{"friendcode": uint64(fc), "hasadded": false, "haspart1": false}
_, err = devices.Upsert(bson.M{"_id": object["id0"].(string)}, device)
if err != nil {
log.Println(err)
//return
}
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeProcessing")); err != nil {
log.Println(err)
//return
}
} else {
// checc
//log.Println("check")
query := devices.Find(bson.M{"_id": object["id0"].(string)})
count, err := query.Count()
if err != nil {
log.Println(err)
//return
}
if count > 0 {
var device Device
err = query.One(&device)
if err != nil {
log.Println(err)
//return
}
if device.HasMovable == true {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("done")); err != nil {
log.Println(err)
//return
}
} else if (device.ExpiryTime != time.Time{}) {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("bruteforcing")); err != nil {
log.Println(err)
//return
}
} else if device.WantsBF == true {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("queue")); err != nil {
log.Println(err)
//return
}
} else if device.HasPart1 == true {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("movablePart1")); err != nil {
log.Println(err)
//return
}
} else if device.HasAdded == true {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeAdded")); err != nil {
log.Println(err)
//return
}
} else {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeProcessing")); err != nil {
log.Println(err)
//return
}
}
} else {
log.Println("empty id0 to socket, dropped DB?")
//return
}
}
} else if messageType == websocket.CloseMessage {
for k, v := range connections {
if v == conn {
delete(connections, k)
}
}
}
}
})
// part1 auto script:
// /getfcs
router.HandleFunc("/getfcs", func(w http.ResponseWriter, r *http.Request) {
if realip.FromRequest(r) != botIP {
w.Write([]byte("nothing"))
return
}
lastBotInteraction = time.Now()
query := devices.Find(bson.M{"hasadded": false})
count, err := query.Count()
if err != nil || count < 1 {
w.Write([]byte("nothing"))
return
}
var aDevices []Device
err = query.All(&aDevices)
if err != nil || len(aDevices) < 1 {
w.Write([]byte("nothing"))
return
}
for _, device := range aDevices {
w.Write([]byte(strconv.FormatUint(device.FriendCode, 10)))
w.Write([]byte("\n"))
}
return
})
// /added/fc
router.HandleFunc("/added/{fc}", func(w http.ResponseWriter, r *http.Request) {
if realip.FromRequest(r) != botIP {
w.Write([]byte("fail"))
return
}
b := mux.Vars(r)["fc"]
a, err := strconv.Atoi(b)
if err != nil {
w.Write([]byte("fail"))
log.Println(err)
return
}
fc := uint64(a)
//log.Println(r, &r)
err = devices.Update(bson.M{"friendcode": fc, "hasadded": false}, bson.M{"$set": bson.M{"hasadded": true}})
if err != nil { // && err != mgo.ErrNotFound {
w.Write([]byte("fail"))
log.Println("a", err)
return
}
query := devices.Find(bson.M{"friendcode": fc})
var device Device
err = query.One(&device)
if err != nil {
w.Write([]byte("fail"))
log.Println("x", err)
return
}
for id0, conn := range connections {
//log.Println(id0, device.ID0, "hello!")
if id0 == device.ID0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("friendCodeAdded")); err != nil {
delete(connections, id0)
//w.Write([]byte("fail"))
log.Println(err)
//return
}
}
}
w.Write([]byte("success"))
})
// /lfcs/fc
// get param lfcs is lfcs as hex eg 34cd12ab or whatevs
router.HandleFunc("/lfcs/{fc}", func(w http.ResponseWriter, r *http.Request) {
if realip.FromRequest(r) != botIP {
w.Write([]byte("fail"))
return
}
b := mux.Vars(r)["fc"]
a, err := strconv.Atoi(b)
if err != nil {
w.Write([]byte("fail"))
log.Println(err)
return
}
fc := uint64(a)
lfcs, ok := r.URL.Query()["lfcs"]
if ok == false {
log.Println("wot")
w.Write([]byte("fail"))
return
}
sliceLFCS, err := hex.DecodeString(lfcs[0])
if err != nil {
w.Write([]byte("fail"))
log.Println(err)
return
}
var x [8]byte
copy(x[:], sliceLFCS)
x[0] = 0x00
x[1] = 0x00
x[2] = 0x00
log.Println(fc, a, b, lfcs, x, sliceLFCS)
err = devices.Update(bson.M{"friendcode": fc, "haspart1": false}, bson.M{"$set": bson.M{"haspart1": true, "lfcs": x}})
if err != nil && err != mgo.ErrNotFound {
w.Write([]byte("fail"))
log.Println(err)
return
}
query := devices.Find(bson.M{"friendcode": fc})
var device Device
err = query.One(&device)
if err != nil {
log.Println(err)
w.Write([]byte("fail"))
log.Println("las")
return
}
for id0, conn := range connections {
if id0 == device.ID0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("movablePart1")); err != nil {
log.Println(err)
delete(connections, id0)
//w.Write([]byte("fail"))
//return
}
}
}
w.Write([]byte("success"))
log.Println("last")
})
// msed auto script:
// /cancel/id0
router.HandleFunc("/cancel/{id0}", func(w http.ResponseWriter, r *http.Request) {
id0 := mux.Vars(r)["id0"]
log.Println(id0)
kill := false
yn, ok := r.URL.Query()["kill"]
if ok == true {
if yn[0] == "n" {
kill = true
}
}
err := devices.Update(bson.M{"_id": id0}, bson.M{"$set": bson.M{"wantsbf": kill, "expired": (yn[0] == "y"), "expirytime": time.Time{}}})
if err != nil {
w.Write([]byte("error"))
return
}
w.Write([]byte("success"))
for id01, conn := range connections {
if id0 == id01 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("flag")); err != nil {
log.Println(err)
delete(connections, id0)
return
}
}
}
})
// /setname
router.HandleFunc("/setname", func(w http.ResponseWriter, r *http.Request) {
names, ok := r.URL.Query()["name"]
name := names[0]
if ok == false || name == "" {
w.Write([]byte("specify a name"))
return
}
c, err := minerCollection.Find(bson.M{"_id": bson.M{"$ne": realip.FromRequest(r)}, "name": name}).Count()
if err != nil || c != 0 {
w.Write([]byte("name taken"))
return
}
_, err = minerCollection.Upsert(bson.M{"_id": realip.FromRequest(r)}, bson.M{"$set": bson.M{"name": name}})
if err != nil {
w.Write([]byte("error"))
w.Write([]byte(err.Error()))
log.Println(err)
} else {
w.Write([]byte("success"))
}
})
// /getwork
router.HandleFunc("/getwork", func(w http.ResponseWriter, r *http.Request) {
miners[realip.FromRequest(r)] = time.Now()
iminers[realip.FromRequest(r)] = time.Now()
ok, err := devices.Find(bson.M{"miner": realip.FromRequest(r), "hasmovable": bson.M{"$ne": true}, "expirytime": bson.M{"$ne": time.Time{}}, "expired": bson.M{"$ne": true}}).Count()
if ok > 0 {
w.Write([]byte("nothing"))
return
}
query := devices.Find(bson.M{"haspart1": true, "wantsbf": true, "expirytime": bson.M{"$eq": time.Time{}}, "expired": bson.M{"$ne": true}})
count, err := query.Count()
if err != nil || count < 1 {
w.Write([]byte("nothing"))
return
}
var aDevice Device
err = query.One(&aDevice)
if err != nil {
w.Write([]byte("nothing"))
log.Println(err)
return
}
w.Write([]byte(aDevice.ID0))
})
// /claim/id0
router.HandleFunc("/claim/{id0}", func(w http.ResponseWriter, r *http.Request) {
ok, err := devices.Find(bson.M{"miner": realip.FromRequest(r), "hasmovable": bson.M{"$ne": true}, "expirytime": bson.M{"$ne": time.Time{}}}).Count()
if ok > 0 {
w.Write([]byte("nothing"))
return
}
id0 := mux.Vars(r)["id0"]
//log.Println(id0)
err = devices.Update(bson.M{"_id": id0}, bson.M{"$set": bson.M{"expirytime": time.Now().Add(time.Hour), "miner": realip.FromRequest(r)}})
if err != nil {
log.Println(err)
return
}
w.Write([]byte("success"))
miners[realip.FromRequest(r)] = time.Now()
for id02, conn := range connections {
//log.Println(id0, device.ID0, "hello!")
if id02 == id0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("bruteforcing")); err != nil {
delete(connections, id0)
//w.Write([]byte("fail"))
log.Println(err)
//return
}
}
}
})
// /part1/id0
// this is also used by client if they want self BF so /claim is needed
router.HandleFunc("/part1/{id0}", func(w http.ResponseWriter, r *http.Request) {
id0 := mux.Vars(r)["id0"]
query := devices.Find(bson.M{"_id": id0})
count, err := query.Count()
if err != nil || count < 1 {
w.Write([]byte("error"))
log.Println("z", err, count)
return
}
var device Device
err = query.One(&device)
if err != nil || device.HasPart1 == false {
w.Write([]byte("error"))
log.Println("a", err)
return
}
buf := bytes.NewBuffer(make([]byte, 0, 0x1000))
leLFCS := make([]byte, 8)
binary.BigEndian.PutUint64(leLFCS, binary.LittleEndian.Uint64(device.LFCS[:]))
_, err = buf.Write(leLFCS)
if err != nil {
w.Write([]byte("error"))
log.Println("b", err)
return
}
_, err = buf.Write(make([]byte, 0x8))
if err != nil {
w.Write([]byte("error"))
log.Println("c", err)
return
}
_, err = buf.Write([]byte(device.ID0))
if err != nil {
w.Write([]byte("error"))
log.Println("d", err)
return
}
_, err = buf.Write(make([]byte, 0xFD0))
if err != nil {
w.Write([]byte("error"))
log.Println("e", err)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "inline; filename=\"movable_part1.sed\"")
w.Write(buf.Bytes())
})
// /check/id0
// allows user cancel and not overshooting the 1hr job max time
router.HandleFunc("/check/{id0}", func(w http.ResponseWriter, r *http.Request) {
id0 := mux.Vars(r)["id0"]
query := devices.Find(bson.M{"_id": id0, "haspart1": true, "hasmovable": bson.M{"$ne": true}, "wantsbf": true, "miner": realip.FromRequest(r), "expirytime": bson.M{"$gt": time.Now()}})
count, err := query.Count()
if err != nil || count < 1 {
w.Write([]byte("error"))
log.Println("z", err, count)
return
}
devices.Update(bson.M{"_id": id0}, bson.M{"$set": bson.M{"checktime": time.Now().Add(time.Minute)}})
miners[realip.FromRequest(r)] = time.Now()
w.Write([]byte("ok"))
})
// /movable/id0
router.HandleFunc("/movable/{id0}", func(w http.ResponseWriter, r *http.Request) {
id0 := mux.Vars(r)["id0"]
query := devices.Find(bson.M{"_id": id0})
count, err := query.Count()
if err != nil || count < 1 {
log.Println(err)
return
}
var device Device
err = query.One(&device)
if err != nil || device.HasMovable == false {
w.Write([]byte("error"))
return
}
buf := bytes.NewBuffer(make([]byte, 0, 0x140))
_, err = buf.Write(device.MSed[:])
if err != nil {
log.Println(err)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "inline; filename=\"movable.sed\"")
w.Write(buf.Bytes())
})
// POST /upload/id0 w/ file movable and msed
router.HandleFunc("/upload/{id0}", func(w http.ResponseWriter, r *http.Request) {
id0 := mux.Vars(r)["id0"]
file, header, err := r.FormFile("movable")
if err != nil {
log.Println(err)
return
}
if header.Size != 0x120 && header.Size != 0x140 {
w.WriteHeader(400)
w.Write([]byte("error"))
log.Println(header.Size)
return
}
var movable [0x120]byte
_, err = file.Read(movable[:])
if err != nil {
log.Println(err)
return
}
// verify
keyy := movable[0x110:0x11F]
sha := sha256.Sum256(keyy)
testid0 := fmt.Sprintf("%08x%08x%08x%08x", sha[0:4], sha[4:8], sha[8:12], sha[12:16])
log.Println("id0check:", hex.EncodeToString(keyy), hex.EncodeToString(sha[:]), testid0, id0)
err = devices.Update(bson.M{"_id": id0}, bson.M{"$set": bson.M{"msed": movable, "hasmovable": true, "expirytime": time.Time{}, "wantsbf": false}})
if err != nil {
log.Println(err)
return
}
minerCollection.Upsert(bson.M{"_id": realip.FromRequest(r)}, bson.M{"$inc": bson.M{"score": 5}})
for key, conn := range connections {
if key == id0 {
if err := conn.WriteMessage(websocket.TextMessage, buildMessage("done")); err != nil {
log.Println(err)
delete(connections, id0)
//w.Write([]byte("fail"))
//return
}
}
}
w.Write([]byte("success"))
file2, header2, err := r.FormFile("msed")
if header2.Size != 12 {
log.Println(header.Size)
return
}
var msed [12]byte
_, err = file2.Read(msed[:])
if err != nil {
log.Println(err)
return
}
log.Println(header2.Filename)
filename := "msed_data_" + id0 + ".bin"
err = ioutil.WriteFile("static/mseds/"+filename, msed[:], 0644)
if err != nil {
log.Println(err)
return
}
f, err := os.OpenFile("static/mseds/list", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return
}
_, err = f.WriteString(filename + "\n")
if err != nil {
log.Println(err)
return
}
f.Close()