storerec

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 30 Imported by: 2 modules, 2 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 storerec is the byte-level contract of bstore: the bucket record a mined token carries, the object entry, the piece, the outcome record and the front statement that ride unmined carriers, the challenge request and response, the hold terms, the key map and its contexts, the proof tree, settlement, BRC-26 advertisements, the names and lookup questions, the topic manager's transaction rules and a reader's checks that need no network. docs/spec.md is the normative text; this package generates the golden vectors under testdata/vectors.

Every record is canonical CBOR through bcommon's cbor package, so one value has one encoding a reader accepts. Every decoder bounds its input before the CBOR decoder runs, and the CBOR decoder bounds every declared length against the bytes present before it allocates.

Index

Constants

View Source
const (
	RoleBefore = 0
	RoleAfter  = 1
	RoleUnheld = 2
)

Roles of a token context's leaves (spec section 11.3).

View Source
const (
	NKMagic uint64 = iota
	NKPayment
	NKRequest
	NKReason
	NKTime
	NKAnswerer
	NKLast = NKAnswerer
)

Record keys of the not-taken note.

View Source
const (
	MaxNotTaken   = 512
	MaxNoteReason = 64
)

MaxNotTaken bounds a signed note; MaxNoteReason a reason.

View Source
const (
	// ProtocolName is the BRC-43 protocol name of every bstore derivation,
	// at security level 1.
	ProtocolName = "bstore"

	KeyBucket    = "bucket"
	KeyChain     = "chain"
	KeyEntry     = "entry"
	KeyPiece     = "piece"
	KeyOutcome   = "outcome"
	KeyFront     = "front"
	KeyHold      = "hold"
	KeyChallenge = "challenge"
	KeyFund      = "fund"

	RecordsPrefix = "tm_bstore_"
	BlobPrefix    = "tm_bstoreblob_"
	LookupService = "ls_bstore"
	HostTerms     = "/ls_bstore/terms"
	FrontSuffix   = "/bstore/v1"

	// DomainBucketID is hashed into a bucket id (spec section 3.3).
	DomainBucketID = "bstore bucket id v1"

	// AdProtocolName and AdKeyID are BRC-26's advertisement derivation as
	// the SDK has it, at security level 2; borrowed, not registered.
	AdProtocolName = "uhrp advertisement"
	AdKeyID        = "1"
	// SettleProtocolName is BRC-29's, at security level 2; borrowed.
	SettleProtocolName = "3241645161d8"
)

Registry values (docs/frozen.md section 1).

View Source
const (
	// MaxSafe is 2^53 - 1, the bound of every unsigned value the contract
	// leaves unbounded, so that a JSON or JavaScript reader holds it exactly.
	MaxSafe = 1<<53 - 1
	// MinTime and MaxTime bound a time in a record, Unix milliseconds.
	MinTime = 1
	MaxTime = 253402300799999

	MaxBucketRecord = 65536
	MaxWriters      = 16
	MaxChanges      = 1024
	MaxConsumed     = 1024
	MaxKeysInMap    = 1048576

	MaxEntry       = 8192
	MaxObjectKey   = 1024
	MaxSize        = 1 << 43
	MinContentType = 3
	MaxContentType = 127
	MaxETag        = 64
	MaxMetaPairs   = 32
	MaxMetaBytes   = 2048
	MaxMetaKey     = 128
	MaxMetaValue   = 1024
	MaxKind        = 255

	MaxPiece       = 4194304
	MaxPieceRecord = 4194560

	MaxOutcome = 4096
	MaxFront   = 2048
	MinURL     = 12
	MaxURL     = 512

	MaxRequest        = 512
	MaxC              = 1024
	NonceLen          = 16
	MaxSignedResponse = 8388608

	// Hold terms (spec section 4.3).
	MaxSatoshis  = 2100000000000000
	MaxT         = 16
	MaxU32       = 1<<32 - 1
	MaxCheckC    = 1024
	ProofProfile = 1

	// Contexts (spec section 11.3).
	MaxEntryContext = 1024
	MaxTokenContext = 4096
	MaxMapPath      = 20
	PageList        = 256
	PageExport      = 512

	// The proof tree (spec section 6).
	SegmentSize      = 4096
	BlobSize         = 4194304
	SegmentsPerBlob  = BlobSize / SegmentSize
	SeedWindow       = 6
	MaxProofPath     = 31
	DefaultC         = 30
	MaxAdsPerTx      = 1024
	MaxAdURL         = 2048
	MinAge           = 0
	MaxMinAge        = 1008
	MinFreeC         = 30
	AdvertisementMin = 1

	// Identifiers (spec section 3.1).
	SuffixLen  = 10
	MaxName    = 25
	MinBucket  = 1 + 1 + SuffixLen
	MaxBucket  = MaxName + 1 + SuffixLen
	BucketID32 = 32

	// The BEEF ceilings of spec section 12.1, whatever a host's own bound.
	MaxCarrierBEEF = 81920
	MaxTokenBEEF   = 196608
	MaxSweepBEEF   = 196608
	MaxMinedBEEF   = 65536
	MaxPieceBEEF   = 4259840
	// DefaultMaxBEEF is a host's own BEEF bound at its floor.
	DefaultMaxBEEF = 262144
	// DefaultMaxSweepInputs is a host's sweep input bound at its floor.
	DefaultMaxSweepInputs = 1024
)

Bounds. A reader accepts every record within them; a later version may raise a bound but never lower it (docs/frozen.md section 12).

View Source
const (
	BKMagic uint64 = iota
	BKBucket
	BKOwner
	BKID
	BKSeq
	BKPrev
	BKWriters
	BKChanges
	BKCount
	BKMapRoot
	BKCreated
	BKConsumed
	BKLast = BKConsumed
)

Record keys of the bucket record (spec section 3.2).

View Source
const (
	EKMagic uint64 = iota
	EKBucket
	EKID
	EKWriter
	EKKey
	EKKind
	EKCreated
	EKSize
	EKRoot
	EKContentHash
	EKProofRoot
	EKProofProfile
	EKContentType
	EKETag
	EKMeta
	EKHold
	EKLast = EKHold
)

Record keys of the object entry (spec section 4.1).

View Source
const (
	PKMagic uint64 = iota
	PKBucket
	PKWriter
	PKRoot
	PKPiece
	PKLast = PKPiece
)

Record keys of the piece (spec section 5).

View Source
const (
	OKMagic uint64 = iota
	OKBucket
	OKBuyer
	OKCreated
	OKRequest
	OKOutcome
	OKResponse
	OKSignature
	OKLast = OKSignature
)

Record keys of the outcome record (spec section 8.1).

View Source
const (
	FKMagic uint64 = iota
	FKBucket
	FKFront
	FKAdvertiser
	FKURL
	FKCreated
	FKLast = FKCreated
)

Record keys of the front statement (spec section 8.2).

View Source
const (
	QKMagic uint64 = iota
	QKRoot
	QKProofRoot
	QKSize
	QKProvider
	QKAnswerer
	QKSeedHeight
	QKSeedHash
	QKNonce
	QKC
	QKRange
	QKLast = QKRange
)

Record keys of the challenge request (spec section 7.1).

View Source
const (
	RKMagic uint64 = iota
	RKRequest
	RKSamples
	RKAnswerer
	RKLast = RKAnswerer
)

Record keys of the response body (spec section 7.3).

View Source
const (
	KindPut    = 1
	KindDelete = 2
)

Entry kinds.

View Source
const (
	OutcomePass          = 1
	OutcomeInvalid       = 2
	OutcomeNoAnswer      = 3
	OutcomeUnretrievable = 4
)

Outcomes (spec section 8.1).

View Source
const MaxAdPayload = MaxAdURL + 256

MaxAdPayload bounds an advertisement's fields together, as the SDK does.

Variables

View Source
var (
	ErrShape      = errors.New("storerec: transaction has the wrong shape")
	ErrBEEF       = chaintoken.ErrBEEF
	ErrMineable   = errors.New("storerec: carrier is mineable")
	ErrUnlock     = errors.New("storerec: unlocking script is not one canonical signature push")
	ErrLock       = errors.New("storerec: output script is not the canonical one for the owner")
	ErrFieldSig   = errors.New("storerec: field signature is not strict or does not verify")
	ErrFunding    = errors.New("storerec: carrier does not spend a funding output of its owner, or does not carry its value")
	ErrUnmined    = errors.New("storerec: proof does not verify against the host's headers")
	ErrTokenInput = errors.New("storerec: token does not spend its predecessor, or its chain tree at seq 0")
	ErrBucketID   = errors.New("storerec: id is not the bucket id of the outpoint the first token spends")
	ErrTooMany    = errors.New("storerec: more than 16 advertisements and hold outputs")
	ErrNotBstore  = errors.New("storerec: transaction is not for this topic")
	ErrPieceTx    = errors.New("storerec: a piece; pieces belong on the blob topic")
	ErrHostConfig = errors.New("storerec: host configuration or previous coins out of range")
)

The transaction refusals of spec section 12.1, beside the record refusals. A transaction is refused for the first rule it breaks.

View Source
var (
	ErrAdvertisement = errors.New("storerec: not an advertisement as the SDK validates it")
	ErrNarrowed      = errors.New("storerec: an internationalised host this codec does not parse")
)

ErrAdvertisement is every refusal of an advertisement; its rule names the SDK check that failed. ErrNarrowed marks a url this codec refuses that the WHATWG parser may admit (url.go).

View Source
var (
	ErrSignature   = errors.New("storerec: the signed response is not [body, signature] or does not verify")
	ErrRespCount   = errors.New("storerec: samples are not c, or a path's length is not the audit path's")
	ErrFetch       = errors.New("storerec: a by-reference segment could not be fetched")
	ErrSegment     = errors.New("storerec: a segment is not its segment's length")
	ErrPath        = errors.New("storerec: a leaf and its siblings do not reproduce proofRoot")
	ErrSeed        = errors.New("storerec: the seed is not a block the answerer holds within the window")
	ErrUnknownRoot = errors.New("storerec: root is not held, or proofRoot or size is not its own")
)

The buyer's labels (spec section 7.4) and the answerer's refusals.

View Source
var (
	DetectionCs      = []int{1, 8, 16, 30, 60, 100, 230, 459, 1000}
	DetectionLosses  = []float64{0.5, 0.25, 0.1, 0.05, 0.01, 0.001}
	ConfidenceLevels = []float64{0.9, 0.99, 0.999}
)

DetectionCs and DetectionLosses are the rows and columns of spec section 7.6's first table; ConfidenceLevels the columns of its second.

View Source
var (
	ErrMapMismatch = errors.New("storerec: a token's changes do not fold to its count and mapRoot")
	ErrMap         = errors.New("storerec: a context does not prove what the answer claims")
)

The fold's and a reader's map labels.

View Source
var (
	ErrRollback  = errors.New("storerec: a token below the seq the reader holds")
	ErrEntry     = errors.New("storerec: the entry is not the one asked for")
	ErrWriter    = errors.New("storerec: the entry's writer is neither the token's owner nor one of its writers")
	ErrRoot      = errors.New("storerec: the root or the closure it names is not valid for the entry")
	ErrClosure   = errors.New("storerec: an object of the closure was not served as its hash names it")
	ErrContent   = errors.New("storerec: the content does not hash to contentHash")
	ErrProofRoot = errors.New("storerec: the proof root recomputed differs from the entry's")
)

A reader's check labels (spec section 15.2), beside map (keymap.go) and the record labels.

View Source
var (
	TagPrefix  = []byte("st")
	TagToken   = []byte{'s', 't', 0x01}
	TagFunding = []byte{'s', 't', 0x02}
	TagHold    = []byte{'s', 't', 0x03}

	MagicBucket   = []byte{'s', 't', 'b', 0x01}
	MagicEntry    = []byte{'s', 't', 'e', 0x01}
	MagicPiece    = []byte{'s', 't', 'p', 0x01}
	MagicOutcome  = []byte{'s', 't', 'o', 0x01}
	MagicFront    = []byte{'s', 't', 'f', 0x01}
	MagicRequest  = []byte{'s', 't', 'q', 0x01}
	MagicResponse = []byte{'s', 't', 'r', 0x01}
)

Tags and magics under the prefix "st".

View Source
var (
	Protocol            = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryApp, Protocol: ProtocolName}
	BucketDerivation    = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyBucket}
	ChainDerivation     = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyChain}
	EntryDerivation     = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyEntry}
	PieceDerivation     = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyPiece}
	OutcomeDerivation   = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyOutcome}
	FrontDerivation     = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyFront}
	HoldDerivation      = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyHold}
	ChallengeDerivation = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyChallenge}
	FundDerivation      = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyFund}

	AdProtocol     = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryAppAndCounterparty, Protocol: AdProtocolName}
	AdDerivation   = pushdrop.Derivation{Protocol: AdProtocol, KeyID: AdKeyID}
	SettleProtocol = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryAppAndCounterparty, Protocol: SettleProtocolName}
)

Derivations under [1, "bstore"], each with counterparty anyone, so a reader derives the key from the identity key alone. The funding key uses counterparty self and no rule reads it.

View Source
var (
	ErrTooLarge = record.ErrTooLarge
	ErrCBOR     = record.ErrCBOR
	ErrKeyType  = record.ErrKeyType
	ErrMagic    = record.ErrMagic
	ErrMissing  = record.ErrMissing
	ErrType     = record.ErrType

	ErrBucket      = errors.New("storerec: bucket identifier breaks the grammar, or is not the topic's")
	ErrIdentity    = errors.New("storerec: key is not a canonical compressed key, or is the anyone key")
	ErrSeq         = errors.New("storerec: seq out of range")
	ErrWriters     = errors.New("storerec: writers over the bound, out of order, or naming the owner")
	ErrChanges     = errors.New("storerec: changes break their rule")
	ErrCount       = errors.New("storerec: count out of range")
	ErrCreated     = errors.New("storerec: created out of range")
	ErrConsumed    = errors.New("storerec: consumed breaks its rule")
	ErrFirst       = errors.New("storerec: seq and prev, changes, consumed, count or mapRoot disagree")
	ErrObjKey      = errors.New("storerec: object key breaks its rule")
	ErrKind        = errors.New("storerec: kind out of range, or a key present or absent against the kind")
	ErrSize        = errors.New("storerec: size out of range")
	ErrProfile     = errors.New("storerec: proofProfile is not 1")
	ErrContentType = errors.New("storerec: contentType breaks its rule")
	ErrETag        = errors.New("storerec: etag breaks its rule")
	ErrMeta        = errors.New("storerec: meta breaks its rule")
	ErrHold        = errors.New("storerec: hold terms break their bounds")
	ErrEmpty       = errors.New("storerec: the empty object's rule is broken")
	ErrPiece       = errors.New("storerec: piece out of range")
	ErrRequest     = errors.New("storerec: not a challenge request under spec section 7.1")
	ErrOutcome     = errors.New("storerec: outcome out of range")
	ErrRespSig     = errors.New("storerec: the answerer's signature does not verify")
	ErrURL         = errors.New("storerec: url breaks its rule")
	ErrQuery       = errors.New("storerec: question is not one of the defined classes")
)

The record refusals, each labelled as its spec section labels it.

View Source
var AnyoneKey = func() []byte {
	k, _ := ec.PrivateKeyFromBytes(append(make([]byte, 31), 1))
	return k.PubKey().Compressed()
}()

AnyoneKey is BRC-43's anyone counterparty: the generator point, whose private key is 1.

View Source
var Baskets = []string{"bstore fund", "bstore entry funding", "bstore piece funding", "bstore outcome funding",
	"bstore front funding", "bstore chain funding", "bstore chain", "bstore hold", "bstore kill tombstone"}

Baskets are the wallet baskets bstore's tooling uses; never on a host.

View Source
var Classes = []Class{
	{"bucket", []string{"bucket", "owner", "id"}, true, false},
	{"bucket-seq", []string{"bucket", "owner", "id", "seq"}, true, false},
	{"object", []string{"bucket", "owner", "id", "key"}, true, true},
	{"list", []string{"bucket", "owner", "id", "prefix", "after"}, true, true},
	{"pending", []string{"bucket", "owner", "id", "pending"}, true, true},
	{"unanchored", []string{"bucket", "owner", "id", "writer", "after"}, true, true},
	{"entry", []string{"bucket", "entry"}, true, false},
	{"ads", []string{"bucket", "root", "after"}, true, false},
	{"ad", []string{"bucket", "root", "advertiser"}, true, false},
	{"fronts", []string{"bucket", "advertiser", "after"}, true, false},
	{"front", []string{"bucket", "advertiser", "front"}, true, false},
	{"hold", []string{"bucket", "hold"}, true, false},
	{"outcomes", []string{"bucket", "answerer"}, true, false},
	{"outcomes-of", []string{"bucket", "provider"}, true, false},
	{"outcomes-by", []string{"bucket", "answerer", "buyer"}, true, false},
	{"outcomes-of-by", []string{"bucket", "provider", "buyer"}, true, false},
	{"sweep", []string{"bucket", "spent"}, true, false},
	{"history", []string{"bucket", "owner", "id", "history", "before"}, false, true},
	{"chain", []string{"bucket", "owner", "chain", "after"}, false, false},
	{"export", []string{"bucket", "owner", "export", "after"}, false, true},
	{"outcome-history", []string{"bucket", "outcome-history", "before"}, false, false},
	{"outcome-history-of", []string{"bucket", "outcome-history-of", "before"}, false, false},
}

Classes are every class ls_bstore answers. No priced class is a superset of a free class: each carries a member no free class carries.

View Source
var ClosureLimits = chirp.Limits{MaxLength: MaxSize}

ClosureLimits are the limits bstore verifies a closure with: content of at most 2^43 bytes (an entry's size bound), and bcommon's default bound on references.

View Source
var EmptyHash = sha256.Sum256(nil)

EmptyHash is SHA-256 of no bytes: the content hash and proof root of the empty object, and the map root of the empty map.

View Source
var EmptyRoot = [32]byte{0x04, 0x03, 0x64, 0x0d, 0x63, 0x5f, 0xd2, 0x7b, 0x6c, 0x71, 0x9d, 0x2b, 0x81, 0xdb, 0x85, 0x34,
	0x83, 0xff, 0x8d, 0x0f, 0xb4, 0x6f, 0x7b, 0x90, 0xce, 0x9f, 0x9d, 0x7e, 0x9a, 0x27, 0x29, 0xee}

EmptyRoot is the CHIRP Profile 1 root of empty content (BRC-167's vector).

View Source
var ErrNotTaken = errors.New("storerec: not a payment-not-taken note under row C30")

ErrNotTaken is a signed note that does not decode or verify; its rule names the step.

KeyIDs are the registry's key ids in the order of spec section 13.1.

View Source
var MagicNotTaken = []byte{'s', 't', 'n', 0x01}

MagicNotTaken is the not-taken note's magic.

View Source
var Since = Class{"since", []string{"bucket", "since"}, true, false}

Since is the free class amendment A2 adds (frozen.md section 15): what a host took for a bucket after a position. It is kept apart from Classes, which the query-v1 vectors pin as the classes of the first publish; a question is parsed against both (AllClasses).

Functions

func AdvertisementFields

func AdvertisementFields(host []byte, adKey *ec.PrivateKey, hash [32]byte, url string, expiry, fileSize uint64) ([][]byte, error)

AdvertisementFields are an advertisement's six fields, signed by the host's key derived under [2, "uhrp advertisement"] key id 1, counterparty anyone (adKey), and the lock that key's public key makes.

func AdvertisementScript

func AdvertisementScript(lock *ec.PublicKey, fields [][]byte) []byte

AdvertisementScript is the canonical PushDrop of six fields under lock, as the SDK writes an advertisement.

func BlobSubtree

func BlobSubtree(blob []byte) [32]byte

BlobSubtree is the subtree root over one blob's segments: what a native provider keeps per blob and rebuilds on demand.

func BlobTopic

func BlobTopic(bucket string) string

func Blobs

func Blobs(size uint64) uint64

Blobs is the number of 4 MiB blobs of an object of size bytes.

func BucketID

func BucketID(txid [32]byte, vout uint32) [32]byte

BucketID is SHA-256("bstore bucket id v1" || txid || uint32be(vout)) of the outpoint a bucket's first token spends, txid in hash byte order.

func CHIRPURLSuffix

func CHIRPURLSuffix(root [32]byte) string

CHIRPURLSuffix is the path a CHIRP root's advertisement url ends in (BRC-167): /chirp/v1/<rootIdentifier>/objects/<rootIdentifier>.

func ChallengeKey

func ChallengeKey(answerer []byte) (*ec.PublicKey, error)

ChallengeKey is derive(answerer, "challenge"), read from the identity key.

func CheckBucket

func CheckBucket(s string) error

CheckBucket holds s to the bucket identifier grammar of spec section 3.1: <name>_<suffix>, the name 1 to 25 bytes of lowercase letters and single underscores with a letter at each end, the suffix exactly 10 lowercase letters; split at the last underscore.

func CheckContentType

func CheckContentType(s string) error

CheckContentType holds s to spec section 4.1: 3 to 127 bytes of lowercase printable ASCII (0x21 to 0x7e, no A to Z), exactly one "/", and no parameters (no ";").

func CheckETag

func CheckETag(s string) error

CheckETag holds s to spec section 4.1: 1 to 64 bytes of printable ASCII (0x20 to 0x7e) without '"'.

func CheckEntry

func CheckEntry(e *Entry, bucket string, id [32]byte, key string) error

CheckEntry is a reader's step 3 on a carrier it verified: the entry's bucket, id and key are what it asked for.

func CheckFrontURL

func CheckFrontURL(s string) error

CheckFrontURL holds a front statement's url to spec section 8.2: "https://", a non-empty authority without user information, no query or fragment, 12 to 512 bytes of 0x21 to 0x7e, not ending in "/"; and the WHATWG parse the advertisement check runs (an https URL with a non-empty host, no username, password or fragment), its host ASCII after percent-decoding with no label beginning "xn--". The last rule is httpsURL's narrowing, made the rule here, so that Go and TypeScript decide every front url alike.

func CheckKey

func CheckKey(b []byte) (*ec.PublicKey, error)

CheckKey holds b to the key rule of spec section 2: a canonical compressed point (bcommon guard.ParsePubKey) that is not the anyone key. A key that held is remembered (keycache.go).

func CheckKind

func CheckKind(e *Entry) error

CheckKind is a reader's step 5: an unknown kind is unsupported, and a delete is never a key's value in a map.

func CheckMetaKey

func CheckMetaKey(s string) bool

CheckMetaKey holds a meta key to 1 to 128 bytes of a-z, 0-9 and "-".

func CheckObjectKey

func CheckObjectKey(k string) error

CheckObjectKey holds k to the object key rule: 1 to 1024 bytes, one line.

func CheckPage

func CheckPage(count uint64, root [32]byte, p, a string, max int, entries []PageEntry, leaves []MapLeaf) error

CheckPage is a reader's check of a list or export page (spec section 11.3) against a token of count keys and root, for prefix p (empty for export), after a, and the page maximum max (256 for list, 512 for export). Every entry's and every leaf's path is checked first (rule path), then checks 1 to 4 in order (rules check-1 to check-4). A page that fails is incomplete and names the host.

func CheckPageOrder

func CheckPageOrder(count uint64, p, a string, max int, answered []PageKey, r0, r1, r2 *PageKey) error

CheckPageOrder is checks 1 to 4 of spec section 11.3 on positions whose paths are already proven: the answered entries, and the role 0, role 1 and role 2 leaves (nil when absent).

func CheckRoot

func CheckRoot(rootBytes []byte, root [32]byte, size uint64, contentHash [32]byte) (*chirp.Root, error)

CheckRoot holds a root node's bytes to bstore's root rules (spec sections 5 and 15.2 step 6): it hashes to root, decodes as a CHIRP version 1.0 root (a later minor version is refused), declares chunking profile 1, carries no extension (bcommon's decoder keeps advisory extensions, so bstore checks the root holds none itself), and its logicalLength and contentHash are the entry's. Rule names the first that fails.

func CheckWalk

func CheckWalk(held *Held, walk []Link) error

CheckWalk is a reader's step 1 on tokens it verified against its own headers, latest first, walked back by prev to the token it holds or to seq 0 (spec section 15.1). held is nil when it holds none. It is rollback when the latest is below the seq held; else bucket when two neighbours do not link (prev is the next one's txid, seq one lower, the same bucket, owner and id), when the walk stops above seq 0 other than on the token held (the same seq and txid), or when it reaches seq 0 and the id is not the bucket id of the outpoint that token spends (bucket-id at admission).

func CheckWriter

func CheckWriter(e *Entry, tok *Bucket) error

CheckWriter is a reader's step 4: the writer is the token's owner or one of its writers (the token the answer is proven against).

func CheckedFetch added in v0.8.0

func CheckedFetch(fetch chirp.Fetch) (checked chirp.Fetch, wrong func() bool)

CheckedFetch wraps fetch to take only bytes hashing to the hash asked for: other bytes are refused as not served. wrong reports whether that ever happened, so ClosureError can tell missing from hash.

func ClosureError added in v0.8.0

func ClosureError(err error, wrong bool) error

ClosureError labels a refusal of bcommon chirp.Verify, or of chirp.Incremental, as VerifyCHIRP does; wrong is CheckedFetch's report.

func CompactSize

func CompactSize(v uint64) []byte

CompactSize is Bitcoin's CompactSize encoding of v.

func DerivationPrefix

func DerivationPrefix(c [32]byte) string

DerivationPrefix is base64(C), standard padded base64 of the entry's commitment in hash byte order.

func DerivationSuffix

func DerivationSuffix(rank int) string

DerivationSuffix is base64(uint16be(rank)).

func DerivedFront

func DerivedFront(adURL string) (string, bool)

DerivedFront is the front of a provider that answers for itself: its advertisement's url up to, not including, the last "/chirp/v1/", followed by "/bstore/v1" (spec section 10.1). ok is false when the url holds no "/chirp/v1/".

func Detect

func Detect(c int, f float64) float64

Detect is the probability that one challenge of c samples catches a provider that lacks a fraction f of the segments: 1 - (1 - f)^c.

func DetectionTables

func DetectionTables() (string, string)

DetectionTables writes spec section 7.6's two tables as the spec prints them, so that a test holds the spec's figures to the formula.

func Eligibility

func Eligibility(ad *Advertisement, e *Entry, rootLen uint64) string

Eligibility is why an advertisement does or does not count for an entry's bounty (spec section 9.3); "" is eligible.

func EncodeTokenContext

func EncodeTokenContext(leaves []MapLeaf) ([]byte, error)

EncodeTokenContext writes a token's context, at most two leaves.

func FundingScript

func FundingScript(key *ec.PublicKey) []byte

FundingScript is a funding output locked to key: <key> OP_CHECKSIG <73 74 02> OP_DROP, unsigned.

func HashBlob added in v0.16.0

func HashBlob(blob []byte) (hash [32]byte, leaves []byte, sub [32]byte)

HashBlob is a blob's three hashes from one pass over its bytes: its SHA-256 (the object it is), the leaf hash of each SegmentSize segment (commit.HashLeaf, 32 bytes a segment, in order) and the subtree root over them (commit.RootOfLeafHashes), which a proof root is composed of. Each segment is read once, while it is in cache, by both digests, and the leaf digest is reused across segments, so nothing is allocated but the leaves. The values are exactly those of sha256.Sum256, commit.HashLeaf and commit.RootOfLeafHashes over the same bytes.

func HoldScript

func HoldScript(key *ec.PublicKey) []byte

HoldScript is a hold output locked to key: <key> OP_CHECKSIG <73 74 03> OP_DROP.

func Leaf

func Leaf(key string, c [32]byte) []byte

Leaf is a map leaf's bytes: uint16be(len(key)) || key || C.

func LeavesLen added in v0.27.0

func LeavesLen(n int) int

LeavesLen is the length of a blob's segment leaves: 32 bytes for each SegmentSize segment of n bytes, the last one short or not.

func LeavesOf added in v0.24.0

func LeavesOf(blob []byte) (leaves []byte, sub [32]byte)

LeavesOf is HashBlob without the blob's own SHA-256, for a caller that already knows it: the segment leaves and their subtree root, the same as HashBlob's.

func LockingKey

func LockingKey(d pushdrop.Derivation, identity []byte) (*ec.PublicKey, error)

LockingKey is the key an identity's output is locked to under d, derived from the identity key alone (counterparty anyone). A key derived is remembered (keycache.go).

func OneLine

func OneLine(s string) bool

OneLine reports whether s holds no control character (U+0000 to U+001F, U+007F to U+009F) and neither U+2028 nor U+2029 (spec section 2). s is valid UTF-8 (the CBOR decoder refuses anything else).

func Payouts

func Payouts(r uint64, k int) []uint64

Payouts is spec section 9.5's rule for k ranks and the hold output's value r: weight(i) = sqrt(k - i + 1) in IEEE-754 binary64, S their sum in rank order, payout(i) = floor(r * weight(i) / S), and the remainder to rank 1. A payout of 0 gets no output; the payouts always sum to r. r must be at most 2,100,000,000,000,000 (below 2^53, so binary64 holds it).

func PieceAt added in v0.11.0

func PieceAt(rec []byte, n int) int

PieceAt is where the piece's n bytes begin in a record Encode wrote: its last field is key PKPiece, a byte string of n bytes, so the piece ends where the record does. It is -1 when the record does not end that way (a record with Extra keys, or n not its piece's length).

func ProofRoot

func ProofRoot(content []byte) [32]byte

ProofRoot is the proof root of content (spec section 6): the RFC 6962 Merkle Tree Hash over its 4 KiB segments in order, the last unpadded; SHA-256 of the empty string for no bytes.

func ProofRootOfBlobs

func ProofRootOfBlobs(blobs [][]byte) [32]byte

ProofRootOfBlobs is the proof root as built per blob: each blob's subtree root, then RFC 6962's split over the subtree roots taken as nodes. It equals ProofRoot because every blob but the last holds exactly 1024 segments (bcommon commit.RootOfSubtrees).

func Reason

func Reason(err error) string

Reason is the fixed label a host counts a refusal by, and a reader or a buyer names a failed check by. A refusal of no defined label is "other".

func RecordsTopic

func RecordsTopic(bucket string) string

RecordsTopic and BlobTopic are a bucket's two topics.

func RequestHash

func RequestHash(raw []byte) [32]byte

Hash is SHA-256 of a request's encoding.

func RootOfLeaves added in v0.27.0

func RootOfLeaves(leaves []byte) [32]byte

RootOfLeaves is the subtree root over a blob's segment leaves (32 bytes a segment, in order, as LeavesOf returns them): the blob's share of a proof root, recomputed from the leaves alone, without the blob.

func Rule

func Rule(err error) string

Rule is the codec's finer name for a refusal inside a label that covers several rules (a request inside `request`, a page check inside `map`); it is pinned by the vectors but is not a label of the contract.

func S3Name

func S3Name(bucket string) (string, bool)

S3Name is a bucket identifier as an S3 bucket name (spec section 16.1), and whether the gateway refuses it for S3 use (the sthree- prefix).

func SamplesFor

func SamplesFor(f, conf float64) int

SamplesFor is the least c that catches a loss of f with probability at least conf: ceil(ln(1 - conf) / ln(1 - f)).

func SegmentLen

func SegmentLen(i, size uint64) uint64

SegmentLen is the length of segment i of an object of size bytes.

func SegmentRootOf added in v0.13.0

func SegmentRootOf(blob []byte) [32]byte

SegmentRootOf is commit.SegmentRoot of a blob at SegmentSize, the segment subtree root a proof root is composed of, hashed in place: each segment is a slice of the blob, copied nowhere.

func Segments

func Segments(size uint64) uint64

Segments is the number of 4 KiB segments of an object of size bytes.

func SignNotTaken added in v0.3.0

func SignNotTaken(priv *ec.PrivateKey, body []byte) ([]byte, error)

SignNotTaken signs a note's body with the answerer's derived challenge key and returns the signed note [body, signature].

func SignResponse

func SignResponse(priv *ec.PrivateKey, requestRaw, body []byte) ([]byte, error)

SignResponse signs a body with the answerer's derived challenge key and returns the signed response [body, signature].

func SignedDigest

func SignedDigest(requestHash, responseHash [32]byte) [32]byte

SignedDigest is what a response signature covers: SHA-256 of SHA-256(request) || response hash (64 bytes), as BRC-100's createSignature computes a signature over data.

func SignedNotTaken added in v0.3.0

func SignedNotTaken(body, sig []byte) ([]byte, error)

SignedNotTaken wraps a body and its signature as a signed note.

func SincePosition added in v0.28.0

func SincePosition(s string) bool

SincePosition reports whether s is a position a since answer gives: 16 decimal digits (the host's time, Unix milliseconds), a colon, a txid of 64 lowercase hex digits in display order, a colon and the output index as 10 decimal digits. Positions compare as bytes.

func SplitSigned

func SplitSigned(signed []byte) (body, sig []byte, ok bool)

SplitSigned reads a signed response [body, signature] as byte strings.

func TieKey added in v0.1.2

func TieKey(txid [32]byte, vout uint32, c [32]byte) [32]byte

TieKey is the key that breaks a tie in first sight (spec section 9.4, as amended): SHA-256 over 68 bytes, the advertisement's txid in hash byte order (32), its output index as 4 bytes little-endian, and the entry's commitment C (32). The lower key, compared as bytes, ranks first. C does not exist until the entry does, so no advertiser can grind a txid toward a low key before it.

func TokenBEEF

func TokenBEEF(token, parent *transaction.Transaction) ([]byte, error)

TokenBEEF assembles the BEEF a bucket token is admitted in (bcommon chaintoken.TokenBEEF): a replayer builds it from the token and its parent.

func VerifyCHIRP

func VerifyCHIRP(rootHash [32]byte, fetch chirp.Fetch) (*chirp.Closure, error)

VerifyCHIRP is bcommon chirp.Verify with ClosureLimits behind a fetch that takes only bytes hashing to the hash asked for, as a reader that asks several advertisers does, with its refusals as labels: an object no fetch served, or served only as other bytes, is closure (rule missing or hash); a node's own checks, a length, depth, cycle, references, too-large or canonical construction is root (the closure the root names is not valid, whoever serves it); content-hash is content.

func VerifyCarried added in v0.27.0

func VerifyCarried(rootHash [32]byte, fetch chirp.Fetch, held func(chirp.Child) bool) (*chirp.Closure, error)

VerifyCarried is VerifyCHIRP for a closure whose blobs the caller holds on its own account: held reports a blob reference whose bytes the caller holds, at the reference's length, as bytes hashed to the reference's name before they were stored, as a storage node's provider holds the pieces its own gateway staged and handed it in process. Such a blob is not read. The rest is VerifyCHIRP's: the root and every branch are fetched and hashed before any field of theirs is read, every node check, length, depth, cycle, reference bound and the canonical construction is applied, and a blob held does not report is fetched and held to its length and its hash.

The content hash is not recomputed: it is the root's, and the call is only for a root the caller's account covers (the gateway computed that content hash over the bytes it staged and handed over). Refusals are labelled as VerifyCHIRP labels them.

func VerifyChallengeSig

func VerifyChallengeSig(answerer []byte, requestHash, responseHash [32]byte, sig []byte) bool

VerifyChallengeSig checks a strict low-S DER signature over SignedDigest under derive(answerer, "challenge").

func VerifyClosure

func VerifyClosure(e *Entry, fetch chirp.Fetch, proof bool) (*chirp.Closure, error)

VerifyClosure is a provider's check before it holds, and a reader's steps 6 to 9 on a whole read (spec sections 9.3 and 15.2): the root fetched (closure when none is served as its hash), CheckRoot (root), the closure by VerifyCHIRP, then, when proof is true, the proof root recomputed over the content against the entry's (proof-root). It returns the verified closure.

Types

type Ad struct {
	Txid       [32]byte // hash byte order
	Vout       uint32
	Advertiser []byte
	Root       [32]byte
	Expiry     uint64
	// SpentBy is the advertisements of the transaction that spends this
	// one, when it is spent: a renewal holds its successor among them.
	Spent   bool
	SpentBy []*Ad
}

Ad is one advertisement as the writer's client knows it at settlement.

func (*Ad) Live

func (a *Ad) Live() bool

Live follows an advertisement's renewal successors (an advertisement of the same key for the same root, with a later expiry, in the transaction that spends it, or that successor's own) and reports whether the last is unspent: a renewal counts as unspent, a spend by anything else cancels.

type Admission

type Admission struct {
	Kind    TxKind
	Txid    [32]byte
	Outputs []int
	Retain  []int
	Carrier *Carrier
	// Token, Predecessor (nil at seq 0), Parent and Spends for a token.
	Token       *Token
	Predecessor *Token
	Parent      [32]byte
	Spends      transaction.Outpoint
	// Ads and Holds index the admitted outputs of a mined object.
	Ads   map[int]*Advertisement
	Holds []int
	// Spent is every outpoint a sweep's inputs spend.
	Spent []transaction.Outpoint
}

Admission is what a host admits from one transaction (BRC-22's admittance instructions) and what the lookup service records.

func Admit

func Admit(ctx context.Context, beef []byte, held []int, h Host) (*Admission, error)

Admit applies spec section 12.1 to one submission: the BEEF as it arrived, and held, the indices of its subject's inputs that spend an output the topic holds (BRC-22's previous coins). held decides only what is retained, never a verdict: every rule reads the submission's own bytes and the host's headers alone. SPV of the BEEF is the engine's and is assumed to have run. Every refusal is an error, which a topic manager raises. Admit is Prepare and then Pending.Admit.

type Advertisement struct {
	Host      []byte
	Hash      [32]byte
	URL       string
	Expiry    uint64
	FileSize  uint64
	Signature []byte
}

Advertisement is a BRC-26 advertisement output as the SDK decodes and verifies it (ts-stack @bsv/sdk storage/UHRPAdvertisementValidation.ts).

func DecodeAdvertisement

func DecodeAdvertisement(script []byte) (*Advertisement, error)

DecodeAdvertisement decodes and verifies one advertisement output's locking script exactly as the SDK does: a canonical PushDrop of six fields, at most 2,048 bytes each and 2,304 together, locked before; a canonical compressed host key; a 32-byte hash; a url of 1 to 2,048 bytes, strict UTF-8 (one leading BOM dropped), no control character, a credential-free https URL with no fragment; expiry and file size as canonical positive CompactSize integers; a canonical DER signature of 8 to 80 bytes, any S; the lock the key derived for the host under [2, "uhrp advertisement"] key id 1, counterparty anyone; and the signature over the first five fields concatenated under that key.

type Applicable

type Applicable struct {
	C       [32]byte
	Key     string
	Kind    uint64
	Created uint64
}

Applicable is an entry as the owner's anchoring tooling sees it.

type Body

type Body struct {
	Request  [32]byte
	Samples  []Sample
	Answerer []byte
}

Body is a response body (magic str 0x01).

func Answer

func Answer(req *Request, requestRaw, content []byte, t *ProofTree, inline bool) *Body

Answer builds the response body for a request from the content: inline segments when inline, else every segment by reference (null).

func DecodeBody

func DecodeBody(raw []byte) (*Body, error)

DecodeBody reads a response body for spec section 7.3's shape alone: the record steps, unknown-key, then per key missing and type, every sample [byte string or null, array of 32-byte strings] (samples). How many samples, and whether they fit the request, is the buyer's check.

func (*Body) Encode

func (r *Body) Encode() ([]byte, error)

Encode writes the body canonically.

func (*Body) View

func (r *Body) View() map[string]any

View is the response body's view.

type Bucket

type Bucket struct {
	Bucket   string
	Owner    []byte
	ID       [32]byte
	Seq      uint64
	Prev     [32]byte
	Writers  [][]byte
	Changes  []Change
	Count    uint64
	MapRoot  [32]byte
	Created  uint64
	Consumed [][32]byte
	// Extra holds keys 12 and above, verbatim.
	Extra cbor.Map
}

Bucket is the bucket record (magic stb 0x01) a token carries.

func DecodeBucket

func DecodeBucket(raw []byte) (*Bucket, error)

DecodeBucket reads a bucket record, refusing it for the first rule it breaks in the order of spec section 3.2: too-large, cbor, key-type, magic, then per key in key order missing, type and the key's own rule, then first.

func (*Bucket) Encode

func (r *Bucket) Encode() ([]byte, error)

Encode writes the record canonically. It refuses what DecodeBucket refuses, so a record this package writes is one it reads.

func (*Bucket) EncodedSize

func (r *Bucket) EncodedSize() (int, error)

EncodedSize is the length the record encodes to, whatever its bounds: what the owner's tooling measures when it splits changes over tokens.

func (*Bucket) View

func (r *Bucket) View() map[string]any

View is the bucket record's view.

type Built

type Built struct {
	chirp.Built
	ContentHash [32]byte
	ProofRoot   [32]byte
	Size        uint64
}

Built is an object's CHIRP Profile 1 closure, as bstore builds it (no extension on the root), and its proof root.

func Build

func Build(content []byte) (*Built, error)

Build builds an object's closure and proof root from content in memory.

func (*Built) Objects

func (b *Built) Objects() [][]byte

Objects are the closure's distinct objects in publishing order: the root, the branches, then the blobs, each once.

func (*Built) Pieces

func (b *Built) Pieces(bucket string, writer []byte) []*Piece

Pieces are the closure's pieces for a bucket and writer: one per distinct object (spec section 5).

type Candidate

type Candidate struct {
	Ad        *Ad
	FirstSeen uint64
	Passed    bool
}

Candidate is an eligible advertisement in the writer's race: when its client first saw it, and whether it passed its settlement challenge.

func Rank

func Rank(c [32]byte, cands []Candidate) []Candidate

Rank orders candidates as the writer's client does for the entry whose commitment is c (spec section 9.4): by first sight, ties to the lower TieKey; each advertiser counted once, at its first place; the anyone key never.

type Carrier

type Carrier struct {
	Kind       TxKind
	Record     []byte
	Entry      *Entry
	Outcome    *Outcome
	Front      *Front
	Commitment [32]byte
	Funding    transaction.Outpoint
}

Carrier is an admitted carrier and the record it holds.

type Change

type Change struct {
	Key     string
	C       [32]byte
	Removal bool
}

Change is one change of a bucket record: a put [key, C] sets the key to the put entry's commitment C; a removal [key, Z, D] removes the key, D being the delete entry's commitment.

func ResolveBatch

func ResolveBatch(current Map, named map[[32]byte]bool, batch []Applicable) ([]Change, [][32]byte)

ResolveBatch is the owner's tooling (spec section 3.4): from the entries it would apply against the current map, it skips every entry a token of the chain has named (and every kind other than put and delete); orders one key's entries by created, then by commitment, the last deciding the key's change and the others going to consumed; and moves to consumed every change that would not change the map (a delete of a key the map does not hold, a put of the value the key already names). Changes come back ascending by key and consumed ascending, so that no change it writes can be a fold error.

type Claim

type Claim string

Claim names what an output claims to be (spec section 12.1, Classify).

const (
	ClaimNone    Claim = ""
	ClaimToken   Claim = "bucket-token"
	ClaimEntry   Claim = "entry"
	ClaimOutcome Claim = "outcome"
	ClaimFront   Claim = "front"
	ClaimPiece   Claim = "piece"
	ClaimFunding Claim = "funding"
	ClaimHold    Claim = "hold"
)

func Classify

func Classify(s []byte) Claim

Classify says what a locking script claims, reading nothing else of it: 0x21, 33 bytes, 0xac, then one push whose data is exactly 73 74 01 (a bucket token) or starts with a CBOR definite-length map head, 00 44 and the magic of an entry, an outcome, a front statement or a piece; or the whole script 21 <33> ac 03 73 74 02 75 (funding-shaped) or 21 <33> ac 03 73 74 03 75 (hold-shaped).

func (Claim) Claims

func (c Claim) Claims() bool

Claims reports whether a claim is one of the claiming kinds (a token or a record), as against a shape (funding, hold) or nothing.

type Class

type Class struct {
	Name    string
	Members []string
	Free    bool
	Served  bool
}

Class is one lookup question class of spec section 11.1: its members, whether it is free, and whether it answers only for a served chain.

func AllClasses added in v0.28.0

func AllClasses() []Class

AllClasses are Classes and the classes amendments added, in that order.

type Entry

type Entry struct {
	Bucket  string
	ID      [32]byte
	Writer  []byte
	Key     string
	Kind    uint64
	Created uint64

	// A put's keys.
	Size         uint64
	Root         [32]byte
	ContentHash  [32]byte
	ProofRoot    [32]byte
	ProofProfile uint64
	ContentType  string
	ETag         *string
	Meta         []MetaPair // nil when absent; ascending by key as CBOR orders them
	Hold         *Hold

	// Unknown holds, for a kind from 3 to 255, its keys 7 to 15 as read,
	// unchecked, so that it re-encodes verbatim.
	Unknown cbor.Map
	// Extra holds keys 16 and above, verbatim.
	Extra cbor.Map
}

Entry is the object entry (magic ste 0x01).

func DecodeEntry

func DecodeEntry(raw []byte) (*Entry, error)

DecodeEntry reads an object entry in the order of spec section 4.2: too-large, cbor, key-type, magic, then keys 0 to 6 in key order (missing, type, own rule); then, for a put, keys 7 to 15 in key order where present (type, own rule); then kind (a key the kind does not carry is present, or one it carries is missing); then empty. A delete's keys 7 to 15 are not read: their presence is kind. A kind from 3 to 255 is checked for keys 0 to 6 only and its keys 7 to 15 kept as read.

func (*Entry) Encode

func (e *Entry) Encode() ([]byte, error)

Encode writes the entry canonically; it refuses what DecodeEntry refuses.

func (*Entry) View

func (e *Entry) View() map[string]any

View is the entry's view.

type EntryContext

type EntryContext struct {
	Index uint64
	Path  [][32]byte
}

EntryContext is an entry's context [index, path].

func DecodeEntryContext

func DecodeEntryContext(raw []byte) (EntryContext, error)

DecodeEntryContext reads an entry's context: map with rule too-large (over 1,024 bytes), cbor, or shape ([index, path], index at most 1,048,575, path at most 20 32-byte steps).

func (EntryContext) Encode

func (c EntryContext) Encode() ([]byte, error)

Encode writes an entry's context.

type Fetcher

type Fetcher interface {
	Range(blob, offset, length uint64) ([]byte, error)
	Blob(blob uint64) ([]byte, error)
}

Fetcher is the buyer's view of the tested URL: a Range fetch of one segment within its blob, and a whole blob, by blob index.

type Fold

type Fold struct {
	// Statuses has one status per token given.
	Statuses []Status
	// Reasons names, for each map-mismatch token that broke the chain, what
	// broke it; "" for the rest.
	Reasons []string
	// Map is the map of the last consistent token; Named is every
	// commitment the consistent tokens named.
	Map   Map
	Named map[[32]byte]bool
}

Fold is a chain folded from seq 0.

func FoldChain

func FoldChain(tokens []*Bucket) (*Fold, error)

FoldChain folds the rooted tokens of one chain, given in seq order from 0, as a host and a replaying reader do: each token's changes applied to its predecessor's map in changes order must each change the map, name no commitment an earlier token of the chain (or an earlier change of its own) named, and leave a map of count keys, at most 1,048,576, whose root is mapRoot; else map-mismatch, which is sticky.

type Front

type Front struct {
	Bucket     string
	Front      []byte
	Advertiser []byte
	URL        string
	Created    uint64
	Extra      cbor.Map
}

Front is the front statement (magic stf 0x01).

func DecodeFront

func DecodeFront(raw []byte) (*Front, error)

DecodeFront reads a front statement in the order of spec section 8.2: too-large, cbor, key-type, magic, per key missing, type and its rule (bucket, identity, identity, url, created).

func (*Front) Encode

func (s *Front) Encode() ([]byte, error)

Encode writes the statement canonically; it refuses what DecodeFront refuses.

func (*Front) View

func (s *Front) View() map[string]any

View is the front statement's view.

type Held

type Held struct {
	Seq  uint64
	Txid [32]byte
}

Held is the token a reader holds for a chain: the highest seq it verified, and that token's txid.

type Hold

type Hold struct {
	Txid      [32]byte // hash byte order
	Vout      uint64
	Satoshis  uint64
	T         uint64
	K         uint64
	Retention uint64
	Deadline  uint64
	CheckC    uint64
}

Hold is an entry's hold terms (spec section 4.3).

func ReadHold

func ReadHold(a []cbor.Value) (*Hold, error)

ReadHold holds a hold array to spec section 4.3. Every failure is hold.

func (*Hold) View

func (h *Hold) View() map[string]any

View is the hold terms' view.

type Host

type Host struct {
	Bucket         string
	Headers        chaintracker.ChainTracker
	MaxBEEF        int
	MaxSweepInputs int
}

Host is what admission needs beyond the submission: the topic's bucket identifier, a chain tracker over the host's own block headers, the host's BEEF bound and its sweep input bound. A bound of zero is its floor; a bound below its floor is a configuration the host refuses to run with (ErrHostConfig). Nothing the topic holds is here: a verdict never reads another record (spec section 12.1).

type Link struct {
	Txid   [32]byte
	Bucket *Bucket
	Spends *Outpoint
}

Link is one token of a walk: its txid (hash byte order), its record and, for the token at seq 0, the outpoint its chain-tree input spends.

type Map

type Map map[string][32]byte

Map is a key map: key to commitment.

func (Map) Clone

func (m Map) Clone() Map

Clone copies the map.

func (Map) Keys

func (m Map) Keys() []string

Keys returns the map's keys ascending by their bytes.

func (Map) Leaves

func (m Map) Leaves() [][]byte

Leaves returns the map's leaves in key order.

func (Map) ProveEntry

func (m Map) ProveEntry(key string) (EntryContext, bool)

ProveEntry returns the context of the entry for key in m.

func (Map) ProveObject

func (m Map) ProveObject(k string, held func([32]byte) bool) (*EntryContext, []MapLeaf)

ProveObject is the honest answer for k: the entry's context when the map names k and held(c), else the role 2 leaf, or the absence leaves.

func (Map) ProvePage

func (m Map) ProvePage(p, a string, max int, held func([32]byte) bool) ([]PageEntry, []MapLeaf)

ProvePage is the honest page for prefix p after a of at most max entries, stopping at the first entry in range that held refuses (role 2).

func (Map) Root

func (m Map) Root() [32]byte

Root is the map root (spec section 3.4).

type MapLeaf

type MapLeaf struct {
	Role  uint64
	Index uint64
	Key   string
	C     [32]byte
	Path  [][32]byte
}

MapLeaf is one leaf of a token's context [role, index, key, C, path].

func DecodeTokenContext

func DecodeTokenContext(raw []byte) ([]MapLeaf, error)

DecodeTokenContext reads a token's context: map with rule too-large (over 4,096 bytes), cbor, or shape (an array of at most two leaves [role, index, key, C, path], role 0 to 2, index at most 1,048,575, key an object key, C 32 bytes, path at most 20 steps; at most one leaf of each role, in role order, and no role 1 beside a role 2).

type MetaPair

type MetaPair struct {
	Key, Value string
}

MetaPair is one pair of an entry's meta map.

type NotTaken added in v0.3.0

type NotTaken struct {
	// Payment is the payment's txid, hash byte order; Request the SHA-256
	// of the request it came with.
	Payment  [32]byte
	Request  [32]byte
	Reason   string
	Time     uint64
	Answerer []byte
}

NotTaken is the body of a payment-not-taken note.

func CheckNotTaken added in v0.3.0

func CheckNotTaken(signed []byte, payment [32]byte, request []byte, answerer []byte) (*NotTaken, error)

CheckNotTaken is the buyer's check of a note it was handed for its own payment: it verifies, and names the payment (hash byte order), the request it sent and the answerer it asked. Anything else is refused, and the payment's coin stays held.

func DecodeNotTakenBody added in v0.3.0

func DecodeNotTakenBody(raw []byte) (*NotTaken, error)

DecodeNotTakenBody reads a note's body. Every refusal is ErrNotTaken; its rule is, in order: too-large, cbor, key-type, magic, unknown-key (a key above 5), then per key missing, type and its rule: reason, time, identity (the answerer).

func VerifyNotTaken added in v0.3.0

func VerifyNotTaken(signed []byte) (*NotTaken, error)

VerifyNotTaken reads a signed note and checks its signature under derive(answerer, "challenge") of the answerer the body names. Its rules, beyond the body's: too-large (over 512 bytes in all), shape (not [body, signature] as byte strings), signature (not strict low-S DER, or not verifying).

func (*NotTaken) Encode added in v0.3.0

func (n *NotTaken) Encode() ([]byte, error)

Encode writes the body, checked by DecodeNotTakenBody.

type ObjectResult

type ObjectResult int

ObjectResult is what an object answer proves about key k.

const (
	ObjectFound ObjectResult = iota + 1
	ObjectAbsent
	ObjectUnheld
)

func CheckHead

func CheckHead(tok *Bucket, key string, c *[32]byte, e *Entry, ctx *EntryContext, leaves []MapLeaf) (ObjectResult, error)

CheckHead is a reader's steps 2 to 5 for an object answer whose token it verified (step 1) and whose carrier it verified (SPV and the carrier rules): the context proves (key, C) or absence, the entry is the one asked for, by a writer of the token, and a put. A head (S3 HeadObject) stops here; it never asks a provider. It returns what the answer proves: found (with the entry), absent, or unheld (incomplete, never absent).

func CheckObject

func CheckObject(count uint64, root [32]byte, k string, entry *[32]byte, ctx *EntryContext, leaves []MapLeaf) (ObjectResult, [32]byte, error)

CheckObject is a reader's step 2 for an object answer (spec section 11.3): with an entry (its commitment c and context), the token's context is empty and (k, c) is proven at the context's index; without one, the token's context is either the role 2 leaf whose key is k (the key exists, its entry unheld) or proves k absent: role 0 at j with a key below k and role 1 at j + 1 with a key above it, role 0 absent when j + 1 = 0 and role 1 absent when j + 1 = count. It returns the commitment the map names for k when it names one.

type Outcome

type Outcome struct {
	Bucket  string
	Buyer   []byte
	Created uint64
	// Request is the request's exact encoding; Req is it decoded.
	Request []byte
	Req     *Request
	Outcome uint64
	// Response and Signature, for outcomes 1 and 2 only.
	Response  *[32]byte
	Signature []byte
	Extra     cbor.Map
}

Outcome is the outcome record (magic sto 0x01).

func DecodeOutcome

func DecodeOutcome(raw []byte) (*Outcome, error)

DecodeOutcome reads an outcome record in the order of spec section 8.1: too-large, cbor, key-type, magic, per key missing, type and its rule (bucket, identity, created, request, outcome; response and signature, where present, by type), then kind (keys 6 and 7 present exactly for outcomes 1 and 2), then response-signature (for outcomes 1 and 2, the signature is strict low-S DER and verifies over SHA-256(request) || response under derive(answerer, "challenge"), answerer from the request).

func (*Outcome) Encode

func (o *Outcome) Encode() ([]byte, error)

Encode writes the outcome canonically; it refuses what DecodeOutcome refuses.

func (*Outcome) View

func (o *Outcome) View() map[string]any

View is the outcome's view.

type Outpoint

type Outpoint struct {
	Txid [32]byte
	Vout uint32
}

Outpoint is a txid in hash byte order and an output index.

type PageEntry

type PageEntry struct {
	Key string
	C   [32]byte
	Ctx EntryContext
}

PageEntry is one answered entry of a page: its key, its commitment and its context.

type PageKey

type PageKey struct {
	Index uint64
	Key   string
}

PageKey is a page position: an index and the key there.

type Parallel added in v0.5.0

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

Parallel builds the same closure and proof root as Streaming, with the hashing spread over several cores by bcommon chirp.ParallelChunker: each complete blob is hashed (its SHA-256, which names it, and its segment subtree) and handed to store by one of workers goroutines, while one more goroutine hashes the content in order. Memory holds at most workers + 2 blobs.

store is called concurrently, from the worker goroutines, once per blob with its index and hash; the slice is reused after it returns. The first error from store stops the build: Write and Finish return it.

func NewParallel added in v0.5.0

func NewParallel(workers int, store func(i int, h [32]byte, blob []byte) error) *Parallel

NewParallel returns a parallel builder with workers blob hashers (chirp.DefaultWorkers when 0 or less) that hands each blob, with its index and hash, to store.

func NewParallelLeaves added in v0.27.0

func NewParallelLeaves(workers int, store func(i int, h [32]byte, blob, leaves []byte) error) *Parallel

NewParallelLeaves is NewParallel that also hands store each blob's segment leaves (LeavesOf: 32 bytes a segment), from the same pass that composes the proof root, for a caller that passes them on with the blob. The leaves are store's to keep.

func (*Parallel) Abort added in v0.5.0

func (p *Parallel) Abort()

Abort stops the builder without a result; it is safe after Finish.

func (*Parallel) Finish added in v0.5.0

func (p *Parallel) Finish() (*Built, error)

Finish hands over the last blob, waits for every blob, and returns the closure (Blobs nil) and its proof root.

func (*Parallel) Write added in v0.5.0

func (p *Parallel) Write(b []byte) (int, error)

Write takes content in order.

type Payee

type Payee struct {
	Rank       int
	Advertiser []byte
	Ad         [32]byte
	Satoshis   uint64
	Prefix     string
	Suffix     string
}

Payee is one rank of a settlement.

type Pending added in v0.11.0

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

Pending is one submission decided on every rule before held is known: Prepare's half of Admit. Since no rule reads what the topic holds, a host may prepare a submission before it takes the topic's lock and finish it with held under the lock.

func Prepare added in v0.11.0

func Prepare(ctx context.Context, beef []byte, h Host) *Pending

Prepare applies every rule of Admit to beef but the range of held.

func (*Pending) Admit added in v0.11.0

func (p *Pending) Admit(held []int) (*Admission, error)

Admit finishes a prepared admission with held, as Admit would have decided it: a BEEF refused stays refused whatever held is, held out of range comes before every other rule, and an admission retains held.

type Piece

type Piece struct {
	Bucket string
	Writer []byte
	Root   [32]byte
	Piece  []byte
	Extra  cbor.Map
}

Piece is one CHIRP object of one closure (magic stp 0x01).

func DecodePiece

func DecodePiece(raw []byte) (*Piece, error)

DecodePiece reads a piece: too-large (over 4,194,560 bytes), cbor, key-type, magic, then per key missing, type and its rule: bucket, identity (writer), root bytes(32), piece (1 to 4,194,304 bytes). Spec section 5 lists no order; this is the one every other record follows.

func (*Piece) Encode

func (p *Piece) Encode() ([]byte, error)

Encode writes the piece canonically; it refuses what DecodePiece refuses. A piece without Extra is written directly, its 4 MiB appended once, and held to DecodePiece's rules without decoding it; one with Extra goes through the record codec and is read back.

func (*Piece) EncodeHead added in v0.27.0

func (p *Piece) EncodeHead() ([]byte, error)

EncodeHead is Encode without the piece's bytes, for a piece without Extra: the record is EncodeHead() followed by p.Piece, its last field, so a carrier can be minted over the two parts and the piece copied once, to where it is sent (carrier.MintOnce). The same refusals as Encode.

func (*Piece) Hash

func (p *Piece) Hash() [32]byte

Hash is the piece's identity, SHA-256 of its bytes.

func (*Piece) View

func (p *Piece) View() map[string]any

View is the piece's view; the piece itself is given by its hash and length.

type PieceCarrier

type PieceCarrier struct {
	Piece      *Piece
	Commitment [32]byte
	Funding    transaction.Outpoint
}

PieceCarrier is a piece carrier a provider took from a blob topic: the piece, its carrier's commitment and the funding outpoint it spends.

func CheckPieceCarrier

func CheckPieceCarrier(ctx context.Context, beef []byte, bucket string, headers chaintracker.ChainTracker) (*PieceCarrier, error)

CheckPieceCarrier holds a submission on a blob topic to a piece carrier's rules, as a host holds an entry carrier to its own (spec sections 5, 12.1 and 13.2): the carrier and its funding tree's minimal path, within the piece carrier's ceiling of 4,259,840 bytes; one output claiming a piece, whose record is a piece of this bucket; not mineable; one canonical signature push; the one-field signed PushDrop under derive(writer, "piece"); its field signature; and the funding output of the writer it spends, whose value it carries. When headers is set the funding tree's proof is checked against them as well: a provider takes pieces only from a writer that paid for a mined funding output.

No host admits a piece; this is a provider's check before it stores the bytes, so that what it keeps is a writer's signed piece and not anyone's junk. The bytes are trusted for nothing else: an object is named by its hash, and the closure check decides what it is.

The PieceCarrier returned aliases beef (chaintoken.ReadWireInPlace): its piece is the carrier's output script where it lies in beef. beef must not be reused or changed while the carrier or its piece is in use.

type ProofTree

type ProofTree struct {
	Size   uint64
	Leaves [][32]byte
}

ProofTree holds every segment's leaf hash of an object: what a bridge front keeps (32 bytes per segment) and answers paths from.

func NewProofTree

func NewProofTree(content []byte) *ProofTree

NewProofTree hashes content's segments.

func (*ProofTree) Path

func (t *ProofTree) Path(i uint64) [][32]byte

Path is segment i's audit path, leaf to root, siblings only.

func (*ProofTree) Root

func (t *ProofTree) Root() [32]byte

Root is the tree's proof root.

type Question

type Question struct {
	Class  string
	Values map[string]string
}

Question is a validated question: its class and its members as given.

func CheckQuery

func CheckQuery(q map[string]any, carries func(bucket string) bool, serves func(bucket, owner, id string) bool) (*Question, error)

CheckQuery is ParseQuery on a parsed object.

func ParseQuery

func ParseQuery(raw []byte, carries func(bucket string) bool, serves func(bucket, owner, id string) bool) (*Question, error)

ParseQuery validates a BRC-24 query given as JSON text, as parsed: a member given twice takes its last value. It must be an object carrying exactly the members of one class, each a string meeting its rule, naming a bucket the host carries (carries nil admits every bucket) and, for a served class, a chain the host serves (serves nil admits every chain); anything else is refused, never answered empty and never ignored.

type Request

type Request struct {
	Root       [32]byte
	ProofRoot  [32]byte
	Size       uint64
	Provider   []byte
	Answerer   []byte
	SeedHeight uint64
	SeedHash   [32]byte
	Nonce      [16]byte
	C          uint64
	// Range is [first, last] blob indices, or nil.
	Range *[2]uint64
}

Request is a challenge request (magic stq 0x01).

func AnswerCheck

func AnswerCheck(requestRaw []byte, tip uint64, headerAt func(height uint64) ([32]byte, bool),
	own func(root [32]byte) (proofRoot [32]byte, size uint64, ok bool)) (*Request, error)

AnswerCheck is an answerer's refusals before it answers (spec sections 7.2 and 10.1): request when the bytes are not a request, seed when its headers hold no block seedHash at seedHeight or seedHeight is outside tip - 6 to tip, unknown-root when it does not hold root or proofRoot or size is not its own computation for root. own reports the answerer's own proof root and size for a root it holds.

func DecodeRequest

func DecodeRequest(raw []byte) (*Request, error)

DecodeRequest reads a request. Every refusal is request; its rule is, in order: too-large (over 512 bytes), cbor, key-type, magic, unknown-key (a key above 10), then per key missing, type and its rule: identity for provider and answerer, size (1 to 2^43), seed-height (0 to 2^32 - 1), c (1 to 1024), range ([first, last], first <= last < the blob count).

func (*Request) Domain

func (q *Request) Domain() (m, offset uint64)

Domain is the number of segments the indices are drawn from, and the first of them: every segment without range, the segments of blobs first to last with it.

func (*Request) Encode

func (q *Request) Encode() ([]byte, error)

Encode writes the request canonically; it refuses what DecodeRequest refuses.

func (*Request) Index

func (q *Request) Index(k uint32) uint64

Index is the segment sample k asks for (spec section 7.2): the digest read as an unsigned little-endian integer, modulo the domain, offset by the domain's first segment.

func (*Request) IndexDigest

func (q *Request) IndexDigest(k uint32) [32]byte

IndexDigest is SHA-256(seedHash || proofRoot || provider || nonce || uint32le(k)).

func (*Request) View

func (q *Request) View() map[string]any

View is the request's view.

type Sample

type Sample struct {
	Segment  []byte // nil: by reference
	Siblings [][32]byte
}

Sample is one sample of a response: the segment, or nil when the answerer leaves it to be fetched, and the siblings of its audit path.

type Settlement

type Settlement struct {
	Settled bool
	// Dropped are the advertisers whose passed advertisement was cancelled
	// before settlement, in rank order.
	Dropped [][]byte
	Payees  []Payee
}

Settlement is the writer's decision at its race's close.

func Settle

func Settle(c [32]byte, r uint64, t, K int, cands []Candidate) Settlement

Settle applies spec sections 9.3 to 9.5: the ranked candidates that passed, the first K of them paid; a payee whose advertisement is cancelled (spent by anything but a renewal) is dropped, the ranks below move up and the next passed candidate fills the last place; the writer settles only if at least t remain, paying k = min(K, remaining) ranks of r by Payouts, each bound to entry commitment c and its rank. A rank whose payout is 0 is left out of Payees but keeps its number.

type Status

type Status string

Status is a rooted token's fold status (spec section 12.2).

const (
	StatusConsistent  Status = "consistent"
	StatusMapMismatch Status = "map-mismatch"
)

type Streaming

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

Streaming builds the closure and the proof root of content written in pieces, holding at most one blob and one segment: each blob goes to emit as soon as it is complete.

func NewStreaming

func NewStreaming(emit func(blob []byte) error) *Streaming

NewStreaming returns a streaming builder that hands each blob to emit.

func (*Streaming) Finish

func (s *Streaming) Finish() (*Built, error)

Finish hands over the last blob and returns the closure (Blobs nil) and its proof root.

func (*Streaming) Write

func (s *Streaming) Write(p []byte) (int, error)

Write takes content in order.

type Token

type Token struct {
	Bucket *Bucket
	Record []byte
	Vout   uint32
}

Token is a bucket token's output, its record decoded.

func ReadToken

func ReadToken(tx *transaction.Transaction) (*Token, error)

ReadToken reads the one bucket token a transaction holds, well formed, without its parent: how an index and a reader read a stored token.

type TxKind

type TxKind string

TxKind is what an admitted transaction is to the topic.

const (
	TxEntry   TxKind = "entry"
	TxOutcome TxKind = "outcome"
	TxFront   TxKind = "front"
	TxToken   TxKind = "bucket-token"
	TxMined   TxKind = "mined"
	TxSweep   TxKind = "sweep"
)

type Verdict

type Verdict struct {
	// Outcome is OutcomePass, OutcomeInvalid, OutcomeNoAnswer or
	// OutcomeUnretrievable.
	Outcome int
	// Err is the step that failed (nil for a pass); Sample is the sample it
	// failed at, -1 when no sample is concerned; Recheck is true when the
	// verdict came from the whole-blob recheck.
	Err     error
	Sample  int
	Recheck bool
	// Rechecked lists the by-reference samples the whole blob passed after
	// a fetched segment failed (the URL's Range handling was wrong).
	Rechecked []int
}

Verdict is a buyer's verdict on a signed response.

func VerifyResponse

func VerifyResponse(req *Request, requestRaw, signed []byte, blobHash func(blob uint64) [32]byte, fetch Fetcher) Verdict

VerifyResponse is the buyer's check of spec section 7.4: steps 1 to 3 once (signature, request, count with every path's length), then per sample in k order fetch, segment and path, stopping at the first that fails. A by-reference sample that fails step 4, 5 or 6 is rechecked from the whole blob: the blob is held to blobHash(blob) (its CHIRP object hash); if it verifies, the segment is taken from it and steps 5 and 6 run again (a pass, or invalid); if it does not verify or cannot be fetched, the sample is unretrievable. req must be a request DecodeRequest admits and requestRaw its encoding.

Jump to

Keyboard shortcuts

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