blobs

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 25 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.

Documentation

Overview

Package blobs defines Rust-compatible iroh blob tickets, blob identifiers, and transfer helpers.

A blob ticket combines a provider endpoint address with a BLAKE3 hash and the blob format to request. Its string form is the "blob" kind prefix followed by RFC 4648 base32 without padding, matching Rust's iroh-blobs ticket format. The transfer helpers implement the raw full-blob subset of the iroh-blobs provider protocol.

The Go API is not stable before v1 and may change in any v0 release; the wire format tracks pinned upstream iroh-blobs releases and does not.

Example
package main

import (
	"fmt"

	"github.com/tmc/go-iroh/blobs"
	"github.com/tmc/go-iroh/key"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	id, _ := key.ParseEndpointID("ae58ff8833241ac82d6ff7611046ed67b5072d142c588d0063e942d9a75502b6")
	hash, _ := blobs.ParseHash("0b84d358e4c8be6c38626b2182ff575818ba6bd3f4b90464994be14cb354a072")
	ticket := blobs.NewTicket(netaddr.NewEndpointAddr(id), hash, blobs.Raw)

	parsed, _ := blobs.ParseTicket(ticket.String())
	fmt.Println(parsed.Hash() == hash, parsed.Format())
}
Output:
true Raw

Index

Examples

Constants

View Source
const (
	// ChunkSize is the BLAKE3 chunk size used by iroh-blobs.
	ChunkSize = 1024
	// BlockSize is the iroh-blobs BAO block size.
	BlockSize = 16 * ChunkSize
	// MaxSingleLeafSize is the largest payload accepted by the single-leaf
	// BAO helpers.
	MaxSingleLeafSize = BlockSize
)
View Source
const ALPN = "/iroh-bytes/4"

ALPN is the application protocol name for Rust iroh-blobs.

View Source
const HashSize = 32

HashSize is the size of a blob hash, in bytes.

View Source
const (
	// TicketKind is the string prefix for blob tickets.
	TicketKind = "blob"
)

Variables

View Source
var (
	// ErrInvalidBlob is returned when a full-range BAO response is malformed
	// or fails hash verification.
	ErrInvalidBlob = errors.New("blobs: invalid blob")
	// ErrSingleLeafTooLarge is returned when data cannot be represented as a
	// single BAO leaf.
	ErrSingleLeafTooLarge = errors.New("blobs: single leaf too large")
	// ErrInvalidSingleLeaf is returned when a single-leaf BAO response is
	// malformed or fails hash verification.
	ErrInvalidSingleLeaf = errors.New("blobs: invalid single leaf")
)
View Source
var (
	// ErrBlobNotFound is returned when a requested blob is not in a store.
	ErrBlobNotFound = errors.New("blobs: blob not found")
	// ErrStoreReadOnly is returned when a store cannot accept new blobs.
	ErrStoreReadOnly = errors.New("blobs: store cannot add content")
	// ErrUnsupportedRequest is returned when a request is outside the
	// raw-blob transfer subset.
	ErrUnsupportedRequest = errors.New("blobs: unsupported request")
)
View Source
var EmptyHash = Hash{
	175, 19, 73, 185, 245, 249, 161, 166, 160, 64, 77, 234, 54, 220, 201, 73,
	155, 203, 37, 201, 173, 193, 18, 183, 204, 154, 147, 202, 228, 31, 50, 98,
}

EmptyHash is the BLAKE3 hash of the empty byte string.

Functions

func DecodeBlob

func DecodeBlob(expected Hash, encoded []byte) ([]byte, error)

DecodeBlob validates and decodes a Rust-compatible full-range BAO response.

func DecodeBlobRange

func DecodeBlobRange(expected Hash, encoded []byte, offset, length uint64) ([]byte, error)

DecodeBlobRange validates and decodes a Rust-compatible BAO slice response.

func DecodeBlobRangeReader

func DecodeBlobRangeReader(expected Hash, r io.Reader, offset, length uint64) ([]byte, error)

DecodeBlobRangeReader validates and decodes one Rust-compatible BAO slice response from r.

func DecodeBlobRangeToWriter

func DecodeBlobRangeToWriter(expected Hash, r io.Reader, offset, length uint64, w io.Writer) error

DecodeBlobRangeToWriter validates a Rust-compatible BAO slice proof against expected and streams [offset, offset+length) to w.

func DecodeBlobReader

func DecodeBlobReader(expected Hash, r io.Reader) ([]byte, error)

DecodeBlobReader validates and decodes one Rust-compatible full-range BAO response from r.

func DecodeBlobToWriter

func DecodeBlobToWriter(expected Hash, r io.Reader, w io.Writer) error

DecodeBlobToWriter validates one Rust-compatible full-range BAO response from r and streams the decoded blob to w.

func DecodeSingleLeaf

func DecodeSingleLeaf(expected Hash, encoded []byte) ([]byte, error)

DecodeSingleLeaf validates and decodes a Rust-compatible single-leaf BAO response.

It accepts only full-range responses for blobs up to one iroh-blobs BAO block. Larger blobs require parent hashes and the full BAO tree decoder.

func DownloadBlob

func DownloadBlob(ctx context.Context, s BidiStream, hash Hash, w io.Writer) error

DownloadBlob requests and validates one full-range raw blob from s.

DownloadBlob sends GetBlob, closes its send side, and streams the verified BAO response into w. It returns an error if the response hash does not match hash or if the peer sends trailing bytes after the blob.

func DownloadBlobParallel

func DownloadBlobParallel(ctx context.Context, open RangeOpener, hash Hash, w io.WriterAt, opts ParallelDownloadOptions) error

DownloadBlobParallel downloads hash as verified ranges in parallel.

Each range is verified against hash before it is written to w. RangeSize must be a positive multiple of ChunkSize. Retries is the number of retries after the first attempt for each range.

func DownloadBlobRange

func DownloadBlobRange(ctx context.Context, s BidiStream, hash Hash, offset, length uint64, w io.Writer) error

DownloadBlobRange requests and validates [offset, offset+length) from hash.

The request is encoded as iroh-blobs chunk ranges, so offset must start on a ChunkSize boundary. The final range may end inside the blob's last chunk.

func EncodeGetManyRequestBytes

func EncodeGetManyRequestBytes(r GetManyRequest) []byte

EncodeGetManyRequestBytes encodes r as a full Request::GetMany message.

func EncodeGetRequestBytes

func EncodeGetRequestBytes(r GetRequest) []byte

EncodeGetRequestBytes encodes r as a full Request::Get message.

func EncodeObserveRequestBytes

func EncodeObserveRequestBytes(r ObserveRequest) []byte

EncodeObserveRequestBytes encodes r as a full Request::Observe message.

func EncodeRequestBytes

func EncodeRequestBytes(req Request) ([]byte, error)

EncodeRequestBytes encodes req as Rust-compatible postcard bytes.

func ExtractBlobRange

func ExtractBlobRange(w io.Writer, data, outboard io.Reader, offset, length uint64) error

ExtractBlobRange writes a Rust-compatible BAO slice proof for [offset, offset+length) from data and outboard.

func GetBlobBytes

func GetBlobBytes(ctx context.Context, s BidiStream, hash Hash) ([]byte, error)

GetBlobBytes requests and validates one full-range raw blob from s.

GetBlobBytes sends GetBlob, closes its send side, reads the response, and verifies the returned BAO body against hash.

func GetBlobRangeBytes

func GetBlobRangeBytes(ctx context.Context, s BidiStream, hash Hash, ranges ChunkRanges, size uint64) ([]byte, error)

GetBlobRangeBytes requests and validates a contiguous chunk range from s.

size is the verified full blob size. The returned bytes are the selected range, clamped to size.

func GetManyBlobBytes

func GetManyBlobBytes(ctx context.Context, s BidiStream, hashes []Hash) ([][]byte, error)

GetManyBlobBytes requests and validates full-range raw blobs from s.

func GetSingleLeaf

func GetSingleLeaf(ctx context.Context, s BidiStream, hash Hash) ([]byte, error)

GetSingleLeaf requests and validates one single-leaf raw blob from s.

GetSingleLeaf sends GetBlob, closes its send side, reads the response, and verifies the returned single-leaf BAO body against hash.

func Observe

func Observe(ctx context.Context, s BidiStream, hash Hash) iter.Seq2[Bitfield, error]

Observe requests bitfield updates for hash from s.

Observe sends ObserveBlob, closes its send side, and yields provider bitfield updates until the response stream ends.

func ReadBlob added in v0.0.2

func ReadBlob(ctx context.Context, s Store, hash Hash) ([]byte, error)

ReadBlob returns the complete contents of hash from s.

ReadBlob buffers the whole blob in memory. Prefer Store.Open and the returned Blob's DataReader for blobs of unknown size.

func Register

func Register(r *endpointticket.Registry) error

Register registers the blob ticket decoder in r.

func ServeBlob

func ServeBlob(ctx context.Context, s BidiStream, store Store) error

ServeBlob serves one full-range raw blob request on s.

The client must send a full RequestGet request, then close its send side. ServeBlob writes the full-range BAO response, or the hash-sequence root and children for GetAll, and closes its send side.

func ServeBlobStreams

func ServeBlobStreams(ctx context.Context, accept AcceptBlobStream, store Store) error

ServeBlobStreams serves blob requests from streams accepted by accept.

ServeBlobStreams accepts streams until accept returns an error or ctx is canceled. Each accepted stream is served concurrently with ServeBlob.

func ServeSingleLeaf

func ServeSingleLeaf(ctx context.Context, s BidiStream, store Store) error

ServeSingleLeaf serves one single-leaf raw blob request on s.

The client must send a full RequestGet / GetBlob request, then close its send side. ServeSingleLeaf writes the single-leaf BAO response and closes its send side. Blobs larger than MaxSingleLeafSize are rejected.

Types

type AcceptBlobStream

type AcceptBlobStream func(context.Context) (BidiStream, error)

AcceptBlobStream accepts the next bidirectional stream from a blob client.

type BidiStream

type BidiStream interface {
	io.Reader
	io.Writer
	Close() error
}

BidiStream is the stream shape used by the blob transfer helpers.

If a stream implements CloseWrite, the helpers use it to close the send side. Otherwise Close must close the send side while still allowing reads from the peer. This matches iroh.Stream. A net.Conn, whose Close closes both directions and which does not implement CloseWrite, is not a suitable BidiStream for these helpers.

type Bitfield

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

Bitfield reports which chunks of a blob a provider has.

func CompleteBitfield

func CompleteBitfield(size uint64) Bitfield

CompleteBitfield returns a bitfield containing every chunk of a blob.

func EmptyBitfield

func EmptyBitfield() Bitfield

EmptyBitfield returns a bitfield with no chunks.

func NewBitfield

func NewBitfield(size uint64, ranges ChunkRanges) Bitfield

NewBitfield returns a bitfield for size and ranges.

func (Bitfield) IsComplete

func (b Bitfield) IsComplete() bool

IsComplete reports whether b contains every chunk of the blob.

func (Bitfield) Ranges

func (b Bitfield) Ranges() ChunkRanges

Ranges returns the observed chunk ranges.

func (Bitfield) Size

func (b Bitfield) Size() uint64

Size returns the observed blob size.

type Blob added in v0.0.2

type Blob interface {
	Hash() Hash
	Size() (size uint64, verified bool)
	IsComplete() bool
	DataReader(ctx context.Context) (BlobReader, error)
	Outboard(ctx context.Context) (Outboard, error)
}

Blob is one stored blob, complete or partial.

type BlobConn

type BlobConn interface {
	OpenStreamSync(context.Context) (BidiStream, error)
	CloseWithError(code uint64, reason string) error
}

BlobConn is the subset of an iroh connection used by Downloader.

type BlobConnFunc

type BlobConnFunc func(context.Context) (BidiStream, error)

BlobConnFunc adapts a stream-opening function to BlobConn.

func (BlobConnFunc) CloseWithError

func (f BlobConnFunc) CloseWithError(uint64, string) error

CloseWithError implements BlobConn.

func (BlobConnFunc) OpenStreamSync

func (f BlobConnFunc) OpenStreamSync(ctx context.Context) (BidiStream, error)

OpenStreamSync calls f(ctx).

type BlobConnector

type BlobConnector interface {
	Connect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (BlobConn, error)
}

BlobConnector opens blob protocol connections to providers.

type BlobConnectorFunc

type BlobConnectorFunc func(context.Context, netaddr.EndpointAddr, string) (BlobConn, error)

BlobConnectorFunc adapts a function to BlobConnector.

func (BlobConnectorFunc) Connect

func (f BlobConnectorFunc) Connect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (BlobConn, error)

Connect calls f(ctx, addr, alpn).

type BlobFormat

type BlobFormat uint64

BlobFormat identifies the format of a blob root.

const (
	// Raw is a single raw blob.
	Raw BlobFormat = iota
	// HashSeq is a sequence of BLAKE3 hashes.
	HashSeq
)

func (BlobFormat) IsHashSeq

func (f BlobFormat) IsHashSeq() bool

IsHashSeq reports whether f is HashSeq.

func (BlobFormat) IsRaw

func (f BlobFormat) IsRaw() bool

IsRaw reports whether f is Raw.

func (BlobFormat) String

func (f BlobFormat) String() string

type BlobReader added in v0.0.2

type BlobReader interface {
	io.ReaderAt
	io.Closer
}

BlobReader reads a blob's data at arbitrary offsets. Callers must close it: a filesystem-backed store hands out an open file, and a caller that does not close it leaks a descriptor per read.

type BlobState

type BlobState uint8

BlobState is the local storage state of a blob.

const (
	// BlobNotFound means the blob is not stored.
	BlobNotFound BlobState = iota
	// BlobPartial means the blob is only partially stored.
	BlobPartial
	// BlobComplete means the blob is stored completely.
	BlobComplete
)

type BlobStatus

type BlobStatus struct {
	State BlobState
	Size  int64
}

BlobStatus describes the local storage state of a blob.

Size is -1 when the size is unknown.

func CompleteBlobStatus

func CompleteBlobStatus(size int64) BlobStatus

CompleteBlobStatus returns the status for a complete blob.

func NotFoundBlobStatus

func NotFoundBlobStatus() BlobStatus

NotFoundBlobStatus returns the status for a missing blob.

func PartialBlobStatus

func PartialBlobStatus(size int64) BlobStatus

PartialBlobStatus returns the status for a partial blob.

func Status

func Status(ctx context.Context, store Store, hash Hash) (BlobStatus, error)

Status reports the local storage status for hash in store.

Status uses Stater when store implements it, and otherwise falls back to Store.Open. Both paths report the same status; the upgrade changes only what the query costs.

A missing blob is NotFoundBlobStatus with a nil error. A non-nil error means the status could not be determined, which is not the same as the blob being absent.

func (BlobStatus) IsComplete

func (s BlobStatus) IsComplete() bool

IsComplete reports whether s describes a complete blob.

func (BlobStatus) IsNotFound

func (s BlobStatus) IsNotFound() bool

IsNotFound reports whether s describes a missing blob.

func (BlobStatus) IsPartial

func (s BlobStatus) IsPartial() bool

IsPartial reports whether s describes a partial blob.

func (BlobStatus) SizeKnown

func (s BlobStatus) SizeKnown() bool

SizeKnown reports whether s has a known size.

type BlobWriter added in v0.0.2

type BlobWriter interface {
	io.Writer
	Commit() (*TempTag, error)
	Close() error
}

BlobWriter accumulates one blob. Write the content, then call Commit to store it and learn its root hash.

Commit returns a TempTag rather than a bare Hash because a blob is collectible the instant it is stored. A caller that received only a hash could not protect the blob it names: the hash does not exist until the blob does, so every add-then-protect sequence has a window in which a concurrent FSStore.GC may delete the blob, and the tag the caller then creates names a file that is already gone. Commit closes that window by installing the blob and its tag together. Close the tag once durable ownership is established, usually by naming the blob with FSStore.SetTag:

tag, err := w.Commit()
if err != nil {
	return err
}
defer tag.Close()

Close releases the writer's resources. Close after a successful Commit is a no-op, so

w, err := s.NewBlob(ctx)
if err != nil {
	return err
}
defer w.Close()

is always correct, whether or not Commit is reached. A writer that is closed without committing discards its content.

An uncommitted writer has no hash yet, so it cannot be protected by a TempTag. Implementations must keep in-flight content out of reach of GC by other means; see FSStore.NewBlob for how the filesystem store does it.

type ChunkRange

type ChunkRange struct {
	Start uint64
	End   uint64
}

ChunkRange is a half-open range of 1024-byte BLAKE3 chunks.

type ChunkRanges

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

ChunkRanges selects chunks from a single blob.

func RangeAll

func RangeAll() ChunkRanges

RangeAll returns a chunk range set selecting every chunk.

func RangeChunks

func RangeChunks(start, end uint64) ChunkRanges

RangeChunks returns a chunk range set selecting [start, end).

func RangeEmpty

func RangeEmpty() ChunkRanges

RangeEmpty returns a chunk range set selecting no chunks.

func RangeLastChunk

func RangeLastChunk() ChunkRanges

RangeLastChunk returns a chunk range set selecting the verified-size proof.

func (ChunkRanges) IsAll

func (r ChunkRanges) IsAll() bool

IsAll reports whether r selects every chunk.

func (ChunkRanges) IsEmpty

func (r ChunkRanges) IsEmpty() bool

IsEmpty reports whether r selects no chunks.

func (ChunkRanges) OpenStart

func (r ChunkRanges) OpenStart() (uint64, bool)

OpenStart returns the start of the open-ended selected chunk range, if any.

func (ChunkRanges) Ranges

func (r ChunkRanges) Ranges() []ChunkRange

Ranges returns the finite selected chunk ranges.

type ChunkRangesSeq

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

ChunkRangesSeq selects ranges for a root blob and its children.

func ChunkRangesSeqAll

func ChunkRangesSeqAll() ChunkRangesSeq

ChunkRangesSeqAll returns a range sequence selecting all chunks forever.

func ChunkRangesSeqEmpty

func ChunkRangesSeqEmpty() ChunkRangesSeq

ChunkRangesSeqEmpty returns a range sequence selecting nothing.

func ChunkRangesSeqFromRanges

func ChunkRangesSeqFromRanges(ranges []ChunkRanges) ChunkRangesSeq

ChunkRangesSeqFromRanges returns a finite range sequence.

func ChunkRangesSeqFromRangesOpen

func ChunkRangesSeqFromRangesOpen(ranges []ChunkRanges) ChunkRangesSeq

ChunkRangesSeqFromRangesOpen returns a range sequence whose last non-empty range repeats forever.

func ChunkRangesSeqRoot

func ChunkRangesSeqRoot() ChunkRangesSeq

ChunkRangesSeqRoot returns a range sequence selecting only the root blob.

func (ChunkRangesSeq) At

func (seq ChunkRangesSeq) At(offset uint64) ChunkRanges

At returns the chunk ranges selected at offset.

func (ChunkRangesSeq) Entries

func (seq ChunkRangesSeq) Entries() []struct {
	Offset uint64
	Ranges ChunkRanges
}

Entries returns the explicit range changes in seq.

func (ChunkRangesSeq) IsAll

func (seq ChunkRangesSeq) IsAll() bool

IsAll reports whether seq selects all chunks forever.

func (ChunkRangesSeq) IsBlob

func (seq ChunkRangesSeq) IsBlob() bool

IsBlob reports whether seq requests a single raw blob.

type Collection

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

Collection is a Rust-compatible iroh-blobs collection.

func GetCollectionBytes

func GetCollectionBytes(ctx context.Context, s BidiStream, root Hash) (Collection, [][]byte, error)

GetCollectionBytes requests a collection and all of its child blobs from s.

func NewCollection

func NewCollection(entries []CollectionEntry) Collection

NewCollection returns a collection containing entries.

func ParseCollection

func ParseCollection(seq HashSequence, meta []byte) (Collection, error)

ParseCollection parses a collection from a root hash sequence and metadata blob.

func (Collection) Entries

func (c Collection) Entries() []CollectionEntry

Entries returns the collection entries.

func (Collection) HashSequence

func (c Collection) HashSequence() HashSequence

HashSequence returns c's root hash sequence.

func (Collection) IsEmpty

func (c Collection) IsEmpty() bool

IsEmpty reports whether c contains no blobs.

func (Collection) Len

func (c Collection) Len() int

Len returns the number of blobs in c.

func (Collection) MetadataBytes

func (c Collection) MetadataBytes() []byte

MetadataBytes returns the Rust-compatible metadata blob for c.

func (*Collection) Push

func (c *Collection) Push(name string, hash Hash)

Push appends name and hash to c.

func (Collection) Root

func (c Collection) Root() Hash

Root returns the hash of c's root hash sequence.

type CollectionEntry

type CollectionEntry struct {
	Name string
	Hash Hash
}

CollectionEntry is one named blob in a collection.

Name must be valid UTF-8.

type DownloadEvent

type DownloadEvent struct {
	Kind     DownloadEventKind
	Hash     Hash
	Provider netaddr.EndpointAddr
	Err      error
}

DownloadEvent reports downloader progress.

type DownloadEventKind

type DownloadEventKind int

DownloadEventKind identifies a downloader progress event.

const (
	// DownloadTryProvider reports that a provider is being tried.
	DownloadTryProvider DownloadEventKind = iota
	// DownloadProviderFailed reports that a provider failed.
	DownloadProviderFailed
	// DownloadComplete reports that a provider completed the download.
	DownloadComplete
)

type Downloader

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

Downloader downloads blobs from multiple providers.

func NewDownloader

func NewDownloader(store Sink, conn BlobConnector, opts DownloaderOptions) *Downloader

NewDownloader returns a downloader using store and conn.

store must implement Sink; downloaded content is streamed into a BlobWriter rather than buffered.

func (*Downloader) Close

func (d *Downloader) Close() error

Close closes cached provider connections.

func (*Downloader) Download

func (d *Downloader) Download(ctx context.Context, hash Hash, providers []netaddr.EndpointAddr) (*TempTag, error)

Download downloads hash from one of providers and stores it locally.

Download returns the TempTag protecting the stored blob. The blob is collectible as soon as the tag is closed, so a caller that runs FSStore.GC must hold it until it has established durable ownership, usually by naming the blob with FSStore.SetTag. A caller that does not collect garbage can close it immediately.

type DownloaderOptions

type DownloaderOptions struct {
	// Concurrency is the maximum number of providers tried at once.
	// Values <= 0 use 1.
	Concurrency int
	// OnEvent, if non-nil, receives progress events. It is called serially,
	// so it need not be safe for concurrent use even when Concurrency > 1.
	OnEvent func(DownloadEvent)
}

DownloaderOptions configures a Downloader.

type FSStore

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

FSStore is a filesystem-backed store for complete raw blobs.

func NewFSStore

func NewFSStore(dir string) (*FSStore, error)

NewFSStore opens or creates a filesystem-backed blob store rooted at dir.

func (*FSStore) Add

func (s *FSStore) Add(data []byte) (Hash, error)

Add stores data as a complete raw blob and returns its hash.

The blob is unprotected when Add returns, so a FSStore.GC running concurrently may collect it before the caller can name it with FSStore.SetTag. Callers that collect garbage should use FSStore.NewBlob and hold the TempTag that BlobWriter.Commit returns.

func (*FSStore) BlobStatus

func (s *FSStore) BlobStatus(ctx context.Context, hash Hash) (BlobStatus, error)

BlobStatus reports the local storage state for hash.

func (*FSStore) DeleteTag

func (s *FSStore) DeleteTag(name string) (bool, error)

DeleteTag deletes name.

func (*FSStore) GC

func (s *FSStore) GC(ctx context.Context) (GCResult, error)

GC deletes blobs that are not reachable from a persistent or temp tag.

func (*FSStore) GCWithEvents

func (s *FSStore) GCWithEvents(ctx context.Context, onEvent func(GCEvent)) (GCResult, error)

GCWithEvents deletes blobs that are not reachable from a persistent or temp tag and calls onEvent with mark, delete, and done progress events.

func (*FSStore) ImportFile

func (s *FSStore) ImportFile(path string, mode ImportMode) (Hash, error)

ImportFile imports path as a complete raw blob.

func (*FSStore) NewBlob added in v0.0.2

func (s *FSStore) NewBlob(ctx context.Context) (BlobWriter, error)

NewBlob returns a writer that streams content to a temporary file and installs it under its root hash on Commit.

The temporary file is named so that it cannot parse as a Hash, which is what keeps in-flight content invisible to FSStore.GC: GC walks the data directory and skips every name that ParseHash rejects. An uncommitted blob has no hash yet and so cannot be protected by a TempTag.

func (*FSStore) NewTempTag

func (s *FSStore) NewTempTag(value HashAndFormat) (*TempTag, error)

NewTempTag creates a process-local tag for value.

A blob is collectible between the moment it is stored and the moment a tag names it, so NewTempTag cannot protect a blob a caller has only just added. Use BlobWriter.Commit, which installs the blob and its tag together.

func (*FSStore) Open added in v0.0.2

func (s *FSStore) Open(ctx context.Context, hash Hash) (Blob, error)

Open returns the blob for hash, or ErrBlobNotFound.

func (*FSStore) SetTag

func (s *FSStore) SetTag(name string, value HashAndFormat) error

SetTag sets name to value.

func (*FSStore) Tag

func (s *FSStore) Tag(name string) (HashAndFormat, bool, error)

Tag returns the value for name.

func (*FSStore) Tags

func (s *FSStore) Tags() ([]TagInfo, error)

Tags returns all persistent tags sorted by name.

type GCEvent

type GCEvent struct {
	Kind    GCEventKind
	Hash    Hash
	Live    int
	Deleted int
}

GCEvent reports progress from FSStore.GCWithEvents.

type GCEventKind

type GCEventKind string

GCEventKind identifies a garbage-collection progress event.

const (
	// GCEventMark reports the number of hashes found reachable from tags.
	GCEventMark GCEventKind = "mark"
	// GCEventDelete reports one deleted blob.
	GCEventDelete GCEventKind = "delete"
	// GCEventDone reports the final sweep result.
	GCEventDone GCEventKind = "done"
)

type GCResult

type GCResult struct {
	Deleted int
}

GCResult reports the result of a filesystem store garbage-collection sweep.

type GetManyRequest

type GetManyRequest struct {
	Hashes []Hash
	Ranges ChunkRangesSeq
}

GetManyRequest requests multiple raw blobs from one provider.

func NewGetManyRequest

func NewGetManyRequest(hashes []Hash, ranges ChunkRangesSeq) GetManyRequest

NewGetManyRequest returns a request for hashes and ranges.

type GetRequest

type GetRequest struct {
	Hash   Hash
	Ranges ChunkRangesSeq
}

GetRequest requests a blob or hash sequence from a provider.

func DecodeGetRequestBytes

func DecodeGetRequestBytes(b []byte) (GetRequest, error)

DecodeGetRequestBytes decodes a full Request::Get message.

func GetAll

func GetAll(hash Hash) GetRequest

GetAll returns a request for a hash sequence and all its children.

func GetBlob

func GetBlob(hash Hash) GetRequest

GetBlob returns a request for a single raw blob.

func GetBlobRanges

func GetBlobRanges(hash Hash, ranges ChunkRanges) GetRequest

GetBlobRanges returns a request for selected ranges from a single raw blob.

func NewGetRequest

func NewGetRequest(hash Hash, ranges ChunkRangesSeq) GetRequest

NewGetRequest returns a get request for hash and ranges.

func (GetRequest) Content

func (r GetRequest) Content() HashAndFormat

Content returns the hash and inferred format requested by r.

type Hash

type Hash [HashSize]byte

Hash is a BLAKE3 hash used by iroh-blobs.

func EncodeBlob

func EncodeBlob(data []byte) (Hash, []byte, error)

EncodeBlob returns the Rust-compatible full-range BAO response for data.

The response bytes are an 8-byte little-endian size prefix followed by the pre-order BAO tree for iroh-blobs' 16 KiB block size. The returned hash is the BLAKE3 root hash of data.

Example
package main

import (
	"fmt"

	"github.com/tmc/go-iroh/blobs"
)

func main() {
	hash, encoded, _ := blobs.EncodeBlob([]byte("hello"))
	data, _ := blobs.DecodeBlob(hash, encoded)
	fmt.Println(string(data))
}
Output:
hello

func EncodeBlobRange

func EncodeBlobRange(data []byte, offset, length uint64) (Hash, []byte, error)

EncodeBlobRange returns the Rust-compatible BAO slice response for data.

The response verifies the byte range [offset, offset+length) against the BLAKE3 root hash of data.

func EncodeSingleLeaf

func EncodeSingleLeaf(data []byte) (Hash, []byte, error)

EncodeSingleLeaf returns the Rust-compatible full-range BAO response for data.

The single-leaf encoding is valid only for blobs up to one iroh-blobs BAO block. The response bytes are an 8-byte little-endian size prefix followed by data. The returned hash is the BLAKE3 hash of data.

func HashFromBytes

func HashFromBytes(b [HashSize]byte) Hash

HashFromBytes returns the hash represented by b.

func NewHash

func NewHash(b []byte) Hash

NewHash returns the BLAKE3 hash of b.

func ParseHash

func ParseHash(s string) (Hash, error)

ParseHash parses s as lowercase hex or RFC 4648 base32 without padding.

func ReadFromBlob added in v0.0.2

func ReadFromBlob(ctx context.Context, s Sink, r io.Reader) (Hash, error)

ReadFromBlob streams r into s and returns the stored blob's root hash.

ReadFromBlob does not buffer the whole blob. It releases the blob's TempTag before returning; see WriteBlob for what that means for callers that collect garbage.

func WriteBlob added in v0.0.2

func WriteBlob(ctx context.Context, s Sink, data []byte) (Hash, error)

WriteBlob stores data in s and returns its root hash.

WriteBlob releases the blob's TempTag before returning, so the blob is unprotected by the time the caller sees its hash. Callers that run FSStore.GC concurrently should use Sink.NewBlob and hold the tag Commit returns.

func (Hash) Bytes

func (h Hash) Bytes() [HashSize]byte

Bytes returns h as a byte array.

func (Hash) MarshalText

func (h Hash) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Hash) Short

func (h Hash) Short() string

Short returns the first five bytes of h as lowercase hex.

func (Hash) String

func (h Hash) String() string

String returns h as lowercase hex.

func (*Hash) UnmarshalText

func (h *Hash) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type HashAndFormat

type HashAndFormat struct {
	Hash   Hash
	Format BlobFormat
}

HashAndFormat is a hash with its blob format.

func HashSeqHash

func HashSeqHash(h Hash) HashAndFormat

HashSeqHash returns h as a hash sequence root.

func RawHash

func RawHash(h Hash) HashAndFormat

RawHash returns h as a raw blob hash.

type HashSequence

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

HashSequence is a sequence of blob hashes.

func GetHashSequenceBytes

func GetHashSequenceBytes(ctx context.Context, s BidiStream, root Hash) (HashSequence, [][]byte, error)

GetHashSequenceBytes requests a hash sequence and all of its child blobs from s.

func NewHashSequence

func NewHashSequence(hashes []Hash) HashSequence

NewHashSequence returns a hash sequence containing hashes.

func ParseHashSequence

func ParseHashSequence(b []byte) (HashSequence, error)

ParseHashSequence parses b as a sequence of 32-byte hashes.

func (HashSequence) At

func (seq HashSequence) At(i int) (Hash, bool)

At returns the hash at index i.

func (HashSequence) Bytes

func (seq HashSequence) Bytes() []byte

Bytes returns seq in the Rust-compatible wire form.

func (HashSequence) Hashes

func (seq HashSequence) Hashes() []Hash

Hashes returns the hashes in seq.

func (HashSequence) IsEmpty

func (seq HashSequence) IsEmpty() bool

IsEmpty reports whether seq contains no hashes.

func (HashSequence) Len

func (seq HashSequence) Len() int

Len returns the number of hashes in seq.

type ImportMode

type ImportMode uint8

ImportMode controls how FSStore.ImportFile stores file data.

const (
	// ImportCopy always copies bytes into the store.
	ImportCopy ImportMode = iota
	// ImportTryReference tries to reference the source with a hardlink, then
	// falls back to [ImportCopy]. Reflink support can be added behind this mode.
	ImportTryReference
)

type MemBlob added in v0.0.2

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

MemBlob is a complete in-memory raw blob.

func NewMemBlob added in v0.0.2

func NewMemBlob(data []byte) *MemBlob

NewMemBlob returns a complete in-memory raw blob holding data.

func (*MemBlob) DataReader added in v0.0.2

func (e *MemBlob) DataReader(ctx context.Context) (BlobReader, error)

DataReader returns an immutable reader for e's data.

func (*MemBlob) Hash added in v0.0.2

func (e *MemBlob) Hash() Hash

Hash returns e's root hash.

func (*MemBlob) IsComplete added in v0.0.2

func (e *MemBlob) IsComplete() bool

IsComplete reports whether e has all data.

func (*MemBlob) Outboard added in v0.0.2

func (e *MemBlob) Outboard(ctx context.Context) (Outboard, error)

Outboard returns an immutable reader for e's BAO outboard.

func (*MemBlob) Size added in v0.0.2

func (e *MemBlob) Size() (uint64, bool)

Size returns e's verified data size.

type MemStore added in v0.0.2

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

MemStore is an in-memory Store holding complete raw blobs.

func NewMemStore added in v0.0.2

func NewMemStore(blobs ...[]byte) (*MemStore, error)

NewMemStore returns an in-memory store holding data as complete raw blobs.

func (*MemStore) Add added in v0.0.2

func (m *MemStore) Add(data []byte) (Hash, error)

Add stores data as a complete raw blob and returns its hash.

func (*MemStore) NewBlob added in v0.0.2

func (m *MemStore) NewBlob(ctx context.Context) (BlobWriter, error)

NewBlob returns a writer that stores a blob in memory on Commit.

func (*MemStore) Open added in v0.0.2

func (m *MemStore) Open(ctx context.Context, hash Hash) (Blob, error)

Open returns the blob for hash, or ErrBlobNotFound.

type ObserveRequest

type ObserveRequest struct {
	Hash   Hash
	Ranges RangeSpec
}

ObserveRequest requests bitfield updates for a raw blob from a provider.

func DecodeObserveRequestBytes

func DecodeObserveRequestBytes(b []byte) (ObserveRequest, error)

DecodeObserveRequestBytes decodes a full Request::Observe message.

func ObserveBlob

func ObserveBlob(hash Hash) ObserveRequest

ObserveBlob returns an observe request for every chunk of hash.

type Outboard

type Outboard interface {
	io.ReaderAt
	io.Closer
	Size() int64
}

Outboard is a BAO outboard reader. Callers must close it, for the same reason as BlobReader.

type ParallelDownloadOptions

type ParallelDownloadOptions struct {
	Size        uint64
	RangeSize   uint64
	Parallelism int
	Retries     int
}

ParallelDownloadOptions configures DownloadBlobParallel.

type RangeOpener

type RangeOpener func(context.Context) (BidiStream, error)

RangeOpener opens one bidirectional stream to a blob provider.

type RangeSpec

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

RangeSpec is the compact wire form of chunk ranges.

func RangeSpecAll

func RangeSpecAll() RangeSpec

RangeSpecAll returns the wire range spec for all chunks.

func RangeSpecEmpty

func RangeSpecEmpty() RangeSpec

RangeSpecEmpty returns the wire range spec for an empty chunk selection.

func RangeSpecFromRanges

func RangeSpecFromRanges(r ChunkRanges) RangeSpec

RangeSpecFromRanges converts ranges to the Rust iroh-blobs wire range spec.

func RangeSpecLastChunk

func RangeSpecLastChunk() RangeSpec

RangeSpecLastChunk returns the wire range spec for the verified-size proof.

func (RangeSpec) ChunkRanges

func (s RangeSpec) ChunkRanges() ChunkRanges

ChunkRanges converts s to selected chunk ranges.

func (RangeSpec) IsAll

func (s RangeSpec) IsAll() bool

IsAll reports whether s selects every chunk.

func (RangeSpec) IsEmpty

func (s RangeSpec) IsEmpty() bool

IsEmpty reports whether s selects no chunks.

func (RangeSpec) Spans

func (s RangeSpec) Spans() []uint64

Spans returns the alternating deselected/selected span widths.

type Request

type Request struct {
	Type    RequestType
	Get     *GetRequest
	Observe *ObserveRequest
	GetMany *GetManyRequest
}

Request is an iroh-blobs provider request.

func DecodeRequestBytes

func DecodeRequestBytes(b []byte) (Request, error)

DecodeRequestBytes decodes Rust-compatible postcard request bytes.

type RequestType

type RequestType uint64

RequestType identifies an iroh-blobs request variant.

const (
	RequestGet     RequestType = 0
	RequestObserve RequestType = 1
	RequestPush    RequestType = 8
	RequestGetMany RequestType = 9
)

Request types are the wire discriminants used by Rust iroh-blobs. Values 2 through 7 are reserved by that numbering and have no Go name.

type Sink added in v0.0.2

type Sink interface {
	NewBlob(ctx context.Context) (BlobWriter, error)
}

Sink is an optional Store upgrade that accepts new blobs. Use WriteBlob or ReadFromBlob, which report a Store that cannot add content.

type Stater added in v0.0.2

type Stater interface {
	BlobStatus(ctx context.Context, hash Hash) (BlobStatus, error)
}

Stater is an optional Store upgrade that reports blob status without opening the blob. Use Status, which falls back to Open.

A Stater must report the same status Open would: an upgrade may change what a status query costs, never what it answers.

type Store

type Store interface {
	Open(ctx context.Context, hash Hash) (Blob, error)
}

Store holds blobs addressable by root hash.

Open reports a missing blob as ErrBlobNotFound. A Store may also implement Stater to answer status queries without opening the blob, and Sink to accept new blobs; callers should use the package-level Status and WriteBlob rather than asserting for those interfaces themselves.

type TagInfo

type TagInfo struct {
	Name  string
	Value HashAndFormat
}

TagInfo describes one named blob tag.

type TempTag

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

TempTag is a process-local tag that protects a blob from collection until it is closed.

A TempTag whose store never collects blobs, such as MemStore, protects nothing and Close is a no-op. Value reports what the tag protects.

func (*TempTag) Close

func (t *TempTag) Close() error

Close removes t from its store.

func (*TempTag) Hash added in v0.0.2

func (t *TempTag) Hash() Hash

Hash returns the hash t protects.

func (*TempTag) Value added in v0.0.2

func (t *TempTag) Value() HashAndFormat

Value returns the hash and format t protects.

type Ticket

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

Ticket is an iroh-blobs ticket.

func DecodeBytes

func DecodeBytes(b []byte) (Ticket, error)

DecodeBytes decodes the postcard bytes of a blob ticket.

func DecodeString

func DecodeString(s string) (Ticket, error)

DecodeString parses s as a blob ticket.

func NewTicket

func NewTicket(addr netaddr.EndpointAddr, hash Hash, format BlobFormat) Ticket

NewTicket returns a blob ticket for addr, hash, and format.

func ParseTicket

func ParseTicket(s string) (Ticket, error)

ParseTicket parses s as a blob ticket.

func (Ticket) Addr

func (t Ticket) Addr() netaddr.EndpointAddr

Addr returns the provider endpoint address.

func (Ticket) EncodeBytes

func (t Ticket) EncodeBytes() []byte

EncodeBytes returns the Rust-compatible postcard ticket payload.

func (Ticket) EncodeString

func (t Ticket) EncodeString() string

EncodeString returns the canonical ticket string.

func (Ticket) Format

func (t Ticket) Format() BlobFormat

Format returns the blob format.

func (Ticket) Hash

func (t Ticket) Hash() Hash

Hash returns the blob hash.

func (Ticket) HashAndFormat

func (t Ticket) HashAndFormat() HashAndFormat

HashAndFormat returns the ticket's content identifier.

func (Ticket) Kind

func (t Ticket) Kind() string

Kind returns the ticket kind prefix.

func (Ticket) MarshalText

func (t Ticket) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Ticket) Recursive

func (t Ticket) Recursive() bool

Recursive reports whether this ticket requests a hash sequence.

func (Ticket) Short

func (t Ticket) Short() Ticket

Short returns a ticket containing only the endpoint id and relay URLs.

func (Ticket) String

func (t Ticket) String() string

String returns the canonical ticket string.

func (*Ticket) UnmarshalText

func (t *Ticket) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

Jump to

Keyboard shortcuts

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