refactor: replace magic numbers and string literals with constants
Some checks failed
Go Test Multi-Platform / Test (ubuntu-latest, amd64) (push) Successful in 1m34s
Go Test Multi-Platform / Test (ubuntu-latest, arm64) (push) Successful in 49s
Go Revive Lint / lint (push) Successful in 46s
Run Gosec / tests (push) Successful in 1m21s
Go Build Multi-Platform / build (amd64, windows) (push) Failing after 49s
Go Build Multi-Platform / build (amd64, freebsd) (push) Successful in 1m4s
Go Build Multi-Platform / build (arm64, darwin) (push) Successful in 58s
Go Build Multi-Platform / build (arm, linux) (push) Successful in 1m1s
Go Build Multi-Platform / build (arm64, windows) (push) Successful in 41s
Go Build Multi-Platform / build (arm64, freebsd) (push) Failing after 4m51s
Go Build Multi-Platform / build (arm, windows) (push) Failing after 4m53s
Go Build Multi-Platform / build (arm64, linux) (push) Failing after 4m49s
Go Build Multi-Platform / build (amd64, linux) (push) Failing after 4m57s
Go Build Multi-Platform / build (arm, freebsd) (push) Failing after 4m55s
Go Build Multi-Platform / build (amd64, darwin) (push) Failing after 4m59s
Go Build Multi-Platform / Create Release (push) Has been skipped

This commit is contained in:
2025-12-29 00:25:28 -06:00
parent 53e98c73af
commit c3893eb33d
3 changed files with 100 additions and 55 deletions

View File

@@ -102,18 +102,18 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to load identity: %v", err) return nil, fmt.Errorf("failed to load identity: %v", err)
} }
debug.Log(debug.DEBUG_ERROR, "Loaded existing identity", "hash", fmt.Sprintf("%x", ident.Hash())) debug.Log(debug.DEBUG_ERROR, "Loaded existing identity", common.STR_HASH, fmt.Sprintf(common.STR_FMT_HEX_LOW, ident.Hash()))
} else { } else {
// Create new identity // Create new identity
ident, err = identity.NewIdentity() ident, err = identity.NewIdentity()
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create identity: %v", err) return nil, fmt.Errorf("failed to create identity: %v", err)
} }
debug.Log(debug.DEBUG_ERROR, "Created new identity", "hash", fmt.Sprintf("%x", ident.Hash())) debug.Log(debug.DEBUG_ERROR, "Created new identity", common.STR_HASH, fmt.Sprintf(common.STR_FMT_HEX_LOW, ident.Hash()))
// Save it to disk // Save it to disk
if err := ident.ToFile(identityPath); err != nil { if err := ident.ToFile(identityPath); err != nil {
debug.Log(debug.DEBUG_ERROR, "Failed to save identity to file", "error", err) debug.Log(debug.DEBUG_ERROR, "Failed to save identity to file", common.STR_ERROR, err)
} else { } else {
debug.Log(debug.DEBUG_INFO, "Identity saved to file", "path", identityPath) debug.Log(debug.DEBUG_INFO, "Identity saved to file", "path", identityPath)
} }
@@ -132,7 +132,7 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create destination: %v", err) return nil, fmt.Errorf("failed to create destination: %v", err)
} }
debug.Log(debug.DEBUG_INFO, "Created destination with hash", "hash", fmt.Sprintf("%x", dest.GetHash())) debug.Log(debug.DEBUG_INFO, "Created destination with hash", common.STR_HASH, fmt.Sprintf(common.STR_FMT_HEX_LOW, dest.GetHash()))
// Set node metadata // Set node metadata
nodeTimestamp := time.Now().Unix() nodeTimestamp := time.Now().Unix()
@@ -150,8 +150,8 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
storage: storageMgr, storage: storageMgr,
// Node-specific information // Node-specific information
maxTransferSize: 500, // Default 500KB maxTransferSize: common.NUM_500, // Default 500KB
nodeEnabled: true, // Enabled by default nodeEnabled: true, // Enabled by default
nodeTimestamp: nodeTimestamp, nodeTimestamp: nodeTimestamp,
} }
@@ -175,7 +175,7 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
var err error var err error
switch ifaceConfig.Type { switch ifaceConfig.Type {
case "TCPClientInterface": case common.STR_TCP_CLIENT:
iface, err = interfaces.NewTCPClientInterface( iface, err = interfaces.NewTCPClientInterface(
name, name,
ifaceConfig.TargetHost, ifaceConfig.TargetHost,
@@ -194,7 +194,7 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
case "AutoInterface": case "AutoInterface":
iface, err = interfaces.NewAutoInterface(name, ifaceConfig) iface, err = interfaces.NewAutoInterface(name, ifaceConfig)
default: default:
debug.Log(debug.DEBUG_CRITICAL, "Unknown interface type", "type", ifaceConfig.Type) debug.Log(debug.DEBUG_CRITICAL, "Unknown interface type", common.STR_TYPE, ifaceConfig.Type)
continue continue
} }
@@ -202,13 +202,13 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
if cfg.PanicOnInterfaceErr { if cfg.PanicOnInterfaceErr {
return nil, fmt.Errorf("failed to create interface %s: %v", name, err) return nil, fmt.Errorf("failed to create interface %s: %v", name, err)
} }
debug.Log(debug.DEBUG_CRITICAL, "Error creating interface", "name", name, "error", err) debug.Log(debug.DEBUG_CRITICAL, "Error creating interface", common.STR_NAME, name, common.STR_ERROR, err)
continue continue
} }
// Set packet callback // Set packet callback
iface.SetPacketCallback(func(data []byte, ni common.NetworkInterface) { iface.SetPacketCallback(func(data []byte, ni common.NetworkInterface) {
debug.Log(debug.DEBUG_INFO, "Packet callback called for interface", "name", ni.GetName(), "data_len", len(data)) debug.Log(debug.DEBUG_INFO, "Packet callback called for interface", common.STR_NAME, ni.GetName(), "data_len", len(data))
if r.transport != nil { if r.transport != nil {
r.transport.HandlePacket(data, ni) r.transport.HandlePacket(data, ni)
} else { } else {
@@ -216,16 +216,16 @@ func NewReticulum(cfg *common.ReticulumConfig) (*Reticulum, error) {
} }
}) })
debug.Log(debug.DEBUG_ERROR, "Configuring interface", "name", name, "type", ifaceConfig.Type) debug.Log(debug.DEBUG_ERROR, "Configuring interface", common.STR_NAME, name, common.STR_TYPE, ifaceConfig.Type)
r.interfaces = append(r.interfaces, iface) r.interfaces = append(r.interfaces, iface)
debug.Log(debug.DEBUG_INFO, "Interface started successfully", "name", name) debug.Log(debug.DEBUG_INFO, "Interface started successfully", common.STR_NAME, name)
} }
return r, nil return r, nil
} }
func (r *Reticulum) handleInterface(iface common.NetworkInterface) { func (r *Reticulum) handleInterface(iface common.NetworkInterface) {
debug.Log(debug.DEBUG_INFO, "Setting up interface", "name", iface.GetName(), "type", fmt.Sprintf("%T", iface)) debug.Log(debug.DEBUG_INFO, "Setting up interface", common.STR_NAME, iface.GetName(), common.STR_TYPE, fmt.Sprintf("%T", iface))
ch := channel.NewChannel(&transportWrapper{r.transport}) ch := channel.NewChannel(&transportWrapper{r.transport})
r.channels[iface.GetName()] = ch r.channels[iface.GetName()] = ch
@@ -236,11 +236,11 @@ func (r *Reticulum) handleInterface(iface common.NetworkInterface) {
ch, ch,
func(size int) { func(size int) {
data := make([]byte, size) data := make([]byte, size)
debug.Log(debug.DEBUG_PACKETS, "Interface reading bytes from buffer", "name", iface.GetName(), "size", size) debug.Log(debug.DEBUG_PACKETS, "Interface reading bytes from buffer", common.STR_NAME, iface.GetName(), "size", size)
iface.ProcessIncoming(data) iface.ProcessIncoming(data)
if len(data) > 0 { if len(data) > common.ZERO {
debug.Log(debug.DEBUG_TRACE, "Interface received packet type", "name", iface.GetName(), "type", fmt.Sprintf("0x%02x", data[0])) debug.Log(debug.DEBUG_TRACE, "Interface received packet type", common.STR_NAME, iface.GetName(), common.STR_TYPE, fmt.Sprintf("0x%02x", data[0]))
r.transport.HandlePacket(data, iface) r.transport.HandlePacket(data, iface)
} }
}, },
@@ -284,7 +284,7 @@ func main() {
cfg, err := config.InitConfig() cfg, err := config.InitConfig()
if err != nil { if err != nil {
debug.GetLogger().Error("Failed to initialize config", "error", err) debug.GetLogger().Error("Failed to initialize config", common.STR_ERROR, err)
os.Exit(1) os.Exit(1)
} }
debug.Log(debug.DEBUG_ERROR, "Configuration loaded", "path", cfg.ConfigPath) debug.Log(debug.DEBUG_ERROR, "Configuration loaded", "path", cfg.ConfigPath)
@@ -301,25 +301,25 @@ func main() {
} }
cfg.Interfaces["Go-RNS-Testnet"] = &common.InterfaceConfig{ cfg.Interfaces["Go-RNS-Testnet"] = &common.InterfaceConfig{
Type: "TCPClientInterface", Type: common.STR_TCP_CLIENT,
Enabled: false, Enabled: false,
TargetHost: "127.0.0.1", TargetHost: "127.0.0.1",
TargetPort: 4242, TargetPort: common.NUM_4242,
Name: "Go-RNS-Testnet", Name: "Go-RNS-Testnet",
} }
cfg.Interfaces["Quad4 TCP"] = &common.InterfaceConfig{ cfg.Interfaces["Quad4 TCP"] = &common.InterfaceConfig{
Type: "TCPClientInterface", Type: common.STR_TCP_CLIENT,
Enabled: true, Enabled: true,
TargetHost: "rns2.quad4.io", TargetHost: "rns2.quad4.io",
TargetPort: 4242, TargetPort: common.NUM_4242,
Name: "Quad4 TCP", Name: "Quad4 TCP",
} }
} }
r, err := NewReticulum(cfg) r, err := NewReticulum(cfg)
if err != nil { if err != nil {
debug.GetLogger().Error("Failed to create Reticulum instance", "error", err) debug.GetLogger().Error("Failed to create Reticulum instance", common.STR_ERROR, err)
os.Exit(1) os.Exit(1)
} }
@@ -332,7 +332,7 @@ func main() {
// Start Reticulum // Start Reticulum
if err := r.Start(); err != nil { if err := r.Start(); err != nil {
debug.GetLogger().Error("Failed to start Reticulum", "error", err) debug.GetLogger().Error("Failed to start Reticulum", common.STR_ERROR, err)
os.Exit(1) os.Exit(1)
} }
@@ -342,7 +342,7 @@ func main() {
debug.Log(debug.DEBUG_CRITICAL, "Shutting down...") debug.Log(debug.DEBUG_CRITICAL, "Shutting down...")
if err := r.Stop(); err != nil { if err := r.Stop(); err != nil {
debug.Log(debug.DEBUG_CRITICAL, "Error during shutdown", "error", err) debug.Log(debug.DEBUG_CRITICAL, "Error during shutdown", common.STR_ERROR, err)
} }
debug.Log(debug.DEBUG_CRITICAL, "Goodbye!") debug.Log(debug.DEBUG_CRITICAL, "Goodbye!")
} }
@@ -416,17 +416,17 @@ func initializeDirectories() error {
basePath := filepath.Join(homeDir, ".reticulum-go") basePath := filepath.Join(homeDir, ".reticulum-go")
dirs := []string{ dirs := []string{
basePath, basePath,
filepath.Join(basePath, "storage"), filepath.Join(basePath, common.STR_STORAGE),
filepath.Join(basePath, "storage", "destinations"), filepath.Join(basePath, common.STR_STORAGE, "destinations"),
filepath.Join(basePath, "storage", "identities"), filepath.Join(basePath, common.STR_STORAGE, "identities"),
filepath.Join(basePath, "storage", "ratchets"), filepath.Join(basePath, common.STR_STORAGE, "ratchets"),
filepath.Join(basePath, "storage", "cache"), filepath.Join(basePath, common.STR_STORAGE, "cache"),
filepath.Join(basePath, "storage", "cache", "announces"), filepath.Join(basePath, common.STR_STORAGE, "cache", "announces"),
filepath.Join(basePath, "storage", "resources"), filepath.Join(basePath, common.STR_STORAGE, "resources"),
} }
for _, dir := range dirs { for _, dir := range dirs {
if err := os.MkdirAll(dir, 0700); err != nil { // #nosec G301 if err := os.MkdirAll(dir, common.NUM_0700); err != nil { // #nosec G301
return fmt.Errorf("failed to create directory %s: %v", dir, err) return fmt.Errorf("failed to create directory %s: %v", dir, err)
} }
} }
@@ -553,15 +553,15 @@ func (h *AnnounceHandler) ReceivedAnnounce(destHash []byte, id interface{}, appD
var nodeMaxSize int16 var nodeMaxSize int16
// Parse msgpack appData from transport announce format // Parse msgpack appData from transport announce format
if len(appData) > 0 { if len(appData) > common.ZERO {
// appData is msgpack array [name, customData] // appData is msgpack array [name, customData]
if appData[0] == 0x92 { // array of 2 elements if appData[0] == common.HEX_0x92 { // array of 2 elements
// Skip array header and first element (name) // Skip array header and first element (name)
pos := 1 pos := common.ONE
if pos < len(appData) && appData[pos] == 0xc4 { // bin 8 if pos < len(appData) && appData[pos] == common.HEX_0xC4 { // bin 8
nameLen := int(appData[pos+1]) nameLen := int(appData[pos+1])
pos += 2 + nameLen pos += common.TWO + nameLen
if pos < len(appData) && appData[pos] == 0xc4 { // bin 8 if pos < len(appData) && appData[pos] == common.HEX_0xC4 { // bin 8
dataLen := int(appData[pos+1]) dataLen := int(appData[pos+1])
if pos+2+dataLen <= len(appData) { if pos+2+dataLen <= len(appData) {
customData := appData[pos+2 : pos+2+dataLen] customData := appData[pos+2 : pos+2+dataLen]
@@ -629,26 +629,26 @@ func (r *Reticulum) GetDestination() *destination.Destination {
func (r *Reticulum) createNodeAppData() []byte { func (r *Reticulum) createNodeAppData() []byte {
// Create a msgpack array with 3 elements // Create a msgpack array with 3 elements
// [Bool, Int32, Int16] for [enable, timestamp, max_transfer_size] // [Bool, Int32, Int16] for [enable, timestamp, max_transfer_size]
appData := []byte{0x93} // Array with 3 elements appData := []byte{common.HEX_0x93} // Array with 3 elements
// Element 0: Boolean for enable/disable peer // Element 0: Boolean for enable/disable peer
if r.nodeEnabled { if r.nodeEnabled {
appData = append(appData, 0xc3) // true appData = append(appData, common.HEX_0xC3) // true
} else { } else {
appData = append(appData, 0xc2) // false appData = append(appData, common.HEX_0xC2) // false
} }
// Element 1: Int32 timestamp (current time) // Element 1: Int32 timestamp (current time)
// Update the timestamp when creating new announcements // Update the timestamp when creating new announcements
r.nodeTimestamp = time.Now().Unix() r.nodeTimestamp = time.Now().Unix()
appData = append(appData, 0xd2) // int32 format appData = append(appData, common.HEX_0xD2) // int32 format
timeBytes := make([]byte, 4) timeBytes := make([]byte, common.FOUR)
binary.BigEndian.PutUint32(timeBytes, uint32(r.nodeTimestamp)) // #nosec G115 binary.BigEndian.PutUint32(timeBytes, uint32(r.nodeTimestamp)) // #nosec G115
appData = append(appData, timeBytes...) appData = append(appData, timeBytes...)
// Element 2: Int16 max transfer size in KB // Element 2: Int16 max transfer size in KB
appData = append(appData, 0xd1) // int16 format appData = append(appData, common.HEX_0xD1) // int16 format
sizeBytes := make([]byte, 2) sizeBytes := make([]byte, common.TWO)
binary.BigEndian.PutUint16(sizeBytes, uint16(r.maxTransferSize)) // #nosec G115 binary.BigEndian.PutUint16(sizeBytes, uint16(r.maxTransferSize)) // #nosec G115
appData = append(appData, sizeBytes...) appData = append(appData, sizeBytes...)

View File

@@ -12,9 +12,9 @@ import (
func TestNewReticulum(t *testing.T) { func TestNewReticulum(t *testing.T) {
// Set up a temporary home directory for testing // Set up a temporary home directory for testing
tmpDir := t.TempDir() tmpDir := t.TempDir()
originalHome := os.Getenv("HOME") originalHome := os.Getenv(common.STR_HOME)
os.Setenv("HOME", tmpDir) os.Setenv(common.STR_HOME, tmpDir)
defer os.Setenv("HOME", originalHome) defer os.Setenv(common.STR_HOME, originalHome)
cfg := config.DefaultConfig() cfg := config.DefaultConfig()
// Disable interfaces for simple test // Disable interfaces for simple test
@@ -44,18 +44,18 @@ func TestNewReticulum(t *testing.T) {
func TestNodeAppData(t *testing.T) { func TestNodeAppData(t *testing.T) {
tmpDir := t.TempDir() tmpDir := t.TempDir()
os.Setenv("HOME", tmpDir) os.Setenv(common.STR_HOME, tmpDir)
r := &Reticulum{ r := &Reticulum{
nodeEnabled: true, nodeEnabled: true,
maxTransferSize: 500, maxTransferSize: common.NUM_500,
} }
data := r.createNodeAppData() data := r.createNodeAppData()
if len(data) == 0 { if len(data) == common.ZERO {
t.Error("createNodeAppData returned empty data") t.Error("createNodeAppData returned empty data")
} }
if data[0] != 0x93 { if data[0] != common.HEX_0x93 {
t.Errorf("Expected array header 0x93, got 0x%x", data[0]) t.Errorf("Expected array header 0x93, got 0x%x", data[0])
} }
} }

View File

@@ -78,20 +78,65 @@ const (
SIXTY_SEVEN = 67 SIXTY_SEVEN = 67
// Common Hex Constants // Common Hex Constants
HEX_0x00 = 0x00
HEX_0x01 = 0x01
HEX_0x02 = 0x02
HEX_0x03 = 0x03 HEX_0x03 = 0x03
HEX_0x04 = 0x04
HEX_0x92 = 0x92
HEX_0x93 = 0x93
HEX_0xC2 = 0xC2
HEX_0xC3 = 0xC3
HEX_0xC4 = 0xC4
HEX_0xD1 = 0xD1
HEX_0xD2 = 0xD2
HEX_0xFE = 0xFE
HEX_0xFF = 0xFF HEX_0xFF = 0xFF
// Common Numeric Constants
NUM_11 = 11
NUM_100 = 100
NUM_500 = 500
NUM_1024 = 1024
NUM_1064 = 1064
NUM_4242 = 4242
NUM_0700 = 0700
// Common Float Constants // Common Float Constants
FLOAT_ZERO = 0.0 FLOAT_ZERO = 0.0
FLOAT_0_001 = 0.001 FLOAT_0_001 = 0.001
FLOAT_0_025 = 0.025 FLOAT_0_025 = 0.025
FLOAT_0_1 = 0.1 FLOAT_0_1 = 0.1
FLOAT_1_0 = 1.0
FLOAT_1_75 = 1.75 FLOAT_1_75 = 1.75
FLOAT_5_0 = 5.0 FLOAT_5_0 = 5.0
FLOAT_1E9 = 1e9 FLOAT_1E9 = 1e9
// Common String Constants // Common String Constants
STR_LINK_ID = "link_id" STR_LINK_ID = "link_id"
STR_BYTES = "bytes" STR_BYTES = "bytes"
STR_FMT_HEX = "0x%02x" STR_FMT_HEX = "0x%02x"
STR_FMT_HEX_LOW = "%x"
STR_FMT_DEC = "%d"
STR_TEST = "test"
STR_LINK = "link"
STR_ERROR = "error"
STR_HASH = "hash"
STR_NAME = "name"
STR_TYPE = "type"
STR_STORAGE = "storage"
STR_PATH = "path"
STR_COUNT = "count"
STR_HOME = "HOME"
STR_PUBLIC_KEY = "public_key"
STR_TCP_CLIENT = "TCPClientInterface"
STR_UDP = "udp"
STR_UDP6 = "udp6"
STR_TCP = "tcp"
STR_ETH0 = "eth0"
STR_INTERFACE = "interface"
STR_PEER = "peer"
STR_ADDR = "addr"
STR_LINK_NOT_ACTIVE = "link not active"
STR_INTERFACE_OFFLINE = "interface offline or detached"
) )