forked from btcsuite/btcwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keystore.go
3245 lines (2780 loc) · 81.5 KB
/
keystore.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) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package keystore
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha512"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math/big"
"os"
"path/filepath"
"sync"
"time"
// consider vendoring this deprecated ripemd160 package
"golang.org/x/crypto/ripemd160" // nolint:staticcheck
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
secp "github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/stroomnetwork/btcwallet/internal/legacy/rename"
)
const (
Filename = "wallet.bin"
// Length in bytes of KDF output.
kdfOutputBytes = 32
)
const (
defaultKdfComputeTime = 0.25
defaultKdfMaxMem = 32 * 1024 * 1024
)
// Possible errors when dealing with key stores.
var (
ErrAddressNotFound = errors.New("address not found")
ErrAlreadyEncrypted = errors.New("private key is already encrypted")
ErrChecksumMismatch = errors.New("checksum mismatch")
ErrDuplicate = errors.New("duplicate key or address")
ErrMalformedEntry = errors.New("malformed entry")
ErrWatchingOnly = errors.New("keystore is watching-only")
ErrLocked = errors.New("keystore is locked")
ErrWrongPassphrase = errors.New("wrong passphrase")
)
var fileID = [8]byte{0xba, 'W', 'A', 'L', 'L', 'E', 'T', 0x00}
type entryHeader byte
const (
addrCommentHeader entryHeader = 1 << iota // nolint:varcheck,deadcode
txCommentHeader // nolint:varcheck,deadcode
deletedHeader // nolint:varcheck,deadcode
scriptHeader
addrHeader entryHeader = 0
)
// We want to use binaryRead and binaryWrite instead of binary.Read
// and binary.Write because those from the binary package do not return
// the number of bytes actually written or read. We need to return
// this value to correctly support the io.ReaderFrom and io.WriterTo
// interfaces.
func binaryRead(r io.Reader, order binary.ByteOrder, data interface{}) (n int64, err error) {
var read int
buf := make([]byte, binary.Size(data))
if read, err = io.ReadFull(r, buf); err != nil {
return int64(read), err
}
return int64(read), binary.Read(bytes.NewBuffer(buf), order, data)
}
// See comment for binaryRead().
func binaryWrite(w io.Writer, order binary.ByteOrder, data interface{}) (n int64, err error) {
buf := bytes.Buffer{}
if err = binary.Write(&buf, order, data); err != nil {
return 0, err
}
written, err := w.Write(buf.Bytes())
return int64(written), err
}
// pubkeyFromPrivkey creates an encoded pubkey based on a
// 32-byte privkey. The returned pubkey is 33 bytes if compressed,
// or 65 bytes if uncompressed.
func pubkeyFromPrivkey(privkey []byte, compress bool) (pubkey []byte) {
_, pk := btcec.PrivKeyFromBytes(privkey)
if compress {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
}
func keyOneIter(passphrase, salt []byte, memReqts uint64) []byte {
saltedpass := append(passphrase, salt...)
lutbl := make([]byte, memReqts)
// Seed for lookup table
seed := sha512.Sum512(saltedpass)
copy(lutbl[:sha512.Size], seed[:])
for nByte := 0; nByte < (int(memReqts) - sha512.Size); nByte += sha512.Size {
hash := sha512.Sum512(lutbl[nByte : nByte+sha512.Size])
copy(lutbl[nByte+sha512.Size:nByte+2*sha512.Size], hash[:])
}
x := lutbl[cap(lutbl)-sha512.Size:]
seqCt := uint32(memReqts / sha512.Size)
nLookups := seqCt / 2
for i := uint32(0); i < nLookups; i++ {
// Armory ignores endianness here. We assume LE.
newIdx := binary.LittleEndian.Uint32(x[cap(x)-4:]) % seqCt
// Index of hash result at newIdx
vIdx := newIdx * sha512.Size
v := lutbl[vIdx : vIdx+sha512.Size]
// XOR hash x with hash v
for j := 0; j < sha512.Size; j++ {
x[j] ^= v[j]
}
// Save new hash to x
hash := sha512.Sum512(x)
copy(x, hash[:])
}
return x[:kdfOutputBytes]
}
// kdf implements the key derivation function used by Armory
// based on the ROMix algorithm described in Colin Percival's paper
// "Stronger Key Derivation via Sequential Memory-Hard Functions"
// (http://www.tarsnap.com/scrypt/scrypt.pdf).
func kdf(passphrase []byte, params *kdfParameters) []byte {
masterKey := passphrase
for i := uint32(0); i < params.nIter; i++ {
masterKey = keyOneIter(masterKey, params.salt[:], params.mem)
}
return masterKey
}
func pad(size int, b []byte) []byte {
// Prevent a possible panic if the input exceeds the expected size.
if len(b) > size {
size = len(b)
}
p := make([]byte, size)
copy(p[size-len(b):], b)
return p
}
// chainedPrivKey deterministically generates a new private key using a
// previous address and chaincode. privkey and chaincode must be 32
// bytes long, and pubkey may either be 33 or 65 bytes.
func chainedPrivKey(privkey, pubkey, chaincode []byte) ([]byte, error) {
if len(privkey) != 32 {
return nil, fmt.Errorf("invalid privkey length %d (must be 32)",
len(privkey))
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
switch n := len(pubkey); n {
case secp.PubKeyBytesLenUncompressed, secp.PubKeyBytesLenCompressed:
// Correct length
default:
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
xorbytes := make([]byte, 32)
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
chainXor := new(big.Int).SetBytes(xorbytes)
privint := new(big.Int).SetBytes(privkey)
t := new(big.Int).Mul(chainXor, privint)
b := t.Mod(t, btcec.S256().N).Bytes()
return pad(32, b), nil
}
// chainedPubKey deterministically generates a new public key using a
// previous public key and chaincode. pubkey must be 33 or 65 bytes, and
// chaincode must be 32 bytes long.
func chainedPubKey(pubkey, chaincode []byte) ([]byte, error) {
var compressed bool
switch n := len(pubkey); n {
case secp.PubKeyBytesLenUncompressed:
compressed = false
case secp.PubKeyBytesLenCompressed:
compressed = true
default:
// Incorrect serialized pubkey length
return nil, fmt.Errorf("invalid pubkey length %d", n)
}
if len(chaincode) != 32 {
return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
len(chaincode))
}
var xorbytes [32]byte
chainMod := chainhash.DoubleHashB(pubkey)
for i := range xorbytes {
xorbytes[i] = chainMod[i] ^ chaincode[i]
}
oldPk, err := btcec.ParsePubKey(pubkey)
if err != nil {
return nil, err
}
var xorBytesScalar btcec.ModNScalar
overflow := xorBytesScalar.SetBytes(&xorbytes)
if overflow != 0 {
return nil, fmt.Errorf("unable to create pubkey due to overflow")
}
var (
newPointJacobian btcec.JacobianPoint
oldPkJacobian btcec.JacobianPoint
)
oldPk.AsJacobian(&oldPkJacobian)
btcec.ScalarMultNonConst(
&xorBytesScalar, &oldPkJacobian, &newPointJacobian,
)
newPointJacobian.ToAffine()
newPk := btcec.NewPublicKey(
&newPointJacobian.X, &newPointJacobian.Y,
)
if compressed {
return newPk.SerializeCompressed(), nil
}
return newPk.SerializeUncompressed(), nil
}
type version struct {
major byte
minor byte
bugfix byte
autoincrement byte
}
// Enforce that version satisifies the io.ReaderFrom and
// io.WriterTo interfaces.
var _ io.ReaderFrom = &version{}
var _ io.WriterTo = &version{}
// readerFromVersion is an io.ReaderFrom and io.WriterTo that
// can specify any particular key store file format for reading
// depending on the key store file version.
type readerFromVersion interface {
readFromVersion(version, io.Reader) (int64, error)
io.WriterTo
}
func (v version) String() string {
str := fmt.Sprintf("%d.%d", v.major, v.minor)
if v.bugfix != 0x00 || v.autoincrement != 0x00 {
str += fmt.Sprintf(".%d", v.bugfix)
}
if v.autoincrement != 0x00 {
str += fmt.Sprintf(".%d", v.autoincrement)
}
return str
}
func (v version) Uint32() uint32 {
return uint32(v.major)<<6 | uint32(v.minor)<<4 | uint32(v.bugfix)<<2 | uint32(v.autoincrement)
}
func (v *version) ReadFrom(r io.Reader) (int64, error) {
// Read 4 bytes for the version.
var versBytes [4]byte
n, err := io.ReadFull(r, versBytes[:])
if err != nil {
return int64(n), err
}
v.major = versBytes[0]
v.minor = versBytes[1]
v.bugfix = versBytes[2]
v.autoincrement = versBytes[3]
return int64(n), nil
}
func (v *version) WriteTo(w io.Writer) (int64, error) {
// Write 4 bytes for the version.
versBytes := []byte{
v.major,
v.minor,
v.bugfix,
v.autoincrement,
}
n, err := w.Write(versBytes)
return int64(n), err
}
// LT returns whether v is an earlier version than v2.
func (v version) LT(v2 version) bool {
switch {
case v.major < v2.major:
return true
case v.minor < v2.minor:
return true
case v.bugfix < v2.bugfix:
return true
case v.autoincrement < v2.autoincrement:
return true
default:
return false
}
}
// EQ returns whether v2 is an equal version to v.
func (v version) EQ(v2 version) bool {
switch {
case v.major != v2.major:
return false
case v.minor != v2.minor:
return false
case v.bugfix != v2.bugfix:
return false
case v.autoincrement != v2.autoincrement:
return false
default:
return true
}
}
// GT returns whether v is a later version than v2.
func (v version) GT(v2 version) bool {
switch {
case v.major > v2.major:
return true
case v.minor > v2.minor:
return true
case v.bugfix > v2.bugfix:
return true
case v.autoincrement > v2.autoincrement:
return true
default:
return false
}
}
// Various versions.
var (
// VersArmory is the latest version used by Armory.
VersArmory = version{1, 35, 0, 0}
// Vers20LastBlocks is the version where key store files now hold
// the 20 most recently seen block hashes.
Vers20LastBlocks = version{1, 36, 0, 0}
// VersUnsetNeedsPrivkeyFlag is the bugfix version where the
// createPrivKeyNextUnlock address flag is correctly unset
// after creating and encrypting its private key after unlock.
// Otherwise, re-creating private keys will occur too early
// in the address chain and fail due to encrypting an already
// encrypted address. Key store versions at or before this
// version include a special case to allow the duplicate
// encrypt.
VersUnsetNeedsPrivkeyFlag = version{1, 36, 1, 0}
// VersCurrent is the current key store file version.
VersCurrent = VersUnsetNeedsPrivkeyFlag
)
type varEntries struct {
store *Store
entries []io.WriterTo
}
func (v *varEntries) WriteTo(w io.Writer) (n int64, err error) {
ss := v.entries
var written int64
for _, s := range ss {
var err error
if written, err = s.WriteTo(w); err != nil {
return n + written, err
}
n += written
}
return n, nil
}
func (v *varEntries) ReadFrom(r io.Reader) (n int64, err error) {
var read int64
// Remove any previous entries.
v.entries = nil
wts := v.entries
// Keep reading entries until an EOF is reached.
for {
var header entryHeader
if read, err = binaryRead(r, binary.LittleEndian, &header); err != nil {
// EOF here is not an error.
if err == io.EOF {
return n + read, nil
}
return n + read, err
}
n += read
var wt io.WriterTo
switch header {
case addrHeader:
var entry addrEntry
entry.addr.store = v.store
if read, err = entry.ReadFrom(r); err != nil {
return n + read, err
}
n += read
wt = &entry
case scriptHeader:
var entry scriptEntry
entry.script.store = v.store
if read, err = entry.ReadFrom(r); err != nil {
return n + read, err
}
n += read
wt = &entry
default:
return n, fmt.Errorf("unknown entry header: %d", uint8(header))
}
if wt != nil {
wts = append(wts, wt)
v.entries = wts
}
}
}
// Key stores use a custom network parameters type so it can be an io.ReaderFrom.
// Due to the way and order that key stores are currently serialized and how
// address reading requires the key store's network parameters, setting and
// erroring on unknown key store networks must happen on the read itself and not
// after the fact. This is admitidly a hack, but with a bip32 keystore on the
// horizon I'm not too motivated to clean this up.
type netParams chaincfg.Params
func (net *netParams) ReadFrom(r io.Reader) (int64, error) {
var buf [4]byte
uint32Bytes := buf[:4]
n, err := io.ReadFull(r, uint32Bytes)
n64 := int64(n)
if err != nil {
return n64, err
}
switch wire.BitcoinNet(binary.LittleEndian.Uint32(uint32Bytes)) {
case wire.MainNet:
*net = (netParams)(chaincfg.MainNetParams)
case wire.TestNet3:
*net = (netParams)(chaincfg.TestNet3Params)
case wire.SimNet:
*net = (netParams)(chaincfg.SimNetParams)
// The legacy key store won't be compatible with custom signets, only
// the main public one.
case chaincfg.SigNetParams.Net:
*net = (netParams)(chaincfg.SigNetParams)
default:
return n64, errors.New("unknown network")
}
return n64, nil
}
func (net *netParams) WriteTo(w io.Writer) (int64, error) {
var buf [4]byte
uint32Bytes := buf[:4]
binary.LittleEndian.PutUint32(uint32Bytes, uint32(net.Net))
n, err := w.Write(uint32Bytes)
n64 := int64(n)
return n64, err
}
// Stringified byte slices for use as map lookup keys.
type addressKey string
func getAddressKey(addr btcutil.Address) addressKey {
return addressKey(addr.ScriptAddress())
}
// Store represents an key store in memory. It implements the
// io.ReaderFrom and io.WriterTo interfaces to read from and
// write to any type of byte streams, including files.
type Store struct {
// TODO: Use atomic operations for dirty so the reader lock
// doesn't need to be grabbed.
dirty bool
path string
dir string
file string
mtx sync.RWMutex
vers version
net *netParams
flags walletFlags
createDate int64
name [32]byte
desc [256]byte
highestUsed int64
kdfParams kdfParameters
keyGenerator btcAddress
// These are non-standard and fit in the extra 1024 bytes between the
// root address and the appended entries.
recent recentBlocks
addrMap map[addressKey]walletAddress
// The rest of the fields in this struct are not serialized.
passphrase []byte
secret []byte
chainIdxMap map[int64]btcutil.Address
importedAddrs []walletAddress
lastChainIdx int64
missingKeysStart int64
}
// New creates and initializes a new Store. name's and desc's byte length
// must not exceed 32 and 256 bytes, respectively. All address private keys
// are encrypted with passphrase. The key store is returned locked.
func New(dir string, desc string, passphrase []byte, net *chaincfg.Params,
createdAt *BlockStamp) (*Store, error) {
// Check sizes of inputs.
if len(desc) > 256 {
return nil, errors.New("desc exceeds 256 byte maximum size")
}
// Randomly-generate rootkey and chaincode.
rootkey := make([]byte, 32)
if _, err := rand.Read(rootkey); err != nil {
return nil, err
}
chaincode := make([]byte, 32)
if _, err := rand.Read(chaincode); err != nil {
return nil, err
}
// Compute AES key and encrypt root address.
kdfp, err := computeKdfParameters(defaultKdfComputeTime, defaultKdfMaxMem)
if err != nil {
return nil, err
}
aeskey := kdf(passphrase, kdfp)
// Create and fill key store.
s := &Store{
path: filepath.Join(dir, Filename),
dir: dir,
file: Filename,
vers: VersCurrent,
net: (*netParams)(net),
flags: walletFlags{
useEncryption: true,
watchingOnly: false,
},
createDate: time.Now().Unix(),
highestUsed: rootKeyChainIdx,
kdfParams: *kdfp,
recent: recentBlocks{
lastHeight: createdAt.Height,
hashes: []*chainhash.Hash{
createdAt.Hash,
},
},
addrMap: make(map[addressKey]walletAddress),
chainIdxMap: make(map[int64]btcutil.Address),
lastChainIdx: rootKeyChainIdx,
missingKeysStart: rootKeyChainIdx,
secret: aeskey,
}
copy(s.desc[:], []byte(desc))
// Create new root address from key and chaincode.
root, err := newRootBtcAddress(s, rootkey, nil, chaincode,
createdAt)
if err != nil {
return nil, err
}
// Verify root address keypairs.
if err := root.verifyKeypairs(); err != nil {
return nil, err
}
if err := root.encrypt(aeskey); err != nil {
return nil, err
}
s.keyGenerator = *root
// Add root address to maps.
rootAddr := s.keyGenerator.Address()
s.addrMap[getAddressKey(rootAddr)] = &s.keyGenerator
s.chainIdxMap[rootKeyChainIdx] = rootAddr
// key store must be returned locked.
if err := s.Lock(); err != nil {
return nil, err
}
return s, nil
}
// ReadFrom reads data from a io.Reader and saves it to a key store,
// returning the number of bytes read and any errors encountered.
func (s *Store) ReadFrom(r io.Reader) (n int64, err error) {
s.mtx.Lock()
defer s.mtx.Unlock()
var read int64
s.net = &netParams{}
s.addrMap = make(map[addressKey]walletAddress)
s.chainIdxMap = make(map[int64]btcutil.Address)
var id [8]byte
appendedEntries := varEntries{store: s}
s.keyGenerator.store = s
// Iterate through each entry needing to be read. If data
// implements io.ReaderFrom, use its ReadFrom func. Otherwise,
// data is a pointer to a fixed sized value.
datas := []interface{}{
&id,
&s.vers,
s.net,
&s.flags,
make([]byte, 6), // Bytes for Armory unique ID
&s.createDate,
&s.name,
&s.desc,
&s.highestUsed,
&s.kdfParams,
make([]byte, 256),
&s.keyGenerator,
newUnusedSpace(1024, &s.recent),
&appendedEntries,
}
for _, data := range datas {
var err error
switch d := data.(type) {
case readerFromVersion:
read, err = d.readFromVersion(s.vers, r)
case io.ReaderFrom:
read, err = d.ReadFrom(r)
default:
read, err = binaryRead(r, binary.LittleEndian, d)
}
n += read
if err != nil {
return n, err
}
}
if id != fileID {
return n, errors.New("unknown file ID")
}
// Add root address to address map.
rootAddr := s.keyGenerator.Address()
s.addrMap[getAddressKey(rootAddr)] = &s.keyGenerator
s.chainIdxMap[rootKeyChainIdx] = rootAddr
s.lastChainIdx = rootKeyChainIdx
// Fill unserializied fields.
wts := appendedEntries.entries
for _, wt := range wts {
switch e := wt.(type) {
case *addrEntry:
addr := e.addr.Address()
s.addrMap[getAddressKey(addr)] = &e.addr
if e.addr.Imported() {
s.importedAddrs = append(s.importedAddrs, &e.addr)
} else {
s.chainIdxMap[e.addr.chainIndex] = addr
if s.lastChainIdx < e.addr.chainIndex {
s.lastChainIdx = e.addr.chainIndex
}
}
// If the private keys have not been created yet, mark the
// earliest so all can be created on next key store unlock.
if e.addr.flags.createPrivKeyNextUnlock {
switch {
case s.missingKeysStart == rootKeyChainIdx:
fallthrough
case e.addr.chainIndex < s.missingKeysStart:
s.missingKeysStart = e.addr.chainIndex
}
}
case *scriptEntry:
addr := e.script.Address()
s.addrMap[getAddressKey(addr)] = &e.script
// script are always imported.
s.importedAddrs = append(s.importedAddrs, &e.script)
default:
return n, errors.New("unknown appended entry")
}
}
return n, nil
}
// WriteTo serializes a key store and writes it to a io.Writer,
// returning the number of bytes written and any errors encountered.
func (s *Store) WriteTo(w io.Writer) (n int64, err error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.writeTo(w)
}
func (s *Store) writeTo(w io.Writer) (n int64, err error) {
var wts []io.WriterTo
var chainedAddrs = make([]io.WriterTo, len(s.chainIdxMap)-1)
var importedAddrs []io.WriterTo
for _, wAddr := range s.addrMap {
switch btcAddr := wAddr.(type) {
case *btcAddress:
e := &addrEntry{
addr: *btcAddr,
}
copy(e.pubKeyHash160[:], btcAddr.AddrHash())
if btcAddr.Imported() {
// No order for imported addresses.
importedAddrs = append(importedAddrs, e)
} else if btcAddr.chainIndex >= 0 {
// Chained addresses are sorted. This is
// kind of nice but probably isn't necessary.
chainedAddrs[btcAddr.chainIndex] = e
}
case *scriptAddress:
e := &scriptEntry{
script: *btcAddr,
}
copy(e.scriptHash160[:], btcAddr.AddrHash())
// scripts are always imported
importedAddrs = append(importedAddrs, e)
}
}
wts = append(chainedAddrs, importedAddrs...) // nolint:gocritic
appendedEntries := varEntries{store: s, entries: wts}
// Iterate through each entry needing to be written. If data
// implements io.WriterTo, use its WriteTo func. Otherwise,
// data is a pointer to a fixed size value.
datas := []interface{}{
&fileID,
&VersCurrent,
s.net,
&s.flags,
make([]byte, 6), // Bytes for Armory unique ID
&s.createDate,
&s.name,
&s.desc,
&s.highestUsed,
&s.kdfParams,
make([]byte, 256),
&s.keyGenerator,
newUnusedSpace(1024, &s.recent),
&appendedEntries,
}
var written int64
for _, data := range datas {
if s, ok := data.(io.WriterTo); ok {
written, err = s.WriteTo(w)
} else {
written, err = binaryWrite(w, binary.LittleEndian, data)
}
n += written
if err != nil {
return n, err
}
}
return n, nil
}
// TODO: set this automatically.
func (s *Store) MarkDirty() {
s.mtx.Lock()
defer s.mtx.Unlock()
s.dirty = true
}
func (s *Store) WriteIfDirty() error {
s.mtx.RLock()
if !s.dirty {
s.mtx.RUnlock()
return nil
}
// TempFile creates the file 0600, so no need to chmod it.
fi, err := os.CreateTemp(s.dir, s.file)
if err != nil {
s.mtx.RUnlock()
return err
}
fiPath := fi.Name()
_, err = s.writeTo(fi)
if err != nil {
s.mtx.RUnlock()
fi.Close()
return err
}
err = fi.Sync()
if err != nil {
s.mtx.RUnlock()
fi.Close()
return err
}
fi.Close()
err = rename.Atomic(fiPath, s.path)
s.mtx.RUnlock()
if err == nil {
s.mtx.Lock()
s.dirty = false
s.mtx.Unlock()
}
return err
}
// OpenDir opens a new key store from the specified directory. If the file
// does not exist, the error from the os package will be returned, and can
// be checked with os.IsNotExist to differentiate missing file errors from
// others (including deserialization).
func OpenDir(dir string) (*Store, error) {
path := filepath.Join(dir, Filename)
fi, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
defer fi.Close()
store := new(Store)
_, err = store.ReadFrom(fi)
if err != nil {
return nil, err
}
store.path = path
store.dir = dir
store.file = Filename
return store, nil
}
// Unlock derives an AES key from passphrase and key store's KDF
// parameters and unlocks the root key of the key store. If
// the unlock was successful, the key store's secret key is saved,
// allowing the decryption of any encrypted private key. Any
// addresses created while the key store was locked without private
// keys are created at this time.
func (s *Store) Unlock(passphrase []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Derive key from KDF parameters and passphrase.
key := kdf(passphrase, &s.kdfParams)
// Unlock root address with derived key.
if _, err := s.keyGenerator.unlock(key); err != nil {
return err
}
// If unlock was successful, save the passphrase and aes key.
s.passphrase = passphrase
s.secret = key
return s.createMissingPrivateKeys()
}
// Lock performs a best try effort to remove and zero all secret keys
// associated with the key store.
func (s *Store) Lock() (err error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
// Remove clear text passphrase from key store.
if s.isLocked() {
err = ErrLocked
} else {
zero(s.passphrase)
s.passphrase = nil
zero(s.secret)
s.secret = nil
}
// Remove clear text private keys from all address entries.
for _, addr := range s.addrMap {
if baddr, ok := addr.(*btcAddress); ok {
_ = baddr.lock()
}
}
return err
}
// ChangePassphrase creates a new AES key from a new passphrase and
// re-encrypts all encrypted private keys with the new key.
func (s *Store) ChangePassphrase(new []byte) error {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.flags.watchingOnly {
return ErrWatchingOnly
}
if s.isLocked() {
return ErrLocked
}
oldkey := s.secret
newkey := kdf(new, &s.kdfParams)
for _, wa := range s.addrMap {
// Only btcAddresses curently have private keys.
a, ok := wa.(*btcAddress)
if !ok {
continue
}
if err := a.changeEncryptionKey(oldkey, newkey); err != nil {
return err
}
}
// zero old secrets.
zero(s.passphrase)
zero(s.secret)
// Save new secrets.
s.passphrase = new
s.secret = newkey
return nil
}
func zero(b []byte) {
for i := range b {