Address.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace TronTool;
  3. use kornrunner\Keccak;
  4. use StephenHill\Base58;
  5. define('TRON_ALPHABET','123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  6. class Address{
  7. protected $base58;
  8. protected $hex;
  9. function hex(){
  10. return $this->hex;
  11. }
  12. function base58(){
  13. return $this->base58;
  14. }
  15. protected function __construct($hex){
  16. $this->hex = $hex;
  17. $this->base58 = $this->encode($this->hex);
  18. }
  19. static function fromPublicKey($key){
  20. $hex = self::compute($key);
  21. return new self($hex);
  22. }
  23. static function fromHex($hex){
  24. return new self($hex);
  25. }
  26. static function fromBase58($b58){
  27. $hex = self::decode($b58);
  28. return new self($hex);
  29. }
  30. static function compute($publicKey){
  31. $bin = hex2bin($publicKey);
  32. $bin = substr($bin,1);
  33. $hash = Keccak::hash($bin,256);
  34. $hex = '41' . substr($hash,24);
  35. return $hex;
  36. }
  37. static function encode($hex){
  38. $base58 = new Base58(TRON_ALPHABET);
  39. $bin = hex2bin($hex);
  40. $hash0 = hash('sha256',$bin,true);
  41. $hash1 = hash('sha256',$hash0,true);
  42. $checksum = substr($hash1,0,4);
  43. $encoded = $base58->encode($bin . $checksum);
  44. return $encoded;
  45. }
  46. static function decode($b58){
  47. if(is_null($b58)) return null;
  48. $base58 = new Base58(TRON_ALPHABET);
  49. $decoded = $base58->decode($b58);
  50. $decoded = substr($decoded,0,-4);
  51. return bin2hex($decoded);
  52. }
  53. function __toString(){
  54. return $this->base58;
  55. }
  56. }