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
- Variables
- func AdvertisementFields(host []byte, adKey *ec.PrivateKey, hash [32]byte, url string, ...) ([][]byte, error)
- func AdvertisementScript(lock *ec.PublicKey, fields [][]byte) []byte
- func BlobSubtree(blob []byte) [32]byte
- func BlobTopic(bucket string) string
- func Blobs(size uint64) uint64
- func BucketID(txid [32]byte, vout uint32) [32]byte
- func CHIRPURLSuffix(root [32]byte) string
- func ChallengeKey(answerer []byte) (*ec.PublicKey, error)
- func CheckBucket(s string) error
- func CheckContentType(s string) error
- func CheckETag(s string) error
- func CheckEntry(e *Entry, bucket string, id [32]byte, key string) error
- func CheckFrontURL(s string) error
- func CheckKey(b []byte) (*ec.PublicKey, error)
- func CheckKind(e *Entry) error
- func CheckMetaKey(s string) bool
- func CheckObjectKey(k string) error
- func CheckPage(count uint64, root [32]byte, p, a string, max int, entries []PageEntry, ...) error
- func CheckPageOrder(count uint64, p, a string, max int, answered []PageKey, r0, r1, r2 *PageKey) error
- func CheckRoot(rootBytes []byte, root [32]byte, size uint64, contentHash [32]byte) (*chirp.Root, error)
- func CheckWalk(held *Held, walk []Link) error
- func CheckWriter(e *Entry, tok *Bucket) error
- func CheckedFetch(fetch chirp.Fetch) (checked chirp.Fetch, wrong func() bool)
- func ClosureError(err error, wrong bool) error
- func CompactSize(v uint64) []byte
- func DerivationPrefix(c [32]byte) string
- func DerivationSuffix(rank int) string
- func DerivedFront(adURL string) (string, bool)
- func Detect(c int, f float64) float64
- func DetectionTables() (string, string)
- func Eligibility(ad *Advertisement, e *Entry, rootLen uint64) string
- func EncodeTokenContext(leaves []MapLeaf) ([]byte, error)
- func FundingScript(key *ec.PublicKey) []byte
- func HoldScript(key *ec.PublicKey) []byte
- func Leaf(key string, c [32]byte) []byte
- func LockingKey(d pushdrop.Derivation, identity []byte) (*ec.PublicKey, error)
- func OneLine(s string) bool
- func Payouts(r uint64, k int) []uint64
- func PieceAt(rec []byte, n int) int
- func ProofRoot(content []byte) [32]byte
- func ProofRootOfBlobs(blobs [][]byte) [32]byte
- func Reason(err error) string
- func RecordsTopic(bucket string) string
- func RequestHash(raw []byte) [32]byte
- func Rule(err error) string
- func S3Name(bucket string) (string, bool)
- func SamplesFor(f, conf float64) int
- func SegmentLen(i, size uint64) uint64
- func Segments(size uint64) uint64
- func SignNotTaken(priv *ec.PrivateKey, body []byte) ([]byte, error)
- func SignResponse(priv *ec.PrivateKey, requestRaw, body []byte) ([]byte, error)
- func SignedDigest(requestHash, responseHash [32]byte) [32]byte
- func SignedNotTaken(body, sig []byte) ([]byte, error)
- func SplitSigned(signed []byte) (body, sig []byte, ok bool)
- func TieKey(txid [32]byte, vout uint32, c [32]byte) [32]byte
- func TokenBEEF(token, parent *transaction.Transaction) ([]byte, error)
- func VerifyCHIRP(rootHash [32]byte, fetch chirp.Fetch) (*chirp.Closure, error)
- func VerifyChallengeSig(answerer []byte, requestHash, responseHash [32]byte, sig []byte) bool
- func VerifyClosure(e *Entry, fetch chirp.Fetch, proof bool) (*chirp.Closure, error)
- type Ad
- type Admission
- type Advertisement
- type Applicable
- type Body
- type Bucket
- type Built
- type Candidate
- type Carrier
- type Change
- type Claim
- type Class
- type Entry
- type EntryContext
- type Fetcher
- type Fold
- type Front
- type Held
- type Hold
- type Host
- type Link
- type Map
- func (m Map) Clone() Map
- func (m Map) Keys() []string
- func (m Map) Leaves() [][]byte
- func (m Map) ProveEntry(key string) (EntryContext, bool)
- func (m Map) ProveObject(k string, held func([32]byte) bool) (*EntryContext, []MapLeaf)
- func (m Map) ProvePage(p, a string, max int, held func([32]byte) bool) ([]PageEntry, []MapLeaf)
- func (m Map) Root() [32]byte
- type MapLeaf
- type MetaPair
- type NotTaken
- type ObjectResult
- type Outcome
- type Outpoint
- type PageEntry
- type PageKey
- type Parallel
- type Payee
- type Pending
- type Piece
- type PieceCarrier
- type ProofTree
- type Question
- type Request
- type Sample
- type Settlement
- type Status
- type Streaming
- type Token
- type TxKind
- type Verdict
Constants ¶
const ( RoleBefore = 0 RoleAfter = 1 RoleUnheld = 2 )
Roles of a token context's leaves (spec section 11.3).
const ( NKMagic uint64 = iota NKPayment NKRequest NKReason NKTime NKAnswerer NKLast = NKAnswerer )
Record keys of the not-taken note.
const ( MaxNotTaken = 512 MaxNoteReason = 64 )
MaxNotTaken bounds a signed note; MaxNoteReason a reason.
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).
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).
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).
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).
const ( PKMagic uint64 = iota PKBucket PKWriter PKRoot PKPiece PKLast = PKPiece )
Record keys of the piece (spec section 5).
const ( OKMagic uint64 = iota OKBucket OKBuyer OKCreated OKRequest OKOutcome OKResponse OKSignature OKLast = OKSignature )
Record keys of the outcome record (spec section 8.1).
const ( FKMagic uint64 = iota FKBucket FKFront FKAdvertiser FKURL FKCreated FKLast = FKCreated )
Record keys of the front statement (spec section 8.2).
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).
const ( RKMagic uint64 = iota RKRequest RKSamples RKAnswerer RKLast = RKAnswerer )
Record keys of the response body (spec section 7.3).
const ( KindPut = 1 KindDelete = 2 )
Entry kinds.
const ( OutcomePass = 1 OutcomeInvalid = 2 OutcomeNoAnswer = 3 OutcomeUnretrievable = 4 )
Outcomes (spec section 8.1).
const MaxAdPayload = MaxAdURL + 256
MaxAdPayload bounds an advertisement's fields together, as the SDK does.
Variables ¶
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.
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).
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.
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.
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.
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.
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".
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.
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.
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.
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.
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.
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.
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.
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).
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.
var KeyIDs = []string{KeyBucket, KeyChain, KeyEntry, KeyPiece, KeyOutcome, KeyFront, KeyHold, KeyChallenge, KeyFund}
KeyIDs are the registry's key ids in the order of spec section 13.1.
var MagicNotTaken = []byte{'s', 't', 'n', 0x01}
MagicNotTaken is the not-taken note's magic.
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 ¶
AdvertisementScript is the canonical PushDrop of six fields under lock, as the SDK writes an advertisement.
func BlobSubtree ¶
BlobSubtree is the subtree root over one blob's segments: what a native provider keeps per blob and rebuilds on demand.
func BucketID ¶
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 ¶
CHIRPURLSuffix is the path a CHIRP root's advertisement url ends in (BRC-167): /chirp/v1/<rootIdentifier>/objects/<rootIdentifier>.
func ChallengeKey ¶
ChallengeKey is derive(answerer, "challenge"), read from the identity key.
func CheckBucket ¶
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 ¶
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 ¶
CheckETag holds s to spec section 4.1: 1 to 64 bytes of printable ASCII (0x20 to 0x7e) without '"'.
func CheckEntry ¶
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 ¶
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 ¶
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 ¶
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 ¶
CheckMetaKey holds a meta key to 1 to 128 bytes of a-z, 0-9 and "-".
func CheckObjectKey ¶
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 ¶
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 ¶
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
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
ClosureError labels a refusal of bcommon chirp.Verify, or of chirp.Incremental, as VerifyCHIRP does; wrong is CheckedFetch's report.
func CompactSize ¶
CompactSize is Bitcoin's CompactSize encoding of v.
func DerivationPrefix ¶
DerivationPrefix is base64(C), standard padded base64 of the entry's commitment in hash byte order.
func DerivationSuffix ¶
DerivationSuffix is base64(uint16be(rank)).
func DerivedFront ¶
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 ¶
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 ¶
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 ¶
EncodeTokenContext writes a token's context, at most two leaves.
func FundingScript ¶
FundingScript is a funding output locked to key: <key> OP_CHECKSIG <73 74 02> OP_DROP, unsigned.
func HoldScript ¶
HoldScript is a hold output locked to key: <key> OP_CHECKSIG <73 74 03> OP_DROP.
func LockingKey ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
RecordsTopic and BlobTopic are a bucket's two topics.
func Rule ¶
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 ¶
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 ¶
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 ¶
SegmentLen is the length of segment i 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 ¶
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
SignedNotTaken wraps a body and its signature as a signed note.
func SplitSigned ¶
SplitSigned reads a signed response [body, signature] as byte strings.
func TieKey ¶ added in v0.1.2
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 ¶
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 VerifyChallengeSig ¶
VerifyChallengeSig checks a strict low-S DER signature over SignedDigest under derive(answerer, "challenge").
func VerifyClosure ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Applicable is an entry as the owner's anchoring tooling sees it.
type Body ¶
Body is a response body (magic str 0x01).
func Answer ¶
Answer builds the response body for a request from the content: inline segments when inline, else every segment by reference (null).
func DecodeBody ¶
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.
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 ¶
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 ¶
Encode writes the record canonically. It refuses what DecodeBucket refuses, so a record this package writes is one it reads.
func (*Bucket) EncodedSize ¶
EncodedSize is the length the record encodes to, whatever its bounds: what the owner's tooling measures when it splits changes over tokens.
type Built ¶
Built is an object's CHIRP Profile 1 closure, as bstore builds it (no extension on the root), and its proof root.
type Candidate ¶
Candidate is an eligible advertisement in the writer's race: when its client first saw it, and whether it passed its settlement challenge.
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 ¶
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 ¶
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).
func Classify ¶
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).
type Class ¶
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.
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 ¶
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.
type EntryContext ¶
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 ¶
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 ¶
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).
type Held ¶
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).
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 ¶
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 ¶
Map is a key map: key to commitment.
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 ¶
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.
type MapLeaf ¶
MapLeaf is one leaf of a token's context [role, index, key, C, path].
func DecodeTokenContext ¶
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
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
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).
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 ¶
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).
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 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
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 (*Parallel) Abort ¶ added in v0.5.0
func (p *Parallel) Abort()
Abort stops the builder without a result; it is safe after Finish.
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.
type Piece ¶
Piece is one CHIRP object of one closure (magic stp 0x01).
func DecodePiece ¶
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 ¶
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.
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.
type ProofTree ¶
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 ¶
NewProofTree hashes content's segments.
type Question ¶
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 ¶
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 ¶
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 ¶
Encode writes the request canonically; it refuses what DecodeRequest refuses.
func (*Request) Index ¶
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 ¶
IndexDigest is SHA-256(seedHash || proofRoot || provider || nonce || uint32le(k)).
type Sample ¶
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 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 ¶
NewStreaming returns a streaming builder that hands each blob to emit.
type Token ¶
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 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.