kolo docsbeta

Step 1: Build a chat in your terminal

A step-by-step tutorial. Two peers on your computer find each other through a bootstrap node and chat directly, with no server in between.

On this page

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:

bash
brew install go

Check your Go version:

Terminal
go version

You should see 1.26 or newer, for example:

Text
go version go1.27.3 darwin/arm64

Now open three terminal windows and keep them side by side:

Open the Terminal app and press Cmd+N twice for two more windows.

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:

bash
mkdir kolo-chat && cd kolo-chat

Then create a Go module in it:

Terminal
go mod init example.com/kolo-chat

Go answers:

Text
go: creating new go.mod: module example.com/kolo-chat

3Get 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.

Terminal
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.0

Go downloads them with what they need and ends with these lines:

Text
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.0

4Write 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.

main.go
// 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 yet and is not sent.
  • It reads the bootstrap node's address from the -bootstrap flag, and 127.0.0.1:7447 is the default. -listen is the address it listens on: 127.0.0.1:0 by default, which keeps it on your computer; use :0 to reach other computers.
  • It looks the topic up again every 15 seconds (-lookup-every), so it finds peers that join later. -lookup-only looks up without announcing.
  • -relay and -relay-key name 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:

Terminal
go install github.com/ciranda-dev/kolo-node/cmd/kolo-node@v0.1.0

Go 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:

bash
export PATH="$PATH:$(go env GOPATH)/bin"

Start the node on your computer only, with its key in a new temporary folder:

bash
kolo-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:

Text
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=0

Leave Terminal 1 open.

6Start the first peer in Terminal 2

In Terminal 2, in the kolo-chat folder, run the chat:

Terminal
go run .

The first run compiles for a moment. Then the peer prints its name and waits:

Text
18:51:59 me 19353b70
18:51:59 joined "chat", type a line and press Enter

7Start 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:

Terminal
cd kolo-chat
Terminal
go run .

Within a few seconds the two peers find each other. Terminal 3 shows:

Text
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:

Text
18:52:07 peer ffdabb7a connected (direct)

8Type a line and see it arrive

In Terminal 2, type a line and press Enter:

Text
hello from terminal 2

It shows up in Terminal 3, next to the name of the peer that sent it:

Text
18:52:23 <19353b70> hello from terminal 2

Now answer from Terminal 3:

Text
hi, terminal 3 here

And Terminal 2 shows:

Text
18:52:31 <ffdabb7a> hi, terminal 3 here

9Stop everything

Press Ctrl-C in Terminal 3. That peer stops, and Terminal 2 notices:

Text
18:52:46 peer ffdabb7a lost: koloswarm: connection lost

Press Ctrl-C in Terminal 2. Then press Ctrl-C in Terminal 1; the node says goodbye with these lines and exits:

Text
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=stopped

Two 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:

Terminal
kolo-node run -listen :7447 -identity "$HOME/kolo-node/node.key" -first

From each computer, check that the port is open, then start the chat listening on every interface:

Terminal
kolo-node check 203.0.113.10:7447
Terminal
go run . -listen :0 -bootstrap 203.0.113.10:7447

What 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-only there: 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:

bash
mkdir kolo-relay-server && cd kolo-relay-server && go mod init kolo-relay-server
Terminal
go get github.com/ciranda-dev/kolo-id@v0.1.0 github.com/ciranda-dev/kolo-relay@v0.1.0

Save 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:

main.go
// 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:

Terminal
go run . -listen :7448

It 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:

Terminal
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:

Text
14:52:42 reserved on the relay
14:54:37 peer 8b4cc656 connected (through the relay)
14:54:50 <8b4cc656> hello

The relay is used only because you passed -relay; nothing falls back to it on its own.

What just happened

  • Each peer joined the topic chat through 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.