Contact & Handshake
The wire-level protocol behind identity in Undertown: the signed Contact document (as JSON and base58), its canonical signature message, and the three handshake protocols that carry it. Everything below is verifiable against the open-source client.
1. Overview — three keys, two trust layers
An Undertown identity binds two cryptographic trust layers into one portable document:
| Layer | Key | Answers the question |
|---|---|---|
| Wallet (secp256k1) | Ethereum-style ECDSA, keccak256 | Who owns this identity on-chain? Signs the Contact and every payment. |
| Peer (Ed25519 + X25519) | libp2p node keys | Who is this machine on the network? Ed25519 signs handshakes and derives the PeerId; X25519 encrypts messages. |
The Contact is the signed statement that ties them together: this wallet
vouches for this peer key pair, at these network addresses, in these relay networks.
Anyone can check that claim with the document alone — no server, no registry.
Three handshake protocols carry and verify Contacts:
- The P2P contact handshake — mandatory on every peer connection; proves the peer holds the Ed25519 key right now (section 6).
- The contract handshake — piggybacks on libp2p's
identifyand announces which group contracts a peer participates in (section 7). - The relay registration handshake — a wallet-signed challenge-response that admits a client to a paid relay (section 8).
2. The Contact document
A Contact consists of ten fields:
| Field | Type | Meaning |
|---|---|---|
peer_id | string | libp2p PeerId, deterministically derived from the Ed25519 public key (see section 5). Starts with 12D3KooW… for Ed25519 identities. |
name | string | Human-readable display name. |
keys | object | ed25519_public (32 bytes) — signatures & PeerId. x25519_public (32 bytes) — message encryption. |
address | string | The Ethereum wallet address that signed this document (0x + 40 hex). |
direct | string|null | Direct libp2p multiaddr where the peer can be reached (optional). |
relay | string|null | Multiaddr of a relay that forwards to this peer (optional; distinct from the paid relay mesh). |
subscriptions | string[] | Entries "chain_id:0xaddress" naming the Subscription contract(s) of the paid relay networks this user belongs to. Signed — part of the canonical message. |
created_at | int | Creation time, Unix seconds. |
expires_at | int | Expiry time, Unix seconds. Four months by default. |
signature | bytes[65] | Wallet ECDSA signature over the canonical message (r ‖ s ‖ v), created with the wallet's private key — which never leaves the device. |
3. The Contact in JSON
The canonical serialization is serde_json, compact form (no whitespace), with fields in the declaration order above. Pretty-printed for readability, a Contact looks like this:
{
"peer_id": "12D3KooW9tJMax94Lrqw7Y5Qw36viGQAS2gTEPQ5Wg1vTk7xPfQs",
"name": "Alice",
"keys": {
"ed25519_public": [1, 2, 3, ..., 31, 32], // 32 bytes — placeholder: ascending 1–32
"x25519_public": [42, 42, 42, ..., 42] // 32 bytes — placeholder: 42, thirty-two times
},
"address": "0xa11ce000000000000000000000000000000000face",
"direct": "/ip4/203.0.113.10/tcp/9000",
"relay": "/ip4/198.51.100.7/tcp/9000/p2p/12D3KooWGaGckmF4tPFMvVqf7cPtWvogbkWNugNFq4ztENZGMeLr",
"subscriptions": ["1:0xc0ffee000000000000000000000000000000000042"],
"created_at": 1760486400,
"expires_at": 1771488000,
"signature": [0, 0, 0, ..., 0] // 65 bytes: r (32) ‖ s (32) ‖ v (1) — placeholder zeros here
}
Every value above is synthetic placeholder data (the IPs use the RFC 5737 documentation ranges). Real fields carry exactly 32 / 32 / 65 integers in the 0–255 range. Any conforming JSON parser accepts the document regardless of key order — but the signature is computed over the canonical message (section 4), not over the JSON, so re-serialization never breaks a valid Contact.
4. The Contact in base58 — the “contact code”
When a Contact travels the wire or gets shared between users, it is encoded as a contact code:
contact JSON (compact serde_json, UTF-8 bytes) │ ▼ bs58 encode // Bitcoin alphabet, no version byte, no checksum │ ▼ "xQ3NDRCpBDPweRsr..."
Decoding is the exact inverse and is always followed by full verification
(decode → UTF-8 → parse → verify()). The example Contact
from section 3 — with the placeholder arrays expanded exactly as annotated
([1–32], thirty-two 42s, sixty-five zeros) —
encodes compactly to 758 bytes and expands to this 1035-character contact code:
xQ3NDRCpBDPweRsrrQwYJb93C39GfKwn64gFTD1fzjjh2q4pXVvNBTtSon2DtnkenB2YKCc4w7DeAEzFxazY3JQRA7R7yVQVmVNcSTc4v6q4qK1pCn6UvgdNSxGsuxah3e1cfABsVMJibPRAnARbZKhrg4zSrJGvb6GKP2icqoAv625pJEUYcCqyKtfK3tApkjQVnRqyicTn1iHfikmiZvnUTLTYk7aPvTA1fUkhaBgH7c53NaA1UWQo1LvB7KD3qoiqWcE4uQuc9NAHV5NwswapeZMzWzgW4VEGBzLVXWgUAUS6CKuUZhffx9eNSADb2gxQBtzwEd3wV5qMz984yqQqanohRqqEokafUhPfTsYL1RQTwPYhPCdV2CXCvt9XazzCVqtxjazxE7ELT8Fj9ASY9gqePsDwNAXyhpQdMtXqpYpseo4bvaTkXwZ5DEUPLmLrAmvzhX4VYbNx2SCVv8kvPkHHn9uKtPr9FYkNvGB3Kg1TgTvtqAaYvQaiJFjVK7DBqiFGcrBVZWFd9bGFQAWSTPSVFy4YDWpQF4KpDP9BVNmqwrtN7FRNqhxorKjEBbt6pZhRuRycsBVaw5Wuedb6RZQbJRPs548fDHQjC1GF5CM7jKSuR1vJb68rsvWUHzo8PrM2mfwhFXr4URWd9F1gyW6XNjdhQ8hAjsLeHy1AGBvZFgZsPHtHZ8K3XCaep6TPWPZK93Szqom6MyW7xRfWqWQmLUEVr5JxQ3dz48gS2mvdL1Dcdaa4FYpH14qHoUUpBWzqibpQzyJdsZ4mnX2ee83vMTa2PYGnTwKPvJetErCGrhEuuYHZ8v2VJkKkUCitEgDxT3VC8gm9w6bY3gkSKQD3fDMxoXnoztoJNmMonoGhUNweq1pF9v3GJAG77B8m1jbJTZd9Hpt9xs5JbGachQMtPwtbM6xPfVZidfVMG4DzvoGELfBveuEi6RFuahAjoUACHwwY6tSB63oCPqcHeVgqjLFWRzyU8ff8jtbtRdCrkJwEEB1gR6EddVeiTZLanaYgCsv
Contact codes are transport, not identity. Two base58 strings for the same Contact may differ (JSON key order, whitespace) while both being perfectly valid — validity is decided by the signature check after decoding, never by string comparison.
Where contact codes appear:
- Handshake responses — the
contactfield of the P2P handshake (section 6) - Contact sharing — the
contact_codefield of the share flow (section 9) - Relay registration — the client's signed Contact rides along as JSON; on-chain, relays publish their contact code via the contract's
contactCode()pointer - Persistence — the local
contactstable stores every verified Contact it has seen
5. PeerId derivation
The peer_id is not an independent field — it is computed from
the Ed25519 public key, which is what makes section 6's key-binding check possible:
ed25519 public key (32 bytes) │ ▼ protobuf: field 1 = key type (1 = Ed25519), field 2 = key bytes 08 01 12 20 ‖ key // 36 bytes │ ▼ identity multihash prefix 00 24 ‖ protobuf // 38 bytes: 0x00 = identity, 0x24 = length 36 │ ▼ base58 (Bitcoin alphabet) 12D3KooW9tJMax94Lrqw7Y5Qw36viGQAS2gTEPQ5Wg1vTk7xPfQs
The identity multihash (prefix 0x00) embeds the key itself rather than a hash
of it — so PeerId ↔ Ed25519 key is a bijective mapping anyone can recompute.
6. The canonical message & wallet signature
The wallet signs a deterministic, line-based rendering of the Contact — never the JSON. The format is frozen; changing any line breaks all existing signatures by design:
I create Undertown Contact for wallet {address}
peer_id:{peer_id}
name:{name}
ed25519:{ed25519_public, hex}
x25519:{x25519_public, hex}
direct:{multiaddr, or empty string}
relay:{multiaddr, or empty string}
subscriptions:{entries joined by ","}
created:{created_at}
expires:{expires_at}
The signing pipeline: the UTF-8 message is hashed with keccak256, signed
with the wallet's secp256k1 private key, and stored as a 65-byte
recoverable signature (r ‖ s ‖ v). Verification reconstructs the exact same
message and recovers the signer's address from the signature:
Which key signs, and where does it live? The signature is produced by the wallet's private key — a secp256k1 key generated on your device when the wallet is created, stored encrypted in the local vault, and unlocked by your password. The private key never appears in the Contact, never travels the wire, and never leaves the device. It also cannot be derived from anything the document contains: the Contact carries only public values, and the signature covers a message — not the key.
Why verification needs no keys at all. Ethereum-style signatures are
recoverable: given the message hash and the 65-byte signature, anyone can
mathematically re-derive the signer's public key (and hash it down to the
address). That is the entire verification trick above — the verifier holds no
wallet key, yet can prove the signature could only have been produced by the private
key of the address claimed in the document. This is also what makes the
Contact safe to share with anyone: leaking it leaks nothing.
- Derive the PeerId from
keys.ed25519_public— must equal thepeer_idfield. - Build the canonical message and hash it with keccak256.
- Recover the signer address from the ECDSA signature.
- The recovered address must equal the
addressfield.
verify() does not check expiry. The signature proves the
wallet authorized the document; freshness is a separate, explicit decision
(created_at / expires_at with a four-month default lifetime).
Callers that care about liveness check the clock — the relay mesh and the DM
watchdog both do.
Because the subscriptions list is inside the signed message, joining or leaving
a paid relay network requires re-signing: the client rewrites the document,
signs a fresh canonical message with the wallet key, and stores the result in its encrypted
vault. Old copies of your Contact keep validating against old signatures — which is
why consumers also check expires_at.
7. Handshake #1 — the P2P contact handshake
Every Undertown peer connection begins with a mandatory challenge-response. Its job: prove the peer still holds the Ed25519 key matching the PeerId you are talking to — without requiring their wallet password — and hand you a fresh, verifiable Contact. It runs as a libp2p request-response with a 10-second timeout:
The request
{
"action": "contact.handshake.request",
"nonce": "a1b2c3..." // 32 random bytes, hex-encoded (64 chars)
}
The response
{
"nonce": "a1b2c3...", // echoed back verbatim
"signature": "9f8e7d...", // Ed25519 signature over the 32 RAW nonce bytes, hex (64 bytes)
"contact": "xQ3NDRCpBDPweRsr..." // responder's own Contact, base58 contact code
}
Verification chain (every check must pass)
- Nonce echo — the returned
nonceequals the one sent (replay of an old response fails here). - Contact present — an empty
contactfield is a hard failure; a peer without a verifiable identity is worthless. - base58 decode → UTF-8 → JSON parse of the contact code.
- Ed25519 signature — the 64-byte signature verifies against
keys.ed25519_publicfrom inside the decoded Contact over the raw 32 nonce bytes. This is the liveness proof: only the key holder could have produced it, and the nonce binds it to this session. - PeerId binding — the PeerId derived from that same Ed25519 key must equal the libp2p PeerId of the connection itself. The Contact cannot be swapped for someone else's.
- Wallet signature — full
verify(): canonical message → keccak256 → ECDSA recovery → address match (section 4).
Note the deliberate division of labor: Ed25519 proves the machine (it holds
the session key), the wallet signature proves the person (the Contact was
authorized by the wallet). A connection is only trusted when both check out. On success the
Contact is stored in the local contacts table and the peer node is marked
connected.
8. Handshake #2 — contract discovery via libp2p identify
To sync group membership cheaply, Undertown piggybacks a second, non-interactive handshake
onto libp2p's built-in identify protocol. The agent-version string carries a
compact, base64-encoded JSON announcement:
undertown/1.0/contracts:eyJjb250cmFjdF9hZGRyZXNzZXMiOltdLCJyZWdpc3RyeV92ZXJzaW9uIjoxfQ==
└────────── base64( JSON ) ──────────┘
decoded:
{
"contract_addresses": ["0xc0ffee0000000000000000000000000000000001", "0xfeedface00000000000000000000000000000002"],
"registry_version": 1
}
contract_addresses— the group contracts this peer currently participates in. Peers use it to discover shared groups and sync efficiently.registry_version— a cache-invalidation counter: if the version moved, peers re-fetch instead of trusting their cache.- The whole agent string is capped at 4096 bytes; announcements above the cap are rejected rather than truncated.
This handshake is advisory — it carries no signature and grants no authority. Membership claims are always re-verified against the chain before access is granted.
9. Handshake #3 — relay client registration
Subscribing on-chain buys you entitlement; registration is how a relay learns who its clients are and proves each one owns a paid subscription. It is a three-step, wallet-signed challenge-response over the existing peer connection:
Step 1 — register
The client sends relay.client_register with { wallet, contact }
— its wallet address and signed Contact. The relay replies with a challenge:
relay.client_challenge {
nonce: 64-hex, // single-use, 32 bytes of OS entropy
relay: <RelayNode contract address>, // binds the signature to THIS relay
ttl_secs: 300 // challenge expires in 5 minutes
}
Step 2 — sign locally
The client signs the canonical challenge message (below) with its wallet key. No password leaves the device — session-key signing, same path as Contact creation.
Step 3 — confirm
The client answers with relay.client_confirm:
relay.client_confirm {
wallet: <client wallet address>,
nonce: 64-hex, echoed from the challenge,
signature: 65-byte r‖s‖v, hex,
contact: the client's signed Contact
}
success: ok { verified, wallet, peer_id, verified_until, ttl_secs: 600 }
failure: { error: "bad_signature" | "no_subscription" | "challenge_expired" | ..., message }
The client signs this canonical challenge message (format frozen):
I register Undertown client for relay
wallet:{client wallet address}
relay:{relay's RelayNode contract address}
nonce:{64 lowercase hex}
Relay-side verification, in order:
- Signature recovery — the ECDSA signature must recover to the claimed wallet (same secp256k1 path as Contact verification), case-insensitive match.
- Signature binding — the signed
relayaddress must be the challenge's relay address. A signature minted for relay A is worthless at relay B (this closed a multi-relay impersonation gap). - On-chain subscription —
hasSubscription(wallet, relay)is checked against the relay's tracked Subscription contracts. Results are cached 10 minutes; RPC errors are never cached. - Contact validation — the attached Contact must pass full
verify().
On success the relay persists the client in its wallet-peer list and admits it to the
verified set for 10 minutes; renewal is a fresh handshake over the live
connection. Challenges are single-use, 32 bytes of OS entropy, and expire after
5 minutes. Failures are rate-limited: 5 per 10 minutes
per source, keyed by the claimed wallet address alone (client-supplied identity fields do
not participate, so rotating them cannot evade the limiter). Typed error kinds include
bad_signature, wallet_mismatch, no_subscription,
challenge_expired, and rate_limited.
After registration, the relay only ever caches this client's traffic as ciphertext — it has no decryption keys. Registration grants delivery service, never read access. For what happens next (routing, the relay-to-relay transfer handshake), see the blog post The Relay Mesh, Explained.
10. Sharing a Contact out-of-band
Handshakes verify peers you are already connected to. To meet someone in the first place, contacts travel as base58 contact codes through the invite/accept flow — over an existing verified connection or pasted between humans:
- Channel 35 carries contact requests; channel 36 carries accept/deny responses.
- Both directions decode the base58, run full
verify(), and the response payload includes the responder's own contact code so the receiving watchdog can verify it against the responder's key — not the requester's. - An acceptance stores each side in the other's
contactstable; a denial simply drops the request.
11. Security notes
- Three keys, three jobs. secp256k1/keccak256 = wallet authority (Contact signature, payments). Ed25519 = peer identity (handshake liveness, PeerId). X25519 = message confidentiality. They are never interchangeable.
- Liveness vs. authorization. The wallet signature proves a document was authorized; the nonce handshake proves the key is presently held. Both are required before a connection is trusted.
- No password on the wire. Contact signing and the relay challenge use cached session keys; the wallet password never travels and never decrypts anything peer-side.
- Replay resistance. Every handshake embeds fresh entropy (32-byte nonces) with tight TTLs, and each nonce is consumed on use.
- Expiry is a policy decision. Signatures don't age; consumers enforce
expires_atexplicitly. Old-but-valid signatures on stale Contacts are expected and handled by re-signing on update. - Contact codes are untrusted input. Decode → parse →
verify()is mandatory on every ingestion path; a base58 string is only as good as its signature.