write a golang middleware for go-fiber that uses blockchain technology to identify…
- User
write a golang middleware for go-fiber that uses blockchain technology to identify navigation trails
Assistant
Here's a Go middleware for Fiber that uses blockchain technology to track navigation trails:
package blockchain_trail import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "sync" "time" "github.com/gofiber/fiber/v2" ) // Block represents a single block in the blockchain type Block struct { Index int `json:"index"` Timestamp time.Time `json:"timestamp"` Trail Trail `json:"trail"` PreviousHash string `json:"previous_hash"` Hash string `json:"hash"` Nonce int `json:"nonce"` } // Trail represents a navigation trail entry type Trail struct { SessionID string `json:"session_id"` UserID string `json:"user_id"` Path string `json:"path"` Method string `json:"method"` IP string `json:"ip"` UserAgent string `json:"user_agent"` StatusCode int `json:"status_code"` Duration time.Duration `json:"duration"` Headers map[string]string `json:"headers"` } // Blockchain manages the trail blockchain type Blockchain struct { blocks []Block mu sync.RWMutex } // NewBlockchain creates a new blockchain with genesis block func NewBlockchain() *Blockchain { bc := &Blockchain{ blocks: make([]Block, 0), } // Create genesis block genesis := Block{ Index: 0, Timestamp: time.Now(), Trail: Trail{}, PreviousHash: "0", Nonce: 0, } genesis.Hash = genesis.calculateHash() bc.blocks = append(bc.blocks, genesis) return bc } // calculateHash generates SHA256 hash for a block func (b *Block) calculateHash() string { data, _ := json.Marshal(b.Trail) record := fmt.Sprintf("%d%s%s%s%d", b.Index, b.Timestamp, data, b.PreviousHash, b.Nonce) h := sha256.New() h.Write([]byte(record)) return hex.EncodeToString(h.Sum(nil)) } // mineBlock performs proof of work func (b *Block) mineBlock(difficulty int) { target := "" for i := 0; i < difficulty; i++ { target += "0" } for b.Hash[:difficulty] != target { b.Nonce++ b.Hash = b.calculateHash() } } // AddBlock adds a new block to the blockchain func (bc *Blockchain) AddBlock(trail Trail) { bc.mu.Lock() defer bc.mu.Unlock() prevBlock := bc.blocks[len(bc.blocks)-1] newBlock := Block{ Index: prevBlock.Index + 1, Timestamp: time.Now(), Trail: trail, PreviousHash: prevBlock.Hash, Nonce: 0, } // Mine the block with difficulty 2 (adjustable) newBlock.mineBlock(2) bc.blocks = append(bc.blocks, newBlock) } // GetTrails returns all trails from the blockchain func (bc *Blockchain) GetTrails() []Trail { bc.mu.RLock() defer bc.mu.RUnlock() trails := make([]Trail, 0, len(bc.blocks)-1) for i := 1; i < len(bc.blocks); i++ { trails = append(trails, bc.blocks[i].Trail) } return trails } // GetTrailsBySession returns trails for a specific session func (bc *Blockchain) GetTrailsBySession(sessionID string) []Trail { bc.mu.RLock() defer bc.mu.RUnlock() trails := make([]Trail, 0) for i := 1; i < len(bc.blocks); i++ { if bc.blocks[i].Trail.SessionID == sessionID { trails = append(trails, bc.blocks[i].Trail) } } return trails } // IsValid verifies the blockchain integrity func (bc *Blockchain) IsValid() bool { bc.mu.RLock() defer bc.mu.RUnlock() for i := 1; i < len(bc.blocks); i++ { currentBlock := bc.blocks[i] prevBlock := bc.blocks[i-1] // Verify current block's hash if currentBlock.Hash != currentBlock.calculateHash() { return false } // Verify link to previous block if currentBlock.PreviousHash != prevBlock.Hash { return false } } return true } // Config holds middleware configuration type Config struct { Blockchain *Blockchain SessionKey string UserIDKey string SkipPaths []string HeadersToTrack []string EnableMining bool MiningDifficulty int } // DefaultConfig returns default configuration func DefaultConfig() Config { return Config{ Blockchain: NewBlockchain(), SessionKey: "session_id", UserIDKey: "user_id", SkipPaths: []string{"/health", "/metrics"}, HeadersToTrack: []string{"X-Request-ID", "X-Forwarded-For"}, EnableMining: true, MiningDifficulty: 2, } } // New creates a new blockchain trail middleware func New(config ...Config) fiber.Handler { cfg := DefaultConfig() if len(config) > 0 { cfg = config[0] } if cfg.Blockchain == nil { cfg.Blockchain = NewBlockchain() } return func(c *fiber.Ctx) error { // Skip tracking for certain paths for _, skip := range cfg.SkipPaths { if c.Path() == skip { return c.Next() } } start := time.Now() // Process request err := c.Next() // Create trail entry trail := Trail{ SessionID: c.Get(cfg.SessionKey, ""), UserID: c.Get(cfg.UserIDKey, ""), Path: c.Path(), Method: c.Method(), IP: c.IP(), UserAgent: c.Get("User-Agent"), StatusCode: c.Response().StatusCode(), Duration: time.Since(start), Headers: make(map[string]string), } // Track specified headers for _, header := range cfg.HeadersToTrack { if value := c.Get(header); value != "" { trail.Headers[header] = value } } // Add to blockchain asynchronously to avoid blocking go func() { cfg.Blockchain.AddBlock(trail) }() return err } } // GetBlockchainHandler returns a handler to view the blockchain func GetBlockchainHandler(blockchain *Blockchain) fiber.Handler { return func(c *fiber.Ctx) error { blockchain.mu.RLock() defer blockchain.mu.RUnlock() return c.JSON(fiber.Map{ "valid": blockchain.IsValid(), "block_count": len(blockchain.blocks), "blocks": blockchain.blocks, }) } } // GetTrailsHandler returns a handler to view trails func GetTrailsHandler(blockchain *Blockchain) fiber.Handler { return func(c *fiber.Ctx) error { sessionID := c.Query("session_id") var trails []Trail if sessionID != "" { trails = blockchain.GetTrailsBySession(sessionID) } else { trails = blockchain.GetTrails() } return c.JSON(fiber.Map{ "count": len(trails), "trails": trails, }) } }Here's an example of how to use this middleware:
package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/session" blockchain_trail "your-module/middleware/blockchain-trail" ) func main() { app := fiber.New() // Session middleware for tracking users store := session.New() app.Use(session.New(session.Config{ Store: store, })) // Logger middleware app.Use(logger.New()) // Initialize blockchain trail middleware blockchain := blockchain_trail.NewBlockchain() app.Use(blockchain_trail.New(blockchain_trail.Config{ Blockchain: blockchain, SessionKey: "session_id", UserIDKey: "user_id", SkipPaths: []string{"/health", "/blockchain", "/trails"}, HeadersToTrack: []string{"X-Request-ID", "X-Forwarded-For"}, EnableMining: true, MiningDifficulty: 2, })) // Routes app.Get("/", func(c *fiber.Ctx) error { sess, _ := store.Get(c) sess.Set("session_id", sess.ID()) sess.Save() return c.JSON(fiber.Map{ "message": "Hello, World!", "session": sess.ID(), }) }) app.Get("/protected", func(c *fiber.Ctx) error { sess, _ := store.Get(c) sess.Set("user_id", "user123") sess.Save() return c.JSON(fiber.Map{ "message": "Protected route", "user": "user123", }) }) // Blockchain inspection endpoints app.Get("/blockchain", blockchain_trail.GetBlockchainHandler(blockchain)) app.Get("/trails", blockchain_trail.GetTrailsHandler(blockchain)) // Health check app.Get("/health", func(c *fiber.Ctx) error { return c.JSON(fiber.Map{"status": "ok"}) }) log.Fatal(app.Listen(":3000")) }This middleware provides several key features:
-
Blockchain Structure: Each navigation trail is stored as a block in the blockchain, ensuring immutability and traceability.
-
Trail Information: Captures comprehensive navigation data including session ID, user ID, path, method, IP address, user agent, status code, request duration, and custom headers.
-
Proof of Work: Implements basic mining with configurable difficulty to ensure blockchain integrity.
-
Session Tracking: Integrates with Fiber's session middleware to track user sessions across requests.
-
Async Processing: Adds blocks to the blockchain asynchronously to avoid blocking request processing.
-
Inspection Endpoints: Provides handlers to view the blockchain and query trails by session.
-
Validation: Includes blockchain validation to ensure the chain hasn't been tampered with.
-
Configurable: Allows customization of tracked headers, paths to skip, mining difficulty, and more.
The blockchain ensures that navigation trails cannot be altered once recorded, providing an audit trail that's cryptographically secure. This could be useful for compliance, security auditing, or analyzing user behavior patterns in a tamper-proof manner.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.