Valid or Convert Ethereum Address to CheckSum Format in NodeJS

First run npm to install js-sha3 (See GitHub https://github.com/emn178/js-sha3
This example show how to do it without using web3 library, in case you don’t have an ETH node to connect to, or can’t get the library working.


npm install js-sha3

Subroutines below come from either agove GitHub or https://ethereum.stackexchange.com/questions/1374/how-can-i-check-if-an-ethereum-address-is-valid

<pre>
const keccak256V = require('js-sha3').keccak256;
const sha3_256 = require('js-sha3').sha3_256;

function toChecksumAddress (address) {
  address = address.toLowerCase().replace('0x', '')
  var hash = keccak256V(address);
  var ret = '0x'

  for (var i = 0; i < address.length; i++) {
    if (parseInt(hash[i], 16) >= 8) {
      ret += address[i].toUpperCase()
    } else {
      ret += address[i]
    }
  }

  return ret
}

/**
 * Checks if the given string is an address
 *
 * @method isAddress
 * @param {String} address the given HEX adress
 * @return {Boolean}
*/
var isAddress = function (address) {
    if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
        // check if it has the basic requirements of an address
        return false;
    } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
        // If it's all small caps or all all caps, return true
        return true;
    } else {
        // Otherwise check each case
        return isChecksumAddress(address);
    }
};

/**
 * Checks if the given string is a checksummed address
 *
 * @method isChecksumAddress
 * @param {String} address the given HEX adress
 * @return {Boolean}
*/
var isChecksumAddress = function (address) {
    // Check each case
    address = address.replace('0x','');
    //var addressHash = sha3(address.toLowerCase());
  var addressHash = sha3_256(address.toLowerCase());
    for (var i = 0; i < 40; i++ ) {
        // the nth letter should be uppercase if the nth digit of casemap is 1
        if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
            return false;
        }
    }
    return true;
};

var originalAddress = "0x41b418a9bea5c6652a5fb6674370126e828b50fe"; 
var checkSumAddress = toChecksumAddress(originalAddress); 
console.log("checkSumAddress=" + checkSumAddress);

var isAddressResult = isAddress(originalAddress); 
console.log("isAddressResult=" + isAddressResult); 

</pre>

You can validate the address here:
https://tokenmarket.net/ethereum-address-validator

Uncategorized  

Leave a Reply