kolo-gossip spreads signed messages to every member of a topic, hop by hop, with no relay in the middle. It follows the GossipSub v1.0 and v1.1 specifications with the IDONTWANT message of v1.2. Each node keeps a mesh of a few peers per topic and pushes full messages along it. It announces the ids of recent messages to its other peers so that gaps are repaired, and it scores its peers so that spam, Sybil and eclipse attacks, the attacks that Vyzovitis et al. evaluate, lose their links. When a well-scored peer prunes a mesh link and lists other peers of the topic, the node dials them (peer exchange). Every message is signed by the author's kolo-id device key and checked against the person the application expects: a roster for closed rooms, or a chain fetched from the forwarding peer in open rooms.
The application supplies three things: the connections, usually kolo-swarm peers (the library itself never dials; with Config.Swarm it asks the swarm to dial the peers of peer exchange); for each room, a roster of the devices it accepts or an open mode; and a validator that decides who may post. Frames are encoded with kolo-codec. The library keeps no history and gives no order: kolo-pin peers keep history for members who were offline, and kolo-braid keeps agreed state, such as roles and bans. It is for small messages: media bytes stay in kolo-moq and file bytes in kolo-blobs. It is not wire compatible with other GossipSub implementations: it follows their algorithm and defaults, not their bytes. The Go package is kologossip.
A mesh per topic, checked at every hop
Each node checks a message before it forwards it, so an honest node forwards only what passed its own checks.
- Each node keeps a mesh of D = 6 peers per topic and fixes it at every heartbeat: it grafts peers when it has fewer than 4 and prunes when it has more than 12. A's mesh is solid; E and F are on the topic but outside it.
- The author signs the message with its device key under the context kolo-gossip/message/v0. With flood publishing, the default, it sends it to every peer on the topic that scores at least the publish threshold (-20), in its mesh or not.
- A checks the copy, cheapest first: size, time window (1 minute either way), signature and author. A message of 1,024 bytes or more then gets an IDONTWANT to A's other mesh peers, so they do not send A a copy.
- The application's validator runs last. On Accept, A delivers the message and forwards it to its mesh, except the sender, the author and the peers that sent IDONTWANT for it.
- Once per heartbeat (1 second), A sends IHAVE with the ids of the messages of its last 3 heartbeats to peers outside its mesh. A peer that misses one asks for it with IWANT, and A answers from its cache.
- A peer that sends invalid messages, such as a bad signature or a validator Reject, loses score. Below 0 it is pruned from the mesh at the next heartbeat; below the graylist threshold (-80) its frames are dropped and its connection is closed.
Install
go get github.com/ciranda-dev/kolo-gossipIt needs Go 1.26 or newer, is pure Go (it builds without cgo) and is IPv4 only. kolo-gossip is tagged v0.1.0: to pin it, run go get github.com/ciranda-dev/kolo-gossip@v0.1.0.
Quick start
A kolo-dht server and two nodes on loopback find each other, join a closed room and exchange a message. This is examples/basic of the repository; run it with go run ./examples/basic.
// Command basic runs a kolo-dht server and two gossip nodes on one IPv4 host (by default loopback); the nodes find
// each other through the server, join one room and exchange a signed message.
//
// go run ./examples/basic [-host 127.0.0.1]
package main
import (
"context"
"crypto/ed25519"
"crypto/sha256"
"flag"
"fmt"
"log"
"net"
"net/netip"
"sync/atomic"
"time"
kolodht "github.com/ciranda-dev/kolo-dht"
kologossip "github.com/ciranda-dev/kolo-gossip"
koloid "github.com/ciranda-dev/kolo-id"
koloswarm "github.com/ciranda-dev/kolo-swarm"
)
// roster is a closed room: the devices the application accepts as authors.
type roster map[string]*kologossip.Author
func (r roster) Lookup(_ kologossip.Topic, person, device ed25519.PublicKey) (*kologossip.Author, error) {
if a := r[string(person)+string(device)]; a != nil {
return a, nil
}
return nil, kologossip.ErrUnknownAuthor
}
// member is a person key with one device it certified.
func member(r roster) (*koloid.Identity, *koloid.DeviceCert) {
person, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
device, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
offer, err := person.OfferDeviceCert(device.PublicKey(), &koloid.IssueOptions{Serial: 1})
if err != nil {
log.Fatal(err)
}
cert, err := device.AcceptDeviceCert(offer, person.PublicKey())
if err != nil {
log.Fatal(err)
}
r[string(person.PublicKey())+string(device.PublicKey())] = &kologossip.Author{Person: person.PublicKey(), Cert: cert}
return device, cert
}
// start runs a swarm and a gossip node as device and serves every peer the swarm connects.
func start(ctx context.Context, host string, server netip.AddrPort, device *koloid.Identity, cert *koloid.DeviceCert) *kologossip.Gossip {
// The swarm refuses keys the gossip graylisted; it asks before the gossip exists.
var gp atomic.Pointer[kologossip.Gossip]
sw, err := koloswarm.New(ctx, net.JoinHostPort(host, "0"), device, &koloswarm.Config{
BootstrapNodes: []string{server.String()},
Allow: func(k ed25519.PublicKey, a netip.AddrPort) bool {
g := gp.Load()
return g == nil || g.Allow(k, a)
},
})
if err != nil {
log.Fatal(err)
}
if err := sw.Bootstrap(ctx, nil); err != nil {
log.Fatal(err)
}
g, err := kologossip.New(device, &kologossip.Config{Cert: cert, Swarm: sw})
if err != nil {
log.Fatal(err)
}
gp.Store(g)
go func() {
for {
ev, err := sw.Next(ctx)
if err != nil {
return
}
if ev.Kind == koloswarm.Connected {
go g.ServeConn(ctx, ev.Peer.Conn(), ev.Peer.Outbound())
}
}
}()
go func() {
<-ctx.Done()
g.Close()
sw.Close()
}()
return g
}
func main() {
host := flag.String("host", "127.0.0.1", "IPv4 address the server and the nodes listen on")
flag.Parse()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
sid, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
server, err := kolodht.New(ctx, net.JoinHostPort(*host, "0"), sid, &kolodht.Config{Server: true})
if err != nil {
log.Fatal(err)
}
defer server.Close()
saddr := server.Addr().(*net.UDPAddr).AddrPort()
saddr = netip.AddrPortFrom(saddr.Addr().Unmap(), saddr.Port())
r := roster{}
aliceDev, aliceCert := member(r)
bobDev, bobCert := member(r)
alice := start(ctx, *host, saddr, aliceDev, aliceCert)
bob := start(ctx, *host, saddr, bobDev, bobCert)
topic := kologossip.Topic(sha256.Sum256([]byte("kolo example room")))
ra, err := alice.Join(ctx, topic, &kologossip.TopicOptions{Authors: r})
if err != nil {
log.Fatal(err)
}
rb, err := bob.Join(ctx, topic, &kologossip.TopicOptions{Authors: r})
if err != nil {
log.Fatal(err)
}
for ra.Stats().Mesh == 0 {
select {
case <-ctx.Done():
log.Fatal(ctx.Err())
case <-time.After(50 * time.Millisecond):
}
}
if _, err := ra.Publish(ctx, []byte("hello room")); err != nil {
log.Fatal(err)
}
m, err := rb.Next(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("bob got %q from person %x, seq %d\n", m.Body, m.Person[:8], m.Seq)
}It prints:
$ go run ./examples/basic
bob got "hello room" from person <16 hex characters>, seq <a number>The roster is the application's list of devices it accepts as authors, here a map filled when each member's device certificate is made. Allow is chained into the swarm, which asks before the Gossip exists, and every peer the swarm connects is served with ServeConn. The loop waits until the room has a mesh peer before it publishes.
Formats
kolo-gossip follows the GossipSub specifications but not their bytes. It uses the kolo-codec encoding and kolo-secure connections. Every integer is a canonical kolo-codec uvarint; every value has exactly one valid encoding, and a decoder refuses short input, trailing bytes and counts that cannot fit in the bytes left.
Streams
A gossip peer is one authenticated connection, usually a kolo-swarm peer. Each side opens two unidirectional streams to the other:
| Kind | Byte | Carries |
|---|---|---|
| Control | c (0x63) | Control frames |
| Message | m (0x6d) | Envelopes, including answers to IWANT |
A stream starts with a header: uvarint version (0) then the kind byte. Then it carries frames: uvarint length || body. A control frame is at most MaxControlSize bytes and a message frame at most MaxMessageSize; the length is checked before the body is read. Two streams keep IDONTWANT, GRAFT and PRUNE from waiting behind a large message.
A peer breaks the protocol when it opens a third stream, a second stream of one kind or a stream with an unknown version or kind, sends a frame over its limit, a non-canonical length or a control frame that does not decode, sends a control frame with more than 32 GRAFT or PRUNE entries or more than MaxCertWants certificates (a peer may announce any number of topics: subscriptions to topics we hold no state for are kept up to MaxPeerTopics and the rest dropped, never a violation). The connection is closed with the QUIC application error code 0x6b67 and the message kologossip: protocol violation. A stream header or a frame that stops for FrameTimeout once started, a peer that opens no stream for FrameTimeout, and a peer that falls below the graylist threshold end gossip with that peer and close the connection with code 0 and no message. A stream that ends or is reset ends gossip with that peer and leaves the connection open.
Envelope
| Field | Encoding |
|---|---|
| version | uvarint, 0 |
| topic | 32 bytes |
| person | 32 bytes, the author's kolo-id person key |
| device | 32 bytes, the author's device key |
| seq | uvarint, the device's sequence number |
| time | uvarint, the author's Unix time in milliseconds |
| body | uvarint length then the bytes |
| signature | 64 bytes |
The signature is kolo-id's Ed25519ctx signature by the device key under the context kolo-gossip/message/v0, over every byte before it. With the default sequence numbers (Unix nanoseconds) the overhead is 177 to 179 bytes plus the body; a TopicOptions.Seq with small numbers makes it as small as 169 bytes for author times of this decade.
The message id is SHA-256("kolo-gossip/message-id/v0" || envelope), over the whole envelope including the signature. A forged copy can never take a real message's id, so the id of an ignored message can be remembered without blocking a real one, and an answer to IWANT is checked by hashing it.
The certificate chain is not carried. A receiver asks the room's roster (Authors), then, in open mode only, a cache of chains it verified, then sends one CERTWANT to the peer that forwarded the message. The peer answers each CERTWANT entry with the chain or, when it holds none, with the 64 bytes of person and device: a CERT entry of exactly that length means "not held" and ends the request without a penalty.
Control frame
Eight lists, each a uvarint count followed by its entries, always in this order:
| List | Entry |
|---|---|
| subscriptions | topic (32), bool: joined (1) or left (0) |
| GRAFT | topic (32) |
| PRUNE | topic (32), backoff in seconds (uvarint), peer records: count, then key (32), IPv4 address (4), port (uvarint, not 0) |
| IHAVE | topic (32), count, ids (32 each) |
| IWANT | ids (32 each) |
| IDONTWANT | ids (32 each) |
| CERTWANT | person (32), device (32) |
| CERT | uvarint length (1 to 514), a kolo-id device certificate chain, or person (32) and device (32) for "not held" |
Peer records in PRUNE are peer exchange, as in GossipSub v1.1, without the signed peer record: the dial that uses one is authenticated by kolo-secure and a wrong address costs one failed dial. A receiver reads them only for a topic it joined, only with scoring on and only from a peer whose score is at least AcceptPX (12 by default; 0 dials none); it takes at most PrunePeers (16) records of an entry, at random, leaves out its own key, keys it is connected to and repeats, and dials the rest through its swarm for that topic. A sender lists records only when Config.PeerExchange is on: in a PRUNE from the heartbeat for an oversubscribed mesh, from Leave, and refusing a GRAFT because the mesh is full, up to PrunePeers random peers subscribed to the topic, with a score of at least 0 and a known listening port (a peer that holds an outbound place and that we dialed from a socket other than our swarm's), never the pruned peer. A PRUNE for a negative score, for a GRAFT in backoff, or answering a frame that also grafts a topic we are not in carries none.
A control frame we send never exceeds what its receiver reads: at most MaxCertWants certificates, 32 GRAFT entries and 32 PRUNE entries. A sender with more puts them in further frames.
API reference
The API reference is generated from the Go source and is in English.
Package kologossip spreads signed messages to every member of a topic, hop by hop, without a relay. It follows a published mesh gossip protocol, version 1.1 with the IDONTWANT rule of 1.2 (docs/design.md, References): each node keeps a mesh of a few peers per topic, forwards full messages along it, announces recent message ids to other peers so gaps are repaired, and scores its peers to resist spam, Sybil and eclipse attacks.
Every message is signed by the author's kolo-id device key under the context "kolo-gossip/message/v0" and checked against the person the application expects: a roster (Authors, closed mode) or, in open mode, a chain fetched from the forwarding peer. The application's Validator decides membership, roles, rate and content. The library keeps no history and gives no order.
A Gossip takes its connections from the application: call ServeConn for each kolo-swarm peer. The API is experimental and may change before v1.0.0.
Variables
var (
// ErrInvalidConfig means a Config, TopicOptions or score parameter set breaks a constraint.
ErrInvalidConfig = errors.New("kologossip: invalid config")
// ErrInvalidArgument means an argument is unusable, such as a nil identity, a topic joined twice or an IPv6 peer.
ErrInvalidArgument = errors.New("kologossip: invalid argument")
// ErrClosed means the Gossip is closed.
ErrClosed = errors.New("kologossip: closed")
// ErrNotJoined means the Room was left.
ErrNotJoined = errors.New("kologossip: topic not joined")
// ErrTooLarge means a message is over its topic's MaxMessageSize.
ErrTooLarge = errors.New("kologossip: message too large")
// ErrLimit means a bound is full: MaxPeers or MaxTopics when the application set one, or the seen cache.
ErrLimit = errors.New("kologossip: limit reached")
// ErrDuplicate means a message with the same bytes was already published or seen, as with a repeated Seq.
ErrDuplicate = errors.New("kologossip: duplicate message")
// ErrProtocol means a peer broke the gossip protocol; ServeConn closed its connection.
ErrProtocol = errors.New("kologossip: protocol violation")
// ErrGraylisted means a peer's score fell below the graylist threshold; ServeConn stopped serving it.
ErrGraylisted = errors.New("kologossip: peer graylisted")
// ErrOwnChain means this node's own certificate chain has expired or its room's roster revoked it.
ErrOwnChain = errors.New("kologossip: own certificate chain not valid")
// ErrUnknownAuthor from Authors.Lookup means the roster does not know the device; the message is ignored.
ErrUnknownAuthor = errors.New("kologossip: unknown author")
// ErrBadEnvelope means VerifyEnvelope refused an envelope: it does not decode, is for another topic or author, is
// badly signed, or its author's chain does not certify the device.
ErrBadEnvelope = errors.New("kologossip: bad envelope")
)Types
type Author
type Author struct {
Person ed25519.PublicKey // must equal the message's person
Cert *koloid.DeviceCert // the device's certificate chain
Revocations []*koloid.Revocation // records that passed Revocation.Verify, kept from first sight, bounded by the application
}Author is what the application knows about a device: the person it expects and the device's chain, both required, and the revocations it accepts. An Author and its slices are read-only once handed out.
type AuthorStats
type AuthorStats struct {
Requests, Answered, Unsolicited, BadChains, Timeouts, Throttled uint64 // CERTWANT sent and the answers' fate
Served, CacheEvicted, NotHeld, Revoked uint64 // chains sent, dropped, answers without a chain, revoked or expired answers
CacheChains, CacheBytes, Waiting, Outstanding int
}AuthorStats are the counters and sizes of the author chain checks.
type Authors
type Authors interface {
Lookup(t Topic, person, device ed25519.PublicKey) (*Author, error)
}Authors is the application's roster. Lookup runs with the Gossip's lock held for every new message, so it answers from memory and must not call the Gossip; ErrUnknownAuthor or any error means the device is unknown.
type Config
type Config struct {
// Cert is the certificate chain of the device key passed to New; its person is the author of every message.
Cert *koloid.DeviceCert
// Swarm, if set, must run as the same device key; Join and Leave then also join and leave the swarm topic.
Swarm *koloswarm.Swarm
// Params are the overlay parameters of topics joined without their own; nil takes DefaultParams.
Params *Params
// Score nil takes DefaultScore.
Score *ScoreParams
// NoScore turns peer scoring off.
NoScore bool
// NoFloodPublish sends our own messages to the mesh (or to fanout peers) instead of every topic peer.
NoFloodPublish bool
// Now is the clock for signing, the time windows, chain checks and heartbeat times; nil is time.Now. The heartbeat
// timer still waits in real time, so a clock that runs faster is noticed at the next timer.
Now func() time.Time
// PeerExchange lists other topic peers in the PRUNE we send, so a pruned peer can dial them; off by default, as
// GossipSub v1.1 advises outside bootstrap nodes. Received peer exchange is dialed through Swarm either way,
// from peers scored at least Thresholds.AcceptPX.
PeerExchange bool
HeartbeatInterval time.Duration // default 1s
HeartbeatInitialDelay time.Duration // default 100ms
FanoutTTL time.Duration // default 1m
HistoryLength int // message cache windows kept, default 5
HistoryGossip int // newest windows announced in IHAVE, default 3
SeenTTL time.Duration // default 2m
MaxAge time.Duration // oldest accepted author time, default 1m; MaxAge + MaxSkew <= SeenTTL
MaxSkew time.Duration // newest accepted author time ahead of ours, default 1m
MaxSeen int // seen message ids, default 200,000
MaxCacheMessages int // cached messages per topic, default 8,333
MaxCacheBytes int // cached message bytes, all topics, default 32 MiB
GossipRetransmission int // IWANT answers per peer per message, default 3
PruneBackoff time.Duration // default 1m
UnsubscribeBackoff time.Duration // default 10s
GraftFloodThreshold time.Duration // default 10s
OpportunisticGraftTicks int // heartbeats between opportunistic grafts, default 60
OpportunisticGraftPeers int // default 2
MaxIHaveLength int // ids read per IHAVE and asked per peer per heartbeat, default 5000
MaxIHaveMessages int // IHAVE frames handled per peer per heartbeat, default 10
MaxIDontWantLength int // ids kept per IDONTWANT frame, default 10
MaxIDontWantMessages int // IDONTWANT frames handled per peer per heartbeat, default 1000
MaxIDontWantIDs int // IDONTWANT ids kept per peer, default 5000
IWantFollowupTime time.Duration // default 3s
IDontWantThreshold int // envelope bytes from which IDONTWANT is sent, default 1024
IDontWantTTL int // heartbeats an IDONTWANT id is kept, default 3
MaxMessageSize int // whole envelope, default 1 MiB
MaxControlSize int // control frame, default 512 KiB
MaxPeers int // peers served at once; default 0, no cap of its own (ServeConn's connections, which kolo-swarm bounds); a positive value is a cap (ErrLimit)
MaxTopics int // joined and fanout topics; default 0, no cap; a positive value is a cap (ErrLimit)
MaxPeerTopics int // topics one peer announces that we hold no state for, kept to join or publish to them later, default 1,024; past it they are not kept (Stats.Router.SubscriptionsDropped), never an error
MaxBackoff int // backoff entries per topic, default 1024
MaxRetained int // scores kept for disconnected peers, default 1024
MaxValidating int // messages waiting for a validator or a chain, or dropped while their validator runs, default max(1,040, 65 x MaxPeerValidating)
MaxValidatingBytes int // their bytes, default max(65 MiB, 65 x MaxPeerValidatingBytes)
MaxPeerValidating int // of those, from one peer, default 16; at most half of MaxValidating
MaxPeerValidatingBytes int // their bytes from one peer, default 1 MiB, at least MaxMessageSize; at most half of MaxValidatingBytes
MaxIgnoredIDs int // ids ignored for their content or author, kept so their copies cost nothing, default 8,333
IgnoredTTL time.Duration // how long such an id is kept, default 5s
RetryInterval time.Duration // how long a message the validator answered Retry waits for its next validation, unless Room.Revalidate comes first; default HeartbeatInterval
LockWork time.Duration // router lock time per second for all peers' frames, default 500ms: half shared by every peer, a quarter by mesh places, a quarter by the messages mesh peers delivered
ReaderWork time.Duration // reader time per second for all peers (hashing, signature checks, peer exchange dials), default 64 x PeerWork, about 7.06s, shared as LockWork
PeerWork time.Duration // most reader time per second one peer gets, default about 110ms
WorkBurst time.Duration // what a peer's work buckets hold: this long of their refill, default 2s
PrunePeers int // peer exchange records read from one PRUNE entry and listed in one we send, default 16
PeerQueue int // control frames queued for one peer, default 32
PeerQueueBytes int // bytes queued for one peer, default the largest of 1 MiB, MaxMessageSize, MaxControlSize
RoomQueue int // delivered messages waiting for Room.Next, default 32
FrameTimeout time.Duration // how long a frame or stream header under way may go without a byte, default 30s
ValidateTimeout time.Duration // how long a Validator may take, default and at most SeenTTL
PXPending int // peer exchange records waiting for a dial, default 128; more are dropped
PXDialers int // peer exchange dials at once through Swarm, default 8
PXTimeout time.Duration // how long one peer exchange dial may take, default 30s
CertCacheBytes int // verified author chains kept, from the roster and fetched, each; default 1 MiB
CertTimeout time.Duration // how long a CERTWANT may stay unanswered, default 3s
MaxCertWants int // CERTWANT requests outstanding per peer and entries answered per peer per heartbeat, default 10
MaxCertAnswers int // CERTWANT requests sent to one peer per heartbeat, default 5, at most half of MaxCertWants
MaxWaiting int // messages waiting for their author's chain, default MaxValidating
}Config configures a Gossip. Cert is required; every other zero field takes its default, and a negative or inconsistent value is ErrInvalidConfig. The defaults are in docs/limits.md with their sources.
type Conn
type Conn = koloswarm.ConnConn is a connection to one peer whose key the connection proved; a kolo-swarm Peer's Conn satisfies it.
type Gossip
type Gossip struct {
// contains filtered or unexported fields
}Gossip is one node's gossip under one device key: the rooms it joined and the peers it serves.
func New
func New(dev *koloid.Identity, cfg *Config) (*Gossip, error)New starts gossip as dev, the device key whose chain is cfg.Cert; with cfg.Swarm, dev is also its key.
func (Gossip) Allow
func (g *Gossip) Allow(key ed25519.PublicKey, _ netip.AddrPort) boolAllow reports whether key is at or above the graylist threshold; chain it into koloswarm.Config.Allow so the swarm refuses graylisted peers. It always allows when scoring is off.
func (Gossip) Close
func (g *Gossip) Close() errorClose stops every room and every ServeConn and waits for their goroutines. It leaves the swarm topics joined through Config.Swarm, which closes the connections that shared no other topic; its peers then close theirs.
func (Gossip) Join
func (g *Gossip) Join(ctx context.Context, t Topic, opts *TopicOptions) (*Room, error)Join subscribes to t. With Config.Swarm it then joins the swarm topic too, and a failure there leaves t.
func (Gossip) Publish
func (g *Gossip) Publish(ctx context.Context, t Topic, body []byte) (*Message, error)Publish signs body as a message of this device in topic t, joined or not, and sends it as GossipSub does: flooded or through the mesh or fanout peers. It returns the message as signed, its Raw included, with a nil From. Next never returns our own messages; the guide has the details.
func (Gossip) Score
func (g *Gossip) Score(key ed25519.PublicKey) float64Score returns a peer's current score, kept for ScoreParams.RetainScore after it disconnects; 0 when scoring is off.
func (Gossip) ServeConn
func (g *Gossip) ServeConn(ctx context.Context, conn Conn, outbound bool) errorServeConn runs gossip with the peer of conn, which must be its only AcceptUniStream caller, until ctx ends, the connection or the peer's gossip ends or a newer ServeConn for the key replaces it (nil), the Gossip closes (ErrClosed), a MaxPeers the application set is reached (ErrLimit; conn is closed), the peer is graylisted (ErrGraylisted; conn is closed) or breaks the protocol (ErrProtocol; conn is closed). outbound is koloswarm.Peer.Outbound; the guide has the details.
func (Gossip) Stats
func (g *Gossip) Stats() StatsStats returns the counters and current sizes.
type Message
type Message struct {
ID MessageID
Topic Topic
Person ed25519.PublicKey
Device ed25519.PublicKey
Seq uint64
Time time.Time // the author's clock, in milliseconds
Body []byte
Raw []byte // the signed envelope as the author sent it, which VerifyEnvelope checks
From ed25519.PublicKey // the neighbour that delivered it, not the author; nil for our own message
}Message is a message whose size, time window, author chain and signature the library checked.
func VerifyEnvelope
func VerifyEnvelope(t Topic, raw []byte, a *Author) (*Message, error)VerifyEnvelope checks raw, the Raw of a Message, against the author a: that it is an envelope of topic t by a's device for a's person, that the device signed it, and that a's certificate chain certifies the device at the envelope's own time with a's revocations. The caller judges that time. It returns the message with a nil From.
type MessageID
type MessageID [32]byteMessageID is a message id: SHA-256 over a domain label and the whole signed envelope.
type Open
type Open func(t Topic, person ed25519.PublicKey) (revocations []*koloid.Revocation, ok bool)Open accepts a person the roster does not know and returns the revocations accepted for it. It runs like Lookup.
type Params
type Params struct {
D, Dlo, Dhi, Dlazy, Dscore, Dout int
GossipFactor float64
// GossipPeers is the node's gossip budget, at least Dlazy: GossipPeers IHAVE of MaxIHaveLength ids a heartbeat,
// shared by every topic. A node that announces fewer ids gossips to more peers per topic, as the specification
// says. 0 takes the default, max(Dlazy, 43); in a Bootstrap Params that keeps no mesh it means no cap.
GossipPeers int
// Bootstrap allows D, Dlo, Dhi and Dout all zero: a node that keeps no mesh, as GossipSub v1.1 lets bootstrap
// nodes run. Without it they are refused, so a zero Params cannot turn the mesh off by mistake.
Bootstrap bool
}Params are the overlay parameters of a topic: the mesh degree D with its bounds Dlo and Dhi, the lazy degree for gossip, the peers kept by score when a mesh is pruned, the outbound quota and the gossip factor.
func DefaultParams
func DefaultParams() *ParamsDefaultParams returns the GossipSub specification's overlay values, except Dscore 6 and GossipFactor 0.75, which our simulator measured under Sybil floods.
type Room
type Room struct {
// contains filtered or unexported fields
}Room is a joined topic: publish to it and read what its members publish.
func (Room) Leave
func (rm *Room) Leave()Leave unsubscribes from the topic, prunes its mesh with the unsubscribe backoff and ends its validators' contexts without waiting for them; with Config.Swarm it also leaves the swarm topic.
func (Room) Next
func (rm *Room) Next(ctx context.Context) (*Message, error)Next returns the next message delivered in the room, ErrNotJoined after Leave or ErrClosed after Close.
func (Room) Publish
func (rm *Room) Publish(ctx context.Context, body []byte) (*Message, error)Publish signs body as the next message of this device in the room and sends it, as Gossip.Publish does.
func (Room) RefreshPeers
func (rm *Room) RefreshPeers()RefreshPeers asks TopicOptions.AllowPeer about every connected peer again, for example after a removal: a peer it refuses now is told that we left the topic and leaves its mesh, and one it admits now is told that we joined it.
func (Room) Revalidate
func (rm *Room) Revalidate()Revalidate runs the validator again, now, on every message of the room it answered Retry for.
func (Room) Stats
func (rm *Room) Stats() RoomStatsStats returns the room's sizes and delivery counters.
func (Room) Topic
func (rm *Room) Topic() TopicTopic returns the room's topic.
type RoomStats
type RoomStats struct {
Peers, Mesh, Outbound, Fanout int // peers subscribed, in our mesh, outbound in it, fanout peers
Delivered, Dropped uint64 // messages queued for Next, and dropped because Next fell behind
}RoomStats are the current sizes of a room and what it delivered.
type RouterStats
type RouterStats struct {
MessagesReceived, MessagesSent, ControlSent uint64 // message frames received and sent, control frames sent
Published, Delivered, Duplicates uint64 // our own messages, messages accepted, copies of known ones
Rejected, Ignored, Throttled uint64 // validator verdicts; messages over a validation bound
NotJoined, TooLarge, Malformed uint64 // for a topic not joined; over its size; not decodable
SeenFull, OutOfWindow, SelfOrigin uint64 // seen cache full; author time outside the window; our own key
BadSignature, Graylisted, ProtocolErrors uint64 // bad device signature; frames of graylisted peers; broken rules
SendDropped, CacheEvicted uint64 // frames dropped by full peer queues; cached messages dropped early
IHaveSent, IHaveReceived uint64 // IHAVE lists sent, IHAVE frames received
IWantSent, IWantReceived uint64 // IWANT frames
IDontWantSent, IDontWantReceived uint64 // IDONTWANT frames
UnknownAuthor, Resolving, CertBroken uint64 // authors that did not check out, messages that waited for a chain, broken requests
CertWantSent, CertWantReceived uint64 // CERTWANT frames
CertSent, CertReceived uint64 // CERT answers sent, CERT frames received
SignatureChecks, IgnoredCopies, Waits uint64 // checks run; copies of ignored ids; times a peer had to wait for its buckets
EdgeOfWindow, PXAccepted uint64 // accepted messages not forwarded because they leave the window; peer exchange records passed to the dialers
SubscriptionsDropped uint64 // subscriptions to topics we hold no state for, past MaxPeerTopics
Retried uint64 // validator answers of Retry
Peers, Topics, Seen, CacheMessages, CacheBytes, Validating, Retained int
}RouterStats are the router's counters and current sizes.
type ScoreParams
type ScoreParams struct {
Thresholds Thresholds
TopicScoreCap float64 // cap of the summed topic scores; 0: no cap
// AppScore is the application's view of a peer (P5); nil, a panic or a value that is not finite scores 0. It
// runs with the Gossip's lock held, so it must not call the Gossip.
AppScore func(key ed25519.PublicKey) float64
AppWeight float64
IPColocationWeight float64 // P6, <= 0
IPColocationThreshold int // peers on one IPv4 address before P6 applies
BehaviourPenaltyWeight float64 // P7, <= 0
BehaviourPenaltyThreshold float64
BehaviourPenaltyDecay float64
DecayInterval time.Duration
DecayToZero float64
RetainScore time.Duration // how long a disconnected peer's score is kept, unchanged; must be positive
}ScoreParams are the score parameters that apply to every peer: thresholds, the application score (P5), IP colocation (P6), the behaviour penalty (P7), decay and retention.
func DefaultScore
func DefaultScore() *ScoreParamsDefaultScore returns the score parameters our simulator found; set AppScore on the copy to use P5.
type Stats
type Stats struct {
Router RouterStats
Authors AuthorStats
ProtocolClosed uint64 // connections ServeConn closed because the peer broke the protocol
Waited uint64 // times a peer's reader waited for its work buckets to refill
StuckValidators int // validators still running past ValidateTimeout or their cancel, in the rooms joined now
PXDials uint64 // peer exchange records dialed through the swarm
PXConnected uint64 // of those, dials the swarm admitted
PXDropped uint64 // records dropped because PXPending records waited already
}Stats counts what the Gossip did and holds its current sizes.
type Thresholds
type Thresholds struct {
Gossip float64 // below: no IHAVE or IWANT to or from the peer; must be < 0
Publish float64 // below: our own messages are not flooded to the peer; must be <= Gossip
Graylist float64 // below: every frame is dropped, ServeConn ends and Allow refuses; must be < Publish
OpportunisticGraft float64 // a mesh median below it grafts better peers; must be >= 0
AcceptPX float64 // at or above: the peer exchange of the peer's PRUNE is dialed; 0 dials none; must be >= 0
}Thresholds are the GossipSub v1.1 score thresholds; a peer below one loses what it gates.
type Topic
type Topic = koloswarm.TopicTopic is a 32-byte topic id chosen by the application, the same type as a kolo-swarm topic.
type TopicOptions
type TopicOptions struct {
// Authors is the roster: closed mode, only the devices it knows are verified.
Authors Authors
// Open, if set, also accepts devices the roster does not know: their chain is fetched from the forwarding peer.
Open Open
// Validate decides what the library leaves to the application; nil accepts every message whose author checks.
Validate Validator
// Params nil takes Config.Params.
Params *Params
// Score nil takes DefaultTopicScore when scoring is on.
Score *TopicScoreParams
// NoScore leaves the topic unscored: its invalid messages then cost a peer nothing.
NoScore bool
// MaxMessageSize is the largest envelope of this topic, at most Config.MaxMessageSize; zero takes that.
MaxMessageSize int
// Seq numbers our messages; nil counts up from the Unix nanosecond time of Join. It may be called concurrently.
Seq func() uint64
// Swarm is how Join joins the swarm topic when Config.Swarm is set; nil announces and looks up.
Swarm *koloswarm.JoinOptions
// AllowPeer admits the peers of this topic; nil admits every peer. A peer it refuses is never told that we joined
// the topic, is never grafted into its mesh, gets no gossip or message of it, and its frames about it are
// ignored without penalty. It is asked once when a peer connects, once at Join and again on RefreshPeers; like
// Authors.Lookup it runs with the Gossip's lock held, answers from memory and must not call the Gossip. A panic
// refuses the peer. Config's swarm Allow stays node-wide.
AllowPeer func(peer ed25519.PublicKey) bool
}TopicOptions configure a joined topic. Authors, Open or both are required.
type TopicScoreParams
type TopicScoreParams struct {
TopicWeight float64
TimeInMeshWeight float64
TimeInMeshQuantum time.Duration
TimeInMeshCap float64
FirstMessageDeliveriesWeight float64
FirstMessageDeliveriesDecay float64
FirstMessageDeliveriesCap float64
MeshMessageDeliveriesWeight float64
MeshMessageDeliveriesDecay float64
MeshMessageDeliveriesCap float64
MeshMessageDeliveriesThreshold float64
MeshMessageDeliveriesWindow time.Duration
MeshMessageDeliveriesActivation time.Duration
MeshFailurePenaltyWeight float64
MeshFailurePenaltyDecay float64
InvalidMessageDeliveriesWeight float64
InvalidMessageDeliveriesDecay float64
}TopicScoreParams are the score parameters of one topic: time in mesh (P1), first deliveries (P2), mesh delivery rate and failures (P3, P3b) and invalid messages (P4).
func DefaultTopicScore
func DefaultTopicScore() *TopicScoreParamsDefaultTopicScore returns the topic score parameters our simulator found; P3 and P3b are off.
type Validator
type Validator func(ctx context.Context, m *Message) VerdictValidator decides membership, bans, roles, rate and content. It runs on its own goroutine; its context ends after ValidateTimeout, on Leave and on Close. One that returns after its timeout counts as Ignore, and its message keeps its places until then; a panic or an unknown verdict is Ignore too. A message answered Retry keeps its place in MaxValidating and in its sender's MaxPeerValidating share, and is dropped as an Ignore at SeenTTL.
type Verdict
type Verdict intVerdict is a validator's answer.
const (
Accept Verdict = iota + 1 // deliver and forward
Reject // invalid: the sender and every peer that sent a copy lose score
Ignore // drop without penalty
Retry // keep the message and validate it again on Room.Revalidate or after RetryInterval, until SeenTTL
)The verdicts of GossipSub v1.1 extended validators; the zero Verdict is not one, and counts as Ignore.
Good to know
Keys and connections
A node gossips as one kolo-id device key, the same key its kolo-swarm runs as, because peers know it by the key of its connection: they skip the author by that key when they forward, and a node takes a copy of a message under its own key as its own. Config.Cert is that device's certificate chain; its person is the author of every message the node publishes.
g, err := kologossip.New(device, &kologossip.Config{Cert: cert, Swarm: sw})New checks that the chain is for this device and verifies it now. With Config.Swarm it also checks that the swarm runs as the same key. Without Config.Swarm the library cannot see the key of its own connections, so the application must use the same key; a second instance of a key, or a restart, only makes the node ignore copies of its own messages.
The library never opens a connection itself: the application gives it connections (peer exchange, below, asks the swarm to dial). With kolo-swarm, serve every peer the swarm connects:
for {
ev, err := sw.Next(ctx)
if err != nil {
return
}
if ev.Kind == koloswarm.Connected {
go func(p *koloswarm.Peer) {
if err := g.ServeConn(ctx, p.Conn(), p.Outbound()); errors.Is(err, kologossip.ErrInvalidArgument) {
p.Conn().CloseWithError(0, "") // a connection gossip cannot serve: an IPv6 address or our own key
}
}(ev.Peer)
}
}ServeConn opens a control and a message stream to the peer and reads the peer's two, so it must be the only caller of the connection's AcceptUniStream; an application that runs other stream libraries on the same connection gives gossip its own part of a stream multiplexer, whose CloseWithError closes only that part. How it ends:
- It returns nil when a newer
ServeConnfor the same key replaces it,ctx.Err()whenctxends andErrClosedwhen the Gossip closes. In those cases the connection stays open. - It closes the connection when the
MaxPeersyou set is reached (ErrLimit; by default there is no cap), when the peer stalls forFrameTimeout(partway through a frame or a stream header, or before opening a stream; it returns nil), falls below the graylist threshold (ErrGraylisted) or breaks the protocol (ErrProtocol). kolo-swarm then reports it lost and may connect again after its backoff, whichAllowdecides, and the loop above serves the new connection. - When the peer ends its own streams, it returns nil and leaves the connection, which may carry other protocols, to the application.
- It returns
ErrInvalidArgumentat once, and leaves the connection open, for an IPv6 address or our own key; the loop above closes such a connection, which gossip cannot serve. Peers that connect and leave are never refused: only aMaxPeersyou set refuses a peer.
The outbound flag feeds the outbound mesh quota (Dout), and it is a condition for offering the peer in peer exchange (see below); with kolo-swarm it is Peer.Outbound. Chain Allow into the swarm so that it refuses the keys gossip graylisted. The swarm asks before the Gossip exists, so keep the Gossip in an atomic pointer:
var gp atomic.Pointer[kologossip.Gossip]
cfg := &koloswarm.Config{Allow: func(k ed25519.PublicKey, a netip.AddrPort) bool {
g := gp.Load()
return g == nil || g.Allow(k, a)
}}Rooms
room, err := g.Join(ctx, topic, &kologossip.TopicOptions{Authors: roster, Validate: validate})Join subscribes to the topic, tells every served peer and grafts a mesh. With Config.Swarm set it also joins the swarm topic (TopicOptions.Swarm, default announce and look up), and Room.Leave leaves it, which closes the connections that shared no other topic. Leave Config.Swarm nil when the application joins the swarm topic itself, for example because a kolo-braid on the same topic uses it.
A room needs Authors, Open or both:
- Closed mode,
Authors: the roster.Lookup(topic, person, device)returns theAuthor(the person it expects and the device's chain, both required, and the revocations it accepts) orErrUnknownAuthor. A device the roster does not know, and anAuthorwithout the person or the chain, are ignored without penalty and the chain is never taken from the network. A revoked or expired device is ignored without penalty too: revocations reach nodes at the application's pace, so a node that already knows one must not punish the peers that do not and forward the device's messages. The cost is that a revoked device's messages reach the nodes that do not know yet, and the others drop them: the first copy costs a signature check within the sender's budget, later copies nothing forIgnoredTTL. - Open mode,
Open: called for a person the roster does not know; it returns whether to accept the person and the revocations it holds for them. The device's chain is then fetched with one CERTWANT from the peer that forwarded the message (it waits up toCertTimeout, 3 s), checked with those revocations, and cached. A device's first message therefore pays one round trip. A peer that answers with a chain the revocations void ends only its own request; a peer that no longer holds the chain says so and is not penalised.
Revocations come only from the application. Keep every verified revocation from the time you first see it.
Lookup and Open run with the Gossip's lock held, once per new message, and ScoreParams.AppScore once per peer per heartbeat: answer from memory and never call the Gossip from them. Return the same Author objects for a device and never change them: the chain check is then found by those objects (about 60 ns), while new objects cost their encoding hash (about 20 us with 100 revocations). Either way a result is kept until the chain's earliest expiry, so a chain is verified once, not at every message. Their time is measured and charged to the peer that sent the message, at least a flat cost per call, so a slow roster slows the peers that make us call it. A panic in them ignores the message (or scores 0). Publish also checks the node's own chain with the revocations its room's roster or open mode holds for it, and refuses to sign once the chain expired or was revoked (ErrOwnChain).
Validators
TopicOptions.Validate decides what the library leaves to the application: membership of the person, bans, roles, rate and content. Before it runs, a message has passed its size, time window (MaxAge and MaxSkew), signature and author checks, cheapest first; nothing a peer can make without an author's key reaches it. It runs on its own goroutine, at most MaxValidating at once (MaxPeerValidating messages and MaxPeerValidatingBytes from one peer, and no more than the global bound divided by the senders holding messages; senders outside the topic's mesh that we did not ask hold at most half of the global bounds together; a peer over its share has only its copy dropped, so the next peer's copy is taken). Its context ends after ValidateTimeout (default and at most SeenTTL), on Leave, on Close, and when the router drops the message: when its sender left and the one departed share for all senders that left is full (the newly departed messages are dropped, the older ones keep their places). A dropped message that was waiting for its author's chain leaves the author check at once too, so keys that come and go cannot keep it full for new authors. A validator must honour its context.
| Verdict | Effect |
|---|---|
Accept | delivered to Room.Next and forwarded |
Reject | dropped; the sender and every peer that sent a copy lose score (P4); three invalid messages bring a peer to the graylist threshold and a fourth below it |
Ignore | dropped without penalty; also the result of a panic, of an unknown verdict (the zero Verdict included) or of a validator that returns after its timeout |
Retry | kept, not delivered and not forwarded, and validated again on Room.Revalidate or after RetryInterval; dropped at SeenTTL |
A nil validator accepts every message whose author checks out. A message becomes seen only when the validator accepts or rejects it. After an Ignore the message is validated again as the copy of a peer that sent it meanwhile, at most twice, since the validator sees the forwarder: a content-based Ignore costs up to three validations, each in its own sender's share. A message held for Retry counts in MaxValidating, MaxValidatingBytes and its sender's share, its copies from other peers are duplicates and are not validated, and its id is not seen.
A dropped validation stays counted in MaxValidating and MaxValidatingBytes until its validator returns, so a validator that ignores its context holds a global place until then, and the global bounds cap the validators that run, stuck or not; past them new messages are throttled. A validator that runs past its timeout keeps its message charged to the share of the peer that sent it until it returns, however long that takes; it then counts as Ignore (a verdict after SeenTTL too) and meanwhile as stuck in Stats.StuckValidators, as does a dropped one that runs on in a room still joined. Each validation has its own number, and a verdict applies only to the validation it answers. The validator's time is not charged to the sender: its CPU is the application's, outside the work budgets, and a sender can make it run only as fast as its reader bucket pays for new messages (at least a signature check each) and its share holds them. Close cancels every validator and never waits for one that ignores its context.
On Accept the message is cached, delivered to Room.Next and forwarded to the mesh except the sender, the author and the peers that sent IDONTWANT for it. An accepted message whose author time is within one heartbeat of either edge of the time window is delivered but not forwarded, so the next hop never refuses it for its time.
Publishing and reading
id, err := room.Publish(ctx, body)
m, err := room.Next(ctx)Publish signs the body with the next sequence number of this device in the room (TopicOptions.Seq supplies your own counter; Gossip.Publish on a joined topic uses the room's) and sends it: with flood publishing (the default, Config.NoFloodPublish turns it off) to every peer that announced the topic and scores at least the publish threshold, else to the mesh. A body over the topic's MaxMessageSize is ErrTooLarge, checked before signing; a message with the same bytes as one already sent (a Seq that repeats within one millisecond) is ErrDuplicate. On any error the returned id is zero. Publish never blocks on the network: a peer whose queue is full misses the copy, and the mesh repairs it with IHAVE and IWANT. Our own messages are not returned by Next.
Next returns the messages in the order they pass validation, each with its author (Person, Device, Seq, Time) and From, the neighbour that delivered it. No order is guaranteed: an application shows messages by author time with the message id as tie breaker, and uses the per-device sequence number to see gaps. A reader that falls more than RoomQueue messages behind loses messages for its room only (RoomStats.Dropped); the node still forwards them.
Gossip.Publish(ctx, topic, body) publishes to a topic the node did not join, as the specification's fanout does, through up to D fanout peers (kept for FanoutTTL after the last publish) or by flooding. The node needs connections to the topic's members, for example a swarm join with Lookup only, and the members' roster must accept its device.
A message received by a peer just before it grafted a new mesh link is not pushed over that link; the new mesh peer gets the next heartbeat's IHAVE of the ids of the last HistoryGossip heartbeats instead and asks for what it lacks. Older messages do not reach a node that connects later: applications that need every message use pins for history.
Close stops every room and every ServeConn and waits for their goroutines. It leaves the swarm topics joined through Config.Swarm, which closes the connections that shared no other topic; it closes no other connection and not the swarm, which belong to the application. Its peers see our streams end and close their side of each connection.
Scoring and statistics
Scoring is on with DefaultScore and DefaultTopicScore, values the library's simulator measured; Config.Score and TopicOptions.Score set others, and nil always means the default. Set ScoreParams.AppScore to add the application's view of a peer (P5), such as a positive score for roster members. Config.NoScore turns scoring off; TopicOptions.NoScore leaves one topic unscored, and then its invalid messages cost nothing. Gossip.Score returns a peer's score, kept unchanged for ScoreParams.RetainScore (10 minutes) after it disconnects, so reconnecting does not clear a penalty.
A peer that falls below the graylist threshold has every frame dropped, its ServeConn ends with ErrGraylisted, its connection is closed, and Allow refuses its key until its score recovers or its retained score expires.
Gossip.Stats returns the router's counters (messages, duplicates, rejects and ignores by reason, drops, IHAVE, IWANT, IDONTWANT and CERTWANT traffic) and sizes, the author chain counters and ProtocolClosed, the connections closed for protocol violations; StuckValidators, the validators still running past their timeout or their cancel; PXDials, PXConnected and PXDropped for peer exchange records, and RouterStats.PXAccepted, those passed to the dialers. Room.Stats returns the room's peers, mesh, outbound mesh peers and fanout, and its delivered and dropped counts.
Peer exchange
A PRUNE may list other peers of its topic, so the pruned peer can find new links. With Config.Swarm set, the Gossip dials the records of a PRUNE it receives when the topic is joined, scoring is on and the sender's score is at least ScoreParams.Thresholds.AcceptPX (12 by default, one above TopicScoreCap, so only a peer the application vouches for through AppScore qualifies; 0 dials no peer exchange at all, as a hand-built Thresholds has). It reads at most PrunePeers (16) records of one PRUNE entry, chosen at random, and leaves out our own key, connected keys and repeats. Each record is dialed with Swarm.Connect(ctx, topic, key, addr, from), from being the PRUNE sender's IPv4 address (zero when it is relayed), for at most Config.PXTimeout (30 s), by Config.PXDialers (8) dialers, with at most Config.PXPending (128) records waiting (Stats.PXDropped counts the rest); an error skips the record, without a retry. Each record the dialers take costs the PRUNE's sender a dial's work on its reader bucket; a record dropped because PXPending records wait already, or because there is no Config.Swarm, costs nothing. A connection the swarm admits reaches the application as a Connected event, like any other. Records are unsigned; the dial is authenticated by kolo-secure, so a wrong address costs one failed dial. Without Config.Swarm nothing is dialed, and with Config.NoScore nothing either, since nothing vouches for the sender.
Config.PeerExchange (off by default, as GossipSub v1.1 advises outside bootstrap nodes) makes the PRUNE we send list up to PrunePeers random peers of the topic with a score of at least 0, never the pruned peer: when the heartbeat prunes an oversubscribed mesh, on Leave, and when it refuses a GRAFT because the mesh is full. A peer pruned for its negative score, a GRAFT in backoff and a frame that also grafts a topic we are not in get none. Only peers whose listening port is known are listed: those that hold an outbound place (the outbound argument of ServeConn) and whose connection we opened from a socket other than our swarm's, so we dialed that address.
Defaults
A zero Config field takes its default, and a negative or inconsistent value is ErrInvalidConfig. The library caps nothing the application should decide: not the size of a topic, the number of authors, the message rate or the retention of history. Every bound below only stops a hostile or broken peer from making memory, CPU or bandwidth grow without limit, and every length is checked against its limit before anything is allocated for it. Each default has a written source: the GossipSub specification, the value GossipSub implementations ship, a value derived from those or from another Kolo library's limit, or a measurement with the library's simulator.
Overlay and gossip:
| Field | Default | Why |
|---|---|---|
Params.D, Dlo, Dhi | 6, 4, 12 | GossipSub v1.0 parameter table: bandwidth, Sybil nodes |
Params.Dlazy | 6 | GossipSub v1.0, equal to D |
Params.Dout | 2 | GossipSub v1.1 ("2 for a D of 6"): eclipse by inbound peers |
Params.Dscore | 6 | Measured: the only value that delivered every message under Sybil floods of up to 20 attacker connections per honest one at 1,000 and 10,000 nodes in one topic with 64 places, and again in 50 topics with 256 places. A review run with the gossip budget rule delivered the 20-to-1 flood at Dscore 4 to 8 too (not rerun on this code), so the earlier misses came from the gossip cap, not from Dscore, and the default stays 6 |
Params.GossipFactor | 0.75 | Measured, inside the specification's range 0 to 1: repair under Sybil floods |
Params.GossipPeers | 43 | The node's gossip budget: GossipPeers IHAVE of MaxIHaveLength ids a heartbeat, shared by every topic's gossip windows. 43 is the most gossip targets a topic had at 64 places (0.75 of the 58 peers outside a mesh of 6); a node below the budget gossips as the specification says, and the targets a heartbeat leaves out go first in the next one. A value under Dlazy is ErrInvalidConfig |
HeartbeatInterval, HeartbeatInitialDelay | 1 s, 100 ms | GossipSub v1.0; the delay is the implementations' value |
FanoutTTL | 1 min | GossipSub v1.0: memory |
HistoryLength, HistoryGossip | 5, 3 windows | GossipSub v1.0: memory |
PruneBackoff, UnsubscribeBackoff | 1 min, 10 s | GossipSub v1.1: churn abuse |
PrunePeers | 16 records | Dials steered by a PRUNE, PRUNE size; the implementations' value (GossipSub v1.1 asks for more than Dhi, 12): the records read from one PRUNE entry and listed in one PRUNE we send |
GraftFloodThreshold | 10 s | GRAFT floods; the implementations' value |
OpportunisticGraftTicks, OpportunisticGraftPeers | 60, 2 | GossipSub v1.1: captured meshes |
GossipRetransmission | 3 | IWANT floods; the implementations' value |
IWantFollowupTime | 3 s | IHAVE spam; the implementations' value |
MaxIHaveLength, MaxIHaveMessages | 5,000 ids, 10 frames per peer per heartbeat | Work for hostile input; the implementations' values |
MaxIDontWantLength, MaxIDontWantMessages | 10 ids, 1,000 frames per peer per heartbeat | Work for hostile input; the implementations' values |
MaxIDontWantIDs | 5,000 ids per peer | Memory: the ids a peer may announce or ask per heartbeat (MaxIHaveLength), also 1,666 messages per second for the 3-heartbeat TTL; past it further IDONTWANT ids are not kept, which only costs extra copies |
IDontWantThreshold, IDontWantTTL | 1,024 bytes, 3 heartbeats | Amplification, memory; the implementations' values, and the threshold must exceed Dhi times the 32-byte id |
Messages, memory and peers:
| Field | Default | Why |
|---|---|---|
SeenTTL | 2 min | GossipSub v1.0: memory, replay |
MaxAge, MaxSkew | 1 min, 1 min | SeenTTL split in two halves; their sum may not exceed SeenTTL, so a message old enough to be forgotten is always refused |
MaxSeen | 200,000 ids | 1,666 messages per second (the IHAVE design rate) for SeenTTL |
MaxCacheMessages | 8,333 per topic | 5,000 ids per 3 gossip windows, times 5 windows |
MaxCacheBytes | 32 MiB | The design rate's history: 8,333 messages of 1 KiB with their 180-byte envelope are 9.6 MiB, and 32 MiB is 3.3 times that. Node-wide, independent of the number of peers and topics |
MaxMessageSize | 1 MiB per envelope | The pubsub specification ("say to 1 MiB"); TopicOptions.MaxMessageSize may lower it per topic, and every member of a topic must use the same value |
MaxControlSize | 512 KiB per control frame | Memory, hostile input; the implementations' value, at least 524 bytes so frame splitting always makes progress, and with PeerExchange at least one PRUNE entry with PrunePeers records of the longest port (666 bytes at 16), so every PRUNE we send fits a frame |
MaxPeers | 0, no cap | Nothing of its own: gossip serves the connections ServeConn is given, which kolo-swarm bounds by its place budget. A positive value is an application cap: a peer over it is refused with ErrLimit and its connection closed |
MaxTopics | 0, no cap | Nothing of its own: joined and fanout topics are made only by the local application (Join, Publish), never by a peer. A positive value is an application cap (ErrLimit). A topic costs the router 11,234 bytes per node at 64 places and 29,247 at 256 places (simulator, 1,000 nodes, 50 topics) |
MaxPeerTopics | 1,024 other topics per peer | Memory from peers' subscriptions: a peer's subscriptions to topics we hold state for (joined, or fanout) are always kept, and those to other topics are kept so a later Join or Publish finds the peers, up to 1,024 per peer (32 KiB of topic ids). Past it a subscription is not kept and is counted in RouterStats.SubscriptionsDropped, never an error |
MaxBackoff, MaxRetained | 1,024 | kolo-swarm's MaxCandidates: a retained peer is a would-be candidate. MaxRetained bounds the retained scores (past it, the one with the highest score at its disconnect is dropped, ties by the earlier expiry, then the lower key) and, apart, the keys kept with a debt after they left (a key that leaves in debt or with messages waiting pushes out the oldest departure when that many are kept; work charged to a departed key that has nothing kept creates an entry only while there is room, and goes unpaid otherwise) |
MaxValidating, MaxValidatingBytes | max(1,040, 65 x MaxPeerValidating) messages, max(65 MiB, 65 x MaxPeerValidatingBytes) | Node budgets of 65 shares of MaxPeerValidating and MaxPeerValidatingBytes: 65 is a chosen budget, not a peer count, room for 64 senders' full shares at once and the departed share (an inconsistent configuration is ErrInvalidConfig; unset, they grow with MaxMessageSize and MaxPeerValidating). A sender holding messages gets at most the global bound divided by the senders holding any, and a message from a sender outside the topic's mesh that we did not ask with IWANT counts in an open tier that holds at most half of each global bound, so no group of peers can fill the bounds for the others. Messages waiting for a validator or for their author's chain both count, and so do validations the router dropped while their validator still runs (canceled, counted until the validator returns; RouterStats.Validating includes them). A new message past a bound is throttled: only that copy is dropped |
MaxPeerValidating, MaxPeerValidatingBytes | 16 messages, 1 MiB | One peer filling the validation bounds; the implementations' validation concurrency; a share holds one largest message and is at most half of its global bound. A message stays charged to its sender's share until its validator answers. When the sender leaves, its waiting messages move to one departed share held for all senders that left; past that share the newly departed messages are dropped (their validators canceled) and the older ones keep their places |
MaxIgnoredIDs, IgnoredTTL | 8,333 ids, 5 s | Copies of an ignored message cost nothing: ids of messages ignored for what holds for every copy (a bad signature, our own key, an unknown, revoked or expired author) are kept, 36 bytes each; the size is MaxCacheMessages's, and the lifetime is HistoryLength heartbeats, after which no peer announces the id |
Connections and rooms:
| Field | Default | Why |
|---|---|---|
PeerQueue | 32 control frames per peer | Memory, slow peers; the per-peer outbound queue of GossipSub implementations |
PeerQueueBytes | the largest of 1 MiB, MaxMessageSize and MaxControlSize | Memory, slow peers: 1 MiB per peer, raised to hold one largest frame |
RoomQueue | 32 messages | Memory, slow readers; the subscription buffer of GossipSub implementations |
FrameTimeout | 30 s without a byte | Memory held by a stalled frame or stream header; kolo-transport's IdleTimeout: a peer silent that long is gone. A frame that keeps arriving is read whole, and waiting between frames has no limit |
RetryInterval | HeartbeatInterval (1 s) | CPU of validators asked to run again: a message the validator answered Retry is validated again at the first heartbeat at least RetryInterval after its last Retry, or at once on Room.Revalidate. A held message counts in MaxValidating, MaxValidatingBytes and its sender's share until it is decided or reaches SeenTTL |
ValidateTimeout | SeenTTL (2 min), at most SeenTTL | A slow validator; the longest a message is kept in the seen window. When the router drops a message whose validator runs, it cancels the validator's context and keeps the validation in the global bounds until the validator returns |
ScoreParams.RetainScore | 10 minutes, must be positive | The score of a disconnected peer is kept so reconnecting does not clear a penalty |
A full peer queue drops the frame (counted in RouterStats.SendDropped); GRAFT, PRUNE and subscriptions are kept and sent with the next control frame, and the other peers are not affected. A full room queue drops the message for that room only. A peer may open one control and one message stream.
Work budgets, which bound the CPU a peer can force, are charged in units of 10 ns where the work happens. A bucket that is empty stops the peer's streams from being read, so flow control slows that peer alone and its score does not change:
| Field | Default | Why |
|---|---|---|
| Design rate | 1,666 messages a second | The rate MaxSeen is sized for (200,000 per SeenTTL); the budgets are sized from it |
LockWork | 500 ms of the router lock per second, at least 64 units | Half of one core for all peers' frames, split three ways into each peer's lock bucket: half equally among the peers connected now, a quarter by mesh places and a quarter by the valid messages the peer delivered. A hostile peer outside the mesh gets at most LockWork / 2P (P the peers connected) and all of them together at most half, whatever their number. A key starts with what the newcomer pool gives, at most one second of the pool's share, LockWork / 64 (7.8 ms); the work of connecting and of leaving is charged to the key itself |
PeerWork | about 110 ms a second per peer | CPU on the peer's reader (hashing ids, decoding, signature checks, the peer exchange dials of its PRUNE): twice what a peer that brings every message of the design rate first causes. The application validator's time is not charged |
ReaderWork | 64 x PeerWork, about 7.06 s of reader time per second, at least 64 units and PeerWork | CPU on the readers of all peers: 64 is a chosen budget, not a peer count, so it does not grow with the number of peers; split like LockWork, each peer's share capped at PeerWork |
WorkBurst | 2 s | Each bucket holds 2 s of its refill, so a burst at twice the rate for 2 s never waits |
A key that connects for the first time starts with only what a node-wide newcomer pool gives (at most one second of a full node's share). Peers that connect and leave are never refused: only a MaxPeers you set refuses a peer (ErrLimit). The work of connecting is charged to the new peer and the work of leaving to the leaving peer, and depends only on its own state; a key that leaves in debt or with messages waiting keeps its debt for RetainScore (WorkBurst with scoring off), at most MaxRetained keys, and gets back only that debt plus the pool's grant when it returns. kolo-swarm bounds reconnects in its own right. At 64 peers and the design rate of 1-KiB messages, an honest mesh peer uses 238,016 of 4,557,291 lock units a second (19.1 times headroom) and 995,435 of 11,032,276 reader units a second (11.1 times headroom). The tests TestHonestHeadroom, TestHonestCatchUp and TestNewPeerCatchUp check that no honest mesh peer waits and that every message is delivered. One attacking connection outside the mesh takes at most about 8.8 ms of the router lock a second at 64 peers, and 1/20 of that at 1,258 peers. The application validator's CPU is outside these budgets: its time is charged to no one, and validators are bounded by the shares, the departed share, the global bounds and ValidateTimeout.
Author chains:
| Field | Default | Why |
|---|---|---|
CertCacheBytes | 1 MiB for chains the roster gave, and 1 MiB for chains fetched | Memory: one largest message each, about 1,800 chains of the largest size; fetched chains never push out the roster's |
CertTimeout | 3 s | Waiting messages; the value of IWantFollowupTime |
MaxCertWants | 10 | Request floods; the value of MaxIHaveMessages: requests outstanding to one peer, CERTWANT entries one peer gets answered per heartbeat, and certificates in one control frame (more break the protocol). The CERT frames we send carry at most as many, further answers going in the next frame |
MaxCertAnswers | 5 requests per peer per heartbeat | Half of MaxCertWants, so two of our heartbeats within one of the peer's never ask more than it answers |
MaxWaiting | MaxValidating | Every waiting message is held within the validation bounds, and a message the router drops (past the departed share, on Leave, at expiry) leaves the author check at once, so keys that rotate cannot keep it full and refuse new open-mode authors |
Chain results kept (not a Config field) | 4,096 | Memory: twice the chains of largest size the two caches hold; past twice that, 8,192, the results are dropped and checked again, and the work is charged |
Peer exchange:
| Field | Default | Why |
|---|---|---|
Config.PeerExchange | off | Our peers' addresses and the dials we make others run: the implementations' default, and GossipSub v1.1 advises it for bootstrap nodes |
Thresholds.AcceptPX | 12 | Dials steered by hostile peers: one above TopicScoreCap (11); received records are dialed only for a joined topic, only with scoring on and only with AcceptPX above 0 |
PrunePeers | 16 records | Dials per PRUNE entry (see the overlay table); records for our own key, connected keys and repeats are left out |
| Work charged per dial | 162,000 units (1.62 ms) per record queued for a dial | CPU of the handshakes a PRUNE makes us run: the slowest of three runs of one authenticated kolo-secure dial on loopback, both sides of the handshake. Charged to the PRUNE sender's reader bucket; a record dropped because PXPending records wait already, or because there is no Config.Swarm, costs nothing. One peer pays for at most about 68 records a second beyond what its 2 s burst holds |
PXPending | 128 records waiting | Memory: the implementations' value; past it a record is dropped (Stats.PXDropped) |
PXDialers | 8 | Dials at once: the implementations' value |
PXTimeout | 30 s | A dial that hangs: the implementations' value |
Any error skips the record, without a retry, and the swarm's own limits for Connect apply.
Scoring (see Scoring and statistics):
| Parameter | Default | Why |
|---|---|---|
| Thresholds | Gossip -10, Publish -20, Graylist -80, OpportunisticGraft 3 | Measured with the simulator |
| Invalid messages | three bring a peer to the graylist threshold, a fourth below it | Measured |
| Behaviour offences | ten are free | Measured |
| Decay | the penalties of a connected peer decay to nothing in 10 minutes | Measured |
| P3 and P3b | off | Measured |
The specification publishes no score values, so these come from the simulator.
Security
- Every message is signed by the author's device key under its own context,
kolo-gossip/message/v0, and verified before it is forwarded, so a signature made for another protocol or message type is never accepted. The message id covers the whole envelope, so a forged copy never takes a real message's id. - Closed rooms take the author's chain from the roster and never from the network. Open rooms fetch it from the forwarding peer and check it with the revocations the application holds. Revocations come only from the application.
- A revoked or expired device is ignored without penalty to the forwarder, which may not know the revocation yet. Its messages can reach nodes that do not know it yet, and the others drop them.
- A bad signature costs the sender P4. A message out of the time window, for a topic not joined, of an unknown, revoked or expired author, or over the validation bounds is ignored without any score change. A message enters the seen cache only once its validator accepts or rejects it, so nothing a peer can make without an author's key, and nothing a validator ignores, stays in it.
Publishrefuses to sign once the node's own chain has expired or its room's roster holds a revocation of it (ErrOwnChain).- A peer that breaks the protocol has its connection closed with code
0x6b67. A peer below the graylist threshold has its frames dropped and its key refused byAllow. - Every frame's work is charged to its peer, and application code under the lock (roster, open mode, application score) is charged by its measured time, so a slow callback slows the peers that make the library call it. The validator's time is not charged: its CPU is the application's, and validators are bounded by the shares of their senders, the departed share, the global bounds and
ValidateTimeout.LookupandOpenrun with the Gossip's lock held: answer from memory and never call the Gossip from them. - Peer exchange records are unsigned hints. Received ones are dialed only from a peer whose score is at least
Thresholds.AcceptPX(12 by default, so only a peer the application vouches for qualifies), within the bounds of Peer exchange, and each record queued for a dial costs the PRUNE's sender one dial's work. The dial is authenticated by kolo-secure, so a wrong address costs one failed dial. - Listing our peers is off by default (
Config.PeerExchange). When on, a PRUNE lists up toPrunePeersrandom peers of the topic with a score of at least 0 and a known listening port, never the pruned peer, so those peers' addresses reach the pruned peer; a peer pruned for its negative score, or in backoff, gets none. ServeConntrusts the key of the connection it is given: pass only authenticated connections, such as kolo-swarm's.- Scoring off (
Config.NoScoreorTopicOptions.NoScore) means invalid messages cost nothing.
Known limits
- No history. A node that was offline does not get from gossip the messages it missed. kolo-pin peers keep ciphertext for members who were offline: archiver devices write the signed messages unchanged to a room history log, and a returning member fetches it and checks each author's signature, so an archiver is trusted for completeness, never for authorship.
- No order. There is no total order for gossip messages. Agreed state, such as membership and bans, goes through kolo-braid.
- No relay. If a deployment needs always-on servers, they are ordinary members.
- No promise that a message is delivered to a member who is offline or on a link that is down.
- Peer exchange is narrow by design: a node lists its peers only with
Config.PeerExchangeon and, by default, dials the records it receives only from a peer the application vouches for through its application score (P5). Without that, a pruned peer finds other links through the swarm. - Nothing about scale is promised beyond what was measured. The library's simulator (seed 1, with a cost model for signature and chain checks) delivered every message of every scenario, from Sybil floods and eclipse attempts to churn and partitions, at 100, 1,000 and 10,000 nodes in one topic with 64 connection places. Larger topics, real networks and other seeds are not measured. Phones sleep and change networks, so they cannot stay mesh members for long; an application that needs a backbone runs always-on members as ordinary peers, which the application score can favour.
- Metadata is not hidden (see Security).
Status
Experimental. The API may change before v1.0.0. Version 0.1.0 is tagged.
- Done: signed messages with closed and open rooms, validators, the mesh with graft and prune, IHAVE, IWANT and IDONTWANT, flood publishing and fanout, peer scoring on by default, work budgets and bounds on every cache, queue and per-peer counter, joining the swarm topic through
Config.Swarm, peer exchange (dialing the records of a received PRUNE and, withConfig.PeerExchangeon, listing our peers in the PRUNE we send), and the formats above. - Tested: unit, fuzz and loopback integration tests with kolo-swarm, and a discrete-event simulator at 100, 1,000 and 10,000 nodes that chose the score parameters and two overlay values (
Params.DscoreandParams.GossipFactor). - Not verified: any real network beyond loopback, and topics larger than the sizes the simulator ran.
Errors
| Error | Message |
|---|---|
ErrBadEnvelope | kologossip: bad envelope |
ErrClosed | kologossip: closed |
ErrDuplicate | kologossip: duplicate message |
ErrGraylisted | kologossip: peer graylisted |
ErrInvalidArgument | kologossip: invalid argument |
ErrInvalidConfig | kologossip: invalid config |
ErrLimit | kologossip: limit reached |
ErrNotJoined | kologossip: topic not joined |
ErrOwnChain | kologossip: own certificate chain not valid |
ErrProtocol | kologossip: protocol violation |
ErrTooLarge | kologossip: message too large |
ErrUnknownAuthor | kologossip: unknown author |
Test errors with errors.Is. ErrUnknownAuthor is what a roster's Lookup returns for a device it does not know. The library's own error messages start with kologossip:.
References
- gossipsub v1.0: An extensible baseline pubsub protocol (Recommendation, revision r2, 2020-03-12).
- Takes: the mesh with its graft and prune rules, the heartbeat, the fanout, and gossip emission with the message cache.
- gossipsub v1.1: Security extensions to improve on attack resilience and bootstrapping (Candidate Recommendation, revision r8, 2021-12-14).
- Takes: peer scoring with its thresholds, flood publishing, prune backoff with peer exchange, the outbound mesh quota, opportunistic grafting and the spam measures.
- gossipsub v1.2 (Working Draft, revision r2, 2026-08-30; the file's own title is still "TODO").
- Takes: the IDONTWANT control message.
- Vyzovitis, Napora, McCormick, Dias and Psaras, GossipSub: Attack-Resilient Message Propagation in the Filecoin and ETH2.0 Networks, arXiv:2007.02754, 2020.
- Takes: the attack scenarios and metrics of the simulator, and the shape of the overlay parameter set.
- The paper gives no peer-score values, so the score defaults are measured with the simulator.
Not implemented: explicit peering agreements, floodsub peers, episub, the v1.3 extensions and partial messages, the unsigned and lax signature policies (every message is signed), the topic descriptor authentication and encryption options, and the peer gater of other implementations.