-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
377 lines (329 loc) · 12.2 KB
/
import.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
package wallet
import (
"encoding/binary"
"errors"
"fmt"
"github.com/fichain/filechain/btcec"
"github.com/fichain/filechain/btcutil"
"github.com/fichain/filechain/btcutil/hdkeychain"
"github.com/fichain/filechain/btcwallet/netparams"
"github.com/fichain/filechain/btcwallet/waddrmgr"
"github.com/fichain/filechain/btcwallet/walletdb"
"github.com/fichain/filechain/wire"
)
const (
// accountPubKeyDepth is the maximum depth of an extended key for an
// account public key.
accountPubKeyDepth = 3
// pubKeyDepth is the depth of an extended key for a derived public key.
pubKeyDepth = 5
)
// keyScopeFromPubKey returns the corresponding wallet key scope for the given
// extended public key. The address type can usually be inferred from the key's
// version, but may be required for certain keys to map them into the proper
// scope.
func keyScopeFromPubKey(pubKey *hdkeychain.ExtendedKey,
addrType *waddrmgr.AddressType) (waddrmgr.KeyScope,
*waddrmgr.ScopeAddrSchema, error) {
switch waddrmgr.HDVersion(binary.BigEndian.Uint32(pubKey.Version())) {
// For BIP-0044 keys, an address type must be specified as we intend to
// not support importing BIP-0044 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will
// force the standard BIP-0049 derivation scheme (nested witness pubkeys
// everywhere), while a witness address type will force the standard
// BIP-0084 derivation scheme.
case waddrmgr.HDVersionMainNetBIP0044, waddrmgr.HDVersionTestNetBIP0044,
waddrmgr.HDVersionSimNetBIP0044:
if addrType == nil {
return waddrmgr.KeyScope{}, nil, errors.New("address " +
"type must be specified for account public " +
"key with legacy version")
}
switch *addrType {
case waddrmgr.NestedWitnessPubKey:
return waddrmgr.KeyScopeBIP0049Plus,
&waddrmgr.KeyScopeBIP0049AddrSchema, nil
case waddrmgr.WitnessPubKey:
return waddrmgr.KeyScopeBIP0084, nil, nil
default:
return waddrmgr.KeyScope{}, nil,
fmt.Errorf("unsupported address type %v",
*addrType)
}
// For BIP-0049 keys, we'll need to make a distinction between the
// traditional BIP-0049 address schema (nested witness pubkeys
// everywhere) and our own BIP-0049Plus address schema (nested
// externally, witness internally).
case waddrmgr.HDVersionMainNetBIP0049, waddrmgr.HDVersionTestNetBIP0049:
if addrType == nil {
return waddrmgr.KeyScope{}, nil, errors.New("address " +
"type must be specified for account public " +
"key with BIP-0049 version")
}
switch *addrType {
case waddrmgr.NestedWitnessPubKey:
return waddrmgr.KeyScopeBIP0049Plus,
&waddrmgr.KeyScopeBIP0049AddrSchema, nil
case waddrmgr.WitnessPubKey:
return waddrmgr.KeyScopeBIP0049Plus, nil, nil
default:
return waddrmgr.KeyScope{}, nil,
fmt.Errorf("unsupported address type %v",
*addrType)
}
case waddrmgr.HDVersionMainNetBIP0084, waddrmgr.HDVersionTestNetBIP0084:
if addrType != nil && *addrType != waddrmgr.WitnessPubKey {
return waddrmgr.KeyScope{}, nil,
errors.New("address type mismatch")
}
return waddrmgr.KeyScopeBIP0084, nil, nil
default:
return waddrmgr.KeyScope{}, nil, fmt.Errorf("unknown version %x",
pubKey.Version())
}
}
// isPubKeyForNet determines if the given public key is for the current network
// the wallet is operating under.
func (w *Wallet) isPubKeyForNet(pubKey *hdkeychain.ExtendedKey) bool {
version := waddrmgr.HDVersion(binary.BigEndian.Uint32(pubKey.Version()))
switch w.chainParams.Net {
case wire.MainNet:
return version == waddrmgr.HDVersionMainNetBIP0044 ||
version == waddrmgr.HDVersionMainNetBIP0049 ||
version == waddrmgr.HDVersionMainNetBIP0084
case wire.TestNet, wire.TestNet3, netparams.SigNetWire(w.chainParams):
return version == waddrmgr.HDVersionTestNetBIP0044 ||
version == waddrmgr.HDVersionTestNetBIP0049 ||
version == waddrmgr.HDVersionTestNetBIP0084
// For simnet, we'll also allow the mainnet versions since simnet
// doesn't have defined versions for some of our key scopes, and the
// mainnet versions are usually used as the default regardless of the
// network/key scope.
case wire.SimNet:
return version == waddrmgr.HDVersionSimNetBIP0044 ||
version == waddrmgr.HDVersionMainNetBIP0049 ||
version == waddrmgr.HDVersionMainNetBIP0084
default:
return false
}
}
// validateExtendedPubKey ensures a sane derived public key is provided.
func (w *Wallet) validateExtendedPubKey(pubKey *hdkeychain.ExtendedKey,
isAccountKey bool) error {
// Private keys are not allowed.
if pubKey.IsPrivate() {
return errors.New("private keys cannot be imported")
}
// The public key must have a version corresponding to the current
// chain.
if !w.isPubKeyForNet(pubKey) {
return fmt.Errorf("expected extended public key for current "+
"network %v", w.chainParams.Name)
}
// Verify the extended public key's depth and child index based on
// whether it's an account key or not.
if isAccountKey {
if pubKey.Depth() != accountPubKeyDepth {
return errors.New("invalid account key, must be of the " +
"form m/purpose'/coin_type'/account'")
}
if pubKey.ChildIndex() < hdkeychain.HardenedKeyStart {
return errors.New("invalid account key, must be hardened")
}
} else {
if pubKey.Depth() != pubKeyDepth {
return errors.New("invalid account key, must be of the " +
"form m/purpose'/coin_type'/account'/change/" +
"address_index")
}
if pubKey.ChildIndex() >= hdkeychain.HardenedKeyStart {
return errors.New("invalid pulic key, must not be " +
"hardened")
}
}
return nil
}
// ImportAccount imports an account backed by an account extended public key.
// The master key fingerprint denotes the fingerprint of the root key
// corresponding to the account public key (also known as the key with
// derivation path m/). This may be required by some hardware wallets for proper
// identification and signing.
//
// The address type can usually be inferred from the key's version, but may be
// required for certain keys to map them into the proper scope.
//
// For BIP-0044 keys, an address type must be specified as we intend to not
// support importing BIP-0044 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
// the standard BIP-0049 derivation scheme, while a witness address type will
// force the standard BIP-0084 derivation scheme.
//
// For BIP-0049 keys, an address type must also be specified to make a
// distinction between the traditional BIP-0049 address schema (nested witness
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested
// externally, witness internally).
func (w *Wallet) ImportAccount(name string, accountPubKey *hdkeychain.ExtendedKey,
masterKeyFingerprint uint32, addrType *waddrmgr.AddressType) (
*waddrmgr.AccountProperties, error) {
// Ensure we have a valid account public key.
if err := w.validateExtendedPubKey(accountPubKey, true); err != nil {
return nil, err
}
// Determine what key scope the account public key should belong to and
// whether it should use a custom address schema.
keyScope, addrSchema, err := keyScopeFromPubKey(accountPubKey, addrType)
if err != nil {
return nil, err
}
scopedMgr, err := w.Manager.FetchScopedKeyManager(keyScope)
if err != nil {
return nil, err
}
// Store the account as watch-only within the database.
var accountProps *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
account, err := scopedMgr.NewAccountWatchingOnly(
ns, name, accountPubKey, masterKeyFingerprint,
addrSchema,
)
if err != nil {
return err
}
accountProps, err = scopedMgr.AccountProperties(ns, account)
return err
})
return accountProps, err
}
// ImportPublicKey imports a single derived public key into the address manager.
// The address type can usually be inferred from the key's version, but in the
// case of legacy versions (xpub, tpub), an address type must be specified as we
// intend to not support importing BIP-44 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme.
func (w *Wallet) ImportPublicKey(pubKey *btcec.PublicKey,
addrType waddrmgr.AddressType) error {
// Determine what key scope the public key should belong to and import
// it into the key scope's default imported account.
var keyScope waddrmgr.KeyScope
switch addrType {
case waddrmgr.NestedWitnessPubKey:
keyScope = waddrmgr.KeyScopeBIP0049Plus
case waddrmgr.WitnessPubKey:
keyScope = waddrmgr.KeyScopeBIP0084
default:
return fmt.Errorf("address type %v is not supported", addrType)
}
scopedKeyManager, err := w.Manager.FetchScopedKeyManager(keyScope)
if err != nil {
return err
}
// TODO: Perform rescan if requested.
var addr waddrmgr.ManagedAddress
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
addr, err = scopedKeyManager.ImportPublicKey(ns, pubKey, nil)
return err
})
if err != nil {
return err
}
log.Infof("Imported address %v", addr.Address())
err = w.chainClient.NotifyReceived([]btcutil.Address{addr.Address()})
if err != nil {
return fmt.Errorf("unable to subscribe for address "+
"notifications: %v", err)
}
return nil
}
// ImportPrivateKey imports a private key to the wallet and writes the new
// wallet to disk.
//
// NOTE: If a block stamp is not provided, then the wallet's birthday will be
// set to the genesis block of the corresponding chain.
func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *btcutil.WIF,
bs *waddrmgr.BlockStamp, rescan bool) (string, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return "", err
}
// The starting block for the key is the genesis block unless otherwise
// specified.
if bs == nil {
bs = &waddrmgr.BlockStamp{
Hash: *w.chainParams.GenesisHash,
Height: 0,
Timestamp: w.chainParams.GenesisBlock.Header.Timestamp,
}
} else if bs.Timestamp.IsZero() {
// Only update the new birthday time from default value if we
// actually have timestamp info in the header.
header, err := w.chainClient.GetBlockHeader(&bs.Hash)
if err == nil {
bs.Timestamp = header.Timestamp
}
}
// Attempt to import private key into wallet.
var addr btcutil.Address
var props *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
maddr, err := manager.ImportPrivateKey(addrmgrNs, wif, bs)
if err != nil {
return err
}
addr = maddr.Address()
props, err = manager.AccountProperties(
addrmgrNs, waddrmgr.ImportedAddrAccount,
)
if err != nil {
return err
}
// We'll only update our birthday with the new one if it is
// before our current one. Otherwise, if we do, we can
// potentially miss detecting relevant chain events that
// occurred between them while rescanning.
birthdayBlock, _, err := w.Manager.BirthdayBlock(addrmgrNs)
if err != nil {
return err
}
if bs.Height >= birthdayBlock.Height {
return nil
}
err = w.Manager.SetBirthday(addrmgrNs, bs.Timestamp)
if err != nil {
return err
}
// To ensure this birthday block is correct, we'll mark it as
// unverified to prompt a sanity check at the next restart to
// ensure it is correct as it was provided by the caller.
return w.Manager.SetBirthdayBlock(addrmgrNs, *bs, false)
})
if err != nil {
return "", err
}
// Rescan blockchain for transactions with txout scripts paying to the
// imported address.
if rescan {
job := &RescanJob{
Addrs: []btcutil.Address{addr},
OutPoints: nil,
BlockStamp: *bs,
}
// Submit rescan job and log when the import has completed.
// Do not block on finishing the rescan. The rescan success
// or failure is logged elsewhere, and the channel is not
// required to be read, so discard the return value.
_ = w.SubmitRescan(job)
} else {
err := w.chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return "", fmt.Errorf("failed to subscribe for address ntfns for "+
"address %s: %s", addr.EncodeAddress(), err)
}
}
addrStr := addr.EncodeAddress()
log.Infof("Imported payment address %s", addrStr)
w.NtfnServer.notifyAccountProperties(props)
// Return the payment address string of the imported private key.
return addrStr, nil
}