Files
system-docs/05_INTEGRACIONES/notario.md
ARCHITECT 6ea70bd34f Update to Skynet v7 - Complete documentation restructure
- Nueva estructura de carpetas según Skynet v7
- Añadidos schemas SQL completos
- Documentación de entidades, componentes e integraciones
- Modelo de seguridad actualizado
- Infraestructura y operaciones reorganizadas
2025-12-29 18:23:41 +00:00

251 lines
7.2 KiB
Markdown

# Notario
**Versión:** 2.0
**Estado:** Especificación
---
## Descripción
Sistema de sellado inmutable en blockchain. Última capa de confianza del ecosistema.
```
┌─────────────────────────────────────────────────────────────────┐
│ PRINCIPIO NOTARIO │
│ │
│ "Lo que NOTARIO sella, nadie lo altera" │
└─────────────────────────────────────────────────────────────────┘
```
---
## Arquitectura
```
┌─────────────────────────────────────────────────────────────────┐
│ NOTARIO │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Feldman (bloques consolidados) │
│ │ │
│ │ (auditados por SENTINEL) │
│ ▼ │
│ ┌─────────────────┐ │
│ │ BATCH COLLECTOR │ Agrupa por ventana temporal │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ MERKLE BUILDER │ Construye árbol Merkle │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ BLOCKCHAIN TX │ Publica hash raíz │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ Registro actualizado con blockchain_tx_ref │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## Dos Franjas Temporales
### Franja Interna
Tiempo del sistema para:
- Procesar operaciones
- Ejecutar auditoría SENTINEL
- Consolidar en Feldman
**Duración:** Minutos a horas
### Franja Blockchain
Tiempo de NOTARIO para:
- Agrupar registros en batches
- Construir pruebas criptográficas
- Publicar en blockchain
- Confirmar transacciones
**Duración:** Horas a días
---
## Ciclo de Sellado
```
1. RECOLECTAR
SELECT FROM feldman_bloques
WHERE audit_status = 'DEEP_PASS'
AND blockchain_tx_ref IS NULL
2. AGRUPAR
Crear batch con ventana temporal (ej: 24h)
Asignar notario_batch_id
3. CONSTRUIR MERKLE
- Ordenar registros por h_bloque
- Calcular hash de cada registro
- Construir árbol binario
- Obtener merkle_root
4. FIRMAR
- Firmar merkle_root con llave NOTARIO
- Generar timestamp certificado
5. PUBLICAR
- Enviar transacción a blockchain
- Esperar confirmaciones
6. ACTUALIZAR
UPDATE feldman_bloques SET blockchain_tx_ref = tx_hash
```
---
## Schema SQL
```sql
CREATE TABLE notario_batches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
batch_id UUID UNIQUE NOT NULL,
-- Ventana temporal
window_start TIMESTAMPTZ NOT NULL,
window_end TIMESTAMPTZ NOT NULL,
-- Contenido
records_count INTEGER NOT NULL,
bloque_hashes TEXT[] NOT NULL,
-- Merkle
merkle_root CHAR(64) NOT NULL,
merkle_tree JSONB,
-- Firma
signature TEXT NOT NULL,
signing_key_id VARCHAR(100),
signed_at TIMESTAMPTZ NOT NULL,
-- Blockchain
blockchain_network VARCHAR(50) DEFAULT 'ethereum',
blockchain_tx_ref VARCHAR(100),
blockchain_block BIGINT,
blockchain_timestamp TIMESTAMPTZ,
confirmations INTEGER DEFAULT 0,
-- Estado
status VARCHAR(20) DEFAULT 'PENDING',
created_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT valid_status CHECK (
status IN ('PENDING', 'SUBMITTED', 'CONFIRMED', 'FAILED')
)
);
CREATE INDEX idx_notario_status ON notario_batches(status);
CREATE INDEX idx_notario_window ON notario_batches(window_start, window_end);
```
---
## Verificación de Integridad
```python
def verify_record_integrity(h_bloque, notario_batch_id):
# 1. Obtener batch
batch = get_batch(notario_batch_id)
# 2. Verificar que h_bloque está en el batch
assert h_bloque in batch.bloque_hashes
# 3. Obtener registro de Feldman
record = get_feldman_record(h_bloque)
# 4. Calcular hash del registro
record_hash = sha256(serialize(record))
# 5. Verificar inclusión en merkle tree
proof = get_merkle_proof(batch.merkle_tree, h_bloque)
assert verify_merkle_proof(record_hash, proof, batch.merkle_root)
# 6. Verificar firma del batch
assert verify_signature(
batch.merkle_root,
batch.signature,
batch.signing_key_id
)
# 7. Verificar que merkle_root está en blockchain
tx = get_blockchain_tx(batch.blockchain_tx_ref)
assert tx.data == batch.merkle_root
return True
```
---
## Integración con S-CONTRACT
### Campos en Response (pre-sellado)
```json
"audit": {
"blockchain_pending": true,
"blockchain_tx_ref": null,
"notario_batch_id": "uuid-batch"
}
```
### Campos post-sellado
```json
"audit": {
"blockchain_pending": false,
"blockchain_tx_ref": "0x1234...abcd",
"notario_batch_id": "uuid-batch"
}
```
---
## Configuración
```yaml
notario:
enabled: true
# Ventana de agregación
batch_window_hours: 24
min_records_per_batch: 10
max_records_per_batch: 10000
# Blockchain
network: ethereum
contract_address: "0x..."
gas_limit: 100000
# Firma
signing_key: kv://production/signing/notario
# Reintentos
max_retries: 3
retry_delay_minutes: 60
```
---
## Pendiente
- [ ] Crear tabla notario_batches
- [ ] Implementar recolector de registros
- [ ] Implementar constructor Merkle tree
- [ ] Configurar llave de firma
- [ ] Integrar con proveedor blockchain
- [ ] Implementar verificador de integridad
- [ ] Crear workflow de sellado periódico