Module: RCS::B58Encode

Extended by:
B58Encode
Included in:
B58Encode
Defined in:
lib/rcs-common/evidence/money.rb

Constant Summary collapse

@@__b58chars =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
@@__b58base =
@@__b58chars.bytesize

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(v, length) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/rcs-common/evidence/money.rb', line 176

def self.decode(v, length)
  #decode v into a string of len bytes

  long_value = 0
  v.chars.to_a.reverse.each_with_index do |c, i|
    long_value += @@__b58chars.index(c) * (@@__b58base**i)
  end

  result = ''
  while long_value >= 256 do
    div, mod = long_value.divmod(256)
    result = mod.chr + result
    long_value = div
  end
  result = long_value.chr + result

  nPad = 0
  v.chars.to_a.each do |c|
    c == @@__b58chars[0] ? nPad += 1 : break
  end
  result = 0.chr * nPad + result

  if !length.nil? and result.size != length
    return nil
  end

  return result
end

.encode(v) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/rcs-common/evidence/money.rb', line 152

def self.encode(v)
  # encode v, which is a string of bytes, to base58.

  long_value = 0
  v.chars.to_a.reverse.each_with_index do |c, i|
    long_value += (256**i) * c.ord
  end

  result = ''
  while long_value >= @@__b58base do
    div, mod = long_value.divmod(@@__b58base)
    result = @@__b58chars[mod] + result
    long_value = div
  end
  result = @@__b58chars[long_value] + result

  nPad = 0
  v.chars.to_a.each do |c|
    c == "\0" ? nPad += 1 : break
  end

  return (@@__b58chars[0] * nPad) + result
end

Instance Method Details

#bc_address_to_hash_160(addr) ⇒ Object



223
224
225
226
# File 'lib/rcs-common/evidence/money.rb', line 223

def bc_address_to_hash_160(addr)
  bytes = self.decode(addr, 25)
  return bytes[1..20]
end

#hash_160(public_key) ⇒ Object



205
206
207
208
209
# File 'lib/rcs-common/evidence/money.rb', line 205

def hash_160(public_key)
  h1 = Digest::SHA256.new.digest(public_key)
  h2 = Digest::RMD160.new.digest(h1)
  return h2
end

#hash_160_to_bc_address(h160, version = 0) ⇒ Object



216
217
218
219
220
221
# File 'lib/rcs-common/evidence/money.rb', line 216

def hash_160_to_bc_address(h160, version = 0)
  vh160 = version.chr + h160
  h3 = Digest::SHA256.new.digest(Digest::SHA256.new.digest(vh160))
  addr = vh160 + h3[0..3]
  return self.encode(addr)
end

#public_key_to_bc_address(public_key, version = 0) ⇒ Object



211
212
213
214
# File 'lib/rcs-common/evidence/money.rb', line 211

def public_key_to_bc_address(public_key, version = 0)
  h160 = hash_160(public_key)
  return hash_160_to_bc_address(h160, version)
end