-
Notifications
You must be signed in to change notification settings - Fork 100
/
ImportKeys.jsx
672 lines (605 loc) · 27.5 KB
/
ImportKeys.jsx
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import React, {Component, PropTypes} from "react";
import PrivateKey from "ecc/key_private";
import Address from "ecc/address"
import Aes from "ecc/aes";
import alt from "alt-instance"
import connectToStores from "alt/utils/connectToStores"
import cname from "classnames"
import config from "chain/config";
import notify from "actions/NotificationActions";
import hash from "common/hash";
import Apis from "rpc_api/ApiInstances"
import PrivateKeyStore from "stores/PrivateKeyStore"
import WalletUnlockActions from "actions/WalletUnlockActions"
import WalletCreate from "components/Wallet/WalletCreate"
import LoadingIndicator from "components/LoadingIndicator"
import Translate from "react-translate-component";
import BalanceClaimActiveActions from "actions/BalanceClaimActiveActions"
import BalanceClaimAssetTotal from "components/Wallet/BalanceClaimAssetTotal"
import WalletDb from "stores/WalletDb";
import ImportKeysStore from "stores/ImportKeysStore"
import PublicKey from "ecc/key_public";
import GenesisFilter from "chain/GenesisFilter"
require("./ImportKeys.scss");
var import_keys_assert_checking = false
@connectToStores
export default class ImportKeys extends Component {
constructor() {
super();
this.state = this._getInitialState();
}
static getStores() {
return [ImportKeysStore]
}
static getPropsFromStores() {
return {
importing: ImportKeysStore.getState().importing
}
}
_getInitialState(keep_file_name = false) {
return {
keys_to_account: { },
no_file: true,
account_keys: [],
//brainkey: null,
//encrypted_brainkey: null,
reset_file_name: keep_file_name ? this.state.reset_file_name : Date.now(),
reset_password: Date.now(),
password_checksum: null,
import_file_message: null,
import_password_message: null,
imported_keys_public: {},
key_text_message: null,
genesis_filtering: false,
genesis_filter_status: [],
genesis_filter_finished: undefined
};
}
reset(e, keep_file_name) {
if(e) e.preventDefault()
var state = this._getInitialState(keep_file_name);
this.setState(state, ()=> this.updateOnChange());
}
render() {
var keys_to_account = this.state.keys_to_account
var key_count = Object.keys(keys_to_account).length
var account_keycount = this.getImportAccountKeyCount(keys_to_account)
// Create wallet prior to the import keys (keeps layout clean)
if( ! WalletDb.getWallet()) return <WalletCreate hideTitle={true}/>
if( this.props.importing ) {
return <div>
<h3><Translate content="wallet.import_keys" /></h3>
<div className="center-content">
<LoadingIndicator type="circle"/>
</div>
</div>
}
var filtering = this.state.genesis_filtering
var was_filtered = !!this.state.genesis_filter_status.length && this.state.genesis_filter_finished
var account_rows = null
if(this.state.genesis_filter_status.length) {
account_rows = []
for(let status of this.state.genesis_filter_status) {
account_rows.push(
<tr key={status.account_name}>
<td>{status.account_name}</td>
<td>{filtering ?
<span>Filtering { Math.round( (status.count / status.total) * 100) } % </span>
: <span>Keeping {status.count} of {status.total}</span>
}</td>
</tr>
)
}
}
var import_ready = key_count !== 0
var password_placeholder = "Enter import file password"
if (import_ready) password_placeholder = ""
if( ! account_rows && account_keycount) {
account_rows = [];
for (let account_name in account_keycount) {
account_rows.push(
<tr key={account_name}>
<td>{account_name}</td>
<td>{account_keycount[account_name]}</td>
</tr>);
}
}
return (
<div>
<h3><Translate content="wallet.import_keys" /></h3>
{/* Key file upload */}
<div>
<span>{this.state.key_text_message ?
this.state.key_text_message :
<KeyCount key_count={key_count}/>
}</span>
{ ! import_ready ?
null :
<span> (<a onClick={this.reset.bind(this)}>reset</a>)</span>
}
</div>
{ account_rows ?
<div>
{ ! account_rows.length ? "No Accounts" :
<div>
<table className="table center-content">
<thead>
<tr>
<th style={{textAlign: "center"}}>Account</th>
<th style={{textAlign: "center"}}># of keys</th>
</tr>
</thead>
<tbody>
{account_rows}
</tbody>
</table>
<br/>
</div>}
</div> : null}
<br/>
{ ! import_ready ?
<div>
<div className="center-content">
<div>
<div>
<label>BTS 0.9.x key export file
{this.state.no_file ? null : <span>
(<a onClick={this.reset.bind(this)}>Reset</a>)</span>}
</label>
<input
type="file" id="file_input"
style={{ border: 'solid' }}
key={this.state.reset_file_name}
onChange={this.upload.bind(this)} />
<div>{this.state.import_file_message}</div>
</div>
{ this.state.no_file ? <span>
<br/><br/>
<div>
<label>Paste Private keys (Wallet Import Format - WIF)</label>
<input type="password" onChange={this.onWif.bind(this)} id="wif" />
</div>
</span>:null}
</div>
<br/>
{ ! this.state.no_file ?
(<div>
<input
type="password" ref="password" autoComplete="off"
key={this.state.reset_password}
placeholder={password_placeholder}
onChange={this._passwordCheck.bind(this)}
/>
<div>{this.state.import_password_message}</div>
</div>) : null}
<br/>
<a href className="button success" onClick={this.onBack.bind(this)}>
Cancel </a>
</div>
</div> : null}
{ this.state.genesis_filter_initalizing ? <div>
<div className="center-content">
<LoadingIndicator type="circle"/>
</div>
</div>:null}
{ import_ready ?
<div>
<h4 className="center-content">Unclaimed balances belonging to these keys:</h4>
<div className="grid-block center-content">
<div className="grid-content no-overflow">
<label>Asset Totals</label>
<BalanceClaimAssetTotal />
</div>
</div>
<br/>
<div className="center-content" style={{width: "100%"}}>
<div className="button-group content-block">
<a href className={cname("button success", {disabled:!import_ready})}
onClick={this._saveImport.bind(this)} >
Import
</a>
<a href className="button secondary" onClick={this.reset.bind(this)}>
Cancel
</a>
</div>
</div>
</div> : null}
</div>
);
}
onWif(event) {
var value = event.target.value
this.addByPattern(value)
}
onBack(e) {
if(e) e.preventDefault()
window.history.back()
}
updateOnChange() {
BalanceClaimActiveActions.setPubkeys(Object.keys(this.state.imported_keys_public))
}
getImportAccountKeyCount(keys_to_account) {
var account_keycount = {}
var found = false
for(let key in keys_to_account)
for(let account_name of keys_to_account[key].account_names) {
account_keycount[account_name] =
(account_keycount[account_name] || 0) + 1
found = true
}
return found ? account_keycount : null
}
upload(evt) {
this.reset(null, true)
var file = evt.target.files[0]
var reader = new FileReader()
reader.onload = evt => {
var contents = evt.target.result
try {
var json_contents
try {
json_contents = JSON.parse(contents)
// This is the only chance to encounter a large file,
// try this format first.
this._parseImportKeyUpload(json_contents, file.name, update_state => {
// console.log("update_state", update_state)
this.setState(update_state, ()=> {
if( update_state.genesis_filter_finished ) {
// try empty password, also display "Enter import file password"
this._passwordCheck()
}
})
})
} catch(e) {
//DEBUG console.log("... _parseImportKeyUpload",e)
try {
if( ! json_contents) file.name + " is an unrecognized format"
this._parseWalletJson(json_contents)
} catch(ee) {
if( ! this.addByPattern(contents))
throw ee
}
// try empty password, also display "Enter import file password"
this._passwordCheck()
}
} catch(message) {
console.error("... ImportKeys upload error", message)
this.setState({import_file_message: message})
}
}
reader.readAsText(file)
}
/** BTS 1.0 client wallet_export_keys format. */
_parseImportKeyUpload(json_contents, file_name, update_state) {
var password_checksum, unfiltered_account_keys
try {
password_checksum = json_contents.password_checksum
if( ! password_checksum)
throw file_name + " is an unrecognized format"
if( ! Array.isArray(json_contents.account_keys))
throw file_name + " is an unrecognized format"
unfiltered_account_keys = json_contents.account_keys
} catch(e) { throw e.message || e }
// BTS 1.0 wallets may have a lot of generated but unused keys or spent TITAN addresses making
// wallets so large it is was not possible to use the JavaScript wallets with them.
var genesis_filter = new GenesisFilter
if( ! genesis_filter.isAvailable() ) {
update_state({ password_checksum, account_keys: unfiltered_account_keys,
genesis_filter_finished: true, genesis_filtering: false })
return
}
genesis_filter.init(()=> {
var filter_status = this.state.genesis_filter_status
// FF < version 41 does not support worker threads internals (like blob urls)
// var GenesisFilterWorker = require("worker!workers/GenesisFilterWorker")
// var worker = new GenesisFilterWorker
// worker.postMessage({
// account_keys: unfiltered_account_keys,
// bloom_filter: genesis_filter.bloom_filter
// })
// worker.onmessage = event => { try {
// var { status, account_keys } = event.data
// // ...
// } catch( e ) { console.error('GenesisFilterWorker', e) }}
var account_keys = unfiltered_account_keys
genesis_filter.filter( account_keys, status => {
console.log("import filter", status)
if( status.error === "missing_public_keys" ) {
console.error("un-released format, just for testing")
update_state({ password_checksum, account_keys: unfiltered_account_keys,
genesis_filter_finished: true, genesis_filtering: false })
return
}
if( status.success ) {
// var { account_keys } = event.data // if using worker thread
update_state({ password_checksum, account_keys,
genesis_filter_finished: true, genesis_filtering: false })
return
}
if( status.initalizing !== undefined ) {
update_state({ genesis_filter_initalizing: status.initalizing, genesis_filtering: true })
return
}
if( status.importing === undefined ) {
// programmer error
console.error('unknown status', status)
return
}
if( ! filter_status.length )
// first account
filter_status.push( status )
else {
var last_account_name = filter_status[filter_status.length - 1].account_name
if( last_account_name === status.account_name )
// update same account
filter_status[filter_status.length - 1] = status
else
// new account
filter_status.push( status )
}
update_state({ genesis_filter_status: filter_status })
})
})
}
/**
BTS 1.0 hosted wallet backup (wallet.bitshares.org) is supported.
BTS 1.0 native wallets should use wallet_export_keys instead of a wallet backup.
Note, Native wallet backups will be rejected. The logic below does not
capture assigned account names (for unregisted accounts) and does not capture
signing keys. The hosted wallet has only registered accounts and no signing
keys.
*/
_parseWalletJson(json_contents) {
var password_checksum
var encrypted_brainkey
var address_to_enckeys = {}
var account_addresses = {}
var savePubkeyAccount = function (pubkey, account_name) {
//replace BTS with GPH
pubkey = config.address_prefix + pubkey.substring(3)
var address = PublicKey.fromPublicKeyString(pubkey).toAddressString()
var addresses = account_addresses[account_name] || []
address = "BTS" + address.substring(3)
//DEBUG console.log("... address",address,account_name)
addresses.push(address)
account_addresses[account_name] = addresses
}
try {
if(! Array.isArray(json_contents)) {
//DEBUG console.log('... json_contents',json_contents)
throw new Error("Invalid wallet format")
}
for(let element of json_contents) {
if( "key_record_type" == element.type &&
element.data.account_address &&
element.data.encrypted_private_key
) {
var address = element.data.account_address
var enckeys = address_to_enckeys[address] || []
enckeys.push(element.data.encrypted_private_key)
//DEBUG console.log("... address",address,enckeys)
address_to_enckeys[address] = enckeys
continue
}
if( "account_record_type" == element.type) {
var account_name = element.data.name
savePubkeyAccount(element.data.owner_key, account_name)
for(let history of element.data.active_key_history) {
savePubkeyAccount(history[1], account_name)
}
continue
}
if ( "property_record_type" == element.type &&
"encrypted_brainkey" == element.data.key
) {
encrypted_brainkey = element.data.value
continue
}
if( "master_key_record_type" == element.type) {
if( ! element.data)
throw file.name + " invalid master_key_record record"
if( ! element.data.checksum)
throw file.name + " is missing master_key_record checksum"
password_checksum = element.data.checksum
}
}
if( ! encrypted_brainkey)
throw "Please use a BTS 1.0 wallet_export_keys file instead"
if( ! password_checksum)
throw file.name + " is missing password_checksum"
if( ! enckeys.length)
throw file.name + " does not contain any private keys"
} catch(e) { throw e.message || e }
var account_keys = []
for(let account_name in account_addresses) {
var encrypted_private_keys = []
for(let address of account_addresses[account_name]) {
var enckeys = address_to_enckeys[address]
if( ! enckeys) continue
for(let enckey of enckeys)
encrypted_private_keys.push(enckey)
}
account_keys.push({
account_name,
encrypted_private_keys
})
}
// We could prompt for this brain key instead on first use. The user
// may already have a brainkey at this point so with a single brainkey
// wallet we can't use it now.
this.setState({
password_checksum,
account_keys
//encrypted_brainkey
})
}
_passwordCheck(evt) {
var pwNode = React.findDOMNode(this.refs.password)
if(pwNode) pwNode.focus()
var password = evt ? evt.target.value : ""
var checksum = this.state.password_checksum
var new_checksum = hash.sha512(hash.sha512(password)).toString("hex")
if(checksum != new_checksum) {
this.setState({no_file: false,
import_password_message: "Enter import file password"
+ (password != "" ? " (keep going)":"") })
return
}
this.setState({
no_file: false,
reset_password: Date.now(),
import_password_message: "Password matches. Loading..."
}, ()=> this._decryptPrivateKeys(password))
// setTimeout(, 250)
}
_decryptPrivateKeys(password) {
var password_aes = Aes.fromSeed(password)
var format_error1_once = true
for(let account of this.state.account_keys) {
if(! account.encrypted_private_keys) {
var error = `Account ${account.account_name} missing encrypted_private_keys`
console.error(error)
if(format_error1_once) {
notify.error(error)
format_error1_once = false
}
continue
}
var account_name = account.account_name.trim()
var same_prefix_regex = new RegExp("^" + config.address_prefix)
for(let i = 0; i < account.encrypted_private_keys.length; i++) {
let encrypted_private = account.encrypted_private_keys[i]
let public_key_string = account.public_keys ?
account.public_keys[i] : null // performance gain
try {
var private_plainhex = password_aes.decryptHex(encrypted_private)
if(import_keys_assert_checking && public_key_string) {
var private_key = PrivateKey.fromHex( private_plainhex )
var pub = private_key.toPublicKey() // S L O W
var addy = pub.toAddressString()
var pubby = pub.toPublicKeyString()
var error = ""
let address_string = account.addresses ?
account.addresses[i] : null // assert checking
if(address_string && addy.substring(3) != address_string.substring(3))
error = "address imported " + address_string + " but calculated " + addy + ". "
if(pubby.substring(3) != public_key_string.substring(3))
error += "public key imported " + public_key_string + " but calculated " + pubby
if(error != "")
console.log("ERROR Miss-match key",error)
}
if( ! public_key_string) {
var private_key = PrivateKey.fromHex( private_plainhex )
var public_key = private_key.toPublicKey()// S L O W
public_key_string = public_key.toPublicKeyString()
} else {
if( ! same_prefix_regex.test(public_key_string))
// This was creating a unresponsive chrome browser
// but after the results were shown. It was probably
// caused by garbage collection.
public_key_string = config.address_prefix +
public_key_string.substring(3)
}
this.state.imported_keys_public[public_key_string] = true
var {account_names} = this.state.keys_to_account[private_plainhex] ||
{account_names: []}
var dup = false
for(let _name of account_names)
if(_name == account_name)
dup = true
if(dup) continue
account_names.push(account_name)
this.state.keys_to_account[private_plainhex] = {account_names, public_key_string}
} catch(e) {
console.log(e, e.stack)
var message = e.message || e
notify.error(`Account ${account_name} had a private key import error: `+message)
}
}
}
//var enc_brainkey = this.state.encrypted_brainkey
//if(enc_brainkey){
// this.setState({
// brainkey: password_aes.decryptHexToText(enc_brainkey)
// })
//}
this.setState({
import_file_message: null,
import_password_message: null,
password_checksum: null
}, ()=> this.updateOnChange())
}
_saveImport(e) {
e.preventDefault()
var keys = PrivateKeyStore.getState().keys
for(let public_key_string in this.state.imported_keys_public) {
if(keys.get(public_key_string)) {
notify.error("This wallet has already been imported")
return
}
}
WalletUnlockActions.unlock().then(()=> {
ImportKeysStore.importing(true)
// show the loading indicator
setTimeout(()=> this.saveImport(), 200)
})
}
saveImport() {
var keys_to_account = this.state.keys_to_account
var private_key_objs = []
for(let private_plainhex of Object.keys(keys_to_account)) {
var {account_names, public_key_string} = keys_to_account[private_plainhex]
private_key_objs.push({
private_plainhex,
import_account_names: account_names,
public_key_string
})
}
this.reset()
WalletDb.importKeysWorker( private_key_objs ).then( result => {
ImportKeysStore.importing(false)
var import_count = private_key_objs.length
notify.success(`Successfully imported ${import_count} keys.`)
this.onBack() // back to claim balances
}).catch( error => {
console.log("error:", error)
ImportKeysStore.importing(false)
var message = error
try { message = error.target.error.message } catch (e){}
notify.error(`Key import error: ${message}`)
})
}
addByPattern(contents) {
if( ! contents)
return false
var count = 0, invalid_count = 0
var wif_regex = /5[HJK][1-9A-Za-z]{49}/g
for(let wif of contents.match(wif_regex) || [] ) {
try {
var private_key = PrivateKey.fromWif(wif) //could throw and error
var private_plainhex = private_key.toBuffer().toString('hex')
var public_key = private_key.toPublicKey() // S L O W
var public_key_string = public_key.toPublicKeyString()
this.state.imported_keys_public[public_key_string] = true
this.state.keys_to_account[private_plainhex] = {
account_names: [], public_key_string}
count++
} catch(e) { invalid_count++ }
}
this.setState({
key_text_message: 'Found ' +
(!count ? "" : count + " valid") +
(!invalid_count ? "" : " and " + invalid_count + " invalid") +
" key" + ( count > 1 || invalid_count > 1 ? "s" : "") + "."
}, ()=> this.updateOnChange())
// removes the message on the next render
this.state.key_text_message = null
return count
}
}
class KeyCount extends Component {
render() {
if( !this.props.key_count) return <span/>
return <span>Found {this.props.key_count} private keys</span>
}
}