Scaffold Allmende: identity, canonical JSON, signed listings
- internal/jcs: RFC 8785 canonical JSON (integers only) - internal/identity: ed25519 keypair, 0600 key file, no overwrite - internal/listing: signed listing record with PoW, validation, tombstones and supersede rules - docs/PROTOCOL.md: architecture and decisions so far Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,4 @@
|
|||||||
|
/bin/
|
||||||
|
*.key
|
||||||
|
node_modules/
|
||||||
|
web/dist/
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# Protocol (draft v1)
|
||||||
|
|
||||||
|
A distributed, free marketplace for buying/selling and renting. Listing requires
|
||||||
|
running a node; searching is browser-only through any node's HTTP gateway.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- **Nodes** (Go, single binary): libp2p between nodes, HTTP gateway + web UI +
|
||||||
|
search API on every node.
|
||||||
|
- **Browsers** never join the P2P network. They fetch from any gateway and
|
||||||
|
**verify signatures themselves**, so a gateway cannot forge listings.
|
||||||
|
- **Sharding**: listings are gossiped per `geohash` region (precision 6, ~1 km)
|
||||||
|
and category. Nodes subscribe to the regions they care about and index them
|
||||||
|
locally.
|
||||||
|
- **Launch scope**: one German state or metro area.
|
||||||
|
|
||||||
|
## Identity
|
||||||
|
|
||||||
|
An ed25519 keypair is the identity. No accounts. The public key (64 hex chars)
|
||||||
|
is the `author`.
|
||||||
|
|
||||||
|
## Listing record
|
||||||
|
|
||||||
|
Canonical JSON (RFC 8785), integers only. See `internal/listing`.
|
||||||
|
|
||||||
|
| field | notes |
|
||||||
|
|---|---|
|
||||||
|
| `v` | format version, currently 1 |
|
||||||
|
| `id` | 32 hex, stable across versions |
|
||||||
|
| `author` | hex ed25519 public key |
|
||||||
|
| `seq` | higher replaces lower for same `id` + `author` |
|
||||||
|
| `created_at`, `expires_at` | unix seconds; lifetime <= 30 days, owner re-signs to renew |
|
||||||
|
| `tombstone` | deletion marker: higher `seq`, no content, only routing `geohash` |
|
||||||
|
| `kind` | `rent` or `sale` |
|
||||||
|
| `category` | `apartment`, `house`, `room`, `commercial` |
|
||||||
|
| `geohash` | precision 6 |
|
||||||
|
| `price` | `{amount_cents, currency: "EUR", period: month|once}` |
|
||||||
|
| `area_m2`, `rooms_x2` | rooms * 2 (2.5 rooms = 5) |
|
||||||
|
| `features`, `title`, `description` | bounded text |
|
||||||
|
| `images` | `{hash, thumb_hash}`, content-addressed, **no location** |
|
||||||
|
| `endpoint` | owner's peer ID |
|
||||||
|
| `delegate` | optional always-on host chosen by the owner |
|
||||||
|
| `pow` | nonce; sha256 of the unsigned canonical bytes has N leading zero bits |
|
||||||
|
| `sig` | ed25519 over the unsigned canonical bytes |
|
||||||
|
|
||||||
|
There is **no address, name, phone or email** in the record.
|
||||||
|
|
||||||
|
## Personal data (GDPR)
|
||||||
|
|
||||||
|
Only non-personal data is replicated. Exact address and contact details are
|
||||||
|
released by the owner's node on request over an encrypted channel. Deletion =
|
||||||
|
signed tombstone, honored by honest nodes, plus the owner's node ceasing to
|
||||||
|
serve details.
|
||||||
|
|
||||||
|
## Images (illegal-content risk, e.g. CSAM)
|
||||||
|
|
||||||
|
- Images are **origin-hosted**: only the owner's node (or a host the owner
|
||||||
|
explicitly delegates to) stores them. Third parties never replicate or
|
||||||
|
persistently cache them. Gateways stream without storing.
|
||||||
|
- Uploads are re-encoded, metadata stripped, size-capped, and checked against
|
||||||
|
hash lists where access is available.
|
||||||
|
- Signed abuse reports feed subscribable blocklists.
|
||||||
|
- **Get a German lawyer's review before any public launch** (§184b StGB).
|
||||||
|
|
||||||
|
## Availability
|
||||||
|
|
||||||
|
Metadata (~2 KB) replicates regionally, so listings remain searchable while the
|
||||||
|
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
|
||||||
|
within 30 days.
|
||||||
|
|
||||||
|
## Spam
|
||||||
|
|
||||||
|
Proof-of-work per listing plus subscribable blocklists. The format leaves room
|
||||||
|
for vouching signatures later.
|
||||||
|
|
||||||
|
## Open
|
||||||
|
|
||||||
|
Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti-
|
||||||
|
discrimination (AGG) content rules.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
// Package identity manages a node's ed25519 keypair. The public key is the
|
||||||
|
// identity: there are no accounts.
|
||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Identity struct {
|
||||||
|
priv ed25519.PrivateKey
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate creates a fresh random identity.
|
||||||
|
func Generate() (*Identity, error) {
|
||||||
|
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Identity{priv: priv}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads an identity previously written by Save.
|
||||||
|
func Load(path string) (*Identity, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
seed, err := hex.DecodeString(strings.TrimSpace(string(data)))
|
||||||
|
if err != nil || len(seed) != ed25519.SeedSize {
|
||||||
|
return nil, fmt.Errorf("identity: %s is not a valid key file", path)
|
||||||
|
}
|
||||||
|
return &Identity{priv: ed25519.NewKeyFromSeed(seed)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save writes the private seed to path with mode 0600. It refuses to
|
||||||
|
// overwrite an existing file so a key can never be destroyed by accident.
|
||||||
|
func (i *Identity) Save(path string) error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, werr := f.WriteString(hex.EncodeToString(i.priv.Seed()) + "\n")
|
||||||
|
if cerr := f.Close(); werr == nil {
|
||||||
|
werr = cerr
|
||||||
|
}
|
||||||
|
if werr != nil {
|
||||||
|
os.Remove(path)
|
||||||
|
}
|
||||||
|
return werr
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadOrCreate loads the identity at path, creating and saving a new one if
|
||||||
|
// the file does not exist.
|
||||||
|
func LoadOrCreate(path string) (*Identity, error) {
|
||||||
|
id, err := Load(path)
|
||||||
|
if err == nil {
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err = Generate()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := id.Save(path); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublicKeyHex returns the hex-encoded public key (64 characters).
|
||||||
|
func (i *Identity) PublicKeyHex() string {
|
||||||
|
return hex.EncodeToString(i.priv.Public().(ed25519.PublicKey))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Identity) Sign(msg []byte) []byte {
|
||||||
|
return ed25519.Sign(i.priv, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify checks sig over msg against a hex-encoded public key.
|
||||||
|
func Verify(pubHex string, msg, sig []byte) bool {
|
||||||
|
pub, err := hex.DecodeString(pubHex)
|
||||||
|
if err != nil || len(pub) != ed25519.PublicKeySize {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return ed25519.Verify(pub, msg, sig)
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSignVerify(t *testing.T) {
|
||||||
|
id, err := Generate()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
msg := []byte("hello")
|
||||||
|
sig := id.Sign(msg)
|
||||||
|
if !Verify(id.PublicKeyHex(), msg, sig) {
|
||||||
|
t.Fatal("valid signature rejected")
|
||||||
|
}
|
||||||
|
if Verify(id.PublicKeyHex(), []byte("other"), sig) {
|
||||||
|
t.Fatal("signature accepted for different message")
|
||||||
|
}
|
||||||
|
if Verify("zz", msg, sig) {
|
||||||
|
t.Fatal("garbage public key accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSaveLoad(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "sub", "key")
|
||||||
|
a, err := LoadOrCreate(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, err := LoadOrCreate(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if a.PublicKeyHex() != b.PublicKeyHex() {
|
||||||
|
t.Fatal("reloaded identity differs")
|
||||||
|
}
|
||||||
|
st, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("key file mode %v, want 0600", st.Mode().Perm())
|
||||||
|
}
|
||||||
|
if err := a.Save(path); err == nil {
|
||||||
|
t.Fatal("Save must not overwrite an existing key")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// Package jcs produces canonical JSON as specified by RFC 8785 (JCS),
|
||||||
|
// restricted to the subset this project needs: numbers must be integers
|
||||||
|
// within the IEEE-754 safe range, so no floating-point formatting is involved.
|
||||||
|
package jcs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"unicode/utf16"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxSafeInt = 1<<53 - 1
|
||||||
|
|
||||||
|
// Marshal returns the canonical JSON encoding of v. v is first encoded with
|
||||||
|
// encoding/json (so struct tags apply) and then re-serialized canonically.
|
||||||
|
func Marshal(v any) ([]byte, error) {
|
||||||
|
raw, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
dec.UseNumber()
|
||||||
|
var generic any
|
||||||
|
if err := dec.Decode(&generic); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := encode(&buf, generic); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encode(buf *bytes.Buffer, v any) error {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case nil:
|
||||||
|
buf.WriteString("null")
|
||||||
|
case bool:
|
||||||
|
if t {
|
||||||
|
buf.WriteString("true")
|
||||||
|
} else {
|
||||||
|
buf.WriteString("false")
|
||||||
|
}
|
||||||
|
case json.Number:
|
||||||
|
n, err := strconv.ParseInt(t.String(), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("jcs: only integer numbers are supported, got %q", t.String())
|
||||||
|
}
|
||||||
|
if n > maxSafeInt || n < -maxSafeInt {
|
||||||
|
return fmt.Errorf("jcs: integer %d outside safe range", n)
|
||||||
|
}
|
||||||
|
buf.WriteString(strconv.FormatInt(n, 10))
|
||||||
|
case string:
|
||||||
|
writeString(buf, t)
|
||||||
|
case []any:
|
||||||
|
buf.WriteByte('[')
|
||||||
|
for i, e := range t {
|
||||||
|
if i > 0 {
|
||||||
|
buf.WriteByte(',')
|
||||||
|
}
|
||||||
|
if err := encode(buf, e); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.WriteByte(']')
|
||||||
|
case map[string]any:
|
||||||
|
keys := make([]string, 0, len(t))
|
||||||
|
for k := range t {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
// RFC 8785 sorts keys by UTF-16 code units.
|
||||||
|
sort.Slice(keys, func(i, j int) bool { return lessUTF16(keys[i], keys[j]) })
|
||||||
|
buf.WriteByte('{')
|
||||||
|
for i, k := range keys {
|
||||||
|
if i > 0 {
|
||||||
|
buf.WriteByte(',')
|
||||||
|
}
|
||||||
|
writeString(buf, k)
|
||||||
|
buf.WriteByte(':')
|
||||||
|
if err := encode(buf, t[k]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.WriteByte('}')
|
||||||
|
default:
|
||||||
|
return errors.New("jcs: unsupported type")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lessUTF16(a, b string) bool {
|
||||||
|
ua, ub := utf16.Encode([]rune(a)), utf16.Encode([]rune(b))
|
||||||
|
for i := 0; i < len(ua) && i < len(ub); i++ {
|
||||||
|
if ua[i] != ub[i] {
|
||||||
|
return ua[i] < ub[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(ua) < len(ub)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hexDigits = "0123456789abcdef"
|
||||||
|
|
||||||
|
// writeString emits a JSON string using the minimal escaping JCS requires.
|
||||||
|
func writeString(buf *bytes.Buffer, s string) {
|
||||||
|
buf.WriteByte('"')
|
||||||
|
for _, r := range s {
|
||||||
|
switch r {
|
||||||
|
case '"':
|
||||||
|
buf.WriteString(`\"`)
|
||||||
|
case '\\':
|
||||||
|
buf.WriteString(`\\`)
|
||||||
|
case '\b':
|
||||||
|
buf.WriteString(`\b`)
|
||||||
|
case '\t':
|
||||||
|
buf.WriteString(`\t`)
|
||||||
|
case '\n':
|
||||||
|
buf.WriteString(`\n`)
|
||||||
|
case '\f':
|
||||||
|
buf.WriteString(`\f`)
|
||||||
|
case '\r':
|
||||||
|
buf.WriteString(`\r`)
|
||||||
|
default:
|
||||||
|
if r < 0x20 {
|
||||||
|
buf.WriteString(`\u00`)
|
||||||
|
buf.WriteByte(hexDigits[r>>4])
|
||||||
|
buf.WriteByte(hexDigits[r&0xf])
|
||||||
|
} else {
|
||||||
|
buf.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.WriteByte('"')
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package jcs
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestMarshal(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
in any
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"sorted keys", map[string]any{"b": 1, "a": 2, "c": []int{3, 1}}, `{"a":2,"b":1,"c":[3,1]}`},
|
||||||
|
{"nested", map[string]any{"z": map[string]any{"y": true, "x": nil}}, `{"z":{"x":null,"y":true}}`},
|
||||||
|
{"no html escaping", "<a href=\"x\">&</a>", `"<a href=\"x\">&</a>"`},
|
||||||
|
{"control chars", "a\tb\nc\u0001", `"a\tb\nc\u0001"`},
|
||||||
|
{"unicode literal", "ä€😀
", "\"ä€😀
\""},
|
||||||
|
{"utf16 key order", map[string]any{"\U0001F600": 1, "": 2}, "{\"\U0001F600\":1,\"\":2}"},
|
||||||
|
{"negative int", -42, `-42`},
|
||||||
|
}
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got, err := Marshal(tc.in)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(got) != tc.want {
|
||||||
|
t.Fatalf("got %s want %s", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectsFloatsAndHugeInts(t *testing.T) {
|
||||||
|
if _, err := Marshal(1.5); err == nil {
|
||||||
|
t.Fatal("expected error for float")
|
||||||
|
}
|
||||||
|
if _, err := Marshal(int64(1) << 60); err == nil {
|
||||||
|
t.Fatal("expected error for out-of-range integer")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
// Package listing defines the signed listing record that is replicated
|
||||||
|
// between nodes. A listing contains no personal data: no address, name, phone
|
||||||
|
// or email. Those are released by the owner's node on request.
|
||||||
|
package listing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math/bits"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||||
|
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
Version = 1
|
||||||
|
MaxLifetime = 30 * 24 * time.Hour
|
||||||
|
MaxClockSkew = 10 * time.Minute
|
||||||
|
GeohashPrecision = 6
|
||||||
|
MaxSize = 16 << 10
|
||||||
|
maxSafeInt = 1<<53 - 1
|
||||||
|
|
||||||
|
geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
kinds = map[string]bool{"rent": true, "sale": true}
|
||||||
|
categories = map[string]bool{"apartment": true, "house": true, "room": true, "commercial": true}
|
||||||
|
)
|
||||||
|
|
||||||
|
type Price struct {
|
||||||
|
AmountCents int64 `json:"amount_cents"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Period string `json:"period"` // "month" for rent, "once" for sale
|
||||||
|
}
|
||||||
|
|
||||||
|
type Image struct {
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
ThumbHash string `json:"thumb_hash"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listing is the replicated record. Numbers are integers only so the
|
||||||
|
// canonical JSON encoding is identical in every implementation.
|
||||||
|
type Listing struct {
|
||||||
|
Version int `json:"v"`
|
||||||
|
ID string `json:"id"` // stable across versions
|
||||||
|
Author string `json:"author"` // hex ed25519 public key
|
||||||
|
Seq uint64 `json:"seq"` // higher replaces lower
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
ExpiresAt int64 `json:"expires_at"`
|
||||||
|
Tombstone bool `json:"tombstone,omitempty"`
|
||||||
|
Kind string `json:"kind,omitempty"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
Geohash string `json:"geohash"`
|
||||||
|
Price *Price `json:"price,omitempty"`
|
||||||
|
AreaM2 int `json:"area_m2,omitempty"`
|
||||||
|
RoomsX2 int `json:"rooms_x2,omitempty"` // rooms*2, so 2.5 rooms = 5
|
||||||
|
Features []string `json:"features,omitempty"`
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
Description string `json:"description,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
|
||||||
|
PoW uint64 `json:"pow"`
|
||||||
|
Sig string `json:"sig,omitempty"` // hex, over canonical bytes without sig
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewID returns a fresh random listing ID (32 hex characters).
|
||||||
|
func NewID() (string, error) {
|
||||||
|
var b [16]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(b[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// unsignedBytes is the canonical encoding without the signature. Both the
|
||||||
|
// signature and the proof-of-work are computed over these bytes.
|
||||||
|
func (l *Listing) unsignedBytes() ([]byte, error) {
|
||||||
|
c := *l
|
||||||
|
c.Sig = ""
|
||||||
|
return jcs.Marshal(&c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bytes returns the full canonical encoding including the signature.
|
||||||
|
func (l *Listing) Bytes() ([]byte, error) {
|
||||||
|
return jcs.Marshal(l)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash identifies this exact version of the listing (including signature).
|
||||||
|
func (l *Listing) Hash() (string, error) {
|
||||||
|
b, err := l.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(b)
|
||||||
|
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) {
|
||||||
|
b, err := l.unsignedBytes()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return leadingZeroBits(sha256.Sum256(b)) >= difficulty, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seal sets the author, mines the proof-of-work and signs the listing.
|
||||||
|
func (l *Listing) Seal(id *identity.Identity, difficulty int) error {
|
||||||
|
l.Author = id.PublicKeyHex()
|
||||||
|
l.Sig = ""
|
||||||
|
for l.PoW = 0; ; l.PoW++ {
|
||||||
|
if l.PoW > maxSafeInt {
|
||||||
|
return errors.New("listing: proof-of-work exhausted")
|
||||||
|
}
|
||||||
|
ok, err := l.powOK(difficulty)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b, err := l.unsignedBytes()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
l.Sig = hex.EncodeToString(id.Sign(b))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check fully validates a received listing: structure, size, signature and
|
||||||
|
// proof-of-work. now is used for lifetime and clock-skew checks.
|
||||||
|
func (l *Listing) Check(now time.Time, difficulty int) error {
|
||||||
|
if err := l.validate(now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
full, err := l.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(full) > MaxSize {
|
||||||
|
return fmt.Errorf("listing: %d bytes exceeds limit of %d", len(full), MaxSize)
|
||||||
|
}
|
||||||
|
unsigned, err := l.unsignedBytes()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sig, err := hex.DecodeString(l.Sig)
|
||||||
|
if err != nil || len(sig) != 64 {
|
||||||
|
return errors.New("listing: malformed signature")
|
||||||
|
}
|
||||||
|
if !identity.Verify(l.Author, unsigned, sig) {
|
||||||
|
return errors.New("listing: bad signature")
|
||||||
|
}
|
||||||
|
ok, err := l.powOK(difficulty)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return errors.New("listing: insufficient proof-of-work")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Supersedes reports whether l is a newer version of other.
|
||||||
|
func (l *Listing) Supersedes(other *Listing) bool {
|
||||||
|
return l.ID == other.ID && l.Author == other.Author && l.Seq > other.Seq
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Listing) validate(now time.Time) error {
|
||||||
|
if l.Version != Version {
|
||||||
|
return fmt.Errorf("listing: unsupported version %d", l.Version)
|
||||||
|
}
|
||||||
|
if !isHex(l.ID, 32) {
|
||||||
|
return errors.New("listing: id must be 32 hex characters")
|
||||||
|
}
|
||||||
|
if !isHex(l.Author, 64) {
|
||||||
|
return errors.New("listing: author must be 64 hex characters")
|
||||||
|
}
|
||||||
|
if l.Seq > maxSafeInt || l.PoW > maxSafeInt {
|
||||||
|
return errors.New("listing: number out of range")
|
||||||
|
}
|
||||||
|
if l.ExpiresAt <= l.CreatedAt {
|
||||||
|
return errors.New("listing: expires_at must be after created_at")
|
||||||
|
}
|
||||||
|
if time.Duration(l.ExpiresAt-l.CreatedAt)*time.Second > MaxLifetime {
|
||||||
|
return errors.New("listing: lifetime exceeds 30 days")
|
||||||
|
}
|
||||||
|
if time.Unix(l.CreatedAt, 0).After(now.Add(MaxClockSkew)) {
|
||||||
|
return errors.New("listing: created_at is in the future")
|
||||||
|
}
|
||||||
|
if !time.Unix(l.ExpiresAt, 0).After(now) {
|
||||||
|
return errors.New("listing: expired")
|
||||||
|
}
|
||||||
|
if err := validGeohash(l.Geohash); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if l.Tombstone {
|
||||||
|
return l.validateTombstone()
|
||||||
|
}
|
||||||
|
return l.validateContent()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Listing) validateTombstone() error {
|
||||||
|
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 ||
|
||||||
|
l.Endpoint != "" || l.Delegate != "" {
|
||||||
|
return errors.New("listing: tombstone must not carry content")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Listing) validateContent() error {
|
||||||
|
if !kinds[l.Kind] {
|
||||||
|
return fmt.Errorf("listing: invalid kind %q", l.Kind)
|
||||||
|
}
|
||||||
|
if !categories[l.Category] {
|
||||||
|
return fmt.Errorf("listing: invalid category %q", l.Category)
|
||||||
|
}
|
||||||
|
p := l.Price
|
||||||
|
if p == nil {
|
||||||
|
return errors.New("listing: price required")
|
||||||
|
}
|
||||||
|
if p.AmountCents <= 0 || p.AmountCents > maxSafeInt {
|
||||||
|
return errors.New("listing: price out of range")
|
||||||
|
}
|
||||||
|
if p.Currency != "EUR" {
|
||||||
|
return errors.New("listing: only EUR is supported")
|
||||||
|
}
|
||||||
|
wantPeriod := map[string]string{"rent": "month", "sale": "once"}[l.Kind]
|
||||||
|
if p.Period != wantPeriod {
|
||||||
|
return fmt.Errorf("listing: %s requires period %q", l.Kind, wantPeriod)
|
||||||
|
}
|
||||||
|
if l.AreaM2 < 0 || l.AreaM2 > 100000 || l.RoomsX2 < 0 || l.RoomsX2 > 200 {
|
||||||
|
return errors.New("listing: area or rooms out of range")
|
||||||
|
}
|
||||||
|
if err := validText(l.Title, 1, 120, false); err != nil {
|
||||||
|
return fmt.Errorf("listing: title: %w", err)
|
||||||
|
}
|
||||||
|
if err := validText(l.Description, 0, 4000, true); err != nil {
|
||||||
|
return fmt.Errorf("listing: description: %w", err)
|
||||||
|
}
|
||||||
|
if len(l.Features) > 20 {
|
||||||
|
return errors.New("listing: too many features")
|
||||||
|
}
|
||||||
|
for _, f := range l.Features {
|
||||||
|
if err := validText(f, 1, 40, false); err != nil {
|
||||||
|
return fmt.Errorf("listing: feature: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(l.Images) > 20 {
|
||||||
|
return errors.New("listing: too many images")
|
||||||
|
}
|
||||||
|
for _, im := range l.Images {
|
||||||
|
if !isHex(im.Hash, 64) || !isHex(im.ThumbHash, 64) {
|
||||||
|
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) {
|
||||||
|
return errors.New("listing: invalid delegate")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func validGeohash(g string) error {
|
||||||
|
if len(g) != GeohashPrecision {
|
||||||
|
return fmt.Errorf("listing: geohash must have precision %d", GeohashPrecision)
|
||||||
|
}
|
||||||
|
for i := 0; i < len(g); i++ {
|
||||||
|
found := false
|
||||||
|
for j := 0; j < len(geohashAlphabet); j++ {
|
||||||
|
if g[i] == geohashAlphabet[j] {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return errors.New("listing: invalid geohash character")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validPeerID(s string) bool {
|
||||||
|
if len(s) < 8 || len(s) > 128 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validText(s string, min, max int, allowNewlines bool) error {
|
||||||
|
if !utf8.ValidString(s) {
|
||||||
|
return errors.New("invalid UTF-8")
|
||||||
|
}
|
||||||
|
n := utf8.RuneCountInString(s)
|
||||||
|
if n < min || n > max {
|
||||||
|
return fmt.Errorf("length must be %d-%d characters", min, max)
|
||||||
|
}
|
||||||
|
for _, r := range s {
|
||||||
|
if r == '\n' && allowNewlines {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if unicode.IsControl(r) {
|
||||||
|
return errors.New("control characters not allowed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package listing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testDifficulty = 12
|
||||||
|
|
||||||
|
var now = time.Unix(1_800_000_000, 0)
|
||||||
|
|
||||||
|
func sample(t *testing.T) *Listing {
|
||||||
|
t.Helper()
|
||||||
|
id, err := NewID()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return &Listing{
|
||||||
|
Version: Version,
|
||||||
|
ID: id,
|
||||||
|
Seq: 1,
|
||||||
|
CreatedAt: now.Unix(),
|
||||||
|
ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
|
||||||
|
Kind: "rent",
|
||||||
|
Category: "apartment",
|
||||||
|
Geohash: "u1xjhx",
|
||||||
|
Price: &Price{AmountCents: 120000, Currency: "EUR", Period: "month"},
|
||||||
|
AreaM2: 55,
|
||||||
|
RoomsX2: 5,
|
||||||
|
Features: []string{"balcony", "elevator"},
|
||||||
|
Title: "Helle 2,5-Zimmer-Wohnung",
|
||||||
|
Endpoint: "12D3KooWExamplePeerID",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sealed(t *testing.T) (*Listing, *identity.Identity) {
|
||||||
|
t.Helper()
|
||||||
|
key, err := identity.Generate()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l := sample(t)
|
||||||
|
if err := l.Seal(key, testDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return l, key
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSealCheckRoundTrip(t *testing.T) {
|
||||||
|
l, _ := sealed(t)
|
||||||
|
if err := l.Check(now, testDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCanonicalBytesDeterministic(t *testing.T) {
|
||||||
|
l, _ := sealed(t)
|
||||||
|
a, _ := l.Bytes()
|
||||||
|
b, _ := l.Bytes()
|
||||||
|
if string(a) != string(b) {
|
||||||
|
t.Fatal("canonical bytes differ between calls")
|
||||||
|
}
|
||||||
|
// keys must be sorted: "author" comes first.
|
||||||
|
if !strings.HasPrefix(string(a), `{"area_m2":55,"author":`) {
|
||||||
|
t.Fatalf("unexpected canonical prefix: %s", a[:40])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTamperDetected(t *testing.T) {
|
||||||
|
l, _ := sealed(t)
|
||||||
|
l.Price.AmountCents = 1
|
||||||
|
if err := l.Check(now, testDifficulty); err == nil {
|
||||||
|
t.Fatal("tampered listing accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForeignSignatureRejected(t *testing.T) {
|
||||||
|
l, _ := sealed(t)
|
||||||
|
other, _ := identity.Generate()
|
||||||
|
l.Author = other.PublicKeyHex()
|
||||||
|
if err := l.Check(now, testDifficulty); err == nil {
|
||||||
|
t.Fatal("listing with swapped author accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInsufficientPoW(t *testing.T) {
|
||||||
|
l, _ := sealed(t)
|
||||||
|
// Difficulty demanded by the verifier is far above what was mined.
|
||||||
|
if err := l.Check(now, 40); err == nil {
|
||||||
|
t.Fatal("expected proof-of-work failure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpiryAndLifetime(t *testing.T) {
|
||||||
|
key, _ := identity.Generate()
|
||||||
|
|
||||||
|
l := sample(t)
|
||||||
|
l.ExpiresAt = l.CreatedAt + int64(31*24*3600)
|
||||||
|
_ = l.Seal(key, 0)
|
||||||
|
if err := l.Check(now, 0); err == nil {
|
||||||
|
t.Fatal("lifetime over 30 days accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
l = sample(t)
|
||||||
|
_ = l.Seal(key, 0)
|
||||||
|
if err := l.Check(now.Add(8*24*time.Hour), 0); err == nil {
|
||||||
|
t.Fatal("expired listing accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
l = sample(t)
|
||||||
|
l.CreatedAt = now.Add(time.Hour).Unix()
|
||||||
|
l.ExpiresAt = l.CreatedAt + 3600
|
||||||
|
_ = l.Seal(key, 0)
|
||||||
|
if err := l.Check(now, 0); err == nil {
|
||||||
|
t.Fatal("future-dated listing accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContentValidation(t *testing.T) {
|
||||||
|
key, _ := identity.Generate()
|
||||||
|
cases := map[string]func(*Listing){
|
||||||
|
"bad kind": func(l *Listing) { l.Kind = "swap" },
|
||||||
|
"bad category": func(l *Listing) { l.Category = "castle" },
|
||||||
|
"bad geohash": func(l *Listing) { l.Geohash = "u1xjh" },
|
||||||
|
"geohash alphabet": func(l *Listing) { l.Geohash = "u1xjha" }, // 'a' is not in the alphabet
|
||||||
|
"rent period": func(l *Listing) { l.Price.Period = "once" },
|
||||||
|
"zero price": func(l *Listing) { l.Price.AmountCents = 0 },
|
||||||
|
"currency": func(l *Listing) { l.Price.Currency = "USD" },
|
||||||
|
"empty title": func(l *Listing) { l.Title = "" },
|
||||||
|
"control char": func(l *Listing) { l.Title = "a\x00b" },
|
||||||
|
"bad image hash": func(l *Listing) { l.Images = []Image{{Hash: "zz", ThumbHash: "zz"}} },
|
||||||
|
"no endpoint": func(l *Listing) { l.Endpoint = "" },
|
||||||
|
"huge description": func(l *Listing) { l.Description = strings.Repeat("x", 4001) },
|
||||||
|
}
|
||||||
|
for name, mutate := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
l := sample(t)
|
||||||
|
mutate(l)
|
||||||
|
if err := l.Seal(key, 0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := l.Check(now, 0); err == nil {
|
||||||
|
t.Fatal("invalid listing accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTombstoneAndSupersedes(t *testing.T) {
|
||||||
|
l, key := sealed(t)
|
||||||
|
|
||||||
|
ts := &Listing{
|
||||||
|
Version: Version,
|
||||||
|
ID: l.ID,
|
||||||
|
Seq: l.Seq + 1,
|
||||||
|
CreatedAt: now.Unix(),
|
||||||
|
ExpiresAt: now.Add(24 * time.Hour).Unix(),
|
||||||
|
Tombstone: true,
|
||||||
|
Geohash: l.Geohash,
|
||||||
|
}
|
||||||
|
if err := ts.Seal(key, testDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ts.Check(now, testDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ts.Supersedes(l) || l.Supersedes(ts) {
|
||||||
|
t.Fatal("tombstone must supersede the original, not the reverse")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A different author cannot supersede someone else's listing.
|
||||||
|
other, _ := identity.Generate()
|
||||||
|
forged := *ts
|
||||||
|
_ = forged.Seal(other, testDifficulty)
|
||||||
|
if forged.Supersedes(l) {
|
||||||
|
t.Fatal("tombstone by a different author must not supersede")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tombstones must not smuggle content.
|
||||||
|
ts.Title = "still here"
|
||||||
|
_ = ts.Seal(key, testDifficulty)
|
||||||
|
if err := ts.Check(now, testDifficulty); err == nil {
|
||||||
|
t.Fatal("tombstone with content accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHashChangesWithContent(t *testing.T) {
|
||||||
|
a, _ := sealed(t)
|
||||||
|
b := *a
|
||||||
|
b.Seq++
|
||||||
|
ha, _ := a.Hash()
|
||||||
|
hb, _ := b.Hash()
|
||||||
|
if ha == hb {
|
||||||
|
t.Fatal("hash must differ for different content")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user