-
Notifications
You must be signed in to change notification settings - Fork 563
/
manager_test.go
3116 lines (2822 loc) · 91.7 KB
/
manager_test.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) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package waddrmgr
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"reflect"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/snacl"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/davecgh/go-spew/spew"
"github.com/stretchr/testify/require"
)
// failingCryptoKey is an implementation of the EncryptorDecryptor interface
// with intentionally fails when attempting to encrypt or decrypt with it.
type failingCryptoKey struct {
cryptoKey
}
// Encrypt intenionally returns a failure when invoked to test error paths.
//
// This is part of the EncryptorDecryptor interface implementation.
func (c *failingCryptoKey) Encrypt(in []byte) ([]byte, error) {
return nil, errors.New("failed to encrypt")
}
// Decrypt intenionally returns a failure when invoked to test error paths.
//
// This is part of the EncryptorDecryptor interface implementation.
func (c *failingCryptoKey) Decrypt(in []byte) ([]byte, error) {
return nil, errors.New("failed to decrypt")
}
// failingSecretKeyGen is a SecretKeyGenerator that always returns
// snacl.ErrDecryptFailed.
func failingSecretKeyGen(passphrase *[]byte,
config *ScryptOptions) (*snacl.SecretKey, error) {
return nil, snacl.ErrDecryptFailed
}
// testContext is used to store context information about a running test which
// is passed into helper functions. The useSpends field indicates whether or
// not the spend data should be empty or figure it out based on the specific
// test blocks provided. This is needed because the first loop where the blocks
// are inserted, the tests are running against the latest block and therefore
// none of the outputs can be spent yet. However, on subsequent runs, all
// blocks have been inserted and therefore some of the transaction outputs are
// spent.
type testContext struct {
t *testing.T
caseName string
db walletdb.DB
rootManager *Manager
manager *ScopedKeyManager
internalAccount uint32
create bool
unlocked bool
watchingOnly bool
}
// addrType is the type of address being tested
type addrType byte
const (
addrPubKeyHash addrType = iota
addrScriptHash
)
// expectedAddr is used to house the expected return values from a managed
// address. Not all fields for used for all managed address types.
type expectedAddr struct {
address string
addressHash []byte
internal bool
compressed bool
imported bool
pubKey []byte
privKey []byte
privKeyWIF string
script []byte
derivationInfo DerivationPath
scriptNotSecret bool
}
// testNamePrefix is a helper to return a prefix to show for test errors based
// on the state of the test context.
func testNamePrefix(tc *testContext) string {
prefix := "Open "
if tc.create {
prefix = "Create "
}
return fmt.Sprintf("(%s) %s account #%d", tc.caseName, prefix, tc.internalAccount)
}
// testManagedPubKeyAddress ensures the data returned by all exported functions
// provided by the passed managed p ublic key address matches the corresponding
// fields in the provided expected address.
//
// When the test context indicates the manager is unlocked, the private data
// will also be tested, otherwise, the functions which deal with private data
// are checked to ensure they return the correct error.
func testManagedPubKeyAddress(tc *testContext, prefix string,
gotAddr ManagedPubKeyAddress, wantAddr *expectedAddr) bool {
// Ensure pubkey is the expected value for the managed address.
var gpubBytes []byte
if gotAddr.Compressed() {
gpubBytes = gotAddr.PubKey().SerializeCompressed()
} else {
gpubBytes = gotAddr.PubKey().SerializeUncompressed()
}
if !reflect.DeepEqual(gpubBytes, wantAddr.pubKey) {
tc.t.Errorf("%s PubKey: unexpected public key - got %x, want "+
"%x", prefix, gpubBytes, wantAddr.pubKey)
return false
}
// Ensure exported pubkey string is the expected value for the managed
// address.
gpubHex := gotAddr.ExportPubKey()
wantPubHex := hex.EncodeToString(wantAddr.pubKey)
if gpubHex != wantPubHex {
tc.t.Errorf("%s ExportPubKey: unexpected public key - got %s, "+
"want %s", prefix, gpubHex, wantPubHex)
return false
}
// Ensure that the derivation path has been properly re-set after the
// address was read from disk.
_, gotAddrPath, ok := gotAddr.DerivationInfo()
if !ok && !gotAddr.Imported() {
tc.t.Errorf("%s PubKey: non-imported address has empty "+
"derivation info", prefix)
return false
}
expectedDerivationInfo := wantAddr.derivationInfo
if gotAddrPath != expectedDerivationInfo {
tc.t.Errorf("%s PubKey: wrong derivation info: expected %v, "+
"got %v", prefix, spew.Sdump(gotAddrPath),
spew.Sdump(expectedDerivationInfo))
return false
}
// Ensure private key is the expected value for the managed address.
// Since this is only available when the manager is unlocked, also check
// for the expected error when the manager is locked.
gotPrivKey, err := gotAddr.PrivKey()
switch {
case tc.watchingOnly:
// Confirm expected watching-only error.
testName := fmt.Sprintf("%s PrivKey", prefix)
if !checkManagerError(tc.t, testName, err, ErrWatchingOnly) {
return false
}
case tc.unlocked:
if err != nil {
tc.t.Errorf("%s PrivKey: unexpected error - got %v",
prefix, err)
return false
}
gpriv := gotPrivKey.Serialize()
if !reflect.DeepEqual(gpriv, wantAddr.privKey) {
tc.t.Errorf("%s PrivKey: unexpected private key - "+
"got %x, want %x", prefix, gpriv, wantAddr.privKey)
return false
}
default:
// Confirm expected locked error.
testName := fmt.Sprintf("%s PrivKey", prefix)
if !checkManagerError(tc.t, testName, err, ErrLocked) {
return false
}
}
// Ensure exported private key in Wallet Import Format (WIF) is the
// expected value for the managed address. Since this is only available
// when the manager is unlocked, also check for the expected error when
// the manager is locked.
gotWIF, err := gotAddr.ExportPrivKey()
switch {
case tc.watchingOnly:
// Confirm expected watching-only error.
testName := fmt.Sprintf("%s ExportPrivKey", prefix)
if !checkManagerError(tc.t, testName, err, ErrWatchingOnly) {
return false
}
case tc.unlocked:
if err != nil {
tc.t.Errorf("%s ExportPrivKey: unexpected error - "+
"got %v", prefix, err)
return false
}
if gotWIF.String() != wantAddr.privKeyWIF {
tc.t.Errorf("%s ExportPrivKey: unexpected WIF - got "+
"%v, want %v", prefix, gotWIF.String(),
wantAddr.privKeyWIF)
return false
}
default:
// Confirm expected locked error.
testName := fmt.Sprintf("%s ExportPrivKey", prefix)
if !checkManagerError(tc.t, testName, err, ErrLocked) {
return false
}
}
// Imported addresses should return a nil derivation info.
if _, _, ok := gotAddr.DerivationInfo(); gotAddr.Imported() && ok {
tc.t.Errorf("%s Imported: expected nil derivation info", prefix)
return false
}
return true
}
// testManagedScriptAddress ensures the data returned by all exported functions
// provided by the passed managed script address matches the corresponding
// fields in the provided expected address.
//
// When the test context indicates the manager is unlocked, the private data
// will also be tested, otherwise, the functions which deal with private data
// are checked to ensure they return the correct error.
func testManagedScriptAddress(tc *testContext, prefix string,
gotAddr ManagedScriptAddress, wantAddr *expectedAddr) bool {
// Ensure script is the expected value for the managed address.
// Ensure script is the expected value for the managed address. Since
// this is only available when the manager is unlocked, also check for
// the expected error when the manager is locked.
gotScript, err := gotAddr.Script()
switch {
case tc.watchingOnly && !wantAddr.scriptNotSecret:
// Confirm expected watching-only error.
testName := fmt.Sprintf("%s Script", prefix)
if !checkManagerError(tc.t, testName, err, ErrWatchingOnly) {
return false
}
// Either the manger is unlocked or the script is not considered to
// be secret and is encrypted with the public key.
case tc.unlocked || wantAddr.scriptNotSecret:
if err != nil {
tc.t.Errorf("%s Script: unexpected error - got %v",
prefix, err)
return false
}
if !reflect.DeepEqual(gotScript, wantAddr.script) {
tc.t.Errorf("%s Script: unexpected script - got %x, "+
"want %x", prefix, gotScript, wantAddr.script)
return false
}
default:
// Confirm expected locked error.
testName := fmt.Sprintf("%s Script", prefix)
if !checkManagerError(tc.t, testName, err, ErrLocked) {
return false
}
}
return true
}
// testAddress ensures the data returned by all exported functions provided by
// the passed managed address matches the corresponding fields in the provided
// expected address. It also type asserts the managed address to determine its
// specific type and calls the corresponding testing functions accordingly.
//
// When the test context indicates the manager is unlocked, the private data
// will also be tested, otherwise, the functions which deal with private data
// are checked to ensure they return the correct error.
func testAddress(tc *testContext, prefix string, gotAddr ManagedAddress,
wantAddr *expectedAddr) bool {
if gotAddr.InternalAccount() != tc.internalAccount {
tc.t.Errorf("ManagedAddress.Account: unexpected account - got "+
"%d, want %d", gotAddr.InternalAccount(), tc.internalAccount)
return false
}
if gotAddr.Address().EncodeAddress() != wantAddr.address {
tc.t.Errorf("%s EncodeAddress: unexpected address - got %s, "+
"want %s", prefix, gotAddr.Address().EncodeAddress(),
wantAddr.address)
return false
}
if !reflect.DeepEqual(gotAddr.AddrHash(), wantAddr.addressHash) {
tc.t.Errorf("%s AddrHash: unexpected address hash - got %x, "+
"want %x", prefix, gotAddr.AddrHash(),
wantAddr.addressHash)
return false
}
if gotAddr.Internal() != wantAddr.internal {
tc.t.Errorf("%s Internal: unexpected internal flag - got %v, "+
"want %v", prefix, gotAddr.Internal(), wantAddr.internal)
return false
}
if gotAddr.Compressed() != wantAddr.compressed {
tc.t.Errorf("%s Compressed: unexpected compressed flag - got "+
"%v, want %v", prefix, gotAddr.Compressed(),
wantAddr.compressed)
return false
}
if gotAddr.Imported() != wantAddr.imported {
tc.t.Errorf("%s Imported: unexpected imported flag - got %v, "+
"want %v", prefix, gotAddr.Imported(), wantAddr.imported)
return false
}
switch addr := gotAddr.(type) {
case ManagedPubKeyAddress:
if !testManagedPubKeyAddress(tc, prefix, addr, wantAddr) {
return false
}
case ManagedScriptAddress:
if !testManagedScriptAddress(tc, prefix, addr, wantAddr) {
return false
}
}
return true
}
// testExternalAddresses tests several facets of external addresses such as
// generating multiple addresses via NextExternalAddresses, ensuring they can be
// retrieved by Address, and that they work properly when the manager is locked
// and unlocked.
func testExternalAddresses(tc *testContext) bool {
prefix := testNamePrefix(tc) + " testExternalAddresses"
var addrs []ManagedAddress
if tc.create {
prefix := prefix + " NextExternalAddresses"
var addrs []ManagedAddress
err := walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addrs, err = tc.manager.NextExternalAddresses(
ns, tc.internalAccount, 5,
)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", prefix, err)
return false
}
if len(addrs) != len(expectedExternalAddrs) {
tc.t.Errorf("%s: unexpected number of addresses - got "+
"%d, want %d", prefix, len(addrs),
len(expectedExternalAddrs))
return false
}
}
// Setup a closure to test the results since the same tests need to be
// repeated with the manager locked and unlocked.
testResults := func() bool {
// Ensure the returned addresses are the expected ones. When
// not in the create phase, there will be no addresses in the
// addrs slice, so this really only runs during the first phase
// of the tests.
for i := 0; i < len(addrs); i++ {
prefix := fmt.Sprintf("%s ExternalAddress #%d", prefix, i)
if !testAddress(tc, prefix, addrs[i], &expectedExternalAddrs[i]) {
return false
}
}
// Ensure the last external address is the expected one.
leaPrefix := prefix + " LastExternalAddress"
var lastAddr ManagedAddress
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
lastAddr, err = tc.manager.LastExternalAddress(
ns, tc.internalAccount,
)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", leaPrefix, err)
return false
}
if !testAddress(tc, leaPrefix, lastAddr, &expectedExternalAddrs[len(expectedExternalAddrs)-1]) {
return false
}
// Now, use the Address API to retrieve each of the expected new
// addresses and ensure they're accurate.
chainParams := tc.manager.ChainParams()
for i := 0; i < len(expectedExternalAddrs); i++ {
pkHash := expectedExternalAddrs[i].addressHash
utilAddr, err := btcutil.NewAddressPubKeyHash(
pkHash, chainParams,
)
if err != nil {
tc.t.Errorf("%s NewAddressPubKeyHash #%d: "+
"unexpected error: %v", prefix, i, err)
return false
}
prefix := fmt.Sprintf("%s Address #%d", prefix, i)
var addr ManagedAddress
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
addr, err = tc.manager.Address(ns, utilAddr)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", prefix,
err)
return false
}
if !testAddress(tc, prefix, addr, &expectedExternalAddrs[i]) {
return false
}
}
return true
}
// Since the manager is locked at this point, the public address
// information is tested and the private functions are checked to ensure
// they return the expected error.
if !testResults() {
return false
}
// Everything after this point involves retesting with an unlocked
// address manager which is not possible for watching-only mode, so
// just exit now in that case.
if tc.watchingOnly {
return true
}
// Unlock the manager and retest all of the addresses to ensure the
// private information is valid as well.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
return false
}
tc.unlocked = true
if !testResults() {
return false
}
// Relock the manager for future tests.
if err := tc.rootManager.Lock(); err != nil {
tc.t.Errorf("Lock: unexpected error: %v", err)
return false
}
tc.unlocked = false
return true
}
// testInternalAddresses tests several facets of internal addresses such as
// generating multiple addresses via NextInternalAddresses, ensuring they can be
// retrieved by Address, and that they work properly when the manager is locked
// and unlocked.
func testInternalAddresses(tc *testContext) bool {
// When the address manager is not in watching-only mode, unlocked it
// first to ensure that address generation works correctly when the
// address manager is unlocked and then locked later. These tests
// reverse the order done in the external tests which starts with a
// locked manager and unlock it afterwards.
if !tc.watchingOnly {
// Unlock the manager and retest all of the addresses to ensure the
// private information is valid as well.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
return false
}
tc.unlocked = true
}
prefix := testNamePrefix(tc) + " testInternalAddresses"
var addrs []ManagedAddress
if tc.create {
prefix := prefix + " NextInternalAddress"
err := walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addrs, err = tc.manager.NextInternalAddresses(
ns, tc.internalAccount, 5,
)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", prefix, err)
return false
}
if len(addrs) != len(expectedInternalAddrs) {
tc.t.Errorf("%s: unexpected number of addresses - got "+
"%d, want %d", prefix, len(addrs),
len(expectedInternalAddrs))
return false
}
}
// Setup a closure to test the results since the same tests need to be
// repeated with the manager locked and unlocked.
testResults := func() bool {
// Ensure the returned addresses are the expected ones. When
// not in the create phase, there will be no addresses in the
// addrs slice, so this really only runs during the first phase
// of the tests.
for i := 0; i < len(addrs); i++ {
prefix := fmt.Sprintf("%s InternalAddress #%d", prefix, i)
if !testAddress(tc, prefix, addrs[i], &expectedInternalAddrs[i]) {
return false
}
}
// Ensure the last internal address is the expected one.
liaPrefix := prefix + " LastInternalAddress"
var lastAddr ManagedAddress
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
lastAddr, err = tc.manager.LastInternalAddress(
ns, tc.internalAccount,
)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", liaPrefix, err)
return false
}
if !testAddress(tc, liaPrefix, lastAddr, &expectedInternalAddrs[len(expectedInternalAddrs)-1]) {
return false
}
// Now, use the Address API to retrieve each of the expected new
// addresses and ensure they're accurate.
chainParams := tc.manager.ChainParams()
for i := 0; i < len(expectedInternalAddrs); i++ {
pkHash := expectedInternalAddrs[i].addressHash
utilAddr, err := btcutil.NewAddressPubKeyHash(
pkHash, chainParams,
)
if err != nil {
tc.t.Errorf("%s NewAddressPubKeyHash #%d: "+
"unexpected error: %v", prefix, i, err)
return false
}
prefix := fmt.Sprintf("%s Address #%d", prefix, i)
var addr ManagedAddress
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
addr, err = tc.manager.Address(ns, utilAddr)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", prefix,
err)
return false
}
if !testAddress(tc, prefix, addr, &expectedInternalAddrs[i]) {
return false
}
}
return true
}
// The address manager could either be locked or unlocked here depending
// on whether or not it's a watching-only manager. When it's unlocked,
// this will test both the public and private address data are accurate.
// When it's locked, it must be watching-only, so only the public
// address information is tested and the private functions are checked
// to ensure they return the expected ErrWatchingOnly error.
if !testResults() {
return false
}
// Everything after this point involves locking the address manager and
// retesting the addresses with a locked manager. However, for
// watching-only mode, this has already happened, so just exit now in
// that case.
if tc.watchingOnly {
return true
}
// Lock the manager and retest all of the addresses to ensure the
// public information remains valid and the private functions return
// the expected error.
if err := tc.rootManager.Lock(); err != nil {
tc.t.Errorf("Lock: unexpected error: %v", err)
return false
}
tc.unlocked = false
return testResults()
}
// testLocking tests the basic locking semantics of the address manager work
// as expected. Other tests ensure addresses behave as expected under locked
// and unlocked conditions.
func testLocking(tc *testContext) bool {
if tc.unlocked {
tc.t.Error("testLocking called with an unlocked manager")
return false
}
if !tc.rootManager.IsLocked() {
tc.t.Error("IsLocked: returned false on locked manager")
return false
}
// Locking an already lock manager should return an error. The error
// should be ErrLocked or ErrWatchingOnly depending on the type of the
// address manager.
err := tc.rootManager.Lock()
wantErrCode := ErrLocked
if tc.watchingOnly {
wantErrCode = ErrWatchingOnly
}
if !checkManagerError(tc.t, "Lock", err, wantErrCode) {
return false
}
// Ensure unlocking with the correct passphrase doesn't return any
// unexpected errors and the manager properly reports it is unlocked.
// Since watching-only address managers can't be unlocked, also ensure
// the correct error for that case.
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if tc.watchingOnly {
if !checkManagerError(tc.t, "Unlock", err, ErrWatchingOnly) {
return false
}
} else if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
return false
}
if !tc.watchingOnly && tc.rootManager.IsLocked() {
tc.t.Error("IsLocked: returned true on unlocked manager")
return false
}
// Unlocking the manager again is allowed. Since watching-only address
// managers can't be unlocked, also ensure the correct error for that
// case.
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if tc.watchingOnly {
if !checkManagerError(tc.t, "Unlock2", err, ErrWatchingOnly) {
return false
}
} else if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
return false
}
if !tc.watchingOnly && tc.rootManager.IsLocked() {
tc.t.Error("IsLocked: returned true on unlocked manager")
return false
}
// Unlocking the manager with an invalid passphrase must result in an
// error and a locked manager.
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, []byte("invalidpassphrase"))
})
wantErrCode = ErrWrongPassphrase
if tc.watchingOnly {
wantErrCode = ErrWatchingOnly
}
if !checkManagerError(tc.t, "Unlock", err, wantErrCode) {
return false
}
if !tc.rootManager.IsLocked() {
tc.t.Error("IsLocked: manager is unlocked after failed unlock " +
"attempt")
return false
}
return true
}
// testImportPrivateKey tests that importing private keys works properly. It
// ensures they can be retrieved by Address after they have been imported and
// the addresses give the expected values when the manager is locked and
// unlocked.
//
// This function expects the manager is already locked when called and returns
// with the manager locked.
func testImportPrivateKey(tc *testContext) bool {
tests := []struct {
name string
in string
blockstamp BlockStamp
expected expectedAddr
}{
{
name: "wif for uncompressed pubkey address",
in: "5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ",
expected: expectedAddr{
address: "1GAehh7TsJAHuUAeKZcXf5CnwuGuGgyX2S",
addressHash: hexToBytes("a65d1a239d4ec666643d350c7bb8fc44d2881128"),
internal: false,
imported: true,
compressed: false,
pubKey: hexToBytes("04d0de0aaeaefad02b8bdc8a01a1b8b11c696bd3" +
"d66a2c5f10780d95b7df42645cd85228a6fb29940e858e7e558" +
"42ae2bd115d1ed7cc0e82d934e929c97648cb0a"),
privKey: hexToBytes("0c28fca386c7a227600b2fe50b7cae11ec86d3bf1fbe471be89827e19d72aa1d"),
// privKeyWIF is set to the in field during tests
},
},
{
name: "wif for compressed pubkey address",
in: "KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617",
expected: expectedAddr{
address: "1LoVGDgRs9hTfTNJNuXKSpywcbdvwRXpmK",
addressHash: hexToBytes("d9351dcbad5b8f3b8bfa2f2cdc85c28118ca9326"),
internal: false,
imported: true,
compressed: true,
pubKey: hexToBytes("02d0de0aaeaefad02b8bdc8a01a1b8b11c696bd3d66a2c5f10780d95b7df42645c"),
privKey: hexToBytes("0c28fca386c7a227600b2fe50b7cae11ec86d3bf1fbe471be89827e19d72aa1d"),
// privKeyWIF is set to the in field during tests
},
},
}
// The manager must be unlocked to import a private key, however a
// watching-only manager can't be unlocked.
if !tc.watchingOnly {
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
return false
}
tc.unlocked = true
}
// Only import the private keys when in the create phase of testing.
tc.internalAccount = ImportedAddrAccount
prefix := testNamePrefix(tc) + " testImportPrivateKey"
if tc.create {
for i, test := range tests {
test := test
test.expected.privKeyWIF = test.in
wif, err := btcutil.DecodeWIF(test.in)
if err != nil {
tc.t.Errorf("%s DecodeWIF #%d (%s): unexpected "+
"error: %v", prefix, i, test.name, err)
continue
}
var addr ManagedPubKeyAddress
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
addr, err = tc.manager.ImportPrivateKey(
ns, wif, &test.blockstamp,
)
return err
})
if err != nil {
tc.t.Errorf("%s ImportPrivateKey #%d (%s): "+
"unexpected error: %v", prefix, i,
test.name, err)
continue
}
if !testAddress(tc, prefix+" ImportPrivateKey", addr,
&test.expected) {
continue
}
}
}
// Setup a closure to test the results since the same tests need to be
// repeated with the manager unlocked and locked.
chainParams := tc.manager.ChainParams()
testResults := func() bool {
failed := false
for i, test := range tests {
test.expected.privKeyWIF = test.in
// Use the Address API to retrieve each of the expected
// new addresses and ensure they're accurate.
utilAddr, err := btcutil.NewAddressPubKeyHash(
test.expected.addressHash, chainParams)
if err != nil {
tc.t.Errorf("%s NewAddressPubKeyHash #%d (%s): "+
"unexpected error: %v", prefix, i,
test.name, err)
failed = true
continue
}
taPrefix := fmt.Sprintf("%s Address #%d (%s)", prefix,
i, test.name)
var ma ManagedAddress
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
ma, err = tc.manager.Address(ns, utilAddr)
return err
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", taPrefix,
err)
failed = true
continue
}
if !testAddress(tc, taPrefix, ma, &test.expected) {
failed = true
continue
}
}
return !failed
}
// The address manager could either be locked or unlocked here depending
// on whether or not it's a watching-only manager. When it's unlocked,
// this will test both the public and private address data are accurate.
// When it's locked, it must be watching-only, so only the public
// address information is tested and the private functions are checked
// to ensure they return the expected ErrWatchingOnly error.
if !testResults() {
return false
}
// Everything after this point involves locking the address manager and
// retesting the addresses with a locked manager. However, for
// watching-only mode, this has already happened, so just exit now in
// that case.
if tc.watchingOnly {
return true
}
// Lock the manager and retest all of the addresses to ensure the
// private information returns the expected error.
if err := tc.rootManager.Lock(); err != nil {
tc.t.Errorf("Lock: unexpected error: %v", err)
return false
}
tc.unlocked = false
return testResults()
}
// testImportScript tests that importing scripts works properly. It ensures
// they can be retrieved by Address after they have been imported and the
// addresses give the expected values when the manager is locked and unlocked.
//
// This function expects the manager is already locked when called and returns
// with the manager locked.
func testImportScript(tc *testContext) bool {
tests := []struct {
name string
in []byte
isWitness bool
isTaproot bool
witnessVersion byte
isSecretScript bool
blockstamp BlockStamp
expected expectedAddr
}{
{
name: "p2sh uncompressed pubkey",
in: hexToBytes("41048b65a0e6bb200e6dac05e74281b1ab9a41e8" +
"0006d6b12d8521e09981da97dd96ac72d24d1a7d" +
"ed9493a9fc20fdb4a714808f0b680f1f1d935277" +
"48b5e3f629ffac"),
expected: expectedAddr{
address: "3MbyWAu9UaoBewR3cArF1nwf4aQgVwzrA5",
addressHash: hexToBytes("da6e6a632d96dc5530d7b3c9f3017725d023093e"),
internal: false,
imported: true,
compressed: false,
// script is set to the in field during tests.
},
},
{
name: "p2sh multisig",
in: hexToBytes("524104cb9c3c222c5f7a7d3b9bd152f363a0b6d5" +
"4c9eb312c4d4f9af1e8551b6c421a6a4ab0e2910" +
"5f24de20ff463c1c91fcf3bf662cdde4783d4799" +
"f787cb7c08869b4104ccc588420deeebea22a7e9" +
"00cc8b68620d2212c374604e3487ca08f1ff3ae1" +
"2bdc639514d0ec8612a2d3c519f084d9a00cbbe3" +
"b53d071e9b09e71e610b036aa24104ab47ad1939" +
"edcb3db65f7fedea62bbf781c5410d3f22a7a3a5" +
"6ffefb2238af8627363bdf2ed97c1f89784a1aec" +
"db43384f11d2acc64443c7fc299cef0400421a53ae"),
expected: expectedAddr{
address: "34CRZpt8j81rgh9QhzuBepqPi4cBQSjhjr",
addressHash: hexToBytes("1b800cec1fe92222f36a502c139bed47c5959715"),
internal: false,
imported: true,
compressed: false,
// script is set to the in field during tests.
},
},
{
name: "p2wsh multisig",
isWitness: true,
witnessVersion: 0,
isSecretScript: true,
in: hexToBytes("52210305a662958b547fe25a71cd28fc7ef1c2" +
"ad4a79b12f34fc40137824b88e61199d21038552c09d9" +
"a709c8cbba6e472307d3f8383f46181895a76e01e258f" +
"09033b4a7821029dd72aba87324af59508380f9564d34" +
"b0f7b20d864d186e7d0428c9ea241c61653ae"),
expected: expectedAddr{
address: "bc1q0jljr70qchwtk3ag0w3gyg9mjhg4c95xr7h8ezhvdrfgppcpz4esfdl9an",
addressHash: hexToBytes("7cbf21f9e0c5dcbb47a87ba28220bb95d15c16861fae7c8aec68d28087011573"),
internal: false,
imported: true,
compressed: true,
// script is set to the in field during tests.
},
},
{
name: "p2wsh multisig as watch-only address",
isWitness: true,
witnessVersion: 0,
isSecretScript: false,
in: hexToBytes("52210305a662958b547fe25a71cd28fc7ef1c2" +
"ad4a79b12f34fc40137824b88e61199d21038552c09d9" +
"a709c8cbba6e472307d3f8383f46181895a76e01e258f" +
"09033b4a7821024794b65a83e9ba415096e59abc4d4d1" +
"1710968e52bf5eec56fe0e5bdb3d3ec0e53ae"),
expected: expectedAddr{
address: "bc1q3a79gkjulrsgp864yskp4d5zmwm49xsdrfwvdypkqtlpj7spd3fqrl5nes",
addressHash: hexToBytes("8f7c545a5cf8e0809f55242c1ab682dbb7529a0d1a5cc6903602fe197a016c52"),
internal: false,
imported: true,
compressed: true,
scriptNotSecret: true,
// script is set to the in field during tests.
},
},
{
name: "p2tr tapscript with all tap leaves",
isTaproot: true,
witnessVersion: 1,
isSecretScript: true,
// The encoded *Tapscript struct for a script with all
// tap script leaves known.
in: hexToBytes(
"0101000221c00ef94ee79c07cbd1988fffd6e6aea1e2" +
"5c3b033a2fd64fe14a9b955e5355f0c60346" +
"1d0101c0021876a914f6c97547d73156abb3" +
"00ae059905c4acaadd09dd88270101c00222" +
"200ef94ee79c07cbd1988fffd6e6aea1e25c" +
"3b033a2fd64fe14a9b955e5355f0c6ac",
),
expected: expectedAddr{
address: "bc1pu92qt24cl4spyp4rsj9sa3y4ma6a3fszgewcmway9f6f80vgnduq5lnd0u",
addressHash: hexToBytes("e15405aab8fd601206a3848b0ec495df75d8a602465d8dbba42a7493bd889b78"),
internal: false,
imported: true,
compressed: true,
// script is set to the in field during tests.
},
},