Understanding Bitcoin HASH160
GOLANG + BITCOIN SCRIPT — Stage 001, Lesson 09 of 12.
Concept
HASH160 is RIPEMD160(SHA256(data)), producing 20 bytes. P2PKH commits to a public key hash and P2SH commits to a redeem script hash. Native P2WPKH also uses a 20-byte public key hash. P2WSH uses SHA-256 instead; Taproot uses a different construction.
Engineering practice
The example uses crypto/sha256 and golang.org/x/crypto/ripemd160. It hashes the raw digest bytes and checks the empty-input vector. This isolated module requires a dependency download. Run go mod tidy and go test in 05-hash160; dependency resolution and Go execution were not verified in the offline preparation environment.
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://pkg.go.dev/golang.org/x/crypto/ripemd160
Series navigation
https://thamer.org/learn/bitcoin-development-libraries-go
Previous lesson:
https://thamer.org/learn/bitcoin-double-sha256-go
Next lesson:
https://thamer.org/learn/bitcoin-chain-parameters-go
