Class: Nostr

Inherits:
Object
  • Object
show all
Defined in:
lib/nostr_ruby.rb

Overview

  • Ruby library to interact with the Nostr protocol

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Nostr

Returns a new instance of Nostr.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nostr_ruby.rb', line 15

def initialize(key)
  hex_private_key =  if key[:private_key]&.include?('nsec')
    Nostr.to_hex(key[:private_key])
  else
    key[:private_key]
  end

  hex_public_key = if key[:public_key]&.include?('npub')
    Nostr.to_hex(key[:public_key])
  else
    key[:public_key]
  end

  if hex_private_key
    @private_key = hex_private_key
    group = ECDSA::Group::Secp256k1
    @public_key = group.generator.multiply_by_scalar(private_key.to_i(16)).x.to_s(16).rjust(64, '0')
  elsif hex_public_key
    @public_key = hex_public_key
  else
    raise 'Missing private or public key'
  end
end

Instance Attribute Details

#pow_difficulty_targetObject (readonly)

Returns the value of attribute pow_difficulty_target.



13
14
15
# File 'lib/nostr_ruby.rb', line 13

def pow_difficulty_target
  @pow_difficulty_target
end

#private_keyObject (readonly)

Returns the value of attribute private_key.



13
14
15
# File 'lib/nostr_ruby.rb', line 13

def private_key
  @private_key
end

#public_keyObject (readonly)

Returns the value of attribute public_key.



13
14
15
# File 'lib/nostr_ruby.rb', line 13

def public_key
  @public_key
end

Class Method Details

.to_bech32(hex_key, hrp) ⇒ Object



56
57
58
59
60
61
# File 'lib/nostr_ruby.rb', line 56

def self.to_bech32(hex_key, hrp)
  custom_addr = CustomAddr.new
  custom_addr.scriptpubkey = hex_key
  custom_addr.hrp = hrp
  custom_addr.addr
end

.to_hex(bech32_key) ⇒ Object



51
52
53
54
# File 'lib/nostr_ruby.rb', line 51

def self.to_hex(bech32_key)
  public_addr = CustomAddr.new(bech32_key)
  public_addr.to_scriptpubkey
end

Instance Method Details

#bech32_keysObject



45
46
47
48
49
# File 'lib/nostr_ruby.rb', line 45

def bech32_keys
  bech32_keys = { public_key: Nostr.to_bech32(@public_key, 'npub') }
  bech32_keys[:private_key] = Nostr.to_bech32(@private_key, 'nsec') if @private_key
  bech32_keys
end

#build_close_event(subscription_id) ⇒ Object



247
248
249
# File 'lib/nostr_ruby.rb', line 247

def build_close_event(subscription_id)
  ['CLOSE', subscription_id]
end

#build_contact_list_event(contacts) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/nostr_ruby.rb', line 166

def build_contact_list_event(contacts)
  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 3,
    "tags": contacts.map { |c| ['p'] + c },
    "content": ''
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_deletion_event(events, reason = '') ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/nostr_ruby.rb', line 201

def build_deletion_event(events, reason = '')
  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 5,
    "tags": events.map{ |e| ['e', e] },
    "content": reason
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_dm_event(text, recipient_public_key) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/nostr_ruby.rb', line 179

def build_dm_event(text, recipient_public_key)
  cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
  cipher.encrypt
  cipher.iv = iv = cipher.random_iv
  cipher.key = calculate_shared_key(recipient_public_key)
  encrypted_text = cipher.update(text)
  encrypted_text << cipher.final
  encrypted_text = "#{Base64.encode64(encrypted_text)}?iv=#{Base64.encode64(iv)}"
  encrypted_text = encrypted_text.gsub("\n", '')

  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 4,
    "tags": [['p', recipient_public_key]],
    "content": encrypted_text
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_event(payload) ⇒ Object



115
116
117
118
# File 'lib/nostr_ruby.rb', line 115

def build_event(payload)
  event = sign_event(payload)
  ['EVENT', event]
end

#build_metadata_event(name, about, picture, nip05) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/nostr_ruby.rb', line 120

def (name, about, picture, nip05)
  data = {}
  data[:name] = name if name
  data[:about] = about if about
  data[:picture] = picture if picture
  data[:nip05] = nip05 if nip05
  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 0,
    "tags": [],
    "content": data.to_json
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_note_event(text, channel_key = nil) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/nostr_ruby.rb', line 138

def build_note_event(text, channel_key = nil)
  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": channel_key ? 42 : 1,
    "tags": channel_key ? [['e', channel_key]] : [],
    "content": text
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_notice_event(message) ⇒ Object



251
252
253
# File 'lib/nostr_ruby.rb', line 251

def build_notice_event(message)
  ['NOTICE', message]
end

#build_reaction_event(reaction, event, author) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/nostr_ruby.rb', line 214

def build_reaction_event(reaction, event, author)
  raise 'Invalid reaction' unless ['+', '-'].include?(reaction) || reaction.match?(Unicode::Emoji::REGEX)
  raise 'Invalid author' unless event.is_a?(String) && event.size == 64
  raise 'Invalid event' unless author.is_a?(String) && author.size == 64

  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 7,
    "tags": [['e', event], ['p', author]],
    "content": reaction
  }

  event = sign_event(event)
  ['EVENT', event]
end


151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/nostr_ruby.rb', line 151

def build_recommended_relay_event(relay)
  raise 'Invalid relay' unless relay.start_with?('wss://') || relay.start_with?('ws://')

  event = {
    "pubkey": @public_key,
    "created_at": Time.now.utc.to_i,
    "kind": 2,
    "tags": [],
    "content": relay
  }

  event = sign_event(event)
  ['EVENT', event]
end

#build_req_event(filters) ⇒ Object



243
244
245
# File 'lib/nostr_ruby.rb', line 243

def build_req_event(filters)
  ['REQ', SecureRandom.random_number.to_s, filters]
end

#calculate_shared_key(other_public_key) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/nostr_ruby.rb', line 63

def calculate_shared_key(other_public_key)
  ec = OpenSSL::PKey::EC.new('secp256k1')
  ec.private_key = OpenSSL::BN.new(@private_key, 16)
  recipient_key_hex = "02#{other_public_key}"
  recipient_pub_bn = OpenSSL::BN.new(recipient_key_hex, 16)
  secret_point = OpenSSL::PKey::EC::Point.new(ec.group, recipient_pub_bn)
  ec.dh_compute_key(secret_point)
end

#decrypt_dm(event) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
# File 'lib/nostr_ruby.rb', line 231

def decrypt_dm(event)
  data = event[1]
  sender_public_key = data[:pubkey] != @public_key ? data[:pubkey] : data[:tags][0][1]
  encrypted = data[:content].split('?iv=')[0]
  iv = data[:content].split('?iv=')[1]
  cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
  cipher.decrypt
  cipher.iv = Base64.decode64(iv)
  cipher.key = calculate_shared_key(sender_public_key)
  (cipher.update(Base64.decode64(encrypted)) + cipher.final).force_encoding('UTF-8')
end

#keysObject



39
40
41
42
43
# File 'lib/nostr_ruby.rb', line 39

def keys
  keys = { public_key: @public_key }
  keys[:private_key] = @private_key if @private_key
  keys
end

#match_pow_difficulty?(event_id) ⇒ Boolean

Returns:

  • (Boolean)


255
256
257
# File 'lib/nostr_ruby.rb', line 255

def match_pow_difficulty?(event_id)
  @pow_difficulty_target.nil? || @pow_difficulty_target == [event_id].pack("H*").unpack("B*")[0].index('1')
end

#set_pow_difficulty_target(n) ⇒ Object



259
260
261
# File 'lib/nostr_ruby.rb', line 259

def set_pow_difficulty_target(n)
  @pow_difficulty_target = n
end

#sign_event(event) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/nostr_ruby.rb', line 72

def sign_event(event)
  raise 'Invalid pubkey' unless event[:pubkey].is_a?(String) && event[:pubkey].size == 64
  raise 'Invalid created_at' unless event[:created_at].is_a?(Integer)
  raise 'Invalid kind' unless (0..29_999).include?(event[:kind])
  raise 'Invalid tags' unless event[:tags].is_a?(Array)
  raise 'Invalid content' unless event[:content].is_a?(String)

  serialized_event = [
    0,
    event[:pubkey],
    event[:created_at],
    event[:kind],
    event[:tags],
    event[:content]
  ]

  serialized_event_sha256 = nil
  if @pow_difficulty_target
    nonce = 1
    loop do
      nonce_tag = ['nonce', nonce.to_s, @pow_difficulty_target.to_s]
      nonced_serialized_event = serialized_event.clone
      nonced_serialized_event[4] = nonced_serialized_event[4] + [nonce_tag]
      serialized_event_sha256 = Digest::SHA256.hexdigest(JSON.dump(nonced_serialized_event))
      if match_pow_difficulty?(serialized_event_sha256)
        event[:tags] << nonce_tag
        break
      end
      nonce += 1
    end
  else
    serialized_event_sha256 = Digest::SHA256.hexdigest(JSON.dump(serialized_event))
  end

  private_key = Array(@private_key).pack('H*')
  message = Array(serialized_event_sha256).pack('H*')
  event_signature = Schnorr.sign(message, private_key).encode.unpack('H*')[0]

  event['id'] = serialized_event_sha256
  event['sig'] = event_signature
  event
end

#test_post_event(event, relay) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/nostr_ruby.rb', line 263

def test_post_event(event, relay)
  response = nil
  ws = WebSocket::Client::Simple.connect relay
  ws.on :message do |msg|
    puts msg
    response = JSON.parse(msg.data)
    ws.close
  end
  ws.on :open do
    ws.send event.to_json
  end
  while response.nil? do
    sleep 0.1
  end
  response[0] == 'OK'
end