Documentation
¶
Overview ¶
Package borgrec is the byte-level contract of borg: the organisation 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
- Variables
- func AnyoneKey() []byte
- func CheckFieldValue(name, value string) error
- func CheckGroupTransition(prev *Group, prevTxid [32]byte, next *Group) error
- func CheckHall(s string) error
- func CheckHallName(s string) error
- func CheckIdentity(k []byte) error
- func CheckOrgTransition(prev *Org, prevTxid [32]byte, next *Org) error
- func CheckRole(s string) error
- func CheckScalar(k [32]byte) error
- func Commitment(k [32]byte) [32]byte
- func EpochID(groupRecord []byte) [32]byte
- func Fold(set map[string]bool, next *Group) error
- func FundingScript(key *ec.PublicKey) []byte
- func GrantType() [32]byte
- func GrantTypeBase64() string
- func Grants(tokens []Token, verb string) bool
- func IsAnyone(k []byte) bool
- func IsMembership(scope string) bool
- func MembersRoot(keys [][]byte) [32]byte
- func Mined(ctx context.Context, tx *transaction.Transaction, ...) bool
- func MinimalPath(mp *transaction.MerklePath, txid *chainhash.Hash) (*transaction.MerklePath, error)
- func NewGroupID(r io.Reader) ([GroupIDLen]byte, error)
- func NewHall(name string, r io.Reader) (string, error)
- func ParseExpiry(s string) (time.Time, error)
- func PushDropScript(key *ec.PublicKey, fields [][]byte, sig []byte) []byte
- func Reason(err error) string
- func RejoinUnrotated(removed map[string]bool, next *Group) bool
- func ReleaseInvoice(epochID [32]byte, epoch uint32) string
- func ReleaseKeyID(epochID [32]byte, epoch uint32) [32]byte
- func RollRoot(grants [][32]byte) [32]byte
- func SampleKey(r io.Reader) ([32]byte, error)
- func SignerKey(org []byte) ([]byte, error)
- func SignerPrivate(orgKey *ec.PrivateKey) (*ec.PrivateKey, error)
- func SymmetricKey(k [32]byte) [32]byte
- func TokenBEEF(token, parent *transaction.Transaction) ([]byte, error)
- func Topic(hall string) string
- func Unwrap(ctx context.Context, w wallet.Interface, wrap []byte, org *ec.PublicKey, ...) ([32]byte, error)
- func Wrap(ctx context.Context, w wallet.Interface, org []byte, member *ec.PublicKey, ...) ([]byte, error)
- func WrapWithIV(orgKey *ec.PrivateKey, member *ec.PublicKey, epochID [32]byte, epoch uint32, ...) ([]byte, error)
- type Admission
- type Carrier
- type ChainToken
- type Class
- type Entry
- type Epoch
- type Grant
- func (g *Grant) Certificate() (*certificates.Certificate, error)
- func (g *Grant) CheckCertificate(ctx context.Context) error
- func (g *Grant) CheckReveal() (map[string]string, error)
- func (g *Grant) CheckRevocation(inputTxid [32]byte, inputVout uint32) error
- func (g *Grant) Encode() ([]byte, error)
- func (g *Grant) OpenFields(ctx context.Context, subject wallet.Interface) (map[string]string, error)
- func (g *Grant) OpenFieldsAsOrg(ctx context.Context, org wallet.Interface) (map[string]string, error)
- func (g *Grant) Preimage() ([]byte, error)
- func (g *Grant) Validate() error
- type GrantSpec
- type Group
- type GroupChain
- type GroupFold
- type Host
- type InclusionContext
- type Kind
- type Link
- type Org
- type OrgFold
- type OutpointRow
- type Question
- type Token
- type TxKind
- type WrapRecord
Constants ¶
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 organisation 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" // 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.
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 organisation'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 organisation'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 // MaxKeys bounds the entries of a record map, unknown keys included. MaxKeys = 64 // 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).
const ( StatusConsistent = "consistent" StatusPending = "pending" StatusRollMismatch = "roll-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.
const ( StatusRetracted = "retracted" StatusSuperseded = "superseded" StatusHeld = "held" )
Carrier statuses (spec section 11.2), the first that applies.
const ( MKMagic = 0 MKHall = 1 MKOrg = 2 MKSubject = 3 MKSerial = 4 MKRevocation = 5 MKFields = 6 MKSignature = 7 MKKeyring = 8 MKReveal = 9 )
Grant record keys.
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 )
Group record keys.
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 )
Organisation record keys.
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.
const ( WKMagic = 0 WKHall = 1 WKOrg = 2 WKGroup = 3 WKEpoch = 4 WKEpochID = 5 WKEntries = 6 )
Wrap record keys.
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.
const DefaultMaxSweepInputs = 1024
DefaultMaxSweepInputs is the sweep input bound Admit applies when a host names none: the floor spec section 11.1 sets.
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).
const KeySigner = "signer"
KeySigner derives the organisation's signer key: the key every instance of the organisation's tooling holds, because each holds the organisation's identity key, and that is a member of the organisation'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.
const MaxContext = 2048
MaxContext bounds an encoded inclusion context.
const MaxPathSteps = 32
MaxPathSteps bounds an inclusion path: a roll of at most MaxRoll grants has a path of at most 16 steps.
Variables ¶
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.
var ( TagPrefix = []byte("bo") // TagOrg is the first field of an organisation 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 organisation 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} // 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.
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} 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.
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 organisation 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") ErrQuery = errors.New("borgrec: question is not one of the defined classes") )
The refusals. A host counts them by Reason.
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.
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}, {"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.
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).
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 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 ¶
CheckFieldValue applies the rule of a grant field to its decrypted value.
func CheckGroupTransition ¶
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 ¶
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 ¶
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 ¶
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 organisation or member.
func CheckOrgTransition ¶
CheckOrgTransition is the admission rule an organisation token meets against the token it spends (read from the topic's previous coins): same hall and organisation, the next seq, prev naming the predecessor's transaction, and a count that follows from the predecessor's and the change lists.
func CheckRole ¶
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 CheckScalar ¶
CheckScalar refuses a 32-byte big-endian value outside [1, n-1].
func Commitment ¶
Commitment is BRC-369 section 2.2's digest form.
func EpochID ¶
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 ¶
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 ¶
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 ¶
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 IsMembership ¶
IsMembership reports whether a scope makes its grant a membership: it parses and grants "member".
func MembersRoot ¶
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 ¶
func Mined(ctx context.Context, tx *transaction.Transaction, headers chaintracker.ChainTracker) bool
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 ¶
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 ¶
ParseExpiry applies the expiry rule: exactly YYYY-MM-DDTHH:MM:SSZ, a real UTC date and time, from 1970 to 9999.
func PushDropScript ¶
PushDropScript is the one canonical lock-before PushDrop for key, fields and an optional field signature (bcommon pushdrop.Script).
func RejoinUnrotated ¶
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 ¶
ReleaseInvoice is the BRC-43 invoice number the wrap is derived under.
func ReleaseKeyID ¶
ReleaseKeyID is BRC-369 section 5.2's key id bytes: SHA-256(epoch id || epoch as four bytes big-endian).
func RollRoot ¶
RollRoot is the RFC 6962 root an organisation record commits its roll to: the leaves are the grant commitments (carrier txids, hash byte order) in ascending byte order.
func SignerKey ¶
SignerKey is the signer key of the organisation org, compressed: the BRC-42 child of org under [1, "borg organisation"], key id signer, counterparty anyone. Anyone derives it from the organisation's public key, so a reader can tell that a member is the organisation's own signer key; only the organisation derives its private key.
func SignerPrivate ¶
func SignerPrivate(orgKey *ec.PrivateKey) (*ec.PrivateKey, error)
SignerPrivate is the private key of the organisation's signer key, derived from the organisation's identity key.
func SymmetricKey ¶
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 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 organisation), 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 organisation'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 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 ¶
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
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 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 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.
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 ¶
Entry is a parsed wrap: the BRC-78 header and the ciphertext.
func CheckEntry ¶
CheckEntry is the host's rule for one wrap of a wrap record: exactly WrapLen bytes, the version, the organisation as sender, a canonical recipient that is neither the organisation nor the anyone key, and the key id BRC-369 derives for the record's epoch.
func ParseEntry ¶
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 organisation, subject the member) laid out as CBOR, with the subject's master keyring and, unless the organisation is opaque, a public reveal of every field.
func BuildGrant ¶
BuildGrant issues a grant under the organisation'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 organisation 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 ¶
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 organisation), revocation outpoint, each field's ciphertext in standard padded base64 (the spelling BRC-52's binary form signs), and the signature.
func (*Grant) CheckCertificate ¶
CheckCertificate is the content rule grant-signature: the certificate's signature verifies under BRC-52 against the organisation as certifier.
func (*Grant) CheckReveal ¶
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 ¶
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) 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 organisation) 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 organisation's side of the same keyring: the BRC-2 key a keyring entry is encrypted under is shared by the two ends, so the organisation's wallet opens it with the subject as counterparty. It is how the organisation reads back the fields of a grant it issued when the grant carries no reveal.
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
Extra cbor.Map // integer keys above 16, 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, organisation, group and epoch. The token's proof against the member's headers is checked by the caller.
func DecodeGroup ¶
DecodeGroup parses a group record in the refusal order.
func (*Group) BeginsEpoch ¶
BeginsEpoch reports whether this token began its epoch.
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 (*GroupFold) Apply ¶
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.
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 ¶
InclusionContext is the BRC-24 context a member answer carries for each grant (spec section 10.2): the organisation 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 (*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 organisation 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.
type Link ¶
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 organisation'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
// Extra holds integer keys above 11, preserved verbatim and ignored.
Extra cbor.Map
}
Org is one organisation record: the second field of an organisation chain token. Each token is one transition of the organisation's roll.
type OrgFold ¶
type OrgFold struct {
// contains filtered or unexported fields
}
OrgFold folds an organisation'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.
type OutpointRow ¶
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 Question ¶
Question is a validated question: its class and its members.
func ParseQuery ¶
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 Token ¶
Token is one scope token: a verb and an optional qualifier.
func ParseScope ¶
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.
The kinds of admitted transaction.
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.