Skip to content

Commit 9d4fa0e

Browse files
committed
feat: implement HDKey ID
1 parent 0a9b9b9 commit 9d4fa0e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

dashhd.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
* @prop {HDFingerprint} _fingerprint
77
* @prop {HDFromSeed} fromSeed
88
* @prop {HDFromXKey} fromXKey
9+
* @prop {HDToId} toId
10+
* @prop {HDToIdBytes} toIdBytes
911
* @prop {HDToAddr} toAddr
1012
* @prop {HDToWif} toWif
1113
* @prop {HDToXPrv} toXPrv
@@ -36,6 +38,7 @@
3638
* @prop {HDHasher} ripemd160sum
3739
* @prop {HDHasher} sha256sum
3840
* @prop {HDHasher} sha512hmac
41+
* @prop {HDBase64Url} bytesToBase64Url
3942
* @prop {HDKeyToKey} toPublicKey
4043
*/
4144

@@ -219,6 +222,23 @@ var DashHd = ("object" === typeof module && exports) || {};
219222
return new Uint8Array(sig);
220223
};
221224

225+
/** @type {HDBase64Url} */
226+
Utils.bytesToBase64Url = function (bytes) {
227+
let bins = [];
228+
229+
for (let i = 0; i < bytes.length; i += 1) {
230+
let b = bytes[i];
231+
let s = String.fromCodePoint(b);
232+
bins.push(s);
233+
}
234+
235+
let str = bins.join("");
236+
let b64 = btoa(str);
237+
let b64url = b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
238+
239+
return b64url;
240+
};
241+
222242
/** @type {HDSecureErase} */
223243
Utils.secureErase = function (buf) {
224244
if (!Crypto.getRandomValues) {
@@ -652,6 +672,23 @@ var DashHd = ("object" === typeof module && exports) || {};
652672
return hdkey;
653673
};
654674

675+
DashHd.toId = async function (hdkey) {
676+
let idBytes = await DashHd.toIdBytes(hdkey);
677+
let id = Utils.bytesToBase64Url(idBytes);
678+
679+
return id;
680+
};
681+
682+
DashHd.toIdBytes = async function (hdkey) {
683+
let xpubBytes = await DashHd.toXPubBytes(hdkey);
684+
685+
let hashBuffer = await Crypto.subtle.digest("SHA-256", xpubBytes);
686+
let idBuffer = hashBuffer.slice(0, 8);
687+
let idBytes = new Uint8Array(idBuffer);
688+
689+
return idBytes;
690+
};
691+
655692
DashHd.toPublic = function (_hdkey) {
656693
let hdkey = Object.assign({}, _hdkey);
657694
hdkey.privateKey = null;
@@ -835,6 +872,18 @@ if ("object" === typeof module) {
835872
* @returns {Promise<String>}
836873
*/
837874

875+
/**
876+
* @callback HDToId
877+
* @param {HDKey} hdkey
878+
* @returns {Promise<String>}
879+
*/
880+
881+
/**
882+
* @callback HDToIdBytes
883+
* @param {HDKey} hdkey
884+
* @returns {Promise<Uint8Array>}
885+
*/
886+
838887
/**
839888
* @callback HDToXKeyBytes
840889
* @param {HDKey} hdkey
@@ -878,6 +927,12 @@ if ("object" === typeof module) {
878927
* @returns {Promise<String>}
879928
*/
880929

930+
/**
931+
* @callback HDBase64Url
932+
* @param {Uint8Array} bytes
933+
* @returns {String} - URL-Safe Base64 Encoding
934+
*/
935+
881936
/**
882937
* @callback HDHasher
883938
* @param {Uint8Array} bytes

0 commit comments

Comments
 (0)