forked from blocktree/openwallet
/
manager.go
1931 lines (1516 loc) · 43.8 KB
/
manager.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 2018 The openwallet Authors
* This file is part of the openwallet library.
*
* The openwallet library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The openwallet library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package hypercash
import (
"errors"
"fmt"
"math"
"path/filepath"
"sort"
"strings"
"time"
"github.com/asdine/storm/q"
"github.com/astaxie/beego/config"
"github.com/blocktree/openwallet/v2/common"
"github.com/blocktree/openwallet/v2/common/file"
"github.com/blocktree/openwallet/v2/hdkeystore"
"github.com/blocktree/openwallet/v2/log"
"github.com/blocktree/openwallet/v2/openwallet"
"github.com/blocktree/openwallet/v2/walletnode"
"github.com/bndr/gotabulate"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/codeskyblue/go-sh"
"github.com/shopspring/decimal"
)
const (
maxAddresNum = 10000
)
type WalletManager struct {
storage *hdkeystore.HDKeystore //秘钥存取
hcdClient *Client // 全节点客户端
walletClient *Client // 节点客户端
config *WalletConfig //钱包管理配置
walletsInSum map[string]*openwallet.Wallet //参与汇总的钱包
blockscanner *BTCBlockScanner //区块扫描器
}
func NewWalletManager() *WalletManager {
wm := WalletManager{}
wm.config = NewConfig()
storage := hdkeystore.NewHDKeystore(wm.config.keyDir, hdkeystore.StandardScryptN, hdkeystore.StandardScryptP)
wm.storage = storage
//参与汇总的钱包
wm.walletsInSum = make(map[string]*openwallet.Wallet)
//区块扫描器
wm.blockscanner = NewBTCBlockScanner(&wm)
return &wm
}
func (wm *WalletManager) GetAddressesByAccount(walletID string) ([]string, error) {
var (
addresses = make([]string, 0)
request []interface{}
)
if walletID == "" {
request = nil
} else {
request = []interface{}{
walletID,
}
}
result, err := wm.walletClient.Call("getaddressesbyaccount", request)
if err != nil {
return nil, err
}
array := result.Array()
for _, a := range array {
addresses = append(addresses, a.String())
}
return addresses, nil
}
//GetAddressesFromLocalDB 从本地数据库
func (wm *WalletManager) GetAddressesFromLocalDB(walletID string, watchOnly bool, offset, limit int) ([]*openwallet.Address, error) {
wallet, err := wm.GetWalletInfo(walletID)
if err != nil {
return nil, err
}
db, err := wallet.OpenDB()
if err != nil {
return nil, err
}
defer db.Close()
var addresses []*openwallet.Address
//err = db.Find("WalletID", walletID, &addresses)
if limit > 0 {
err = db.Select(q.And(
q.Eq("AccountID", walletID),
q.Eq("WatchOnly", watchOnly),
)).Limit(limit).Skip(offset).Find(&addresses)
//err = db.Find("AccountID", walletID, &addresses, storm.Limit(limit), storm.Skip(offset))
} else {
err = db.Select(q.And(
q.Eq("AccountID", walletID),
q.Eq("WatchOnly", watchOnly),
)).Skip(offset).Find(&addresses)
}
if err != nil {
return nil, err
}
return addresses, nil
}
//CreateNewAddress 给指定账户创建地址
func (wm *WalletManager) CreateNewAddress(key *hdkeystore.HDKey) (*openwallet.Address, error) {
request := []interface{}{
"default",
"ignore",
}
result, err := wm.walletClient.Call("getnewaddress", request)
if err != nil {
return nil, err
}
addr := openwallet.Address{
Address: result.String(),
AccountID: key.KeyID,
HDPath: "",
CreatedTime: time.Now().Unix(),
Symbol: wm.config.symbol,
Index: 0,
WatchOnly: false,
}
return &addr, err
}
//CreateNewAddress 给指定账户创建地址
func (wm *WalletManager) CreateNewChangeAddress(walletID string) (*openwallet.Address, error) {
request := []interface{}{
"default",
}
result, err := wm.walletClient.Call("getrawchangeaddress", request)
if err != nil {
return nil, err
}
addr := openwallet.Address{
Address: result.String(),
AccountID: walletID,
HDPath: "",
CreatedTime: time.Now().Unix(),
Symbol: wm.config.symbol,
Index: 0,
WatchOnly: false,
}
wallet, err := wm.GetWalletInfo(walletID)
if err != nil {
return nil, err
}
//写入数据库
err = wm.saveAddressToDB([]*openwallet.Address{&addr}, wallet)
if err != nil {
return nil, err
}
return &addr, err
}
//CreateNewAccount 创建新账户
//func (wm *WalletManager) ImportPrivateKey(wif string, walletID string) error {
//
// request := []interface{}{
// wif,
// walletID,
// false,
// }
//
// _, err := wm.walletClient.Call("importprivkey", request)
// if err != nil {
// return err
// }
//
// return nil
//
//}
//ImportMulti 批量导入地址和私钥
func (wm *WalletManager) ImportMulti(addresses []*openwallet.Address, keys []string, walletID string, watchOnly bool) ([]int, error) {
/*
[
{
"scriptPubKey" : { "address": "1NL9w5fP9kX2D9ToNZPxaiwFJCngNYEYJo" },
"timestamp" : 0,
"label" : "Personal"
},
{
"scriptPubKey" : "76a9149e857da0a5b397559c78c98c9d3f7f655d19c68688ac",
"timestamp" : 1493912405,
"label" : "TestFailure"
}
]' '{ "rescan": true }'
*/
var (
request []interface{}
imports = make([]interface{}, 0)
failedIndex = make([]int, 0)
)
if len(addresses) != len(keys) {
return nil, errors.New("Import addresses is not equal keys count!")
}
for i, a := range addresses {
k := keys[i]
obj := map[string]interface{}{
"scriptPubKey": map[string]interface{}{
"address": a.Address,
},
"label": walletID,
"timestamp": "now",
"watchonly": watchOnly,
}
if !watchOnly {
obj["keys"] = []string{k}
}
imports = append(imports, obj)
}
request = []interface{}{
imports,
map[string]interface{}{
"rescan": false,
},
}
result, err := wm.walletClient.Call("importmulti", request)
if err != nil {
return nil, err
}
for i, r := range result.Array() {
if !r.Get("success").Bool() {
failedIndex = append(failedIndex, i)
}
}
return failedIndex, err
}
//UnlockWallet 解锁钱包
func (wm *WalletManager) UnlockWallet(passphrase string, seconds int) error {
request := []interface{}{
passphrase,
seconds,
}
_, err := wm.walletClient.Call("walletpassphrase", request)
if err != nil {
return err
}
return err
}
//LockWallet 锁钱包
func (wm *WalletManager) LockWallet() error {
_, err := wm.walletClient.Call("walletlock", nil)
if err != nil {
return err
}
return err
}
//CreateBatchAddress 批量创建地址
func (wm *WalletManager) CreateBatchAddress(name, password string, count uint64) (string, []*openwallet.Address, error) {
var (
synCount uint64 = 10
quit = make(chan struct{})
done = 0 //完成标记
shouldDone = 0 //需要完成的总数
)
//读取钱包
w, err := wm.GetWalletInfo(name)
if err != nil {
return "", nil, err
}
//加载钱包
key, err := w.HDKey(password)
if err != nil {
return "", nil, err
}
timestamp := time.Now()
//建立文件名,时间格式2006-01-02 15:04:05
filename := "address-" + common.TimeFormat("20060102150405", timestamp) + ".txt"
filePath := filepath.Join(wm.config.addressDir, filename)
//生产通道
producer := make(chan []*openwallet.Address)
defer close(producer)
//消费通道
worker := make(chan []*openwallet.Address)
defer close(worker)
//保存地址过程
saveAddressWork := func(addresses chan []*openwallet.Address, filename string, wallet *openwallet.Wallet) {
var (
saveErr error
)
for {
//回收创建的地址
getAddrs := <-addresses
//批量写入数据库
saveErr = wm.saveAddressToDB(getAddrs, wallet)
//数据保存成功才导出文件
if saveErr == nil {
//导出一批地址
wm.exportAddressToFile(getAddrs, filename)
} else {
log.Std.Info("saveAddressToDB unexpected error: %v", saveErr)
}
//累计完成的线程数
done++
if done == shouldDone {
close(quit) //关闭通道,等于给通道传入nil
}
}
}
//解锁钱包
err = wm.UnlockWallet(password, 3600)
if err != nil {
return "", nil, err
}
/* 开启导出的线程,监听新地址,批量导出 */
go saveAddressWork(worker, filePath, w)
/* 计算synCount个线程,内部运行的次数 */
//每个线程内循环的数量,以synCount个线程并行处理
runCount := count / synCount
otherCount := count % synCount
if runCount > 0 {
for i := uint64(0); i < synCount; i++ {
//开始创建地址
log.Std.Info("Start create address thread[%d]", i)
s := i * runCount
e := (i + 1) * runCount
go wm.createAddressWork(key, producer, name, uint64(timestamp.Unix()), s, e)
shouldDone++
}
}
if otherCount > 0 {
//开始创建地址
log.Std.Info("Start create address thread[REST]")
s := count - otherCount
e := count
go wm.createAddressWork(key, producer, name, uint64(timestamp.Unix()), s, e)
shouldDone++
}
values := make([][]*openwallet.Address, 0)
outputAddress := make([]*openwallet.Address, 0)
//以下使用生产消费模式
for {
var activeWorker chan<- []*openwallet.Address
var activeValue []*openwallet.Address
//当数据队列有数据时,释放顶部,激活消费
if len(values) > 0 {
activeWorker = worker
activeValue = values[0]
}
select {
//生成者不断生成数据,插入到数据队列尾部
case pa := <-producer:
values = append(values, pa)
outputAddress = append(outputAddress, pa...)
//log.Std.Info("completed %d", len(pa))
//当激活消费者后,传输数据给消费者,并把顶部数据出队
case activeWorker <- activeValue:
//log.Std.Info("Get %d", len(activeValue))
values = values[1:]
case <-quit:
//退出
wm.LockWallet()
log.Std.Info("All addresses have been created!")
return filePath, outputAddress, nil
}
}
wm.LockWallet()
return filePath, outputAddress, nil
}
//CreateNewWallet 创建钱包
func (wm *WalletManager) CreateNewWallet(name, password string) (*openwallet.Wallet, string, error) {
var (
err error
wallets []*openwallet.Wallet
)
//检查钱包名是否存在
wallets, err = wm.GetWallets()
for _, w := range wallets {
if w.Alias == name {
return nil, "", errors.New("The wallet's alias is duplicated! ")
}
}
fmt.Printf("Verify password in hcwallet wallet...\n")
//钱包已经加密,解锁钱包1秒,检查密码
err = wm.UnlockWallet(password, 1)
if err != nil {
fmt.Printf("%v\n", err)
return nil, "", errors.New("The wallet's password is not equal hcwallet wallet!")
}
fmt.Printf("Create new wallet hdkeystore...\n")
seed, err := hdkeychain.GenerateSeed(32)
if err != nil {
return nil, "", err
}
extSeed, err := hdkeystore.GetExtendSeed(seed, wm.config.masterKey)
if err != nil {
return nil, "", err
}
key, keyFile, err := hdkeystore.StoreHDKeyWithSeed(wm.config.keyDir, name, password, extSeed, hdkeystore.StandardScryptN, hdkeystore.StandardScryptP)
if err != nil {
return nil, "", err
}
file.MkdirAll(wm.config.dbPath)
file.MkdirAll(wm.config.keyDir)
w := &openwallet.Wallet{
WalletID: key.KeyID,
Alias: key.Alias,
KeyFile: keyFile,
DBFile: filepath.Join(wm.config.dbPath, key.Alias+"-"+key.KeyID+".db"),
}
w.SaveToDB()
//w := Wallet{WalletID: key.RootId, Alias: key.Alias}
return w, keyFile, nil
}
//EncryptWallet 通过密码加密钱包,只在第一次加密码时才有效
func (wm *WalletManager) EncryptWallet(password string) error {
request := []interface{}{
password,
}
_, err := wm.walletClient.Call("encryptwallet", request)
if err != nil {
return err
}
return nil
}
//GetWallets 获取钱包列表
func (wm *WalletManager) GetWallets() ([]*openwallet.Wallet, error) {
wallets, err := openwallet.GetWalletsByKeyDir(wm.config.keyDir)
if err != nil {
return nil, err
}
for _, w := range wallets {
w.DBFile = filepath.Join(wm.config.dbPath, w.FileName()+".db")
}
return wallets, nil
}
//GetWalletInfo 获取钱包列表
func (wm *WalletManager) GetWalletInfo(walletID string) (*openwallet.Wallet, error) {
wallets, err := wm.GetWallets()
if err != nil {
return nil, err
}
//获取钱包余额
for _, w := range wallets {
if w.WalletID == walletID {
return w, nil
}
}
return nil, errors.New("The wallet that your given name is not exist!")
}
//GetWalletBalance 获取钱包余额
func (wm *WalletManager) GetWalletBalance(accountID string) string {
//request := []interface{}{
// name,
// 1,
// true,
//}
wm.RebuildWalletUnspent(accountID)
utxos, err := wm.ListUnspentFromLocalDB(accountID)
if err != nil {
return "0"
}
balance := decimal.New(0, 0)
//批量插入到本地数据库
//设置utxo的钱包账户
for _, utxo := range utxos {
if accountID == utxo.AccountID {
amount, _ := decimal.NewFromString(utxo.Amount)
balance = balance.Add(amount)
}
}
//for _, u := range utxos {
// amount, _ := decimal.NewFromString(u.Amount)
// balance = balance.Add(amount)
//}
//balance, err := client.Call("getbalance", request)
//if err != nil {
// return "", err
//}
return balance.StringFixed(8)
}
//GetAddressBalance 获取地址余额
func (wm *WalletManager) GetAddressBalance(walletID, address string) string {
wm.RebuildWalletUnspent(walletID)
wallet, err := wm.GetWalletInfo(walletID)
if err != nil {
return "0"
}
db, err := wallet.OpenDB()
if err != nil {
return "0"
}
defer db.Close()
var utxos []*Unspent
err = db.Select(q.And(
q.Eq("AccountID", walletID),
q.Eq("Address", address),
)).Find(&utxos)
if err != nil {
return "0"
}
balance := decimal.New(0, 0)
for _, utxo := range utxos {
amount, _ := decimal.NewFromString(utxo.Amount)
balance = balance.Add(amount)
}
return balance.StringFixed(8)
}
//CreateNewPrivateKey 创建私钥,返回私钥wif格式字符串
//func (wm *WalletManager) CreateNewPrivateKey(key *hdkeystore.HDKey, start, index uint64) (string, *openwallet.Address, error) {
//
// derivedPath := fmt.Sprintf("%s/%d/%d", key.RootPath, start, index)
// //fmt.Printf("derivedPath = %s\n", derivedPath)
// childKey, err := key.DerivedKeyWithPath(derivedPath)
//
// privateKey, err := childKey.ECPrivKey()
// if err != nil {
// return "", nil, err
// }
//
// privKey, _ := chainec.Secp256k1.PrivKeyFromBytes(privateKey.Serialize())
//
// cfg := chaincfg.MainNetParams
// if wm.config.isTestNet {
// cfg = chaincfg.TestNet2Params
// }
//
// wif, err := hcutil.NewWIF(privKey, &cfg, chainec.ECTypeSecp256k1)
// if err != nil {
// return "", nil, err
// }
//
// publicKey, err := childKey.ECPubKey()
// if err != nil {
// return "", nil, err
// }
//
// pkHash := hcutil.Hash160(publicKey.SerializeCompressed())
// address, err := hcutil.NewAddressPubKeyHash(pkHash, &cfg, chainec.ECTypeSecp256k1)
//
// //address, err := childKey.Address(&cfg)
// if err != nil {
// return "", nil, err
// }
//
// addr := openwallet.Address{
// Address: address.String(),
// AccountID: key.RootId,
// HDPath: derivedPath,
// CreatedAt: time.Now(),
// Symbol: wm.config.symbol,
// Index: index,
// }
//
// return wif.String(), &addr, err
// //return "", &addr, err
//}
//CreateBatchPrivateKey
//func (wm *WalletManager) CreateBatchPrivateKey(key *hdkeystore.HDKey, count uint64) ([]string, error) {
//
// var (
// wifs = make([]string, 0)
// )
//
// start := time.Now().Unix()
// for i := uint64(0); i < count; i++ {
// wif, _, err := wm.CreateNewPrivateKey(key, uint64(start), i)
// if err != nil {
// continue
// }
// wifs = append(wifs, wif)
// }
//
// return wifs, nil
//
//}
//BackupWalletData 备份钱包
//func (wm *WalletManager) BackupWalletData(dest string) error {
//
// request := []interface{}{
// dest,
// }
//
// _, err := wm.walletClient.Call("backupwallet", request)
// if err != nil {
// return err
// }
//
// return nil
//
//}
//FileName 该钱包定义的文件名规则
func (wm *WalletManager) WalletFileName(w *openwallet.Wallet) string {
return w.Alias + "-" + w.WalletID
}
//BackupWallet 备份数据
func (wm *WalletManager) BackupWallet(walletID string) (string, error) {
w, err := wm.GetWalletInfo(walletID)
if err != nil {
return "", err
}
//创建备份文件夹
newBackupDir := filepath.Join(wm.config.backupDir, wm.WalletFileName(w)+"-"+common.TimeFormat("20060102150405"))
file.MkdirAll(newBackupDir)
//创建临时备份文件wallet.db
//tmpWalletDat := fmt.Sprintf("tmp-walllet-%d.dat", time.Now().Unix())
coreWalletDat := filepath.Join(wm.config.walletDataPath, "wallet.db")
//1. 备份核心钱包的wallet.db
//err = wm.BackupWalletData(tmpWalletDat)
//if err != nil {
// return "", err
//}
//复制临时文件到备份文件夹
file.Copy(coreWalletDat, filepath.Join(newBackupDir, "wallet.db"))
//删除临时文件
//file.Delete(tmpWalletDat)
//2. 备份种子文件
file.Copy(w.KeyFile, newBackupDir)
//3. 备份地址数据库
file.Copy(w.DBFile, newBackupDir)
return newBackupDir, nil
}
//RestoreWallet 恢复钱包
func (wm *WalletManager) RestoreWallet(keyFile, dbFile, datFile, password string) error {
//根据流程,提供种子文件路径,wallet.db文件的路径,钱包数据库文件的路径。
//输入钱包密码。
//先备份核心钱包原来的wallet.db到临时文件夹。
//关闭钱包节点,复制wallet.db到钱包的data目录下。
//启动钱包,通过GetCoreWalletinfo检查钱包是否启动了。
//检查密码是否可以解析种子文件,是否可以解锁钱包。
//如果密码错误,关闭钱包节点,恢复原钱包的wallet.db。
//重新启动钱包。
//复制种子文件到data/btc/key/。
//复制钱包数据库文件到data/btc/db/。
var (
restoreSuccess = false
err error
key *hdkeystore.HDKey
//sleepTime = 30 * time.Second
)
fmt.Printf("Validating key file... \n")
//检查密码是否可以解析种子文件,是否可以解锁钱包。
key, err = wm.storage.GetKey("", keyFile, password)
if err != nil {
return errors.New("Passowrd is incorrect! ")
}
//钱包当前的dat文件
curretWDFile := filepath.Join(wm.config.walletDataPath, "wallet.db")
//创建临时备份文件wallet.db,备份
tmpWalletDat := fmt.Sprintf("restore-walllet-%d.dat", time.Now().Unix())
tmpWalletDat = filepath.Join(wm.config.walletDataPath, tmpWalletDat)
fmt.Printf("Backup current wallet.db file... \n")
//复制临时文件到备份文件夹
file.Copy(curretWDFile, tmpWalletDat)
//err = wm.BackupWalletData(tmpWalletDat)
//if err != nil {
// return err
//}
//调试使用
//file.Copy(curretWDFile, tmpWalletDat)
//fmt.Printf("Stop node server... \n")
//关闭钱包节点
//wm.stopNode()
//time.Sleep(sleepTime)
fmt.Printf("Restore wallet.db file... \n")
//删除当前钱包文件
file.Delete(curretWDFile)
//恢复备份dat到钱包数据目录
err = file.Copy(datFile, wm.config.walletDataPath)
if err != nil {
return err
}
//fmt.Printf("Start node server... \n")
//重新启动钱包
//wm.startNode()
//time.Sleep(sleepTime)
fmt.Printf("Validating wallet password... \n")
//检查wallet.db是否可以解锁钱包
err = wm.UnlockWallet(password, 1)
if err != nil {
restoreSuccess = false
err = errors.New("Password is incorrect!")
} else {
restoreSuccess = true
}
if restoreSuccess {
/* 恢复成功 */
fmt.Printf("Restore wallet key and datebase file... \n")
//复制种子文件到data/btc/key/
file.MkdirAll(wm.config.keyDir)
file.Copy(keyFile, filepath.Join(wm.config.keyDir, key.FileName()+".key"))
//复制钱包数据库文件到data/btc/db/
file.MkdirAll(wm.config.dbPath)
file.Copy(dbFile, filepath.Join(wm.config.dbPath, key.FileName()+".db"))
fmt.Printf("Backup wallet has been restored. \n")
fmt.Printf("Finally, you should restart the hcwallet to ensure. \n")
err = nil
} else {
/* 恢复失败还远原来的文件 */
fmt.Printf("Wallet unlock password is incorrect. \n")
//fmt.Printf("Stop node server... \n")
//关闭钱包节点
//wm.stopNode()
//time.Sleep(sleepTime)
fmt.Printf("Restore original wallet.db... \n")
//删除当前钱包文件
file.Delete(curretWDFile)
file.Copy(tmpWalletDat, curretWDFile)
//fmt.Printf("Start node server... \n")
//重新启动钱包
//wm.startNode()
//time.Sleep(sleepTime)
fmt.Printf("Original wallet has been restored. \n")
}
//删除临时备份的dat文件
file.Delete(tmpWalletDat)
return err
}
//GetBlockChainInfo 获取钱包区块链信息
func (wm *WalletManager) GetBlockChainInfo() (*BlockchainInfo, error) {
result, err := wm.walletClient.Call("getinfo", nil)
if err != nil {
return nil, err
}
blockchain := NewBlockchainInfo(result)
return blockchain, nil
}
//ListUnspent 获取未花记录
func (wm *WalletManager) ListUnspent(min uint64) ([]*Unspent, error) {
var (
utxos = make([]*Unspent, 0)
)
request := []interface{}{
min,
}
result, err := wm.walletClient.Call("listunspent", request)
if err != nil {
return nil, err
}
if !result.IsArray() {
return nil, nil
}
array := result.Array()
for _, a := range array {
utxos = append(utxos, NewUnspent(&a))
}
return utxos, nil
}
//RebuildWalletUnspent 批量插入未花记录到本地
func (wm *WalletManager) RebuildWalletUnspent(walletID string) error {
var (
wallet *openwallet.Wallet
)
wallets, err := wm.GetWallets()
if err != nil {
return err
}
//获取钱包余额
for _, w := range wallets {
if w.WalletID == walletID {
wallet = w
break
}
}
if wallet == nil {
return errors.New("The wallet that your given name is not exist!")
}
//查找核心钱包确认数大于1的
utxos, err := wm.ListUnspent(1)
if err != nil {
return err
}
db, err := wallet.OpenDB()
if err != nil {
return err
}
defer db.Close()
//清空历史的UTXO
db.Drop("Unspent")
//开始事务
tx, err := db.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
//批量插入到本地数据库
//设置utxo的钱包账户
for _, utxo := range utxos {
var addr openwallet.Address
err = db.One("Address", utxo.Address, &addr)
//找不到或观测的地址不计入utxo
if err != nil || addr.WatchOnly == true {
continue