blockchain

package
v0.35.4 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 23 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsLive added in v0.35.0

func IsLive(healthData map[string]Data, owner string, ttl time.Duration, now time.Time) bool

IsLive reports whether owner has a heartbeat in healthData (a map of peer.ID -> RFC3339 timestamp, as written by the alive service) that is newer than ttl relative to now.

func Verify added in v0.35.0

func Verify(bucket, key string, d SignedData) error

Verify checks that an entry was signed by the peer it claims as Owner. The verifying public key is recovered directly from the Owner peer.ID (libp2p Ed25519 identities embed it), so no key distribution is needed.

Types

type Block

type Block struct {
	Index     int
	Timestamp string
	Storage   map[string]map[string]SignedData
	Hash      string
	PrevHash  string
}

Block represents each 'item' in the blockchain

func (Block) Checksum

func (b Block) Checksum() string

Checksum does SHA256 hashing of the block

func (Block) IsValid

func (newBlock Block) IsValid(oldBlock Block) bool

make sure block is valid by checking index, and comparing the hash of the previous block

func (Block) NewBlock

func (oldBlock Block) NewBlock(s map[string]map[string]SignedData) Block

create a new block using previous block's hash

type Blockchain

type Blockchain []Block

Blockchain is a series of validated Blocks

type BucketPolicy added in v0.35.0

type BucketPolicy struct {
	Owned       bool                            // signed + owner-enforced?
	OwnerOf     func(key string, v Data) string // who owns this entry
	Expiry      ExpiryKind
	TTL         time.Duration // only meaningful for Absolute
	Reclaimable bool          // may a non-owner claim the key after expiry?
}

BucketPolicy is the single source of truth for whether a bucket is authenticated and how its entries expire. Adding a new authenticated bucket is a one-line registry entry.

type Data added in v0.1.0

type Data string

func (Data) Unmarshal added in v0.2.0

func (d Data) Unmarshal(i interface{}) error

Unmarshal the result into the interface. Use it to retrieve data set with SetValue

type DataString added in v0.2.0

type DataString string

type DiskStore added in v0.3.0

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

func NewDiskStore added in v0.3.0

func NewDiskStore(d *diskv.Diskv) *DiskStore

func (*DiskStore) Add added in v0.3.0

func (m *DiskStore) Add(b Block)

func (*DiskStore) Last added in v0.3.0

func (m *DiskStore) Last() Block

func (*DiskStore) Len added in v0.3.0

func (m *DiskStore) Len() int

type ExpiryKind added in v0.35.0

type ExpiryKind int

ExpiryKind selects how a bucket's entries are aged out. See docs/content/en/docs/explanation/authenticated-ledger.md.

const (
	// NoExpiry: entries live forever (default for unregistered/legacy buckets).
	NoExpiry ExpiryKind = iota
	// Liveness: an entry is alive iff its owner's heartbeat is fresh.
	Liveness
	// Absolute: an entry expires TTL after its own signed UpdatedAt.
	Absolute
)

type Ledger

type Ledger struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func New

func New(w io.Writer, s Store, opts ...LedgerOption) *Ledger

New returns a new ledger which writes to the writer

func (*Ledger) Add

func (l *Ledger) Add(b string, s map[string]interface{})

Add data to the blockchain

func (*Ledger) Announce added in v0.1.0

func (l *Ledger) Announce(ctx context.Context, d time.Duration, async func())

Announce keeps updating async data to the blockchain. Sends a broadcast at the specified interval by making sure the async retrieved value is written to the blockchain

func (*Ledger) AnnounceDeleteBucket added in v0.2.5

func (l *Ledger) AnnounceDeleteBucket(ctx context.Context, interval, timeout time.Duration, bucket string)

AnnounceDeleteBucket Announce a deletion of a bucket. It stops when the bucket is deleted It takes an interval time and a max timeout. It is best effort, and the timeout is necessary, or we might flood network with requests if more writers are attempting to write to the same resource

func (*Ledger) AnnounceDeleteBucketKey added in v0.2.5

func (l *Ledger) AnnounceDeleteBucketKey(ctx context.Context, interval, timeout time.Duration, bucket, key string)

AnnounceDeleteBucketKey Announce a deletion of a key from a bucket. It stops when the key is deleted

func (*Ledger) AnnounceUpdate added in v0.8.4

func (l *Ledger) AnnounceUpdate(ctx context.Context, interval time.Duration, bucket, key string, value interface{})

AnnounceUpdate Keeps announcing something into the blockchain if state is differing

func (*Ledger) CurrentData added in v0.1.0

func (l *Ledger) CurrentData() map[string]map[string]Data

CurrentData returns the current ledger data (locking). Tombstoned entries are hidden and only the inner Value is exposed, so existing readers are unchanged.

func (*Ledger) CurrentStorage added in v0.35.0

func (l *Ledger) CurrentStorage() map[string]map[string]SignedData

CurrentStorage returns a deep copy of the raw signed storage (locking). Used by the reaper, which needs owner/version metadata.

func (*Ledger) Delete added in v0.2.4

func (l *Ledger) Delete(b string, k string)

Delete data from the ledger. With a signer this writes a signed tombstone so the deletion survives gossip reconciliation; without one it removes the key (legacy behaviour).

func (*Ledger) DeleteBucket added in v0.2.4

func (l *Ledger) DeleteBucket(b string)

DeleteBucket deletes a bucket from the ledger.

func (*Ledger) Exists added in v0.1.0

func (l *Ledger) Exists(b string, f func(Data) bool) (exists bool)

Exists returns true if there is one element with a matching value

func (*Ledger) GetKey

func (l *Ledger) GetKey(b, s string) (value Data, exists bool)

GetKey retrieve the current key from the blockchain

func (*Ledger) Index added in v0.3.0

func (l *Ledger) Index() int

Index returns last known blockchain index

func (*Ledger) IsOwnerLive added in v0.35.0

func (l *Ledger) IsOwnerLive(owner string) bool

IsOwnerLive reports whether owner currently has a fresh heartbeat. When ownership is disabled it always returns true, so existing readers behave exactly as before; under observe/enforce it lets readers skip entries whose owner has gone inactive without waiting for the reaper to tombstone them.

func (*Ledger) LastBlock added in v0.3.0

func (l *Ledger) LastBlock() Block

LastBlock returns the last block in the blockchain

func (*Ledger) LivenessBuckets added in v0.35.0

func (l *Ledger) LivenessBuckets() []string

LivenessBuckets returns the buckets whose entries expire with owner liveness.

func (*Ledger) OwnershipEnabled added in v0.35.0

func (l *Ledger) OwnershipEnabled() bool

OwnershipEnabled reports whether the ledger is running the authenticated merge (observe or enforce).

func (*Ledger) Persist

func (l *Ledger) Persist(ctx context.Context, interval, timeout time.Duration, bucket, key string, value interface{})

Persist Keeps announcing something into the blockchain until it is reconciled

func (*Ledger) Reap added in v0.35.0

func (l *Ledger) Reap(tombstoneTTL time.Duration)

Reap bounds ledger growth from inactive nodes. For every Liveness-managed bucket it signs a tombstone over each entry whose owner is no longer live, and it physically prunes tombstones older than tombstoneTTL. It is a no-op unless ownership is enabled and a signer is set; callers should run it only on the elected leader to avoid redundant writes.

See docs/content/en/docs/explanation/authenticated-ledger.md (section 9).

func (*Ledger) SetOwnership added in v0.35.0

func (l *Ledger) SetOwnership(mode OwnershipMode, r Registry, ttl time.Duration)

SetOwnership configures the merge mode/registry/ttl at runtime (called during node startup before the message hub is running).

func (*Ledger) SetSigner added in v0.35.0

func (l *Ledger) SetSigner(s Signer)

SetSigner installs the signing key (called once the host identity exists).

func (*Ledger) String

func (l *Ledger) String() string

String returns the blockchain as string

func (*Ledger) Syncronizer

func (l *Ledger) Syncronizer(ctx context.Context, t time.Duration)

Syncronizer starts a goroutine which writes the blockchain to the periodically

func (*Ledger) Update

func (l *Ledger) Update(f *Ledger, h *hub.Message, c chan *hub.Message) (err error)

Update the blockchain from a message

type LedgerOption added in v0.35.0

type LedgerOption func(*Ledger)

LedgerOption configures optional ledger behaviour.

func WithClock added in v0.35.0

func WithClock(f func() time.Time) LedgerOption

WithClock overrides the time source (tests).

func WithEnforcedOwnership added in v0.35.0

func WithEnforcedOwnership(r Registry, ttl time.Duration) LedgerOption

WithEnforcedOwnership is shorthand for WithOwnership(OwnershipEnforce, ...).

func WithOwnership added in v0.35.0

func WithOwnership(mode OwnershipMode, r Registry, ttl time.Duration) LedgerOption

WithOwnership switches Update to the per-key authorized merge using the given policy registry, liveness window and mode (observe = log-only, enforce = drop).

func WithSigner added in v0.35.0

func WithSigner(s Signer) LedgerOption

WithSigner makes the ledger sign every write with s. Without enforcement this only annotates entries (so a network can pre-sign before flipping enforcement on); with enforcement it is required for the local node to author entries.

func WithViolationLogger added in v0.35.0

func WithViolationLogger(f func(string, ...interface{})) LedgerOption

WithViolationLogger sets the sink for ownership-violation warnings.

type MemoryStore added in v0.3.0

type MemoryStore struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*MemoryStore) Add added in v0.3.0

func (m *MemoryStore) Add(b Block)

func (*MemoryStore) Last added in v0.3.0

func (m *MemoryStore) Last() Block

func (*MemoryStore) Len added in v0.3.0

func (m *MemoryStore) Len() int

type OwnershipMode added in v0.35.0

type OwnershipMode int

OwnershipMode selects how the ledger handles authenticated buckets.

const (
	// OwnershipOff: legacy height-wins replace; entries unsigned (default).
	OwnershipOff OwnershipMode = iota
	// OwnershipObserve: run the authorized merge but accept-and-warn on
	// violations instead of dropping (safe rollout / observation).
	OwnershipObserve
	// OwnershipEnforce: run the authorized merge and drop invalid writes.
	OwnershipEnforce
)

func ParseOwnershipMode added in v0.35.4

func ParseOwnershipMode(s string) (OwnershipMode, error)

ParseOwnershipMode maps a configuration string to an OwnershipMode. It is the single source of truth for the accepted spellings — the config layer, the CLI and the documentation all go through it, so the accepted set cannot drift between them.

An unrecognised value is an error rather than a fall-through to OwnershipOff. Falling through silently disabled ledger authentication for anyone who wrote --ownership=enabled or misspelled the mode: the node came up happily, logged nothing, and accepted forged writes from any token holder.

The empty string is deliberately valid and means off. It is the zero value of config.Ownership.Mode, i.e. the library default for embedders that never set the field; rejecting it would break them.

func (OwnershipMode) String added in v0.35.4

func (m OwnershipMode) String() string

String renders the mode the way an operator writes it on the command line.

type Registry added in v0.35.0

type Registry map[string]BucketPolicy

Registry maps bucket name -> policy. The zero BucketPolicy (returned for any unregistered bucket) is unowned/open and never expires, preserving legacy behaviour for buckets we have not opted in.

func DefaultRegistry added in v0.35.0

func DefaultRegistry(ttl time.Duration) Registry

DefaultRegistry is the built-in policy set. ttl is the liveness window (reused as the Absolute TTL for the heartbeat bucket itself).

func (Registry) Policy added in v0.35.0

func (r Registry) Policy(bucket string) BucketPolicy

Policy returns the policy for a bucket, or the open/legacy zero value.

type SignedData added in v0.35.0

type SignedData struct {
	Value     Data   // original JSON payload
	Owner     string // peer.ID (base58) of the author
	Version   uint64 // monotonic per (bucket,key); bumps only when Value changes
	UpdatedAt int64  // unix seconds, signed; drives TTL/lease renewal
	Deleted   bool   // signed tombstone marker
	Sig       []byte // signature over canonical(bucket,key,...)
}

SignedData is a ledger entry authenticated by its author. The Value is the original JSON payload (readers still call Value.Unmarshal); the remaining fields bind that value to the owning peer and a monotonic version so that only the owner can update it and an older value cannot be replayed over a newer one. See docs/content/en/docs/explanation/authenticated-ledger.md.

func (SignedData) MarshalJSON added in v0.35.0

func (d SignedData) MarshalJSON() ([]byte, error)

MarshalJSON keeps unsigned entries on the legacy wire format (a bare JSON value), so nodes that predate authentication can still decode them. Signed entries are encoded as the full object.

func (*SignedData) UnmarshalJSON added in v0.35.0

func (d *SignedData) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts either the legacy bare value or the full signed object.

type Signer added in v0.35.0

type Signer interface {
	Sign(msg []byte) ([]byte, error)
	ID() string // base58 peer.ID of the signer
}

Signer authenticates ledger writes. In production it wraps the libp2p host identity key; in tests it can wrap any generated key.

func NewSigner added in v0.35.0

func NewSigner(priv crypto.PrivKey) (Signer, error)

NewSigner builds a Signer from a libp2p private key, deriving the peer ID that owners are matched against.

type Store added in v0.3.0

type Store interface {
	Add(Block)
	Len() int
	Last() Block
}

Jump to

Keyboard shortcuts

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