Sunday, October 5, 2014

A simple second Ruby bitcoin program

In order to get this to run you need install the ffi gem with:

     $ sudo gem install ffi

Now save the following code in a file (I called mine check.rb):

     require 'bitcoin'
   
     privwif = ARGV[0]
   
     mykey = Bitcoin::Key.from_base58(privwif)
     puts mykey.addr

If you run this with a valide base58 private key, it will output the corresponding public key. But there is one problem - if the private key is invalid, you get a complicated error. So let's add a section to check for this. Replace your file with the following:

     require 'bitcoin'
   
     privwif = ARGV[0]
   
     begin
       mykey = Bitcoin::Key.from_base58(privwif)
       puts mykey.addr
     rescue
         puts "Invalid private key."
     end

As soon as the wrong key error occurs the program jumps to the rescue section and prints out that there is an invalid key. However, if any other error occurs it will also print that message, so the program needs extending.