2. Cryptographic Primitives (fleetmesh_core.crypto)
The fleetmesh_core.crypto package provides cryptographic operations required
for zero-trust communication, message sealing, and zero-knowledge verification.
2.1. Core Crypto Utilities
secp256k1, HKDF and envelope commitments. Standard library only.
Everything the protocol needs below the event layer, in one readable file. It is not constant-time and it is not for production key handling: it exists so that the mechanisms in this package are executable and testable, and so an implementer has something to compare against.
Sources of truth: BIP-340 for Schnorr, RFC 5869 for HKDF, and schema/constants.json for every label. Nothing here hardcodes a domain string.
- fleetmesh_core.crypto.crypto.lift_x(x)[source]
The even-y point with this x, per BIP-340. None if x is not on the curve.
- fleetmesh_core.crypto.crypto.hkdf(ikm, info, salt, length=32)[source]
RFC 5869. Both stages carry a domain string; see schema/constants.json. length is 1..8160 (255 blocks of SHA-256), as the RFC bounds it.
- fleetmesh_core.crypto.crypto.commit(payload_bytes, blinding_hex)[source]
C = SHA256(blinding || payload). Binding by collision resistance, hiding by the 32-byte blinding the subject already receives in the payload.
- fleetmesh_core.crypto.crypto.open_commit(commitment_hex, payload_bytes, blinding_hex)[source]
True if the commitment opens to this payload under this blinding.
- fleetmesh_core.crypto.crypto.canonical(obj)[source]
The serialisation every digest in this protocol is taken over.
UTF-8 with only the escapes JSON mandates: a non-ASCII character is written as itself, never as uXXXX. json.dumps’s ensure_ascii default is a Python habit, not the wire, and it hashed differently from every other language.
2.2. Key Management & Keypairs
The three keys a node holds, and their Multikey encodings:
node secp256k1, x-only; the nostr identity and the did:nostr subject.
BIP-340 signatures come from fleetmesh_core/crypto/crypto.py. multicodec 0xe7.
agreement X25519; every DIDComm v2 envelope. multicodec 0xec.
transport Ed25519; iroh NodeId, libp2p PeerId, gossipsub StrictSign. 0xed.
A Multikey here is multibase ‘f’ (lowercase hex) over the multicodec varint and the public key, which is why a descriptor’s key tags read fec01<x25519> and fed01<ed25519>: 0xec and 0xed each encode as two varint bytes, ec 01 and ed 01. The node key is a compressed secp256k1 point, fe70102<x>. constants.json crypto names all three; nothing here is a choice.
- fleetmesh_core.crypto.keys.parse_multikey(s)[source]
(kind, raw 32 bytes). Rejects anything that is not one of the three.
- fleetmesh_core.crypto.keys.agreement_public(raw)[source]
- Parameters:
raw (bytes)
- Return type:
X25519PublicKey
- fleetmesh_core.crypto.keys.raw_public(key)[source]
- Parameters:
key (X25519PublicKey | Ed25519PublicKey)
- Return type:
- Parameters:
priv (X25519PrivateKey)
their_pub (X25519PublicKey)
- Return type:
2.3. Elliptic Curves & Math
secp256k1 Jacobian arithmetic, fixed-base comb, and windowed scalar multiplication.
Same answers as fleetmesh_core/crypto/crypto.py with ~50x acceleration: - Jacobian coordinates: (X, Y, Z) representing (X/Z^2, Y/Z^3), avoiding modular inversions until the final conversion. - 4-bit comb for G: precomputed multiples of the generator point G, reducing G-scalar multiplication to 64 additions and 0 doublings. - 4-bit windowed multiplication for variable points: ECDH and verification. - 100% equivalent to BIP-340 Schnorr signatures and RFC 5869 HKDF.
- fleetmesh_core.crypto.curve.mul_g(k)[source]
k * G, affine, or None. No doublings: one mixed addition per window.
- fleetmesh_core.crypto.curve.mul(k, point)[source]
k * point for a point not known in advance. 4-bit window.
- fleetmesh_core.crypto.curve.mul_add(a, b, point)[source]
a * G + b * point, which is the verification equation, in one pass.
- fleetmesh_core.crypto.curve.schnorr_sign(msg32, sk_hex, aux=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')[source]
- fleetmesh_core.crypto.curve.install()[source]
Point fleetmesh_core.crypto’s four hot functions at this module.
- Return type:
2.4. NIP-44 & ChaCha20-Poly1305 Sealing
NIP-44 v2: the envelope scheme constants.json names as nip44/2.
ChaCha20 with HMAC-SHA256 in encrypt-then-MAC. The conversation key is HKDF-extract over the secp256k1 ECDH x-coordinate under the salt “nip44-v2”; per message, HKDF-expand under the 32-byte nonce yields the cipher key, the cipher nonce and the MAC key. Plaintext is length-prefixed and padded to a power-of-two schedule so message sizes leak less.
Used by kind 30801 and 30811 content, the compute ask’s enc field, and the NIP-59 gift wraps this node uses as its transport. Pinned to the vectors published with the NIP (meshnode: node/tests/testdata/nip44.vectors.json).
This module needs the cryptography package for ChaCha20, as didcomm.py does.
- exception fleetmesh_core.crypto.nip44.Nip44Error[source]
Bases:
ValueError
- fleetmesh_core.crypto.nip44.conversation_key(sec_hex, pub_hex)[source]
HKDF-extract(salt=”nip44-v2”, ikm=ECDH x-coordinate). Symmetric in the pair.
- fleetmesh_core.crypto.nip44.message_keys(conv_key, nonce)[source]
(chacha_key, chacha_nonce, hmac_key) = HKDF-expand(conv_key, nonce, 76).
- fleetmesh_core.crypto.nip44.calc_padded_len(unpadded_len)[source]
The schedule alone. pad() enforces the 1..65535 limit; the NIP’s own vectors exercise this function past it.
- fleetmesh_core.crypto.nip44.decode_payload(payload)[source]
(nonce, ciphertext, mac). Every length check the NIP lists, before any crypto.
2.5. Giftwrap (NIP-59 / NIP-44)
NIP-59 gift wraps: the control transport that always works.
A DIDComm envelope travels to a peer as the content of a kind 13 seal signed by the sender, itself the content of a kind 21059 wrap signed by a key used once and thrown away. Both layers are nip44/2 to the recipient’s node key. The NIP says kind 21059 (ephemeral) by default and kind 1059 when store-and-forward is required, and that this binding always works, which is what makes the transport ladder safe to attempt in order.
The seal’s created_at, and a stored wrap’s, are randomised up to two days into the past as NIP-59 recommends, so a relay that keeps the wrap cannot line messages up by time. A live wrap is dated now: relays refuse an ephemeral event older than about a minute (strfry and the public relays alike), so a skewed one is never delivered, and an event nothing stores gives a relay nothing to order. The seal is never seen by a relay, so its skew is what hides the sender’s clock from the recipient. Signing is BIP-340 from crypto.py; ids are computed as every nostr event’s is.
- exception fleetmesh_core.crypto.giftwrap.GiftWrapError[source]
Bases:
ValueError
- fleetmesh_core.crypto.giftwrap.verify_event(ev)[source]
NIP-01: the id is the hash of the serialised event and the signature is BIP-340 over that id by the event’s pubkey.
- fleetmesh_core.crypto.giftwrap.wrap_created_at(now, kind, rng)[source]
When a wrap says it was made. Live: now, or relays drop it as an expired ephemeral event. Stored: skewed, so the relay keeping it learns nothing from the order. The rng is drawn either way so the one-time key and nonces that follow it are the same bytes for the same rng.
- fleetmesh_core.crypto.giftwrap.seal_created_at(now, rng=None)[source]
When a seal says it was made: now skewed back up to SKEW_MAX, as NIP-59 asks, so a relay that keeps a stored wrap cannot order messages by the sender’s clock. The seal never reaches a relay, so a skewed seal is always delivered.
Public for the one caller outside this module: control.seal builds the seal itself when the sender is an event signer (a browser extension, a remote signer) and needs the same date a wrap’s own seal would carry.
- fleetmesh_core.crypto.giftwrap.wrap_seal(seal, recipient_pk, now, kind=21059, rng=None)[source]
Wrap an already signed kind 13 seal.
The seal is the caller’s - signed by an event signer (a browser extension, a remote signer), whose NIP-44 step is its own - so only the outer layer is made here: a one-time key, the seal as the content, addressed to recipient_pk. Returns the wrap event.
- fleetmesh_core.crypto.giftwrap.wrap(payload, sender_sk, recipient_pk, now, kind=21059, rng=None)[source]
payload: any JSON-serialisable object (a DIDComm JWE here).
rng, when given, is the only source of randomness - skew, one-time key and both NIP-44 nonces - so the same rng yields the same bytes.
Returns the wrap event. The seal is signed by the sender so the recipient learns who wrote it after unwrapping; the wrap is signed by a one-time key so nobody else does.
- fleetmesh_core.crypto.giftwrap.unwrap(wrap_event, recipient_sk, now=None)[source]
(payload, sender_pk). Every layer is checked: the wrap’s signature and addressing, the seal’s signature, and that the seal’s author is the key the inner ciphertext was agreed with. With now, the wrap’s and the seal’s created_at must also lie within the window RETENTION describes; without it (offline tooling, tests of the cryptography alone) age is not judged.
2.6. Zero-Knowledge Groth16 Verifier
Pure-Python BN254 (alt_bn128) pairing cryptography and Groth16 verifier.
Implements pairing-friendly elliptic curve arithmetic over BN254 for off-chain zero-knowledge proof verification without external C dependencies: - Base field FQ (mod P) - Quadratic extension FQ2 = FQ[u] / (u^2 + 1) - Degree-12 extension FQ12 = FQ[w] / (w^12 - 18*w^6 + 82) - G1 curve over FQ: y^2 = x^3 + 3 - G2 twist curve over FQ2: y^2 = x^3 + 3 / (9 + u) - Optimal Ate pairing and multi-Miller loop - Groth16 zk-SNARK verification conforming to compute:zk-verify-groth16/1.0
Portable (fleetmesh_core): a ZK receipt is part of the wire contract, so a second implementation verifies exactly this. Pinned to vectors/groth16.json.
- fleetmesh_core.crypto.zk.inv_mod(a, m=21888242871839275222246405745257275088696311157297823662689037894645226208583)[source]
Modular inverse via Fermat’s little theorem.
- class fleetmesh_core.crypto.zk.FQ2[source]
Bases:
objectQuadratic extension field F_p[u] / (u^2 + 1).
- c0
- c1
- class fleetmesh_core.crypto.zk.FQ12[source]
Bases:
objectDegree-12 extension field F_p[w] / (w^12 - 18*w^6 + 82).
- coeffs
- fleetmesh_core.crypto.zk.double_g1(pt)
Homogeneous projective point doubling.
- fleetmesh_core.crypto.zk.add_g1(p1, p2)
Homogeneous projective point addition.
- fleetmesh_core.crypto.zk.mul_g1(pt, n)
Scalar multiplication via double-and-add.
- fleetmesh_core.crypto.zk.double_g2(pt)
Homogeneous projective point doubling.
- fleetmesh_core.crypto.zk.add_g2(p1, p2)
Homogeneous projective point addition.
- fleetmesh_core.crypto.zk.mul_g2(pt, n)
Scalar multiplication via double-and-add.
- fleetmesh_core.crypto.zk.double_g12(pt)
Homogeneous projective point doubling.
- fleetmesh_core.crypto.zk.add_g12(p1, p2)
Homogeneous projective point addition.
- fleetmesh_core.crypto.zk.linefunc(p1, p2, t)[source]
Evaluate line between P1 and P2 at point T in projective coords.
- fleetmesh_core.crypto.zk.multi_miller_loop(pairs)[source]
Accumulated multi-Miller loop over multiple G2/G1 pairs.
- fleetmesh_core.crypto.zk.set_pairing_accelerator(fn)[source]
Register native/accelerated multi-pairing backend function.
- fleetmesh_core.crypto.zk.set_groth16_accelerator(fn)[source]
Register native/accelerated Groth16 verification backend function.
- fleetmesh_core.crypto.zk.is_pairing_accelerated()[source]
Check if an accelerated multi-pairing backend is currently active.
- Return type:
- fleetmesh_core.crypto.zk.is_groth16_accelerated()[source]
Check if an accelerated Groth16 verifier backend is currently active.
- Return type:
- fleetmesh_core.crypto.zk.multi_pairing(pairs)[source]
Evaluate product of pairings: prod_k e(Q_k, P_k).
- fleetmesh_core.crypto.zk.parse_scalar(hex_str)[source]
Parse 0x-prefixed hex string into integer modulo R.
- fleetmesh_core.crypto.zk.parse_g1(pt_coords)[source]
Parse [x_hex, y_hex] into projective G1 point.
- fleetmesh_core.crypto.zk.parse_g2(pt_coords)[source]
Parse [[x0, x1], [y0, y1]] into projective G2 point.
- class fleetmesh_core.crypto.zk.VerificationKey[source]
Bases:
objectRepresents a Groth16 verification key circuit.
- fleetmesh_core.crypto.zk.register_verification_key(vk)[source]
- Parameters:
vk (VerificationKey)
- Return type:
- fleetmesh_core.crypto.zk.is_on_curve_g1(pt)[source]
y^2 == x^3 + 3 in affine coordinates; the point at infinity counts.
- fleetmesh_core.crypto.zk.is_on_curve_g2(pt)[source]
y^2 == x^3 + b/xi on the twist; the point at infinity counts.
- fleetmesh_core.crypto.zk.in_g2_subgroup(pt)[source]
[r]Q == O. BN254’s G1 has prime order r so on-curve is enough there, but the twist has a large cofactor: a point outside G2 satisfies the curve equation yet breaks the pairing’s bilinearity assumptions, and a prover can use one to smuggle a proof that verifies for the wrong statement. One scalar multiplication costs far less than a pairing.
- fleetmesh_core.crypto.zk.verify_groth16(vk, public_inputs, proof)[source]
Verify a Groth16 proof against public inputs and verification key.
Evaluates the 4-pairing equation: e(-A, B) * e(alpha, beta) * e(vk_x, gamma) * e(C, delta) == 1 where vk_x = IC[0] + sum_i (x_i * IC[i+1]).
Malformed input (unparseable coordinates, points off the curve or, for B, outside G2) is an invalid proof, never an exception: the caller is settling a payment on this answer and must not confuse a prover’s garbage with its own failure.
- fleetmesh_core.crypto.zk.verify_groth16_job(job_input, custom_vk=None)[source]
Execute a compute:zk-verify-groth16/1.0 job and return schema-valid output.
- Parameters:
custom_vk (VerificationKey | None)
- Return type:
2.7. Bech32 Encoding
Bech32 for NIP-19 identifiers (npub), and nothing else.
A leaf module: it imports nothing from node/, so the transport layer and the CLI can both reach it without one depending on the other. It used to live in node/commands/base.py, where node/fips_transport.py fetched it lazily from the CLI package, which made a transport module depend on the command line that drives it (a 17-module import cycle, lazy only by luck of where the imports sat).
2.8. RFC 9421 HTTP Message Signatures
HTTP Message Signatures for ActivityPub federation.
Supports: - draft-cavage-http-signatures-12 (Mastodon, Misskey, Lemmy standard). - RFC 9421 HTTP Message Signatures compatibility. - Ed25519 and RSA-SHA256 signing and verification. - In-band Digest validation (SHA-256).
- exception fleetmesh_core.crypto.http_signatures.HttpSignatureError[source]
Bases:
FleetmeshErrorBase error for HTTP Message Signature failures.
- fleetmesh_core.crypto.http_signatures.compute_digest(body)[source]
Compute standard RFC 3230 / draft-cavage Digest header value for a request body.
- fleetmesh_core.crypto.http_signatures.parse_signature_header(header_value)[source]
Parse comma-separated key=”value” pairs from a Signature header.
- fleetmesh_core.crypto.http_signatures.sign_http_request(method, url, headers, body, private_key, key_id, algorithm=None, sign_headers=('(request-target)', 'host', 'date', 'digest'))[source]
Sign an outbound HTTP request, returning updated headers with Signature, Date, and Digest.
2.9. SSB Secret Handshake & Box Stream
Secure Scuttlebutt (SSB) Cryptography: Secret Handshake (SSB-SHS) & Box Stream (SSB-BoxStream).
Standard library and cryptography (Poly1305, Ed25519, X25519) only. Supports: - Dominic Tarr’s 4-phase Secret Handshake (SSB-SHS) authenticated key exchange. - Birational Ed25519 <-> Curve25519 (X25519) point and scalar translation. - Verified XSalsa20-Poly1305 symmetric authenticated encryption (crypto_secretbox). - Box Stream (SSB-BoxStream) 34-byte packet framing with Poly1305 MAC tag and goodbye termination. - SSB feed identity format (@<base64>.ed25519).
- exception fleetmesh_core.crypto.ssb.SSBCryptoError[source]
Bases:
FleetmeshErrorBase error for Secure Scuttlebutt cryptographic operations.
- fleetmesh_core.crypto.ssb.format_ssb_feed_id(ed25519_pk)[source]
Format 32-byte Ed25519 public key as SSB feed ID (@<base64>.ed25519).
- fleetmesh_core.crypto.ssb.parse_ssb_feed_id(feed_id)[source]
Parse SSB feed ID string into 32-byte Ed25519 public key.
- fleetmesh_core.crypto.ssb.ed25519_pk_to_curve25519(ed_pk)[source]
Map Ed25519 public key to Curve25519 (X25519) u-coordinate: u = (1 + y) / (1 - y) mod p.
- fleetmesh_core.crypto.ssb.ed25519_sk_to_curve25519(ed_sk)[source]
Derive Curve25519 private scalar from Ed25519 private seed.
- fleetmesh_core.crypto.ssb.crypto_auth(msg, key)[source]
NaCl crypto_auth: first 32 bytes of HMAC-SHA-512.
- fleetmesh_core.crypto.ssb.crypto_auth_verify(tag, msg, key)[source]
Verify NaCl crypto_auth tag in constant time.
- fleetmesh_core.crypto.ssb.crypto_secretbox_easy(m, nonce, key)[source]
NaCl crypto_secretbox_easy: XSalsa20-Poly1305 authenticated encryption.
- fleetmesh_core.crypto.ssb.crypto_secretbox_open_easy(c, nonce, key)[source]
NaCl crypto_secretbox_open_easy: verify and decrypt.
- class fleetmesh_core.crypto.ssb.SHSClient[source]
Bases:
objectClient-side state machine for 4-phase Secret Handshake.
- __init__(local_ed25519_sk, server_ed25519_pk, network_key=b'\xd4\xa1\xcb\x88\xa6o\x02\xf8\xdbc\\\xe2dA\xcc]\xac\x1b\x08B\x0c\xea\xac#\x089\xb7U\x84Z\x9f\xfb', ephemeral_sk=None)[source]
- verify_server_hello(msg2)[source]
Phase 2: Verify Server Hello (64 bytes) and derive initial shared secrets.
- Parameters:
msg2 (bytes)
- Return type:
None
- create_client_authenticate()[source]
Phase 3: Produce Client Authenticate message (112 bytes).
- Return type:
- class fleetmesh_core.crypto.ssb.SHSServer[source]
Bases:
objectServer-side state machine for 4-phase Secret Handshake.
- __init__(local_ed25519_sk, network_key=b'\xd4\xa1\xcb\x88\xa6o\x02\xf8\xdbc\\\xe2dA\xcc]\xac\x1b\x08B\x0c\xea\xac#\x089\xb7U\x84Z\x9f\xfb', ephemeral_sk=None)[source]
- verify_client_hello(msg1)[source]
Phase 1: Verify Client Hello (64 bytes).
- Parameters:
msg1 (bytes)
- Return type:
None
- verify_client_authenticate(msg3)[source]
Phase 3: Verify Client Authenticate (112 bytes) and return client Ed25519 pubkey.
- class fleetmesh_core.crypto.ssb.BoxStreamEncryptor[source]
Bases:
objectFrames and encrypts duplex stream packets.