UNPKG

2.31 kBJavaScriptView Raw
1var fs = require('fs')
2 , path = require('path')
3 , request = require('micro-request')
4 , libPubkey = require('../lib/pubkey')
5 , prompt = require('cli-prompt')
6
7module.exports = function (input, options) {
8 var outPath = path.join(options.parent.wallet, 'imported_keys')
9 if (input.indexOf('http') === 0) {
10 request(input, function (err, resp, body) {
11 if (err) throw err
12 if (resp.statusCode !== 200) throw new Error('non-200 status from remote: ' + resp.statusCode)
13 if (Buffer.isBuffer(body)) body = body.toString('utf8')
14 var pubkey = libPubkey.parse(body)
15 withPubkey(pubkey)
16 })
17 return
18 }
19 try {
20 var stat = fs.statSync(input)
21 var str = fs.readFileSync(input, {encoding: 'utf8'})
22 var pubkey = libPubkey.parse(str)
23 withPubkey(pubkey)
24 }
25 catch (e) {
26 if (e.code === 'ENOENT') {
27 var pubkey = libPubkey.parse(input)
28 return withPubkey(pubkey)
29 }
30 throw e
31 }
32 function withPubkey (pubkey) {
33 prompt.multi([
34 {
35 label: 'Enter name',
36 key: 'name',
37 default: pubkey.name
38 },
39 {
40 label: 'Enter email',
41 key: 'email',
42 default: pubkey.email
43 }
44 ], function (info) {
45 pubkey.name = info.name
46 pubkey.email = info.email
47 var walletDir = options.parent.wallet
48 var inFile = path.join(walletDir, 'imported_keys')
49 var str
50 try {
51 str = fs.readFileSync(inFile, {encoding: 'utf8'})
52 }
53 catch (e) {
54 str = ''
55 }
56 var lines = (str || '').trim().split('\n').filter(function (line) {
57 return !!line.trim()
58 })
59 var goodKeys = []
60 lines.forEach(function (line) {
61 try {
62 var thisPubkey = libPubkey.parse(line.trim())
63 }
64 catch (e) {
65 return
66 }
67 if (thisPubkey.verifyPk.toString('hex') !== pubkey.verifyPk.toString('hex') && thisPubkey.email !== pubkey.email) {
68 goodKeys.push(thisPubkey)
69 }
70 })
71 goodKeys.push(pubkey)
72 var goodLines = goodKeys.map(function (pubkey) {
73 return pubkey.toString()
74 })
75 fs.writeFileSync(inFile, goodLines.join('\n'), {mode: parseInt('0600', 8)})
76 console.log('Imported OK: ' + pubkey.toString(true))
77 }, function (err) {
78 throw err
79 })
80 }
81}
\No newline at end of file