exampleutil

package
v0.1.59999 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package exampleutil provides common utilities for go-noise examples

Package shared provides common utilities for go-noise examples

Package shared provides common utilities for go-noise examples

Package shared provides NTCP2-specific utilities for go-noise examples

Package shared provides common utilities for go-noise examples

Package shared provides common utilities for go-noise examples

Package shared provides common utilities for go-noise examples

Index

Constants

This section is empty.

Variables

View Source
var PatternsRequiringLocalKey = map[string]bool{
	"K": true, "X": true,
	"XK": true, "XX": true,
	"KN": true, "KK": true, "KX": true,
	"IK": true, "IX": true,
}

PatternsRequiringLocalKey returns patterns that require a static key for the local party

View Source
var PatternsRequiringRemoteKey = map[string]bool{
	"K": true, "NK": true,
	"XK": true, "KN": true, "KK": true, "KX": true,
	"IK": true, "IN": true,
}

PatternsRequiringRemoteKey returns patterns that require a remote static key

View Source
var SupportedPatterns = []string{

	"N", "K", "X",

	"NN", "NK", "NX",
	"XN", "XK", "XX",
	"KN", "KK", "KX",
	"IN", "IK", "IX",
}

SupportedPatterns lists all standard Noise Protocol patterns

Functions

func AcceptConnections

func AcceptConnections(ctx context.Context, listener net.Listener, config *noise.ConnConfig)

AcceptConnections accepts incoming connections in a loop, dispatching each to HandleEchoConnection, until ctx is cancelled. It configures a 1-second Accept deadline so the loop remains responsive to context cancellation.

func AwaitShutdownSignal

func AwaitShutdownSignal(cancel context.CancelFunc, wg *sync.WaitGroup)

AwaitShutdownSignal blocks until SIGINT or SIGTERM is received. It then calls cancel and waits for wg to finish (with a 10-second timeout).

func EchoOnce

func EchoOnce(conn net.Conn)

EchoOnce reads one message from a net.Conn and writes back an echo response. This consolidates the simple echo handler duplicated across pool and retry server examples.

func GenerateKeyPair

func GenerateKeyPair() (localKey, remoteKey []byte, err error)

GenerateKeyPair generates a pair of keys for testing (static key and remote key)

func GenerateRandomKey

func GenerateRandomKey() ([]byte, error)

GenerateRandomKey generates a random 32-byte Curve25519 private key for testing

func GetPatternRequirements

func GetPatternRequirements(pattern string) (needsLocal, needsRemote bool)

GetPatternRequirements returns the key requirements for a pattern

func HandleConnection

func HandleConnection(conn net.Conn, echoPrefix string, postHandshake func(*noise.NoiseConn))

HandleConnection handles a Noise connection with handshake, optional post-handshake callback, and echo loop. This consolidates the common connection handler pattern duplicated across state, transport, and other examples.

func HandleDefaultAddress

func HandleDefaultAddress(args *CommonArgs, defaultAddr string)

HandleDefaultAddress sets the default server address when no address is provided. This consolidates the common default-address pattern used across example programs.

func HandleEchoConnection

func HandleEchoConnection(rawConn net.Conn)

HandleEchoConnection echoes bytes from rawConn back to the sender until EOF or a non-timeout error.

func HandleNTCP2DefaultAddress

func HandleNTCP2DefaultAddress(args *NTCP2Args, defaultAddr string)

HandleNTCP2DefaultAddress sets the default server address for an NTCP2 example when no address is provided. This consolidates the common default-address pattern used across NTCP2 example programs.

func HandleSpecialModes

func HandleSpecialModes(args *CommonArgs, demoFunc func(*CommonArgs)) bool

HandleSpecialModes handles demo and generate modes, returning true if handled. demoFunc is a callback that runs the example-specific demo logic. This consolidates the common special-mode dispatch pattern used across example programs.

func KeyToHex

func KeyToHex(key []byte) string

KeyToHex converts a 32-byte key to a hex string for display/storage

func ParseKeyFromHex

func ParseKeyFromHex(keyStr string) ([]byte, error)

ParseKeyFromHex parses a hexadecimal string into a 32-byte key

func ParseKeys

func ParseKeys(args *CommonArgs) (staticKey, remoteKey []byte, err error)

ParseKeys parses cryptographic keys based on pattern requirements for general Noise examples

func ParseNTCP2Keys

func ParseNTCP2Keys(args *NTCP2Args) (routerHash, remoteRouterHash, destHash, staticKey []byte, err error)

ParseNTCP2Keys handles parsing of NTCP2-specific cryptographic material

func PrintKeys

func PrintKeys(localKey, remoteKey []byte)

PrintKeys displays keys in a user-friendly format

func PrintLines

func PrintLines(lines ...string)

PrintLines prints each provided string on its own line, consolidating repeated fmt.Println sequences into a single function call to reduce code duplication across example programs.

func PrintNTCP2Usage

func PrintNTCP2Usage(appName, description string)

PrintNTCP2Usage displays usage information for an NTCP2 example

func PrintUsage

func PrintUsage(appName, description string)

PrintUsage displays usage information for a Noise example

func PrintUsageExample

func PrintUsageExample(appName, description, command string)

PrintUsageExample prints a single usage example consisting of a description comment and the corresponding command line, consolidating the repeated description-plus-command pattern used by PrintUsage and PrintNTCP2Usage.

func PrintUsageHeader

func PrintUsageHeader(appName, description string)

PrintUsageHeader prints the common header portion of usage output shared between PrintUsage and PrintNTCP2Usage. It displays the app name, description, usage syntax, available options, and the "Examples:" label.

func RegisterModeFlags

func RegisterModeFlags(demo, generate, verbose *bool, demoDesc, generateDesc string)

RegisterModeFlags registers the common operation mode flags shared by both standard and NTCP2 argument parsing.

func RegisterNetworkFlags

func RegisterNetworkFlags(serverAddr, clientAddr *string, serverExample string)

RegisterNetworkFlags registers the common -server and -client flags shared by both standard and NTCP2 argument parsing.

func RegisterTimeoutFlags

func RegisterTimeoutFlags(handshakeTimeout, readTimeout, writeTimeout *time.Duration, defaultHandshake time.Duration, handshakeDesc string)

RegisterTimeoutFlags registers the common timeout flags shared by both standard and NTCP2 argument parsing.

func RequiresLocalStaticKey

func RequiresLocalStaticKey(pattern string) bool

RequiresLocalStaticKey returns true if the pattern requires a local static key

func RequiresRemoteStaticKey

func RequiresRemoteStaticKey(pattern string) bool

RequiresRemoteStaticKey returns true if the pattern requires a remote static key

func RunClient

func RunClient(args *CommonArgs, staticKey, remoteKey []byte, label string, postConnect func(*noise.NoiseConn))

RunClient creates a Noise connection and invokes the provided callback with the established connection. This consolidates the common client setup pattern duplicated across state, transport, and other examples. Pass nil for remoteKey when the pattern does not require one.

func RunDemo

func RunDemo()

RunDemo executes demonstration mode showing supported patterns and configurations

func RunDemo2

func RunDemo2(args *CommonArgs, label string, serverFunc, clientFunc func(*CommonArgs, []byte))

RunDemo2 starts a server in the background, waits briefly, then runs a client. This consolidates the common demo pattern duplicated across state, transport, and other examples.

func RunExample

func RunExample(appName, description, defaultAddr, banner string,
	demoFunc func(*CommonArgs),
	serverFunc func(*CommonArgs, []byte),
	clientFunc func(*CommonArgs, []byte),
)

RunExample runs a standard example program with common argument parsing, validation, and mode dispatch. This consolidates the main() boilerplate duplicated across listener, shutdown, state, and transport examples. Pass an empty banner to skip the startup message. Pass nil for clientFunc if the example only runs in server mode.

func RunGenerate

func RunGenerate()

RunGenerate generates and displays cryptographic keys for testing

func RunLongRunningClient

func RunLongRunningClient(addr, pattern string, clientID int, staticKey []byte)

RunLongRunningClient connects to addr using pattern and staticKey, then calls SendPeriodicMessages with count=5.

func RunNTCP2Demo

func RunNTCP2Demo()

RunNTCP2Demo executes demonstration mode for NTCP2

func RunNTCP2Example

func RunNTCP2Example(appName, description, defaultAddr string,
	demoFunc func(*NTCP2Args),
	runFunc func(*NTCP2Args, []byte, []byte, []byte, []byte),
)

RunNTCP2Example runs a standard NTCP2 example program with common argument parsing, validation, and mode dispatch. This consolidates the main() boilerplate duplicated across ntcp2, ntcp2-config, and ntcp2-listener examples.

func RunNTCP2Generate

func RunNTCP2Generate()

RunNTCP2Generate generates and displays NTCP2 cryptographic material

func RunServer

func RunServer(args *CommonArgs, staticKey []byte, label string, handler func(net.Conn))

RunServer creates a Noise listener and runs an accept loop, dispatching connections to the provided handler function. This consolidates the common server setup pattern duplicated across state, transport, and other examples.

func SendAndDisplay

func SendAndDisplay(conn *noise.NoiseConn, messages []string)

SendAndDisplay sends a series of messages on a NoiseConn and displays responses with a pause between each. This consolidates the common send-receive loop duplicated across the state and transport examples.

func SendAndReceive

func SendAndReceive(conn *noise.NoiseConn, message, responseLabel string)

SendAndReceive sends a message on a NoiseConn and prints the response. This consolidates the common send-and-echo pattern duplicated across the listener and retry examples.

func SendPeriodicMessages

func SendPeriodicMessages(conn net.Conn, clientID, count int)

SendPeriodicMessages sends count messages on conn, printing echoed responses.

func ValidatePattern

func ValidatePattern(pattern string) error

ValidatePattern checks if a pattern is supported

Types

type CommonArgs

type CommonArgs struct {
	// Network configuration
	ServerAddr string
	ClientAddr string
	Pattern    string

	// Cryptographic material
	StaticKey string
	RemoteKey string

	// Timeouts
	HandshakeTimeout time.Duration
	ReadTimeout      time.Duration
	WriteTimeout     time.Duration

	// Operation modes
	Demo     bool
	Generate bool
	Verbose  bool
}

CommonArgs holds common command-line arguments for Noise examples

func ParseCommonArgs

func ParseCommonArgs(appName string) (*CommonArgs, error)

ParseCommonArgs parses standard command-line arguments for Noise examples

func (*CommonArgs) ValidateArgs

func (args *CommonArgs) ValidateArgs() error

ValidateArgs performs validation on parsed arguments

type NTCP2Args

type NTCP2Args struct {
	// Network configuration
	ServerAddr string
	ClientAddr string

	// NTCP2-specific material
	RouterHash       string
	RemoteRouterHash string
	DestinationHash  string

	// Cryptographic keys (Curve25519)
	StaticKey string

	// Timeouts
	HandshakeTimeout time.Duration
	ReadTimeout      time.Duration
	WriteTimeout     time.Duration

	// NTCP2 features
	EnableAESObfuscation bool
	EnableSipHashLength  bool
	MaxFrameSize         int

	// Operation modes
	Demo     bool
	Generate bool
	Verbose  bool
}

NTCP2Args holds NTCP2-specific command-line arguments

func ParseNTCP2Args

func ParseNTCP2Args(appName string) (*NTCP2Args, error)

ParseNTCP2Args parses NTCP2-specific command-line arguments

func (*NTCP2Args) ValidateArgs

func (args *NTCP2Args) ValidateArgs() error

ValidateArgs performs validation on parsed NTCP2 arguments

Jump to

Keyboard shortcuts

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