Re: Ruby Quiz - Challenge #15 - Generate the Bitcoin (Base58) Address from the (Elliptic Curve) Public Key

Gerald Bauer <[email protected]> Tue, 23 Jul 2019 14:03:37 +0200
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAAxEZd_AmMELraOoaKP5O6UfRw9oLCmAQBvfi2_Og4GGxHbBww@mail.gmail.com>
Hello Ruby Quiz Friends,

    Continuing talking to myself. Just for the record - spoiler alert
(!) - I posted my little test (reference) answer / solution [1] for
the code challenge / quiz  #15 -  Generate the Bitcoin (Base58)
Address from the
(Elliptic Curve) Public Key..

require 'digest'

module Base58
  ALPHABET = %w[
        1 2 3 4 5 6 7 8 9
      A B C D E F G H   J K L M N   P Q R S T U V W X Y Z
      a b c d e f g h i j k   m n o p q r s t u v w x y z
  ]
  BASE = 58   # note: ALPHABET.length == 58

  def self.encode( hex )
    num = hex.to_i(16)

    buf = String.new
    while num > 0
      remainder = num % BASE
      buf = ALPHABET[remainder] + buf
      num = num / BASE
    end

    # Note: Leading zeros (in bytes, that is, 00 in hex)
    ##      need to get preserved and added up front (0 in base58 is 1)
    leading_zero_bytes = (hex.match( /^(0+)/ ) ? $1 : '').size / 2

    (ALPHABET[0]*leading_zero_bytes) + buf
  end
end  # module Base58


def base58( hex ) Base58.encode( hex ); end


def hash160( pubkey )
  binary    = [pubkey].pack( "H*" )       # Convert to binary (string)
first before hashing
  sha256    = Digest::SHA256.digest( binary )
  ripemd160 = Digest::RMD160.digest( sha256 )
              ripemd160.unpack( "H*" )[0]    # Convert back to hex
(string) from binary (string)
end

def hash256( hex )
  binary = [hex].pack( "H*" )       # Convert to binary (string) first
before hashing
  step1  = Digest::SHA256.digest( binary )
  step2  = Digest::SHA256.digest( step1 )
           step2.unpack( "H*" )[0]    # Convert back to hex (string)
from binary (string)
end

   Happy crypto hashing with ruby. Cheers. Prost.

[1] https://github.com/planetruby/quiz/blob/master/015/solution.rb

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>