Blockchain foundations in Go · 5 MIN READ
Hash chains: every block commits to the exact bytes of the block before it
Link blocks with SHA-256 over a canonical byte encoding, verify the chain from genesis and report the first link that breaks.
A blockchain's first job is evidence, not consensus: if a past record changes, the change must show. Each block stores the hash of its predecessor, so editing one block breaks the link that points at it. That guarantee holds only when every party hashes the same bytes for the same block, and only when the newest hash is kept somewhere the editor cannot rewrite.
blockchain · A MAP OF THE IDEA
- Encode block canonically
- Hash with SHA-256
- Verify links from genesis
- Compare tip with anchor
Useful when
- Any edit to history changes the tip hash.
- Verification is linear and needs only the standard library.
Watch out
- Without a trusted tip, a rewritten chain verifies cleanly.
- Re-serializing JSON before hashing breaks honest data.
Implementation & operation cost: One hash per block to write and to verify, an encoding you can never change casually, and a separate place to keep the trusted tip.
Why a stored hash exposes an edit
A database row or a log line can be updated in place, and nothing about its neighbors changes. A hash pointer removes that silence. Block n stores H(block n-1), where H is SHA-256, a function for which no one knows how to find two different inputs with the same output. Change one byte of an old block and its hash changes, so the pointer stored in the next block no longer matches. This is tamper evidence, not tamper prevention: the bytes can still be edited, but a verifier notices. The rest of this unit adds the other pieces in order: Merkle trees commit to many transactions at once, signatures say who authorized them, proof of work makes extending the chain expensive, and fork choice decides which extension counts.
Build and verify a chain with crypto/sha256
The program defines a block as a height, the previous block's hash and a payload. encode turns a block into bytes with a fixed field order, big-endian fixed-width integers and a length prefix in front of the variable payload; hash is sha256.Sum256 over exactly those bytes. firstBrokenLink checks every block against its predecessor and returns the first height where either the height sequence or the hash pointer fails. The run records the tip, edits an old payload, and then plays an attacker who rewrites every later pointer.
package main
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
)
type Block struct {
Height uint64
Prev [32]byte
Data string
}
// encode is the canonical byte form: fixed-width fields first, then a
// length-prefixed payload, so two different blocks never share bytes.
func encode(b Block) []byte {
buf := binary.BigEndian.AppendUint64(nil, b.Height)
buf = append(buf, b.Prev[:]...)
buf = binary.BigEndian.AppendUint32(buf, uint32(len(b.Data)))
return append(buf, b.Data...)
}
func hash(b Block) [32]byte { return sha256.Sum256(encode(b)) }
func build(payloads ...string) []Block {
var chain []Block
var prev [32]byte // genesis points at the all-zero hash
for i, p := range payloads {
b := Block{Height: uint64(i), Prev: prev, Data: p}
chain = append(chain, b)
prev = hash(b)
}
return chain
}
// firstBrokenLink returns the height of the first block that does not commit
// to its predecessor, or -1 when every link holds.
func firstBrokenLink(chain []Block) int {
for i := 1; i < len(chain); i++ {
if chain[i].Height != chain[i-1].Height+1 || chain[i].Prev != hash(chain[i-1]) {
return i
}
}
return -1
}
func short(h [32]byte) string { return hex.EncodeToString(h[:4]) }
func main() {
chain := build("genesis", "alice->bob:5", "bob->carol:2", "carol->dave:1")
trustedTip := hash(chain[len(chain)-1])
fmt.Println("links ok:", firstBrokenLink(chain) == -1, "tip:", short(trustedTip))
chain[1].Data = "alice->bob:500"
fmt.Println("after edit, first broken link at height", firstBrokenLink(chain))
for i := 2; i < len(chain); i++ {
chain[i].Prev = hash(chain[i-1])
}
tip := hash(chain[len(chain)-1])
fmt.Println("relinked:", firstBrokenLink(chain) == -1, "tip:", short(tip))
fmt.Println("matches trusted tip:", tip == trustedTip)
}build starts from the all-zero hash for genesis and feeds each block's hash into the next block. After the payload at height 1 changes, height 2 is the first block whose Prev no longer equals hash(chain[1]), so the verifier reports 2 rather than a bare false. Rewriting Prev at heights 2 and 3 makes every link consistent again, so the chain on its own looks valid; only the comparison with the tip recorded before the edit exposes it. The printed values are the first four bytes of each 32-byte digest.
Pick one byte encoding and never let it drift
The hash covers bytes, not meaning. Two nodes that agree a block says alice pays bob 5 but serialize it differently compute different hashes and then disagree about the whole chain. encode avoids that by construction, and its length prefix also removes ambiguity at field boundaries: without it, a payload "ab" followed by a field "c" and a payload "a" followed by "bc" would hash identical bytes. Text formats are where this usually goes wrong. JSON objects are unordered, whitespace is insignificant, a number has several spellings (5, 5.0, 5e0), and Go's encoding/json adds its own choices: it sorts map keys, writes struct fields in declaration order and escapes <, > and & unless told otherwise.
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
)
func main() {
// One logical transfer, three byte strings a JSON parser treats as equal.
forms := []string{
`{"from":"alice","to":"bob","amount":5}`,
`{"amount":5,"from":"alice","to":"bob"}`,
`{"amount": 5, "from": "alice", "to": "bob"}`,
}
for _, f := range forms {
sum := sha256.Sum256([]byte(f))
fmt.Println(hex.EncodeToString(sum[:4]), f)
}
// encoding/json sorts map keys, but it also escapes HTML characters.
plain, _ := json.Marshal(map[string]any{"to": "bob", "memo": "a<b", "amount": 5})
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
_ = enc.Encode(map[string]any{"to": "bob", "memo": "a<b", "amount": 5})
fmt.Println(string(plain))
fmt.Println(string(bytes.TrimSpace(buf.Bytes())))
}The three literal strings decode to the same object yet print three different digests, 8cd4d93c, 560a0696 and 39350022, so a verifier that re-serializes before hashing accepts or rejects data depending on which form it happens to produce. json.Marshal sorts the map keys and writes the memo as a\u003cb; an Encoder with SetEscapeHTML(false) writes a<b and appends a newline, trimmed here. Both outputs are valid JSON, and neither is a hashing format unless one canonicalization scheme, such as RFC 8785, is applied everywhere.
Anchor the tip, or the chain proves nothing
The relinking step in the first program is the realistic attack. Whoever can rewrite one block can usually recompute every later hash in microseconds. What the chain buys you is that one 32-byte value, the tip hash, commits to the entire history, so protecting history reduces to protecting that value. Publish it, sign it, store it in a system with different administrators, or make producing a replacement expensive, which is what proof of work and proof of stake do later in this unit. Audit logs, release manifests and blockchains share this structure and differ in who is trusted to produce or hold the tip. When verification fails, report the first broken height and treat every later block as unverified until it is checked against a trusted tip again; an operator needs to know which record and which neighbor disagree.
Test the encoding like a consensus rule
Check in known-answer vectors: a fixed block and its expected digest, so a refactor that reorders fields or changes an integer width fails a test instead of silently forking your history. Mutate each field in turn and assert that the hash changes. Fuzz pairs of blocks with go test -fuzz and assert that different blocks never encode to the same bytes, which catches a missing length prefix. Keep a single encode function shared by writer and verifier; two implementations of one format is how nodes come to disagree. Test the verifier on an empty chain, a lone genesis block, a height gap and an edited genesis. SHA-256 appears here because it is in the standard library; Ethereum uses Keccak-256, a different function, as the signing-boundaries lesson explains.
TAKE THIS WITH YOU
Hash one canonical byte encoding of each block, verify every link from genesis, report the first break, and keep the trusted tip hash out of reach of anyone who can edit the data.
Check your understanding
An attacker edits an old block and recomputes every later hash so that all links verify again. What still exposes the edit?
Go to the source
Progress stays in this browser. No account needed.