Bitcoin/address validation: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (actually RIPEMD-160 is not needed for address validation)
Line 3: Line 3:
Write a program that takes a [[wp:bitcoin|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.
Write a program that takes a [[wp:bitcoin|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]] and [[RIPEMD-160]].
You can use a digest library for [[SHA-256]].


==Unix shell==
==Unix shell==

Revision as of 19:38, 27 November 2012

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 a digest library for SHA-256.

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>