Make a reader in Go, step 3: follow a feed

A feed is one author's numbered series of entries. Each entry is small and signed with the author's key, and says, for example, "number 1 of my feed is this blob, this size, with this title". The key is the feed's name: 64 hexadecimal digits. In this step your reader subscribes to a feed on a relay, checks every entry's signature, lists the titles of the articles, and opens one.

The code

follow/main.go, with step 1's article and step 2's relay packages:

// Step 3: follow a feed and open one of its articles.
package main

import (
    "bytes"
    "encoding/binary"
    "encoding/hex"
    "fmt"
    "log"
    "os"
    "strconv"

    "github.com/gorilla/websocket"
    tersenet "github.com/runvnc/terse/sdk/go"

    "reader/article"
    "reader/relay"
)

func main() {
    key, err := hex.DecodeString(os.Args[2])
    if err != nil || len(key) != 32 {
        log.Fatal("a feed key is 64 hexadecimal digits")
    }
    url := os.Args[1]
    conn, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        log.Fatal(err)
    }
    subscribe := append([]byte{0x04, 2, 0, 0, 0}, key...)
    subscribe = append(subscribe, 0, 0, 0, 0)
    err = conn.WriteMessage(websocket.BinaryMessage, subscribe)
    if err != nil {
        log.Fatal(err)
    }
    _, reply, err := conn.ReadMessage()
    if err != nil || len(reply) < 10 || reply[5] != 1 {
        log.Fatal("the relay refused the subscription")
    }
    highest := binary.LittleEndian.Uint32(reply[6:])
    articles := map[uint32][32]byte{}
    for caughtUp := highest == 0; !caughtUp; {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Fatal(err)
        }
        if len(message) < 37 || message[0] != 0x90 {
            continue
        }
        entry := message[1:]
        seq := binary.LittleEndian.Uint32(entry[32:])
        caughtUp = seq >= highest
        e, err := tersenet.VerifyEntry(entry)
        mine := err == nil && bytes.Equal(e.Feed[:], key)
        if mine && e.Kind == 1 {
            title := article.Visible(e.Title)
            fmt.Printf("%d  %s\n", seq, title)
            articles[seq] = e.Blob
        }
    }
    if len(os.Args) < 4 {
        return
    }
    seq, _ := strconv.Atoi(os.Args[3])
    id, ok := articles[uint32(seq)]
    if !ok {
        log.Fatal("no such article in the feed")
    }
    blob, err := relay.Get(conn, id)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println()
    article.Show(blob)
}

It is 75 lines; the whole program, with the article and relay packages, is 182. The entries are checked by one call to the Tersenet SDK for Go, tersenet.VerifyEntry, named in step 2's go.mod.

How it works

main connects and sends a Subscribe: the byte 04h, a request number (here 2), the feed's key, and 4 bytes after, the highest entry number you already hold: 0, so the relay sends everything it has. Its reply starts with 84h and gives, after a status byte, highest: the highest entry number it holds.

Then the relay sends the feed's entries, oldest first, each in a message that starts with 90h. The loop reads them until it has one numbered highest or more: then it has caught up. An entry is, in order: the feed's key (32 bytes), its number seq (4), a time (4), a kind (1: 1 for an article), the blob's size (3) and ID (32), a reply-to ID (32), the title's length (1), the title, and a 64-byte signature. So an entry with a title of n bytes is 173 + n bytes long.

tersenet.VerifyEntry checks an entry by every rule the network sets and returns its fields, or an error naming the rule it breaks: the length, a title of at most 120 bytes and valid UTF-8, a seq from 1, a kind that is not reserved, a size from 1 byte to 1 MiB (4 KiB for a profile), a display name as a profile's or a program's title, and the signature. main keeps the valid entries of the feed asked for that are of kind 1, articles, and prints each one's number and title; any other entry is dropped, unseen.

The signature is Ed25519, over the 13 bytes terse-entry-0 followed by the entry without its signature, and it is checked strictly. Go's own ed25519.Verify is not enough: it accepts a key that is not the canonical encoding of its point, and a key or an R of small order, for which anyone can forge signatures. Signatures and valid entries gives every rule and the reason for it, enough to write the check yourself. The SDK is one file, sdk/go/tersenet.go in the Tersenet sources, 168 lines with its comments: read it. vectors/entries.txt holds a forged entry for each rule; the test sends every one to this program from a fake relay, and only the valid articles are listed.

To open an entry, main gets its blob with step 2's relay.Get, which checks its hash and skips any entry the relay sends meanwhile, and shows it with article.Show.

Getting the SDK

In a module of your own, go get adds it to go.mod:

go get github.com/runvnc/terse/sdk/[email protected]

In the Tersenet sources, go.work beside go.mod replaces that version with the copy in sdk/go, so the examples build with the SDK they are tested with.

Run it

With the relay of step 2 running, make a key and publish the article as entry 1 of your feed:

terse key new
terse feed publish ../hello.txt --title Hello \
  --relay ws://127.0.0.1:7979

terse key new makes your key and prints it; if you made a profile in the user guide you have one already. terse key show prints it, so give it to the program:

go run ./follow ws://127.0.0.1:7979 $(terse key show)
1  Hello

Add an entry's number to open it:

go run ./follow ws://127.0.0.1:7979 $(terse key show) 1

It prints the list again, an empty line, and the article as step 1 shows it.

What it leaves out

A complete reader keeps its subscriptions and every entry it receives, lists the newest first, follows several feeds on several relays and stays connected for new entries, downloads small articles before you open them, and shows each feed's name with its key. It also notes when a blob's length is not the size its entry gives. tersereader, written from the specification alone, checks entries without the SDK, in internal/terse/entry.go and internal/terse/key.go, and does the rest in internal/client/client.go; a test checks that it and the SDK agree on thousands of altered entries. Writing a reader without the machine lists all a complete reader must do.

What you have now

A Tersenet reader in Go: it follows a feed, checks everything it receives against its signature and hash, and shows the articles.