Class: Nostr

Inherits:
Object
  • Object
show all
Includes:
CryptoTools
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

Methods included from CryptoTools

aes_256_cbc_decrypt, aes_256_cbc_encrypt, calculate_shared_key

Constructor Details

#initialize(key) ⇒ Nostr

Returns a new instance of Nostr.



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

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

#nip26_delegation_tagObject (readonly)

Returns the value of attribute nip26_delegation_tag.



16
17
18
# File 'lib/nostr_ruby.rb', line 16

def nip26_delegation_tag
  @nip26_delegation_tag
end

#pow_difficulty_targetObject (readonly)

Returns the value of attribute pow_difficulty_target.



16
17
18
# File 'lib/nostr_ruby.rb', line 16

def pow_difficulty_target
  @pow_difficulty_target
end

#private_keyObject (readonly)

Returns the value of attribute private_key.



16
17
18
# File 'lib/nostr_ruby.rb', line 16

def private_key
  @private_key
end

#public_keyObject (readonly)

Returns the value of attribute public_key.



16
17
18
# File 'lib/nostr_ruby.rb', line 16

def public_key
  @public_key
end

Class Method Details

.to_bech32(hex_key, hrp) ⇒ Object



59
60
61
62
63
64
# File 'lib/nostr_ruby.rb', line 59

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



54
55
56
57
# File 'lib/nostr_ruby.rb', line 54

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

.verify_delegation_signature(delegatee_pubkey, tag) ⇒ Object



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

def self.verify_delegation_signature(delegatee_pubkey, tag)
  delegation_message_sha256 = Digest::SHA256.hexdigest("nostr:delegation:#{delegatee_pubkey}:#{tag[2]}")
  Schnorr.valid_sig?(Array(delegation_message_sha256).pack('H*'), Array(tag[1]).pack('H*'), Array(tag[3]).pack('H*'))
end

Instance Method Details

#bech32_keysObject



48
49
50
51
52
# File 'lib/nostr_ruby.rb', line 48

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



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

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

#build_contact_list_event(contacts) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/nostr_ruby.rb', line 161

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": ''
  }

  build_event(event)
end

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



187
188
189
190
191
192
193
194
195
196
197
# File 'lib/nostr_ruby.rb', line 187

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
  }

  build_event(event)
end

#build_dm_event(text, recipient_public_key) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/nostr_ruby.rb', line 173

def build_dm_event(text, recipient_public_key)
  encrypted_text = CryptoTools.aes_256_cbc_encrypt(@private_key, recipient_public_key, text)

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

  build_event(event)
end

#build_event(payload) ⇒ Object



109
110
111
112
113
114
115
116
# File 'lib/nostr_ruby.rb', line 109

def build_event(payload)
  if @nip26_delegation_tag
    payload[:tags] = [] unless payload[:tags]
    payload[:tags] << @nip26_delegation_tag
  end
  event = sign_event(payload)
  ['EVENT', event]
end

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



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

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
  }

  build_event(event)
end

#build_note_event(text, channel_key = nil) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
# File 'lib/nostr_ruby.rb', line 135

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
  }

  build_event(event)
end

#build_notice_event(message) ⇒ Object



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

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

#build_reaction_event(reaction, event, author) ⇒ Object



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

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
  }

  build_event(event)
end


147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/nostr_ruby.rb', line 147

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
  }

  build_event(event)
end

#build_req_event(filters) ⇒ Object



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

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

#decrypt_dm(event) ⇒ Object



215
216
217
218
219
220
221
# File 'lib/nostr_ruby.rb', line 215

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]
  CryptoTools.aes_256_cbc_decrypt(@private_key, sender_public_key, encrypted, iv)
end

#get_delegation_tag(delegatee_pubkey, conditions) ⇒ Object



223
224
225
226
227
228
229
230
231
232
# File 'lib/nostr_ruby.rb', line 223

def get_delegation_tag(delegatee_pubkey, conditions)
  delegation_message_sha256 = Digest::SHA256.hexdigest("nostr:delegation:#{delegatee_pubkey}:#{conditions}")
  signature = Schnorr.sign(Array(delegation_message_sha256).pack('H*'), Array(@private_key).pack('H*')).encode.unpack('H*')[0]
  [
    "delegation",
    @public_key,
    conditions,
    signature
  ]
end

#keysObject



42
43
44
45
46
# File 'lib/nostr_ruby.rb', line 42

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)


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

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

#reset_delegationObject



238
239
240
# File 'lib/nostr_ruby.rb', line 238

def reset_delegation
  @nip26_delegation_tag = nil
end

#set_delegation(tag) ⇒ Object



234
235
236
# File 'lib/nostr_ruby.rb', line 234

def set_delegation(tag)
  @nip26_delegation_tag = tag
end

#set_pow_difficulty_target(n) ⇒ Object



263
264
265
# File 'lib/nostr_ruby.rb', line 263

def set_pow_difficulty_target(n)
  @pow_difficulty_target = n
end

#sign_event(event) ⇒ Object



66
67
68
69
70
71
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
# File 'lib/nostr_ruby.rb', line 66

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



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/nostr_ruby.rb', line 267

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