THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

Understanding Satoshis and Bitcoin Amounts in Go

permalink THAMER
#bitcoin#bitcoin-development#bitcoin-script#golang

GOLANG + BITCOIN SCRIPT — Stage 001, Lesson 07 of 12.

Concept

One BTC equals 100,000,000 satoshis. Use int64 for monetary arithmetic rather than binary floating point. Bitcoin consensus bounds individual output values and total output value; a valid amount alone does not make a transaction valid.

Engineering practice

The example formats 123456789 satoshis as 1.23456789 BTC without floating point. It rejects negative values and values above 21 million BTC. In real transaction construction, also check aggregate sums before addition, input availability, fees and applicable dust policy. Dust is a relay policy concept, not a universal minimum consensus output value.

Source example

Go · 16 lines
1package main
2
3import (
4	"errors"
5	"fmt"
6)
7
8const maxMoney int64 = 21000000 * 100000000
9
10func amount(s int64) (string, error) {
11	if s < 0 || s > maxMoney {
12		return "", errors.New("amount out of range")
13	}
14	return fmt.Sprintf("%d.%08d", s/100000000, s%100000000), nil
15}
16func main() { v, e := amount(123456789); fmt.Println(v, e) }

Run locally

From the 001-foundations directory:

go test ./03-satoshis
go run ./03-satoshis

Regression test

Go · 15 lines
1package main
2
3import (
4	"testing"
5)
6
7func TestExample(t *testing.T) {
8	v, e := amount(123456789)
9	if e != nil || v != "1.23456789" {
10		t.Fatal(v, e)
11	}
12	if _, e = amount(-1); e == nil {
13		t.Fatal("negative accepted")
14	}
15}

Exercise

Test zero, one satoshi and the maximum permitted amount.

Reference

https://github.com/bitcoin/bitcoin

Series navigation

https://thamer.org/learn/bitcoin-development-libraries-go

Previous lesson:
https://thamer.org/learn/bitcoin-serialization-little-endian-go

Next lesson:
https://thamer.org/learn/bitcoin-double-sha256-go

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects