Add device keys, revocation and libp2p gossip with sync

- identity: 12-word recovery phrase, device certificates, revocations,
  device key storage; the identity key is never stored on a node
- listing: signed by a device with an embedded certificate, domain-separated
  signatures, ErrTimeWindow for clock-related failures, region helpers
- store: revocations purge a device's listings; keyset-paged Since for sync
- p2p: gossipsub topic per geohash region plus a global revocation topic,
  validators run before relaying, /allmende/1/sync catch-up protocol,
  bootstrap peers and mDNS
- docs: key model, replication and conflict rules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 17:43:25 +01:00
co-authored by Claude Sonnet 5.5
parent 08f6441f03
commit d3efe5a3a7
16 changed files with 2306 additions and 119 deletions
+59 -14
View File
@@ -9,16 +9,41 @@ running a node; searching is browser-only through any node's HTTP gateway.
search API on every node. search API on every node.
- **Browsers** never join the P2P network. They fetch from any gateway and - **Browsers** never join the P2P network. They fetch from any gateway and
**verify signatures themselves**, so a gateway cannot forge listings. **verify signatures themselves**, so a gateway cannot forge listings.
- **Sharding**: listings are gossiped per `geohash` region (precision 6, ~1 km) - **Sharding**: a listing carries a precision-6 `geohash` (~1 km) and is gossiped
and category. Nodes subscribe to the regions they care about and index them on the topic of its precision-3 *region* (~150 km cell),
locally. `/allmende/1/listings/<region>`. Nodes subscribe to the regions they care
about, replicate them, and index them locally. Fine-grained filtering
(precision, kind, category, price) happens in local search.
- **Discovery**: configured bootstrap peers plus mDNS on the local network;
gossipsub peer exchange spreads the mesh. A Kademlia DHT can be added later
without protocol changes.
- **License**: AGPL-3.0, so modified nodes and gateways must publish their source. - **License**: AGPL-3.0, so modified nodes and gateways must publish their source.
- **Launch scope**: one German state or metro area. - **Launch scope**: one German state or metro area.
## Identity ## Identity and keys
An ed25519 keypair is the identity. No accounts. The public key (64 hex chars) Designed so non-technical people can use it and a compromised node can be
is the `author`. revoked. There are no accounts.
- **Identity key** (ed25519): derived from a **12-word recovery phrase** shown
once at first run. Its public key is the `author`. It signs *certificates*
and *revocations* only, and is **deleted from the machine** right after
enrolling the first device.
- **Device key** (ed25519): generated per node, stored on that node. It signs
listings and is also the node's libp2p identity, so the node's peer ID derives
from the `device` field. There is no separate `endpoint` field.
- **Certificate**: `{v, author, device, issued_at, expires_at (<= 1 year), sig}`
signed by the identity key. Travels inside every listing.
- **Revocation**: `{v, author, device, revoked_at, cert_expires_at, pow, sig}`
signed by the identity key, gossiped on `/allmende/1/revocations` (all nodes
subscribe), kept until `cert_expires_at`. A revoked device's signatures are
void: its listings are purged and refused. The owner restores the identity
from the phrase on a new machine, revokes the old device, enrolls a new one
and republishes (higher `seq`).
- Lost phrase and lost device: start a new identity. Cheap, because listings
expire within 30 days anyway.
- Signed payloads are domain-separated (`allmende-cert-v1\n`,
`allmende-revocation-v1\n`, `allmende-listing-v1\n` prefixes).
## Listing record ## Listing record
@@ -28,8 +53,10 @@ Canonical JSON (RFC 8785), integers only. See `internal/listing`.
|---|---| |---|---|
| `v` | format version, currently 1 | | `v` | format version, currently 1 |
| `id` | 32 hex, stable across versions | | `id` | 32 hex, stable across versions |
| `author` | hex ed25519 public key | | `author` | identity public key (hex) |
| `seq` | higher replaces lower for same `id` + `author` | | `device` | signing device's public key (hex) |
| `cert` | certificate binding `device` to `author` |
| `seq` | higher replaces lower for the same `author` + `id` (any device of the author may supersede) |
| `created_at`, `expires_at` | unix seconds; lifetime <= 30 days, owner re-signs to renew | | `created_at`, `expires_at` | unix seconds; lifetime <= 30 days, owner re-signs to renew |
| `tombstone` | deletion marker: higher `seq`, no content, only routing `geohash` | | `tombstone` | deletion marker: higher `seq`, no content, only routing `geohash` |
| `kind` | `rent` or `sale` | | `kind` | `rent` or `sale` |
@@ -39,10 +66,9 @@ Canonical JSON (RFC 8785), integers only. See `internal/listing`.
| `area_m2`, `rooms_x2` | rooms * 2 (2.5 rooms = 5) | | `area_m2`, `rooms_x2` | rooms * 2 (2.5 rooms = 5) |
| `features`, `title`, `description` | bounded text | | `features`, `title`, `description` | bounded text |
| `images` | `{hash, thumb_hash}`, content-addressed, **no location** | | `images` | `{hash, thumb_hash}`, content-addressed, **no location** |
| `endpoint` | owner's peer ID | | `delegate` | optional always-on host's peer ID, chosen by the owner |
| `delegate` | optional always-on host chosen by the owner |
| `pow` | nonce; sha256 of the unsigned canonical bytes has N leading zero bits | | `pow` | nonce; sha256 of the unsigned canonical bytes has N leading zero bits |
| `sig` | ed25519 over the unsigned canonical bytes | | `sig` | device signature over the unsigned canonical bytes (with context prefix) |
There is **no address, name, phone or email** in the record. There is **no address, name, phone or email** in the record.
@@ -70,12 +96,31 @@ owner is offline. Images and contact details need the owner's node or its
delegate. UI shows an "owner offline" badge; listings expire if not re-signed delegate. UI shows an "owner offline" badge; listings expire if not re-signed
within 30 days. within 30 days.
## Replication
- **Gossip**: every message is checked by a topic validator *before* it is
relayed: canonical encoding, size, signature chain, proof-of-work, region
match, not revoked. Invalid messages are rejected (the relaying peer loses
score); clock-related failures (expired, future) are ignored without penalty.
Publishers flood to all subscribed peers so a listing published right after
connecting is not lost before the mesh forms.
- **Conflict rules** (identical on every node, so replicas converge): keyed by
`(author, id)`; higher `seq` wins; equal `seq` -> smaller hash wins;
tombstones are stored like any version so old copies cannot resurrect a
deleted listing.
- **Sync** (`/allmende/1/sync`): on connecting to a peer (at most every
5 minutes) a node pulls revocations first, then each subscribed region,
paged by a `(created_at, author, id)` keyset cursor. Tombstones are included
so deletions propagate. Currently a full pull; a digest-based incremental
sync is future work.
## Spam ## Spam
Proof-of-work per listing plus subscribable blocklists. The format leaves room Proof-of-work per listing and per revocation, plus subscribable blocklists
for vouching signatures later. (not built yet). The format leaves room for vouching signatures later.
## Open ## Open
Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti- Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti-
discrimination (AGG) content rules. discrimination (AGG) content rules, blocklists, peer scoring and rate limits,
incremental sync, DHT discovery, HTTP gateway and web UI, image hosting.
+94 -2
View File
@@ -2,15 +2,107 @@ module git.stinnesbeck.com/nils/allmende
go 1.27.3 go 1.27.3
require modernc.org/sqlite v1.62.0 require (
github.com/libp2p/go-libp2p v0.52.0
github.com/libp2p/go-libp2p-pubsub v0.19.0
github.com/tyler-smith/go-bip39 v1.1.0
modernc.org/sqlite v1.62.0
)
require ( require (
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 // indirect
filippo.io/keygen v1.0.0 // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
github.com/dunglas/httpsfv v1.1.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect github.com/dustin/go-humanize v1.1.0 // indirect
github.com/filecoin-project/go-clock v0.1.0 // indirect
github.com/flynn/noise v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/huin/goupnp v1.3.1 // indirect
github.com/ipfs/go-cid v0.6.2 // indirect
github.com/jackpal/go-nat-pmp v1.1.0 // indirect
github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect
github.com/klauspost/cpuid/v2 v2.4.2 // indirect
github.com/koron/go-ssdp v0.9.2 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/libp2p/go-flow-metrics v0.3.0 // indirect
github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect
github.com/libp2p/go-msgio v0.3.0 // indirect
github.com/libp2p/go-netroute v0.4.0 // indirect
github.com/libp2p/go-reuseport v0.4.0 // indirect
github.com/libp2p/go-yamux/v5 v5.1.0 // indirect
github.com/libp2p/zeroconf/v2 v2.2.0 // indirect
github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd // indirect
github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-isatty v0.0.24 // indirect
github.com/miekg/dns v1.1.73 // indirect
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b // indirect
github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/mr-tron/base58 v1.3.0 // indirect
github.com/multiformats/go-base32 v0.1.0 // indirect
github.com/multiformats/go-base36 v0.2.0 // indirect
github.com/multiformats/go-multiaddr v0.16.1 // indirect
github.com/multiformats/go-multiaddr-dns v0.6.0 // indirect
github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect
github.com/multiformats/go-multibase v0.3.0 // indirect
github.com/multiformats/go-multicodec v0.10.0 // indirect
github.com/multiformats/go-multihash v0.2.3 // indirect
github.com/multiformats/go-multistream v0.6.1 // indirect
github.com/multiformats/go-varint v0.1.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
github.com/pion/datachannel v1.5.10 // indirect
github.com/pion/dtls/v3 v3.1.2 // indirect
github.com/pion/ice/v4 v4.0.10 // indirect
github.com/pion/interceptor v0.1.40 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.16 // indirect
github.com/pion/rtp v1.8.19 // indirect
github.com/pion/sctp v1.8.39 // indirect
github.com/pion/sdp/v3 v3.0.18 // indirect
github.com/pion/srtp/v3 v3.0.6 // indirect
github.com/pion/stun/v3 v3.1.1 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/pion/transport/v4 v4.0.1 // indirect
github.com/pion/turn/v4 v4.0.2 // indirect
github.com/pion/webrtc/v4 v4.1.2 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.64.1 // indirect
github.com/quic-go/webtransport-go v0.13.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.49.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
go.uber.org/dig v1.19.0 // indirect
go.uber.org/fx v1.24.0 // indirect
go.uber.org/mock v0.6.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 // indirect
golang.org/x/mod v0.43.0 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/telemetry v0.0.0-20261111153349-cdaf7e97dd7b // indirect
golang.org/x/text v0.44.0 // indirect
golang.org/x/time v0.16.0 // indirect
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
google.golang.org/protobuf v1.36.12 // indirect
lukechampine.com/blake3 v1.4.1 // indirect
modernc.org/libc v1.80.1 // indirect modernc.org/libc v1.80.1 // indirect
modernc.org/mathutil v1.7.1 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect modernc.org/memory v1.12.1 // indirect
+240 -8
View File
@@ -1,25 +1,257 @@
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 h1:JA0fFr+kxpqTdxR9LOBiTWpGNchqmkcsgmdeJZRclZ0=
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
filippo.io/keygen v1.0.0 h1:u0/Fhxlgz3uPv+XxhfgTq3BJt5VesIPM5ue/OuG7qjQ=
filippo.io/keygen v1.0.0/go.mod h1:9nnw1SlYHYuPSo/3wjQzNjSbeHlq2NsKo5iEtfJPWP0=
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6fCvaEpkhyW3qAicT0TnGtyht/UrgvOwMcEgLb7Aw=
github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU=
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U=
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/dunglas/httpsfv v1.1.2 h1:432E+FKy2DLMbVcZeAnOuM7nhyJ4vTiH7b9iXJ/Dkmc=
github.com/dunglas/httpsfv v1.1.2/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/filecoin-project/go-clock v0.1.0 h1:SFbYIM75M8NnFm1yMHhN9Ahy3W5bEZV9gd6MPfXbKVU=
github.com/filecoin-project/go-clock v0.1.0/go.mod h1:4uB/O4PvOjlx1VCMdZ9MyDZXRm//gkj1ELEbxfI1AZs=
github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg=
github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/huin/goupnp v1.3.1 h1:n8259zVoE4BU7dBCQEUlwZK1h0Z3pxZ58ov0xbJuIQU=
github.com/huin/goupnp v1.3.1/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
github.com/ipfs/go-cid v0.6.2 h1:VuGwJd+KJTaMJ4S4d5EEf9SXc17YUblS5axCbocn9YE=
github.com/ipfs/go-cid v0.6.2/go.mod h1:Xhwg8NzHeK9xPCEZkCw4idzPiuNMpX3fARuI5Iwj1Lo=
github.com/jackpal/go-nat-pmp v1.1.0 h1:UInMLPV1VQdP860ggNiz0YxGvJH/bWzxL099y+1EdCs=
github.com/jackpal/go-nat-pmp v1.1.0/go.mod h1:m9o4DK1wHA4h2pPpErD5vwzWLf91tJcfNQ3QyUIbh5A=
github.com/jbenet/go-temp-err-catcher v0.1.0 h1:zpb3ZH6wIE8Shj2sKS+khgRvf7T7RABoLk/+KKHggpk=
github.com/jbenet/go-temp-err-catcher v0.1.0/go.mod h1:0kJRvmDZXNMIiJirNPEYfhpPwbGVtZVWC34vc5WLsDk=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/koron/go-ssdp v0.9.2 h1:s7YOSyV2Sch54U4+JGtiT+qgyUUKqbHbelgAV5PBCu0=
github.com/koron/go-ssdp v0.9.2/go.mod h1:AfRmwB0yUX/pCcB5dI7Z3947zo+sC3lXmqQOW8VO/TA=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8=
github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg=
github.com/libp2p/go-flow-metrics v0.3.0 h1:q31zcHUvHnwDO0SHaukewPYgwOBSxtt830uJtUx6784=
github.com/libp2p/go-flow-metrics v0.3.0/go.mod h1:nuhlreIwEguM1IvHAew3ij7A8BMlyHQJ279ao24eZZo=
github.com/libp2p/go-libp2p v0.52.0 h1:jMnbVokEwR/XYnu7J9VCPClbtvlkWPvv4kFGO6r5aKY=
github.com/libp2p/go-libp2p v0.52.0/go.mod h1:USTtm7OAlCwOlDlwGVgEGzKw4iizPcAFuZERQ+RWvtE=
github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94=
github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8=
github.com/libp2p/go-libp2p-pubsub v0.19.0 h1:9eyitBeXjW09XyDQF+EYL6RGRJ50Df1G9aTjB3XOMQQ=
github.com/libp2p/go-libp2p-pubsub v0.19.0/go.mod h1:BfhG/m4TM39nKlcW6myqsoUjsJhOPpSLBCo4OtHLweI=
github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA=
github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg=
github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0=
github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM=
github.com/libp2p/go-netroute v0.4.0 h1:sZZx9hyANYUx9PZyqcgE/E1GUG3iEtTZHUEvdtXT7/Q=
github.com/libp2p/go-netroute v0.4.0/go.mod h1:Nkd5ShYgSMS5MUKy/MU2T57xFoOKvvLR92Lic48LEyA=
github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s=
github.com/libp2p/go-reuseport v0.4.0/go.mod h1:ZtI03j/wO5hZVDFo2jKywN6bYKWLOy8Se6DrI2E1cLU=
github.com/libp2p/go-yamux/v5 v5.1.0 h1:8Qlxj4E9JGJAQVW6+uj2o7mqkqsIVlSUGmTWhlXzoHE=
github.com/libp2p/go-yamux/v5 v5.1.0/go.mod h1:tgIQ07ObtRR/I0IWsFOyQIL9/dR5UXgc2s8xKmNZv1o=
github.com/libp2p/zeroconf/v2 v2.2.0 h1:Cup06Jv6u81HLhIj1KasuNM/RHHrJ8T7wOTS4+Tv53Q=
github.com/libp2p/zeroconf/v2 v2.2.0/go.mod h1:fuJqLnUwZTshS3U/bMRJ3+ow/v9oid1n0DmyYyNO1Xs=
github.com/marcopolo/simnet v0.0.7 h1:DpH8BMGsF9+1w13L8rvCaAhb6nYJdY+dIXncDrssvUs=
github.com/marcopolo/simnet v0.0.7/go.mod h1:tfQF1u2DmaB6WHODMtQaLtClEf3a296CKQLq5gAsIS0=
github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd h1:br0buuQ854V8u83wA0rVZ8ttrq5CpaPZdvrK0LP2lOk=
github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd/go.mod h1:QuCEs1Nt24+FYQEqAAncTDPJIuGs+LxK1MCiFL25pMU=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c h1:bzE/A84HN25pxAuk9Eej1Kz9OUelF97nAc82bDquQI8=
github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c/go.mod h1:0SQS9kMwD2VsyFEB++InYyBJroV/FRmBgcydeSUcJms=
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b h1:z78hV3sbSMAUoyUMM0I83AUIT6Hu17AWfgjzIbtrYFc=
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b/go.mod h1:lxPUiZwKoFL8DUUmalo2yJJUCxbPKtm8OKfqr2/FTNU=
github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc h1:PTfri+PuQmWDqERdnNMiD9ZejrlswWrCpBEZgWOiTrc=
github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc/go.mod h1:cGKTAVKx4SxOuR/czcZ/E2RSJ3sfHs8FpHhQ5CWMf9s=
github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ=
github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM=
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
github.com/mr-tron/base58 v1.1.2/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/mr-tron/base58 v1.3.0 h1:K6Y13R2h+dku0wOqKtecgRnBUBPrZzLZy5aIj8lCcJI=
github.com/mr-tron/base58 v1.3.0/go.mod h1:2BuubE67DCSWwVfx37JWNG8emOC0sHEU4/HpcYgCLX8=
github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE=
github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI=
github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0=
github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4=
github.com/multiformats/go-multiaddr v0.1.1/go.mod h1:aMKBKNEYmzmDmxfX88/vz+J5IU55txyt0p4aiWVohjo=
github.com/multiformats/go-multiaddr v0.16.1 h1:fgJ0Pitow+wWXzN9do+1b8Pyjmo8m5WhGfzpL82MpCw=
github.com/multiformats/go-multiaddr v0.16.1/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0=
github.com/multiformats/go-multiaddr-dns v0.6.0 h1:yKIW08WJHSPJ8bDAT2O/5fypCaUu9Bjl8r/1eJ4XAW8=
github.com/multiformats/go-multiaddr-dns v0.6.0/go.mod h1:dwIQwdORZfnNQCeS7xLXyn+7626oRmMsVP30Uronhf0=
github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E=
github.com/multiformats/go-multiaddr-fmt v0.1.0/go.mod h1:hGtDIW4PU4BqJ50gW2quDuPVjyWNZxToGUh/HwTZYJo=
github.com/multiformats/go-multibase v0.3.0 h1:8helZD2+4Db7NNWFiktk2NePbF0boolBe6bDQvM4r68=
github.com/multiformats/go-multibase v0.3.0/go.mod h1:MoBLQPCkRTOL3eveIPO81860j2AQY8JwcnNlRkGRUfI=
github.com/multiformats/go-multicodec v0.10.0 h1:UpP223cig/Cx8J76jWt91njpK3GTAO1w02sdcjZDSuc=
github.com/multiformats/go-multicodec v0.10.0/go.mod h1:wg88pM+s2kZJEQfRCKBNU+g32F5aWBEjyFHXvZLTcLI=
github.com/multiformats/go-multihash v0.0.8/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew=
github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U=
github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM=
github.com/multiformats/go-multistream v0.6.1 h1:4aoX5v6T+yWmc2raBHsTvzmFhOI8WVOer28DeBBEYdQ=
github.com/multiformats/go-multistream v0.6.1/go.mod h1:ksQf6kqHAb6zIsyw7Zm+gAuVo57Qbq84E27YlYqavqw=
github.com/multiformats/go-varint v0.1.0 h1:i2wqFp4sdl3IcIxfAonHQV9qU5OsZ4Ts9IOoETFs5dI=
github.com/multiformats/go-varint v0.1.0/go.mod h1:5KVAVXegtfmNQQm/lCY+ATvDzvJJhSkUlGQV9wgObdI=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pion/datachannel v1.5.10 h1:ly0Q26K1i6ZkGf42W7D4hQYR90pZwzFOjTq5AuCKk4o=
github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oLo8Rs4Py/M=
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4=
github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw=
github.com/pion/interceptor v0.1.40 h1:e0BjnPcGpr2CFQgKhrQisBU7V3GXK6wrfYrGYaU6Jq4=
github.com/pion/interceptor v0.1.40/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM=
github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
github.com/pion/rtp v1.8.19 h1:jhdO/3XhL/aKm/wARFVmvTfq0lC/CvN1xwYKmduly3c=
github.com/pion/rtp v1.8.19/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
github.com/pion/sctp v1.8.39 h1:PJma40vRHa3UTO3C4MyeJDQ+KIobVYRZQZ0Nt7SjQnE=
github.com/pion/sctp v1.8.39/go.mod h1:cNiLdchXra8fHQwmIoqw0MbLLMs+f7uQ+dGMG2gWebE=
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
github.com/pion/srtp/v3 v3.0.6 h1:E2gyj1f5X10sB/qILUGIkL4C2CqK269Xq167PbGCc/4=
github.com/pion/srtp/v3 v3.0.6/go.mod h1:BxvziG3v/armJHAaJ87euvkhHqWe9I7iiOy50K2QkhY=
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
github.com/pion/turn/v4 v4.0.2 h1:ZqgQ3+MjP32ug30xAbD6Mn+/K4Sxi3SdNOTFf+7mpps=
github.com/pion/turn/v4 v4.0.2/go.mod h1:pMMKP/ieNAG/fN5cZiN4SDuyKsXtNTr0ccN7IToA1zs=
github.com/pion/webrtc/v4 v4.1.2 h1:mpuUo/EJ1zMNKGE79fAdYNFZBX790KE7kQQpLMjjR54=
github.com/pion/webrtc/v4 v4.1.2/go.mod h1:xsCXiNAmMEjIdFxAYU0MbB3RwRieJsegSB2JZsGN+8U=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0=
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.64.1 h1:BCNTP+6x6++OPKrGST2FR3f1tycx8O3QOA3QQv09g70=
github.com/quic-go/quic-go v0.64.1/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w=
github.com/quic-go/webtransport-go v0.13.0 h1:RJLrTUHlTj8jJaQlQJUy0z0Mf7u1fVM0I6L1b9pe2M0=
github.com/quic-go/webtransport-go v0.13.0/go.mod h1:K83X9YHbAqgSLO6ikS6BXCMdWOvqh9JTHALulvb2JVk=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=
go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=
go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200602180216-279210d13fed/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 h1:lfvjMWyv5q5oJgIhGfBDf7Szvu8POtgSpMy2XbXlEFs=
golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210423184538-5f58ad60dda6/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210426080607-c94f62235c83/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/telemetry v0.0.0-20261111153349-cdaf7e97dd7b h1:HDLCiByjRbzmSn/z4+smkCRQ58Hr5yxP+pq4CwqwCv8=
golang.org/x/telemetry v0.0.0-20261111153349-cdaf7e97dd7b/go.mod h1:frnW8knEsfI9dILitAKHe8/iQ1ycXgpvIjQ/xz9QFYk=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE=
modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4=
+109
View File
@@ -0,0 +1,109 @@
package identity
import (
"encoding/hex"
"errors"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
)
const (
CertVersion = 1
MaxCertLifetime = 366 * 24 * time.Hour
certContext = "allmende-cert-v1\n"
)
// Cert is the identity key's statement "this device may sign on my behalf".
// It is public and travels with every listing.
type Cert struct {
Version int `json:"v"`
Author string `json:"author"` // identity public key, hex
Device string `json:"device"` // device public key, hex
IssuedAt int64 `json:"issued_at"`
ExpiresAt int64 `json:"expires_at"`
Sig string `json:"sig,omitempty"`
}
func (c *Cert) signingBytes() ([]byte, error) {
cp := *c
cp.Sig = ""
b, err := jcs.Marshal(&cp)
if err != nil {
return nil, err
}
return append([]byte(certContext), b...), nil
}
// IssueCert signs a certificate for devicePub with the identity key.
func IssueCert(root *Identity, devicePub string, issuedAt, expiresAt time.Time) (*Cert, error) {
c := &Cert{
Version: CertVersion,
Author: root.PublicKeyHex(),
Device: devicePub,
IssuedAt: issuedAt.Unix(),
ExpiresAt: expiresAt.Unix(),
}
if err := c.checkFields(); err != nil {
return nil, err
}
b, err := c.signingBytes()
if err != nil {
return nil, err
}
c.Sig = hex.EncodeToString(root.Sign(b))
return c, nil
}
func (c *Cert) checkFields() error {
switch {
case c.Version != CertVersion:
return errors.New("identity: unsupported cert version")
case !isHex(c.Author, 64) || !isHex(c.Device, 64):
return errors.New("identity: cert keys must be 64 hex characters")
case c.ExpiresAt <= c.IssuedAt:
return errors.New("identity: cert expires before it is issued")
case time.Duration(c.ExpiresAt-c.IssuedAt)*time.Second > MaxCertLifetime:
return errors.New("identity: cert lifetime too long")
}
return nil
}
// Check verifies structure and signature. It does not look at the clock;
// use Covers for that.
func (c *Cert) Check() error {
if err := c.checkFields(); err != nil {
return err
}
sig, err := hex.DecodeString(c.Sig)
if err != nil || len(sig) != 64 {
return errors.New("identity: malformed cert signature")
}
b, err := c.signingBytes()
if err != nil {
return err
}
if !Verify(c.Author, b, sig) {
return errors.New("identity: bad cert signature")
}
return nil
}
// Covers reports whether unix time t lies within the certificate's validity.
func (c *Cert) Covers(t int64) bool {
return t >= c.IssuedAt && t < c.ExpiresAt
}
func isHex(s string, n int) bool {
if len(s) != n {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
+85
View File
@@ -0,0 +1,85 @@
package identity
import (
"crypto/ed25519"
"encoding/json"
"errors"
"os"
"path/filepath"
"time"
)
// Device is what a running node holds: its own key plus the certificate that
// ties it to an identity. The identity key itself is never stored.
type Device struct {
Key *Identity
Cert *Cert
}
// Enroll creates a new device key and certifies it with the identity key.
func Enroll(root *Identity, now time.Time, validFor time.Duration) (*Device, error) {
key, err := Generate()
if err != nil {
return nil, err
}
cert, err := IssueCert(root, key.PublicKeyHex(), now, now.Add(validFor))
if err != nil {
return nil, err
}
return &Device{Key: key, Cert: cert}, nil
}
const (
deviceKeyFile = "device.key"
deviceCertFile = "device.cert"
)
// Save writes the device key (refusing to overwrite) and certificate into dir.
func (d *Device) Save(dir string) error {
if err := d.Key.Save(filepath.Join(dir, deviceKeyFile)); err != nil {
return err
}
return d.SaveCert(dir)
}
// SaveCert (over)writes only the certificate, e.g. after renewal.
func (d *Device) SaveCert(dir string) error {
data, err := json.Marshal(d.Cert)
if err != nil {
return err
}
path := filepath.Join(dir, deviceCertFile)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return err
}
return os.Rename(tmp, path)
}
// LoadDevice reads a device saved by Save and checks that key and
// certificate belong together.
func LoadDevice(dir string) (*Device, error) {
key, err := Load(filepath.Join(dir, deviceKeyFile))
if err != nil {
return nil, err
}
data, err := os.ReadFile(filepath.Join(dir, deviceCertFile))
if err != nil {
return nil, err
}
var cert Cert
if err := json.Unmarshal(data, &cert); err != nil {
return nil, err
}
if err := cert.Check(); err != nil {
return nil, err
}
if cert.Device != key.PublicKeyHex() {
return nil, errors.New("identity: certificate does not match device key")
}
return &Device{Key: key, Cert: &cert}, nil
}
// PrivateKey exposes the raw key so the p2p layer can use it as the node's
// libp2p identity. Handle with care.
func (i *Identity) PrivateKey() ed25519.PrivateKey { return i.priv }
+123
View File
@@ -0,0 +1,123 @@
package identity
import (
"strings"
"testing"
"time"
)
var testNow = time.Unix(1_800_000_000, 0)
func TestPhraseRoundTrip(t *testing.T) {
root, phrase, err := NewRoot()
if err != nil {
t.Fatal(err)
}
if n := len(strings.Fields(phrase)); n != 12 {
t.Fatalf("phrase has %d words, want 12", n)
}
again, err := FromPhrase(" " + strings.ToUpper(phrase) + "\n")
if err != nil {
t.Fatal(err)
}
if again.PublicKeyHex() != root.PublicKeyHex() {
t.Fatal("phrase did not recreate the same identity")
}
}
func TestBadPhraseRejected(t *testing.T) {
_, phrase, _ := NewRoot()
words := strings.Fields(phrase)
// Swapping two different words almost always breaks the checksum;
// changing the last word to another one is deterministic enough to try several.
bad := 0
for _, w := range []string{"abandon", "zoo", "legal", "winner"} {
if w == words[11] {
continue
}
cp := append([]string{}, words...)
cp[11] = w
if _, err := FromPhrase(strings.Join(cp, " ")); err != nil {
bad++
}
}
if bad == 0 {
t.Fatal("checksum never rejected a modified phrase")
}
if _, err := FromPhrase("not a real phrase"); err == nil {
t.Fatal("garbage phrase accepted")
}
}
func TestCert(t *testing.T) {
root, _, _ := NewRoot()
dev, err := Enroll(root, testNow, 30*24*time.Hour)
if err != nil {
t.Fatal(err)
}
if err := dev.Cert.Check(); err != nil {
t.Fatal(err)
}
if !dev.Cert.Covers(testNow.Unix()) || dev.Cert.Covers(testNow.Add(31*24*time.Hour).Unix()) ||
dev.Cert.Covers(testNow.Add(-time.Second).Unix()) {
t.Fatal("Covers returned wrong validity window")
}
forged := *dev.Cert
forged.Device = strings.Repeat("a", 64)
if forged.Check() == nil {
t.Fatal("tampered cert accepted")
}
other, _, _ := NewRoot()
swapped := *dev.Cert
swapped.Author = other.PublicKeyHex()
if swapped.Check() == nil {
t.Fatal("cert with swapped author accepted")
}
if _, err := Enroll(root, testNow, 3*366*24*time.Hour); err == nil {
t.Fatal("over-long cert lifetime accepted")
}
}
func TestRevocation(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
r, err := Revoke(root, dev.Cert, testNow, 10)
if err != nil {
t.Fatal(err)
}
if err := r.Check(10); err != nil {
t.Fatal(err)
}
if r.Check(40) == nil {
t.Fatal("insufficient proof-of-work accepted")
}
t2 := *r
t2.Device = strings.Repeat("b", 64)
if t2.Check(0) == nil {
t.Fatal("tampered revocation accepted")
}
other, _, _ := NewRoot()
if _, err := Revoke(other, dev.Cert, testNow, 0); err == nil {
t.Fatal("foreign identity revoked someone else's device")
}
}
func TestDeviceSaveLoad(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
dir := t.TempDir()
if err := dev.Save(dir); err != nil {
t.Fatal(err)
}
got, err := LoadDevice(dir)
if err != nil {
t.Fatal(err)
}
if got.Key.PublicKeyHex() != dev.Key.PublicKeyHex() || got.Cert.Sig != dev.Cert.Sig {
t.Fatal("device differs after reload")
}
if err := dev.Save(dir); err == nil {
t.Fatal("Save must not overwrite an existing device key")
}
}
+53
View File
@@ -0,0 +1,53 @@
package identity
import (
"crypto/ed25519"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"errors"
"strings"
"github.com/tyler-smith/go-bip39"
)
const entropyBytes = 16 // 128 bits = 12 words
// NewRoot creates a fresh identity key together with its 12-word recovery
// phrase. The caller must show the phrase to the user once and then discard
// the key: the phrase alone is enough to recreate it.
func NewRoot() (*Identity, string, error) {
entropy := make([]byte, entropyBytes)
if _, err := rand.Read(entropy); err != nil {
return nil, "", err
}
phrase, err := bip39.NewMnemonic(entropy)
if err != nil {
return nil, "", err
}
id, err := fromEntropy(entropy)
return id, phrase, err
}
// FromPhrase recreates an identity key from its recovery phrase. Extra
// whitespace and letter case are tolerated; the word checksum is verified so
// typos are caught.
func FromPhrase(phrase string) (*Identity, error) {
phrase = strings.ToLower(strings.Join(strings.Fields(phrase), " "))
entropy, err := bip39.EntropyFromMnemonic(phrase)
if err != nil {
return nil, errors.New("identity: invalid recovery phrase")
}
if len(entropy) != entropyBytes {
return nil, errors.New("identity: recovery phrase must have 12 words")
}
return fromEntropy(entropy)
}
func fromEntropy(entropy []byte) (*Identity, error) {
seed, err := hkdf.Key(sha256.New, entropy, nil, "allmende identity key v1", ed25519.SeedSize)
if err != nil {
return nil, err
}
return &Identity{priv: ed25519.NewKeyFromSeed(seed)}, nil
}
+95
View File
@@ -0,0 +1,95 @@
package identity
import (
"encoding/hex"
"errors"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const (
RevocationVersion = 1
revocationContext = "allmende-revocation-v1\n"
)
// Revocation voids a device: every signature made by Device is rejected from
// now on. Nodes keep it until the device's certificate would have expired
// anyway (CertExpiresAt). It carries proof-of-work so nobody can flood the
// network with revocations for throwaway identities.
type Revocation struct {
Version int `json:"v"`
Author string `json:"author"`
Device string `json:"device"`
RevokedAt int64 `json:"revoked_at"`
CertExpiresAt int64 `json:"cert_expires_at"`
PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"`
}
func (r *Revocation) signingBytes() ([]byte, error) {
cp := *r
cp.Sig = ""
b, err := jcs.Marshal(&cp)
if err != nil {
return nil, err
}
return append([]byte(revocationContext), b...), nil
}
// Revoke signs a revocation of the device named in cert, mining the
// proof-of-work to the given difficulty.
func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocation, error) {
if root.PublicKeyHex() != cert.Author {
return nil, errors.New("identity: cert does not belong to this identity")
}
r := &Revocation{
Version: RevocationVersion,
Author: cert.Author,
Device: cert.Device,
RevokedAt: at.Unix(),
CertExpiresAt: cert.ExpiresAt,
}
for ; ; r.PoW++ {
b, err := r.signingBytes()
if err != nil {
return nil, err
}
if pow.LeadingZeroBits(b) >= difficulty {
r.Sig = hex.EncodeToString(root.Sign(b))
return r, nil
}
}
}
// Check verifies structure, signature and proof-of-work.
func (r *Revocation) Check(difficulty int) error {
if r.Version != RevocationVersion {
return errors.New("identity: unsupported revocation version")
}
if !isHex(r.Author, 64) || !isHex(r.Device, 64) {
return errors.New("identity: revocation keys must be 64 hex characters")
}
if r.PoW > 1<<53-1 {
return errors.New("identity: number out of range")
}
sig, err := hex.DecodeString(r.Sig)
if err != nil || len(sig) != 64 {
return errors.New("identity: malformed revocation signature")
}
b, err := r.signingBytes()
if err != nil {
return err
}
if !Verify(r.Author, b, sig) {
return errors.New("identity: bad revocation signature")
}
if pow.LeadingZeroBits(b) < difficulty {
return errors.New("identity: insufficient proof-of-work")
}
return nil
}
// Bytes returns the canonical encoding including the signature.
func (r *Revocation) Bytes() ([]byte, error) { return jcs.Marshal(r) }
+59 -30
View File
@@ -9,7 +9,6 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"math/bits"
"strings" "strings"
"time" "time"
"unicode" "unicode"
@@ -17,6 +16,7 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
) )
const ( const (
@@ -24,12 +24,35 @@ const (
MaxLifetime = 30 * 24 * time.Hour MaxLifetime = 30 * 24 * time.Hour
MaxClockSkew = 10 * time.Minute MaxClockSkew = 10 * time.Minute
GeohashPrecision = 6 GeohashPrecision = 6
// RegionPrecision is the geohash prefix length that names a gossip
// region (~150 km cells).
RegionPrecision = 3
MaxSize = 16 << 10 MaxSize = 16 << 10
maxSafeInt = 1<<53 - 1 maxSafeInt = 1<<53 - 1
geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz" geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
listingContext = "allmende-listing-v1\n"
) )
// ErrTimeWindow marks failures caused by the clock (expired, or created in
// the future). They are not the sender's fault, so the p2p layer ignores such
// messages instead of penalizing the peer that relayed them.
var ErrTimeWindow = errors.New("outside time window")
// Region returns the gossip region of a geohash.
func Region(geohash string) string {
if len(geohash) < RegionPrecision {
return geohash
}
return geohash[:RegionPrecision]
}
// ValidRegion reports whether s is a well-formed region name.
func ValidRegion(s string) bool {
return len(s) == RegionPrecision && ValidGeohashPrefix(s)
}
var ( var (
kinds = map[string]bool{"rent": true, "sale": true} kinds = map[string]bool{"rent": true, "sale": true}
categories = map[string]bool{"apartment": true, "house": true, "room": true, "commercial": true} categories = map[string]bool{"apartment": true, "house": true, "room": true, "commercial": true}
@@ -51,7 +74,8 @@ type Image struct {
type Listing struct { type Listing struct {
Version int `json:"v"` Version int `json:"v"`
ID string `json:"id"` // stable across versions ID string `json:"id"` // stable across versions
Author string `json:"author"` // hex ed25519 public key Author string `json:"author"` // identity public key (hex)
Device string `json:"device"` // signing device's public key (hex)
Seq uint64 `json:"seq"` // higher replaces lower Seq uint64 `json:"seq"` // higher replaces lower
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"` ExpiresAt int64 `json:"expires_at"`
@@ -66,10 +90,12 @@ type Listing struct {
Title string `json:"title,omitempty"` Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"` Description string `json:"description,omitempty"`
Images []Image `json:"images,omitempty"` Images []Image `json:"images,omitempty"`
Endpoint string `json:"endpoint,omitempty"` // owner's peer ID
Delegate string `json:"delegate,omitempty"` // optional always-on host's peer ID Delegate string `json:"delegate,omitempty"` // optional always-on host's peer ID
PoW uint64 `json:"pow"` PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"` // hex, over canonical bytes without sig // Cert proves that Device may sign for Author. The owner's node is the
// peer whose ID derives from Device.
Cert *identity.Cert `json:"cert"`
Sig string `json:"sig,omitempty"` // device signature, hex
} }
// NewID returns a fresh random listing ID (32 hex characters). // NewID returns a fresh random listing ID (32 hex characters).
@@ -104,29 +130,20 @@ func (l *Listing) Hash() (string, error) {
return hex.EncodeToString(sum[:]), nil return hex.EncodeToString(sum[:]), nil
} }
func leadingZeroBits(sum [32]byte) int {
n := 0
for _, b := range sum {
if b == 0 {
n += 8
continue
}
return n + bits.LeadingZeros8(b)
}
return n
}
func (l *Listing) powOK(difficulty int) (bool, error) { func (l *Listing) powOK(difficulty int) (bool, error) {
b, err := l.unsignedBytes() b, err := l.unsignedBytes()
if err != nil { if err != nil {
return false, err return false, err
} }
return leadingZeroBits(sha256.Sum256(b)) >= difficulty, nil return pow.LeadingZeroBits(b) >= difficulty, nil
} }
// Seal sets the author, mines the proof-of-work and signs the listing. // Seal fills in author, device and certificate from dev, mines the
func (l *Listing) Seal(id *identity.Identity, difficulty int) error { // proof-of-work and signs the listing with the device key.
l.Author = id.PublicKeyHex() func (l *Listing) Seal(dev *identity.Device, difficulty int) error {
l.Author = dev.Cert.Author
l.Device = dev.Cert.Device
l.Cert = dev.Cert
l.Sig = "" l.Sig = ""
for l.PoW = 0; ; l.PoW++ { for l.PoW = 0; ; l.PoW++ {
if l.PoW > maxSafeInt { if l.PoW > maxSafeInt {
@@ -144,7 +161,7 @@ func (l *Listing) Seal(id *identity.Identity, difficulty int) error {
if err != nil { if err != nil {
return err return err
} }
l.Sig = hex.EncodeToString(id.Sign(b)) l.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(listingContext), b...)))
return nil return nil
} }
@@ -169,7 +186,7 @@ func (l *Listing) Check(now time.Time, difficulty int) error {
if err != nil || len(sig) != 64 { if err != nil || len(sig) != 64 {
return errors.New("listing: malformed signature") return errors.New("listing: malformed signature")
} }
if !identity.Verify(l.Author, unsigned, sig) { if !identity.Verify(l.Device, append([]byte(listingContext), unsigned...), sig) {
return errors.New("listing: bad signature") return errors.New("listing: bad signature")
} }
ok, err := l.powOK(difficulty) ok, err := l.powOK(difficulty)
@@ -194,8 +211,23 @@ func (l *Listing) validate(now time.Time) error {
if !isHex(l.ID, 32) { if !isHex(l.ID, 32) {
return errors.New("listing: id must be 32 hex characters") return errors.New("listing: id must be 32 hex characters")
} }
if !isHex(l.Author, 64) { if !isHex(l.Author, 64) || !isHex(l.Device, 64) {
return errors.New("listing: author must be 64 hex characters") return errors.New("listing: author and device must be 64 hex characters")
}
if l.Cert == nil {
return errors.New("listing: certificate required")
}
if err := l.Cert.Check(); err != nil {
return fmt.Errorf("listing: %w", err)
}
if l.Cert.Author != l.Author || l.Cert.Device != l.Device {
return errors.New("listing: certificate does not match author and device")
}
if !l.Cert.Covers(l.CreatedAt) {
return errors.New("listing: created outside the certificate's validity")
}
if now.Unix() >= l.Cert.ExpiresAt {
return fmt.Errorf("listing: certificate expired: %w", ErrTimeWindow)
} }
if l.Seq > maxSafeInt || l.PoW > maxSafeInt { if l.Seq > maxSafeInt || l.PoW > maxSafeInt {
return errors.New("listing: number out of range") return errors.New("listing: number out of range")
@@ -207,10 +239,10 @@ func (l *Listing) validate(now time.Time) error {
return errors.New("listing: lifetime exceeds 30 days") return errors.New("listing: lifetime exceeds 30 days")
} }
if time.Unix(l.CreatedAt, 0).After(now.Add(MaxClockSkew)) { if time.Unix(l.CreatedAt, 0).After(now.Add(MaxClockSkew)) {
return errors.New("listing: created_at is in the future") return fmt.Errorf("listing: created_at is in the future: %w", ErrTimeWindow)
} }
if !time.Unix(l.ExpiresAt, 0).After(now) { if !time.Unix(l.ExpiresAt, 0).After(now) {
return errors.New("listing: expired") return fmt.Errorf("listing: expired: %w", ErrTimeWindow)
} }
if err := validGeohash(l.Geohash); err != nil { if err := validGeohash(l.Geohash); err != nil {
return err return err
@@ -224,7 +256,7 @@ func (l *Listing) validate(now time.Time) error {
func (l *Listing) validateTombstone() error { func (l *Listing) validateTombstone() error {
if l.Kind != "" || l.Category != "" || l.Price != nil || l.AreaM2 != 0 || l.RoomsX2 != 0 || if l.Kind != "" || l.Category != "" || l.Price != nil || l.AreaM2 != 0 || l.RoomsX2 != 0 ||
len(l.Features) > 0 || l.Title != "" || l.Description != "" || len(l.Images) > 0 || len(l.Features) > 0 || l.Title != "" || l.Description != "" || len(l.Images) > 0 ||
l.Endpoint != "" || l.Delegate != "" { l.Delegate != "" {
return errors.New("listing: tombstone must not carry content") return errors.New("listing: tombstone must not carry content")
} }
return nil return nil
@@ -276,9 +308,6 @@ func (l *Listing) validateContent() error {
return errors.New("listing: image hashes must be 64 hex characters") return errors.New("listing: image hashes must be 64 hex characters")
} }
} }
if !validPeerID(l.Endpoint) {
return errors.New("listing: invalid endpoint")
}
if l.Delegate != "" && !validPeerID(l.Delegate) { if l.Delegate != "" && !validPeerID(l.Delegate) {
return errors.New("listing: invalid delegate") return errors.New("listing: invalid delegate")
} }
+126 -31
View File
@@ -1,6 +1,7 @@
package listing package listing
import ( import (
"errors"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -12,6 +13,19 @@ const testDifficulty = 12
var now = time.Unix(1_800_000_000, 0) var now = time.Unix(1_800_000_000, 0)
func newDevice(t *testing.T) *identity.Device {
t.Helper()
root, _, err := identity.NewRoot()
if err != nil {
t.Fatal(err)
}
dev, err := identity.Enroll(root, now.Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func sample(t *testing.T) *Listing { func sample(t *testing.T) *Listing {
t.Helper() t.Helper()
id, err := NewID() id, err := NewID()
@@ -32,28 +46,27 @@ func sample(t *testing.T) *Listing {
RoomsX2: 5, RoomsX2: 5,
Features: []string{"balcony", "elevator"}, Features: []string{"balcony", "elevator"},
Title: "Helle 2,5-Zimmer-Wohnung", Title: "Helle 2,5-Zimmer-Wohnung",
Endpoint: "12D3KooWExamplePeerID",
} }
} }
func sealed(t *testing.T) (*Listing, *identity.Identity) { func sealed(t *testing.T) (*Listing, *identity.Device) {
t.Helper() t.Helper()
key, err := identity.Generate() dev := newDevice(t)
if err != nil {
t.Fatal(err)
}
l := sample(t) l := sample(t)
if err := l.Seal(key, testDifficulty); err != nil { if err := l.Seal(dev, testDifficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
return l, key return l, dev
} }
func TestSealCheckRoundTrip(t *testing.T) { func TestSealCheckRoundTrip(t *testing.T) {
l, _ := sealed(t) l, dev := sealed(t)
if err := l.Check(now, testDifficulty); err != nil { if err := l.Check(now, testDifficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if l.Author != dev.Cert.Author || l.Device != dev.Key.PublicKeyHex() {
t.Fatal("seal did not fill author/device from the device")
}
} }
func TestCanonicalBytesDeterministic(t *testing.T) { func TestCanonicalBytesDeterministic(t *testing.T) {
@@ -63,7 +76,6 @@ func TestCanonicalBytesDeterministic(t *testing.T) {
if string(a) != string(b) { if string(a) != string(b) {
t.Fatal("canonical bytes differ between calls") t.Fatal("canonical bytes differ between calls")
} }
// keys must be sorted: "author" comes first.
if !strings.HasPrefix(string(a), `{"area_m2":55,"author":`) { if !strings.HasPrefix(string(a), `{"area_m2":55,"author":`) {
t.Fatalf("unexpected canonical prefix: %s", a[:40]) t.Fatalf("unexpected canonical prefix: %s", a[:40])
} }
@@ -77,50 +89,112 @@ func TestTamperDetected(t *testing.T) {
} }
} }
func TestForeignSignatureRejected(t *testing.T) { func TestAuthorMustMatchCertificate(t *testing.T) {
l, _ := sealed(t) l, _ := sealed(t)
other, _ := identity.Generate() other, _, _ := identity.NewRoot()
l.Author = other.PublicKeyHex() l.Author = other.PublicKeyHex()
if err := l.Check(now, testDifficulty); err == nil { if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("listing with swapped author accepted") t.Fatal("listing claiming a foreign author accepted")
}
}
func TestDeviceWithoutCertificateForAuthorRejected(t *testing.T) {
// A device certified by identity A cannot sign for identity B, even if
// the attacker attaches B's public key as author.
attacker := newDevice(t)
victim, _, _ := identity.NewRoot()
l := sample(t)
if err := l.Seal(attacker, testDifficulty); err != nil {
t.Fatal(err)
}
l.Author = victim.PublicKeyHex()
l.Cert.Author = victim.PublicKeyHex() // forged field; certificate signature breaks
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("forged identity accepted")
}
}
func TestSignedByWrongDeviceRejected(t *testing.T) {
l, _ := sealed(t)
other := newDevice(t)
// Re-sign with a different device key while keeping the original cert.
l.Sig = ""
b, _ := l.unsignedBytes()
l.Sig = hexSig(other, b)
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("signature by a different device accepted")
}
}
func hexSig(dev *identity.Device, unsigned []byte) string {
const hexd = "0123456789abcdef"
sig := dev.Key.Sign(append([]byte(listingContext), unsigned...))
out := make([]byte, 0, len(sig)*2)
for _, b := range sig {
out = append(out, hexd[b>>4], hexd[b&0xf])
}
return string(out)
}
func TestCertificateWindow(t *testing.T) {
root, _, _ := identity.NewRoot()
// Listing created before the certificate was issued.
dev, _ := identity.Enroll(root, now.Add(time.Hour), 24*time.Hour)
l := sample(t)
_ = l.Seal(dev, 0)
if err := l.Check(now.Add(2*time.Hour), 0); err == nil {
t.Fatal("listing older than its certificate accepted")
}
// Certificate expired at verification time.
dev, _ = identity.Enroll(root, now.Add(-48*time.Hour), 24*time.Hour)
l = sample(t)
l.CreatedAt = now.Add(-30 * time.Hour).Unix()
l.ExpiresAt = now.Add(24 * time.Hour).Unix()
_ = l.Seal(dev, 0)
err := l.Check(now, 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired certificate: got %v, want ErrTimeWindow", err)
} }
} }
func TestInsufficientPoW(t *testing.T) { func TestInsufficientPoW(t *testing.T) {
l, _ := sealed(t) l, _ := sealed(t)
// Difficulty demanded by the verifier is far above what was mined.
if err := l.Check(now, 40); err == nil { if err := l.Check(now, 40); err == nil {
t.Fatal("expected proof-of-work failure") t.Fatal("expected proof-of-work failure")
} }
} }
func TestExpiryAndLifetime(t *testing.T) { func TestExpiryAndLifetime(t *testing.T) {
key, _ := identity.Generate() dev := newDevice(t)
l := sample(t) l := sample(t)
l.ExpiresAt = l.CreatedAt + int64(31*24*3600) l.ExpiresAt = l.CreatedAt + int64(31*24*3600)
_ = l.Seal(key, 0) _ = l.Seal(dev, 0)
if err := l.Check(now, 0); err == nil { if err := l.Check(now, 0); err == nil {
t.Fatal("lifetime over 30 days accepted") t.Fatal("lifetime over 30 days accepted")
} }
l = sample(t) l = sample(t)
_ = l.Seal(key, 0) _ = l.Seal(dev, 0)
if err := l.Check(now.Add(8*24*time.Hour), 0); err == nil { err := l.Check(now.Add(8*24*time.Hour), 0)
t.Fatal("expired listing accepted") if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired listing: got %v, want ErrTimeWindow", err)
} }
l = sample(t) l = sample(t)
l.CreatedAt = now.Add(time.Hour).Unix() l.CreatedAt = now.Add(time.Hour).Unix()
l.ExpiresAt = l.CreatedAt + 3600 l.ExpiresAt = l.CreatedAt + 3600
_ = l.Seal(key, 0) _ = l.Seal(dev, 0)
if err := l.Check(now, 0); err == nil { err = l.Check(now, 0)
t.Fatal("future-dated listing accepted") if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("future-dated listing: got %v, want ErrTimeWindow", err)
} }
} }
func TestContentValidation(t *testing.T) { func TestContentValidation(t *testing.T) {
key, _ := identity.Generate() dev := newDevice(t)
cases := map[string]func(*Listing){ cases := map[string]func(*Listing){
"bad kind": func(l *Listing) { l.Kind = "swap" }, "bad kind": func(l *Listing) { l.Kind = "swap" },
"bad category": func(l *Listing) { l.Category = "castle" }, "bad category": func(l *Listing) { l.Category = "castle" },
@@ -132,14 +206,14 @@ func TestContentValidation(t *testing.T) {
"empty title": func(l *Listing) { l.Title = "" }, "empty title": func(l *Listing) { l.Title = "" },
"control char": func(l *Listing) { l.Title = "a\x00b" }, "control char": func(l *Listing) { l.Title = "a\x00b" },
"bad image hash": func(l *Listing) { l.Images = []Image{{Hash: "zz", ThumbHash: "zz"}} }, "bad image hash": func(l *Listing) { l.Images = []Image{{Hash: "zz", ThumbHash: "zz"}} },
"no endpoint": func(l *Listing) { l.Endpoint = "" }, "bad delegate": func(l *Listing) { l.Delegate = "no" },
"huge description": func(l *Listing) { l.Description = strings.Repeat("x", 4001) }, "huge description": func(l *Listing) { l.Description = strings.Repeat("x", 4001) },
} }
for name, mutate := range cases { for name, mutate := range cases {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
l := sample(t) l := sample(t)
mutate(l) mutate(l)
if err := l.Seal(key, 0); err != nil { if err := l.Seal(dev, 0); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := l.Check(now, 0); err == nil { if err := l.Check(now, 0); err == nil {
@@ -150,7 +224,7 @@ func TestContentValidation(t *testing.T) {
} }
func TestTombstoneAndSupersedes(t *testing.T) { func TestTombstoneAndSupersedes(t *testing.T) {
l, key := sealed(t) l, dev := sealed(t)
ts := &Listing{ ts := &Listing{
Version: Version, Version: Version,
@@ -161,7 +235,7 @@ func TestTombstoneAndSupersedes(t *testing.T) {
Tombstone: true, Tombstone: true,
Geohash: l.Geohash, Geohash: l.Geohash,
} }
if err := ts.Seal(key, testDifficulty); err != nil { if err := ts.Seal(dev, testDifficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ts.Check(now, testDifficulty); err != nil { if err := ts.Check(now, testDifficulty); err != nil {
@@ -171,17 +245,29 @@ func TestTombstoneAndSupersedes(t *testing.T) {
t.Fatal("tombstone must supersede the original, not the reverse") t.Fatal("tombstone must supersede the original, not the reverse")
} }
// A different author cannot supersede someone else's listing. // A different identity cannot supersede someone else's listing.
other, _ := identity.Generate()
forged := *ts forged := *ts
_ = forged.Seal(other, testDifficulty) _ = forged.Seal(newDevice(t), testDifficulty)
if forged.Supersedes(l) { if forged.Supersedes(l) {
t.Fatal("tombstone by a different author must not supersede") t.Fatal("tombstone by a different author must not supersede")
} }
// Another device of the same identity can (e.g. after a node was replaced).
root, _, _ := identity.NewRoot()
devA, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
devB, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
v1 := sample(t)
_ = v1.Seal(devA, 0)
v2 := *v1
v2.Seq = 2
_ = v2.Seal(devB, 0)
if !v2.Supersedes(v1) {
t.Fatal("a second device of the same identity must be able to supersede")
}
// Tombstones must not smuggle content. // Tombstones must not smuggle content.
ts.Title = "still here" ts.Title = "still here"
_ = ts.Seal(key, testDifficulty) _ = ts.Seal(dev, testDifficulty)
if err := ts.Check(now, testDifficulty); err == nil { if err := ts.Check(now, testDifficulty); err == nil {
t.Fatal("tombstone with content accepted") t.Fatal("tombstone with content accepted")
} }
@@ -197,3 +283,12 @@ func TestHashChangesWithContent(t *testing.T) {
t.Fatal("hash must differ for different content") t.Fatal("hash must differ for different content")
} }
} }
func TestRegion(t *testing.T) {
if Region("u1xjhx") != "u1x" {
t.Fatal("wrong region")
}
if !ValidRegion("u1x") || ValidRegion("u1") || ValidRegion("u1xa") || ValidRegion("u1a") {
t.Fatal("ValidRegion wrong")
}
}
+437
View File
@@ -0,0 +1,437 @@
// Package p2p connects a node's store to the network.
//
// - Listings are gossiped on one pubsub topic per geohash region
// (precision 3). A node subscribes only to the regions it cares about.
// - Revocations are gossiped on a single global topic.
// - A sync stream protocol lets a node that was offline (or just joined)
// catch up from any peer.
//
// Every message is verified by a topic validator before it is relayed, so a
// node never forwards garbage and misbehaving peers lose reputation.
package p2p
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/libp2p/go-libp2p"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
listingTopicPrefix = "/allmende/1/listings/"
// RevocationTopic carries identity revocations for the whole network.
RevocationTopic = "/allmende/1/revocations"
mdnsService = "allmende"
resyncInterval = 5 * time.Minute
maintenanceTick = time.Hour
)
// Config describes a node.
type Config struct {
Device *identity.Device
Store *store.Store
ListenAddrs []string // default: TCP and QUIC on all interfaces, random ports
Bootstrap []string // multiaddrs ending in /p2p/<peer id>
Regions []string // geohash precision-3 cells to replicate
MDNS bool // discover peers on the local network
Difficulty int // required proof-of-work bits
SyncPageSize int // records per sync page (default 500)
Clock func() time.Time // default time.Now
Logger *slog.Logger
}
// Node is a running participant.
type Node struct {
cfg Config
host host.Host
ps *pubsub.PubSub
clock func() time.Time
log *slog.Logger
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
mdns mdns.Service
mu sync.Mutex
topics map[string]*pubsub.Topic
subscribed []string
synced map[peer.ID]time.Time
revTopic *pubsub.Topic
}
// New starts a node. Cancel ctx or call Close to stop it.
func New(ctx context.Context, cfg Config) (*Node, error) {
if cfg.Device == nil || cfg.Store == nil {
return nil, errors.New("p2p: Device and Store are required")
}
for _, r := range cfg.Regions {
if !listing.ValidRegion(r) {
return nil, fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
}
}
if len(cfg.ListenAddrs) == 0 {
cfg.ListenAddrs = []string{"/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/udp/0/quic-v1"}
}
if cfg.SyncPageSize <= 0 {
cfg.SyncPageSize = 500
}
priv, err := crypto.UnmarshalEd25519PrivateKey(cfg.Device.Key.PrivateKey())
if err != nil {
return nil, err
}
h, err := libp2p.New(libp2p.Identity(priv), libp2p.ListenAddrStrings(cfg.ListenAddrs...))
if err != nil {
return nil, err
}
nctx, cancel := context.WithCancel(ctx)
n := &Node{
cfg: cfg,
host: h,
clock: cfg.Clock,
log: cfg.Logger,
ctx: nctx,
cancel: cancel,
topics: map[string]*pubsub.Topic{},
synced: map[peer.ID]time.Time{},
}
if n.clock == nil {
n.clock = time.Now
}
if n.log == nil {
n.log = slog.Default()
}
// Flood-publish: the origin sends to every subscribed peer instead of only
// its mesh. Regional topics are small, and without it a listing published
// in the first second after connecting (before the mesh forms) is lost.
n.ps, err = pubsub.NewGossipSub(nctx, h,
pubsub.WithMaxMessageSize(listing.MaxSize+4096),
pubsub.WithFloodPublish(true))
if err != nil {
n.Close()
return nil, err
}
if err := n.startRevocations(); err != nil {
n.Close()
return nil, err
}
for _, r := range cfg.Regions {
if err := n.subscribeRegion(r); err != nil {
n.Close()
return nil, err
}
}
h.SetStreamHandler(SyncProtocol, n.handleSync)
h.Network().Notify(&network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) },
})
for _, addr := range cfg.Bootstrap {
if err := n.Connect(nctx, addr); err != nil {
n.log.Warn("bootstrap peer unreachable", "addr", addr, "err", err)
}
}
if cfg.MDNS {
n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n})
if err := n.mdns.Start(); err != nil {
n.Close()
return nil, err
}
}
n.wg.Add(1)
go n.maintain()
return n, nil
}
// ID returns the node's peer ID, which derives from its device key.
func (n *Node) ID() peer.ID { return n.host.ID() }
// Addrs returns dialable multiaddrs including the /p2p/<id> suffix.
func (n *Node) Addrs() []string {
addrs, err := peer.AddrInfoToP2pAddrs(&peer.AddrInfo{ID: n.host.ID(), Addrs: n.host.Addrs()})
if err != nil {
return nil
}
out := make([]string, len(addrs))
for i, a := range addrs {
out[i] = a.String()
}
return out
}
// Connect dials a peer given as a multiaddr ending in /p2p/<peer id>.
func (n *Node) Connect(ctx context.Context, addr string) error {
ai, err := peer.AddrInfoFromString(addr)
if err != nil {
return err
}
return n.host.Connect(ctx, *ai)
}
// RegionPeers lists peers known to be subscribed to the region's topic.
func (n *Node) RegionPeers(region string) []peer.ID {
return n.ps.ListPeers(listingTopicPrefix + region)
}
// Publish stores l locally (which verifies it) and gossips it to its region.
func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
if _, err := n.cfg.Store.Put(ctx, l); err != nil {
return err
}
data, err := l.Bytes()
if err != nil {
return err
}
t, err := n.regionTopic(listing.Region(l.Geohash))
if err != nil {
return err
}
return t.Publish(ctx, data)
}
// PublishRevocation stores r locally and gossips it to the whole network.
func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) error {
if _, err := n.cfg.Store.PutRevocation(ctx, r); err != nil {
return err
}
data, err := r.Bytes()
if err != nil {
return err
}
return n.revTopic.Publish(ctx, data)
}
// Close stops the node.
func (n *Node) Close() error {
n.cancel()
if n.mdns != nil {
n.mdns.Close()
}
n.wg.Wait()
return n.host.Close()
}
// --- topics ---------------------------------------------------------------
func (n *Node) startRevocations() error {
if err := n.ps.RegisterTopicValidator(RevocationTopic, n.revocationValidator,
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return err
}
t, err := n.ps.Join(RevocationTopic)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.revTopic = t
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) {
r, ok := msg.ValidatorData.(*identity.Revocation)
if !ok {
return
}
if _, err := n.cfg.Store.PutRevocation(n.ctx, r); err != nil {
n.log.Warn("store revocation", "err", err)
}
})
}()
return nil
}
func (n *Node) subscribeRegion(region string) error {
t, err := n.regionTopic(region)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.mu.Lock()
n.subscribed = append(n.subscribed, region)
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) {
l, ok := msg.ValidatorData.(*listing.Listing)
if !ok {
return
}
switch _, err := n.cfg.Store.Put(n.ctx, l); {
case err == nil, errors.Is(err, store.ErrRevoked):
default:
n.log.Warn("store listing", "err", err)
}
})
}()
return nil
}
// regionTopic joins (once) the topic for region and installs its validator.
func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
return nil, fmt.Errorf("p2p: invalid region %q", region)
}
n.mu.Lock()
defer n.mu.Unlock()
if t, ok := n.topics[region]; ok {
return t, nil
}
name := listingTopicPrefix + region
if err := n.ps.RegisterTopicValidator(name, n.listingValidator(region),
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return nil, err
}
t, err := n.ps.Join(name)
if err != nil {
return nil, err
}
n.topics[region] = t
return t, nil
}
func (n *Node) consume(sub *pubsub.Subscription, handle func(*pubsub.Message)) {
for {
msg, err := sub.Next(n.ctx)
if err != nil {
return
}
handle(msg)
}
}
// --- validation -----------------------------------------------------------
func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
l, res := n.validateListing(ctx, msg.Data)
if res != pubsub.ValidationAccept {
return res
}
// A listing may only travel on its own region's topic.
if listing.Region(l.Geohash) != region {
return pubsub.ValidationReject
}
msg.ValidatorData = l
return pubsub.ValidationAccept
}
}
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
if len(data) > listing.MaxSize {
return nil, pubsub.ValidationReject
}
var l listing.Listing
if err := json.Unmarshal(data, &l); err != nil {
return nil, pubsub.ValidationReject
}
// Only the canonical encoding is accepted, so every honest node derives
// the same message ID and nobody can re-encode someone else's listing.
if canon, err := l.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := l.Check(n.clock(), n.cfg.Difficulty); err != nil {
if errors.Is(err, listing.ErrTimeWindow) {
return nil, pubsub.ValidationIgnore // clocks differ; not the relay's fault
}
return nil, pubsub.ValidationReject
}
if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device); err != nil || revoked {
return nil, pubsub.ValidationIgnore
}
return &l, pubsub.ValidationAccept
}
func (n *Node) revocationValidator(_ context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
r, res := n.validateRevocation(msg.Data)
if res == pubsub.ValidationAccept {
msg.ValidatorData = r
}
return res
}
func (n *Node) validateRevocation(data []byte) (*identity.Revocation, pubsub.ValidationResult) {
if len(data) > 4096 {
return nil, pubsub.ValidationReject
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, pubsub.ValidationReject
}
if canon, err := r.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := r.Check(n.cfg.Difficulty); err != nil {
return nil, pubsub.ValidationReject
}
if r.CertExpiresAt <= n.clock().Unix() {
return nil, pubsub.ValidationIgnore
}
return &r, pubsub.ValidationAccept
}
// --- discovery and upkeep -------------------------------------------------
type mdnsNotifee struct{ n *Node }
func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
if pi.ID == m.n.host.ID() {
return
}
go func() {
ctx, cancel := context.WithTimeout(m.n.ctx, 15*time.Second)
defer cancel()
if err := m.n.host.Connect(ctx, pi); err != nil {
m.n.log.Debug("mdns connect", "peer", pi.ID, "err", err)
}
}()
}
// maintain periodically drops expired data.
func (n *Node) maintain() {
defer n.wg.Done()
t := time.NewTicker(maintenanceTick)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
return
case <-t.C:
if removed, err := n.cfg.Store.Expire(n.ctx); err != nil {
n.log.Warn("expire", "err", err)
} else if removed > 0 {
n.log.Info("expired records", "count", removed)
}
}
}
}
+257
View File
@@ -0,0 +1,257 @@
package p2p
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"testing"
"time"
pubsub "github.com/libp2p/go-libp2p-pubsub"
pb "github.com/libp2p/go-libp2p-pubsub/pb"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const difficulty = 6
type tnode struct {
*Node
s *store.Store
root *identity.Identity
dev *identity.Device
}
func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode {
t.Helper()
if root == nil {
root, _, _ = identity.NewRoot()
}
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
if err != nil {
t.Fatal(err)
}
n, err := New(context.Background(), Config{
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
SyncPageSize: 3,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { n.Close(); s.Close() })
return &tnode{Node: n, s: s, root: root, dev: dev}
}
func (tn *tnode) listing(t *testing.T, geohash string) *listing.Listing {
t.Helper()
id, _ := listing.NewID()
now := time.Now()
l := &listing.Listing{
Version: listing.Version,
ID: id,
Seq: 1,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
Kind: "rent",
Category: "apartment",
Geohash: geohash,
Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
Title: "Wohnung",
}
if err := l.Seal(tn.dev, difficulty); err != nil {
t.Fatal(err)
}
return l
}
func connect(t *testing.T, from, to *tnode) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := from.Connect(ctx, to.Addrs()[0]); err != nil {
t.Fatal(err)
}
}
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("timed out waiting for: %s", what)
}
func count(tn *tnode) int {
n, _ := tn.s.Count(context.Background())
return n
}
func TestGossipDeliversWithinRegion(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u1x")
c := startNode(t, nil, "u30") // different region
connect(t, b, a)
connect(t, c, a)
eventually(t, "a sees b on the region topic", func() bool { return len(a.RegionPeers("u1x")) == 1 })
l := a.listing(t, "u1xjhx")
if err := a.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
eventually(t, "b receives the listing", func() bool { return count(b) == 1 })
got, err := b.s.Get(context.Background(), l.Author, l.ID)
if err != nil || got.Title != "Wohnung" {
t.Fatalf("b has %v, %v", got, err)
}
time.Sleep(500 * time.Millisecond)
if count(c) != 0 {
t.Fatal("node in another region received the listing")
}
}
func TestSyncCatchesUpLateJoiner(t *testing.T) {
a := startNode(t, nil, "u1x")
ctx := context.Background()
// Seven listings (page size is 3, so three pages), one of them deleted,
// plus one in a region b does not replicate.
var ls []*listing.Listing
for i := 0; i < 7; i++ {
l := a.listing(t, "u1xjhx")
if _, err := a.s.Put(ctx, l); err != nil {
t.Fatal(err)
}
ls = append(ls, l)
}
ts := &listing.Listing{
Version: listing.Version, ID: ls[0].ID, Seq: 2,
CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: ls[0].Geohash,
}
if err := ts.Seal(a.dev, difficulty); err != nil {
t.Fatal(err)
}
if _, err := a.s.Put(ctx, ts); err != nil {
t.Fatal(err)
}
other := a.listing(t, "u30000")
if _, err := a.s.Put(ctx, other); err != nil {
t.Fatal(err)
}
b := startNode(t, nil, "u1x") // joins after everything was published
connect(t, b, a)
eventually(t, "b has caught up", func() bool { return count(b) == 6 })
if _, err := b.s.Get(ctx, ls[0].Author, ls[0].ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("deleted listing was not deleted on the late joiner")
}
if _, err := b.s.Get(ctx, other.Author, other.ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("b stored a listing from a region it does not replicate")
}
}
func TestRevocationPropagatesAndBlocks(t *testing.T) {
owner, _, _ := identity.NewRoot()
a := startNode(t, owner, "u1x") // the owner's (soon to be compromised) node
b := startNode(t, nil, "u1x")
connect(t, b, a)
eventually(t, "mesh formed", func() bool {
return len(a.RegionPeers("u1x")) == 1 && len(b.RegionPeers("u1x")) == 1
})
ctx := context.Background()
l := a.listing(t, "u1xjhx")
if err := a.Publish(ctx, l); err != nil {
t.Fatal(err)
}
eventually(t, "b has the listing", func() bool { return count(b) == 1 })
// The owner enters the recovery phrase on a new machine and revokes node a.
rev, err := identity.Revoke(owner, a.dev.Cert, time.Now(), difficulty)
if err != nil {
t.Fatal(err)
}
newMachine := startNode(t, owner, "u1x")
connect(t, newMachine, b)
if err := newMachine.PublishRevocation(ctx, rev); err != nil {
t.Fatal(err)
}
eventually(t, "b dropped the revoked device's listing", func() bool { return count(b) == 0 })
eventually(t, "a dropped it too", func() bool { return count(a) == 0 })
// The compromised node can no longer publish anything.
if err := a.Publish(ctx, a.listing(t, "u1xjhx")); !errors.Is(err, store.ErrRevoked) {
t.Fatalf("revoked node could publish: %v", err)
}
// A node joining later learns about the revocation through sync.
late := startNode(t, nil, "u1x")
connect(t, late, b)
eventually(t, "late joiner learns the revocation", func() bool {
ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device)
return ok
})
}
func TestValidatorRejectsBadMessages(t *testing.T) {
a := startNode(t, nil, "u1x")
good := a.listing(t, "u1xjhx")
goodBytes, _ := good.Bytes()
validate := func(region string, data []byte) pubsub.ValidationResult {
v := a.listingValidator(region)
return v(context.Background(), "", &pubsub.Message{Message: &pb.Message{Data: data}})
}
if r := validate("u1x", goodBytes); r != pubsub.ValidationAccept {
t.Fatalf("good listing: %v", r)
}
if r := validate("u30", goodBytes); r != pubsub.ValidationReject {
t.Fatalf("listing on the wrong region topic: %v", r)
}
if r := validate("u1x", []byte(`{"v":1`)); r != pubsub.ValidationReject {
t.Fatalf("garbage: %v", r)
}
tampered := *good
tampered.Title = "Betrug"
tb, _ := tampered.Bytes()
if r := validate("u1x", tb); r != pubsub.ValidationReject {
t.Fatalf("tampered listing: %v", r)
}
// Valid content, but not in canonical form (extra whitespace).
var m map[string]any
_ = json.Unmarshal(goodBytes, &m)
pretty, _ := json.MarshalIndent(m, "", " ")
if r := validate("u1x", pretty); r != pubsub.ValidationReject {
t.Fatalf("non-canonical encoding: %v", r)
}
// Expired: ignored (clock difference), not penalized.
old := a.listing(t, "u1xjhx")
a.clock = func() time.Time { return time.Now().Add(30 * 24 * time.Hour) }
ob, _ := old.Bytes()
if r := validate("u1x", ob); r != pubsub.ValidationIgnore {
t.Fatalf("expired listing: %v", r)
}
}
+218
View File
@@ -0,0 +1,218 @@
package p2p
import (
"bufio"
"context"
"encoding/json"
"io"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// SyncProtocol lets a node catch up with everything a peer holds for a
// region. Gossip only delivers what is published while you are online.
//
// Request: one JSON object. Response: newline-delimited canonical JSON
// records, then EOF. Listings are paged with a keyset cursor over
// (created_at, author, id), so pages are stable and cannot loop.
const SyncProtocol = "/allmende/1/sync"
const (
syncTimeout = 2 * time.Minute
maxSyncPages = 200 // bounds work per region against a misbehaving peer
maxRevocations = 5000
)
type syncRequest struct {
Kind string `json:"kind"` // "listings" or "revocations"
Region string `json:"region,omitempty"`
AfterCreated int64 `json:"after_created,omitempty"`
AfterAuthor string `json:"after_author,omitempty"`
AfterID string `json:"after_id,omitempty"`
Limit int `json:"limit,omitempty"`
}
// --- server ---------------------------------------------------------------
func (n *Node) handleSync(s network.Stream) {
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
var req syncRequest
if err := json.NewDecoder(io.LimitReader(s, 4096)).Decode(&req); err != nil {
_ = s.Reset()
return
}
w := bufio.NewWriter(s)
write := func(b []byte, err error) bool {
if err != nil {
return false
}
w.Write(b)
w.WriteByte('\n')
return true
}
switch req.Kind {
case "listings":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
return
}
limit := req.Limit
if limit <= 0 || limit > n.cfg.SyncPageSize {
limit = n.cfg.SyncPageSize
}
items, err := n.cfg.Store.Since(n.ctx, req.Region,
store.Cursor{CreatedAt: req.AfterCreated, Author: req.AfterAuthor, ID: req.AfterID}, limit)
if err != nil {
_ = s.Reset()
return
}
for _, l := range items {
if !write(l.Bytes()) {
_ = s.Reset()
return
}
}
case "revocations":
revs, err := n.cfg.Store.Revocations(n.ctx)
if err != nil {
_ = s.Reset()
return
}
if len(revs) > maxRevocations {
revs = revs[:maxRevocations]
}
for _, r := range revs {
if !write(r.Bytes()) {
_ = s.Reset()
return
}
}
default:
_ = s.Reset()
return
}
_ = w.Flush()
}
// --- client ---------------------------------------------------------------
// syncSoon schedules a catch-up with p, at most once per resyncInterval.
func (n *Node) syncSoon(p peer.ID) {
n.mu.Lock()
if last, ok := n.synced[p]; ok && n.clock().Sub(last) < resyncInterval {
n.mu.Unlock()
return
}
n.synced[p] = n.clock()
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
ctx, cancel := context.WithTimeout(n.ctx, syncTimeout)
defer cancel()
if err := n.SyncFrom(ctx, p); err != nil {
n.log.Debug("sync", "peer", p, "err", err)
}
}()
}
// SyncFrom pulls revocations and then every subscribed region from p.
// Revocations go first so listings from revoked devices are refused.
func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
if err := n.syncRevocations(ctx, p); err != nil {
return err
}
n.mu.Lock()
regions := append([]string(nil), n.subscribed...)
n.mu.Unlock()
for _, region := range regions {
if err := n.syncRegion(ctx, p, region); err != nil {
return err
}
}
return nil
}
func (n *Node) syncRevocations(ctx context.Context, p peer.ID) error {
return n.request(ctx, p, syncRequest{Kind: "revocations"}, func(line []byte) {
var r identity.Revocation
if json.Unmarshal(line, &r) != nil {
return
}
if _, err := n.cfg.Store.PutRevocation(ctx, &r); err != nil {
n.log.Debug("sync: revocation rejected", "peer", p, "err", err)
}
})
}
func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error {
var cur store.Cursor
for page := 0; page < maxSyncPages; page++ {
var count int
var last *listing.Listing
err := n.request(ctx, p, syncRequest{
Kind: "listings", Region: region, Limit: n.cfg.SyncPageSize,
AfterCreated: cur.CreatedAt, AfterAuthor: cur.Author, AfterID: cur.ID,
}, func(line []byte) {
var l listing.Listing
if json.Unmarshal(line, &l) != nil {
return
}
count++
last = &l
if listing.Region(l.Geohash) != region {
return // peer sent something we did not ask for
}
if _, err := n.cfg.Store.Put(ctx, &l); err != nil {
n.log.Debug("sync: listing rejected", "peer", p, "err", err)
}
})
if err != nil {
return err
}
if count < n.cfg.SyncPageSize || last == nil {
return nil
}
cur = store.CursorOf(last)
}
return nil
}
// request opens a sync stream, sends req and calls handle for each line.
func (n *Node) request(ctx context.Context, p peer.ID, req syncRequest, handle func([]byte)) error {
s, err := n.host.NewStream(ctx, p, SyncProtocol)
if err != nil {
return err
}
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
if err := json.NewEncoder(s).Encode(req); err != nil {
_ = s.Reset()
return err
}
if err := s.CloseWrite(); err != nil {
_ = s.Reset()
return err
}
sc := bufio.NewScanner(s)
sc.Buffer(make([]byte, 0, 64<<10), listing.MaxSize+4096)
for sc.Scan() {
handle(sc.Bytes())
}
if err := sc.Err(); err != nil {
_ = s.Reset()
return err
}
return nil
}
+22
View File
@@ -0,0 +1,22 @@
// Package pow implements the hashcash-style proof-of-work used to make
// mass-publishing of listings and revocations expensive.
package pow
import (
"crypto/sha256"
"math/bits"
)
// LeadingZeroBits returns the number of leading zero bits of sha256(data).
func LeadingZeroBits(data []byte) int {
sum := sha256.Sum256(data)
n := 0
for _, b := range sum {
if b == 0 {
n += 8
continue
}
return n + bits.LeadingZeros8(b)
}
return n
}
+155 -8
View File
@@ -15,6 +15,7 @@ import (
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/listing"
) )
@@ -23,6 +24,8 @@ var (
ErrInvalid = errors.New("store: invalid listing") ErrInvalid = errors.New("store: invalid listing")
// ErrNotFound is returned when a listing is absent, expired or deleted. // ErrNotFound is returned when a listing is absent, expired or deleted.
ErrNotFound = errors.New("store: not found") ErrNotFound = errors.New("store: not found")
// ErrRevoked is returned for listings signed by a revoked device.
ErrRevoked = errors.New("store: device revoked")
) )
// Outcome tells the caller what Put did, so the p2p layer knows whether a // Outcome tells the caller what Put did, so the p2p layer knows whether a
@@ -54,6 +57,7 @@ const schema = `
CREATE TABLE IF NOT EXISTS listings ( CREATE TABLE IF NOT EXISTS listings (
author TEXT NOT NULL, author TEXT NOT NULL,
id TEXT NOT NULL, id TEXT NOT NULL,
device TEXT NOT NULL,
seq INTEGER NOT NULL, seq INTEGER NOT NULL,
hash TEXT NOT NULL, hash TEXT NOT NULL,
tombstone INTEGER NOT NULL, tombstone INTEGER NOT NULL,
@@ -70,6 +74,16 @@ CREATE TABLE IF NOT EXISTS listings (
) WITHOUT ROWID; ) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash); CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash);
CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at); CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at);
CREATE INDEX IF NOT EXISTS listings_device ON listings (author, device);
CREATE INDEX IF NOT EXISTS listings_created ON listings (created_at, author, id);
CREATE TABLE IF NOT EXISTS revocations (
author TEXT NOT NULL,
device TEXT NOT NULL,
cert_expires_at INTEGER NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (author, device)
) WITHOUT ROWID;
` `
// Open opens (creating if needed) the database at path. Use ":memory:" for // Open opens (creating if needed) the database at path. Use ":memory:" for
@@ -125,6 +139,17 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
} }
defer tx.Rollback() defer tx.Rollback()
var revoked int
err = tx.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, l.Author, l.Device).
Scan(&revoked)
if err != nil {
return Ignored, err
}
if revoked > 0 {
return Ignored, ErrRevoked
}
var curSeq int64 var curSeq int64
var curHash string var curHash string
err = tx.QueryRowContext(ctx, err = tx.QueryRowContext(ctx,
@@ -149,10 +174,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
} }
_, err = tx.ExecContext(ctx, ` _, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO listings INSERT OR REPLACE INTO listings
(author, id, seq, hash, tombstone, created_at, expires_at, geohash, (author, id, device, seq, hash, tombstone, created_at, expires_at, geohash,
kind, category, price_cents, area_m2, rooms_x2, data) kind, category, price_cents, area_m2, rooms_x2, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt, l.Author, l.ID, l.Device, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data) l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data)
if err != nil { if err != nil {
return Ignored, err return Ignored, err
@@ -270,15 +295,137 @@ func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error)
return out, rows.Err() return out, rows.Err()
} }
// Expire deletes everything whose lifetime has ended, tombstones included, // Cursor is a keyset position in the (created_at, author, id) order, used to
// and returns how many rows were removed. A tombstone outlives any version it // page through listings during sync. The zero Cursor is the very beginning.
// supersedes because listings live at most 30 days from creation. type Cursor struct {
CreatedAt int64
Author string
ID string
}
// CursorOf returns the cursor positioned at l.
func CursorOf(l *listing.Listing) Cursor {
return Cursor{CreatedAt: l.CreatedAt, Author: l.Author, ID: l.ID}
}
// Since returns up to limit unexpired records (tombstones included, since
// peers need them to learn about deletions) in region prefix that sort after
// cur, oldest first.
func (s *Store) Since(ctx context.Context, prefix string, cur Cursor, limit int) ([]*listing.Listing, error) {
if !listing.ValidGeohashPrefix(prefix) {
return nil, fmt.Errorf("store: invalid geohash prefix %q", prefix)
}
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM listings
WHERE geohash >= ? AND geohash <= ? AND expires_at > ?
AND (created_at, author, id) > (?, ?, ?)
ORDER BY created_at, author, id LIMIT ?`,
prefix, prefix+"~", s.clock().Unix(), cur.CreatedAt, cur.Author, cur.ID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*listing.Listing
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
l, err := decode(data)
if err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
}
// PutRevocation verifies and stores a revocation, and removes every listing
// the revoked device signed. The owner re-publishes them from a new device.
func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outcome, error) {
if err := r.Check(s.difficulty); err != nil {
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
}
if r.CertExpiresAt <= s.clock().Unix() {
return Ignored, nil // the certificate is dead anyway
}
data, err := r.Bytes()
if err != nil {
return Ignored, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Ignored, err
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
`INSERT OR IGNORE INTO revocations (author, device, cert_expires_at, data) VALUES (?, ?, ?, ?)`,
r.Author, r.Device, r.CertExpiresAt, data)
if err != nil {
return Ignored, err
}
if n, _ := res.RowsAffected(); n == 0 {
return Ignored, nil // already known
}
if _, err := tx.ExecContext(ctx,
`DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device); err != nil {
return Ignored, err
}
if err := tx.Commit(); err != nil {
return Ignored, err
}
return Inserted, nil
}
// Revocations returns every revocation still relevant (certificate unexpired).
func (s *Store) Revocations(ctx context.Context) ([]*identity.Revocation, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT data FROM revocations WHERE cert_expires_at > ? ORDER BY author, device`, s.clock().Unix())
if err != nil {
return nil, err
}
defer rows.Close()
var out []*identity.Revocation
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, fmt.Errorf("store: corrupt revocation: %w", err)
}
out = append(out, &r)
}
return out, rows.Err()
}
// IsRevoked reports whether the device has been revoked.
func (s *Store) IsRevoked(ctx context.Context, author, device string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, author, device).Scan(&n)
return n > 0, err
}
// Expire deletes everything whose lifetime has ended (listings, tombstones
// and revocations) and returns how many rows were removed. A tombstone
// outlives any version it supersedes because listings live at most 30 days
// from creation.
func (s *Store) Expire(ctx context.Context) (int64, error) { func (s *Store) Expire(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, s.clock().Unix()) now := s.clock().Unix()
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, now)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return res.RowsAffected() n, _ := res.RowsAffected()
res, err = s.db.ExecContext(ctx, `DELETE FROM revocations WHERE cert_expires_at <= ?`, now)
if err != nil {
return n, err
}
m, _ := res.RowsAffected()
return n + m, nil
} }
// Count returns the number of live listings. // Count returns the number of live listings.
+170 -22
View File
@@ -21,13 +21,24 @@ var (
type env struct { type env struct {
s *Store s *Store
now time.Time now time.Time
key *identity.Identity root *identity.Identity
dev *identity.Device
}
func newDevice(t *testing.T, root *identity.Identity) *identity.Device {
t.Helper()
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 180*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
} }
func newEnv(t *testing.T) *env { func newEnv(t *testing.T) *env {
t.Helper() t.Helper()
e := &env{now: t0} e := &env{now: t0}
e.key, _ = identity.Generate() e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }}) s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -37,6 +48,14 @@ func newEnv(t *testing.T) *env {
return e return e
} }
// sibling returns a second store sharing e's identity and clock.
func (e *env) sibling(t *testing.T) *env {
t.Helper()
e2 := newEnv(t)
e2.root, e2.dev = e.root, e.dev
return e2
}
func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing { func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing {
t.Helper() t.Helper()
id, _ := listing.NewID() id, _ := listing.NewID()
@@ -53,12 +72,11 @@ func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.List
AreaM2: 50, AreaM2: 50,
RoomsX2: 4, RoomsX2: 4,
Title: "Wohnung", Title: "Wohnung",
Endpoint: "12D3KooWExamplePeerID",
} }
if mutate != nil { if mutate != nil {
mutate(l) mutate(l)
} }
if err := l.Seal(e.key, difficulty); err != nil { if err := l.Seal(e.dev, difficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
return l return l
@@ -112,7 +130,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
v2 := *v1 v2 := *v1
v2.Seq = 2 v2.Seq = 2
v2.Title = "Neuer Titel" v2.Title = "Neuer Titel"
if err := v2.Seal(e.key, difficulty); err != nil { if err := v2.Seal(e.dev, difficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -129,8 +147,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
} }
// Fresh store, natural order: second is a replacement. // Fresh store, natural order: second is a replacement.
e2 := newEnv(t) e2 := e.sibling(t)
e2.key = e.key
e2.put(t, v1) e2.put(t, v1)
if o := e2.put(t, &v2); o != Replaced { if o := e2.put(t, &v2); o != Replaced {
t.Fatalf("got %v want replaced", o) t.Fatalf("got %v want replaced", o)
@@ -142,7 +159,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
a := e.listing(t, nil) a := e.listing(t, nil)
b := *a b := *a
b.Title = "Anderer Titel" b.Title = "Anderer Titel"
if err := b.Seal(e.key, difficulty); err != nil { if err := b.Seal(e.dev, difficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
ha, _ := a.Hash() ha, _ := a.Hash()
@@ -157,8 +174,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
"loser first": {loser, winner}, "loser first": {loser, winner},
} { } {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
e2 := newEnv(t) e2 := e.sibling(t)
e2.key = e.key
for _, l := range order { for _, l := range order {
e2.put(t, l) e2.put(t, l)
} }
@@ -170,19 +186,25 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
} }
} }
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) { func (e *env) tombstone(t *testing.T, l *listing.Listing) *listing.Listing {
e := newEnv(t) t.Helper()
l := e.listing(t, nil)
e.put(t, l)
ts := &listing.Listing{ ts := &listing.Listing{
Version: listing.Version, ID: l.ID, Seq: l.Seq + 1, Version: listing.Version, ID: l.ID, Seq: l.Seq + 1,
CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(), CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: l.Geohash, Tombstone: true, Geohash: l.Geohash,
} }
if err := ts.Seal(e.key, difficulty); err != nil { if err := ts.Seal(e.dev, difficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
return ts
}
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
e.put(t, l)
ts := e.tombstone(t, l)
if o := e.put(t, ts); o != Replaced { if o := e.put(t, ts); o != Replaced {
t.Fatalf("got %v want replaced", o) t.Fatalf("got %v want replaced", o)
} }
@@ -197,8 +219,7 @@ func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
} }
// A tombstone arriving before the listing it deletes still wins. // A tombstone arriving before the listing it deletes still wins.
e2 := newEnv(t) e2 := e.sibling(t)
e2.key = e.key
e2.put(t, ts) e2.put(t, ts)
if o := e2.put(t, l); o != Ignored { if o := e2.put(t, l); o != Ignored {
t.Fatalf("listing after tombstone: %v", o) t.Fatalf("listing after tombstone: %v", o)
@@ -210,11 +231,11 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
victim := e.listing(t, nil) victim := e.listing(t, nil)
e.put(t, victim) e.put(t, victim)
other, _ := identity.Generate() otherRoot, _, _ := identity.NewRoot()
squat := *victim squat := *victim
squat.Seq = 99 squat.Seq = 99
squat.Title = "Betrug" squat.Title = "Betrug"
if err := squat.Seal(other, difficulty); err != nil { if err := squat.Seal(newDevice(t, otherRoot), difficulty); err != nil {
t.Fatal(err) t.Fatal(err)
} }
e.put(t, &squat) e.put(t, &squat)
@@ -225,6 +246,88 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
} }
} }
func TestRevocationVoidsDevice(t *testing.T) {
e := newEnv(t)
stolen := e.dev
mine := e.listing(t, nil)
e.put(t, mine)
// The attacker hijacks the listing with the stolen device and a huge seq.
hijack := *mine
hijack.Seq = 1 << 40
hijack.Title = "Betrug"
if err := hijack.Seal(stolen, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &hijack); o != Replaced {
t.Fatalf("hijack: %v", o)
}
// The owner restores from the recovery phrase and revokes the device.
rev, err := identity.Revoke(e.root, stolen.Cert, e.now, difficulty)
if err != nil {
t.Fatal(err)
}
if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted {
t.Fatalf("PutRevocation = %v, %v", o, err)
}
if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) {
t.Fatal("revoked device's listing still readable")
}
if _, err := e.s.Put(ctx, &hijack); !errors.Is(err, ErrRevoked) {
t.Fatalf("revoked device accepted again: %v", err)
}
if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored {
t.Fatalf("duplicate revocation: %v", o)
}
// The owner republishes from a new device with a low seq: it must win,
// because the attacker's huge seq was purged with the revocation.
newDev := newDevice(t, e.root)
again := *mine
again.Seq = 2
if err := again.Seal(newDev, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &again); o != Inserted {
t.Fatalf("republish from new device: %v", o)
}
got, _ := e.s.Get(ctx, mine.Author, mine.ID)
if got.Title != "Wohnung" {
t.Fatalf("got %q", got.Title)
}
}
func TestRevocationValidation(t *testing.T) {
e := newEnv(t)
other, _, _ := identity.NewRoot()
// Someone else's identity cannot revoke our device.
if _, err := identity.Revoke(other, e.dev.Cert, e.now, difficulty); err == nil {
t.Fatal("foreign identity could create a revocation")
}
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
rev.Device = other.PublicKeyHex()
if _, err := e.s.PutRevocation(ctx, rev); !errors.Is(err, ErrInvalid) {
t.Fatalf("tampered revocation: %v", err)
}
}
func TestRevocationExpiresWithCertificate(t *testing.T) {
e := newEnv(t)
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
e.s.PutRevocation(ctx, rev)
if list, _ := e.s.Revocations(ctx); len(list) != 1 {
t.Fatalf("got %d revocations, want 1", len(list))
}
e.now = time.Unix(e.dev.Cert.ExpiresAt+1, 0)
if list, _ := e.s.Revocations(ctx); len(list) != 0 {
t.Fatal("expired revocation still listed")
}
if n, _ := e.s.Expire(ctx); n != 1 {
t.Fatalf("Expire removed %d, want 1", n)
}
}
func TestSearch(t *testing.T) { func TestSearch(t *testing.T) {
e := newEnv(t) e := newEnv(t)
mk := func(geo, kind string, cents int64, area, rooms int) { mk := func(geo, kind string, cents int64, area, rooms int) {
@@ -278,6 +381,51 @@ func TestSearch(t *testing.T) {
} }
} }
func TestSinceKeysetPaging(t *testing.T) {
e := newEnv(t)
// Five listings in the same second plus one tombstone and one outside the region.
var all []*listing.Listing
for i := 0; i < 5; i++ {
l := e.listing(t, nil)
e.put(t, l)
all = append(all, l)
}
e.put(t, e.tombstone(t, all[0]))
e.put(t, e.listing(t, func(l *listing.Listing) { l.Geohash = "u30000" }))
var got []*listing.Listing
cur := Cursor{}
for pages := 0; pages < 10; pages++ {
page, err := e.s.Since(ctx, "u1x", cur, 2)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
got = append(got, page...)
cur = CursorOf(page[len(page)-1])
}
// 5 distinct listings; one of them is now a tombstone.
if len(got) != 5 {
t.Fatalf("paged %d records, want 5", len(got))
}
tombstones := 0
seen := map[string]bool{}
for _, l := range got {
if seen[l.ID] {
t.Fatalf("duplicate %s across pages", l.ID)
}
seen[l.ID] = true
if l.Tombstone {
tombstones++
}
}
if tombstones != 1 {
t.Fatalf("got %d tombstones, want 1 (peers need them to learn deletions)", tombstones)
}
}
func TestExpiry(t *testing.T) { func TestExpiry(t *testing.T) {
e := newEnv(t) e := newEnv(t)
l := e.listing(t, nil) l := e.listing(t, nil)
@@ -298,14 +446,14 @@ func TestExpiry(t *testing.T) {
func TestPersistence(t *testing.T) { func TestPersistence(t *testing.T) {
path := filepath.Join(t.TempDir(), "allmende.db") path := filepath.Join(t.TempDir(), "allmende.db")
key, _ := identity.Generate()
opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }} opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }}
s, err := Open(path, opt) s, err := Open(path, opt)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
e := &env{s: s, now: t0, key: key} e := newEnv(t)
e.s = s
l := e.listing(t, nil) l := e.listing(t, nil)
e.put(t, l) e.put(t, l)
s.Close() s.Close()