Skip to content

Instantly share code, notes, and snippets.

@rickhull
Last active September 29, 2024 23:32
Show Gist options
  • Save rickhull/715b21883c453a8a1269a81cb29a0c46 to your computer and use it in GitHub Desktop.
Save rickhull/715b21883c453a8a1269a81cb29a0c46 to your computer and use it in GitHub Desktop.
Nostr client using async websockets
require 'async'
require 'async/barrier'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'nostrb/source'
module Nostrb
class Client
def initialize(relay_url)
@url = relay_url
@endpoint = Async::HTTP::Endpoint.parse(@url)
end
def publish(signed_event)
barrier = Async::Barrier.new
resp = nil
Sync do |task|
task.async do
conn = Async::WebSocket::Client.connect(@endpoint)
conn.write(Nostrb.json(Nostrb::Source.publish(signed_event)))
conn.flush
resp = conn.read
conn.shutdown
end.wait
ensure
barrier.stop
end
Nostrb.parse(resp.buffer)[2] if resp
end
end
end
# path/to/falcon serve \
# --bind wss://localhost:7070 \
# --config examples/config.ru \
require 'async/websocket/adapters/rack'
require 'nostrb/relay'
relay = Nostrb::Server.new
Adapter = Async::WebSocket::Adapters::Rack
app = lambda do |env|
Adapter.open(env, protocols: ['ws', 'wss']) do |conn|
puts "New connection: #{conn}"
reqs, resps = 0, 0
while req = conn.read
reqs += 1
puts req.buffer
relay.ingest(req.buffer).each { |resp|
resps += 1
conn.write Nostrb.json(resp)
}
end
puts "Closed after #{reqs} requests and #{resps} responses"
end
end
run app
[rwh@nixos:~/git/nostrb]$ irb -rnostrb/client
irb(main):001> c = Nostrb::Client.new('wss://localhost:7070')
=>
#<Nostrb::Client:0x00007f5989ad2750
...
irb(main):002> sk, pk = SchnorrSig.keypair
=> ["\xADl\x84\xD8W\xAA\xCB\x91\x8FJ\x83Y\x93T\xA2u5\xB9\x94\x9E\xF4\xD1\x7...
irb(main):003> src = Nostrb::Source.new(pk)
=>
#<Nostrb::Source:0x00007f5989ad5ce8
...
irb(main):004> e = src.text_note('hi').sign(sk)
=>
#<Nostrb::SignedEvent:0x00007f5989b26918
...
irb(main):005> c.publish(e)
# ... never returns ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment