How to validate bitcoin address?

+3 votes

I have found the following code that validates bitcoin address using python:

from hashlib import sha256

digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

def decode_base58(bc, length):

    n = 0

    for char in bc:

        n = n * 58 + digits58.index(char)

    return n.to_bytes(length, 'big')

def check_bc(bc):

    bcbytes = decode_base58(bc, 25)

    return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]

if __name__ == '__main__':

    bc = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i'

    assert check_bc(bc)

    assert not check_bc( bc.replace('N', 'P', 1) )

    assert check_bc('1111111111111111111114oLvT2')

    assert check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")

Now I want to validate bitcoin address using Java, javascript or php. Any idea how to do it?

Aug 17, 2018 in Blockchain by digger
• 26,550 points

edited Aug 20, 2018 by Omkar 870 views

3 answers to this question.

+4 votes
Best answer

I found these 2 scripts online:

Javascript:

<html>

<head>

<script type="text/javascript" src="http://dl.dropboxusercontent.com/u/28441300/BigInt.js"></script>

<script type="text/javascript" src="http://dl.dropboxusercontent.com/u/28441300/sha256.js"></script>

</head>

<body>


<div id="text">

</div>


<script type="text/javascript">

var address = "1Eym7pyJcaambv8FG4ZoU8A4xsiL9us2zz";

if (check(address)) {

    document.getElementById('text').innerHTML += "valid";

} else {

    document.getElementById('text').innerHTML += "invalid";

}



function check(address) {

  var decoded = base58_decode(address);    

  if (decoded.length != 25) return false;


  var cksum = decoded.substr(decoded.length - 4);

  var rest = decoded.substr(0, decoded.length - 4); 


  var good_cksum = hex2a(sha256_digest(hex2a(sha256_digest(rest)))).substr(0, 4);


  if (cksum != good_cksum) return false;

  return true;

}


function base58_decode(string) {

  var table = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

  var table_rev = new Array();


  var i;

  for (i = 0; i < 58; i++) {

    table_rev[table[i]] = int2bigInt(i, 8, 0);

  }


  var l = string.length;

  var long_value = int2bigInt(0, 1, 0); 


  var num_58 = int2bigInt(58, 8, 0);


  var c;

  for(i = 0; i < l; i++) {

    c = string[l - i - 1];

    long_value = add(long_value, mult(table_rev[c], pow(num_58, i)));

  }


  var hex = bigInt2str(long_value, 16); 


  var str = hex2a(hex); 


  var nPad;

  for (nPad = 0; string[nPad] == table[0]; nPad++); 


  var output = str;

  if (nPad > 0) output = repeat("\0", nPad) + str;


  return output;

}


function hex2a(hex) {

    var str = '';

    for (var i = 0; i < hex.length; i += 2)

        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));

    return str;

}


function a2hex(str) {

    var aHex = "0123456789abcdef";

    var l = str.length;

    var nBuf;

    var strBuf;

    var strOut = "";

    for (var i = 0; i < l; i++) {

      nBuf = str.charCodeAt(i);

      strBuf = aHex[Math.floor(nBuf/16)];

      strBuf += aHex[nBuf % 16];

      strOut += strBuf;

    }

    return strOut;

}


function pow(big, exp) {

    if (exp == 0) return int2bigInt(1, 1, 0);

    var i;

    var newbig = big;

    for (i = 1; i < exp; i++) {

        newbig = mult(newbig, big);

    }


    return newbig;

}


function repeat(s, n){

    var a = [];

    while(a.length < n){

        a.push(s);

    }

    return a.join('');

}

</script>

</body>

</html>

PHP:

<?php


function checkAddress($address)

{

    $origbase58 = $address;

    $dec = "0";


    for ($i = 0; $i < strlen($address); $i++)

    {

        $dec = bcadd(bcmul($dec,"58",0),strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",substr($address,$i,1)),0);

    }


    $address = "";


    while (bccomp($dec,0) == 1)

    {

        $dv = bcdiv($dec,"16",0);

        $rem = (integer)bcmod($dec,"16");

        $dec = $dv;

        $address = $address.substr("0123456789ABCDEF",$rem,1);

    }


    $address = strrev($address);


    for ($i = 0; $i < strlen($origbase58) && substr($origbase58,$i,1) == "1"; $i++)

    {

        $address = "00".$address;

    }


    if (strlen($address)%2 != 0)

    {

        $address = "0".$address;

    }


    if (strlen($address) != 50)

    {

        return false;

    }


    if (hexdec(substr($address,0,2)) > 0)

    {

        return false;

    }


    return substr(strtoupper(hash("sha256",hash("sha256",pack("H*",substr($address,0,strlen($address)-8)),true))),0,8) == substr($address,strlen($address)-8);

}


?>

Source: http://www.php.net/manual/en/ref.bc.php

http://jsfiddle.net/timrpeterson/XsCQq/2/

answered Aug 17, 2018 by slayer
• 29,170 points

selected Aug 20, 2018 by Omkar
0 votes

For Java, have a look at the validateAddress(String) method in this class:https://github.com/jim618/multibit/blob/master/src/main/java/org/multibit/viewsystem/swing/action/Validator.java

answered Aug 20, 2018 by Omkar
• 67,620 points
+1 vote
Is there any better solution for validating bitcoin address ?
Can you explain me the javascript code?
answered Aug 21, 2018 by anonymous
An easier solution for validating bitcoin address would be to use an online Bitcoin address validator. Example: https://awebanalysis.com/en/bitcoin-address-validate/
You could also do it w CSS, like this:

.container {
  padding: 10px;
}

.msg {
  margin: 10px 0px;
  color: #000;
  &.fail {
    color: red;
  }
  &.pass {
    color: green;
  }
}

input,
button {
  font-size: 18px;
  user-select: none;
}

.link-action {
  color: green;
  text-decoration: underline;
  cursor: pointer;
  display: inline-block;
  margin: 10px;
}
Before explaning the Javascript to validate the Bitcoin address, let us look at some key factors of a valid Bitcoin address:

1. A Bitcoin address is between 25 and 34 characters long.
2. The address always starts with a 1 (for P2PKH address format) or 3 (for P2SH address format).
3. An address can contain all alphanumeric characters, with the exceptions of 0(zero), O(Uppercase letter 'O'), I(Uppercase i)
and l(Lowercase L) to avoid visual ambiguity.

Explanation of Javascript:

The programming checks if the given address is a valid Bitcoin address or not. If it is valid, it prints Valid and if it is
not valid then it prints invalid


function check(address)
This is the function from where the procedure to check whether the given address is valid or not starts.


base58_decode(address)
This is the function that is used to convert the address from its encoded form to normal form.
Base58 is a group of binary-to-text encoding schemes used to represent large integers as alphanumeric text, introduced by Satoshi Nakamoto for use with Bitcoin.


var cksum = decoded.substr(decoded.length - 4);
The checksum of an address is the string of the address excluding the first 4 characters.


var rest = decoded.substr(0, decoded.length - 4);
This is the rest of the address (from character 5 to the last character in the address)


function hex2a(hex)
Converts a hex string into an alpha-numerical string


function a2hex(str)
Converts an alpha-numerical into hex string


Conversion from alpha-numerical to hex and the reverse is done during the encoding and decoding so these functions are used
to convert the strings back to their original form for validation.


All these functions are used to validate the Bitcoin address in the following way:
First the address is decoded from base58. Then the checksum and the rest of the address is set to the variables "cksum" and
"rest". The code checks whether the checksum of the address is a good checksum by comparing it to the standard checksum.
If all these conditions are satisfied then the given address is valid.

Related Questions In Blockchain

0 votes
1 answer

How to generate Bitcoin address in Ruby?

In your generate_address_from_public_key_hash method, the checksum should be over ...READ MORE

answered Aug 22, 2018 in Blockchain by slayer
• 29,170 points
705 views
0 votes
1 answer

How to create Bitcoin Address in PHP?

You need to understand that Bitcoin address and ...READ MORE

answered Aug 27, 2018 in Blockchain by Perry
• 17,020 points
494 views
0 votes
1 answer

How to generate coin address using bitcoin-ruby?

The only difference between the addresses is ...READ MORE

answered Aug 29, 2018 in Blockchain by slayer
• 29,170 points
61 views
+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to extract h160 address of bitcoin blockchain?

You can extract the data using the ...READ MORE

answered Jul 16, 2018 in Blockchain by digger
• 26,550 points
144 views
0 votes
1 answer

How to solve “More than one instance of bitcore-lib found” error?

There is a temp solution here. ~/bitcore-explorers/node_modules/bitcore-lib/index.js line 7: bitcore.versionGuard ...READ MORE

answered Jul 25, 2018 in Blockchain by slayer
• 29,170 points
490 views
0 votes
1 answer

How to generate Bitcoin address?

Convert the hex string back to bytes ...READ MORE

answered Aug 20, 2018 in Blockchain by slayer
• 29,170 points
74 views
0 votes
2 answers

How to check if bitcoin address is valid?

For Java, have a look at the ...READ MORE

answered Aug 20, 2018 in Blockchain by Omkar
• 67,620 points
336 views