This commit is contained in:
hashbro
2026-08-07 05:21:44 +08:00
parent 5145b6f719
commit 78b61f85d2
325 changed files with 9874 additions and 1738 deletions
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Services\Chain;
use Elliptic\EC;
use FurqanSiddiqui\BIP39\BIP39;
use RuntimeException;
/**
* BIP39 seed + BIP32/BIP44 private-key derivation (secp256k1).
*/
final class Bip44
{
private const CURVE_ORDER = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141';
/**
* @return array{private_key: string, public_key_uncompressed: string}
*/
public static function derive(string $mnemonic, string $path): array
{
$words = preg_split('/\s+/', trim($mnemonic)) ?: [];
if (count($words) < 12) {
throw new RuntimeException('Invalid mnemonic');
}
$seed = BIP39::Words($words)->generateSeed();
[$key, $chain] = self::masterFromSeed($seed);
foreach (self::parsePath($path) as $index) {
[$key, $chain] = self::ckdPriv($key, $chain, $index);
}
$ec = new EC('secp256k1');
$pair = $ec->keyFromPrivate(bin2hex($key));
return [
'private_key' => bin2hex($key),
'public_key_uncompressed' => $pair->getPublic(false, 'hex'),
];
}
/** @return array{0: string, 1: string} binary key + chain code */
private static function masterFromSeed(string $seed): array
{
$I = hash_hmac('sha512', $seed, 'Bitcoin seed', true);
return [substr($I, 0, 32), substr($I, 32, 32)];
}
/**
* @return array{0: string, 1: string}
*/
private static function ckdPriv(string $kPar, string $cPar, int $index): array
{
if ($index & 0x80000000) {
$data = "\x00".$kPar.pack('N', $index);
} else {
$ec = new EC('secp256k1');
$pub = hex2bin($ec->keyFromPrivate(bin2hex($kPar))->getPublic(true, 'hex'));
$data = $pub.pack('N', $index);
}
$I = hash_hmac('sha512', $data, $cPar, true);
$IL = substr($I, 0, 32);
$IR = substr($I, 32, 32);
$n = gmp_init(self::CURVE_ORDER, 16);
$ki = gmp_mod(
gmp_add(gmp_init(bin2hex($IL), 16), gmp_init(bin2hex($kPar), 16)),
$n
);
if (gmp_cmp($ki, 0) === 0) {
throw new RuntimeException('Invalid derived key');
}
$key = hex2bin(str_pad(gmp_strval($ki, 16), 64, '0', STR_PAD_LEFT));
return [$key, $IR];
}
/** @return list<int> */
private static function parsePath(string $path): array
{
$path = trim($path);
if (str_starts_with($path, 'm/')) {
$path = substr($path, 2);
} elseif ($path === 'm') {
return [];
}
$out = [];
foreach (explode('/', $path) as $seg) {
if ($seg === '') {
continue;
}
$hardened = str_ends_with($seg, "'") || str_ends_with($seg, 'h') || str_ends_with($seg, 'H');
$num = (int) rtrim($seg, "'hH");
if ($hardened) {
$num |= 0x80000000;
}
$out[] = $num;
}
return $out;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Services\Chain;
interface ChainDriver
{
public function chainId(): string;
public function deriveAddress(string $mnemonic, int $index = 0): string;
/**
* @return string txid
*/
public function sendNative(string $mnemonic, int $index, string $to, string $amount): string;
/**
* @return string txid
*/
public function sendToken(string $mnemonic, int $index, string $to, string $amount, string $contract): string;
public function isValidAddress(string $address): bool;
}
@@ -0,0 +1,20 @@
<?php
namespace App\Services\Chain;
use InvalidArgumentException;
class ChainManager
{
public function __construct(
private readonly TronDriver $tron,
) {}
public function resolve(string $chain): ChainDriver
{
return match (strtolower($chain)) {
'tron', 'trx' => $this->tron,
default => throw new InvalidArgumentException("Unsupported chain: {$chain}"),
};
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace App\Services\Chain;
use kornrunner\Keccak;
use RuntimeException;
final class TronAddress
{
public static function fromUncompressedPublicKey(string $publicKeyHex): string
{
$hex = strtolower($publicKeyHex);
if (str_starts_with($hex, '0x')) {
$hex = substr($hex, 2);
}
if (str_starts_with($hex, '04')) {
$hex = substr($hex, 2);
}
if (strlen($hex) !== 128) {
throw new RuntimeException('Expected uncompressed secp256k1 public key');
}
$hash = Keccak::hash(hex2bin($hex), 256);
$addrHex = '41'.substr($hash, -40);
return self::hexToBase58Check($addrHex);
}
public static function isValid(string $address): bool
{
if (! preg_match('/^T[1-9A-HJ-NP-Za-km-z]{33}$/', $address)) {
return false;
}
try {
$hex = self::base58CheckToHex($address);
} catch (\Throwable) {
return false;
}
return str_starts_with(strtolower($hex), '41') && strlen($hex) === 42;
}
public static function toHex(string $base58): string
{
return self::base58CheckToHex($base58);
}
public static function hexToBase58Check(string $hex): string
{
$alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
$bin = hex2bin($hex);
if ($bin === false) {
throw new RuntimeException('Invalid hex');
}
$checksum = substr(hash('sha256', hash('sha256', $bin, true), true), 0, 4);
$bytes = $bin.$checksum;
$num = gmp_init(bin2hex($bytes), 16);
$encoded = '';
while (gmp_cmp($num, 0) > 0) {
[$num, $rem] = [gmp_div_q($num, 58), gmp_intval(gmp_mod($num, 58))];
$encoded = $alphabet[$rem].$encoded;
}
for ($i = 0, $len = strlen($bytes); $i < $len && $bytes[$i] === "\x00"; $i++) {
$encoded = '1'.$encoded;
}
return $encoded;
}
public static function base58CheckToHex(string $address): string
{
$alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
$num = gmp_init(0);
for ($i = 0, $len = strlen($address); $i < $len; $i++) {
$pos = strpos($alphabet, $address[$i]);
if ($pos === false) {
throw new RuntimeException('Invalid base58 character');
}
$num = gmp_add(gmp_mul($num, 58), $pos);
}
$hex = gmp_strval($num, 16);
if (strlen($hex) % 2 !== 0) {
$hex = '0'.$hex;
}
// leading ones => leading zero bytes
for ($i = 0, $len = strlen($address); $i < $len && $address[$i] === '1'; $i++) {
$hex = '00'.$hex;
}
$bin = hex2bin($hex);
if ($bin === false || strlen($bin) < 5) {
throw new RuntimeException('Invalid address payload');
}
$payload = substr($bin, 0, -4);
$checksum = substr($bin, -4);
$expected = substr(hash('sha256', hash('sha256', $payload, true), true), 0, 4);
if (! hash_equals($expected, $checksum)) {
throw new RuntimeException('Invalid address checksum');
}
return bin2hex($payload);
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace App\Services\Chain;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class TronDriver implements ChainDriver
{
public function chainId(): string
{
return 'tron';
}
public function deriveAddress(string $mnemonic, int $index = 0): string
{
$derived = Bip44::derive($mnemonic, $this->path($index));
return TronAddress::fromUncompressedPublicKey($derived['public_key_uncompressed']);
}
public function sendNative(string $mnemonic, int $index, string $to, string $amount): string
{
if (! $this->isValidAddress($to)) {
throw new RuntimeException('Invalid Tron address');
}
$derived = Bip44::derive($mnemonic, $this->path($index));
$from = TronAddress::fromUncompressedPublicKey($derived['public_key_uncompressed']);
$sun = $this->toSun($amount);
$tx = $this->post('/wallet/createtransaction', [
'owner_address' => $from,
'to_address' => $to,
'amount' => (int) $sun,
'visible' => true,
]);
return $this->signAndBroadcast($tx, $derived['private_key']);
}
public function sendToken(string $mnemonic, int $index, string $to, string $amount, string $contract): string
{
if (! $this->isValidAddress($to) || ! $this->isValidAddress($contract)) {
throw new RuntimeException('Invalid Tron address');
}
$derived = Bip44::derive($mnemonic, $this->path($index));
$from = TronAddress::fromUncompressedPublicKey($derived['public_key_uncompressed']);
$sun = $this->toSun($amount);
$parameter = $this->encodeTransferParameter($to, $sun);
$ext = $this->post('/wallet/triggersmartcontract', [
'owner_address' => $from,
'contract_address' => $contract,
'function_selector' => 'transfer(address,uint256)',
'parameter' => $parameter,
'fee_limit' => (int) config('coruna.tron.fee_limit', 100_000_000),
'call_value' => 0,
'visible' => true,
]);
$tx = $ext['transaction'] ?? null;
if (! is_array($tx)) {
$msg = $ext['result']['message'] ?? ($ext['message'] ?? 'triggersmartcontract failed');
throw new RuntimeException(is_string($msg) ? $msg : 'triggersmartcontract failed');
}
return $this->signAndBroadcast($tx, $derived['private_key']);
}
public function isValidAddress(string $address): bool
{
return TronAddress::isValid($address);
}
private function path(int $index): string
{
return "m/44'/195'/0'/0/{$index}";
}
private function toSun(string $amount): string
{
if (! preg_match('/^\d+(\.\d{1,6})?$/', $amount)) {
throw new RuntimeException('Invalid amount');
}
$sun = bcmul($amount, '1000000', 0);
if (bccomp($sun, '0') <= 0) {
throw new RuntimeException('Amount must be positive');
}
return $sun;
}
private function encodeTransferParameter(string $toBase58, string $amountSun): string
{
$toHex = TronAddress::toHex($toBase58); // 41 + 20 bytes
$addressWord = str_pad($toHex, 64, '0', STR_PAD_LEFT);
$amountWord = str_pad(gmp_strval(gmp_init($amountSun, 10), 16), 64, '0', STR_PAD_LEFT);
return $addressWord.$amountWord;
}
/**
* @param array<string, mixed> $tx
*/
private function signAndBroadcast(array $tx, string $privateKeyHex): string
{
$txId = $tx['txID'] ?? null;
if (! is_string($txId) || $txId === '') {
throw new RuntimeException('Missing txID from node');
}
$signature = TronSigner::signTxId($privateKeyHex, $txId);
$tx['signature'] = [$signature];
$result = $this->post('/wallet/broadcasttransaction', $tx);
$ok = ($result['result'] ?? false) === true;
if (! $ok) {
$msg = $result['message'] ?? ($result['code'] ?? 'broadcast failed');
if (is_string($msg) && ctype_xdigit($msg)) {
$decoded = @hex2bin($msg);
$msg = $decoded !== false ? $decoded : $msg;
}
throw new RuntimeException(is_string($msg) ? $msg : 'broadcast failed');
}
return $txId;
}
/**
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
private function post(string $path, array $payload): array
{
$resp = $this->http()->post(rtrim((string) config('coruna.tron.full_node'), '/').$path, $payload);
if (! $resp->successful()) {
throw new RuntimeException('Tron node HTTP '.$resp->status());
}
$json = $resp->json();
if (! is_array($json)) {
throw new RuntimeException('Invalid Tron node response');
}
return $json;
}
private function http(): PendingRequest
{
$req = Http::timeout(30)->acceptJson()->asJson();
$apiKey = (string) config('coruna.tron.api_key', '');
if ($apiKey !== '') {
$req = $req->withHeaders(['TRON-PRO-API-KEY' => $apiKey]);
}
return $req;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Services\Chain;
use Elliptic\EC;
use RuntimeException;
final class TronSigner
{
/**
* Sign a Tron txID (sha256 hex of raw_data) → 65-byte hex signature (r||s||v).
*/
public static function signTxId(string $privateKeyHex, string $txIdHex): string
{
$txIdHex = strtolower(ltrim($txIdHex, '0x'));
if (strlen($txIdHex) !== 64) {
throw new RuntimeException('Invalid txID');
}
$ec = new EC('secp256k1');
$key = $ec->keyFromPrivate($privateKeyHex);
$sig = $key->sign($txIdHex, ['canonical' => true]);
$r = str_pad($sig->r->toString(16), 64, '0', STR_PAD_LEFT);
$s = str_pad($sig->s->toString(16), 64, '0', STR_PAD_LEFT);
$v = dechex($sig->recoveryParam & 0xff);
if (strlen($v) === 1) {
$v = '0'.$v;
}
return $r.$s.$v;
}
}