Skip to content

Commit

Permalink
feat<descriptor>: added key derivation functions in KeyProvider class
Browse files Browse the repository at this point in the history
  • Loading branch information
Vasu-08 committed Jul 30, 2023
1 parent 014a104 commit ca83bdd
Showing 1 changed file with 100 additions and 1 deletion.
101 changes: 100 additions & 1 deletion lib/descriptor/keyprovider.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,24 @@ class KeyProvider {
hasPrivateKey() {
return this.ring.privateKey !== null;
}

/**
* Get the public key
* @returns {Buffer}
*/

getPublicKey() {
return this.ring.publicKey;
}

/**
* Get the private key (if available)
* @returns {Buffer}
*/

getPrivateKey() {
return this.ring.privateKey;
}
}

/**
Expand Down Expand Up @@ -407,6 +425,87 @@ class HDKeyProvider extends KeyProvider {
}
return null;
}

/**
* Derive private key at a given position..
* @returns {HDPrivateKey}
*/

getHDPrivateKey(pos) {
assert(
this.hdkey.privateKey,
'Private key not available for hardened derivation.'
);

let childkey = this.hdkey;

if (this.path.length > 0) {
const path = 'm' + HD.common.format(this.path, this.hardenedMarker);
childkey = childkey.derivePath(path);
}

if (this.type === deriveType.UNHARDENED) {
childkey = childkey.derive(pos, false);
} else if (this.type === deriveType.HARDENED) {
childkey = childkey.derive(pos, true);
}

return childkey;
}

/**
* Derive public key at a given position
* @param {Number} pos
* @returns {HDPublicKey}
*/

getHDPublicKey(pos) {
if (this.isHardened()) {
const childprivkey = this.getHDPrivateKey(pos);
return childprivkey.toPublic();
}

let childkey = this.hdkey;

if (this.hdkey instanceof HD.PrivateKey) {
childkey = this.hdkey.toPublic();
}

if (this.path.length > 0) {
const path = 'm' + HD.common.format(this.path, this.hardenedMarker);
childkey = childkey.derivePath(path);
}

if (this.type === deriveType.UNHARDENED) {
childkey = childkey.derive(pos);
}

assert(this.type !== deriveType.HARDENED);

return childkey;
}

/**
* Get public key at a given position
* @param {Number} pos
* @returns {Buffer} public key
*/

getPublicKey(pos) {
const hdkey = this.getHDPublicKey(pos);
return hdkey.publicKey;
}

/**
* Get private key at a given position
* @param {Number} pos
* @returns {Buffer} private key
*/

getPrivateKey(pos) {
const hdkey = this.getHDPrivateKey(pos);
return hdkey.privateKey;
}
}

/**
Expand All @@ -424,7 +523,7 @@ function getHardenedMarker(path) {

let hardenedMarker = null;
for (const p of path) {
const last = p[p.length - 1];
const last = p[p.length - 1];
if (last === '\'' || last === 'h') {
hardenedMarker = last;
}
Expand Down

0 comments on commit ca83bdd

Please sign in to comment.