aboutsummaryrefslogtreecommitdiff
path: root/libs/stellar-util/stellar-util.js
diff options
context:
space:
mode:
Diffstat (limited to 'libs/stellar-util/stellar-util.js')
-rw-r--r--libs/stellar-util/stellar-util.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/libs/stellar-util/stellar-util.js b/libs/stellar-util/stellar-util.js
new file mode 100644
index 0000000..1922d5c
--- /dev/null
+++ b/libs/stellar-util/stellar-util.js
@@ -0,0 +1,48 @@
1const createHmac = require('create-hmac');
2const StellarBase = require('stellar-base');
3
4window.stellarUtil = {
5
6 HARDENED_OFFSET: 0x80000000,
7 ED25519_CURVE: 'ed25519 seed',
8
9 replaceDerive: (val) => val.replace("'", ''),
10
11 getMasterKeyFromSeed: function (seed) {
12 const hmac = createHmac('sha512', this.ED25519_CURVE);
13 const I = hmac.update(Buffer.from(seed, 'hex')).digest();
14 const IL = I.slice(0, 32);
15 const IR = I.slice(32);
16 return {
17 key: IL,
18 chainCode: IR,
19 };
20 },
21
22 CKDPriv: ({key, chainCode}, index) => {
23 const indexBuffer = Buffer.allocUnsafe(4);
24 indexBuffer.writeUInt32BE(index, 0);
25 const data = Buffer.concat([Buffer.alloc(1, 0), key, indexBuffer]);
26 const I = createHmac('sha512', chainCode)
27 .update(data)
28 .digest();
29 const IL = I.slice(0, 32);
30 const IR = I.slice(32);
31 return {
32 key: IL,
33 chainCode: IR,
34 };
35 },
36
37 derivePath: function (path, seed) {
38
39 const {key, chainCode} = this.getMasterKeyFromSeed(seed);
40 const segments = path
41 .split('/')
42 .slice(1)
43 .map(this.replaceDerive)
44 .map(el => parseInt(el, 10));
45 const result = segments.reduce((parentKeys, segment) => this.CKDPriv(parentKeys, segment + this.HARDENED_OFFSET), {key, chainCode});
46 return StellarBase.Keypair.fromRawEd25519Seed(result.key);
47 }
48}