Credential.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace TronTool;
  3. use Elliptic\EC;
  4. use kornrunner\Keccak;
  5. use TronTool\Address;
  6. class Credential{
  7. protected $keyPair;
  8. function __construct($privateKey){
  9. $ec = new EC('secp256k1');
  10. $this->keyPair = $ec->keyFromPrivate($privateKey);
  11. }
  12. public static function fromPrivateKey($privateKey){
  13. return new self($privateKey);
  14. }
  15. static function create(){
  16. $bin = random_bytes(32);
  17. $privateKey = bin2hex($bin);
  18. return new self($privateKey);
  19. }
  20. function privateKey(){
  21. return $this->keyPair->getPrivate()->toString(16,2);
  22. }
  23. function publicKey(){
  24. return $this->keyPair->getPublic()->encode('hex');
  25. }
  26. function address(){
  27. return Address::fromPublicKey($this->publicKey());
  28. }
  29. function sign($hex){
  30. $signature = $this->keyPair->sign($hex);
  31. $r = $signature->r->toString('hex');
  32. $s = $signature->s->toString('hex');
  33. //$v = bin2hex(pack('C',$signature->recoveryParam));
  34. $v = bin2hex(chr($signature->recoveryParam));
  35. return $r.$s.$v;
  36. }
  37. function signTx($tx){
  38. $signature = $this->sign($tx->txID);
  39. //var_dump($signature);
  40. $tx->signature = [$signature];
  41. return $tx;
  42. }
  43. }