-
Notifications
You must be signed in to change notification settings - Fork 307
feat(sdk-core): add root-fetch detour in getUserPrv for safe child wallets #9488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
s84krish
wants to merge
1
commit into
master
Choose a base branch
from
sibikrishnan/wcn-1200-sdk-multisig-signing-root-fetch-detour-in-getuserprvasync
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| export * from './iSafe'; | ||
| export * from './iSafes'; | ||
| export * from './safe'; | ||
| export * from './safeDerivation'; | ||
| export * from './safes'; |
This file contains hidden or 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,42 @@ | ||
| /** | ||
| * @prettier | ||
| * | ||
| * Shared safe child derivation for mint and sign. | ||
| * Path: m/999999'/<index>' where index is the mint allocation stored on the | ||
| * child key as derivedFromParentWithSeed. | ||
| * | ||
| * Soft deriveKeyWithSeed (m/999999/a/b) must not be used for safe children — | ||
| * it cannot reproduce a hardened key. | ||
| */ | ||
| import { bip32 } from '@bitgo/utxo-lib'; | ||
|
|
||
| /** BIP32 purpose for safe wallet derivation (hardened). */ | ||
| export const SAFE_DERIVATION_PURPOSE = 999999; | ||
|
|
||
| export function getSafeHardenedDerivationPath(index: string | number): string { | ||
| const idx = typeof index === 'number' ? String(index) : index; | ||
| if (!/^\d+$/.test(idx)) { | ||
| throw new Error(`Invalid safe derivation index '${index}': expected a non-negative integer`); | ||
| } | ||
| return `m/${SAFE_DERIVATION_PURPOSE}'/${idx}'`; | ||
| } | ||
|
|
||
| export interface SafeHardenedChildKey { | ||
| prv: string; | ||
| pub: string; | ||
| derivationPath: string; | ||
| } | ||
|
|
||
| /** Hardened BIP32 derive for secp256k1 multisig from a root xprv and mint index. */ | ||
| export function deriveSafeChildHardenedFromXprv(rootXprv: string, index: string | number): SafeHardenedChildKey { | ||
| const derivationPath = getSafeHardenedDerivationPath(index); | ||
| const child = bip32.fromBase58(rootXprv).derivePath(derivationPath); | ||
| if (!child.privateKey) { | ||
| throw new Error(`Failed to derive hardened safe child at ${derivationPath}`); | ||
| } | ||
| return { | ||
| prv: child.toBase58(), | ||
| pub: child.neutered().toBase58(), | ||
| derivationPath, | ||
| }; | ||
| } |
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| export * from './iWallet'; | ||
| export * from './iWallets'; | ||
| export * from './safeKeychain'; | ||
| export * from './wallet'; | ||
| export * from './wallets'; |
This file contains hidden or 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,133 @@ | ||
| /** | ||
| * @prettier | ||
| */ | ||
| import { BitGoBase } from '../bitgoBase'; | ||
| import { decryptKeychainPrivateKey, IKeychains, Keychain, KeychainWithEncryptedPrv } from '../keychain'; | ||
| import { deriveSafeChildHardenedFromXprv } from '../safe/safeDerivation'; | ||
| import { IncorrectPasswordError } from '../errors'; | ||
|
|
||
| export class InvalidRootKeychainSourceError extends Error { | ||
| constructor(id: string, source: string | undefined) { | ||
| super( | ||
| `Root keychain ${id} has source '${source ?? 'unknown'}'; expected 'user'. ` + | ||
| `Using a backup or BitGo root would fail at signing.` | ||
| ); | ||
| this.name = 'InvalidRootKeychainSourceError'; | ||
| } | ||
| } | ||
|
|
||
| /** Thrown when hardened derivation does not match the registered child public key. */ | ||
| export class SafeDerivedPublicKeyMismatchError extends Error { | ||
| constructor(walletId: string, expectedPub: string, derivedPub: string) { | ||
| super( | ||
| `Safe wallet ${walletId}: derived child public key does not match the registered user key. ` + | ||
| `Expected ${expectedPub}, got ${derivedPub}.` | ||
| ); | ||
| this.name = 'SafeDerivedPublicKeyMismatchError'; | ||
| } | ||
| } | ||
|
|
||
| /** Thrown when owner signing is not implemented for this safe slot (TSS, ed25519 multisig, …). */ | ||
| export class SafeOwnerSigningNotImplementedError extends Error { | ||
| constructor(walletId: string, detail: string) { | ||
| super(`Safe wallet ${walletId}: ${detail}`); | ||
| this.name = 'SafeOwnerSigningNotImplementedError'; | ||
| } | ||
| } | ||
|
|
||
| /** ed25519 onchain multisig (slot ④). Needs SLIP-0010, not secp256k1 BIP32. */ | ||
| const ED25519_ONCHAIN_FAMILIES = new Set(['algo', 'xlm', 'hbar']); | ||
|
|
||
| /** | ||
| * True when this is the safe minter's user key: wallet is in a safe, the key | ||
| * has a parent root, and there is no child-level encryptedPrv (sharees have one). | ||
| */ | ||
| export function isSafeChildPublicOnlyKeychain( | ||
| walletSafeId: string | undefined, | ||
| keychain: Keychain | undefined | ||
| ): keychain is Keychain & { parent: string } { | ||
| return !!(walletSafeId && keychain?.parent && !keychain.encryptedPrv); | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the root user keychain for a safe child key. | ||
| * Requires `source === 'user'` so a misconfigured parent fails early. | ||
| */ | ||
| export async function fetchRootKeychainForSafeChild( | ||
| keychains: IKeychains, | ||
| childKeychain: Keychain | ||
| ): Promise<KeychainWithEncryptedPrv> { | ||
| if (!childKeychain.parent) { | ||
| throw new Error('childKeychain.parent is required to fetch the root keychain'); | ||
| } | ||
| const root = await keychains.get({ id: childKeychain.parent }); | ||
| if (root.source !== 'user') { | ||
| throw new InvalidRootKeychainSourceError(root.id, root.source); | ||
| } | ||
| if (!root.encryptedPrv) { | ||
| throw new Error(`root keychain ${root.id} does not have property encryptedPrv`); | ||
| } | ||
| return root as KeychainWithEncryptedPrv; | ||
| } | ||
|
|
||
| export interface ResolveSafeOwnerSigningPrvParams { | ||
| bitgo: BitGoBase; | ||
| keychains: IKeychains; | ||
| walletId: string; | ||
| /** Onchain secp256k1: hardened-derive and verify pub. Other slots throw. */ | ||
| multisigType: string | undefined; | ||
| coinFamily: string; | ||
| childKeychain: Keychain; | ||
| walletPassphrase: string; | ||
| /** When already fetched (passphrase preflight), skip a second GET. */ | ||
| rootKeychain?: KeychainWithEncryptedPrv; | ||
| } | ||
|
|
||
| /** | ||
| * Resolve signing material for a safe owner (child key has no encryptedPrv). | ||
| * | ||
| * Onchain secp256k1: decrypt root → hardened-derive at `derivedFromParentWithSeed` → | ||
| * verify derived pub against the registered child pub. | ||
| * TSS and ed25519 onchain: throw — do not return root material or BIP32-derive the wrong curve. | ||
| * | ||
| * Do not use for wallet sharing — that must not receive root key material. | ||
| * Call only when `isSafeChildPublicOnlyKeychain` is true. | ||
| */ | ||
| export async function resolveSafeOwnerSigningPrv(params: ResolveSafeOwnerSigningPrvParams): Promise<string> { | ||
| const { bitgo, keychains, walletId, multisigType, coinFamily, childKeychain, walletPassphrase } = params; | ||
|
|
||
| if (multisigType !== 'onchain') { | ||
| throw new SafeOwnerSigningNotImplementedError( | ||
| walletId, | ||
| 'TSS owner signing from the root keyshare is not implemented. ' + | ||
| 'Returning the root private key would expose material that can derive every child in this slot.' | ||
| ); | ||
| } | ||
| if (ED25519_ONCHAIN_FAMILIES.has(coinFamily)) { | ||
| throw new SafeOwnerSigningNotImplementedError( | ||
| walletId, | ||
| `ed25519 multisig owner derivation (${coinFamily}) is not implemented; BIP32 would produce the wrong child key.` | ||
| ); | ||
| } | ||
|
|
||
| const rootKeychain = params.rootKeychain ?? (await fetchRootKeychainForSafeChild(keychains, childKeychain)); | ||
| const rootPrv = await decryptKeychainPrivateKey(bitgo, rootKeychain, walletPassphrase); | ||
| if (!rootPrv) { | ||
| throw new IncorrectPasswordError(); | ||
| } | ||
|
|
||
| if (childKeychain.derivedFromParentWithSeed === undefined) { | ||
| throw new Error(`Safe wallet ${walletId}: child keychain is missing derivedFromParentWithSeed (derivation index)`); | ||
| } | ||
|
|
||
| const derived = deriveSafeChildHardenedFromXprv(rootPrv, childKeychain.derivedFromParentWithSeed); | ||
|
|
||
| if (!childKeychain.pub) { | ||
| throw new Error(`Safe wallet ${walletId}: child keychain is missing pub for pre-sign verification`); | ||
| } | ||
| if (derived.pub !== childKeychain.pub) { | ||
| throw new SafeDerivedPublicKeyMismatchError(walletId, childKeychain.pub, derived.pub); | ||
| } | ||
|
|
||
| return derived.prv; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: doesn't assert rootKeychain.id === childKeychain.parent before use, the pub-match check below catches a mismatch but an explicit assertion would make the invariant self-documenting
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I feel this could be a bit redundant - am okay with adding if we strongly feel it adds value though!