Skip to content

Commit

Permalink
fix: use a signing domain prefix for offline message signing
Browse files Browse the repository at this point in the history
  • Loading branch information
sagar-a16z committed Oct 24, 2024
1 parent 68867cb commit 52441db
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
5 changes: 3 additions & 2 deletions app/components/message/MessageForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import dynamic from 'next/dynamic';
import { SetStateAction, useCallback, useEffect, useMemo, useState } from "react";

import { MeteredMessageBox } from "./MeteredMessageBox";
import { SigningContext, SignMessageBox } from "./SignMessageButton";
import { SigningContext, SignMessageBox, SIGNING_DOMAIN } from "./SignMessageButton";

const ConnectButton = dynamic(async () => ((await import('@solana/wallet-adapter-react-ui')).WalletMultiButton), { ssr: false });

Expand Down Expand Up @@ -72,7 +72,8 @@ export const MessageForm = (props: { reportVerification: ReportMessageVerificati

const handleVerifyClick = useCallback(() => {
try {
const verified = ed25519.verify(bs58.decode(signature), new TextEncoder().encode(message), bs58.decode(address));
const messageBytes = new TextEncoder().encode(SIGNING_DOMAIN + message);
const verified = ed25519.verify(bs58.decode(signature), messageBytes, bs58.decode(address));
if (!verified) throw new Error("Message verification failed!");
setVerified(true)
} catch (error) {
Expand Down
9 changes: 7 additions & 2 deletions app/components/message/SignMessageButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Message, Transaction } from '@solana/web3.js';
import bs58 from 'bs58';
import React, { useCallback } from 'react';

export const SIGNING_DOMAIN = "_sign offchain_\n"

export interface SigningContext {
input: string;
address: string;
Expand Down Expand Up @@ -41,10 +43,13 @@ export const SignMessageBox = (props: Props) => {
if (!shouldSign(formattedMessage)) {
throw new Error('Message may be used in a transaction! Refusing to sign.');
}
const signature = await signMessage(new TextEncoder().encode(formattedMessage));
if (!ed25519.verify(signature, new TextEncoder().encode(formattedMessage), publicKey.toBytes())) {
const messageBytes = new TextEncoder().encode(SIGNING_DOMAIN + formattedMessage);
console.log(`Signing message: ${formattedMessage}`);
const signature = await signMessage(messageBytes);
if (!ed25519.verify(signature, messageBytes, publicKey.toBytes())) {
throw new Error('Message signature invalid!');
}
console.log(`Finished signing`);

// update the UI fields to reflect the signed message
props.signingcontext.setInput({ target: { value: formattedMessage } });
Expand Down

0 comments on commit 52441db

Please sign in to comment.