-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
601 lines (489 loc) · 12 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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
package main
import (
// Stdlib
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
// RPC
"github.com/shaunmza/steemgo"
"github.com/shaunmza/steemgo/encoding/wif"
"github.com/shaunmza/steemgo/transactions"
"github.com/shaunmza/steemgo/transports/websocket"
"github.com/shaunmza/steemgo/types"
// Vendor
)
type transfer struct {
To string
Amount string
Memo string
}
type transferIn struct {
Player string
Amount float64
Memo string
}
type status struct {
Message string
Transfer *transfer
}
type output struct {
Status []status
Error string
}
//Config struct
type Config struct {
WitnessUrl string
PrivateKey string
Port string
AccountName string
Currency string
MinimumReputation int
LogFile string
}
type transferStatus struct {
Account string
Status string
BlockId int32
TrxNum int32
Expired string
Error string
}
var client *steemgo.Client
var c *Config
var logFileName string
func main() {
var err error
var cFile *string
m := "Absolute path to config file. ie -config=/config.json"
cFile = flag.String("config", "", m)
mT := "Absolute path to file. ie -csv=/file.{csv,json}"
tFile := flag.String("csv", "", mT)
flag.Parse()
// Make sure we have a config file
if *cFile == "" {
panic(fmt.Sprintf("Error: %s", m))
}
// Make sure we have a csv file
if *tFile == "" {
panic(fmt.Sprintf("Error: %s", mT))
}
c = loadConfig(*cFile)
_ = http.Server{ReadTimeout: 10 * time.Second}
addr, err := net.ResolveTCPAddr("tcp", ":"+c.Port)
_, err = net.ListenTCP("tcp", addr)
if err != nil {
if err.Error() == "listen tcp :"+c.Port+": bind: address already in use" {
fmt.Println("Already running")
} else {
panic(err)
}
os.Exit(3)
}
fmt.Println("Running...")
tme := time.Now()
logFileName = c.LogFile + "_" + tme.Format("2006-01-02")
f, err := os.Create(c.LogFile)
if err != nil {
panic(fmt.Sprintf("Cannot create log file: %s", c.LogFile))
}
f.Close()
logLine("[")
t := *tFile
if strings.Contains(*tFile, ".csv") {
importCsv(t)
} else {
importJson(t)
}
logLine("]")
fmt.Println("Done!")
}
func send(tr *transfer, client *steemgo.Client) (res string, blockId int32, trxNum int32, expired bool) {
config, err := client.Database.GetConfig()
if err != nil {
return "Could not connect (configs)", 0, 0, false
}
// Get the props to get the head block number and ID
// so that we can use that for the transaction.
props, err := client.Database.GetDynamicGlobalProperties()
if err != nil {
return "Could not connect (properties)", 0, 0, false
}
// Prepare the transaction.
refBlockPrefix, err := transactions.RefBlockPrefix(props.HeadBlockID)
if err != nil {
return "Could not connect (block prefix)", 0, 0, false
}
tx := transactions.NewSignedTransaction(&types.Transaction{
RefBlockNum: transactions.RefBlockNum(props.HeadBlockNumber),
RefBlockPrefix: refBlockPrefix,
})
tx.PushOperation(&types.TransferOperation{
From: c.AccountName,
To: tr.To,
Amount: tr.Amount,
Memo: tr.Memo,
})
// Sign.
privKey, err := wif.Decode(c.PrivateKey)
if err != nil {
return "Could not decode the WIF key, please make sure you supplied the correct private key " + err.Error(), 0, 0, false
}
privKeys := [][]byte{privKey}
if err := tx.Sign(privKeys, transactions.SteemChain); err != nil {
return "Could not sign error is: " + err.Error(), 0, 0, false
}
// Broadcast.
resp, err := client.NetworkBroadcast.BroadcastTransactionSynchronous(tx.Transaction)
if err != nil {
return "Could not broadcast error is: " + err.Error(), 0, 0, false
}
time.Sleep(time.Duration(config.SteemitBlockInterval) * time.Second)
// Success!
return "Sent", resp.BlockNum, resp.TrxNum, resp.Expired
}
func importCsv(csvFile string) {
f, err := os.Open(csvFile)
if err != nil {
panic(fmt.Sprintf("Failed to open csv file: %v\n", err))
}
defer f.Close()
r := csv.NewReader(f)
r.Comma = '\t'
// Start catching signals.
var interrupted bool
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
// Instantiate the WebSocket transport.
t, err := websocket.NewTransport(c.WitnessUrl)
if err != nil {
fmt.Println("Could not connect (websocket)")
return
}
// Use the transport to get an RPC client.
client, err := steemgo.NewClient(t)
if err != nil {
fmt.Println("Could not connect (client)")
return
}
defer func() {
if !interrupted {
client.Close()
}
}()
// Start processing signals.
go func() {
<-signalCh
fmt.Println()
log.Println("Signal received, exiting...")
logLine("]")
signal.Stop(signalCh)
interrupted = true
client.Close()
}()
if err == nil {
for {
record, err := r.Read()
if err == io.EOF {
break
}
st := transferStatus{}
if err != nil {
log.Fatal(err)
}
var ac []string
ac = append(ac, strings.ToLower(strings.TrimSpace(record[0])))
st.Account = record[0]
acc, err := client.Database.GetAccounts(ac)
if err != nil {
st.Status = "Failed"
st.Error = "Could not fetch user details from the blockchain"
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
continue
}
rp := acc[0].Reputation
rpSimple := calcReputation(rp)
if rpSimple < c.MinimumReputation {
st.Status = "Failed"
st.Error = fmt.Sprintf("User reputation (%d) below Minimum reputation of %d", rpSimple, c.MinimumReputation)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
// Send them 0.001 SBD and a message instead
//continue
record[1] = "0.001"
record[2] = fmt.Sprintf("Lucksacks.com payout rejected. Reason : Rep level below %d", c.MinimumReputation)
}
tr := &transfer{To: ac[0],
Amount: strings.TrimSpace(record[1]) + " " + c.Currency,
Memo: strings.TrimSpace(record[2])}
r, blockId, trxNum, expired := send(tr, client)
if r == "Sent" {
st.Status = "Success"
st.BlockId = blockId
st.TrxNum = trxNum
st.Expired = expiredString(expired)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
} else {
st.Status = "Failed"
st.Error = r
st.BlockId = blockId
st.TrxNum = trxNum
st.Expired = expiredString(expired)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
}
}
}
}
func importJson(jsonFile string) {
f, err := ioutil.ReadFile(jsonFile)
if err != nil {
panic(fmt.Sprintf("Failed to open json file: %v\n", err))
}
// Start catching signals.
var interrupted bool
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
// Instantiate the WebSocket transport.
t, err := websocket.NewTransport(c.WitnessUrl)
if err != nil {
fmt.Println("Could not connect (websocket)")
return
}
// Use the transport to get an RPC client.
client, err := steemgo.NewClient(t)
if err != nil {
fmt.Println("Could not connect (client)")
return
}
defer func() {
if !interrupted {
client.Close()
}
}()
// Start processing signals.
go func() {
<-signalCh
fmt.Println()
log.Println("Signal received, exiting...")
logLine("]")
signal.Stop(signalCh)
interrupted = true
client.Close()
}()
records := make([]*transfer, 0)
err = json.Unmarshal(f, &records)
if err != nil {
fmt.Println("Could not read file: " + err.Error())
return
}
for _, record := range records {
st := transferStatus{}
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
st.Account = record.To
var ac []string
ac = append(ac, strings.ToLower(strings.TrimSpace(record.To)))
acc, err := client.Database.GetAccounts(ac)
if err != nil {
st.Status = "Failed"
st.Error = "Could not fetch user details from the blockchain"
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
continue
}
if len(acc) == 0 {
st.Status = "Failed"
st.Error = "User not found:" + ac[0]
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
continue
}
rp := acc[0].Reputation
rpSimple := calcReputation(rp)
if rpSimple < c.MinimumReputation {
st.Status = "Failed"
st.Error = fmt.Sprintf("User reputation (%d) below Minimum reputation of %d", rpSimple, c.MinimumReputation)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
// Send them 0.001 SBD and a message instead
//continue
record.Amount = "0.001"
record.Memo = fmt.Sprintf("Lucksacks.com payout rejected. Reason : Rep level below %d", c.MinimumReputation)
}
tr := &transfer{To: ac[0],
Amount: strings.TrimSpace(record.Amount) + " " + c.Currency,
Memo: strings.TrimSpace(record.Memo)}
r, blockId, trxNum, expired := send(tr, client)
if r == "Sent" {
st.Status = "Success"
st.BlockId = blockId
st.TrxNum = trxNum
st.Expired = expiredString(expired)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
} else {
st.Status = "Failed"
st.Error = r
st.BlockId = blockId
st.TrxNum = trxNum
st.Expired = expiredString(expired)
ln, err := json.Marshal(st)
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
err = logLine(string(ln[:]))
if err != nil {
fmt.Println("Transfer failed: " + err.Error())
return
}
}
}
}
func (t *transfer) UnmarshalJSON(data []byte) (err error) {
var raw transferIn
if err := json.NewDecoder(strings.NewReader(string(data))).Decode(&raw); err != nil {
return err
}
t.To = raw.Player
t.Memo = raw.Memo
t.Amount = fmt.Sprintf("%.3f", raw.Amount)
return nil
}
func calcReputation(rep string) int {
if rep == "" {
return 0
}
neg := strings.Contains(rep, "-")
rep = strings.Replace(rep, "-", "", 1)
l := 4
if len(rep) < 4 {
l = len(rep)
}
leadingDigits, err := strconv.Atoi(rep[:l])
if err != nil {
return 0
}
lg := math.Log(float64(leadingDigits)) / math.Log(10)
n := float64(len(rep) - 1)
out := n + (lg - float64(int(lg)))
out = math.Max(out-9, 0)
if neg {
out = out * -1
}
out = out*9 + 25
ret := int(out)
return ret
}
func loadConfig(cFile string) *Config {
f, err := ioutil.ReadFile(cFile)
if err != nil {
panic(fmt.Sprintf("Failed to open config file: %v\n", err))
}
c := &Config{}
err = json.Unmarshal(f, &c)
if err != nil {
panic(fmt.Sprintf("Could not open config file: %v\n", err))
}
return c
}
func logLine(ln string) (err error) {
f, err := os.OpenFile(c.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.WriteString(ln + "\n")
if err != nil {
return err
}
f.Sync()
return nil
}
func expiredString(expired bool) string {
if expired == true {
return "Expired"
}
return ""
}