- Inicio con cuatro tarjetas; glosario completo; Ayuda revisada según la tanda B1. - URL para el nodo; «Txoko» en vez de «el dashboard»; avisos de estado con nombres. - Mi nodo, La cadena e informe en castellano y con el vocabulario de referencia. - README al día. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
486 lines
32 KiB
React
486 lines
32 KiB
React
function Lab({base}) {
|
|
const {get,getStrict}=useApi(base);
|
|
const [query,setQuery]=useState("");
|
|
const [result,setResult]=useState(null);
|
|
const [analysis,setAnalysis]=useState(null);
|
|
const [loading,setLoading]=useState(false);
|
|
const [err,setErr]=useState(null);
|
|
useEffect(()=>{setAnalysis(analyzeTx(MOCK_TX));},[]);
|
|
const search=useCallback(async(q)=>{
|
|
q=(q||query).trim(); if(!q)return;
|
|
setResult(null);setAnalysis(null);setErr(null);
|
|
if(!clasificarBusqueda(q)){ setErr("No reconozco eso. Escribe un txid o hash de bloque (64 caracteres, 0-9 y a-f), una dirección Bitcoin (bc1…, 1…, 3…) o una altura de bloque (solo números)."); return; }
|
|
setLoading(true);
|
|
if(!base){
|
|
setTimeout(()=>{
|
|
if(/^[0-9a-f]{64}$/i.test(q)){setResult({type:"tx",data:MOCK_TX});setAnalysis(analyzeTx(MOCK_TX));}
|
|
else if(/^\d+$/.test(q)){setResult({type:"block",data:MOCK_BLOCKS[0]});}
|
|
else{const d={...MOCK_ADDRESS,address:q};setResult({type:"address",data:d});setAnalysis(analyzeAddress(d));}
|
|
setLoading(false);
|
|
},400); return;
|
|
}
|
|
try{
|
|
if(/^[0-9a-f]{64}$/i.test(q)){
|
|
// 64 caracteres: transacción o bloque. Solo se prueba como bloque si
|
|
// el nodo dice que no conoce la transacción (404); si no contesta,
|
|
// se dice eso, no «no encontrado» (revisión A-03).
|
|
let tx=null, fallo=null;
|
|
try{ tx=await getStrict(`/api/tx/${q}`); }catch(e){ fallo=e; }
|
|
if(tx){setResult({type:"tx",data:tx});setAnalysis(analyzeTx(tx));}
|
|
else if(fallo && !/HTTP 404/.test(fallo.message)){ throw new Error(mensajeTxNoLlega(fallo)); }
|
|
else { const block=await getStrict(`/api/block/${q}`); setResult({type:"block",data:block}); }
|
|
} else if(/^\d+$/.test(q)&&parseInt(q)<1000000){
|
|
// v1.48.1 (auditoría A5-05): si esa altura no existe (o el nodo no
|
|
// contesta) no se pide «/api/block/null»: se dice.
|
|
// Ojo: /block-height devuelve el hash en texto, no en JSON; leerlo
|
|
// como JSON fallaba siempre y la búsqueda por altura no funcionaba.
|
|
let hash=null;
|
|
try{ const r=await fetchWithTimeout(`${base}/api/block-height/${q}`); if(r.ok) hash=(await r.text()).trim(); else if(r.status!==404) throw new Error(`el nodo respondió HTTP ${r.status}`); }
|
|
catch(e){ throw new Error(`No se pudo consultar a tu nodo (${e.message}).`); }
|
|
if(typeof hash!=="string"||!/^[0-9a-f]{64}$/i.test(hash.trim())) throw new Error(`No hay ningún bloque a la altura ${q} (la cadena todavía no llega ahí).`);
|
|
const block=await getStrict(`/api/block/${hash.trim()}`);
|
|
setResult({type:"block",data:block});
|
|
} else {
|
|
// Las monedas sin gastar se piden en modo estricto: si /utxo falla
|
|
// (Mempool sobre Electrum puede dar 404), antes se mostraba
|
|
// «UTXOs 0» como si fuera un dato (revisión W-10). Ahora, si falla,
|
|
// se reconstruyen desde el historial cuando está completo, como ya
|
|
// hacía el mapa de UTXOs; si no, quedan como «no disponible».
|
|
if(RED.signet&&datoDeMainnet(`/address/${q}`)){ const e=new Error(MSG_MAINNET_EN_SIGNET); e.bloqueado=true; throw e; }
|
|
const [info,txs0,tip]=await Promise.all([get(`/api/address/${q}`,null),get(`/api/address/${q}/txs`,[]),get(`/api/blocks/tip/height`,null)]);
|
|
// v1.38.0: el resto del historial, página a página (10 por página
|
|
// sobre Fulcrum, 25 en Esplora), hasta HISTORIAL_FICHA_PAGINAS. Con
|
|
// todo el historial salen los totales y la ficha completa; si se
|
|
// corta, la ficha dice que es parcial. Un fallo a mitad no tumba la
|
|
// búsqueda: se queda con lo que llegó.
|
|
let txs=Array.isArray(txs0)?txs0:[];
|
|
const totalTx=(info?.chain_stats?.tx_count||0)+(info?.mempool_stats?.tx_count||0);
|
|
if(txs.length&&txs.length<totalTx){
|
|
const raiz=`/api/address/${q}`, primero=txs[0].txid, vistas=new Set(txs.map(t=>t.txid));
|
|
let ult=txs[txs.length-1].txid;
|
|
try{
|
|
for(let pag=0;pag<HISTORIAL_FICHA_PAGINAS&&vistas.size<totalTx;pag++){
|
|
const p=await paginaSiguiente(getStrict,raiz,ult,primero);
|
|
const nuevas=(Array.isArray(p)?p:[]).filter(t=>t&&t.txid&&!vistas.has(t.txid));
|
|
if(!nuevas.length) break;
|
|
nuevas.forEach(t=>{vistas.add(t.txid);txs.push(t);});
|
|
ult=nuevas[nuevas.length-1].txid;
|
|
}
|
|
}catch{}
|
|
}
|
|
let utxos=null, utxosOrigen=null;
|
|
try{ const u=await getStrict(`/api/address/${q}/utxo`); if(Array.isArray(u)){ utxos=u; utxosOrigen="nodo"; } }catch{}
|
|
if(!utxos){
|
|
const total=(info?.chain_stats?.tx_count||0)+(info?.mempool_stats?.tx_count||0);
|
|
if(Array.isArray(txs)&&txs.length>=total){
|
|
const gastadas=new Set(); txs.forEach(t=>(t.vin||[]).forEach(v=>{ if(v.txid) gastadas.add(`${v.txid}:${v.vout}`); }));
|
|
utxos=[]; txs.forEach(t=>(t.vout||[]).forEach((o,i)=>{ if(o.scriptpubkey_address===q&&!gastadas.has(`${t.txid}:${i}`)) utxos.push({txid:t.txid,vout:i,value:o.value,status:t.status}); }));
|
|
utxosOrigen="historial";
|
|
}
|
|
}
|
|
const addrData={...info,txs,utxos,utxosOrigen,tip:typeof tip==="number"?tip:(parseInt(tip)||null)}; setResult({type:"address",data:addrData}); setAnalysis(analyzeAddress(addrData));
|
|
}
|
|
}catch(e){setErr(e&&e.bloqueado ? "Esta dirección es de mainnet y estás en modo signet: no se ha enviado a ningún sitio. Para consultarla, cambia a Mainnet en ⚙ Ajustes." : /^No se pudo consultar/.test(e.message) ? e.message : /HTTP 404/.test(e.message) ? "No encontrado: tu nodo responde, pero no lo conoce." : /HTTP 5\d\d/.test(e.message) ? "Tu nodo ha respondido con un fallo interno. Prueba otra vez en un momento; si sigue, revisa en ⚙ Ajustes que el nodo responde." : `No se pudo consultar: ${e.message}`);}
|
|
setLoading(false);
|
|
},[query,base,get]);
|
|
|
|
return (
|
|
<div style={{display:"flex",flexDirection:"column",gap:12}}>
|
|
{!base&&<DemoBanner/>}
|
|
<SectionTitle accent={C.purple} icon="⌕">Explorar la cadena</SectionTitle>
|
|
<div style={{display:"flex",gap:8}}>
|
|
<input value={query} onChange={e=>setQuery(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&search()}
|
|
placeholder="txid · dirección · altura · block hash"
|
|
style={{flex:1,background:C.bgCard,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"11px 14px",color:C.t1,fontFamily:C.mono,fontSize:"0.78rem",outline:"none"}}
|
|
onFocus={e=>e.target.style.borderColor=C.purple} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
|
/>
|
|
<BotonQR campo="busqueda" onLeido={v=>setQuery(v)}/>
|
|
<button onClick={()=>search()} style={{padding:"11px 20px",background:C.purpleMuted,border:`1px solid ${C.purple}40`,borderRadius:6,color:C.purple,fontFamily:C.mono,fontSize:"0.75rem",cursor:"pointer",fontWeight:700}}>
|
|
{loading?"···":"BUSCAR"}
|
|
</button>
|
|
</div>
|
|
{err&&<div style={{padding:"10px 14px",background:C.redMuted,border:`1px solid ${C.red}30`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.75rem"}}>{err}</div>}
|
|
{loading&&<Spinner/>}
|
|
{!base&&!loading&&!err&&<EjemploAviso texto={result?undefined:"Sin nodo, esto es una transacción de ejemplo para que veas cómo se muestra."}/>}
|
|
{!base&&!loading&&!result&&(
|
|
<div style={{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"}}>
|
|
<button onClick={()=>{setQuery(MOCK_TX.txid);search(MOCK_TX.txid);}} style={{padding:"9px 14px",background:"none",border:`1px solid ${C.amber}70`,borderRadius:6,color:C.amber,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer"}}>Probar con una transacción de ejemplo</button>
|
|
<button onClick={()=>{setQuery(MOCK_ADDRESS.address);search(MOCK_ADDRESS.address);}} style={{padding:"9px 14px",background:"none",border:`1px solid ${C.amber}70`,borderRadius:6,color:C.amber,fontFamily:C.mono,fontSize:"0.7rem",cursor:"pointer"}}>…o con una dirección de ejemplo</button>
|
|
</div>
|
|
)}
|
|
{!result&&!base&&!loading&&!err&&<TxResult tx={MOCK_TX} onAnalyze={q=>{window.__setTab&&window.__setTab("auditoria",q);}}/>}
|
|
{result&&result.type==="tx"&&<TxResult tx={result.data} base={base} onAnalyze={q=>{window.__setTab&&window.__setTab("auditoria",q);}}/>}
|
|
{result&&result.type==="address"&&<AddressResult addr={result.data} analysis={analysis} base={base}/>}
|
|
{result&&result.type==="block"&&<BlockResult block={result.data}/>}
|
|
<UTXOMap base={base}/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function TxVerifier({base}) {
|
|
const {get,getStrict}=useApi(base);
|
|
const [txid,setTxid]=useState("");
|
|
const [result,setResult]=useState(null);
|
|
const [loading,setLoading]=useState(false);
|
|
const [err,setErr]=useState(null);
|
|
|
|
const verify=async()=>{
|
|
const q=txid.trim();
|
|
if(!q||!/^[0-9a-f]{64}$/i.test(q)){setErr("El txid son 64 letras y números (0-9 y a-f).");return;}
|
|
setLoading(true);setResult(null);setErr(null);
|
|
if(!base){ setResult({tx:{...MOCK_TX,txid:q},confs:MOCK_HEIGHT-MOCK_TX.status.block_height+1,height:MOCK_HEIGHT,ejemplo:true}); setLoading(false); return; }
|
|
try{
|
|
// v1.49.3 (auditoría B2): «No encontrada en el nodo: No encontrada».
|
|
// Se distingue que el nodo no la conozca de que no conteste.
|
|
let tx;
|
|
try{ tx=await getStrict(`/api/tx/${q}`); }
|
|
catch(e2){ const m=String(e2&&e2.message||""); throw new Error(/HTTP 4\d\d/.test(m)?"desconocida":m||"sin respuesta"); }
|
|
if(!tx)throw new Error("desconocida");
|
|
const height=await get("/api/blocks/tip/height",MOCK_HEIGHT);
|
|
const confs=tx.status?.confirmed?(height-tx.status.block_height+1):0;
|
|
setResult({tx,confs,height});
|
|
}catch(e){setErr(e.message==="desconocida"
|
|
? `Tu nodo no conoce esta transacción. Comprueba el txid y que es de esta red (${RED.signet?"signet":"mainnet"}); si se acaba de enviar, puede que aún no le haya llegado.`
|
|
: `No se pudo preguntar a tu nodo (${e.message}). Comprueba en ⚙ Ajustes que responde.`);}
|
|
setLoading(false);
|
|
};
|
|
|
|
const statusColor = result
|
|
? result.confs===0 ? C.amber : result.confs<6 ? C.blue : C.green
|
|
: C.t2;
|
|
const statusLabel = result
|
|
? result.confs===0 ? "SIN CONFIRMAR" : result.confs<6 ? `${result.confs} CONFIRMACI${result.confs===1?"ÓN":"ONES"}` : `${fmt.num(result.confs)} CONFIRMACIONES ✓`
|
|
: "";
|
|
|
|
return (
|
|
<Card style={{marginBottom:4}}>
|
|
<div style={{fontSize:"0.62rem",color:C.green,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.2em",marginBottom:12,display:"flex",alignItems:"center",gap:8}}>
|
|
<span>✓</span> Verificar transacción propia
|
|
<div style={{flex:1,height:1,background:`linear-gradient(to right,${C.green}40,transparent)`}}/>
|
|
</div>
|
|
<div style={{fontSize:"0.66rem",color:C.t2,marginBottom:10,lineHeight:1.5}}>Para comprobar que una transacción tuya ha llegado a la cadena: confirmaciones, bloque y comisión, preguntando solo a tu nodo.</div>
|
|
<div style={{display:"flex",gap:8,marginBottom:err||result?"10px":"0"}}>
|
|
<input value={txid} onChange={e=>setTxid(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&verify()}
|
|
placeholder="Pega aquí tu txid para verificar"
|
|
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
|
onFocus={e=>e.target.style.borderColor=C.green} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
|
/>
|
|
<BotonQR campo="txid" color={C.green} onLeido={v=>setTxid(v)}/>
|
|
<button onClick={verify} style={{padding:"9px 16px",background:C.greenMuted,border:`1px solid ${C.green}40`,borderRadius:6,color:C.green,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>
|
|
{loading?"···":"VERIFICAR"}
|
|
</button>
|
|
</div>
|
|
{err&&<div style={{padding:"8px 12px",background:C.redMuted,border:`1px solid ${C.red}30`,borderRadius:6,color:C.red,fontFamily:C.mono,fontSize:"0.72rem"}}>{err}</div>}
|
|
{result?.ejemplo&&<div style={{marginBottom:8}}><EjemploAviso/></div>}
|
|
{result&&(
|
|
<div style={{padding:"12px 14px",background:C.bg,borderRadius:6,border:`1px solid ${statusColor}40`}}>
|
|
<div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
|
|
<span style={{fontSize:"0.68rem",fontFamily:C.mono,color:C.t2,wordBreak:"break-all"}}><IdCopiable id={result.tx.txid} texto={fmt.hash(result.tx.txid)}/></span>
|
|
<Badge color={statusColor}>{statusLabel}</Badge>
|
|
</div>
|
|
<div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(120px,1fr))",gap:10}}>
|
|
<Tag label="Estado" value={result.confs===0?"Pendiente":"Confirmada"} color={statusColor}/>
|
|
<Tag label="Bloque" value={result.tx.status?.block_height!=null?`#${fmt.num(result.tx.status.block_height)}`:"mempool"} color={C.purple}/>
|
|
<Tag label="Comisión" value={fmtFee(comisionDe(result.tx))} color={C.amber}/>
|
|
<Tag label="Tarifa" value={fmtTasa(comisionDe(result.tx))} color={C.amber}/>
|
|
{comisionDe(result.tx).fee===0&&<div style={{gridColumn:"1 / -1",fontSize:"0.64rem",color:C.t2,lineHeight:1.5}}>{notaComisionCero(result.tx)}</div>}
|
|
<Tag label="Confirmado" value={result.tx.status?.block_time?fmt.date(result.tx.status.block_time):"-"} color={C.t1}/>
|
|
<Tag label="Tamaño" value={result.tx.weight?`${Math.ceil(result.tx.weight/4)} vB`:"-"} color={C.t1}/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
function UTXOMap({base}) {
|
|
const {get}=useApi(base);
|
|
const [addr,setAddr]=useState("");
|
|
const [utxos,setUtxos]=useState(null);
|
|
const [txCache,setTxCache]=useState({});
|
|
const [loading,setLoading]=useState(false);
|
|
const [err,setErr]=useState(null);
|
|
const MAX_UTXOS = 25; // límite para no estresar el nodo
|
|
|
|
const MOCK_UTXOS=[
|
|
{txid:"abc1def2abc1def2abc1def2abc1def2abc1def2abc1def2abc1def2abc1def2",vout:0,value:10000000,status:{confirmed:true,block_height:846089,block_time:1713000000}},
|
|
{txid:"123a456b123a456b123a456b123a456b123a456b123a456b123a456b123a456b",vout:1,value:4000000,status:{confirmed:true,block_height:846911,block_time:1713200000}},
|
|
{txid:"789c012d789c012d789c012d789c012d789c012d789c012d789c012d789c012d",vout:0,value:823000,status:{confirmed:false}},
|
|
{txid:"aabbccddaabbccddaabbccddaabbccddaabbccddaabbccddaabbccddaabbccdd",vout:2,value:50000000,status:{confirmed:true,block_height:840000,block_time:1710000000}},
|
|
{txid:"11223344112233441122334411223344112233441122334411223344aabbcc11",vout:0,value:1500000,status:{confirmed:true,block_height:950000,block_time:1716000000}},
|
|
];
|
|
|
|
// Calcular score de privacidad por UTXO
|
|
// Privacidad de una moneda. Desde la v1.27 sale del MISMO análisis que
|
|
// la vista de transacción: la nota es la de la transacción que la creó
|
|
// (analyzeTx), con sus cortes 85/55. Antes el mapa tenía reglas propias
|
|
// que contradecían al analizador: restaba por RBF (que allí es
|
|
// informativo), por lote (que allí es «lo que hicieron otros»), por
|
|
// valer más de 0,1 BTC (que allí no existe), usaba un umbral de polvo
|
|
// fijo y el CoinJoin con Math.floor (revisión H-18). Lo propio de la
|
|
// moneda —que sea polvo, que esté sin confirmar— se añade aparte.
|
|
const getUtxoPrivacy = (utxo, originTx) => {
|
|
const issues = [];
|
|
if (!utxo.status?.confirmed) issues.push({ label:"Sin confirmar", color:C.t2 });
|
|
if (!originTx) {
|
|
// Solo se traen las transacciones de origen de las 10 monedas más
|
|
// grandes: sin ella no hay análisis, y un 100 por defecto mentiría.
|
|
return { score:null, issues:[...issues, { label:"Sin analizar (no se trajo su transacción de origen)", color:C.t2 }], color:C.t2 };
|
|
}
|
|
let a = null;
|
|
try { a = analyzeTx(originTx); } catch {}
|
|
if (!a) return { score:null, issues:[...issues, { label:"No se pudo analizar su transacción de origen", color:C.t2 }], color:C.t2 };
|
|
let score = a.score;
|
|
const fallidos = a.checks.filter(c => !c.pass && !c.informational && !c.heredado);
|
|
for (const c of fallidos.slice(0, 3)) issues.push({ label:`Al crearse: ${c.label}`, color: C.amber });
|
|
if (a.checks.find(c => c.id === "coinjoin")?.pass) issues.push({ label:"Al crearse: CoinJoin", color:C.green });
|
|
if (a.exposicion?.puntos > 0) issues.push({ label:"Al crearse: lo que decidieron otros (no resta)", color:C.t2 });
|
|
// Polvo, con los mismos umbrales por tipo de salida que el analizador.
|
|
const tipo = originTx.vout?.[utxo.vout]?.scriptpubkey_type || "";
|
|
const umbral = tipo.includes("p2tr") || tipo.includes("v1") ? 330 : tipo.includes("p2wpkh") ? 294 : tipo.includes("p2wsh") ? 330 : 546;
|
|
if (utxo.value > 0 && utxo.value < umbral) {
|
|
issues.push({ label:"Polvo: si se gasta junto a otras monedas, las vincula", color:C.red });
|
|
score = Math.min(score, BANDA_MEDIA - 1);
|
|
}
|
|
const band = score >= BANDA_ALTA && a.band === "ALTA" ? "ALTA" : score >= BANDA_MEDIA ? "MEDIA" : "BAJA";
|
|
const color = band === "ALTA" ? C.green : band === "MEDIA" ? C.amber : C.red;
|
|
return { score, band, issues, color };
|
|
};
|
|
|
|
// Detectar patrones temporales del conjunto de UTXOs
|
|
const getTemporalPattern = (utxoList) => {
|
|
const times = utxoList
|
|
.filter(u=>u.status?.block_time)
|
|
.map(u=>new Date(u.status.block_time*1000).getUTCHours());
|
|
if (times.length < 3) return null;
|
|
const avg = times.reduce((a,b)=>a+b,0)/times.length;
|
|
const zone = avg>=6&&avg<=10?"mañana europea (6-10 UTC)":
|
|
avg>=14&&avg<=18?"tarde europea / mañana americana (14-18 UTC)":
|
|
avg>=22||avg<=2?"madrugada Europa / tarde América":null;
|
|
return zone ? `Patrón horario detectado: la mayoría de transacciones ocurren en ${zone}.` : null;
|
|
};
|
|
|
|
const fetchUtxos=async()=>{
|
|
const q=addr.trim();
|
|
if(!q){setErr("Introduce una dirección Bitcoin");return;}
|
|
setLoading(true);setUtxos(null);setErr(null);setTxCache({});
|
|
try{
|
|
if(!base){
|
|
setTimeout(()=>{setUtxos(MOCK_UTXOS);setLoading(false);},400); return;
|
|
}
|
|
|
|
// Obtener UTXOs
|
|
let data=null;
|
|
try{
|
|
const res=await fetchWithTimeout(`${base}/api/address/${q}/utxo`);
|
|
if(res.ok){ const json=await res.json(); if(Array.isArray(json)&&json.length>0) data=json; }
|
|
}catch{}
|
|
|
|
if(!data){
|
|
const txRes=await fetchWithTimeout(`${base}/api/v1/address/${q}/txs`);
|
|
if(!txRes.ok) throw new Error(`HTTP ${txRes.status}`);
|
|
const txs=await txRes.json();
|
|
const spentTxids=new Set();
|
|
txs.forEach(tx=>tx.vin.forEach(v=>{ if(v.txid) spentTxids.add(`${v.txid}:${v.vout}`); }));
|
|
const outputs=[];
|
|
txs.forEach(tx=>{
|
|
tx.vout.forEach((out,i)=>{
|
|
if(out.scriptpubkey_address===q&&!spentTxids.has(`${tx.txid}:${i}`)){
|
|
outputs.push({txid:tx.txid,vout:i,value:out.value,status:tx.status});
|
|
}
|
|
});
|
|
});
|
|
data=outputs;
|
|
}
|
|
|
|
if(!data||data.length===0){
|
|
setErr("No se encontraron UTXOs para esta dirección — puede que todos estén gastados");
|
|
setLoading(false);return;
|
|
}
|
|
|
|
const sorted=[...data].sort((a,b)=>b.value-a.value);
|
|
const limited=sorted.slice(0,MAX_UTXOS);
|
|
if(sorted.length>MAX_UTXOS) setErr(`Mostrando ${MAX_UTXOS} de ${sorted.length} UTXOs — se muestran los de mayor valor.`);
|
|
|
|
// Cargar txs de origen para contexto (máx 10, las más grandes)
|
|
// Vía get() y no fetch directo: así pasa por la caché compartida.
|
|
// Las transacciones confirmadas son inmutables y se guardan toda la
|
|
// sesión, de modo que volver a este UTXO Map (o analizar una de estas
|
|
// txs en otra pestaña) no cuesta ni una petición más al nodo.
|
|
const cache={};
|
|
const toFetch=limited.slice(0,10);
|
|
await Promise.all(toFetch.map(async u=>{
|
|
const t = await get(`/api/tx/${u.txid}`, null);
|
|
if (t) cache[u.txid] = t;
|
|
}));
|
|
|
|
setTxCache(cache);
|
|
setUtxos(limited);
|
|
}catch(e){ const msg = e.name==="AbortError" ? "El nodo tardó demasiado en responder (timeout). Puede estar ocupado — inténtalo de nuevo en un momento." : `Error: ${e.message}`; setErr(msg); }
|
|
setLoading(false);
|
|
};
|
|
|
|
const totalBtc = utxos ? utxos.reduce((s,u)=>s+u.value,0) : 0;
|
|
const maxVal = utxos ? Math.max(...utxos.map(u=>u.value)) : 1;
|
|
const temporalPattern = utxos ? getTemporalPattern(utxos) : null;
|
|
const privacyScores = utxos ? utxos.map(u=>getUtxoPrivacy(u,txCache[u.txid])) : [];
|
|
// Promedio solo de las monedas analizadas. Se llama «promedio» y no
|
|
// «media» para no confundirlo con la banda MEDIA (revisión UX-06).
|
|
const conNota = privacyScores.filter(p => typeof p.score === "number");
|
|
const avgPrivacy = conNota.length>0
|
|
? Math.round(conNota.reduce((s,p)=>s+p.score,0)/conNota.length) : null;
|
|
|
|
// ── Exportar UTXOs a CSV ──────────────────────────────────────────
|
|
// Genera el archivo en el navegador y lo descarga en local.
|
|
// No pasa por ningún servidor, no sale nada del nodo.
|
|
const exportUtxosCSV = () => {
|
|
if(!utxos || utxos.length===0) return;
|
|
// Escapar campos: si llevan coma, comilla o salto, van entre comillas
|
|
const esc = (val) => {
|
|
const s = String(val ?? "");
|
|
return /[",\n]/.test(s) ? '"' + s.replace(/"/g,'""') + '"' : s;
|
|
};
|
|
const cabeceras = ["txid","vout","valor_sats","valor_btc","confirmado","altura_bloque","nota_privacidad","señales"];
|
|
const filas = utxos.map((u,i) => {
|
|
const priv = privacyScores[i] || {score:"", issues:[]};
|
|
return [
|
|
u.txid,
|
|
u.vout,
|
|
u.value,
|
|
(u.value/1e8).toFixed(8),
|
|
u.status?.confirmed ? "si" : "no",
|
|
u.status?.confirmed ? (u.status.block_height ?? "") : "sin confirmar",
|
|
priv.score,
|
|
(priv.issues || []).map(x => x.label || x).join("; "),
|
|
].map(esc).join(",");
|
|
});
|
|
const csv = [cabeceras.join(","), ...filas].join("\n");
|
|
// BOM para que Excel abra los acentos bien + descarga vía Blob
|
|
const blob = new Blob(["\uFEFF" + csv], {type:"text/csv;charset=utf-8"});
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement("a");
|
|
const fecha = new Date().toISOString().slice(0,10);
|
|
const addrCorto = (addr || "utxos").slice(0,12);
|
|
a.href = url;
|
|
a.download = `txoko-utxos-${addrCorto}-${fecha}.csv`;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
};
|
|
|
|
return(
|
|
<Card>
|
|
<div style={{fontSize:"0.62rem",color:C.purple,fontFamily:C.mono,textTransform:"uppercase",letterSpacing:"0.2em",marginBottom:8,display:"flex",alignItems:"center",gap:8}}>
|
|
<span>◎</span> Mapa de UTXOs
|
|
<div style={{flex:1,height:1,background:`linear-gradient(to right,${C.purple}40,transparent)`}}/>
|
|
{utxos&&utxos.length>0&&(
|
|
<button onClick={exportUtxosCSV} title="Descargar los UTXOs en CSV (local, no sale del nodo)"
|
|
style={{padding:"4px 10px",background:C.bg,border:`1px solid ${C.purple}40`,borderRadius:5,color:C.purple,fontFamily:C.mono,fontSize:"0.6rem",letterSpacing:"0.08em",cursor:"pointer",whiteSpace:"nowrap"}}
|
|
onMouseEnter={e=>e.currentTarget.style.borderColor=C.purple}
|
|
onMouseLeave={e=>e.currentTarget.style.borderColor=C.purple+"40"}>
|
|
↓ CSV
|
|
</button>
|
|
)}
|
|
</div>
|
|
<div style={{fontSize:"0.65rem",color:C.t2,marginBottom:12,lineHeight:1.5}}>
|
|
Las monedas sin gastar de una dirección (UTXOs), cada una con la banda de privacidad (alta, media o baja) de la transacción que la creó. Si la moneda la recibiste, esa banda refleja lo que hizo quien te pagó. Hasta {MAX_UTXOS} monedas; se analizan las 10 mayores, para no cargar tu nodo.
|
|
</div>
|
|
<div style={{display:"flex",gap:8,marginBottom:10}}>
|
|
<input value={addr} onChange={e=>setAddr(filtrarSecreto(e.target.value))} onKeyDown={e=>e.key==="Enter"&&fetchUtxos()}
|
|
placeholder="Dirección Bitcoin (bc1q..., bc1p..., 1..., 3...)"
|
|
style={{flex:1,background:C.bg,border:`1px solid ${C.borderBright}`,borderRadius:6,padding:"9px 12px",color:C.t1,fontFamily:C.mono,fontSize:"0.75rem",outline:"none"}}
|
|
onFocus={e=>e.target.style.borderColor=C.purple} onBlur={e=>e.target.style.borderColor=C.borderBright}
|
|
/>
|
|
<BotonQR campo="direccion" onLeido={v=>setAddr(v)}/>
|
|
<button onClick={fetchUtxos} style={{padding:"9px 16px",background:C.purpleMuted,border:`1px solid ${C.purple}40`,borderRadius:6,color:C.purple,fontFamily:C.mono,fontSize:"0.72rem",cursor:"pointer",fontWeight:700}}>
|
|
{loading?"···":"VER MONEDAS"}
|
|
</button>
|
|
</div>
|
|
{err&&<div style={{padding:"8px 12px",background:C.amberMuted,border:`1px solid ${C.amber}30`,borderRadius:6,color:C.amber,fontFamily:C.mono,fontSize:"0.72rem",marginBottom:8}}>{err}</div>}
|
|
{loading&&<Spinner/>}
|
|
{utxos&&utxos.length>0&&(
|
|
<div style={{display:"flex",flexDirection:"column",gap:10}}>
|
|
{/* Summary */}
|
|
<div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(120px,1fr))",gap:8,padding:"10px 14px",background:C.bg,borderRadius:6,border:`1px solid ${C.border}`}}>
|
|
<Tag label="Monedas sin gastar" value={utxos.length} color={C.purple}/>
|
|
<Tag label="Saldo" value={fmt.sbtc(totalBtc)} color={C.green}/>
|
|
<Tag label="Sin confirmar" value={utxos.filter(u=>!u.status?.confirmed).length} color={C.amber}/>
|
|
{avgPrivacy!==null&&<Tag label={`Banda media (${conNota.length} de ${privacyScores.length} analizadas)`} value={avgPrivacy>=BANDA_ALTA?"ALTA":avgPrivacy>=BANDA_MEDIA?"MEDIA":"BAJA"} color={avgPrivacy>=BANDA_ALTA?C.green:avgPrivacy>=BANDA_MEDIA?C.amber:C.red}/>}
|
|
</div>
|
|
|
|
{/* Patrón temporal */}
|
|
{temporalPattern&&(
|
|
<div style={{padding:"8px 12px",background:C.purpleMuted,border:`1px solid ${C.purple}30`,borderRadius:6,fontSize:"0.65rem",color:C.t1,lineHeight:1.6}}>
|
|
<span style={{color:C.purple,fontFamily:C.mono,fontWeight:700}}>⏱ </span>{temporalPattern}
|
|
</div>
|
|
)}
|
|
|
|
{/* UTXO list */}
|
|
<div style={{display:"flex",flexDirection:"column",gap:8}}>
|
|
{utxos.map((u,i)=>{
|
|
const priv=privacyScores[i]||{score:null,issues:[],color:C.t2};
|
|
const pct=Math.max(4,(u.value/maxVal)*100);
|
|
const sharePct=fmtDec((u.value/totalBtc)*100, 1);
|
|
return(
|
|
<div key={i} style={{background:C.bg,borderRadius:8,border:`1px solid ${C.border}`,padding:"12px 14px",transition:"border-color 0.15s"}}
|
|
onMouseEnter={e=>e.currentTarget.style.borderColor=priv.color+"60"}
|
|
onMouseLeave={e=>e.currentTarget.style.borderColor=C.border}
|
|
>
|
|
{/* Top row */}
|
|
<div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6}}>
|
|
<div style={{display:"flex",alignItems:"center",gap:8}}>
|
|
<div style={{width:8,height:8,borderRadius:"50%",background:priv.color,boxShadow:`0 0 6px ${priv.color}`,flexShrink:0}}/>
|
|
<span style={{fontSize:"0.68rem",fontFamily:C.mono,color:C.t2,display:"inline-flex",alignItems:"center",gap:6,flexWrap:"wrap"}}><IdCopiable id={u.txid} texto={fmt.hash(u.txid)}/> · salida {u.vout}</span>
|
|
</div>
|
|
<div style={{display:"flex",alignItems:"center",gap:8}}>
|
|
<span style={{fontSize:"0.7rem",fontFamily:C.mono,color:priv.color,fontWeight:700}}>{typeof priv.score==="number"?(priv.band||(priv.score>=BANDA_ALTA?"ALTA":priv.score>=BANDA_MEDIA?"MEDIA":"BAJA")):"sin analizar"}</span>
|
|
<span style={{fontSize:"0.62rem",color:C.t2,fontFamily:C.mono}}>{sharePct}%</span>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Bar */}
|
|
<div style={{height:5,background:C.border,borderRadius:3,overflow:"hidden",marginBottom:8}}>
|
|
<div style={{width:`${pct}%`,height:"100%",background:`linear-gradient(to right,${priv.color}80,${priv.color})`,borderRadius:3}}/>
|
|
</div>
|
|
|
|
{/* Value + block */}
|
|
<div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom: priv.issues.length>0?6:0}}>
|
|
<span style={{fontSize:"0.88rem",color:priv.color,fontFamily:C.mono,fontWeight:700}}>{fmt.btc(u.value)}</span>
|
|
<span style={{fontSize:"0.62rem",color:C.t2,fontFamily:C.mono}}>
|
|
{u.status?.confirmed?`bloque #${fmt.num(u.status.block_height)}`:"sin confirmar"}
|
|
</span>
|
|
</div>
|
|
|
|
{/* Issues */}
|
|
{priv.issues.length>0&&(
|
|
<div style={{display:"flex",flexWrap:"wrap",gap:4,marginTop:4}}>
|
|
{priv.issues.map((issue,j)=>(
|
|
<span key={j} style={{fontSize:"0.58rem",fontFamily:C.mono,padding:"2px 6px",borderRadius:3,
|
|
background:"transparent",color:issue.color,border:`1px solid ${issue.color}40`}}>
|
|
{issue.label}
|
|
</span>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{/* Legend */}
|
|
<div style={{display:"flex",gap:16,flexWrap:"wrap",paddingTop:4}}>
|
|
{[{color:C.green,label:"Banda alta"},{color:C.amber,label:"Banda media"},{color:C.red,label:"Banda baja"}].map(l=>(
|
|
<div key={l.label} style={{display:"flex",alignItems:"center",gap:5}}>
|
|
<div style={{width:7,height:7,borderRadius:"50%",background:l.color,flexShrink:0}}/>
|
|
<span style={{fontSize:"0.62rem",color:C.t2,fontFamily:C.mono}}>{l.label}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</Card>
|
|
);
|
|
}
|
|
|