Source code for fleetmesh_core.crypto.giftwrap

"""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.
"""
from __future__ import annotations

import json
import os
from typing import Any, Callable, Mapping, Optional

from . import crypto, nip44

from ..wire import schema_files

from ..storage import store
from ..wire.interfaces import NostrEvent, TagList

SEAL: int = 13
WRAP_LIVE: int = 21059
WRAP_STORED: int = 1059
TWO_DAYS: int = 2 * 86400
# A receiver subscribes for wraps since its own clock minus two days. A wrap
# skewed the full two days back by a sender whose clock is behind lands
# before that `since` and the relay never delivers it: one message in three
# thousand, silently, at the skew the protocol tolerates. So the skew stops
# twice the tolerance short of the window.
_CONSTANTS = schema_files.load_constants()
SKEW_MAX: int = TWO_DAYS - 2 * int(_CONSTANTS['grant']['max_clock_skew_seconds'])
# How long a wrap or seal stays openable after it was made. A relay stores
# wraps for two days and a sender may have skewed its timestamp SKEW_MAX
# back, so an honest wrap can be that old; the retention gives a week's
# slack past it for a node that was down. Anything older is a wrap being
# replayed from a store, and the message it carries has already been acted
# on or never will be. Forward, the limit is SKEW_MAX: the protocol never
# dates a wrap ahead of now on purpose, and a future-dated wrap is one a
# relay would hold and deliver long after the sender meant it.
RETENTION: int = 7 * 86400


[docs]class GiftWrapError(ValueError): pass
def _signed(sk_hex: str, created_at: int, kind: int, tags: TagList, content: str) -> NostrEvent: return store.make_signed_event(sk_hex, created_at, kind, tags, content)
[docs]def verify_event(ev: Mapping[str, Any]) -> bool: """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.""" return bool(store.verify_event(ev))
def _skew(now: int, rng: Callable[[int], bytes]) -> int: # Draw the skew from the same source as the keys and nonces: one rng # argument makes a wrap fully deterministic (vectors), none makes it random. return now - int.from_bytes(rng(4), 'big') % (SKEW_MAX + 1)
[docs]def wrap_created_at(now: int, kind: int, rng: Callable[[int], bytes]) -> int: """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.""" skewed = _skew(now, rng) return now if kind == WRAP_LIVE else skewed
[docs]def seal_created_at(now: int, rng: Optional[Callable[[int], bytes]] = None) -> int: """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. """ return _skew(now, rng or os.urandom)
def _wrap_seal( seal: Mapping[str, Any], recipient_pk: str, now: int, kind: int, draw: Callable[[int], bytes], ) -> NostrEvent: """The outer layer alone: one-time key, the seal as its NIP-44 content, the wrap's date and its signature. `wrap` and `wrap_seal` share exactly these draws in this order, so the same rng bytes give the same wrap whichever signer made the seal.""" once = draw(32).hex() conv_w = nip44.conversation_key(once, recipient_pk) sealed = json.dumps(seal, separators=(',', ':'), sort_keys=True, ensure_ascii=False) return _signed(once, wrap_created_at(now, kind, draw), kind, [['p', recipient_pk]], nip44.encrypt(sealed, conv_w, draw(32)))
[docs]def wrap_seal( seal: Mapping[str, Any], recipient_pk: str, now: int, kind: int = WRAP_LIVE, rng: Optional[Callable[[int], bytes]] = None, ) -> NostrEvent: """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. """ if kind not in (WRAP_LIVE, WRAP_STORED): raise GiftWrapError('a wrap is kind 21059 or kind 1059') if not isinstance(seal, Mapping) or seal.get('kind') != SEAL: raise GiftWrapError('the sealed event is not a kind 13 seal') try: return _wrap_seal(seal, recipient_pk, now, kind, rng or os.urandom) except (nip44.Nip44Error, ValueError) as e: raise GiftWrapError('the seal does not fit one wrap (%s); fragment it' % e)
[docs]def wrap( payload: Any, sender_sk: str, recipient_pk: str, now: int, kind: int = WRAP_LIVE, rng: Optional[Callable[[int], bytes]] = None, ) -> NostrEvent: """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. """ if kind not in (WRAP_LIVE, WRAP_STORED): raise GiftWrapError('a wrap is kind 21059 or kind 1059') body = json.dumps(payload, separators=(',', ':'), sort_keys=True, ensure_ascii=False) try: conv = nip44.conversation_key(sender_sk, recipient_pk) except (nip44.Nip44Error, ValueError) as e: raise GiftWrapError('invalid key for gift wrap: %s' % e) draw = rng or os.urandom try: seal = _signed(sender_sk, _skew(now, draw), SEAL, [], nip44.encrypt(body, conv, draw(32))) return _wrap_seal(seal, recipient_pk, now, kind, draw) except (nip44.Nip44Error, ValueError) as e: # Two NIP-44 layers, each base64: a payload over about forty kilobytes # no longer fits the outer one, and the error named the inner size. raise GiftWrapError('a payload of %d bytes does not fit one wrap (%s); fragment it' % (len(body), e))
def _in_date(ev: Mapping[str, Any], now: Optional[int], what: str) -> None: if now is None: return created = ev.get('created_at') if not isinstance(created, int): raise GiftWrapError('%s has no created_at' % what) if created < now - SKEW_MAX - RETENTION: raise GiftWrapError('%s is older than %d seconds' % (what, SKEW_MAX + RETENTION)) if created > now + SKEW_MAX: raise GiftWrapError('%s is dated more than %d seconds ahead' % (what, SKEW_MAX))
[docs]def unwrap(wrap_event: Mapping[str, Any], recipient_sk: str, now: Optional[int] = None) -> tuple[Any, str]: """(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.""" try: my_pk = crypto.pubkey(recipient_sk) except ValueError as e: raise GiftWrapError('invalid recipient key: %s' % e) if wrap_event.get('kind') not in (WRAP_LIVE, WRAP_STORED): raise GiftWrapError('not a gift wrap') _in_date(wrap_event, now, 'wrap') if not any(t[:2] == ['p', my_pk] for t in wrap_event.get('tags', [])): raise GiftWrapError('not addressed to me') if not verify_event(wrap_event): raise GiftWrapError('wrap signature does not verify') try: conv_w = nip44.conversation_key(recipient_sk, wrap_event['pubkey']) seal = json.loads(nip44.decrypt(wrap_event['content'], conv_w)) except (nip44.Nip44Error, ValueError, KeyError, TypeError) as e: raise GiftWrapError('wrap does not open: %s' % e) if not isinstance(seal, Mapping): raise GiftWrapError('seal is not a JSON object') if seal.get('kind') != SEAL or seal.get('tags'): raise GiftWrapError('inner event is not a seal') if not verify_event(seal): raise GiftWrapError('seal signature does not verify') _in_date(seal, now, 'seal') try: conv = nip44.conversation_key(recipient_sk, seal['pubkey']) payload = json.loads(nip44.decrypt(seal['content'], conv)) except (nip44.Nip44Error, ValueError, KeyError, TypeError) as e: raise GiftWrapError('seal does not open: %s' % e) return payload, seal['pubkey']