forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcrwallet.go
324 lines (291 loc) · 9.28 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
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015 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"
"io/ioutil"
"net"
"net/http"
_ "net/http/pprof"
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrwallet/chain"
"github.com/decred/dcrwallet/internal/prompt"
"github.com/decred/dcrwallet/internal/zero"
"github.com/decred/dcrwallet/rpc/legacyrpc"
"github.com/decred/dcrwallet/wallet"
)
var (
cfg *config
)
func main() {
// Use all processor cores.
runtime.GOMAXPROCS(runtime.NumCPU())
// Work around defer not working after os.Exit.
if err := walletMain(); err != nil {
os.Exit(1)
}
}
// walletMain is a work-around main function that is required since deferred
// functions (such as log flushing) are not called with calls to os.Exit.
// Instead, main runs this function and checks for a non-nil error, at which
// point any defers have already run, and if the error is non-nil, the program
// can be exited with an error exit status.
func walletMain() error {
// Load configuration and parse command line. This function also
// initializes logging and configures it accordingly.
log.Infof("load the config")
tcfg, _, err := loadConfig()
if err != nil {
return err
}
cfg = tcfg
defer backendLog.Flush()
// Show version at startup.
log.Infof("Version %s", version())
if cfg.Profile != "" {
go func() {
listenAddr := net.JoinHostPort("", cfg.Profile)
log.Infof("Profile server listening on %s", listenAddr)
profileRedirect := http.RedirectHandler("/debug/pprof",
http.StatusSeeOther)
http.Handle("/", profileRedirect)
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
fatalf(err.Error())
}
}()
}
// Write mem profile if requested.
if cfg.MemProfile != "" {
f, err := os.Create(cfg.MemProfile)
if err != nil {
log.Errorf("Unable to create cpu profile: %v", err)
return err
}
timer := time.NewTimer(time.Minute * 5) // 5 minutes
go func() {
<-timer.C
pprof.WriteHeapProfile(f)
f.Close()
}()
}
dbDir := networkDir(cfg.DataDir, activeNet.Params)
stakeOptions := &wallet.StakeOptions{
VoteBits: cfg.VoteBits,
StakeMiningEnabled: cfg.EnableStakeMining,
BalanceToMaintain: cfg.BalanceToMaintain,
RollbackTest: cfg.RollbackTest,
PruneTickets: cfg.PruneTickets,
AddressReuse: cfg.ReuseAddresses,
TicketAddress: cfg.TicketAddress,
TicketMaxPrice: cfg.TicketMaxPrice,
}
loader := wallet.NewLoader(activeNet.Params, dbDir, stakeOptions, cfg.AutomaticRepair, cfg.UnsafeMainNet, cfg.PromptPass)
// Create and start HTTP server to serve wallet client connections.
// This will be updated with the wallet and chain server RPC client
// created below after each is created.
rpcs, legacyRPCServer, err := startRPCServers(loader)
if err != nil {
log.Errorf("Unable to create RPC servers: %v", err)
return err
}
// Create and start chain RPC client so it's ready to connect to
// the wallet when loaded later.
if !cfg.NoInitialLoad {
go rpcClientConnectLoop(legacyRPCServer, loader)
}
loader.RunAfterLoad(func(w *wallet.Wallet) {
startPromptPass(w)
startWalletRPCServices(w, rpcs, legacyRPCServer)
})
if !cfg.NoInitialLoad {
// Load the wallet database. It must have been created already
// or this will return an appropriate error.
_, err = loader.OpenExistingWallet([]byte(cfg.WalletPass), true)
if err != nil {
log.Error(err)
return err
}
}
// Add interrupt handlers to shutdown the various process components
// before exiting. Interrupt handlers run in LIFO order, so the wallet
// (which should be closed last) is added first.
addInterruptHandler(func() {
err := loader.UnloadWallet()
if err != nil && err != wallet.ErrNotLoaded {
log.Errorf("Failed to close wallet: %v", err)
}
})
if rpcs != nil {
addInterruptHandler(func() {
// TODO: Does this need to wait for the grpc server to
// finish up any requests?
log.Warn("Stopping RPC server...")
rpcs.Stop()
log.Info("RPC server shutdown")
})
}
if legacyRPCServer != nil {
addInterruptHandler(func() {
log.Warn("Stopping legacy RPC server...")
legacyRPCServer.Stop()
log.Info("Legacy RPC server shutdown")
})
go func() {
<-legacyRPCServer.RequestProcessShutdown()
simulateInterrupt()
}()
}
<-interruptHandlersDone
log.Info("Shutdown complete")
return nil
}
// 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(w *wallet.Wallet) {
promptPass := cfg.PromptPass
// 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.
firstRunBS := w.Manager.SyncedTo()
if firstRunBS.Hash == *w.ChainParams().GenesisHash {
promptPass = true
}
if promptPass {
w.SetResyncAccounts(true)
log.Infof("Please enter the private wallet passphrase. " +
"This will complete syncing of the wallet accounts " +
"and then leave your wallet unlocked. You may relock " +
"wallet after by calling 'walletlock' through the RPC.")
} else {
return
}
// 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() == &chaincfg.SimNetParams {
var unlockAfter <-chan time.Time
err := w.Unlock(wallet.SimulationPassphrase, unlockAfter)
if err == nil {
// Unlock success with the default password.
return
}
}
if promptPass {
reader := bufio.NewReader(os.Stdin)
passphrase, err := prompt.PromptPass(reader, "", false)
if err != nil {
log.Errorf("Failed to input password. Please try again.")
continue
}
defer zero.Bytes(passphrase)
var unlockAfter <-chan time.Time
err = w.Unlock(passphrase, unlockAfter)
if err != nil {
log.Errorf("Incorrect password entered. Please " +
"try again.")
continue
}
break
}
}
}
// rpcClientConnectLoop continuously attempts a connection to the consensus RPC
// server. When a connection is established, the client is used to sync the
// loaded wallet, either immediately or when loaded at a later time.
//
// The legacy RPC is optional. If set, the connected RPC client will be
// associated with the server for RPC passthrough and to enable additional
// methods.
func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {
certs := readCAFile()
for {
chainClient, err := startChainRPC(certs)
if err != nil {
log.Errorf("Unable to open connection to consensus RPC server: %v", err)
continue
}
// Rather than inlining this logic directly into the loader
// callback, a function variable is used to avoid running any of
// this after the client disconnects by setting it to nil. This
// prevents the callback from associating a wallet loaded at a
// later time with a client that has already disconnected. A
// mutex is used to make this concurrent safe.
associateRPCClient := func(w *wallet.Wallet) {
w.SynchronizeRPC(chainClient)
if legacyRPCServer != nil {
legacyRPCServer.SetChainServer(chainClient)
}
}
mu := new(sync.Mutex)
loader.RunAfterLoad(func(w *wallet.Wallet) {
mu.Lock()
associate := associateRPCClient
mu.Unlock()
if associate != nil {
associate(w)
}
})
chainClient.WaitForShutdown()
mu.Lock()
associateRPCClient = nil
mu.Unlock()
loadedWallet, ok := loader.LoadedWallet()
if ok {
// Do not attempt a reconnect when the wallet was
// explicitly stopped.
if loadedWallet.ShuttingDown() {
return
}
loadedWallet.SetChainSynced(false)
// TODO: Rework the wallet so changing the RPC client
// does not require stopping and restarting everything.
loadedWallet.Stop()
loadedWallet.WaitForShutdown()
loadedWallet.Start()
}
}
}
func readCAFile() []byte {
// Read certificate file if TLS is not disabled.
var certs []byte
if !cfg.DisableClientTLS {
var err error
certs, err = ioutil.ReadFile(cfg.CAFile)
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
}
// startChainRPC opens a RPC client connection to a dtcd server for blockchain
// services. This function uses the RPC options from the global config and
// there is no recovery in case the server is not available or if there is an
// authentication error. Instead, all requests to the client will simply error.
func startChainRPC(certs []byte) (*chain.RPCClient, error) {
log.Infof("Attempting RPC client connection to %v", cfg.RPCConnect)
rpcc, err := chain.NewRPCClient(activeNet.Params, cfg.RPCConnect,
cfg.DcrdUsername, cfg.DcrdPassword, certs, cfg.DisableClientTLS, 0)
if err != nil {
return nil, err
}
err = rpcc.Start()
return rpcc, err
}