-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeysStorage.mjs
43 lines (39 loc) · 1.18 KB
/
keysStorage.mjs
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
import { describe, eq } from "./bitcoin/tests.mjs";
import { bufToHex, parseHexToBuf } from "./bitcoin/utils/arraybuffer-hex.mjs";
import {
encodePrefixedWif as encodePrefixedWif,
parsePrefixedWif,
readPrivateKeyFromWif,
} from "./bitcoin/utils/wif.mjs";
const LOCAL_STORAGE_PRIVATE_KEY_KEY = "bitcoin_wallet_private_key";
export function loadSavedKeysFromStorage() {
const privateKeysString = localStorage.getItem(LOCAL_STORAGE_PRIVATE_KEY_KEY);
if (!privateKeysString) {
return null;
}
if (privateKeysString.startsWith("v2 ")) {
const items = privateKeysString.split(" ").slice(1);
return items.map((item) => parsePrefixedWif(item));
}
const privKeys = privateKeysString
.split(" ")
.map((keyHex) => parseHexToBuf(keyHex));
return privKeys.map((key) => ({
type: /** @type {const} */ ("p2wpkh"),
key: key,
}));
}
/**
*
* @param {ReturnType<typeof parsePrefixedWif>[] | null} keys
*/
export function saveKeysToStorage(keys) {
if (keys === null) {
localStorage.removeItem(LOCAL_STORAGE_PRIVATE_KEY_KEY);
return;
}
localStorage.setItem(
LOCAL_STORAGE_PRIVATE_KEY_KEY,
"v2 " + keys.map((key) => encodePrefixedWif(key)).join(" ")
);
}