Skip to content

Commit acf271c

Browse files
authored
Merge pull request #10141 from BitGo/backmerge/master-into-rel-latest-nov-6-2026
Backmerge/master into rel latest nov 6 2026
2 parents 788977a + 05970f2 commit acf271c

31 files changed

Lines changed: 1486 additions & 36 deletions

File tree

‎modules/abstract-lightning/src/codecs/api/payment.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ export const SubmitPaymentParams = t.intersection([
123123
t.partial({
124124
sequenceId: optionalString,
125125
comment: optionalString,
126+
/**
127+
* Upgrade the stored encryption of your user auth key to the latest format after signing with your
128+
* passphrase. Defaults to the `upgradeEncryptionOnSign` setting.
129+
*/
130+
upgradeEncryption: t.boolean,
126131
}),
127132
]);
128133

‎modules/abstract-lightning/src/codecs/api/wallet.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
import type { IRequestTracer } from '@bitgo/sdk-core';
12
import * as t from 'io-ts';
23
import { NonEmptyString } from 'io-ts-types';
34
import { getCodecPair } from '../shared';
45

56
// codec for lightning wallet and keychain related apis
67

8+
export type UpgradeUserAuthKeyEncryptionParams = {
9+
/** The wallet passphrase that decrypts the user auth key. */
10+
passphrase: string;
11+
reqId?: IRequestTracer;
12+
};
13+
714
export const KeyPurpose = t.union([t.literal('userAuth'), t.literal('nodeAuth')], 'KeyPurpose');
815

916
export type KeyPurpose = t.TypeOf<typeof KeyPurpose>;

‎modules/abstract-lightning/src/codecs/api/withdraw.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ export const LightningOnchainWithdrawParams = t.intersection([
1616
t.partial({
1717
sequenceId: optionalString,
1818
comment: optionalString,
19+
/**
20+
* Upgrade the stored encryption of your user auth key to the latest format after signing with your
21+
* passphrase. Defaults to the `upgradeEncryptionOnSign` setting.
22+
*/
23+
upgradeEncryption: t.boolean,
1924
}),
2025
]);
2126
export type LightningOnchainWithdrawParams = t.TypeOf<typeof LightningOnchainWithdrawParams>;

‎modules/abstract-lightning/src/wallet/lightning.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import {
88
commonTssMethods,
99
TxRequestState,
1010
decodeOrElse,
11+
KeyEncryptionUpgradeFailureReason,
12+
KeyEncryptionUpgradeResult,
13+
shouldUpgradeEncryption,
1114
} from '@bitgo/sdk-core';
1215
import * as t from 'io-ts';
1316
import {
@@ -35,6 +38,7 @@ import {
3538
ListPaymentsResponse,
3639
LndCreateWithdrawResponse,
3740
WatchOnly,
41+
UpgradeUserAuthKeyEncryptionParams,
3842
} from '../codecs';
3943
import { LightningPaymentIntent, LightningPaymentRequest } from '@bitgo/public-types';
4044

@@ -161,6 +165,15 @@ export interface ILightningWallet {
161165
*/
162166
payInvoice(params: SubmitPaymentParams): Promise<PayInvoiceResponse>;
163167

168+
/**
169+
* Upgrade the stored encryption of the user auth key to the latest format, using the wallet
170+
* passphrase. Use it after a payment or withdrawal to run the upgrade and show the outcome. It
171+
* applies regardless of the `upgradeEncryptionOnSign` setting and never throws.
172+
* @param params.passphrase - the wallet passphrase that decrypts the user auth key
173+
* @param params.reqId - optional request tracer
174+
*/
175+
upgradeUserAuthKeyEncryption(params: UpgradeUserAuthKeyEncryptionParams): Promise<KeyEncryptionUpgradeResult>;
176+
164177
/**
165178
* On chain withdrawal
166179
* @param {LightningOnchainWithdrawParams} params - Withdraw parameters
@@ -254,6 +267,18 @@ export class LightningWallet implements ILightningWallet {
254267
});
255268
}
256269

270+
async upgradeUserAuthKeyEncryption(params: UpgradeUserAuthKeyEncryptionParams): Promise<KeyEncryptionUpgradeResult> {
271+
let userAuthKey: LightningAuthKeychain;
272+
try {
273+
({ userAuthKey } = await getLightningAuthKeychains(this.wallet));
274+
} catch (e) {
275+
return { upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error };
276+
}
277+
return this.wallet.baseCoin
278+
.keychains()
279+
.upgradeEncryption({ keychain: userAuthKey, passphrase: params.passphrase, reqId: params.reqId });
280+
}
281+
257282
async payInvoice(params: SubmitPaymentParams): Promise<PayInvoiceResponse> {
258283
const reqId = new RequestTracer();
259284
this.wallet.bitgo.setRequestTracer(reqId);
@@ -267,6 +292,9 @@ export class LightningWallet implements ILightningWallet {
267292
t.exact(LightningPaymentRequest).encode(params),
268293
await this.wallet.bitgo.decrypt({ password: params.passphrase, input: userAuthKeyEncryptedPrv })
269294
);
295+
if (shouldUpgradeEncryption(this.wallet.bitgo, params.upgradeEncryption)) {
296+
void this.wallet.baseCoin.keychains().upgradeEncryption({ keychain: userAuthKey, passphrase: params.passphrase });
297+
}
270298

271299
const paymentIntent: { intent: LightningPaymentIntent } = {
272300
intent: {
@@ -392,6 +420,9 @@ export class LightningWallet implements ILightningWallet {
392420
transactionRequestCreate.transactions[0].unsignedTx.serializedTxHex,
393421
await this.wallet.bitgo.decrypt({ password: params.passphrase, input: userAuthKeyEncryptedPrv })
394422
);
423+
if (shouldUpgradeEncryption(this.wallet.bitgo, params.upgradeEncryption)) {
424+
void this.wallet.baseCoin.keychains().upgradeEncryption({ keychain: userAuthKey, passphrase: params.passphrase });
425+
}
395426

396427
const transactionRequestWithSignature = (await this.wallet.bitgo
397428
.put(

‎modules/bitgo/test/v2/unit/keychains.ts‎

Lines changed: 233 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,17 @@ import nock = require('nock');
99
import should = require('should');
1010
import * as sinon from 'sinon';
1111

12-
import { common, decodeOrElse, ECDSAUtils, EDDSAUtils, Keychain, Keychains, OvcShare } from '@bitgo/sdk-core';
12+
import {
13+
common,
14+
decodeOrElse,
15+
ECDSAUtils,
16+
EDDSAUtils,
17+
KeyEncryptionUpgradeFailureReason,
18+
KeyEncryptionUpgradeSkipReason,
19+
Keychain,
20+
Keychains,
21+
OvcShare,
22+
} from '@bitgo/sdk-core';
1323
import { TestBitGo } from '@bitgo/sdk-test';
1424
import { BitGo } from '../../../src/bitgo';
1525
import { SinonStub } from 'sinon';
@@ -1467,4 +1477,226 @@ describe('V2 Keychains', function () {
14671477
await keychains.reencryptAsV2(encrypted, 'wrongPass').should.be.rejected();
14681478
});
14691479
});
1480+
1481+
describe('upgradeEncryption', function () {
1482+
const prv = 'xprvUpgradeTestKey';
1483+
const passphrase = 'upgradePass';
1484+
const keyId = 'upgradeKeyId';
1485+
let sandbox: sinon.SinonSandbox;
1486+
let encryptedV1: string;
1487+
type UpgradeBody = {
1488+
encryptedPrv: string;
1489+
existingEncryptedPrv: string;
1490+
encryptionUpgrade: boolean;
1491+
pub?: string;
1492+
};
1493+
1494+
before(async function () {
1495+
encryptedV1 = await bitgo.encrypt({ input: prv, password: passphrase, encryptionVersion: 1 });
1496+
});
1497+
1498+
beforeEach(function () {
1499+
sandbox = sinon.createSandbox();
1500+
});
1501+
1502+
afterEach(function () {
1503+
sandbox.restore();
1504+
nock.cleanAll();
1505+
// Every upgrade a test starts must have settled, so none is shared with the next test.
1506+
keychains.upgradesInFlight.size.should.equal(0);
1507+
});
1508+
1509+
function v1Keychain(overrides: Partial<Keychain> = {}): Keychain {
1510+
return { id: keyId, pub: 'xpubUpgrade', encryptedPrv: encryptedV1, type: 'independent', ...overrides };
1511+
}
1512+
1513+
function mockPut(status = 200, times = 1) {
1514+
const bodies: UpgradeBody[] = [];
1515+
const scope = nock(bgUrl)
1516+
.put(`/api/v2/tltc/key/${keyId}`)
1517+
.times(times)
1518+
.reply((uri, body) => {
1519+
bodies.push(body as UpgradeBody);
1520+
return [status, status === 200 ? { id: keyId } : { error: 'failed' }];
1521+
});
1522+
return { scope, bodies };
1523+
}
1524+
1525+
it('upgrades a v1 key by sending the v2 encryption of the same prv with existingEncryptedPrv', async function () {
1526+
const keychain = v1Keychain();
1527+
const { scope, bodies } = mockPut();
1528+
1529+
const result = await keychains.upgradeEncryption({ keychain, passphrase });
1530+
1531+
result.should.deepEqual({ upgraded: true });
1532+
scope.isDone().should.be.true();
1533+
bodies.should.have.length(1);
1534+
const body = bodies[0];
1535+
body.encryptionUpgrade.should.equal(true);
1536+
body.existingEncryptedPrv.should.equal(encryptedV1);
1537+
body.should.not.have.property('pub');
1538+
JSON.parse(body.encryptedPrv).v.should.equal(2);
1539+
(await bitgo.decrypt({ input: body.encryptedPrv, password: passphrase })).should.equal(prv);
1540+
should(keychain.encryptedPrv).equal(encryptedV1);
1541+
});
1542+
1543+
it('upgrades when called directly, even with upgradeEncryptionOnSign off', async function () {
1544+
sandbox.stub(bitgo, 'isUpgradeEncryptionOnSignEnabled').returns(false);
1545+
const { scope, bodies } = mockPut();
1546+
1547+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1548+
1549+
result.should.deepEqual({ upgraded: true });
1550+
scope.isDone().should.be.true();
1551+
bodies.should.have.length(1);
1552+
});
1553+
1554+
it('skips a key that is already v2', async function () {
1555+
const encryptedV2 = await bitgo.encrypt({ input: prv, password: passphrase, encryptionVersion: 2 });
1556+
const { scope } = mockPut();
1557+
1558+
const result = await keychains.upgradeEncryption({
1559+
keychain: v1Keychain({ encryptedPrv: encryptedV2 }),
1560+
passphrase,
1561+
});
1562+
1563+
result.should.deepEqual({ upgraded: false, skipped: KeyEncryptionUpgradeSkipReason.AlreadyUpgraded });
1564+
scope.isDone().should.be.false();
1565+
});
1566+
1567+
it('reports an error without writing when encryptedPrv cannot be parsed', async function () {
1568+
const { scope } = mockPut();
1569+
1570+
const result = await keychains.upgradeEncryption({
1571+
keychain: v1Keychain({ encryptedPrv: 'not json' }),
1572+
passphrase,
1573+
});
1574+
1575+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error });
1576+
scope.isDone().should.be.false();
1577+
});
1578+
1579+
it('reports an error without writing when the keychain has no id', async function () {
1580+
const { scope } = mockPut();
1581+
1582+
const result = await keychains.upgradeEncryption({
1583+
keychain: v1Keychain({ id: undefined as unknown as string }),
1584+
passphrase,
1585+
});
1586+
1587+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error });
1588+
scope.isDone().should.be.false();
1589+
});
1590+
1591+
it('reports an error without writing when the passphrase is wrong', async function () {
1592+
const { scope } = mockPut();
1593+
1594+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase: 'wrongPass' });
1595+
1596+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error });
1597+
scope.isDone().should.be.false();
1598+
});
1599+
1600+
it('reports keyChanged when the key changed on the server (409)', async function () {
1601+
const { scope } = mockPut(409);
1602+
1603+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1604+
1605+
scope.isDone().should.be.true();
1606+
result.should.deepEqual({ upgraded: false, skipped: KeyEncryptionUpgradeSkipReason.KeyChanged });
1607+
});
1608+
1609+
it('reports an error when the server fails with 500', async function () {
1610+
const { scope } = mockPut(500);
1611+
1612+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1613+
1614+
scope.isDone().should.be.true();
1615+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error });
1616+
});
1617+
1618+
it('reports unavailable when the server rejects the upgrade with 503', async function () {
1619+
const { scope } = mockPut(503);
1620+
1621+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1622+
1623+
scope.isDone().should.be.true();
1624+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Unavailable });
1625+
});
1626+
1627+
it('reports an error when the request fails at the network level', async function () {
1628+
const scope = nock(bgUrl).put(`/api/v2/tltc/key/${keyId}`).replyWithError('socket hang up');
1629+
1630+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1631+
1632+
scope.isDone().should.be.true();
1633+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.Error });
1634+
});
1635+
1636+
it('reports verificationFailed without writing when the new encryption does not decrypt back to the same prv', async function () {
1637+
const decrypt = sandbox.stub(bitgo, 'decrypt').callThrough();
1638+
decrypt.onSecondCall().resolves('other');
1639+
const { scope } = mockPut();
1640+
1641+
const result = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1642+
1643+
decrypt.callCount.should.equal(2);
1644+
result.should.deepEqual({ upgraded: false, failed: KeyEncryptionUpgradeFailureReason.VerificationFailed });
1645+
scope.isDone().should.be.false();
1646+
});
1647+
1648+
it('sends one write for concurrent upgrades of the same key and gives both callers its outcome', async function () {
1649+
const { bodies } = mockPut(200, 2);
1650+
1651+
const results = await Promise.all([
1652+
keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase }),
1653+
keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase }),
1654+
]);
1655+
1656+
bodies.should.have.length(1);
1657+
results.should.deepEqual([{ upgraded: true }, { upgraded: true }]);
1658+
});
1659+
1660+
it('starts a new upgrade of the same key after the previous one settled', async function () {
1661+
const { bodies } = mockPut(200, 2);
1662+
1663+
const first = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1664+
const second = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1665+
1666+
first.should.deepEqual({ upgraded: true });
1667+
second.should.deepEqual({ upgraded: true });
1668+
bodies.should.have.length(2);
1669+
});
1670+
1671+
it('starts a new upgrade of the same key after the previous one was skipped', async function () {
1672+
const { bodies } = mockPut(409, 2);
1673+
1674+
const first = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1675+
const second = await keychains.upgradeEncryption({ keychain: v1Keychain(), passphrase });
1676+
1677+
first.should.deepEqual({ upgraded: false, skipped: KeyEncryptionUpgradeSkipReason.KeyChanged });
1678+
second.should.deepEqual({ upgraded: false, skipped: KeyEncryptionUpgradeSkipReason.KeyChanged });
1679+
bodies.should.have.length(2);
1680+
});
1681+
1682+
it('includes pub for an OFC multi-user key', async function () {
1683+
const ofcKeychains = bitgo.coin('ofc').keychains();
1684+
const bodies: UpgradeBody[] = [];
1685+
const scope = nock(bgUrl)
1686+
.put(`/api/v2/ofc/key/${keyId}`)
1687+
.reply((uri, body) => {
1688+
bodies.push(body as UpgradeBody);
1689+
return [200, { id: keyId }];
1690+
});
1691+
1692+
await ofcKeychains.upgradeEncryption({
1693+
keychain: v1Keychain({ coinSpecific: { ofc: { features: ['multi-user-key'] } } }),
1694+
passphrase,
1695+
});
1696+
1697+
scope.isDone().should.be.true();
1698+
should(bodies[0].pub).equal('xpubUpgrade');
1699+
bodies[0].encryptionUpgrade.should.equal(true);
1700+
});
1701+
});
14701702
});

0 commit comments

Comments
 (0)