This is the first step: you build a chat that runs in your terminal.
In about ten minutes you will run three programs on your own computer: a bootstrap node, and two copies of a small chat. The two chats find each other, connect directly and send each other what you type.
Everything stays on your computer, on the address 127.0.0.1. Nothing
here needs an account or a server of ours. When it works, the last section
moves the same chat to two computers on different
networks.
1Check what you need
You need Go 1.26 or newer and three terminal windows. If Go is not installed yet, install it for your system:
Download the macOS installer (the .pkg file) from
go.dev/dl and run it. If you use Homebrew, this works
too:
brew install goDownload the Windows installer (the .msi file) from
go.dev/dl and run it. It adds Go to your PATH. Then
open PowerShell.
Use your distribution's golang package if it is version 1.26 or newer.
Otherwise download the .tar.gz file from go.dev/dl
and follow the Linux steps on go.dev/doc/install.
Check your Go version:
go versionYou should see 1.26 or newer, for example:
go version go1.27.3 darwin/arm64Now open three terminal windows and keep them side by side:
Open the Terminal app and press Cmd+N twice for two more windows.
Open PowerShell three times, or open Windows Terminal and press Ctrl+Shift+T twice for two more tabs.
Open your terminal app and press Ctrl+Shift+N twice for two more windows (Ctrl+Shift+T opens tabs instead in most terminals).
This tutorial calls them Terminal 1 (the bootstrap node), Terminal 2 and Terminal 3 (the two chat peers).
2Create a folder and a module
In Terminal 2, make a folder for the chat and go into it:
mkdir kolo-chat && cd kolo-chatmkdir kolo-chat; cd kolo-chatmkdir kolo-chat && cd kolo-chatThen create a Go module in it:
go mod init example.com/kolo-chatGo answers:
go: creating new go.mod: module example.com/kolo-chat3Get the libraries
Still in Terminal 2, add the three Kolo libraries the chat uses: kolo-swarm to find and connect to peers, kolo-id for each peer's key, and kolo-relay for the relay you can add later.
go get github.com/ciranda-dev/kolo-swarm@v0.1.0 github.com/ciranda-dev/kolo-id@v0.1.0 github.com/ciranda-dev/kolo-relay@v0.1.0Go downloads them with what they need and ends with these lines:
go: added github.com/ciranda-dev/kolo-codec v0.1.0
go: added github.com/ciranda-dev/kolo-dht v0.1.0
go: added github.com/ciranda-dev/kolo-id v0.1.0
go: added github.com/ciranda-dev/kolo-relay v0.1.0
go: added github.com/ciranda-dev/kolo-secure v0.1.0
go: added github.com/ciranda-dev/kolo-swarm v0.1.0
go: added github.com/ciranda-dev/kolo-transport v0.1.0
go: added golang.org/x/crypto v0.59.0
go: added golang.org/x/net v0.63.0
go: added golang.org/x/sys v0.50.0
go: added golang.org/x/time v0.16.04Write the program
Create a file named main.go in the kolo-chat folder and paste this
program into it. It joins a topic named chat, prints every line another
peer sends, and sends every line you type to every peer it is connected
to.
// Command chat joins a Kolo topic through a bootstrap node and sends each line typed to every connected peer.
package main
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"net/netip"
"os"
"os/signal"
"strings"
"sync"
"time"
"unicode"
koloid "github.com/ciranda-dev/kolo-id"
kolorelay "github.com/ciranda-dev/kolo-relay"
koloswarm "github.com/ciranda-dev/kolo-swarm"
)
const (
maxLine = 4096
sendTimeout = 10 * time.Second
codeTooLong = 1
)
func main() {
boot := flag.String("bootstrap", "127.0.0.1:7447", "IP:PORT of the bootstrap node")
topic := flag.String("topic", "chat", "topic name")
lookupOnly := flag.Bool("lookup-only", false, "only look up peers on the topic, do not announce (for a network where announcing fails)")
every := flag.Duration("lookup-every", 15*time.Second, "time between lookups of the topic (finds peers that join later)")
relayAddr := flag.String("relay", "", "IP:PORT of a kolo-relay to use when a direct connection fails")
relayKey := flag.String("relay-key", "", "public key of that relay, in hex")
listen := flag.String("listen", "127.0.0.1:0", "local IP:PORT to listen on; \":0\" listens on every interface")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
log.SetFlags(log.Ltime)
if err := run(ctx, *listen, *boot, *topic, *lookupOnly, *every, *relayAddr, *relayKey); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}
func run(ctx context.Context, listen, boot, name string, lookupOnly bool, every time.Duration, relayAddr, relayHex string) error {
var relayKey []byte
if relayAddr != "" {
k, err := hex.DecodeString(relayHex)
if err != nil || len(k) != 32 {
return fmt.Errorf("-relay-key must be 64 hex characters")
}
relayKey = k
}
server, err := netip.ParseAddrPort(boot)
if err != nil {
return err
}
id, err := koloid.Generate() // in memory only, a new identity each run
if err != nil {
return err
}
s, err := koloswarm.New(ctx, listen, id, &koloswarm.Config{LookupInterval: every})
if err != nil {
return err
}
defer s.Close()
log.Printf("me %x", id.PublicKey()[:4])
var opts *koloswarm.JoinOptions
if lookupOnly {
opts = &koloswarm.JoinOptions{Lookup: true}
}
if err := s.Bootstrap(ctx, []netip.AddrPort{server}); err != nil {
return fmt.Errorf("bootstrap: %w", err)
}
if err := s.Join(ctx, koloswarm.Topic(sha256.Sum256([]byte("kolo-chat-example/topic/v0"+name))), opts); err != nil {
return fmt.Errorf("join: %w", err)
}
log.Printf("joined %q, type a line and press Enter", name)
if relayKey != nil {
go reserve(ctx, s, relayAddr, relayKey, id)
}
dialing := map[string]bool{}
var mu sync.Mutex
peers := map[string]*koloswarm.Peer{}
go func() {
sc := bufio.NewScanner(os.Stdin)
sc.Buffer(make([]byte, maxLine), maxLine)
for sc.Scan() {
mu.Lock()
if len(peers) == 0 {
log.Print("no peer connected yet")
}
for _, p := range peers {
go send(ctx, p, sc.Bytes())
}
mu.Unlock()
}
}()
for {
ev, err := s.Next(ctx)
if err != nil {
return err
}
switch ev.Kind {
case koloswarm.Connected:
mu.Lock()
peers[string(ev.Peer.PublicKey())] = ev.Peer
mu.Unlock()
path := "direct"
if !ev.Peer.Direct() {
path = "through the relay"
}
log.Printf("peer %x connected (%s)", ev.Peer.PublicKey()[:4], path)
go receive(ctx, ev.Peer)
case koloswarm.Found:
log.Printf("found %x at %v, connecting", ev.PublicKey[:4], ev.Addr)
case koloswarm.Unreachable:
log.Printf("could not reach %x directly (%v)", ev.PublicKey[:4], ev.Err)
if relayKey != nil && !dialing[string(ev.PublicKey)] {
dialing[string(ev.PublicKey)] = true
go dialRelay(ctx, s, relayAddr, relayKey, id, ev.PublicKey)
}
case koloswarm.Lost:
mu.Lock()
delete(peers, string(ev.PublicKey))
mu.Unlock()
log.Printf("peer %x lost: %v", ev.PublicKey[:4], ev.Err)
}
}
}
// send writes line on a new unidirectional stream, one stream per line.
func send(ctx context.Context, p *koloswarm.Peer, line []byte) {
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
defer cancel()
st, err := p.Conn().OpenUniStream(ctx)
if err == nil {
st.SetWriteDeadline(time.Now().Add(sendTimeout))
if _, err = st.Write(line); err == nil {
err = st.Close()
}
}
if err != nil && ctx.Err() == nil {
log.Printf("send to %x failed: %v", p.PublicKey()[:4], err)
}
}
// receive prints each line p sends, one stream at a time, so a peer cannot make it read many at once.
func receive(ctx context.Context, p *koloswarm.Peer) {
for {
st, err := p.Conn().AcceptUniStream(ctx)
if err != nil {
return
}
st.SetReadDeadline(time.Now().Add(sendTimeout))
b, err := io.ReadAll(io.LimitReader(st, maxLine+1))
if err != nil || len(b) > maxLine {
st.CancelRead(codeTooLong)
continue
}
log.Printf("<%x> %s", p.PublicKey()[:4], printable(string(b)))
}
}
// printable drops control characters, so a peer cannot move the cursor or clear the terminal.
func printable(s string) string {
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) || r == unicode.ReplacementChar {
return -1
}
return r
}, strings.ToValidUTF8(s, ""))
}
// reserve keeps our key reserved on the relay and attaches every peer that reaches us through it.
func reserve(ctx context.Context, s *koloswarm.Swarm, addr string, key []byte, id *koloid.Identity) {
for ctx.Err() == nil {
res, err := kolorelay.Reserve(ctx, addr, key, id, nil)
if err != nil {
log.Printf("relay reservation failed: %v; retrying in 10s", err)
select {
case <-ctx.Done():
case <-time.After(10 * time.Second):
}
continue
}
log.Print("reserved on the relay")
for {
c, err := res.Accept(ctx)
if err != nil {
break
}
go func() {
if err := s.Attach(ctx, c, false); err != nil && ctx.Err() == nil {
log.Printf("relayed peer %x not attached: %v", c.RemotePublicKey()[:4], err)
}
}()
}
res.Close()
}
}
// dialRelay connects to peer through the relay and hands the connection to the swarm.
func dialRelay(ctx context.Context, s *koloswarm.Swarm, addr string, key []byte, id *koloid.Identity, peer []byte) {
log.Printf("trying %x through the relay", peer[:4])
c, err := kolorelay.Dial(ctx, addr, key, id, peer, nil)
if err != nil {
log.Printf("relay dial to %x failed: %v", peer[:4], err)
return
}
if err := s.Attach(ctx, c, true); err != nil && ctx.Err() == nil {
log.Printf("relayed peer %x not attached: %v", peer[:4], err)
}
}A few things worth knowing about it:
- Each run makes a new key in memory, so each peer gets a new name every time you start it. Its name is the first 4 bytes of its public key.
- A line you type before any peer is connected prints
no peer connected yetand is not sent. - It reads the bootstrap node's address from the
-bootstrapflag, and127.0.0.1:7447is the default.-listenis the address it listens on:127.0.0.1:0by default, which keeps it on your computer; use:0to reach other computers. - It looks the topic up again every 15 seconds (
-lookup-every), so it finds peers that join later.-lookup-onlylooks up without announcing. -relayand-relay-keyname a kolo-relay server to try when a direct connection fails. Without them, no relay is used.- What another peer sends is untrusted: the program reads at most 4,096 bytes per message and drops control characters before printing.
5Start a bootstrap node in Terminal 1
The bootstrap node is the first address peers ask. It helps them find each other, then steps aside: your messages never go through it.
In Terminal 1, install kolo-node:
go install github.com/ciranda-dev/kolo-node/cmd/kolo-node@v0.1.0Go may print a few go: downloading lines, then nothing. The program goes
into Go's bin folder. If your shell cannot find kolo-node in the next
step, add that folder to your PATH for this terminal:
export PATH="$PATH:$(go env GOPATH)/bin"$env:Path += ";$env:USERPROFILE\go\bin"export PATH="$PATH:$(go env GOPATH)/bin"Start the node on your computer only, with its key in a new temporary folder:
kolo-node run -listen 127.0.0.1:7447 -identity "$(mktemp -d)/node.key" -first$dir = New-Item -ItemType Directory -Path (Join-Path $env:TEMP "kolo-node-$(Get-Random)")
kolo-node run -listen 127.0.0.1:7447 -identity (Join-Path $dir.FullName "node.key") -firstkolo-node run -listen 127.0.0.1:7447 -identity "$(mktemp -d)/node.key" -first-first starts a new network: this node has no other entry nodes to join. It prints three lines and keeps running. Your times and key will differ:
time=2026-11-11T18:51:56.880+07:00 level=INFO msg=identity key=152978a8aa6e5a00500cdc20c26ec281ba9b3a5f1dd17fd617354488f40a3cda created=true
time=2026-11-11T18:51:56.880+07:00 level=INFO msg=started version=v0.1.0 addr=127.0.0.1:7447
time=2026-11-11T18:51:56.880+07:00 level=INFO msg=network mode=first entries=0Leave Terminal 1 open.
6Start the first peer in Terminal 2
In Terminal 2, in the kolo-chat folder, run the chat:
go run .The first run compiles for a moment. Then the peer prints its name and waits:
18:51:59 me 19353b70
18:51:59 joined "chat", type a line and press Enter7Start the second peer in Terminal 3
In Terminal 3, go to the same kolo-chat folder (use the path where
you created it) and run the chat again:
cd kolo-chatgo run .Within a few seconds the two peers find each other. Terminal 3 shows:
18:52:07 me ffdabb7a
18:52:07 joined "chat", type a line and press Enter
18:52:07 found 19353b70 at 127.0.0.1:52144, connecting
18:52:07 peer 19353b70 connected (direct)The port after 127.0.0.1 will differ. Terminal 2 adds a line with the new
peer's name, and may print a found line for it at its next lookup:
18:52:07 peer ffdabb7a connected (direct)8Type a line and see it arrive
In Terminal 2, type a line and press Enter:
hello from terminal 2It shows up in Terminal 3, next to the name of the peer that sent it:
18:52:23 <19353b70> hello from terminal 2Now answer from Terminal 3:
hi, terminal 3 hereAnd Terminal 2 shows:
18:52:31 <ffdabb7a> hi, terminal 3 here9Stop everything
Press Ctrl-C in Terminal 3. That peer stops, and Terminal 2 notices:
18:52:46 peer ffdabb7a lost: koloswarm: connection lostPress Ctrl-C in Terminal 2. Then press Ctrl-C in Terminal 1; the node says goodbye with these lines and exits:
time=2026-11-11T18:52:54.949+07:00 level=INFO msg=stopping cause="interrupt signal received"
time=2026-11-11T18:52:54.951+07:00 level=INFO msg=stats servers=0 records=2 requests=16 limited=0 closed=0 since=58s
time=2026-11-11T18:52:54.952+07:00 level=INFO msg=stoppedTwo computers on different networks
The same program works between two computers, for example one at home and
one at work. The finished Kolo examples, and any program that calls
Bootstrap(ctx, nil) with no list, use the public entry nodes that Ciranda
runs, so they need no setup. This chat takes its entry node from
-bootstrap, so here you run an entry node of your own: a third machine
that both computers can reach, a host with a public IPv4 address, such as a
small VPS. The steps below use 203.0.113.10 for its address; use yours.
On that host, install kolo-node as in step 5, open UDP port 7447 in its firewall (and in the provider's, if it has one), and start the node on all its addresses:
kolo-node run -listen :7447 -identity "$HOME/kolo-node/node.key" -firstFrom each computer, check that the port is open, then start the chat listening on every interface:
kolo-node check 203.0.113.10:7447go run . -listen :0 -bootstrap 203.0.113.10:7447What the lines mean:
found <peer> at <address>, connecting: the lookup returned the other peer, and the chat is opening a connection to it.peer <peer> connected (direct): the two computers talk directly; the host only helped them meet.could not reach <peer> directly (...): no direct path. Both sides sent packets to open one (hole punching), and the networks dropped them.join: ...at start: the chat could not announce or look up the topic. If announcing is what fails on that network, try-lookup-onlythere: that chat still finds the other one, but cannot be found, so start it second.
A corporate network or a VPN can block the announce and the hole punching, or both. Then you need a relay.
A relay for when no direct path exists
This part was tested between two computers over the internet, through a relay on a cloud host.
kolo-relay forwards encrypted packets between two peers that cannot reach each other. It cannot read them: the peers' own kolo-secure connection runs inside. On the same public host, make a second folder and module for the relay server:
mkdir kolo-relay-server && cd kolo-relay-server && go mod init kolo-relay-servergo get github.com/ciranda-dev/kolo-id@v0.1.0 github.com/ciranda-dev/kolo-relay@v0.1.0Save this as main.go. It keeps its key in relay.key (or the file you
pass with -identity), so the key stays the same across restarts:
// Command relay runs a kolo-relay server for the chat example.
package main
import (
"context"
"errors"
"flag"
"io/fs"
"log"
"os"
"os/signal"
koloid "github.com/ciranda-dev/kolo-id"
kolorelay "github.com/ciranda-dev/kolo-relay"
)
func main() {
listen := flag.String("listen", ":7448", "UDP IP:PORT to listen on")
keyFile := flag.String("identity", "relay.key", "identity file, created if missing")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
log.SetFlags(log.Ltime)
id, err := koloid.Load(*keyFile)
if errors.Is(err, fs.ErrNotExist) {
if id, err = koloid.Generate(); err == nil {
err = id.SaveNew(*keyFile)
}
}
if err != nil {
log.Fatal(err)
}
s, err := kolorelay.Listen(ctx, *listen, id, nil)
if err != nil {
log.Fatal(err)
}
defer s.Close()
log.Printf("relay on %v, key %x", s.Addr(), id.PublicKey())
<-ctx.Done()
}Open UDP port 7448 on the host, then start it:
go run . -listen :7448It prints one line, relay on <address>, key <key>, where the key is 64
hex characters. Start both chats with the relay's address and that full key:
go run . -listen :0 -bootstrap 203.0.113.10:7447 -relay 203.0.113.10:7448 -relay-key <relay key>Each chat prints reserved on the relay. When a direct connection fails,
the chat prints trying <peer> through the relay, and then the peer
connects through the relay and lines go both ways. From that test:
14:52:42 reserved on the relay
14:54:37 peer 8b4cc656 connected (through the relay)
14:54:50 <8b4cc656> helloThe relay is used only
because you passed -relay; nothing falls back to it on its own.
What just happened
- Each peer joined the topic
chatthrough the bootstrap node's DHT: it announced itself there and looked the topic up. That is how the second peer found the first. See Topics. - Once they found each other, the two peers connected directly. The bootstrap node only helped them meet; your messages never went through it.
- The connection is an encrypted channel tied to each peer's key, from kolo-secure. Each side knows the full key of the peer it talks to. See Peers.
- In the first steps everything ran on
127.0.0.1, so only programs on your computer could join. Between computers, your own bootstrap node runs on a host both can reach and each chat listens on:0; the kolo-node page explains running the node for real.
Next steps
- Read the kolo-swarm page: its API, its limits and what each event means.
- Read the Concepts: peers, topics, logs, replicas, deletion and the relay, one short page each.
- See what else you can build on kolo.ciranda.dev: Use cases.