Skip to content

Commit

Permalink
feat: first working version
Browse files Browse the repository at this point in the history
  • Loading branch information
cnixbtc committed Sep 26, 2022
1 parent 9cf97ca commit 3a99a5e
Show file tree
Hide file tree
Showing 23 changed files with 694 additions and 21 deletions.
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2022 cnixbtc

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

41 changes: 41 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"pins" : [
{
"identity" : "secp256k1.swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/GigaBitcoin/secp256k1.swift.git",
"state" : {
"revision" : "b80388789a8058fc99202436225f8f15d35dfbea",
"version" : "0.8.1"
}
},
{
"identity" : "starscream",
"kind" : "remoteSourceControl",
"location" : "https://github.com/daltoniam/Starscream",
"state" : {
"revision" : "e6b65c6d9077ea48b4a7bdda8994a1d3c6969c8d",
"version" : "3.1.1"
}
},
{
"identity" : "swift-crypto",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto.git",
"state" : {
"revision" : "d9825fa541df64b1a7b182178d61b9a82730d01f",
"version" : "2.1.0"
}
},
{
"identity" : "swift-nio-zlib-support",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-zlib-support.git",
"state" : {
"revision" : "37760e9a52030bb9011972c5213c3350fa9d41fd",
"version" : "1.0.0"
}
}
],
"version" : 2
}
31 changes: 26 additions & 5 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,35 @@ import PackageDescription

let package = Package(
name: "NostrKit",
platforms: [
.macOS(.v11),
],
products: [
.library(name: "NostrKit", targets: ["NostrKit"]),
.executable(name: "example", targets: ["Example"]),
.executable(name: "example-reader", targets: ["ExampleReader"]),
.executable(name: "example-writer", targets: ["ExampleWriter"]),
],
dependencies: [
.package(url: "https://github.com/GigaBitcoin/secp256k1.swift", exact: .init(stringLiteral: "0.8.1")),
.package(url: "https://github.com/apple/swift-crypto.git", exact: .init(stringLiteral: "2.1.0")),
.package(url: "https://github.com/daltoniam/Starscream", exact: .init(stringLiteral: "3.1.1")),
],
dependencies: [],
targets: [
.target(name: "NostrKit", dependencies: []),
.testTarget(name: "NostrKitTests", dependencies: ["NostrKit"]),
.executableTarget(name: "Example", dependencies: ["NostrKit"]),
.target(name: "NostrKit", dependencies: [
.product(name: "secp256k1", package: "secp256k1.swift"),
.product(name: "Crypto", package: "swift-crypto"),
.product(name: "Starscream", package: "Starscream"),
]),
.testTarget(name: "NostrKitTests", dependencies: [
.target(name: "NostrKit"),
]),
.executableTarget(name: "ExampleReader", dependencies: [
.target(name: "NostrKit"),
.product(name: "Starscream", package: "Starscream"),
]),
.executableTarget(name: "ExampleWriter", dependencies: [
.target(name: "NostrKit"),
.product(name: "Starscream", package: "Starscream"),
]),
]
)
50 changes: 49 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,49 @@
# NostrKit
# NostrKit

A Swift library for interacting with a [Nostr](https://github.com/nostr-protocol/nostr) relay.

## Installation

NostrKit is available as a [Swift Package Manager](https://swift.org/package-manager/) package.
To use it, add the following dependency to your `Package.swift` file:

``` swift
.package(url: "https://github.com/cnixbtc/NostrKit.git", from: "0.1.0"),
```

## Functionality

NostrKit can be used to publish events on a Nostr relay as well as request events and subscribe to new updates.

### Subscribing to Events

``` swift
let keyPair = try KeyPair(privateKey: "<hex>")
let relay = Relay(url: URL("<url>")!, onEvent: { print($0) })

let subscription = Subscription(filters: [
.init(authors: [keyPair.publicKey])
])

try await relay.connect()
try await relay.subscribe(to: subscription)

// later on...

try await relay.unsubscribe(from: subscription.id)
```

### Publishing Events

``` swift
let keyPair = try KeyPair(privateKey: "<hex>")
let relay = Relay(url: URL("<url>")!)

let event = try Event(keyPair: keyPair, content: "Hello NostrKit.")

try await relay.connect()
try await relay.send(event: event)
```

Fully functional code examples can be found in `Sources/ExampleReader` as well as `Sources/ExampleWriter`.
Run `swift run example-reader` and `swift run example-writer` to see them in action.
6 changes: 0 additions & 6 deletions Sources/Example/Example.swift

This file was deleted.

30 changes: 30 additions & 0 deletions Sources/ExampleReader/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import Foundation
import Starscream
import NostrKit

// See the `docker/` directory in the project root for a local relay to use in development and testing.
let relayUrl = URL(string: "http://localhost:8080")!

// This is just a dummy key pair. Don't use it like this in production.
let keyPair = try KeyPair(privateKey: "df9aae2ac8233ffa210a086c54059d02ba3247dab1130dad968f28f036326a83")

let relay = Relay(url: relayUrl, onEvent: { message in
print(message)
})

let subscription = Subscription(filters: [
.init(authors: [keyPair.publicKey])
])

Task {
do {
try await relay.connect()
try await relay.subscribe(to: subscription)
} catch {
print("Something went wrong: \(error)")

exit(EXIT_FAILURE)
}
}

RunLoop.current.run()
28 changes: 28 additions & 0 deletions Sources/ExampleWriter/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Foundation
import Starscream
import NostrKit

// See the `docker/` directory in the project root for a local relay to use in development and testing.
let relayUrl = URL(string: "http://localhost:8080")!

// This is just a dummy key pair. Don't use it like this in production.
let keyPair = try KeyPair(privateKey: "df9aae2ac8233ffa210a086c54059d02ba3247dab1130dad968f28f036326a83")

let relay = Relay(url: relayUrl)

let event = try Event(keyPair: keyPair, content: "Hello NostrKit.")

Task {
do {
try await relay.connect()
try await relay.send(event: event)

exit(EXIT_SUCCESS)
} catch {
print("Something went wrong: \(error)")

exit(EXIT_FAILURE)
}
}

RunLoop.current.run()
29 changes: 29 additions & 0 deletions Sources/NostrKit/ClientMessage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Foundation

enum ClientMessage: Encodable {
case event(Event)
case subscribe(Subscription)
case unsubscribe(SubscriptionId)

func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()

switch self {
case .event(let event):
try container.encode("EVENT")
try container.encode(event)
case .subscribe(let subscription):
try container.encode("REQ")
try container.encode(subscription.id)
try subscription.filters.forEach { try container.encode($0) }
case .unsubscribe(let subscriptionId):
try container.encode("CLOSE")
try container.encode(subscriptionId)
}
}

func string() throws -> String {
return String(data: try JSONEncoder().encode(self), encoding: .utf8)!
}
}

40 changes: 40 additions & 0 deletions Sources/NostrKit/DataExtensions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Foundation

private extension Collection {
func unfoldSubSequences(ofMaxLength maxSequenceLength: Int) -> UnfoldSequence<SubSequence, Index> {
sequence(state: startIndex) { current in
guard current < endIndex else { return nil }

let upperBound = index(current, offsetBy: maxSequenceLength, limitedBy: endIndex) ?? endIndex
defer { current = upperBound }

return self[current..<upperBound]
}
}
}

extension Data {
enum DecodingError: Error {
case oddNumberOfCharacters
case invalidHexCharacters([Character])
}

func hex() -> String {
return self.map { String(format: "%02hhx", $0) }.joined()
}

init(hex: String) throws {
guard hex.count.isMultiple(of: 2) else { throw DecodingError.oddNumberOfCharacters }

self = .init(capacity: hex.utf8.count / 2)

for pair in hex.unfoldSubSequences(ofMaxLength: 2) {
guard let byte = UInt8(pair, radix: 16) else {
let invalidCharacters = Array(pair.filter({ !$0.isHexDigit }))
throw DecodingError.invalidHexCharacters(invalidCharacters)
}

append(byte)
}
}
}
Loading

0 comments on commit 3a99a5e

Please sign in to comment.