-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmain.go
1111 lines (921 loc) · 34.4 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
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 (c) 2018, The TurtleCoin Developers
//
// Please see the included LICENSE file for more information.
//
package main
import (
"TurtleCoin-Nest/turtlecoinwalletdrpcgo"
"TurtleCoin-Nest/walletdmanager"
"database/sql"
"encoding/json"
"io"
"io/ioutil"
"math"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/atotto/clipboard"
"github.com/dustin/go-humanize"
_ "github.com/mattn/go-sqlite3"
log "github.com/sirupsen/logrus"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/gui"
"github.com/therecipe/qt/qml"
"github.com/therecipe/qt/quickcontrols2"
)
var (
// qmlObjects = make(map[string]*core.QObject)
qmlBridge *QmlBridge
transfers []turtlecoinwalletdrpcgo.Transfer
remoteNodes []node
indexSelectedRemoteNode = 0
tickerRefreshWalletData *time.Ticker
tickerRefreshConnectionInfo *time.Ticker
tickerRefreshNodeFeeInfo *time.Ticker
tickerSaveWallet *time.Ticker
db *sql.DB
useRemoteNode = true
useCheckpoints = true
displayFiatConversion = false
stringBackupKeys = ""
rateUSDTRTL float64 // USD value for 1 TRTL
customRemoteDaemonAddress = defaultRemoteDaemonAddress
customRemoteDaemonPort = defaultRemoteDaemonPort
limitDisplayedTransactions = true
countConnectionProblem = 0
newVersionAvailable = ""
urlNewVersion = ""
)
// QmlBridge is the bridge between qml and go
type QmlBridge struct {
core.QObject
// go to qml
_ func(balance string,
balanceUSD string) `signal:"displayTotalBalance"`
_ func(data string) `signal:"displayAvailableBalance"`
_ func(data string) `signal:"displayLockedBalance"`
_ func(address string,
wallet string,
displayFiatConversion bool) `signal:"displayAddress"`
_ func(paymentID string,
transactionID string,
amount string,
confirmations string,
time string,
number string) `signal:"addTransactionToList"`
_ func(nodeURL string) `signal:"addRemoteNodeToList"`
_ func(index int) `signal:"setSelectedRemoteNode"`
_ func(text string, time int) `signal:"displayPopup"`
_ func(syncing string, syncingInfo string) `signal:"displaySyncingInfo"`
_ func(errorText string,
errorInformativeText string) `signal:"displayErrorDialog"`
_ func() `signal:"clearTransferAmount"`
_ func() `signal:"askForFusion"`
_ func() `signal:"clearListTransactions"`
_ func(filename string,
privateViewKey string,
privateSpendKey string,
walletAddress string) `signal:"displayPrivateKeys"`
_ func(filename string,
mnemonicSeed string,
walletAddress string) `signal:"displaySeed"`
_ func() `signal:"displayOpenWalletScreen"`
_ func() `signal:"displayMainWalletScreen"`
_ func() `signal:"finishedLoadingWalletd"`
_ func() `signal:"finishedCreatingWallet"`
_ func() `signal:"finishedSendingTransaction"`
_ func(pathToPreviousWallet string) `signal:"displayPathToPreviousWallet"`
_ func(walletLocation string) `signal:"displayWalletCreationLocation"`
_ func(useRemote bool) `signal:"displayUseRemoteNode"`
_ func() `signal:"hideSettingsScreen"`
_ func() `signal:"displaySettingsScreen"`
_ func(displayFiat bool) `signal:"displaySettingsValues"`
_ func(remoteNodeAddress string,
remoteNodePort string) `signal:"displaySettingsRemoteDaemonInfo"`
_ func(fullBalance string) `signal:"displayFullBalanceInTransferAmount"`
_ func(fee string) `signal:"displayDefaultFee"`
_ func(nodeFee string) `signal:"displayNodeFee"`
_ func(index int, confirmations string) `signal:"updateConfirmationsOfTransaction"`
_ func() `signal:"displayInfoDialog"`
_ func(dbID int,
name string,
address string,
paymentID string) `signal:"addSavedAddressToList"`
// qml to go
_ func(msg string) `slot:"log"`
_ func(transactionID string) `slot:"clickedButtonExplorer"`
_ func(url string) `slot:"goToWebsite"`
_ func(transactionID string) `slot:"clickedButtonCopyTx"`
_ func() `slot:"clickedButtonCopyAddress"`
_ func() `slot:"clickedButtonCopyKeys"`
_ func(stringToCopy string) `slot:"clickedButtonCopy"`
_ func(transferAddress string,
transferAmount string,
transferPaymentID string,
transferFee string) `slot:"clickedButtonSend"`
_ func() `slot:"clickedButtonBackupWallet"`
_ func() `slot:"clickedCloseWallet"`
_ func(pathToWallet string, passwordWallet string) `slot:"clickedButtonOpen"`
_ func(filenameWallet string,
passwordWallet string,
confirmPasswordWallet string) `slot:"clickedButtonCreate"`
_ func(filenameWallet string,
passwordWallet string,
privateViewKey string,
privateSpendKey string,
mnemonicSeed string,
confirmPasswordWallet string,
scanHeight string) `slot:"clickedButtonImport"`
_ func(remote bool) `slot:"choseRemote"`
_ func(index int) `slot:"selectedRemoteNode"`
_ func(amountTRTL string) string `slot:"getTransferAmountUSD"`
_ func() `slot:"clickedCloseSettings"`
_ func() `slot:"clickedSettingsButton"`
_ func(displayFiat bool) `slot:"choseDisplayFiat"`
_ func(checkpoints bool) `slot:"choseCheckpoints"`
_ func(daemonAddress string,
daemonPort string) `slot:"saveRemoteDaemonInfo"`
_ func() `slot:"resetRemoteDaemonInfo"`
_ func(transferFee string) `slot:"getFullBalanceAndDisplayInTransferAmount"`
_ func() `slot:"getDefaultFeeAndDisplay"`
_ func(limit bool) `slot:"limitDisplayTransactions"`
_ func() string `slot:"getVersion"`
_ func() string `slot:"getNewVersion"`
_ func() string `slot:"getNewVersionURL"`
_ func() `slot:"optimizeWalletWithFusion"`
_ func(name string,
address string,
paymentID string) `slot:"saveAddress"`
_ func() `slot:"fillListSavedAddresses"`
_ func(dbID int) `slot:"deleteSavedAddress"`
_ func(object *core.QObject) `slot:"registerToGo"`
_ func(objectName string) `slot:"deregisterToGo"`
}
func main() {
pathToLogFile := logFileFilename
pathToDB := dbFilename
pathToHomeDir := ""
pathToAppDirectory, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal("error finding current directory. Error: ", err)
}
if isPlatformDarwin {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
pathToHomeDir = usr.HomeDir
pathToAppFolder := pathToHomeDir + "/Library/Application Support/TurtleCoin-Nest"
os.Mkdir(pathToAppFolder, os.ModePerm)
pathToLogFile = pathToAppFolder + "/" + logFileFilename
pathToDB = pathToAppFolder + "/" + pathToDB
} else if isPlatformLinux {
pathToLogFile = pathToAppDirectory + "/" + logFileFilename
pathToDB = pathToAppDirectory + "/" + pathToDB
}
logFile, err := os.OpenFile(pathToLogFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal("error opening log file: ", err)
}
defer logFile.Close()
if isPlatformLinux {
// log to file and console
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)
} else {
log.SetOutput(logFile)
}
log.SetLevel(log.DebugLevel)
setupDB(pathToDB)
log.WithField("version", versionNest).Info("Application started")
go func() {
requestRateTRTL()
}()
platform := "linux"
if isPlatformDarwin {
platform = "darwin"
} else if isPlatformWindows {
platform = "windows"
}
walletdmanager.Setup(platform)
if isPlatformWindows {
// for scaling on windows high res screens
core.QCoreApplication_SetAttribute(core.Qt__AA_EnableHighDpiScaling, true)
}
app := gui.NewQGuiApplication(len(os.Args), os.Args)
app.SetWindowIcon(gui.NewQIcon5("qrc:/qml/images/icon.png"))
quickcontrols2.QQuickStyle_SetStyle("material")
engine := qml.NewQQmlApplicationEngine(nil)
engine.Load(core.NewQUrl3("qrc:/qml/nestmain.qml", 0))
qmlBridge = NewQmlBridge(nil)
connectQMLToGOFunctions()
engine.RootContext().SetContextProperty("QmlBridge", qmlBridge)
if isPlatformDarwin {
textLocation := "Your wallet will be saved in your home directory: " + pathToHomeDir + "/"
qmlBridge.DisplayWalletCreationLocation(textLocation)
}
getAndDisplayStartInfoFromDB()
go func() {
getAndDisplayListRemoteNodes()
}()
go func() {
newVersionAvailable, urlNewVersion = checkIfNewReleaseAvailableOnGithub(versionNest)
if newVersionAvailable != "" {
qmlBridge.DisplayInfoDialog()
}
}()
gui.QGuiApplication_Exec()
log.Info("Application closed")
walletdmanager.GracefullyQuitWalletd()
walletdmanager.GracefullyQuitTurtleCoind()
}
func connectQMLToGOFunctions() {
qmlBridge.ConnectLog(func(msg string) {
log.Info("QML: ", msg)
})
qmlBridge.ConnectClickedButtonCopyAddress(func() {
clipboard.WriteAll(walletdmanager.WalletAddress)
qmlBridge.DisplayPopup("Copied!", 1500)
})
qmlBridge.ConnectClickedButtonCopyKeys(func() {
clipboard.WriteAll(stringBackupKeys)
})
qmlBridge.ConnectClickedButtonCopy(func(stringToCopy string) {
clipboard.WriteAll(stringToCopy)
})
qmlBridge.ConnectClickedButtonCopyTx(func(transactionID string) {
clipboard.WriteAll(transactionID)
qmlBridge.DisplayPopup("Copied!", 1500)
})
qmlBridge.ConnectClickedButtonExplorer(func(transactionID string) {
url := urlBlockExplorer + "?hash=" + transactionID + "#blockchain_transaction"
successOpenBrowser := openBrowser(url)
if !successOpenBrowser {
log.Error("failure opening browser, url: " + url)
}
})
qmlBridge.ConnectGoToWebsite(func(url string) {
successOpenBrowser := openBrowser(url)
if !successOpenBrowser {
log.Error("failure opening browser, url: " + url)
}
})
qmlBridge.ConnectClickedButtonSend(func(transferAddress string, transferAmount string, transferPaymentID string, transferFee string) {
go func() {
transfer(transferAddress, transferAmount, transferPaymentID, transferFee)
}()
})
qmlBridge.ConnectGetTransferAmountUSD(func(amountTRTL string) string {
return amountStringUSDToTRTL(amountTRTL)
})
qmlBridge.ConnectClickedButtonBackupWallet(func() {
showWalletPrivateInfo()
})
qmlBridge.ConnectClickedButtonOpen(func(pathToWallet string, passwordWallet string) {
go func() {
recordPathWalletToDB(pathToWallet)
startWalletWithWalletInfo(pathToWallet, passwordWallet)
}()
})
qmlBridge.ConnectClickedButtonCreate(func(filenameWallet string, passwordWallet string, confirmPasswordWallet string) {
go func() {
createWalletWithWalletInfo(filenameWallet, passwordWallet, confirmPasswordWallet)
}()
})
qmlBridge.ConnectClickedButtonImport(func(filenameWallet string, passwordWallet string, privateViewKey string, privateSpendKey string, mnemonicSeed string, confirmPasswordWallet string, scanHeight string) {
go func() {
importWalletWithWalletInfo(filenameWallet, passwordWallet, confirmPasswordWallet, privateViewKey, privateSpendKey, mnemonicSeed, scanHeight)
}()
})
qmlBridge.ConnectClickedCloseWallet(func() {
closeWallet()
})
qmlBridge.ConnectChoseRemote(func(remote bool) {
useRemoteNode = remote
recordUseRemoteToDB(useRemoteNode)
})
qmlBridge.ConnectSelectedRemoteNode(func(index int) {
indexSelectedRemoteNode = index
node := remoteNodes[indexSelectedRemoteNode]
recordSelectedRemoteDaemonToDB(node)
})
qmlBridge.ConnectClickedCloseSettings(func() {
qmlBridge.HideSettingsScreen()
})
qmlBridge.ConnectClickedSettingsButton(func() {
qmlBridge.DisplaySettingsScreen()
})
qmlBridge.ConnectChoseDisplayFiat(func(displayFiat bool) {
displayFiatConversion = displayFiat
recordDisplayConversionToDB(displayFiat)
})
qmlBridge.ConnectChoseCheckpoints(func(checkpoints bool) {
useCheckpoints = checkpoints
})
qmlBridge.ConnectSaveRemoteDaemonInfo(func(daemonAddress string, daemonPort string) {
saveRemoteDaemonInfo(daemonAddress, daemonPort)
})
qmlBridge.ConnectResetRemoteDaemonInfo(func() {
saveRemoteDaemonInfo(defaultRemoteDaemonAddress, defaultRemoteDaemonPort)
qmlBridge.DisplaySettingsRemoteDaemonInfo(defaultRemoteDaemonAddress, defaultRemoteDaemonPort)
})
qmlBridge.ConnectGetFullBalanceAndDisplayInTransferAmount(func(transferFee string) {
getFullBalanceAndDisplayInTransferAmount(transferFee)
})
qmlBridge.ConnectLimitDisplayTransactions(func(limit bool) {
limitDisplayedTransactions = limit
getAndDisplayListTransactions(true)
})
qmlBridge.ConnectGetVersion(func() string {
return versionNest
})
qmlBridge.ConnectGetNewVersion(func() string {
return newVersionAvailable
})
qmlBridge.ConnectGetNewVersionURL(func() string {
return urlNewVersion
})
qmlBridge.ConnectOptimizeWalletWithFusion(func() {
go func() {
optimizeWalletWithFusion()
}()
})
qmlBridge.ConnectSaveAddress(func(name string, address string, paymentID string) {
saveAddress(name, address, paymentID)
})
qmlBridge.ConnectFillListSavedAddresses(func() {
getSavedAddressesFromDBAndDisplay()
})
qmlBridge.ConnectDeleteSavedAddress(func(dbID int) {
deleteSavedAddressFromDB(dbID)
})
}
func startDisplayWalletInfo() {
getAndDisplayBalances()
getAndDisplayAddress()
getAndDisplayListTransactions(true)
getAndDisplayConnectionInfo()
getDefaultFeeAndDisplay()
getNodeFeeAndDisplay()
go func() {
tickerRefreshWalletData = time.NewTicker(time.Second * 30)
for range tickerRefreshWalletData.C {
getAndDisplayBalances()
getAndDisplayListTransactions(false)
}
}()
go func() {
tickerRefreshConnectionInfo = time.NewTicker(time.Second * 5)
for range tickerRefreshConnectionInfo.C {
getAndDisplayConnectionInfo()
}
}()
go func() {
tickerRefreshNodeFeeInfo = time.NewTicker(time.Second * 15)
for range tickerRefreshNodeFeeInfo.C {
getNodeFeeAndDisplay()
}
}()
go func() {
tickerSaveWallet = time.NewTicker(time.Second * 289) // every 5 or so minutes
for range tickerSaveWallet.C {
walletdmanager.SaveWallet()
}
}()
}
func getAndDisplayBalances() {
walletAvailableBalance, walletLockedBalance, walletTotalBalance, err := walletdmanager.RequestBalance()
if err == nil {
qmlBridge.DisplayAvailableBalance(humanize.FormatFloat("#,###.##", walletAvailableBalance))
qmlBridge.DisplayLockedBalance(humanize.FormatFloat("#,###.##", walletLockedBalance))
balanceUSD := walletTotalBalance * rateUSDTRTL
qmlBridge.DisplayTotalBalance(humanize.FormatFloat("#,###.##", walletTotalBalance), humanize.FormatFloat("#,###.##", balanceUSD))
}
}
func getAndDisplayAddress() {
walletAddress, err := walletdmanager.RequestAddress()
if err == nil {
qmlBridge.DisplayAddress(walletAddress, walletdmanager.WalletFilename, displayFiatConversion)
}
}
func getAndDisplayConnectionInfo() {
syncing, walletBlockCount, knownBlockCount, _, peers, err := walletdmanager.RequestConnectionInfo()
if err != nil {
log.Info("error getting connection info: ", err)
return
}
walletBlockCountString := humanize.FormatInteger("#,###.", walletBlockCount)
// add percentage info if not synced
if walletBlockCount > 1 && knownBlockCount-walletBlockCount > 2 {
percentageSync := int(math.Floor(100 * (float64(walletBlockCount) / float64(knownBlockCount))))
walletBlockCountString += " (" + humanize.FormatInteger("#,###.", percentageSync) + "%)"
}
localDaemonBlockCountString := "N/A"
// localDaemonBlockCountString := "..."
// if localDaemonBlockCount > 1 {
// localDaemonBlockCountString = humanize.FormatInteger("#,###.", localDaemonBlockCount)
// // add percentage info if not synced
// if knownBlockCount-localDaemonBlockCount > 2 {
// percentageSync := int(math.Floor(100 * (float64(localDaemonBlockCount) / float64(knownBlockCount))))
// localDaemonBlockCountString += " (" + humanize.FormatInteger("#,###.", percentageSync) + "%)"
// }
// }
knownBlockCountString := "..."
if knownBlockCount > 1 {
knownBlockCountString = humanize.FormatInteger("#,###.", knownBlockCount)
}
syncingInfo := "wallet: " + walletBlockCountString + " - node: " + localDaemonBlockCountString + " (" + knownBlockCountString + " blocks - " + strconv.Itoa(peers) + " peers)"
qmlBridge.DisplaySyncingInfo(syncing, syncingInfo)
// when not connected to remote node, the knownBlockCount stays at 1. So inform users if there seems to be a connection problem
if useRemoteNode {
if knownBlockCount == 1 {
countConnectionProblem++
} else {
countConnectionProblem = 0
}
if countConnectionProblem > 2 {
countConnectionProblem = 0
qmlBridge.DisplayErrorDialog("Error connecting to remote node", "Check your internet connection, the remote node address and the remote node status. If you cannot connect to the remote node, try another one or choose the \"local blockchain\" option.")
}
}
}
func getAndDisplayListTransactions(forceFullUpdate bool) {
newTransfers, err := walletdmanager.RequestListTransactions()
if err == nil {
needFullUpdate := false
if len(newTransfers) != len(transfers) || forceFullUpdate {
needFullUpdate = true
}
transfers = newTransfers
// sort starting by the most recent transaction
sort.Slice(transfers, func(i, j int) bool { return transfers[i].Timestamp.After(transfers[j].Timestamp) })
if needFullUpdate {
transactionNumber := len(transfers)
qmlBridge.ClearListTransactions()
for index, transfer := range transfers {
if limitDisplayedTransactions && index >= numberTransactionsToDisplay {
break
}
amount := transfer.Amount
amountString := ""
if amount >= 0 {
amountString += "+ "
amountString += strconv.FormatFloat(amount, 'f', -1, 64)
} else {
amountString += "- "
amountString += strconv.FormatFloat(-amount, 'f', -1, 64)
}
amountString += " TRTL (fee: " + strconv.FormatFloat(transfer.Fee, 'f', 2, 64) + ")"
confirmationsString := confirmationsStringRepresentation(transfer.Confirmations)
timeString := transfer.Timestamp.Format("2006-01-02 15:04:05")
transactionNumberString := strconv.Itoa(transactionNumber) + ")"
transactionNumber--
qmlBridge.AddTransactionToList(transfer.PaymentID, transfer.TxID, amountString, confirmationsString, timeString, transactionNumberString)
}
} else { // just update the number of confirmations of transactions with less than 110 conf
for index, transfer := range transfers {
if limitDisplayedTransactions && index >= numberTransactionsToDisplay {
break
}
if transfer.Confirmations < 110 {
qmlBridge.UpdateConfirmationsOfTransaction(index, confirmationsStringRepresentation(transfer.Confirmations))
} else {
break
}
}
}
}
}
func transfer(transferAddress string, transferAmount string, transferPaymentID string, transferFee string) {
log.Info("SEND: to: ", transferAddress, " amount: ", transferAmount, " payment ID: ", transferPaymentID, " network fee: ", transferFee, " node fee: ", walletdmanager.NodeFee)
transactionID, err := walletdmanager.SendTransaction(transferAddress, transferAmount, transferPaymentID, transferFee)
if err != nil {
log.Warn("error transfer: ", err)
qmlBridge.FinishedSendingTransaction()
if strings.Contains(err.Error(), "Transaction size is too big") {
qmlBridge.AskForFusion()
} else {
qmlBridge.DisplayErrorDialog("Error transfer.", err.Error())
}
return
}
log.Info("success transfer: ", transactionID)
getAndDisplayBalances()
qmlBridge.ClearTransferAmount()
qmlBridge.FinishedSendingTransaction()
qmlBridge.DisplayPopup("TRTLs sent successfully", 4000)
}
func optimizeWalletWithFusion() {
transactionID, err := walletdmanager.OptimizeWalletWithFusion()
if err != nil {
log.Warn("error fusion transaction: ", err)
qmlBridge.FinishedSendingTransaction()
qmlBridge.DisplayErrorDialog("Error sending fusion transaction.", err.Error())
return
}
log.Info("succes fusion: ", transactionID)
getAndDisplayBalances()
qmlBridge.ClearTransferAmount()
qmlBridge.FinishedSendingTransaction()
qmlBridge.DisplayPopup("Success fusion", 4000)
}
func startWalletWithWalletInfo(pathToWallet string, passwordWallet string) bool {
remoteDaemonAddress := customRemoteDaemonAddress
remoteDaemonPort := customRemoteDaemonPort
if useRemoteNode {
if indexSelectedRemoteNode+1 < len(remoteNodes) {
// user did not chose custom node (last item of the list is custom node)
node := remoteNodes[indexSelectedRemoteNode]
remoteDaemonAddress = node.URL
remoteDaemonPort = strconv.FormatUint(node.Port, 10)
}
}
err := walletdmanager.StartWalletd(pathToWallet, passwordWallet, useRemoteNode, useCheckpoints, remoteDaemonAddress, remoteDaemonPort)
if err != nil {
log.Warn("error starting turtle-service with provided wallet info. error: ", err)
qmlBridge.FinishedLoadingWalletd()
qmlBridge.DisplayErrorDialog("Error opening wallet.", err.Error())
return false
}
log.Info("success starting turtle-service")
qmlBridge.FinishedLoadingWalletd()
startDisplayWalletInfo()
qmlBridge.DisplayMainWalletScreen()
return true
}
func createWalletWithWalletInfo(filenameWallet string, passwordWallet string, confirmPasswordWallet string) bool {
err := walletdmanager.CreateWallet(filenameWallet, passwordWallet, confirmPasswordWallet, "", "", "", "")
if err != nil {
log.Warn("error creating wallet. error: ", err)
qmlBridge.FinishedCreatingWallet()
qmlBridge.DisplayErrorDialog("Error creating the wallet.", err.Error())
return false
}
log.Info("success creating wallet")
startWalletWithWalletInfo(filenameWallet, passwordWallet)
showWalletPrivateInfo()
return true
}
func importWalletWithWalletInfo(filenameWallet string, passwordWallet string, confirmPasswordWallet string, privateViewKey string, privateSpendKey string, mnemonicSeed string, scanHeight string) bool {
err := walletdmanager.CreateWallet(filenameWallet, passwordWallet, confirmPasswordWallet, privateViewKey, privateSpendKey, mnemonicSeed, scanHeight)
if err != nil {
log.Warn("error importing wallet. error: ", err)
qmlBridge.FinishedCreatingWallet()
qmlBridge.DisplayErrorDialog("Error importing the wallet.", err.Error())
return false
}
log.Info("success importing wallet")
startWalletWithWalletInfo(filenameWallet, passwordWallet)
return true
}
func closeWallet() {
tickerRefreshWalletData.Stop()
tickerRefreshConnectionInfo.Stop()
tickerRefreshNodeFeeInfo.Stop()
tickerSaveWallet.Stop()
stringBackupKeys = ""
transfers = nil
limitDisplayedTransactions = true
countConnectionProblem = 0
go func() {
walletdmanager.GracefullyQuitWalletd()
}()
qmlBridge.DisplayOpenWalletScreen()
}
func showWalletPrivateInfo() {
isDeterministicWallet, mnemonicSeed, privateViewKey, privateSpendKey, err := walletdmanager.GetPrivateKeys()
if err != nil {
log.Error("Error getting private keys: ", err)
} else {
stringBackupKeys = "Wallet: " + walletdmanager.WalletFilename + "\n\nAddress: " + walletdmanager.WalletAddress + "\n\n"
if isDeterministicWallet {
qmlBridge.DisplaySeed(walletdmanager.WalletFilename, mnemonicSeed, walletdmanager.WalletAddress)
stringBackupKeys += "Seed: " + mnemonicSeed
} else {
qmlBridge.DisplayPrivateKeys(walletdmanager.WalletFilename, privateViewKey, privateSpendKey, walletdmanager.WalletAddress)
stringBackupKeys += "Private view key: " + privateViewKey + "\n\nPrivate spend key: " + privateSpendKey
}
}
}
func getFullBalanceAndDisplayInTransferAmount(transferFee string) {
availableBalance, err := walletdmanager.RequestAvailableBalanceToBeSpent(transferFee)
if err != nil {
qmlBridge.DisplayErrorDialog("Error calculating full balance minus fee.", err.Error())
}
qmlBridge.DisplayFullBalanceInTransferAmount(humanize.FtoaWithDigits(availableBalance, 2))
}
func getDefaultFeeAndDisplay() {
qmlBridge.DisplayDefaultFee(humanize.FtoaWithDigits(walletdmanager.DefaultTransferFee, 2))
}
func getNodeFeeAndDisplay() {
nodeFee, err := walletdmanager.RequestFeeinfo()
if err != nil {
qmlBridge.DisplayNodeFee("-")
} else {
qmlBridge.DisplayNodeFee(humanize.FtoaWithDigits(nodeFee, 2))
}
}
func saveRemoteDaemonInfo(daemonAddress string, daemonPort string) {
customRemoteDaemonAddress = daemonAddress
customRemoteDaemonPort = daemonPort
recordRemoteDaemonInfoToDB(customRemoteDaemonAddress, customRemoteDaemonPort)
qmlBridge.DisplayUseRemoteNode(getUseRemoteFromDB())
}
func saveAddress(name string, address string, paymentID string) {
if name == "" || address == "" {
qmlBridge.DisplayErrorDialog("Address not saved", "The address field and the name cannot be empty")
} else {
recordSavedAddressToDB(name, address, paymentID)
qmlBridge.DisplayPopup("Saved!", 1500)
}
}
func setupDB(pathToDB string) {
var err error
db, err = sql.Open("sqlite3", pathToDB)
if err != nil {
log.Fatal("error opening db file. err: ", err)
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS pathWallet (id INTEGER PRIMARY KEY AUTOINCREMENT,path VARCHAR(64) NULL)")
if err != nil {
log.Fatal("error creating table pathWallet. err: ", err)
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS remoteNode (id INTEGER PRIMARY KEY AUTOINCREMENT, useRemote BOOL NOT NULL DEFAULT '1')")
if err != nil {
log.Fatal("error creating table remoteNode. err: ", err)
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS fiatConversion (id INTEGER PRIMARY KEY AUTOINCREMENT, displayFiat BOOL NOT NULL DEFAULT '0', currency VARCHAR(64) DEFAULT 'USD')")
if err != nil {
log.Fatal("error creating table fiatConversion. err: ", err)
}
// table for storing custom node set in settings
_, err = db.Exec("CREATE TABLE IF NOT EXISTS remoteNodeInfo (id INTEGER PRIMARY KEY AUTOINCREMENT, address VARCHAR(64), port VARCHAR(64))")
if err != nil {
log.Fatal("error creating table remoteNodeInfo. err: ", err)
}
// table for remembering which remote node was lastly selected by the user in the list
_, err = db.Exec("CREATE TABLE IF NOT EXISTS selectedRemoteNode (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(64), address VARCHAR(64), port INTEGER)")
if err != nil {
log.Fatal("error creating table selectedRemoteNode. err: ", err)
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS savedAddresses (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(64), address VARCHAR(64), paymentID VARCHAR(64))")
if err != nil {
log.Fatal("error creating table savedAddresses. err: ", err)
}
}
func getAndDisplayStartInfoFromDB() {
qmlBridge.DisplayPathToPreviousWallet(getPathWalletFromDB())
customRemoteDaemonAddress, customRemoteDaemonPort = getRemoteDaemonInfoFromDB()
qmlBridge.DisplayUseRemoteNode(getUseRemoteFromDB())
qmlBridge.DisplaySettingsValues(getDisplayConversionFromDB())
qmlBridge.DisplaySettingsRemoteDaemonInfo(customRemoteDaemonAddress, customRemoteDaemonPort)
}
func getPathWalletFromDB() string {
pathToPreviousWallet := ""
rows, err := db.Query("SELECT path FROM pathWallet ORDER BY id DESC LIMIT 1")
if err != nil {
log.Fatal("error querying path from pathwallet table. err: ", err)
}
defer rows.Close()
for rows.Next() {
path := ""
err = rows.Scan(&path)
if err != nil {
log.Fatal("error reading item from pathWallet table. err: ", err)
}
pathToPreviousWallet = path
}
return pathToPreviousWallet
}
func recordPathWalletToDB(path string) {
stmt, err := db.Prepare(`INSERT INTO pathWallet(path) VALUES(?)`)
if err != nil {
log.Fatal("error preparing to insert pathWallet into db. err: ", err)
}
_, err = stmt.Exec(path)
if err != nil {
log.Fatal("error inserting pathWallet into db. err: ", err)
}
}
func getUseRemoteFromDB() bool {
rows, err := db.Query("SELECT useRemote FROM remoteNode ORDER BY id DESC LIMIT 1")
if err != nil {
log.Fatal("error querying useRemote from remoteNode table. err: ", err)
}
defer rows.Close()
for rows.Next() {
useRemote := true
err = rows.Scan(&useRemote)
if err != nil {
log.Fatal("error reading item from remoteNode table. err: ", err)
}
useRemoteNode = useRemote
}
return useRemoteNode
}
func recordUseRemoteToDB(useRemote bool) {
stmt, err := db.Prepare(`INSERT INTO remoteNode(useRemote) VALUES(?)`)
if err != nil {
log.Fatal("error preparing to insert useRemoteNode into db. err: ", err)
}
_, err = stmt.Exec(useRemote)
if err != nil {
log.Fatal("error inserting useRemoteNode into db. err: ", err)
}
}
func getRemoteDaemonInfoFromDB() (daemonAddress string, daemonPort string) {
rows, err := db.Query("SELECT address, port FROM remoteNodeInfo ORDER BY id DESC LIMIT 1")
if err != nil {
log.Fatal("error querying address and port from remoteNodeInfo table. err: ", err)
}
defer rows.Close()
for rows.Next() {
daemonAddress := ""
daemonPort := ""
err = rows.Scan(&daemonAddress, &daemonPort)
if err != nil {
log.Fatal("error reading item from remoteNodeInfo table. err: ", err)
}
customRemoteDaemonAddress = daemonAddress
customRemoteDaemonPort = daemonPort
}
return customRemoteDaemonAddress, customRemoteDaemonPort
}
func recordRemoteDaemonInfoToDB(daemonAddress string, daemonPort string) {
stmt, err := db.Prepare(`INSERT INTO remoteNodeInfo(address,port) VALUES(?,?)`)
if err != nil {
log.Fatal("error preparing to insert address and port of remote node into db. err: ", err)
}
_, err = stmt.Exec(daemonAddress, daemonPort)
if err != nil {
log.Fatal("error inserting address and port of remote node into db. err: ", err)
}
}
func getSelectedRemoteDaemonFromDB() (daemonAddress string, daemonPort int) {
rows, err := db.Query("SELECT address, port FROM selectedRemoteNode ORDER BY id DESC LIMIT 1")
if err != nil {
log.Fatal("error querying address and port from selectedRemoteNode table. err: ", err)
}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&daemonAddress, &daemonPort)
if err != nil {
log.Fatal("error reading item from selectedRemoteNode table. err: ", err)
}
}
return daemonAddress, daemonPort
}
func recordSelectedRemoteDaemonToDB(selectedNode node) {
stmt, err := db.Prepare(`INSERT INTO selectedRemoteNode(name,address,port) VALUES(?,?,?)`)
if err != nil {
log.Fatal("error preparing to insert name, address and port of selected remote node into db. err: ", err)
}
_, err = stmt.Exec(selectedNode.Name, selectedNode.URL, selectedNode.Port)
if err != nil {
log.Fatal("error inserting name, address and port of selected remote node into db. err: ", err)
}
}
func getDisplayConversionFromDB() bool {
rows, err := db.Query("SELECT displayFiat FROM fiatConversion ORDER BY id DESC LIMIT 1")
if err != nil {
log.Fatal("error reading displayFiat from fiatConversion table. err: ", err)
}
defer rows.Close()
for rows.Next() {
displayFiat := false
err = rows.Scan(&displayFiat)
if err != nil {
log.Fatal("error reading item from fiatConversion table. err: ", err)
}
displayFiatConversion = displayFiat
}
return displayFiatConversion
}
func recordDisplayConversionToDB(displayConversion bool) {
stmt, err := db.Prepare(`INSERT INTO fiatConversion(displayFiat) VALUES(?)`)
if err != nil {
log.Fatal("error preparing to insert displayFiat into db. err: ", err)
}
_, err = stmt.Exec(displayConversion)
if err != nil {
log.Fatal("error inserting displayFiat into db. err: ", err)
}
}
func getSavedAddressesFromDBAndDisplay() {
rows, err := db.Query("SELECT id, name, address, paymentID FROM savedAddresses ORDER BY id ASC")
if err != nil {
log.Fatal("error querying saved addresses from savedAddresses table. err: ", err)
}
defer rows.Close()
for rows.Next() {
dbID := 0
name := ""
address := ""
paymentID := ""
err = rows.Scan(&dbID, &name, &address, &paymentID)
if err != nil {
log.Fatal("error reading item from savedAddresses table. err: ", err)
}
qmlBridge.AddSavedAddressToList(dbID, name, address, paymentID)
}
}