Module: Bech32::Nostr::NIP19

Defined in:
lib/bech32/nostr/nip19.rb,
sig/bech32/nostr/nip19.rbs

Constant Summary collapse

HRP_PUBKEY =

Returns:

  • (String)
'npub'
HRP_PRIVATE_KEY =

Returns:

  • (String)
'nsec'
HRP_NOTE_ID =

Returns:

  • (String)
'note'
HRP_PROFILE =

Returns:

  • (String)
'nprofile'
HRP_EVENT =

Returns:

  • (String)
'nevent'
HRP_RELAY =

Returns:

  • (String)
'nrelay'
HRP_EVENT_COORDINATE =

Returns:

  • (String)
'naddr'
BARE_PREFIXES =

Returns:

  • (Array[String])
[HRP_PUBKEY, HRP_PRIVATE_KEY, HRP_NOTE_ID]
TLV_PREFIXES =

Returns:

  • (Array[String])
[HRP_PROFILE, HRP_EVENT, HRP_RELAY, HRP_EVENT_COORDINATE]
ALL_PREFIXES =

Returns:

  • (Array[String])
BARE_PREFIXES + TLV_PREFIXES

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(string) ⇒ BareEntity, TLVEntity

Decode NIP-19 bech32 string.

Parameters:

  • string (String)

Returns:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/bech32/nostr/nip19.rb', line 25

def decode(string)
  hrp, data, spec = Bech32.decode(string, string.length)

  raise ArgumentError, 'Invalid nip19 string.' if hrp.nil?
  raise ArgumentError, 'Invalid bech32 spec.' unless spec == Bech32::Encoding::BECH32

  converted = Bech32.convert_bits(data, 5, 8, false)
  raise ArgumentError, 'Invalid data.' if converted.nil?
  entity = converted.pack('C*')
  raise ArgumentError, "Data whose HRP is #{hrp} must be 32 bytes." if BARE_PREFIXES.include?(hrp) && entity.bytesize != 32
  if BARE_PREFIXES.include?(hrp)
    BareEntity.new(hrp, entity.unpack1('H*'))
  elsif TLV_PREFIXES.include?(hrp)
    TLVEntity.parse(hrp, entity)
  else
    raise ArgumentError, "HRP #{hrp} is unsupported."
  end
end

Instance Method Details

#decode(string) ⇒ BareEntity, TLVEntity

module_function methods are also available as instance methods

Parameters:

  • string (String)

Returns:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/bech32/nostr/nip19.rb', line 25

def decode(string)
  hrp, data, spec = Bech32.decode(string, string.length)

  raise ArgumentError, 'Invalid nip19 string.' if hrp.nil?
  raise ArgumentError, 'Invalid bech32 spec.' unless spec == Bech32::Encoding::BECH32

  converted = Bech32.convert_bits(data, 5, 8, false)
  raise ArgumentError, 'Invalid data.' if converted.nil?
  entity = converted.pack('C*')
  raise ArgumentError, "Data whose HRP is #{hrp} must be 32 bytes." if BARE_PREFIXES.include?(hrp) && entity.bytesize != 32
  if BARE_PREFIXES.include?(hrp)
    BareEntity.new(hrp, entity.unpack1('H*'))
  elsif TLV_PREFIXES.include?(hrp)
    TLVEntity.parse(hrp, entity)
  else
    raise ArgumentError, "HRP #{hrp} is unsupported."
  end
end