Nostrino is a Nostr SDK for Kotlin, providing a multiplatform implementation of the Nostr protocol. The project implements various NIPs (Nostr Implementation Possibilities) and is used by Block/CashApp for Nostr-based features. Nostrino supports JVM, iOS, and Linux platforms.
Read this when a service or app needs Nostr or Buzz, not only when working on Nostrino itself.
- On the JVM or in Kotlin, use Nostrino for all Nostr work: keys, event ids and signatures, NIP-98 HTTP auth, NIP-44
encryption and relays. Use
nostr-sdk-buzz(BuzzClient) to post to Buzz. - Do not hand-roll NIP-01 id hashing, Schnorr event signing or
Authorization: Nostrheaders. The id preimage must match the relay's serialization byte for byte, and default Moshi and Jackson settings get it wrong for some content (for example U+2028 and U+2029). - If Nostrino lacks something a caller needs, add it to Nostrino rather than working around it in the caller. Standard
NIPs go in
lib, and Buzz-specific behaviour goes inbuzz. - See README.md for usage examples.
- Language: Kotlin (Multiplatform)
- Build System: Gradle with Kotlin DSL
- Java Version: JVM 11
- Test Framework: JUnit 5 (Jupiter) + Kotest
- Platforms: JVM, iOS (x64, ARM64, Simulator ARM64), Linux x64
- Key Dependencies:
- OkHttp (HTTP client for JVM)
- Moshi (JSON)
- acinq secp256k1 (Cryptographic curves)
- Kotlinx Coroutines (Asynchronous programming)
- OkIO (I/O operations)
- Kotest (Testing and assertions)
- Turbine (Flow testing)
This project uses Hermit for consistent tooling. Activate it with:
. ./bin/activate-hermitIMPORTANT: This project uses Hermit. Always use bin/gradle instead of gradlew or gradle.
# Build the entire project (includes tests)
bin/gradle build
# Run tests only
bin/gradle test
# Clean build
bin/gradle clean build
# Check for API breaking changes (binary compatibility)
bin/gradle apiCheck
# Generate new API dumps after API changes
bin/gradle apiDump
# Check for dependency updates
bin/gradle dependencyUpdates -Drevision=release
# Update version catalog
bin/gradle versionCatalogUpdate
# Generate API documentation
bin/gradle dokkaHtmlnostrino/
├── lib/ # Main SDK library (multiplatform)
│ └── src/
│ ├── commonMain/kotlin/ # Platform-agnostic code
│ └── jvmMain/kotlin/ # JVM-specific code
├── lib-test/ # Testing utilities and integration tests
│ └── src/
│ ├── main/kotlin/ # Test helpers and Arb generators
│ └── test/kotlin/ # Integration tests
├── buzz/ # Buzz-specific client (JVM)
│ └── src/
│ ├── main/kotlin/ # BuzzClient and BuzzChannel
│ └── test/kotlin/ # Tests against the Buzz relay in Docker
├── buildSrc/ # Build configuration
└── gradle/ # Gradle wrapper and version catalog
└── libs.versions.toml # Dependency versions
- Indentation: 2 spaces (NOT tabs)
- Line Length: Maximum 120 characters
- Line Endings: LF (Unix-style)
- Charset: UTF-8
- Final Newline: Always insert
- Copyright Headers: Required for all new files. Always use the current year (2025) in the copyright year field, not the project start year (2023)
- Imports: No wildcard imports (use explicit imports)
ij_kotlin_name_count_to_use_star_import = 2147483647ij_kotlin_name_count_to_use_star_import_for_members = 2147483647
- Naming: Follow standard Kotlin conventions
- Null Safety: Leverage Kotlin's null safety features
- Function Syntax: Prefer expression syntax over block body. Avoid early returns when possible
- ✅
fun add(a: Int, b: Int): Int = a + b - ✅
fun isValid(x: Int): Boolean = x > 0 - ❌
fun add(a: Int, b: Int): Int { return a + b }
- ✅
- Parameters: Wrap on every item with proper formatting
- Method parameters: new line after
(, right paren on new line - Call parameters: new line after
(, right paren on new line
- Method parameters: new line after
- Code Style: Follow Kotlin official code style
Nostrino follows the Sociable Unit Testing approach for comprehensive, resilient test coverage.
Core Principle: Write unit tests for all classes, but let them connect through to real dependencies until hitting the system boundary.
- ✅ Real object graphs: Classes use their actual dependencies (services, stores, validators)
- ✅ Fake external services: Only external APIs and services are faked at system boundaries
- ✅ Fast execution: Still runs quickly despite using real components
- ✅ Less brittle: No need to update mocks when internal implementations change
System Boundaries (what gets faked or containerised):
- External relay servers: use
FakeRelayfor unit tests, and the Docker relays for integration tests - Nostr relay connections
- HTTP relay APIs (such as Buzz's
/events): always the real Buzz relay in Docker, never a mock server
Benefits over traditional mock-based testing:
- Tests behavior, not implementation details
- Resilient to refactoring
- Real integration confidence
- Simpler test setup
- Framework: JUnit 5 (Jupiter) + Kotest - configured in root
build.gradle.kts - Test Style: ALWAYS use Kotest StringSpec (test names in strings)
- Assertions: Use Kotest matchers (
shouldBe,shouldBeEqual,shouldContainExactly, etc.) - NOT JUnit assertions - Test Naming: Test class suffix is
Test(e.g.,RelaySetTest.kt) - Test Names: Use string literals for readable test names (StringSpec style)
- Integration Tests: Use the Docker relays that start before the tests that need them:
- nostr-rs-relay at
ws://localhost:7707, started bylib-test, for NIP-01 websocket traffic - a second nostr-rs-relay with NIP-42 auth enabled at
ws://localhost:7710, also started bylib-test, which sends anAUTHchallenge on connect - the Buzz relay (
ghcr.io/block/buzz, with Postgres and Redis, frombuzz/buzz-relay.compose.yml), started bybuzz, athttp://localhost:7708, for Buzz's HTTP API - a second Buzz relay from the same file, with closed membership, at
http://localhost:7709, owned by the key whose secret is 1, for NIP-OA owner attestation
- nostr-rs-relay at
- Never use MockWebServer: Do not use MockWebServer, or any other mock HTTP server, in tests. Test HTTP clients against the real relay in Docker, so the tests prove what the relay accepts. Keep Docker image tags pinned to a released version, and update them when the relay releases
- Mocking: Use fake implementations (e.g.,
FakeRelay) for external system boundaries, not internal dependencies - Test Data Generation: Prefer
Arb<T>generators over hard-coded values. Compose existingArbgenerators for new types- Located in
lib-test/src/main/kotlin(e.g.,ArbEvent.kt,ArbPubKey.kt) - Use
Arb.next()to generate single values - Use
checkAll()for property-based testing
- Located in
- Flow Testing: Use Turbine for testing Kotlin Flows
- Assertion Style: Use Kotest matchers for clean, expressive assertions
// Simple unit test with Kotest StringSpec
class RelaySetTest : StringSpec({
"delegates start" {
val set = RelaySet(
setOf(FakeRelay(), FakeRelay(), FakeRelay())
)
set.start()
set.relays.map { it as FakeRelay }.map { it.started } shouldBe listOf(true, true, true)
}
"merge distinct events into a single flow" {
val events = Arb.list(arbEvent, 20..20).next().distinct().take(6)
val set = RelaySet(
setOf(
FakeRelay(events.take(2).toMutableList()),
FakeRelay(events.drop(2).take(2).toMutableList()),
FakeRelay(events.drop(4).take(2).toMutableList())
)
)
set.subscribe(Filter.globalFeedNotes)
set.allEvents.toList() shouldContainExactly events
}
})
// Fake implementation for testing (defined in same file as tests)
class FakeRelay(val sent: MutableList<Event> = mutableListOf()) : Relay() {
var started = false
override fun start() {
started = true
}
var stopped = false
override fun stop() {
stopped = true
}
override fun send(event: Event) {
sent.add(event)
}
val subscriptions = mutableMapOf<Subscription, Set<Filter>>()
override fun subscribe(filters: Set<Filter>, subscription: Subscription): Subscription =
subscription.also {
subscriptions[subscription] = filters
}
val unsubscriptions = mutableSetOf<Subscription>()
override fun unsubscribe(subscription: Subscription) {
unsubscriptions.add(subscription)
}
override val relayMessages: Flow<RelayMessage> =
sent.asSequence()
.zip(arbSubscriptionId.samples())
.map { (event, id) -> EventMessage(id.value, event) }
.asFlow()
override val allEvents: Flow<Event> = sent.asFlow()
}- Use real dependencies - Let controllers use real stores, validators, etc.
- Fake at boundaries - Only fake external relay servers, and never with a mock HTTP server
- Test both paths - Write tests for success and failure cases
- Use property-based testing - Leverage Kotest's
Arbgenerators andcheckAll()for comprehensive coverage - Avoid redundant comments - Let test names be descriptive. Never add AAA (Arrange/Act/Assert) comments
- Prefer brevity - Keep tests concise and to the point
- Independent tests - Each test creates its own test data
- Property-based test data - Use Kotest's
Arbgenerators where applicable - Add relay integration tests - When implementing new NIPs or message exchanges, add integration tests in
RelayClientTest.ktthat connect to the real Docker relay atws://localhost:7707to verify end-to-end functionality
Nostrino is a Kotlin Multiplatform project. When making changes:
- Platform-specific code: Place in appropriate source sets (
jvmMain,commonMain, etc.) - Common code first: Prefer platform-agnostic implementations in
commonMain - Platform implementations: Use
expect/actualpattern when platform-specific implementations are required - Dependencies: Check platform compatibility of dependencies
- Testing: Focus integration tests in
lib-test(JVM-only), unit tests can be inlib
The project uses the Kotlin Binary Compatibility Validator to prevent unintentional API changes.
- API changes: Run
bin/gradle apiDumpafter making intentional API changes - Before committing: Always run
bin/gradle apiCheckto verify no unintentional breaking changes - API files: Commit
.apifiles alongside code changes - Breaking changes: Avoid removals and additions in the same change to prevent downstream compatibility issues
Main SDK library implementing Nostr protocol functionality. Contains multiplatform code for:
- Event creation and validation
- Cryptographic operations (signing, encryption)
- Relay communication
- Message encoding/decoding
- Filter construction
Testing utilities and integration tests. Contains:
- Arb generators for test data (
ArbEvent,ArbPubKey, etc.) - Fake implementations (
FakeRelay) - Integration tests against real relay server
- Docker-based relay setup for testing (nostr-rs-relay)
Client for Buzz, published as nostr-sdk-buzz. Contains:
BuzzClientandBuzzChannel, for Buzz's HTTP API- Tests against the Buzz relay stack in Docker
- Buzz-specific behaviour belongs here, not in
lib. Standard NIPs that Buzz uses (such as NIP-29 and NIP-98) stay inlib
The project is published to Maven Central:
- Group:
app.cash.nostrino - License: Apache License 2.0
- Repository: https://github.com/block/nostrino
- Documentation: https://cashapp.github.io/nostrino
- Code Style: Follow the
.editorconfigsettings (automatically enforced by IntelliJ IDEA) - Testing: All new features must include comprehensive tests
- Binary Compatibility: Run
bin/gradle apiCheckbefore committing; usebin/gradle apiDumpfor intentional API changes - No Warnings: Compiler is configured with
allWarningsAsErrors = true - Multiplatform: Ensure changes work across all target platforms when possible
- Documentation: Update module documentation and KDoc comments for public APIs
- Build Verification: Always run
bin/gradle buildbefore committing to ensure tests pass - Dependencies: Check existing dependencies before adding new ones
- Licensing: New runtime dependencies must be licensed with Apache 2.0, MIT, BSD, ISC, or Creative Commons Attribution (test & build dependencies can be more flexible)
- Never add wildcard imports - use explicit imports for all Kotlin files
- Use Kotest for assertions, not JUnit assertions
- Use StringSpec style for test classes with string-based test names
- Use Arb generators for test data instead of hard-coded values
- Check
.editorconfigbefore making formatting decisions - All tests use JUnit 5 (Jupiter) with Kotest - configured in root
build.gradle.kts - Binary compatibility matters - always run
bin/gradle apiCheckbefore committing - Multiplatform project - be mindful of platform-specific vs common code placement
- No compiler warnings allowed -
allWarningsAsErrors = trueis set
@ai-rules/issue-tracking.md
When ending a work session, you MUST complete ALL steps below. Work is NOT complete until git push succeeds.
MANDATORY WORKFLOW:
- File issues for remaining work - Create issues for anything that needs follow-up
- Run quality gates (if code changed) - Tests, linters, builds
- Update issue status - Close finished work, update in-progress items
- PUSH TO REMOTE - This is MANDATORY:
git pull --rebase bd sync git push git status # MUST show "up to date with origin" - Clean up - Clear stashes, prune remote branches
- Verify - All changes committed AND pushed
- Hand off - Provide context for next session
CRITICAL RULES:
- Work is NOT complete until
git pushsucceeds - NEVER stop before pushing - that leaves work stranded locally
- NEVER say "ready to push when you are" - YOU must push
- If push fails, resolve and retry until it succeeds