-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
70 lines (62 loc) · 1.68 KB
/
index.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
import fs from 'fs';
import os from 'os';
import path from 'path';
const runCatching = <T>(block: () => T, fallback: T) => {
try {
return block();
} catch {
return fallback;
}
};
interface EOA {
alias: string
address: string
privateKey: string
}
enum State {
FindingAlias,
FindingAddress,
FindingPrivateKey,
}
const throwFormatError = () => { throw new Error('File format error : .blockchain/eoa') };
const getEoaList = () => {
const lines = runCatching(
() => fs.readFileSync(path.join(os.homedir(), '.blockchain/eoa')).toString(),
'',
).split(/\r\n|\r|\n/);
const result: EOA[] = [];
let state = State.FindingAlias;
let alias = '';
let address = '';
for (const l of lines) {
if (l.startsWith('[') && l.endsWith(']')) {
if (state !== State.FindingAlias) {
throwFormatError();
}
alias = l.substring(1, l.length - 1);
state = State.FindingAddress;
} else {
const [a, b] = l.split('=');
if (a === 'address') {
if (state !== State.FindingAddress) {
throwFormatError();
}
address = b;
state = State.FindingPrivateKey;
} else if (a === 'private_key') {
if (state !== State.FindingPrivateKey) {
throwFormatError();
}
result.push({ alias, address, privateKey: b });
state = State.FindingAlias;
}
}
}
if (state !== State.FindingAlias) {
throwFormatError();
}
return result;
}
export const getEoa = (alias: string) => getEoaList().find((eoa) => eoa.alias === alias);
export const getAddress = (alias: string) => getEoa(alias)?.address;
export const getPrivateKey = (alias: string) => getEoa(alias)?.privateKey;