/
createwallet.component.ts
297 lines (255 loc) · 8.25 KB
/
createwallet.component.ts
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
import {
Component, Inject, forwardRef, ViewChild, ElementRef, ComponentRef, HostListener,
OnDestroy
} from '@angular/core';
import { Log } from 'ng2-logger';
import { MatDialogRef } from '@angular/material';
import { PasswordComponent } from '../shared/password/password.component';
import { IPassword } from '../shared/password/password.interface';
import { slideDown } from '../../core-ui/core.animations';
import { ModalsService } from '../modals.service';
import { PassphraseComponent } from './passphrase/passphrase.component';
import { PassphraseService } from './passphrase/passphrase.service';
import { StateService } from '../../core/core.module';
import { SnackbarService } from '../../core/snackbar/snackbar.service';
@Component({
selector: 'modal-createwallet',
templateUrl: './createwallet.component.html',
styleUrls: ['./createwallet.component.scss'],
animations: [slideDown()]
})
export class CreateWalletComponent implements OnDestroy {
log: any = Log.create('createwallet.component');
step: number = 0;
isRestore: boolean = false;
name: string;
isCrypted: boolean = false;
@ViewChild('nameField') nameField: ElementRef;
password: string = '';
passwordVerify: string = '';
words: string[];
toggleShowPass: boolean = false;
@ViewChild('passphraseComponent')
passphraseComponent: ComponentRef<PassphraseComponent>;
@ViewChild('passwordElement') passwordElement: PasswordComponent;
@ViewChild('passwordElementVerify') passwordElementVerify: PasswordComponent;
@ViewChild('passwordRestoreElement') passwordRestoreElement: PasswordComponent;
// Used for verification
private wordsVerification: string[];
private validating: boolean = false;
errorString: string = '';
private destroyed: boolean = false;
constructor (
@Inject(forwardRef(() => ModalsService))
private _modalsService: ModalsService,
private _passphraseService: PassphraseService,
private state: StateService,
private flashNotification: SnackbarService,
private dialogRef: MatDialogRef<CreateWalletComponent>
) {
this.reset();
}
ngOnDestroy() {
this.destroyed = true;
}
reset(): void {
this._modalsService.enableClose = true;
this.state.set('modal:fullWidth:enableClose', true);
this.words = Array(24).fill('');
this.isRestore = false;
this.name = '';
this.password = '';
this.passwordVerify = '';
this.errorString = '';
this.step = 0;
this.state.observe('encryptionstatus')
.takeWhile(() => !this.destroyed)
.subscribe(status => this.isCrypted = status !== 'Unencrypted');
}
initialize(type: number): void {
this.reset();
switch (type) {
case 0: // Encrypt wallet
this.dialogRef.close();
this._modalsService.open('encrypt', {forceOpen: true});
return;
case 1: // Create
break;
case 2: // Restore
this.isRestore = true;
break;
}
this.nextStep();
}
nextStep(): void {
this.validating = true;
/* Recovery password entered */
if (this.step === 2) {
this.passwordElement.sendPassword();
this.passwordElementVerify.sendPassword();
return;
}
if (this.validate()) {
this.validating = false;
this.step++;
this.doStep();
}
this.log.d(`moving to step: ${this.step}`);
}
prevStep(): void {
this.step--;
this.errorString = '';
this.doStep();
}
doStep(): void {
switch (this.step) {
case 1:
setTimeout(() => this.nameField.nativeElement.focus(this), 1);
break;
case 2:
if (this.isRestore) {
this.step = 4;
}
this.password = undefined;
this.passwordVerify = undefined;
break;
case 3:
this._passphraseService.generateMnemonic(
this.mnemonicCallback.bind(this), this.password
);
this.flashNotification.open(
'Please remember to write down your recovery passphrase',
'warning');
break;
case 4:
while (this.words.reduce((prev, curr) => prev + +(curr === ''), 0) < 5) {
const k = Math.floor(Math.random() * 23);
this.words[k] = '';
}
this.flashNotification.open(
'Did you write your password at the previous step ?',
'warning');
break;
case 5:
this.step = 4;
this.errorString = '';
if (this.state.get('locked')) {
// unlock wallet
this.step = 6
} else {
// wallet already unlocked
this.importMnemonicSeed();
}
break;
}
this._modalsService.enableClose = (this.step === 0);
this.state.set('modal:fullWidth:enableClose', (this.step === 0));
}
private mnemonicCallback(response: Object): void {
const words = response['mnemonic'].split(' ');
if (words.length > 1) {
this.words = words;
}
this.wordsVerification = Object.assign({}, this.words);
this.log.d(`word string: ${this.words.join(' ')}`);
}
public importMnemonicSeed(): void {
this.state.set('ui:spinner', true);
this._passphraseService.importMnemonic(this.words, this.password)
.subscribe(
success => {
this._passphraseService.generateDefaultAddresses();
this.step = 5;
this.state.set('ui:walletInitialized', true);
this.state.set('ui:spinner', false);
this.log.i('Mnemonic imported successfully');
},
error => {
this.step = 4;
this.log.er(error);
this.errorString = error.message;
this._modalsService.enableClose = true;
this.state.set('ui:spinner', false);
this.state.set('modal:fullWidth:enableClose', true);
this.log.er('Mnemonic import failed');
});
}
validate(): boolean {
if (this.validating && this.step === 1) {
return !!this.name;
}
if (this.validating && this.step === 4 && !this.isRestore) {
const valid = !this.words.filter(
(value, index) => this.wordsVerification[index] !== value).length;
this.errorString = valid ? '' : 'You have entered an invalid recovery phrase';
return valid;
}
return true;
}
/**
* Returns how many words were entered in passphrase component.
*/
getCountOfWordsEntered(): number {
const count = this.words.filter((value: string) => value).length;
this.log.d(`allWordsEntered() ${count} were entered!`);
return count;
}
/**
* Trigger password emit from restore password component
* Which in turn will trigger the next step (see html)
*/
restoreWallet(): void {
this.passwordRestoreElement.sendPassword();
}
/** Triggered when the password is emitted from PasswordComponent */
passwordFromEmitter(pass: IPassword, verify?: boolean) {
this[verify ? 'passwordVerify' : 'password'] = pass.password;
this.log.d(`passwordFromEmitter: ${this.password} ${verify}`);
if (!!this[verify ? 'password' : 'passwordVerify']
|| this.password === '' && this.passwordVerify === ''
|| this.password === undefined && this.passwordVerify === undefined) {
this.verifyPasswords();
}
}
/** Triggered when showPassword is emitted from PasswordComponent */
showPasswordToggle(show: boolean) {
this.toggleShowPass = show;
}
/** verify if passwords match */
verifyPasswords() {
if (!this.validating) {
return;
}
if (this.password !== this.passwordVerify) {
this.flashNotification.open('Passwords Do Not Match!', 'warning');
} else {
// We should probably make this a function because it isn't reusing code??
this.validating = false;
this.step++;
this.doStep();
}
this.passwordVerify = undefined;
}
/** Triggered when the password is emitted from PassphraseComponent */
wordsFromEmitter(words: string): void {
this.words = words.split(',');
}
close(): void {
this.reset();
document.body.dispatchEvent(
new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
}
public countWords (count: number): boolean {
if ([12, 15, 18, 24].indexOf(count) !== -1) {
return false;
}
return true;
}
// capture the enter button
@HostListener('window:keydown', ['$event'])
keyDownEvent(event: any) {
if (event.keyCode === 13) {
this.nextStep();
}
}
}