Skip to content
This repository has been archived by the owner on Jan 22, 2025. It is now read-only.

Issue 2978: Verify signature for address helper #3703

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: 18 additions & 0 deletions packages/keys/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
}
```
34 changes: 34 additions & 0 deletions packages/keys/src/signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
try {
// Encode the address to bytes
const addressBytes: ReadonlyUint8Array = new Uint8Array(getBase58Encoder().encode(address));
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
const addressBytes: ReadonlyUint8Array = new Uint8Array(getBase58Encoder().encode(address));
const addressBytes = getAddressEncoder().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;
}
}