scionic

package module
v2.5.6 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 22 Imported by: ? 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.

README

nostr Badge Go Badge CI codecov Version

Scionic Merkle Trees

Combining Merkle Trees and Merkle DAGs

We've designed a new type of Merkle DAG/Merkle Tree hybrid known as the Scionic Merkle Tree. Scionic Merkle Trees contain small branches like Classic Merkle Trees, the folder storage support of Merkle DAGs, and numbered file chunks, so anyone can sync a file by its hash and request the range of chunk numbers they are missing. LeafSync is the name of the simple protocol used to request a range of a file's chunk numbers in order to retrieve a batch of missing file chunks. Identical chunks, files and folders have identical hashes wherever they appear, so each one is stored once and sent once.

This repository is the Go implementation, at version 2.5.6. The Scionic tree format is specified in spec/FORMAT.md. The Rust library is the reference for it, and this library is held to the same test vectors, under spec/, byte for byte.

Scionic Merkle Trees maintain the advantages of IPFS Merkle DAGs with the slim Merkle Branches of Classic Merkle Trees, while providing LeafSync as a new feature that complements any set reconciliation system (IBLTs, negentropy, et al.). In plant grafting, the "Scion" is the upper part of the plant, chosen for its desirable fruits or flowers; it's grafted onto another plant's base to grow together. In a similar vein, the Scionic Merkle Tree was born from grafting together Merkle Trees and Merkle DAGs. This process emphasizes why we use the term "Scion" for the Scionic Merkle Trees: it symbolizes the digital grafting of these two similar data structures, combining their strengths into one piece of software.

Contents

Scionic Merkle Trees: The Best of Both Worlds

Scionic Merkle Tree

Scionic Merkle Branch

Classic Merkle Trees

Merkle Trees are cryptographic structures used to manage and securely verify large amounts of data. However, there's a significant drawback: they cannot store folders of files.

The number of hashes required for a Merkle proof in a Classic Merkle Tree grows logarithmically with the number of file chunks, meaning the growth rate slows as the tree grows. This pattern makes them very efficient for large datasets.

Scionic Merkle Trees vs. IPFS Merkle DAGs

Merkle DAGs were developed as a solution to incorporate folders of files, addressing a key limitation of Classic Merkle Trees. However, this structure has its own challenge: to securely download a single file chunk, you must download the hash of every other file chunk inside the folder it's stored in. Each parent leaf keeps growing as the folder grows, even though the size of each Merkle chunk should always remain the same.

Scionic Merkle Trees resolve this flaw, because each Scionic parent leaf is itself chunked using a Classic Merkle Tree, ensuring every part of the Scionic Merkle Tree is uniformly small. In the most extreme cases of P2P decentralization, a user could retrieve each Merkle branch from a different source without needing to download the entire parent leaf first.

Folders and Subfolders of Files

Like Merkle DAGs, Scionic Merkle Trees can accommodate storing folders of files. An entire directory of files and subfolders can be converted into a Scionic Merkle Tree, and a single file can be a tree on its own.

Content-Defined File Chunking

Files are split into chunks with content-defined chunking (FastCDC): chunk boundaries are derived from the bytes themselves rather than from fixed offsets, so identical content produces identical chunks no matter where it appears. Editing a large file no longer shifts every boundary after the edit: only the chunks around the edit change, and every other chunk is reused.

Chunk sizes are bounded: more than 512 KiB, 2 MiB on average, and 8 MiB at most, with only a file's last chunk allowed to be smaller. No crafted content can produce a flood of tiny chunks or one giant chunk to stall producers, verifiers or transports. The algorithm is frozen as fastcdc-v1 in spec/FORMAT.md and pinned by the vectors in spec/fastcdc-vectors, so every implementation cuts the same bytes at the same places.

Deduplication at Every Level

A hash covers what a thing is, and never where it sits:

  • A chunk's hash is the SHA-256 of its bytes, and nothing else.
  • A file's hash covers the ordered list of its chunks. It does not cover the file's name.
  • A folder's hash covers its entries: each name with the hash under it. It does not cover the folder's own name.

So the same chunk, the same file and the same folder have the same hash in every tree. A store keeps each of them once, and a sync skips whatever the receiver already holds, whichever tree it first arrived with. A renamed file, a copied folder, and a new version of a large file that changes a few megabytes each cost only what is new.

Chunked Parent Leaves

Within each parent leaf, the list of children is organized as a Classic Merkle Tree rather than one potentially large list of hashes. This holds for a folder with its entries and for a file with its chunks. Large files and large folders lead to very long lists, and chunking the parent leaf with a Classic Merkle Tree avoids that scaling problem.

  • A folder's Classic Merkle Tree covers its entries, in the order of their names.
  • A file's Classic Merkle Tree covers its chunks, in the order they have in the file. A chunk's number is its place in that tree, so a chunk cannot be shown under a number it does not have.

The top of each tree is its Classic Merkle root. The hash of a folder or of a file covers three things: how many items its list has, its size in bytes, and its Classic Merkle root. That hash is what a parent holds for its child, and what the tree's record holds for the folder or file on top. In the pictures above, every folder and file shows those three in a box, and every link by hash ends at that box.

A large file has far more chunks than most folders have entries: about 500,000 for a file of a terabyte. A file of 512 KiB or less is a single chunk, and its tree is that one leaf.

File Chunk Downloading with Chunked Parent Leaves

If a user wants to download a specific file chunk within a Scionic Merkle Tree, they no longer need to download the hash of every other chunk of its file, or the listing of every other file in its folder. Instead, they download a Classic Merkle branch for each parent on the way down from the root. This allows the user to verify that the chunk is part of the tree without the rest of it.

One Place for Every Name

A folder's entries are sorted by name, and every fork of the folder's Merkle tree records the name at which its right half begins. A name can therefore sit in exactly one place. One branch proves that a name is in a folder and what it holds, and the same kind of branch proves that a name is not in the folder. A publisher cannot show one file under a name to a reviewer and a different file under the same name to everyone else.

Scionic Merkle Branch Statistics

Comparing the size of a Scionic Merkle Branch to the whole parent leaf that a Merkle DAG has you download. These are bytes on the wire in version 2.5.6, measured by examples/proofsizes. The tests hold this table to that program.

One file out of a folder, proven by its name:

Entries in the folder The whole folder listing A Scionic branch Smaller by
10 610 bytes 300 bytes 2x
1,000 61 KB 648 bytes 94x
10,000 610 KB 880 bytes 693x
1,000,000 61 MB 1,228 bytes 50,000x

One chunk out of a file, proven by its number:

Chunks in the file About The file's whole chunk list A Scionic branch Smaller by
10 20 MB 360 bytes 219 bytes 2x
1,000 2 GB 36 KB 459 bytes 78x
10,000 20 GB 360 KB 619 bytes 582x
500,000 1 TB 18 MB 819 bytes 22,000x
go run ./examples/proofsizes

Scionic Merkle Trees incorporate Classic Merkle Trees within their structure, so their branches grow logarithmically: each time a folder or a file doubles in size, a branch through it grows by one step. In stark contrast, a parent leaf in an IPFS Merkle DAG grows linearly, because the hash of every child must be downloaded to check any one of them.

Syncing by File Hash and Chunk Number

A Scionic Merkle Tree says what is in it. The root names what is on top, a folder lists its entries, and a file lists its chunks. LeafSync is the protocol that fetches from it. A receiver asks for:

  • a file by its hash, and its chunks by their numbers: chunks 100 to 200 of this file;
  • a range of a file's bytes, for which only the chunks that hold those bytes are sent;
  • one name of a folder, or a range of its entries.

A chunk's number is its position in its file's list, and the file's hash covers that list, so nobody can lie about a number. A file's hash is the same in every tree, so the same request means the same thing wherever the file appears.

Negentropy Symbiosis

LeafSync complements any set reconciliation system, such as Negentropy. Each does the part it is suited to:

  • Set reconciliation syncs the Merkle roots, and the file hashes that link to each root. Two sides work out which roots, and which files under a root, one of them holds and the other is missing. These are small sets: one hash for a tree and one for a file.
  • LeafSync then syncs the chunks of each file. A file's chunks are numbered, so a receiver asks for the ranges of numbers it is missing. Chunk hashes are never reconciled as a set. They are by far the largest set, about 500,000 for a terabyte of files, and set reconciliation costs memory and work for every hash in the set.

This library provides LeafSync. It holds no set reconciliation of its own, and works beside whichever one an application runs. A receiver that has nothing but a root needs none at all: it walks down from the root, skips everything it already holds by its hash, and asks for the rest.

A phone can read one file out of a tree of terabytes and hold almost nothing. Which chunks of a file a peer holds is one bit per chunk: about 60 KB for a file of a terabyte. Different ranges of one file can be requested from different peers at the same time.

Everything is verified on arrival. Every answer is checked against a hash that has already been checked, all the way back to the root, before it is kept or passed on. Nothing is trusted because of who sent it.

What's New in 2.5.6

Version 2.5.6 is a new tree format, built for deduplication and for trees of a terabyte and more. It does not read trees made by 2.4.x, and the same folder has a different root than it had there.

  • Deduplication comes first. A chunk's hash covers its bytes alone and a file's hash covers its chunks alone. Names and chunk numbers moved into the parent. Earlier versions hashed a chunk's number into the chunk and a file's name into the file, so the same bytes had different hashes in different places.
  • LeafSync numbers a file's chunks, not a tree's leaves. Earlier versions numbered every leaf of a tree. It now asks for a file by its hash and for its chunks by their numbers within that file, which the file's hash covers. Set reconciliation is left with the small sets: the Merkle roots, and the file hashes that link to them.
  • A folder has one place for each name, so one branch proves that a name is in a folder, or that it is not.
  • Hardened against forged data. A made-up leaf, a file that comes back short, a chunk that belongs to another file, and a store that is tricked into handing back other bytes are each refused, and each has a test.
  • Bounded memory and work. Every request says how long its answer may be, a tree's record says how much the tree holds, and writing a tree out counts what it would create before it creates anything.
  • Built for terabytes. Building and verifying use every core, a file is never held in memory whole, a damaged chunk is named by its hash and fetched again on its own, and any byte range of a file can be read without the rest of it.
  • Safe on disk. A link is never followed, in building or in writing out, even when one is swapped in while the work is under way.
  • A new API, in one package. The dag package of 2.4.x, with CreateDag, Dag and the transmission packets, is replaced by Build, Verify, Fetch, Serve and Remote, in the package at the module's root.

Documentation

Install

go get github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2@v2.5.6

The package is named scionic, and it is the module's root:

import (
	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)
Requirement
Go 1.26 or newer
Systems Linux, macOS and Windows, each tested on every push, and a 32-bit build on Linux
Dependencies golang.org/x/sys
unsafe and cgo none in this module

Quick Start

Turn a folder into a Scionic Merkle Tree, verify it, read a file out of it, and write the tree back to disk:

package main

import (
	"fmt"
	"log"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

func main() {
	// A store keeps chunks and lists by their hashes. This one is in memory.
	store := scionic.NewMemoryStore()

	// Build a tree from a folder. The root depends on the folder's contents
	// alone: not on where the folder is, what it is called, or how many
	// goroutines built it.
	root, err := scionic.Build(store, "models/my-model", scionic.BuildOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(root) // bafkrei...

	// Verify everything the store holds for that root: every list, every chunk.
	summary, err := scionic.Verify(store, root)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%d files, %d bytes\n", summary.Files, summary.Record.Top().Size)

	// Read one file by its path in the tree.
	entry, found, err := scionic.Lookup(store, root, "config.json")
	if err != nil {
		log.Fatal(err)
	}
	if found {
		content, err := scionic.ReadFileBytes(store, entry.Target())
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("config.json holds %d bytes\n", len(content))
	}

	// Write the whole tree back out, to a path that does not exist yet.
	if err := scionic.WriteToDisk(store, root, "restored"); err != nil {
		log.Fatal(err)
	}
}

A root is written as a CID that begins bafkrei. Root has a String method, ParseRoot reads one back, and only that one spelling of a root is read.

Syncing Between Two Stores

Anything that answers requests is a peer: a connection to another machine, or a store in the same program. This example runs as it stands.

package main

import (
	"bytes"
	"fmt"
	"log"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

func main() {
	// A publisher builds a tree. Here it is built from bytes in memory.
	publisher := scionic.NewMemoryStore()
	builder := scionic.NewBuilder(publisher, scionic.FastCDCV1)
	readme, err := builder.FileFromBytes([]byte("# My model\n"))
	if err != nil {
		log.Fatal(err)
	}
	weights, err := builder.FileFromBytes(bytes.Repeat([]byte{7}, 3<<20))
	if err != nil {
		log.Fatal(err)
	}
	readmeEntry, err := scionic.NewEntry("README.md", readme, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}
	weightsEntry, err := scionic.NewEntry("weights.bin", weights, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}
	top, err := builder.Folder([]scionic.Entry{readmeEntry, weightsEntry})
	if err != nil {
		log.Fatal(err)
	}
	root, err := builder.Finish(top, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}

	// A responder answers requests from the publisher's store.
	peer := scionic.NewResponder(publisher)

	// Read a part of the tree and keep nothing: find one file by its name,
	// then take 16 bytes from the middle of it. Only the chunk that holds
	// those bytes is sent, and it is verified against the root.
	remote, err := scionic.OpenRemote(peer, root)
	if err != nil {
		log.Fatal(err)
	}
	entry, found, err := remote.Lookup("weights.bin")
	if err != nil || !found {
		log.Fatal("the tree has the file: ", err)
	}
	var middle bytes.Buffer
	if err := remote.Read(entry.Target(), 1<<20, 16, &middle); err != nil {
		log.Fatal(err)
	}
	fmt.Println(middle.Bytes())

	// Or fetch the whole tree into another store. Each part is verified
	// before it is kept, and what the store already holds is skipped.
	mirror := scionic.NewMemoryStore()
	summary, err := scionic.Fetch(mirror, root, peer)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(summary.Files, "files")
}

Syncing Over a Connection

Syncing runs over anything that reads and writes bytes: a TCP or QUIC stream, a WebSocket, a pipe. One side serves and the other asks.

import (
	"bufio"
	"net"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

// serveOnePeer is the side that holds the tree. It answers one peer's
// requests until the peer hangs up.
func serveOnePeer(store scionic.Store, listener net.Listener) error {
	conn, err := listener.Accept()
	if err != nil {
		return err
	}
	defer conn.Close()
	return scionic.Serve(store, conn, bufio.NewWriter(conn))
}

// fetchTree is the side that wants the tree. A fetch that was cut off goes
// on from what the store holds when it is run again.
func fetchTree(address string, root scionic.Root, store scionic.Store) error {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return err
	}
	defer conn.Close()
	peer := scionic.NewStreamPeer(bufio.NewReader(conn), bufio.NewWriter(conn))
	_, err = scionic.Fetch(store, root, peer)
	return err
}

The library verifies everything against the root, so a connection does not have to be trusted for the data to be right. It does not encrypt or authenticate the connection: use TLS or Noise where a transfer should be private.

A writer that has a Flush method, as a buffered one has, is flushed by the library where the other side waits for what was written. Serve reads its requests through a buffer of its own.

What Else It Does

To do this Use
Build a tree from a folder or a file on disk Build, BuildWith, BuildOptions
Build a tree from bytes or streams, entry by entry Builder
Verify a tree that a store holds, and mend damage Verify, VerifyWith, VerifyOptions
Find a path, read a file, read a range of its bytes Lookup, ReadFile, ReadRange, ReadOpen
Write a tree out to disk WriteToDisk, WriteToDiskWith, WriteOptions
Serve a store to peers Serve, Responder
Fetch a whole tree from a peer Fetch
Read parts of a peer's tree and keep nothing Remote
Carry a whole tree as one file or stream Export, Import
List what changed between two trees Diff, Change
Bring your own transport Intake, Request, Frame, the Peer interface
Bring your own storage the Store interface

Building. Building uses every core unless BuildOptions.Workers says otherwise. Several files are chunked at once, and the chunks of one long file are hashed several at once. A file is never held in memory whole: a builder holds up to 16 MiB of it, or up to 64 MiB while other goroutines help it. BuildOptions.Timestamp writes the time into the tree's record, and BuildWith attaches extra data to each entry, such as a file mode or a media type. A link or a special file in the folder is refused, or left out with LinksSkip. It is never followed.

Verifying and mending. Verify checks every list and every chunk that a store holds for a root, on every core. When bytes were harmed where they are kept, the error says which thing it is: it matches ErrCorrupt, and carries the hash. With VerifyOptions{DiscardDamaged: true} the damaged parts are removed, and the next Fetch brings back exactly those. VerifyOptions.Rechunk also chunks every file again, and refuses a file that was not chunked the standard way.

	// Verifying finds the damage, and the error names what was harmed.
	_, err = scionic.Verify(mirror, root)
	var damaged *scionic.Error
	if errors.Is(err, scionic.ErrCorrupt) && errors.As(err, &damaged) {
		fmt.Println("the damaged chunk is named:", damaged.Hash == chunk)
	}

	// With DiscardDamaged the damaged parts are removed, and the next fetch
	// brings back exactly those.
	_, err = scionic.VerifyWith(mirror, root, scionic.VerifyOptions{DiscardDamaged: true})
	fmt.Println("it is missing now:", errors.Is(err, scionic.ErrMissing))
	if _, err := scionic.Fetch(mirror, root, scionic.NewResponder(publisher)); err != nil {
		log.Fatal(err)
	}

Bundles and changes. A whole tree can travel as one stream, and two trees in one store can be compared:

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

func main() {
	store := scionic.NewMemoryStore()
	older, err := scionic.Build(store, "release-1", scionic.BuildOptions{})
	if err != nil {
		log.Fatal(err)
	}
	newer, err := scionic.Build(store, "release-2", scionic.BuildOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// What changed, by path. The chunks that both releases share are held once.
	changes, err := scionic.Diff(store, older, newer)
	if err != nil {
		log.Fatal(err)
	}
	for _, change := range changes {
		fmt.Println(change.Kind, change.Path)
	}

	// The new release as one file: the record, then every list and every
	// chunk once.
	bundle, err := os.Create("release-2.bundle")
	if err != nil {
		log.Fatal(err)
	}
	if err := scionic.Export(store, newer, bufio.NewWriter(bundle)); err != nil {
		log.Fatal(err)
	}
	if err := bundle.Close(); err != nil {
		log.Fatal(err)
	}

	// Reading it back runs the same checks as a fetch from a peer.
	bundle, err = os.Open("release-2.bundle")
	if err != nil {
		log.Fatal(err)
	}
	defer bundle.Close()
	elsewhere := scionic.NewMemoryStore()
	summary, err := scionic.Import(elsewhere, newer, bufio.NewReader(bundle))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(summary.Files, "files arrived")
}

Every example in this file is run by the tests, from the example_*_test.go files, and they are shown with the package's documentation.

Three programs come with the module. examples/roundtrip takes a folder the whole way round with a store on disk: it builds the tree, verifies it, fetches it into a second store, reads 4 KiB from 64 places in its largest file, writes it out again, and holds the copy to the same root, timing each step. examples/speed measures chunking, hashing, building and verifying into a store in memory, then fetching the tree into a second store and carrying it to a third as a bundle, and builds a folder of your own when it is given one. examples/proofsizes prints the branch sizes in the tables above.

go run ./examples/roundtrip <folder> <work-dir>
go run ./examples/speed <MiB> [folder]
go run ./examples/proofsizes

Stores

A store keeps bytes under hashes, and that is all the library asks of one. MemoryStore is a store in memory, for tests and small trees. A database, a folder on disk or an object store has the three methods of the Store interface:

type Store interface {
	// Put keeps bytes under hash. Keeping what is kept already changes
	// nothing. The bytes are lent for the call only: a store that keeps
	// them keeps a copy.
	Put(kind Stored, hash Hash, bytes []byte) error
	// Get gives what is kept under hash, and false if nothing is. The
	// bytes it gives are never changed afterwards, by the store or by the
	// caller.
	Get(kind Stored, hash Hash) ([]byte, bool, error)
	// Remove forgets what is kept under hash.
	Remove(kind Stored, hash Hash) error
}

Stored says which of four kinds of thing it is: a chunk, a file's chunk list, a folder's listing, or a tree's record. A store never has to understand what it holds: every byte it hands back is checked again before it is used.

A store that can answer without reading the bytes may also have a Has or a Size method (StoreHas, StoreSize), and a store that can lend what it keeps a Lend method (StoreLend). The library uses them when they are there. A store on disk should have Size at the least: without it, seeing whether a chunk is there takes a read of the whole chunk. It should have Lend too: the library reads chunks through it, and a store that reads each one into memory it uses again spares the system finding fresh memory for every chunk. examples/roundtrip has a complete store that keeps each thing as a file named by its hash.

Errors

Every error the library returns is an *Error. What went wrong is told by matching it with errors.Is against one of the package's Err values, such as ErrCorrupt, ErrMissing, ErrHashMismatch, ErrLimitExceeded or ErrInvalidData. The fields of the *Error say more where they apply, as Hash does for a damaged chunk above: read them with errors.As. An error from a store, a reader or a writer of yours is handed back as it is, or wrapped so that errors.Is still finds it.

A reader that fails is never taken for one that ended. A file whose reader breaks off, or a stream that fails with its last bytes, is an error, and not a shorter file. A writer that takes fewer bytes than it is given is an error too.

Words Used in the API

The API and the specification use the same words as this page. This is where each one is found:

Here In the API and in spec/FORMAT.md
chunk ChunkRef, StoredChunk
a file's chunk list file list: FileList
a folder's listing folder list: FolderList, made of entries: Entry
Merkle branch, Merkle proof branch: FileBranch, FolderBranch
chunking Chunking, FastCDCV1
root Root, the hash of the tree's record: Record
File What it holds
format.go The bytes of a chunk, a file, a folder, an entry and the record, and the branches that show a part of a list. Reading is strict.
tree.go The Classic Merkle Tree of a list: building it, showing a part of it, and checking a part.
fastcdc.go Content-defined chunking (fastcdc-v1), in memory and as a stream.
build.go Building a tree from a folder on disk or from bytes.
intake.go The one set of checks for a tree that comes from a peer, comes in a bundle, or sits in a store.
read.go Finding a path, reading a file or a range of one, and writing a tree out to disk.
diff.go What changed between two trees.
wire.go The requests, and the frames that answer them.
sync.go Serving a store, fetching a tree, reading parts of a peer's tree, and bundles.
store.go The Store interface, and a store in memory.
disk.go and the three beside it Holding a folder open, so that nothing below it is reached through a link.

Performance

Measured on a Windows 11 laptop with Go 1.27: each figure is the median of the five rounds of the benchmark at the end of this file. The two programs named in the tables print the same figures on any machine.

Into a store in memory (examples/speed)
Content-defined chunking, one core 6.0 GiB/s
SHA-256 of the chunks, one core 4.1 GiB/s
Building a tree from one file of 1 GiB, every core 4.4 GiB/s
Building a tree from ten files of 256 MiB on disk, every core 7.6 GiB/s
Building a tree from 20,000 files of 4 KiB on disk, every core 0.16 s
Verifying every byte of a tree of 1 GiB, every core 67 GiB/s
With a store on disk, a folder of 3.5 GiB (examples/roundtrip)
Building the tree into the store 1.2 s
Verifying every byte from the store 0.2 s
Fetching the tree into a second store 2.7 s
Reading 4 KiB of a file of 1.5 GiB through a peer, on average over 64 places 1.3 ms
Writing the tree back out as files 2.4 s

That folder holds one file of 1 GiB twice. The tree stores it once: 3.5 GiB of files are kept as 2.5 GiB of chunks and 40 KB of lists.

Security

A receiver trusts one thing: the root. The peer that sends a tree, the network in between, and the bytes that sit in a store are all treated as untrusted. The tests hold the library to the guarantees below with forged bytes (forgery_test.go, forgery_shape_test.go), which are made by a second, independent copy of the format's rules (oracle_test.go).

What is verified

  • No forged content. A made-up child under a folder or a file, a real child's branch offered with another child, a file offered as a folder, a list offered as a chunk, and a file given another file's chunks are all refused.
  • No short files. A file never comes back shorter than it is. If a chunk is missing, reading is an error.
  • One name, one place. A folder cannot show one name at two places, even if it was put together out of order on purpose.
  • Every byte of a branch counts. A branch that differs in any one byte is refused, so no two branches prove the same thing.
  • Nothing is kept before it is verified. A frame that nothing asked for is refused and not kept. A list that fails a check is not kept either, and that transfer takes nothing more.

What is bounded

  • Memory. A peer cannot make a receiver set aside more memory than the tree it trusts calls for: every request says how long its answer may be.
  • Size. A tree's record says how much the tree holds, and taking it in stops as soon as it would hold more.
  • Expansion. A small tree that stands for an endless one, by holding one folder under many names, is counted before it is written out, and refused.
  • Malformed input is an error, and never a crash or a loop.
  • Waiting. A reader that never gives a byte is given up after a hundred tries, and nothing waits for a goroutine that is gone.

What a store can count on

  • Damage is found and named. Bytes that were harmed in a store are found when the tree is verified, and named by their hash. They can be removed and fetched again on their own.
  • A peer cannot delete your data. Nothing a peer sends makes a store remove bytes that are sound. A list that names a held chunk with a wrong length is refused, and the chunk stays.

What happens on disk

  • A link is never followed when a tree is built. That holds for a link that is in the folder, and for one that takes a file's or a folder's place while the folder is being read. Each folder is held open while it is read, and what is in it is opened from the folder itself, never by a path that is looked up again.
  • Nothing is written outside the destination. A tree is written only to a new place, and only with names the system can hold as they are. The new folders are held open while they are filled, so a link that takes the place of one is not written through.
  • A file is read under its own name. Windows drops a dot or a space from the end of a name when it looks a path up, and takes NUL for a device wherever it stands, so a file model. beside a file model would be read as model. Everything below the folder a caller names is opened by a path that Windows takes letter for letter.
  • Whatever is held open is let go of, however the work ends: with an error, or with a store of yours that panics.

The exact rules are in spec/FORMAT.md, under "What a receiver checks", "Limits", "Building a tree" and "Writing a tree out".

Known Limitations

  • One file is chunked on one core, because where a chunk ends decides where the next begins. That is about 6.0 GiB a second on the machine above. Hashing the chunks, which is the greater part of the work, uses every core.
  • Fetching a tree and writing a tree out use one core each. On the disks they were tried on, the disk was the slower part.
  • Verifying or fetching a whole tree keeps a small record in memory for every different chunk, so that each chunk is counted once: some tens of megabytes for a terabyte.
  • A list is taken in whole. A file's chunk list is 36 bytes a chunk, about 18 MB for each terabyte of the file, and a folder's listing has to fit in memory.
  • A tree is built from a folder as the folder is while it is read. If another program changes files in it meanwhile, the tree can hold a mix of old and new. It cannot be led outside the folder.
  • Links, special files and file permissions are not stored. An entry's extra data has room for a caller to record a mode.
  • A responder that tells a peer which chunks of a file it holds looks into its store for each of them. Responder.Have(false) switches that off for one that serves strangers.
  • A connection has to hold 2,048 bytes of requests on their way, which every connection over a network does. Go's net.Pipe and io.Pipe hold nothing: between a StreamPeer and a Serve they work all the same, and for an answerer of another make there is StreamPeer.Ahead(0).
  • On Windows, opening a file so that it cannot be led astray costs more than a plain open. With every core at work it does not show. While a folder is being read on Windows, other programs cannot rename or delete it.
  • On systems that are neither Unix nor Windows, a folder is not held open, and a link that is swapped in while a folder is read can be followed.

Specification and Test Vectors

  • spec/FORMAT.md is the format: what every hash covers, what a receiver checks, the bytes of every request and answer, and the limits.
  • spec/vectors/manifest.json holds the shared vectors, which the Rust library makes and every implementation is held to, byte for byte: 7 whole trees with every one of their bytes, 9 branches of them, 8 lookups of a name, 12 requests with their answers, 3 exchanges on a connection, and 76 forged inputs that must be refused. spec/vectors/README.md says how a library reads the file.
  • spec/fastcdc-vectors/manifest.json pins where 11 files are chunked, and what each file hashes to.

The files under spec/ are the Rust library's, copied byte for byte. The tests check the vectors' own hash before they use them.

Other Implementations

Implementation Version
Go, this repository 2.5.6
Rust 2.5.6 The reference for the format.
Swift 2.5.6

The three libraries are kept in step: one format, one set of vectors and one version number. A tree built by the Rust or the Swift library and one built by this library from the same folder have the same root, and each reads what the others write.

Development

gofmt -l .
go vet ./...
go test -race ./...

CI runs these on Linux, macOS and Windows on every push, runs the tests once more on Go 1.26, the oldest version the module supports, and once as a 32-bit program. The tests also hold this file to the module: its Go code is taken from files that are compiled and run, and its tables of branch sizes from the program that measures them.

The three pictures of this file are drawn by docs/pictures/pictures.mjs. docs/pictures/README.md says how to draw them again, and what their colours are.

License

Released under the MIT License: see LICENSE.

Benchmark: Go, Rust and Swift

The three libraries, measured one after another on the same machine and the same files. None of them is fastest at everything:

  • Swift is fastest at chunking a file, at building its tree in memory, at fetching a tree from one store in memory into another, at building a tree from ten large files, and at building a tree again from the copy written out to disk.
  • Rust is fastest at writing a tree as a bundle and reading it back, and at building a tree from 20,000 small files.
  • Rust and Swift tie for fastest at building a tree into a store on disk, verifying it from there, fetching it into a second store on disk, reading 4 KiB through a peer, and writing a tree out as files. Go is behind them at each.
  • All three tie at hashing, and at verifying a tree in memory.

Each time is the median of five rounds. Lower is faster, and the times of those named fastest are in bold.

Step Fastest Go Rust Swift
A file of 1 GiB, in memory
Content-defined chunking, one core Swift 0.166 s 0.142 s 0.139 s
SHA-256 of its chunks, one core All three tied 0.242 s 0.241 s 0.242 s
Building its tree into a store in memory, every core Swift 0.229 s 0.060 s 0.056 s
Verifying every byte of the tree, every core All three tied 0.015 s 0.014 s 0.014 s
Fetching the tree into a second store, as from a peer Swift 0.661 s 0.154 s 0.151 s
Writing the tree as a bundle, and reading that into a third store Rust 0.950 s 0.426 s 0.436 s
Folders on disk, built into a store in memory
Ten files of 256 MiB Swift 0.330 s 0.269 s 0.265 s
20,000 files of 4 KiB Rust 0.158 s 0.154 s 0.174 s
A folder of 3.5 GiB, with a store on disk
Building the tree into the store Rust and Swift, tied 1.24 s 0.73 s 0.72 s
Verifying every byte from the store Rust and Swift, tied 0.17 s 0.13 s 0.14 s
Fetching the tree into a second store Rust and Swift, tied 2.70 s 0.82 s 0.81 s
Reading 4 KiB of a file of 1.5 GiB through a peer, on average over 64 places Rust and Swift, tied 1.3 ms 1.1 ms 1.2 ms
Writing the tree back out as files Rust and Swift, tied 2.35 s 1.24 s 1.26 s
Building a tree from the copy, into a third store Swift 1.24 s 0.87 s 0.76 s

Fastest names the library with the lowest time. Where another wasn't slower than it in at least four of the five rounds, the two are named as tied, since the difference between them could be chance.

How much the rounds varied: each library's best and worst of the five
Step Go Rust Swift
A file of 1 GiB, in memory
Content-defined chunking, one core 0.165 s to 0.171 s 0.139 s to 0.143 s 0.139 s to 0.141 s
SHA-256 of its chunks, one core 0.238 s to 0.244 s 0.240 s to 0.245 s 0.239 s to 0.243 s
Building its tree into a store in memory, every core 0.228 s to 0.232 s 0.059 s to 0.064 s 0.055 s to 0.058 s
Verifying every byte of the tree, every core 0.013 s to 0.017 s 0.013 s to 0.014 s 0.014 s to 0.015 s
Fetching the tree into a second store, as from a peer 0.660 s to 0.664 s 0.152 s to 0.157 s 0.149 s to 0.155 s
Writing the tree as a bundle, and reading that into a third store 0.918 s to 1.113 s 0.420 s to 0.427 s 0.433 s to 0.437 s
Folders on disk, built into a store in memory
Ten files of 256 MiB 0.326 s to 0.337 s 0.263 s to 0.292 s 0.264 s to 0.269 s
20,000 files of 4 KiB 0.150 s to 0.171 s 0.143 s to 0.158 s 0.171 s to 0.182 s
A folder of 3.5 GiB, with a store on disk
Building the tree into the store 1.13 s to 1.56 s 0.72 s to 0.77 s 0.67 s to 0.74 s
Verifying every byte from the store 0.14 s to 0.19 s 0.12 s to 0.15 s 0.13 s to 0.15 s
Fetching the tree into a second store 2.60 s to 2.80 s 0.78 s to 0.86 s 0.77 s to 0.87 s
Reading 4 KiB of a file of 1.5 GiB through a peer, on average over 64 places 1.2 ms to 1.3 ms 1.1 ms to 1.2 ms 1.1 ms to 1.2 ms
Writing the tree back out as files 2.31 s to 2.42 s 1.23 s to 1.29 s 1.23 s to 1.29 s
Building a tree from the copy, into a third store 1.12 s to 1.54 s 0.77 s to 0.94 s 0.70 s to 0.89 s

How it was measured.

  • The machine: one Windows 11 laptop, the same for all three.
  • The builds: Go 1.27.3; Rust 1.100.0, with --release; Swift 6.3.1, with -c release. The libraries were at Go 13c91dc, Rust 2ca0f1f and Swift 72bdc41.
  • The programs: each library's own speed and roundtrip, which take the same steps in the same order (What Else It Does says how to run them). speed was given 1,024 MiB and the folder of ten files, and then 1 MiB and the folder of 20,000 files, of which only the time for the folder is taken. roundtrip was given the folder of 3.5 GiB.
  • The files: bytes that look random, so that nothing in them compresses, and nothing repeats unless it is there twice on purpose. The folder of 3.5 GiB holds one file of 1 GiB twice, one of 1.5 GiB and one of 2,000 bytes, and its tree keeps 2.5 GiB of chunks. The 20,000 files stand in 100 folders. speed makes its file of 1 GiB itself.
  • The order: in each round, each library ran its programs in turn, and the order of the three changed from round to round, so that none always went first. Before each program the machine rested for 20 seconds, so that one program's heat and writing to the disk would not carry into the next.
  • The two folders built into a store in memory are the best of five builds within each program: by then the system holds their files in memory, so the library is measured and not the disk.

What it does not show.

  • The steps with a store on disk measure the disk as much as the library. From one round to the next, the same library's time for such a step moved by as much as 1.4 times, which is more than Rust and Swift differ by at any of them. The disk is the laptop's own, which other programs may write to at any time. Even a step in memory had a slow round now and then, which the medians leave out.
  • Each library's roundtrip brings its own store on disk. All three keep each thing as a file named by its hash, write it under another name first, and lend what they read from memory that they use again. Rust's and Swift's can also read a chunk straight into the library's memory, which Go's library doesn't ask for. They are not the same code.
  • A store in memory keeps a copy of every chunk, and on Windows the fresh memory for each costs more than the copy into it. Fetching and bundling into a store in memory measure that too.
  • One machine, one system. Nothing here was measured on Linux or macOS, or on another disk.

Documentation

Overview

Example

A folder becomes a Scionic Merkle Tree, the tree is verified, one file is read out of it, and the tree is written back to disk.

// The example works in a folder of its own, which holds a small model.
defer workIn(map[string][]byte{
	"models/my-model/config.json":       []byte("{\"layers\": 12}\n"),
	"models/my-model/weights/model.bin": bytes.Repeat([]byte{7}, 3<<20),
})()

// A store keeps chunks and lists by their hashes. This one is in memory.
store := scionic.NewMemoryStore()

// Build a tree from a folder. The root depends on the folder's contents
// alone: not on where the folder is, what it is called, or how many
// goroutines built it.
root, err := scionic.Build(store, "models/my-model", scionic.BuildOptions{})
if err != nil {
	log.Fatal(err)
}
fmt.Println(root) // bafkrei...

// Verify everything the store holds for that root: every list, every chunk.
summary, err := scionic.Verify(store, root)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%d files, %d bytes\n", summary.Files, summary.Record.Top().Size)

// Read one file by its path in the tree.
entry, found, err := scionic.Lookup(store, root, "config.json")
if err != nil {
	log.Fatal(err)
}
if found {
	content, err := scionic.ReadFileBytes(store, entry.Target())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("config.json holds %d bytes\n", len(content))
}

// Write the whole tree back out, to a path that does not exist yet.
if err := scionic.WriteToDisk(store, root, "restored"); err != nil {
	log.Fatal(err)
}
Output:
bafkreifxao4std4w2b2cmzl6boesplar2mlntpqdwx43ujnvijef7hbbsy
2 files, 3145743 bytes
config.json holds 15 bytes
Example (BundlesAndChanges)

A whole tree can travel as one stream, and two trees in one store can be compared.

// The example works in a folder of its own, which holds two releases.
defer workIn(map[string][]byte{
	"release-1/README.md":   []byte("# My model\n"),
	"release-1/weights.bin": bytes.Repeat([]byte{7}, 3<<20),
	"release-2/README.md":   []byte("# My model, improved\n"),
	"release-2/weights.bin": bytes.Repeat([]byte{7}, 3<<20),
	"release-2/LICENSE":     []byte("MIT\n"),
})()

store := scionic.NewMemoryStore()
older, err := scionic.Build(store, "release-1", scionic.BuildOptions{})
if err != nil {
	log.Fatal(err)
}
newer, err := scionic.Build(store, "release-2", scionic.BuildOptions{})
if err != nil {
	log.Fatal(err)
}

// What changed, by path. The chunks that both releases share are held once.
changes, err := scionic.Diff(store, older, newer)
if err != nil {
	log.Fatal(err)
}
for _, change := range changes {
	fmt.Println(change.Kind, change.Path)
}

// The new release as one file: the record, then every list and every
// chunk once.
bundle, err := os.Create("release-2.bundle")
if err != nil {
	log.Fatal(err)
}
if err := scionic.Export(store, newer, bufio.NewWriter(bundle)); err != nil {
	log.Fatal(err)
}
if err := bundle.Close(); err != nil {
	log.Fatal(err)
}

// Reading it back runs the same checks as a fetch from a peer.
bundle, err = os.Open("release-2.bundle")
if err != nil {
	log.Fatal(err)
}
defer bundle.Close()
elsewhere := scionic.NewMemoryStore()
summary, err := scionic.Import(elsewhere, newer, bufio.NewReader(bundle))
if err != nil {
	log.Fatal(err)
}
fmt.Println(summary.Files, "files arrived")
Output:
added LICENSE
changed README.md
3 files arrived
Example (DamageIsFoundAndMended)

Bytes that were harmed where a store keeps them are found when the tree is verified, named by their hash, and fetched again on their own.

package main

import (
	"bytes"
	"errors"
	"fmt"
	"log"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

func main() {
	// A tree in two stores: a publisher's, and a mirror of it.
	publisher := scionic.NewMemoryStore()
	builder := scionic.NewBuilder(publisher, scionic.FastCDCV1)
	weights, err := builder.FileFromBytes(bytes.Repeat([]byte{7}, 3<<20))
	if err != nil {
		log.Fatal(err)
	}
	root, err := builder.Finish(weights, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}
	mirror := scionic.NewMemoryStore()
	if _, err := scionic.Fetch(mirror, root, scionic.NewResponder(publisher)); err != nil {
		log.Fatal(err)
	}

	// A chunk is harmed where the mirror keeps it.
	chunk := mirror.Hashes(scionic.StoredChunk)[0]
	mirror.Remove(scionic.StoredChunk, chunk)
	mirror.Put(scionic.StoredChunk, chunk, []byte("not what the hash says"))

	// Verifying finds the damage, and the error names what was harmed.
	_, err = scionic.Verify(mirror, root)
	var damaged *scionic.Error
	if errors.Is(err, scionic.ErrCorrupt) && errors.As(err, &damaged) {
		fmt.Println("the damaged chunk is named:", damaged.Hash == chunk)
	}

	// With DiscardDamaged the damaged parts are removed, and the next fetch
	// brings back exactly those.
	_, err = scionic.VerifyWith(mirror, root, scionic.VerifyOptions{DiscardDamaged: true})
	fmt.Println("it is missing now:", errors.Is(err, scionic.ErrMissing))
	if _, err := scionic.Fetch(mirror, root, scionic.NewResponder(publisher)); err != nil {
		log.Fatal(err)
	}
	if _, err := scionic.Verify(mirror, root); err != nil {
		log.Fatal(err)
	}
	fmt.Println("the tree is whole again")
}
Output:
the damaged chunk is named: true
it is missing now: true
the tree is whole again
Example (SyncBetweenTwoStores)

Anything that answers requests is a peer: a connection to another machine, or a store in the same program, as here.

package main

import (
	"bytes"
	"fmt"
	"log"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

func main() {
	// A publisher builds a tree. Here it is built from bytes in memory.
	publisher := scionic.NewMemoryStore()
	builder := scionic.NewBuilder(publisher, scionic.FastCDCV1)
	readme, err := builder.FileFromBytes([]byte("# My model\n"))
	if err != nil {
		log.Fatal(err)
	}
	weights, err := builder.FileFromBytes(bytes.Repeat([]byte{7}, 3<<20))
	if err != nil {
		log.Fatal(err)
	}
	readmeEntry, err := scionic.NewEntry("README.md", readme, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}
	weightsEntry, err := scionic.NewEntry("weights.bin", weights, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}
	top, err := builder.Folder([]scionic.Entry{readmeEntry, weightsEntry})
	if err != nil {
		log.Fatal(err)
	}
	root, err := builder.Finish(top, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}

	// A responder answers requests from the publisher's store.
	peer := scionic.NewResponder(publisher)

	// Read a part of the tree and keep nothing: find one file by its name,
	// then take 16 bytes from the middle of it. Only the chunk that holds
	// those bytes is sent, and it is verified against the root.
	remote, err := scionic.OpenRemote(peer, root)
	if err != nil {
		log.Fatal(err)
	}
	entry, found, err := remote.Lookup("weights.bin")
	if err != nil || !found {
		log.Fatal("the tree has the file: ", err)
	}
	var middle bytes.Buffer
	if err := remote.Read(entry.Target(), 1<<20, 16, &middle); err != nil {
		log.Fatal(err)
	}
	fmt.Println(middle.Bytes())

	// Or fetch the whole tree into another store. Each part is verified
	// before it is kept, and what the store already holds is skipped.
	mirror := scionic.NewMemoryStore()
	summary, err := scionic.Fetch(mirror, root, peer)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(summary.Files, "files")
}
Output:
[7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7]
2 files
Example (SyncOverAConnection)

Syncing runs over anything that reads and writes bytes. Here it is a TCP connection of this machine to itself.

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"net"

	scionic "github.com/HORNET-Storage/Scionic-MerkleTree-Go/v2"
)

// serveOnePeer is the side that holds the tree. It answers one peer's
// requests until the peer hangs up.
func serveOnePeer(store scionic.Store, listener net.Listener) error {
	conn, err := listener.Accept()
	if err != nil {
		return err
	}
	defer conn.Close()
	return scionic.Serve(store, conn, bufio.NewWriter(conn))
}

// fetchTree is the side that wants the tree. A fetch that was cut off goes
// on from what the store holds when it is run again.
func fetchTree(address string, root scionic.Root, store scionic.Store) error {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return err
	}
	defer conn.Close()
	peer := scionic.NewStreamPeer(bufio.NewReader(conn), bufio.NewWriter(conn))
	_, err = scionic.Fetch(store, root, peer)
	return err
}

// Syncing runs over anything that reads and writes bytes. Here it is a TCP
// connection of this machine to itself.
func main() {
	// The side that holds a tree. A single file can be a tree on its own.
	publisher := scionic.NewMemoryStore()
	builder := scionic.NewBuilder(publisher, scionic.FastCDCV1)
	weights, err := builder.FileFromBytes(bytes.Repeat([]byte{7}, 3<<20))
	if err != nil {
		log.Fatal(err)
	}
	root, err := builder.Finish(weights, scionic.ExtraData{})
	if err != nil {
		log.Fatal(err)
	}

	// It listens on this machine alone, on a port that the system picks.
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	served := make(chan error, 1)
	go func() { served <- serveOnePeer(publisher, listener) }()

	// The side that wants the tree.
	mirror := scionic.NewMemoryStore()
	if err := fetchTree(listener.Addr().String(), root, mirror); err != nil {
		log.Fatal(err)
	}
	if err := <-served; err != nil {
		log.Fatal(err)
	}
	fmt.Println(mirror.Bytes(scionic.StoredChunk), "bytes of chunks arrived")
}
Output:
3145728 bytes of chunks arrived

Index

Examples

Constants

View Source
const (
	// FastCDCMinSize is the floor below which no boundary is looked for: the
	// first FastCDCMinSize bytes of a chunk are not hashed at all. Every chunk
	// but a file's last is therefore at least FastCDCMinSize + 1 bytes.
	FastCDCMinSize = 512 * 1024
	// FastCDCTargetSize is where the strict mask gives way to the loose one,
	// which squeezes the sizes of chunks toward this size.
	FastCDCTargetSize = 2048 * 1024
	// FastCDCMaxSize is where a chunk is cut whatever its bytes are.
	FastCDCMaxSize = 8192 * 1024
	// FastCDCStrictMask selects the top 23 bits of the rolling hash. It
	// judges positions before FastCDCTargetSize.
	FastCDCStrictMask uint64 = 0xFFFF_FE00_0000_0000
	// FastCDCLooseMask selects the top 19 bits. It judges positions at or
	// after FastCDCTargetSize.
	FastCDCLooseMask uint64 = 0xFFFF_E000_0000_0000
	// FastCDCGearSeedPrefix is what the gear table is made from: entry i is
	// the first 8 bytes, big-endian, of SHA-256(prefix + the byte i).
	FastCDCGearSeedPrefix = "scionic-fastcdc-v1:gear:"
)

fastcdc-v1: chunking a file by its content (FastCDC, Xia et al. 2016). It is the way a tree's files are chunked. The Rust library's code and the vectors under spec/fastcdc-vectors define its exact bytes, and this file is held to them.

Every constant here is frozen as fastcdc-v1. A change to a size, a mask, a gear entry or the boundary loop would be another way of chunking under another name, never a change to this one: two builders give the same file the same hash only when both cut at the same bytes.

View Source
const (
	// MaxChunkBytes is the most bytes a chunk may hold: 8 MiB.
	MaxChunkBytes = FastCDCMaxSize
	// ListItemBytes is how many bytes one item of a file's list takes: a
	// hash and a length.
	ListItemBytes = 36
	// MaxNameBytes is the most bytes a name may hold.
	MaxNameBytes = 255
	// MaxExtraValues is the most values a set of extra data may hold.
	MaxExtraValues = 32
	// MaxExtraNameBytes is the most bytes the name of an extra value may
	// hold.
	MaxExtraNameBytes = 64
	// MaxExtraValueBytes is the most bytes an extra value may hold.
	MaxExtraValueBytes = 1024
	// MaxFolderDepth is the most folders that may sit inside one another,
	// the top one counted.
	MaxFolderDepth = 128
	// MaxCarriedNodes is the most nodes a branch may carry: 40 on each
	// side of what it shows.
	MaxCarriedNodes = 80
	// MaxExtraBytes is the most bytes a set of extra data may take: how
	// many values it has, and 32 values that are as long as they can be.
	MaxExtraBytes = 2 + MaxExtraValues*(4+MaxExtraNameBytes+MaxExtraValueBytes)
	// MaxRecordBytes is the most bytes a record may take: its fixed part,
	// and extra data that is as full as it can be.
	MaxRecordBytes = 66 + MaxExtraBytes
	// MaxEntryBytes is the most bytes a folder's entry may take: its fixed
	// part, the longest name, and extra data that is as full as it can be.
	MaxEntryBytes = 43 + MaxNameBytes + MaxExtraBytes
	// ChunkingKey names the extra value of a record that says how the tree's
	// files were chunked.
	ChunkingKey = "chunking"
	// TimestampKey names the extra value of a record that says when the
	// tree was built.
	TimestampKey = "timestamp"
	// ChunkingFastCDCV1 is how a tree says that its files were chunked by
	// content.
	ChunkingFastCDCV1 = "fastcdc-v1"
)
View Source
const BundleMagic = "SCIONIC\x01"

BundleMagic is what starts a bundle: a tree written out as one stream of frames.

View Source
const DefaultMaxChanges = 1_000_000

DefaultMaxChanges is the most changes that Diff lists.

View Source
const DefaultMaxWrittenEntries uint64 = 1_000_000

DefaultMaxWrittenEntries is the most files and folders that WriteToDisk makes unless it is told otherwise.

View Source
const MaxListItems uint64 = 1 << 40

MaxListItems is the most items a list may hold. It bounds how deep any walk goes.

View Source
const MaxRequestBytes = 35 + MaxNameBytes

MaxRequestBytes is the most bytes a request may take. The longest one asks for a name in a folder: its first byte, the folder's hash, and the longest name with its length.

View Source
const RequestsAheadBytes = 2048

RequestsAheadBytes is how many bytes of requests a StreamPeer sends ahead of their answers, and the most that the format lets anyone send ahead. It is small on purpose. The other end answers one request before it reads the next, so requests that are sent ahead wait in the connection, and a connection that could not hold them would leave both ends waiting for each other. A connection over a network holds this much. One that holds nothing, as Go's net.Pipe and io.Pipe do, needs StreamPeer.Ahead set to zero.

View Source
const Version = "2.5.6"

Version is the version of this library. The Rust, Go and Swift libraries carry one number, and write and read one format.

Variables

View Source
var (
	// ErrIO: the file system refused something.
	ErrIO = &Error{kind: kindIO}
	// ErrStream: reading from a stream or writing to one failed.
	ErrStream = &Error{kind: kindStream}
	// ErrInvalidData: bytes that are not a well-formed thing of the format.
	ErrInvalidData = &Error{kind: kindInvalidData}
	// ErrInvalidBase32: text that is not lowercase base32.
	ErrInvalidBase32 = &Error{kind: kindInvalidBase32}
	// ErrInvalidHex: text that is not lowercase hex of the right length.
	ErrInvalidHex = &Error{kind: kindInvalidHex}
	// ErrInvalidRoot: text that is not a root.
	ErrInvalidRoot = &Error{kind: kindInvalidRoot}
	// ErrInvalidName: a name that the format does not allow.
	ErrInvalidName = &Error{kind: kindInvalidName}
	// ErrHashMismatch: a thing does not hash to what it has to.
	ErrHashMismatch = &Error{kind: kindHashMismatch}
	// ErrSizeMismatch: a thing does not have the size it has to.
	ErrSizeMismatch = &Error{kind: kindSizeMismatch}
	// ErrTotalsMismatch: a record's totals are not those of its tree.
	ErrTotalsMismatch = &Error{kind: kindTotalsMismatch}
	// ErrIntakeFailed: an intake was used again after a part of its tree
	// was refused.
	ErrIntakeFailed = &Error{kind: kindIntakeFailed}
	// ErrNotWanted: something arrived that is not tied to the root, or was
	// not asked for.
	ErrNotWanted = &Error{kind: kindNotWanted}
	// ErrCorrupt: a store holds, under a hash, bytes that are not what the
	// hash says. Removing them from the store and fetching the tree again
	// mends it.
	ErrCorrupt = &Error{kind: kindCorrupt}
	// ErrMissing: a store does not hold something that the tree needs.
	ErrMissing = &Error{kind: kindMissing}
	// ErrTooDeep: folders sit inside one another more deeply than the
	// format allows.
	ErrTooDeep = &Error{kind: kindTooDeep}
	// ErrUnwritableName: a name that this system cannot hold as it is.
	ErrUnwritableName = &Error{kind: kindUnwritableName}
	// ErrUnsupportedEntry: a link or a special file, where only files and
	// folders are stored.
	ErrUnsupportedEntry = &Error{kind: kindUnsupportedEntry}
	// ErrNonUTF8FileName: a file's name on disk is not UTF-8.
	ErrNonUTF8FileName = &Error{kind: kindNonUTF8FileName}
	// ErrPeer: a peer could not answer, or stopped early.
	ErrPeer = &Error{kind: kindPeer}
	// ErrLimitExceeded: something needs more than its limit allows.
	ErrLimitExceeded = &Error{kind: kindLimitExceeded}
	// ErrSystemTimeBeforeUnixEpoch: the system clock is before 1970.
	ErrSystemTimeBeforeUnixEpoch = &Error{kind: kindSystemTimeBeforeUnixEpoch}
	// ErrSizeOverflow: a size or a count does not fit.
	ErrSizeOverflow = &Error{kind: kindSizeOverflow}
	// ErrInvariant: the library found itself in a state it rules out.
	ErrInvariant = &Error{kind: kindInvariant}
)

One value for each kind of error, to match with errors.Is.

View Source
var FastCDCV1 = Chunking{}

FastCDCV1 chunks by content: chunks of more than 512 KiB, about 2 MiB on average, and 8 MiB at most. Only a file's last chunk may be smaller.

Functions

func CheckName

func CheckName(name string) error

CheckName checks a name: 1 to 255 bytes of UTF-8, no "/", no zero byte, and not "." or "..".

func ChunkFrame

func ChunkFrame(chunk []byte) []byte

ChunkFrame is the frame for a chunk's bytes.

func Export

func Export(store Store, root Root, out io.Writer) error

Export writes a whole tree to out as one stream: the bundle's first bytes, the record, and then every list and every chunk once, each after what names it. Import reads it back. If out has a Flush method, as a buffered writer has, it is called once the bundle is written.

func FileBranchFrame

func FileBranchFrame(branch *FileBranch) []byte

FileBranchFrame is the frame for a branch of a file's list.

func FileListFrame

func FileListFrame(list []byte) []byte

FileListFrame is the frame for a file's whole list.

func FolderBranchFrame

func FolderBranchFrame(branch *FolderBranch) []byte

FolderBranchFrame is the frame for a branch of a folder's list.

func FolderListFrame

func FolderListFrame(list []byte) []byte

FolderListFrame is the frame for a folder's whole list.

func HaveFrame

func HaveFrame(held *HaveMap) []byte

HaveFrame is the frame for a map of held chunks.

func ReadFile

func ReadFile(store Store, file Target, out io.Writer) error

ReadFile writes all of a file's bytes to out.

func ReadFileBytes

func ReadFileBytes(store Store, file Target) ([]byte, error)

ReadFileBytes gives a file's bytes, in memory. Room for them is taken only once every chunk of the file is found.

func ReadFrame

func ReadFrame(input io.Reader, limit int) ([]byte, error)

ReadFrame reads one frame from a stream. When the stream has ended between two frames, it gives io.EOF. A frame longer than limit is refused before any of it is read, and a stream that ends inside a frame is an error.

func ReadOpen

func ReadOpen(store Store, file *OpenFile, offset, length uint64, out io.Writer) error

ReadOpen writes length bytes of a file whose list is open, from byte offset, to out. It does what ReadRange does, and finds the chunks without a pass over the list.

func ReadRange

func ReadRange(store Store, file Target, offset, length uint64, out io.Writer) error

ReadRange writes length bytes of a file, from byte offset, to out.

Before the first byte goes out, every chunk of the stretch is looked for. If one is missing, nothing is written. Each chunk is then checked against its hash as it is written.

The file's list is read and checked on every call. For many stretches of one long file, open its list once and use ReadOpen.

func RefusedFrame

func RefusedFrame(why Refusal) []byte

RefusedFrame is the frame that says why a peer does not answer.

func Serve

func Serve(store Store, from io.Reader, output io.Writer) error

Serve answers the requests that come in on a connection, until it ends.

A request comes as a frame does: its length in four bytes, and then its bytes. The answer goes out as its frames, each with its length before it, and then a length of zero. Requests are answered one at a time, in the order they come. If output has a Flush method, as a buffered writer has, it is called after each answer.

A request that is malformed or too long ends the serving with an error. What is not held is answered with a refusal, and the serving goes on.

Serve reads from the connection until it ends, and may read requests before it answers the ones before them.

func Unwritable

func Unwritable(name string) (reason string, unwritable bool)

Unwritable says why this system cannot hold a name as it is, if it cannot.

A tree can hold a name that one system cannot. What is checked here is what would make a name land somewhere else than it says: on another file, on a device, or outside the folder.

func UnwritableOnWindows

func UnwritableOnWindows(name string) (reason string, unwritable bool)

UnwritableOnWindows says why Windows cannot hold a name as it is, if it cannot.

func WriteFrame

func WriteFrame(out io.Writer, frame []byte) error

WriteFrame writes one frame to a stream: its length as four bytes, then the frame.

func WriteToDisk

func WriteToDisk(store Store, root Root, dest string) error

WriteToDisk writes a tree out to disk: its top folder as the new folder dest, or its top file as the new file dest.

Writing is stricter than holding. dest must not exist. Before anything is written, the whole tree is looked through: every list and every chunk must be there, no folder may sit too deep, every name must be one that this system can hold as it is, and what would be made must fit within the limits of WriteOptions. Every file and folder is then created as new. Where two names of one folder would land on the same file, as "File" and "file" do on Windows and macOS, the second one is refused, and so is a name that the system keeps differently from how it was given. A name is never changed to make it fit: the error says which name it was.

A tree holds no links, and every folder written into is one this call created, so nothing is written outside dest. After an error, what was written so far stays.

func WriteToDiskWith

func WriteToDiskWith(store Store, root Root, dest string, options WriteOptions) error

WriteToDiskWith writes a tree out to disk as WriteToDisk does, within other limits.

Types

type Accepted

type Accepted struct {
	What Arrived
	// Kept says whether it was kept now. It is not when it was held
	// already.
	Kept bool
}

Accepted is what became of a frame that an intake accepted.

type Arrived

type Arrived struct {
	Kind ArrivedKind
	// Hash is the folder's, the file's or the chunk's. A record has none.
	Hash Hash
}

Arrived is what a frame turned out to be, once its hash was worked out: the record, or a list or a chunk with that hash.

type ArrivedKind

type ArrivedKind uint8

ArrivedKind is the kind of thing a frame turned out to be.

const (
	// ArrivedRecord is the tree's record.
	ArrivedRecord ArrivedKind = iota + 1
	// ArrivedFolderList is a folder's whole list.
	ArrivedFolderList
	// ArrivedFileList is a file's whole list.
	ArrivedFileList
	// ArrivedChunk is a chunk.
	ArrivedChunk
)

type Asked

type Asked struct {
	Request []byte
	Limit   int
}

Asked is a request as it is sent, with the longest frame that its asker takes in answer.

type BuildOptions

type BuildOptions struct {
	// Chunking is how files are chunked. The zero value chunks them by content,
	// as every tree outside a test should be.
	Chunking Chunking
	// Extra is extra data for the tree's record.
	Extra ExtraData
	// Timestamp writes the time of building into the record. Two builds of
	// the same folder then have different roots.
	Timestamp bool
	// Workers is how many goroutines build the tree. Zero is one for each
	// core. Files are chunked several at once, and a goroutine that has no
	// file of its own helps to hash the chunks of a long one.
	Workers int
	// Links is what is done with a link or a special file.
	Links Links
}

BuildOptions says how a tree is built from disk. The zero value chunks by content, on every core, and refuses links.

type Builder

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

Builder builds a tree part by part: files from their bytes, folders from their entries, and at the end the record.

Everything goes into the store as it is made. A chunk, a file or a folder that the store holds already is not written again.

A builder is used by one goroutine at a time.

func NewBuilder

func NewBuilder(store Store, chunking Chunking) *Builder

NewBuilder makes a builder that uses one goroutine for each core on a long file.

func (*Builder) Chunking

func (b *Builder) Chunking() Chunking

Chunking is how this builder chunks files.

func (*Builder) File

func (b *Builder) File(reader io.Reader) (Target, error)

File splits everything reader gives into chunks, keeps the chunks and the file's list, and says what the file is. The file is never held in memory whole: only a window of it, as Threads says.

func (*Builder) FileAt

func (b *Builder) FileAt(path string) (Target, error)

FileAt is the file at path on disk.

func (*Builder) FileFromBytes

func (b *Builder) FileFromBytes(content []byte) (Target, error)

FileFromBytes is the file with these bytes. They are chunked where they lie, and nothing is copied on the way to the store.

func (*Builder) Finish

func (b *Builder) Finish(top Target, extra ExtraData) (Root, error)

Finish writes the record of the tree that has top on top, and gives the tree's root. The store must hold every list under top.

The whole tree is checked before its record is kept: its sizes, how its files are chunked, and how deep its folders sit. The checks are the ones a tree goes through when it is taken in, and the totals in the record are what those checks counted.

func (*Builder) Folder

func (b *Builder) Folder(entries []Entry) (Target, error)

Folder keeps the folder with these entries, and says what it is. The entries may come in any order. Two entries with one name are an error.

func (*Builder) Threads

func (b *Builder) Threads(threads int) *Builder

Threads sets how many goroutines hash and keep the chunks of one file: 1 is the calling goroutine alone, and zero is one for each core. A file is always chunked on the calling goroutine. With help, a builder holds up to 64 MiB of a long file at a time; alone it holds up to 16 MiB. It gives the builder back.

type Change

type Change struct {
	Kind ChangeKind
	// Path is where in the tree the change is: names with "/" between
	// them.
	Path string
	// Old is the old tree's entry: for ChangeRemoved and ChangeChanged.
	Old Entry
	// New is the new tree's entry: for ChangeAdded and ChangeChanged.
	New Entry
}

Change is one difference between an old tree and a new one.

func Diff

func Diff(store Store, old, new Root) ([]Change, error)

Diff gives the differences between two trees that a store holds, sorted by path. Both trees must have a folder on top, or be the same tree.

A change is listed at every place it has. A tree keeps a folder once, however many places the folder has in it, so two small trees can differ at more places than any list holds. More than DefaultMaxChanges changes are an error, found as soon as there are that many.

func DiffWithin

func DiffWithin(store Store, old, new Root, most int) ([]Change, error)

DiffWithin gives the differences between two trees, as Diff gives them, where more than most changes are an error.

type ChangeKind

type ChangeKind uint8

ChangeKind is the kind of difference between an old tree and a new one.

const (
	// ChangeAdded: the new tree has this entry, and the old one has nothing
	// there. A folder that was added is one change: what is in it is not
	// listed.
	ChangeAdded ChangeKind = iota + 1
	// ChangeRemoved: the old tree has this entry, and the new one has
	// nothing there.
	ChangeRemoved
	// ChangeChanged: both trees have an entry here, and it differs: a
	// file's bytes, or an entry's extra data. A folder is listed here only
	// for its extra data. What differs inside it is listed by its own path.
	ChangeChanged
)

func (ChangeKind) String

func (k ChangeKind) String() string

type ChunkRef

type ChunkRef struct {
	Hash   Hash
	Length uint32
}

ChunkRef is one item of a file's list: a chunk's hash, and how many bytes it holds.

func ChunkRefOf

func ChunkRefOf(bytes []byte) (ChunkRef, error)

ChunkRefOf is the item for a chunk with these bytes. A chunk holds 1 byte to 8 MiB.

func (ChunkRef) Matches

func (p ChunkRef) Matches(bytes []byte) bool

Matches reports whether bytes are the chunk this item names: of its length, and with its hash.

type Chunking

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

Chunking is how a tree's files are split into chunks. The zero value is FastCDCV1.

func ChunkingFromTag

func ChunkingFromTag(tag []byte) (Chunking, error)

ChunkingFromTag reads what a record says. A size is written in digits with no zero in front, so each way of chunking has one spelling.

func FixedChunking

func FixedChunking(size uint32) (Chunking, error)

FixedChunking chunks at a fixed size, of 1 byte to 8 MiB: every chunk but a file's last holds exactly this many bytes. It is for tests.

func (Chunking) CheckCount

func (c Chunking) CheckCount(size, count uint64) error

CheckCount reports whether a file of size bytes can have count chunks.

func (Chunking) CheckLength

func (c Chunking) CheckLength(length uint32, isLast bool) error

CheckLength reports whether a chunk of length bytes fits, as a file's last chunk or as one before it.

func (Chunking) CountBounds

func (c Chunking) CountBounds(size uint64) (fewest, most uint64)

CountBounds gives the fewest and the most chunks that a file of size bytes can have.

func (Chunking) Cut

func (c Chunking) Cut(data []byte) [][]byte

Cut cuts data into chunks. The chunks are parts of data, in order, and nothing is copied. No bytes give no chunks.

A caller that holds a file in memory cuts it with this, so that every builder cuts the same bytes at the same places.

func (Chunking) Fixed

func (c Chunking) Fixed() (size uint32, fixed bool)

Fixed gives the size of a chunk when every chunk has one size.

func (Chunking) String

func (c Chunking) String() string

func (Chunking) Tag

func (c Chunking) Tag() string

Tag is how a record says this: "fastcdc-v1", or "fixed-" and the size.

type Entries

type Entries struct {
	// Total is how many entries the folder has in all.
	Total uint64
	// Start is the place of the first entry here.
	Start   uint64
	Entries []Entry
}

Entries is a branch of a folder's entries, as a peer showed it and as it was checked.

type Entry

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

Entry is one entry of a folder: a name, the file or folder under it, and extra data. An entry is made by NewEntry, or read from a folder's list: the zero value is not an entry.

func Lookup

func Lookup(store Store, root Root, path string) (Entry, bool, error)

Lookup gives what is at path in a tree: names with "/" between them, as in "weights/model.safetensors". Nothing is there when a name on the way is missing, or is a file. A path that leads through more folders than a tree may have is an error.

func NewEntry

func NewEntry(name string, target Target, extra ExtraData) (Entry, error)

NewEntry makes an entry. The name is checked as CheckName checks it.

func (Entry) EncodedLen

func (e Entry) EncodedLen() int

EncodedLen is how many bytes the entry takes in its folder's list.

func (Entry) Equal

func (e Entry) Equal(other Entry) bool

Equal reports whether two entries are the same in everything.

func (Entry) Extra

func (e Entry) Extra() ExtraData

Extra is the entry's extra data.

func (Entry) Hash

func (e Entry) Hash() Hash

Hash is the hash of the file or folder under the entry.

func (Entry) Kind

func (e Entry) Kind() Kind

Kind says whether a file or a folder is under the entry.

func (Entry) Name

func (e Entry) Name() string

Name is the entry's name.

func (Entry) Size

func (e Entry) Size() uint64

Size is how many bytes of file content are under the entry.

func (Entry) Target

func (e Entry) Target() Target

Target is the file or folder under the entry.

type EntryExtra

type EntryExtra func(path, name string, kind Kind) (ExtraData, error)

EntryExtra gives the extra data for one entry: its path on disk, its name, and whether it is a file or a folder.

type Error

type Error struct {

	// Operation is what was being done: for ErrIO and ErrStream.
	Operation string
	// Path is a path on disk: for ErrIO, ErrUnsupportedEntry and
	// ErrNonUTF8FileName.
	Path string
	// Detail says more: for ErrInvalidData, ErrInvalidRoot, ErrPeer and
	// ErrInvariant.
	Detail string
	// Name is the name in question: for ErrInvalidName and
	// ErrUnwritableName. It is cut to 80 characters.
	Name string
	// Reason is why a name is refused.
	Reason string
	// What is the thing in question: "a chunk", "a stored file's list".
	What string
	// Hash names the thing: for ErrCorrupt and ErrMissing.
	Hash Hash
	// Expected and Actual are sizes in bytes: for ErrSizeMismatch. For
	// ErrTotalsMismatch, Expected is what the record says and Actual is
	// what the tree has.
	Expected, Actual uint64
	// Limit and Requested: for ErrLimitExceeded. ErrTooDeep has Limit.
	Limit, Requested uint64
	// Err is the system's own error: for ErrIO and ErrStream.
	Err error
	// contains filtered or unexported fields
}

Error is every error this package returns. What went wrong is told by matching it with errors.Is against one of the Err values of this package, and the fields say more about it where they apply. Read them with errors.As.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is an *Error of the same kind, so that errors.Is(err, ErrCorrupt) matches every error of that kind.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap gives the system's own error, for the kinds that have one.

type ExtraData

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

ExtraData is a small set of named values, kept beside a name in a folder or in a tree's record. It holds at most 32 values. A value's name is 1 to 64 bytes of UTF-8, and a value is at most 1,024 bytes.

A set is never changed once it is made: With and Without give another set. The zero value is the empty set.

func (ExtraData) All

func (e ExtraData) All() iter.Seq2[string, []byte]

All gives the values, in the order of their names' bytes. Each value is a copy.

func (ExtraData) Equal

func (e ExtraData) Equal(other ExtraData) bool

Equal reports whether two sets hold the same values under the same names.

func (ExtraData) Get

func (e ExtraData) Get(name string) ([]byte, bool)

Get gives a copy of the value of this name.

func (ExtraData) Len

func (e ExtraData) Len() int

Len is how many values the set holds.

func (ExtraData) Text

func (e ExtraData) Text(name string) (string, bool)

Text gives a value as text, when it is UTF-8.

func (ExtraData) With

func (e ExtraData) With(name string, value []byte) (ExtraData, error)

With gives the same set with one more value, in place of any value of the same name.

func (ExtraData) WithText

func (e ExtraData) WithText(name, value string) (ExtraData, error)

WithText is With for a value that is text.

func (ExtraData) Without

func (e ExtraData) Without(name string) ExtraData

Without gives the same set without the value of this name.

type FileBranch

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

FileBranch is a branch of a file's list, with the nodes that stand for the rest of it.

func DecodeFileBranch

func DecodeFileBranch(bytes []byte) (*FileBranch, error)

DecodeFileBranch reads a branch of a file's list.

func (*FileBranch) Check

func (r *FileBranch) Check(file Target) (uint64, error)

Check checks the branch against the file it is said to be a part of, and gives the byte of the file at which the branch starts.

func (*FileBranch) CheckWithChunking

func (r *FileBranch) CheckWithChunking(file Target, chunking Chunking) (uint64, error)

CheckWithChunking is Check, with the chunks' lengths and their number held to a way of chunking too.

func (*FileBranch) Count

func (r *FileBranch) Count() uint64

Count is how many chunks the whole file is said to have.

func (*FileBranch) Encode

func (r *FileBranch) Encode() []byte

Encode gives the branch's bytes.

func (*FileBranch) Items

func (r *FileBranch) Items() []ChunkRef

Items gives the chunks shown. The slice is the branch's own, and must not be changed.

func (*FileBranch) Start

func (r *FileBranch) Start() uint64

Start is the number of the first chunk shown.

type FileList

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

FileList is a file: the list of its chunks, in the file's order.

func DecodeFileList

func DecodeFileList(bytes []byte) (*FileList, error)

DecodeFileList reads a whole list: 36 bytes for each chunk.

func FileOf

func FileOf(store Store, file Target) (*FileList, error)

FileOf gives the list of a file's chunks.

func NewFileList

func NewFileList(items []ChunkRef) (*FileList, error)

NewFileList is the file with these chunks, in this order. A chunk that occurs twice is listed twice. No chunks at all is the empty file.

func (*FileList) CheckChunking

func (l *FileList) CheckChunking(chunking Chunking) error

CheckChunking reports whether every chunk has a length that chunking gives.

func (*FileList) Count

func (l *FileList) Count() uint64

Count is how many chunks the file has.

func (*FileList) Encode

func (l *FileList) Encode() []byte

Encode gives the list's bytes.

func (*FileList) EncodedLen

func (l *FileList) EncodedLen() uint64

EncodedLen is how many bytes the list takes.

func (*FileList) Hash

func (l *FileList) Hash() Hash

Hash is the file's hash. It covers the chunks, their order, how many there are and the size, and nothing about where the file sits.

func (*FileList) Items

func (l *FileList) Items() []ChunkRef

Items gives the file's chunks, in order. The slice is the list's own, and must not be changed.

func (*FileList) Open

func (l *FileList) Open(start, end uint64) (*FileBranch, error)

Open shows chunks start up to, not including, end. This hashes the whole list each time: keep an OpenFile to show many parts.

func (*FileList) Size

func (l *FileList) Size() uint64

Size is how many bytes the file holds.

func (*FileList) Target

func (l *FileList) Target() Target

Target is the file as the thing above it names it.

type FolderBranch

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

FolderBranch is a branch of a folder's list, with the nodes that stand for the rest of it. A branch of an empty folder shows nothing, and carries nothing: the zero value is that branch.

func DecodeFolderBranch

func DecodeFolderBranch(bytes []byte) (*FolderBranch, error)

DecodeFolderBranch reads a branch of a folder's list.

func (*FolderBranch) Check

func (r *FolderBranch) Check(folder Target) error

Check checks the branch against the folder it is said to be a part of. Every entry shown is then an entry of that folder, at the place where a search for its name ends.

func (*FolderBranch) CheckName

func (r *FolderBranch) CheckName(folder Target, name string) (Entry, bool, error)

CheckName checks the branch as the answer to "what is under name in this folder". It gives the entry, or false when the folder has no entry of that name. Either answer is proven: the branch must show the one place where the name can be.

func (*FolderBranch) Count

func (r *FolderBranch) Count() uint64

Count is how many entries the whole folder is said to have.

func (*FolderBranch) Encode

func (r *FolderBranch) Encode() []byte

Encode gives the branch's bytes.

func (*FolderBranch) Entries

func (r *FolderBranch) Entries() []Entry

Entries gives the entries shown. The slice is the branch's own, and must not be changed.

func (*FolderBranch) Start

func (r *FolderBranch) Start() uint64

Start is the place of the first entry shown.

type FolderList

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

FolderList is a folder: the list of its entries, sorted by name, with no name twice.

func DecodeFolderList

func DecodeFolderList(bytes []byte) (*FolderList, error)

DecodeFolderList reads a whole list: its entries, one after another.

func FolderOf

func FolderOf(store Store, folder Target) (*FolderList, error)

FolderOf gives the entries of a folder.

func NewFolderList

func NewFolderList(entries []Entry) (*FolderList, error)

NewFolderList is the folder with these entries. They must be in the order of their names' bytes, with no name twice. No entries is the empty folder.

func (*FolderList) Count

func (l *FolderList) Count() uint64

Count is how many entries the folder has.

func (*FolderList) Encode

func (l *FolderList) Encode() []byte

Encode gives the list's bytes.

func (*FolderList) EncodedLen

func (l *FolderList) EncodedLen() uint64

EncodedLen is how many bytes the list takes.

func (*FolderList) Entries

func (l *FolderList) Entries() []Entry

Entries gives the folder's entries, in the order of their names. The slice is the list's own, and must not be changed.

func (*FolderList) Get

func (l *FolderList) Get(name string) (Entry, bool)

Get gives the entry with this name.

func (*FolderList) Hash

func (l *FolderList) Hash() Hash

Hash is the folder's hash. It covers every entry: its name, its kind, its size, its hash and its extra data. It does not cover a name for the folder itself.

func (*FolderList) Open

func (l *FolderList) Open(start, end uint64) (*FolderBranch, error)

Open shows entries start up to, not including, end. This hashes the whole list each time: keep an OpenFolder to show many parts.

func (*FolderList) OpenName

func (l *FolderList) OpenName(name string) (*FolderBranch, error)

OpenName shows the entry at the one place where name can be. It answers whether the folder has the name, whichever way the answer falls.

func (*FolderList) PlaceOf

func (l *FolderList) PlaceOf(name string) (uint64, bool)

PlaceOf gives the one place where name can be: that of the last entry whose name does not sort after it, or the first place. An empty folder has none.

func (*FolderList) Size

func (l *FolderList) Size() uint64

Size is how many bytes of file content are under the folder.

func (*FolderList) Target

func (l *FolderList) Target() Target

Target is the folder as the thing above it names it.

type Frame

type Frame struct {
	Kind FrameKind
	// Bytes is the whole frame for a record, the list for a file's or a
	// folder's whole list, and the chunk's bytes for a chunk. It is a part
	// of the bytes that were read, and not a copy.
	Bytes []byte
	// FileBranch: for FrameFileBranch.
	FileBranch *FileBranch
	// FolderBranch: for FrameFolderBranch.
	FolderBranch *FolderBranch
	// Have: for FrameHave.
	Have *HaveMap
	// Refusal: for FrameRefused.
	Refusal Refusal
}

Frame is a frame, read. Kind says what it is, and one of the other fields holds what it carries.

func DecodeFrame

func DecodeFrame(bytes []byte) (Frame, error)

DecodeFrame reads a frame. This says what kind of frame it is and that it is well formed. It does not say that the frame is true: that is checked against a hash the receiver trusts.

type FrameKind

type FrameKind uint8

FrameKind is the first byte of a frame, which says what the frame is.

const (
	// FrameRecord is a tree's record. The frame is the record itself, whose
	// first byte this is.
	FrameRecord FrameKind = recordMark
	// FrameFileList is a file's whole list.
	FrameFileList FrameKind = 0x21
	// FrameFolderList is a folder's whole list.
	FrameFolderList FrameKind = 0x22
	// FrameFileBranch is a branch of a file's list, with the nodes that stand for
	// the rest.
	FrameFileBranch FrameKind = 0x23
	// FrameFolderBranch is a branch of a folder's list, with the nodes that stand
	// for the rest.
	FrameFolderBranch FrameKind = 0x24
	// FrameChunk is a chunk's bytes.
	FrameChunk FrameKind = 0x25
	// FrameHave says which chunks of a file a peer holds.
	FrameHave FrameKind = 0x26
	// FrameRefused: the peer does not answer, and why.
	FrameRefused FrameKind = 0x27
)

type Hash

type Hash [32]byte

Hash is a SHA-256 hash: of a chunk's bytes, or of the bytes that describe a file, a folder or a tree.

func FileHash

func FileHash(count, size uint64, list Hash) Hash

FileHash is the hash of a file with count chunks and size bytes, whose list's tree has list on top.

func FolderHash

func FolderHash(count, size uint64, list Hash) Hash

FolderHash is the hash of a folder with count entries and size bytes of file content, whose list's tree has list on top.

func HashFromHex

func HashFromHex(text string) (Hash, error)

HashFromHex reads 64 lowercase hex digits.

func HashFromSlice

func HashFromSlice(bytes []byte) (Hash, error)

HashFromSlice reads a hash from exactly 32 bytes.

func HashOf

func HashOf(bytes []byte) Hash

HashOf is the SHA-256 of bytes.

func (Hash) Hex

func (h Hash) Hex() string

Hex is the hash as 64 lowercase hex digits.

func (Hash) IsZero

func (h Hash) IsZero() bool

IsZero reports whether the hash is all zero, which is what an empty list has in place of a hash.

func (Hash) String

func (h Hash) String() string

String is the hash as 64 lowercase hex digits.

type HaveMap

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

HaveMap says which chunks of a file a peer holds: one bit a chunk, in the file's order. A peer says this about itself, and nothing proves it.

func DecodeHaveMap

func DecodeHaveMap(bytes []byte) (*HaveMap, error)

DecodeHaveMap reads a map. It has one bit for each chunk and no more, and the bits left over in its last byte are zero.

func NewHaveMap

func NewHaveMap(count uint64) (*HaveMap, error)

NewHaveMap makes a map for a file of count chunks, with none held.

func (*HaveMap) Count

func (m *HaveMap) Count() uint64

Count is how many chunks the file has.

func (*HaveMap) Encode

func (m *HaveMap) Encode() []byte

Encode gives the map's bytes.

func (*HaveMap) Get

func (m *HaveMap) Get(index uint64) bool

Get reports whether chunk index is held. A chunk beyond the count is not.

func (*HaveMap) Held

func (m *HaveMap) Held() uint64

Held is how many chunks are held.

func (*HaveMap) Set

func (m *HaveMap) Set(index uint64) error

Set marks chunk index as held.

type Intake

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

Intake takes one tree into a store, checking every part as it arrives.

An intake is given frames in any order that puts parents first. What the store holds already is found when it is named, and is not asked for.

A frame that is refused at the door leaves the intake as it was: one that nothing names, one that is malformed, one that was not asked for. A list that is named and then fails a check shows that the tree itself is wrong. The list is not kept, and the intake is done: every later call gives ErrIntakeFailed. A new intake picks up from what the store holds.

What the store holds under a hash and is not what the hash says is damaged. An intake removes it from the store and wants it again, so a tree that was harmed where it is kept is made whole by fetching it once more. Nothing a peer sends can make an intake remove what is sound.

An intake is used by one goroutine at a time.

func NewIntake

func NewIntake(store Store, root Root) (*Intake, error)

NewIntake starts taking in the tree with this root. If the store holds the tree's record, everything else it holds of the tree is found now.

func (*Intake) Accept

func (i *Intake) Accept(frame []byte) (Accepted, error)

Accept takes one frame: a record, a whole list, or a chunk.

A frame is accepted when it is what a checked parent names. A frame that is named and held already is accepted and not kept again. Any other frame is an error: one that nothing names, one that is malformed, and one that does not have the size it was given.

func (*Intake) AcceptExpected

func (i *Intake) AcceptExpected(frame []byte, expected Arrived) (Accepted, error)

AcceptExpected takes one frame, which has to be exactly expected: the answer to what was asked. Anything else is refused, and nothing of it is kept.

func (*Intake) AnswerLimit

func (i *Intake) AnswerLimit(request Request) int

AnswerLimit is the longest frame that can answer one of this intake's requests. A peer that sends a longer one is not answering what was asked, and its frame need not be read: a file's list is no longer than the file's size allows, no list is longer than the record leaves room for, and a chunk is no longer than the tree's way of chunking allows.

func (*Intake) Expected

func (i *Intake) Expected(request Request) []Arrived

Expected gives what the answer to one of this intake's requests has to be: the frames, in order. A peer may send fewer chunks than were asked for, and never anything else.

func (*Intake) Finish

func (i *Intake) Finish() (*Summary, error)

Finish ends the intake. The tree must be whole: the record in, every list and every chunk held, no folder too deep, and the record's totals right.

func (*Intake) FrameLimit

func (i *Intake) FrameLimit() int

FrameLimit is the longest frame that a stream of this tree can hold, whatever comes next: for a reader of a stream that was not asked frame by frame, as a bundle is. Before the record it is the longest record. After it, it is the longest of a record, a chunk, and all the bytes of lists that the record gives the tree. What the store holds already may come too, and is passed over, so this does not shrink as lists come.

func (*Intake) Outstanding

func (i *Intake) Outstanding() int

Outstanding is how many lists and chunks are named and not held yet. The record counts as one while it is not in.

func (*Intake) Record

func (i *Intake) Record() *Record

Record is the tree's record, once it is in, and nil before. Its totals say how much the tree will take before any of it is taken, and an intake stops as soon as a tree turns out to hold more than its record says.

func (*Intake) Requests

func (i *Intake) Requests(limit int) []Request

Requests gives what to ask a peer for next: at most limit requests. The record comes first, then lists, then chunks by their file and their numbers. Nothing is asked for twice while it is still wanted, so the caller asks again only after the answers have come, or have failed to.

func (*Intake) Root

func (i *Intake) Root() Root

Root is the root of the tree that is taken in.

type Kind

type Kind uint8

Kind says whether an entry is a file or a folder.

const (
	// KindFile is a file: a list of chunks.
	KindFile Kind = 1
	// KindFolder is a folder: a list of entries.
	KindFolder Kind = 2
)

func (Kind) String

func (k Kind) String() string
type Links uint8

Links is what a builder does with a link or a special file that it finds in a folder. Neither is stored in a tree, and a link is never followed: it could lead out of the folder that is being built.

const (
	// LinksRefuse stops, and says which one it was.
	LinksRefuse Links = iota
	// LinksSkip leaves it out of the tree.
	LinksSkip
)

type MemoryStore

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

MemoryStore is a store in memory. The zero value is an empty store.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore makes an empty store in memory.

func (*MemoryStore) Bytes

func (s *MemoryStore) Bytes(kind Stored) uint64

Bytes is how many bytes the things of kind hold together.

func (*MemoryStore) Count

func (s *MemoryStore) Count(kind Stored) int

Count is how many things of kind are kept.

func (*MemoryStore) Get

func (s *MemoryStore) Get(kind Stored, hash Hash) ([]byte, bool, error)

Get gives what is kept under hash.

func (*MemoryStore) Has

func (s *MemoryStore) Has(kind Stored, hash Hash) (bool, error)

Has reports whether anything is kept under hash.

func (*MemoryStore) Hashes

func (s *MemoryStore) Hashes(kind Stored) []Hash

Hashes gives the hashes of the things of kind, in order.

func (*MemoryStore) Put

func (s *MemoryStore) Put(kind Stored, hash Hash, content []byte) error

Put keeps a copy of bytes under hash.

func (*MemoryStore) Remove

func (s *MemoryStore) Remove(kind Stored, hash Hash) error

Remove forgets what is kept under hash.

func (*MemoryStore) Size

func (s *MemoryStore) Size(kind Stored, hash Hash) (uint64, bool, error)

Size gives how many bytes are kept under hash.

type OpenFile

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

OpenFile is a file's list with its tree kept, for showing many parts of it, and for finding the chunks that hold a stretch of bytes.

func DecodeOpenFile

func DecodeOpenFile(bytes []byte) (*OpenFile, error)

DecodeOpenFile reads a whole list as DecodeFileList does, and keeps its tree. The list is hashed once for both.

func NewOpenFile

func NewOpenFile(list *FileList) (*OpenFile, error)

NewOpenFile keeps the tree of a list.

func (*OpenFile) ChunksFor

func (f *OpenFile) ChunksFor(offset, length uint64) (first, after uint64, err error)

ChunksFor gives the chunks that hold the length bytes from offset: the first one's number, and the number after the last one. The stretch must lie inside the file and hold at least one byte.

func (*OpenFile) List

func (f *OpenFile) List() *FileList

List is the file's list.

func (*OpenFile) Open

func (f *OpenFile) Open(start, end uint64) (*FileBranch, error)

Open shows chunks start up to, not including, end.

func (*OpenFile) OpenBytes

func (f *OpenFile) OpenBytes(offset, length uint64) (*FileBranch, error)

OpenBytes shows the chunks that hold the length bytes from offset.

func (*OpenFile) StartOf

func (f *OpenFile) StartOf(index uint64) (uint64, bool)

StartOf gives the byte at which chunk index starts. The count gives the size.

type OpenFolder

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

OpenFolder is a folder's list with its tree kept, for showing many parts of it.

func DecodeOpenFolder

func DecodeOpenFolder(bytes []byte) (*OpenFolder, error)

DecodeOpenFolder reads a whole list as DecodeFolderList does, and keeps its tree. The list is hashed once for both.

func NewOpenFolder

func NewOpenFolder(list *FolderList) (*OpenFolder, error)

NewOpenFolder keeps the tree of a list.

func (*OpenFolder) List

func (f *OpenFolder) List() *FolderList

List is the folder's list.

func (*OpenFolder) Open

func (f *OpenFolder) Open(start, end uint64) (*FolderBranch, error)

Open shows entries start up to, not including, end.

func (*OpenFolder) OpenName

func (f *OpenFolder) OpenName(name string) (*FolderBranch, error)

OpenName shows the entry at the one place where name can be.

type Peer

type Peer interface {
	// Ask sends one request, and hands each frame of the answer to onFrame
	// in the order the frames come. A frame is lent for the call only. An
	// error from onFrame ends the answer, and is what Ask returns.
	//
	// limit is the longest frame the asker takes in answer. A frame that
	// is longer is an error, and a peer on a connection refuses it by its
	// length, before any of it is read.
	Ask(request []byte, limit int, onFrame func(frame []byte) error) error
}

Peer is something that answers requests: a connection to another machine, or a Responder in this one. A peer is used by one goroutine at a time.

A peer that can send requests ahead of their answers may also have the method of PeerAskAll. It is used when it is there.

type PeerAskAll

type PeerAskAll interface {
	// AskAll sends several requests, each with its limit, and hands each
	// frame to onFrame with the place of the request that it answers.
	// Answers come in the order of the requests.
	AskAll(requests []Asked, onFrame func(place int, frame []byte) error) error
}

PeerAskAll is a peer that takes several requests at once.

type Record

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

Record is a tree's record: the file or folder on top, the tree's totals, and its extra data. The hash of the record is the tree's root.

func DecodeRecord

func DecodeRecord(bytes []byte) (*Record, error)

DecodeRecord reads a record.

func NewRecord

func NewRecord(top Target, totals Totals, chunking Chunking, extra ExtraData) (*Record, error)

NewRecord is the record of a tree with top on top. How the tree was chunked is written into the extra data, in place of anything the caller put under that name.

func RecordOf

func RecordOf(store Store, root Root) (*Record, error)

RecordOf gives the record of the tree with this root.

func (*Record) Chunking

func (r *Record) Chunking() Chunking

Chunking is how the tree's files were chunked.

func (*Record) Encode

func (r *Record) Encode() []byte

Encode gives the record's bytes.

func (*Record) Extra

func (r *Record) Extra() ExtraData

Extra is the record's extra data.

func (*Record) Root

func (r *Record) Root() Root

Root is the tree's root: the hash of the record.

func (*Record) Top

func (r *Record) Top() Target

Top is the file or folder on top of the tree.

func (*Record) Totals

func (r *Record) Totals() Totals

Totals gives the tree's totals.

type Refusal

type Refusal uint8

Refusal is why a peer does not answer.

const (
	// RefusalNotHeld: the peer does not hold what was asked for.
	RefusalNotHeld Refusal = 1
	// RefusalOutOfRange: what was asked for lies outside the list or the
	// file.
	RefusalOutOfRange Refusal = 2
)

func (Refusal) String

func (r Refusal) String() string

type Remote

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

Remote reads parts of one tree straight from a peer, with nothing kept.

It starts from a root that the caller trusts. Each thing it hands back was shown by the peer and checked against that root: an entry by its place in its folder, and bytes by their place in their file.

func OpenRemote

func OpenRemote(peer Peer, root Root) (*Remote, error)

OpenRemote asks the peer for the record of root, and checks it.

func (*Remote) Entries

func (r *Remote) Entries(folder Target, start uint64, count uint32) (*Entries, error)

Entries gives up to count entries of a folder, from place start. Fewer come back when the folder ends first, or when the peer gives fewer at a time. An empty folder gives none.

func (*Remote) Entry

func (r *Remote) Entry(folder Target, name string) (Entry, bool, error)

Entry gives what is under name in folder, or false when the folder has no such name. Either answer is proven by the one entry the peer shows.

func (*Remote) Have

func (r *Remote) Have(file Target) (*HaveMap, error)

Have gives which chunks of a file the peer says it holds, one bit a chunk. This is what the peer says about itself: nothing proves it, and a chunk it claims is still checked when it comes. Only the number of chunks is held to what the file's size allows.

func (*Remote) Lookup

func (r *Remote) Lookup(path string) (Entry, bool, error)

Lookup gives what is at path in the tree: names with "/" between them. One question is asked for each name on the way.

func (*Remote) Read

func (r *Remote) Read(file Target, offset, length uint64, out io.Writer) error

Read writes length bytes of a file, from byte offset, to out.

The peer shows the branch of the file's list that holds the stretch, and that proves each chunk's number and the byte it starts at. Then the chunks are asked for by their numbers, and each is checked against the list before any of its bytes is written. Nothing else of the file is taken.

func (*Remote) Record

func (r *Remote) Record() *Record

Record is the tree's record.

func (*Remote) Root

func (r *Remote) Root() Root

Root is the root of the tree that is read.

type Request

type Request struct {
	Kind RequestKind
	Hash Hash
	// Start and Count: for AskFolderBranch, AskFileBranch and AskChunks.
	Start uint64
	Count uint32
	// Name: for AskFolderName.
	Name string
	// Offset and Length: for AskFileBytes.
	Offset uint64
	Length uint64
}

Request is what a receiver asks a peer for. Kind says what, and Hash says of which thing: the root, the folder, the file or the chunk. The other fields are used by the kinds that their names are given with above.

func DecodeRequest

func DecodeRequest(bytes []byte) (Request, error)

DecodeRequest reads a request. One that asks for nothing, or for a name that no folder can hold, is refused here.

func RequestChunk

func RequestChunk(chunk Hash) Request

RequestChunk asks for one chunk, by its hash.

func RequestChunks

func RequestChunks(file Hash, start uint64, count uint32) Request

RequestChunks asks for count chunks of a file, from chunk number start.

func RequestFile

func RequestFile(file Hash) Request

RequestFile asks for all of a file's list.

func RequestFileBranch

func RequestFileBranch(file Hash, start uint64, count uint32) Request

RequestFileBranch asks for count items of a file's list, from chunk number start.

func RequestFileBytes

func RequestFileBytes(file Hash, offset, length uint64) Request

RequestFileBytes asks for the items of a file's list that hold length bytes from offset.

func RequestFolder

func RequestFolder(folder Hash) Request

RequestFolder asks for all of a folder's entries.

func RequestFolderBranch

func RequestFolderBranch(folder Hash, start uint64, count uint32) Request

RequestFolderBranch asks for count of a folder's entries, from place start.

func RequestFolderName

func RequestFolderName(folder Hash, name string) Request

RequestFolderName asks what is under one name in a folder, or that the name is not there.

func RequestHave

func RequestHave(file Hash) Request

RequestHave asks which chunks of a file the peer holds.

func RequestRecord

func RequestRecord(root Root) Request

RequestRecord asks for the record of a root.

func (Request) Encode

func (r Request) Encode() []byte

Encode gives the request's bytes.

type RequestKind

type RequestKind uint8

RequestKind is the first byte of a request, which says what is asked for.

const (
	// AskRecord asks for the record of a root.
	AskRecord RequestKind = 0x30
	// AskFolder asks for all of a folder's entries.
	AskFolder RequestKind = 0x31
	// AskFolderBranch asks for Count of a folder's entries, from place Start.
	AskFolderBranch RequestKind = 0x32
	// AskFolderName asks what is under one name in a folder, or that the
	// name is not there.
	AskFolderName RequestKind = 0x33
	// AskFile asks for all of a file's list.
	AskFile RequestKind = 0x34
	// AskFileBranch asks for Count items of a file's list, from chunk number
	// Start.
	AskFileBranch RequestKind = 0x35
	// AskFileBytes asks for the items of a file's list that hold Length
	// bytes from Offset.
	AskFileBytes RequestKind = 0x36
	// AskChunks asks for Count chunks of a file, from chunk number Start.
	AskChunks RequestKind = 0x37
	// AskChunk asks for one chunk, by its hash.
	AskChunk RequestKind = 0x38
	// AskHave asks which chunks of a file the peer holds.
	AskHave RequestKind = 0x39
)

type Responder

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

Responder answers requests from a store.

It answers for whatever the store holds, by hash. It gives what it has and says so when it has nothing: a receiver never has to trust it, because a receiver checks every answer.

One responder serves many goroutines at once.

func NewResponder

func NewResponder(store Store) *Responder

NewResponder makes a responder that answers from store.

func (*Responder) Answer

func (r *Responder) Answer(request []byte, onFrame func(frame []byte) error) error

Answer answers one request. Each frame of the answer is handed to onFrame, and is lent for the call only. A request that is malformed is an error. A request for something the store does not hold is answered with a refusal.

func (*Responder) Ask

func (r *Responder) Ask(request []byte, limit int, onFrame func(frame []byte) error) error

Ask answers one request as a peer does: a frame that is longer than the asker takes is an error.

func (*Responder) Have

func (r *Responder) Have(on bool) *Responder

Have sets whether a peer is told which chunks of a file are held here. Telling takes a look into the store for every chunk of the file, so a responder that serves strangers may leave it off. It then answers such a request as it does for a file it does not hold. It is set before the responder is used, and gives the responder back.

func (*Responder) Recent

func (r *Responder) Recent(items uint64) *Responder

Recent sets how many items of lists are kept between requests, for each of the three kinds: files' lists, files' trees and folders' trees. A list that is not kept is read from the store and hashed again when it is next asked about, which takes a pass over the whole of it. An item kept costs some tens of bytes for a file and some hundreds for a folder. The list that was used last is kept whatever its length. It is set before the responder is used, and gives the responder back.

type Root

type Root Hash

Root is the root of a tree: the hash of its record. It is what a tree is known by.

Written out, a root is a CID that begins "bafkrei".

func Build

func Build(store Store, path string, options BuildOptions) (Root, error)

Build builds the tree of the folder or the file at path into store, and gives its root.

A folder's own name is not part of its tree, so the same folder gives the same root wherever it is and whatever it is called. Entries have no extra data: BuildWith adds some.

func BuildWith

func BuildWith(store Store, path string, options BuildOptions, entryExtra EntryExtra) (Root, error)

BuildWith builds a tree as Build does, and asks entryExtra for the extra data of every entry.

func ParseRoot

func ParseRoot(text string) (Root, error)

ParseRoot reads a root from its text. Only the one way of writing a root is read: any other spelling of the same bytes is refused.

func RootOfRecord

func RootOfRecord(record []byte) Root

RootOfRecord is the root of the tree whose record is record.

func (Root) Hash

func (r Root) Hash() Hash

Hash is the hash that the root is.

func (Root) String

func (r Root) String() string

String is the root as text.

type Store

type Store interface {
	// Put keeps bytes under hash. Keeping what is kept already changes
	// nothing. The bytes are lent for the call only: a store that keeps
	// them keeps a copy.
	Put(kind Stored, hash Hash, bytes []byte) error
	// Get gives what is kept under hash, and false if nothing is. The
	// bytes it gives are never changed afterwards, by the store or by the
	// caller.
	Get(kind Stored, hash Hash) ([]byte, bool, error)
	// Remove forgets what is kept under hash.
	Remove(kind Stored, hash Hash) error
}

Store is a place that keeps bytes under hashes. Its methods are called from many goroutines at once.

A store that can answer without reading the bytes may also have the methods of StoreHas and StoreSize, and one that can lend what it keeps the method of StoreLend. They are used when they are there. A store on disk should have Size at the least: without it, seeing whether a chunk is there takes a read of the whole chunk. It should have Lend too.

type StoreHas

type StoreHas interface {
	// Has reports whether anything is kept under hash.
	Has(kind Stored, hash Hash) (bool, error)
}

StoreHas is a store that says whether it keeps a thing without reading it. A store that has Size and not Has is asked for the size instead.

type StoreLend

type StoreLend interface {
	// Lend hands what is kept under hash to with, and reports whether
	// anything is kept: with is called once if it is, and not at all if it
	// is not. The bytes are lent for that call only, and an error from with
	// is what Lend returns.
	Lend(kind Stored, hash Hash, with func(bytes []byte) error) (bool, error)
}

StoreLend is a store that lends what it keeps. The library reads a tree's chunks this way when a store has it. A store on disk should: it can read into memory that it uses again, where Get gives memory of its own for every chunk, which costs some systems more than the reading does.

type StoreSize

type StoreSize interface {
	// Size gives how many bytes are kept under hash, and false if nothing
	// is.
	Size(kind Stored, hash Hash) (uint64, bool, error)
}

StoreSize is a store that says how long a thing is without reading it.

type Stored

type Stored uint8

Stored is one of the kinds of thing a store keeps.

const (
	// StoredChunk is a chunk's bytes, under the SHA-256 of them.
	StoredChunk Stored = iota + 1
	// StoredFileList is a file's whole list, under the file's hash.
	StoredFileList
	// StoredFolderList is a folder's whole list, under the folder's hash.
	StoredFolderList
	// StoredRecord is a tree's record, under the tree's root.
	StoredRecord
)

func (Stored) String

func (s Stored) String() string

type StreamPeer

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

StreamPeer is a peer at the other end of a connection, where Serve answers.

An answer that is left half read, because a frame of it was refused, leaves the connection where nobody knows what comes next. Nothing more is asked on it then: open a new one.

func NewStreamPeer

func NewStreamPeer(input io.Reader, output io.Writer) *StreamPeer

NewStreamPeer makes a peer of a connection: input is what the other end sends, and output is what it reads. If output has a Flush method, as a buffered writer has, it is called once requests are written.

Requests are sent ahead of their answers, up to RequestsAheadBytes of them, and the connection has to hold that much on the way: see Ahead.

func (*StreamPeer) Ahead

func (p *StreamPeer) Ahead(bytes int) *StreamPeer

Ahead sets how many bytes of requests are sent ahead of their answers: RequestsAheadBytes unless it is set, and never more than that. It is set before the peer is used, and gives the peer back.

Requests that are sent ahead save a wait for each answer, which is most of the time a fetch of many small files takes on a slow connection. While the other end answers the first of them, the rest have to wait somewhere. A connection over a network holds them. Go's net.Pipe and io.Pipe hold nothing, and hand a write over only as the other end reads it: there Serve holds them, which reads requests through a buffer of its own. So a StreamPeer and a Serve do not wait for each other on any of these.

Zero sends one request at a time, and waits for its answer. It is for an answerer of another make, which reads one request at a time from a connection that holds nothing. With requests sent ahead there, this end would wait to send its next request while the other end waits to send its first answer, for ever.

func (*StreamPeer) Ask

func (p *StreamPeer) Ask(request []byte, limit int, onFrame func(frame []byte) error) error

Ask sends one request, and reads its answer.

func (*StreamPeer) AskAll

func (p *StreamPeer) AskAll(requests []Asked, onFrame func(place int, frame []byte) error) error

AskAll sends requests ahead of their answers, as far as Ahead lets it, and reads the answers in the order of the requests.

A request that no answerer takes, because it is empty or longer than a request may be, is an error before anything is sent.

type Summary

type Summary struct {
	Record *Record
	// Folders is how many different folders the tree has.
	Folders uint64
	// Files is how many different files the tree has.
	Files uint64
}

Summary is a tree that is whole and checked.

func Fetch

func Fetch(store Store, root Root, peer Peer) (*Summary, error)

Fetch takes the whole tree with this root from a peer into a store.

It goes from the top down: the record, then each folder's entries and each file's list, then the chunks, by their file and their numbers in it. Whatever the store holds already is skipped by its hash, be it a chunk, a file or a whole folder, and wherever it came from. Every answer has to be exactly what was asked for, and is checked before it is kept.

A fetch that fails can be started again: it goes on from what the store holds.

func Import

func Import(store Store, root Root, from io.Reader) (*Summary, error)

Import reads a bundle that Export wrote, and takes the tree with this root from it into a store. Every frame goes through the same checks as a frame from a peer, and the tree must be whole when the stream ends. A frame for something the store holds already is passed over. A frame that nothing in the tree names is an error.

func Verify

func Verify(store Store, root Root) (*Summary, error)

Verify checks a whole tree that a store holds: every list, every chunk's bytes, the depth of its folders and the totals in its record. It is the same set of checks that a tree goes through when it is taken in.

func VerifyWith

func VerifyWith(store Store, root Root, options VerifyOptions) (*Summary, error)

VerifyWith checks a whole tree that a store holds, with more checks switched on.

The lists are checked first. Then every chunk is hashed again, several at once, and last, when that is asked for, every file is chunked again.

type Target

type Target struct {
	Kind Kind
	Hash Hash
	Size uint64
}

Target is a file or a folder as the thing above it names it: its kind, its hash, and how many bytes of file content it holds.

type Totals

type Totals struct {
	// Chunks is how many different chunks the tree has.
	Chunks uint64
	// ChunkBytes is how many bytes those chunks hold.
	ChunkBytes uint64
	// ListBytes is how many bytes the lists of its different files and
	// folders take.
	ListBytes uint64
}

Totals is what a tree says about itself as a whole: how much a store has to keep for it. Each counts a thing once, however often the tree uses it.

type VerifyOptions

type VerifyOptions struct {
	// Rechunk also chunks every file's bytes again, and refuses a file whose
	// list is not the one the chunker gives. With this, the same bytes
	// always have the same file hash. It costs one more pass over the
	// bytes.
	Rechunk bool
	// DiscardDamaged removes from the store what is damaged there: a chunk,
	// a list or a record whose bytes are not what its hash says. The check
	// then ends with one of them as missing, and a fetch of the tree brings
	// them all again. Without this the check stops at a damaged thing and
	// names it, and the store is left as it is.
	DiscardDamaged bool
	// Workers is how many chunks are hashed at once. Zero is one for each
	// core.
	Workers int
}

VerifyOptions says how a held tree is checked, beyond what is always checked. The zero value checks what is always checked, on every core.

type WorkerPanic

type WorkerPanic struct {
	Value any
	Stack []byte
}

WorkerPanic is what a panic on one of this library's own goroutines is raised again as, on the goroutine of the caller. Value is what was panicked with, and Stack is where.

A panic on a goroutine that nobody waits for ends the whole program, and no caller can catch it. So this library catches a panic where it starts work, lets the other work end, and raises it again where the caller can see it: nothing waits for a goroutine that is gone, and a panic reaches the caller as a panic.

func (*WorkerPanic) Error

func (p *WorkerPanic) Error() string

func (*WorkerPanic) Unwrap

func (p *WorkerPanic) Unwrap() error

Unwrap gives the value that was panicked with, when it is an error.

type WriteOptions

type WriteOptions struct {
	// MaxEntries is the most files and folders that may be made, the top
	// one counted. Zero is DefaultMaxWrittenEntries.
	MaxEntries uint64
	// MaxBytes is the most bytes that may be written. A tree's record says
	// how many it takes: the size of what is on top, with a file or a chunk
	// that the tree uses twice counted twice. Zero is as many bytes as the
	// tree has.
	MaxBytes uint64
}

WriteOptions says how far writing a tree out may go.

A tree keeps each folder once, however many places the folder has in it, and writing it out makes the folder at every one of those places. So a tree of a few small lists can stand for more folders than any disk holds: a folder with two names for one folder, a hundred deep. Both limits are held before anything is written.

Directories

Path Synopsis
examples
proofsizes command
Proofsizes shows how small a Merkle branch is beside the list it stands in for.
Proofsizes shows how small a Merkle branch is beside the list it stands in for.
roundtrip command
Roundtrip takes a tree its whole way round, with a store on disk.
Roundtrip takes a tree its whole way round, with a store on disk.
speed command
Speed measures how fast the parts of building and checking a tree are, on one file held in memory, so that no disk is in the way.
Speed measures how fast the parts of building and checking a tree are, on one file held in memory, so that no disk is in the way.

Jump to

Keyboard shortcuts

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