Pages:
Author

Topic: Python code for validating bitcoin address (Read 47294 times)

newbie
Activity: 16
Merit: 0
March 18, 2014, 07:42:15 AM
#46
A few people mentioned a 27 character bitcoin address, but there's been no mention that 26 character addresses exist. 11111111111111111111ufYVpS is an example.  The odds of it actually coming up in practice seem astronomical, but it is still valid (and a couple of the code examples here give a false negative for it).
newbie
Activity: 1
Merit: 0
February 25, 2014, 07:47:14 PM
#45
Special thanks to Gavin Anderson

So I re-worked Gavin's code just a little bit, so I could basically type cast a Bitcoin address.

Below is my code.  Please let me know if you find any issues.

Code:
#!/usr/bin/env python
"""
# Special thanks to Gavin Andresen from bitcointalk.org
# in reference to: https://bitcointalk.org/index.php?topic=1026.0
# Edited By/Author Josh Lee PyTis.com, I also release my changes into the
# public domain.
"""

class BTCaddress(str):
""" Custom Bitcoin Address Verify-turend into a type for type-casting.
"""
import re

address_pattern = "[a-zA-Z1-9]{27,35}$"
address_expr = re.compile(r"%s"%address_pattern)
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
_valid = False
_version = None

def __new__(cls,val):
if val is None:
# allow None to be passed in, so that we may clear out bitcoin addresses
# if you want, youc an raise an error instead, so that None doesn't pass silently
inst = str.__new__(cls, None)
inst._valid = False
inst._version = None
return inst

# I don't know if there could be a valid address with only numbers, but just in-case
if isinstance(val, int): val = str(val)

# remove preceading and trailing whitespace
if isinstance(val, basestring):
val = val.strip()
if not val:
# again, allow '' to be passed in, so that we may clear out bitcoin addresses
# if you want, you can raise an error instead, so that None doesn't pass silently
inst = str.__new__(cls, None)
inst._valid = False
inst._version = None
return inst
else:
if not cls.address_expr.match(val):
raise ValueError('Invalid Bitcoin address. Bad RE match r"%s".' % cls.address_pattern)
version = cls.getVersion(val)
if version is None:
raise ValueError('Invalid Bitcoin address. Version Missmatch: %r' % version)
else:
inst = str.__new__(cls, val)
inst._valid = True
inst._version = version
return inst
else:
raise TypeError('Invalid Bitcoin address. Not a string.')

valid = property(lambda s: s._valid)
version = property(lambda s: s._version)

@classmethod
def getVersion(cls, strAddress):
""" Returns None if strAddress is invalid. Otherwise returns integer version of address. """
from Crypto.Hash import SHA256
addr = cls.b58decode(strAddress,25)
if addr is None: return None
version = addr[0]
checksum = addr[-4:]
vh160 = addr[:-4] # Version plus hash160 is what is checksummed
h3=SHA256.new(SHA256.new(vh160).digest()).digest()
if h3[0:4] == checksum:
return ord(version)
return None

@classmethod
def b58encode(cls, v):
""" encode v, which is a string of bytes, to base58.
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += (256**i) * ord(c)
result = ''
while long_value >= cls.__b58base:
div, mod = divmod(long_value, cls.__b58base)
result = cls.__b58chars[mod] + result
long_value = div
result = cls.__b58chars[long_value] + result

# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break

return (cls.__b58chars[0]*nPad) + result

@classmethod
def b58decode(cls, v, length):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += cls.__b58chars.find(c) * (cls.__b58base**i)

result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result

nPad = 0
for c in v:
if c == cls.__b58chars[0]: nPad += 1
else: break

result = chr(0)*nPad + result
if length is not None and len(result) != length:
return None

return result

# - - - - - - - - - - - - - -
# END OF Custom Type class.
#



#
# tests below
# I found a page on a bitcoin wiki to explain to me different bitcoin address
# versions, I decided to test these, and other things that could go wrong.
# I then altered my code above, to get desired results.
#
# For more information on bitcoin address versions, please follow link:
# https://en.bitcoin.it/wiki/List_of_address_prefixes

tests = [
'17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem', # version 0 || TEST 1
u'3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX', # version 5 || TEST 2
'LhK2kQwiaAvhjWY799cZvMyYwnQAcxkarr', # vesrion 48 || TEST 3
'NATX6zEUNfxfvgVwz8qVnnw3hLhhYXhgQn', # version 52 || TEST 4
'mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn', # version 111 || TEST 5
'5Hwgr3u458GLafKBgxtssHSPqJnYoGrSzgQsPwLFhLNYskDPyyA', # version 128 || TEST 6
'92Pg46rUhgTT7romnV7iGW6W1gbGdeezqdbJCzShkCsYNzyyNcc', # version 239 || TEST 7
None, # testing None, No version || TEST 8
' 1111111111111111111114oLvT2', # test from https://bitcointalk.org/index.php?topic=1026.0 || TEST 9
float(123456789.01), #|| TEST 10
bool(True), # || TEST 11
'', # || TEST 12
'1NnZEPLmBEK2HryY4heeJQhQPB8LLbNiPe' # my bitcoin address :-) || TEST 13
]

for i, test in enumerate(tests):
print '-'*80
print 'typeof test: ', type(test)
print 'original value: ', test
try:
t = BTCaddress(test)
except TypeError, e:
print "TypeError: %s" % str(e)
except  ValueError, e:
print "ValueError: %s" % str(e)
else:
print 'test %s' % i, t
print 'test %s.type' % i, type(t)
print 'test %s.valid' % i, t.valid
print 'test %s.version' % i, t.version
print 't.getVersion()', t.getVersion(str(t))

print


-- fixed

Test output below:
Quote
--------------------------------------------------------------------------------
typeof test:  
original value:  17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem
test 0 17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem
test 0.type
test 0.valid True
test 0.version 0
--------------------------------------------------------------------------------
typeof test:  
original value:  3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
test 1 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
test 1.type
test 1.valid True
test 1.version 5
--------------------------------------------------------------------------------
typeof test:  
original value:  LhK2kQwiaAvhjWY799cZvMyYwnQAcxkarr
test 2 LhK2kQwiaAvhjWY799cZvMyYwnQAcxkarr
test 2.type
test 2.valid True
test 2.version 48
--------------------------------------------------------------------------------
typeof test:  
original value:  NATX6zEUNfxfvgVwz8qVnnw3hLhhYXhgQn
test 3 NATX6zEUNfxfvgVwz8qVnnw3hLhhYXhgQn
test 3.type
test 3.valid True
test 3.version 52
--------------------------------------------------------------------------------
typeof test:  
original value:  mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn
test 4 mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn
test 4.type
test 4.valid True
test 4.version 111
--------------------------------------------------------------------------------
typeof test:  
original value:  5Hwgr3u458GLafKBgxtssHSPqJnYoGrSzgQsPwLFhLNYskDPyyA
ValueError: Invalid Bitcoin address. Bad RE match r"[a-zA-Z1-9]{27,35}$".
--------------------------------------------------------------------------------
typeof test:  
original value:  92Pg46rUhgTT7romnV7iGW6W1gbGdeezqdbJCzShkCsYNzyyNcc
ValueError: Invalid Bitcoin address. Bad RE match r"[a-zA-Z1-9]{27,35}$".
--------------------------------------------------------------------------------
typeof test:  
original value:  None
test 7 None
test 7.type
test 7.valid False
test 7.version None
--------------------------------------------------------------------------------
typeof test:  
original value:   1111111111111111111114oLvT2
test 8 1111111111111111111114oLvT2
test 8.type
test 8.valid True
test 8.version 0
--------------------------------------------------------------------------------
typeof test:  
original value:  123456789.01
TypeError: Invalid Bitcoin address. Not a string.
--------------------------------------------------------------------------------
typeof test:  
original value:  True
ValueError: Invalid Bitcoin address. Bad RE match r"[a-zA-Z1-9]{27,35}$".
--------------------------------------------------------------------------------
typeof test:  
original value:  
test 11 None
test 11.type
test 11.valid False
test 11.version None
--------------------------------------------------------------------------------
typeof test:  
original value:  1NnZEPLmBEK2HryY4heeJQhQPB8LLbNiPe
test 12 1NnZEPLmBEK2HryY4heeJQhQPB8LLbNiPe
test 12.type
test 12.valid True
test 12.version 0

-- last fix was just a typo in a code's comment
newbie
Activity: 3
Merit: 0
January 20, 2014, 08:34:07 AM
#44
OK, duh, the problem was with the version number. The address' version is 6F, which is bogus, but otherwise it is valid. Code which doesn't care about the version number will report the address as valid.
newbie
Activity: 3
Merit: 0
January 19, 2014, 11:18:20 AM
#43
I wrote an Ada version of the bitcoin address validation code and posted it at rosettacode.org.
The example address someone posted in this thread, "miwxGypTcHDXT3m4avmrMMC4co7XWqbG9r," gets reported as invalid, but it also gets reported as invalid by http://blockexplorer.com/q/checkaddress/miwxGypTcHDXT3m4avmrMMC4co7XWqbG9r
Does someone have a quick answer to this puzzle? Ada is a good language to write reliable code, so I think it would be a good idea to have reference code for Ada for key functions like this.

 
newbie
Activity: 27
Merit: 0
January 04, 2014, 06:43:39 PM
#42
This is regardless of whatever language you are trying to use and will require a bitcoind wallet running on your machine. basically take whatever text field that has the string you're trying to validate and turn it into a variable.


in your app or web page... textbox = $varAddress

onclick or script... whatever, send this to the wallet.
bitcoind validateaddress $varAddress

monitor response from [isvalid]. if "true," execute code. if false, execute other code.



Valid Address: [isvalid] = true            [address] = submitted address
Code:
server:~$ bitcoind validateaddress mkZuF2onXAxyGuuvoALbPEesMg99uv6k7r
{
    "isvalid" : true,
    "address" : "mkZuF2onXAxyGuuvoALbPEesMg99uv6k7r",
    "ismine" : false
}


Invalid Address: [isvalid] = false
Code:
server:~$ bitcoind validateaddress mkZuF2onXAxyGuuvoALbPEeIMg99uv6k7r 
{
    "isvalid" : false
}


Invalid Address: [isvalid] = false
Code:
server:~$ bitcoind validateaddress 7kZuF2onXAxyGuuvoALbPEeIMg99uv6k7r
{
    "isvalid" : false
}

legendary
Activity: 1094
Merit: 1000
Is there any standalone Python code floating around out there? This is what I am using right now:

Code:
	def validate_address(self, address):
"""
Does simple validation of a bitcoin-like address.
Source: http://bit.ly/17OhFP5

param : address : an ASCII or unicode string, of a bitcoin address.
returns : boolean, indicating that the address has a correct format.

"""

address = self.clean(address)
# The first character indicates the "version" of the address.
CHARS_OK_FIRST = "123"
# alphanumeric characters without : l I O 0
CHARS_OK = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

# We do not check the high length limit of the address.
# Usually, it is 35, but nobody knows what could happen in the future.
if len(address) < 27:
return False
elif address[0] not in CHARS_OK_FIRST:
return False

# We use the function "all" by passing it an enumerator as parameter.
# It does a little optimization :
# if one of the character is not valid, the next ones are not tested.
return all( ( char in CHARS_OK for char in address[1:] ) )
legendary
Activity: 1722
Merit: 1003
The pastebin code is mine and public domain. That bitcoin-php library is a separate thing that I wasn't involved with.


Great, thanks. I just glanced at the function sigs and assumed they were by the same author. In any event, I just integrated your code from that pastebin link. That was easy - thanks very much!
administrator
Activity: 4228
Merit: 8647
The pastebin code is mine and public domain. That bitcoin-php library is a separate thing that I wasn't involved with.
legendary
Activity: 1722
Merit: 1003
why is there no simple tool like  http://blockexplorer.com/q/checkaddress

/q/checkaddress uses this plus some extra checking. Note that the checkAddress function assumes that the input is valid base58. Do something like:

Code:
if(preg_match('/^[1-9A-HJ-NP-Za-km-z]+$/', $address) && strlen($address) <= 34 && checkAddress($address))
    address is valid

theymos - that pastebin-linked code is yours, right, from: http://code.gogulski.com/bitcoin-php/

Just want to make sure the public domain license applies before I integrate.

Thanks!
legendary
Activity: 902
Merit: 1002
The code mentioned in the original post returns true for BTC and LTC addresses, because
Code:
get_bcaddress_version(address)

returns 0 for BTC addresses and 48 for LTC addresses, so both is not None. I wouldnt call this a bug, more a feature that allowes to check other coin addresses.
hero member
Activity: 924
Merit: 501
after further testing it appears to be working as expected.  Here's the working code:


called with:

http://yourdomain/btcvalidate.php?address="btc-address-here"



btcvalidate.php:

Code:
include("base58.php"); ?>














btc address validator


$address $_GET["address"];
if(
preg_match('/^[1-9A-HJ-NP-Za-km-z]+$/'$address) && strlen($address) <= 34 && checkAddress($address)){
echo    "

address is valid

"
;
} else {
echo    "

address is NOT valid

"
;
}
?>
 




base58.php:

Code:
/*



*/
//hex input must be in uppercase, with no leading 0x
define("ADDRESSVERSION","00"); //this is a hex byte

function decodeHex($hex){
$hex=strtoupper($hex);
$chars="0123456789ABCDEF";
$return="0";
for($i=0;$i<strlen($hex);$i++){
$current=(string)strpos($chars,$hex[$i]);
$return=(string)bcmul($return,"16",0);
$return=(string)bcadd($return,$current,0);
}
return $return;
}

function 
encodeHex($dec){
$chars="0123456789ABCDEF";
$return="";
while (bccomp($dec,0)==1){
$dv=(string)bcdiv($dec,"16",0);
$rem=(integer)bcmod($dec,"16");
$dec=$dv;
$return=$return.$chars[$rem];
}
return strrev($return);
}

function 
decodeBase58($base58){
$origbase58=$base58;

$chars="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
$return="0";
for($i=0;$i<strlen($base58);$i++){
$current=(string)strpos($chars,$base58[$i]);
$return=(string)bcmul($return,"58",0);
$return=(string)bcadd($return,$current,0);
}

$return=encodeHex($return);

//leading zeros
for($i=0;$i<strlen($origbase58)&&$origbase58[$i]=="1";$i++){
$return="00".$return;
}

if(strlen($return)%2!=0){
$return="0".$return;
}

return $return;
}

function 
encodeBase58($hex){
if(strlen($hex)%2!=0){
die("encodeBase58: uneven number of hex characters");
}
$orighex=$hex;

$chars="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
$hex=decodeHex($hex);
$return="";
while (bccomp($hex,0)==1){
$dv=(string)bcdiv($hex,"58",0);
$rem=(integer)bcmod($hex,"58");
$hex=$dv;
$return=$return.$chars[$rem];
}
$return=strrev($return);

//leading zeros
for($i=0;$i<strlen($orighex)&&substr($orighex,$i,2)=="00";$i+=2){
$return="1".$return;
}

return $return;
}

function 
hash160ToAddress($hash160,$addressversion=ADDRESSVERSION){
$hash160=$addressversion.$hash160;
$check=pack("H*" $hash160);
$check=hash("sha256",hash("sha256",$check,true));
$check=substr($check,0,8);
$hash160=strtoupper($hash160.$check);
return encodeBase58($hash160);
}

function 
addressToHash160($addr){
$addr=decodeBase58($addr);
$addr=substr($addr,2,strlen($addr)-10);
return $addr;
}

function 
checkAddress($addr,$addressversion=ADDRESSVERSION){
$addr=decodeBase58($addr);
if(strlen($addr)!=50){
return false;
}
$version=substr($addr,0,2);
if(hexdec($version)>hexdec($addressversion)){
return false;
}
$check=substr($addr,0,strlen($addr)-8);
$check=pack("H*" $check);
$check=strtoupper(hash("sha256",hash("sha256",$check,true)));
$check=substr($check,0,8);
return $check==substr($addr,strlen($addr)-8);
}

function 
hash160($data){
$data=pack("H*" $data);
return strtoupper(hash("ripemd160",hash("sha256",$data,true)));
}

function 
pubKeyToAddress($pubkey){
return hash160ToAddress(hash160($pubkey));
}

function 
remove0x($string){
if(substr($string,0,2)=="0x"||substr($string,0,2)=="0X"){
$string=substr($string,2);
}
return $string;
}

?>

administrator
Activity: 4228
Merit: 8647
I'm not getting the same results I see from http://blockexplorer.com/q/checkaddress/ with the above php code.  Checking further...

In what cases? It should be identical other than /q/checkaddress's additional info about why the address failed.
legendary
Activity: 1176
Merit: 1111
May Bitcoin be touched by his Noodly Appendage
That's why I told you to look for the definition of DecodeBase58Check in the code, that's the function to decode address to hash160
hero member
Activity: 924
Merit: 501
thank you thank you.  dang dude, I can't dive into a 1700 line program right now.  what's that do with all those lines?

fwiw my code is down to 7 lines, and two of those are comments.

Code:
// use with validator.php?refund=btc-address-here
$validateBTCURL 'http://blockexplorer.com/q/checkaddress/' $_GET["refund"];
//echo $validateBTCURL;
$validBTC file_get_contents($validateBTCURL);
//echo $validBTC;
if($validBTC == "00"){
//do something
} else {
//do something else
}
?>

legendary
Activity: 1176
Merit: 1111
May Bitcoin be touched by his Noodly Appendage
hero member
Activity: 924
Merit: 501
I'm not getting the same results I see from http://blockexplorer.com/q/checkaddress/ with the above php code.  Checking further...

Are there any commercial use restrictions on grabbing data from blockexplore.com? 



ps. got a link for that, jack?
legendary
Activity: 1176
Merit: 1111
May Bitcoin be touched by his Noodly Appendage
Did you try pywallet's code?
Look for DecodeBase58Check or something like that
hero member
Activity: 924
Merit: 501
thanks!

EDIT
working code:

Shows Good Addresses as bad.

[retracted code]

working code a few posts down the thread

that way
|
|
|
V
administrator
Activity: 4228
Merit: 8647
why is there no simple tool like  http://blockexplorer.com/q/checkaddress

/q/checkaddress uses this plus some extra checking. Note that the checkAddress function assumes that the input is valid base58. Do something like:

Code:
if(preg_match('/^[1-9A-HJ-NP-Za-km-z]+$/', $address) && strlen($address) <= 34 && checkAddress($address))
    address is valid
hero member
Activity: 924
Merit: 501
I REALLY did want to use your code, grondilu, but it lacks documentation.  I tried to use the perl version and the bash version but couldn't get either to work.  I'm sure it's a lack of understanding on my part.  

Could you report your error message here or on the rosettacode talk page please?

lol, it would look like this:

I'm too dumb to figure out how to use a bash script and I forget what issue it was that caused me to not want to use the perl, oh yea... I had no idea how to"feed" the address into the program.  So I gave up.  No reason to noise up your page with that.

now I'm looking at  http://blockexplorer.com/q/checkaddress as I found the above php useless.... it just gives false negatives.

why is there no simple tool like  http://blockexplorer.com/q/checkaddress

oh, wait, maybe there is over at  http://blockexplorer.com/q/checkaddress.. I'll report back (unless I just get lost in smoke and code).

Oh, I should probably start with my objective.... but finishing with it will suffice:

I am trying to figure out how to check bitcoin addresses and make bitcoin addresses and valid data in an online php form.

Pages:
Jump to: