Add UTXO consolidation, pagination and sorting to UTXO list

**Motivations:**
- Améliorer l'affichage de la liste des UTXOs avec pagination et tri
- Permettre la consolidation des petits UTXOs (< 2500 sats) pour optimiser le wallet
- Afficher le nombre d'UTXOs confirmés disponibles pour l'ancrage

**Root causes:**
- La liste des UTXOs pouvait être très longue et difficile à naviguer
- Les petits UTXOs (< 2500 sats) s'accumulaient sans possibilité de consolidation
- Le nombre d'UTXOs confirmés n'était pas affiché séparément

**Correctifs:**
- Filtrage des UTXOs confirmés (minconf=1) dans getUtxoList() pour éviter les erreurs too-long-mempool-chain
- Ajout du compteur confirmedAvailableForAnchor dans la réponse API
- Création de la méthode consolidateSmallUtxos() pour consolider les UTXOs < 2500 sats
- Ajout de la route POST /api/utxo/consolidate pour déclencher la consolidation

**Evolutions:**
- Pagination des résultats par 100 UTXOs par page avec contrôles précédent/suivant
- Tri des montants et confirmations avec flèches (croissant/décroissant) au clic sur les en-têtes
- Affichage du nombre d'UTXOs confirmés dans la section "Capacité d'ancrage restante"
- Bouton "Consolider les UTXOs < 2500 sats" pour optimiser le wallet
- Pagination également appliquée à la table des frais

**Pages affectées:**
- signet-dashboard/src/bitcoin-rpc.js: Filtrage UTXOs confirmés, méthode consolidateSmallUtxos()
- signet-dashboard/src/server.js: Route /api/utxo/consolidate, ajout confirmedAvailableForAnchor dans counts
- signet-dashboard/public/utxo-list.html: Pagination, tri, bouton consolidation, affichage UTXOs confirmés
This commit is contained in:
ncantu 2026-01-25 23:30:35 +01:00
parent c31d3a4f0c
commit e86ac5a0d9
3 changed files with 600 additions and 24 deletions

View File

@ -147,6 +147,61 @@
background: #6c757d; background: #6c757d;
cursor: not-allowed; cursor: not-allowed;
} }
.consolidate-button {
background: #ffc107;
color: #000;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
margin-top: 10px;
}
.consolidate-button:hover {
background: #e0a800;
}
.consolidate-button:disabled {
background: #6c757d;
cursor: not-allowed;
}
.sortable-header {
cursor: pointer;
user-select: none;
position: relative;
}
.sortable-header:hover {
background: #e9ecef;
}
.sort-arrow {
display: inline-block;
margin-left: 5px;
font-size: 0.8em;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
margin: 20px 0;
}
.pagination-button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.pagination-button:hover:not(:disabled) {
background: #0056b3;
}
.pagination-button:disabled {
background: #6c757d;
cursor: not-allowed;
}
.pagination-info {
font-weight: bold;
}
.total-amount { .total-amount {
font-size: 1.2em; font-size: 1.2em;
font-weight: bold; font-weight: bold;
@ -208,7 +263,8 @@
<h1>Liste des UTXO</h1> <h1>Liste des UTXO</h1>
<div class="info-section"> <div class="info-section">
<p><strong>Total d'UTXO :</strong> <span id="utxo-count">-</span></p> <p><strong>Total d'UTXO :</strong> <span id="utxo-count">-</span></p>
<p><strong>Capacité d'ancrage restante :</strong> <span id="available-for-anchor">-</span> ancrages</p> <p><strong>Capacité d'ancrage restante :</strong> <span id="available-for-anchor">-</span> ancrages (<span id="confirmed-available-for-anchor">-</span> UTXOs confirmés)</p>
<button class="consolidate-button" onclick="consolidateSmallUtxos()" style="margin-left: 10px; background: #ffc107; color: #000; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-size: 1em; margin-top: 10px;">Consolider les UTXOs < 2500 sats</button>
<p><strong>Montant total :</strong> <span id="total-amount" class="total-amount">-</span></p> <p><strong>Montant total :</strong> <span id="total-amount" class="total-amount">-</span></p>
<p><strong>Dernière mise à jour :</strong> <span id="last-update">-</span></p> <p><strong>Dernière mise à jour :</strong> <span id="last-update">-</span></p>
<button class="refresh-button" onclick="loadUtxoList()">Actualiser</button> <button class="refresh-button" onclick="loadUtxoList()">Actualiser</button>
@ -231,12 +287,58 @@
<script> <script>
const API_BASE_URL = window.location.origin; const API_BASE_URL = window.location.origin;
const ITEMS_PER_PAGE = 100;
// État de tri et pagination pour chaque catégorie
const tableState = {};
// Charger la liste au chargement de la page // Charger la liste au chargement de la page
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
loadUtxoList(); loadUtxoList();
}); });
function getSortState(categoryName) {
if (!tableState[categoryName]) {
tableState[categoryName] = {
sortColumn: null,
sortDirection: 'desc',
currentPage: 1,
};
}
return tableState[categoryName];
}
function sortUtxos(utxos, sortColumn, sortDirection) {
const sorted = [...utxos];
sorted.sort((a, b) => {
let aVal, bVal;
if (sortColumn === 'amount') {
aVal = a.amount;
bVal = b.amount;
} else if (sortColumn === 'confirmations') {
aVal = a.confirmations || 0;
bVal = b.confirmations || 0;
} else {
return 0;
}
if (sortDirection === 'asc') {
return aVal - bVal;
} else {
return bVal - aVal;
}
});
return sorted;
}
function getSortArrow(sortColumn, currentSortColumn, sortDirection) {
if (sortColumn !== currentSortColumn) {
return '<span class="sort-arrow"></span>';
}
return sortDirection === 'asc'
? '<span class="sort-arrow"></span>'
: '<span class="sort-arrow"></span>';
}
function renderTable(utxos, categoryName, categoryLabel) { function renderTable(utxos, categoryName, categoryLabel) {
if (utxos.length === 0) { if (utxos.length === 0) {
return ` return `
@ -253,6 +355,20 @@
`; `;
} }
const state = getSortState(categoryName);
// Trier les UTXOs
let sortedUtxos = utxos;
if (state.sortColumn) {
sortedUtxos = sortUtxos(utxos, state.sortColumn, state.sortDirection);
}
// Paginer les UTXOs
const totalPages = Math.ceil(sortedUtxos.length / ITEMS_PER_PAGE);
const startIndex = (state.currentPage - 1) * ITEMS_PER_PAGE;
const endIndex = startIndex + ITEMS_PER_PAGE;
const paginatedUtxos = sortedUtxos.slice(startIndex, endIndex);
const totalAmount = utxos.reduce((sum, utxo) => sum + utxo.amount, 0); const totalAmount = utxos.reduce((sum, utxo) => sum + utxo.amount, 0);
const totalSats = Math.round(totalAmount * 100000000); const totalSats = Math.round(totalAmount * 100000000);
const isAnchors = categoryName === 'ancrages'; const isAnchors = categoryName === 'ancrages';
@ -290,32 +406,32 @@
if (isAnchors) { if (isAnchors) {
tableHTML += ` tableHTML += `
<th>Numéro de bloc</th> <th>Numéro de bloc</th>
<th style="text-align: right;">Montant (✅)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (✅)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th>Confirmations</th> <th class="sortable-header" onclick="toggleSort('${categoryName}', 'confirmations')">Confirmations${getSortArrow('confirmations', state.sortColumn, state.sortDirection)}</th>
<th>Statut</th> <th>Statut</th>
`; `;
} else if (isBlocRewards) { } else if (isBlocRewards) {
tableHTML += ` tableHTML += `
<th style="text-align: right;">Montant (🛡)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (🛡)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th>Date</th> <th>Date</th>
<th>Confirmations</th> <th class="sortable-header" onclick="toggleSort('${categoryName}', 'confirmations')">Confirmations${getSortArrow('confirmations', state.sortColumn, state.sortDirection)}</th>
<th>Statut</th> <th>Statut</th>
`; `;
} else { } else {
// Pour la section changes, ajouter une colonne pour indiquer si c'est un change d'ancrage // Pour la section changes, ajouter une colonne pour indiquer si c'est un change d'ancrage
if (categoryName === 'changes') { if (categoryName === 'changes') {
tableHTML += ` tableHTML += `
<th style="text-align: right;">Montant (🛡)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (🛡)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th style="text-align: right;">Montant (✅)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (✅)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th>Confirmations</th> <th class="sortable-header" onclick="toggleSort('${categoryName}', 'confirmations')">Confirmations${getSortArrow('confirmations', state.sortColumn, state.sortDirection)}</th>
<th>Type</th> <th>Type</th>
<th>Statut</th> <th>Statut</th>
`; `;
} else { } else {
tableHTML += ` tableHTML += `
<th style="text-align: right;">Montant (🛡)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (🛡)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th style="text-align: right;">Montant (✅)</th> <th class="sortable-header" style="text-align: right;" onclick="toggleSort('${categoryName}', 'amount')">Montant (✅)${getSortArrow('amount', state.sortColumn, state.sortDirection)}</th>
<th>Confirmations</th> <th class="sortable-header" onclick="toggleSort('${categoryName}', 'confirmations')">Confirmations${getSortArrow('confirmations', state.sortColumn, state.sortDirection)}</th>
<th>Statut</th> <th>Statut</th>
`; `;
} }
@ -327,7 +443,7 @@
<tbody> <tbody>
`; `;
utxos.forEach((utxo) => { paginatedUtxos.forEach((utxo) => {
const mempoolUrl = 'https://mempool.4nkweb.com/fr'; const mempoolUrl = 'https://mempool.4nkweb.com/fr';
const txLink = `${mempoolUrl}/tx/${utxo.txid}`; const txLink = `${mempoolUrl}/tx/${utxo.txid}`;
const amountSats = Math.round(utxo.amount * 100000000); const amountSats = Math.round(utxo.amount * 100000000);
@ -384,6 +500,20 @@
</tbody> </tbody>
</table> </table>
</div> </div>
`;
// Ajouter la pagination
if (totalPages > 1) {
tableHTML += `
<div class="pagination">
<button class="pagination-button" onclick="changePage('${categoryName}', ${state.currentPage - 1})" ${state.currentPage === 1 ? 'disabled' : ''}>← Précédent</button>
<span class="pagination-info">Page ${state.currentPage} / ${totalPages} (${sortedUtxos.length.toLocaleString('fr-FR')} UTXOs)</span>
<button class="pagination-button" onclick="changePage('${categoryName}', ${state.currentPage + 1})" ${state.currentPage === totalPages ? 'disabled' : ''}>Suivant →</button>
</div>
`;
}
tableHTML += `
</div> </div>
`; `;
@ -411,8 +541,12 @@
const changes = data.changes || []; const changes = data.changes || [];
const fees = data.fees || []; const fees = data.fees || [];
// Sauvegarder les données pour la pagination
currentUtxosData = { blocRewards, anchors, changes, fees };
document.getElementById('utxo-count').textContent = counts.total.toLocaleString('fr-FR'); document.getElementById('utxo-count').textContent = counts.total.toLocaleString('fr-FR');
document.getElementById('available-for-anchor').textContent = (counts.availableForAnchor || 0).toLocaleString('fr-FR'); document.getElementById('available-for-anchor').textContent = (counts.availableForAnchor || 0).toLocaleString('fr-FR');
document.getElementById('confirmed-available-for-anchor').textContent = (counts.confirmedAvailableForAnchor || 0).toLocaleString('fr-FR');
// Calculer le montant total // Calculer le montant total
const totalAmount = blocRewards.reduce((sum, utxo) => sum + utxo.amount, 0) + const totalAmount = blocRewards.reduce((sum, utxo) => sum + utxo.amount, 0) +
@ -469,6 +603,14 @@
`; `;
} }
const state = getSortState(categoryName);
// Paginer les fees
const totalPages = Math.ceil(fees.length / ITEMS_PER_PAGE);
const startIndex = (state.currentPage - 1) * ITEMS_PER_PAGE;
const endIndex = startIndex + ITEMS_PER_PAGE;
const paginatedFees = fees.slice(startIndex, endIndex);
const totalFees = fees.reduce((sum, fee) => sum + fee.fee, 0); const totalFees = fees.reduce((sum, fee) => sum + fee.fee, 0);
const totalFeesSats = Math.round(totalFees * 100000000); const totalFeesSats = Math.round(totalFees * 100000000);
@ -498,7 +640,7 @@
<tbody> <tbody>
`; `;
fees.forEach((fee) => { paginatedFees.forEach((fee) => {
const mempoolUrl = 'https://mempool.4nkweb.com/fr'; const mempoolUrl = 'https://mempool.4nkweb.com/fr';
const txLink = `${mempoolUrl}/tx/${fee.txid}`; const txLink = `${mempoolUrl}/tx/${fee.txid}`;
const feeSats = fee.fee_sats || Math.round(fee.fee * 100000000); const feeSats = fee.fee_sats || Math.round(fee.fee * 100000000);
@ -534,12 +676,87 @@
const now = new Date(); const now = new Date();
document.getElementById('last-update').textContent = now.toLocaleString('fr-FR'); document.getElementById('last-update').textContent = now.toLocaleString('fr-FR');
} }
function toggleSort(categoryName, column) {
const state = getSortState(categoryName);
if (state.sortColumn === column) {
state.sortDirection = state.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
state.sortColumn = column;
state.sortDirection = 'desc';
}
state.currentPage = 1; // Reset to first page when sorting
loadUtxoList();
}
function changePage(categoryName, page) {
const state = getSortState(categoryName);
let items = [];
if (categoryName === 'fees') {
items = currentUtxosData.fees || [];
} else {
items = getCurrentUtxos(categoryName);
}
const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
if (page >= 1 && page <= totalPages) {
state.currentPage = page;
loadUtxoList();
}
}
function getCurrentUtxos(categoryName) {
if (categoryName === 'bloc-rewards') return currentUtxosData.blocRewards || [];
if (categoryName === 'ancrages') return currentUtxosData.anchors || [];
if (categoryName === 'changes') return currentUtxosData.changes || [];
if (categoryName === 'fees') return currentUtxosData.fees || [];
return [];
}
async function consolidateSmallUtxos() {
const button = document.querySelector('.consolidate-button');
const originalText = button.textContent;
button.disabled = true;
button.textContent = '⏳ Consolidation en cours...';
try {
const response = await fetch(`${API_BASE_URL}/api/utxo/consolidate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
alert(`Consolidation réussie!\n\nTransaction ID: ${result.txid}\nUTXOs consolidés: ${result.inputCount}\nMontant total: ${formatBTC(result.totalInputAmount)}\nChange: ${formatBTC(result.changeAmount)}\nFrais estimés: ${formatBTC(result.estimatedFee)}`);
// Recharger la liste après consolidation
setTimeout(() => {
loadUtxoList();
}, 2000);
} else {
throw new Error(result.error || 'Consolidation échouée');
}
} catch (error) {
console.error('Error consolidating UTXOs:', error);
alert(`Erreur lors de la consolidation: ${error.message}`);
} finally {
button.disabled = false;
button.textContent = originalText;
}
}
</script> </script>
<footer> <footer>
<p>Bitcoin Ancrage Dashboard - Équipe 4NK</p> <p>Bitcoin Ancrage Dashboard - Équipe 4NK</p>
<a href="https://git.4nkweb.com/4nk/anchorage_layer_simple.git" target="_blank" rel="noopener noreferrer" class="git-link" title="Voir le code source sur Git"> <a href="https://git.4nkweb.com/4nk/anchorage_layer_simple.git" target="_blank" rel="noopener noreferrer" class="git-link" title="Voir le code source sur Git">
<svg class="git-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <svg class="git-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/> <path d="M23.546 10.93L13.067.452c-.604-.603-1.582-.603-2.188 0L8.708 2.627l2.76 2.76c.645-.215 1.379-.07 1.889.441.516.515.658 1.258.438 1.9l2.658 2.66c.645-.223 1.387-.083 1.9.435.721.72.721 1.884 0 2.604-.719.719-1.881.719-2.6 0-.539-.541-.674-1.337-.404-1.996L12.86 8.955v6.525c.176.086.342.203.488.348.713.721.713 1.883 0 2.6-.719.721-1.884.721-2.599 0-.72-.719-.72-1.879 0-2.598.182-.18.387-.316.605-.406V8.835c-.217-.091-.424-.222-.6-.401-.545-.545-.676-1.342-.396-2.011L7.636 3.7.45 10.881c-.6.605-.6 1.584 0 2.189l10.48 10.477c.604.604 1.582.604 2.186 0l10.43-10.43c.605-.603.605-1.582 0-2.187"/>
</svg> </svg>
</a> </a>
</footer> </footer>

View File

@ -338,7 +338,7 @@ class BitcoinRPC {
jsonrpc: '1.0', jsonrpc: '1.0',
id: 'listunspent', id: 'listunspent',
method: 'listunspent', method: 'listunspent',
params: [0], // Inclure les non confirmés params: [1], // Minimum 1 confirmation to avoid too-long-mempool-chain errors
}), }),
}); });
@ -673,11 +673,22 @@ class BitcoinRPC {
return b.amount - a.amount; return b.amount - a.amount;
}); });
// Calculer le nombre d'UTXO disponibles pour l'ancrage (> 2000 sats et non dépensés) // Calculer le nombre d'UTXO disponibles pour l'ancrage (> 2000 sats, confirmés et non dépensés)
const allUtxos = [...blocRewards, ...anchors, ...changes]; const allUtxos = [...blocRewards, ...anchors, ...changes];
const minAnchorAmount = 2000 / 100000000; // 2000 sats en BTC const minAnchorAmount = 2000 / 100000000; // 2000 sats en BTC
const availableForAnchor = allUtxos.filter(utxo => const availableForAnchor = allUtxos.filter(utxo =>
utxo.amount >= minAnchorAmount && !utxo.isSpentOnchain && !utxo.isLockedInMutex utxo.amount >= minAnchorAmount &&
(utxo.confirmations || 0) > 0 && // Only confirmed UTXOs
!utxo.isSpentOnchain &&
!utxo.isLockedInMutex
).length;
// Compter les UTXOs confirmés disponibles pour l'ancrage
const confirmedAvailableForAnchor = allUtxos.filter(utxo =>
utxo.amount >= minAnchorAmount &&
(utxo.confirmations || 0) > 0 && // Only confirmed UTXOs
!utxo.isSpentOnchain &&
!utxo.isLockedInMutex
).length; ).length;
// Mettre à jour le cache // Mettre à jour le cache
@ -725,6 +736,7 @@ class BitcoinRPC {
fees, fees,
total: allUtxos.length, total: allUtxos.length,
availableForAnchor, availableForAnchor,
confirmedAvailableForAnchor,
}; };
} catch (error) { } catch (error) {
logger.error('Error getting UTXO list', { error: error.message }); logger.error('Error getting UTXO list', { error: error.message });
@ -732,6 +744,266 @@ class BitcoinRPC {
} }
} }
/**
* Consolide les UTXOs de moins de 2500 sats en un gros UTXO
* @returns {Promise<Object>} Transaction créée avec txid
*/
async consolidateSmallUtxos() {
try {
const walletName = process.env.BITCOIN_RPC_WALLET || 'custom_signet';
const host = process.env.BITCOIN_RPC_HOST || 'localhost';
const port = process.env.BITCOIN_RPC_PORT || '38332';
const username = process.env.BITCOIN_RPC_USER || 'bitcoin';
const password = process.env.BITCOIN_RPC_PASSWORD || 'bitcoin';
const rpcUrl = `http://${host}:${port}/wallet/${walletName}`;
const auth = Buffer.from(`${username}:${password}`).toString('base64');
// Récupérer les UTXOs confirmés
const rpcResponse = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify({
jsonrpc: '1.0',
id: 'listunspent',
method: 'listunspent',
params: [1], // Minimum 1 confirmation
}),
});
if (!rpcResponse.ok) {
const errorText = await rpcResponse.text();
logger.error('HTTP error in listunspent for consolidation', {
status: rpcResponse.status,
statusText: rpcResponse.statusText,
response: errorText,
});
throw new Error(`HTTP error fetching UTXOs: ${rpcResponse.status} ${rpcResponse.statusText}`);
}
const rpcResult = await rpcResponse.json();
if (rpcResult.error) {
logger.error('RPC error in listunspent for consolidation', { error: rpcResult.error });
throw new Error(`RPC error: ${rpcResult.error.message}`);
}
const unspent = rpcResult.result || [];
// Récupérer les UTXOs verrouillés depuis l'API d'ancrage
let lockedUtxos = new Set();
try {
const anchorApiUrl = process.env.ANCHOR_API_URL || 'http://localhost:3010';
const anchorApiKey = process.env.ANCHOR_API_KEY || '';
const headers = {
'Content-Type': 'application/json',
};
if (anchorApiKey) {
headers['x-api-key'] = anchorApiKey;
}
const lockedResponse = await fetch(`${anchorApiUrl}/api/anchor/locked-utxos`, {
method: 'GET',
headers,
});
if (lockedResponse.ok) {
const lockedData = await lockedResponse.json();
for (const locked of lockedData.locked || []) {
lockedUtxos.add(`${locked.txid}:${locked.vout}`);
}
}
} catch (error) {
logger.debug('Error getting locked UTXOs for consolidation', { error: error.message });
}
// Filtrer les UTXOs de moins de 2500 sats (0.000025 BTC), confirmés, non dépensés et non verrouillés
const maxAmount = 0.000025; // 2500 sats
const smallUtxos = unspent.filter(utxo => {
const utxoKey = `${utxo.txid}:${utxo.vout}`;
return utxo.amount < maxAmount &&
(utxo.confirmations || 0) > 0 &&
!lockedUtxos.has(utxoKey);
});
// Vérifier si l'UTXO est dépensé onchain
const availableSmallUtxos = [];
for (const utxo of smallUtxos) {
try {
const txOutResponse = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify({
jsonrpc: '1.0',
id: 'gettxout',
method: 'gettxout',
params: [utxo.txid, utxo.vout],
}),
});
if (txOutResponse.ok) {
const txOutResult = await txOutResponse.json();
// Si gettxout retourne null, l'UTXO est dépensé
if (txOutResult.result !== null) {
availableSmallUtxos.push(utxo);
}
}
} catch (error) {
logger.debug('Error checking if UTXO is spent for consolidation', { txid: utxo.txid, vout: utxo.vout, error: error.message });
}
}
if (availableSmallUtxos.length === 0) {
throw new Error('No small UTXOs available for consolidation');
}
logger.info('Consolidating small UTXOs', {
count: availableSmallUtxos.length,
totalAmount: availableSmallUtxos.reduce((sum, utxo) => sum + utxo.amount, 0),
});
// Calculer le montant total
const totalAmount = availableSmallUtxos.reduce((sum, utxo) => sum + utxo.amount, 0);
// Estimation des frais : base + frais par input
const estimatedFeePerInput = 0.000001; // Frais par input (conservateur)
const estimatedFeeBase = 0.00001; // Frais de base
const estimatedFee = estimatedFeeBase + (availableSmallUtxos.length * estimatedFeePerInput);
// Arrondir à 8 décimales
const roundTo8Decimals = (amount) => {
return Math.round(amount * 100000000) / 100000000;
};
const change = roundTo8Decimals(totalAmount - estimatedFee);
if (change <= 0) {
throw new Error('Consolidation would result in negative or zero change after fees');
}
// Obtenir une adresse de destination pour le gros UTXO consolidé
const address = await this.getNewAddress();
// Créer les inputs
const inputs = availableSmallUtxos.map(utxo => ({
txid: utxo.txid,
vout: utxo.vout,
}));
// Créer les outputs
const outputs = {
[address]: change,
};
// Créer la transaction
const createTxResponse = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify({
jsonrpc: '1.0',
id: 'createrawtransaction',
method: 'createrawtransaction',
params: [inputs, outputs],
}),
});
if (!createTxResponse.ok) {
const errorText = await createTxResponse.text();
throw new Error(`HTTP error creating transaction: ${createTxResponse.status} ${errorText}`);
}
const createTxResult = await createTxResponse.json();
if (createTxResult.error) {
throw new Error(`RPC error creating transaction: ${createTxResult.error.message}`);
}
const rawTx = createTxResult.result;
// Signer la transaction
const signTxResponse = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify({
jsonrpc: '1.0',
id: 'signrawtransactionwithwallet',
method: 'signrawtransactionwithwallet',
params: [rawTx],
}),
});
if (!signTxResponse.ok) {
const errorText = await signTxResponse.text();
throw new Error(`HTTP error signing transaction: ${signTxResponse.status} ${errorText}`);
}
const signTxResult = await signTxResponse.json();
if (signTxResult.error) {
throw new Error(`RPC error signing transaction: ${signTxResult.error.message}`);
}
if (!signTxResult.result.complete) {
throw new Error('Transaction signing failed');
}
// Envoyer la transaction au mempool
const sendTxResponse = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify({
jsonrpc: '1.0',
id: 'sendrawtransaction',
method: 'sendrawtransaction',
params: [signTxResult.result.hex, 0], // maxfeerate = 0 (accepter n'importe quel taux)
}),
});
if (!sendTxResponse.ok) {
const errorText = await sendTxResponse.text();
throw new Error(`HTTP error sending transaction: ${sendTxResponse.status} ${errorText}`);
}
const sendTxResult = await sendTxResponse.json();
if (sendTxResult.error) {
throw new Error(`RPC error sending transaction: ${sendTxResult.error.message}`);
}
const txid = sendTxResult.result;
logger.info('Consolidation transaction sent to mempool', {
txid,
inputCount: availableSmallUtxos.length,
totalInputAmount: totalAmount,
changeAmount: change,
estimatedFee,
});
return {
txid,
inputCount: availableSmallUtxos.length,
totalInputAmount: totalAmount,
changeAmount: change,
estimatedFee,
};
} catch (error) {
logger.error('Error consolidating small UTXOs', { error: error.message });
throw error;
}
}
/** /**
* Obtient le nombre d'ancrages en comptant tous les blocs depuis le début * Obtient le nombre d'ancrages en comptant tous les blocs depuis le début
* Utilise un fichier de cache anchor_count.txt pour éviter de tout recompter * Utilise un fichier de cache anchor_count.txt pour éviter de tout recompter

View File

@ -129,8 +129,9 @@ const HOST = process.env.DASHBOARD_HOST || '0.0.0.0';
// Middleware // Middleware
app.use(cors()); app.use(cors());
app.use(express.json()); // Augmenter la limite de taille pour le body JSON (100MB) pour supporter les gros fichiers en base64
app.use(express.urlencoded({ extended: true })); app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
// Middleware de logging // Middleware de logging
app.use((req, res, next) => { app.use((req, res, next) => {
@ -141,6 +142,22 @@ app.use((req, res, next) => {
next(); next();
}); });
// Middleware pour gérer les erreurs de parsing JSON
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
logger.error('JSON parsing error', {
error: err.message,
path: req.path,
method: req.method
});
return res.status(400).json({
error: 'Invalid JSON',
message: err.message
});
}
next(err);
});
// Routes spécifiques AVANT le middleware static pour éviter les conflits // Routes spécifiques AVANT le middleware static pour éviter les conflits
// Route pour la page principale // Route pour la page principale
app.get('/', (req, res) => { app.get('/', (req, res) => {
@ -272,6 +289,7 @@ app.get('/api/utxo/list', async (req, res) => {
fees: (utxoData.fees || []).length, fees: (utxoData.fees || []).length,
total: utxoData.total, total: utxoData.total,
availableForAnchor: utxoData.availableForAnchor || 0, availableForAnchor: utxoData.availableForAnchor || 0,
confirmedAvailableForAnchor: utxoData.confirmedAvailableForAnchor || 0,
}, },
}); });
} catch (error) { } catch (error) {
@ -280,6 +298,27 @@ app.get('/api/utxo/list', async (req, res) => {
} }
}); });
// Route pour consolider les UTXOs de moins de 2500 sats
app.post('/api/utxo/consolidate', async (req, res) => {
try {
const result = await bitcoinRPC.consolidateSmallUtxos();
res.json({
success: true,
txid: result.txid,
inputCount: result.inputCount,
totalInputAmount: result.totalInputAmount,
changeAmount: result.changeAmount,
estimatedFee: result.estimatedFee,
});
} catch (error) {
logger.error('Error consolidating UTXOs', { error: error.message });
res.status(500).json({
success: false,
error: error.message,
});
}
});
// Route pour servir le fichier texte des UTXO // Route pour servir le fichier texte des UTXO
app.get('/api/utxo/list.txt', async (req, res) => { app.get('/api/utxo/list.txt', async (req, res) => {
try { try {
@ -471,18 +510,66 @@ function formatBlockTime(seconds) {
// Route pour générer un hash SHA256 // Route pour générer un hash SHA256
app.post('/api/hash/generate', (req, res) => { app.post('/api/hash/generate', (req, res) => {
try { try {
const { text, fileContent } = req.body; const { text, fileContent, isBase64 } = req.body;
// Validation des paramètres
if (!text && !fileContent) { if (!text && !fileContent) {
return res.status(400).json({ error: 'text or fileContent is required' }); return res.status(400).json({ error: 'text or fileContent is required' });
} }
const content = text || fileContent; if (text && fileContent) {
const hash = crypto.createHash('sha256').update(content, 'utf8').digest('hex'); return res.status(400).json({ error: 'Cannot provide both text and fileContent' });
}
let hash;
if (text) {
// Pour le texte, utiliser UTF-8
if (typeof text !== 'string') {
return res.status(400).json({ error: 'text must be a string' });
}
hash = crypto.createHash('sha256').update(text, 'utf8').digest('hex');
} else if (fileContent) {
if (typeof fileContent !== 'string') {
return res.status(400).json({ error: 'fileContent must be a string' });
}
if (isBase64) {
// Pour les fichiers binaires, décoder le base64 et calculer le hash sur les bytes bruts
if (!fileContent || fileContent.trim().length === 0) {
return res.status(400).json({ error: 'fileContent cannot be empty' });
}
let buffer;
try {
buffer = Buffer.from(fileContent, 'base64');
} catch (error) {
logger.error('Error decoding base64', {
error: error.message,
fileContentLength: fileContent.length,
fileContentPreview: fileContent.substring(0, 100)
});
return res.status(400).json({ error: 'Invalid base64 data', message: error.message });
}
if (buffer.length === 0) {
return res.status(400).json({ error: 'Empty file content after base64 decoding' });
}
hash = crypto.createHash('sha256').update(buffer).digest('hex');
} else {
// Fallback pour compatibilité : traiter comme UTF-8 (pour fichiers texte)
hash = crypto.createHash('sha256').update(fileContent, 'utf8').digest('hex');
}
}
res.json({ hash }); res.json({ hash });
} catch (error) { } catch (error) {
logger.error('Error generating hash', { error: error.message }); logger.error('Error generating hash', {
error: error.message,
stack: error.stack,
bodyKeys: req.body ? Object.keys(req.body) : []
});
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}); });