Address.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Tron;
  3. use IEXBase\TronAPI\Support\Base58Check;
  4. use IEXBase\TronAPI\Support\Hash;
  5. class Address
  6. {
  7. public $privateKey,
  8. $address,
  9. $hexAddress = '';
  10. const ADDRESS_SIZE = 34;
  11. const ADDRESS_PREFIX = "41";
  12. const ADDRESS_PREFIX_BYTE = 0x41;
  13. public function __construct(string $address = '', string $privateKey = '', string $hexAddress = '')
  14. {
  15. if (strlen($address) === 0) {
  16. throw new \InvalidArgumentException('Address can not be empty');
  17. }
  18. $this->privateKey = $privateKey;
  19. $this->address = $address;
  20. $this->hexAddress = $hexAddress;
  21. }
  22. /**
  23. * Dont rely on this. Always use Wallet::validateAddress to double check
  24. * against tronGrid.
  25. *
  26. * @return bool
  27. */
  28. public function isValid(): bool
  29. {
  30. if (strlen($this->address) !== Address::ADDRESS_SIZE) {
  31. return false;
  32. }
  33. $address = Base58Check::decode($this->address, false, 0, false);
  34. $utf8 = hex2bin($address);
  35. if (strlen($utf8) !== 25) {
  36. return false;
  37. }
  38. if (strpos($utf8, chr(self::ADDRESS_PREFIX_BYTE)) !== 0) {
  39. return false;
  40. }
  41. $checkSum = substr($utf8, 21);
  42. $address = substr($utf8, 0, 21);
  43. $hash0 = Hash::SHA256($address);
  44. $hash1 = Hash::SHA256($hash0);
  45. $checkSum1 = substr($hash1, 0, 4);
  46. if ($checkSum === $checkSum1) {
  47. return true;
  48. }
  49. return false;
  50. }
  51. }