From c076ed54ffa3b696dd35affbd14c9c801cbf51b4 Mon Sep 17 00:00:00 2001 From: AricRedemption Date: Tue, 22 Oct 2024 18:31:51 +0800 Subject: [PATCH] chore: update ecdh api --- src/lib/actions/common/ecdh.ts | 35 ++++++++++++++++++++++++++++++++++ src/lib/wallet.ts | 16 ++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/lib/actions/common/ecdh.ts diff --git a/src/lib/actions/common/ecdh.ts b/src/lib/actions/common/ecdh.ts new file mode 100644 index 0000000..1a03b4b --- /dev/null +++ b/src/lib/actions/common/ecdh.ts @@ -0,0 +1,35 @@ +import * as ecdh from 'crypto' +import { getNet } from '@/lib/network' +import { getActiveWallet } from '@/lib/wallet' +import { AddressType, BaseWallet, ScriptType } from '@metalet/utxo-wallet-service' + +export async function process( + _: unknown, + { path = "m/100'/0'/0'/0/0", externalPubKey }: { path?: string; externalPubKey: string } +) { + const network = getNet() + const activeWallet = await getActiveWallet() + + const wallet = new BaseWallet({ + // @ts-ignore + path, + network, + addressIndex: 0, + scriptType: ScriptType.P2PKH, + mnemonic: activeWallet.mnemonic, + addressType: AddressType.Legacy, + }) + + const privateKey = wallet.getPrivateKeyBuffer() + + const _externalPubKey = Buffer.from(externalPubKey, 'hex') + + const ecdhKey = ecdh.createECDH('secp256k1') + // @ts-ignore + ecdhKey.setPrivateKey(privateKey) + + // 返回协商密钥 + const sharedSecret = ecdhKey.computeSecret(_externalPubKey) + + return sharedSecret.toString('hex') +} diff --git a/src/lib/wallet.ts b/src/lib/wallet.ts index 6e4a782..9dd5986 100644 --- a/src/lib/wallet.ts +++ b/src/lib/wallet.ts @@ -106,6 +106,22 @@ export async function getV3CurrentWallet() { return wallet } +export async function getActiveWallet() { + const currentWalletId = await getCurrentWalletId() + if (!currentWalletId) { + throw new Error('currentWalletId id not found') + } + const wallets = await getV3EncryptedWallets() + if (!wallets.length) { + throw new Error('wallets not found') + } + let wallet = wallets.find((wallet) => wallet.id === currentWalletId) + if (!wallet) { + throw new Error('wallets not found') + } + return wallet +} + export async function getWalletOnlyAccount(walletId: string, accountId: string) { if (!walletId) { throw new Error('wallet id not found')