### Configure REALITY Server with Go Source: https://context7.com/xtls/reality/llms.txt Demonstrates how to configure and start a REALITY server using the Go library. This includes setting up network dialers, target destinations, authentication keys, client validation parameters, and rate limiting. It requires a valid X25519 private key and specifies accepted server names and client versions. ```go package main import ( "context" "encoding/hex" "net" "time" reality "github.com/xtls/reality" ) func main() { // Generate or load your X25519 private key (32 bytes) privateKey, _ := hex.DecodeString("your_64_char_hex_private_key_here") config := &reality.Config{ // Network dial function for connecting to target DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, // Debug output Show: true, // Target website configuration Type: "tcp", Dest: "example.com:443", // PROXY protocol version (0=disabled, 1=v1, 2=v2) Xver: 0, // Accepted SNI values from clients ServerNames: map[string]bool{ "example.com": true, "www.example.com": true, }, // X25519 private key for authentication PrivateKey: privateKey, // Optional client version constraints (format: x.y.z as 3 bytes) MinClientVer: []byte{1, 8, 0}, MaxClientVer: []byte{2, 0, 0}, // Maximum allowed time difference (0 = disabled) MaxTimeDiff: 2 * time.Minute, // Accepted short IDs for client differentiation ShortIds: map[[8]byte]bool{ [8]byte{}: true, // empty allowed [8]byte{0x01, 0x23, 0x45, 0x67, 0x89}: true, }, // Rate limiting for fallback connections LimitFallbackUpload: reality.LimitFallback{ AfterBytes: 1024 * 1024, // Start after 1MB BytesPerSec: 10240, // 10KB/s base BurstBytesPerSec: 51200, // 50KB/s burst }, LimitFallbackDownload: reality.LimitFallback{ AfterBytes: 1024 * 1024, BytesPerSec: 10240, BurstBytesPerSec: 51200, }, } // Start listening listener, err := reality.Listen("tcp", ":443", config) if err != nil { panic(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { continue } go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() // Handle the REALITY connection buf := make([]byte, 4096) for { n, err := conn.Read(buf) if err != nil { return } conn.Write(buf[:n]) } } ``` -------------------------------- ### Configure Post-Quantum Cryptography Server in Go Source: https://context7.com/xtls/reality/llms.txt Demonstrates how to initialize a REALITY server with ML-KEM-768 key encapsulation and ML-DSA-65 certificate signatures. This setup ensures quantum-resistant communication by providing a seed for post-quantum signatures within the configuration. ```go package main import ( "context" "encoding/hex" "net" reality "github.com/xtls/reality" ) func main() { privateKey, _ := hex.DecodeString("your_x25519_private_key_hex") // ML-DSA-65 seed for post-quantum certificate signatures // Generate with: ./xray mldsa65 mldsa65Seed, _ := hex.DecodeString("your_mldsa65_seed_hex") config := &reality.Config{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, Type: "tcp", Dest: "example.com:443", ServerNames: map[string]bool{"example.com": true}, PrivateKey: privateKey, ShortIds: map[[8]byte]bool{[8]byte{}: true}, // Enable ML-DSA-65 post-quantum signatures Mldsa65Key: mldsa65Seed, } listener, _ := reality.Listen("tcp", ":443", config) defer listener.Close() for { conn, _ := listener.Accept() go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() } ``` -------------------------------- ### Dial TLS Connections with REALITY in Go Source: https://context7.com/xtls/reality/llms.txt Provides examples of using the Dial, DialWithDialer, and Dialer struct methods to establish TLS connections. These methods simplify the process of connecting to a server with custom network configurations. ```go package main import ( "crypto/x509" "fmt" "net" "time" reality "github.com/xtls/reality" ) func main() { config := &reality.Config{ ServerName: "example.com", InsecureSkipVerify: false, RootCAs: x509.NewCertPool(), MinVersion: reality.VersionTLS13, } conn1, err := reality.Dial("tcp", "example.com:443", config) if err != nil { panic(err) } defer conn1.Close() dialer := &net.Dialer{ Timeout: 10 * time.Second, KeepAlive: 30 * time.Second, } conn2, err := reality.DialWithDialer(dialer, "tcp", "example.com:443", config) if err != nil { panic(err) } defer conn2.Close() tlsDialer := &reality.Dialer{ NetDialer: &net.Dialer{ Timeout: 5 * time.Second, }, Config: config, } conn3, err := tlsDialer.Dial("tcp", "example.com:443") if err != nil { panic(err) } defer conn3.Close() fmt.Println("All connections established successfully") } ``` -------------------------------- ### Establish TLS Client Connection in Go Source: https://context7.com/xtls/reality/llms.txt Shows how to create a TLS client connection using the REALITY library. It covers configuring the client, performing the handshake, and inspecting the connection state. ```go package main import ( "crypto/x509" "fmt" "net" reality "github.com/xtls/reality" ) func main() { rawConn, err := net.Dial("tcp", "example.com:443") if err != nil { panic(err) } config := &reality.Config{ ServerName: "example.com", RootCAs: x509.NewCertPool(), MinVersion: reality.VersionTLS12, MaxVersion: reality.VersionTLS13, NextProtos: []string{"h2", "http/1.1"}, } tlsConn := reality.Client(rawConn, config) if err := tlsConn.Handshake(); err != nil { panic(err) } state := tlsConn.ConnectionState() fmt.Printf("TLS Version: %s\n", reality.VersionName(state.Version)) fmt.Printf("Cipher Suite: %x\n", state.CipherSuite) fmt.Printf("Server Name: %s\n", state.ServerName) fmt.Printf("ALPN Protocol: %s\n", state.NegotiatedProtocol) tlsConn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")) buf := make([]byte, 4096) n, _ := tlsConn.Read(buf) fmt.Println(string(buf[:n])) tlsConn.Close() } ``` -------------------------------- ### Initialize REALITY listener with convenience wrapper in Go Source: https://context7.com/xtls/reality/llms.txt The Listen function provides a streamlined way to initialize both the underlying TCP listener and the REALITY protocol wrapper in one step. It is ideal for standard server implementations requiring minimal boilerplate. ```go package main import ( "context" "encoding/hex" "net" "time" reality "github.com/xtls/reality" ) func main() { privateKey, _ := hex.DecodeString("your_private_key_hex") config := &reality.Config{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, Type: "tcp", Dest: "cloudflare.com:443", ServerNames: map[string]bool{"cloudflare.com": true}, PrivateKey: privateKey, ShortIds: map[[8]byte]bool{ [8]byte{}: true, [8]byte{0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x9a}: true, }, MaxTimeDiff: 5 * time.Minute, } listener, err := reality.Listen("tcp", ":443", config) if err != nil { panic(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { return } go func(c net.Conn) { defer c.Close() }(conn) } } ``` -------------------------------- ### REALITY/TLS Connection Metadata and State (Go) Source: https://context7.com/xtls/reality/llms.txt Demonstrates how to use the `reality.Conn` type to access REALITY-specific client information, TLS connection state, network addresses, and set connection deadlines. It also shows how to export keying material and perform basic read/write operations. The underlying `net.Conn` can be accessed but should be used with caution. ```go package main import ( "context" "encoding/hex" "fmt" "net" reality "github.com/xtls/reality" ) func handleConnection(conn *reality.Conn) { defer conn.Close() // Access REALITY-specific client information fmt.Printf("Auth Key: %x\n", conn.AuthKey[:16]) fmt.Printf("Client Version: %d.%d.%d\n", conn.ClientVer[0], conn.ClientVer[1], conn.ClientVer[2]) fmt.Printf("Client Time: %v\n", conn.ClientTime) fmt.Printf("Client Short ID: %x\n", conn.ClientShortId) // Get TLS connection state state := conn.ConnectionState() fmt.Printf("TLS Version: %s\n", reality.VersionName(state.Version)) fmt.Printf("Cipher Suite: 0x%04x\n", state.CipherSuite) fmt.Printf("Handshake Complete: %v\n", state.HandshakeComplete) fmt.Printf("Server Name: %s\n", state.ServerName) fmt.Printf("ALPN Protocol: %s\n", state.NegotiatedProtocol) fmt.Printf("Did Resume: %v\n", state.DidResume) // Access network addresses fmt.Printf("Local Address: %v\n", conn.LocalAddr()) fmt.Printf("Remote Address: %v\n", conn.RemoteAddr()) // Get underlying connection (use with caution) underlyingConn := conn.NetConn() _ = underlyingConn // Set deadlines conn.SetDeadline(time.Now().Add(30 * time.Second)) conn.SetReadDeadline(time.Now().Add(10 * time.Second)) conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) // Export keying material (TLS 1.3) ekm, err := state.ExportKeyingMaterial("my-app", nil, 32) if err == nil { fmt.Printf("Exported Key Material: %x\n", ekm) } // Read/Write data buf := make([]byte, 4096) n, _ := conn.Read(buf) conn.Write(buf[:n]) } ``` -------------------------------- ### Create authenticated REALITY listeners in Go Source: https://context7.com/xtls/reality/llms.txt The NewListener function wraps an existing net.Listener to automatically handle protocol negotiation. It ensures that only authenticated REALITY connections are accepted by the application. ```go package main import ( "context" "encoding/hex" "net" reality "github.com/xtls/reality" ) func main() { privateKey, _ := hex.DecodeString("your_private_key_hex") config := &reality.Config{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, Type: "tcp", Dest: "www.google.com:443", ServerNames: map[string]bool{"www.google.com": true}, PrivateKey: privateKey, ShortIds: map[[8]byte]bool{[8]byte{}: true}, } tcpListener, _ := net.Listen("tcp", ":443") realityListener := reality.NewListener(tcpListener, config) defer realityListener.Close() for { conn, err := realityListener.Accept() if err != nil { break } go handleConnection(conn.(*reality.Conn)) } } func handleConnection(conn *reality.Conn) { defer conn.Close() } ``` -------------------------------- ### Load X.509 Certificates for TLS (Go) Source: https://context7.com/xtls/reality/llms.txt Provides functions `LoadX509KeyPair` and `X509KeyPair` to load TLS certificates and private keys from files or PEM-encoded byte slices. The loaded certificates can be used to configure standard TLS connections. The `Leaf` field of the returned `Certificate` struct contains the parsed certificate. ```go package main import ( "crypto/x509" "fmt" reality "github.com/xtls/reality" ) func main() { // Load certificate and key from files cert, err := reality.LoadX509KeyPair("server.crt", "server.key") if err != nil { panic(err) } fmt.Printf("Certificate loaded: %d bytes\n", len(cert.Certificate[0])) fmt.Printf("Has Leaf: %v\n", cert.Leaf != nil) // Load from PEM data certPEM := []byte(`-----BEGIN CERTIFICATE----- MIIBkTCB+wIJAKHBfpf... -----END CERTIFICATE-----`) keyPEM := []byte(`-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqh... -----END PRIVATE KEY-----`) cert2, err := reality.X509KeyPair(certPEM, keyPEM) if err != nil { panic(err) } // Use in Config for standard TLS (not REALITY mode) config := &reality.Config{ Certificates: []reality.Certificate{cert, cert2}, ClientAuth: reality.RequireAndVerifyClientCert, ClientCAs: x509.NewCertPool(), } _ = config } ``` -------------------------------- ### Manage TLS Version Constants Source: https://context7.com/xtls/reality/llms.txt Provides constants for TLS versions and a helper function to resolve version names. Essential for configuring minimum and maximum protocol versions in the REALITY configuration. ```go package main import ( "fmt" reality "github.com/xtls/reality" ) func main() { versions := []uint16{ reality.VersionTLS10, reality.VersionTLS11, reality.VersionTLS12, reality.VersionTLS13, } for _, v := range versions { fmt.Printf("0x%04x: %s\n", v, reality.VersionName(v)) } config := &reality.Config{ MinVersion: reality.VersionTLS12, MaxVersion: reality.VersionTLS13, } _ = config } ``` -------------------------------- ### TLS Session Cache for Resumption (Go) Source: https://context7.com/xtls/reality/llms.txt Demonstrates the use of `NewLRUClientSessionCache` to create a Least Recently Used (LRU) session cache. This cache helps reduce TLS handshake latency for clients that reconnect by enabling session resumption. The cache capacity can be customized. ```go package main import ( "crypto/x509" "fmt" "net" "time" reality "github.com/xtls/reality" ) func main() { // Create session cache with custom capacity sessionCache := reality.NewLRUClientSessionCache(128) config := &reality.Config{ ServerName: "example.com", RootCAs: x509.NewCertPool(), ClientSessionCache: sessionCache, MinVersion: reality.VersionTLS13, } // First connection - full handshake conn1, _ := reality.Dial("tcp", "example.com:443", config) state1 := conn1.ConnectionState() fmt.Printf("First connection - Resumed: %v\n", state1.DidResume) conn1.Close() // Wait a moment time.Sleep(100 * time.Millisecond) // Second connection - should resume conn2, _ := reality.Dial("tcp", "example.com:443", config) state2 := conn2.ConnectionState() fmt.Printf("Second connection - Resumed: %v\n", state2.DidResume) conn2.Close() } ``` -------------------------------- ### Configure Curve and Key Exchange Source: https://context7.com/xtls/reality/llms.txt Defines supported elliptic curves and key exchange mechanisms, including post-quantum hybrid algorithms. Allows setting preferences for cryptographic handshakes. ```go package main import ( "fmt" reality "github.com/xtls/reality" ) func main() { curves := []reality.CurveID{ reality.CurveP256, reality.CurveP384, reality.CurveP521, reality.X25519, reality.X25519MLKEM768, } for _, c := range curves { fmt.Printf("CurveID %d: %s\n", c, c.String()) } config := &reality.Config{ CurvePreferences: []reality.CurveID{ reality.X25519MLKEM768, reality.X25519, reality.CurveP256, }, } _ = config } ``` -------------------------------- ### Implement Rate-Limited Connections Source: https://context7.com/xtls/reality/llms.txt Wraps a network connection with rate limiting to control bandwidth usage. Useful for fallback connections to prevent abuse by limiting bytes per second and burst capacity. ```go package main import ( "io" "net" "time" reality "github.com/xtls/reality" ) func main() { rawConn, _ := net.Dial("tcp", "example.com:80") limit := &reality.LimitFallback{ AfterBytes: 1024, BytesPerSec: 4096, BurstBytesPerSec: 8192, } limitedConn := reality.NewRatelimitedConn(rawConn, limit) buf := make([]byte, 65536) start := time.Now() total := 0 for { n, err := limitedConn.Read(buf) if err != nil { break } total += n if total >= 10240 { break } } elapsed := time.Since(start) rate := float64(total) / elapsed.Seconds() println("Transfer rate:", int(rate), "bytes/sec") limitedConn.Close() } ``` -------------------------------- ### Wrap raw connections with REALITY protocol in Go Source: https://context7.com/xtls/reality/llms.txt The Server function authenticates incoming raw TCP connections against a REALITY configuration. It returns an authenticated connection or forwards traffic to a target destination if authentication fails. ```go package main import ( "context" "encoding/hex" "fmt" "net" reality "github.com/xtls/reality" ) func main() { privateKey, _ := hex.DecodeString("your_private_key_hex") config := &reality.Config{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, Type: "tcp", Dest: "example.com:443", ServerNames: map[string]bool{"example.com": true}, PrivateKey: privateKey, ShortIds: map[[8]byte]bool{[8]byte{}: true}, Show: true, } reality.DetectPostHandshakeRecordsLens(config) listener, _ := net.Listen("tcp", ":443") defer listener.Close() for { rawConn, err := listener.Accept() if err != nil { continue } go func(raw net.Conn) { conn, err := reality.Server(context.Background(), raw, config) if err != nil { fmt.Printf("REALITY: %v\n", err) return } defer conn.Close() fmt.Printf("Client Version: %v\n", conn.ClientVer) handleSecureConnection(conn) }(rawConn) } } func handleSecureConnection(conn *reality.Conn) { buf := make([]byte, 4096) for { n, err := conn.Read(buf) if err != nil { return } conn.Write(buf[:n]) } } ``` -------------------------------- ### Detect Post-Handshake TLS Records Source: https://context7.com/xtls/reality/llms.txt Probes a target server to identify post-handshake TLS record patterns. This data allows the REALITY protocol to mimic the target server's behavior accurately. ```go package main import ( "context" "encoding/hex" "net" "time" reality "github.com/xtls/reality" ) func main() { privateKey, _ := hex.DecodeString("your_private_key_hex") config := &reality.Config{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { return net.Dial(network, address) }, Type: "tcp", Dest: "www.google.com:443", ServerNames: map[string]bool{ "www.google.com": true, "google.com": true, }, PrivateKey: privateKey, ShortIds: map[[8]byte]bool{[8]byte{}: true}, } reality.DetectPostHandshakeRecordsLens(config) time.Sleep(10 * time.Second) key := config.Dest + " www.google.com 2" if val, ok := reality.GlobalPostHandshakeRecordsLens.Load(key); ok { if lens, ok := val.([]int); ok { println("Post-handshake record lengths:", lens) } } listener, _ := reality.Listen("tcp", ":443", config) defer listener.Close() } ``` -------------------------------- ### Xray-core Server Inbound Configuration with VLESS-XTLS-uTLS-REALITY Source: https://github.com/xtls/reality/blob/main/README.en.md This JSON configuration sets up the server's inbound listener for VLESS protocol using XTLS and REALITY security. It specifies ports, client configurations including UUID and flow, and detailed REALITY settings like target, server names, private key, and short IDs for enhanced security and traffic obfuscation. ```json { "inbounds": [ { "listen": "0.0.0.0", "port": 443, "protocol": "vless", "settings": { "clients": [ { "id": "", "flow": "xtls-rprx-vision" } ], "decryption": "none" }, "streamSettings": { "network": "raw", "security": "reality", "realitySettings": { "show": false, "target": "example.com:443", "xver": 0, "serverNames": [ "example.com", "www.example.com" ], "privateKey": "", "minClientVer": "", "maxClientVer": "", "maxTimeDiff": 0, "shortIds": [ "", "0123456789abcdef" ], "mldsa65Seed": "", "limitFallbackUpload": { "afterBytes": 0, "bytesPerSec": 0, "burstBytesPerSec": 0 }, "limitFallbackDownload": { "afterBytes": 0, "bytesPerSec": 0, "burstBytesPerSec": 0 } } } } ] } ``` -------------------------------- ### Xray-core Client Outbound Configuration for VLESS Source: https://github.com/xtls/reality/blob/main/README.en.md This JSON snippet outlines the client's outbound configuration for the VLESS protocol. It is a partial configuration, typically used in conjunction with other settings to establish a connection to a VLESS server, specifying the remote server address and port. ```json { "outbounds": [ { "protocol": "vless", "settings": { "vnext": [ { "address": "your_server_address", "port": 443, "users": [ { "id": "your_client_uuid", "flow": "xtls-rprx-vision", "encryption": "none" } ] } ] }, "streamSettings": { "network": "raw", "security": "reality", "realitySettings": { "handshakePath": "/your_reality_path", "serverName": "your_server_name", "privateKey": "your_client_private_key", "shortIds": [ "your_short_id" ], "spiderX": "your_sni" } } } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.