# Bitcoin address validator in C

Here is a Bitcoin address validator I am looking to have reviewed in C. Normally I would have the enum and function prototypes declared in a header file, but I decided for the purpose of this question to integrate them into one for easy copying and compilation.

/**
* @file bitcoin.c
*/

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

/**
* @fn BitcoinAddressState unbase58(const char *s, unsigned char *out)
* @brief Takes a base58 encoded address and decodes it into the receiver. Errors are returned if the argument is not valid base58 or if the decoded value does not fit in the 25 byte address.
* @return The state of decoding the Bitcoin address
*/
{
/* A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters 0, O, I and l. */
const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
const char *p;

memset(out, 0, 25);
for (int i = 0; addr[i]; ++i)
{

size_t c = p - tmpl;
for (int j = 25; --j; )
{
c += 58 * out[j];
out[j] = c % 256;
c /= 256;
}
}
return VALID;
}

/**
* @brief Takes a Bitcoin address as argument, and checks whether or not the address is valid.
* @return The state of the Bitcoin address
*/
{
unsigned char dec[32];
unsigned char d1[SHA256_DIGEST_LENGTH];
unsigned char d2[SHA256_DIGEST_LENGTH];

if (val) return val;

SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);

if (memcmp(dec + 21, d2, 4)) return BAD_DIGEST;

return VALID;
}

int main (void) {
{
"1EYDqUKuLKF9di1pSEtEfNA8pj2CgL7Wne", // my actual Bitcoin wallet address
0
};
for (int i = 0; addresses[i]; ++i)
{
{
case VALID:
puts("Okay");
break;
break;
break;
break;
default:
puts("An unknown error occurred");
break;
}
}
}

• there is a c99 and a c11 I didn't edit either in because I don't know which one this is I was thinking that I just put in c99 because it sounds like that is the lowest one that would be possible given your comment on @vnp's answer – Malachi Jul 28 '14 at 13:32

• Instead of switch I'd rather have a table of strings indexed by BitcoinAddressState values.
• In C, main must return a value explicitly.
• Rebuttling your last point: C99 & C11 §5.1.2.2(3) says, "...reaching the } that terminates the main() function returns a value of 0." – syb0rg Jul 24 '14 at 22:25
• When no standard version is mentioned, I feel it makes little sense to assume a 30 year old version (C89) rather than the current version (C11) or the one before that (C99), even for C. (That said, I agree that main should nonetheless return an explicit value.) – Will Aug 1 at 17:38