diff --git a/Gemfile b/Gemfile index 776cf26b..2cf72485 100644 --- a/Gemfile +++ b/Gemfile @@ -30,6 +30,7 @@ gem 'geoip' gem 'io-extra', require: 'io/extra' gem 'rye' gem 'dnsruby' +gem 'base32' platform :mri, :rbx do gem 'magic' # sudo apt-get install file, For OSX: brew install libmagic diff --git a/Gemfile.lock b/Gemfile.lock index 6e10420f..7f7dfeb9 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -16,6 +16,7 @@ GEM addressable (>= 2.3.1) extlib (>= 0.9.15) multi_json (>= 1.0.0) + base32 (0.3.2) bcrypt (3.1.7) blankslate (3.1.3) builder (3.2.2) @@ -261,6 +262,7 @@ PLATFORMS DEPENDENCIES ago + base32 bcrypt capybara_minitest_spec cocaine diff --git a/ext/base58.rb b/ext/base58.rb new file mode 100644 index 00000000..048f7cb8 --- /dev/null +++ b/ext/base58.rb @@ -0,0 +1,41 @@ +module Base58 + class << self + def int_to_base58(int_val, leading_zero_bytes=0) + alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + base58_val, base = '', alpha.size + while int_val > 0 + int_val, remainder = int_val.divmod(base) + base58_val = alpha[remainder] + base58_val + end + base58_val + end + + def base58_to_int(base58_val) + alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + int_val, base = 0, alpha.size + base58_val.reverse.each_char.with_index do |char,index| + raise ArgumentError, 'Value not a valid Base58 String.' unless char_index = alpha.index(char) + int_val += char_index*(base**index) + end + int_val + end + + def base58_to_bytestring(base58_val) + [Base58.decode_base58(base58_val)].pack('H*') + end + + def encode_base58(hex) + leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 + ("1"*leading_zero_bytes) + int_to_base58( hex.to_i(16) ) + end + + def decode_base58(base58_val) + s = base58_to_int(base58_val).to_s(16); s = (s.bytesize.odd? ? '0'+s : s) + s = '' if s == '00' + leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size + s = ("00"*leading_zero_bytes) + s if leading_zero_bytes > 0 + s + end + alias_method :base58_to_hex, :decode_base58 + end +end diff --git a/models/archive.rb b/models/archive.rb index 53731056..93b30b03 100644 --- a/models/archive.rb +++ b/models/archive.rb @@ -1,9 +1,19 @@ +require 'base32' + class Archive < Sequel::Model many_to_one :site set_primary_key [:site_id, :ipfs_hash] unrestrict_primary_key + def self.base58_to_hshca(base58) + Base32.encode(Base58.base58_to_bytestring(base58)).gsub('=', '').downcase + end + + def hshca_hash + self.class.base58_to_hshca ipfs_hash + end + def url - "https://#{ipfs_hash}.ipfs.neocities.org" + "http://#{hshca_hash}.ipfs.neocitiesops.net" end end