keyecdh

On-chain elliptic-curve Diffie-Hellman key exchange

Perform on-chain ECDH key exchange using Mercury EVM's ECDH precompile.

Overview

ecdh() and async_ecdh() call the ECDH precompile at address 0x65 to compute a shared secret from a private key and a public key using elliptic-curve Diffie-Hellman. The result is a 32-byte shared secret derived via HKDF.

Signature

def ecdh(
    w3: Web3,
    *,
    sk: PrivateKey,
    pk: CompressedPublicKey,
) -> Bytes32

async def async_ecdh(
    w3: AsyncWeb3,
    *,
    sk: PrivateKey,
    pk: CompressedPublicKey,
) -> Bytes32

Parameters

Parameter
Type
Required
Description

w3

Web3 or AsyncWeb3

Yes

Web3 instance connected to a Seismic node

sk

Yes

32-byte secret key

pk

Yes

33-byte compressed public key

Returns

Type
Description

32-byte shared secret

Examples

Basic Usage

Two-Party Key Exchange

Async Usage

Use with AES Encryption

Generate Keypair from Private Key

How It Works

  1. Encode parameters - Concatenates 32-byte private key and 33-byte public key

  2. Call precompile - Issues an eth_call to address 0x65 with 3120 gas

  3. Compute ECDH - Precompile performs scalar multiplication on secp256k1 curve

  4. Derive key - Applies HKDF to the ECDH point to produce a 32-byte secret

Gas Cost

Fixed gas cost: 3120 gas

  • 3000 gas for ECDH scalar multiplication

  • 120 gas for HKDF key derivation

Notes

  • Uses the secp256k1 elliptic curve (same as Ethereum)

  • Public keys must be in compressed format (33 bytes starting with 0x02 or 0x03)

  • The ECDH point is passed through HKDF for key uniformity

  • Both parties compute the same shared secret: ecdh(sk_A, pk_B) == ecdh(sk_B, pk_A)

  • The shared secret can be used as an AES-256 key

Warnings

  • Private key security - Never expose or log private keys

  • Public key validation - Invalid public keys will cause the precompile to revert

  • Key reuse - Using the same keypair for multiple sessions reduces forward secrecy

See Also

Last updated