forked from planetdecred/dcrlibwallet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmobilewallet.go
1614 lines (1455 loc) · 42 KB
/
mobilewallet.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 mobilewallet
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"net"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/decred/dcrd/addrmgr"
stake "github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
chainhash "github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/hdkeychain"
"github.com/decred/dcrd/rpcclient"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrwallet/chain"
"github.com/decred/dcrwallet/errors"
"github.com/decred/dcrwallet/netparams"
"github.com/decred/dcrwallet/p2p"
"github.com/decred/dcrwallet/spv"
"github.com/decred/dcrwallet/wallet"
"github.com/decred/dcrwallet/wallet/txauthor"
"github.com/decred/dcrwallet/wallet/txrules"
walletseed "github.com/decred/dcrwallet/walletseed"
"github.com/decred/slog"
)
var shutdownRequestChannel = make(chan struct{})
var shutdownSignaled = make(chan struct{})
var signals = []os.Signal{os.Interrupt, syscall.SIGTERM}
const BlockValid int = 1 << 0
type LibWallet struct {
dataDir string
dbDriver string
wallet *wallet.Wallet
rpcClient *chain.RPCClient
spvSyncer *spv.Syncer
cancelSync context.CancelFunc
loader *Loader
mu sync.Mutex
activeNet *netparams.Params
syncResponses []SpvSyncResponse
rescannning bool
}
func NewLibWallet(homeDir string, dbDriver string, netType string) *LibWallet {
var activeNet *netparams.Params
if netType == "mainnet" {
activeNet = &netparams.MainNetParams
} else {
activeNet = &netparams.TestNet3Params
}
lw := &LibWallet{
dataDir: filepath.Join(homeDir, netType),
dbDriver: dbDriver,
activeNet: activeNet,
}
errors.Separator = ":: "
initLogRotator(filepath.Join(homeDir, "/logs/"+netType+"/dcrwallet.log"))
return lw
}
func (lw *LibWallet) SetLogLevel(loglevel string) {
_, ok := slog.LevelFromString(loglevel)
if ok {
setLogLevels(loglevel)
}
}
func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) {
// If the first SplitHostPort errors because of a missing port and not
// for an invalid host, add the port. If the second SplitHostPort
// fails, then a port is not missing and the original error should be
// returned.
host, port, origErr := net.SplitHostPort(addr)
if origErr == nil {
return net.JoinHostPort(host, port), nil
}
addr = net.JoinHostPort(addr, defaultPort)
_, _, err = net.SplitHostPort(addr)
if err != nil {
return "", origErr
}
return addr, nil
}
func (lw *LibWallet) UnlockWallet(privPass []byte) error {
wallet, ok := lw.loader.LoadedWallet()
if !ok {
return fmt.Errorf("Wallet has not been loaded")
}
defer func() {
for i := range privPass {
privPass[i] = 0
}
}()
err := wallet.Unlock(privPass, nil)
return err
}
func (lw *LibWallet) LockWallet() {
if lw.wallet.Locked() {
lw.wallet.Lock()
}
}
func (lw *LibWallet) ChangePrivatePassphrase(oldPass []byte, newPass []byte) error {
defer func() {
for i := range oldPass {
oldPass[i] = 0
}
for i := range newPass {
newPass[i] = 0
}
}()
err := lw.wallet.ChangePrivatePassphrase(oldPass, newPass)
if err != nil {
return translateError(err)
}
return nil
}
func (lw *LibWallet) ChangePublicPassphrase(oldPass []byte, newPass []byte) error {
defer func() {
for i := range oldPass {
oldPass[i] = 0
}
for i := range newPass {
newPass[i] = 0
}
}()
if len(oldPass) == 0 {
oldPass = []byte(wallet.InsecurePubPassphrase)
}
if len(newPass) == 0 {
newPass = []byte(wallet.InsecurePubPassphrase)
}
err := lw.wallet.ChangePublicPassphrase(oldPass, newPass)
if err != nil {
return translateError(err)
}
return nil
}
func (lw *LibWallet) Shutdown() {
log.Info("Shuting down mobile wallet")
if lw.rpcClient != nil {
lw.rpcClient.Stop()
}
close(shutdownSignaled)
if lw.cancelSync != nil {
lw.cancelSync()
}
if logRotator != nil {
log.Infof("Shutting down log rotator")
logRotator.Close()
}
err := lw.loader.UnloadWallet()
if err != nil {
log.Errorf("Failed to close wallet: %v", err)
} else {
log.Infof("Closed wallet")
}
os.Exit(0)
}
func shutdownListener() {
interruptChannel := make(chan os.Signal, 1)
signal.Notify(interruptChannel, signals...)
// Listen for the initial shutdown signal
select {
case sig := <-interruptChannel:
log.Infof("Received signal (%s). Shutting down...", sig)
case <-shutdownRequestChannel:
log.Info("Shutdown requested. Shutting down...")
}
// Cancel all contexts created from withShutdownCancel.
close(shutdownSignaled)
// Listen for any more shutdown signals and log that shutdown has already
// been signaled.
for {
select {
case <-interruptChannel:
case <-shutdownRequestChannel:
}
log.Info("Shutdown signaled. Already shutting down...")
}
}
func contextWithShutdownCancel(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
go func() {
<-shutdownSignaled
cancel()
}()
return ctx
}
func decodeAddress(a string, params *chaincfg.Params) (dcrutil.Address, error) {
addr, err := dcrutil.DecodeAddress(a)
if err != nil {
return nil, err
}
if !addr.IsForNet(params) {
return nil, fmt.Errorf("address %v is not intended for use on %v",
a, params.Name)
}
return addr, nil
}
func (lw *LibWallet) InitLoader() {
stakeOptions := &StakeOptions{
VotingEnabled: false,
AddressReuse: false,
VotingAddress: nil,
TicketFee: 10e8,
}
fmt.Println("Initizing Loader: ", lw.dataDir, "Db: ", lw.dbDriver)
l := NewLoader(lw.activeNet.Params, lw.dataDir, stakeOptions,
20, false, 10e5, wallet.DefaultAccountGapLimit)
l.SetDatabaseDriver(lw.dbDriver)
lw.loader = l
go shutdownListener()
}
func (lw *LibWallet) CreateWallet(passphrase string, seedMnemonic string) error {
log.Info("Creating Wallet")
if len(seedMnemonic) == 0 {
return errors.New(ErrEmptySeed)
}
pubPass := []byte(wallet.InsecurePubPassphrase)
privPass := []byte(passphrase)
seed, err := walletseed.DecodeUserInput(seedMnemonic)
if err != nil {
log.Error(err)
return err
}
w, err := lw.loader.CreateNewWallet(pubPass, privPass, seed)
if err != nil {
log.Error(err)
return err
}
lw.wallet = w
log.Info("Created Wallet")
return nil
}
func (lw *LibWallet) CloseWallet() error {
err := lw.loader.UnloadWallet()
return err
}
func (lw *LibWallet) GenerateSeed() (string, error) {
seed, err := hdkeychain.GenerateSeed(hdkeychain.RecommendedSeedLen)
if err != nil {
log.Error(err)
return "", err
}
return walletseed.EncodeMnemonic(seed), nil
}
func (lw *LibWallet) VerifySeed(seedMnemonic string) bool {
_, err := walletseed.DecodeUserInput(seedMnemonic)
return err == nil
}
func (lw *LibWallet) AddSyncResponse(syncResponse SpvSyncResponse) {
lw.syncResponses = append(lw.syncResponses, syncResponse)
}
func (lw *LibWallet) SpvSync(peerAddresses string) error {
wallet, ok := lw.loader.LoadedWallet()
if !ok {
return errors.New(ErrWalletNotLoaded)
}
addr := &net.TCPAddr{IP: net.ParseIP("::1"), Port: 0}
amgrDir := filepath.Join(lw.dataDir, lw.wallet.ChainParams().Name)
amgr := addrmgr.New(amgrDir, net.LookupIP) // TODO: be mindful of tor
lp := p2p.NewLocalPeer(wallet.ChainParams(), addr, amgr)
ntfns := &spv.Notifications{
Synced: func(sync bool) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSynced(sync)
}
},
FetchHeadersStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(0, 0, START)
}
},
FetchHeadersProgress: func(fetchedHeadersCount int32, lastHeaderTime int64) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(fetchedHeadersCount, lastHeaderTime, PROGRESS)
}
},
FetchHeadersFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(0, 0, FINISH)
}
},
FetchMissingCFiltersStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(0, 0, START)
}
},
FetchMissingCFiltersProgress: func(missingCFitlersStart, missingCFitlersEnd int32) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(missingCFitlersStart, missingCFitlersEnd, PROGRESS)
}
},
FetchMissingCFiltersFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(0, 0, FINISH)
}
},
DiscoverAddressesStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnDiscoveredAddresses(START)
}
},
DiscoverAddressesFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnDiscoveredAddresses(FINISH)
}
if !wallet.Locked() {
wallet.Lock()
}
},
RescanStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(0, START)
}
},
RescanProgress: func(rescannedThrough int32) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(rescannedThrough, PROGRESS)
}
},
RescanFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(0, FINISH)
}
},
PeerDisconnected: func(peerCount int32, addr string) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnPeerDisconnected(peerCount)
}
},
PeerConnected: func(peerCount int32, addr string) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnPeerConnected(peerCount)
}
},
}
var spvConnect []string
if len(peerAddresses) > 0 {
spvConnect = strings.Split(peerAddresses, ";")
}
go func() {
syncer := spv.NewSyncer(wallet, lp)
syncer.SetNotifications(ntfns)
if len(spvConnect) > 0 {
spvConnects := make([]string, len(spvConnect))
for i := 0; i < len(spvConnect); i++ {
spvConnect, err := NormalizeAddress(spvConnect[i], lw.activeNet.Params.DefaultPort)
if err != nil {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(3, errors.E("SPV Connect address invalid: %v", err))
}
return
}
spvConnects[i] = spvConnect
}
syncer.SetPersistantPeers(spvConnects)
}
wallet.SetNetworkBackend(syncer)
lw.loader.SetNetworkBackend(syncer)
ctx, cancel := context.WithCancel(context.Background())
lw.cancelSync = cancel
err := syncer.Run(ctx)
if err != nil {
if err == context.Canceled {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(1, errors.E("SPV synchronization canceled: %v", err))
}
return
} else if err == context.DeadlineExceeded {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(2, errors.E("SPV synchronization deadline exceeded: %v", err))
}
return
}
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(-1, err)
}
return
}
}()
return nil
}
func (lw *LibWallet) RpcSync(networkAddress string, username string, password string, cert []byte) error {
// Error if the wallet is already syncing with the network.
wallet, walletLoaded := lw.loader.LoadedWallet()
if walletLoaded {
_, err := wallet.NetworkBackend()
if err == nil {
return errors.New(ErrFailedPrecondition)
}
}
lw.mu.Lock()
chainClient := lw.rpcClient
lw.mu.Unlock()
ctx := contextWithShutdownCancel(context.Background())
// If the rpcClient is already set, you can just use that instead of attempting a new connection.
if chainClient == nil {
networkAddress, err := NormalizeAddress(networkAddress, lw.activeNet.JSONRPCClientPort)
if err != nil {
return errors.New(ErrInvalidAddress)
}
chainClient, err = chain.NewRPCClient(lw.activeNet.Params, networkAddress, username,
password, cert, len(cert) == 0)
if err != nil {
return translateError(err)
}
err = chainClient.Start(ctx, false)
if err != nil {
if err == rpcclient.ErrInvalidAuth {
return errors.New(ErrInvalid)
}
if errors.Match(errors.E(context.Canceled), err) {
return errors.New(ErrContextCanceled)
}
return errors.New(ErrUnavailable)
}
lw.mu.Lock()
lw.rpcClient = chainClient
lw.mu.Unlock()
}
n := chain.BackendFromRPCClient(chainClient.Client)
lw.loader.SetNetworkBackend(n)
wallet.SetNetworkBackend(n)
// Disassociate the RPC client from all subsystems until reconnection
// occurs.
defer lw.wallet.SetNetworkBackend(nil)
defer lw.loader.SetNetworkBackend(nil)
defer lw.loader.StopTicketPurchase()
ntfns := &chain.Notifications{
Synced: func(sync bool) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSynced(sync)
}
},
FetchMissingCFiltersStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(0, 0, START)
}
},
FetchMissingCFiltersProgress: func(missingCFitlersStart, missingCFitlersEnd int32) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(missingCFitlersStart, missingCFitlersEnd, PROGRESS)
}
},
FetchMissingCFiltersFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchMissingCFilters(0, 0, FINISH)
}
},
FetchHeadersStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(0, 0, START)
}
},
FetchHeadersProgress: func(fetchedHeadersCount int32, lastHeaderTime int64) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(fetchedHeadersCount, lastHeaderTime, PROGRESS)
}
},
FetchHeadersFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnFetchedHeaders(0, 0, FINISH)
}
},
DiscoverAddressesStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnDiscoveredAddresses(START)
}
},
DiscoverAddressesFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnDiscoveredAddresses(FINISH)
}
if !wallet.Locked() {
wallet.Lock()
}
},
RescanStarted: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(0, START)
}
},
RescanProgress: func(rescannedThrough int32) {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(rescannedThrough, PROGRESS)
}
},
RescanFinished: func() {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnRescan(0, FINISH)
}
},
}
syncer := chain.NewRPCSyncer(wallet, chainClient)
syncer.SetNotifications(ntfns)
go func() {
// Run wallet synchronization until it is cancelled or errors. If the
// context was cancelled, return immediately instead of trying to
// reconnect.
err := syncer.Run(ctx, true)
if err != nil {
if err == context.Canceled {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(1, errors.E("SPV synchronization canceled: %v", err))
}
return
} else if err == context.DeadlineExceeded {
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(2, errors.E("SPV synchronization deadline exceeded: %v", err))
}
return
}
for _, syncResponse := range lw.syncResponses {
syncResponse.OnSyncError(-1, err)
}
}
}()
return nil
}
func (lw *LibWallet) DropSpvConnection() {
if lw.cancelSync != nil {
lw.cancelSync()
}
}
func done(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
func (lw *LibWallet) OpenWallet(pubPass []byte) error {
w, err := lw.loader.OpenExistingWallet(pubPass)
if err != nil {
log.Error(err)
return translateError(err)
}
lw.wallet = w
return nil
}
func (lw *LibWallet) RescanBlocks() error {
netBackend, err := lw.wallet.NetworkBackend()
if err != nil {
return errors.E(ErrNotConnected)
}
if lw.rescannning {
return errors.E(ErrInvalid)
}
go func() {
defer func() {
lw.rescannning = false
}()
lw.rescannning = true
progress := make(chan wallet.RescanProgress, 1)
ctx := contextWithShutdownCancel(context.Background())
var totalHeight int32
go lw.wallet.RescanProgressFromHeight(ctx, netBackend, 0, progress)
for p := range progress {
if p.Err != nil {
log.Error(p.Err)
return
}
totalHeight += p.ScannedThrough
for _, response := range lw.syncResponses {
response.OnRescan(p.ScannedThrough, PROGRESS)
}
}
select {
case <-ctx.Done():
for _, response := range lw.syncResponses {
response.OnRescan(totalHeight, PROGRESS)
}
default:
for _, response := range lw.syncResponses {
response.OnRescan(totalHeight, FINISH)
}
}
}()
return nil
}
func (lw *LibWallet) GetBestBlock() int32 {
_, height := lw.wallet.MainChainTip()
return height
}
func (lw *LibWallet) GetBestBlockTimeStamp() int64 {
_, height := lw.wallet.MainChainTip()
identifier := wallet.NewBlockIdentifierFromHeight(height)
info, err := lw.wallet.BlockInfo(identifier)
if err != nil {
log.Error(err)
return 0
}
return info.Timestamp
}
func (lw *LibWallet) TransactionNotification(listener TransactionListener) {
go func() {
n := lw.wallet.NtfnServer.TransactionNotifications()
defer n.Done()
for {
v := <-n.C
for _, transaction := range v.UnminedTransactions {
var amount int64
var inputAmounts int64
var outputAmounts int64
tempCredits := make([]TransactionCredit, len(transaction.MyOutputs))
for index, credit := range transaction.MyOutputs {
outputAmounts += int64(credit.Amount)
tempCredits[index] = TransactionCredit{
Index: int32(credit.Index),
Account: int32(credit.Account),
Internal: credit.Internal,
Amount: int64(credit.Amount),
Address: credit.Address.String()}
}
tempDebits := make([]TransactionDebit, len(transaction.MyInputs))
for index, debit := range transaction.MyInputs {
inputAmounts += int64(debit.PreviousAmount)
tempDebits[index] = TransactionDebit{
Index: int32(debit.Index),
PreviousAccount: int32(debit.PreviousAccount),
PreviousAmount: int64(debit.PreviousAmount),
AccountName: lw.AccountName(int32(debit.PreviousAccount))}
}
var direction int32
amountDifference := outputAmounts - inputAmounts
if amountDifference < 0 && (float64(transaction.Fee) == math.Abs(float64(amountDifference))) {
//Transfered
direction = 2
amount = int64(transaction.Fee)
} else if amountDifference > 0 {
//Received
direction = 1
amount = outputAmounts
} else {
//Sent
direction = 0
amount = inputAmounts
amount -= outputAmounts
amount -= int64(transaction.Fee)
}
tempTransaction := Transaction{
Fee: int64(transaction.Fee),
Hash: fmt.Sprintf("%02x", reverse(transaction.Hash[:])),
Raw: fmt.Sprintf("%02x", transaction.Transaction[:]),
Timestamp: transaction.Timestamp,
Type: transactionType(transaction.Type),
Credits: &tempCredits,
Amount: amount,
Height: -1,
Direction: direction,
Debits: &tempDebits}
fmt.Println("New Transaction")
result, err := json.Marshal(tempTransaction)
if err != nil {
log.Error(err)
} else {
listener.OnTransaction(string(result))
}
}
for _, block := range v.AttachedBlocks {
listener.OnBlockAttached(int32(block.Header.Height), block.Header.Timestamp.UnixNano())
for _, transaction := range block.Transactions {
listener.OnTransactionConfirmed(fmt.Sprintf("%02x", reverse(transaction.Hash[:])), int32(block.Header.Height))
}
}
}
}()
}
func (lw *LibWallet) GetTransaction(txHash []byte) (string, error) {
hash, err := chainhash.NewHash(txHash)
if err != nil {
log.Error(err)
return "", err
}
txSummary, _, blockHash, err := lw.wallet.TransactionSummary(hash)
if err != nil {
log.Error(err)
return "", err
}
var inputTotal int64
var outputTotal int64
var amount int64
credits := make([]TransactionCredit, len(txSummary.MyOutputs))
for index, credit := range txSummary.MyOutputs {
outputTotal += int64(credit.Amount)
credits[index] = TransactionCredit{
Index: int32(credit.Index),
Account: int32(credit.Account),
Internal: credit.Internal,
Amount: int64(credit.Amount),
Address: credit.Address.String()}
}
debits := make([]TransactionDebit, len(txSummary.MyInputs))
for index, debit := range txSummary.MyInputs {
inputTotal += int64(debit.PreviousAmount)
debits[index] = TransactionDebit{
Index: int32(debit.Index),
PreviousAccount: int32(debit.PreviousAccount),
PreviousAmount: int64(debit.PreviousAmount),
AccountName: lw.AccountName(int32(debit.PreviousAccount))}
}
var direction int32
if txSummary.Type == wallet.TransactionTypeRegular {
amountDifference := outputTotal - inputTotal
if amountDifference < 0 && (float64(txSummary.Fee) == math.Abs(float64(amountDifference))) {
//Transfered
direction = 2
amount = int64(txSummary.Fee)
} else if amountDifference > 0 {
//Received
direction = 1
amount = outputTotal
} else {
//Sent
direction = 0
amount = inputTotal
amount -= outputTotal
amount -= int64(txSummary.Fee)
}
}
var height int32 = -1
if blockHash != nil {
blockIdentifier := wallet.NewBlockIdentifierFromHash(blockHash)
blockInfo, err := lw.wallet.BlockInfo(blockIdentifier)
if err != nil {
log.Error(err)
} else {
height = blockInfo.Height
}
}
transaction := Transaction{
Fee: int64(txSummary.Fee),
Hash: fmt.Sprintf("%02x", reverse(txSummary.Hash[:])),
Raw: fmt.Sprintf("%02x", txSummary.Transaction[:]),
Timestamp: txSummary.Timestamp,
Type: transactionType(txSummary.Type),
Credits: &credits,
Amount: amount,
Height: height,
Direction: direction,
Debits: &debits}
result, err := json.Marshal(transaction)
if err != nil {
return "", err
}
return string(result), nil
}
func (lw *LibWallet) GetTransactions(response GetTransactionsResponse) error {
ctx := contextWithShutdownCancel(context.Background())
var startBlock, endBlock *wallet.BlockIdentifier
transactions := make([]Transaction, 0)
rangeFn := func(block *wallet.Block) (bool, error) {
for _, transaction := range block.Transactions {
var inputAmounts int64
var outputAmounts int64
var amount int64
tempCredits := make([]TransactionCredit, len(transaction.MyOutputs))
for index, credit := range transaction.MyOutputs {
outputAmounts += int64(credit.Amount)
tempCredits[index] = TransactionCredit{
Index: int32(credit.Index),
Account: int32(credit.Account),
Internal: credit.Internal,
Amount: int64(credit.Amount),
Address: credit.Address.String()}
}
tempDebits := make([]TransactionDebit, len(transaction.MyInputs))
for index, debit := range transaction.MyInputs {
inputAmounts += int64(debit.PreviousAmount)
tempDebits[index] = TransactionDebit{
Index: int32(debit.Index),
PreviousAccount: int32(debit.PreviousAccount),
PreviousAmount: int64(debit.PreviousAmount),
AccountName: lw.AccountName(int32(debit.PreviousAccount))}
}
var direction int32
if transaction.Type == wallet.TransactionTypeRegular {
amountDifference := outputAmounts - inputAmounts
if amountDifference < 0 && (float64(transaction.Fee) == math.Abs(float64(amountDifference))) {
//Transfered
direction = 2
amount = int64(transaction.Fee)
} else if amountDifference > 0 {
//Received
direction = 1
for _, credit := range transaction.MyOutputs {
amount += int64(credit.Amount)
}
} else {
//Sent
direction = 0
for _, debit := range transaction.MyInputs {
amount += int64(debit.PreviousAmount)
}
for _, credit := range transaction.MyOutputs {
amount -= int64(credit.Amount)
}
amount -= int64(transaction.Fee)
}
}
var height int32 = -1
if block.Header != nil {
height = int32(block.Header.Height)
}
tempTransaction := Transaction{
Fee: int64(transaction.Fee),
Hash: fmt.Sprintf("%02x", reverse(transaction.Hash[:])),
Raw: fmt.Sprintf("%02x", transaction.Transaction[:]),
Timestamp: transaction.Timestamp,
Type: transactionType(transaction.Type),
Credits: &tempCredits,
Amount: amount,
Height: height,
Direction: direction,
Debits: &tempDebits}
transactions = append(transactions, tempTransaction)
}
select {
case <-ctx.Done():
return true, ctx.Err()
default:
return false, nil
}
}
err := lw.wallet.GetTransactions(rangeFn, startBlock, endBlock)
result, _ := json.Marshal(getTransactionsResponse{ErrorOccurred: false, Transactions: transactions})
response.OnResult(string(result))
return err
}
func (lw *LibWallet) DecodeTransaction(txHash []byte) (string, error) {
hash, err := chainhash.NewHash(txHash)
if err != nil {
log.Error(err)
return "", err
}
txSummary, _, _, err := lw.wallet.TransactionSummary(hash)
if err != nil {
log.Error(err)
return "", err
}
serializedTx := txSummary.Transaction
var mtx wire.MsgTx
err = mtx.Deserialize(bytes.NewReader(serializedTx))
if err != nil {
log.Error(err)
return "", err
}
var ssGenVersion uint32
var lastBlockValid bool
var votebits string
if stake.IsSSGen(&mtx) {
ssGenVersion = voteVersion(&mtx)
lastBlockValid = voteBits(&mtx)&uint16(BlockValid) != 0
votebits = fmt.Sprintf("%#04x", voteBits(&mtx))
}
var tx = DecodedTransaction{
Hash: fmt.Sprintf("%02x", reverse(hash[:])),
Type: transactionType(wallet.TxTransactionType(&mtx)),
Version: int32(mtx.Version),
LockTime: int32(mtx.LockTime),
Expiry: int32(mtx.Expiry),
Inputs: decodeTxInputs(&mtx),
Outputs: decodeTxOutputs(&mtx, lw.wallet.ChainParams()),
VoteVersion: int32(ssGenVersion),
LastBlockValid: lastBlockValid,
VoteBits: votebits,
}
result, _ := json.Marshal(tx)
return string(result), nil
}
func decodeTxInputs(mtx *wire.MsgTx) []DecodedInput {
inputs := make([]DecodedInput, len(mtx.TxIn))
for i, txIn := range mtx.TxIn {
inputs[i] = DecodedInput{
PreviousTransactionHash: fmt.Sprintf("%02x", reverse(txIn.PreviousOutPoint.Hash[:])),
PreviousTransactionIndex: int32(txIn.PreviousOutPoint.Index),
AmountIn: txIn.ValueIn,
}
}
return inputs
}
func decodeTxOutputs(mtx *wire.MsgTx, chainParams *chaincfg.Params) []DecodedOutput {
outputs := make([]DecodedOutput, len(mtx.TxOut))
txType := stake.DetermineTxType(mtx)
for i, v := range mtx.TxOut {
var addrs []dcrutil.Address
var encodedAddrs []string
var scriptClass txscript.ScriptClass
if (txType == stake.TxTypeSStx) && (stake.IsStakeSubmissionTxOut(i)) {
scriptClass = txscript.StakeSubmissionTy
addr, err := stake.AddrFromSStxPkScrCommitment(v.PkScript,
chainParams)
if err != nil {
encodedAddrs = []string{fmt.Sprintf(
"[error] failed to decode ticket "+
"commitment addr output for tx hash "+
"%v, output idx %v", mtx.TxHash(), i)}