forked from DanielKrawisz/bmagent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbsetup.go
425 lines (365 loc) · 10.6 KB
/
dbsetup.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
// Originally derived from: btcsuite/btcwallet/walletsetup.go
// Copyright (c) 2013-2014 The btcsuite developers
// Copyright (c) 2015 Monetas.
// Copyright 2016 Daniel Krawisz.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"strings"
"regexp"
"errors"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/DanielKrawisz/bmagent/email"
"github.com/DanielKrawisz/bmagent/keymgr"
"github.com/DanielKrawisz/bmagent/store"
"golang.org/x/crypto/ssh/terminal"
)
var (
consoleReader = bufio.NewReader(os.Stdin)
)
// promptConsoleList prompts the user with the given prefix, list of valid
// responses, and default list entry to use. The function will repeat the
// prompt to the user until they enter a valid response.
func promptConsoleList(prefix string, validResponses []string, defaultEntry string) (string, error) {
// Setup the prompt according to the parameters.
validStrings := strings.Join(validResponses, "/")
var prompt string
if defaultEntry != "" {
prompt = fmt.Sprintf("%s (%s) [%s]: ", prefix, validStrings,
defaultEntry)
} else {
prompt = fmt.Sprintf("%s (%s): ", prefix, validStrings)
}
// Prompt the user until one of the valid responses is given.
for {
fmt.Print(prompt)
reply, err := consoleReader.ReadString('\n')
if err != nil {
return "", err
}
reply = strings.TrimSpace(strings.ToLower(reply))
if reply == "" {
reply = defaultEntry
}
for _, validResponse := range validResponses {
if reply == validResponse {
return reply, nil
}
}
}
}
// promptConsoleListBool prompts the user for a boolean (yes/no) with the given
// prefix. The function will repeat the prompt to the user until they enter a
// valid reponse.
func promptConsoleListBool(prefix string, defaultEntry string) (bool, error) {
// Setup the valid responses.
valid := []string{"n", "no", "y", "yes"}
response, err := promptConsoleList(prefix, valid, defaultEntry)
if err != nil {
return false, err
}
return response == "yes" || response == "y", nil
}
// promptConsolePass uses the given prefix to ask the user for a password.
// The function will ask the user to confirm the passphrase and will repeat
// the prompts until they enter a matching response.
func promptConsolePass(prefix string, confirm bool) ([]byte, error) {
// Prompt the user until they enter a passphrase.
prompt := fmt.Sprintf("%s: ", prefix)
for {
fmt.Print(prompt)
pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return nil, err
}
fmt.Print("\n")
pass = bytes.TrimSpace(pass)
if len(pass) == 0 {
return nil, nil
}
if !confirm {
return pass, nil
}
fmt.Print("Confirm passphrase: ")
confirm, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return nil, err
}
fmt.Print("\n")
confirm = bytes.TrimSpace(confirm)
if !bytes.Equal(pass, confirm) {
fmt.Println("The entered passphrases do not match.")
continue
}
return pass, nil
}
}
// promptKeyfilePassPhrase is used to prompt for the passphrase required to
// decrypt the key file.
func promptKeyfilePassPhrase() ([]byte, error) {
prompt := "Enter key file passphrase: "
var pass []byte
var err error
for {
pass, err = promptConsolePass(prompt, false)
if (err != nil) {
return nil, err
}
if (pass != nil) {
return pass, err
}
}
}
func promptUsername(prefix string) (string, error) {
// Prompt the user until they enter a passphrase.
prompt := fmt.Sprintf("%s: ", prefix)
match := "^[a-zA-Z][a-zA-Z0-9]*$"
r, _ := regexp.Compile(match)
for {
fmt.Print(prompt)
uname, err := consoleReader.ReadString('\n')
if err != nil {
return "", err
}
fmt.Print("\n")
uname = strings.TrimSpace(uname)
if r.MatchString(uname) {
fmt.Printf("Username is \"%s\"\n", uname)
return uname, nil
}
fmt.Println("Username must match ", match)
}
}
// promptStorePassPhrase is used to prompt for the passphrase required to
// decrypt the data store.
func promptStorePassPhrase() ([]byte, error) {
prompt := "Enter data store passphrase: "
var pass []byte
var err error
for {
pass, err = promptConsolePass(prompt, false)
if (err != nil) {
return nil, err
}
if (pass != nil) {
return pass, err
}
}
}
// promptConsoleSeed prompts the user whether they want to use an existing
// Bitmessage address generation seed. When the user answers no, a seed will be
// generated and displayed to the user along with prompting them for
// confirmation. When the user answers yes, the user is prompted for it. All
// prompts are repeated until the user enters a valid response.
func promptConsoleSeed() ([]byte, error) {
// Ascertain the wallet generation seed.
useUserSeed, err := promptConsoleListBool("\nDo you have an "+
"existing Bitmessage address generation seed you want to use?", "no")
if err != nil {
return nil, err
}
if !useUserSeed {
seed, err := hdkeychain.GenerateSeed(hdkeychain.RecommendedSeedLen)
if err != nil {
return nil, err
}
fmt.Println("\nYour address generation seed is:")
fmt.Printf("%x\n\n", seed)
fmt.Println("IMPORTANT: Please keep in mind that anyone who has" +
" access to the seed can also restore your addresses thereby " +
"giving them access to all your Bitmessage identities, so it is " +
"imperative that you keep it in a secure location.\n")
for {
fmt.Print(`Once you have stored the seed in a safe ` +
`and secure location, enter "OK" to continue: `)
confirmSeed, err := consoleReader.ReadString('\n')
if err != nil {
return nil, err
}
confirmSeed = strings.TrimSpace(confirmSeed)
confirmSeed = strings.Trim(confirmSeed, `"`)
if confirmSeed == "OK" {
break
}
}
return seed, nil
}
for {
fmt.Print("Enter existing address generation seed: ")
seedStr, err := consoleReader.ReadString('\n')
if err != nil {
return nil, err
}
seedStr = strings.TrimSpace(strings.ToLower(seedStr))
seed, err := hex.DecodeString(seedStr)
if err != nil || len(seed) < hdkeychain.MinSeedBytes ||
len(seed) > hdkeychain.MaxSeedBytes {
fmt.Printf("Invalid seed specified. Must be a "+
"hexadecimal value that is at least %d bits and "+
"at most %d bits\n", hdkeychain.MinSeedBytes*8,
hdkeychain.MaxSeedBytes*8)
continue
}
return seed, nil
}
}
// createDatabases prompts the user for information needed to generate a new
// key file and data store and generates them accordingly. The new databases
// will reside at the provided path.
func createDatabases(cfg *config) error {
var keyfilePass, storePass []byte
var err error
var prompt string
// Create default mailboxes and associated data.
var username string
if (cfg.Username != "") {
username = cfg.Username
} else {
// Prompt user for username.
prompt = "\nEnter your username"
username, err = promptUsername(prompt)
if err != nil {
return err
}
cfg.Username = username
}
// Ascertain the address generation seed. This will either be an
// automatically generated value the user has already confirmed or a value
// the user has entered which has already been validated.
seed, err := promptConsoleSeed()
if err != nil {
return err
}
// Prompt for the private passphrase for the data store.
prompt = "\nEnter passphrase for the data store"
for {
storePass, err = promptConsolePass(prompt, true)
if err != nil {
return err
}
if cfg.PlaintextDB || storePass != nil {
break
}
}
// Intialize key manager with seed.
kmgr, err := keymgr.New(seed)
if err != nil {
return err
}
// Create the data store.
fmt.Println("Creating the data store...")
load, err := store.Open(cfg.storePath)
if err != nil {
return fmt.Errorf("Failed to create data store: %v", err)
}
s, _, _, err := load.Construct(storePass)
if err != nil {
return fmt.Errorf("Failed to create data store: %v", err)
}
user, err := s.NewUser(username)
if err != nil {
return err
}
err = email.InitializeUser(user, kmgr, cfg.GenKeys)
if err != nil {
return err
}
fmt.Println("The data store has successfully been created with default mailboxes.")
err = load.Close()
if err != nil {
return err
}
// Prompt for the private passphrase for the key file.
prompt = "Enter passphrase for the key file"
for {
keyfilePass, err = promptConsolePass(prompt, true)
if err != nil {
return err
}
if cfg.PlaintextDB || keyfilePass != nil {
break
}
}
// Create the key file.
fmt.Println("\nCreating the key file...")
// Save key file to disk with the specified passphrase, if one was given.
saveKeyfile(kmgr, cfg.keyfilePath, keyfilePass)
fmt.Println("Keyfile saved.")
return nil
}
// openDatabases returns an instance of keymgr.Manager, and store.Store based on
// the configuration.
func openDatabases(cfg *config) (*keymgr.Manager,
*store.Store, *store.PowQueue, *store.PKRequests, error) {
// Read key file.
keyFile, err := ioutil.ReadFile(cfg.keyfilePath)
if err != nil {
return nil, nil, nil, nil, err
}
var kmgr *keymgr.Manager
if cfg.PlaintextDB { // If allowed, check for plaintext key file.
// Attempt to load unencrypted key file.
kmgr, err = keymgr.FromPlaintext(bytes.NewBuffer(keyFile))
if err != nil {
return nil, nil, nil, nil, err
}
}
if kmgr == nil {
// Read key file passphrase from console.
keyfilePass, err := promptKeyfilePassPhrase()
if err != nil {
return nil, nil, nil, nil, err
}
// Create an instance of key manager.
kmgr, err = keymgr.FromEncrypted(keyFile, keyfilePass)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("Failed to create key manager: %v", err)
}
cfg.keyfilePass = keyfilePass
}
load, err := store.Open(cfg.storePath)
if err != nil {
return nil, nil, nil, nil, err
}
var dstore *store.Store
var q *store.PowQueue
var pk *store.PKRequests
if cfg.PlaintextDB && !load.IsEncrypted() {
dstore, q, pk, err = load.Construct(nil)
} else {
// Read store passphrase from console.
storePass, err := promptStorePassPhrase()
if err != nil {
return nil, nil, nil, nil, err
}
// Open store.
dstore, q, pk, err = load.Construct(storePass)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("Failed to open data store: %v", err)
}
}
return kmgr, dstore, q, pk, nil
}
// importKeyfile is used to import a keys.dat file from PyBitmessage. It adds
// private keys to the key manager.
func importKeyfile(kmgr *keymgr.Manager, file string) error {
b, err := ioutil.ReadFile(file)
if err != nil {
return err
}
keys := kmgr.ImportKeys(b)
if keys == nil {
return errors.New("Could not read file.")
}
for addr, name := range keys {
fmt.Printf("Imported address %s %s\n", addr, name)
}
return nil
}