bech32 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 22cba51d19b0989743f7f679f187311e735ce018dec53880ddfefebee89f688f
4
- data.tar.gz: 1cd7be33ab83fd724054202a812f818ed02adb5eb7545baa27e27f6b3358da2e
3
+ metadata.gz: 385b10727c1105f233c1c387c5b03aa6f12b9e2c131261cc99bc865f95df0eb1
4
+ data.tar.gz: c629dcae33f0edddba292c6a7a9803ef5d7fa4f366ebda3c69b1c2b08316040f
5
5
  SHA512:
6
- metadata.gz: dc71997f097a817224b687dc53baf048ba2954cd030f7db50523d7e45121632b7f2edf758ed78298102214c3e3407cf7c7da6b3469a3cde089ade10e8346088d
7
- data.tar.gz: 6c246c4107a40193d317738bfa4637ccf6452efb48f1d36532570cec1e09681cc17fd374f47361467017e6546f36c4513f2585ed2d4b767939dcef05047ede46
6
+ metadata.gz: 84ec7efd44d61918d538193c7cedaf2049a7bb4c0a7f724fc11a1230b0d957b04ab56ee73ee06fd7ce14b64ea0f069be0472f62c1393ba21eb5e33f05b0cb921
7
+ data.tar.gz: 999a0096238621ad5ff3e889ae12b8e77aec1fbb740e26cc04e799af02979e008451e30a7cc4422f2f3992c4254bc26f80c373bfde7b4224e9d5388e6a95e21d
data/README.md CHANGED
@@ -135,7 +135,7 @@ Supports encoding/decoding of Nostr's [NIP-19](https://github.com/nostr-protocol
135
135
  ```ruby
136
136
  # Decode bare entity
137
137
  bech32 = 'npub10elfcs4fr0l0r8af98jlmgdh9c8tcxjvz9qkw038js35mp4dma8qzvjptg'
138
- entity = Bech32::Nostr::NIP19.parse(bech32)
138
+ entity = Bech32::Nostr::NIP19.decode(bech32)
139
139
  entity.hrp
140
140
  => 'npub'
141
141
  entity.data
@@ -143,7 +143,7 @@ entity.data
143
143
 
144
144
  # Decode tlv entity
145
145
  bech32 = 'nprofile1qqsrhuxx8l9ex335q7he0f09aej04zpazpl0ne2cgukyawd24mayt8gpp4mhxue69uhhytnc9e3k7mgpz4mhxue69uhkg6nzv9ejuumpv34kytnrdaksjlyr9p'
146
- entity = Bech32::Nostr::NIP19.parse(bech32)
146
+ entity = Bech32::Nostr::NIP19.decode(bech32)
147
147
  entity.hrp
148
148
  => 'nprofile'
149
149
  entity.entries[0].value
@@ -157,11 +157,12 @@ entity.encode
157
157
  => 'npub10elfcs4fr0l0r8af98jlmgdh9c8tcxjvz9qkw038js35mp4dma8qzvjptg'
158
158
 
159
159
  # Encode tlv entity
160
+ entry_id = Bech32::Nostr::TLVEntry.new(Bech32::Nostr::TLVEntity::TYPE_SPECIAL, 'b9f5441e45ca39179320e0031cfb18e34078673dcc3d3e3a3b3a981760aa5696')
160
161
  entry_relay = Bech32::Nostr::TLVEntry.new(Bech32::Nostr::TLVEntity::TYPE_RELAY, 'wss://relay.nostr.example')
161
162
  entry_author = Bech32::Nostr::TLVEntry.new(Bech32::Nostr::TLVEntity::TYPE_AUTHOR, '97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322')
162
- entity = Bech32::Nostr::TLVEntity.new(Bech32::Nostr::NIP19::HRP_EVENT, [entry_relay, entry_author])
163
+ entity = Bech32::Nostr::TLVEntity.new(Bech32::Nostr::NIP19::HRP_EVENT, [entry_id, entry_relay, entry_author])
163
164
  entity.encode
164
- => 'nevent1qyvhwumn8ghj7un9d3shjtnwdaehgu3wv4uxzmtsd3jsygyhcu9ygdn2v56uz3dnx0uh865xmlwz675emfsccsxxguz6mx8rygstv78u'
165
+ => 'nevent1qqstna2yrezu5wghjvswqqculvvwxsrcvu7uc0f78gan4xqhvz49d9spr9mhxue69uhhyetvv9ujumn0wd68ytn90psk6urvv5pzp978pfzrv6n9xhq5tvenl9e74pklmskh4xw6vxxyp3j8qkke3cez9uxngd'
165
166
  ```
166
167
 
167
168
  ### CLI
data/exe/bech32 CHANGED
@@ -5,56 +5,68 @@ require 'thor'
5
5
 
6
6
  class CLI < Thor
7
7
 
8
+ # Exit with a non-zero status when Thor fails on arguments (e.g. missing or unknown command).
9
+ def self.exit_on_failure?
10
+ true
11
+ end
12
+
8
13
  desc 'encode hrp data bech32/bech32m', 'Encoding data to bech32/bech32m string.'
9
14
  def encode(hrp, data, type)
10
- if type && !['bech32', 'bech32m'].include?(type)
15
+ unless ['bech32', 'bech32m'].include?(type)
11
16
  puts 'Invalid type value. type must be bech32 or bech32m.'
12
- else
13
- spec = type.nil? || type == 'bech32' ? 1 : 2
14
- data = [data].pack('H*').unpack('C*')
15
- puts Bech32.encode(hrp, data, spec)
17
+ exit 1
16
18
  end
19
+ spec = type == 'bech32' ? Bech32::Encoding::BECH32 : Bech32::Encoding::BECH32M
20
+ raise ArgumentError, 'data must be a hex string.' unless Bech32.hex_string?(data)
21
+ data = [data].pack('H*').unpack('C*')
22
+ puts Bech32.encode(hrp, data, spec)
23
+ rescue ArgumentError => e
24
+ puts "Can not encode: #{e.message}"
25
+ exit 1
17
26
  end
18
27
 
19
28
  desc 'decode "bech32string"', 'Decoding bech32/bech32m string.'
20
29
  def decode(bech32_str)
21
30
  hrp, data, spec = Bech32.decode(bech32_str, bech32_str.length)
22
- if hrp
23
- puts <<~EOS
24
- HRP: #{hrp}
25
- DATA: #{data.pack('C*').unpack1('H*')}
26
- TYPE: #{spec == Bech32::Encoding::BECH32 ? 'bech32' : 'bech32m'}
31
+ unless hrp
32
+ puts 'Can not decode.'
33
+ exit 1
34
+ end
35
+ # Build all the output first, so that nothing is printed if parsing the address or entity fails.
36
+ output = <<~EOS
37
+ HRP: #{hrp}
38
+ DATA: #{data.pack('C*').unpack1('H*')}
39
+ TYPE: #{spec == Bech32::Encoding::BECH32 ? 'bech32' : 'bech32m'}
40
+ EOS
41
+ case hrp
42
+ when Bech32::SegwitAddr::HRP_MAINNET, Bech32::SegwitAddr::HRP_TESTNET, Bech32::SegwitAddr::HRP_REGTEST
43
+ addr = Bech32::SegwitAddr.new(bech32_str)
44
+ output += <<~EOS
45
+ WITNESS VERSION: #{addr.ver}
46
+ WITNESS PROGRAM: #{addr.prog.pack('C*').unpack1('H*')}
27
47
  EOS
28
- case hrp
29
- when Bech32::SegwitAddr::HRP_MAINNET, Bech32::SegwitAddr::HRP_TESTNET, Bech32::SegwitAddr::HRP_REGTEST
30
- addr = Bech32::SegwitAddr.new(bech32_str)
31
- puts <<~EOS
32
- WITNESS VERSION: #{addr.ver}
33
- WITNESS PROGRAM: #{addr.prog.pack('C*').unpack1('H*')}
34
- EOS
35
- when *Bech32::Nostr::NIP19::ALL_PREFIXES
36
- entity = Bech32::Nostr::NIP19.decode(bech32_str)
37
- if entity.is_a?(Bech32::Nostr::BareEntity)
38
- puts <<~EOS
39
- NIP19 Entity: #{entity.data}
40
- EOS
41
- else
42
- puts 'NIP19 Entities:'
43
- entity.entries.each do |entry|
44
- puts " #{entry.to_s}"
45
- end
48
+ when *Bech32::Nostr::NIP19::ALL_PREFIXES
49
+ entity = Bech32::Nostr::NIP19.decode(bech32_str)
50
+ if entity.is_a?(Bech32::Nostr::BareEntity)
51
+ output += "NIP19 Entity: #{entity.data}\n"
52
+ else
53
+ output += "NIP19 Entities:\n"
54
+ entity.entries.each do |entry|
55
+ output += " #{entry.to_s}\n"
46
56
  end
47
- when Bech32::SilentPaymentAddr::HRP_MAINNET, Bech32::SilentPaymentAddr::HRP_TESTNET
48
- addr = Bech32::SilentPaymentAddr.parse(bech32_str)
49
- puts <<~EOS
50
- version: #{addr.version}
51
- scan public key: #{addr.scan_key}
52
- spend public key: #{addr.spend_key}
53
- EOS
54
57
  end
55
- else
56
- puts 'Can not decode.'
58
+ when Bech32::SilentPaymentAddr::HRP_MAINNET, Bech32::SilentPaymentAddr::HRP_TESTNET
59
+ addr = Bech32::SilentPaymentAddr.parse(bech32_str)
60
+ output += <<~EOS
61
+ version: #{addr.version}
62
+ scan public key: #{addr.scan_key}
63
+ spend public key: #{addr.spend_key}
64
+ EOS
57
65
  end
66
+ puts output
67
+ rescue ArgumentError => e
68
+ puts "Can not decode: #{e.message}"
69
+ exit 1
58
70
  end
59
71
 
60
72
  end
@@ -1,3 +1,5 @@
1
+ require 'stringio'
2
+
1
3
  module Bech32
2
4
  module Nostr
3
5
  class BareEntity
@@ -9,6 +11,7 @@ module Bech32
9
11
  # @param [String] data Entity data(hex string).
10
12
  def initialize(hrp, data)
11
13
  raise ArgumentError, "HRP #{hrp} is unsupported." unless NIP19::BARE_PREFIXES.include?(hrp)
14
+ raise ArgumentError, "Data must be a hex string." unless Bech32.hex_string?(data)
12
15
  raise ArgumentError, "Data whose HRP is #{hrp} must be 32 bytes." unless [data].pack('H*').bytesize == 32
13
16
  @hrp = hrp
14
17
  @data = data
@@ -29,21 +32,41 @@ module Bech32
29
32
 
30
33
  def initialize(type, value, label = nil)
31
34
  raise ArgumentError, "Type #{type} unsupported." unless TLVEntity::TYPES.include?(type)
35
+ if type == TLVEntity::TYPE_KIND
36
+ raise ArgumentError, "Value of kind must be Integer. #{value.class} given." unless value.is_a?(Integer)
37
+ else
38
+ raise ArgumentError, "Value of type #{type} must be String. #{value.class} given." unless value.is_a?(String)
39
+ end
32
40
 
33
41
  @type = type
34
42
  @value = value
35
43
  @label = label
36
44
  end
37
45
 
46
+ # Maximum byte length of a TLV value (the length field is 1 byte).
47
+ MAX_VALUE_LENGTH = 255
48
+
38
49
  # Convert to binary data.
50
+ # @param [String] hrp human-readable part of the entity this entry belongs to.
51
+ # It determines whether a special entry's value is a hex string (nprofile, nevent)
52
+ # or a raw string (nrelay, naddr). If omitted, a special value is treated as hex
53
+ # only when it looks like a hex string.
39
54
  # @return [String] binary data.
40
- def to_payload
55
+ # @raise [ArgumentError] if the value is out of range or longer than MAX_VALUE_LENGTH bytes.
56
+ def to_payload(hrp = nil)
41
57
  data = if value.is_a?(Integer)
58
+ unless value.between?(0, 0xffffffff)
59
+ raise ArgumentError, "Integer value must be between 0 and #{0xffffffff}."
60
+ end
42
61
  [value].pack('N')
62
+ elsif hex_value?(hrp)
63
+ raise ArgumentError, "Value of type #{type} must be a hex string." unless hex_string?(value)
64
+ [value].pack('H*')
43
65
  else
44
- hex_string?(value) ? [value].pack('H*') : value
66
+ value.b
45
67
  end
46
68
  len = data.bytesize
69
+ raise ArgumentError, "Value must be at most #{MAX_VALUE_LENGTH} bytes." if len > MAX_VALUE_LENGTH
47
70
  [type, len].pack('CC') + data
48
71
  end
49
72
 
@@ -65,14 +88,25 @@ module Bech32
65
88
 
66
89
  private
67
90
 
91
+ # Check whether the value of this entry is a hex-encoded string.
92
+ # @param [String] hrp human-readable part (may be nil).
93
+ # @return [Boolean]
94
+ def hex_value?(hrp)
95
+ case type
96
+ when TLVEntity::TYPE_AUTHOR
97
+ true
98
+ when TLVEntity::TYPE_SPECIAL
99
+ hrp.nil? ? hex_string?(value) : [NIP19::HRP_PROFILE, NIP19::HRP_EVENT].include?(hrp)
100
+ else
101
+ false
102
+ end
103
+ end
104
+
68
105
  # Check whether +str+ is hex string or not.
69
106
  # @param [String] str string.
70
107
  # @return [Boolean]
71
108
  def hex_string?(str)
72
- return false if str.bytes.any? { |b| b > 127 }
73
- return false if str.length % 2 != 0
74
- hex_chars = str.chars.to_a
75
- hex_chars.all? { |c| c =~ /[0-9a-fA-F]/ }
109
+ Bech32.hex_string?(str)
76
110
  end
77
111
  end
78
112
 
@@ -85,6 +119,25 @@ module Bech32
85
119
 
86
120
  TYPES = [TYPE_SPECIAL, TYPE_RELAY, TYPE_AUTHOR, TYPE_KIND]
87
121
 
122
+ # TLV types each HRP supports. Other types are ignored when parsing (NIP-19).
123
+ SUPPORTED_TYPES = {
124
+ NIP19::HRP_PROFILE => [TYPE_SPECIAL, TYPE_RELAY].freeze,
125
+ NIP19::HRP_EVENT => [TYPE_SPECIAL, TYPE_RELAY, TYPE_AUTHOR, TYPE_KIND].freeze,
126
+ NIP19::HRP_RELAY => [TYPE_SPECIAL].freeze,
127
+ NIP19::HRP_EVENT_COORDINATE => [TYPE_SPECIAL, TYPE_RELAY, TYPE_AUTHOR, TYPE_KIND].freeze
128
+ }.freeze
129
+
130
+ # TLV types each HRP requires (NIP-19).
131
+ REQUIRED_TYPES = {
132
+ NIP19::HRP_PROFILE => [TYPE_SPECIAL].freeze,
133
+ NIP19::HRP_EVENT => [TYPE_SPECIAL].freeze,
134
+ NIP19::HRP_RELAY => [TYPE_SPECIAL].freeze,
135
+ NIP19::HRP_EVENT_COORDINATE => [TYPE_SPECIAL, TYPE_AUTHOR, TYPE_KIND].freeze
136
+ }.freeze
137
+
138
+ # Byte length of a public key or an event id (NIP-19).
139
+ KEY_LENGTH = 32
140
+
88
141
  attr_reader :hrp
89
142
  attr_reader :entries
90
143
 
@@ -107,6 +160,7 @@ module Bech32
107
160
  # @param [String] data Entity data(binary format).
108
161
  # @return [TLVEntity]
109
162
  def self.parse(hrp, data)
163
+ supported = SUPPORTED_TYPES.fetch(hrp) { raise ArgumentError, "HRP #{hrp} is unsupported." }
110
164
  buf = ::StringIO.new(data)
111
165
  entries = []
112
166
  until buf.eof?
@@ -116,52 +170,100 @@ module Bech32
116
170
  value = buf.read(len)
117
171
  raise ArgumentError, "Invalid TLV: truncated value." if value.nil? ? len > 0 : value.bytesize < len
118
172
  value ||= ''
119
- case type
120
- when TYPE_SPECIAL # special
121
- case hrp
122
- when NIP19::HRP_PROFILE
123
- entries << TLVEntry.new(type, value.unpack1('H*'), 'pubkey')
124
- when NIP19::HRP_RELAY
125
- entries << TLVEntry.new(type, value, 'relay')
126
- when NIP19::HRP_EVENT
127
- entries << TLVEntry.new(type, value.unpack1('H*'), 'id')
128
- when NIP19::HRP_EVENT_COORDINATE
129
- entries << TLVEntry.new(type, value, 'identifier')
130
- end
131
- when TYPE_RELAY # relay
132
- case hrp
133
- when NIP19::HRP_PROFILE, NIP19::HRP_EVENT, NIP19::HRP_EVENT_COORDINATE
134
- entries << TLVEntry.new(type, value, 'relay')
135
- else
136
- raise ArgumentError, "Type: #{type} does not supported for HRP: #{hrp}"
137
- end
138
- when TYPE_AUTHOR # author
139
- case hrp
140
- when NIP19::HRP_EVENT, NIP19::HRP_EVENT_COORDINATE
141
- entries << TLVEntry.new(type, value.unpack1('H*'), 'author')
142
- else
143
- raise ArgumentError, "Type: #{type} does not supported for HRP: #{hrp}"
144
- end
145
- when TYPE_KIND # kind
146
- case hrp
147
- when NIP19::HRP_EVENT, NIP19::HRP_EVENT_COORDINATE
148
- entries << TLVEntry.new(type, value.unpack1('H*').to_s.to_i(16), 'kind')
149
- else
150
- raise ArgumentError, "Type: #{type} does not supported for HRP: #{hrp}"
151
- end
152
- else
153
- raise ArgumentError, "Unknown TLV type: #{type}"
154
- end
173
+ # NIP-19: TLVs that are not recognized or supported should be ignored, rather than causing an error.
174
+ next unless supported.include?(type)
175
+
176
+ check_value_length(hrp, type, value.bytesize)
177
+ check_value_encoding(hrp, type, value)
178
+
179
+ entries << case type
180
+ when TYPE_SPECIAL
181
+ case hrp
182
+ when NIP19::HRP_PROFILE then TLVEntry.new(type, value.unpack1('H*'), 'pubkey')
183
+ when NIP19::HRP_RELAY then TLVEntry.new(type, value.force_encoding(::Encoding::UTF_8), 'relay')
184
+ when NIP19::HRP_EVENT then TLVEntry.new(type, value.unpack1('H*'), 'id')
185
+ else TLVEntry.new(type, value.force_encoding(::Encoding::UTF_8), 'identifier')
186
+ end
187
+ when TYPE_RELAY
188
+ TLVEntry.new(type, value.force_encoding(::Encoding::UTF_8), 'relay')
189
+ when TYPE_AUTHOR
190
+ TLVEntry.new(type, value.unpack1('H*'), 'author')
191
+ else # TYPE_KIND
192
+ raise ArgumentError, 'Invalid TLV: kind must be 4 bytes.' unless value.bytesize == 4
193
+ TLVEntry.new(type, value.unpack1('N'), 'kind')
194
+ end
155
195
  end
156
196
 
197
+ check_required_types(hrp, entries)
157
198
  TLVEntity.new(hrp, entries)
158
199
  end
159
200
 
160
201
  # Encode tlv entity to bech32 string.
202
+ # The entity is checked against the same rules as {.parse}, so that the result can be decoded.
161
203
  # @return [String] bech32 string.
204
+ # @raise [ArgumentError] if an entry type is unsupported for the HRP, a value has an invalid length
205
+ # or encoding, a required entry is missing, or the result is longer than NIP19::MAX_LENGTH characters.
162
206
  def encode
163
- data = entries.map(&:to_payload).join
164
- Bech32.encode(hrp, Bech32.convert_bits(data.unpack('C*'), 8, 5), Bech32::Encoding::BECH32)
207
+ supported = SUPPORTED_TYPES[hrp]
208
+ entries.each do |e|
209
+ raise ArgumentError, "Type #{e.type} is unsupported for HRP: #{hrp}" unless supported.include?(e.type)
210
+ end
211
+ payloads = entries.map { |e| e.to_payload(hrp) }
212
+ entries.zip(payloads) do |e, payload|
213
+ TLVEntity.check_value_length(hrp, e.type, payload.bytesize - 2)
214
+ TLVEntity.check_value_encoding(hrp, e.type, payload.byteslice(2..))
215
+ end
216
+ TLVEntity.check_required_types(hrp, entries)
217
+ data = payloads.join
218
+ bech32 = Bech32.encode(hrp, Bech32.convert_bits(data.unpack('C*'), 8, 5), Bech32::Encoding::BECH32)
219
+ if bech32.length > NIP19::MAX_LENGTH
220
+ raise ArgumentError, "nip19 string must be at most #{NIP19::MAX_LENGTH} characters."
221
+ end
222
+ bech32
223
+ end
224
+
225
+ # Check the byte length of a TLV value.
226
+ # Public keys and event ids must be 32 bytes, and the relay of nrelay must not be empty.
227
+ # @param [String] hrp human-readable part.
228
+ # @param [Integer] type TLV type.
229
+ # @param [Integer] length byte length of the value.
230
+ # @raise [ArgumentError] if the length is invalid.
231
+ def self.check_value_length(hrp, type, length)
232
+ if type == TYPE_AUTHOR || (type == TYPE_SPECIAL && [NIP19::HRP_PROFILE, NIP19::HRP_EVENT].include?(hrp))
233
+ return if length == KEY_LENGTH
234
+
235
+ raise ArgumentError, "Invalid TLV: type #{type} for HRP: #{hrp} must be #{KEY_LENGTH} bytes."
236
+ elsif type == TYPE_SPECIAL && hrp == NIP19::HRP_RELAY && length.zero?
237
+ raise ArgumentError, "Invalid TLV: type #{type} for HRP: #{hrp} must not be empty."
238
+ end
239
+ end
240
+
241
+ # Check the character encoding of a relay or identifier value.
242
+ # NIP-19: a relay is ASCII. The naddr identifier ("d" tag) must be valid UTF-8.
243
+ # @param [String] hrp human-readable part.
244
+ # @param [Integer] type TLV type.
245
+ # @param [String] value raw value bytes.
246
+ # @raise [ArgumentError] if the encoding is invalid.
247
+ def self.check_value_encoding(hrp, type, value)
248
+ if type == TYPE_RELAY || (type == TYPE_SPECIAL && hrp == NIP19::HRP_RELAY)
249
+ raise ArgumentError, 'Invalid TLV: relay must be ASCII.' unless value.b.ascii_only?
250
+ elsif type == TYPE_SPECIAL && hrp == NIP19::HRP_EVENT_COORDINATE
251
+ unless value.dup.force_encoding(::Encoding::UTF_8).valid_encoding?
252
+ raise ArgumentError, 'Invalid TLV: identifier must be valid UTF-8.'
253
+ end
254
+ end
255
+ end
256
+
257
+ # Check that all TLV types required for the HRP are present.
258
+ # @param [String] hrp human-readable part.
259
+ # @param [Array<TLVEntry>] entries TLV entries.
260
+ # @raise [ArgumentError] if a required type is missing.
261
+ def self.check_required_types(hrp, entries)
262
+ REQUIRED_TYPES[hrp].each do |required|
263
+ next if entries.any? { |e| e.type == required }
264
+
265
+ raise ArgumentError, "Invalid TLV: missing required type #{required} for HRP: #{hrp}"
266
+ end
165
267
  end
166
268
  end
167
269
  end
@@ -16,14 +16,20 @@ module Bech32
16
16
  TLV_PREFIXES = [HRP_PROFILE, HRP_EVENT, HRP_RELAY, HRP_EVENT_COORDINATE]
17
17
  ALL_PREFIXES = BARE_PREFIXES + TLV_PREFIXES
18
18
 
19
+ # Maximum length of a NIP-19 string (NIP-19: "SHOULD be limited in size to 5000 characters").
20
+ MAX_LENGTH = 5000
21
+
19
22
  module_function
20
23
 
21
24
  # Decode nip19 string.
22
25
  # @param [String] string Bech32 string.
23
26
  # @return [BareEntity]
24
27
  # @return [TLVEntity]
28
+ # @raise [ArgumentError] if the string is invalid or longer than MAX_LENGTH characters.
25
29
  def decode(string)
26
- hrp, data, spec = Bech32.decode(string, string.length)
30
+ raise ArgumentError, 'nip19 string must be String.' unless string.is_a?(String)
31
+ raise ArgumentError, "nip19 string must be at most #{MAX_LENGTH} characters." if string.length > MAX_LENGTH
32
+ hrp, data, spec = Bech32.decode(string, MAX_LENGTH)
27
33
 
28
34
  raise ArgumentError, 'Invalid nip19 string.' if hrp.nil?
29
35
  raise ArgumentError, 'Invalid bech32 spec.' unless spec == Bech32::Encoding::BECH32
data/lib/bech32/nostr.rb CHANGED
@@ -2,6 +2,7 @@ module Bech32
2
2
  module Nostr
3
3
  autoload :NIP19, 'bech32/nostr/nip19'
4
4
  autoload :BareEntity, 'bech32/nostr/entity'
5
+ autoload :TLVEntry, 'bech32/nostr/entity'
5
6
  autoload :TLVEntity, 'bech32/nostr/entity'
6
7
  end
7
8
 
@@ -10,6 +10,8 @@ module Bech32
10
10
  attr_accessor :ver # witness version
11
11
  attr_accessor :prog # witness program
12
12
 
13
+ # @param [String] addr segwit address. If given, it is parsed into hrp, witness version and program.
14
+ # @raise [ArgumentError] if addr is not a valid segwit address.
13
15
  def initialize(addr = nil)
14
16
  @hrp = HRP_MAINNET
15
17
  parse_addr(addr) if addr
@@ -22,10 +24,27 @@ module Bech32
22
24
  end
23
25
 
24
26
  # parse script pubkey into witness version and witness program
27
+ # @param [String] script_pubkey segwit script pubkey with hex format.
28
+ # @raise [ArgumentError] if the script is not a valid segwit script pubkey.
25
29
  def script_pubkey=(script_pubkey)
26
- values = [script_pubkey].pack('H*').unpack("C*")
27
- @ver = values[0] == 0 ? values[0] : values[0] - 0x50
28
- @prog = values[2..-1]
30
+ raise ArgumentError, 'script_pubkey must be String.' unless script_pubkey.is_a?(String)
31
+ raise ArgumentError, 'script_pubkey must be a hex string.' unless Bech32.hex_string?(script_pubkey)
32
+ values = [script_pubkey].pack('H*').unpack('C*')
33
+ raise ArgumentError, 'Invalid segwit script pubkey.' if values.length < 2
34
+ op, push_len = values[0], values[1]
35
+ prog = values[2..-1]
36
+ ver = if op == 0
37
+ 0
38
+ elsif op.between?(0x51, 0x60) # OP_1..OP_16
39
+ op - 0x50
40
+ else
41
+ raise ArgumentError, 'Invalid segwit script pubkey.'
42
+ end
43
+ raise ArgumentError, 'Invalid segwit script pubkey.' unless push_len == prog.length
44
+ raise ArgumentError, 'Invalid witness program' if prog.length < 2 || prog.length > 40
45
+ raise ArgumentError, 'Invalid witness program with version 0' if ver == 0 && prog.length != 20 && prog.length != 32
46
+ @ver = ver
47
+ @prog = prog
29
48
  end
30
49
 
31
50
  # Returns segwit address string which generated from hrp, witness version and witness program.
@@ -38,13 +57,13 @@ module Bech32
38
57
 
39
58
  def parse_addr(addr)
40
59
  @hrp, data, spec = Bech32.decode(addr)
41
- raise 'Invalid address.' if hrp.nil? || data[0].nil? || ![HRP_MAINNET, HRP_TESTNET, HRP_REGTEST].include?(hrp)
60
+ raise ArgumentError, 'Invalid address.' if hrp.nil? || data[0].nil? || ![HRP_MAINNET, HRP_TESTNET, HRP_REGTEST].include?(hrp)
42
61
  @ver = data[0]
43
- raise 'Invalid witness version' if @ver > 16
62
+ raise ArgumentError, 'Invalid witness version' if @ver > 16
44
63
  @prog = Bech32.convert_bits(data[1..-1], 5, 8, false)
45
- raise 'Invalid witness program' if @prog.nil? || @prog.length < 2 || @prog.length > 40
46
- raise 'Invalid witness program with version 0' if @ver == 0 && (@prog.length != 20 && @prog.length != 32)
47
- raise 'Witness version and encoding spec do not match' if (@ver == 0 && spec != Bech32::Encoding::BECH32) || (@ver != 0 && spec != Bech32::Encoding::BECH32M)
64
+ raise ArgumentError, 'Invalid witness program' if @prog.nil? || @prog.length < 2 || @prog.length > 40
65
+ raise ArgumentError, 'Invalid witness program with version 0' if @ver == 0 && (@prog.length != 20 && @prog.length != 32)
66
+ raise ArgumentError, 'Witness version and encoding spec do not match' if (@ver == 0 && spec != Bech32::Encoding::BECH32) || (@ver != 0 && spec != Bech32::Encoding::BECH32M)
48
67
  end
49
68
 
50
69
  end
@@ -5,6 +5,9 @@ module Bech32
5
5
  HRP_MAINNET = 'sp'
6
6
  HRP_TESTNET = 'tsp'
7
7
 
8
+ # Maximum valid version. Version 31 is reserved as invalid by BIP-352.
9
+ MAX_VERSION = 30
10
+
8
11
  attr_reader :hrp
9
12
  attr_reader :version
10
13
  attr_reader :scan_key
@@ -18,35 +21,72 @@ module Bech32
18
21
  def initialize(hrp, version, scan_key, spend_key)
19
22
  raise ArgumentError, "hrp must be sp or tsp." unless [HRP_MAINNET, HRP_TESTNET].include?(hrp)
20
23
  raise ArgumentError, "version must be Integer." unless version.is_a?(Integer)
24
+ raise ArgumentError, "version must be between 0 and #{MAX_VERSION}." unless version.between?(0, MAX_VERSION)
21
25
  raise ArgumentError, "scan_key must be String." unless scan_key.is_a?(String)
22
26
  raise ArgumentError, "spend_key must be String." unless spend_key.is_a?(String)
27
+ raise ArgumentError, 'scan_key must be a hex string.' unless Bech32.hex_string?(scan_key)
28
+ raise ArgumentError, 'spend_key must be a hex string.' unless Bech32.hex_string?(spend_key)
23
29
  raise ArgumentError, 'scan_key must be 33 bytes.' unless [scan_key].pack('H*').bytesize == 33
24
30
  raise ArgumentError, 'spend_key must be 33 bytes.' unless [spend_key].pack('H*').bytesize == 33
31
+ # BIP-352: keys are serialized in SEC1 compressed form (0x02 or 0x03 followed by the x coordinate).
32
+ # Whether the x coordinate is on the curve is not checked.
33
+ raise ArgumentError, 'scan_key must be a compressed public key.' unless compressed_key?(scan_key)
34
+ raise ArgumentError, 'spend_key must be a compressed public key.' unless compressed_key?(spend_key)
25
35
  @hrp = hrp
26
36
  @version = version
27
37
  @scan_key = scan_key
28
38
  @spend_key = spend_key
29
39
  end
30
40
 
41
+ # Byte length of the data part (scan key + spend key) for version 0.
42
+ KEYS_LENGTH = 66
43
+
44
+ # Number of 5-bit groups that cover KEYS_LENGTH bytes.
45
+ KEYS_GROUPS = (KEYS_LENGTH * 8 + 4) / 5
46
+
47
+ # Maximum length of an address string recommended by BIP-352.
48
+ MAX_LENGTH = 1023
49
+
31
50
  # Parse silent payment address.
51
+ # Following BIP-352, the data part of a version 0 address must be exactly 66 bytes.
52
+ # For versions 1 through 30, the first 66 bytes are read and the remaining bytes are discarded,
53
+ # so {#to_s} of such an address does not reproduce the original string if it had extra bytes.
32
54
  # @param [String] addr Silent payment address.
33
55
  # @return [Bech32::SilentPaymentAddr]
34
56
  # @raise [ArgumentError]
35
57
  def self.parse(addr)
36
58
  raise ArgumentError, "addr must be String." unless addr.is_a?(String)
37
- hrp, data, spec = Bech32.decode(addr, addr.length)
59
+ raise ArgumentError, "addr must be at most #{MAX_LENGTH} characters." if addr.length > MAX_LENGTH
60
+ hrp, data, spec = Bech32.decode(addr, MAX_LENGTH)
38
61
  raise ArgumentError, "addr must be encoded with bech32m." unless spec == Bech32::Encoding::BECH32M
39
62
  raise ArgumentError, 'Invalid hrp.' if hrp.nil? || data[0].nil? || ![HRP_MAINNET, HRP_TESTNET].include?(hrp)
40
63
  version = data[0]
41
- converted = Bech32.convert_bits(data[1..-1], 5, 8, false)
42
- raise ArgumentError, "Invalid data." if converted.nil?
43
- keys = converted.pack('C*').unpack1('H*')
44
- raise ArgumentError, "Invalid key size." unless keys.length == 132
64
+ if version.zero?
65
+ converted = Bech32.convert_bits(data[1..-1], 5, 8, false)
66
+ raise ArgumentError, "Invalid data." if converted.nil?
67
+ raise ArgumentError, "Invalid key size." unless converted.length == KEYS_LENGTH
68
+ else
69
+ # Convert only the 5-bit groups that cover the first 66 bytes, so that the discarded rest
70
+ # does not need to end on a byte boundary.
71
+ groups = data[1..-1]
72
+ raise ArgumentError, "Invalid key size." if groups.length < KEYS_GROUPS
73
+ converted = Bech32.convert_bits(groups[0...KEYS_GROUPS], 5, 8, true)
74
+ raise ArgumentError, "Invalid data." if converted.nil?
75
+ end
76
+ keys = converted[0...KEYS_LENGTH].pack('C*').unpack1('H*')
45
77
  scan = keys[0...66]
46
78
  spend = keys[66..-1]
47
79
  Bech32::SilentPaymentAddr.new(hrp, version, scan, spend)
48
80
  end
49
81
 
82
+ # Check whether the first byte of the 33-byte hex key is 0x02 or 0x03.
83
+ # @param [String] key public key with hex format.
84
+ # @return [Boolean]
85
+ def compressed_key?(key)
86
+ [0x02, 0x03].include?([key].pack('H*').getbyte(0))
87
+ end
88
+ private :compressed_key?
89
+
50
90
  # Get silent payment address.
51
91
  # @return [String]
52
92
  def to_s
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Bech32
4
- VERSION = '1.5.1'
4
+ VERSION = '1.7.0'
5
5
  end
data/lib/bech32.rb CHANGED
@@ -15,6 +15,9 @@ module Bech32
15
15
 
16
16
  BECH32M_CONST = 0x2bc830a3
17
17
 
18
+ # Maximum length of the human-readable part.
19
+ HRP_MAX_LENGTH = 83
20
+
18
21
  module_function
19
22
 
20
23
  # Returns the encoded Bech32 string.
@@ -26,7 +29,12 @@ module Bech32
26
29
  # <i>Generates:</i>
27
30
  # 'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4' # bech
28
31
  #
32
+ # @param [String] hrp human-readable part (1 to 83 lowercase characters in the range 33-126).
33
+ # @param [Array<Integer>] data data values (each 0 to 31).
34
+ # @param [Integer] spec encoding spec, see Bech32::Encoding.
35
+ # @raise [ArgumentError] if hrp or data is invalid.
29
36
  def encode(hrp, data, spec)
37
+ validate_encode_args(hrp, data)
30
38
  checksummed = data + create_checksum(hrp, data, spec)
31
39
  hrp + SEPARATOR + checksummed.map{|i|CHARSET[i]}.join
32
40
  end
@@ -51,6 +59,8 @@ module Bech32
51
59
  # check data length
52
60
  pos = bech.rindex(SEPARATOR)
53
61
  return nil if pos.nil? || pos < 1 || pos + 7 > bech.length || bech.length > max_length
62
+ # check hrp length (BIP-173: 1 to 83 characters), regardless of max_length
63
+ return nil if pos > HRP_MAX_LENGTH
54
64
  # check valid charset
55
65
  bech[pos+1..-1].each_char{|c|return nil unless CHARSET.include?(c)}
56
66
  # split hrp and data
@@ -117,6 +127,35 @@ module Bech32
117
127
  ret
118
128
  end
119
129
 
130
+ # Check whether +str+ is a hex string: an even number of hex characters (0-9, a-f, A-F).
131
+ # An empty string is a hex string of zero bytes. It never raises, whatever the encoding of +str+.
132
+ # @param [Object] str the value to check.
133
+ # @return [Boolean]
134
+ def hex_string?(str)
135
+ return false unless str.is_a?(String)
136
+ # Match on the raw bytes, so that invalid or non-ASCII-compatible encodings return false instead of raising.
137
+ bytes = str.b
138
+ bytes.bytesize.even? && bytes.match?(/\A\h*\z/n)
139
+ end
140
+
141
+ # Validate arguments of encode.
142
+ # @param [String] hrp human-readable part.
143
+ # @param [Array<Integer>] data data values.
144
+ # @raise [ArgumentError]
145
+ def validate_encode_args(hrp, data)
146
+ raise ArgumentError, 'hrp must be String.' unless hrp.is_a?(String)
147
+ unless hrp.length.between?(1, HRP_MAX_LENGTH)
148
+ raise ArgumentError, "hrp must be between 1 and #{HRP_MAX_LENGTH} characters."
149
+ end
150
+ if hrp.bytes.any? { |b| b < 33 || b > 126 } || hrp != hrp.downcase
151
+ raise ArgumentError, 'hrp must consist of lowercase characters in the range 33-126.'
152
+ end
153
+ raise ArgumentError, 'data must be Array.' unless data.is_a?(Array)
154
+ unless data.all? { |v| v.is_a?(Integer) && v.between?(0, 31) }
155
+ raise ArgumentError, 'data values must be Integer between 0 and 31.'
156
+ end
157
+ end
158
+
120
159
  # Compute Bech32 checksum
121
160
  def polymod(values)
122
161
  generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
@@ -129,6 +168,6 @@ module Bech32
129
168
  chk
130
169
  end
131
170
 
132
- private_class_method :polymod, :expand_hrp
171
+ private_class_method :polymod, :expand_hrp, :validate_encode_args
133
172
 
134
173
  end
@@ -9,6 +9,7 @@ module Bech32
9
9
  SEPARATOR: String
10
10
  CHARSET: Array[String]
11
11
  BECH32M_CONST: Integer
12
+ HRP_MAX_LENGTH: Integer
12
13
 
13
14
  # Encode hrp and data to bech32/bech32m string.
14
15
  def self.encode: (String hrp, Array[Integer] data, Integer spec) -> String
@@ -25,12 +26,16 @@ module Bech32
25
26
  # Verify checksum. Returns encoding spec if valid, nil otherwise.
26
27
  def self.verify_checksum: (String hrp, Array[Integer] data) -> Integer?
27
28
 
29
+ # Check whether the value is a hex string.
30
+ def self.hex_string?: (untyped str) -> bool
31
+
28
32
  # module_function methods are also available as instance methods
29
33
  def encode: (String hrp, Array[Integer] data, Integer spec) -> String
30
34
  def decode: (String bech, ?Integer max_length) -> [String, Array[Integer], Integer]?
31
35
  def convert_bits: (Array[Integer] data, Integer from, Integer to, ?bool padding) -> Array[Integer]?
32
36
  def create_checksum: (String hrp, Array[Integer] data, Integer spec) -> Array[Integer]
33
37
  def verify_checksum: (String hrp, Array[Integer] data) -> Integer?
38
+ def hex_string?: (untyped str) -> bool
34
39
 
35
40
  private
36
41
 
@@ -40,6 +45,10 @@ module Bech32
40
45
  # Compute polymod checksum.
41
46
  def self.polymod: (Array[Integer] values) -> Integer
42
47
 
48
+ # Validate arguments of encode.
49
+ def self.validate_encode_args: (String hrp, Array[Integer] data) -> void
50
+
43
51
  def expand_hrp: (String hrp) -> Array[Integer]
44
52
  def polymod: (Array[Integer] values) -> Integer
53
+ def validate_encode_args: (String hrp, Array[Integer] data) -> void
45
54
  end
@@ -12,6 +12,8 @@ module Bech32
12
12
  end
13
13
 
14
14
  class TLVEntry
15
+ MAX_VALUE_LENGTH: Integer
16
+
15
17
  attr_reader type: Integer
16
18
  attr_reader label: String?
17
19
  attr_reader value: String | Integer
@@ -20,13 +22,16 @@ module Bech32
20
22
  def initialize: (Integer type, String | Integer value, ?String? label) -> void
21
23
 
22
24
  # Convert to binary payload.
23
- def to_payload: () -> String
25
+ def to_payload: (?String? hrp) -> String
24
26
 
25
27
  # String representation.
26
28
  def to_s: () -> String
27
29
 
28
30
  private
29
31
 
32
+ # Check if the value of this entry is hex encoded.
33
+ def hex_value?: (String? hrp) -> bool
34
+
30
35
  # Check if string is hex encoded.
31
36
  def hex_string?: (String str) -> bool
32
37
  end
@@ -38,6 +43,10 @@ module Bech32
38
43
  TYPE_KIND: Integer
39
44
  TYPES: Array[Integer]
40
45
 
46
+ SUPPORTED_TYPES: Hash[String, Array[Integer]]
47
+ REQUIRED_TYPES: Hash[String, Array[Integer]]
48
+ KEY_LENGTH: Integer
49
+
41
50
  attr_reader hrp: String
42
51
  attr_reader entries: Array[TLVEntry]
43
52
 
@@ -49,6 +58,15 @@ module Bech32
49
58
 
50
59
  # Encode to bech32 string.
51
60
  def encode: () -> String
61
+
62
+ # Check the byte length of a TLV value.
63
+ def self.check_value_length: (String hrp, Integer type, Integer length) -> void
64
+
65
+ # Check that all required TLV types are present.
66
+ def self.check_required_types: (String hrp, Array[TLVEntry] entries) -> void
67
+
68
+ # Check the character encoding of a relay or identifier value.
69
+ def self.check_value_encoding: (String hrp, Integer type, String value) -> void
52
70
  end
53
71
  end
54
72
  end
@@ -12,6 +12,7 @@ module Bech32
12
12
  BARE_PREFIXES: Array[String]
13
13
  TLV_PREFIXES: Array[String]
14
14
  ALL_PREFIXES: Array[String]
15
+ MAX_LENGTH: Integer
15
16
 
16
17
  # Decode NIP-19 bech32 string.
17
18
  def self.decode: (String string) -> (BareEntity | TLVEntity)
@@ -3,6 +3,10 @@ module Bech32
3
3
  class SilentPaymentAddr
4
4
  HRP_MAINNET: String
5
5
  HRP_TESTNET: String
6
+ MAX_VERSION: Integer
7
+ KEYS_LENGTH: Integer
8
+ KEYS_GROUPS: Integer
9
+ MAX_LENGTH: Integer
6
10
 
7
11
  attr_reader hrp: String
8
12
  attr_reader version: Integer
@@ -17,5 +21,10 @@ module Bech32
17
21
 
18
22
  # Generate silent payment address string.
19
23
  def to_s: () -> String
24
+
25
+ private
26
+
27
+ # Check whether the key starts with 0x02 or 0x03.
28
+ def compressed_key?: (String key) -> bool
20
29
  end
21
30
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bech32
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.5.1
4
+ version: 1.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Shigeyuki Azuchi