Bitcoin Development with Go Modules
GOLANG + BITCOIN SCRIPT — Stage 001, Lesson 03 of 12.
Concept
A go.mod file declares a module and dependency requirements. go.sum records checksums for downloaded module content; it is not a substitute for reviewing dependency code. Major versions from v2 generally require a matching import path suffix. Pin versions and commit go.mod and go.sum after resolving dependencies.
Engineering practice
Run go list -m all to inspect the resolved graph and go test ./... to compile and test packages. Use go mod tidy only after reviewing imports. This stage isolates HASH160 in a separate module because it needs x/crypto; the root module uses only the standard library. Go does not recursively test nested modules with ./..., so test that directory separately.
Source example
1package main
2
3import (
4 "crypto/sha256"
5 "fmt"
6 "golang.org/x/crypto/ripemd160"
7)
8
9func hash160(b []byte) []byte {
10 s := sha256.Sum256(b)
11 h := ripemd160.New()
12 h.Write(s[:])
13 return h.Sum(nil)
14}
15func main() { fmt.Printf("%x\n", hash160(nil)) }Run locally
From the 001-foundations directory:
cd 05-hash160
go mod tidy
go test ./...
go run .
Regression test
1package main
2
3import (
4 "fmt"
5 "testing"
6)
7
8func TestHash160(t *testing.T) {
9 if fmt.Sprintf("%x", hash160(nil)) != "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" {
10 t.Fatal("wrong HASH160")
11 }
12}Exercise
After resolving dependencies, compare the hash of empty bytes with a nonempty byte slice.
Reference
https://go.dev/ref/mod
Series navigation
https://thamer.org/learn/bitcoin-development-libraries-go
Previous lesson:
https://thamer.org/learn/understanding-btcsuite-ecosystem
Next lesson:
https://thamer.org/learn/migrating-btcsuite-v2-modules
