Words
0
Reading
0 min
1d
<?php
declare(strict_types=1);
/*
* Scanner Hive pour les opérations "comment" contenant !ECU.
* Démarre au bloc courant lorsque la page est ouverte/rechargée.
* Nécessite PHP 7.4+ et l'extension cURL.
*/
const RPC_URL = 'https://api.hive.blog';
const MARKER = '!ECU';
const TOKEN_SYMBOL = 'ECU';
const REWARD_AMOUNT = '0.00000001';
const BLOCKS_PER_REQUEST = 5;
$dataDir = __DIR__ . '/ecu-monitor-data';
if (!is_dir($dataDir) && !mkdir($dataDir, 0750, true) && !is_dir($dataDir)) {
http_response_code(500);
exit('Impossible de créer le dossier de données.');
}
$stateFile = $dataDir . '/state.json';
if (!file_exists($dataDir . '/.htaccess')) {
@file_put_contents($dataDir . '/.htaccess', "Require all denied\nDeny from all\n");
}
function readState(string $file): array
{
if (!is_file($file)) {
return ['next_block' => 0, 'items' => [], 'status' => 'Initialisation'];
}
$data = json_decode((string)file_get_contents($file), true);
return is_array($data)
? array_merge(['next_block' => 0, 'items' => [], 'status' => 'État initialisé'], $data)
: ['next_block' => 0, 'items' => [], 'status' => 'État illisible'];
}
function saveState(string $file, array $state): void
{
file_put_contents(
$file,
json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
LOCK_EX
);
}
function hiveRpc(string $method, array $params): array
{
$payload = json_encode([
'jsonrpc' => '2.0',
'method' => $method,
'params' => $params,
'id' => 1
]);
if ($payload === false) {
throw new RuntimeException('Impossible de préparer la requête Hive.');
}
$lastError = 'Erreur API inconnue';
for ($attempt = 1; $attempt <= 3; $attempt++) {
$ch = curl_init(RPC_URL);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 25
]);
$raw = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw !== false && $httpCode >= 200 && $httpCode < 300) {
$decoded = json_decode($raw, true);
if (is_array($decoded) && array_key_exists('result', $decoded)
&& is_array($decoded['result'])) {
return $decoded['result'];
}
$lastError = 'Réponse invalide de l’API Hive.';
} else {
$lastError = $curlError ?: "Erreur HTTP $httpCode";
}
usleep(300000);
}
throw new RuntimeException($lastError);
}
function jsonResponse(array $data, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
$action = $_GET['action'] ?? '';
if ($action === 'start') {
try {
$props = hiveRpc('condenser_api.get_dynamic_global_properties', []);
$head = (int)($props['head_block_number'] ?? 0);
if ($head < 1) {
throw new RuntimeException('Impossible de récupérer le dernier bloc Hive.');
}
$state = readState($stateFile);
$state['next_block'] = $head;
$state['status'] = "Démarrage au dernier bloc disponible : $head";
saveState($stateFile, $state);
jsonResponse(['ok' => true, 'state' => $state, 'head' => $head]);
} catch (Throwable $e) {
jsonResponse(['ok' => false, 'error' => $e->getMessage()], 500);
}
}
if ($action === 'clear') {
$state = readState($stateFile);
$state['items'] = [];
$state['status'] = 'Liste effacée. La position du scan est conservée.';
saveState($stateFile, $state);
jsonResponse(['ok' => true]);
}
if ($action === 'poll') {
try {
$state = readState($stateFile);
$props = hiveRpc('condenser_api.get_dynamic_global_properties', []);
$head = (int)($props['head_block_number'] ?? 0);
if ($head < 1) {
throw new RuntimeException('Hive n’a pas fourni le dernier numéro de bloc.');
}
if ((int)$state['next_block'] < 1) {
$state['next_block'] = $head;
}
$processed = 0;
$block = (int)$state['next_block'];
while ($processed < BLOCKS_PER_REQUEST && $block <= $head) {
$ops = hiveRpc('condenser_api.get_ops_in_block', [$block, false]);
foreach ($ops as $entry) {
$op = $entry['op'] ?? null;
if (!is_array($op) || count($op) < 2) {
continue;
}
$type = $op[0] ?? '';
$data = $op[1] ?? null;
if ($type !== 'comment' || !is_array($data)) {
continue;
}
$body = (string)($data['body'] ?? '');
if (stripos($body, MARKER) === false) {
continue;
}
$author = (string)($data['author'] ?? '');
$permlink = (string)($data['permlink'] ?? '');
if ($author === '' || $permlink === '') {
continue;
}
$key = $author . '/' . $permlink;
$state['items'][$key] = [
'author' => $author,
'parent_author' => (string)($data['parent_author'] ?? ''),
'parent_permlink' => (string)($data['parent_permlink'] ?? ''),
'permlink' => $permlink,
'block' => $block,
'timestamp' => (string)($entry['timestamp'] ?? ''),
'body' => $body
];
}
$block++;
$processed++;
}
$state['next_block'] = $block;
$state['status'] = 'OK — bloc scanné : ' . max(0, $block - 1) . ' / dernier bloc : ' . $head;
saveState($stateFile, $state);
jsonResponse([
'ok' => true,
'state' => $state,
'head' => $head,
'processed' => $processed
]);
} catch (Throwable $e) {
$state = readState($stateFile);
$state['status'] = 'Erreur : ' . $e->getMessage();
saveState($stateFile, $state);
jsonResponse(['ok' => false, 'error' => $e->getMessage(), 'state' => $state], 500);
}
}
$state = readState($stateFile);
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Scanner Hive — !ECU</title>
<style>
body{font:15px Arial,sans-serif;max-width:1000px;margin:25px auto;padding:0 14px;color:#222}
.card{border:1px solid #ddd;border-radius:8px;padding:18px}
.status{background:#f3f7fa;padding:10px;border-radius:5px;margin:12px 0}
button,input{padding:8px 12px;margin:4px}
button{cursor:pointer}
button:disabled{cursor:not-allowed;opacity:.55}
table{width:100%;border-collapse:collapse;margin-top:14px}
th,td{border:1px solid #ddd;padding:8px;text-align:left;vertical-align:top}
th{background:#f2f2f2}
#csvPreview{box-sizing:border-box;width:100%;margin-top:8px}
.note{color:#555;font-size:13px}
</style>
</head>
<body>
<div class="card">
<h2>�� Commentaires Hive contenant !ECU</h2>
<p>Recherche dans le corps des opérations « comment ». La page démarre au dernier bloc disponible et se met à jour toutes les 5 secondes.</p>
<div id="status" class="status">Démarrage du scanner…</div>
<p><button id="clear" type="button">�� Effacer la liste</button></p>
<h3>�� Récompenses ECU</h3>
<label for="sender">Compte Hive expéditeur :</label>
<input id="sender" type="text" placeholder="votre-compte">
<div>
<button id="prepare" type="button">�� Préparer les transferts</button>
<button id="download" type="button" disabled>⬇️ Télécharger CSV</button>
<button id="send" type="button" disabled>�� Envoyer ECU</button>
</div>
<p class="note">
Une récompense est proposée à l’auteur du commentaire et à l’auteur du commentaire parent, s’il existe.
Vérifiez chaque transfert : Hive Keychain demandera votre confirmation.
</p>
<textarea id="csvPreview" rows="6" readonly placeholder="La liste CSV apparaîtra ici."></textarea>
<div id="transferStatus" class="status">Aucun transfert préparé.</div>
<hr>
<div id="count">0 résultat</div>
<table>
<thead><tr><th>Auteur</th><th>Bloc</th><th>Date</th><th>Répond à</th><th>Commentaire</th></tr></thead>
<tbody id="rows"></tbody>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/@hiveio/keychain/dist/keychain.min.js"></script>
<script>
'use strict';
const amount = '<?=htmlspecialchars(REWARD_AMOUNT, ENT_QUOTES, 'UTF-8')?>';
const token = '<?=htmlspecialchars(TOKEN_SYMBOL, ENT_QUOTES, 'UTF-8')?>';
let items = [];
let prepared = [];
let isSending = false;
function esc(value) {
return String(value).replace(/[&<>"']/g, c => ({
'&':'&', '<':'<', '>':'>', '"':'"', "'":'''
})[c]);
}
function validAccount(account) {
return /^[a-z0-9][a-z0-9.-]{1,14}$/.test(account);
}
function storageKey(sender) {
return 'ecuSentAccounts:' + sender.toLowerCase();
}
function sentAccounts(sender) {
try {
const value = JSON.parse(localStorage.getItem(storageKey(sender)) || '[]');
return new Set(Array.isArray(value) ? value : []);
} catch (e) {
return new Set();
}
}
function rememberSent(sender, recipient) {
const sent = sentAccounts(sender);
sent.add(recipient.toLowerCase());
localStorage.setItem(storageKey(sender), JSON.stringify([...sent]));
}
async function poll() {
const response = await fetch('?action=poll&_=' + Date.now(), {cache:'no-store'});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || 'Erreur de scan inconnue.');
}
const state = data.state || {};
document.getElementById('status').textContent = state.status || '';
items = Object.values(state.items || {}).sort((a,b) => Number(b.block) - Number(a.block));
document.getElementById('count').textContent =
items.length + (items.length === 1 ? ' résultat trouvé' : ' résultats trouvés');
document.getElementById('rows').innerHTML = items.map(item => {
const author = String(item.author || '').replace(/^@/, '');
const parent = String(item.parent_author || '').replace(/^@/, '');
const body = String(item.body || '');
const preview = body.length > 400 ? body.slice(0,400) + '…' : body;
const link = 'https://peakd.com/@' + encodeURIComponent(author) + '/' +
encodeURIComponent(String(item.permlink || ''));
return `<tr>
<td><a target="_blank" rel="noopener" href="${esc(link)}">@${esc(author)}</a></td>
<td>${esc(item.block || '')}</td>
<td>${esc(item.timestamp || '')}</td>
<td>${parent ? '@' + esc(parent) : '—'}</td>
<td>${esc(preview)}</td>
</tr>`;
}).join('');
}
async function startScanner() {
const response = await fetch('?action=start&_=' + Date.now(), {cache:'no-store'});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || 'Impossible de démarrer le scanner.');
}
await poll();
}
document.getElementById('prepare').addEventListener('click', function() {
const sender = document.getElementById('sender').value.trim().replace(/^@/,'').toLowerCase();
const recipients = new Set();
for (const item of items) {
const author = String(item.author || '').replace(/^@/,'').toLowerCase();
const parent = String(item.parent_author || '').replace(/^@/,'').toLowerCase();
if (validAccount(author)) recipients.add(author);
if (validAccount(parent)) recipients.add(parent);
}
const already = validAccount(sender) ? sentAccounts(sender) : new Set();
prepared = [...recipients]
.filter(account => account !== sender && !already.has(account))
.map(to => ({to, amount, token, memo:'!ECU'}));
const csv = prepared.map(t => `${t.to},${t.amount},${t.token},${t.memo}`).join('\n');
document.getElementById('csvPreview').value = csv;
document.getElementById('download').disabled = prepared.length === 0;
document.getElementById('send').disabled = prepared.length === 0;
document.getElementById('transferStatus').textContent = prepared.length
? `${prepared.length} transfert(s) préparé(s). Les comptes déjà récompensés dans ce navigateur sont ignorés.`
: 'Aucun nouveau compte à récompenser.';
});
document.getElementById('download').addEventListener('click', function() {
if (!prepared.length) return;
const csv = prepared.map(t => `${t.to},${t.amount},${t.token},${t.memo}`).join('\n');
const url = URL.createObjectURL(new Blob([csv], {type:'text/csv;charset=utf-8'}));
const link = document.createElement('a');
link.href = url;
link.download = 'ecu-transfers.csv';
link.click();
URL.revokeObjectURL(url);
});
document.getElementById('send').addEventListener('click', async function() {
if (isSending) return;
const sender = document.getElementById('sender').value.trim().replace(/^@/,'').toLowerCase();
const status = document.getElementById('transferStatus');
if (!validAccount(sender)) {
status.textContent = 'Saisissez un nom de compte Hive valide.';
return;
}
if (!prepared.length) {
status.textContent = 'Préparez d’abord la liste des transferts.';
return;
}
if (!window.hive_keychain || typeof window.hive_keychain.requestCustomJson !== 'function') {
status.textContent = 'Hive Keychain est introuvable. Activez ou installez l’extension.';
return;
}
if (!confirm(`Envoyer ${prepared.length} transfert(s) de ${amount} ${token} depuis @${sender} ?`)) {
return;
}
isSending = true;
document.getElementById('send').disabled = true;
try {
for (let i = 0; i < prepared.length; i++) {
const transfer = prepared[i];
status.textContent = `Transfert ${i + 1}/${prepared.length} vers @${transfer.to} : confirmez dans Hive Keychain…`;
const json = JSON.stringify({
contractName: 'tokens',
contractAction: 'transfer',
contractPayload: {
symbol: transfer.token,
to: transfer.to,
quantity: transfer.amount,
memo: transfer.memo
}
});
const result = await new Promise(resolve => {
window.hive_keychain.requestCustomJson(
sender,
'ssc-mainnet-hive',
'Active',
json,
`Envoyer ${amount} ${token} à @${transfer.to} pour !ECU`,
resolve
);
});
if (!result || !result.success) {
status.textContent = `Arrêt du transfert vers @${transfer.to} : ` +
(result?.message || result?.error || 'transfert refusé ou erreur inconnue.');
return;
}
rememberSent(sender, transfer.to);
status.textContent = `✅ ${i + 1}/${prepared.length} transfert(s) confirmé(s) par Keychain.`;
await new Promise(resolve => setTimeout(resolve, 1200));
}
status.textContent = `✅ Terminé : ${prepared.length} transfert(s) confirmé(s).`;
prepared = [];
document.getElementById('csvPreview').value = '';
document.getElementById('download').disabled = true;
document.getElementById('send').disabled = true;
} catch (error) {
status.textContent = 'Erreur pendant les transferts : ' + error.message;
} finally {
isSending = false;
document.getElementById('send').disabled = prepared.length === 0;
}
});
document.getElementById('clear').addEventListener('click', async function() {
if (!confirm('Effacer les résultats affichés ?')) return;
try {
const response = await fetch('?action=clear', {cache:'no-store'});
if (!response.ok) throw new Error('Impossible d’effacer la liste.');
prepared = [];
document.getElementById('csvPreview').value = '';
document.getElementById('download').disabled = true;
document.getElementById('send').disabled = true;
document.getElementById('transferStatus').textContent = 'Liste effacée.';
await poll();
} catch (error) {
document.getElementById('status').textContent = error.message;
}
});
startScanner().catch(error => {
document.getElementById('status').textContent = 'Erreur de démarrage : ' + error.message;
});
setInterval(() => {
poll().catch(error => {
document.getElementById('status').textContent = 'Erreur de scan : ' + error.message;
});
}, 5000);
</script>
</body>
</html>
RE: Francophones: Hive.vote migre, pensez à rester actifs...