-
Notifications
You must be signed in to change notification settings - Fork 155
/
dcrwallet.go
618 lines (567 loc) · 17.3 KB
/
dcrwallet.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
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2024 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"time"
"decred.org/dcrwallet/v5/chain"
"decred.org/dcrwallet/v5/errors"
ldr "decred.org/dcrwallet/v5/internal/loader"
"decred.org/dcrwallet/v5/internal/loggers"
"decred.org/dcrwallet/v5/internal/prompt"
"decred.org/dcrwallet/v5/internal/rpc/rpcserver"
"decred.org/dcrwallet/v5/p2p"
"decred.org/dcrwallet/v5/spv"
"decred.org/dcrwallet/v5/ticketbuyer"
"decred.org/dcrwallet/v5/version"
"decred.org/dcrwallet/v5/wallet"
"github.com/decred/dcrd/addrmgr/v2"
"github.com/decred/dcrd/wire"
)
func init() {
// Format nested errors without newlines (better for logs).
errors.Separator = ":: "
}
var (
cfg *config
)
func main() {
// Create a context that is cancelled when a shutdown request is received
// through an interrupt signal or an RPC request.
ctx := withShutdownCancel(context.Background())
go shutdownListener()
// Run the wallet until permanent failure or shutdown is requested.
if err := run(ctx); err != nil && !errors.Is(err, context.Canceled) {
os.Exit(1)
}
}
// done returns whether the context's Done channel was closed due to
// cancellation or exceeded deadline.
func done(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
func zero(b []byte) {
for i := range b {
b[i] = 0
}
}
// run is the main startup and teardown logic performed by the main package. It
// is responsible for parsing the config, starting RPC servers, loading and
// syncing the wallet (if necessary), and stopping all started services when the
// context is cancelled.
func run(ctx context.Context) error {
// Load configuration and parse command line. This function also
// initializes logging and configures it accordingly.
tcfg, _, err := loadConfig(ctx)
if err != nil {
return err
}
cfg = tcfg
defer loggers.CloseLogRotator()
// Show version at startup.
log.Infof("Version %s (Go version %s %s/%s)", version.String(), runtime.Version(),
runtime.GOOS, runtime.GOARCH)
if cfg.NoFileLogging {
log.Info("File logging disabled")
}
// Read IPC messages from the read end of a pipe created and passed by the
// parent process, if any. When this pipe is closed, shutdown is
// initialized.
if cfg.PipeRx != nil {
go serviceControlPipeRx(uintptr(*cfg.PipeRx))
}
if cfg.PipeTx != nil {
go serviceControlPipeTx(uintptr(*cfg.PipeTx))
} else {
go drainOutgoingPipeMessages()
}
// Run the pprof profiler if enabled.
if len(cfg.Profile) > 0 {
if done(ctx) {
return ctx.Err()
}
profileRedirect := http.RedirectHandler("/debug/pprof", http.StatusSeeOther)
http.Handle("/", profileRedirect)
for _, listenAddr := range cfg.Profile {
listenAddr := listenAddr // copy for closure
go func() {
log.Infof("Starting profile server on %s", listenAddr)
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
fatalf("Unable to run profiler: %v", err)
}
}()
}
}
// Write cpu profile if requested.
if cfg.CPUProfile != "" {
if done(ctx) {
return ctx.Err()
}
f, err := os.Create(cfg.CPUProfile)
if err != nil {
log.Errorf("Unable to create cpu profile: %v", err.Error())
return err
}
pprof.StartCPUProfile(f)
defer f.Close()
defer pprof.StopCPUProfile()
}
// Write mem profile if requested.
if cfg.MemProfile != "" {
if done(ctx) {
return ctx.Err()
}
f, err := os.Create(cfg.MemProfile)
if err != nil {
log.Errorf("Unable to create mem profile: %v", err)
return err
}
defer func() {
pprof.WriteHeapProfile(f)
f.Close()
}()
}
if done(ctx) {
return ctx.Err()
}
// Create the loader which is used to load and unload the wallet. If
// --noinitialload is not set, this function is responsible for loading the
// wallet. Otherwise, loading is deferred so it can be performed over RPC.
dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
loader := ldr.NewLoader(activeNet.Params, dbDir, cfg.EnableVoting,
cfg.GapLimit, cfg.WatchLast, cfg.AllowHighFees, cfg.RelayFee.Amount,
cfg.AccountGapLimit, cfg.DisableCoinTypeUpgrades, !cfg.Mixing,
cfg.ManualTickets, cfg.MixSplitLimit, cfg.dial)
// Stop any services started by the loader after the shutdown procedure is
// initialized and this function returns.
defer func() {
// When panicing, do not cleanly unload the wallet (by closing
// the db). If a panic occurred inside a bolt transaction, the
// db mutex is still held and this causes a deadlock.
if r := recover(); r != nil {
panic(r)
}
err := loader.UnloadWallet()
if err != nil && !errors.Is(err, errors.Invalid) {
log.Errorf("Failed to close wallet: %v", err)
} else if err == nil {
log.Infof("Closed wallet")
}
}()
// Open the wallet when --noinitialload was not set.
var vspClient *wallet.VSPClient
passphrase := []byte{}
if !cfg.NoInitialLoad {
walletPass := []byte(cfg.WalletPass)
if cfg.PromptPublicPass {
walletPass, _ = passPrompt(ctx, "Enter public wallet passphrase", false)
}
if done(ctx) {
return ctx.Err()
}
// Load the wallet. It must have been created already or this will
// return an appropriate error.
var w *wallet.Wallet
errc := make(chan error, 1)
go func() {
defer zero(walletPass)
var err error
w, err = loader.OpenExistingWallet(ctx, walletPass)
if err != nil {
log.Errorf("Failed to open wallet: %v", err)
if errors.Is(err, errors.Passphrase) {
// walletpass not provided, advice using --walletpass or --promptpublicpass
if cfg.WalletPass == wallet.InsecurePubPassphrase {
log.Info("Configure public passphrase with walletpass or promptpublicpass options.")
}
}
}
errc <- err
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errc:
if err != nil {
return err
}
}
// TODO(jrick): I think that this prompt should be removed
// entirely instead of enabling it when --noinitialload is
// unset. It can be replaced with an RPC request (either
// providing the private passphrase as a parameter, or require
// unlocking the wallet first) to trigger a full accounts
// rescan.
//
// Until then, since --noinitialload users are expecting to use
// the wallet only over RPC, disable this feature for them.
if cfg.Pass != "" {
passphrase = []byte(cfg.Pass)
err = w.Unlock(ctx, passphrase, nil)
if err != nil {
log.Errorf("Incorrect passphrase in pass config setting.")
return err
}
} else {
passphrase = startPromptPass(ctx, w)
}
if cfg.VSPOpts.URL != "" {
changeAccountName := cfg.ChangeAccount
if changeAccountName == "" && !cfg.Mixing {
log.Warnf("Change account not set, using "+
"purchase account %q", cfg.PurchaseAccount)
changeAccountName = cfg.PurchaseAccount
}
changeAcct, err := w.AccountNumber(ctx, changeAccountName)
if err != nil {
log.Warnf("failed to get account number for "+
"ticket change account %q: %v",
changeAccountName, err)
return err
}
purchaseAcct, err := w.AccountNumber(ctx, cfg.PurchaseAccount)
if err != nil {
log.Warnf("failed to get account number for "+
"ticket purchase account %q: %v",
cfg.PurchaseAccount, err)
return err
}
vspCfg := wallet.VSPClientConfig{
URL: cfg.VSPOpts.URL,
PubKey: cfg.VSPOpts.PubKey,
Policy: &wallet.VSPPolicy{
MaxFee: cfg.VSPOpts.MaxFee.Amount,
FeeAcct: purchaseAcct,
ChangeAcct: changeAcct,
},
}
vspClient, err = w.VSP(vspCfg)
if err != nil {
log.Errorf("vsp: %v", err)
return err
}
}
if cfg.MixChange || cfg.EnableTicketBuyer {
var err error
var lastFlag, lastLookup string
lookup := func(flag, name string) (account uint32) {
if err == nil {
lastFlag = flag
lastLookup = name
account, err = w.AccountNumber(ctx, name)
}
return
}
var (
purchaseAccount uint32 // enableticketbuyer
votingAccount uint32 // enableticketbuyer
mixedAccount uint32 // (enableticketbuyer && mixing) || mixchange
changeAccount uint32 // (enableticketbuyer && mixing) || mixchange
ticketSplitAccount uint32 // enableticketbuyer && mixing
)
if cfg.EnableTicketBuyer {
purchaseAccount = lookup("purchaseaccount", cfg.PurchaseAccount)
if cfg.Mixing && cfg.TBOpts.VotingAccount == "" {
err := errors.New("cannot run mixed ticketbuyer without --votingaccount")
log.Error(err)
return err
}
if cfg.TBOpts.VotingAccount != "" {
votingAccount = lookup("ticketbuyer.votingaccount", cfg.TBOpts.VotingAccount)
}
}
if (cfg.EnableTicketBuyer && cfg.Mixing) || cfg.MixChange {
mixedAccount = lookup("mixedaccount", cfg.mixedAccount)
changeAccount = lookup("changeaccount", cfg.ChangeAccount)
}
if cfg.EnableTicketBuyer && cfg.Mixing {
ticketSplitAccount = lookup("ticketsplitaccount", cfg.TicketSplitAccount)
}
// Check if any of the above calls to lookup() have failed.
if err != nil {
log.Errorf("%s: account %q does not exist", lastFlag, lastLookup)
return err
}
// Start a ticket buyer.
tb := ticketbuyer.New(w, ticketbuyer.Config{
BuyTickets: cfg.EnableTicketBuyer,
Account: purchaseAccount,
Maintain: cfg.TBOpts.BalanceToMaintainAbsolute.Amount,
Limit: int(cfg.TBOpts.Limit),
VotingAccount: votingAccount,
Mixing: cfg.Mixing,
MixChange: cfg.MixChange,
MixedAccount: mixedAccount,
MixedAccountBranch: cfg.mixedBranch,
TicketSplitAccount: ticketSplitAccount,
ChangeAccount: changeAccount,
VSP: vspClient,
})
log.Infof("Starting auto transaction creator")
tbdone := make(chan struct{})
go func() {
err := tb.Run(ctx, passphrase)
if err != nil && !errors.Is(err, context.Canceled) {
log.Errorf("Transaction creator ended: %v", err)
}
tbdone <- struct{}{}
}()
defer func() { <-tbdone }()
}
}
if done(ctx) {
return ctx.Err()
}
// Create and start the RPC servers to serve wallet client connections. If
// any of the servers can not be started, it will be nil. If none of them
// can be started, this errors since at least one server must run for the
// wallet to be useful.
//
// Servers will be associated with a loaded wallet if it has already been
// loaded, or after it is loaded later on.
gRPCServer, jsonRPCServer, err := startRPCServers(loader)
if err != nil {
log.Errorf("Unable to create RPC servers: %v", err)
return err
}
if gRPCServer != nil {
// Start wallet, voting and network gRPC services after a
// wallet is loaded.
loader.RunAfterLoad(func(w *wallet.Wallet) {
rpcserver.StartWalletService(gRPCServer, w)
rpcserver.StartNetworkService(gRPCServer, w)
rpcserver.StartVotingService(gRPCServer, w)
})
defer func() {
log.Warn("Stopping gRPC server...")
gRPCServer.Stop()
log.Info("gRPC server shutdown")
}()
}
if jsonRPCServer != nil {
go func() {
for range jsonRPCServer.RequestProcessShutdown() {
requestShutdown()
}
}()
defer func() {
log.Warn("Stopping JSON-RPC server...")
jsonRPCServer.Stop()
log.Info("JSON-RPC server shutdown")
}()
}
// When not running with --noinitialload, it is the main package's
// responsibility to synchronize the wallet with the network through SPV or
// the trusted dcrd server. This blocks until cancelled.
if !cfg.NoInitialLoad {
if done(ctx) {
return ctx.Err()
}
loader.RunAfterLoad(func(w *wallet.Wallet) {
if vspClient != nil && cfg.VSPOpts.Sync {
tickets, err := w.ProcessedTickets(ctx)
if err != nil {
log.Errorf("Getting VSP tickets failed: %v", err)
}
err = vspClient.ProcessManagedTickets(ctx, tickets)
if err != nil {
log.Errorf("Adding tickets to VSP client failed: %v", err)
}
}
switch {
case cfg.Offline:
w.SetNetworkBackend(wallet.OfflineNetworkBackend{})
case cfg.SPV:
spvLoop(ctx, w)
default:
rpcSyncLoop(ctx, w)
}
})
}
// Wait until shutdown is signaled before returning and running deferred
// shutdown tasks.
<-ctx.Done()
return ctx.Err()
}
func passPrompt(ctx context.Context, prefix string, confirm bool) (passphrase []byte, err error) {
os.Stdout.Sync()
c := make(chan struct{}, 1)
go func() {
passphrase, err = prompt.PassPrompt(bufio.NewReader(os.Stdin), prefix, confirm)
c <- struct{}{}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-c:
return passphrase, err
}
}
// startPromptPass prompts the user for a password to unlock their wallet in
// the event that it was restored from seed or --promptpass flag is set.
func startPromptPass(ctx context.Context, w *wallet.Wallet) []byte {
promptPass := cfg.PromptPass
// Watching only wallets never require a password.
if w.WatchingOnly() {
return nil
}
// The wallet is totally desynced, so we need to resync accounts.
// Prompt for the password. Then, set the flag it wallet so it
// knows which address functions to call when resyncing.
needSync, err := w.NeedsAccountsSync(ctx)
if err != nil {
log.Errorf("Error determining whether an accounts sync is necessary: %v", err)
}
if err == nil && needSync {
fmt.Println("*** ATTENTION ***")
fmt.Println("Since this is your first time running we need to sync accounts. Please enter")
fmt.Println("the private wallet passphrase. This will complete syncing of the wallet")
fmt.Println("accounts and then leave your wallet unlocked. You may relock wallet after by")
fmt.Println("calling 'walletlock' through the RPC.")
fmt.Println("*****************")
promptPass = true
}
if cfg.EnableTicketBuyer {
promptPass = true
}
if !promptPass {
return nil
}
// We need to rescan accounts for the initial sync. Unlock the
// wallet after prompting for the passphrase. The special case
// of a --createtemp simnet wallet is handled by first
// attempting to automatically open it with the default
// passphrase. The wallet should also request to be unlocked
// if stake mining is currently on, so users with this flag
// are prompted here as well.
for {
if w.ChainParams().Net == wire.SimNet {
err := w.Unlock(ctx, wallet.SimulationPassphrase, nil)
if err == nil {
// Unlock success with the default password.
return wallet.SimulationPassphrase
}
}
passphrase, err := passPrompt(ctx, "Enter private passphrase", false)
if err != nil {
return nil
}
err = w.Unlock(ctx, passphrase, nil)
if err != nil {
fmt.Println("Incorrect password entered. Please " +
"try again.")
continue
}
return passphrase
}
}
func spvLoop(ctx context.Context, w *wallet.Wallet) {
addr := &net.TCPAddr{IP: net.ParseIP("::1"), Port: 0}
amgrDir := filepath.Join(cfg.AppDataDir.Value, w.ChainParams().Name)
amgr := addrmgr.New(amgrDir, cfg.lookup)
lp := p2p.NewLocalPeer(w.ChainParams(), addr, amgr)
lp.SetDialFunc(cfg.dial)
lp.SetDisableRelayTx(cfg.SPVDisableRelayTx)
syncer := spv.NewSyncer(w, lp)
if len(cfg.SPVConnect) > 0 {
syncer.SetPersistentPeers(cfg.SPVConnect)
}
w.SetNetworkBackend(syncer)
for {
err := syncer.Run(ctx)
if done(ctx) {
return
}
log.Errorf("SPV synchronization ended: %v", err)
}
}
// rpcSyncLoop loops forever, attempting to create a connection to the
// consensus RPC server. If this connection succeeds, the RPC client is used as
// the loaded wallet's network backend and used to keep the wallet synchronized
// to the network. If/when the RPC connection is lost, the wallet is
// disassociated from the client and a new connection is attempmted.
func rpcSyncLoop(ctx context.Context, w *wallet.Wallet) {
certs := readCAFile()
clientCert, clientKey := readClientCertKey()
dial := cfg.dial
if cfg.NoDcrdProxy {
dial = new(net.Dialer).DialContext
}
for {
rpcOptions := &chain.RPCOptions{
Address: cfg.RPCConnect,
DefaultPort: activeNet.JSONRPCClientPort,
User: cfg.DcrdUsername,
Pass: cfg.DcrdPassword,
Dial: dial,
CA: certs,
Insecure: cfg.DisableClientTLS,
}
if len(clientCert) != 0 {
rpcOptions.User = ""
rpcOptions.Pass = ""
rpcOptions.ClientCert = clientCert
rpcOptions.ClientKey = clientKey
}
syncer := chain.NewSyncer(w, rpcOptions)
err := syncer.Run(ctx)
if err != nil {
loggers.SyncLog.Errorf("Wallet synchronization stopped: %v", err)
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
}
}
}
}
func readCAFile() []byte {
// Read certificate file if TLS is not disabled.
var certs []byte
if !cfg.DisableClientTLS {
var err error
certs, err = os.ReadFile(cfg.CAFile.Value)
if err != nil {
log.Warnf("Cannot open CA file: %v", err)
// If there's an error reading the CA file, continue
// with nil certs and without the client connection.
certs = nil
}
} else {
log.Info("Chain server RPC TLS is disabled")
}
return certs
}
func readClientCertKey() ([]byte, []byte) {
if cfg.DcrdAuthType != authTypeClientCert {
return nil, nil
}
cert, err := os.ReadFile(cfg.DcrdClientCert.Value)
if err != nil {
log.Warnf("Cannot open dcrd RPC client certificate: %v", err)
cert = nil
}
key, err := os.ReadFile(cfg.DcrdClientKey.Value)
if err != nil {
log.Warnf("Cannot open dcrd RPC client key: %v", err)
key = nil
}
return cert, key
}