### Start Simple NKN Tunnel (C) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Initiates a basic NKN tunnel connection. Ensure the log file path is set before starting. ```c #include #include int main() { SetLogFilePath("/tmp/tunnel.log"); int status = StartNknTunnel( 4, "mainnet-rpc.example.com:30003", "e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435", "MyApp", "127.0.0.1:8080", "127.0.0.1:9090", 0, 0, "", "", 0, 0, "", 0, "", 0, 1 ); if (status != 0) { fprintf(stderr, "Failed: %d\n", status); return 1; } // Tunnel is running sleep(60); CloseNknTunnel(); return 0; } ``` -------------------------------- ### Instantiate multiClientDialer Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/multiClientDialer.md Example of how to instantiate a multiClientDialer by wrapping a MultiClient. This is for internal usage. ```go // Internal usage - not called by users mc, _ := nkn.NewMultiClient(account, id, 4, false, nil) dialer := newMultiClientDialer(mc) ``` -------------------------------- ### StartNknTunnel Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Creates and starts a tunnel with the given configuration. This function is thread-safe and closes any existing tunnel before creating a new one. It starts the tunnel in the background and applies default values if parameters are empty or zero. ```APIDOC ## StartNknTunnel ### Description Creates and starts a tunnel with the given configuration. ### Signature ```c int StartNknTunnel( int numClients, const char* seedRpcServers, const char* seedHex, const char* identifier, const char* from, const char* to, int udp, int useTuna, const char* tunaMaxPrice, const char* tunaMinFee, float tunaFeeRatio, int tunaDownloadGeoDB, const char* tunaGeoDBPath, int tunaMeasureBandwidth, const char* tunaMeasureStoragePath, int tunaMeasurementBytesDownLink, int verbose ); ``` ### Parameters - **numClients** (int) - Required - Number of NKN sub-clients. Default: 4. - **seedRpcServers** (const char*) - Required - Comma-separated RPC server addresses. - **seedHex** (const char*) - Required - 64-character hex-encoded seed (32 bytes). - **identifier** (const char*) - Required - NKN address identifier (can be empty). - **from** (const char*) - Required - Listen address: `ip:port` or `"nkn"` or `""`. - **to** (const char*) - Required - Destination address: NKN address or `ip:port`. - **udp** (int) - Optional - 1 to enable UDP, 0 to disable. Default: 0. - **useTuna** (int) - Optional - 1 to enable Tuna mode, 0 for standard NKN. Default: 0. - **tunaMaxPrice** (const char*) - Optional - Max price per MB; uses default if empty. Default: "0.01". - **tunaMinFee** (const char*) - Optional - Min nanopay fee; uses default if empty. Default: "0.00001". - **tunaFeeRatio** (float) - Optional - Nanopay fee ratio; uses default if 0. Default: 0.1. - **tunaDownloadGeoDB** (int) - Optional - 1 to download geo database, 0 to skip. Default: 0. - **tunaGeoDBPath** (const char*) - Optional - Path to store geo database. Default: "". - **tunaMeasureBandwidth** (int) - Optional - 1 to measure bandwidth, 0 to skip. Default: 0. - **tunaMeasureStoragePath** (const char*) - Optional - Path to store bandwidth measurement. Default: "". - **tunaMeasurementBytesDownLink** (int) - Optional - Bytes to measure (0 = 65536). Default: 65536. - **verbose** (int) - Optional - 1 for verbose logging, 0 for normal. Default: 0. ### Returns `int` - Status code | Code | Meaning | Cause | |------|---------|-------| | 0 | Success | Tunnel created and started | | 1 | Invalid seed hex | Seed hex is empty or not empty but invalid | | 2 | Invalid seed format | Seed hex is not valid hexadecimal | | 3 | Account creation failed | Seed is invalid or NKN SDK error | | 4 | Tunnel creation failed | Configuration error or resource unavailable | | -1 | Unknown error | Unexpected error (check logs) | ### Behavior - Closes any existing tunnel before creating a new one. - Starts tunnel in background (non-blocking). - Default values are applied if parameters are empty or zero. - Thread-safe via internal mutex. ### Example (C) ```c #include int status = StartNknTunnel( 4, // numClients "mainnet-rpc1.example.com:30003,mainnet-rpc2.example.com:30003", // seedRpcServers "e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435", // seedHex "MyApp", // identifier "127.0.0.1:8080", // from "127.0.0.1:9090", // to 0, // udp (disabled) 0, // useTuna (disabled) "", // tunaMaxPrice (use default) "", // tunaMinFee (use default) 0, // tunaFeeRatio (use default) 0, // tunaDownloadGeoDB "", // tunaGeoDBPath 0, // tunaMeasureBandwidth "", // tunaMeasureStoragePath 0, // tunaMeasurementBytesDownLink (use default) 1 // verbose ); if (status != 0) { printf("Failed to start tunnel: %d\n", status); } ``` ### Example (Python via ctypes) ```python import ctypes lib = ctypes.CDLL('./libnkntunnel.so') status = lib.StartNknTunnel( 4, # numClients b'mainnet-rpc1.example.com:30003', # seedRpcServers b'e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435', # seedHex b'MyApp', # identifier b'127.0.0.1:8080', # from b'127.0.0.1:9090', # to 0, # udp 0, # useTuna b'', # tunaMaxPrice b'', # tunaMinFee 0, # tunaFeeRatio 0, # tunaDownloadGeoDB b'', # tunaGeoDBPath 0, # tunaMeasureBandwidth b'', # tunaMeasureStoragePath 0, # tunaMeasurementBytesDownLink 1 # verbose ) if status != 0: print(f"Failed: {status}") ``` ``` -------------------------------- ### Handle Tunnel Start Errors Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/errors.md Shows how to handle errors returned from the Start() method, differentiating between graceful closure (io.EOF), network errors (*net.OpError), and other tunnel-specific errors. ```go go func() { if err := t.Start(); err != nil { if err == io.EOF { log.Println("Tunnel closed gracefully") } else if ne, ok := err.(*net.OpError); ok { log.Println("Network error:", ne) } else { log.Println("Tunnel error:", err) } } }() ``` -------------------------------- ### Start Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Starts the tunnel, accepting connections and forwarding data. This method blocks until an error occurs or the tunnel is explicitly closed. It should be called in a goroutine if other operations are needed concurrently. ```APIDOC ## Start ### Description Starts the tunnel and blocks until an error occurs or the tunnel is closed. ### Method ```go func (t *Tunnel) Start() error ``` ### Returns `error` — Listener or connection error; nil if closed gracefully ### Behavior - Blocks indefinitely, accepting connections and forwarding data - Launches goroutines for each accepted connection - If UDP is enabled in config, starts UDP forwarding on a separate listener - Returns nil on graceful close (no error raised) - Must be called in a goroutine if other operations are needed ### Example ```go // Start tunnel in background go func() { if err := t.Start(); err != nil { log.Println("Tunnel error:", err) } }() // Meanwhile, perform other operations time.Sleep(1 * time.Second) log.Println("Tunnel is running at:", t.FromAddr()) // Later, close it t.Close() ``` ``` -------------------------------- ### Example: Close NKN Tunnel (C) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Demonstrates how to call the CloseNknTunnel function and check its return status in C. ```c #include int status = CloseNknTunnel(); if (status == 0) { printf("Tunnel closed\n"); } else if (status == -1) { printf("No tunnel running\n"); } ``` -------------------------------- ### Start NKN Tunnel (C Export) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Initiate an NKN tunnel using `StartNknTunnel()`. This function is designed for C-based applications to manage tunnels. ```go func StartNknTunnel(config string) int32 ``` -------------------------------- ### Tunnel NewTunnel Example Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/multiClientDialer.md Illustrates the correct, high-level usage of creating a tunnel, which internally utilizes multiClientDialer. ```go // High-level API (correct usage) t, err := tunnel.NewTunnel(account, id, from, to, false, config, nil) // Internally creates multiClientDialer ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/nknorg/nkn-tunnel/blob/master/README.md If the `lipo` command is not found on macOS, ensure Xcode is installed and the correct developer tools are selected by running this command. ```shell xcode-select --install ``` -------------------------------- ### StartNknTunnel C Example Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Demonstrates how to use the `StartNknTunnel` function in C to establish a basic NKN tunnel with verbose logging enabled. Ensure the NKN SDK is properly linked. ```c #include int status = StartNknTunnel( 4, // numClients "mainnet-rpc1.example.com:30003,mainnet-rpc2.example.com:30003", // seedRpcServers "e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435", // seedHex "MyApp", // identifier "127.0.0.1:8080", // from "127.0.0.1:9090", // to 0, // udp (disabled) 0, // useTuna (disabled) "", // tunaMaxPrice (use default) "", // tunaMinFee (use default) 0, // tunaFeeRatio (use default) 0, // tunaDownloadGeoDB "", // tunaGeoDBPath 0, // tunaMeasureBandwidth "", // tunaMeasureStoragePath 0, // tunaMeasurementBytesDownLink (use default) 1 // verbose ); if (status != 0) { printf("Failed to start tunnel: %d\n", status); } ``` -------------------------------- ### Get Default Configuration Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/config.md Returns a new Config instance with default values. Customize this instance as needed. ```go config := tunnel.DefaultConfig() // Now customize as needed config.Verbose = true config.UDP = true ``` -------------------------------- ### Basic TCP-to-TCP Tunnel Configuration Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/config.md Minimal setup for a basic TCP-to-TCP tunnel using default configuration values. ```go config := tunnel.DefaultConfig() // All fields use defaults - minimal setup ``` -------------------------------- ### Ensure Go Module Dependencies Source: https://github.com/nknorg/nkn-tunnel/blob/master/README.md If the build fails with a 'library not found' error, run this command to install all necessary Go module dependencies. ```shell go mod tidy ``` -------------------------------- ### NKN Tunnel Starting Flow Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Details the process of starting an established tunnel. This includes launching listener goroutines, handling incoming connections, establishing remote connections, and initiating data piping between peers. ```Go Start() ↓ Launch listener accept goroutines ↓ Launch UDP listener (if config.UDP) ↓ Accept connection ├─ Dial remote ├─ Start pipe goroutines (A→B and B→A) └─ Return to accept (next connection) ``` -------------------------------- ### Example CLI Usage for NKN Tunnel Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md Demonstrates how to launch the NKN tunnel with specific configuration flags. Ensure you replace placeholder values with your actual seed and server addresses. ```bash ./nkn-tunnel \ -s e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435 \ -i Alice \ -from 127.0.0.1:8081 \ -to Bob \ -n 8 \ -v \ -rpc rpc.example.com:30003,rpc2.example.com:30003 ``` -------------------------------- ### Python FFI Example for NKN Tunnel C Bindings Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt This example demonstrates how to use the NKN Tunnel C bindings from Python using Foreign Function Interface (FFI). It shows how to call C functions like SetLogFilePath, StartNknTunnel, and CloseNknTunnel. ```Python from cffi import FFI ffi = FFI() ffi.cdef("void SetLogFilePath(const char* path);\nint StartNknTunnel(const char* config_json);\nvoid CloseNknTunnel(int tunnel_id);") # Load the shared library (adjust path as needed) nkn_tunnel_lib = ffi.dlopen("./libnkntunnel.so") # Example usage: log_path = b"/var/log/nkn-tunnel.log" nkn_tunnel_lib.SetLogFilePath(log_path) config_data = b'{"some": "config"}' # Replace with actual JSON config tunnel_id = nkn_tunnel_lib.StartNknTunnel(config_data) if tunnel_id >= 0: print(f"NKN Tunnel started with ID: {tunnel_id}") # ... perform operations ... nkn_tunnel_lib.CloseNknTunnel(tunnel_id) print(f"NKN Tunnel {tunnel_id} closed") else: print("Failed to start NKN Tunnel") ``` -------------------------------- ### StartNknTunnel Python Example via ctypes Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Shows how to call the `StartNknTunnel` C function from Python using the `ctypes` library. Ensure `libnkntunnel.so` is in the current directory or accessible via the system's library path. Note that string arguments must be byte strings. ```python import ctypes lib = ctypes.CDLL('./libnkntunnel.so') status = lib.StartNknTunnel( 4, # numClients b'mainnet-rpc1.example.com:30003', # seedRpcServers b'e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435', # seedHex b'MyApp', # identifier b'127.0.0.1:8080', # from b'127.0.0.1:9090', # to 0, # udp 0, # useTuna b'', # tunaMaxPrice b'', # tunaMinFee 0, # tunaFeeRatio 0, # tunaDownloadGeoDB b'', # tunaGeoDBPath 0, # tunaMeasureBandwidth b'', # tunaMeasureStoragePath 0, # tunaMeasurementBytesDownLink 1 # verbose ) if status != 0: print(f"Failed: {status}") ``` -------------------------------- ### SetLogFilePath C Example Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Demonstrates how to set the log file path to a specific file or revert to stdout using the SetLogFilePath function in C. ```c #include // Log to file SetLogFilePath("/var/log/nkn-tunnel.log"); // Log to stdout (clear previous path) SetLogFilePath(""); ``` -------------------------------- ### Start NKN Tunnel (NKN SDK Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Initiates the NKN tunnel connection. Ensure all necessary configurations and accounts are set before calling this method. ```go func (t *Tunnel) Start() error ``` -------------------------------- ### StartNknTunnel C API Signature Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md The C library interface for starting an NKN tunnel. It exposes numerous configuration parameters. ```c int StartNknTunnel( int numClients, const char* seedRpcServers, const char* seedHex, const char* identifier, const char* from, const char* to, int udp, int useTuna, const char* tunaMaxPrice, const char* tunaMinFee, float tunaFeeRatio, int tunaDownloadGeoDB, const char* tunaGeoDBPath, int tunaMeasureBandwidth, const char* tunaMeasureStoragePath, int tunaMeasurementBytesDownLink, int verbose ); ``` -------------------------------- ### Create Tunnel via Go Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/00-START-HERE.md Programmatically create and start an NKN tunnel using the Go SDK. Requires an account and configuration object. ```go t, _ := tunnel.NewTunnel(account, "MyApp", "127.0.0.1:8081", "127.0.0.1:8080", false, config, nil) go t.Start() ``` -------------------------------- ### Configure UDP Idle Connection Management Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/udp.md Example of enabling UDP and setting UDPIdleTime to 600 seconds, which configures the system to automatically purge idle connections after 10 minutes. This is useful for managing session state. ```go config := tunnel.DefaultConfig() config.UDP = true config.UDPIdleTime = 600 // Auto-purge after 10 minutes t, err := tunnel.NewTunnel(account, id, "127.0.0.1:5353", "10.0.0.1:53", true, config, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### NKN Tunnel Initialization Flow Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Illustrates the sequence of steps involved in creating a single tunnel using the NewTunnel or NewTunnels functions. It highlights validation, configuration merging, client creation, and listener setup. ```Go NewTunnel() ↓ NewTunnels() with single from/to ↓ Validate: len(from) == len(to) != 0 ↓ MergedConfig(config) ↓ Determine: fromNKN, toNKN ↓ Create MultiClient (if needed) ↓ Create Tuna client (if tuna=true) ↓ Create listeners (TCP or NKN) ↓ Create Tunnel struct ↓ Return []*Tunnel slice ``` -------------------------------- ### TCP-to-TCP Tunnel (Go Library) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Implement a TCP tunnel using the NKN SDK for Go. This example shows how to create a tunnel that forwards local TCP connections to a remote service. ```go package main import ( "encoding/hex" "log" "github.com/nknorg/nkn-sdk-go" "github.com/nknorg/nkn-tunnel" ) func main() { // Decode seed (get from secure storage) seed, _ := hex.DecodeString("your-seed-hex") account, err := nkn.NewAccount(seed) if err != nil { log.Fatal(err) } // Create tunnel from local port to remote config := tunnel.DefaultConfig() t, err := tunnel.NewTunnel( account, "MyClient", "127.0.0.1:8081", // Local TCP listen "127.0.0.1:8080", // Remote TCP false, // Not using Tuna config, nil, // Create new MultiClient ) if err != nil { log.Fatal(err) } // Start forwarding (blocks until error) log.Fatal(t.Start()) } ``` -------------------------------- ### DNS Tunnel over Tuna UDP Example Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/udp.md This Go code demonstrates how to set up a DNS tunnel using NKN's UDP forwarding capabilities. It configures both a server and a client tunnel, enabling UDP traffic to be tunneled over NKN. Ensure you replace 'DNS-Server.pubkey123...' with the actual public key of your server. ```go package main import ( "log" "github.com/nknorg/nkn-sdk-go" "github.com/nknorg/nkn-tunnel" ) func main() { account, err := nkn.NewAccount(seed) if err != nil { log.Fatal(err) } // Configure tunnel with UDP support config := tunnel.DefaultConfig() config.UDP = true config.UDPIdleTime = 300 config.TunaSessionConfig = &ts.Config{ NumTunaListeners: 4, TunaMaxPrice: "0.01", } // Create server tunnel: listen on UDP 127.0.0.1:5353, forward to remote DNS server, err := tunnel.NewTunnel( account, "DNS-Server", "127.0.0.1:5353", // Local UDP listen "8.8.8.8:53", // Google DNS true, // Tuna mode config, nil, ) if err != nil { log.Fatal(err) } go func() { if err := server.Start(); err != nil { log.Println("Server error:", err) } }() // Create client tunnel: listen on local UDP, forward to server NKN address client, err := tunnel.NewTunnel( account, "DNS-Client", "127.0.0.1:53", // Local UDP listen "DNS-Server.pubkey123...", // Server NKN address true, // Tuna mode config, nil, ) if err != nil { log.Fatal(err) } if err := client.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Handle Tunnel Creation Errors Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/errors.md Provides an example of handling various errors that can occur during tunnel creation using a switch statement on the error message. ```go tunnels, err := tunnel.NewTunnels(account, id, from, to, true, config, nil) if err != nil { switch err.Error() { case "from should have same length as to": log.Fatal("Configuration error: mismatched tunnel pairs") case "multiple tunnels is not supported when from NKN": log.Fatal("Cannot create multiple NKN listeners") default: log.Fatal("Tunnel creation failed:", err) } } ``` -------------------------------- ### High Performance NKN Tunnel Setup Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md Optimize the NKN tunnel for high performance by increasing concurrency, enabling Tuna with bandwidth measurement, and reducing dial timeouts for faster failure detection. Verbose logging is also enabled for monitoring. ```go config := tunnel.DefaultConfig() // Increase concurrency config.NumSubClients = 16 config.OriginalClient = true // Enable Tuna if available config.TunaSessionConfig = &ts.Config{ NumTunaListeners: 8, TunaMaxPrice: "0.02", TunaMeasureBandwidth: true, } // Shorter timeouts for faster failure detection config.DialConfig = &nkn.DialConfig{ DialTimeout: 10000, // 10 seconds } // Verbose logging for monitoring config.Verbose = true ``` -------------------------------- ### SetLogFilePath Python Example using ctypes Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Shows how to call the SetLogFilePath function from Python using the ctypes library to manage nkn-tunnel logs. ```python import ctypes lib = ctypes.CDLL('./libnkntunnel.so') lib.SetLogFilePath(b'/var/log/tunnel.log') ``` -------------------------------- ### Bandwidth-Constrained Environment Setup Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md Configure the NKN tunnel for bandwidth-constrained environments by reducing concurrency, disabling UDP, and increasing dial timeouts for high-latency networks. This minimizes bandwidth usage and improves stability. ```go config := tunnel.DefaultConfig() // Reduce concurrency to lower bandwidth usage config.NumSubClients = 2 config.OriginalClient = false // Disable UDP for simpler protocol config.UDP = false // Longer timeouts for high-latency networks config.DialConfig = &nkn.DialConfig{ DialTimeout: 60000, // 60 seconds } ``` -------------------------------- ### Start NKN Tunnel with Tuna and UDP (C) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Configures an NKN tunnel to use Tuna for pricing and UDP for communication. This is useful for services like DNS. ```c int status = StartNknTunnel( 4, // numClients "mainnet-rpc.example.com:30003", // seedRpcServers "e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435", "MyApp", "127.0.0.1:5353", // Local UDP listen "8.8.8.8:53", // Remote DNS 1, // udp = true 1, // useTuna = true "0.02", // tunaMaxPrice "0.00001", // tunaMinFee 0.1, // tunaFeeRatio 0, // tunaDownloadGeoDB "", // tunaGeoDBPath 1, // tunaMeasureBandwidth "/tmp/bandwidth", // tunaMeasureStoragePath 65536, // tunaMeasurementBytesDownLink 1 // verbose ); ``` -------------------------------- ### Tuna Mode with UDP (Go Library) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Configure and create a tunnel that operates in Tuna mode, supporting both UDP and TCP traffic. This example sets specific parameters for UDP and Tuna session configuration, such as listener count and pricing. ```go config := tunnel.DefaultConfig() config.UDP = true config.UDPIdleTime = 300 config.TunaSessionConfig = &ts.Config{ NumTunaListeners: 4, TunaMaxPrice: "0.01", TunaMinNanoPayFee: "0.00001", TunaNanoPayFeeRatio: 0.1, } // Create tunnel with Tuna t, err := tunnel.NewTunnel( account, "MyApp", "127.0.0.1:5353", // Local UDP/TCP listen "127.0.0.1:53", // Remote DNS true, // Tuna mode config, nil, ) if err != nil { log.Fatal(err) } log.Fatal(t.Start()) ``` -------------------------------- ### UDP Not Supported Validation Example Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md Demonstrates how to handle the ErrUDPNotSupported error by enabling Tuna when UDP is used. This snippet shows a common validation scenario. ```go config := tunnel.DefaultConfig() config.UDP = true // This will fail with ErrUDPNotSupported tunnels, err := tunnel.NewTunnels(account, id, from, to, false, config, nil) if err == tunnel.ErrUDPNotSupported { // Fix: enable Tuna tunnels, err = tunnel.NewTunnels(account, id, from, to, true, config, nil) } ``` -------------------------------- ### Example: Close NKN Tunnel (Python via ctypes) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Shows how to call the CloseNknTunnel function from Python using ctypes, assuming the shared library is available. ```python import ctypes lib = ctypes.CDLL('./libnkntunnel.so') status = lib.CloseNknTunnel() if status == 0: print("Tunnel closed") else: print("No tunnel running") ``` -------------------------------- ### Start NKN Tunnel Server Source: https://github.com/nknorg/nkn-tunnel/blob/master/README.md Initiate the NKN Tunnel in server mode, specifying the local TCP port to forward to. The output will indicate the listening address. ```shell ./nkn-tunnel -to 127.0.0.1:8080 -s ``` -------------------------------- ### Start Tunnel Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Initiates the tunnel's operation, blocking until an error occurs or the tunnel is explicitly closed. It's recommended to run this in a separate goroutine to avoid blocking the main thread. ```go // Start tunnel in background go func() { if err := t.Start(); err != nil { log.Println("Tunnel error:", err) } }() // Meanwhile, perform other operations time.Sleep(1 * time.Second) log.Println("Tunnel is running at:", t.FromAddr()) // Later, close it t.Close() ``` -------------------------------- ### Graceful Tunnel Shutdown (Go Library) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Implement graceful shutdown for an NKN tunnel. This example shows how to catch termination signals and close the tunnel cleanly, ensuring no data is lost during shutdown. ```go t, err := tunnel.NewTunnel(account, id, from, to, false, config, nil) if err != nil { log.Fatal(err) } // Start in background go func() { if err := t.Start(); err != nil { log.Println("Tunnel error:", err) } }() // Monitor and shutdown sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) <-sig log.Println("Shutting down...") if err := t.Close(); err != nil { log.Println("Close error:", err) } log.Println("Done") ``` -------------------------------- ### Error Handling with StartNknTunnel and CloseNknTunnel Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Demonstrates how to check the return status of `StartNknTunnel` and handle specific error codes. It also shows how to call `CloseNknTunnel` and check its status. ```c int status = StartNknTunnel(/* ... */); if (status != 0) { // Check logs for details switch (status) { case 1: fprintf(stderr, "Invalid seed hex\n"); break; case 2: fprintf(stderr, "Seed format error\n"); break; case 3: fprintf(stderr, "Account creation failed\n"); break; case 4: fprintf(stderr, "Tunnel creation failed\n"); break; default: fprintf(stderr, "Unknown error\n"); } return status; } // Tunnel is running // ... int close_status = CloseNknTunnel(); if (close_status != 0) { // Likely no tunnel was running } ``` -------------------------------- ### Enable UDP with Default Configuration Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/udp.md Demonstrates how to enable UDP forwarding using the DefaultConfig and setting the UDP field to true. UDPIdleTime can also be configured to purge idle connections. ```go config := tunnel.DefaultConfig() config.UDP = true config.UDPIdleTime = 300 // Purge idle connections after 300 seconds ``` -------------------------------- ### Default Configuration for Development Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Use this configuration for development and testing to enable verbose logging. ```go config := tunnel.DefaultConfig() config.Verbose = true ``` -------------------------------- ### Simple TCP-to-TCP Tunnel (CLI) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Set up a basic TCP tunnel using the NKN tunnel CLI. The listener side forwards traffic to a local port, and the client side connects to the listener's NKN address. ```bash ./nkn-tunnel \ -s YOUR_SECRET_SEED \ -to 127.0.0.1:8080 ``` ```bash ./nkn-tunnel \ -s YOUR_SECRET_SEED \ -from 127.0.0.1:8081 \ -to Abc123Def456... ``` -------------------------------- ### Print Version and Exit Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/cli-reference.md Use the -version flag to print the program version and exit. ```bash ./nkn-tunnel -version ``` -------------------------------- ### Get Default Tunnel Configuration Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Retrieve the default configuration for tunnel creation using `DefaultConfig()`. This provides a baseline for customization. ```go func DefaultConfig() Config ``` -------------------------------- ### nknListener Interface Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md The nknListener interface specifies the contract for NKN listeners, enabling them to start listening for incoming connections on specified addresses. ```APIDOC ## nknListener Interface Generic interface for NKN listeners. ```go type nknListener interface { Listen(addrsRe *nkngomobile.StringArray) error } ``` ``` -------------------------------- ### Get Tunnel MultiClient Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Returns the NKN MultiClient instance used internally by the tunnel. This allows access to MultiClient specific methods. ```go mc := t.MultiClient() // Access MultiClient methods log.Println("Client address:", mc.Addr().String()) ``` -------------------------------- ### Get Tunnel Listening Address Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md The `FromAddr` method returns the local address the tunnel is listening on. This is useful for verifying the listening endpoint. ```go listenAddr := t.FromAddr() log.Println("Tunnel listening on:", listenAddr) // Output: "127.0.0.1:8081" ``` -------------------------------- ### Build nkn-tunnel CLI Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Clone the repository, navigate to the directory, and build the CLI tool using Go. The output executable will be named 'nkn-tunnel'. ```bash git clone https://github.com/nknorg/nkn-tunnel.git cd nkn-tunnel go build -o nkn-tunnel bin/main.go ``` -------------------------------- ### Listen for UDP Connections (NKN SDK Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Sets up a listener for incoming UDP connections on the tunnel. Returns the listener or an error. ```go func (t *Tunnel) listenUDP() (udpConn, error) ``` -------------------------------- ### Get Default Tunnel Configuration (NKN SDK Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Retrieves the default configuration for an NKN tunnel. This is useful for initializing tunnel settings. ```go func DefaultConfig() *Config ``` -------------------------------- ### Get Tuna Public Addresses Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Fetches the public node address information for Tuna listeners. Returns nil if no Tuna listener is active. ```go if pubAddrs := t.TunaPubAddrs(); pubAddrs != nil { log.Println("Tuna public address:", pubAddrs) } ``` -------------------------------- ### Create a New Tunnel Client Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Use `NewTunnel()` to create a single tunnel client. This is the main entry point for establishing connections. ```go func NewTunnel() Tunnel ``` -------------------------------- ### Get Tuna Session Client Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Retrieves the Tuna session client if the tunnel is operating in Tuna mode. Returns nil if Tuna is disabled. ```go if tsClient := t.TunaSessionClient(); tsClient != nil { log.Println("Tuna session is active") // Access Tuna-specific methods } ``` -------------------------------- ### Get Tunnel NKN Address Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Retrieves the NKN network address of the tunnel. Returns nil if the tunnel is listening on TCP instead of NKN. ```go if addr := t.Addr(); addr != nil { log.Println("NKN address:", addr.String()) } ``` -------------------------------- ### Get Tunnel Destination Address Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md The `ToAddr` method returns the remote destination address of the tunnel. This helps in confirming where the tunnel is forwarding traffic. ```go destAddr := t.ToAddr() log.Println("Tunnel forwards to:", destAddr) // Output: "Bob.abc123def..." ``` -------------------------------- ### Build Shared and Static Libraries Source: https://github.com/nknorg/nkn-tunnel/blob/master/README.md Run this command to build dynamic and static libraries for multiple platforms. Generated files are located in the `build/lib` directory. ```shell make lib ``` -------------------------------- ### Handling UDP Not Supported Error Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/udp.md Example of how to handle the ErrUDPNotSupported error when creating tunnels. It logs a message indicating that UDP requires Tuna mode. ```go tunnels, err := tunnel.NewTunnels(account, id, from, to, false, config, nil) if err == tunnel.ErrUDPNotSupported { log.Println("UDP requires Tuna mode - enable with tuna=true") return } ``` -------------------------------- ### Start NKN Tunnel Client Source: https://github.com/nknorg/nkn-tunnel/blob/master/README.md Configure the NKN Tunnel client to forward local TCP connections to the server's listening address. This enables traffic forwarding. ```shell ./nkn-tunnel -from 127.0.0.1:8081 -to ``` -------------------------------- ### StartNknTunnel C Function Signature Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Defines the signature for the `StartNknTunnel` function, outlining all available parameters for configuring an NKN tunnel. ```c int StartNknTunnel( int numClients, const char* seedRpcServers, const char* seedHex, const char* identifier, const char* from, const char* to, int udp, int useTuna, const char* tunaMaxPrice, const char* tunaMinFee, float tunaFeeRatio, int tunaDownloadGeoDB, const char* tunaGeoDBPath, int tunaMeasureBandwidth, const char* tunaMeasureStoragePath, int tunaMeasurementBytesDownLink, int verbose ); ``` -------------------------------- ### Get UDP Connection (NKN SDK Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Retrieves an existing UDP connection from a given network address. Returns the connection, a boolean indicating if it was found, and an error. ```go func (t *Tunnel) getToUDPConn(from net.Addr) (udpConn, bool, error) ``` -------------------------------- ### Database Access - Client Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Configure the client to forward local database connections to the NKN address of the listener. ```bash # Client (App Host) ./nkn-tunnel -s -from 127.0.0.1:5432 -to ``` -------------------------------- ### C Library API Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Documentation for the C library bindings, including initialization, configuration, and FFI usage. ```APIDOC ## C Library API ### Description This section covers the C library API for NKN Tunnel, enabling integration with various programming languages via Foreign Function Interface (FFI). ### Key Features - **Basic Initialization and Teardown**: Functions to initialize and clean up the C library context. - **Configuration with C Types**: Methods to configure tunnels using C-compatible data types. - **Error Code Handling**: Mechanisms for handling errors returned as error codes. - **FFI from Python, Node.js, etc.**: Examples and guidance for calling the C library from other languages. - **Graceful Shutdown**: Procedures for shutting down the tunnel instance cleanly. ### Constraints & Limitations - **One global tunnel instance**: The C library operates with a single, global tunnel instance. ### Usage Patterns Demonstrated - **Basic initialization and teardown** - **Configuration with C types** - **Error code handling** - **FFI from Python, Node.js, etc.** - **Graceful shutdown** ### Example Snippet (Conceptual C Code) ```c // Include the C library header // #include "nkn_tunnel_c.h" int main() { // Initialize the C library int init_result = nkn_tunnel_init(); if (init_result != 0) { // Handle initialization error return init_result; } // Configure the tunnel (using C types for configuration) // C_Config c_config; // nkn_tunnel_get_default_config(&c_config); // ... modify c_config ... // int config_result = nkn_tunnel_set_config(&c_config); // if (config_result != 0) { // // Handle configuration error // } // Start the tunnel // int start_result = nkn_tunnel_start(); // if (start_result != 0) { // // Handle start error // } // ... perform tunnel operations ... // Graceful shutdown // nkn_tunnel_stop(); // nkn_tunnel_cleanup(); return 0; } ``` ### Error Handling Errors are typically returned as integer error codes. Consult the `errors.md` document for a mapping of error codes to specific error conditions. ``` -------------------------------- ### Database Access - Listener Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Configure the listener on the database host to forward traffic to the local database port. ```bash # Listener (Database Host) ./nkn-tunnel -s -to 127.0.0.1:5432 ``` -------------------------------- ### DefaultConfig Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/config.md Creates a new Config instance initialized with default values. These defaults cover various settings like the number of sub-clients, UDP support, and verbosity. ```APIDOC ## DefaultConfig ### Description Returns a new Config instance with default values. ### Signature ```go func DefaultConfig() *Config ``` ### Returns *Config - Config with defaults: - NumSubClients: 4 - OriginalClient: false - AcceptAddrs: nil - All *Config fields: nil - UDP: false - UDPIdleTime: 0 - Verbose: false ### Example ```go config := tunnel.DefaultConfig() // Now customize as needed config.Verbose = true config.UDP = true ``` ``` -------------------------------- ### Remote SSH Access - Listener Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Set up a listener on the remote server to accept SSH connections. ```bash ./nkn-tunnel -s -to 127.0.0.1:22 ``` -------------------------------- ### Download Tuna Geographic Database Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/cli-reference.md Enable downloading the geographic database to disk for Tuna mode using the -tuna-download-geo-db flag. ```bash ./nkn-tunnel -tuna -tuna-download-geo-db ``` -------------------------------- ### Configure Tuna Session for Low Latency Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/getting-started.md Optimizes performance and reduces latency by switching to Tuna mode and configuring session parameters. Use this when experiencing high latency due to the default relay-based NKN mode. Adjust `NumTunaListeners` and `TunaMaxPrice` as needed. ```go config.TunaSessionConfig = &ts.Config{ NumTunaListeners: 8, TunaMaxPrice: "0.01", } ``` -------------------------------- ### C Bindings for NKN Tunnel Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt This section outlines the C export functions provided by the NKN Tunnel library, including functions for logging, starting, and closing tunnels. It also mentions support for various languages through FFI. ```C // SetLogFilePath sets the path for log files. void SetLogFilePath(const char* path); // StartNknTunnel starts an NKN tunnel with the given configuration. // It takes 17 parameters for detailed configuration. int StartNknTunnel(const char* config_json); // CloseNknTunnel closes an existing NKN tunnel. void CloseNknTunnel(int tunnel_id); ``` -------------------------------- ### NKN Tunnel State Management (Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/c-bindings.md Illustrates the global state variables used to manage a single NKN tunnel instance in Go, including the tunnel pointer and a mutex for thread safety. ```go var ( instanceTunnel *tunnel.Tunnel // Currently running tunnel tunnelMutex sync.Mutex // Protects tunnel state ) ``` -------------------------------- ### Bidirectional Connection Piping with Goroutines Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/module-overview.md Illustrates how two goroutines are used for bidirectional forwarding, each handling data copying in one direction and managing connection closure upon error. ```go Accept A ──> Dial B │ │ └─ io.Copy ←─┘ (goroutine 1) ┌─ io.Copy ───┐ (goroutine 2) │ │ └──────────→─┘ ``` -------------------------------- ### Create a Single Tunnel Client Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/api-reference/tunnel.md Use `NewTunnel` to create a single tunnel client. It requires an NKN account, identifier, local and remote addresses, and a boolean to enable Tuna mode. Optional configuration and a shared MultiClient can be provided. ```go package main import ( "log" "github.com/nknorg/nkn-sdk-go" "github.com/nknorg/nkn-tunnel" ) func main() { // Create account from seed seed := []byte{...} // 32-byte seed account, err := nkn.NewAccount(seed) if err != nil { log.Fatal(err) } // Create tunnel: listen on TCP localhost:8081, forward to NKN address Bob config := tunnel.DefaultConfig() t, err := tunnel.NewTunnel( account, "Alice", // identifier "127.0.0.1:8081", // local TCP listen "Bob", // remote NKN address false, // not using tuna config, nil, // create new MultiClient ) if err != nil { log.Fatal(err) } // Start forwarding if err := t.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Enable UDP for Tunnel (Go) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/README.md Configure the tunnel to use UDP and set the UDP idle time. Ensure Tuna mode is enabled when using UDP. ```go config := tunnel.DefaultConfig() config.UDP = true config.UDPIdleTime = 300 t, err := tunnel.NewTunnel(account, id, from, to, true, config, nil) // tuna=true ``` -------------------------------- ### Create Tunnel (CLI) Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/README.md Create an NKN tunnel using the command-line interface. Requires your seed, and local/remote addresses. ```bash ./nkn-tunnel \ -s YOUR_SEED \ -from 127.0.0.1:8081 \ -to 127.0.0.1:8080 ``` -------------------------------- ### Configure NKN Client Behavior Source: https://github.com/nknorg/nkn-tunnel/blob/master/_autodocs/configuration.md Sets up the NKN client configuration, including RPC server addresses and NCP session settings. Useful for customizing blockchain queries and network protocol behavior. ```go config := tunnel.DefaultConfig() config.ClientConfig = &nkn.ClientConfig{ SeedRPCServerAddr: nkn.NewStringArray( "mainnet-rpc1.example.com:30003", "mainnet-rpc2.example.com:30003", ), SessionConfig: &ncp.Config{ MTU: 1500, // Maximum transmission unit }, } ```