blockchain

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsLive

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

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

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

type Data string

func (Data) Unmarshal

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

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

type DataString

type DataString string

type DiskStore

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

func NewDiskStore

func NewDiskStore(d *diskv.Diskv) *DiskStore

func (*DiskStore) Add

func (m *DiskStore) Add(b Block)

func (*DiskStore) Last

func (m *DiskStore) Last() Block

func (*DiskStore) Len

func (m *DiskStore) Len() int

type EnforcementMode

type EnforcementMode int

EnforcementMode defines the strictness of ownership enforcement. See docs/design/authenticated-ledger.md (section 6).

const (
	// EnforceStrict: reject all unauthorized mutations, no exceptions.
	EnforceStrict EnforcementMode = iota
	// EnforceWithGraceful: reject hijacks but allow some version transitions.
	EnforceWithGraceful
)

type EnforcementPolicy

type EnforcementPolicy struct {
	Mode            EnforcementMode
	MaxVersionDrift uint64        // how far a re-submitted older version can lag
	TTL             time.Duration // ownership TTL for policy enforcement
	BlockVersioning bool          // enforce block version constraints
	SignatureCheck  bool          // require valid signatures (should always be true)
}

EnforcementPolicy defines how strictly a merge must validate ownership and detect violations (hijacks, replays, tombstone forgery, etc.).

func DefaultEnforcementPolicy

func DefaultEnforcementPolicy(ttl time.Duration) EnforcementPolicy

DefaultEnforcementPolicy returns a production-ready enforcement policy for enforce mode rollout (M2).

func (EnforcementPolicy) CanMutate

func (ep EnforcementPolicy) CanMutate(
	bucket string,
	key string,
	old SignedData,
	new SignedData,
	pol BucketPolicy,
	health map[string]Data,
	now time.Time,
) error

CanMutate checks whether an entry mutation (old -> new) is allowed under enforcement policy. It detects:

  • hijacks: new owner != old owner (and old owner is still live)
  • replays: new version <= old version
  • signature forgery: invalid sig (delegated to Verify)
  • staleness: owner is dead and entry is not reclaimable

func (EnforcementPolicy) ShouldAcceptBlock

func (ep EnforcementPolicy) ShouldAcceptBlock(
	prevBlockVersion uint64,
	newBlockVersion uint64,
) error

ShouldAcceptBlock checks if a block's version and metadata meet enforcement constraints (version monotonicity, signature chain continuity, etc.).

type ExpiryKind

type ExpiryKind int

ExpiryKind selects how a bucket's entries are aged out. See docs/design/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

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

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

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

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

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

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

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

func (l *Ledger) DeleteBucket(b string)

DeleteBucket deletes a bucket from the ledger.

func (*Ledger) Exists

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

func (l *Ledger) Index() int

Index returns last known blockchain index

func (*Ledger) IsOwnerLive

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

func (l *Ledger) LastBlock() Block

LastBlock returns the last block in the blockchain

func (*Ledger) LivenessBuckets

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

LivenessBuckets returns the buckets whose entries expire with owner liveness.

func (*Ledger) OwnershipEnabled

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

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/design/authenticated-ledger.md (section 9).

func (*Ledger) SetOwnership

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

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

type LedgerOption func(*Ledger)

LedgerOption configures optional ledger behaviour.

func WithClock

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

WithClock overrides the time source (tests).

func WithEnforcedOwnership

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

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

func WithOwnership

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

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

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

WithViolationLogger sets the sink for ownership-violation warnings.

type MemoryStore

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

func (*MemoryStore) Add

func (m *MemoryStore) Add(b Block)

func (*MemoryStore) Last

func (m *MemoryStore) Last() Block

func (*MemoryStore) Len

func (m *MemoryStore) Len() int

type OwnershipMode

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
)

type Registry

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

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

func (r Registry) Policy(bucket string) BucketPolicy

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

type ReplayDetectionState

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

ReplayDetectionState tracks recent mutations to detect and reject replayed blocks or entries. Useful when a peer re-announces an old state.

func NewReplayDetectionState

func NewReplayDetectionState() *ReplayDetectionState

NewReplayDetectionState creates an empty replay detection state.

func (*ReplayDetectionState) MarkBlockSeen

func (r *ReplayDetectionState) MarkBlockSeen(blockVersion uint64) bool

MarkBlockSeen records that we have processed blockVersion. Returns true if we've seen it before (probable replay).

func (*ReplayDetectionState) MarkEntrySeen

func (r *ReplayDetectionState) MarkEntrySeen(bucket, key string, version uint64) bool

MarkEntrySeen records the version we accepted for bucket/key. Returns true if this version is older than a previously accepted version (replay).

type SignedData

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/design/authenticated-ledger.md.

func (SignedData) MarshalJSON

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

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

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

type Signer

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

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

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