Rename the binary to allmende, add a Makefile with Bonn as default region

- cmd/node -> cmd/allmende; usage, messages and docs use the new name
- Makefile: build, init, run (REGION defaults to u1j, Bonn), vet, test,
  web, web-test, check, clean

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:49:55 +01:00
co-authored by Claude Sonnet 5.5
parent d021989f09
commit 19fea7f524
8 changed files with 60 additions and 25 deletions
+126
View File
@@ -0,0 +1,126 @@
package main
import (
"bufio"
"crypto/rand"
"errors"
"flag"
"fmt"
"io"
"math/big"
"os"
"path/filepath"
"strings"
"time"
"golang.org/x/term"
"git.stinnesbeck.com/nils/allmende/internal/identity"
)
func cmdInit(args []string) error {
fs := flag.NewFlagSet("init", flag.ExitOnError)
data := dataFlag(fs)
fs.Parse(args)
if _, err := os.Stat(filepath.Join(*data, "device.key")); err == nil {
return fmt.Errorf("%s is already set up. To get access back after losing this machine, use 'allmende recover'", *data)
}
root, phrase, err := identity.NewRoot()
if err != nil {
return err
}
words := strings.Fields(phrase)
showPhrase(words)
// Only ask for confirmation when a person is at the keyboard.
if term.IsTerminal(int(os.Stdin.Fd())) {
if err := confirmPhrase(bufio.NewReader(os.Stdin), words); err != nil {
return err
}
}
dev, err := identity.Enroll(root, time.Now(), certLifetime)
if err != nil {
return err
}
// The identity key is not saved anywhere: only the phrase can recreate it.
if err := dev.Save(*data); err != nil {
return err
}
token, err := newToken()
if err != nil {
return err
}
if err := writeToken(*data, token); err != nil {
return err
}
fmt.Printf("\nDone. This machine is set up as a device of identity %s…\n", dev.Cert.Author[:12])
fmt.Printf("Your device certificate is valid until %s.\n\n", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
fmt.Printf("Next: allmende run --region <region> --data %s\n", *data)
fmt.Printf("The admin token for publishing is in %s\n", filepath.Join(*data, tokenFile))
return nil
}
func showPhrase(words []string) {
fmt.Print(`
Your recovery phrase
--------------------
These 12 words ARE your identity. They are shown only once and are not stored
on this computer. Write them on paper and keep them somewhere safe.
With them you can recover your account if this computer is lost, broken or
hacked. Anyone who has them can act as you, so never type them into a website
or share them.
`)
for i := 0; i < len(words); i += 3 {
fmt.Printf(" %2d. %-12s %2d. %-12s %2d. %-12s\n",
i+1, words[i], i+2, words[i+1], i+3, words[i+2])
}
fmt.Println()
}
// confirmPhrase asks for two random words so the user has really written
// the phrase down.
func confirmPhrase(in *bufio.Reader, words []string) error {
picks, err := twoDistinct(len(words))
if err != nil {
return err
}
fmt.Println("To make sure you wrote it down, please enter two of the words.")
for _, i := range picks {
for {
fmt.Printf("Word number %d: ", i+1)
line, err := in.ReadString('\n')
if err != nil && (!errors.Is(err, io.EOF) || line == "") {
return errors.New("no input; run 'allmende init' again in a terminal")
}
if strings.EqualFold(strings.TrimSpace(line), words[i]) {
break
}
fmt.Println("That is not the right word. Check your notes and try again.")
}
}
return nil
}
func twoDistinct(n int) ([2]int, error) {
a, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
if err != nil {
return [2]int{}, err
}
b, err := rand.Int(rand.Reader, big.NewInt(int64(n-1)))
if err != nil {
return [2]int{}, err
}
x, y := int(a.Int64()), int(b.Int64())
if y >= x {
y++
}
if x > y {
x, y = y, x
}
return [2]int{x, y}, nil
}
+17
View File
@@ -0,0 +1,17 @@
package main
import "testing"
func TestLoginURL(t *testing.T) {
for addr, want := range map[string]string{
"127.0.0.1:8080": "http://127.0.0.1:8080/#/login/tok",
"0.0.0.0:8080": "http://127.0.0.1:8080/#/login/tok", // a wildcard cannot be opened
"[::]:9000": "http://127.0.0.1:9000/#/login/tok",
"[::1]:8080": "http://[::1]:8080/#/login/tok",
"192.0.2.7:80": "http://192.0.2.7:80/#/login/tok",
} {
if got := loginURL(addr, "tok"); got != want {
t.Errorf("loginURL(%q) = %q, want %q", addr, got, want)
}
}
}
+118
View File
@@ -0,0 +1,118 @@
// Command allmende runs an Allmende node.
//
// allmende init first-time setup: creates your identity and shows your recovery phrase
// allmende run run the node (replicates listings, serves the HTTP API)
// allmende recover restore from the recovery phrase after a lost or compromised machine
package main
import (
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
const (
certLifetime = 365 * 24 * time.Hour
dbFile = "allmende.db"
tokenFile = "admin.token"
)
const usage = `Allmende: a free, distributed marketplace for homes.
Usage:
allmende init [--data DIR] create your identity (first run)
allmende run [--data DIR] --region u1x run the node
allmende recover [--data DIR] restore access using your recovery phrase
Run "allmende <command> -h" for the options of a command.
`
func main() {
if len(os.Args) < 2 {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
var err error
switch os.Args[1] {
case "init":
err = cmdInit(os.Args[2:])
case "run":
err = cmdRun(os.Args[2:])
case "recover":
err = cmdRecover(os.Args[2:])
case "help", "-h", "--help":
fmt.Print(usage)
default:
fmt.Fprintf(os.Stderr, "unknown command %q\n\n%s", os.Args[1], usage)
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
// --- shared helpers -------------------------------------------------------
func defaultDataDir() string {
if d := os.Getenv("ALLMENDE_DATA"); d != "" {
return d
}
if x := os.Getenv("XDG_DATA_HOME"); x != "" {
return filepath.Join(x, "allmende")
}
home, err := os.UserHomeDir()
if err != nil {
return "allmende-data"
}
return filepath.Join(home, ".local", "share", "allmende")
}
func dataFlag(fs *flag.FlagSet) *string {
return fs.String("data", defaultDataDir(), "directory for keys and the database (env ALLMENDE_DATA)")
}
// listFlag is a repeatable, comma-separated string flag.
type listFlag []string
func (l *listFlag) String() string { return strings.Join(*l, ",") }
func (l *listFlag) Set(v string) error {
for _, p := range strings.Split(v, ",") {
if p = strings.TrimSpace(p); p != "" {
*l = append(*l, p)
}
}
return nil
}
func newToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return hex.EncodeToString(b[:]), nil
}
// writeToken replaces the admin token file, readable only by the owner.
func writeToken(dir, token string) error {
path := filepath.Join(dir, tokenFile)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, []byte(token+"\n"), 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
func readToken(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, tokenFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
+137
View File
@@ -0,0 +1,137 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"time"
"golang.org/x/term"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// cmdRecover restores access from the recovery phrase. It voids every device
// certified so far (including a stolen one), enrolls this machine as a fresh
// device, and re-signs this node's own listings so they carry on. It also
// serves as the yearly certificate renewal.
func cmdRecover(args []string) error {
fs := flag.NewFlagSet("recover", flag.ExitOnError)
data := dataFlag(fs)
difficulty := fs.Int("difficulty", listing.DefaultDifficulty, "proof-of-work bits; must match the network")
fs.Parse(args)
phrase, err := readPhrase()
if err != nil {
return err
}
root, err := identity.FromPhrase(phrase)
if err != nil {
return err
}
author := root.PublicKeyHex()
ctx := context.Background()
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty})
if err != nil {
return err
}
defer st.Close()
// Remember our listings: the revocation below purges them from the store.
own, err := st.ByAuthor(ctx, author)
if err != nil {
return err
}
now := time.Now()
rev, err := identity.RevokeAll(root, now, *difficulty)
if err != nil {
return err
}
// Enrolled at the same instant: a certificate issued at the cutoff stays valid.
dev, err := identity.Enroll(root, now, certLifetime)
if err != nil {
return err
}
if err := retireOldDevice(*data, now); err != nil {
return err
}
if err := dev.Save(*data); err != nil {
return err
}
token, err := newToken()
if err != nil {
return err
}
if err := writeToken(*data, token); err != nil {
return err
}
if _, err := st.PutRevocation(ctx, rev); err != nil {
return err
}
republished := 0
for _, old := range own {
l := *old
l.Seq = old.Seq + 1
l.CreatedAt = now.Unix()
if max := now.Add(listing.MaxLifetime).Unix(); l.ExpiresAt > max {
l.ExpiresAt = max
}
if err := l.Seal(dev, *difficulty); err != nil {
return err
}
if _, err := st.Put(ctx, &l); err != nil {
fmt.Fprintf(os.Stderr, "warning: could not re-sign listing %s: %v\n", old.ID, err)
continue
}
republished++
}
fmt.Printf("Recovered identity %s…\n", author[:12])
fmt.Println(" - All earlier devices of this identity have been revoked.")
fmt.Printf(" - This machine is now a new device (certificate valid until %s).\n",
time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
fmt.Printf(" - %d of your listings were re-signed from this device.\n", republished)
fmt.Println(" - A new admin token was written; the old one no longer works.")
fmt.Println("\nStart the node with 'allmende run' so the revocation spreads through the network.")
return nil
}
// retireOldDevice moves a previous device's files aside so the revoked key is
// never used again but is not silently destroyed either.
func retireOldDevice(dir string, now time.Time) error {
for _, name := range []string{"device.key", "device.cert"} {
src := filepath.Join(dir, name)
if _, err := os.Stat(src); errors.Is(err, os.ErrNotExist) {
continue
}
dst := fmt.Sprintf("%s.revoked-%d", src, now.Unix())
if err := os.Rename(src, dst); err != nil {
return err
}
}
return nil
}
// readPhrase reads the recovery phrase without echoing it when possible.
func readPhrase() (string, error) {
fd := int(os.Stdin.Fd())
if term.IsTerminal(fd) {
fmt.Fprint(os.Stderr, "Recovery phrase (12 words; what you type is hidden): ")
b, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
return string(b), err
}
b, err := io.ReadAll(io.LimitReader(os.Stdin, 4096))
return string(b), err
}
+199
View File
@@ -0,0 +1,199 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"git.stinnesbeck.com/nils/allmende/internal/api"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/p2p"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
announceFirst = 10 * time.Second
announceInterval = 30 * time.Minute
certWarnBefore = 30 * 24 * time.Hour
)
func cmdRun(args []string) error {
fs := flag.NewFlagSet("run", flag.ExitOnError)
data := dataFlag(fs)
var regions, bootstrap, listen listFlag
fs.Var(&regions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable")
fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/<id>); repeatable")
fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)")
httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API")
noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network")
difficulty := fs.Int("difficulty", listing.DefaultDifficulty,
"proof-of-work bits for listings; must match the rest of the network")
msgDifficulty := fs.Int("message-difficulty", message.DefaultDifficulty,
"proof-of-work bits for messages; must match the rest of the network")
maxNewThreads := fs.Int("max-new-threads", inbox.DefaultMaxNewThreads,
"how many new conversations each of your listings can start per day")
fs.Parse(args)
if len(regions) == 0 {
return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)")
}
dev, err := identity.LoadDevice(*data)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%s is not set up yet: run 'allmende init' first", *data)
}
return err
}
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
if until <= 0 {
return errors.New("this device's certificate has expired; run 'allmende recover' to renew it")
}
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
if until < certWarnBefore {
log.Warn("device certificate expires soon; run 'allmende recover' to renew it",
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
}
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{
Difficulty: *difficulty, MessageDifficulty: *msgDifficulty,
})
if err != nil {
return err
}
defer st.Close()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
node, err := p2p.New(ctx, p2p.Config{
Device: dev,
Store: st,
ListenAddrs: listen,
Bootstrap: bootstrap,
Regions: regions,
MDNS: !*noMDNS,
Difficulty: *difficulty,
Logger: log,
MessageDifficulty: *msgDifficulty,
})
if err != nil {
return err
}
defer node.Close()
token := readToken(*data)
if token == "" {
log.Warn("no admin token found; publishing through the API is disabled")
}
handler := api.New(api.Config{
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
MessageDifficulty: *msgDifficulty,
Inbox: &inbox.Inbox{
Store: st, Device: dev, Publisher: node,
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
},
})
ln, err := net.Listen("tcp", *httpAddr)
if err != nil {
return err
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second, // publishing mines proof-of-work
IdleTimeout: 2 * time.Minute,
}
go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("http server", "err", err)
stop()
}
}()
log.Info("node running",
"peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…",
"regions", []string(regions), "http", ln.Addr().String())
for _, a := range node.Addrs() {
log.Info("listening", "addr", a)
}
if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" {
log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public")
}
if token != "" {
// Printed to the terminal, not logged: the token must not end up in a
// log file. It sits in the URL fragment, which a browser never sends to
// a server; the page moves it into sessionStorage and removes it.
fmt.Fprintf(os.Stderr, "\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(ln.Addr().String(), token))
}
go announce(ctx, log, node, st, dev.Cert.Author)
<-ctx.Done()
log.Info("shutting down")
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutdown)
}
// announce periodically re-gossips this identity's revocations and live
// listings. Gossip only reaches peers connected at that moment; this makes
// sure newcomers hear about them without waiting for a sync.
func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) {
timer := time.NewTimer(announceFirst)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if revs, err := st.Revocations(ctx); err == nil {
for _, r := range revs {
if r.Author == author {
if err := node.PublishRevocation(ctx, r); err != nil {
log.Debug("announce revocation", "err", err)
}
}
}
}
if own, err := st.ByAuthor(ctx, author); err == nil {
for _, l := range own {
if err := node.Publish(ctx, l); err != nil {
log.Debug("announce listing", "id", l.ID, "err", err)
}
}
}
timer.Reset(announceInterval)
}
}
// loginURL is the link that signs the owner in to the web UI.
func loginURL(listenAddr, token string) string {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "http://" + listenAddr + "/#/login/" + token
}
// A wildcard address (0.0.0.0, ::) is not something a browser can open.
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
host = "127.0.0.1"
}
// JoinHostPort brackets IPv6 addresses.
return "http://" + net.JoinHostPort(host, port) + "/#/login/" + token
}