diff --git a/modules/express/package.json b/modules/express/package.json index a0c37ad41d..e936c8a8b2 100644 --- a/modules/express/package.json +++ b/modules/express/package.json @@ -49,6 +49,7 @@ "debug": "^3.1.0", "dotenv": "^16.0.0", "express": "4.21.2", + "io-ts-types": "^0.5.16", "io-ts": "npm:@bitgo-forks/io-ts@2.1.4", "io-ts-types": "^0.5.19", "lodash": "^4.17.20", diff --git a/modules/express/src/clientRoutes.ts b/modules/express/src/clientRoutes.ts index f6433eb73b..ee0aeef511 100755 --- a/modules/express/src/clientRoutes.ts +++ b/modules/express/src/clientRoutes.ts @@ -637,11 +637,11 @@ export async function handleV2OFCSignPayload( * handle new wallet creation * @param req */ -export async function handleV2GenerateWallet(req: express.Request) { +export async function handleV2GenerateWallet(req: ExpressApiRouteRequest<'express.wallet.generate', 'post'>) { const bitgo = req.bitgo; - const coin = bitgo.coin(req.params.coin); + const coin = bitgo.coin(req.decoded.coin); const result = await coin.wallets().generateWallet(req.body); - if (req.query.includeKeychains === 'false') { + if ((req.decoded.includeKeychains as any) === false) { return result.wallet.toJSON(); } return { ...result, wallet: result.wallet.toJSON() }; @@ -1605,7 +1605,7 @@ export function setupAPIRoutes(app: express.Application, config: Config): void { router.post('express.keychain.local', [prepareBitGo(config), typedPromiseWrapper(handleV2CreateLocalKeyChain)]); // generate wallet - app.post('/api/v2/:coin/wallet/generate', parseBody, prepareBitGo(config), promiseWrapper(handleV2GenerateWallet)); + router.post('express.wallet.generate', [prepareBitGo(config), typedPromiseWrapper(handleV2GenerateWallet)]); app.put('/express/api/v2/:coin/wallet/:id', parseBody, prepareBitGo(config), promiseWrapper(handleWalletUpdate)); diff --git a/modules/express/src/typedRoutes/api/index.ts b/modules/express/src/typedRoutes/api/index.ts index b4db56f42d..dc86216a3e 100644 --- a/modules/express/src/typedRoutes/api/index.ts +++ b/modules/express/src/typedRoutes/api/index.ts @@ -26,6 +26,7 @@ import { PostCreateAddress } from './v2/createAddress'; import { PutFanoutUnspents } from './v1/fanoutUnspents'; import { PostOfcSignPayload } from './v2/ofcSignPayload'; import { PostWalletRecoverToken } from './v2/walletRecoverToken'; +import { PostGenerateWallet } from './v2/generateWallet'; export const ExpressApi = apiSpec({ 'express.ping': { @@ -100,6 +101,9 @@ export const ExpressApi = apiSpec({ 'express.v2.wallet.recovertoken': { post: PostWalletRecoverToken, }, + 'express.wallet.generate': { + post: PostGenerateWallet, + }, }); export type ExpressApi = typeof ExpressApi; diff --git a/modules/express/src/typedRoutes/api/v2/generateWallet.ts b/modules/express/src/typedRoutes/api/v2/generateWallet.ts new file mode 100644 index 0000000000..e37184e1b9 --- /dev/null +++ b/modules/express/src/typedRoutes/api/v2/generateWallet.ts @@ -0,0 +1,115 @@ +import * as t from 'io-ts'; +import { BooleanFromString } from 'io-ts-types'; +import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http'; +import { BitgoExpressError } from '../../schemas/error'; +import { UserKeychainCodec, BackupKeychainCodec, BitgoKeychainCodec } from '../../schemas/keychain'; +import { multisigType, walletType } from '../../schemas/wallet'; + +/** + * Request body for wallet generation. + */ +export const GenerateWalletBody = { + /** Wallet label */ + label: t.string, + /** Enterprise id. This is required for Ethereum wallets since they can only be created as part of an enterprise */ + enterprise: t.string, + /** If absent, BitGo uses the default wallet type for the asset */ + multisigType: multisigType, + /** The type of wallet, defined by key management and signing protocols. 'hot' and 'cold' are both self-managed wallets. If absent, defaults to 'hot' */ + type: walletType, + /** Passphrase to be used to encrypt the user key on the wallet */ + passphrase: optional(t.string), + /** User provided public key */ + userKey: optional(t.string), + /** Backup extended public key */ + backupXpub: optional(t.string), + /** Optional key recovery service to provide and store the backup key */ + backupXpubProvider: optional(t.literal('dai')), + /** Flag for disabling wallet transaction notifications */ + disableTransactionNotifications: optional(t.boolean), + /** The passphrase used for decrypting the encrypted wallet passphrase during wallet recovery */ + passcodeEncryptionCode: optional(t.string), + /** Seed that derives an extended user key or common keychain for a cold wallet */ + coldDerivationSeed: optional(t.string), + /** Gas price to use when deploying an Ethereum wallet */ + gasPrice: optional(t.number), + /** Flag for preventing KRS from sending email after creating backup key */ + disableKRSEmail: optional(t.boolean), + /** (ETH only) Specify the wallet creation contract version used when creating a wallet contract */ + walletVersion: optional(t.number), + /** True, if the wallet type is a distributed-custodial. If passed, you must also pass the 'enterprise' parameter */ + isDistributedCustody: optional(t.boolean), + /** BitGo key ID for self-managed cold MPC wallets */ + bitgoKeyId: optional(t.string), + /** Common keychain for self-managed cold MPC wallets */ + commonKeychain: optional(t.string), +} as const; + +export const GenerateWalletResponse200 = t.union([ + t.UnknownRecord, + t.type({ + wallet: t.UnknownRecord, + encryptedWalletPassphrase: optional(t.string), + userKeychain: optional(UserKeychainCodec), + backupKeychain: optional(BackupKeychainCodec), + bitgoKeychain: optional(BitgoKeychainCodec), + warning: optional(t.string), + }), +]); + +/** + * Response body for wallet generation. + */ +export const GenerateWalletResponse = { + /** The newly created wallet */ + 200: GenerateWalletResponse200, + /** Bad request */ + 400: BitgoExpressError, +} as const; + +/** + * Path parameters for wallet generation. + */ +export const GenerateWalletV2Params = { + /** Coin ticker / chain identifier */ + coin: t.string, +}; + +/** + * Query parameters for wallet generation. + * @property includeKeychains - Include user, backup and bitgo keychains along with generated wallet + */ +export const GenerateWalletV2Query = { + /** Include user, backup and bitgo keychains along with generated wallet */ + includeKeychains: optional(BooleanFromString), +}; + +/** + * Generate Wallet + * + * This API call creates a new wallet. Under the hood, the SDK (or BitGo Express) does the following: + * + * 1. Creates the user keychain locally on the machine, and encrypts it with the provided passphrase (skipped if userKey is provided). + * 2. Creates the backup keychain locally on the machine. + * 3. Uploads the encrypted user keychain and public backup keychain. + * 4. Creates the BitGo key (and the backup key if backupXpubProvider is set) on the service. + * 5. Creates the wallet on BitGo with the 3 public keys above. + * + * ⓘ Ethereum wallets can only be created under an enterprise. Pass in the id of the enterprise to associate the wallet with. Your enterprise id can be seen by clicking on the "Manage Organization" link on the enterprise dropdown. Each enterprise has a fee address which will be used to pay for transaction fees on all Ethereum wallets in that enterprise. The fee address is displayed in the dashboard of the website, please fund it before creating a wallet. + * + * ⓘ You cannot generate a wallet by passing in a subtoken as the coin. Subtokens share wallets with their parent coin and it is not possible to create a wallet specific to one token. + * + * ⓘ This endpoint should be called through BitGo Express if used without the SDK, such as when using cURL. + * + * @operationId express.wallet.generate + */ +export const PostGenerateWallet = httpRoute({ + path: '/api/v2/:coin/wallet/generate', + method: 'POST', + request: httpRequest({ + params: GenerateWalletV2Params, + query: GenerateWalletV2Query, + body: GenerateWalletBody, + }), + response: GenerateWalletResponse, +}); diff --git a/modules/express/src/typedRoutes/schemas/keychain.ts b/modules/express/src/typedRoutes/schemas/keychain.ts new file mode 100644 index 0000000000..f15b896cde --- /dev/null +++ b/modules/express/src/typedRoutes/schemas/keychain.ts @@ -0,0 +1,41 @@ +import * as t from 'io-ts'; + +// Base keychain fields +const BaseKeychainCodec = t.type({ + id: t.string, + pub: t.string, + source: t.string, +}); + +// User keychain: can have encryptedPrv and prv +export const UserKeychainCodec = t.intersection([ + BaseKeychainCodec, + t.partial({ + ethAddress: t.string, + coinSpecific: t.UnknownRecord, + encryptedPrv: t.string, + prv: t.string, + }), +]); + +// Backup keychain: can have prv +export const BackupKeychainCodec = t.intersection([ + BaseKeychainCodec, + t.partial({ + ethAddress: t.string, + coinSpecific: t.UnknownRecord, + prv: t.string, + }), +]); + +// BitGo keychain: must have isBitGo +export const BitgoKeychainCodec = t.intersection([ + BaseKeychainCodec, + t.type({ + isBitGo: t.boolean, + }), + t.partial({ + ethAddress: t.string, + coinSpecific: t.UnknownRecord, + }), +]); diff --git a/modules/express/src/typedRoutes/schemas/wallet.ts b/modules/express/src/typedRoutes/schemas/wallet.ts new file mode 100644 index 0000000000..716f245213 --- /dev/null +++ b/modules/express/src/typedRoutes/schemas/wallet.ts @@ -0,0 +1,5 @@ +import * as t from 'io-ts'; + +export const multisigType = t.union([t.literal('onchain'), t.literal('tss'), t.literal('blsdkg')]); + +export const walletType = t.union([t.literal('hot'), t.literal('cold'), t.literal('custodial')]); diff --git a/modules/express/test/unit/clientRoutes/generateWallet.ts b/modules/express/test/unit/clientRoutes/generateWallet.ts index 52baca2017..1dc222818b 100644 --- a/modules/express/test/unit/clientRoutes/generateWallet.ts +++ b/modules/express/test/unit/clientRoutes/generateWallet.ts @@ -1,38 +1,102 @@ -import * as sinon from 'sinon'; +import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; +import { BitGo } from 'bitgo'; +import { common, decodeOrElse } from '@bitgo/sdk-core'; +import nock from 'nock'; import 'should-http'; import 'should-sinon'; import '../../lib/asserts'; -import * as express from 'express'; - +import { ExpressApiRouteRequest } from '../../../src/typedRoutes/api'; import { handleV2GenerateWallet } from '../../../src/clientRoutes'; - -import { BitGo } from 'bitgo'; -import { BaseCoin, Wallets, WalletWithKeychains } from '@bitgo/sdk-core'; +import { GenerateWalletResponse } from '../../../src/typedRoutes/api/v2/generateWallet'; describe('Generate Wallet', () => { + let bitgo: TestBitGoAPI; + let bgUrl: string; + const coin = 'tbtc'; + + before(async function () { + if (!nock.isActive()) { + nock.activate(); + } + + bitgo = TestBitGo.decorate(BitGo, { env: 'test' }); + bitgo.initializeTestVars(); + + bgUrl = common.Environments[bitgo.getEnv()].uri; + + nock.disableNetConnect(); + nock.enableNetConnect('127.0.0.1'); + }); + + after(() => { + if (nock.isActive()) { + nock.restore(); + } + }); + it('should return the internal wallet object and keychains by default or if includeKeychains is true', async () => { - const walletStub = sinon - .stub<[], Promise>() - .resolves({ wallet: { toJSON: () => 'walletdata with keychains' } } as any); - const walletsStub = sinon.createStubInstance(Wallets, { generateWallet: walletStub }); - const coinStub = sinon.createStubInstance(BaseCoin, { - wallets: sinon.stub<[], Wallets>().returns(walletsStub as any), - }); - const stubBitgo = sinon.createStubInstance(BitGo, { coin: sinon.stub<[string]>().returns(coinStub) }); - const walletGenerateBody = {}; - const coin = 'tbtc'; + // Mock keychain creation calls + const userKeychainId = 'user-keychain-id'; + const backupKeychainId = 'backup-keychain-id'; + const bitgoKeychainId = 'bitgo-keychain-id'; + const walletId = 'wallet-id'; + + // Mock wallet creation + const walletNock = nock(bgUrl) + .post(`/api/v2/${coin}/wallet/add`) + .times(2) + .reply(200, { + id: walletId, + label: 'Test Wallet', + keys: [userKeychainId, backupKeychainId, bitgoKeychainId], + coin: coin, + }); + + // Mock keychain retrieval calls + const keychainRetrievalNocks = [ + nock(bgUrl).get(`/api/v2/${coin}/key/${userKeychainId}`).times(2).reply(200, { + id: userKeychainId, + pub: 'user-pub-key', + source: 'user', + encryptedPrv: 'encrypted-user-prv', + }), + nock(bgUrl).get(`/api/v2/${coin}/key/${backupKeychainId}`).times(2).reply(200, { + id: backupKeychainId, + pub: 'backup-pub-key', + source: 'backup', + prv: 'backup-prv', + }), + nock(bgUrl).get(`/api/v2/${coin}/key/${bitgoKeychainId}`).times(2).reply(200, { + id: bitgoKeychainId, + pub: 'bitgo-pub-key', + source: 'bitgo', + isBitGo: true, + }), + ]; + + const walletGenerateBody = { + label: 'Test Wallet', + type: 'custodial', + enterprise: 'test-enterprise', + } as const; + const reqDefault = { - bitgo: stubBitgo, + bitgo, params: { coin, }, query: {}, body: walletGenerateBody, - } as unknown as express.Request; + decoded: { + ...walletGenerateBody, + coin, + }, + } as unknown as ExpressApiRouteRequest<'express.wallet.generate', 'post'>; + const reqIncludeKeychains = { - bitgo: stubBitgo, + bitgo, params: { coin, }, @@ -40,33 +104,112 @@ describe('Generate Wallet', () => { includeKeychains: true, }, body: walletGenerateBody, - } as unknown as express.Request; + decoded: { + ...walletGenerateBody, + coin, + includeKeychains: true, + }, + } as unknown as ExpressApiRouteRequest<'express.wallet.generate', 'post'>; + + const resDefault = await handleV2GenerateWallet(reqDefault); + decodeOrElse('GenerateWalletResponse', GenerateWalletResponse[200], resDefault, (_) => { + throw new Error('Response did not match expected codec'); + }); - await handleV2GenerateWallet(reqDefault).should.be.resolvedWith({ wallet: 'walletdata with keychains' }); - await handleV2GenerateWallet(reqIncludeKeychains).should.be.resolvedWith({ wallet: 'walletdata with keychains' }); + const resIncludeKeychains = await handleV2GenerateWallet(reqIncludeKeychains); + decodeOrElse('GenerateWalletResponse', GenerateWalletResponse[200], resIncludeKeychains, (_) => { + throw new Error('Response did not match expected codec'); + }); + + // Double verify the responses contain the expected structure + resDefault.should.have.property('wallet'); + resDefault.should.have.property('userKeychain'); + resDefault.should.have.property('backupKeychain'); + resDefault.should.have.property('bitgoKeychain'); + + resIncludeKeychains.should.have.property('wallet'); + resIncludeKeychains.should.have.property('userKeychain'); + resIncludeKeychains.should.have.property('backupKeychain'); + resIncludeKeychains.should.have.property('bitgoKeychain'); + + walletNock.done(); + keychainRetrievalNocks.forEach((nock) => nock.done()); }); it('should only return wallet data if includeKeychains query param is false', async () => { - const walletsStub = sinon.createStubInstance(Wallets, { - generateWallet: { wallet: { toJSON: () => 'walletdata' } } as any, - }); - const coinStub = sinon.createStubInstance(BaseCoin, { - wallets: sinon.stub<[], Wallets>().returns(walletsStub as any), - }); - const stubBitgo = sinon.createStubInstance(BitGo, { coin: sinon.stub<[string]>().returns(coinStub) }); - const walletGenerateBody = {}; - const coin = 'tbtc'; + // Mock keychain creation calls + const userKeychainId = 'user-keychain-id'; + const backupKeychainId = 'backup-keychain-id'; + const bitgoKeychainId = 'bitgo-keychain-id'; + const walletId = 'wallet-id'; + + // Mock wallet creation + const walletNock = nock(bgUrl) + .post(`/api/v2/${coin}/wallet/add`) + .reply(200, { + id: walletId, + label: 'Test Wallet', + keys: [userKeychainId, backupKeychainId, bitgoKeychainId], + coin: coin, + }); + + // Mock keychain retrieval calls + const keychainRetrievalNocks = [ + nock(bgUrl).get(`/api/v2/${coin}/key/${userKeychainId}`).reply(200, { + id: userKeychainId, + pub: 'user-pub-key', + source: 'user', + encryptedPrv: 'encrypted-user-prv', + }), + nock(bgUrl).get(`/api/v2/${coin}/key/${backupKeychainId}`).reply(200, { + id: backupKeychainId, + pub: 'backup-pub-key', + source: 'backup', + prv: 'backup-prv', + }), + nock(bgUrl).get(`/api/v2/${coin}/key/${bitgoKeychainId}`).reply(200, { + id: bitgoKeychainId, + pub: 'bitgo-pub-key', + source: 'bitgo', + isBitGo: true, + }), + ]; + + const walletGenerateBody = { + label: 'Test Wallet', + type: 'custodial', + enterprise: 'test-enterprise', + } as const; + const req = { - bitgo: stubBitgo, + bitgo, params: { coin, }, query: { - includeKeychains: 'false', + includeKeychains: false, }, body: walletGenerateBody, - } as unknown as express.Request; + decoded: { + ...walletGenerateBody, + coin, + includeKeychains: false, + }, + } as unknown as ExpressApiRouteRequest<'express.wallet.generate', 'post'>; + + const res = await handleV2GenerateWallet(req); + decodeOrElse('GenerateWalletResponse', GenerateWalletResponse[200], res, (_) => { + throw new Error('Response did not match expected codec'); + }); - await handleV2GenerateWallet(req).should.be.resolvedWith('walletdata'); + // When includeKeychains is false, should only return wallet data + res.should.have.property('id', walletId); + res.should.have.property('label', 'Test Wallet'); + res.should.have.property('coin', coin); + res.should.not.have.property('userKeychain'); + res.should.not.have.property('backupKeychain'); + res.should.not.have.property('bitgoKeychain'); + walletNock.done(); + keychainRetrievalNocks.forEach((nock) => nock.done()); }); });