logrec

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package logrec is the byte-level contract of a blogs log stream: the batch record a carrier holds, the digest-only locator, the interval anchor record a mined token holds, and the RFC 6962 leaf rule an anchor's root is computed by, and the topic manager's transaction rules (Admit): which output claims a record, and the carrier, anchor token and funding rules in their refusal order. docs/spec.md is the normative text; this package generates the golden vectors under testdata/vectors, and the TypeScript codec under host/ is held to the same bytes.

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 (
	// ProtocolName is the BRC-43 protocol name, security level 1.
	ProtocolName = "blogs"
	// KeyBatch locks a batch carrier's record output, signs its field, and
	// locks the funding-tree outputs a carrier spends.
	KeyBatch = "batch"
	// KeyAnchor locks and signs the mined interval-anchor token.
	KeyAnchor = "anchor"
	// KeyFund is the embedded wallet's funding key.
	KeyFund = "fund"

	// TopicPrefix and LookupService are the overlay names (BRC-87).
	TopicPrefix   = "tm_log_"
	LookupService = "ls_log"
)

Registry values (docs/frozen.md); frozen once the first record is published to a public host.

View Source
const (
	// MaxSafe is 2^53 - 1: every integer a record carries fits a JSON
	// number and a JavaScript number exactly.
	MaxSafe = 1<<53 - 1
	// SuffixLen is the length of a stream's random suffix: lowercase
	// letters, about 47 bits.
	SuffixLen = 10
	// MaxStream is the longest stream identifier <name>_<suffix>: BRC-87
	// caps a name at 50 characters and the topic prefix takes 7.
	MaxStream = 50 - len(TopicPrefix)
	// MaxStreamName is the longest readable part: MaxStream less the
	// underscore and the suffix.
	MaxStreamName = MaxStream - 1 - SuffixLen
	// MinStream is the shortest stream identifier: one letter, the
	// underscore and the suffix.
	MinStream = 1 + 1 + SuffixLen
	// MaxContent bounds a full-bytes batch's content, in bytes as carried.
	MaxContent = 256 << 10
	// MaxExpanded bounds a batch's decoded content.
	MaxExpanded = 16 << 20
	// MaxLocated bounds the content a digest-only locator may name, as
	// fetched. It equals MaxExpanded: a batch's decoded size is bounded
	// there whatever its profile.
	MaxLocated = MaxExpanded
	// MaxBatchRecord bounds an encoded batch record, content included.
	MaxBatchRecord = MaxContent + 4096
	// MaxAnchorRecord bounds an encoded anchor record.
	MaxAnchorRecord = 1024
	// MaxIntervalBatches bounds the batches one anchor covers.
	MaxIntervalBatches = 1 << 16
	// MaxURLs and MaxURL bound a locator's fetch hints.
	MaxURLs = 4
	MaxURL  = 256
	// MaxKeys bounds the entries of a record map, unknown keys included.
	MaxKeys = 64
)

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

View Source
const (
	BKMagic     = 0
	BKProducer  = 1
	BKStream    = 2
	BKSeq       = 3
	BKPrev      = 4
	BKTimestamp = 5
	BKCount     = 6
	BKEncoding  = 7
	BKProfile   = 8
	BKContent   = 9
	BKLocator   = 10
	BKSize      = 11
)

Batch record keys.

View Source
const (
	AKMagic     = 0
	AKProducer  = 1
	AKStream    = 2
	AKInterval  = 3
	AKPrev      = 4
	AKFirst     = 5
	AKCount     = 6
	AKRoot      = 7
	AKTimestamp = 8
)

Anchor record keys.

View Source
const (
	// EncodingLines is UTF-8 text, one log record per line, each line
	// terminated by LF (0x0A).
	EncodingLines = 1
	// EncodingLinesGzip is EncodingLines compressed as one gzip member
	// (RFC 1952).
	EncodingLinesGzip = 2
)

Content encodings.

View Source
const (
	// ProfileFull carries the content in the record (key 9).
	ProfileFull = 1
	// ProfileDigest carries a locator (key 10) instead of the content.
	ProfileDigest = 2
)

Profiles.

View Source
const (
	ClassBatch    = "batch"
	ClassInterval = "interval"
	ClassTree     = "tree"
)

The ls_log question classes (docs/spec.md section 7.2), all free.

Variables

View Source
var (
	ErrCarrierShape   = errors.New("logrec: carrier has the wrong shape")
	ErrAnchorShape    = errors.New("logrec: anchor token has the wrong shape")
	ErrProducerPolicy = errors.New("logrec: producer is not in the stream's producer set")
	ErrMineable       = errors.New("logrec: carrier is mineable")
	ErrLock           = errors.New("logrec: output script is not the canonical one for the producer")
	ErrSignature      = errors.New("logrec: field signature is not strict or does not verify")
	ErrFunding        = errors.New("logrec: carrier does not spend a funding output of the producer")
	ErrUnlock         = errors.New("logrec: unlocking script is not in canonical form")
	ErrAnchorInput    = errors.New("logrec: anchor token does not spend its predecessor or a funding output")
	ErrUnmined        = errors.New("logrec: transaction has no proof that verifies")
)

The transaction refusals of docs/spec.md section 8.1, beside the record refusals in logrec.go. A transaction is refused for the first rule it breaks. A carrier or token whose record's stream is not the topic's is refused with ErrStream, the same label as a record whose stream breaks the grammar.

View Source
var (
	TagPrefix = []byte("bl")
	// TagAnchor is the first field of an anchor token.
	TagAnchor = []byte{'b', 'l', 0x01}
	// TagFunding is the one field of a funding-tree output.
	TagFunding = []byte{'b', 'l', 0x02}
	// MagicBatch is key 0 of a batch record: "bl", 'b', version 1.
	MagicBatch = []byte{'b', 'l', 'b', 0x01}
	// MagicAnchor is key 0 of an anchor record: "bl", 'a', version 1.
	MagicAnchor = []byte{'b', 'l', 'a', 0x01}
)

Tags and magics. The tag prefix "bl" belongs to blogs.

View Source
var (
	Protocol         = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryApp, Protocol: ProtocolName}
	BatchDerivation  = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyBatch}
	AnchorDerivation = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyAnchor}
	FundDerivation   = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyFund}
)

Derivations under [1, "blogs"], each with counterparty anyone, so a reader derives the key from the producer's identity key alone. For key id fund that is the key the vectors record; the embedded wallet's own funding key is bcommon bwallet's, derived under counterparty self, and no rule reads it (docs/spec.md section 6.1).

View Source
var (
	ErrTooLarge     = record.ErrTooLarge
	ErrCBOR         = record.ErrCBOR
	ErrMagic        = record.ErrMagic
	ErrKeyType      = record.ErrKeyType
	ErrMissing      = record.ErrMissing
	ErrType         = record.ErrType
	ErrRange        = record.ErrRange
	ErrProducer     = errors.New("logrec: producer key is not a canonical compressed key")
	ErrStream       = errors.New("logrec: stream identifier breaks the grammar")
	ErrPrev         = errors.New("logrec: prev must be zero exactly on the first")
	ErrProfileShape = errors.New("logrec: profile and content keys disagree")
	ErrLocator      = errors.New("logrec: locator is malformed")
	ErrContent      = errors.New("logrec: content does not match its declared size or count")
)

The refusals. Their texts name the rule broken; a host counts them by the Reason of each.

View Source
var ErrPolicy = errors.New("logrec: a policy is open or names producers, exactly one")

ErrPolicy is a policy that is neither open nor names a producer, or is both.

Functions

func CheckFetched

func CheckFetched(l *Locator, content []byte) error

CheckFetched holds bytes fetched for a digest-only batch to its locator: the length first, then the digest. Bytes that fail are discarded, never stored.

func CheckProducer

func CheckProducer(k []byte) error

CheckProducer refuses anything but a canonical compressed secp256k1 key: 33 bytes, prefix 0x02 or 0x03, an x-coordinate below the field prime, and a point on the curve. A reader that accepted x >= p would accept two encodings of one key, so two byte strings would name one producer.

func CheckStream

func CheckStream(s string) error

CheckStream applies the stream identifier grammar: <name>_<suffix>, where name meets CheckStreamName and suffix is exactly SuffixLen lowercase ASCII letters. "tm_log_" + stream is then a BRC-87 topic manager name. The suffix holds no underscore, so the split is the last underscore.

func CheckStreamName

func CheckStreamName(name string) error

CheckStreamName applies the grammar of a stream's readable part: 1 to MaxStreamName bytes of lowercase ASCII letters and single underscores, starting and ending with a letter.

func CheckTxid

func CheckTxid(s string) error

CheckTxid holds s to the form a question names a transaction by: 64 lowercase hex characters.

func Expand

func Expand(b *Batch, content []byte) ([]byte, error)

Expand decodes a batch's content (carried or fetched) under its encoding and checks it against the record: exactly Size bytes, exactly Count LF-terminated lines; valid UTF-8 is NOT required here (a renderer filters text, docs/spec.md section 10). Decompression stops at Size+1 bytes, so a compressed bomb costs at most MaxExpanded+1 bytes of output.

func FundingScript

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

FundingScript is a funding-tree output locked to key: <key> OP_CHECKSIG <62 6c 02> OP_DROP.

func IntervalRoot

func IntervalRoot(commitments [][32]byte) [32]byte

IntervalRoot is the anchor root over the commitments of batches First to First+Count-1, in ascending seq order: bcommon's RFC 6962 root, whose leaves are the commitments themselves (it applies Leaf).

func IsAnchor

func IsAnchor(payload []byte) bool

IsAnchor reports whether payload claims to be an anchor record.

func IsBatch

func IsBatch(payload []byte) bool

IsBatch reports whether payload claims to be a batch record: a CBOR map whose first entry is key 0 with the batch magic. It is the carrier classifier's test and allocates nothing.

func IsFundingShape

func IsFundingShape(s []byte) bool

IsFundingShape reports whether s is a well-formed funding output under some canonical compressed key: exactly the funding script rebuilt from its own key. Whose key it is cannot be read from the script (the derivation is one way); a carrier's rule 8 compares with the producer's.

func Leaf

func Leaf(c [32]byte) [32]byte

Leaf is the RFC 6962 leaf hash of one batch: SHA-256(0x00 || c), where c is the batch carrier's commitment (its txid in hash byte order).

func Mined

Mined reports whether tx carries a proof that verifies against the headers. No headers means nothing is mined.

func NewStream

func NewStream(name string, r io.Reader) (string, error)

NewStream creates a stream identifier for name: name, an underscore, and SuffixLen letters drawn uniformly at random from a to z by r (crypto/rand.Reader when r is nil). A producer calls it once, when it creates the stream, and keeps the result for the stream's life.

func ProveBatch

func ProveBatch(a *Anchor, commitments [][32]byte, seq uint64) (commit.Path, error)

ProveBatch returns the inclusion path of the batch at seq under an anchor, given every commitment the anchor covers in order.

func PushDropScript

func PushDropScript(key *ec.PublicKey, fields [][]byte, sig []byte) []byte

PushDropScript is the one canonical lock-before PushDrop for key, fields and an optional field signature (bcommon pushdrop.Script).

func Reason

func Reason(err error) string

Reason is the fixed label a host counts a refusal by.

func SplitStream

func SplitStream(s string) (name, suffix string, err error)

SplitStream returns a stream identifier's readable part and suffix. The readable part alone never identifies a stream.

func StrictSignature

func StrictSignature(der []byte) bool

StrictSignature reports whether der is a strict DER ECDSA signature (BIP 66) with R in [1, n-1] and S in [1, n/2]: the one encoding of a signature a host accepts, so nobody can re-encode it into another byte string that still verifies.

func Topic

func Topic(stream string) (string, error)

Topic is the topic manager name of a stream identifier.

func VerifyBatch

func VerifyBatch(a *Anchor, c [32]byte, seq uint64, path commit.Path) bool

VerifyBatch checks that the batch with commitment c sits at seq under the anchor. The path's shape fixes the leaf's index, so a verifier also checks that index against seq - First; commit.Verify alone would accept a path for another position.

Types

type Admission

type Admission struct {
	Kind    Kind
	Carrier *Carrier
	Token   *Token
	// Funding lists the admitted funding outputs of a mined funding tree or
	// sweep.
	Funding []int
}

Admission is what a host admits from one transaction: a carrier, a token, or funding outputs. A transaction that claims nothing and admits no funding output has all three empty; whether it spends something the topic holds is the host's question, not the codec's.

func Admit

func Admit(ctx context.Context, tx *transaction.Transaction, coins Coins, h Host) (*Admission, error)

Admit applies docs/spec.md section 8.1 to tx, read from its BEEF, given the previous coins the engine hands the topic manager for its inputs. A carrier's funding output comes from the carrier's own BEEF, which carries its unmined ancestry; an anchor token's spent outputs come only from coins, because a mined transaction's BEEF carries no parents. SPV of the BEEF is the engine's and is assumed to have run; Admit checks what the topic manager checks, in the order given, and refuses for the first rule broken.

type Anchor

type Anchor struct {
	Producer  []byte   // key 1
	Stream    string   // key 2
	Interval  uint64   // key 3, 1 to MaxSafe, contiguous per producer and stream
	Prev      [32]byte // key 4, the previous anchor token's txid; zero on interval 1
	First     uint64   // key 5, the first seq covered
	Count     uint64   // key 6, batches covered
	Root      [32]byte // key 7, Root over the covered batches' commitments
	Timestamp uint64   // key 8, producer clock, Unix milliseconds
	// Extra holds integer keys above 8, preserved verbatim and ignored.
	Extra cbor.Map
}

Anchor is one interval anchor record: the second field of a mined anchor token. It commits the batches First to First+Count-1 of one producer's stream under Root.

func DecodeAnchor

func DecodeAnchor(p []byte) (*Anchor, error)

DecodeAnchor parses an anchor record: bounded first, then canonical CBOR, then the magic, then each key in ascending order, then the rules across fields.

func DecodeToken

func DecodeToken(tx *transaction.Transaction) (*Anchor, int, error)

DecodeToken reads the anchor record of a transaction that claims an anchor, and the claiming output's index, without the admission rules: a reader walking the anchor chain uses it to choose the candidates it then holds to Admit, once it has the outputs they spend.

func (*Anchor) Covers

func (a *Anchor) Covers(seq uint64) bool

Covers reports whether seq falls in the anchor's range.

func (*Anchor) Encode

func (a *Anchor) Encode() ([]byte, error)

Encode writes the anchor record in canonical CBOR.

func (*Anchor) Last

func (a *Anchor) Last() uint64

Last is the last seq the anchor covers.

func (*Anchor) Validate

func (a *Anchor) Validate() error

Validate applies every rule that needs only the record itself, in the refusal order.

type Batch

type Batch struct {
	Producer  []byte   // key 1, compressed identity key, 33 bytes
	Stream    string   // key 2
	Seq       uint64   // key 3, 1 to MaxSafe
	Prev      [32]byte // key 4, the previous batch's commitment; zero on seq 1
	Timestamp uint64   // key 5, producer clock, Unix milliseconds
	Count     uint64   // key 6, log records in the content
	Encoding  uint64   // key 7
	Profile   uint64   // key 8
	Content   []byte   // key 9, ProfileFull only
	Locator   *Locator // key 10, ProfileDigest only
	Size      uint64   // key 11, decoded content length
	// Extra holds integer keys above 11, preserved verbatim and ignored.
	Extra cbor.Map
}

Batch is one batch record: the payload of one carrier.

func DecodeBatch

func DecodeBatch(p []byte) (*Batch, error)

DecodeBatch parses a batch record in the refusal order: the bound, then canonical CBOR and the map's shape, then the magic, then each defined key in ascending order (missing, type, the key's own rule), then the rules across fields.

func (*Batch) Encode

func (b *Batch) Encode() ([]byte, error)

Encode writes the batch record in canonical CBOR.

func (*Batch) Supported

func (b *Batch) Supported() bool

Supported reports whether this version can read the batch's content: its profile and encoding are known and, for a digest-only batch, its locator has no member this version does not define. An unsupported batch is still a valid link in its stream.

func (*Batch) Validate

func (b *Batch) Validate() error

Validate applies every rule that needs only the record itself, in the refusal order (steps 6 and 7). Encode and DecodeBatch both run it, so a producer cannot write what a reader refuses.

type Carrier

type Carrier struct {
	Batch *Batch
	// Record is the batch record exactly as carried.
	Record []byte
	// Commitment is C = txid(K), hash byte order.
	Commitment [32]byte
	// Funding is the outpoint the carrier spends; a mined spend of it by
	// another transaction retracts the batch.
	Funding transaction.Outpoint
}

Carrier is an admitted batch carrier.

type Coin

type Coin struct {
	LockingScript []byte
	Satoshis      uint64
}

Coin is an output the topic holds, as the overlay engine hands it to the topic manager for an input that spends it (BRC-22's previous coins): its locking script and its value.

type Coins

type Coins map[transaction.Outpoint]Coin

Coins are the previous coins of one transaction: every output the topic holds that one of its inputs spends, by outpoint. An input whose outpoint is absent spends something the topic does not hold.

type Host

type Host struct {
	Stream  string
	Policy  Policy
	Headers chaintracker.ChainTracker
}

Host is what admission needs from the host beyond the object: the topic's stream, its producer policy and a chain tracker over the host's own block headers.

type Kind

type Kind int

Kind is what a transaction's outputs claim to be.

const (
	// KindNone claims nothing: a funding tree, a sweep or a spend.
	KindNone Kind = iota
	// KindBatch has an output that claims a batch.
	KindBatch
	// KindAnchor has an output that claims an anchor.
	KindAnchor
)

func Classify

func Classify(tx *transaction.Transaction) (Kind, int, error)

Classify finds the one claiming output. An output claims a batch when it is a PushDrop whose first field starts with a CBOR map head, key 0 and the batch magic; it claims an anchor when its first field is 62 6c 01. More than one claiming output refuses the transaction: carrier-shape when any of them claims a batch, else anchor-shape.

type Locator

type Locator struct {
	Digest [32]byte // "digest": SHA-256 of the content bytes as fetched
	Length uint64   // "length": the content's length in bytes
	URLs   []string // "urls": fetch hints, possibly empty
	// Extra holds members this version does not define, whatever their
	// key type, preserved verbatim. A locator with any is unsupported: a
	// reader does not fetch through it, and the batch stays a valid link.
	Extra cbor.Map
}

Locator is a digest-only batch's pointer to its content: the SHA-256 of the content bytes (the hash a BRC-26 UHRP URL encodes), their length, and zero to MaxURLs HTTPS fetch hints. Every member is always present, so one locator has one encoding.

func DecodeLocator

func DecodeLocator(p []byte) (*Locator, error)

DecodeLocator parses a locator encoded alone.

func (*Locator) Encode

func (l *Locator) Encode() ([]byte, error)

EncodeLocator writes a locator alone, as it appears under key 10.

func (*Locator) Unsupported

func (l *Locator) Unsupported() bool

Unsupported reports whether the locator carries a member this version does not define.

type Policy

type Policy struct {
	// Open admits any producer.
	Open bool
	// Producers is the set a closed stream admits, as compressed keys.
	Producers [][]byte
}

Policy is a host's producer policy for one stream. Openness is stated, never inferred: a closed policy with no producers is a configuration error, not an open stream.

func (Policy) Validate

func (p Policy) Validate() error

Validate refuses a policy that does not say which it is.

type Query

type Query struct {
	Class  string
	Stream string
	// Producer is the identity key, set for the batch and interval classes.
	Producer []byte
	// Seq is set for the batch class, Interval for the interval class.
	Seq, Interval uint64
	// Tree is the funding tree's txid, 64 lowercase hex characters
	// (display order), set for the tree class.
	Tree string
}

Query is one ls_log question, validated: exactly one class's members.

func ParseQuery

func ParseQuery(raw []byte) (*Query, error)

ParseQuery validates a question's query object as parsed (docs/spec.md section 7.2): exactly the members of one class, each within its rule. A member given twice takes its last value, as JSON parsers give it. Anything else is an error, never an empty answer and never ignored.

type Token

type Token struct {
	Anchor *Anchor
	// Record is the anchor record exactly as carried.
	Record []byte
	// OutputIndex is the anchor output.
	OutputIndex int
	// Txid is the token transaction's txid, hash byte order: what the next
	// interval's prev names.
	Txid [32]byte
}

Token is an admitted anchor token.

Jump to

Keyboard shortcuts

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