chirp

package
v0.32.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package chirp is a codec for CHIRP (BRC-167) major version 1 and its chunking profile 1: the root and branch node encodings, the canonical construction of a closure from content, the verification of a closure fetched object by object, and the UHRP object identifier and CHIRP URL of a hash.

A CHIRP object is a byte string named by its SHA-256 hash: a blob of content, a branch node or the root node. The root commits to the content's length, its SHA-256 and its children; profile 1 cuts the content into blobs of exactly ChunkSize bytes (the last holds the rest) and groups their references 256 at a time until at most 256 remain.

The decoder refuses everything BRC-167 says a consumer must reject, and the encoder refuses to write what the decoder would refuse, so a node this package writes is one it reads. Each refusal is one of the errors below; Reason names it with the short code the TypeScript twin uses.

Index

Constants

View Source
const (
	// ChunkSize is profile 1's blob size: every blob but the last is exactly
	// this long, and the last is 1 to ChunkSize bytes.
	ChunkSize = 4194304
	// Fanout is the most children a node holds, and profile 1's grouping.
	Fanout = 256
	// MaxNode is the largest node, root or branch, in bytes.
	MaxNode = 65536
	// MaxExtensionBytes bounds the extension values of one node together.
	MaxExtensionBytes = 16384
	// MaxDepth bounds the nodes on any path from the root to an object, the
	// root and the object included.
	MaxDepth = 16
	// Profile1 is the chunking profile this package constructs and checks.
	Profile1 = 1
	// MediaType is the one extension type version 1 assigns: advisory, on
	// the root only.
	MediaType = 1
	// DefaultMaxReferences bounds the child references Verify follows when
	// Limits leaves it zero: every blob and branch reference, repeats
	// counted, about 16 TiB of content in profile 1.
	DefaultMaxReferences = 1 << 22
)
View Source
const (
	KindRoot   = 0
	KindBranch = 1

	ChildBlob   = 0
	ChildBranch = 1
)

Node kinds and child kinds.

View Source
const DefaultBuffer = 16 * ChunkSize

DefaultBuffer is the bytes an Incremental keeps of pieces that arrived ahead of its walk when NewIncremental is given 0: sixteen blobs.

View Source
const MaxWorkers = 64

MaxWorkers bounds the blob hashers of a ParallelChunker and of BuildParallel.

Variables

View Source
var (
	ErrNodeSize    = errors.New("chirp: node larger than MaxNode")
	ErrTruncated   = errors.New("chirp: node ends early")
	ErrMagic       = errors.New("chirp: not a CHIRP node")
	ErrVersion     = errors.New("chirp: version not 1.0")
	ErrNodeKind    = errors.New("chirp: unknown node kind")
	ErrProfile     = errors.New("chirp: chunking profile 0 is reserved")
	ErrCompactSize = errors.New("chirp: CompactSize not minimal")
	ErrChildCount  = errors.New("chirp: child count out of range")
	ErrChildKind   = errors.New("chirp: unknown child kind")
	ErrLength      = errors.New("chirp: lengths disagree")
	ErrExtension   = errors.New("chirp: extension refused")
	ErrTrailing    = errors.New("chirp: bytes after the node")
	ErrEmpty       = errors.New("chirp: empty content with children or another content hash")

	// Refusals of a closure.
	ErrMissing     = errors.New("chirp: object not available")
	ErrHash        = errors.New("chirp: object does not hash to its reference")
	ErrDepth       = errors.New("chirp: closure deeper than MaxDepth")
	ErrCycle       = errors.New("chirp: closure refers to an ancestor")
	ErrReferences  = errors.New("chirp: closure has more references than the limit")
	ErrTooLarge    = errors.New("chirp: content longer than the limit")
	ErrContentHash = errors.New("chirp: content does not hash to the root's content hash")
	ErrCanonical   = errors.New("chirp: not profile 1's canonical construction")

	// ErrIdentifier is a string that is not a UHRP object identifier or a
	// CHIRP URL.
	ErrIdentifier = errors.New("chirp: not an object identifier")
)

The refusals, in the order a node is read.

View Source
var ErrFinished = errors.New("chirp: chunker already finished")

ErrFinished is a Write, Finish or Abort on a ParallelChunker after Finish or Abort.

View Source
var Magic = [5]byte{'C', 'H', 'I', 'R', 'P'}

Magic is the five bytes every node starts with, ASCII "CHIRP".

Functions

func DefaultWorkers added in v0.13.0

func DefaultWorkers() int

DefaultWorkers is the number of blob hashers used when none is given: the cores the process may use, at most 8.

func EncodeBranch

func EncodeBranch(br Branch) ([]byte, error)

EncodeBranch writes a branch node. It refuses what DecodeBranch refuses.

func EncodeRoot

func EncodeRoot(r Root) ([]byte, error)

EncodeRoot writes a root node. It refuses what DecodeRoot refuses.

func Identifier

func Identifier(hash [32]byte) string

Identifier is the UHRP object identifier of hash: Base58Check of the prefix ce00 and the 32 hash bytes, in natural order.

func Kind

func Kind(b []byte) (byte, error)

Kind returns the kind of a node from its prefix alone, after the size, magic and version checks.

func ParseIdentifier

func ParseIdentifier(s string) ([32]byte, error)

ParseIdentifier returns the hash an object identifier names, refusing a bad checksum, another prefix or another length.

func ParseURL

func ParseURL(s string) ([32]byte, error)

ParseURL returns the root a CHIRP URI names. It takes the canonical chirp://<identifier> and the compact chirp:<identifier>, the scheme in any case, and nothing else: no user information, port, path, query or fragment, which a valid identifier cannot contain.

func Reason

func Reason(err error) (string, bool)

Reason returns the short code of a refusal of this package, the code the TypeScript twin's ChirpError carries, and false for any other error.

func URL

func URL(root [32]byte) string

URL is the canonical CHIRP URI of a root: chirp://<identifier>.

func ValidMediaType

func ValidMediaType(s string) bool

ValidMediaType reports whether s is a mediaType value BRC-167 admits: a lower-case media-type essence of 3 to 127 bytes, type and subtype each an RFC 6838 restricted name, joined by one "/", with no parameters and no whitespace.

Types

type Branch

type Branch struct {
	Length     uint64
	Children   []Child
	Extensions []Extension
}

Branch is a decoded branch node.

func DecodeBranch

func DecodeBranch(b []byte) (Branch, error)

DecodeBranch reads a branch node, with DecodeRoot's checks in the same order, at least one child required.

type Built

type Built struct {
	// Root is the root node's bytes and RootHash their SHA-256, the object
	// the closure is named by.
	Root     []byte
	RootHash [32]byte
	// Branches are the branch nodes' bytes, lowest level first and left to
	// right within a level. Two equal branches appear twice.
	Branches [][]byte
	// Blobs are the content's blobs in order when the closure was built from
	// content; nil when it was built from references.
	Blobs [][]byte
}

Built is a closure as profile 1 constructs it.

func Build

func Build(content []byte, ext []Extension) (Built, error)

Build is profile 1's closure of content held in memory: its blobs, the branches over them and the root, with ext the root's extensions.

func BuildParallel added in v0.13.0

func BuildParallel(content []byte, ext []Extension, workers int) (Built, error)

BuildParallel is Build with the blobs and the content hashed on up to workers + 1 cores (workers as NewParallelChunker takes it). It returns what Build returns, byte for byte, and holds nothing beyond it: the blobs are slices of content.

func BuildTree

func BuildTree(blobs []Child, contentHash [32]byte, ext []Extension) (Built, error)

BuildTree is profile 1's canonical tree over blob references in content order: at most Fanout references are the root's children; more are grouped Fanout at a time, left to right, into branches, repeated until at most Fanout remain. Every reference must be a blob of exactly ChunkSize bytes but the last, which holds 1 to ChunkSize; anything else is ErrCanonical. contentHash is the SHA-256 of the content, which BuildTree cannot compute from references; ext are the root's extensions.

type Child

type Child struct {
	Kind   uint8 // ChildBlob or ChildBranch
	Length uint64
	Hash   [32]byte
}

Child is one child reference: 41 bytes on the wire.

type Chunker

type Chunker struct {
	// contains filtered or unexported fields
}

Chunker builds a closure from content written in pieces, holding at most one blob: each blob is handed to emit as soon as it is complete, so that it can be published before the content ends. Finish hands over the last.

func NewChunker

func NewChunker(emit func(blob []byte) error) *Chunker

NewChunker returns a Chunker that hands each blob to emit. The slice emit receives is reused after emit returns.

func (*Chunker) Finish

func (c *Chunker) Finish(ext []Extension) (Built, error)

Finish hands over the last blob and returns the closure's root and branches; Built.Blobs is nil, since every blob went to emit.

func (*Chunker) Write

func (c *Chunker) Write(p []byte) (int, error)

Write takes content in order. An error from emit is returned, and every later call returns it too.

type Closure

type Closure struct {
	Root     Root
	RootHash [32]byte
	// Blobs are the blob references in content order, repeats included.
	Blobs []Child
	// Objects are the closure's distinct objects, root first, then in the
	// order a depth-first walk in child order first meets them.
	Objects [][32]byte
	// Canonical is true when the root declares profile 1 and the closure is
	// profile 1's canonical construction. A closure of another profile is
	// verified for everything but its construction, and Canonical is false.
	Canonical bool
}

Closure is a verified closure.

func Verify

func Verify(rootHash [32]byte, fetch Fetch, lim Limits) (*Closure, error)

Verify fetches and checks the closure of the root named rootHash, holding at most one blob at a time:

  1. the root: missing, hash, its node checks (DecodeRoot), then too-large against Limits.MaxLength;
  2. a depth-first walk in child order, for each reference: references (over the limit), depth (an object past MaxDepth), cycle (a branch that is its own ancestor), missing; a branch's hash, its node checks, and length (its length against the reference's); a blob's length (its byte count against the reference's), then hash;
  3. content-hash: the blobs in order against the root's content hash;
  4. for profile 1, canonical: BuildTree over the blob references, with the root's content hash and extensions, gives this root.

Every node is hashed before any of its fields is read, as BRC-167 has it: bytes that are not the object asked for are the host's fault, while a node that hashes right and still fails its checks is a fault of the closure itself, which no other host can mend.

type Extension

type Extension struct {
	Type  uint64
	Value []byte
}

Extension is one entry of a node's extension vector.

type Fetch

type Fetch func(hash [32]byte) ([]byte, error)

Fetch returns the bytes of the object named by hash, or an error when it has none; Verify checks the bytes against the hash itself. A blob may be asked for more than once when the closure repeats it.

type Incremental added in v0.13.0

type Incremental struct {
	// contains filtered or unexported fields
}

Incremental is Verify run as the closure's pieces arrive instead of at the end. Each piece handed to Add is hashed there (AddHashed takes the caller's hash instead), on the caller's goroutine, so pieces arriving on several goroutines are hashed on several cores; the walk then moves as far as the pieces on hand allow, and the content hash advances over the blobs in order as they come. When the last piece lands, what is left of the check is the canonical construction over the blob references, which hashes only nodes.

The walk is Verify's: the same checks of the root, the same depth-first walk in child order with the same checks of each reference, the same content hash and canonical checks, and the same Closure. Where Verify would report missing, the walk waits instead: a refusal is reported when the walk reaches the object it concerns, which is after every object before it in Verify's order has arrived and passed. A piece that arrives early is never judged early, so the first refusal reported is always the one Verify reports over the same objects, and the result once complete is Verify's, byte for byte, with the same error sentinel. Check reports missing as Verify does, for the object the walk waits for.

Memory is bounded as Verify's is (the walk's state, under Limits.MaxReferences), plus the copies of pieces that arrived ahead of the walk, at most the buffer given to NewIncremental (DefaultBuffer when 0) besides the one piece the walk waits for. A piece not kept, or one the closure repeats, is fetched when the walk reaches it and checked as Verify checks a fetched object, so fetch must serve every piece already handed to Add, as a store the pieces are written to before Add does. An Incremental made after a restart, with nothing handed to Add yet, walks what fetch serves on its first Advance, Add or Check and continues from there as pieces arrive: only the pieces held before the restart are read back, and each is checked once.

An Incremental is safe for concurrent use. Its methods never return before the walk has moved as far as the pieces given allow, except Add and Advance while another goroutine is walking: that goroutine then carries the walk on to the new piece before it stops.

func NewIncremental added in v0.13.0

func NewIncremental(rootHash [32]byte, fetch Fetch, lim Limits, buffer int) *Incremental

NewIncremental returns an Incremental for the closure of the root named rootHash, with Verify's limits and a fetch for the pieces it does not keep (see Incremental). buffer bounds the bytes of pieces kept ahead of the walk; DefaultBuffer when 0 or less.

func (*Incremental) Add added in v0.13.0

func (v *Incremental) Add(piece []byte) [32]byte

Add hands over a piece of the closure, or any object: it is hashed here, a copy kept when the walk waits for it or the buffer has room, and the walk moved on. It returns the piece's hash, the object it is. A piece that is no object of the closure is kept until the buffer is needed and otherwise ignored.

func (*Incremental) AddHashed added in v0.14.2

func (v *Incremental) AddHashed(hash [32]byte, piece []byte)

AddHashed is Add for a caller that has already hashed the piece: hash must be sha256 of piece, and the caller vouches for it. It saves the one hash of the piece that Add makes, which is most of Add's cost for a blob.

The trust is narrow. A root or branch handed here is hashed again when the walk takes it (nodes are small), so the closure's structure, every reference's hash and length and the content hash it commits to, is always checked as Verify checks it. Only a blob's own hash is taken on the caller's word; its length is still checked against its reference, and its bytes still go into the content hash, which must equal the root's. So with a correct hash the walk and its verdict are Add's, the same as Verify's, byte for byte. With a wrong one, no bytes but the content the root commits to can ever pass: a blob whose bytes differ from the content in its place fails the content hash. What a wrong hash can do is place a piece under a reference that its bytes do not hash to and, where those bytes are the committed content anyway, pass a closure whose blob references Verify would refuse with ErrHash; and a piece kept under a hash that no reference names is ignored, as any stray piece is. A caller that cannot vouch for the hash, or must refuse such malformed closures, calls Add.

func (*Incremental) Advance added in v0.13.0

func (v *Incremental) Advance()

Advance moves the walk as far as the pieces kept and fetch allow: after a restart, or after a piece Add did not keep has been stored.

func (*Incremental) Check added in v0.13.0

func (v *Incremental) Check() (*Closure, error)

Check is Verify's answer over the pieces on hand: it moves the walk as far as it goes and returns the verified closure or the refusal, missing (ErrMissing) when the walk waits for an object that fetch does not serve. Missing is not final: the walk resumes when the piece arrives.

func (*Incremental) Result added in v0.13.0

func (v *Incremental) Result() (*Closure, error)

Result is the outcome so far: the verified closure, or the refusal, or neither while the walk waits for a piece.

func (*Incremental) Waiting added in v0.13.0

func (v *Incremental) Waiting() ([32]byte, bool)

Waiting returns the object the walk waits for, and false when it waits for nothing: finished, or not started.

type Limits

type Limits struct {
	// MaxReferences bounds the child references followed, repeats counted;
	// DefaultMaxReferences when zero.
	MaxReferences int
	// MaxLength bounds the content's length, checked against the root before
	// anything else is fetched; no bound beyond MaxReferences when zero.
	MaxLength uint64
}

Limits bounds what Verify follows. A zero field takes its default.

type ParallelChunker added in v0.13.0

type ParallelChunker struct {
	// contains filtered or unexported fields
}

ParallelChunker is Chunker with the hashing spread over several cores: each complete blob is hashed (the SHA-256 that names it) and handed to emit by one of workers goroutines, while one more goroutine hashes the content in order. Write only copies into the current blob, so the caller's loop waits for a hash only when every buffer is in use. Memory holds at most workers + 2 blobs.

Finish returns the closure Chunker returns for the same content, byte for byte.

emit is called concurrently, from the worker goroutines, once per blob, in no particular order: i is the blob's index in content order and ref its reference. The slice is reused after emit returns. emit is where a caller does its own per-blob work on the same core, such as commit.SegmentRoot of the blob for a byte-leaf tree (see commit.SegmentRoots). The first error from emit stops the build: later blobs are not hashed or emitted, and Write and Finish return it.

A ParallelChunker is used from one goroutine; emit runs on others. Call Finish or Abort once, or its goroutines are never released.

func NewParallelChunker added in v0.13.0

func NewParallelChunker(workers int, emit func(i int, ref Child, blob []byte) error) *ParallelChunker

NewParallelChunker returns a ParallelChunker with workers blob hashers (DefaultWorkers when 0 or less, at most MaxWorkers) that hands each blob to emit.

func (*ParallelChunker) Abort added in v0.13.0

func (c *ParallelChunker) Abort()

Abort stops the chunker without a result and waits for its goroutines; emit is not called again once Abort returns. It is safe after Finish.

func (*ParallelChunker) Finish added in v0.13.0

func (c *ParallelChunker) Finish(ext []Extension) (Built, error)

Finish hands over the last blob, waits for every blob, and returns the closure's root and branches; Built.Blobs is nil, since every blob went to emit.

func (*ParallelChunker) Write added in v0.13.0

func (c *ParallelChunker) Write(p []byte) (int, error)

Write takes content in order. After an error from emit, it returns that error, having taken the bytes counted by n.

type Root

type Root struct {
	Profile     uint16
	Length      uint64
	ContentHash [32]byte
	Children    []Child
	Extensions  []Extension
}

Root is a decoded root node.

func DecodeRoot

func DecodeRoot(b []byte) (Root, error)

DecodeRoot reads a root node. The checks run in order: size, magic, version, kind, profile, then the layout (truncated, compact-size, child-count, child-kind, trailing), then the child lengths against the root's (length), the empty-content rule (empty), and the extensions (extension).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL