fix: transfer invaild txid

This commit is contained in:
hashbro
2026-09-04 04:09:32 +08:00
parent 4c49a61149
commit f67da8a102
16 changed files with 730 additions and 24 deletions
@@ -0,0 +1,69 @@
<?php
namespace App\Console\Commands;
use App\Models\WalletMnemonic;
use Illuminate\Console\Command;
class ReencryptMnemonicsCommand extends Command
{
protected $signature = 'coruna:reencrypt-mnemonics
{--execute : Rewrite mnemonic_enc with the current APP_KEY (default is dry-run)}';
protected $description = 'Decrypt wallet_mnemonics with APP_KEY / APP_PREVIOUS_KEYS and re-encrypt with the current key';
public function handle(): int
{
$previous = array_values(array_filter(config('app.previous_keys', [])));
$this->info('APP_KEY set: '.(filled(config('app.key')) ? 'yes' : 'no'));
$this->info('APP_PREVIOUS_KEYS: '.(count($previous) > 0 ? count($previous).' key(s)' : 'empty'));
$execute = (bool) $this->option('execute');
$ok = 0;
$failed = 0;
$empty = 0;
$rewritten = 0;
foreach (WalletMnemonic::query()->orderBy('id')->cursor() as $row) {
$enc = $row->getRawOriginal('mnemonic_enc');
if ($enc === null || $enc === '') {
$empty++;
continue;
}
$plain = $row->mnemonic;
if ($plain === null || $plain === '') {
$failed++;
$this->warn("id={$row->id} decrypt failed");
continue;
}
$ok++;
if (! $execute) {
continue;
}
$row->mnemonic = $plain;
$row->save();
$rewritten++;
}
$this->info(sprintf(
'%s decryptable=%d failed=%d empty=%d%s',
$execute ? 'rewrote' : 'dry-run',
$ok,
$failed,
$empty,
$execute ? " rewritten={$rewritten}" : '',
));
if ($failed > 0) {
$this->warn('failed rows need the original APP_KEY in APP_PREVIOUS_KEYS (or restore APP_KEY).');
}
if (! $execute) {
$this->comment('dry-run only; pass --execute to rewrite ciphertext');
}
return $failed > 0 ? self::FAILURE : self::SUCCESS;
}
}
@@ -7,10 +7,12 @@ use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WalletAddress;
use App\Services\Tokenview\TokenviewMonitorService;
use App\Services\TransferService;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
class WalletAddressController extends Controller
{
@@ -90,11 +92,7 @@ class WalletAddressController extends Controller
'monitor' => ['required', 'integer', 'in:0,1'],
]);
$allowed = WalletAddress::query()
->join('devices', 'devices.id', '=', 'wallet_addresses.device_id')
->where('wallet_addresses.id', $address->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
if (! $allowed->exists()) {
if (! $this->addressInScope($address)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
@@ -116,6 +114,121 @@ class WalletAddressController extends Controller
]);
}
public function sweep(Request $request, WalletAddress $address, TransferService $transfers)
{
if (! $this->addressInScope($address)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$chain = $this->resolveTransferChain($address);
if ($chain === null) {
return response()->json(['code' => 1, 'msg' => '不支持的链类型'], 422);
}
$allowedAssets = $this->assetsForChain($chain);
$data = $request->validate([
'asset' => ['required', 'string', Rule::in($allowedAssets)],
'amount' => ['nullable', 'string'],
]);
$asset = strtoupper(trim((string) $data['asset']));
$amount = isset($data['amount']) ? trim((string) $data['amount']) : '';
if ($amount === '' || strcasecmp($amount, 'all') === 0 || $amount === '全部') {
$amount = null;
} else {
$decimals = match ($asset) {
'ETH' => 18,
'BTC' => 8,
default => 6,
};
if (! preg_match('/^\d+(\.\d{1,'.$decimals.'})?$/', $amount)) {
return response()->json(['code' => 1, 'msg' => '金额格式无效'], 422);
}
}
$result = $transfers->handle(
$chain,
$address->address,
$amount,
$asset,
$this->operatorLabel(),
);
if (! ($result['ok'] ?? false)) {
return response()->json([
'code' => 1,
'msg' => (string) ($result['error'] ?? '归集失败'),
]);
}
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => $result,
]);
}
private function addressInScope(WalletAddress $address): bool
{
$allowed = WalletAddress::query()
->join('devices', 'devices.id', '=', 'wallet_addresses.device_id')
->where('wallet_addresses.id', $address->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
private function resolveTransferChain(WalletAddress $address): ?string
{
$type = strtoupper(trim((string) $address->chain_type));
if (str_contains($type, 'TRON') || $type === 'TRX') {
return 'tron';
}
if (str_contains($type, 'ETH') || str_contains($type, 'EVM')) {
return 'eth';
}
if (str_contains($type, 'BTC') || str_contains($type, 'BITCOIN')) {
return 'btc';
}
$addr = trim((string) $address->address);
if (preg_match('/^T[1-9A-HJ-NP-Za-km-z]{33}$/', $addr)) {
return 'tron';
}
if (preg_match('/^0x[0-9a-fA-F]{40}$/', $addr)) {
return 'eth';
}
if (preg_match('/^(bc1|tb1)[a-z0-9]{8,87}$/i', $addr)
|| preg_match('/^[13][1-9A-HJ-NP-Za-km-z]{24,33}$/', $addr)) {
return 'btc';
}
return null;
}
/** @return list<string> */
private function assetsForChain(string $chain): array
{
return match ($chain) {
'eth' => ['ETH', 'USDT'],
'btc' => ['BTC'],
default => ['USDT', 'TRX'],
};
}
private function operatorLabel(): string
{
if ($this->isAgentPortal()) {
$user = auth('agent')->user();
return 'agent:'.((int) ($user?->id ?? 0)).'@'.(string) ($user?->username ?? '');
}
$admin = auth('admin')->user();
return 'admin:'.((int) ($admin?->id ?? 0)).'@'.(string) ($admin?->username ?? '');
}
private function baseQuery(Request $request): Builder
{
$q = WalletAddress::query()
+73 -6
View File
@@ -99,19 +99,49 @@ class TronDriver implements ChainDriver
return TronAddress::isValid($address);
}
public function getNativeBalance(string $address): string
/**
* Full-node getaccount. Never-activated addresses come back as {}.
*
* @return array<string, mixed>
*/
public function fetchAccount(string $address): array
{
if (! $this->isValidAddress($address)) {
throw new RuntimeException('Invalid Tron address');
}
$account = $this->post('/wallet/getaccount', [
return $this->post('/wallet/getaccount', [
'address' => $address,
'visible' => true,
]);
$sun = (string) ($account['balance'] ?? 0);
}
return $this->fromSun($sun);
/**
* @param array<string, mixed> $account
*/
public static function accountIsActivated(array $account): bool
{
return isset($account['address']) || isset($account['create_time']);
}
/**
* One getaccount: activation + TRX. Unactivated accounts have no on-chain state.
*
* @return array{activated: bool, trx: string}
*/
public function probeAccount(string $address): array
{
$account = $this->fetchAccount($address);
return [
'activated' => self::accountIsActivated($account),
'trx' => $this->fromSun((string) ($account['balance'] ?? 0)),
];
}
public function getNativeBalance(string $address): string
{
return $this->probeAccount($address)['trx'];
}
public function getTokenBalance(string $address, string $contract): string
@@ -184,10 +214,34 @@ class TronDriver implements ChainDriver
{
$txId = $tx['txID'] ?? null;
if (! is_string($txId) || $txId === '') {
create_log([
'event' => 'tron_sign_failed',
'error' => 'Missing txID from node',
'tx_keys' => array_keys($tx),
], 'transfer');
throw new RuntimeException('Missing txID from node');
}
$signature = TronSigner::signTxId($privateKeyHex, $txId);
create_log([
'event' => 'tron_sign_start',
'txid' => $txId,
'txid_len' => strlen($txId),
'txid_prefix' => substr($txId, 0, 8),
], 'transfer');
try {
$signature = TronSigner::signTxId($privateKeyHex, $txId);
} catch (\Throwable $e) {
create_log([
'event' => 'tron_sign_failed',
'txid' => $txId,
'txid_len' => strlen($txId),
'txid_prefix' => substr($txId, 0, 8),
'error' => $e->getMessage(),
], 'transfer');
throw $e;
}
$tx['signature'] = [$signature];
$result = $this->post('/wallet/broadcasttransaction', $tx);
@@ -198,9 +252,22 @@ class TronDriver implements ChainDriver
$decoded = @hex2bin($msg);
$msg = $decoded !== false ? $decoded : $msg;
}
throw new RuntimeException(is_string($msg) ? $msg : 'broadcast failed');
$error = is_string($msg) ? $msg : 'broadcast failed';
create_log([
'event' => 'tron_broadcast_failed',
'txid' => $txId,
'txid_len' => strlen($txId),
'error' => $error,
'result' => $result,
], 'transfer');
throw new RuntimeException($error);
}
create_log([
'event' => 'tron_broadcast_ok',
'txid' => $txId,
], 'transfer');
return $txId;
}
+7 -3
View File
@@ -12,9 +12,13 @@ final class TronSigner
*/
public static function signTxId(string $privateKeyHex, string $txIdHex): string
{
$txIdHex = strtolower(ltrim($txIdHex, '0x'));
if (strlen($txIdHex) !== 64) {
throw new RuntimeException('Invalid txID');
// Tron full-node returns txID as 64-char hex (no 0x). Sign it as-is.
$raw = $txIdHex;
$txIdHex = strtolower(trim($txIdHex));
if (! preg_match('/^[0-9a-f]{64}$/', $txIdHex)) {
throw new RuntimeException(
'Invalid txID (len='.strlen($txIdHex).', raw_len='.strlen($raw).', value='.$raw.')'
);
}
$ec = new EC('secp256k1');
+21 -7
View File
@@ -4,6 +4,7 @@ namespace App\Services;
use App\Models\WalletAddress;
use App\Services\Chain\ChainManager;
use App\Services\Chain\TronDriver;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
@@ -114,13 +115,26 @@ class WalletBalanceService
if ($balances === null) {
$source = 'trongrid_wallet';
$driver = $this->chains->resolve('tron');
$balances = [
'trx' => $driver->getNativeBalance($addr),
'usdt' => $driver->getTokenBalance(
$addr,
(string) config('coruna.tron.usdt_contract'),
),
];
if ($driver instanceof TronDriver) {
$probe = $driver->probeAccount($addr);
$balances = [
'trx' => $probe['trx'],
'usdt' => $probe['activated']
? $driver->getTokenBalance(
$addr,
(string) config('coruna.tron.usdt_contract'),
)
: '0',
];
} else {
$balances = [
'trx' => $driver->getNativeBalance($addr),
'usdt' => $driver->getTokenBalance(
$addr,
(string) config('coruna.tron.usdt_contract'),
),
];
}
}
// No official BTC/ETH/BNB on Tron — leave those columns untouched.