Skip to content

Instantly share code, notes, and snippets.

@APTy
Created January 18, 2022 16:07
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save APTy/f2a6864a97889793c587635b562c7d72 to your computer and use it in GitHub Desktop.
Save APTy/f2a6864a97889793c587635b562c7d72 to your computer and use it in GitHub Desktop.
Signing and Verifying Eth Sign Typed Data (eth_signTypedData_v4)

Signing and Verifying Eth Sign Typed Data (eth_signTypedData_v4)

This is an example of signing EIP-712 typed data in javascript and verifying in golang.

The auth token is an "identity token" that only proves that the sender is the owner of an Ethereum address.

Usage

  1. Copy the javascript file into a browser window console that has MetaMask installed.
  2. Run await createEthereumSignedAuthToken(), which will open a window to sign a token.
  3. Copy the result from the console, and run then go run main.go <authToken>.

Security Discussion

This approach only uses security primitives provided by Ethereum, and hasn't undergone extensive security review.

  • Replay attacks are not prevented, as tokens can be verified multiple times repeatedly. Verifiers should store a durable reference to the sighash to ensure it isn't re-used. Also, the createdAt timestamp should be sufficiently recent (within minutes).
  • In order to prevent leaking information about the signer's private key, the typed data payload should include a nonce. It's possible that the createdAt timestamp fulfills this requirement, but the answer isn't entirely clear.
  • Since ecrecover pulls the public key used to sign the data, it may not be necessary to then verify the signature as well, since ecrecover has effectively already proven this. But we do it just to be safe.
const RINKEBY_TESTNET_CHAIN_ID = "4";
async function createEthereumSignedAuthToken(chainId = RINKEBY_TESTNET_CHAIN_ID) {
// More info on typed data: https://docs.metamask.io/guide/signing-data.html#sign-typed-data-v4
const typedData = JSON.stringify({
domain: {
chainId,
name: "Example App",
verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC",
version: "1",
},
message: {
prompt: "Welcome! In order to authenticate to this website, sign this request and your public address will be sent to the server in a verifiable way.",
createdAt: `${Date.now()}`,
},
primaryType: 'AuthRequest',
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
],
AuthRequest: [
{ name: 'prompt', type: 'string' },
{ name: 'createdAt', type: 'uint256' },
],
},
});
// this requests to connect wallet if it isn't already connected
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
var from = accounts[0];
var params = [from, typedData];
var method = 'eth_signTypedData_v4';
const signature = await window.ethereum.request({ method, params });
return JSON.stringify({
address: from,
typedData: btoa(typedData),
signature,
});
}
MIT License
Copyright 2022 APTy
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package main
import (
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
)
type AuthToken struct {
TypedData string `json:"typedData"`
Signature string `json:"signature"`
Address string `json:"address"`
}
func main() {
data := os.Args[1]
address, err := verifyAuthTokenAddress(data)
if err != nil {
log.Fatal(err)
}
fmt.Println("Verified address:", address)
}
func verifyAuthTokenAddress(data string) (string, error) {
var authToken AuthToken
if err := json.Unmarshal([]byte(data), &authToken); err != nil {
return "", fmt.Errorf("unmarshal auth token: %w", err)
}
signature, err := hexutil.Decode(authToken.Signature)
if err != nil {
return "", fmt.Errorf("decode signature: %w", err)
}
// fmt.Println("SIG:", hexutil.Encode(signature))
typedDataBytes, err := base64.StdEncoding.DecodeString(authToken.TypedData)
if err != nil {
return "", fmt.Errorf("decode typed data: %w", err)
}
typedData := apitypes.TypedData{}
if err := json.Unmarshal(typedDataBytes, &typedData); err != nil {
return "", fmt.Errorf("unmarshal typed data: %w", err)
}
// EIP-712 typed data marshalling
domainSeparator, err := typedData.HashStruct("EIP712Domain", typedData.Domain.Map())
if err != nil {
return "", fmt.Errorf("eip712domain hash struct: %w", err)
}
typedDataHash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message)
if err != nil {
return "", fmt.Errorf("primary type hash struct: %w", err)
}
// add magic string prefix
rawData := []byte(fmt.Sprintf("\x19\x01%s%s", string(domainSeparator), string(typedDataHash)))
sighash := crypto.Keccak256(rawData)
// fmt.Println("SIG HASH:", hexutil.Encode(sighash))
// update the recovery id
// https://github.com/ethereum/go-ethereum/blob/55599ee95d4151a2502465e0afc7c47bd1acba77/internal/ethapi/api.go#L442
signature[64] -= 27
// get the pubkey used to sign this signature
sigPubkey, err := crypto.Ecrecover(sighash, signature)
if err != nil {
return "", fmt.Errorf("ecrecover: %w", err)
}
// fmt.Println("SIG PUBKEY:", hexutil.Encode(sigPubkey))
// get the address to confirm it's the same one in the auth token
pubkey, err := crypto.UnmarshalPubkey(sigPubkey)
if err != nil {
return "", fmt.Errorf("", err)
}
address := crypto.PubkeyToAddress(*pubkey)
// fmt.Println("ADDRESS:", address.Hex())
// verify the signature (not sure if this is actually required after ecrecover)
signatureNoRecoverID := signature[:len(signature)-1]
verified := crypto.VerifySignature(sigPubkey, sighash, signatureNoRecoverID)
if !verified {
return "", errors.New("verification failed")
}
// fmt.Println("VERIFIED:", verified)
tokenAddress := common.HexToAddress(authToken.Address)
if subtle.ConstantTimeCompare(address.Bytes(), tokenAddress.Bytes()) == 0 {
return "", errors.New("address mismatch")
}
return address.Hex(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment