-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover_public_key.mjs
48 lines (41 loc) · 1.31 KB
/
recover_public_key.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
44
45
46
47
48
// @ts-check
import base58_to_binary from "base58-js/base58_to_binary.mjs";
import get_pub from "isomorphic-secp256k1-js/recover_public_key.mjs";
import public_key_to_wif from "./keys/public_key_to_wif.mjs";
/**
* Recovers an Antelope secp256k1 public key from K1 signature.
* @kind function
* @name recover_public_key
* @param {object} Arg Argument
* @param {String} Arg.signature Signature (SIG_K1…).
* @param {String | Uint8Array} Arg.hash hash data that was used to create signature.
* @param {Boolean} [Arg.legacy] Returns the key in the legacy format.
* @returns {Promise<String>} WIF Public key.
*/
export default async function recover_public_key({ signature, hash }) {
let hash_array;
if (typeof hash == "string")
hash_array = Uint8Array.from(
hash.match(/[a-fA-F0-9]{2}/gmu).map((i) => Number(`0x${i}`))
);
else hash_array = hash;
if (!signature?.startsWith("SIG_K1_"))
throw new TypeError("Signature must start with “SIG_K1_”");
const raw_sig = base58_to_binary(signature.replace("SIG_K1_", "")).slice(
0,
-4
);
const v = raw_sig.slice(0, 1)[0] - 31;
const r = raw_sig.slice(1, 33);
const s = raw_sig.slice(33, 65);
return public_key_to_wif(
await get_pub({
hash: hash_array,
signature: {
r,
s,
v,
},
})
);
}