transparency

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package transparency implements an append-only binary Merkle tree and the supporting types for the Hush transparency log (RFC 6962 / CT model).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LeafHash

func LeafHash(data []byte) [32]byte

LeafHash computes SHA-256(0x00 || data) per RFC 6962 §2.1. Exported so tests and the entry package can compute reference values.

func NodeHash

func NodeHash(left, right [32]byte) [32]byte

NodeHash computes SHA-256(0x01 || left || right) per RFC 6962 §2.1. Exported for test validation.

func VerifyProof

func VerifyProof(leafData []byte, leafIndex, treeSize uint64, auditPath [][32]byte, expectedRoot [32]byte) bool

VerifyProof verifies an inclusion proof for leafData at leafIndex in a tree of treeSize leaves with the given expectedRoot.

Types

type AppendResult

type AppendResult struct {
	LeafIndex    uint64
	TreeSize     uint64
	AuditPath    [][32]byte
	RootHash     [32]byte
	LogSignature []byte
}

AppendResult is returned by AppendEntry with proof data the caller can forward to the client for immediate verification.

type Broadcaster

type Broadcaster interface {
	BroadcastToUser(userID string, message []byte)
}

Broadcaster sends WS messages to connected users. Implemented by ws.Hub.

type LogEntry

type LogEntry struct {
	// Field 1: type of key operation.
	OperationType OperationType
	// Field 2: 32-byte Ed25519 root public key of the acting user.
	UserPublicKey []byte
	// Field 3: device public key, KeyPackage reference hash, or nil.
	SubjectKey []byte
	// Field 4: Unix seconds of the event.
	Timestamp int64
	// Field 5: Ed25519 signature by UserPublicKey over SerializeForUserSign().
	UserSignature []byte
}

LogEntry represents a single entry in the transparency log. Field numbering matches the CBOR wire format (1-indexed integer keys).

Signing model:

  • Fields 1-4 form the payload the user signs (SerializeForUserSign).
  • UserSignature (field 5) is the Ed25519 signature by the user's root key.
  • The log countersigns the full CBOR (fields 1-5) + leaf index + root hash.

func (*LogEntry) LeafHash

func (e *LogEntry) LeafHash() ([32]byte, error)

LeafHash returns leafHash(MarshalCBOR()) - the 32-byte value stored in the Merkle tree for this entry.

func (*LogEntry) MarshalCBOR

func (e *LogEntry) MarshalCBOR() ([]byte, error)

MarshalCBOR returns the deterministic CBOR encoding of all five fields (including UserSignature). This is the byte sequence hashed as the leaf.

func (*LogEntry) SerializeForUserSign

func (e *LogEntry) SerializeForUserSign() ([]byte, error)

SerializeForUserSign returns the deterministic CBOR encoding of fields 1-4. This is the payload the user signs before submitting the entry.

type LogSigner

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

LogSigner holds the Ed25519 signing keypair for the transparency log. It countersigns each log entry after the entry is appended to the tree, proving that the log operator witnessed the inclusion.

func LoadLogSignerFromEnv

func LoadLogSignerFromEnv() (*LogSigner, error)

LoadLogSignerFromEnv reads the transparency log signing keypair from the TRANSPARENCY_LOG_PRIVATE_KEY environment variable (32-byte seed, hex-encoded).

Behavior:

  • Variable present: parse and return keypair.
  • Variable absent + PRODUCTION not set: generate an ephemeral key and log a warning.
  • Variable absent + PRODUCTION set: return an error (safe default).

func NewEphemeralLogSigner

func NewEphemeralLogSigner() (*LogSigner, error)

NewEphemeralLogSigner generates a fresh random Ed25519 keypair. Exported for use in tests that need a valid LogSigner without environment variables.

func NewLogSignerFromKey

func NewLogSignerFromKey(privKey ed25519.PrivateKey) *LogSigner

NewLogSignerFromKey constructs a LogSigner from an existing Ed25519 private key. Used in tests to inject a known keypair.

func (*LogSigner) Countersign

func (s *LogSigner) Countersign(entry *LogEntry, leafIndex uint64, root [32]byte) ([]byte, error)

Countersign signs CBOR(entry fields 1-5) || leafIndexBE8 || rootHash[32]. The signature proves that the log operator included this entry at the given position under the given root at the time of signing.

func (*LogSigner) PublicKey

func (s *LogSigner) PublicKey() ed25519.PublicKey

PublicKey returns the log's Ed25519 public key. Clients use this key to verify log countersignatures received via the handshake response.

func (*LogSigner) Sign

func (s *LogSigner) Sign(data []byte) []byte

Sign returns an Ed25519 signature over data using the log's private key.

type MerkleTree

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

MerkleTree is an in-memory, append-only binary Merkle tree. Each leaf stores the hash of raw leaf data. The fringe (right-edge sibling hashes) enables O(log N) append without recomputing the full tree.

func FromFringe

func FromFringe(fringe [][32]byte, size uint64) *MerkleTree

FromFringe reconstructs a MerkleTree state from a stored fringe and size. This is used on startup to recover from the latest persisted tree head without re-reading all log entries.

func NewMerkleTree

func NewMerkleTree() *MerkleTree

NewMerkleTree returns an empty MerkleTree.

func (*MerkleTree) Append

func (t *MerkleTree) Append(leafData []byte) uint64

Append adds a new leaf (raw data bytes) and returns its 0-based index. Each call is O(log N).

func (*MerkleTree) Fringe

func (t *MerkleTree) Fringe() [][32]byte

Fringe returns a copy of the right-edge sibling hashes needed to reconstruct the tree state after persistence.

func (*MerkleTree) Proof

func (t *MerkleTree) Proof(leafIndex uint64) ([][32]byte, error)

Proof returns the inclusion audit path for the leaf at leafIndex. The audit path contains the sibling hashes from the leaf level up to the root - enough to recompute the root without the other leaves. Returns an error if leafIndex >= Size().

func (*MerkleTree) Root

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

Root returns the current Merkle root. Returns the zero value for an empty tree.

func (*MerkleTree) SetLeaves

func (t *MerkleTree) SetLeaves(hashes [][32]byte)

SetLeaves populates the stored leaf hashes for a fringe-recovered tree. Must be called before Proof() when the tree was loaded via FromFringe. The hashes must be in leaf-index order and len(hashes) must equal Size().

func (*MerkleTree) Size

func (t *MerkleTree) Size() uint64

Size returns the number of leaves in the tree.

type OperationType

type OperationType = string

OperationType enumerates the allowed key lifecycle operations.

const (
	OpRegister        OperationType = "register"
	OpDeviceAdd       OperationType = "device_add"
	OpDeviceRevoke    OperationType = "device_revoke"
	OpKeyPackage      OperationType = "keypackage"
	OpMLSCredential   OperationType = "mls_credential"
	OpAccountRecovery OperationType = "account_recovery"
)

type ProofResponse

type ProofResponse struct {
	Entries  []models.TransparencyLogEntry
	Proofs   []models.MerkleInclusionProof
	TreeSize uint64
	RootHash [32]byte
}

ProofResponse is returned by GetProof - the full inclusion evidence for a given public key's history.

type TransparencyService

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

TransparencyService orchestrates appending entries to the Merkle tree, countersigning them, persisting to the DB, and generating inclusion proofs.

The in-memory MerkleTree is recovered from the DB on construction via RecoverFromDB. It is protected by a mutex so concurrent handler goroutines can safely call AppendEntry.

func NewTransparencyService

func NewTransparencyService(store TransparencyStore, signer *LogSigner) (*TransparencyService, error)

NewTransparencyService creates a service and recovers the Merkle tree fringe from the latest DB tree head. If the log is empty the tree starts at size 0.

func (*TransparencyService) AppendAndNotify

func (s *TransparencyService) AppendAndNotify(ctx context.Context, entry *LogEntry, userID string) error

AppendAndNotify appends an entry (skipping user signature in MVP mode) and broadcasts a transparency.key_change WS event to the specified user. Used by handlers that know the user ID and want fire-and-forget notification.

func (*TransparencyService) AppendEntry

func (s *TransparencyService) AppendEntry(ctx context.Context, entry *LogEntry) (*AppendResult, error)

AppendEntry verifies the user's signature (when present), appends the entry to the Merkle tree, countersigns, persists both the entry and the new tree head, and returns an AppendResult for immediate client verification.

When UserSignature is nil or empty the signature verification step is skipped. This is the MVP mode - client-side signing is added in T.1 Plan 03. A non-nil, non-empty UserSignature that fails verification returns an error without modifying tree state.

func (*TransparencyService) AppendEntrySkipSig

func (s *TransparencyService) AppendEntrySkipSig(ctx context.Context, entry *LogEntry) error

AppendEntrySkipSig appends an entry without requiring a user signature. Used by server handlers in MVP mode (T.1 Plan 02) before client-side signing is implemented in Plan 03. The UserSignature field of the entry is set to nil.

func (*TransparencyService) GetProof

func (s *TransparencyService) GetProof(ctx context.Context, pubKey []byte) (*ProofResponse, error)

GetProof returns inclusion proofs for all log entries belonging to pubKey. Each entry has its own MerkleInclusionProof. The proofs reference the current tree size and root so the client can verify freshness.

func (*TransparencyService) RecoverFromDB

func (s *TransparencyService) RecoverFromDB(ctx context.Context) error

RecoverFromDB loads the latest persisted tree head and reconstructs the in-memory tree fringe so new entries can be appended without a full replay.

func (*TransparencyService) RootHash

func (s *TransparencyService) RootHash() [32]byte

RootHash returns the current Merkle root.

func (*TransparencyService) SetBroadcaster

func (s *TransparencyService) SetBroadcaster(b Broadcaster)

SetBroadcaster wires the WS hub for transparency.key_change notifications. Called once in main.go after the hub is created. Nil-safe: the service works without a broadcaster; key_change events are simply not sent.

func (*TransparencyService) SignerPublicKey

func (s *TransparencyService) SignerPublicKey() ed25519.PublicKey

SignerPublicKey returns the log's Ed25519 public key for inclusion in the instance handshake response.

func (*TransparencyService) TreeSize

func (s *TransparencyService) TreeSize() uint64

TreeSize returns the current number of leaves in the tree. Safe to call without the lock since uint64 reads are atomic on all supported architectures, but callers needing consistency should use the lock explicitly.

type TransparencyStore

type TransparencyStore interface {
	// InsertLogEntry persists one log entry after it has been appended to the
	// in-memory Merkle tree and countersigned by the log. All fields are
	// mandatory (nil slices are rejected at the DB level).
	InsertLogEntry(ctx context.Context, leafIndex uint64, entry *LogEntry, cborBytes, leafHash, logSig []byte) error

	// GetLogEntriesByPubKey returns all log entries for the given user public key,
	// ordered by leaf_index ASC. Returns an empty slice (not an error) when no
	// entries exist.
	GetLogEntriesByPubKey(ctx context.Context, pubKey []byte) ([]models.TransparencyLogEntry, error)

	// GetAllLeafHashes returns every leaf_hash in leaf_index order.
	// Used at startup to rehydrate the Merkle tree's leaves slice so
	// Proof() can rebuild the full tree for any leaf index.
	GetAllLeafHashes(ctx context.Context) ([][32]byte, error)

	// GetLatestTreeHead returns the most recently persisted tree head, used to
	// restore the Merkle tree fringe after a server restart. Returns nil (no
	// error) when the log is empty.
	GetLatestTreeHead(ctx context.Context) (*models.TransparencyTreeHead, error)

	// InsertTreeHead persists the Merkle tree state after each append. The fringe
	// is the serialized right-edge sibling hashes (fringeToBytes format).
	InsertTreeHead(ctx context.Context, treeSize uint64, rootHash, fringe, headSig []byte) error
}

TransparencyStore is the persistence contract for the transparency log. The pgx implementation in db/transparency.go satisfies this interface. A mock can be injected in unit tests.

Jump to

Keyboard shortcuts

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