store

package
v0.0.0-...-e617a74 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInsufficientBalance = errors.New("insufficient wallet balance")

ErrInsufficientBalance is returned when a wallet debit exceeds the available balance.

Functions

This section is empty.

Types

type ActiveRentalRow

type ActiveRentalRow struct {
	TransactionID string
	UserDID       string
	ProviderDID   string
	ResourceType  string
	ResourceID    string
	PaymentAmount int64
	CreatedAt     time.Time
}

ActiveRentalRow represents an active rental transaction.

type AggregateResources

type AggregateResources struct {
	TotalCPU       int
	UsedCPU        int
	TotalStorageGB int64
	UsedStorageGB  int64
	TotalMemoryGB  int64
	UsedMemoryGB   int64
}

AggregateResources holds summed resource counts.

type AlertRow

type AlertRow struct {
	AlertID       string
	TransactionID string
	UserDID       string
	ProviderDID   string
	CenterDID     string
	AlertType     string
	Severity      string
	Status        string
	CreatedAt     time.Time
}

AlertRow represents a row from the rating_alerts table.

type AutoAcceptRuleRow

type AutoAcceptRuleRow struct {
	RuleID           string
	RuleName         string
	Enabled          bool
	Priority         int
	MinUserScore     int
	MaxAmount        int64
	ResourceType     string
	AllowedHoursJSON string
	AllowedDaysJSON  string
	RequirePrepay    bool
	Action           string
	NotifyOperator   bool
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

AutoAcceptRuleRow stores a rental auto-accept rule.

type BlockchainBatchRow

type BlockchainBatchRow struct {
	Height     int64
	MerkleRoot []byte
	PrevHash   []byte
	Hash       []byte
	Timestamp  time.Time
	NodeDID    string
	Signature  []byte
	SourceFile string
	LeafCount  int
	TreeHeight int
}

BlockchainBatchRow represents a row in the blockchain_batches table.

type BlockedDIDRow

type BlockedDIDRow struct {
	DID        string
	Reason     string
	BlockedAt  time.Time
	BlockedBy  string
	ExpiresAt  *time.Time // nil = permanent
	Propagated bool
}

BlockedDIDRow describes a blocked DID entry.

type CenterRatingRow

type CenterRatingRow struct {
	RatingID  string
	DisputeID string
	CenterDID string
	RaterDID  string
	RaterRole string
	Score     int
	Feedback  string
	CreatedAt time.Time
	Signature []byte
}

CenterRatingRow is a single rating of a central SOHO's dispute handling.

type CenterScoreRow

type CenterScoreRow struct {
	CenterDID            string
	OverallScore         int
	InvestigationQuality float64
	Fairness             float64
	Timeliness           float64
	Communication        float64
	TotalDisputes        int
	TotalRatings         int
	AverageScore         float64
	ScoreHistoryJSON     string
	Active               bool
	SuspendedAt          *time.Time
	UpdatedAt            time.Time
}

CenterScoreRow is the aggregate reputation of a central SOHO node.

type CentralRevenueRow

type CentralRevenueRow struct {
	RevenueID      string
	TransactionID  string
	TenantID       string
	TotalAmount    int64
	CentralFee     int64
	ProducerPayout int64
	ProcessorFee   int64
	Currency       string
	SettledAt      *time.Time
	CreatedAt      time.Time
}

CentralRevenueRow tracks revenue splits for each transaction.

type ContentHashRow

type ContentHashRow struct {
	HashSHA256 string
	HashType   string // "sha256"|"photodna"|"md5"
	Reason     string // "csam"|"illegal_content"|"known_malware"
	Source     string // "ncmec"|"manual"|"clamav_heuristic"
	AddedAt    time.Time
	AddedByDID string
}

ContentHashRow describes a blocked content hash.

type DailyRevenueRow

type DailyRevenueRow struct {
	Date string // "YYYY-MM-DD"
	Sats int64
}

DailyRevenueRow is a per-day revenue aggregate used by the mobile dashboard.

type DisputeRow

type DisputeRow struct {
	DisputeID     string
	TransactionID string
	FilerDID      string
	Reason        string
	Priority      string
	Status        string
	Resolution    string
	ResolvedAt    *time.Time
	CreatedAt     time.Time
}

DisputeRow records a dispute for a transaction.

type FederationNodeRow

type FederationNodeRow struct {
	NodeDID              string
	Address              string
	Region               string
	TotalCPU             float64
	AvailableCPU         float64
	TotalMemoryMB        int64
	AvailableMemoryMB    int64
	TotalDiskGB          int64
	AvailableDiskGB      int64
	GPUModel             string
	GPUVRAMFree          int64   // MB
	GPUVRAMTotal         int64   // MB
	GPUComputeCapability string  // e.g. "8.6", "9.0"
	GPUTemperature       float32 // Celsius
	GPUPCIeBandwidth     int64   // MB/s
	PricePerCPUHour      int64
	ReputationScore      int
	UptimePercent        float64
	FailureRate          float64
	Status               string
	LastHeartbeat        time.Time
	PublicKey            string // base64-encoded Ed25519 public key (32 bytes)
}

FederationNodeRow represents a federation node in the database.

type GovernanceProposal

type GovernanceProposal struct {
	ProposalID   string
	ProposerDID  string
	Title        string
	Description  string
	ProposalType string
	State        string
	VotingStart  time.Time
	VotingEnd    time.Time
	QuorumPct    int
	PassPct      int
	YesVotes     int
	NoVotes      int
	AbstainVotes int
	CreatedAt    time.Time
	UpdatedAt    time.Time
	ExecutedAt   *time.Time
}

GovernanceProposal represents a governance proposal in the store.

type GovernanceVote

type GovernanceVote struct {
	VoteID     string
	ProposalID string
	VoterDID   string
	Choice     string
	Signature  string
	CreatedAt  time.Time
}

GovernanceVote represents a vote on a proposal in the store.

type InvestigationRow

type InvestigationRow struct {
	InvestigationID string
	DisputeID       string
	InvestigatorDID string
	Status          string
	Findings        string
	Recommendation  string
	Deadline        time.Time
	CreatedAt       time.Time
	ResolvedAt      *time.Time
}

InvestigationRow tracks a dispute investigation.

type LBTASScoreRow

type LBTASScoreRow struct {
	DID                   string
	OverallScore          int
	PaymentReliability    float64
	ExecutionQuality      float64
	Communication         float64
	ResourceUsage         float64
	TotalTransactions     int
	CompletedTransactions int
	DisputedTransactions  int
	ScoreHistoryJSON      string
	LastAnchorBlock       *int64
	LastAnchorHash        []byte
	UpdatedAt             time.Time
}

LBTASScoreRow is the store-layer representation of an LBTAS score.

type OrderRow

type OrderRow struct {
	OrderID       string
	RequesterDID  string
	OrderType     string // "workload" | "service"
	ResourceRefID string // workload_id or service_instance_id
	Description   string
	CPUCores      float64
	MemoryMB      int64
	DiskGB        int64
	DurationHours int
	EstimatedSats int64
	ChargedSats   int64
	Status        string // "pending"|"running"|"completed"|"cancelled"|"failed"
	ManifestJSON  string // JSON-encoded WorkloadManifest for audit trail (Item 5)
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

OrderRow represents a marketplace purchase (workload or managed service).

type OtherRatingRow

type OtherRatingRow struct {
	Score int
}

OtherRatingRow is a minimal view of a rating used for cross-checking.

type P2PBlockRow

type P2PBlockRow struct {
	Height    int64
	Data      []byte
	Hash      []byte
	PrevHash  []byte
	Timestamp time.Time
	Synced    bool
}

P2PBlockRow is a locally-produced blockchain block for offline operation.

type P2PPeerRow

type P2PPeerRow struct {
	PeerDID   string
	Address   string
	PublicKey []byte
	LastSeen  time.Time
	Score     int
	CPUCores  int
	StorageGB int64
	GPUModel  string
}

P2PPeerRow represents a known peer on the P2P mesh.

type P2PPendingSyncRow

type P2PPendingSyncRow struct {
	SyncID     string
	DataType   string
	Data       []byte
	CreatedAt  time.Time
	RetryCount int
}

P2PPendingSyncRow is an operation queued for sync to central.

type PayoutRow

type PayoutRow struct {
	PayoutID    string
	ProviderDID string
	AmountSats  int64
	Processor   string // "lightning", "stripe", "barter", etc.
	Status      string // "pending", "processing", "settled", "failed"
	ExternalID  string // processor-side transaction/payment ID
	ErrorMsg    string
	RequestedAt time.Time
	SettledAt   *time.Time
}

PayoutRow represents a payout request in the payouts table.

type PendingPaymentRow

type PendingPaymentRow struct {
	ID           string
	ChargeID     string
	UserDID      string
	ProviderDID  string
	Amount       int64
	Currency     string
	ResourceType string
	Status       string
	Attempts     int
	NextRetry    time.Time
	CreatedAt    time.Time
}

PendingPaymentRow is the store-layer representation of a pending payment.

type PlacementRow

type PlacementRow struct {
	PlacementID string
	WorkloadID  string
	ReplicaNum  int
	NodeDID     string
	NodeAddress string
	Status      string
	StartedAt   time.Time
}

PlacementRow represents a workload replica placement on a federation node.

type RatingAlertRow

type RatingAlertRow struct {
	AlertID        string
	TransactionID  string
	UserDID        string
	ProviderDID    string
	CenterDID      string
	AlertType      string
	Severity       string
	Evidence       []byte
	Notes          string
	Status         string
	Resolution     string
	InvestigatedBy string
	InvestigatedAt *time.Time
	ResolvedAt     *time.Time
	CreatedAt      time.Time
}

RatingAlertRow records a catastrophic-rating alert.

type RentalAuditRow

type RentalAuditRow struct {
	RequestID string
	UserDID   string
	RuleID    string // empty when no rule matched
	Action    string // "accept" | "reject" | "pending"
	Reason    string
	DecidedAt time.Time
}

RentalAuditRow is the store-layer representation of a rental engine decision.

type ResourceTransactionRow

type ResourceTransactionRow struct {
	TransactionID     string
	UserDID           string
	ProviderDID       string
	ResourceType      string
	ResourceID        string
	State             string
	PaymentAmount     int64
	PaymentCurrency   string
	PaymentEscrowed   bool
	PaymentProof      []byte
	ResultsReady      bool
	ResultsHash       []byte
	ResultsPath       string
	ResultsKey        []byte
	RatingDeadline    time.Time
	DisputeID         *string
	DisputeReason     string
	BlockchainBlock   *int64
	BlockchainHash    []byte
	UserSignature     []byte
	ProviderSignature []byte
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

ResourceTransactionRow is the store-layer representation of a resource transaction. This avoids circular imports between store and lbtas packages.

type RevenueRow

type RevenueRow struct {
	RevenueID      string
	TransactionID  string
	TenantID       string
	TotalAmount    int64
	CentralFee     int64
	ProducerPayout int64
	ProcessorFee   int64
	Currency       string
	Status         string
	ResourceType   string
	CreatedAt      time.Time
	SettledAt      *time.Time
}

RevenueRow represents a row from the central_revenue table.

type SLAContractRow

type SLAContractRow struct {
	ContractID      string
	OwnerDID        string
	Tier            string
	Status          string
	UptimeTarget    float64
	LatencyTargetMs int
	StartDate       time.Time
	EndDate         time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

SLAContractRow represents an SLA contract in the database.

type SLAViolationRow

type SLAViolationRow struct {
	ViolationID   string
	ContractID    string
	ViolationType string
	Severity      string
	MeasuredValue float64
	TargetValue   float64
	CreditAmount  int64
	DetectedAt    time.Time
	ResolvedAt    sql.NullTime
}

SLAViolationRow represents an SLA violation in the database.

type ServiceInstanceRow

type ServiceInstanceRow struct {
	InstanceID  string
	OwnerDID    string
	ServiceType string
	Name        string
	Plan        string
	Status      string
	NodeDID     string
	Endpoint    string
	Port        int
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

ServiceInstanceRow represents a managed service instance in the database.

type Store

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

Store wraps a SQLite database for SoHoLINK credential and user management.

func NewMemoryStore

func NewMemoryStore() (*Store, error)

NewMemoryStore creates an in-memory SQLite store for testing.

func NewStore

func NewStore(dbPath string) (*Store, error)

NewStore opens or creates a SQLite database at the given path and runs migrations.

func (*Store) ActiveUserCount

func (s *Store) ActiveUserCount(ctx context.Context) (int, error)

ActiveUserCount returns the number of non-revoked users.

func (*Store) AddContentHash

func (s *Store) AddContentHash(ctx context.Context, sha256hex, hashType, reason, source, byDID string) error

AddContentHash inserts a hash into the blocklist (idempotent on conflict).

func (*Store) AddUser

func (s *Store) AddUser(ctx context.Context, username, did string, publicKey []byte, role string) error

AddUser creates a new user in the database.

func (*Store) BlockDID

func (s *Store) BlockDID(ctx context.Context, did, reason, byDID string, expiresAt *time.Time) error

BlockDID adds a DID to the blocklist. If the DID is already present, the reason and expiry are updated.

func (*Store) CheckNonce

func (s *Store) CheckNonce(ctx context.Context, nonce string) (bool, error)

CheckNonce returns true if the nonce has already been seen (replay attempt).

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) CountActiveTenants

func (s *Store) CountActiveTenants(ctx context.Context, since time.Duration) (int, error)

CountActiveTenants returns tenants active within the given duration.

func (*Store) CountEligibleVoters

func (s *Store) CountEligibleVoters(ctx context.Context) (int, error)

CountEligibleVoters returns the number of nodes eligible to vote.

func (*Store) CountJobsByState

func (s *Store) CountJobsByState(ctx context.Context, state string) (int, error)

CountJobsByState returns the count of resource transactions in a given state.

func (*Store) CountPendingPayments

func (s *Store) CountPendingPayments(ctx context.Context) (int, error)

CountPendingPayments returns the number of pending payments.

func (*Store) CountTenants

func (s *Store) CountTenants(ctx context.Context) (int, error)

CountTenants returns the total number of tenants.

func (*Store) CreateAutoAcceptRule

func (s *Store) CreateAutoAcceptRule(ctx context.Context, r *AutoAcceptRuleRow) error

CreateAutoAcceptRule inserts a new auto-accept rule.

func (*Store) CreateBlockchainBatch

func (s *Store) CreateBlockchainBatch(ctx context.Context, row *BlockchainBatchRow) error

CreateBlockchainBatch inserts a new blockchain batch record.

func (*Store) CreateCenterRating

func (s *Store) CreateCenterRating(ctx context.Context, r *CenterRatingRow) error

CreateCenterRating inserts a rating of a central SOHO.

func (*Store) CreateCentralRevenue

func (s *Store) CreateCentralRevenue(ctx context.Context, r *CentralRevenueRow) error

CreateCentralRevenue records a revenue split.

func (*Store) CreateDispute

func (s *Store) CreateDispute(ctx context.Context, d *DisputeRow) error

CreateDispute inserts a new dispute.

func (*Store) CreateGovernanceProposal

func (s *Store) CreateGovernanceProposal(ctx context.Context, p *GovernanceProposal) error

CreateGovernanceProposal inserts a new governance proposal.

func (*Store) CreateGovernanceVote

func (s *Store) CreateGovernanceVote(ctx context.Context, v *GovernanceVote) error

CreateGovernanceVote records a vote on a proposal.

func (*Store) CreateInvestigation

func (s *Store) CreateInvestigation(ctx context.Context, inv *InvestigationRow) error

CreateInvestigation inserts a new investigation.

func (*Store) CreateOrder

func (s *Store) CreateOrder(ctx context.Context, o *OrderRow) error

CreateOrder inserts a new order record.

func (*Store) CreateP2PBlock

func (s *Store) CreateP2PBlock(ctx context.Context, b *P2PBlockRow) error

CreateP2PBlock stores a new block produced by P2P consensus.

func (*Store) CreatePayout

func (s *Store) CreatePayout(ctx context.Context, p *PayoutRow) error

CreatePayout inserts a new payout record. The caller must set PayoutID.

func (*Store) CreatePendingPayment

func (s *Store) CreatePendingPayment(ctx context.Context, p *PendingPaymentRow) error

CreatePendingPayment inserts a new pending payment for offline settlement.

func (*Store) CreatePlacement

func (s *Store) CreatePlacement(ctx context.Context, p *PlacementRow) error

CreatePlacement inserts a new placement record.

func (*Store) CreateRatingAlert

func (s *Store) CreateRatingAlert(ctx context.Context, a *RatingAlertRow) error

CreateRatingAlert inserts a new rating alert.

func (*Store) CreateSLAContract

func (s *Store) CreateSLAContract(ctx context.Context, c *SLAContractRow) error

CreateSLAContract inserts a new SLA contract.

func (*Store) CreateSLAViolation

func (s *Store) CreateSLAViolation(ctx context.Context, v *SLAViolationRow) error

CreateSLAViolation inserts a new SLA violation.

func (*Store) CreateServiceInstance

func (s *Store) CreateServiceInstance(ctx context.Context, si *ServiceInstanceRow) error

CreateServiceInstance inserts a new managed service instance.

func (*Store) CreateTenant

func (s *Store) CreateTenant(ctx context.Context, t *TenantRow) error

CreateTenant inserts a new tenant record.

func (*Store) CreateTransaction

func (s *Store) CreateTransaction(ctx context.Context, tx *ResourceTransactionRow) error

CreateTransaction inserts a new resource transaction record.

func (*Store) CreateWalletTopup

func (s *Store) CreateWalletTopup(ctx context.Context, t *WalletTopupRow) error

CreateWalletTopup inserts a new topup record. If IdempotencyKey is non-empty and a row with that key already exists, the insert is silently skipped (ON CONFLICT DO NOTHING semantics via the unique index added in migration v5).

func (*Store) CreateWorkload

func (s *Store) CreateWorkload(ctx context.Context, w *WorkloadRow) error

CreateWorkload inserts a new workload record.

func (*Store) CreditWallet

func (s *Store) CreditWallet(ctx context.Context, did string, sats int64) error

CreditWallet adds sats to the wallet balance, creating the row if needed.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying *sql.DB for advanced operations.

func (*Store) DebitWallet

func (s *Store) DebitWallet(ctx context.Context, did string, sats int64) error

DebitWallet atomically subtracts sats from the wallet balance. Returns ErrInsufficientBalance when the current balance is less than sats.

func (*Store) DeleteAutoAcceptRule

func (s *Store) DeleteAutoAcceptRule(ctx context.Context, ruleID string) error

DeleteAutoAcceptRule removes a rule.

func (*Store) DeletePendingSync

func (s *Store) DeletePendingSync(ctx context.Context, syncID string) error

DeletePendingSync removes a sync operation.

func (*Store) EnsureNodeSigningKeypair

func (s *Store) EnsureNodeSigningKeypair(ctx context.Context) (pubKeyB64 string, err error)

EnsureNodeSigningKeypair generates and stores an Ed25519 keypair for signing federation announcements if one does not already exist. Returns the public key as base64 on every call (new or existing).

func (*Store) EnsureOwnerKeypair

func (s *Store) EnsureOwnerKeypair(ctx context.Context) (privateKeyHex string, isNew bool, err error)

EnsureOwnerKeypair checks whether an owner public key has been stored. If not, it generates a fresh Ed25519 keypair, persists the public key in node_info, and returns the 32-byte seed as a 64-char hex string — the only time the private key material is ever available in plaintext.

If the keypair already exists the returned privateKeyHex is empty and isNew is false; the caller should not log anything in that case.

func (*Store) FederationBlocklistSnapshot

func (s *Store) FederationBlocklistSnapshot(ctx context.Context) ([]BlockedDIDRow, error)

FederationBlocklistSnapshot returns all permanent (non-expiring) blocked DIDs for federation pull by peer nodes.

func (*Store) GetActiveRentals

func (s *Store) GetActiveRentals(ctx context.Context) ([]ActiveRentalRow, error)

GetActiveRentals returns all resource transactions in an active state.

func (*Store) GetAggregateResources

func (s *Store) GetAggregateResources(ctx context.Context) (*AggregateResources, error)

GetAggregateResources sums resource counts across all active tenants.

func (*Store) GetAutoAcceptRules

func (s *Store) GetAutoAcceptRules(ctx context.Context) ([]AutoAcceptRuleRow, error)

GetAutoAcceptRules returns all auto-accept rules ordered by priority.

func (*Store) GetBlockchainBatchByHash

func (s *Store) GetBlockchainBatchByHash(ctx context.Context, hash []byte) (*BlockchainBatchRow, error)

GetBlockchainBatchByHash returns a blockchain batch by its hash.

func (*Store) GetBlockchainBatchByHeight

func (s *Store) GetBlockchainBatchByHeight(ctx context.Context, height int64) (*BlockchainBatchRow, error)

GetBlockchainBatchByHeight returns a blockchain batch by height.

func (*Store) GetCenterScore

func (s *Store) GetCenterScore(ctx context.Context, centerDID string) (*CenterScoreRow, error)

GetCenterScore retrieves the aggregate score for a center.

func (*Store) GetDailyRevenueLast30Days

func (s *Store) GetDailyRevenueLast30Days(ctx context.Context) ([]DailyRevenueRow, error)

GetDailyRevenueLast30Days returns per-day revenue totals for the past 30 days, ordered oldest-first. Days with no revenue are omitted.

func (*Store) GetDispute

func (s *Store) GetDispute(ctx context.Context, disputeID string) (*DisputeRow, error)

GetDispute retrieves a dispute by ID.

func (*Store) GetFederationNode

func (s *Store) GetFederationNode(ctx context.Context, nodeDID string) (*FederationNodeRow, error)

GetFederationNode returns a single node by DID, or nil if not found.

func (*Store) GetGovernanceProposal

func (s *Store) GetGovernanceProposal(ctx context.Context, proposalID string) (*GovernanceProposal, error)

GetGovernanceProposal retrieves a proposal by ID.

func (*Store) GetGovernanceVote

func (s *Store) GetGovernanceVote(ctx context.Context, proposalID, voterDID string) (*GovernanceVote, error)

GetGovernanceVote retrieves a specific vote by proposal and voter.

func (*Store) GetLBTASScore

func (s *Store) GetLBTASScore(ctx context.Context, did string) (*LBTASScoreRow, error)

GetLBTASScore retrieves the LBTAS score for a DID.

func (*Store) GetLatestBlockHash

func (s *Store) GetLatestBlockHash(ctx context.Context) ([]byte, error)

GetLatestBlockHash returns the hash of the most recent P2P block.

func (*Store) GetLatestBlockHeight

func (s *Store) GetLatestBlockHeight(ctx context.Context) (int64, error)

GetLatestBlockHeight returns the height of the most recent P2P block.

func (*Store) GetLatestBlockchainBatch

func (s *Store) GetLatestBlockchainBatch(ctx context.Context) (*BlockchainBatchRow, error)

GetLatestBlockchainBatch returns the most recent blockchain batch.

func (*Store) GetNodeInfo

func (s *Store) GetNodeInfo(ctx context.Context, key string) (string, error)

GetNodeInfo retrieves a value from the node_info table.

func (*Store) GetNodeSigningKey

func (s *Store) GetNodeSigningKey(ctx context.Context) (privSeedHex, pubKeyB64 string, err error)

GetNodeSigningKey returns the node's federation signing keypair. privSeed is a 64-char hex string (32-byte Ed25519 seed). pubKeyB64 is a base64-encoded 32-byte Ed25519 public key. Returns ("", "", nil) if the keypair has not been generated yet.

func (*Store) GetOnlineNodes

func (s *Store) GetOnlineNodes(ctx context.Context) ([]FederationNodeRow, error)

GetOnlineNodes returns all federation nodes with status "online".

func (*Store) GetOrder

func (s *Store) GetOrder(ctx context.Context, orderID string) (*OrderRow, error)

GetOrder retrieves a single order by ID.

func (*Store) GetOtherRating

func (s *Store) GetOtherRating(ctx context.Context, transactionID string, currentRaterRole string) (*OtherRatingRow, error)

GetOtherRating retrieves the rating from the opposite role in a transaction.

func (*Store) GetOwnerPublicKey

func (s *Store) GetOwnerPublicKey(ctx context.Context) (pubB64 string, ok bool, err error)

GetOwnerPublicKey returns the base64-encoded Ed25519 public key stored in node_info. Returns ("", false, nil) if not yet initialised.

func (*Store) GetP2PPeers

func (s *Store) GetP2PPeers(ctx context.Context) ([]P2PPeerRow, error)

GetP2PPeers returns all known peers.

func (*Store) GetPaymentByChargeID

func (s *Store) GetPaymentByChargeID(ctx context.Context, chargeID string) (*PendingPaymentRow, error)

GetPaymentByChargeID retrieves a pending payment by its charge_id.

func (*Store) GetPendingPayments

func (s *Store) GetPendingPayments(ctx context.Context, limit int) ([]PendingPaymentRow, error)

GetPendingPayments retrieves pending payments for offline settlement.

func (*Store) GetPendingPayout

func (s *Store) GetPendingPayout(ctx context.Context) (int64, error)

GetPendingPayout returns total unsettled revenue.

func (*Store) GetPendingSync

func (s *Store) GetPendingSync(ctx context.Context) ([]P2PPendingSyncRow, error)

GetPendingSync returns all pending sync operations.

func (*Store) GetPlacementsForWorkload

func (s *Store) GetPlacementsForWorkload(ctx context.Context, workloadID string) ([]PlacementRow, error)

GetPlacementsForWorkload returns all placements for a workload.

func (*Store) GetRatingAlerts

func (s *Store) GetRatingAlerts(ctx context.Context, status string) ([]RatingAlertRow, error)

GetRatingAlerts returns rating alerts filtered by status.

func (*Store) GetRecentAlerts

func (s *Store) GetRecentAlerts(ctx context.Context, limit int) ([]AlertRow, error)

GetRecentAlerts returns the most recent rating alerts.

func (*Store) GetRecentRevenue

func (s *Store) GetRecentRevenue(ctx context.Context, limit int) ([]RevenueRow, error)

GetRecentRevenue returns the most recent revenue entries.

func (*Store) GetRevenueByType

func (s *Store) GetRevenueByType(ctx context.Context, resourceType string) (int64, error)

GetRevenueByType returns total revenue for a specific resource type.

func (*Store) GetRevenueSince

func (s *Store) GetRevenueSince(ctx context.Context, since time.Time) (int64, error)

GetRevenueSince returns total revenue since the given time.

func (*Store) GetSLAContract

func (s *Store) GetSLAContract(ctx context.Context, contractID string) (*SLAContractRow, error)

GetSLAContract retrieves an SLA contract by ID.

func (*Store) GetSLAViolations

func (s *Store) GetSLAViolations(ctx context.Context, contractID string) ([]SLAViolationRow, error)

GetSLAViolations returns violations for a contract.

func (*Store) GetServiceInstances

func (s *Store) GetServiceInstances(ctx context.Context, ownerDID string) ([]ServiceInstanceRow, error)

GetServiceInstances returns all service instances for an owner.

func (*Store) GetTenant

func (s *Store) GetTenant(ctx context.Context, tenantID string) (*TenantRow, error)

GetTenant retrieves a tenant by ID.

func (*Store) GetTenantsByCenter

func (s *Store) GetTenantsByCenter(ctx context.Context, centerDID string) ([]TenantRow, error)

GetTenantsByCenter returns tenants connected to a specific center.

func (*Store) GetTimedOutTransactions

func (s *Store) GetTimedOutTransactions(ctx context.Context) ([]ResourceTransactionRow, error)

GetTimedOutTransactions returns transactions past their rating deadline.

func (*Store) GetTotalRevenue

func (s *Store) GetTotalRevenue(ctx context.Context) (int64, error)

GetTotalRevenue returns total revenue across all time.

func (*Store) GetTransaction

func (s *Store) GetTransaction(ctx context.Context, transactionID string) (*ResourceTransactionRow, error)

GetTransaction retrieves a resource transaction by ID.

func (*Store) GetUnsyncedBlocks

func (s *Store) GetUnsyncedBlocks(ctx context.Context) ([]P2PBlockRow, error)

GetUnsyncedBlocks returns all blocks not yet synced to central.

func (*Store) GetUserByDID

func (s *Store) GetUserByDID(ctx context.Context, did string) (*User, error)

GetUserByDID retrieves a user by their DID.

func (*Store) GetUserByUsername

func (s *Store) GetUserByUsername(ctx context.Context, username string) (*User, error)

GetUserByUsername retrieves a user by their username.

func (*Store) GetWalletBalance

func (s *Store) GetWalletBalance(ctx context.Context, did string) (int64, error)

GetWalletBalance returns the current sats balance for the given DID. Returns 0 if no wallet record exists yet (new requester).

func (*Store) GetWalletTopup

func (s *Store) GetWalletTopup(ctx context.Context, topupID string) (*WalletTopupRow, error)

GetWalletTopup retrieves a single topup record by ID.

func (*Store) GetWalletTopupByIdempotencyKey

func (s *Store) GetWalletTopupByIdempotencyKey(ctx context.Context, key string) (*WalletTopupRow, error)

GetWalletTopupByIdempotencyKey looks up an existing topup by idempotency key. Returns nil, nil when no matching row is found.

func (*Store) GetWorkload

func (s *Store) GetWorkload(ctx context.Context, workloadID string) (*WorkloadRow, error)

GetWorkload retrieves a workload by ID.

func (*Store) InitGovernanceSchema

func (s *Store) InitGovernanceSchema(ctx context.Context) error

InitGovernanceSchema creates the governance tables if they don't exist.

func (*Store) InsertRentalAudit

func (s *Store) InsertRentalAudit(ctx context.Context, row *RentalAuditRow) error

InsertRentalAudit records a rental engine auto-accept/reject decision.

func (*Store) IsDIDBlocked

func (s *Store) IsDIDBlocked(ctx context.Context, did string) (bool, string, error)

IsDIDBlocked returns (blocked, reason, error). Expired entries are treated as not blocked (caller is responsible for periodic cleanup).

func (*Store) IsHashBlocked

func (s *Store) IsHashBlocked(ctx context.Context, sha256hex string) (bool, string, error)

IsHashBlocked returns (blocked, reason, error).

func (*Store) IsRevoked

func (s *Store) IsRevoked(ctx context.Context, did string) (bool, error)

IsRevoked checks if a user DID is in the revocation list.

func (*Store) ListActiveFederationNodes

func (s *Store) ListActiveFederationNodes(ctx context.Context) ([]FederationNodeRow, error)

ListActiveFederationNodes returns all nodes that sent a heartbeat within the last 2 minutes (considered online), ordered by reputation score.

func (*Store) ListBlockedDIDs

func (s *Store) ListBlockedDIDs(ctx context.Context, limit int) ([]BlockedDIDRow, error)

ListBlockedDIDs returns up to limit blocked DIDs, newest first.

func (*Store) ListContentHashes

func (s *Store) ListContentHashes(ctx context.Context, limit int) ([]ContentHashRow, error)

ListContentHashes returns up to limit blocked hashes, newest first.

func (*Store) ListGovernanceProposals

func (s *Store) ListGovernanceProposals(ctx context.Context, state string, limit, offset int) ([]*GovernanceProposal, error)

ListGovernanceProposals returns proposals filtered by state.

func (*Store) ListGovernanceVotes

func (s *Store) ListGovernanceVotes(ctx context.Context, proposalID string) ([]*GovernanceVote, error)

ListGovernanceVotes returns all votes for a proposal.

func (*Store) ListOrders

func (s *Store) ListOrders(ctx context.Context, requesterDID string, limit int) ([]OrderRow, error)

ListOrders returns orders for a requester (most recent first).

func (*Store) ListPaymentsFiltered

func (s *Store) ListPaymentsFiltered(ctx context.Context, userDID, providerDID, status string, limit, offset int) ([]PendingPaymentRow, error)

ListPaymentsFiltered retrieves payments matching optional filter criteria.

func (*Store) ListPayouts

func (s *Store) ListPayouts(ctx context.Context, providerDID string, limit int) ([]PayoutRow, error)

ListPayouts returns recent payout records for a provider, newest first. Pass limit ≤ 0 for a default of 50.

func (*Store) ListTenants

func (s *Store) ListTenants(ctx context.Context) ([]TenantRow, error)

ListTenants returns all tenants.

func (*Store) ListUsers

func (s *Store) ListUsers(ctx context.Context) ([]User, error)

ListUsers returns all users in the database.

func (*Store) ListWalletTopups

func (s *Store) ListWalletTopups(ctx context.Context, did string, limit int) ([]WalletTopupRow, error)

ListWalletTopups returns topup history for a DID (most recent first).

func (*Store) MarkBlockSynced

func (s *Store) MarkBlockSynced(ctx context.Context, height int64) error

MarkBlockSynced marks a block as synced to central.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping verifies the database connection is alive. Used by health checks and readiness probes.

func (*Store) PruneExpiredNonces

func (s *Store) PruneExpiredNonces(ctx context.Context, maxAge time.Duration) (int64, error)

PruneExpiredNonces removes nonces older than maxAge.

func (*Store) RecordCentralRevenue

func (s *Store) RecordCentralRevenue(ctx context.Context, r *RevenueRow) error

RecordCentralRevenue inserts a RevenueRow into the central_revenue table. It ensures the referenced tenant exists (creating a stub if absent) then maps RevenueRow fields to CentralRevenueRow and delegates to CreateCentralRevenue.

func (*Store) RecordNonce

func (s *Store) RecordNonce(ctx context.Context, nonce string) error

RecordNonce records a nonce as seen to prevent replay attacks.

func (*Store) ResolveDispute

func (s *Store) ResolveDispute(ctx context.Context, disputeID, resolution string, resolvedAt time.Time) error

ResolveDispute marks a dispute as resolved.

func (*Store) RevocationCount

func (s *Store) RevocationCount(ctx context.Context) (int, error)

RevocationCount returns the total number of revocations.

func (*Store) RevokeDeviceToken

func (s *Store) RevokeDeviceToken(ctx context.Context, tokenRawHex string) error

RevokeDeviceToken marks a token as revoked by its raw hex value.

func (*Store) RevokeUser

func (s *Store) RevokeUser(ctx context.Context, username, reason string) error

RevokeUser marks a user as revoked by updating their revoked_at field and inserting a revocation record.

func (*Store) SetFederationNodeOffline

func (s *Store) SetFederationNodeOffline(ctx context.Context, nodeDID string) error

SetFederationNodeOffline marks a node as offline (called on clean deregister or when a node misses too many heartbeats).

func (*Store) SetNodeInfo

func (s *Store) SetNodeInfo(ctx context.Context, key, value string) error

SetNodeInfo stores a key-value pair in the node_info table.

func (*Store) SetTransactionDispute

func (s *Store) SetTransactionDispute(ctx context.Context, transactionID, disputeID, reason string) error

SetTransactionDispute sets the dispute reference on a resource transaction.

func (*Store) StoreDeviceToken

func (s *Store) StoreDeviceToken(ctx context.Context, tokenRawHex, deviceName string) error

StoreDeviceToken persists a new device session. tokenRawHex is the 64-char hex representation of a random 32-byte token; only its SHA-256 hash is stored so a database leak cannot replay tokens.

func (*Store) ToggleAutoAcceptRule

func (s *Store) ToggleAutoAcceptRule(ctx context.Context, ruleID string, enabled bool) error

ToggleAutoAcceptRule enables or disables a rule.

func (*Store) UnblockDID

func (s *Store) UnblockDID(ctx context.Context, did string) error

UnblockDID removes a DID from the blocklist.

func (*Store) UpdateFederationHeartbeat

func (s *Store) UpdateFederationHeartbeat(
	ctx context.Context,
	nodeDID string,
	availCPU float64,
	availMemMB, availDiskGB int64,
) error

UpdateFederationHeartbeat refreshes a node's available resources and last_heartbeat timestamp. Called on every provider heartbeat.

func (*Store) UpdateGovernanceProposal

func (s *Store) UpdateGovernanceProposal(ctx context.Context, p *GovernanceProposal) error

UpdateGovernanceProposal updates an existing governance proposal.

func (*Store) UpdateOrderStatus

func (s *Store) UpdateOrderStatus(ctx context.Context, orderID, status string) error

UpdateOrderStatus changes the status of an order and sets updated_at.

func (*Store) UpdatePaymentStatus

func (s *Store) UpdatePaymentStatus(ctx context.Context, paymentID string, status string) error

UpdatePaymentStatus updates the status of a pending payment.

func (*Store) UpdatePayoutStatus

func (s *Store) UpdatePayoutStatus(ctx context.Context, payoutID, status, externalID, errMsg string) error

UpdatePayoutStatus advances the status of a payout and optionally records the processor-side ID and any error message.

func (*Store) UpdatePlacementStatus

func (s *Store) UpdatePlacementStatus(ctx context.Context, placementID, status string) error

UpdatePlacementStatus updates the status of a placement.

func (*Store) UpdateServiceInstanceStatus

func (s *Store) UpdateServiceInstanceStatus(ctx context.Context, instanceID, status string) error

UpdateServiceInstanceStatus updates the status of a service instance.

func (*Store) UpdateTenantStatus

func (s *Store) UpdateTenantStatus(ctx context.Context, tenantID, status string) error

UpdateTenantStatus changes a tenant's status.

func (*Store) UpdateTopupStatus

func (s *Store) UpdateTopupStatus(ctx context.Context, topupID, status string, confirmedAt *time.Time) error

UpdateTopupStatus changes the status (and optionally sets confirmed_at) of a topup.

func (*Store) UpdateTransaction

func (s *Store) UpdateTransaction(ctx context.Context, tx *ResourceTransactionRow) error

UpdateTransaction updates a resource transaction record.

func (*Store) UpdateTransactionState

func (s *Store) UpdateTransactionState(ctx context.Context, transactionID string, state string) error

UpdateTransactionState updates only the state of a transaction.

func (*Store) UpdateWorkloadStatus

func (s *Store) UpdateWorkloadStatus(ctx context.Context, workloadID, status string) error

UpdateWorkloadStatus updates the status of a workload.

func (*Store) UpsertCenterScore

func (s *Store) UpsertCenterScore(ctx context.Context, cs *CenterScoreRow) error

UpsertCenterScore inserts or updates a center's aggregate score.

func (*Store) UpsertFederationNode

func (s *Store) UpsertFederationNode(ctx context.Context, n *FederationNodeRow) error

UpsertFederationNode inserts or updates a federation node.

func (*Store) UpsertLBTASScore

func (s *Store) UpsertLBTASScore(ctx context.Context, score *LBTASScoreRow) error

UpsertLBTASScore inserts or updates an LBTAS score.

func (*Store) UpsertP2PPeer

func (s *Store) UpsertP2PPeer(ctx context.Context, p *P2PPeerRow) error

UpsertP2PPeer inserts or updates a peer record.

func (*Store) UserCount

func (s *Store) UserCount(ctx context.Context) (int, error)

UserCount returns the total number of users.

func (*Store) ValidateDeviceToken

func (s *Store) ValidateDeviceToken(ctx context.Context, tokenRawHex string) (bool, error)

ValidateDeviceToken checks whether a raw token is valid (exists and not revoked). It updates last_seen on every successful validation.

type TenantRow

type TenantRow struct {
	TenantID   string
	Name       string
	CenterDID  string
	Status     string // "active", "suspended"
	CPUCores   int
	StorageGB  int64
	MemoryGB   int64
	GPUModel   string
	LastActive time.Time
	CreatedAt  time.Time
}

TenantRow represents a registered thin-client tenant.

type User

type User struct {
	ID        int64
	Username  string
	DID       string
	PublicKey []byte
	Role      string
	CreatedAt string
	RevokedAt sql.NullString
}

User represents a registered user in the system.

type WalletBalanceRow

type WalletBalanceRow struct {
	DID         string
	BalanceSats int64
	UpdatedAt   time.Time
}

WalletBalanceRow holds a requester's prepaid sats balance.

type WalletTopupRow

type WalletTopupRow struct {
	TopupID        string
	DID            string
	AmountSats     int64
	Processor      string // "lightning" | "stripe"
	Invoice        string // bolt11 invoice or Stripe payment_intent ID
	Status         string // "awaiting_payment" | "confirmed" | "expired" | "failed"
	IdempotencyKey string // optional client-provided key for deduplication
	CreatedAt      time.Time
	ConfirmedAt    *time.Time
}

WalletTopupRow represents a single topup transaction.

type WorkloadRow

type WorkloadRow struct {
	WorkloadID   string
	OwnerDID     string
	Name         string
	WorkloadType string
	Replicas     int
	Status       string
	Image        string
	CPUCores     float64
	MemoryMB     int64
	DiskGB       int64
	GPURequired  bool
	GPUModel     string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

WorkloadRow represents a workload in the database.

Jump to

Keyboard shortcuts

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