-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor deriveXpub to eliminate repetition from crypto providers
- Loading branch information
Showing
4 changed files
with
74 additions
and
98 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
const indexIsHardened = require('./indexIsHardened') | ||
const {derivePublic: deriveChildXpub} = require('cardano-crypto.js') | ||
|
||
function CachedDeriveXpubFactory(derivationScheme, deriveXpubHardenedFn) { | ||
const derivedXpubs = {} | ||
|
||
async function deriveXpub(absDerivationPath) { | ||
const memoKey = JSON.stringify(absDerivationPath) | ||
|
||
if (!derivedXpubs[memoKey]) { | ||
const deriveHardened = | ||
absDerivationPath.length === 0 || indexIsHardened(absDerivationPath.slice(-1)[0]) | ||
|
||
/* | ||
* TODO - reset cache if the promise fails, for now it does not matter | ||
* since a failure (e.g. rejection by user) there leads to | ||
* the creation of a fresh wallet and crypto provider instance | ||
*/ | ||
derivedXpubs[memoKey] = deriveHardened | ||
? deriveXpubHardenedFn(absDerivationPath) | ||
: deriveXpubNonhardenedFn(absDerivationPath) | ||
} | ||
|
||
/* | ||
* the derivedXpubs map stores promises instead of direct results | ||
* to deal with concurrent requests to derive the same xpub | ||
*/ | ||
return await derivedXpubs[memoKey] | ||
} | ||
|
||
async function deriveXpubNonhardenedFn(derivationPath) { | ||
const lastIndex = derivationPath.slice(-1)[0] | ||
const parentXpub = await deriveXpub(derivationPath.slice(0, -1)) | ||
|
||
return deriveChildXpub(parentXpub, lastIndex, derivationScheme.number) | ||
} | ||
|
||
return deriveXpub | ||
} | ||
|
||
module.exports = CachedDeriveXpubFactory |