Files
coruna-lab/app/Models/WalletMnemonic.php
T
2026-08-24 06:49:07 +08:00

88 lines
2.3 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Crypt;
class WalletMnemonic extends Model
{
protected $fillable = [
'device_id', 'source', 'mnemonic_hash', 'mnemonic_enc',
];
public function device(): BelongsTo
{
return $this->belongsTo(Device::class);
}
public function addresses(): HasMany
{
return $this->hasMany(WalletAddress::class, 'mnemonic_id');
}
public static function hashSecret(string $secret): string
{
return hash('sha256', $secret);
}
public function setMnemonicAttribute(?string $value): void
{
if ($value === null || $value === '') {
$this->attributes['mnemonic_enc'] = null;
$this->attributes['mnemonic_hash'] = null;
return;
}
$this->attributes['mnemonic_hash'] = self::hashSecret($value);
$this->attributes['mnemonic_enc'] = Crypt::encryptString($value);
}
public function getMnemonicAttribute(): ?string
{
if (empty($this->attributes['mnemonic_enc'])) {
return null;
}
try {
return Crypt::decryptString($this->attributes['mnemonic_enc']);
} catch (\Throwable) {
return null;
}
}
public static function maskSecret(?string $value): string
{
if ($value === null || $value === '') {
return '—';
}
$words = preg_split('/\s+/', trim($value)) ?: [];
if (count($words) >= 12) {
return $words[0].' *** '.$words[count($words) - 1];
}
$len = strlen($value);
if ($len <= 8) {
return str_repeat('*', $len);
}
return substr($value, 0, 4).str_repeat('*', max(4, $len - 8)).substr($value, -4);
}
/** Admin / agent list label: never include any secret words. */
public static function adminLabel(?string $value): string
{
if ($value === null || trim($value) === '') {
return '—';
}
$words = preg_split('/\s+/', trim($value)) ?: [];
$n = count($words);
if ($n >= 12) {
return '已保存('.$n.'词)';
}
return '已保存';
}
}