Last active
August 13, 2022 21:28
-
-
Save malitta/29de6b697e4d37ff0af7a04a6063804d to your computer and use it in GitHub Desktop.
Check if Ether address is valid (a PHP implementation of the Ethereum Web3 API's isAddress() method). Credits to @tormuto.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Checks if the given string is an address | |
* | |
* @param String $address the given HEX adress | |
* @return Boolean | |
*/ | |
function isAddress($address) { | |
if (!preg_match('/^(0x)?[0-9a-f]{40}$/i',$address)) { | |
// Check if it has the basic requirements of an address | |
return false; | |
} elseif (preg_match('/^(0x)?[0-9a-f]{40}$/',$address) || preg_match('/^(0x)?[0-9A-F]{40}$/',$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 | |
* | |
* @param String $address the given HEX adress | |
* @return Boolean | |
*/ | |
function isChecksumAddress($address) { | |
// Check each case | |
$address = str_replace('0x','',$address); | |
$addressHash = hash('sha3',strtolower($address)); | |
$addressArray=str_split($address); | |
$addressHashArray=str_split($addressHash); | |
for($i = 0; $i < 40; $i++ ) { | |
// The nth letter should be uppercase if the nth digit of casemap is 1 | |
if ((intval($addressHashArray[$i], 16) > 7 && strtoupper($addressArray[$i]) !== $addressArray[$i]) || (intval($addressHashArray[$i], 16) <= 7 && strtolower($addressArray[$i]) !== $addressArray[$i])) { | |
return false; | |
} | |
} | |
return true; | |
} |
both sha or sha3-256 is incorrect.
and what would be correct?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP hash() function does not support SHA3 algorithm. Use "sha3-256" instead (it's available from PHP 7.1.0).