DEV Community

Cover image for From Piscine Go to a Bitcoin node in Kisumu: what eight months of building taught me
Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on

From Piscine Go to a Bitcoin node in Kisumu: what eight months of building taught me

The short version, for everyone: In March I was doing beginner Go exercises at Zone01 Kisumu. By November I was writing Go that signs and encrypts alarms for activists and a wallet that pays Kisumu shops in M-Pesa. This post is the path between those two points, and then the part I wish someone had shown me in week one: five "pointless" beginner exercises, each traced to the real production code it turned into.

In March I was writing IsNegative and PrintNbr in the Zone01 Kisumu Piscine. This month I'm writing Go that seals an activist's alarm into 228 encrypted bytes, and running a Lightning node behind a wallet in Kisumu. This post is the path between those two points, written down so I can see it clearly, and so anyone starting out can see that the small exercises lead somewhere specific.

Contents

  1. March to April: the boring part that mattered most
  2. April to August: building things nobody asked for
  3. September to November: one domain
  4. Lesson 1: slices share memory
  5. Lesson 2: bytes are not characters
  6. Lesson 3: a number is just bytes in an order
  7. Lesson 4: recursion over a structure
  8. Lesson 5: pointers, and who owns the state
  9. The habit that ties it together: tests first
  10. Run the demo yourself
  11. What I would tell someone in their first Piscine week

March to April: the boring part that mattered most

The Piscine was 21 days of small Go exercises: runes, slices, pointers, linked lists, binary trees. Hundreds of commits, most of them tiny. I did not see the point of BTreeDeleteNode at the time.

Then came the group projects: go-reloaded, ascii-art, push-swap, groupie-tracker, lem-in, forum. They taught the things a tutorial skips: how to split work across a team, how to review a pull request without breaking someone else's branch, how to write the test before arguing about the code.

April to August: building things nobody asked for

In parallel I kept starting small products of my own:

  • A coding platform where a learner writes Go on one side and reads the instructions on the other.
  • BursaryHub, a full-stack bursary application.
  • YeboBank, a savings and chama product for Kenyan groups.
  • Convert, my first attempt at a Bitcoin to M-Pesa screen.

Most of them were not finished. All of them taught me something I used later: Docker, PostgreSQL, Next.js, payment APIs, and above all that a product is the part the user touches, not the code I am proud of.

September to November: one domain

By September the problem was clear. In Kisumu many small shop owners have M-Pesa, and Bitcoin payments are cheap and fast, but only if the merchant can receive them in the money they already use.

So I built Ye₿ente, a Lightning wallet with M-Pesa integration, on a Lightning node I run myself, and started studying Bitcoin Core properly: PSBTs, HTLCs, mempool policy, reading real pull requests. Then kTown, a QR that lets any shop take bitcoin and receive shillings. A correction to the first version of this post: kTown payments don't run through my node; the customer's sats go straight to a payout partner that pays the shop's M-Pesa, and kTown never holds the money. The wallet is what runs on my node.

And in November, Kengele, an open-source alarm for activists, written in Go.

GitHub logo altradits / kengele

An alarm for when an activist goes missing. No servers, works through shutdowns. Swahili first.

Kengele

When an activist goes silent, the right people know within minutes, and nobody can switch the alarm off.

Ukinyamaza, kengele inalia. ("If you go quiet, the bell rings.")

Warning

Status: design stage. Not for real use. There is no working app yet. Do not rely on Kengele to protect anyone until an independent security review is complete and published here. People's lives may depend on this tool, so we will not cut corners to ship it sooner.

Why

When an activist disappears, how fast the public finds out often decides how quickly they are freed.

That last one is where the Piscine came back to me, line by line. Here are five exercises I thought were pointless, and the real code each one became.

Lesson 1: slices share memory

The Piscine version. Exercises like AppendRange, MakeRange and slice manipulation, where you learn that a slice is a pointer, a length and a capacity over an array.

What I didn't understand then: when a function returns a slice, the caller and the function now share the same array. If the caller writes to it, they change your data.

Where it came back. Kengele's deadline engine keeps the list of activists a guardian watches. Other code needs that list (to know which keys to try when decrypting a message). The engine hands out a copy:

// Senders returns the keys of every watched activist, for message.Open.
func (e *Engine) Senders() [][32]byte {
    out := make([][32]byte, len(e.order))
    copy(out, e.order)
    return out
}
Enter fullscreen mode Exit fullscreen mode

Returning e.order directly would compile, pass most tests, and let any caller silently rewrite which activists the engine watches. In a tool where a missed alarm can cost a life, "the caller probably won't modify it" is not good enough. Here is the difference, runnable:

type engine struct{ order [][32]byte }

func (e *engine) leaky() [][32]byte { return e.order }   // shares the array

func (e *engine) senders() [][32]byte {                     // copies, like Kengele
    out := make([][32]byte, len(e.order))
    copy(out, e.order)
    return out
}

e := &engine{order: [][32]byte{{1}, {2}}}
l := e.leaky()
l[0] = [32]byte{9}
fmt.Println("after editing leaky():  engine's first key starts with", e.order[0][0])
e.order[0] = [32]byte{1}
s := e.senders()
s[0] = [32]byte{9}
fmt.Println("after editing senders(): engine's first key starts with", e.order[0][0])
Enter fullscreen mode Exit fullscreen mode
after editing leaky():  engine's first key starts with 9
after editing senders(): engine's first key starts with 1
Enter fullscreen mode Exit fullscreen mode

Note the element type: [32]byte, an array, not a slice. Arrays are values in Go, so copying the outer slice copies every key too. If the keys were []byte, copy would copy only the slice headers and the bytes underneath would still be shared. That distinction is exactly the one the Piscine's array-versus-slice exercises were drilling.

Lesson 2: bytes are not characters

The Piscine version. StrLen, StrRev, Capitalize, and the moment you discover that len("é") is 2 and you have to range over runes.

Where it came back. Kengele is Swahili-first, and people type place names, names and messages in whatever script and emoji they like. Two different limits apply, and mixing them up is a bug:

  • The wire format counts bytes. A message body is at most 86 bytes, because the whole message must fit in two SMS. That limit is about storage.
  • The alert text counts characters. A human writes "at most 280 characters", so the alert checker counts runes and validates the encoding:
for _, f := range []string{a.Name, a.Photo, a.Lawyer, a.Text} {
    if !utf8.ValidString(f) || utf8.RuneCountInString(f) > maxField {
        return fmt.Errorf("%w: fields must be valid text of at most %d characters", ErrAlert, maxField)
    }
    ...
}
Enter fullscreen mode Exit fullscreen mode

The danger is cutting a string by bytes. A place like "Kisumu, Ziwa Victoria 🌊" is 23 characters but 26 bytes, and the wave emoji alone is 4 bytes. Cut it at byte 24 and you have produced invalid UTF-8:

place := "Kisumu, Ziwa Victoria 🌊"
fmt.Println("len (bytes):", len(place), " runes:", utf8.RuneCountInString(place))
fmt.Println("first 24 bytes valid UTF-8?", utf8.ValidString(place[:24]))
Enter fullscreen mode Exit fullscreen mode
len (bytes): 26  runes: 23
first 24 bytes valid UTF-8? false
Enter fullscreen mode Exit fullscreen mode

So the rule in the code is: refuse what doesn't fit, never truncate silently. Half an emoji in a public alert about a missing person is not a cosmetic bug.

Lesson 3: a number is just bytes in an order

The Piscine version. PrintNbr, Atoi, ItoA, PrintNbrBase: turning an integer into digits by hand, base by base, sign and all. It feels like busywork when strconv exists.

Where it came back. Every Kengele message carries the sender's time and a sequence number as raw bytes inside the signed part, at fixed offsets, so the Go watcher and the Kotlin Android app agree byte for byte:

inner[0] = byte(e.Kind)
binary.BigEndian.PutUint32(inner[1:5], uint32(ts))   // created at, Unix seconds
binary.BigEndian.PutUint32(inner[5:9], e.Seq)        // sequence number
inner[9] = byte(len(e.Body))
Enter fullscreen mode Exit fullscreen mode
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, 1768486020) // 2026-01-15T14:07:00Z
fmt.Printf("created_at on the wire: % x\n", b)
Enter fullscreen mode Exit fullscreen mode
created_at on the wire: 69 68 f4 84
Enter fullscreen mode Exit fullscreen mode

PrintNbrBase taught the idea that a number is a sequence of digits in a base, most significant first. Big-endian is the same idea in base 256. And the 2038 question that a uint32 timestamp raises is the same overflow thinking as handling -2147483648 in PrintNbr: the code checks the range before converting (if ts <= 0 || ts > int64(^uint32(0)) { return nil, ErrTime }).

Bitcoin itself is full of this: little-endian fields in transactions, variable-length integers in scripts, bech32 turning 8-bit bytes into 5-bit words. Kengele's LNURL and BOLT11 code does exactly that regrouping, and it reads like a base-conversion exercise because it is one.

Lesson 4: recursion over a structure

The Piscine version. BTreeInsertData, BTreeApplyInorder, BTreeDeleteNode: recursive functions over a tree, where the hard part is keeping the structure valid after you change it.

Where it came back. Kengele's 2-of-3 guardian rule rebuilds a secret key from any 2 of the guardians' shares. If one guardian sends a bad share, the code must try every possible group of 2 until one works, so a single bad actor can't block the release. That is a recursive walk over all k-sized subsets:

// combinations calls f with every k-sized subset of 0..n-1 until f returns
// false. n is at most MaxGuardians, so this is small.
func combinations(n, k int, f func([]int) bool) {
    idx := make([]int, k)
    var rec func(start, depth int) bool
    rec = func(start, depth int) bool {
        if depth == k {
            return f(idx)
        }
        for i := start; i <= n-(k-depth); i++ {
            idx[depth] = i
            if !rec(i+1, depth+1) {
                return false
            }
        }
        return true
    }
    rec(0, 0)
}
Enter fullscreen mode Exit fullscreen mode

Everything from the tree exercises is in there: a base case (depth == k), a recursive step, pruning (i <= n-(k-depth) stops branches that can't complete), and early exit (return false up the stack the moment a group works). And the "keep the structure valid" lesson from BTreeDeleteNode shows up in reverse: f receives idx, which the recursion keeps mutating, so f must use it immediately and never keep a reference. (Lesson 1 again.)

Lesson 5: pointers, and who owns the state

The Piscine version. PointOne, Swap, UltimatePointOne, linked lists with *NodeL. You learn that a function given a pointer can change the caller's value, and given a copy, can't.

Where it came back. The deadline engine keeps one tracker per activist, in a map of pointers:

type Engine struct {
    cfg   Config
    acts  map[[32]byte]*tracker
    order [][32]byte
    ...
}
Enter fullscreen mode Exit fullscreen mode

*tracker, not tracker. Every method does t := e.acts[k] and then changes t.state, t.missAt and so on. With a map of values, t would be a copy, every change would be lost, and the tests would show deadlines that never move. That's the Swap exercise, at the scale of a real system.

The engine also makes an ownership decision the linked-list exercises hinted at: it owns all of its state and has no goroutines. Nothing changes a tracker except the engine's own methods, called by one caller, one at a time. That rule is enforced by a test:

func TestNoGoroutines(t *testing.T) {
    before := runtime.NumGoroutine()
    e := New(Config{}, t0)
    ...
    if after := runtime.NumGoroutine(); after > before {
        t.Errorf("goroutines: %d before, %d after", before, after)
    }
}
Enter fullscreen mode Exit fullscreen mode

Where state is shared across goroutines (the confirmation tally can receive messages concurrently), it sits behind one sync.Mutex, and the tests run under the race detector.

The habit that ties it together: tests first

The Piscine graded everything with automated tests. You pushed, a machine said yes or no, and arguing with it was useless. The group projects added the other half: write the test before arguing about the code.

Kengele's deadline engine has 999 lines of code and 1,118 lines of tests. A typical case reads like a story about a real day:

{
    name: "flapping network cannot stretch one deadline again and again",
    steps: []step{
        tick(0), offline(60), online(120), // deadline +105 in outage -> +240, return window used
        offline(130), online(135),          // 5 min outage -> +245
        offline(200), online(260),          // +245 passed in outage, but window already used -> +305
        tick(304), tick(305),
    },
    want: []want{{0, StateMissed, 305}},
},
Enter fullscreen mode Exit fullscreen mode

That is exactly the Piscine loop: a precise expected output, a machine that checks it, and no way to talk your way past it.

Run the demo yourself

The three runnable snippets above (slice copying, runes, big-endian) are one small program. Save as main.go and run go run main.go:

main.go (click to expand)
package main

import (
    "encoding/binary"
    "fmt"
    "unicode/utf8"
)

type engine struct{ order [][32]byte }

// leaky returns the engine's own slice: callers can change the engine.
func (e *engine) leaky() [][32]byte { return e.order }

// senders copies, like Kengele's Engine.Senders.
func (e *engine) senders() [][32]byte {
    out := make([][32]byte, len(e.order))
    copy(out, e.order)
    return out
}

func main() {
    // 1. Slices share their backing array.
    e := &engine{order: [][32]byte{{1}, {2}}}
    l := e.leaky()
    l[0] = [32]byte{9}
    fmt.Println("after editing leaky():  engine's first key starts with", e.order[0][0])
    e.order[0] = [32]byte{1}
    s := e.senders()
    s[0] = [32]byte{9}
    fmt.Println("after editing senders(): engine's first key starts with", e.order[0][0])

    // 2. Bytes are not characters.
    place := "Kisumu, Ziwa Victoria 🌊"
    fmt.Println("len (bytes):", len(place), " runes:", utf8.RuneCountInString(place))
    fmt.Println("first 24 bytes valid UTF-8?", utf8.ValidString(place[:24]))

    // 3. A number on the wire: big-endian, fixed width.
    b := make([]byte, 4)
    binary.BigEndian.PutUint32(b, 1768486020) // 2026-01-15T14:07:00Z
    fmt.Printf("created_at on the wire: % x\n", b)
}
Enter fullscreen mode Exit fullscreen mode

after editing leaky():  engine's first key starts with 9
after editing senders(): engine's first key starts with 1
len (bytes): 26  runes: 23
first 24 bytes valid UTF-8? false
created_at on the wire: 69 68 f4 84
Enter fullscreen mode Exit fullscreen mode

And the real code those lessons became is all public: git clone https://github.com/altradits/kengele && go test -race ./....

What I would tell someone in their first Piscine week

  1. The small exercises are the foundation. Slices, runes, number bases, trees and pointers are not school topics. They are the five things I used most in my first serious Go project.
  2. Ship something a real person can touch, even if it is ugly. Feedback from one shop owner is worth more than a week of polish.
  3. Pick one hard domain and stay in it. For me that is Bitcoin. Going deep in one place made everything else easier to learn.
  4. Write the test first. The Piscine's grader is the best habit it teaches. Keep it when nobody is grading you.
  5. Write it down. Commits, logs, posts like this one. Your record of the work is how others, and you, can see the progress.

What is next

Next is Go without shortcuts: reading Bitcoin and Lightning code by hand, LND first, so that by 2027 I can contribute to Bitcoin open source full time, and help the BitDevs Kisumu students do the same. I also joined the work around BitDevs Kisumu with Btrust and signed the Education Network Charter with My First Bitcoin. And I submitted Altradits to the Meta Global AI Developer Hackathon on 4 November.

If you are building with Bitcoin in East Africa, reviewing Go, or you run a small shop in Kisumu and want to try kTown, find me at altradits.com or github.com/altradits.

Not sponsored.

Top comments (0)