Blockchain infrastructure · 5 MIN READ

Signed messages and Sign-In with Ethereum: recover the right address and refuse replays

Verify an EIP-191 personal signature, normalize its V byte, and accept an EIP-4361 sign-in only for this domain, chain and expiry with an unused server nonce.

Wallets can sign arbitrary text as well as transactions, and many services use that to log users in without passwords. The cryptography is the easy part. A recovered address only says that some key signed some bytes; whether those bytes were meant for your site, for now and for exactly one login is decided by the message format and by state your server keeps. This lesson verifies both halves with a fixed test key and an in-memory nonce store.

blockchain · A MAP OF THE IDEA

  1. Issue nonce with TTL
  2. Check domain, chain, time
  3. Recover and match address
  4. Consume nonce atomically

Useful when

  • Password-free logins verified offline with go-ethereum primitives.
  • Domain binding and single-use nonces defeat relayed and replayed signatures.

Watch out

  • ecrecover cannot verify smart-contract wallets; EIP-1271 needs an RPC call.
  • A login signature must never double as authorization to move value.

Implementation & operation cost: A nonce table with a TTL and atomic consume, a strict message parser and a test matrix for V, s, domain, expiry and concurrency.

01

What personal_sign actually signs

EIP-191 version 0x45, the personal_sign format, prefixes the message with "\x19Ethereum Signed Message:\n" and its decimal byte length, then hashes with keccak256; go-ethereum exposes exactly this as accounts.TextHash. The 0x19 prefix keeps the signed bytes from ever parsing as a valid transaction, so a site cannot get a wallet to sign a transfer by calling it a message. The signature is 65 bytes: R, S and a recovery byte V. crypto.Sign returns V as 0 or 1, while wallets and geth's own eth_sign return 27 or 28 for historical reasons, and crypto.SigToPub accepts only 0 or 1. The signing-boundaries lesson argued that recovery is not authorization; this lesson adds the rules that turn a recovery into a login.

02

Verify a sign-in end to end

The program plays both parties. The wallet side builds an EIP-4361 message, hashes it with TextHash, signs it with a fixed test key and shifts V to 27 or 28 as wallets do. The server side parses the fields it relies on, checks them against its own configuration and clock, recovers the signer and consumes the nonce last. Five attempts show which rule stops which attack.

go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"math/big"
	"strings"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/accounts"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
)

const header = " wants you to sign in with your Ethereum account:"

var fields = map[string]bool{"URI": true, "Version": true, "Chain ID": true,
	"Nonce": true, "Issued At": true, "Expiration Time": true}

// recoverPersonal returns the address that produced an EIP-191 personal_sign signature.
func recoverPersonal(message string, sig []byte) (common.Address, error) {
	if len(sig) != crypto.SignatureLength {
		return common.Address{}, errors.New("signature must be 65 bytes")
	}
	s := bytes.Clone(sig) // never mutate the caller's slice
	if s[64] == 27 || s[64] == 28 {
		s[64] -= 27 // wallets send 27/28; go-ethereum expects 0/1
	}
	r, sv := new(big.Int).SetBytes(s[:32]), new(big.Int).SetBytes(s[32:64])
	if !crypto.ValidateSignatureValues(s[64], r, sv, true) {
		return common.Address{}, errors.New("invalid or high-s signature")
	}
	pub, err := crypto.SigToPub(accounts.TextHash([]byte(message)), s)
	if err != nil {
		return common.Address{}, err
	}
	return crypto.PubkeyToAddress(*pub), nil
}

// parse reads the EIP-4361 fields this server checks. A production parser
// should implement the full ABNF, including field order and Resources.
func parse(msg string) (map[string]string, error) {
	lines := strings.Split(msg, "\n")
	if len(lines) < 8 || !strings.HasSuffix(lines[0], header) {
		return nil, errors.New("not a sign-in message")
	}
	f := map[string]string{"Domain": strings.TrimSuffix(lines[0], header), "Address": lines[1]}
	for _, line := range lines[2:] {
		k, v, ok := strings.Cut(line, ": ")
		if !ok || !fields[k] {
			continue // blank lines and the free-text statement
		}
		if _, dup := f[k]; dup {
			return nil, fmt.Errorf("duplicate field %q", k)
		}
		f[k] = v
	}
	return f, nil
}

type Server struct {
	Domain, ChainID string
	mu              sync.Mutex
	nonces          map[string]bool // issued and not yet used
}

func (s *Server) Verify(msg string, sig []byte, now time.Time) (common.Address, error) {
	f, err := parse(msg)
	if err != nil {
		return common.Address{}, err
	}
	if f["Domain"] != s.Domain {
		return common.Address{}, fmt.Errorf("domain %q is not %q", f["Domain"], s.Domain)
	}
	if f["URI"] != "https://"+s.Domain+"/login" || f["Version"] != "1" || f["Chain ID"] != s.ChainID {
		return common.Address{}, errors.New("wrong URI, version or chain")
	}
	exp, err := time.Parse(time.RFC3339, f["Expiration Time"])
	if err != nil || !now.Before(exp) {
		return common.Address{}, errors.New("missing or past expiration time")
	}
	claimed := f["Address"]
	if !common.IsHexAddress(claimed) || common.HexToAddress(claimed).Hex() != claimed {
		return common.Address{}, errors.New("address is not EIP-55 checksummed")
	}
	signer, err := recoverPersonal(msg, sig)
	if err != nil {
		return common.Address{}, err
	}
	if signer != common.HexToAddress(claimed) {
		return common.Address{}, fmt.Errorf("signature recovers %s", signer.Hex())
	}
	s.mu.Lock() // consuming the nonce is the commit point
	defer s.mu.Unlock()
	if !s.nonces[f["Nonce"]] {
		return common.Address{}, errors.New("nonce unknown or already used")
	}
	delete(s.nonces, f["Nonce"])
	return signer, nil
}

func message(domain string, addr common.Address, nonce string, issued time.Time) string {
	return domain + header + "\n" + addr.Hex() + "\n\n" +
		"Sign in to the dashboard.\n\n" +
		"URI: https://" + domain + "/login\nVersion: 1\nChain ID: 1337\n" +
		"Nonce: " + nonce + "\n" +
		"Issued At: " + issued.Format(time.RFC3339) + "\n" +
		"Expiration Time: " + issued.Add(5*time.Minute).Format(time.RFC3339)
}

// walletSign mimics personal_sign: EIP-191 hash, then V shifted to 27/28.
func walletSign(msg string, key []byte) []byte {
	prv, err := crypto.ToECDSA(key)
	if err != nil {
		panic(err)
	}
	sig, err := crypto.Sign(accounts.TextHash([]byte(msg)), prv)
	if err != nil {
		panic(err)
	}
	sig[64] += 27
	return sig
}

func main() {
	testKey := bytes.Repeat([]byte{1}, 32) // TEST KEY ONLY, never funded
	prv, _ := crypto.ToECDSA(testKey)
	user := crypto.PubkeyToAddress(prv.PublicKey)
	now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) // fixed clock for the example
	srv := &Server{Domain: "app.example.com", ChainID: "1337", nonces: map[string]bool{}}

	// In production each nonce comes from crypto/rand.Text and is stored with a TTL.
	srv.nonces["K7Q2M9XW4PZ3"], srv.nonces["H5R8T2LN6QVA"] = true, true
	msg := message("app.example.com", user, "K7Q2M9XW4PZ3", now)
	sig := walletSign(msg, testKey)
	fmt.Println(strings.Split(msg, "\n")[0])
	fmt.Println("wallet V byte:", sig[64])

	flipped := bytes.Clone(sig)
	flipped[64] = 27 + 28 - flipped[64] // 27 <-> 28: valid, but for another key
	try := func(label, m string, s []byte, at time.Time) {
		addr, err := srv.Verify(m, s, at)
		if err != nil {
			fmt.Printf("%-9s rejected: %v\n", label, err)
			return
		}
		fmt.Printf("%-9s signed in as %s\n", label, addr.Hex())
	}
	try("flipped V", msg, flipped, now)
	try("login", msg, sig, now.Add(30*time.Second))
	try("replay", msg, sig, now.Add(40*time.Second))

	phish := message("evil.example", user, "H5R8T2LN6QVA", now)
	try("phishing", phish, walletSign(phish, testKey), now)
	late := message("app.example.com", user, "H5R8T2LN6QVA", now)
	try("late", late, walletSign(late, testKey), now.Add(6*time.Minute))
}
Read the code

recoverPersonal copies the signature before normalizing V, rejects high-s values with ValidateSignatureValues and recovers with SigToPub over TextHash of the exact message text. Swapping V between 27 and 28 is not detected as malformed: it recovers a different, valid-looking address, so only the comparison with the claimed address catches it, and the nonce survives that failure. The genuine login succeeds and deletes the nonce, so the identical replay fails. A message signed for evil.example fails the domain check even though its signature is perfect, and a message presented six minutes later fails its five-minute expiration. The clock is a fixed value so the output is deterministic.

03

The EIP-4361 fields the server must own

A Sign-In with Ethereum message is plain text with a fixed layout: the requesting domain, the account in EIP-55 checksum form, an optional statement for the user, then URI, Version (1), Chain ID, Nonce, Issued At and optional Expiration Time, Not Before, Request ID and Resources lines. Every value the server compares must come from server state, never from the message: the expected domain and URI from configuration, the chain ID from the deployment, the time from the server clock and the nonce from the server's own store. EIP-4361 requires at least eight alphanumeric characters of nonce; crypto/rand.Text returns 26 base32 characters, which fits. The domain check defeats a phishing site that relays a genuine signature: the wallet shows the user which domain is asking, and your server refuses any domain but its own. Parse strictly against the specification's ABNF and reject duplicate fields, because two parsers that disagree about which Nonce line counts are a vulnerability. The example's parser is deliberately small and skips Issued At and Not Before checks that a real verifier performs with a bounded clock skew.

04

Store nonces so a replay loses the race

The in-memory map and mutex model a single process. A real deployment issues nonces from a shared store with a time-to-live and consumes them with one atomic operation, so two concurrent submissions of the same signed message cannot both succeed. Run the stateless checks and signature recovery first, and make the consume the final step that commits the login.

go
// Issue: bind each nonce to the pre-login browser session that asked for it.
nonce := rand.Text() // crypto/rand: 26 base32 characters
if _, err := db.ExecContext(ctx,
	`INSERT INTO siwe_nonces (nonce, session_id, expires_at)
	 VALUES ($1, $2, now() + interval '5 minutes')`, nonce, sessionID); err != nil {
	return err
}

// Verify: only after domain, URI, chain, expiry and signature checks pass.
res, err := db.ExecContext(ctx,
	`DELETE FROM siwe_nonces WHERE nonce = $1 AND session_id = $2 AND expires_at > now()`,
	fields["Nonce"], sessionID)
if err != nil {
	return err
}
if n, err := res.RowsAffected(); err != nil || n != 1 {
	return errors.New("nonce unknown, expired or already used")
}
Read the code

This fragment needs a PostgreSQL database, so it runs in your own native environment; db is a *sql.DB and sessionID identifies the pre-login browser session. Binding the nonce to that session stops a signed message captured from one session from being redeemed in another. The DELETE with the expiry condition is the atomic test-and-consume: when two requests race, exactly one sees RowsAffected equal to 1. After a successful login, issue a fresh session identifier instead of promoting the pre-login one.

05

Limits worth stating in a review

ecrecover verifies only externally owned accounts. A smart-contract wallet has no single private key; it validates signatures through EIP-1271 isValidSignature, which needs an eth_call on the chain named in the message, so supporting those wallets adds an RPC-dependent path with the timeouts and trust questions of the rpc-boundaries lesson. KMS and HSM signers can return a high s value; normalize it (s becomes n - s and V flips) before publishing, because EIP-2 makes high-s transactions invalid and many message verifiers, including this one, reject them. Sign-in proves control of an address at login time and nothing more: map it to an account, issue your own session with its own expiry, and require a fresh, purpose-specific signature or EIP-712 typed data for anything that moves value. Test the verifier with a wrong domain, URI or chain, a missing or past expiration, an unchecksummed address, V of 0, 1, 27 and 28, a high-s signature, a duplicate Nonce line and two concurrent submissions.

TAKE THIS WITH YOU

A valid signature only recovers an address; a login also needs your domain, URI and chain, an unexpired message and a server-issued nonce that is consumed atomically exactly once.

Check your understanding

An attacker resubmits a user's valid Sign-In with Ethereum message and signature a minute after the user logged in. What makes the server reject it?

Go to the source

Progress stays in this browser. No account needed.