borgrec

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 30 Imported by: 2 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 borgrec is the byte-level contract of borg: the organization and group records that ride mined chain tokens, the membership grant and the epoch-key wrap that ride unmined carriers, the hall and scope grammars, the BRC-369 epoch key, and the lookup question classes. 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.

The package is importable by other modules at a tagged version (docs/packages.md names the supported part of it).

Index

Constants

View Source
const (
	// ProtocolName is the BRC-43 protocol name, security level 1. BRC-43 key
	// derivation refuses a name under five characters, so the application
	// name alone ("borg") cannot be the protocol name.
	ProtocolName = "borg organisation"
	// KeyOrg locks an organization chain token and signs its fields.
	KeyOrg = "org"
	// KeyGroup locks a group chain token and signs its fields.
	KeyGroup = "group"
	// KeyRecord locks a wrap carrier's record output, signs its field, and
	// locks the outputs of the trees that fund wraps.
	KeyRecord = "record"
	// KeyGrant does the same for grant carriers and the trees that fund
	// them, so that a host can tell a grant's funding from any other.
	KeyGrant = "grant"
	// KeyPolicy locks a policy carrier's record output, signs its field, and
	// locks the outputs of the trees that fund policy records, so that a host
	// can tell a policy record's funding from a grant's.
	KeyPolicy = "policy"
	// KeyChain locks the outputs of the trees that pay for a chain's first
	// token; no carrier is ever funded under it.
	KeyChain = "chain"
	// KeyFund is the embedded wallet's funding key.
	KeyFund = "fund"

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

	// GrantTypeString is hashed into the BRC-52 certificate type of a
	// membership grant by the rule of BRC-169 section 4.5.
	GrantTypeString = "borg membership grant v1"

	// ReleaseProtocolName is BRC-369 section 5.2's protocol for an epoch-key
	// wrap, at security level 2. It is BRC-369's, adopted, not borg's.
	ReleaseProtocolName = "keyed content release"

	// DomainSymmetric and DomainCommitment are BRC-369 section 2's domain
	// strings, adopted verbatim.
	DomainSymmetric  = keyed.DomainSymmetric
	DomainCommitment = keyed.DomainCommitment
)

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

View Source
const (
	// MaxSafe is 2^53 - 1.
	MaxSafe = 1<<53 - 1
	// MaxTime is 9999-12-31T23:59:59Z, the last second RFC 3339 can write.
	MaxTime = 253402300799
	// MaxEpoch is the largest epoch: BRC-369 section 5.2 writes the epoch as
	// four bytes.
	MaxEpoch = 1<<32 - 1
	// SuffixLen is the length of a hall's random suffix.
	SuffixLen = 10
	// MaxHall is the longest hall identifier: BRC-87 caps a name at 50
	// characters and the topic prefix takes 8.
	MaxHall = 50 - len(TopicPrefix)
	// MaxHallName is the longest readable part of a hall identifier.
	MaxHallName = MaxHall - 1 - SuffixLen
	// MinHall is the shortest hall identifier.
	MinHall = 1 + 1 + SuffixLen
	// GroupIDLen is the length of a group identifier.
	GroupIDLen = 16
	// MaxName bounds an organization's or a group's display name, in bytes.
	MaxName = 64
	// MaxDelta bounds each change list of one transition: grants admitted
	// or revoked, members added or removed.
	MaxDelta = 64
	// MaxRoll bounds the grants an organization's roll holds.
	MaxRoll = 65536
	// MaxMembers bounds the members of one group (BRC-369 section 8.3: the
	// linear rekey serves groups of a few hundred).
	MaxMembers = 1024
	// MaxEntries bounds the wraps one wrap record carries.
	MaxEntries = 16
	// MaxOrgRecord and MaxGroupRecord bound an encoded chain-token record.
	MaxOrgRecord   = 8192
	MaxGroupRecord = 8192
	// MaxGrantRecord and MaxWrapRecord bound an encoded carrier record.
	MaxGrantRecord = 4096
	MaxWrapRecord  = 4096
	// MaxPolicyRecord bounds an encoded policy record: 24 permissions of the
	// grammar's full length take about 6.1 KB.
	MaxPolicyRecord = 8192
	// MaxPolicySet bounds the policy records an organization's set holds.
	MaxPolicySet = 65536
	// MaxKeys bounds the entries of a record map, unknown keys included.
	MaxKeys = 64
	// ExpirySkew is the clock skew a reader allows an expiry, in either
	// direction (spec section 5.2; BRC-169 section 9.6). It is part of the
	// contract: two readers with clocks within it reach one verdict.
	ExpirySkew = 300 * time.Second
	// MaxRole and MaxScope bound a grant's role and scope, in bytes.
	MaxRole  = 64
	MaxScope = 512
	// WrapLen is the exact length of one wrap: the BRC-78 serialization of a
	// 32-byte scalar (4 + 33 + 33 + 32 + 32 + 32 + 16).
	WrapLen = 182
	// KeyringEntryLen is the exact length of one master-keyring entry: a
	// 32-byte field revelation key under BRC-2 (32 + 32 + 16).
	KeyringEntryLen = 80
	// RevealLen is the length of one revealed field revelation key.
	RevealLen = 32
)

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 (
	StatusConsistent      = "consistent"
	StatusPending         = "pending"
	StatusRollMismatch    = "roll-mismatch"
	StatusPolicyMismatch  = "policy-mismatch"
	StatusMembersMismatch = "members-mismatch"
	StatusCommitmentReuse = "commitment-reuse"
	StatusRejoinUnrotated = "rejoin-unrotated"
)

Token statuses the index reports (spec section 11.2). They are never admission verdicts: each needs the chain, which a topic manager does not read while it admits.

View Source
const (
	StatusRetracted  = "retracted"
	StatusSuperseded = "superseded"
	StatusHeld       = "held"
)

Carrier statuses (spec section 11.2), the first that applies.

View Source
const (
	MKMagic      = 0
	MKHall       = 1
	MKOrg        = 2
	MKSubject    = 3
	MKSerial     = 4
	MKRevocation = 5
	MKFields     = 6
	MKSignature  = 7
	MKKeyring    = 8
	MKReveal     = 9
)

Grant record keys.

View Source
const (
	GKMagic        = 0
	GKHall         = 1
	GKOrg          = 2
	GKGroup        = 3
	GKSeq          = 4
	GKPrev         = 5
	GKName         = 6
	GKEpoch        = 7
	GKEpochSeq     = 8
	GKCommitment   = 9
	GKAdd          = 10
	GKRemove       = 11
	GKCount        = 12
	GKMembers      = 13
	GKRotateOnJoin = 14
	GKRotateEvery  = 15
	GKCreated      = 16
	GKSuccessor    = 17
)

Group record keys.

View Source
const (
	OKMagic       = 0
	OKHall        = 1
	OKOrg         = 2
	OKSeq         = 3
	OKPrev        = 4
	OKName        = 5
	OKAdmit       = 6
	OKRevoke      = 7
	OKCount       = 8
	OKRoll        = 9
	OKOpaque      = 10
	OKCreated     = 11
	OKDefine      = 12
	OKRetire      = 13
	OKPolicyCount = 14
	OKPolicy      = 15
	OKSuccessor   = 16
)

Organization record keys.

View Source
const (
	MaxPermission = 256
	MaxService    = 16
	MaxAction     = 32
	MaxResource   = 192
	// MaxPermissions bounds the permissions one policy record carries.
	MaxPermissions = 24
	// MaxRoleName bounds a role name, the same bound as a grant's role field.
	MaxRoleName = MaxRole
)

Permission bounds (spec section 5A.2). The grammar's longest permission is MaxService + 1 + MaxAction + 1 + MaxResource + 1 = 243 bytes; MaxPermission is the bound a reader holds the text to before it parses.

View Source
const (
	PKMagic       = 0
	PKHall        = 1
	PKOrg         = 2
	PKKind        = 3
	PKRole        = 4
	PKPermissions = 5
	PKTo          = 6
	PKExpiry      = 7
	PKCreated     = 8
)

Policy record keys (spec section 5A).

View Source
const (
	// PolicyRole defines a role and the permissions it carries.
	PolicyRole uint64 = 0
	// PolicyBinding gives a role to a group or to one identity key.
	PolicyBinding uint64 = 1
)

The two kinds of policy record.

View Source
const (
	VerbMember = "member"
	VerbAdmin  = "admin"
)

Scope tokens this version defines (spec section 5.3). Every other verb is unknown: it authorises nothing, and a known verb with a qualifier this version does not define is denied, never read as the bare verb.

View Source
const (
	WKMagic   = 0
	WKHall    = 1
	WKOrg     = 2
	WKGroup   = 3
	WKEpoch   = 4
	WKEpochID = 5
	WKEntries = 6
)

Wrap record keys.

View Source
const DefaultMaxBEEF = chaintoken.DefaultMaxBEEF

DefaultMaxBEEF is the BEEF bound Admit applies when a host names none: the floor spec section 11.1 sets for a host's own bound.

View Source
const DefaultMaxSweepInputs = 1024

DefaultMaxSweepInputs is the sweep input bound Admit applies when a host names none: the floor spec section 11.1 sets.

View Source
const ExpiryLayout = "2006-01-02T15:04:05Z"

ExpiryLayout is the one spelling of a grant's expiry: ISO-8601 UTC to the second (BRC-169 section 9.1's expiry, its format pinned).

View Source
const KeySigner = "signer"

KeySigner derives the organization's signer key: the key every instance of the organization's tooling holds, because each holds the organization's identity key, and that is a member of the organization's groups like any other member (spec section 7.4). An epoch key wrapped to it is what a second instance, or a home rebuilt on a new machine, opens to hold the key another instance sampled.

View Source
const MaxContext = 2048

MaxContext bounds an encoded inclusion context.

View Source
const MaxPathSteps = 32

MaxPathSteps bounds an inclusion path: a roll of at most MaxRoll grants has a path of at most 16 steps.

Variables

View Source
var (
	ErrShape      = errors.New("borgrec: transaction has the wrong shape")
	ErrBEEF       = chaintoken.ErrBEEF
	ErrMineable   = errors.New("borgrec: carrier is mineable")
	ErrUnlock     = errors.New("borgrec: unlocking script is not one canonical signature push")
	ErrLock       = errors.New("borgrec: output script is not the canonical one for the owner")
	ErrFieldSig   = errors.New("borgrec: field signature is not strict or does not verify")
	ErrFunding    = errors.New("borgrec: carrier does not spend a funding output of the owner")
	ErrUnmined    = errors.New("borgrec: proof does not verify against the host's headers")
	ErrTokenInput = errors.New("borgrec: token does not spend its predecessor, or its chain tree at seq 0")
	ErrNotBorg    = errors.New("borgrec: transaction is not for this topic")
	ErrHostConfig = errors.New("borgrec: host configuration or previous coins out of range")
)

The transaction refusals of spec section 11.1, beside the record and content refusals. A transaction is refused for the first rule it breaks. A record that names another hall than the topic's is refused with ErrHall, the label of a hall that breaks the grammar.

View Source
var (
	TagPrefix = []byte("bo")
	// TagOrg is the first field of an organization chain token.
	TagOrg = []byte{'b', 'o', 0x01}
	// TagFunding is the one field of a funding-tree output.
	TagFunding = []byte{'b', 'o', 0x02}
	// TagGroup is the first field of a group chain token.
	TagGroup = []byte{'b', 'o', 0x03}
	// MagicOrg is key 0 of an organization record: "bo", 'o', version 1.
	MagicOrg = []byte{'b', 'o', 'o', 0x01}
	// MagicGroup is key 0 of a group record: "bo", 'g', version 1.
	MagicGroup = []byte{'b', 'o', 'g', 0x01}
	// MagicGrant is key 0 of a membership grant record: "bo", 'm', version 1.
	MagicGrant = []byte{'b', 'o', 'm', 0x01}
	// MagicPolicy is key 0 of a policy record: "bo", 'p', version 1.
	MagicPolicy = []byte{'b', 'o', 'p', 0x01}
	// MagicWrap is key 0 of an epoch-key wrap record: "bo", 'w', version 1.
	MagicWrap = []byte{'b', 'o', 'w', 0x01}
)

Tags and magics. The tag prefix "bo" belongs to borg.

View Source
var (
	Protocol         = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryApp, Protocol: ProtocolName}
	OrgDerivation    = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyOrg}
	GroupDerivation  = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyGroup}
	RecordDerivation = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyRecord}
	GrantDerivation  = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyGrant}
	PolicyDerivation = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyPolicy}
	ChainDerivation  = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyChain}
	FundDerivation   = pushdrop.Derivation{Protocol: Protocol, KeyID: KeyFund}

	// ReleaseProtocol is BRC-369 section 5.2's derivation protocol.
	ReleaseProtocol = wallet.Protocol{SecurityLevel: wallet.SecurityLevelEveryAppAndCounterparty, Protocol: ReleaseProtocolName}
)

Derivations under [1, "borg organisation"], each with counterparty anyone, so a reader derives the key from the identity key alone.

View Source
var (
	ErrTooLarge   = record.ErrTooLarge
	ErrCBOR       = record.ErrCBOR
	ErrKeyType    = record.ErrKeyType
	ErrMagic      = record.ErrMagic
	ErrMissing    = record.ErrMissing
	ErrType       = record.ErrType
	ErrRange      = record.ErrRange
	ErrIdentity   = errors.New("borgrec: identity key is not a canonical compressed key")
	ErrHall       = errors.New("borgrec: hall identifier breaks the grammar")
	ErrName       = errors.New("borgrec: name is not 1 to 64 bytes of text")
	ErrList       = record.ErrList
	ErrChain      = errors.New("borgrec: seq, prev and epoch fields disagree")
	ErrMembers    = errors.New("borgrec: member list names the organization or the anyone key")
	ErrFields     = errors.New("borgrec: grant fields, keyring or reveal are not exactly expiry, role and scope")
	ErrSignature  = chaintoken.ErrSignature
	ErrEntry      = errors.New("borgrec: wrap entry does not match the record")
	ErrRevocation = errors.New("borgrec: revocation outpoint is not the carrier's funding outpoint")
	ErrCert       = errors.New("borgrec: grant certificate signature does not verify")
	ErrReveal     = errors.New("borgrec: revealed field does not decrypt to a valid value")
	ErrTransition = errors.New("borgrec: transition breaks the chain rules")
	ErrRotation   = errors.New("borgrec: transition removes a member without a new epoch")
	ErrCount      = errors.New("borgrec: count disagrees with the predecessor and the change lists")
	ErrScope      = errors.New("borgrec: scope breaks the grammar")
	ErrExpiry     = errors.New("borgrec: expiry is not YYYY-MM-DDTHH:MM:SSZ")
	ErrRole       = errors.New("borgrec: role is not 1 to 64 bytes of text")
	ErrRoleName   = errors.New("borgrec: role name breaks the grammar")
	ErrPermission = errors.New("borgrec: permission breaks the grammar")
	ErrBinding    = errors.New("borgrec: policy record's kind and fields disagree")
	ErrQuery      = errors.New("borgrec: question is not one of the defined classes")
)

The refusals. A host counts them by Reason.

View Source
var (
	ErrScalar     = keyed.ErrScalar
	ErrCommitment = keyed.ErrCommitment
	ErrUnwrap     = keyed.ErrUnwrap
	ErrToken      = errors.New("borgrec: the wrap's epoch id is not the record of the token that began its epoch")
)

Epoch-key errors, a reader's (BRC-369 section 5.3), never a host's.

View Source
var Classes = []Class{
	{"org", []string{"hall", "org"}, true, 8},
	{"org-seq", []string{"hall", "org", "seq"}, true, 8},
	{"roll", []string{"hall", "roll"}, true, 64},
	{"roll-after", []string{"after", "hall", "roll"}, true, 64},
	{"member", []string{"hall", "member", "org"}, true, 8},
	{"policy", []string{"hall", "policy"}, true, 64},
	{"policy-after", []string{"after", "hall", "policy"}, true, 64},
	{"role", []string{"hall", "org", "role"}, true, 64},
	{"role-after", []string{"after", "hall", "org", "role"}, true, 64},
	{"bound", []string{"boundTo", "hall", "org"}, true, 64},
	{"bound-after", []string{"after", "boundTo", "hall", "org"}, true, 64},
	{"groups", []string{"groupsOf", "hall"}, true, 64},
	{"groups-after", []string{"after", "groupsOf", "hall"}, true, 64},
	{"member-of", []string{"hall", "memberOf", "org"}, true, 64},
	{"member-of-after", []string{"after", "hall", "memberOf", "org"}, true, 64},
	{"group", []string{"group", "hall", "org"}, true, 8},
	{"group-seq", []string{"group", "hall", "org", "seq"}, true, 8},
	{"wraps", []string{"epoch", "group", "hall", "org"}, true, 64},
	{"wraps-after", []string{"after", "epoch", "group", "hall", "org"}, true, 64},
	{"wrap", []string{"epoch", "group", "hall", "member", "org"}, true, 8},
	{"sweep", []string{"hall", "spent"}, true, 8},
	{"history", []string{"chain", "hall", "history"}, false, 64},
	{"history-after", []string{"after", "chain", "hall", "history"}, false, 64},
}

Classes is every class this version defines. A question carries exactly the members of one of them.

View Source
var GrantFieldNames = []string{"expiry", "role", "scope"}

GrantFieldNames are the BRC-52 field names of a membership grant, in the order BRC-52 serializes them (sorted).

View Source
var WrapVersion = []byte{0x42, 0x42, 0x10, 0x33}

WrapVersion is the BRC-78 version prefix borg writes and requires: the bytes go-sdk and ts-sdk write. BRC-78's hex example prints 10334242 and BRC-369's release vector carries 33104242; neither is accepted.

Functions

func Allows added in v0.6.0

func Allows(effective []string, ask string) (bool, error)

Allows reports whether a subject's effective set grants the asked permission, which carries no wildcard (section 5A.3).

func AnyoneKey

func AnyoneKey() []byte

AnyoneKey is the public key of BRC-43's "anyone" counterparty, the generator point (private key 1). Nothing is ever released to it (BRC-369 section 5.2 rule 4), so it is never a member and never a wrap recipient.

func CheckFieldValue

func CheckFieldValue(name, value string) error

CheckFieldValue applies the rule of a grant field to its decrypted value.

func CheckGroupTransition

func CheckGroupTransition(prev *Group, prevTxid [32]byte, next *Group) error

CheckGroupTransition is the admission rule a group token meets against the token it spends (read from the parent the token's BEEF carries). It is what makes removal a rekey at every host: a transition that removes anyone, or adds anyone while the predecessor asks for rotation on join, begins the next epoch with a different commitment, and no other transition may change the epoch's key.

func CheckHall

func CheckHall(s string) error

CheckHall applies the hall identifier grammar: <name>_<suffix>, where name meets CheckHallName and suffix is exactly SuffixLen lowercase ASCII letters. TopicPrefix + hall is then a BRC-87 topic manager name.

func CheckHallName

func CheckHallName(s string) error

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

func CheckIdentity

func CheckIdentity(k []byte) error

CheckIdentity refuses anything but a canonical compressed secp256k1 key (bcommon guard.ParsePubKey): 33 bytes, prefix 0x02 or 0x03, an x-coordinate below the field prime, and a point on the curve. Accepting an alias would let two byte strings name one organization or member.

func CheckOrgTransition

func CheckOrgTransition(prev *Org, prevTxid [32]byte, next *Org) error

CheckOrgTransition is the admission rule an organization token meets against the token it spends (read from the topic's previous coins): same hall and organization, the next seq, prev naming the predecessor's transaction, and a count that follows from the predecessor's and the change lists.

func CheckRole

func CheckRole(s string) error

CheckRole applies the role rule: 1 to MaxRole bytes of UTF-8 text. A role is a label a client shows; it authorises nothing.

func CheckRoleName added in v0.6.0

func CheckRoleName(s string) error

CheckRoleName applies the role-name grammar of spec section 5A.1: 1 to 64 of lower-case ASCII letters, digits, "-", "_" and ".", the characters BRC-169 section 9.2 allows a scope qualifier. A role name is an identifier compared byte for byte, so it carries no case and no character a renderer would strip; an organization's human wording is in its display names.

func CheckScalar

func CheckScalar(k [32]byte) error

CheckScalar refuses a 32-byte big-endian value outside [1, n-1].

func Commitment

func Commitment(k [32]byte) [32]byte

Commitment is BRC-369 section 2.2's digest form.

func Effective added in v0.6.0

func Effective(s Subject, set []*Policy, now time.Time) []string

Effective is the effective permission set of a subject at time now, over the policy set of the organization's latest token (spec section 5A.4): the union of what the subject's own roles carry and what every binding that reaches it carries, attenuated. The caller supplies only records it has verified and found current; expiry is the one currency rule applied here, because it needs the clock.

Nothing subtracts. The result is ascending and holds no duplicate, so two implementations of this contract produce the same set.

func EpochID

func EpochID(groupRecord []byte) [32]byte

EpochID is the identifier of an epoch: SHA-256 of the encoded group record of the token that began it, BRC-369 section 4.2 rule 3's content id with the record in the descriptor's place.

func Fold

func Fold(set map[string]bool, next *Group) error

Fold applies a transition to a member set, refusing a removal of a non-member or an addition of a member. The result's MembersRoot must equal the token's Members; that is a reader's and an index's check, never an admission rule, because a host cannot hold the set while it admits.

func FundingScript

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

FundingScript is a funding output locked to key: `<key> OP_CHECKSIG <62 6f 02> OP_DROP`, unsigned (spec section 9.4).

func GrantType

func GrantType() [32]byte

GrantType is the BRC-52 certificate type of a membership grant: SHA-256 of GrantTypeString (BRC-169 section 4.5's derivation rule).

func GrantTypeBase64

func GrantTypeBase64() string

GrantTypeBase64 is GrantType as BRC-52 writes a type: standard base64.

func Grants

func Grants(tokens []Token, verb string) bool

Grants reports whether a parsed scope authorises verb with no qualifier. It fails closed (BRC-169 section 9.2 rule 4): a token for verb that carries a qualifier this version does not define denies verb outright, rather than being read as the bare verb.

func GrantsAny added in v0.6.0

func GrantsAny(held []string, asked string) (bool, error)

GrantsAny reports whether any held permission grants the asked one. held is the text of an effective set; a member of it that breaks the grammar is refused, because a reader that met one has read a record no host admits.

func Intersect added in v0.6.0

func Intersect(a, b []string) []string

Intersect keeps the permissions of a that b also carries, in a's order. Attenuating a binding is this over the role's set, so a binding can never widen a role, and two definitions of one role are read as this over both.

func IsAnyone

func IsAnyone(k []byte) bool

IsAnyone reports whether k is the anyone key.

func IsMembership

func IsMembership(scope string) bool

IsMembership reports whether a scope makes its grant a membership: it parses and grants "member".

func MembersRoot

func MembersRoot(keys [][]byte) [32]byte

MembersRoot is the RFC 6962 root (bcommon commit) a group record commits its members to: the leaves are SHA-256 of each 33-byte identity key, in ascending order of the keys' bytes. The empty set's root is SHA-256 of nothing.

func Mined

Mined reports whether tx carries a proof that verifies against the headers (bcommon chaintoken.Mined).

func MinimalPath added in v0.1.1

func MinimalPath(mp *transaction.MerklePath, txid *chainhash.Hash) (*transaction.MerklePath, error)

MinimalPath is mp cut to the proof of txid alone (spec section 11.1: every path is minimal): at the lowest level txid, flagged as the txid, and its sibling; above that the one sibling each level needs, computed from the leaves below when mp holds only those. A node may answer a proof that carries more of its block than one transaction needs, and a host refuses a carrier or token whose BEEF carries such a proof. The result proves the same root.

func NewGroupID

func NewGroupID(r io.Reader) ([GroupIDLen]byte, error)

NewGroupID draws a group identifier: GroupIDLen bytes uniformly at random from r (crypto/rand.Reader when r is nil).

func NewHall

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

NewHall creates a hall 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). Whoever creates the hall calls it once; the suffix never changes.

func ParseExpiry

func ParseExpiry(s string) (time.Time, error)

ParseExpiry applies the expiry rule: exactly YYYY-MM-DDTHH:MM:SSZ, a real UTC date and time, from 1970 to 9999.

func PolicyRoot added in v0.6.0

func PolicyRoot(policies [][32]byte) [32]byte

PolicyRoot is the RFC 6962 root an organization record commits its policy set to, computed exactly as RollRoot is over the grant commitments: the leaves are the policy carriers' commitments in ascending byte order. The two roots are separate so that a change of membership and a change of policy are told apart, and one chain orders both.

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 RejoinUnrotated

func RejoinUnrotated(removed map[string]bool, next *Group) bool

RejoinUnrotated reports a token that adds a key an earlier token of the group removed without beginning an epoch: the index's rejoin-unrotated status (spec section 4.2). removed holds every key any earlier token of the group removed. It is never an admission rule, because the predecessor's record names no removed keys.

func ReleaseInvoice

func ReleaseInvoice(epochID [32]byte, epoch uint32) string

ReleaseInvoice is the BRC-43 invoice number the wrap is derived under.

func ReleaseKeyID

func ReleaseKeyID(epochID [32]byte, epoch uint32) [32]byte

ReleaseKeyID is BRC-369 section 5.2's key id bytes: SHA-256(epoch id || epoch as four bytes big-endian).

func RollRoot

func RollRoot(grants [][32]byte) [32]byte

RollRoot is the RFC 6962 root an organization record commits its roll to: the leaves are the grant commitments (carrier txids, hash byte order) in ascending byte order.

func SampleKey

func SampleKey(r io.Reader) ([32]byte, error)

SampleKey draws an epoch key (BRC-369 section 2.1 rule 1).

func SignerKey

func SignerKey(org []byte) ([]byte, error)

SignerKey is the signer key of the organization org, compressed: the BRC-42 child of org under [1, "borg organisation"], key id signer, counterparty anyone. Anyone derives it from the organization's public key, so a reader can tell that a member is the organization's own signer key; only the organization derives its private key.

func SignerPrivate

func SignerPrivate(orgKey *ec.PrivateKey) (*ec.PrivateKey, error)

SignerPrivate is the private key of the organization's signer key, derived from the organization's identity key.

func SymmetricKey

func SymmetricKey(k [32]byte) [32]byte

SymmetricKey is BRC-369 section 2.1 rule 3.

func TokenBEEF

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

TokenBEEF assembles the BEEF a chain token is admitted in (spec sections 11.1 and 11.6): bcommon chaintoken.TokenBEEF.

func Topic

func Topic(hall string) string

Topic is the topic manager name of a hall.

func Unwrap

func Unwrap(ctx context.Context, w wallet.Interface, wrap []byte, org *ec.PublicKey, epochID [32]byte, epoch uint32, commitment [32]byte) ([32]byte, error)

Unwrap is the member's side of BRC-369 sections 5.2 and 5.3: it decrypts its wrap through its own wallet (counterparty the organization), refuses a value that is not a scalar, and checks it against the epoch's commitment before anything else uses it.

func Wrap

func Wrap(ctx context.Context, w wallet.Interface, org []byte, member *ec.PublicKey, epochID [32]byte, epoch uint32, k [32]byte) ([]byte, error)

Wrap releases the epoch key k to member under BRC-369 section 5.2, through the organization's wallet: the wallet's BRC-2 ciphertext under [2, "keyed content release"], the derived key id and counterparty member, framed as BRC-78 (version, sender, recipient, key id, ciphertext).

func WrapWithIV

func WrapWithIV(orgKey *ec.PrivateKey, member *ec.PublicKey, epochID [32]byte, epoch uint32, k [32]byte, iv [32]byte) ([]byte, error)

WrapWithIV is Wrap with a caller's 32-byte IV in place of a random one, for golden vectors only: the symmetric key is the one the wallet derives (BRC-42 child keys, the raw x-coordinate of their shared point), and the result decrypts through any wallet's Decrypt.

Types

type Admission

type Admission struct {
	Kind TxKind
	// Txid is the transaction's txid, hash byte order.
	Txid [32]byte
	// Outputs are the output indices admitted.
	Outputs []int
	// Retain are the input indices that spend an output the topic holds.
	Retain []int
	// Carrier is set for TxGrant, TxPolicy and TxWrap.
	Carrier *Carrier
	// Token, Predecessor and Parent are set for a token. Predecessor is the
	// token at seq - 1 read from the parent the BEEF carries; nil at seq 0,
	// where the parent is the chain tree.
	Token       *ChainToken
	Predecessor *ChainToken
	Parent      [32]byte
	// Spent is, for TxSweep, every outpoint the sweep's inputs spend.
	Spent []transaction.Outpoint
}

Admission is what a host admits from one transaction: the outputs to admit and the held inputs to retain (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 11.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, as the engine hands them to the topic manager). held decides only what is retained, never a verdict: the predecessor of a token is read from the parent its BEEF carries, and no rule reads another topic or anything this topic holds. SPV of the BEEF is the engine's and is assumed to have run, including the scripts of an unproven carrier's input.

Every refusal is an error: a topic manager raises it rather than answer with empty instructions, so the engine records nothing for the txid.

type Carrier

type Carrier struct {
	Grant  *Grant
	Policy *Policy
	Wrap   *WrapRecord
	// Owner is the record's org, the key the carrier is bound to.
	Owner []byte
	// Record is the 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 sweep of it
	// retracts the carrier, and for a grant it is the revocation outpoint.
	Funding transaction.Outpoint
}

Carrier is an admitted grant, policy or wrap carrier.

type ChainToken

type ChainToken struct {
	Kind  Kind // KindOrg or KindGroup
	Org   *Org
	Group *Group
	// Record is the record exactly as carried (the token's second field).
	Record []byte
	// Vout is the token output's index.
	Vout uint32
}

ChainToken is a chain token's output: its record, decoded.

func ReadToken

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

ReadToken reads the one token a transaction holds, well formed, without its parent: how the index and a reader read a stored token (spec section 11.6), which the engine keeps alone with its proof.

func ReadTokenOutput added in v0.7.3

func ReadTokenOutput(o *transaction.TransactionOutput, vout uint32) (*ChainToken, error)

ReadTokenOutput reads one output as a well-formed chain token, without its parent: a token's tag, two fields and a signature, 1 satoshi, a record that decodes, the canonical lock under the record's organization and a field signature that verifies. It is how a host's index reads an output its topic admitted.

func StoredToken

func StoredToken(b []byte) (*transaction.Transaction, *ChainToken, error)

StoredToken reads a chain token as a host stores it: the token's transaction alone, with its proof. It returns the transaction and the token output's record, decoded, without the parent.

func (*ChainToken) Seq

func (t *ChainToken) Seq() uint64

Seq is the token's seq.

type Class

type Class struct {
	Name    string
	Members []string // sorted
	Free    bool
	Limit   int // most outputs one answer holds
}

Class is one lookup question class of ls_borg (spec section 10.2).

type Entry

type Entry struct {
	Sender     []byte
	Recipient  []byte
	KeyID      [32]byte
	Ciphertext []byte
}

Entry is a parsed wrap: the BRC-78 header and the ciphertext.

func CheckEntry

func CheckEntry(b, org []byte, epochID [32]byte, epoch uint32) (*Entry, error)

CheckEntry is the host's rule for one wrap of a wrap record: exactly WrapLen bytes, the version, the organization as sender, a canonical recipient that is neither the organization nor the anyone key, and the key id BRC-369 derives for the record's epoch.

func ParseEntry

func ParseEntry(b []byte) (*Entry, error)

ParseEntry splits one wrap without checking it against a record.

type Epoch

type Epoch struct {
	Epoch uint64
	// ID is EpochID of the record of the token that began the epoch.
	ID [32]byte
	// Commitment is the BRC-369 digest of the epoch's key.
	Commitment [32]byte
	// Seq, Txid and Height are that token's.
	Seq    uint64
	Txid   [32]byte
	Height uint32
	// Removed reports that the token removed a member.
	Removed bool
}

Epoch is one epoch a group's chain began.

type Grant

type Grant struct {
	Hall      string            // key 1
	Org       []byte            // key 2, the certifier and the carrier's owner
	Subject   []byte            // key 3, the member's identity key
	Serial    [32]byte          // key 4, the certificate serial number
	RevTxid   [32]byte          // key 5 [0], hash byte order
	RevVout   uint32            // key 5 [1]
	Fields    map[string][]byte // key 6, each field's BRC-2 ciphertext
	Signature []byte            // key 7, the certifier's DER signature
	Keyring   map[string][]byte // key 8, each field revelation key encrypted to the subject
	Reveal    map[string][]byte // key 9, each field revelation key in the clear; nil when absent
	Extra     cbor.Map          // integer keys above 9, preserved and ignored
}

Grant is one membership grant record: the payload of one grant carrier. It is a BRC-52 certificate (certifier the organization, subject the member) laid out as CBOR, with the subject's master keyring and, unless the organization is opaque, a public reveal of every field.

func BuildGrant

func BuildGrant(ctx context.Context, orgKey *ec.PrivateKey, s GrantSpec) (*Grant, error)

BuildGrant issues a grant under the organization's private key: each field encrypted under its revelation key (BRC-52), each revelation key encrypted to the subject under [2, "certificate field encryption"] with the field name as key id (the master keyring), and the certificate signed by the organization under [2, "certificate signature"] (go-sdk's Sign). A client with only a BRC-100 wallet builds the same record through Encrypt and CreateSignature.

func DecodeGrant

func DecodeGrant(p []byte) (*Grant, error)

DecodeGrant parses a grant record in the refusal order. It checks the record's own rules; the certificate's signature, the revocation outpoint and the reveal are content rules (CheckCertificate, CheckRevocation, CheckReveal), applied after the carrier's.

func (*Grant) Certificate

func (g *Grant) Certificate() (*certificates.Certificate, error)

Certificate is the grant as a go-sdk BRC-52 certificate: the type this version defines, the serial, subject, certifier (the organization), revocation outpoint, each field's ciphertext in standard padded base64 (the spelling BRC-52's binary form signs), and the signature.

func (*Grant) CheckCertificate

func (g *Grant) CheckCertificate(ctx context.Context) error

CheckCertificate is the content rule grant-signature: the certificate's signature verifies under BRC-52 against the organization as certifier.

func (*Grant) CheckReveal

func (g *Grant) CheckReveal() (map[string]string, error)

CheckReveal is the content rule grant-reveal, applied when the record carries a reveal: every revealed key opens its field, and every value meets its rule. It returns the plaintext fields.

func (*Grant) CheckRevocation

func (g *Grant) CheckRevocation(inputTxid [32]byte, inputVout uint32) error

CheckRevocation is the content rule grant-revocation: the certificate's revocation outpoint is the outpoint the carrier's one input spends, so sweeping the carrier's funding output revokes the certificate for every BRC-52 verifier.

func (*Grant) Encode

func (g *Grant) Encode() ([]byte, error)

Encode writes the grant record in canonical CBOR.

func (*Grant) OpenFields

func (g *Grant) OpenFields(ctx context.Context, subject wallet.Interface) (map[string]string, error)

OpenFields is the subject's side: it decrypts its master keyring through its own wallet (counterparty the organization) and every field with it, as go-sdk's certificates.DecryptFields does for a stored certificate.

func (*Grant) OpenFieldsAsOrg

func (g *Grant) OpenFieldsAsOrg(ctx context.Context, org wallet.Interface) (map[string]string, error)

OpenFieldsAsOrg is the organization's side of the same keyring: the BRC-2 key a keyring entry is encrypted under is shared by the two ends, so the organization's wallet opens it with the subject as counterparty. It is how the organization reads back the fields of a grant it issued when the grant carries no reveal.

func (*Grant) Preimage

func (g *Grant) Preimage() ([]byte, error)

Preimage is the BRC-52 binary form without the signature: the bytes the organization signs.

func (*Grant) Validate

func (g *Grant) Validate() error

Validate applies every rule that needs only the record itself.

type GrantSpec

type GrantSpec struct {
	Hall       string
	Subject    *ec.PublicKey
	Serial     [32]byte
	RevTxid    [32]byte
	RevVout    uint32
	Values     map[string]string   // expiry, role, scope in the clear
	FieldKeys  map[string][32]byte // each field's revelation key
	FieldIVs   map[string][32]byte // each field ciphertext's IV
	KeyringIVs map[string][32]byte // each keyring entry's IV
	Reveal     bool                // publish the revelation keys
}

GrantSpec is everything a grant is built from. The random values (field revelation keys, IVs) are inputs so that vectors are reproducible; a client draws them from a CSPRNG.

type Group

type Group struct {
	Hall         string           // key 1
	Org          []byte           // key 2
	Group        [GroupIDLen]byte // key 3, random, fixed at creation
	Seq          uint64           // key 4
	Prev         [32]byte         // key 5, txid of the token at seq-1; zero at seq 0
	Name         string           // key 6
	Epoch        uint64           // key 7
	EpochSeq     uint64           // key 8, seq of the token that began this epoch
	Commitment   [32]byte         // key 9, BRC-369 digest of this epoch's key
	Add          [][]byte         // key 10, members added, ascending
	Remove       [][]byte         // key 11, members removed, ascending
	Count        uint64           // key 12, members after this transition
	Members      [32]byte         // key 13, MembersRoot after this transition
	RotateOnJoin bool             // key 14, adding a member also begins an epoch
	RotateEvery  uint64           // key 15, seconds; 0 means no schedule
	Created      uint64           // key 16, Unix seconds, a claim
	Successor    []byte           // key 17, the key that may carry this chain on; nil is CBOR null
	Extra        cbor.Map         // integer keys above 17, preserved and ignored
}

Group is one group record: the second field of a group chain token. Each token is one transition of the group's membership; a token that begins an epoch is that epoch's descriptor.

func CheckEpochToken

func CheckEpochToken(groupRecord []byte, w *WrapRecord) (*Group, error)

CheckEpochToken is the member's check 1 (spec section 6.4): the group record of the token that began the wrap's epoch hashes to the wrap's epoch id and names the same hall, organization, group and epoch. The token's proof against the member's headers is checked by the caller.

func DecodeGroup

func DecodeGroup(p []byte) (*Group, error)

DecodeGroup parses a group record in the refusal order.

func (*Group) BeginsEpoch

func (g *Group) BeginsEpoch() bool

BeginsEpoch reports whether this token began its epoch.

func (*Group) Encode

func (g *Group) Encode() ([]byte, error)

Encode writes the group record in canonical CBOR.

func (*Group) Validate

func (g *Group) Validate() error

Validate applies every rule that needs only the record itself.

type GroupChain

type GroupChain struct {
	// Tokens are the records in chain order, and Statuses the fold's status
	// of each (GroupFold.Apply).
	Tokens   []*Group
	Statuses []string
	// Epochs are the epochs the usable chain began, ascending.
	Epochs []Epoch
	// contains filtered or unexported fields
}

GroupChain is a group's chain folded from seq 0 (FoldGroup).

func FoldGroup

func FoldGroup(links []Link) (*GroupChain, error)

FoldGroup folds a group's chain from seq 0 with nothing but the records: links are the tokens in chain order, each the successor by spend of the one before. It asks no host and verifies no proof; the caller has checked each token against its own headers. It refuses a chain no host would have admitted (a record that does not decode, a first token that is not seq 0, a transition that breaks CheckGroupTransition, a token mined below its predecessor), and reports per token the status GroupFold gives. Epochs come only from the usable part.

func (*GroupChain) EpochByNumber

func (c *GroupChain) EpochByNumber(e uint64) (Epoch, bool)

EpochByNumber is epoch e of the usable chain, if the chain began it.

func (*GroupChain) Latest

func (c *GroupChain) Latest() *Group

Latest is the last usable token, or nil.

func (*GroupChain) Members

func (c *GroupChain) Members() [][]byte

Members is the member set after the last usable token, ascending.

func (*GroupChain) Usable

func (c *GroupChain) Usable() int

Usable is how many tokens from seq 0 fold without a mismatch: a reader fails closed from the first mismatched token on.

type GroupFold

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

GroupFold folds a group's chain from seq 0: the members after each token, every key any token removed, and every epoch's commitment.

func NewGroupFold

func NewGroupFold() *GroupFold

NewGroupFold starts a fold before seq 0.

func (*GroupFold) Apply

func (f *GroupFold) Apply(g *Group) string

Apply folds the next token and returns its status, the first that applies: members-mismatch (it removes a non-member, adds a member, or does not reproduce count and members; sticky), commitment-reuse (it begins an epoch whose commitment an earlier epoch had), rejoin-unrotated (it adds a key an earlier token removed without beginning an epoch), consistent.

func (*GroupFold) Clone added in v0.7.3

func (f *GroupFold) Clone() *GroupFold

Clone is a copy of the fold, to fold a second successor on.

func (*GroupFold) Holds added in v0.7.3

func (f *GroupFold) Holds(key []byte) bool

Holds reports whether key is a member after the last token folded.

func (*GroupFold) Members

func (f *GroupFold) Members() [][]byte

Members is the member set after the last token folded, ascending.

type Host

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

Host is what admission needs beyond the submission: the topic's hall, a chain tracker over the host's own block headers, the host's BEEF bound (DefaultMaxBEEF when zero) and its sweep input bound (DefaultMaxSweepInputs when zero). Nothing the topic holds is here: a verdict never reads another record (spec section 11.1).

type InclusionContext

type InclusionContext struct {
	Seq   uint64
	Index uint64
	Size  uint64
	Path  commit.Path
}

InclusionContext is the BRC-24 context a member answer carries for each grant (spec section 10.2): the organization token whose roll was used, the grant's leaf index and the roll's size, and the RFC 6962 inclusion path.

func DecodeContext

func DecodeContext(b []byte) (*InclusionContext, error)

DecodeContext parses a context, bounding it first.

func ProveGrant

func ProveGrant(seq uint64, roll [][32]byte, grant [32]byte) (*InclusionContext, error)

ProveGrant builds the context for the grant at commitment within a roll.

func ProvePolicy added in v0.6.0

func ProvePolicy(seq uint64, set [][32]byte, policy [32]byte) (*InclusionContext, error)

ProvePolicy builds the context for the policy record at commitment within a policy set. The context has a grant's shape (spec section 10.2); only the root it proves against differs, because the roll and the policy set are two RFC 6962 roots over commitments on one chain.

func (*InclusionContext) Encode

func (c *InclusionContext) Encode() ([]byte, error)

Encode writes the context as canonical CBOR [seq, index, size, path], each step [bytes(32), bool], the bool true when the sibling is on the left.

func (*InclusionContext) VerifyGrant

func (c *InclusionContext) VerifyGrant(grant, roll [32]byte) bool

VerifyGrant checks a context against the roll root of the organization token at its seq: the path takes the grant's commitment to the root. The leaf and node prefixes of RFC 6962 keep a path from passing a subtree off as a leaf, so membership needs no more; index and size are hints.

func (*InclusionContext) VerifyPolicy added in v0.6.0

func (c *InclusionContext) VerifyPolicy(policy, root [32]byte) bool

VerifyPolicy checks a context against the policy root of the organization token at its seq: the path takes the policy record's commitment to the root.

type Kind

type Kind string

Kind names what an output claims to be (spec section 11.1, Classify).

const (
	KindNone    Kind = ""
	KindGrant   Kind = "grant"
	KindPolicy  Kind = "policy"
	KindWrap    Kind = "wrap"
	KindOrg     Kind = "org-token"
	KindGroup   Kind = "group-token"
	KindFunding Kind = "funding"
)

func Classify

func Classify(s []byte) Kind

Classify says what a locking script claims, reading nothing else of it. A script that claims something is then held to the exact script rebuilt from its fields (spec section 11.1); this is only the first look.

type Link struct {
	Record []byte
	Txid   [32]byte
	Height uint32
}

Link is one token of a group's chain as a reader holds it: its record, the txid of its transaction (hash byte order) and the height of its block.

type Org

type Org struct {
	Hall    string     // key 1
	Org     []byte     // key 2, the organization's identity key
	Seq     uint64     // key 3, 0 for the first token
	Prev    [32]byte   // key 4, txid (hash byte order) of the token at seq-1; zero at seq 0
	Name    string     // key 5, display name
	Admit   [][32]byte // key 6, grant commitments entering the roll, ascending
	Revoke  [][32]byte // key 7, grant commitments leaving the roll, ascending
	Count   uint64     // key 8, grants in the roll after this transition
	Roll    [32]byte   // key 9, RollRoot of the roll after this transition
	Opaque  bool       // key 10, grants carry no public reveal
	Created uint64     // key 11, Unix seconds, a claim
	// The policy set, beside the roll and on the same chain, so that one
	// order covers a change of membership and a change of policy.
	Define      [][32]byte // key 12, policy commitments entering the set, ascending
	Retire      [][32]byte // key 13, policy commitments leaving it, ascending
	PolicyCount uint64     // key 14, policy records in the set after this transition
	Policy      [32]byte   // key 15, PolicyRoot of the set after this transition
	Successor   []byte     // key 16, the key that may carry the chain on; nil is CBOR null
	// Extra holds integer keys above 16, preserved verbatim and ignored.
	Extra cbor.Map
}

Org is one organization record: the second field of an organization chain token. Each token is one transition of the organization's roll.

func DecodeOrg

func DecodeOrg(p []byte) (*Org, error)

DecodeOrg parses an organization record in the refusal order.

func (*Org) Encode

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

Encode writes the organization record in canonical CBOR.

func (*Org) Validate

func (o *Org) Validate() error

Validate applies every rule that needs only the record itself, in the refusal order of spec section 3.1.

type OrgFold

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

OrgFold folds an organization's chain from seq 0: the roll after each token. Once a token breaks the fold the chain is unusable from it on, and every later token reports the same status.

func NewOrgFold

func NewOrgFold() *OrgFold

NewOrgFold starts a fold before seq 0.

func (*OrgFold) Apply

func (f *OrgFold) Apply(o *Org) string

Apply folds the next token (the caller supplies them in seq order along spends) and returns its status: roll-mismatch when it revokes a commitment the roll does not hold, admits one it already holds, or does not reproduce count and roll; policy-mismatch when the same happens to the policy set; consistent otherwise. Both are sticky, and the roll is reported first, so a chain that breaks once reports the same status from there on.

func (*OrgFold) Clone added in v0.7.3

func (f *OrgFold) Clone() *OrgFold

Clone is a copy of the fold, to fold a second successor on: a host's index keeps the fold after a token while a successor of it may still arrive.

func (*OrgFold) Holds added in v0.7.3

func (f *OrgFold) Holds(c [32]byte) bool

Holds reports whether the roll after the last token folded holds the commitment c.

func (*OrgFold) Policy added in v0.6.0

func (f *OrgFold) Policy() [][32]byte

Policy is the policy set after the last token folded, ascending.

func (*OrgFold) Roll

func (f *OrgFold) Roll() [][32]byte

Roll is the roll after the last token folded, ascending.

type OutpointRow

type OutpointRow struct {
	Commitments   [][32]byte
	WinnerDropped bool
	Swept         bool
}

OutpointRow is the index's row for one funding outpoint (spec section 11.2): the commitments of the carriers admitted on it, whether its winner was dropped, and whether an admitted sweep in the host's best chain spends it.

func (*OutpointRow) Status

func (r *OutpointRow) Status(c [32]byte) string

Status is a carrier's status on its row: retracted, then superseded, then held. It depends on the admitted set and the row, never on arrival order.

func (*OutpointRow) Winner

func (r *OutpointRow) Winner() (c [32]byte, ok bool)

Winner is the outpoint's answered carrier: the lowest commitment, compared as 32 bytes in hash byte order. ok is false for an empty row.

type Permission added in v0.6.0

type Permission struct {
	Service  string
	Action   string
	Resource string
	Prefix   bool
}

Permission is one parsed permission: what a service, an action and a resource a subject may be granted. Prefix is set when the resource ended in "*", which makes it a prefix rather than a whole resource.

permission = service "/" action "/" resource
service    = 1*16( lower / DIGIT / "-" )
action     = 1*32( lower / DIGIT / "-" )
resource   = "*" / ( 1*192( lower / DIGIT / "-" / "_" / "." / "/" / ":" ) [ "*" ] )

The grammar is ASCII and lower case, so no two permissions can look alike and every implementation compares them as bytes. A service and an action are never "*", so no permission is everything everywhere.

func Asked added in v0.6.0

func Asked(s string) (Permission, error)

Asked parses a permission a service asks about. It is stricter than ParsePermission: a "*" anywhere in it is a programming error, so it is refused rather than treated as a character or as a wildcard.

func ParsePermission added in v0.6.0

func ParsePermission(s string) (Permission, error)

ParsePermission applies the grammar of spec section 5A.2. A service and an action hold no "/", so the first two separators split the three parts even where the resource holds further ones.

func (Permission) Grants added in v0.6.0

func (p Permission) Grants(asked Permission) bool

Grants reports whether the held permission p grants the asked one. The service and the action always match exactly; a held resource that ended in "*" matches by prefix, and nothing else matches: there is no suffix wildcard, none inside a resource, and no hierarchy a separator implies.

The asked permission must carry no "*" (Asked below); Grants reads one that does as a resource of its own and so grants nothing by accident.

func (Permission) String added in v0.6.0

func (p Permission) String() string

String writes the permission back, which is the one spelling a reader accepted: ParsePermission(p.String()) == p for every parsed permission.

type Policy added in v0.6.0

type Policy struct {
	Hall        string   // key 1
	Org         []byte   // key 2, the organization's identity key, and the carrier's owner
	Kind        uint64   // key 3, PolicyRole or PolicyBinding
	Role        string   // key 4, the role this record defines or binds
	Permissions []string // key 5, a definition's permissions, or a binding's attenuation
	To          []byte   // key 6, a binding's group id (16 bytes) or identity key (33); nil is CBOR null
	Expiry      string   // key 7, a binding's expiry; "" is CBOR null
	Created     uint64   // key 8, Unix seconds, a claim
	// Extra holds integer keys above 8, preserved verbatim and ignored.
	Extra cbor.Map
}

Policy is one policy record: the payload of a policy carrier's one output. It is either a role definition or a binding, by Kind. The organization's version 2 token commits to the set of them by its policy root, so what a role may do is a committed fact of the chain and not a claim of whoever serves it.

A policy record is in the clear: nothing in it is encrypted, so every host and every follower of the hall reads an organization's roles and bindings (spec section 16.16).

func DecodePolicy added in v0.6.0

func DecodePolicy(b []byte) (*Policy, error)

DecodePolicy parses a policy record in the refusal order.

func (*Policy) BoundToGroup added in v0.6.0

func (p *Policy) BoundToGroup() bool

BoundToGroup reports whether the record binds its role to a group, which is a To of GroupIDLen bytes, rather than to one identity key.

func (*Policy) Encode added in v0.6.0

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

Encode writes the policy record in canonical CBOR. A To or an Expiry this version leaves out is written as CBOR null, so the key is always present.

func (*Policy) IsBinding added in v0.6.0

func (p *Policy) IsBinding() bool

IsBinding reports whether the record binds a role rather than defining one.

func (*Policy) Validate added in v0.6.0

func (p *Policy) Validate() error

Validate applies every rule that needs only the record itself, in the refusal order of spec section 3.1.

type Question

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

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

func ParseQuery

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

ParseQuery validates a BRC-24 query object as parsed: a JSON object whose members are all strings (a member given twice takes its last value, as JSON parsers do), whose member set is exactly one class's, and whose values meet their rules. Anything else is refused, never answered empty.

type Subject added in v0.6.0

type Subject struct {
	// Key is the subject's identity key.
	Key []byte
	// Member is false unless the caller established a current membership.
	Member bool
	// Roles are the roles the subject's current grants name. A value that is
	// not a well-formed role name names no role.
	Roles []string
	// Groups are the groups of this organization whose latest token's
	// members include Key.
	Groups [][GroupIDLen]byte
}

Subject is what a service has established about one subject before it asks what that subject may do. Every field is a conclusion the caller reached by the checks of spec section 13: that the subject is a current member, which roles its current grants name (read in the clear, revealed or disclosed by the subject), and which of the organization's groups hold it at their latest token.

type Token

type Token struct {
	Verb      string
	Qualifier string
	HasQual   bool
}

Token is one scope token: a verb and an optional qualifier.

func ParseScope

func ParseScope(s string) ([]Token, error)

ParseScope applies BRC-169 section 9.2's grammar with one restriction: the whole-scope "*" is refused, because a membership grant never confers unrestricted authority.

scope       = scope-token *( "," scope-token )
scope-token = verb [ ":" qualifier ]
verb        = 1*32( lower / DIGIT / "-" )
qualifier   = 1*64( lower / DIGIT / "-" / "_" / "." )

type TxKind

type TxKind int

TxKind is what an admitted transaction is to the topic.

const (
	TxGrant TxKind = iota + 1
	TxPolicy
	TxWrap
	TxOrgToken
	TxGroupToken
	TxSweep
)

The kinds of admitted transaction.

func (TxKind) String

func (k TxKind) String() string

type WrapRecord

type WrapRecord struct {
	Hall    string           // key 1
	Org     []byte           // key 2, the releaser and the carrier's owner
	Group   [GroupIDLen]byte // key 3
	Epoch   uint64           // key 4
	EpochID [32]byte         // key 5, SHA-256 of the record of the token that began the epoch
	Entries [][]byte         // key 6, WrapLen bytes each, ascending by recipient
	Extra   cbor.Map         // integer keys above 6, preserved and ignored
}

WrapRecord is one wrap record: the payload of one wrap carrier. It releases one epoch's key to up to MaxEntries members, one BRC-369 release (BRC-78 serialization) each.

func DecodeWrap

func DecodeWrap(p []byte) (*WrapRecord, error)

DecodeWrap parses a wrap record in the refusal order.

func (*WrapRecord) Encode

func (w *WrapRecord) Encode() ([]byte, error)

Encode writes the wrap record in canonical CBOR.

func (*WrapRecord) Recipients

func (w *WrapRecord) Recipients() [][]byte

Recipients returns each entry's recipient key, in record order.

func (*WrapRecord) Validate

func (w *WrapRecord) Validate() error

Validate applies every rule that needs only the record itself.

Jump to

Keyboard shortcuts

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