From 41c1a255a6e2847deaa339ff9810bf54124e9dbb Mon Sep 17 00:00:00 2001 From: LunarFang416 Date: Mon, 9 Dec 2024 23:19:31 -0500 Subject: [PATCH 1/2] verifySignatureForAddress method implementation --- packages/keys/src/signatures.ts | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/keys/src/signatures.ts b/packages/keys/src/signatures.ts index f27a788710ec..dc73a5930cbf 100644 --- a/packages/keys/src/signatures.ts +++ b/packages/keys/src/signatures.ts @@ -75,3 +75,37 @@ export async function verifySignature( assertVerificationCapabilityIsAvailable(); return await crypto.subtle.verify('Ed25519', key, signature, data); } + + +export async function verifySignatureForAddress( + address: string, + signature: Uint8Array, + messageBytes: Uint8Array +): Promise { + try { + // Encode the address to bytes + const addressBytes: ReadonlyUint8Array = new Uint8Array(getBase58Encoder().encode(address)); + + // Create a public Ed25519 key from the address bytes + const publicKey = await crypto.subtle.importKey( + 'raw', + addressBytes, + 'Ed25519', + true, + ['verify'] + ); + + // Verify the signature using the public key + const isValid = await crypto.subtle.verify( + 'Ed25519', + publicKey, + signature, + messageBytes + ); + + return isValid; + } catch (error) { + console.error('Error verifying signature:', error); + return false; + } +} From e5c420b03649fe0096e6074775c4234d8fead7dd Mon Sep 17 00:00:00 2001 From: LunarFang416 Date: Mon, 9 Dec 2024 23:19:51 -0500 Subject: [PATCH 2/2] add documentation for verifySignatureForAddress usage and example --- packages/keys/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/keys/README.md b/packages/keys/README.md index 70f292652afb..34f27adbb8e0 100644 --- a/packages/keys/README.md +++ b/packages/keys/README.md @@ -179,3 +179,21 @@ if (!(await verifySignature(publicKey, signature, data))) { throw new Error('The data were *not* signed by the private key associated with `publicKey`'); } ``` + +### `verifySignatureForAddress()` + +This helper function verifies if a digital signature was produced by signing specific data with the private key associated with a given address. It simplifies the process of verifying signatures by internally handling the conversion of the address to a public Ed25519 key. + +```ts +import { verifySignatureForAddress } from '@solana/keys'; + +const signedByAddress = 'ED1WqT2hWJLSZtj4TtTdoovmpMrr7zpkUdbfxmcJR1Fq'; +const signature = new Uint8Array([/* ...signature bytes... */]); +const data = new Uint8Array([/* ...data bytes... */]); + +const isVerified = await verifySignatureForAddress(signedByAddress, signature, data); + +if (!isVerified) { + throw new Error(`The signature is not valid for the provided address: ${signedByAddress}`); +} +```