Bitcoin/address validation

From Rosetta Code
Revision as of 19:36, 27 November 2012 by Grondilu (talk | contribs) (Created page with "{{draft task}} Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. The program can either return a bool...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Bitcoin/address validation is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. The program can either return a boolean value or throw an exception when not valid.

You can use digest libraries for SHA-256 or RIPEMD-160.

Unix shell

<lang bash>base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z}) bitcoinregex="^[$(printf "%s" "${base58[@]}")]{34}$"

decodeBase58() {

   local s=$1
   for i in {0..57}
   do s="${s//${base58[i]}/ $i}"
   done
   dc <<< "16o0d${s// /+58*}+f" 

}

checksum() {

   xxd -p -r <<<"$1" |
   openssl dgst -sha256 -binary |
   openssl dgst -sha256 -binary |
   xxd -p -c 80 |
   head -c 8

}

checkBitcoinAddress() {

   if "$1" =~ $bitcoinregex 
   then
       h=$(decodeBase58 "$1")
       checksum "00${h::${#h}-8}" |
       grep -qi "^${h: -8}$"
   else return 2
   fi

}</lang>