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 ¶
- Constants
- Variables
- func DecodeBlob(expected Hash, encoded []byte) ([]byte, error)
- func DecodeBlobRange(expected Hash, encoded []byte, offset, length uint64) ([]byte, error)
- func DecodeBlobRangeReader(expected Hash, r io.Reader, offset, length uint64) ([]byte, error)
- func DecodeBlobRangeToWriter(expected Hash, r io.Reader, offset, length uint64, w io.Writer) error
- func DecodeBlobReader(expected Hash, r io.Reader) ([]byte, error)
- func DecodeBlobToWriter(expected Hash, r io.Reader, w io.Writer) error
- func DecodeSingleLeaf(expected Hash, encoded []byte) ([]byte, error)
- func DownloadBlob(ctx context.Context, s BidiStream, hash Hash, w io.Writer) error
- func DownloadBlobParallel(ctx context.Context, open RangeOpener, hash Hash, w io.WriterAt, ...) error
- func DownloadBlobRange(ctx context.Context, s BidiStream, hash Hash, offset, length uint64, ...) error
- func EncodeGetManyRequestBytes(r GetManyRequest) []byte
- func EncodeGetRequestBytes(r GetRequest) []byte
- func EncodeObserveRequestBytes(r ObserveRequest) []byte
- func EncodeRequestBytes(req Request) ([]byte, error)
- func ExtractBlobRange(w io.Writer, data, outboard io.Reader, offset, length uint64) error
- func GetBlobBytes(ctx context.Context, s BidiStream, hash Hash) ([]byte, error)
- func GetBlobRangeBytes(ctx context.Context, s BidiStream, hash Hash, ranges ChunkRanges, size uint64) ([]byte, error)
- func GetManyBlobBytes(ctx context.Context, s BidiStream, hashes []Hash) ([][]byte, error)
- func GetSingleLeaf(ctx context.Context, s BidiStream, hash Hash) ([]byte, error)
- func Observe(ctx context.Context, s BidiStream, hash Hash) iter.Seq2[Bitfield, error]
- func ReadBlob(ctx context.Context, s Store, hash Hash) ([]byte, error)
- func Register(r *endpointticket.Registry) error
- func ServeBlob(ctx context.Context, s BidiStream, store Store) error
- func ServeBlobStreams(ctx context.Context, accept AcceptBlobStream, store Store) error
- func ServeSingleLeaf(ctx context.Context, s BidiStream, store Store) error
- type AcceptBlobStream
- type BidiStream
- type Bitfield
- type Blob
- type BlobConn
- type BlobConnFunc
- type BlobConnector
- type BlobConnectorFunc
- type BlobFormat
- type BlobReader
- type BlobState
- type BlobStatus
- type BlobWriter
- type ChunkRange
- type ChunkRanges
- type ChunkRangesSeq
- type Collection
- type CollectionEntry
- type DownloadEvent
- type DownloadEventKind
- type Downloader
- type DownloaderOptions
- type FSStore
- func (s *FSStore) Add(data []byte) (Hash, error)
- func (s *FSStore) BlobStatus(ctx context.Context, hash Hash) (BlobStatus, error)
- func (s *FSStore) DeleteTag(name string) (bool, error)
- func (s *FSStore) GC(ctx context.Context) (GCResult, error)
- func (s *FSStore) GCWithEvents(ctx context.Context, onEvent func(GCEvent)) (GCResult, error)
- func (s *FSStore) ImportFile(path string, mode ImportMode) (Hash, error)
- func (s *FSStore) NewBlob(ctx context.Context) (BlobWriter, error)
- func (s *FSStore) NewTempTag(value HashAndFormat) (*TempTag, error)
- func (s *FSStore) Open(ctx context.Context, hash Hash) (Blob, error)
- func (s *FSStore) SetTag(name string, value HashAndFormat) error
- func (s *FSStore) Tag(name string) (HashAndFormat, bool, error)
- func (s *FSStore) Tags() ([]TagInfo, error)
- type GCEvent
- type GCEventKind
- type GCResult
- type GetManyRequest
- type GetRequest
- type Hash
- func EncodeBlob(data []byte) (Hash, []byte, error)
- func EncodeBlobRange(data []byte, offset, length uint64) (Hash, []byte, error)
- func EncodeSingleLeaf(data []byte) (Hash, []byte, error)
- func HashFromBytes(b [HashSize]byte) Hash
- func NewHash(b []byte) Hash
- func ParseHash(s string) (Hash, error)
- func ReadFromBlob(ctx context.Context, s Sink, r io.Reader) (Hash, error)
- func WriteBlob(ctx context.Context, s Sink, data []byte) (Hash, error)
- type HashAndFormat
- type HashSequence
- type ImportMode
- type MemBlob
- type MemStore
- type ObserveRequest
- type Outboard
- type ParallelDownloadOptions
- type RangeOpener
- type RangeSpec
- type Request
- type RequestType
- type Sink
- type Stater
- type Store
- type TagInfo
- type TempTag
- type Ticket
- func (t Ticket) Addr() netaddr.EndpointAddr
- func (t Ticket) EncodeBytes() []byte
- func (t Ticket) EncodeString() string
- func (t Ticket) Format() BlobFormat
- func (t Ticket) Hash() Hash
- func (t Ticket) HashAndFormat() HashAndFormat
- func (t Ticket) Kind() string
- func (t Ticket) MarshalText() ([]byte, error)
- func (t Ticket) Recursive() bool
- func (t Ticket) Short() Ticket
- func (t Ticket) String() string
- func (t *Ticket) UnmarshalText(text []byte) error
Examples ¶
Constants ¶
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 )
const ALPN = "/iroh-bytes/4"
ALPN is the application protocol name for Rust iroh-blobs.
const DefaultStallTimeout = 30 * time.Second
DefaultStallTimeout is the DownloaderOptions.StallTimeout used when it is zero. It matches github.com/tmc/go-iroh/iroh.RelayPathMaxIdleTimeout, the longest an iroh connection waits on a silent peer: a provider that keeps its connection alive but sends nothing for that long is as good as gone.
const HashSize = 32
HashSize is the size of a blob hash, in bytes.
const MaxRequestSize = 1 << 20
MaxRequestSize is the largest request a server reads, as in iroh-blobs.
const (
// TicketKind is the string prefix for blob tickets.
TicketKind = "blob"
)
Variables ¶
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") )
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") // ErrRequestTooLarge is returned when a request is longer than // [MaxRequestSize]. ErrRequestTooLarge = errors.New("blobs: request too large") )
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.
var ErrProviderStalled = errors.New("blobs: provider stalled")
ErrProviderStalled reports a provider that delivered no verified content for DownloaderOptions.StallTimeout.
Functions ¶
func DecodeBlob ¶
DecodeBlob validates and decodes a Rust-compatible full-range BAO response.
func DecodeBlobRange ¶
DecodeBlobRange validates and decodes a Rust-compatible BAO slice response.
func DecodeBlobRangeReader ¶
DecodeBlobRangeReader validates and decodes one Rust-compatible BAO slice response from r.
func DecodeBlobRangeToWriter ¶
DecodeBlobRangeToWriter validates a Rust-compatible BAO slice proof against expected and streams [offset, offset+length) to w.
func DecodeBlobReader ¶
DecodeBlobReader validates and decodes one Rust-compatible full-range BAO response from r.
func DecodeBlobToWriter ¶
DecodeBlobToWriter validates one Rust-compatible full-range BAO response from r and streams the decoded blob to w.
func DecodeSingleLeaf ¶
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 ¶
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 ¶
EncodeRequestBytes encodes req as Rust-compatible postcard bytes.
func ExtractBlobRange ¶
ExtractBlobRange writes a Rust-compatible BAO slice proof for [offset, offset+length) from data and outboard.
func GetBlobBytes ¶
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 ¶
GetManyBlobBytes requests and validates full-range raw blobs from s.
func GetSingleLeaf ¶
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 ¶
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
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. A request longer than MaxRequestSize fails with ErrRequestTooLarge.
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, and then waits for the streams it is serving. Each accepted stream is served concurrently with ServeBlob; an error serving one stream ends only that stream. ServeBlobStreams returns nil when ctx is done or when the accept error matches net.ErrClosed, as the close errors of an iroh connection do, and returns any other accept error.
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 ¶
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.
If a stream implements CancelRead(code uint64), as iroh.Stream does, the helpers call it to abandon a response when their context ends. Otherwise a helper still returns when its context ends, but leaves a goroutine blocked in Read until the stream fails; the helper stops writing to the caller's writer before it returns.
type Bitfield ¶
type Bitfield struct {
// contains filtered or unexported fields
}
Bitfield reports which chunks of a blob a provider has.
func CompleteBitfield ¶
CompleteBitfield returns a bitfield containing every chunk of a blob.
func NewBitfield ¶
func NewBitfield(size uint64, ranges ChunkRanges) Bitfield
NewBitfield returns a bitfield for size and ranges.
func (Bitfield) IsComplete ¶
IsComplete reports whether b contains every chunk of the blob.
func (Bitfield) Ranges ¶
func (b Bitfield) Ranges() ChunkRanges
Ranges returns the observed chunk ranges.
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 ¶
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) String ¶
func (f BlobFormat) String() string
type BlobReader ¶ added in v0.0.2
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 BlobStatus ¶
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 ¶
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
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 ¶
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) 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 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)
// StallTimeout is how long a provider may go without delivering
// verified content, counting from when it is first tried, before
// Download abandons it with [ErrProviderStalled] and tries the next.
// Zero means [DefaultStallTimeout]; a negative value disables the limit.
StallTimeout time.Duration
}
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 ¶
NewFSStore opens or creates a filesystem-backed blob store rooted at dir.
func (*FSStore) Add ¶
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 ¶
BlobStatus reports the local storage state for hash.
func (*FSStore) GCWithEvents ¶
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
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.
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 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 ¶
Hash is a BLAKE3 hash used by iroh-blobs.
func EncodeBlob ¶
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 ¶
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 ¶
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 ¶
HashFromBytes returns the hash represented by b.
func ReadFromBlob ¶ added in v0.0.2
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
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) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Hash) UnmarshalText ¶
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.
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
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) IsComplete ¶ added in v0.0.2
IsComplete reports whether e has all data.
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
NewMemStore returns an in-memory store holding data as complete raw blobs.
type ObserveRequest ¶
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 ¶
Outboard is a BAO outboard reader. Callers must close it, for the same reason as BlobReader.
type ParallelDownloadOptions ¶
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.
type Request ¶
type Request struct {
Type RequestType
Get *GetRequest
Observe *ObserveRequest
GetMany *GetManyRequest
}
Request is an iroh-blobs provider request.
func DecodeRequestBytes ¶
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 ¶
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) 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 ¶
DecodeBytes decodes the postcard bytes of a blob ticket.
func DecodeString ¶
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 ¶
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 ¶
EncodeBytes returns the Rust-compatible postcard ticket payload.
func (Ticket) EncodeString ¶
EncodeString returns the canonical ticket string.
func (Ticket) HashAndFormat ¶
func (t Ticket) HashAndFormat() HashAndFormat
HashAndFormat returns the ticket's content identifier.
func (Ticket) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Ticket) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.