Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion modules/abstract-lightning/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
# BitGo abstract-lightning
# @bitgo/abstract-lightning

## Custodial userAuth key reset

For a custody Lightning wallet, call `requestUserAuthKeyReset` with the new wallet
passphrase and optional `encryptionVersion`. The SDK creates and encrypts a new
userAuth key locally, registers the encrypted key, and signs the reset request.
The returned verification code is calculated locally; the customer reads it to
support. The unencrypted private key and passphrase are never sent to the API.

Use `getUserAuthKeyResetRequest` to retrieve the latest request (a missing request
returns HTTP 404), and `cancelUserAuthKeyResetRequest` with its request ID to
cancel it. After a successful reset, other wallet members must be re-shared the
new key before they can regain access.

`computeUserAuthResetVerificationCode` and `compareUserAuthResetVerificationCodes`
are also exported for independent verification.
1 change: 1 addition & 0 deletions modules/abstract-lightning/src/codecs/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './payment';
export * from './withdraw';
export * from './transaction';
export * from './wallet';
export * from './userAuthKeyReset';
44 changes: 44 additions & 0 deletions modules/abstract-lightning/src/codecs/api/userAuthKeyReset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as t from 'io-ts';

const SignedRequestFields = t.type({
walletId: t.string,
oldUserAuthKeyPub: t.string,
newUserAuthKeyPub: t.string,
newUserAuthKeyId: t.string,
createdAt: t.string,
});

export type UserAuthKeyResetSignedRequest = t.TypeOf<typeof SignedRequestFields>;

export const UserAuthKeyResetSignedRequest = new t.Type<UserAuthKeyResetSignedRequest>(
'UserAuthKeyResetSignedRequest',
(value): value is UserAuthKeyResetSignedRequest =>
SignedRequestFields.is(value) &&
Object.keys(value).every((key) => Object.prototype.hasOwnProperty.call(SignedRequestFields.props, key)),
(value, context) => {
const result = SignedRequestFields.validate(value, context);
if (result._tag === 'Left') {
return result;
}
return Object.keys(result.right).every((key) =>

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reject unknown fields rather than using io-ts exact, which strips them. A verifier must not silently accept a different signed payload.

Object.prototype.hasOwnProperty.call(SignedRequestFields.props, key)
)
? result
: t.failure(value, context);
},
t.identity
);

export const UserAuthKeyResetRequest = t.type({
newUserAuthKeyId: t.string,
signedRequest: UserAuthKeyResetSignedRequest,
signature: t.string,
});
export type UserAuthKeyResetRequest = t.TypeOf<typeof UserAuthKeyResetRequest>;

export const UserAuthKeyResetResponse = t.type({
requestId: t.string,
status: t.string,
createdAt: t.string,
});
export type UserAuthKeyResetResponse = t.TypeOf<typeof UserAuthKeyResetResponse>;
12 changes: 10 additions & 2 deletions modules/abstract-lightning/src/lightning/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import * as utxolib from '@bitgo/utxo-lib';
import * as sdkcore from '@bitgo/sdk-core';
import { canonicalizeObject, Signable } from './signableJson';

function parseLightningKey(key: string, network: utxolib.Network): utxolib.BIP32Interface {
// Lightning auth keys use Bitcoin BIP32 versions on both networks.
if (key.startsWith('xpub') || key.startsWith('xprv')) {

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I parse Bitcoin-versioned keys independently of the signing network: existing Lightning key generation returns xpub/xprv on testnet too, while the signature still uses the coin network.

return utxolib.bip32.fromBase58(key, utxolib.networks.bitcoin);
}
return utxolib.bip32.fromBase58(key, network);
}

/**
* Verifies a signature for a given message.
*
Expand All @@ -18,7 +26,7 @@ export function verifyMessageSignature(
network: utxolib.Network = utxolib.networks.bitcoin
): boolean {
const messageString = JSON.stringify(canonicalizeObject(message));
const pubKey = utxolib.bip32.fromBase58(pub, network).publicKey;
const pubKey = parseLightningKey(pub, network).publicKey;
const signatureBuffer = Buffer.from(signature, 'hex');
return sdkcore.verifyMessage(messageString, pubKey, signatureBuffer, network);
}
Expand All @@ -37,6 +45,6 @@ export function createMessageSignature(
network: utxolib.Network = utxolib.networks.bitcoin
): string {
const requestString = JSON.stringify(canonicalizeObject(message));
const prvKey = utxolib.bip32.fromBase58(xprv, network);
const prvKey = parseLightningKey(xprv, network);
return sdkcore.signMessage(requestString, prvKey, network).toString('hex');
}
81 changes: 79 additions & 2 deletions modules/abstract-lightning/src/wallet/custodialLightning.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { ILightningWallet, LightningWallet } from './lightning';
import { getLightningAuthKeychains, ILightningWallet, LightningWallet } from './lightning';
import * as sdkcore from '@bitgo/sdk-core';
import { createMessageSignature, getUtxolibNetwork } from '../lightning';
import { UserAuthKeyResetRequest, UserAuthKeyResetResponse, UserAuthKeyResetSignedRequest } from '../codecs';
import { computeUserAuthResetVerificationCode } from './userAuthKeyReset';

export type ICustodialLightningWallet = ILightningWallet;
export interface ICustodialLightningWallet extends ILightningWallet {
requestUserAuthKeyReset(params: {
passphrase: string;
encryptionVersion?: sdkcore.EncryptionVersion;
}): Promise<{ requestId: string; status: string; verificationCode: string }>;
getUserAuthKeyResetRequest(): Promise<UserAuthKeyResetResponse>;
cancelUserAuthKeyResetRequest(requestId: string): Promise<unknown>;
}

export class CustodialLightningWallet extends LightningWallet implements ICustodialLightningWallet {
constructor(wallet: sdkcore.IWallet) {
Expand All @@ -10,4 +20,71 @@ export class CustodialLightningWallet extends LightningWallet implements ICustod
throw new Error(`Invalid lightning wallet type for custodial lightning: ${wallet.subType()}`);
}
}

async requestUserAuthKeyReset(params: {
passphrase: string;
encryptionVersion?: sdkcore.EncryptionVersion;
}): Promise<{ requestId: string; status: string; verificationCode: string }> {
const { userAuthKey } = await getLightningAuthKeychains(this.wallet);
const coin = this.wallet.baseCoin;
const { pub, prv } = coin.keychains().create();
if (!pub || !prv) {
throw new Error('Failed to generate user auth key');
}
const encryptedPrv = await this.wallet.bitgo.encrypt({
password: params.passphrase,
input: prv,
encryptionVersion: params.encryptionVersion,
});
const { id: newUserAuthKeyId } = await coin.keychains().add({
pub,
encryptedPrv,
source: 'user',
keyType: 'independent',
coinSpecific: { [coin.getChain()]: { purpose: 'userAuth' } },
});
const signedRequest: UserAuthKeyResetSignedRequest = {
walletId: this.wallet.id(),
oldUserAuthKeyPub: userAuthKey.pub,
newUserAuthKeyPub: pub,
newUserAuthKeyId,
createdAt: new Date().toISOString(),
};
const request: UserAuthKeyResetRequest = {
newUserAuthKeyId,
signedRequest,
signature: createMessageSignature(signedRequest, prv, getUtxolibNetwork(coin.getChain())),
};
const response = await this.wallet.bitgo
.post(coin.url(`/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest`))
.send(UserAuthKeyResetRequest.encode(request))
.result();
const result = sdkcore.decodeOrElse(UserAuthKeyResetResponse.name, UserAuthKeyResetResponse, response, () => {
throw new Error('Invalid user auth key reset response');
});
return {
requestId: result.requestId,
status: result.status,

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compute this from the locally generated public key instead of trusting any server-provided code, so support verification binds to the key the customer actually generated.

verificationCode: computeUserAuthResetVerificationCode(this.wallet.id(), pub),
};
}

async getUserAuthKeyResetRequest(): Promise<UserAuthKeyResetResponse> {
const response = await this.wallet.bitgo
.get(this.wallet.baseCoin.url(`/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest`))
.result();
return sdkcore.decodeOrElse(UserAuthKeyResetResponse.name, UserAuthKeyResetResponse, response, () => {
throw new Error('Invalid user auth key reset response');
});
}

async cancelUserAuthKeyResetRequest(requestId: string): Promise<unknown> {
return await this.wallet.bitgo
.del(
this.wallet.baseCoin.url(
`/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest/${encodeURIComponent(requestId)}`
)
)
.result();
}
}
2 changes: 2 additions & 0 deletions modules/abstract-lightning/src/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export * from './lightning';
export * from './custodialLightning';
export * from './selfCustodialLightning';
export * from './wallet';
export * from './userAuthKeyReset';
export * from '../codecs/api/userAuthKeyReset';
29 changes: 29 additions & 0 deletions modules/abstract-lightning/src/wallet/userAuthKeyReset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createHash } from 'crypto';

const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

export function computeUserAuthResetVerificationCode(walletId: string, newUserAuthKeyPub: string): string {
const digest = createHash('sha256')
.update(`lightning-userauth-reset:v1:${walletId}:${newUserAuthKeyPub}`, 'utf8')
.digest();
let bits = 0;
let value = 0;
let code = '';
for (const byte of digest) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5 && code.length < 10) {
bits -= 5;
code += BASE32_ALPHABET[(value >>> bits) & 31];
}
if (code.length === 10) {
break;
}
}
return `${code.slice(0, 5)}-${code.slice(5)}`;
}

export function compareUserAuthResetVerificationCodes(left: string, right: string): boolean {
const normalize = (code: string): string => code.replace(/[- ]/g, '').toUpperCase();
return normalize(left) === normalize(right);
}
Loading
Loading