### Serve libsignal Documentation Book with mdBook Source: https://github.com/signalapp/libsignal/blob/main/doc/src/README.md This snippet demonstrates how to serve the libsignal documentation book locally using mdBook. It requires mdBook to be installed and is executed from the 'doc' directory. The command starts a local server, typically at http://localhost:3000, and watches for file changes to automatically reload the book. ```console % mdbook serve 2025-01-21 18:05:27 [INFO] (mdbook::book): Book building has started 2025-01-21 18:05:27 [INFO] (mdbook::book): Running the html backend 2025-01-21 18:05:27 [INFO] (mdbook::cmd::serve): Serving on: http://localhost:3000 2025-01-21 18:05:27 [INFO] (mdbook::cmd::watch::poller): Watching for changes... 2025-01-21 18:05:27 [INFO] (warp::server): Server::run; addr=[::1]:3000 2025-01-21 18:05:27 [INFO] (warp::server): listening on http://[::1]:3000 ``` -------------------------------- ### Build and Test Node.js Project Source: https://github.com/signalapp/libsignal/blob/main/README.md Commands to install dependencies, build the Rust library, compile TypeScript, and run tests for the Node.js bindings. Ensure Node.js and npm are installed. ```shell $ cd node $ nvm use $ npm install $ npm run build $ npm run tsc $ npm run test ``` -------------------------------- ### Build and Test Environment Setup for LibSignalClient Source: https://github.com/signalapp/libsignal/blob/main/swift/cocoapods-testing/README.md This shell script cleans existing CocoaPods artifacts, reinstalls dependencies, and triggers an Xcode build for testing on an iOS device. It is used to verify that the library compiles correctly outside of standard automated linting processes. ```shell % rm -rf Pods Testing.xcworkspace % pod install % xcodebuild -scheme LibSignalClient -sdk iphoneos build-for-testing ``` -------------------------------- ### Canonicalize Unencrypted Backup for Testing (Pseudocode) Source: https://github.com/signalapp/libsignal/blob/main/doc/src/backups/README.md A pseudocode example demonstrating the process of canonicalizing an unencrypted backup into a JSON string for testing purposes. This format is intended for comparison and should not be persisted. ```pseudocode let comparableBackup = ComparableBackup.fromUnencryptedBackup(unencryptedBackup); let jsonString = comparableBackup.toJsonString(); ``` -------------------------------- ### Build with Docker Source: https://github.com/signalapp/libsignal/blob/main/README.md Builds the project using a Docker-based system. This is an alternative to using Gradle directly. Ensure you are in the 'java' directory. ```shell $ cd java $ make ``` -------------------------------- ### Add Android Targets to Rust Compiler Source: https://github.com/signalapp/libsignal/blob/main/README.md This command adds the necessary Android architectures as targets for the Rust compiler. Ensure you have rustup installed and configured. ```shell rustup target add armv7-linux-androideabi aarch64-linux-android i686-linux-android x86_64-linux-android ``` -------------------------------- ### Configure Java Alternatives on Debian/Ubuntu Source: https://github.com/signalapp/libsignal/blob/main/README.md Manually configures the default Java runtime on Debian-based systems like Ubuntu. This is an alternative to setting JAVA_HOME directly. ```shell sudo update-alternatives --config java ``` -------------------------------- ### Build and Test Java/Android Artifacts with Gradle Source: https://github.com/signalapp/libsignal/blob/main/README.md Commands to build the Java/Android JAR and AAR files, and run tests. Navigate to the 'java' directory first. Use './gradlew build' for AAR outputs. ```shell $ cd java $ ./gradlew test $ ./gradlew build # if you need AAR outputs ``` -------------------------------- ### Elliptic Curve Key Operations with libsignal-client Source: https://context7.com/signalapp/libsignal/llms.txt Demonstrates Ed25519/X25519 key generation, serialization, signing, verification, and Diffie-Hellman key agreement using the `@signalapp/libsignal-client` TypeScript library. It also includes an example of Hybrid Public Key Encryption (HPKE). ```typescript import * as SignalClient from '@signalapp/libsignal-client'; // Generate a new key pair const privateKey = SignalClient.PrivateKey.generate(); const publicKey = privateKey.getPublicKey(); // Serialize and deserialize keys const privateKeyBytes = privateKey.serialize(); // 32 bytes const publicKeyBytes = publicKey.serialize(); // 33 bytes (includes type prefix) const restoredPrivate = SignalClient.PrivateKey.deserialize(privateKeyBytes); const restoredPublic = SignalClient.PublicKey.deserialize(publicKeyBytes); // Sign and verify messages const message = Buffer.from('Hello, Signal!', 'utf8'); const signature = privateKey.sign(message); // 64-byte signature const isValid = publicKey.verify(message, signature); // true // Diffie-Hellman key agreement const alicePrivate = SignalClient.PrivateKey.generate(); const bobPrivate = SignalClient.PrivateKey.generate(); const sharedSecretA = alicePrivate.agree(bobPrivate.getPublicKey()); const sharedSecretB = bobPrivate.agree(alicePrivate.getPublicKey()); // sharedSecretA equals sharedSecretB // HPKE (Hybrid Public Key Encryption) - RFC 9180 const plaintext = Uint8Array.of(11, 22, 33, 44); const sealed = publicKey.seal(plaintext, 'context-info', Uint8Array.of(1, 2, 3)); const opened = privateKey.open(sealed, 'context-info', Uint8Array.of(1, 2, 3)); ``` -------------------------------- ### Run Tests in Swift Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Generates the Foreign Function Interface (FFI) for Swift and then executes Swift tests. This process ensures the integration between Rust and Swift is working as expected. ```shell # Swift % ./build_ffi.sh --generate-ffi && swift test ``` -------------------------------- ### Network Operations and Chat Connections in TypeScript Source: https://context7.com/signalapp/libsignal/llms.txt Provides high-level networking for connecting to Signal's servers, enabling authenticated chat, CDSI lookups, and registration. It requires the '@signalapp/libsignal-client' module. The module allows configuration of network settings, proxy setup, and handling of chat connections with callbacks for message reception and connection interruptions. ```typescript import * as SignalClient from '@signalapp/libsignal-client'; // Create network instance const net = new SignalClient.Net.Net({ env: SignalClient.Net.Environment.Production, userAgent: 'MyApp/1.0' }); // Configure network settings net.setIpv6Enabled(true); net.setCensorshipCircumventionEnabled(false); // Set up proxy (optional) net.setProxy({ scheme: 'socks5', host: 'localhost', port: 1080 }); // Or Signal TLS proxy net.setProxy('proxy.example.com', 443); // Connect authenticated chat const chatConnection = await net.connectAuthenticatedChat( username, password, true, // receiveStories { onConnectionInterrupted(cause) { console.log('Connection interrupted:', cause); }, onIncomingMessage(envelope, timestamp, ack) { console.log('Received message at', timestamp); ack(); }, onQueueEmpty() { console.log('Message queue empty'); } }, { languages: ['en-US', 'es'] } ); // Send request over chat connection const response = await chatConnection.send({ verb: 'GET', path: '/v1/profile/ப்புகளை', headers: [['Accept', 'application/json']], timeoutMillis: 30000 }); // CDSI lookup (Contact Discovery Service) const cdsiResult = await net.cdsiLookup( { username: 'user', password: 'pass' }, { e164s: ['+14155551234', '+14155555678'], acisAndAccessKeys: [], prevE164s: [] } ); // Registration session const registrationService = await net.createRegistrationSession({ e164: '+14155551234' }); ``` -------------------------------- ### Configure Rust Benchmarks for ARM64 AES Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Enables hardware acceleration for AES encryption on ARM64 devices during Rust benchmarks. This flag should be set via RUSTFLAGS to improve performance. ```shell RUSTFLAGS="--cfg aes_armv8" ``` -------------------------------- ### Set JAVA_HOME for JDK 17 on macOS Source: https://github.com/signalapp/libsignal/blob/main/README.md Configures the JAVA_HOME environment variable to point to JDK 17 on macOS. This is required for Android builds. ```shell export JAVA_HOME=$(/usr/libexec/java_home -v 17) ``` -------------------------------- ### Validate Message Backups with libsignal-client Source: https://context7.com/signalapp/libsignal/llms.txt Demonstrates how to initialize backup keys from entropy or raw bytes and perform both batch and online frame-by-frame validation of encrypted backup files. ```typescript import * as SignalClient from '@signalapp/libsignal-client'; import { MessageBackupKey, Purpose, validate } from '@signalapp/libsignal-client'; import { Aci } from '@signalapp/libsignal-client'; const backupKey = new MessageBackupKey({ accountEntropy: 'abcdefghijklmnopqrstuvwxyz0123456789...', aci: Aci.fromUuid('9d0652a3-dcc3-4d11-975f-74d61598733f') }); const outcome = await validate( backupKey, Purpose.RemoteBackup, () => createInputStream(file), BigInt(fileSize) ); if (outcome.ok) { console.log('Backup is valid'); } else { console.error('Validation error:', outcome.errorMessage); } ``` -------------------------------- ### Configure Rust Benchmarks for SHA-2 Assembly Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Enables assembly optimizations for the SHA-2 crate during Rust benchmarks. This feature improves SHA-2 performance and is often enabled by default in specific crates. ```shell --features sha2/asm ``` -------------------------------- ### Accessing Typed APIs for Chat Services Source: https://github.com/signalapp/libsignal/blob/main/doc/src/net/chat.md Demonstrates how to utilize high-level typed service APIs to perform requests like username lookups. These implementations abstract the underlying transport layer, providing platform-specific patterns for Android, iOS, and Desktop. ```kotlin val usernamesService = UnauthUsernamesService(chatConnection) val response = usernamesService.lookUpUsernameHash(hash).get() // or await() ``` ```swift try await accessService(chatConnection, as: .usernames) { usernamesService in let response = try await usernamesService.lookUpUsernameHash(hash) } ``` ```typescript const service = connectionManager.accessUnauthService(); const response = await service.lookUpUsernameHash(hash); ``` -------------------------------- ### Run Cross-Compiled Rust Tests on Android Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Executes Rust tests on an Android target using cross-compilation. This command requires the environment variables for the Android toolchain and runner to be set beforehand. ```shell cargo test --target aarch64-linux-android -p PACKAGE ``` -------------------------------- ### Set Environment Variables for Android Rust Testing Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Configures the necessary environment variables for cross-compiling and running Rust tests on Android devices or emulators. This includes setting the NDK home, linker, and a custom test runner. ```shell ANDROID_NDK_HOME=path/to/ndk CARGO_PROFILE_TEST_STRIP=debuginfo CARGO_PROFILE_BENCH_STRIP=debuginfo CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=path/to/ndk/toolchains/llvm/prebuilt/YOUR_HOST_HERE/bin/aarch64-linux-android23-clang CARGO_TARGET_AARCH64_LINUX_ANDROID_RUNNER=bin/adb-run-test ``` -------------------------------- ### Run Cross-Compiled Rust Tests on iOS Simulator Source: https://github.com/signalapp/libsignal/blob/main/TESTING.md Executes Rust tests on an iOS simulator target using cross-compilation. This command requires the environment variable for the simulator runner to be set beforehand. ```shell cargo test --target aarch64-apple-ios-sim -p PACKAGE ```