BTC ADDRESS VALIDATOR


SUBMITTED BY: Guest

DATE: April 18, 2014, 8:09 p.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 1077

  1. PHP CLASS I USED TO VALIDATE AN BITCOIN ADDRESS
  2. namespace Bitcoin;
  3. class AddressValidator {
  4. CONST MAINNET = "00";
  5. CONST TESTNET = "6F";
  6. static public function isValid($addr, $version = null) {
  7. if (is_null($version)) {
  8. $version = self::MAINNET;
  9. }
  10. if (preg_match('/[^1-9A-HJ-NP-Za-km-z]/', $addr)) {
  11. return false;
  12. }
  13. $decoded = self::decodeAddress($addr);
  14. if (strlen($decoded) != 50) {
  15. return false;
  16. }
  17. if (substr($decoded, 0, 2) != $version && substr($decoded, 0, 2) != "05") {
  18. return false;
  19. }
  20. $check = substr($decoded, 0, strlen($decoded) - 8);
  21. $check = pack("H*", $check);
  22. $check = hash("sha256", $check, true);
  23. $check = hash("sha256", $check);
  24. $check = strtoupper($check);
  25. $check = substr($check, 0, 8);
  26. return ($check == substr($decoded, strlen($decoded) - 8));
  27. }
  28. static protected function decodeAddress($data) {
  29. $charsetHex = '0123456789ABCDEF';
  30. $charsetB58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  31. $raw = "0";
  32. for ($i = 0; $i < strlen($data); $i++) {
  33. $current = (string) strpos($charsetB58, $data[$i]);
  34. $raw = (string) bcmul($raw, "58", 0);
  35. $raw = (string) bcadd($raw, $current, 0);
  36. }
  37. $hex = "";
  38. while (bccomp($raw, 0) == 1) {
  39. $dv = (string) bcdiv($raw, "16", 0);
  40. $rem = (integer) bcmod($raw, "16");
  41. $raw = $dv;
  42. $hex = $hex . $charsetHex[$rem];
  43. }
  44. $withPadding = strrev($hex);
  45. for ($i = 0; $i < strlen($data) && $data[$i] == "1"; $i++) {
  46. $withPadding = "00" . $withPadding;
  47. }
  48. if (strlen($withPadding) % 2 != 0) {
  49. $withPadding = "0" . $withPadding;
  50. }
  51. return $withPadding;
  52. }
  53. }

comments powered by Disqus