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 ¶
- Constants
- Variables
- func CheckName(name string) error
- func ChunkFrame(chunk []byte) []byte
- func Export(store Store, root Root, out io.Writer) error
- func FileBranchFrame(branch *FileBranch) []byte
- func FileListFrame(list []byte) []byte
- func FolderBranchFrame(branch *FolderBranch) []byte
- func FolderListFrame(list []byte) []byte
- func HaveFrame(held *HaveMap) []byte
- func ReadFile(store Store, file Target, out io.Writer) error
- func ReadFileBytes(store Store, file Target) ([]byte, error)
- func ReadFrame(input io.Reader, limit int) ([]byte, error)
- func ReadOpen(store Store, file *OpenFile, offset, length uint64, out io.Writer) error
- func ReadRange(store Store, file Target, offset, length uint64, out io.Writer) error
- func RefusedFrame(why Refusal) []byte
- func Serve(store Store, from io.Reader, output io.Writer) error
- func Unwritable(name string) (reason string, unwritable bool)
- func UnwritableOnWindows(name string) (reason string, unwritable bool)
- func WriteFrame(out io.Writer, frame []byte) error
- func WriteToDisk(store Store, root Root, dest string) error
- func WriteToDiskWith(store Store, root Root, dest string, options WriteOptions) error
- type Accepted
- type Arrived
- type ArrivedKind
- type Asked
- type BuildOptions
- type Builder
- func (b *Builder) Chunking() Chunking
- func (b *Builder) File(reader io.Reader) (Target, error)
- func (b *Builder) FileAt(path string) (Target, error)
- func (b *Builder) FileFromBytes(content []byte) (Target, error)
- func (b *Builder) Finish(top Target, extra ExtraData) (Root, error)
- func (b *Builder) Folder(entries []Entry) (Target, error)
- func (b *Builder) Threads(threads int) *Builder
- type Change
- type ChangeKind
- type ChunkRef
- type Chunking
- func (c Chunking) CheckCount(size, count uint64) error
- func (c Chunking) CheckLength(length uint32, isLast bool) error
- func (c Chunking) CountBounds(size uint64) (fewest, most uint64)
- func (c Chunking) Cut(data []byte) [][]byte
- func (c Chunking) Fixed() (size uint32, fixed bool)
- func (c Chunking) String() string
- func (c Chunking) Tag() string
- type Entries
- type Entry
- type EntryExtra
- type Error
- type ExtraData
- func (e ExtraData) All() iter.Seq2[string, []byte]
- func (e ExtraData) Equal(other ExtraData) bool
- func (e ExtraData) Get(name string) ([]byte, bool)
- func (e ExtraData) Len() int
- func (e ExtraData) Text(name string) (string, bool)
- func (e ExtraData) With(name string, value []byte) (ExtraData, error)
- func (e ExtraData) WithText(name, value string) (ExtraData, error)
- func (e ExtraData) Without(name string) ExtraData
- type FileBranch
- type FileList
- func (l *FileList) CheckChunking(chunking Chunking) error
- func (l *FileList) Count() uint64
- func (l *FileList) Encode() []byte
- func (l *FileList) EncodedLen() uint64
- func (l *FileList) Hash() Hash
- func (l *FileList) Items() []ChunkRef
- func (l *FileList) Open(start, end uint64) (*FileBranch, error)
- func (l *FileList) Size() uint64
- func (l *FileList) Target() Target
- type FolderBranch
- type FolderList
- func (l *FolderList) Count() uint64
- func (l *FolderList) Encode() []byte
- func (l *FolderList) EncodedLen() uint64
- func (l *FolderList) Entries() []Entry
- func (l *FolderList) Get(name string) (Entry, bool)
- func (l *FolderList) Hash() Hash
- func (l *FolderList) Open(start, end uint64) (*FolderBranch, error)
- func (l *FolderList) OpenName(name string) (*FolderBranch, error)
- func (l *FolderList) PlaceOf(name string) (uint64, bool)
- func (l *FolderList) Size() uint64
- func (l *FolderList) Target() Target
- type Frame
- type FrameKind
- type Hash
- type HaveMap
- type Intake
- func (i *Intake) Accept(frame []byte) (Accepted, error)
- func (i *Intake) AcceptExpected(frame []byte, expected Arrived) (Accepted, error)
- func (i *Intake) AnswerLimit(request Request) int
- func (i *Intake) Expected(request Request) []Arrived
- func (i *Intake) Finish() (*Summary, error)
- func (i *Intake) FrameLimit() int
- func (i *Intake) Outstanding() int
- func (i *Intake) Record() *Record
- func (i *Intake) Requests(limit int) []Request
- func (i *Intake) Root() Root
- type Kind
- type Links
- type MemoryStore
- func (s *MemoryStore) Bytes(kind Stored) uint64
- func (s *MemoryStore) Count(kind Stored) int
- func (s *MemoryStore) Get(kind Stored, hash Hash) ([]byte, bool, error)
- func (s *MemoryStore) Has(kind Stored, hash Hash) (bool, error)
- func (s *MemoryStore) Hashes(kind Stored) []Hash
- func (s *MemoryStore) Put(kind Stored, hash Hash, content []byte) error
- func (s *MemoryStore) Remove(kind Stored, hash Hash) error
- func (s *MemoryStore) Size(kind Stored, hash Hash) (uint64, bool, error)
- type OpenFile
- func (f *OpenFile) ChunksFor(offset, length uint64) (first, after uint64, err error)
- func (f *OpenFile) List() *FileList
- func (f *OpenFile) Open(start, end uint64) (*FileBranch, error)
- func (f *OpenFile) OpenBytes(offset, length uint64) (*FileBranch, error)
- func (f *OpenFile) StartOf(index uint64) (uint64, bool)
- type OpenFolder
- type Peer
- type PeerAskAll
- type Record
- type Refusal
- type Remote
- func (r *Remote) Entries(folder Target, start uint64, count uint32) (*Entries, error)
- func (r *Remote) Entry(folder Target, name string) (Entry, bool, error)
- func (r *Remote) Have(file Target) (*HaveMap, error)
- func (r *Remote) Lookup(path string) (Entry, bool, error)
- func (r *Remote) Read(file Target, offset, length uint64, out io.Writer) error
- func (r *Remote) Record() *Record
- func (r *Remote) Root() Root
- type Request
- func DecodeRequest(bytes []byte) (Request, error)
- func RequestChunk(chunk Hash) Request
- func RequestChunks(file Hash, start uint64, count uint32) Request
- func RequestFile(file Hash) Request
- func RequestFileBranch(file Hash, start uint64, count uint32) Request
- func RequestFileBytes(file Hash, offset, length uint64) Request
- func RequestFolder(folder Hash) Request
- func RequestFolderBranch(folder Hash, start uint64, count uint32) Request
- func RequestFolderName(folder Hash, name string) Request
- func RequestHave(file Hash) Request
- func RequestRecord(root Root) Request
- type RequestKind
- type Responder
- type Root
- type Store
- type StoreHas
- type StoreLend
- type StoreSize
- type Stored
- type StreamPeer
- type Summary
- type Target
- type Totals
- type VerifyOptions
- type WorkerPanic
- type WriteOptions
Examples ¶
Constants ¶
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.
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" )
const BundleMagic = "SCIONIC\x01"
BundleMagic is what starts a bundle: a tree written out as one stream of frames.
const DefaultMaxChanges = 1_000_000
DefaultMaxChanges is the most changes that Diff lists.
const DefaultMaxWrittenEntries uint64 = 1_000_000
DefaultMaxWrittenEntries is the most files and folders that WriteToDisk makes unless it is told otherwise.
const MaxListItems uint64 = 1 << 40
MaxListItems is the most items a list may hold. It bounds how deep any walk goes.
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.
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.
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 ¶
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.
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 ¶
CheckName checks a name: 1 to 255 bytes of UTF-8, no "/", no zero byte, and not "." or "..".
func Export ¶
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 ¶
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 ¶
FolderListFrame is the frame for a folder's whole list.
func ReadFileBytes ¶
ReadFileBytes gives a file's bytes, in memory. Room for them is taken only once every chunk of the file is found.
func ReadFrame ¶
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 ¶
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 ¶
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 ¶
RefusedFrame is the frame that says why a peer does not answer.
func Serve ¶
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 ¶
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 ¶
UnwritableOnWindows says why Windows cannot hold a name as it is, if it cannot.
func WriteFrame ¶
WriteFrame writes one frame to a stream: its length as four bytes, then the frame.
func WriteToDisk ¶
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 ¶
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 ¶
NewBuilder makes a builder that uses one goroutine for each core on a long file.
func (*Builder) File ¶
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) FileFromBytes ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
ChunkRef is one item of a file's list: a chunk's hash, and how many bytes it holds.
func ChunkRefOf ¶
ChunkRefOf is the item for a chunk with these bytes. A chunk holds 1 byte to 8 MiB.
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 ¶
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 ¶
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 ¶
CheckCount reports whether a file of size bytes can have count chunks.
func (Chunking) CheckLength ¶
CheckLength reports whether a chunk of length bytes fits, as a file's last chunk or as one before it.
func (Chunking) CountBounds ¶
CountBounds gives the fewest and the most chunks that a file of size bytes can have.
func (Chunking) Cut ¶
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.
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 ¶
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 (Entry) EncodedLen ¶
EncodedLen is how many bytes the entry takes in its folder's list.
type EntryExtra ¶
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.
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 ¶
All gives the values, in the order of their names' bytes. Each value is a copy.
func (ExtraData) With ¶
With gives the same set with one more value, in place of any value of the same 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) 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 ¶
DecodeFileList reads a whole list: 36 bytes for each chunk.
func NewFileList ¶
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 ¶
CheckChunking reports whether every chunk has a length that chunking gives.
func (*FileList) EncodedLen ¶
EncodedLen is how many bytes the list takes.
func (*FileList) 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 ¶
Items gives the file's chunks, in order. The slice is the list's own, and must not be changed.
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 ¶
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) 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 ¶
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 ¶
FileHash is the hash of a file with count chunks and size bytes, whose list's tree has list on top.
func FolderHash ¶
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 ¶
HashFromHex reads 64 lowercase hex digits.
func HashFromSlice ¶
HashFromSlice reads a hash from exactly 32 bytes.
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 ¶
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 ¶
NewHaveMap makes a map for a file of count chunks, with none 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type Links ¶
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.
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) 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.
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 ¶
DecodeOpenFile reads a whole list as DecodeFileList does, and keeps its tree. The list is hashed once for both.
func NewOpenFile ¶
NewOpenFile keeps the tree of a list.
func (*OpenFile) ChunksFor ¶
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) Open ¶
func (f *OpenFile) Open(start, end uint64) (*FileBranch, error)
Open shows chunks start up to, not including, end.
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) 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 NewRecord ¶
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.
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 ¶
OpenRemote asks the peer for the record of root, and checks it.
func (*Remote) Entries ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
DecodeRequest reads a request. One that asks for nothing, or for a name that no folder can hold, is refused here.
func RequestChunk ¶
RequestChunk asks for one chunk, by its hash.
func RequestChunks ¶
RequestChunks asks for count chunks of a file, from chunk number start.
func RequestFileBranch ¶
RequestFileBranch asks for count items of a file's list, from chunk number start.
func RequestFileBytes ¶
RequestFileBytes asks for the items of a file's list that hold length bytes from offset.
func RequestFolder ¶
RequestFolder asks for all of a folder's entries.
func RequestFolderBranch ¶
RequestFolderBranch asks for count of a folder's entries, from place start.
func RequestFolderName ¶
RequestFolderName asks what is under one name in a folder, or that the name is not there.
func RequestHave ¶
RequestHave asks which chunks of a file the peer holds.
func RequestRecord ¶
RequestRecord asks for the record of a root.
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 ¶
NewResponder makes a responder that answers from store.
func (*Responder) Answer ¶
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 ¶
Ask answers one request as a peer does: a frame that is longer than the asker takes is an error.
func (*Responder) Have ¶
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 ¶
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 ¶
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 ¶
RootOfRecord is the root of the tree whose record is record.
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 )
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
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. |


