db

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const BadNodeRecheckInterval = 7 * 24 * time.Hour // 7 days

BadNodeRecheckInterval is the default time to wait before rechecking a bad node.

Variables

This section is empty.

Functions

This section is empty.

Types

type Database

type Database struct {
	ReaderDb *sqlx.DB // Database connection for read operations
	// contains filtered or unexported fields
}

Database manages SQLite database connections with WAL mode and connection pooling. It provides both reader and writer connections with mutex protection for write operations and embedded schema migration support using goose.

func NewDatabase

func NewDatabase(config *SqliteDatabaseConfig, logger logrus.FieldLogger) *Database

NewDatabase creates a new Database instance with the specified configuration and logger. The database connections are not initialized until Init() is called.

func (*Database) ApplyEmbeddedDbSchema

func (d *Database) ApplyEmbeddedDbSchema(version int64) error

ApplyEmbeddedDbSchema applies database schema migrations using embedded SQL files. Supports different migration strategies: -2 (all), -1 (one up), or specific version. Uses goose migration library with allowMissing option for flexible schema management.

func (*Database) CleanupOldBadNodes

func (d *Database) CleanupOldBadNodes(maxAge time.Duration) (int64, error)

CleanupOldBadNodes removes bad node entries older than the given age. This should be called periodically (e.g., once per day) to prevent unbounded growth.

func (*Database) Close

func (d *Database) Close() error

Close closes the database writer connection. Should be called during application shutdown to ensure proper cleanup.

func (*Database) CountAllNodes

func (d *Database) CountAllNodes() (int, error)

CountAllNodes returns the total number of nodes (all layers).

func (*Database) CountNodes

func (d *Database) CountNodes(layer NodeLayer) (int, error)

CountNodes returns the total number of nodes for a specific layer.

func (*Database) DeleteNode

func (d *Database) DeleteNode(tx *sqlx.Tx, layer NodeLayer, nodeID []byte) error

DeleteNode removes a node.

func (*Database) DeleteNodesBefore

func (d *Database) DeleteNodesBefore(tx *sqlx.Tx, layer NodeLayer, timestamp int64) (int64, error)

DeleteNodesBefore removes nodes with last_active older than the given timestamp for a specific layer.

func (*Database) DeleteState

func (d *Database) DeleteState(tx *sqlx.Tx, key string) error

DeleteState removes a state entry by key.

func (*Database) GetAllNodes

func (d *Database) GetAllNodes() ([]*Node, error)

GetAllNodes retrieves all nodes (both EL and CL).

func (*Database) GetBadNodesCount

func (d *Database) GetBadNodesCount() (map[NodeLayer]int, error)

GetBadNodesCount returns the total number of bad nodes per layer.

func (*Database) GetInactiveNodes

func (d *Database) GetInactiveNodes(layer NodeLayer, n int) ([]*Node, error)

GetInactiveNodes retrieves N nodes ordered by oldest last_active time for a specific layer.

func (*Database) GetNode

func (d *Database) GetNode(layer NodeLayer, nodeID []byte) (*Node, error)

GetNode retrieves a single node by ID and layer.

func (*Database) GetNodeStats

func (d *Database) GetNodeStats() (map[NodeLayer]int, error)

GetNodeStats returns statistics about nodes.

func (*Database) GetNodes

func (d *Database) GetNodes(layer NodeLayer) ([]*Node, error)

GetNodes retrieves all nodes for a specific layer.

func (*Database) GetNodesByForkDigest

func (d *Database) GetNodesByForkDigest(layer NodeLayer, forkDigest []byte, limit int) ([]*Node, error)

GetNodesByForkDigest retrieves nodes filtered by fork digest for a specific layer.

func (*Database) GetRandomNodes

func (d *Database) GetRandomNodes(layer NodeLayer, n int) ([]*Node, error)

GetRandomNodes retrieves N random nodes for a specific layer.

func (*Database) GetState

func (d *Database) GetState(key string) ([]byte, error)

GetState retrieves a state value by key.

func (*Database) GetStats

func (d *Database) GetStats() DatabaseStats

GetStats returns database statistics from the SQL driver.

func (*Database) Init

func (d *Database) Init() error

Init initializes the database connections with WAL mode and connection pooling. Sets default connection limits (50 max open, 10 max idle) if not specified. Enables WAL mode for better concurrent access and configures connection timeouts.

func (*Database) IsBadNode

func (d *Database) IsBadNode(nodeID []byte, layer NodeLayer, recheckInterval time.Duration) (isBad bool, shouldRecheck bool, reason string, err error)

IsBadNode checks if a node is marked as bad and whether it should be rechecked. Returns:

  • isBad: true if the node is in the bad nodes list
  • shouldRecheck: true if enough time has passed since rejection (> recheckInterval)
  • reason: the reason the node was rejected

func (*Database) LoadLocalENR

func (d *Database) LoadLocalENR() ([]byte, error)

LoadLocalENR loads the stored local ENR from the database.

Returns the ENR bytes if found, or an error if not found or on failure. The local ENR is stored in the state table with key "local_enr".

func (*Database) NodeExists

func (d *Database) NodeExists(layer NodeLayer, nodeID []byte) (bool, uint64, error)

NodeExists checks if a node exists for a specific layer.

func (*Database) RemoveBadNode

func (d *Database) RemoveBadNode(nodeID []byte, layer NodeLayer) error

RemoveBadNode removes a node from the bad nodes list. This is called when a previously bad node passes admission checks.

func (*Database) RunDBTransaction

func (d *Database) RunDBTransaction(handler func(tx *sqlx.Tx) error) error

RunDBTransaction executes a function within a database transaction with automatic rollback. The transaction is protected by a mutex to ensure sequential write operations. Automatically rolls back on error and commits on success.

func (*Database) SetState

func (d *Database) SetState(tx *sqlx.Tx, key string, value []byte) error

SetState stores a state value by key. If tx is nil, creates and manages its own transaction automatically.

func (*Database) StoreBadNode

func (d *Database) StoreBadNode(nodeID []byte, layer NodeLayer, reason string) error

StoreBadNode stores a node that failed admission checks. This prevents repeatedly requesting ENRs from nodes that won't pass filters.

func (*Database) StoreLocalENR

func (d *Database) StoreLocalENR(enrBytes []byte) error

StoreLocalENR stores the local ENR to the database.

This should be called whenever the local ENR is created or updated. The ENR is stored in the state table for persistence across restarts.

func (*Database) UpdateNodeENR

func (d *Database) UpdateNodeENR(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, ip []byte, ipv6 []byte, port int, seq uint64, forkDigest []byte, enr []byte, hasV4 bool, hasV5 bool) error

UpdateNodeENR updates only ENR-related fields.

func (*Database) UpdateNodeLastActive

func (d *Database) UpdateNodeLastActive(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, timestamp int64) error

UpdateNodeLastActive updates the last_active timestamp.

func (*Database) UpdateNodeLastSeen

func (d *Database) UpdateNodeLastSeen(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, timestamp int64) error

UpdateNodeLastSeen updates the last_seen timestamp.

func (*Database) UpsertNode

func (d *Database) UpsertNode(tx *sqlx.Tx, node *Node) error

UpsertNode inserts or updates a node.

type DatabaseStats

type DatabaseStats struct {
	TotalQueries      int64         // Total queries from SQL driver stats
	Transactions      int64         // Total transactions executed
	OpenConnections   int           // Current number of open connections
	InUse             int           // Connections currently in use
	Idle              int           // Connections currently idle
	WaitCount         int64         // Total number of times waited for a connection
	WaitDuration      time.Duration // Total time blocked waiting for connections
	MaxIdleClosed     int64         // Total connections closed due to SetMaxIdleConns
	MaxLifetimeClosed int64         // Total connections closed due to SetConnMaxLifetime
}

DatabaseStats contains statistics about database operations.

type Node

type Node struct {
	NodeID       []byte        `db:"nodeid"`        // 32-byte node ID
	Layer        string        `db:"layer"`         // 'el' or 'cl'
	IP           []byte        `db:"ip"`            // IPv4 address (4 bytes)
	IPv6         []byte        `db:"ipv6"`          // IPv6 address (16 bytes)
	Port         int           `db:"port"`          // UDP port
	Seq          uint64        `db:"seq"`           // ENR sequence number
	ForkDigest   []byte        `db:"fork_digest"`   // Fork digest from 'eth' or 'eth2'
	FirstSeen    int64         `db:"first_seen"`    // Unix timestamp
	LastSeen     sql.NullInt64 `db:"last_seen"`     // Unix timestamp (nullable)
	LastActive   sql.NullInt64 `db:"last_active"`   // Unix timestamp (nullable)
	ENR          []byte        `db:"enr"`           // RLP-encoded ENR
	HasV4        bool          `db:"has_v4"`        // Supports discv4 (EL only)
	HasV5        bool          `db:"has_v5"`        // Supports discv5
	SuccessCount int           `db:"success_count"` // Successful pings
	FailureCount int           `db:"failure_count"` // Failed pings
	AvgRTT       int           `db:"avg_rtt"`       // Average RTT in milliseconds
}

Node represents a node stored in the database (EL or CL).

type NodeLayer

type NodeLayer string

NodeLayer represents whether a node belongs to EL or CL.

const (
	LayerEL NodeLayer = "el"
	LayerCL NodeLayer = "cl"
)

type SqliteDatabaseConfig

type SqliteDatabaseConfig struct {
	File         string `yaml:"file"`         // Database file path
	MaxOpenConns int    `yaml:"maxOpenConns"` // Maximum number of open connections to the database
	MaxIdleConns int    `yaml:"maxIdleConns"` // Maximum number of idle connections in the pool
}

SqliteDatabaseConfig defines the configuration for SQLite database connections. It specifies the database file path and connection pool limits for managing concurrent database access efficiently.

type State

type State struct {
	Key   string `db:"key"`   // State key identifier
	Value []byte `db:"value"` // State value (raw bytes)
}

State represents a key-value pair for storing runtime state.

Jump to

Keyboard shortcuts

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