Documentation
¶
Index ¶
- Constants
- type Database
- func (d *Database) ApplyEmbeddedDbSchema(version int64) error
- func (d *Database) CleanupOldBadNodes(maxAge time.Duration) (int64, error)
- func (d *Database) Close() error
- func (d *Database) CountAllNodes() (int, error)
- func (d *Database) CountNodes(layer NodeLayer) (int, error)
- func (d *Database) DeleteNode(tx *sqlx.Tx, layer NodeLayer, nodeID []byte) error
- func (d *Database) DeleteNodesBefore(tx *sqlx.Tx, layer NodeLayer, timestamp int64) (int64, error)
- func (d *Database) DeleteState(tx *sqlx.Tx, key string) error
- func (d *Database) GetAllNodes() ([]*Node, error)
- func (d *Database) GetBadNodesCount() (map[NodeLayer]int, error)
- func (d *Database) GetInactiveNodes(layer NodeLayer, n int) ([]*Node, error)
- func (d *Database) GetNode(layer NodeLayer, nodeID []byte) (*Node, error)
- func (d *Database) GetNodeStats() (map[NodeLayer]int, error)
- func (d *Database) GetNodes(layer NodeLayer) ([]*Node, error)
- func (d *Database) GetNodesByForkDigest(layer NodeLayer, forkDigest []byte, limit int) ([]*Node, error)
- func (d *Database) GetRandomNodes(layer NodeLayer, n int) ([]*Node, error)
- func (d *Database) GetState(key string) ([]byte, error)
- func (d *Database) GetStats() DatabaseStats
- func (d *Database) Init() error
- func (d *Database) IsBadNode(nodeID []byte, layer NodeLayer, recheckInterval time.Duration) (isBad bool, shouldRecheck bool, reason string, err error)
- func (d *Database) LoadLocalENR() ([]byte, error)
- func (d *Database) NodeExists(layer NodeLayer, nodeID []byte) (bool, uint64, error)
- func (d *Database) RemoveBadNode(nodeID []byte, layer NodeLayer) error
- func (d *Database) RunDBTransaction(handler func(tx *sqlx.Tx) error) error
- func (d *Database) SetState(tx *sqlx.Tx, key string, value []byte) error
- func (d *Database) StoreBadNode(nodeID []byte, layer NodeLayer, reason string) error
- func (d *Database) StoreLocalENR(enrBytes []byte) error
- func (d *Database) UpdateNodeENR(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, ip []byte, ipv6 []byte, port int, ...) error
- func (d *Database) UpdateNodeLastActive(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, timestamp int64) error
- func (d *Database) UpdateNodeLastSeen(tx *sqlx.Tx, layer NodeLayer, nodeID []byte, timestamp int64) error
- func (d *Database) UpsertNode(tx *sqlx.Tx, node *Node) error
- type DatabaseStats
- type Node
- type NodeLayer
- type SqliteDatabaseConfig
- type State
Constants ¶
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 ¶
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 ¶
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 ¶
Close closes the database writer connection. Should be called during application shutdown to ensure proper cleanup.
func (*Database) CountAllNodes ¶
CountAllNodes returns the total number of nodes (all layers).
func (*Database) CountNodes ¶
CountNodes returns the total number of nodes for a specific layer.
func (*Database) DeleteNode ¶
DeleteNode removes a node.
func (*Database) DeleteNodesBefore ¶
DeleteNodesBefore removes nodes with last_active older than the given timestamp for a specific layer.
func (*Database) DeleteState ¶
DeleteState removes a state entry by key.
func (*Database) GetAllNodes ¶
GetAllNodes retrieves all nodes (both EL and CL).
func (*Database) GetBadNodesCount ¶
GetBadNodesCount returns the total number of bad nodes per layer.
func (*Database) GetInactiveNodes ¶
GetInactiveNodes retrieves N nodes ordered by oldest last_active time for a specific layer.
func (*Database) GetNodeStats ¶
GetNodeStats returns statistics about nodes.
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 ¶
GetRandomNodes retrieves N random nodes for a specific layer.
func (*Database) GetStats ¶
func (d *Database) GetStats() DatabaseStats
GetStats returns database statistics from the SQL driver.
func (*Database) Init ¶
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 ¶
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 ¶
NodeExists checks if a node exists for a specific layer.
func (*Database) RemoveBadNode ¶
RemoveBadNode removes a node from the bad nodes list. This is called when a previously bad node passes admission checks.
func (*Database) RunDBTransaction ¶
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 ¶
SetState stores a state value by key. If tx is nil, creates and manages its own transaction automatically.
func (*Database) StoreBadNode ¶
StoreBadNode stores a node that failed admission checks. This prevents repeatedly requesting ENRs from nodes that won't pass filters.
func (*Database) StoreLocalENR ¶
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.
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 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.