sqlite

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: BSD-3-Clause Imports: 13 Imported by: 0

README

Hanzo SQLite

Distributed SQLite with sqlcipher encryption, CRDT replication, and Raft consensus.

Drop-in replacement for modernc.org/sqlite in Hanzo Base with:

  • Encryption at rest: sqlcipher (AES-256-CBC page-level encryption)
  • Distributed replication: Raft consensus for multi-node (LiteFS-style)
  • CRDT sync: conflict-free replicated data types for eventual consistency
  • Multi-party sharding: each party runs a node, threshold for writes

Architecture

┌─────────────────────────────────────────────┐
│              Hanzo SQLite Node               │
├─────────────────────────────────────────────┤
│  Application (Hanzo Base)                    │
│    ↕ database/sql driver                    │
│  SQLCipher Engine (AES-256-CBC pages)       │
│    ↕ WAL intercept                          │
│  Replication Layer                           │
│    ├─ Raft (strong consistency, writes)     │
│    └─ CRDT (eventual consistency, reads)    │
│    ↕ ZAP transport                          │
│  Peer Discovery (mDNS or explicit)          │
└─────────────────────────────────────────────┘

Modes

Mode Consistency Use Case
single Local only Development, single-instance prod
raft Strong (leader writes) Multi-node KMS, MPC state
crdt Eventual (all write) Edge sync, offline-first apps
threshold t-of-n attest writes MPC wallet shards, multi-party

Multi-Party Threshold Mode

Multiple parties each run a node. Write operations require t-of-n attestations:

Party A (node-0) ──┐
Party B (node-1) ──┼── 2-of-3 attest ──→ write committed
Party C (node-2) ──┘

Each party signs their attestation locally. Simple 2/3 threshold for writes. Reads are local (each node has a full replica).

Encryption

SQLCipher provides transparent page-level encryption:

  • Algorithm: AES-256-CBC
  • KDF: PBKDF2-HMAC-SHA512 (256K iterations)
  • HMAC: SHA-512 per-page integrity
  • Key: derived from passphrase or provided as raw 256-bit key
db, err := sqlite.Open("data.db", sqlite.WithKey("my-passphrase"))
// or
db, err := sqlite.Open("data.db", sqlite.WithRawKey(keyBytes))

Usage

import "github.com/hanzoai/sqlite"

// Single node (encrypted)
db, err := sqlite.Open("data.db", sqlite.WithKey("passphrase"))

// Raft cluster (3 nodes, encrypted)
db, err := sqlite.Open("data.db",
    sqlite.WithKey("passphrase"),
    sqlite.WithRaft("node-0", ":4001", []string{
        "node-1:4001",
        "node-2:4001",
    }),
)

// Threshold mode (2-of-3 for writes)
db, err := sqlite.Open("data.db",
    sqlite.WithKey("passphrase"),
    sqlite.WithThreshold(2, 3, mySigningKey),
    sqlite.WithPeers([]string{
        "node-1:4001",
        "node-2:4001",
    }),
)

Integration with Hanzo Base

Replace modernc.org/sqlite in Base's go.mod:

replace modernc.org/sqlite => github.com/hanzoai/sqlite v0.1.0

Base gets encryption at rest + distribution for free. No code changes needed.

Per-Principal CEK

Each org or user gets a unique 256-bit content encryption key (CEK) derived via HKDF-SHA256:

// DeriveKey(masterKey, principalType, principalID) → 32-byte CEK
db, err := sqlite.Open("data.db",
    sqlite.WithPrincipalKey(masterKey, PrincipalOrg, "my-org"),
)
  • DeriveKey(masterKey, principalType, principalID) uses HKDF-SHA256
  • Master key stored in KMS (ENCRYPTION_MASTER_KEY env)
  • Used by IAM, KMS, ATS, BD, TA for per-tenant isolation
  • Destroying the master key renders all derived CEKs irrecoverable

License

Apache-2.0

Documentation

Overview

Per-principal CEK derivation via HKDF.

Each org/user gets a unique 256-bit Content Encryption Key derived from:

CEK = HKDF-SHA256(master_key, principal_id)

This ensures:

  • Different orgs can't read each other's databases
  • Master key compromise + principal ID needed to derive any CEK
  • Key rotation: re-derive all CEKs from new master, re-encrypt databases

Package sqlite provides a distributed, encrypted SQLite driver for Hanzo.

Built on go-sqlite3 with sqlcipher for page-level AES-256-CBC encryption. Supports single-node, Raft consensus, CRDT sync, and threshold attestation modes.

Drop-in replacement for modernc.org/sqlite in Hanzo Base.

Threshold write attestation for multi-party SQLite.

Each party runs a node with a full replica. Write operations require t-of-n parties to sign the write before it's committed. Reads are local.

Use case: MPC wallet shard storage, DEX trade approvals, multi-sig transaction authorization in trading platforms.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrThresholdNotMet = errors.New("sqlite: threshold attestations not met")
	ErrDuplicateSigner = errors.New("sqlite: duplicate signer")
	ErrInvalidSig      = errors.New("sqlite: invalid attestation signature")
	ErrSessionExpired  = errors.New("sqlite: attestation session expired")
)

Functions

func DeriveKey

func DeriveKey(masterKey []byte, principalType PrincipalType, principalID string) ([]byte, error)

DeriveKey derives a 256-bit CEK for a principal from a master key using HKDF-SHA256.

masterKey: 32-byte master encryption key (from KMS)
principalType: "org" or "user"
principalID: unique identifier (org slug, user ID)

The info string is "{principalType}:{principalID}" ensuring domain separation.

Types

type Config

type Config struct {
	// Encryption
	RawKey []byte // raw 256-bit key (skips KDF)

	// Replication
	Mode   Mode
	NodeID string
	Listen string   // bind address for replication
	Peers  []string // peer addresses

	// Threshold mode
	Threshold  int                // t value (signatures required)
	Parties    int                // n value (total parties)
	SigningKey ed25519.PrivateKey // this node's signing key
	// contains filtered or unexported fields
}

Config for opening a database.

type DB

type DB struct {
	*sql.DB
	// contains filtered or unexported fields
}

DB wraps sql.DB with replication and encryption.

func Open

func Open(path string, opts ...Option) (*DB, error)

Open opens an encrypted, optionally distributed SQLite database.

type Mode

type Mode string

Mode determines the replication strategy.

const (
	ModeSingle    Mode = "single"    // Local only
	ModeRaft      Mode = "raft"      // Strong consistency (leader writes)
	ModeCRDT      Mode = "crdt"      // Eventual consistency (all write)
	ModeThreshold Mode = "threshold" // t-of-n attestation for writes
)

type Option

type Option func(*Config)

Option configures a database.

func WithCRDT

func WithCRDT(nodeID, listen string, peers []string) Option

WithCRDT enables CRDT eventual consistency replication.

func WithKey

func WithKey(passphrase string) Option

WithKey derives a raw 256-bit key from a passphrase via SHA-256 and configures sqlcipher to use it directly (skipping KDF).

func WithPeers

func WithPeers(peers []string) Option

WithPeers sets replication peers.

func WithPrincipalKey

func WithPrincipalKey(masterKey []byte, principalType PrincipalType, principalID string) Option

WithPrincipalKey derives a CEK and configures the database to use it. This is the primary API for per-org and per-user encryption.

func WithRaft

func WithRaft(nodeID, listen string, peers []string) Option

WithRaft enables Raft consensus replication.

func WithRawKey

func WithRawKey(key []byte) Option

WithRawKey sets a raw 256-bit encryption key (skips KDF).

func WithThreshold

func WithThreshold(t, n int, signingKey ed25519.PrivateKey) Option

WithThreshold enables multi-party threshold attestation for writes.

type PrincipalType

type PrincipalType string

PrincipalType identifies the type of principal for CEK derivation.

const (
	PrincipalOrg  PrincipalType = "org"
	PrincipalUser PrincipalType = "user"
)

type ThresholdManager

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

ThresholdManager coordinates multi-party write attestation.

func NewThresholdManager

func NewThresholdManager(threshold, parties int, nodeID string, signingKey ed25519.PrivateKey) *ThresholdManager

NewThresholdManager creates a threshold write coordinator.

func (*ThresholdManager) Attest

func (tm *ThresholdManager) Attest(proposalID [32]byte, nodeID string, signature []byte) error

Attest adds a peer's attestation to a pending proposal.

func (*ThresholdManager) CleanExpired

func (tm *ThresholdManager) CleanExpired() int

CleanExpired removes expired proposals.

func (*ThresholdManager) Pending

func (tm *ThresholdManager) Pending() int

Pending returns the number of pending proposals.

func (*ThresholdManager) Propose

func (tm *ThresholdManager) Propose(sql string, params []any) ([32]byte, error)

Propose creates a new write proposal. Returns the proposal ID.

func (*ThresholdManager) RegisterPeer

func (tm *ThresholdManager) RegisterPeer(nodeID string, pubKey ed25519.PublicKey)

RegisterPeer adds a peer's public key for attestation verification.

func (*ThresholdManager) SetCommitFunc

func (tm *ThresholdManager) SetCommitFunc(fn func(string, []any) error)

SetCommitFunc sets the function called when threshold is met.

type WriteProposal

type WriteProposal struct {
	ID        [32]byte // SHA-256 of the SQL + params
	SQL       string
	Params    []any
	Proposer  string // node ID of proposer
	CreatedAt time.Time
	ExpiresAt time.Time
	// contains filtered or unexported fields
}

WriteProposal is a proposed write that needs t-of-n attestations.

Jump to

Keyboard shortcuts

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