How I can validate a standard bitcoin address?


If it is the format and the checksum then that can be easily done. Specifically you can use steps 4 to 9 in the technical description of Addresses to check for typos. Beyond that however it gets difficult

If you want to access blockchain information such as the current balance you cannot unless you have a copy of the blockchain somewhere, and on a phone or tablet disk space is still too precious for that. For that you'll need to rely on some external service or sacrifice disk space to track the blockchain in its entirety.

Notice that Andreas' Bitcoin Wallet only selectively tracks addresses that were known while synchronizing with the network, so if the addresses you'll eventually be interested in are known in advance you could also selectively sync those.

EDIT: as requested here is the reversed example from the documentation, as python code:

import hashlib

# Take the address as input, using the sample address from the
# technical description to follow along
address = "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"

# Decode into 25 bytes (0x00 for the network identifier, 20 byte
# RIPE-160 hash and 4 byte checksum
decoded_address = b58decode(address,25)

# Print as hex, should match step 8 in the docs
print decoded_address.encode("hex")

# Slice into its components
network_id = decoded_address[0]
private_key_hash = decoded_address[1:21]
checksum = decoded_address[-4:]

if network_id != chr(0):
    print "ERROR: not a Bitcoin Main Net address"

# Print the private key hash as hex, matches step 4 in the docs
print private_key_hash.encode("hex")

# Print the checksum as hex, matches step 7 from the docs
print checksum.encode("hex")

# Now we can check the checksum to reduce chances of typos
# Print first round of hashing (docs step 5)
hash1 = hashlib.sha256(network_id + private_key_hash).digest()
print hash1.encode("hex")

# Print second round of hashing (docs step 6)
hash2 = hashlib.sha256(hash1).digest()
print hash2.encode("hex")

# And finally verify that the checksum we extracted from the address
# and the one we just calculated match

if checksum == hash2[:4]:
    print "Everything ok, checksums match"
    print "The end is nigh"

Sadly we can't go any further in verifying without further information, like the actual public key.

  • Do you have any code which implement steps 4 to 9 ?
    – Alex
    Oct 16 '13 at 14:37
  • I assume this would not work with a SegWit address (starting with a "3") or a Bech32 address (starting with a "bc1")?
    – pferg
    May 8 '19 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.