forked from sinantaifour/braimey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase58.rb
More file actions
52 lines (46 loc) · 1.53 KB
/
base58.rb
File metadata and controls
52 lines (46 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Adapated from pywallet.
# Implements the variant of Base58 encoding used in BitCoin.
# Probably doesn't play well with unicode, but that's not needed for BitCoin
# addresses.
require 'bigdecimal'
class Base58
CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
BASE = CHARS.length
def self.encode58(str)
# Turn the string into a number.
num = BigDecimal.new(0)
str.split("").reverse.each_with_index do |c, i|
num += c.ord * (256) ** i
end
# Turn the number into a string using the Base58 alphabet.
res = ""
while num > 0 do
mod = num % BASE
res = CHARS[mod] + res
num = (num - mod) / BASE
end
# Encoding leading zeros, every leading zero byte is replaced with an
# instance of CHARS[0] (thus doing a bit of leading-zero compression).
num_leading_zeros = str.split("").inject(0) { |a, c| break a if c.ord != 0; a + 1 }
CHARS[0] * num_leading_zeros + res
end
def self.decode58(str)
# Strip leading zeros.
num_leading_zeros = str.split("").inject(0) { |a, c| break a if c != CHARS[0]; a + 1 }
str = str[num_leading_zeros..-1]
# Turn the string into a number.
num = BigDecimal.new(0)
str.split("").reverse.each_with_index do |c, i|
num += CHARS.index(c) * BASE ** i
end
# Get the binary representation of the number.
res = ""
while num > 0 do
mod = num % 256
res = mod.to_i.chr + res
num = (num - mod) / 256
end
# Add back the leading zeros.
0.chr * num_leading_zeros + res
end
end