Compare commits
8 Commits
7ea4ef1920
...
bbb0c12506
| Author | SHA1 | Date | |
|---|---|---|---|
| bbb0c12506 | |||
| 614569f5aa | |||
| 465a4a3c18 | |||
| dddbe04a2d | |||
| f78ed88cb1 | |||
| 696fc5833c | |||
| 059f3e2e33 | |||
| 9d30e84bd2 |
385
WORKFLOW_PAIRING_ANALYSIS.md
Normal file
385
WORKFLOW_PAIRING_ANALYSIS.md
Normal file
@ -0,0 +1,385 @@
|
||||
# Analyse du Workflow de Pairing - Processus de Couplage d'Appareils
|
||||
|
||||
## Introduction
|
||||
|
||||
Ce document présente une analyse complète du workflow de pairing (processus de couplage) dans l'écosystème 4NK, qui permet à deux appareils de s'associer de manière sécurisée. Le processus implique à la fois le code TypeScript côté client (`ihm_client_dev2`) et les fonctionnalités WebAssembly compilées depuis Rust (`sdk_client`).
|
||||
|
||||
## Vue d'ensemble du Processus
|
||||
|
||||
Le workflow de pairing est déclenché par la fonction `onCreateButtonClick()` et suit une séquence d'actions coordonnées entre l'interface utilisateur, les services JavaScript et le module WebAssembly.
|
||||
|
||||
## Étapes Détaillées du Workflow
|
||||
|
||||
### 1. Déclenchement Initial
|
||||
|
||||
**Fonction :** `onCreateButtonClick()`
|
||||
**Localisation :** `src/utils/sp-address.utils.ts:152-160`
|
||||
|
||||
```@/home/ank/dev/ihm_client_dev2/src/utils/sp-address.utils.ts#152:160
|
||||
async function onCreateButtonClick() {
|
||||
try {
|
||||
await prepareAndSendPairingTx();
|
||||
// Don't call confirmPairing immediately - it will be called when the pairing process is complete
|
||||
console.log('Pairing process initiated. Waiting for completion...');
|
||||
} catch (e) {
|
||||
console.error(`onCreateButtonClick error: ${e}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Actions :**
|
||||
- Appel de `prepareAndSendPairingTx()`
|
||||
- Gestion d'erreur avec logging
|
||||
- Attente de la complétion du processus
|
||||
|
||||
### 2. Préparation et Envoi de la Transaction de Pairing
|
||||
|
||||
**Fonction :** `prepareAndSendPairingTx()`
|
||||
**Localisation :** `src/utils/sp-address.utils.ts:162-201`
|
||||
|
||||
**Actions principales :**
|
||||
|
||||
#### 2.1 Initialisation du Service
|
||||
```typescript
|
||||
const service = await Services.getInstance();
|
||||
const relayAddress = service.getAllRelays();
|
||||
```
|
||||
|
||||
#### 2.2 Création du Processus de Pairing
|
||||
```typescript
|
||||
const createPairingProcessReturn = await service.createPairingProcess("", []);
|
||||
```
|
||||
|
||||
#### 2.3 Vérification des Connexions
|
||||
```typescript
|
||||
await service.checkConnections(
|
||||
createPairingProcessReturn.updated_process.current_process,
|
||||
createPairingProcessReturn.updated_process.current_process.states[0].state_id
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.4 Configuration des Identifiants
|
||||
```typescript
|
||||
service.setProcessId(createPairingProcessReturn.updated_process.process_id);
|
||||
service.setStateId(createPairingProcessReturn.updated_process.current_process.states[0].state_id);
|
||||
```
|
||||
|
||||
#### 2.5 Mise à Jour du Device
|
||||
```typescript
|
||||
const currentDevice = await service.getDeviceFromDatabase();
|
||||
if (currentDevice) {
|
||||
currentDevice.pairing_process_commitment = createPairingProcessReturn.updated_process.process_id;
|
||||
await service.saveDeviceInDatabase(currentDevice);
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.6 Traitement du Retour API
|
||||
```typescript
|
||||
await service.handleApiReturn(createPairingProcessReturn);
|
||||
```
|
||||
|
||||
### 3. Création du Processus de Pairing (Côté Service)
|
||||
|
||||
**Fonction :** `createPairingProcess()`
|
||||
**Localisation :** `src/services/service.ts:334-371`
|
||||
|
||||
**Paramètres :**
|
||||
- `userName`: Nom d'utilisateur (vide dans ce cas)
|
||||
- `pairWith`: Liste des adresses à coupler (vide initialement)
|
||||
|
||||
**Actions :**
|
||||
|
||||
#### 3.1 Vérification de l'État de Pairing
|
||||
```typescript
|
||||
if (this.sdkClient.is_paired()) {
|
||||
throw new Error('Device already paired');
|
||||
}
|
||||
```
|
||||
|
||||
#### 3.2 Préparation des Données
|
||||
```typescript
|
||||
const myAddress: string = this.sdkClient.get_address();
|
||||
pairWith.push(myAddress);
|
||||
|
||||
const privateData = {
|
||||
description: 'pairing',
|
||||
counter: 0,
|
||||
};
|
||||
|
||||
const publicData = {
|
||||
memberPublicName: userName,
|
||||
pairedAddresses: pairWith,
|
||||
};
|
||||
```
|
||||
|
||||
#### 3.3 Définition des Rôles
|
||||
```typescript
|
||||
const roles: Record<string, RoleDefinition> = {
|
||||
pairing: {
|
||||
members: [],
|
||||
validation_rules: [{
|
||||
quorum: 1.0,
|
||||
fields: validation_fields,
|
||||
min_sig_member: 1.0,
|
||||
}],
|
||||
storages: [STORAGEURL]
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
#### 3.4 Appel de Création du Processus
|
||||
```typescript
|
||||
return this.createProcess(privateData, publicData, roles);
|
||||
```
|
||||
|
||||
### 4. Création du Processus (Côté WebAssembly)
|
||||
|
||||
**Fonction :** `create_new_process()`
|
||||
**Localisation :** `sdk_client/src/api.rs:1218-1264`
|
||||
|
||||
**Actions principales :**
|
||||
|
||||
#### 4.1 Validation des Rôles
|
||||
```rust
|
||||
if roles.is_empty() {
|
||||
return Err(ApiError { message: "Roles can't be empty".to_owned() });
|
||||
}
|
||||
```
|
||||
|
||||
#### 4.2 Création de la Transaction
|
||||
```rust
|
||||
let relay_address: SilentPaymentAddress = relay_address.try_into()?;
|
||||
let tx = create_transaction_for_addresses(&local_device, &freezed_utxos, &vec![relay_address], fee_rate_checked)?;
|
||||
let unsigned_transaction = SpClient::finalize_transaction(tx)?;
|
||||
```
|
||||
|
||||
#### 4.3 Gestion des Secrets Partagés
|
||||
```rust
|
||||
let new_secrets = get_shared_secrets_in_transaction(&unsigned_transaction, &vec![relay_address])?;
|
||||
let mut shared_secrets = lock_shared_secrets()?;
|
||||
for (address, secret) in new_secrets {
|
||||
shared_secrets.confirm_secret_for_address(secret, address);
|
||||
}
|
||||
```
|
||||
|
||||
#### 4.4 Création de l'État du Processus
|
||||
```rust
|
||||
let process_id = OutPoint::new(unsigned_transaction.unsigned_tx.as_ref().unwrap().txid(), 0);
|
||||
let mut new_state = ProcessState::new(process_id, private_data.clone(), public_data.clone(), roles.clone())?;
|
||||
let mut process = Process::new(process_id);
|
||||
```
|
||||
|
||||
### 5. Vérification des Connexions
|
||||
|
||||
**Fonction :** `checkConnections()`
|
||||
**Localisation :** `src/services/service.ts:232-289`
|
||||
|
||||
**Actions :**
|
||||
|
||||
#### 5.1 Validation des États
|
||||
```typescript
|
||||
if (process.states.length < 2) {
|
||||
throw new Error('Process doesn\'t have any state yet');
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.2 Extraction des Rôles et Membres
|
||||
```typescript
|
||||
let roles: Record<string, RoleDefinition> | null = null;
|
||||
if (!stateId) {
|
||||
roles = process.states[process.states.length - 2].roles;
|
||||
} else {
|
||||
roles = process.states.find(state => state.state_id === stateId)?.roles || null;
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.3 Gestion des Processus de Pairing
|
||||
```typescript
|
||||
if (members.size === 0) {
|
||||
// This must be a pairing process
|
||||
const publicData = process.states[0]?.public_data;
|
||||
if (!publicData || !publicData['pairedAddresses']) {
|
||||
throw new Error('Not a pairing process');
|
||||
}
|
||||
const decodedAddresses = this.decodeValue(publicData['pairedAddresses']);
|
||||
members.add({ sp_addresses: decodedAddresses });
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.4 Connexion aux Adresses Non Connectées
|
||||
```typescript
|
||||
if (unconnectedAddresses && unconnectedAddresses.size != 0) {
|
||||
const apiResult = await this.connectAddresses(Array.from(unconnectedAddresses));
|
||||
await this.handleApiReturn(apiResult);
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Traitement du Retour API
|
||||
|
||||
**Fonction :** `handleApiReturn()`
|
||||
**Localisation :** `src/services/service.ts:648-775`
|
||||
|
||||
**Actions principales :**
|
||||
|
||||
#### 6.1 Signature de Transaction
|
||||
```typescript
|
||||
if (apiReturn.partial_tx) {
|
||||
const res = this.sdkClient.sign_transaction(apiReturn.partial_tx);
|
||||
apiReturn.new_tx_to_send = res.new_tx_to_send;
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.2 Envoi de Transaction
|
||||
```typescript
|
||||
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
||||
this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.3 Gestion des Secrets
|
||||
```typescript
|
||||
if (apiReturn.secrets) {
|
||||
const unconfirmedSecrets = apiReturn.secrets.unconfirmed_secrets;
|
||||
const confirmedSecrets = apiReturn.secrets.shared_secrets;
|
||||
// Sauvegarde en base de données
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.4 Mise à Jour du Processus
|
||||
```typescript
|
||||
if (apiReturn.updated_process) {
|
||||
const updatedProcess = apiReturn.updated_process;
|
||||
const processId: string = updatedProcess.process_id;
|
||||
await this.saveProcessToDb(processId, updatedProcess.current_process);
|
||||
}
|
||||
```
|
||||
|
||||
#### 6.5 Confirmation Automatique du Pairing
|
||||
```typescript
|
||||
// Check if this is a pairing process that's ready for confirmation
|
||||
const existingDevice = await this.getDeviceFromDatabase();
|
||||
if (existingDevice && existingDevice.pairing_process_commitment === processId) {
|
||||
const lastState = updatedProcess.current_process.states[updatedProcess.current_process.states.length - 1];
|
||||
if (lastState && lastState.public_data && lastState.public_data['pairedAddresses']) {
|
||||
console.log('Pairing process updated with paired addresses, confirming pairing...');
|
||||
await this.confirmPairing();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 7. Confirmation du Pairing
|
||||
|
||||
**Fonction :** `confirmPairing()`
|
||||
**Localisation :** `src/services/service.ts:793-851`
|
||||
|
||||
**Actions :**
|
||||
|
||||
#### 7.1 Récupération du Processus de Pairing
|
||||
```typescript
|
||||
const existingDevice = await this.getDeviceFromDatabase();
|
||||
const pairingProcessId = existingDevice.pairing_process_commitment;
|
||||
const myPairingProcess = await this.getProcess(pairingProcessId);
|
||||
```
|
||||
|
||||
#### 7.2 Extraction des Adresses Couplées
|
||||
```typescript
|
||||
let myPairingState = this.getLastCommitedState(myPairingProcess);
|
||||
const encodedSpAddressList = myPairingState.public_data['pairedAddresses'];
|
||||
const spAddressList = this.decodeValue(encodedSpAddressList);
|
||||
```
|
||||
|
||||
#### 7.3 Pairing Effectif du Device
|
||||
```typescript
|
||||
this.sdkClient.unpair_device(); // Clear any existing pairing
|
||||
this.sdkClient.pair_device(pairingProcessId, spAddressList);
|
||||
```
|
||||
|
||||
#### 7.4 Sauvegarde du Device Mis à Jour
|
||||
```typescript
|
||||
const newDevice = this.dumpDeviceFromMemory();
|
||||
newDevice.pairing_process_commitment = pairingProcessId;
|
||||
await this.saveDeviceInDatabase(newDevice);
|
||||
```
|
||||
|
||||
## Architecture Technique
|
||||
|
||||
### Côté Client (TypeScript)
|
||||
|
||||
**Composants principaux :**
|
||||
- **Interface Utilisateur :** Gestion des événements de clic et affichage des emojis
|
||||
- **Services :** Orchestration du workflow et communication avec WebAssembly
|
||||
- **Base de Données :** Stockage des devices, secrets et processus
|
||||
- **WebSocket :** Communication avec les relais
|
||||
|
||||
### Côté WebAssembly (Rust)
|
||||
|
||||
**Fonctionnalités clés :**
|
||||
- **Gestion des Wallets :** Création et manipulation des portefeuilles Silent Payment
|
||||
- **Cryptographie :** Génération de secrets partagés et signatures
|
||||
- **Transactions :** Création et finalisation des transactions Bitcoin
|
||||
- **Processus :** Gestion des états et validation des changements
|
||||
|
||||
## Types de Données Importants
|
||||
|
||||
### Device
|
||||
```typescript
|
||||
interface Device {
|
||||
sp_wallet: SpWallet;
|
||||
pairing_process_commitment: OutPoint | null;
|
||||
paired_member: Member;
|
||||
}
|
||||
```
|
||||
|
||||
### Process
|
||||
```typescript
|
||||
interface Process {
|
||||
states: ProcessState[];
|
||||
}
|
||||
```
|
||||
|
||||
### ApiReturn
|
||||
```typescript
|
||||
interface ApiReturn {
|
||||
secrets: SecretsStore | null;
|
||||
updated_process: UpdatedProcess | null;
|
||||
new_tx_to_send: NewTxMessage | null;
|
||||
ciphers_to_send: string[];
|
||||
commit_to_send: CommitMessage | null;
|
||||
push_to_storage: string[];
|
||||
partial_tx: TsUnsignedTransaction | null;
|
||||
}
|
||||
```
|
||||
|
||||
## Flux de Communication
|
||||
|
||||
1. **UI → Service :** Déclenchement du processus via `onCreateButtonClick()`
|
||||
2. **Service → WebAssembly :** Appel des fonctions WASM pour la création du processus
|
||||
3. **WebAssembly → Service :** Retour des données via `ApiReturn`
|
||||
4. **Service → WebSocket :** Envoi des messages aux relais
|
||||
5. **WebSocket → Service :** Réception des réponses des relais
|
||||
6. **Service → Database :** Sauvegarde des états et secrets
|
||||
7. **Service → UI :** Mise à jour de l'interface utilisateur
|
||||
|
||||
## Points d'Attention
|
||||
|
||||
### Sécurité
|
||||
- Les secrets partagés sont générés côté WebAssembly (Rust)
|
||||
- Les transactions sont signées de manière sécurisée
|
||||
- Les données sensibles sont chiffrées avant stockage
|
||||
|
||||
### Asynchronisme
|
||||
- Le processus est entièrement asynchrone
|
||||
- Utilisation de promesses et callbacks pour la coordination
|
||||
- Gestion d'erreur à chaque étape critique
|
||||
|
||||
### État du Processus
|
||||
- Suivi de l'état via `processId` et `stateId`
|
||||
- Sauvegarde persistante en base de données
|
||||
- Récupération possible en cas d'interruption
|
||||
|
||||
## Conclusion
|
||||
|
||||
Le workflow de pairing représente un processus complexe mais bien structuré qui coordonne l'interface utilisateur TypeScript avec les fonctionnalités cryptographiques Rust via WebAssembly. Cette architecture permet une sécurité maximale tout en maintenant une expérience utilisateur fluide. Le processus est conçu pour être résilient aux interruptions et permet une récupération d'état en cas de problème.
|
||||
|
||||
La séparation claire entre les responsabilités (UI, orchestration, cryptographie) facilite la maintenance et les évolutions futures du système de pairing.
|
||||
@ -26,7 +26,7 @@ server {
|
||||
|
||||
location /storage/ {
|
||||
rewrite ^/storage(/.*)$ $1 break;
|
||||
proxy_pass http://localhost:8080;
|
||||
proxy_pass http://localhost:8081;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
|
||||
79
nginx.prod.conf
Normal file
79
nginx.prod.conf
Normal file
@ -0,0 +1,79 @@
|
||||
# --- 1. REDIRECTION HTTP VERS HTTPS ---
|
||||
server {
|
||||
listen 80;
|
||||
server_name dev2.4nkweb.com;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
# --- 2. CONFIGURATION HTTPS PRINCIPALE ---
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name dev2.4nkweb.com;
|
||||
|
||||
# Chemins des certificats SSL
|
||||
ssl_certificate /etc/letsencrypt/live/dev2.4nkweb.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/dev2.4nkweb.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
# --- LOCATION POUR VITE (Front-end + HMR WebSocket) ---
|
||||
location / {
|
||||
proxy_pass http://localhost:3003;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# --- LOCATION POUR L'AUTRE WEBSOCKET (port 8090) ---
|
||||
location /ws/ {
|
||||
proxy_pass http://localhost:8090;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-NginX-Proxy true;
|
||||
proxy_read_timeout 86400;
|
||||
}
|
||||
|
||||
# --- LOCATION POUR SDK_STORAGE (port 8081) ---
|
||||
location /storage/ {
|
||||
# Gestion du préflight CORS
|
||||
if ($request_method = 'OPTIONS') {
|
||||
add_header 'Access-Control-Allow-Origin' '*' always;
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
|
||||
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With' always;
|
||||
add_header 'Access-Control-Max-Age' 86400;
|
||||
add_header 'Content-Length' 0;
|
||||
add_header 'Content-Type' 'text/plain';
|
||||
return 204;
|
||||
}
|
||||
# Headers CORS pour les requêtes réelles
|
||||
add_header 'Access-Control-Allow-Origin' '*' always;
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
|
||||
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With' always;
|
||||
rewrite ^/storage(/.*)$ $1 break;
|
||||
proxy_pass http://localhost:8081;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# --- LOCATION POUR TON API (port 8091) ---
|
||||
location /api/ {
|
||||
proxy_pass http://localhost:8091;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# CORS headers
|
||||
add_header Access-Control-Allow-Origin "*" always;
|
||||
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE" always;
|
||||
add_header Access-Control-Allow-Headers "Authorization,Content-Type,Accept,X-Requested-With" always;
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "sdk_client",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build_wasm": "wasm-pack build --out-dir ../ihm_client/pkg ../sdk_client --target bundler --dev",
|
||||
"build_wasm": "wasm-pack build --out-dir ../ihm_client_dev2/pkg ../sdk_client --target bundler --dev",
|
||||
"start": "vite --host 0.0.0.0",
|
||||
"build": "tsc && vite build",
|
||||
"deploy": "sudo cp -r dist/* /var/www/html/",
|
||||
|
||||
22
src/main.ts
22
src/main.ts
@ -1,20 +1,20 @@
|
||||
import { SignatureComponent } from './pages/signature/signature-component';
|
||||
import { SignatureElement } from './pages/signature/signature';
|
||||
/*import { ChatComponent } from './pages/chat/chat-component';
|
||||
import { ChatElement } from './pages/chat/chat';*/
|
||||
import { AccountComponent } from './pages/account/account-component';
|
||||
import { AccountElement } from './pages/account/account';
|
||||
// import { ChatComponent } from './pages/chat/chat-component';
|
||||
// import { ChatElement } from './pages/chat/chat';
|
||||
// import { AccountComponent } from './pages/account/account-component';
|
||||
// import { AccountElement } from './pages/account/account';
|
||||
|
||||
export { SignatureComponent, SignatureElement, AccountComponent, AccountElement };
|
||||
export { SignatureComponent, SignatureElement };
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'signature-component': SignatureComponent;
|
||||
'signature-element': SignatureElement;
|
||||
/*'chat-component': ChatComponent;
|
||||
'chat-element': ChatElement;*/
|
||||
'account-component': AccountComponent;
|
||||
'account-element': AccountElement;
|
||||
// 'chat-component': ChatComponent;
|
||||
// 'chat-element': ChatElement;
|
||||
// 'account-component': AccountComponent;
|
||||
// 'account-element': AccountElement;
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,6 +25,6 @@ if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB) {
|
||||
customElements.define('signature-element', SignatureElement);
|
||||
/*customElements.define('chat-component', ChatComponent);
|
||||
customElements.define('chat-element', ChatElement);*/
|
||||
customElements.define('account-component', AccountComponent);
|
||||
customElements.define('account-element', AccountElement);
|
||||
// customElements.define('account-component', AccountComponent);
|
||||
// customElements.define('account-element', AccountElement);
|
||||
}
|
||||
|
||||
@ -1,62 +1,62 @@
|
||||
import { AccountElement } from './account';
|
||||
import accountCss from '../../../public/style/account.css?raw';
|
||||
import Services from '../../services/service.js';
|
||||
// import { AccountElement } from './account';
|
||||
// import accountCss from '../../../style/account.css?raw';
|
||||
// import Services from '../../services/service.js';
|
||||
|
||||
class AccountComponent extends HTMLElement {
|
||||
_callback: any;
|
||||
accountElement: AccountElement | null = null;
|
||||
// class AccountComponent extends HTMLElement {
|
||||
// _callback: any;
|
||||
// accountElement: AccountElement | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
console.log('INIT');
|
||||
this.attachShadow({ mode: 'open' });
|
||||
// constructor() {
|
||||
// super();
|
||||
// console.log('INIT');
|
||||
// this.attachShadow({ mode: 'open' });
|
||||
|
||||
this.accountElement = this.shadowRoot?.querySelector('account-element') || null;
|
||||
}
|
||||
// this.accountElement = this.shadowRoot?.querySelector('account-element') || null;
|
||||
// }
|
||||
|
||||
connectedCallback() {
|
||||
console.log('CALLBACKs');
|
||||
this.render();
|
||||
this.fetchData();
|
||||
// connectedCallback() {
|
||||
// console.log('CALLBACKs');
|
||||
// this.render();
|
||||
// this.fetchData();
|
||||
|
||||
if (!customElements.get('account-element')) {
|
||||
customElements.define('account-element', AccountElement);
|
||||
}
|
||||
}
|
||||
// if (!customElements.get('account-element')) {
|
||||
// customElements.define('account-element', AccountElement);
|
||||
// }
|
||||
// }
|
||||
|
||||
async fetchData() {
|
||||
if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB === false) {
|
||||
const data = await (window as any).myService?.getProcesses();
|
||||
} else {
|
||||
const service = await Services.getInstance();
|
||||
const data = await service.getProcesses();
|
||||
}
|
||||
}
|
||||
// async fetchData() {
|
||||
// if ((import.meta as any).env.VITE_IS_INDEPENDANT_LIB === false) {
|
||||
// const data = await (window as any).myService?.getProcesses();
|
||||
// } else {
|
||||
// const service = await Services.getInstance();
|
||||
// const data = await service.getProcesses();
|
||||
// }
|
||||
// }
|
||||
|
||||
set callback(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
this._callback = fn;
|
||||
} else {
|
||||
console.error('Callback is not a function');
|
||||
}
|
||||
}
|
||||
// set callback(fn) {
|
||||
// if (typeof fn === 'function') {
|
||||
// this._callback = fn;
|
||||
// } else {
|
||||
// console.error('Callback is not a function');
|
||||
// }
|
||||
// }
|
||||
|
||||
get callback() {
|
||||
return this._callback;
|
||||
}
|
||||
// get callback() {
|
||||
// return this._callback;
|
||||
// }
|
||||
|
||||
render() {
|
||||
if (this.shadowRoot && !this.shadowRoot.querySelector('account-element')) {
|
||||
const style = document.createElement('style');
|
||||
style.textContent = accountCss;
|
||||
// render() {
|
||||
// if (this.shadowRoot && !this.shadowRoot.querySelector('account-element')) {
|
||||
// const style = document.createElement('style');
|
||||
// style.textContent = accountCss;
|
||||
|
||||
const accountElement = document.createElement('account-element');
|
||||
// const accountElement = document.createElement('account-element');
|
||||
|
||||
this.shadowRoot.appendChild(style);
|
||||
this.shadowRoot.appendChild(accountElement);
|
||||
}
|
||||
}
|
||||
}
|
||||
// this.shadowRoot.appendChild(style);
|
||||
// this.shadowRoot.appendChild(accountElement);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
export { AccountComponent };
|
||||
customElements.define('account-component', AccountComponent);
|
||||
// export { AccountComponent };
|
||||
// customElements.define('account-component', AccountComponent);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- <!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Account</title>
|
||||
@ -7,4 +7,4 @@
|
||||
<account-component></account-component>
|
||||
<script type="module" src="./account.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html> -->
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,321 +1,321 @@
|
||||
import { ProcessState } from '../../../pkg/sdk_client';
|
||||
import Services from '../../services/service';
|
||||
// import { ProcessState } from '../../../pkg/sdk_client';
|
||||
// import Services from '../../services/service';
|
||||
|
||||
interface State {
|
||||
file: File | null;
|
||||
fileHash: string | null;
|
||||
certificate: ProcessState | null;
|
||||
commitmentHashes: string[];
|
||||
}
|
||||
// interface State {
|
||||
// file: File | null;
|
||||
// fileHash: string | null;
|
||||
// certificate: ProcessState | null;
|
||||
// commitmentHashes: string[];
|
||||
// }
|
||||
|
||||
export interface Vin {
|
||||
txid: string; // The txid of the previous transaction (being spent)
|
||||
vout: number; // The output index in the previous tx
|
||||
prevout: {
|
||||
scriptpubkey: string;
|
||||
scriptpubkey_asm: string;
|
||||
scriptpubkey_type: string;
|
||||
scriptpubkey_address: string;
|
||||
value: number;
|
||||
};
|
||||
scriptsig: string;
|
||||
scriptsig_asm: string;
|
||||
witness: string[];
|
||||
is_coinbase: boolean;
|
||||
sequence: number;
|
||||
}
|
||||
// export interface Vin {
|
||||
// txid: string; // The txid of the previous transaction (being spent)
|
||||
// vout: number; // The output index in the previous tx
|
||||
// prevout: {
|
||||
// scriptpubkey: string;
|
||||
// scriptpubkey_asm: string;
|
||||
// scriptpubkey_type: string;
|
||||
// scriptpubkey_address: string;
|
||||
// value: number;
|
||||
// };
|
||||
// scriptsig: string;
|
||||
// scriptsig_asm: string;
|
||||
// witness: string[];
|
||||
// is_coinbase: boolean;
|
||||
// sequence: number;
|
||||
// }
|
||||
|
||||
export interface TransactionInfo {
|
||||
txid: string;
|
||||
version: number;
|
||||
locktime: number;
|
||||
vin: Vin[];
|
||||
vout: any[];
|
||||
size: number;
|
||||
weight: number;
|
||||
fee: number;
|
||||
status: {
|
||||
confirmed: boolean;
|
||||
block_height: number;
|
||||
block_hash: string;
|
||||
block_time: number;
|
||||
};
|
||||
}
|
||||
// export interface TransactionInfo {
|
||||
// txid: string;
|
||||
// version: number;
|
||||
// locktime: number;
|
||||
// vin: Vin[];
|
||||
// vout: any[];
|
||||
// size: number;
|
||||
// weight: number;
|
||||
// fee: number;
|
||||
// status: {
|
||||
// confirmed: boolean;
|
||||
// block_height: number;
|
||||
// block_hash: string;
|
||||
// block_time: number;
|
||||
// };
|
||||
// }
|
||||
|
||||
export function getDocumentValidation(container: HTMLElement) {
|
||||
const state: State = {
|
||||
file: null,
|
||||
fileHash: null,
|
||||
certificate: null,
|
||||
commitmentHashes: []
|
||||
}
|
||||
// export function getDocumentValidation(container: HTMLElement) {
|
||||
// const state: State = {
|
||||
// file: null,
|
||||
// fileHash: null,
|
||||
// certificate: null,
|
||||
// commitmentHashes: []
|
||||
// }
|
||||
|
||||
container.innerHTML = '';
|
||||
container.style.cssText = `
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
gap: 2rem;
|
||||
`;
|
||||
// container.innerHTML = '';
|
||||
// container.style.cssText = `
|
||||
// display: flex;
|
||||
// flex-direction: column;
|
||||
// justify-content: center;
|
||||
// align-items: center;
|
||||
// min-height: 100vh;
|
||||
// gap: 2rem;
|
||||
// `;
|
||||
|
||||
function createDropButton(
|
||||
label: string,
|
||||
onDrop: (file: File, updateVisuals: (file: File) => void) => void,
|
||||
accept: string = '*/*'
|
||||
): HTMLElement {
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.style.cssText = `
|
||||
width: 200px;
|
||||
height: 100px;
|
||||
border: 2px dashed #888;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
background: #f8f8f8;
|
||||
text-align: center;
|
||||
padding: 0.5rem;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
// function createDropButton(
|
||||
// label: string,
|
||||
// onDrop: (file: File, updateVisuals: (file: File) => void) => void,
|
||||
// accept: string = '*/*'
|
||||
// ): HTMLElement {
|
||||
// const wrapper = document.createElement('div');
|
||||
// wrapper.style.cssText = `
|
||||
// width: 200px;
|
||||
// height: 100px;
|
||||
// border: 2px dashed #888;
|
||||
// border-radius: 8px;
|
||||
// display: flex;
|
||||
// flex-direction: column;
|
||||
// align-items: center;
|
||||
// justify-content: center;
|
||||
// cursor: pointer;
|
||||
// font-weight: bold;
|
||||
// background: #f8f8f8;
|
||||
// text-align: center;
|
||||
// padding: 0.5rem;
|
||||
// box-sizing: border-box;
|
||||
// `;
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.textContent = label;
|
||||
// const title = document.createElement('div');
|
||||
// title.textContent = label;
|
||||
|
||||
const filename = document.createElement('div');
|
||||
filename.style.cssText = `
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.5rem;
|
||||
color: #444;
|
||||
word-break: break-word;
|
||||
text-align: center;
|
||||
`;
|
||||
// const filename = document.createElement('div');
|
||||
// filename.style.cssText = `
|
||||
// font-size: 0.85rem;
|
||||
// margin-top: 0.5rem;
|
||||
// color: #444;
|
||||
// word-break: break-word;
|
||||
// text-align: center;
|
||||
// `;
|
||||
|
||||
wrapper.appendChild(title);
|
||||
wrapper.appendChild(filename);
|
||||
// wrapper.appendChild(title);
|
||||
// wrapper.appendChild(filename);
|
||||
|
||||
const updateVisuals = (file: File) => {
|
||||
wrapper.style.borderColor = 'green';
|
||||
wrapper.style.background = '#e6ffed';
|
||||
filename.textContent = file.name;
|
||||
};
|
||||
// const updateVisuals = (file: File) => {
|
||||
// wrapper.style.borderColor = 'green';
|
||||
// wrapper.style.background = '#e6ffed';
|
||||
// filename.textContent = file.name;
|
||||
// };
|
||||
|
||||
// === Hidden file input ===
|
||||
const fileInput = document.createElement('input');
|
||||
fileInput.type = 'file';
|
||||
fileInput.accept = accept;
|
||||
fileInput.style.display = 'none';
|
||||
document.body.appendChild(fileInput);
|
||||
// // === Hidden file input ===
|
||||
// const fileInput = document.createElement('input');
|
||||
// fileInput.type = 'file';
|
||||
// fileInput.accept = accept;
|
||||
// fileInput.style.display = 'none';
|
||||
// document.body.appendChild(fileInput);
|
||||
|
||||
fileInput.onchange = () => {
|
||||
const file = fileInput.files?.[0];
|
||||
if (file) {
|
||||
onDrop(file, updateVisuals);
|
||||
fileInput.value = ''; // reset so same file can be re-selected
|
||||
}
|
||||
};
|
||||
// fileInput.onchange = () => {
|
||||
// const file = fileInput.files?.[0];
|
||||
// if (file) {
|
||||
// onDrop(file, updateVisuals);
|
||||
// fileInput.value = ''; // reset so same file can be re-selected
|
||||
// }
|
||||
// };
|
||||
|
||||
// === Handle drag-and-drop ===
|
||||
wrapper.ondragover = e => {
|
||||
e.preventDefault();
|
||||
wrapper.style.background = '#e0e0e0';
|
||||
};
|
||||
// // === Handle drag-and-drop ===
|
||||
// wrapper.ondragover = e => {
|
||||
// e.preventDefault();
|
||||
// wrapper.style.background = '#e0e0e0';
|
||||
// };
|
||||
|
||||
wrapper.ondragleave = () => {
|
||||
wrapper.style.background = '#f8f8f8';
|
||||
};
|
||||
// wrapper.ondragleave = () => {
|
||||
// wrapper.style.background = '#f8f8f8';
|
||||
// };
|
||||
|
||||
wrapper.ondrop = e => {
|
||||
e.preventDefault();
|
||||
wrapper.style.background = '#f8f8f8';
|
||||
// wrapper.ondrop = e => {
|
||||
// e.preventDefault();
|
||||
// wrapper.style.background = '#f8f8f8';
|
||||
|
||||
const file = e.dataTransfer?.files?.[0];
|
||||
if (file) {
|
||||
onDrop(file, updateVisuals);
|
||||
}
|
||||
};
|
||||
// const file = e.dataTransfer?.files?.[0];
|
||||
// if (file) {
|
||||
// onDrop(file, updateVisuals);
|
||||
// }
|
||||
// };
|
||||
|
||||
// === Handle click to open file manager ===
|
||||
wrapper.onclick = () => {
|
||||
fileInput.click();
|
||||
};
|
||||
// // === Handle click to open file manager ===
|
||||
// wrapper.onclick = () => {
|
||||
// fileInput.click();
|
||||
// };
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
// return wrapper;
|
||||
// }
|
||||
|
||||
const fileDropButton = createDropButton('Drop file', async (file, updateVisuals) => {
|
||||
try {
|
||||
state.file = file;
|
||||
updateVisuals(file);
|
||||
console.log('Loaded file:', state.file);
|
||||
checkReady();
|
||||
} catch (err) {
|
||||
alert('Failed to drop the file.');
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
// const fileDropButton = createDropButton('Drop file', async (file, updateVisuals) => {
|
||||
// try {
|
||||
// state.file = file;
|
||||
// updateVisuals(file);
|
||||
// console.log('Loaded file:', state.file);
|
||||
// checkReady();
|
||||
// } catch (err) {
|
||||
// alert('Failed to drop the file.');
|
||||
// console.error(err);
|
||||
// }
|
||||
// });
|
||||
|
||||
const certDropButton = createDropButton('Drop certificate', async (file, updateVisuals) => {
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
if (
|
||||
typeof json === 'object' &&
|
||||
json !== null &&
|
||||
typeof json.pcd_commitment === 'object' &&
|
||||
typeof json.state_id === 'string'
|
||||
) {
|
||||
state.certificate = json as ProcessState;
|
||||
// const certDropButton = createDropButton('Drop certificate', async (file, updateVisuals) => {
|
||||
// try {
|
||||
// const text = await file.text();
|
||||
// const json = JSON.parse(text);
|
||||
// if (
|
||||
// typeof json === 'object' &&
|
||||
// json !== null &&
|
||||
// typeof json.pcd_commitment === 'object' &&
|
||||
// typeof json.state_id === 'string'
|
||||
// ) {
|
||||
// state.certificate = json as ProcessState;
|
||||
|
||||
state.commitmentHashes = Object.values(json.pcd_commitment).map((h: string) =>
|
||||
h.toLowerCase()
|
||||
);
|
||||
// state.commitmentHashes = Object.values(json.pcd_commitment).map((h: string) =>
|
||||
// h.toLowerCase()
|
||||
// );
|
||||
|
||||
updateVisuals(file);
|
||||
console.log('Loaded certificate, extracted hashes:', state.commitmentHashes);
|
||||
checkReady();
|
||||
} else {
|
||||
alert('Invalid certificate structure.');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to parse certificate JSON.');
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
// updateVisuals(file);
|
||||
// console.log('Loaded certificate, extracted hashes:', state.commitmentHashes);
|
||||
// checkReady();
|
||||
// } else {
|
||||
// alert('Invalid certificate structure.');
|
||||
// }
|
||||
// } catch (err) {
|
||||
// alert('Failed to parse certificate JSON.');
|
||||
// console.error(err);
|
||||
// }
|
||||
// });
|
||||
|
||||
const buttonRow = document.createElement('div');
|
||||
buttonRow.style.display = 'flex';
|
||||
buttonRow.style.gap = '2rem';
|
||||
buttonRow.appendChild(fileDropButton);
|
||||
buttonRow.appendChild(certDropButton);
|
||||
// const buttonRow = document.createElement('div');
|
||||
// buttonRow.style.display = 'flex';
|
||||
// buttonRow.style.gap = '2rem';
|
||||
// buttonRow.appendChild(fileDropButton);
|
||||
// buttonRow.appendChild(certDropButton);
|
||||
|
||||
container.appendChild(buttonRow);
|
||||
// container.appendChild(buttonRow);
|
||||
|
||||
async function checkReady() {
|
||||
if (state.file && state.certificate && state.commitmentHashes.length > 0) {
|
||||
// We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash
|
||||
const fileBlob = {
|
||||
type: state.file.type,
|
||||
data: new Uint8Array(await state.file.arrayBuffer())
|
||||
};
|
||||
const service = await Services.getInstance();
|
||||
const commitedIn = state.certificate.commited_in;
|
||||
if (!commitedIn) return;
|
||||
const [prevTxid, prevTxVout] = commitedIn.split(':');
|
||||
const processId = state.certificate.process_id;
|
||||
const stateId = state.certificate.state_id;
|
||||
const process = await service.getProcess(processId);
|
||||
if (!process) return;
|
||||
// async function checkReady() {
|
||||
// if (state.file && state.certificate && state.commitmentHashes.length > 0) {
|
||||
// // We take the commited_in and all pcd_commitment keys to reconstruct all the possible hash
|
||||
// const fileBlob = {
|
||||
// type: state.file.type,
|
||||
// data: new Uint8Array(await state.file.arrayBuffer())
|
||||
// };
|
||||
// const service = await Services.getInstance();
|
||||
// const commitedIn = state.certificate.commited_in;
|
||||
// if (!commitedIn) return;
|
||||
// const [prevTxid, prevTxVout] = commitedIn.split(':');
|
||||
// const processId = state.certificate.process_id;
|
||||
// const stateId = state.certificate.state_id;
|
||||
// const process = await service.getProcess(processId);
|
||||
// if (!process) return;
|
||||
|
||||
// Get the transaction that comes right after the commited_in
|
||||
const nextState = service.getNextStateAfterId(process, stateId);
|
||||
// // Get the transaction that comes right after the commited_in
|
||||
// const nextState = service.getNextStateAfterId(process, stateId);
|
||||
|
||||
if (!nextState) {
|
||||
alert(`❌ Validation failed: No next state, is the state you're trying to validate commited?`);
|
||||
return;
|
||||
}
|
||||
// if (!nextState) {
|
||||
// alert(`❌ Validation failed: No next state, is the state you're trying to validate commited?`);
|
||||
// return;
|
||||
// }
|
||||
|
||||
const [outspentTxId, _] = nextState.commited_in.split(':');
|
||||
console.log(outspentTxId);
|
||||
// const [outspentTxId, _] = nextState.commited_in.split(':');
|
||||
// console.log(outspentTxId);
|
||||
|
||||
// Check that the commitment transaction exists, and that it commits to the state id
|
||||
// // Check that the commitment transaction exists, and that it commits to the state id
|
||||
|
||||
const txInfo = await fetchTransaction(outspentTxId);
|
||||
if (!txInfo) {
|
||||
console.error(`Validation error: Can't fetch new state commitment transaction`);
|
||||
alert(`❌ Validation failed: invalid or non existent commited_in for state ${stateId}.`);
|
||||
return;
|
||||
}
|
||||
// const txInfo = await fetchTransaction(outspentTxId);
|
||||
// if (!txInfo) {
|
||||
// console.error(`Validation error: Can't fetch new state commitment transaction`);
|
||||
// alert(`❌ Validation failed: invalid or non existent commited_in for state ${stateId}.`);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// We must check that this transaction indeed spend the commited_in we have in the certificate
|
||||
let found = false;
|
||||
for (const vin of txInfo.vin) {
|
||||
if (vin.txid === prevTxid) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// // We must check that this transaction indeed spend the commited_in we have in the certificate
|
||||
// let found = false;
|
||||
// for (const vin of txInfo.vin) {
|
||||
// if (vin.txid === prevTxid) {
|
||||
// found = true;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
if (!found) {
|
||||
console.error(`Validation error: new state doesn't spend previous state commitment transaction`);
|
||||
alert('❌ Validation failed: Unconsistent commitment transactions history.');
|
||||
return;
|
||||
}
|
||||
// if (!found) {
|
||||
// console.error(`Validation error: new state doesn't spend previous state commitment transaction`);
|
||||
// alert('❌ Validation failed: Unconsistent commitment transactions history.');
|
||||
// return;
|
||||
// }
|
||||
|
||||
// set found back to false for next check
|
||||
found = false;
|
||||
// // set found back to false for next check
|
||||
// found = false;
|
||||
|
||||
// is the state_id commited in the transaction?
|
||||
for (const vout of txInfo.vout) {
|
||||
console.log(vout);
|
||||
if (vout.scriptpubkey_type && vout.scriptpubkey_type === 'op_return') {
|
||||
found = true;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
// // is the state_id commited in the transaction?
|
||||
// for (const vout of txInfo.vout) {
|
||||
// console.log(vout);
|
||||
// if (vout.scriptpubkey_type && vout.scriptpubkey_type === 'op_return') {
|
||||
// found = true;
|
||||
// } else {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (vout.scriptpubkey_asm) {
|
||||
const hash = extractHexFromScriptAsm(vout.scriptpubkey_asm);
|
||||
if (hash) {
|
||||
if (hash !== stateId) {
|
||||
console.error(`Validation error: expected stateId ${stateId}, got ${hash}`);
|
||||
alert('❌ Validation failed: Transaction does not commit to that state.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (vout.scriptpubkey_asm) {
|
||||
// const hash = extractHexFromScriptAsm(vout.scriptpubkey_asm);
|
||||
// if (hash) {
|
||||
// if (hash !== stateId) {
|
||||
// console.error(`Validation error: expected stateId ${stateId}, got ${hash}`);
|
||||
// alert('❌ Validation failed: Transaction does not commit to that state.');
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
if (!found) {
|
||||
alert('❌ Validation failed: Transaction does not contain data.');
|
||||
return;
|
||||
}
|
||||
// if (!found) {
|
||||
// alert('❌ Validation failed: Transaction does not contain data.');
|
||||
// return;
|
||||
// }
|
||||
|
||||
// set found back to false for next check
|
||||
found = false;
|
||||
// // set found back to false for next check
|
||||
// found = false;
|
||||
|
||||
for (const label of Object.keys(state.certificate.pcd_commitment)) {
|
||||
// Compute the hash for this label
|
||||
console.log(`Computing hash with label ${label}`)
|
||||
const fileHex = service.getHashForFile(commitedIn, label, fileBlob);
|
||||
console.log(`Found hash ${fileHex}`);
|
||||
found = state.commitmentHashes.includes(fileHex);
|
||||
if (found) break;
|
||||
}
|
||||
// for (const label of Object.keys(state.certificate.pcd_commitment)) {
|
||||
// // Compute the hash for this label
|
||||
// console.log(`Computing hash with label ${label}`)
|
||||
// const fileHex = service.getHashForFile(commitedIn, label, fileBlob);
|
||||
// console.log(`Found hash ${fileHex}`);
|
||||
// found = state.commitmentHashes.includes(fileHex);
|
||||
// if (found) break;
|
||||
// }
|
||||
|
||||
if (found) {
|
||||
alert('✅ Validation successful: file hash found in pcd_commitment.');
|
||||
} else {
|
||||
alert('❌ Validation failed: file hash NOT found in pcd_commitment.');
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (found) {
|
||||
// alert('✅ Validation successful: file hash found in pcd_commitment.');
|
||||
// } else {
|
||||
// alert('❌ Validation failed: file hash NOT found in pcd_commitment.');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
async function fetchTransaction(txid: string): Promise<TransactionInfo> {
|
||||
const url = `https://mempool.4nkweb.com/api/tx/${txid}`;
|
||||
// async function fetchTransaction(txid: string): Promise<TransactionInfo> {
|
||||
// const url = `https://mempool.4nkweb.com/api/tx/${txid}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch outspend status: ${response.statusText}`);
|
||||
}
|
||||
// const response = await fetch(url);
|
||||
// if (!response.ok) {
|
||||
// throw new Error(`Failed to fetch outspend status: ${response.statusText}`);
|
||||
// }
|
||||
|
||||
const outspend: TransactionInfo = await response.json();
|
||||
return outspend;
|
||||
}
|
||||
// const outspend: TransactionInfo = await response.json();
|
||||
// return outspend;
|
||||
// }
|
||||
|
||||
function extractHexFromScriptAsm(scriptAsm: string): string | null {
|
||||
const parts = scriptAsm.trim().split(/\s+/);
|
||||
const last = parts[parts.length - 1];
|
||||
// function extractHexFromScriptAsm(scriptAsm: string): string | null {
|
||||
// const parts = scriptAsm.trim().split(/\s+/);
|
||||
// const last = parts[parts.length - 1];
|
||||
|
||||
// Basic validation: must be 64-char hex (32 bytes)
|
||||
if (/^[0-9a-fA-F]{64}$/.test(last)) {
|
||||
return last.toLowerCase();
|
||||
}
|
||||
// // Basic validation: must be 64-char hex (32 bytes)
|
||||
// if (/^[0-9a-fA-F]{64}$/.test(last)) {
|
||||
// return last.toLowerCase();
|
||||
// }
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
|
||||
@ -1,196 +1,196 @@
|
||||
import { ValidationRule, RoleDefinition } from '../../../pkg/sdk_client';
|
||||
import { showValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal';
|
||||
// import { ValidationRule, RoleDefinition } from '../../../pkg/sdk_client';
|
||||
// import { showValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal';
|
||||
|
||||
export function createKeyValueSection(title: string, id: string, isRoleSection = false) {
|
||||
const section = document.createElement('div');
|
||||
section.id = id;
|
||||
section.style.cssText = 'margin-bottom: 2rem; background: #fff; padding: 1rem; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);';
|
||||
// export function createKeyValueSection(title: string, id: string, isRoleSection = false) {
|
||||
// const section = document.createElement('div');
|
||||
// section.id = id;
|
||||
// section.style.cssText = 'margin-bottom: 2rem; background: #fff; padding: 1rem; border-radius: 0.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);';
|
||||
|
||||
const titleEl = document.createElement('h2');
|
||||
titleEl.textContent = title;
|
||||
titleEl.style.cssText = 'font-size: 1.25rem; font-weight: bold; margin-bottom: 1rem;';
|
||||
section.appendChild(titleEl);
|
||||
// const titleEl = document.createElement('h2');
|
||||
// titleEl.textContent = title;
|
||||
// titleEl.style.cssText = 'font-size: 1.25rem; font-weight: bold; margin-bottom: 1rem;';
|
||||
// section.appendChild(titleEl);
|
||||
|
||||
const rowContainer = document.createElement('div');
|
||||
section.appendChild(rowContainer);
|
||||
// const rowContainer = document.createElement('div');
|
||||
// section.appendChild(rowContainer);
|
||||
|
||||
const addBtn = document.createElement('button');
|
||||
addBtn.textContent = '+ Add Row';
|
||||
addBtn.style.cssText = `
|
||||
margin-top: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
border: 1px solid #888;
|
||||
border-radius: 0.375rem;
|
||||
background-color: #f9f9f9;
|
||||
cursor: pointer;
|
||||
`;
|
||||
section.appendChild(addBtn);
|
||||
// const addBtn = document.createElement('button');
|
||||
// addBtn.textContent = '+ Add Row';
|
||||
// addBtn.style.cssText = `
|
||||
// margin-top: 1rem;
|
||||
// padding: 0.5rem 1rem;
|
||||
// border: 1px solid #888;
|
||||
// border-radius: 0.375rem;
|
||||
// background-color: #f9f9f9;
|
||||
// cursor: pointer;
|
||||
// `;
|
||||
// section.appendChild(addBtn);
|
||||
|
||||
const roleRowStates: {
|
||||
roleNameInput: HTMLInputElement;
|
||||
membersInput: HTMLInputElement;
|
||||
storagesInput: HTMLInputElement;
|
||||
validationRules: ValidationRule[];
|
||||
}[] = [];
|
||||
type fileBlob = {
|
||||
type: string,
|
||||
data: Uint8Array
|
||||
};
|
||||
const nonRoleRowStates: {
|
||||
keyInput: HTMLInputElement,
|
||||
valueInput: HTMLInputElement,
|
||||
fileInput: HTMLInputElement,
|
||||
fileBlob: fileBlob | null
|
||||
}[] = [];
|
||||
// const roleRowStates: {
|
||||
// roleNameInput: HTMLInputElement;
|
||||
// membersInput: HTMLInputElement;
|
||||
// storagesInput: HTMLInputElement;
|
||||
// validationRules: ValidationRule[];
|
||||
// }[] = [];
|
||||
// type fileBlob = {
|
||||
// type: string,
|
||||
// data: Uint8Array
|
||||
// };
|
||||
// const nonRoleRowStates: {
|
||||
// keyInput: HTMLInputElement,
|
||||
// valueInput: HTMLInputElement,
|
||||
// fileInput: HTMLInputElement,
|
||||
// fileBlob: fileBlob | null
|
||||
// }[] = [];
|
||||
|
||||
const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;';
|
||||
// const inputStyle = 'flex: 1; height: 2.5rem; padding: 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem;';
|
||||
|
||||
const createRow = () => {
|
||||
const row = document.createElement('div');
|
||||
row.style.cssText = 'display: flex; gap: 1rem; margin-bottom: 0.5rem; align-items: center;';
|
||||
// const createRow = () => {
|
||||
// const row = document.createElement('div');
|
||||
// row.style.cssText = 'display: flex; gap: 1rem; margin-bottom: 0.5rem; align-items: center;';
|
||||
|
||||
const deleteBtn = document.createElement('button');
|
||||
deleteBtn.textContent = '🗑️';
|
||||
deleteBtn.style.cssText = 'background: none; border: none; font-size: 1.2rem; cursor: pointer;';
|
||||
deleteBtn.onclick = () => {
|
||||
row.remove();
|
||||
updateDeleteButtons();
|
||||
};
|
||||
// const deleteBtn = document.createElement('button');
|
||||
// deleteBtn.textContent = '🗑️';
|
||||
// deleteBtn.style.cssText = 'background: none; border: none; font-size: 1.2rem; cursor: pointer;';
|
||||
// deleteBtn.onclick = () => {
|
||||
// row.remove();
|
||||
// updateDeleteButtons();
|
||||
// };
|
||||
|
||||
if (isRoleSection) {
|
||||
const roleName = document.createElement('input');
|
||||
const members = document.createElement('input');
|
||||
const storages = document.createElement('input');
|
||||
// if (isRoleSection) {
|
||||
// const roleName = document.createElement('input');
|
||||
// const members = document.createElement('input');
|
||||
// const storages = document.createElement('input');
|
||||
|
||||
roleName.placeholder = 'Role name';
|
||||
members.placeholder = 'members';
|
||||
storages.placeholder = 'storages';
|
||||
[roleName, members, storages].forEach(input => {
|
||||
input.type = 'text';
|
||||
input.style.cssText = inputStyle;
|
||||
});
|
||||
// roleName.placeholder = 'Role name';
|
||||
// members.placeholder = 'members';
|
||||
// storages.placeholder = 'storages';
|
||||
// [roleName, members, storages].forEach(input => {
|
||||
// input.type = 'text';
|
||||
// input.style.cssText = inputStyle;
|
||||
// });
|
||||
|
||||
const ruleButton = document.createElement('button');
|
||||
ruleButton.textContent = 'Add Validation Rule';
|
||||
ruleButton.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
// const ruleButton = document.createElement('button');
|
||||
// ruleButton.textContent = 'Add Validation Rule';
|
||||
// ruleButton.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
|
||||
const rules: ValidationRule[] = [];
|
||||
ruleButton.onclick = () => {
|
||||
showValidationRuleModal(rule => {
|
||||
rules.push(rule);
|
||||
ruleButton.textContent = `Rules (${rules.length})`;
|
||||
});
|
||||
};
|
||||
// const rules: ValidationRule[] = [];
|
||||
// ruleButton.onclick = () => {
|
||||
// showValidationRuleModal(rule => {
|
||||
// rules.push(rule);
|
||||
// ruleButton.textContent = `Rules (${rules.length})`;
|
||||
// });
|
||||
// };
|
||||
|
||||
row.appendChild(roleName);
|
||||
row.appendChild(members);
|
||||
row.appendChild(storages);
|
||||
row.appendChild(ruleButton);
|
||||
row.appendChild(deleteBtn);
|
||||
// row.appendChild(roleName);
|
||||
// row.appendChild(members);
|
||||
// row.appendChild(storages);
|
||||
// row.appendChild(ruleButton);
|
||||
// row.appendChild(deleteBtn);
|
||||
|
||||
roleRowStates.push({ roleNameInput: roleName, membersInput: members, storagesInput: storages, validationRules: rules });
|
||||
} else {
|
||||
const fileInput = document.createElement('input');
|
||||
fileInput.type = 'file';
|
||||
fileInput.style.display = 'none';
|
||||
fileInput.onchange = async () => {
|
||||
const file = fileInput.files?.[0];
|
||||
if (!file) return;
|
||||
// roleRowStates.push({ roleNameInput: roleName, membersInput: members, storagesInput: storages, validationRules: rules });
|
||||
// } else {
|
||||
// const fileInput = document.createElement('input');
|
||||
// fileInput.type = 'file';
|
||||
// fileInput.style.display = 'none';
|
||||
// fileInput.onchange = async () => {
|
||||
// const file = fileInput.files?.[0];
|
||||
// if (!file) return;
|
||||
|
||||
const buffer = await file.arrayBuffer();
|
||||
const uint8 = new Uint8Array(buffer);
|
||||
// const buffer = await file.arrayBuffer();
|
||||
// const uint8 = new Uint8Array(buffer);
|
||||
|
||||
rowState.fileBlob = {
|
||||
type: file.type,
|
||||
data: uint8,
|
||||
};
|
||||
// rowState.fileBlob = {
|
||||
// type: file.type,
|
||||
// data: uint8,
|
||||
// };
|
||||
|
||||
valueInput.value = `📄 ${file.name}`;
|
||||
valueInput.disabled = true;
|
||||
attachBtn.textContent = `📎 ${file.name}`;
|
||||
};
|
||||
// valueInput.value = `📄 ${file.name}`;
|
||||
// valueInput.disabled = true;
|
||||
// attachBtn.textContent = `📎 ${file.name}`;
|
||||
// };
|
||||
|
||||
const attachBtn = document.createElement('button');
|
||||
attachBtn.textContent = '📎 Attach';
|
||||
attachBtn.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
attachBtn.onclick = () => fileInput.click();
|
||||
// const attachBtn = document.createElement('button');
|
||||
// attachBtn.textContent = '📎 Attach';
|
||||
// attachBtn.style.cssText = 'padding: 0.3rem 0.75rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
// attachBtn.onclick = () => fileInput.click();
|
||||
|
||||
const keyInput = document.createElement('input');
|
||||
const valueInput = document.createElement('input');
|
||||
// const keyInput = document.createElement('input');
|
||||
// const valueInput = document.createElement('input');
|
||||
|
||||
const rowState = {
|
||||
keyInput,
|
||||
valueInput,
|
||||
fileInput,
|
||||
fileBlob: null as fileBlob | null
|
||||
};
|
||||
nonRoleRowStates.push(rowState);
|
||||
// const rowState = {
|
||||
// keyInput,
|
||||
// valueInput,
|
||||
// fileInput,
|
||||
// fileBlob: null as fileBlob | null
|
||||
// };
|
||||
// nonRoleRowStates.push(rowState);
|
||||
|
||||
keyInput.placeholder = 'Key';
|
||||
valueInput.placeholder = 'Value';
|
||||
[keyInput, valueInput].forEach(input => {
|
||||
input.type = 'text';
|
||||
input.style.cssText = inputStyle;
|
||||
});
|
||||
// keyInput.placeholder = 'Key';
|
||||
// valueInput.placeholder = 'Value';
|
||||
// [keyInput, valueInput].forEach(input => {
|
||||
// input.type = 'text';
|
||||
// input.style.cssText = inputStyle;
|
||||
// });
|
||||
|
||||
row.appendChild(keyInput);
|
||||
row.appendChild(valueInput);
|
||||
// row.appendChild(keyInput);
|
||||
// row.appendChild(valueInput);
|
||||
|
||||
row.appendChild(attachBtn);
|
||||
row.appendChild(fileInput);
|
||||
// row.appendChild(attachBtn);
|
||||
// row.appendChild(fileInput);
|
||||
|
||||
row.appendChild(deleteBtn);
|
||||
}
|
||||
// row.appendChild(deleteBtn);
|
||||
// }
|
||||
|
||||
rowContainer.appendChild(row);
|
||||
updateDeleteButtons();
|
||||
};
|
||||
// rowContainer.appendChild(row);
|
||||
// updateDeleteButtons();
|
||||
// };
|
||||
|
||||
const updateDeleteButtons = () => {
|
||||
const rows = Array.from(rowContainer.children);
|
||||
rows.forEach(row => {
|
||||
const btn = row.querySelector('button:last-child') as HTMLButtonElement;
|
||||
if (rows.length === 1) {
|
||||
btn.disabled = true;
|
||||
btn.style.visibility = 'hidden';
|
||||
} else {
|
||||
btn.disabled = false;
|
||||
btn.style.visibility = 'visible';
|
||||
}
|
||||
});
|
||||
};
|
||||
// const updateDeleteButtons = () => {
|
||||
// const rows = Array.from(rowContainer.children);
|
||||
// rows.forEach(row => {
|
||||
// const btn = row.querySelector('button:last-child') as HTMLButtonElement;
|
||||
// if (rows.length === 1) {
|
||||
// btn.disabled = true;
|
||||
// btn.style.visibility = 'hidden';
|
||||
// } else {
|
||||
// btn.disabled = false;
|
||||
// btn.style.visibility = 'visible';
|
||||
// }
|
||||
// });
|
||||
// };
|
||||
|
||||
createRow();
|
||||
addBtn.addEventListener('click', createRow);
|
||||
// createRow();
|
||||
// addBtn.addEventListener('click', createRow);
|
||||
|
||||
return {
|
||||
element: section,
|
||||
getData: () => {
|
||||
if (isRoleSection) {
|
||||
const data: Record<string, RoleDefinition> = {};
|
||||
for (const row of roleRowStates) {
|
||||
const key = row.roleNameInput.value.trim();
|
||||
if (!key) continue;
|
||||
data[key] = {
|
||||
members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
||||
storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
||||
validation_rules: row.validationRules
|
||||
};
|
||||
}
|
||||
return data;
|
||||
} else {
|
||||
const data: Record<string, string | fileBlob> = {};
|
||||
for (const row of nonRoleRowStates) {
|
||||
const key = row.keyInput.value.trim();
|
||||
if (!key) continue;
|
||||
if (row.fileBlob) {
|
||||
data[key] = row.fileBlob;
|
||||
} else {
|
||||
data[key] = row.valueInput.value.trim();
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
// return {
|
||||
// element: section,
|
||||
// getData: () => {
|
||||
// if (isRoleSection) {
|
||||
// const data: Record<string, RoleDefinition> = {};
|
||||
// for (const row of roleRowStates) {
|
||||
// const key = row.roleNameInput.value.trim();
|
||||
// if (!key) continue;
|
||||
// data[key] = {
|
||||
// members: row.membersInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
||||
// storages: row.storagesInput.value.split(',').map(x => x.trim()).filter(Boolean),
|
||||
// validation_rules: row.validationRules
|
||||
// };
|
||||
// }
|
||||
// return data;
|
||||
// } else {
|
||||
// const data: Record<string, string | fileBlob> = {};
|
||||
// for (const row of nonRoleRowStates) {
|
||||
// const key = row.keyInput.value.trim();
|
||||
// if (!key) continue;
|
||||
// if (row.fileBlob) {
|
||||
// data[key] = row.fileBlob;
|
||||
// } else {
|
||||
// data[key] = row.valueInput.value.trim();
|
||||
// }
|
||||
// }
|
||||
// return data;
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
|
||||
@ -1,91 +1,91 @@
|
||||
import { createKeyValueSection } from './key-value-section';
|
||||
import { loadValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal';
|
||||
import Services from '../../services/service';
|
||||
import { RoleDefinition } from '../../../pkg/sdk_client';
|
||||
// import { createKeyValueSection } from './key-value-section';
|
||||
// import { loadValidationRuleModal } from '../../components/validation-rule-modal/validation-rule-modal';
|
||||
// import Services from '../../services/service';
|
||||
// import { RoleDefinition } from '../../../pkg/sdk_client';
|
||||
|
||||
export async function getProcessCreation(container: HTMLElement) {
|
||||
await loadValidationRuleModal();
|
||||
// export async function getProcessCreation(container: HTMLElement) {
|
||||
// await loadValidationRuleModal();
|
||||
|
||||
container.style.display = 'block';
|
||||
container.innerHTML = `<div class="parameter-header">Process Creation</div>`;
|
||||
const privateSec = createKeyValueSection('Private Data', 'private-section');
|
||||
const publicSec = createKeyValueSection('Public Data', 'public-section');
|
||||
const rolesSec = createKeyValueSection('Roles', 'roles-section', true);
|
||||
// container.style.display = 'block';
|
||||
// container.innerHTML = `<div class="parameter-header">Process Creation</div>`;
|
||||
// const privateSec = createKeyValueSection('Private Data', 'private-section');
|
||||
// const publicSec = createKeyValueSection('Public Data', 'public-section');
|
||||
// const rolesSec = createKeyValueSection('Roles', 'roles-section', true);
|
||||
|
||||
container.appendChild(privateSec.element);
|
||||
container.appendChild(publicSec.element);
|
||||
container.appendChild(rolesSec.element);
|
||||
// container.appendChild(privateSec.element);
|
||||
// container.appendChild(publicSec.element);
|
||||
// container.appendChild(rolesSec.element);
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = 'Create Process';
|
||||
btn.style.cssText = `
|
||||
display: block;
|
||||
margin: 2rem auto 0;
|
||||
padding: 0.75rem 2rem;
|
||||
font-size: 1rem;
|
||||
font-weight: bold;
|
||||
background-color: #4f46e5;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0.5rem;
|
||||
cursor: pointer;
|
||||
`;
|
||||
// const btn = document.createElement('button');
|
||||
// btn.textContent = 'Create Process';
|
||||
// btn.style.cssText = `
|
||||
// display: block;
|
||||
// margin: 2rem auto 0;
|
||||
// padding: 0.75rem 2rem;
|
||||
// font-size: 1rem;
|
||||
// font-weight: bold;
|
||||
// background-color: #4f46e5;
|
||||
// color: white;
|
||||
// border: none;
|
||||
// border-radius: 0.5rem;
|
||||
// cursor: pointer;
|
||||
// `;
|
||||
|
||||
btn.onclick = async () => {
|
||||
const privateData = privateSec.getData();
|
||||
const publicData = publicSec.getData();
|
||||
const roles = rolesSec.getData() as Record<string, RoleDefinition>;
|
||||
// btn.onclick = async () => {
|
||||
// const privateData = privateSec.getData();
|
||||
// const publicData = publicSec.getData();
|
||||
// const roles = rolesSec.getData() as Record<string, RoleDefinition>;
|
||||
|
||||
console.log('Private:', privateData);
|
||||
console.log('Public:', publicData);
|
||||
console.log('Roles:', roles);
|
||||
// console.log('Private:', privateData);
|
||||
// console.log('Public:', publicData);
|
||||
// console.log('Roles:', roles);
|
||||
|
||||
const service = await Services.getInstance();
|
||||
// const service = await Services.getInstance();
|
||||
|
||||
const createProcessResult = await service.createProcess(privateData, publicData, roles);
|
||||
const processId = createProcessResult.updated_process!.process_id;
|
||||
const stateId = createProcessResult.updated_process!.current_process.states[0].state_id;
|
||||
await service.handleApiReturn(createProcessResult);
|
||||
// const createProcessResult = await service.createProcess(privateData, publicData, roles);
|
||||
// const processId = createProcessResult.updated_process!.process_id;
|
||||
// const stateId = createProcessResult.updated_process!.current_process.states[0].state_id;
|
||||
// await service.handleApiReturn(createProcessResult);
|
||||
|
||||
// Now we want to validate the update and register the first state of our new process
|
||||
const updateProcessResult = await service.createPrdUpdate(processId, stateId);
|
||||
await service.handleApiReturn(createProcessResult);
|
||||
// // Now we want to validate the update and register the first state of our new process
|
||||
// const updateProcessResult = await service.createPrdUpdate(processId, stateId);
|
||||
// await service.handleApiReturn(createProcessResult);
|
||||
|
||||
const approveChangeResult = await service.approveChange(processId, stateId);
|
||||
await service.handleApiReturn(approveChangeResult);
|
||||
if (approveChangeResult) {
|
||||
const process = await service.getProcess(processId);
|
||||
let newState = service.getStateFromId(process, stateId);
|
||||
if (!newState) return;
|
||||
for (const label of Object.keys(newState.keys)) {
|
||||
const hash = newState.pcd_commitment[label];
|
||||
const encryptedData = await service.getBlobFromDb(hash);
|
||||
const filename = `${label}-${hash.slice(0,8)}.bin`;
|
||||
// const approveChangeResult = await service.approveChange(processId, stateId);
|
||||
// await service.handleApiReturn(approveChangeResult);
|
||||
// if (approveChangeResult) {
|
||||
// const process = await service.getProcess(processId);
|
||||
// let newState = service.getStateFromId(process, stateId);
|
||||
// if (!newState) return;
|
||||
// for (const label of Object.keys(newState.keys)) {
|
||||
// const hash = newState.pcd_commitment[label];
|
||||
// const encryptedData = await service.getBlobFromDb(hash);
|
||||
// const filename = `${label}-${hash.slice(0,8)}.bin`;
|
||||
|
||||
const blob = new Blob([encryptedData], { type: "application/octet-stream" });
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = filename;
|
||||
link.click();
|
||||
// const blob = new Blob([encryptedData], { type: "application/octet-stream" });
|
||||
// const link = document.createElement("a");
|
||||
// link.href = URL.createObjectURL(blob);
|
||||
// link.download = filename;
|
||||
// link.click();
|
||||
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
}
|
||||
// setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
// }
|
||||
|
||||
await service.generateProcessPdf(processId, newState);
|
||||
// await service.generateProcessPdf(processId, newState);
|
||||
|
||||
// Add processId to the state we export
|
||||
newState['process_id'] = processId;
|
||||
const blob = new Blob([JSON.stringify(newState, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
// // Add processId to the state we export
|
||||
// newState['process_id'] = processId;
|
||||
// const blob = new Blob([JSON.stringify(newState, null, 2)], { type: 'application/json' });
|
||||
// const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `process_${processId}_${stateId}.json`;
|
||||
a.click();
|
||||
// const a = document.createElement('a');
|
||||
// a.href = url;
|
||||
// a.download = `process_${processId}_${stateId}.json`;
|
||||
// a.click();
|
||||
|
||||
URL.revokeObjectURL(url); // Clean up
|
||||
}
|
||||
};
|
||||
// URL.revokeObjectURL(url); // Clean up
|
||||
// }
|
||||
// };
|
||||
|
||||
container.appendChild(btn);
|
||||
}
|
||||
// container.appendChild(btn);
|
||||
// }
|
||||
|
||||
@ -1,66 +1,66 @@
|
||||
export function createProcessTab(container: HTMLElement, processes: { name: string, publicData: Record<string, any> }[]): HTMLElement {
|
||||
container.id = 'process-tab';
|
||||
container.style.display = 'block';
|
||||
container.style.cssText = 'padding: 1.5rem;';
|
||||
// export function createProcessTab(container: HTMLElement, processes: { name: string, publicData: Record<string, any> }[]): HTMLElement {
|
||||
// container.id = 'process-tab';
|
||||
// container.style.display = 'block';
|
||||
// container.style.cssText = 'padding: 1.5rem;';
|
||||
|
||||
const title = document.createElement('h2');
|
||||
title.textContent = 'Processes';
|
||||
title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;';
|
||||
container.appendChild(title);
|
||||
// const title = document.createElement('h2');
|
||||
// title.textContent = 'Processes';
|
||||
// title.style.cssText = 'font-size: 1.5rem; font-weight: bold; margin-bottom: 1rem;';
|
||||
// container.appendChild(title);
|
||||
|
||||
processes.forEach(proc => {
|
||||
const card = document.createElement('div');
|
||||
card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;';
|
||||
// processes.forEach(proc => {
|
||||
// const card = document.createElement('div');
|
||||
// card.style.cssText = 'margin-bottom: 1rem; padding: 1rem; border: 1px solid #ddd; border-radius: 0.5rem; background: #fff;';
|
||||
|
||||
const nameEl = document.createElement('h3');
|
||||
nameEl.textContent = proc.name;
|
||||
nameEl.style.cssText = 'font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem;';
|
||||
card.appendChild(nameEl);
|
||||
// const nameEl = document.createElement('h3');
|
||||
// nameEl.textContent = proc.name;
|
||||
// nameEl.style.cssText = 'font-size: 1.2rem; font-weight: bold; margin-bottom: 0.5rem;';
|
||||
// card.appendChild(nameEl);
|
||||
|
||||
const dataList = document.createElement('div');
|
||||
for (const [key, value] of Object.entries(proc.publicData)) {
|
||||
const item = document.createElement('div');
|
||||
item.style.cssText = 'margin-bottom: 0.5rem;';
|
||||
// const dataList = document.createElement('div');
|
||||
// for (const [key, value] of Object.entries(proc.publicData)) {
|
||||
// const item = document.createElement('div');
|
||||
// item.style.cssText = 'margin-bottom: 0.5rem;';
|
||||
|
||||
const label = document.createElement('strong');
|
||||
label.textContent = key + ': ';
|
||||
item.appendChild(label);
|
||||
// const label = document.createElement('strong');
|
||||
// label.textContent = key + ': ';
|
||||
// item.appendChild(label);
|
||||
|
||||
// Let's trim the quotes
|
||||
const trimmed = value.replace(/^'|'$/g, '');
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch (_) {
|
||||
parsed = trimmed;
|
||||
}
|
||||
// // Let's trim the quotes
|
||||
// const trimmed = value.replace(/^'|'$/g, '');
|
||||
// let parsed;
|
||||
// try {
|
||||
// parsed = JSON.parse(trimmed);
|
||||
// } catch (_) {
|
||||
// parsed = trimmed;
|
||||
// }
|
||||
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
const saveBtn = document.createElement('button');
|
||||
saveBtn.textContent = '💾 Save as JSON';
|
||||
saveBtn.style.cssText = 'margin-left: 0.5rem; padding: 0.25rem 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
saveBtn.onclick = () => {
|
||||
const blob = new Blob([JSON.stringify(parsed, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${proc.name}_${key}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
item.appendChild(saveBtn);
|
||||
} else {
|
||||
const span = document.createElement('span');
|
||||
span.textContent = String(parsed);
|
||||
item.appendChild(span);
|
||||
}
|
||||
// if (parsed && typeof parsed === 'object') {
|
||||
// const saveBtn = document.createElement('button');
|
||||
// saveBtn.textContent = '💾 Save as JSON';
|
||||
// saveBtn.style.cssText = 'margin-left: 0.5rem; padding: 0.25rem 0.5rem; border: 1px solid #ccc; border-radius: 0.375rem; background: #f0f0f0; cursor: pointer;';
|
||||
// saveBtn.onclick = () => {
|
||||
// const blob = new Blob([JSON.stringify(parsed, null, 2)], { type: 'application/json' });
|
||||
// const url = URL.createObjectURL(blob);
|
||||
// const a = document.createElement('a');
|
||||
// a.href = url;
|
||||
// a.download = `${proc.name}_${key}.json`;
|
||||
// a.click();
|
||||
// URL.revokeObjectURL(url);
|
||||
// };
|
||||
// item.appendChild(saveBtn);
|
||||
// } else {
|
||||
// const span = document.createElement('span');
|
||||
// span.textContent = String(parsed);
|
||||
// item.appendChild(span);
|
||||
// }
|
||||
|
||||
dataList.appendChild(item);
|
||||
}
|
||||
// dataList.appendChild(item);
|
||||
// }
|
||||
|
||||
card.appendChild(dataList);
|
||||
container.appendChild(card);
|
||||
});
|
||||
// card.appendChild(dataList);
|
||||
// container.appendChild(card);
|
||||
// });
|
||||
|
||||
return container;
|
||||
}
|
||||
// return container;
|
||||
// }
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// src/pages/home/home-component.ts
|
||||
|
||||
import loginHtml from './home.html?raw';
|
||||
import loginScript from './home.ts?raw';
|
||||
import loginCss from '../../4nk.css?raw';
|
||||
import { initHomePage } from './home';
|
||||
|
||||
@ -11,11 +12,26 @@ export class LoginComponent extends HTMLElement {
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
console.log('CALLBACK LOGIN PAGE');
|
||||
this.render();
|
||||
setTimeout(() => {
|
||||
initHomePage();
|
||||
}, 500);
|
||||
|
||||
try {
|
||||
if (this.shadowRoot) {
|
||||
initHomePage(this.shadowRoot);
|
||||
} else {
|
||||
console.error("[LoginComponent] 💥 ShadowRoot est nul. Impossible d'initialiser.");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[LoginComponent] 💥 Échec de l'initHomePage:", e);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.shadowRoot) {
|
||||
this.shadowRoot.innerHTML = `
|
||||
<style>${loginCss}</style>
|
||||
${loginHtml}
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
set callback(fn) {
|
||||
@ -25,23 +41,9 @@ export class LoginComponent extends HTMLElement {
|
||||
console.error('Callback is not a function');
|
||||
}
|
||||
}
|
||||
|
||||
get callback() {
|
||||
return this._callback;
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.shadowRoot)
|
||||
this.shadowRoot.innerHTML = `
|
||||
<style>
|
||||
${loginCss}
|
||||
</style>${loginHtml}
|
||||
<script type="module">
|
||||
${loginScript}
|
||||
</scipt>
|
||||
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!customElements.get('login-4nk-component')) {
|
||||
|
||||
@ -13,9 +13,6 @@
|
||||
<div id="tab1" class="card tab-content active">
|
||||
<div class="card-description">Create an account :</div>
|
||||
<div class="pairing-request"></div>
|
||||
<!-- <div class="card-image qr-code">
|
||||
<img src="assets/qr_code.png" alt="QR Code" width="150" height="150" />
|
||||
</div> -->
|
||||
<button id="createButton" class="create-btn"></button>
|
||||
</div>
|
||||
<div class="separator"></div>
|
||||
@ -23,18 +20,14 @@
|
||||
<div class="card-description">Add a device for an existing member :</div>
|
||||
<div class="card-image camera-card">
|
||||
<img id="scanner" src="assets/camera.jpg" alt="QR Code" width="150" height="150" />
|
||||
<button id="scan-btn" onclick="scanDevice()">Scan</button>
|
||||
<div class="qr-code-scanner">
|
||||
<button id="scan-btn" onclick="scanDevice()">Scan</button> <div class="qr-code-scanner">
|
||||
<div id="qr-reader" style="width: 200px; display: contents"></div>
|
||||
<div id="qr-reader-results"></div>
|
||||
</div>
|
||||
</div>
|
||||
<p>Or</p>
|
||||
<!-- <input type="text" id="addressInput" placeholder="Paste address" />
|
||||
<div id="emoji-display-2"></div> -->
|
||||
<div class="card-description">Chose a member :</div>
|
||||
<select name="memberSelect" id="memberSelect" size="5" class="custom-select">
|
||||
<!-- Options -->
|
||||
</select>
|
||||
|
||||
<button id="okButton" style="display: none">OK</button>
|
||||
|
||||
@ -1,20 +1,30 @@
|
||||
// src/pages/home/home.ts
|
||||
|
||||
import Routing from '../../services/modal.service';
|
||||
import Services from '../../services/service';
|
||||
import { addSubscription } from '../../utils/subscription.utils';
|
||||
import { displayEmojis, generateQRCode, generateCreateBtn, addressToEmoji } from '../../utils/sp-address.utils';
|
||||
import { getCorrectDOM } from '../../utils/html.utils';
|
||||
import QrScannerComponent from '../../components/qrcode-scanner/qrcode-scanner-component';
|
||||
import { navigate, registerAllListeners } from '../../router';
|
||||
|
||||
export { QrScannerComponent };
|
||||
export async function initHomePage(): Promise<void> {
|
||||
console.log('INIT-HOME');
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
container.querySelectorAll('.tab').forEach((tab) => {
|
||||
|
||||
/**
|
||||
* Fonction d'initialisation principale.
|
||||
* Elle est appelée par home-component.ts et reçoit le ShadowRoot.
|
||||
*/
|
||||
export async function initHomePage(container: ShadowRoot): Promise<void> {
|
||||
|
||||
if (!container) {
|
||||
console.error('[home.ts] 💥 ERREUR: Le shadowRoot est nul !');
|
||||
return;
|
||||
}
|
||||
|
||||
const tabs = container.querySelectorAll('.tab');
|
||||
|
||||
tabs.forEach((tab) => {
|
||||
addSubscription(tab, 'click', () => {
|
||||
container.querySelectorAll('.tab').forEach((t) => t.classList.remove('active'));
|
||||
tab.classList.add('active');
|
||||
|
||||
container.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active'));
|
||||
container.querySelector(`#${tab.getAttribute('data-tab') as string}`)?.classList.add('active');
|
||||
});
|
||||
@ -22,41 +32,21 @@ export async function initHomePage(): Promise<void> {
|
||||
|
||||
const service = await Services.getInstance();
|
||||
const spAddress = await service.getDeviceAddress();
|
||||
// generateQRCode(spAddress);
|
||||
generateCreateBtn();
|
||||
displayEmojis(spAddress);
|
||||
|
||||
// Add this line to populate the select when the page loads
|
||||
await populateMemberSelect();
|
||||
await populateMemberSelect(container);
|
||||
}
|
||||
|
||||
//// Modal
|
||||
export async function openModal(myAddress: string, receiverAddress: string) {
|
||||
const router = await Routing.getInstance();
|
||||
router.openLoginModal(myAddress, receiverAddress);
|
||||
}
|
||||
|
||||
// const service = await Services.getInstance()
|
||||
// service.setNotification()
|
||||
|
||||
function scanDevice() {
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
const scannerImg = container.querySelector('#scanner') as HTMLElement;
|
||||
if (scannerImg) scannerImg.style.display = 'none';
|
||||
const scannerQrCode = container.querySelector('.qr-code-scanner') as HTMLElement;
|
||||
if (scannerQrCode) scannerQrCode.style.display = 'block';
|
||||
const scanButton = container?.querySelector('#scan-btn') as HTMLElement;
|
||||
if (scanButton) scanButton.style.display = 'none';
|
||||
const reader = container?.querySelector('#qr-reader');
|
||||
if (reader) reader.innerHTML = '<qr-scanner></qr-scanner>';
|
||||
}
|
||||
|
||||
async function populateMemberSelect() {
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
/**
|
||||
* Remplit le <select> des membres.
|
||||
* Doit utiliser le 'container' (ShadowRoot) pour trouver l'élément.
|
||||
*/
|
||||
async function populateMemberSelect(container: ShadowRoot) {
|
||||
const memberSelect = container.querySelector('#memberSelect') as HTMLSelectElement;
|
||||
|
||||
if (!memberSelect) {
|
||||
console.error('Could not find memberSelect element');
|
||||
console.error('[home.ts] Impossible de trouver #memberSelect dans le shadowRoot.');
|
||||
return;
|
||||
}
|
||||
|
||||
@ -65,8 +55,7 @@ async function populateMemberSelect() {
|
||||
|
||||
for (const [processId, member] of Object.entries(members)) {
|
||||
const process = await service.getProcess(processId);
|
||||
let memberPublicName;
|
||||
|
||||
let memberPublicName = 'Unnamed Member';
|
||||
if (process) {
|
||||
const publicMemberData = service.getPublicData(process);
|
||||
if (publicMemberData) {
|
||||
@ -77,11 +66,6 @@ async function populateMemberSelect() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!memberPublicName) {
|
||||
memberPublicName = 'Unnamed Member';
|
||||
}
|
||||
|
||||
// Récupérer les emojis pour ce processId
|
||||
const emojis = await addressToEmoji(processId);
|
||||
|
||||
const option = document.createElement('option');
|
||||
@ -91,6 +75,32 @@ async function populateMemberSelect() {
|
||||
}
|
||||
}
|
||||
|
||||
(window as any).populateMemberSelect = populateMemberSelect;
|
||||
/**
|
||||
* Fonction appelée par le 'onclick="scanDevice()"' dans le HTML.
|
||||
* Doit être attachée à 'window' pour être globale.
|
||||
*/
|
||||
function scanDevice() {
|
||||
const hostElement = document.querySelector('login-4nk-component');
|
||||
const container = hostElement?.shadowRoot;
|
||||
|
||||
if (!container) {
|
||||
console.error('[home.ts] scanDevice: Impossible de trouver le shadowRoot !');
|
||||
return;
|
||||
}
|
||||
|
||||
const scannerImg = container.querySelector('#scanner') as HTMLElement;
|
||||
if (scannerImg) scannerImg.style.display = 'none';
|
||||
const scannerQrCode = container.querySelector('.qr-code-scanner') as HTMLElement;
|
||||
if (scannerQrCode) scannerQrCode.style.display = 'block';
|
||||
const scanButton = container.querySelector('#scan-btn') as HTMLElement;
|
||||
if (scanButton) scanButton.style.display = 'none';
|
||||
const reader = container.querySelector('#qr-reader');
|
||||
if (reader) reader.innerHTML = '<qr-scanner></qr-scanner>';
|
||||
}
|
||||
|
||||
(window as any).scanDevice = scanDevice;
|
||||
|
||||
export async function openModal(myAddress: string, receiverAddress: string) {
|
||||
const router = await Routing.getInstance();
|
||||
router.openLoginModal(myAddress, receiverAddress);
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import processHtml from './process-element.html?raw';
|
||||
import processScript from './process-element.ts?raw';
|
||||
import processCss from '../../4nk.css?raw';
|
||||
import { initProcessElement } from './process-element';
|
||||
// src/pages/process-element/process-component.ts
|
||||
|
||||
export class ProcessListComponent extends HTMLElement {
|
||||
import processHtml from './process-element.html?raw';
|
||||
import processCss from '../../4nk.css?raw';
|
||||
import { initProcessElement } from './process-element'; // On importe la vraie fonction
|
||||
|
||||
// 1. Nom de classe corrigé (plus logique)
|
||||
export class ProcessElementComponent extends HTMLElement {
|
||||
_callback: any;
|
||||
id: string = '';
|
||||
zone: string = '';
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@ -14,38 +14,61 @@ export class ProcessListComponent extends HTMLElement {
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
console.log('CALLBACK PROCESS LIST PAGE');
|
||||
console.log('[ProcessElementComponent] 1. Composant connecté.');
|
||||
|
||||
// 2. Lire les attributs passés par le routeur (router.ts)
|
||||
const processId = this.getAttribute('process-id');
|
||||
const stateId = this.getAttribute('state-id');
|
||||
|
||||
if (!processId || !stateId) {
|
||||
console.error("💥 ProcessElementComponent a été créé sans 'process-id' ou 'state-id'.");
|
||||
this.renderError("Erreur: ID de processus ou d'état manquant.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Afficher le HTML/CSS du squelette
|
||||
this.render();
|
||||
setTimeout(() => {
|
||||
initProcessElement(this.id, this.zone);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
set callback(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
this._callback = fn;
|
||||
// 4. Appeler la logique (init) en lui passant le shadowRoot et les IDs
|
||||
try {
|
||||
if (this.shadowRoot) {
|
||||
console.log(`[ProcessElementComponent] 2. Appel de initProcessElement pour ${processId}_${stateId}`);
|
||||
initProcessElement(this.shadowRoot, processId, stateId);
|
||||
} else {
|
||||
console.error('Callback is not a function');
|
||||
console.error("[ProcessElementComponent] 💥 ShadowRoot est nul.");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[ProcessElementComponent] 💥 Échec de l'initProcessElement():", e);
|
||||
}
|
||||
|
||||
get callback() {
|
||||
return this._callback;
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.shadowRoot)
|
||||
if (this.shadowRoot) {
|
||||
this.shadowRoot.innerHTML = `
|
||||
<style>
|
||||
${processCss}
|
||||
</style>${processHtml}
|
||||
<script type="module">
|
||||
${processScript}
|
||||
</scipt>
|
||||
<style>${processCss}</style>
|
||||
${processHtml}
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!customElements.get('process-4nk-component')) {
|
||||
customElements.define('process-4nk-component', ProcessListComponent);
|
||||
renderError(message: string) {
|
||||
if (this.shadowRoot) {
|
||||
this.shadowRoot.innerHTML = `<style>${processCss}</style>
|
||||
<div class="title-container"><h1>Erreur</h1></div>
|
||||
<div class="process-container"><p>${message}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ... (Tes callbacks) ...
|
||||
set callback(fn) {
|
||||
if (typeof fn === 'function') { this._callback = fn; }
|
||||
else { console.error('Callback is not a function'); }
|
||||
}
|
||||
get callback() { return this._callback; }
|
||||
}
|
||||
|
||||
// 6. Utilisation du bon nom de classe
|
||||
if (!customElements.get('process-4nk-component')) {
|
||||
console.log('[ProcessElementComponent] Définition de <process-4nk-component>.');
|
||||
customElements.define('process-4nk-component', ProcessElementComponent);
|
||||
}
|
||||
@ -1,50 +1,111 @@
|
||||
// src/pages/process-element/process-element.ts
|
||||
|
||||
import { interpolate } from '../../utils/html.utils';
|
||||
import Services from '../../services/service';
|
||||
import { Process } from 'pkg/sdk_client';
|
||||
import { getCorrectDOM } from '~/utils/document.utils';
|
||||
import { Process, ProcessState } from 'pkg/sdk_client';
|
||||
// 1. Plus besoin de 'getCorrectDOM'
|
||||
|
||||
let currentPageStyle: HTMLStyleElement | null = null;
|
||||
/**
|
||||
* Fonction d'initialisation, appelée par process-component.ts
|
||||
* Reçoit le shadowRoot et les IDs.
|
||||
*/
|
||||
export async function initProcessElement(container: ShadowRoot, processId: string, stateId: string) {
|
||||
console.log(`[process-element.ts] 3. init() appelé pour ${processId}_${stateId}`);
|
||||
|
||||
export async function initProcessElement(id: string, zone: string) {
|
||||
const processes = await getProcesses();
|
||||
const container = getCorrectDOM('process-4nk-component');
|
||||
// const currentProcess = processes.find((process) => process[0] === id)[1];
|
||||
// const currentProcess = {title: 'Hello', html: '', css: ''};
|
||||
// await loadPage({ processTitle: currentProcess.title, inputValue: 'Hello World !' });
|
||||
// const wrapper = document.querySelector('.process-container');
|
||||
// if (wrapper) {
|
||||
// wrapper.innerHTML = interpolate(currentProcess.html, { processTitle: currentProcess.title, inputValue: 'Hello World !' });
|
||||
// injectCss(currentProcess.css);
|
||||
// }
|
||||
const services = await Services.getInstance();
|
||||
|
||||
// 2. Récupérer les éléments du DOM *dans* le shadowRoot (container)
|
||||
const titleH1 = container.querySelector('h1');
|
||||
const processContainer = container.querySelector('.process-container');
|
||||
|
||||
if (!titleH1 || !processContainer) {
|
||||
console.error("[process-element.ts] 💥 Le HTML de base (h1 ou .process-container) est introuvable !");
|
||||
return;
|
||||
}
|
||||
|
||||
async function loadPage(data?: any) {
|
||||
const content = document.getElementById('containerId');
|
||||
if (content && data) {
|
||||
if (data) {
|
||||
content.innerHTML = interpolate(content.innerHTML, data);
|
||||
// 3. Récupérer les données
|
||||
const process = await services.getProcess(processId);
|
||||
if (!process) {
|
||||
console.error(`[process-element.ts] 💥 Processus ${processId} non trouvé !`);
|
||||
titleH1.innerText = "Erreur";
|
||||
processContainer.innerHTML = `<p>Le processus ${processId} n'a pas pu être chargé.</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const state = services.getStateFromId(process, stateId);
|
||||
if (!state) {
|
||||
console.error(`[process-element.ts] 💥 État ${stateId} non trouvé dans le processus ${processId} !`);
|
||||
titleH1.innerText = "Erreur";
|
||||
processContainer.innerHTML = `<p>L'état ${stateId} n'a pas pu être chargé.</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[process-element.ts] ✅ Processus et État chargés.");
|
||||
|
||||
// 4. Mettre à jour le titre
|
||||
const processName = services.getProcessName(process) || "Processus";
|
||||
titleH1.innerHTML = interpolate(titleH1.innerHTML, { processTitle: processName });
|
||||
|
||||
// 5. Logique de rendu de l'élément (À COMPLÉTER PAR TES SOINS)
|
||||
// C'est là que tu dois construire le HTML pour cet état spécifique
|
||||
// Par exemple, déchiffrer les attributs et les afficher.
|
||||
processContainer.innerHTML = `
|
||||
<div class="card" style="margin: 1rem; padding: 1rem;">
|
||||
<h3>État: ${stateId.substring(0, 10)}...</h3>
|
||||
<p>Commit: ${state.commited_in}</p>
|
||||
<div id="attributes-list">
|
||||
<p><em>Chargement des attributs...</em></p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 6. Tenter de déchiffrer les données de cet état
|
||||
await decryptAndDisplayAttributes(services, container, processId, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper (exemple) pour déchiffrer et afficher les données dans le conteneur
|
||||
*/
|
||||
async function decryptAndDisplayAttributes(services: Services, container: ShadowRoot, processId: string, state: ProcessState) {
|
||||
const attributesList = container.querySelector('#attributes-list');
|
||||
if (!attributesList) return;
|
||||
|
||||
console.log(`[process-element.ts] 🔐 Déchiffrement des attributs pour l'état ${state.state_id}...`);
|
||||
attributesList.innerHTML = ''; // Vide le message "Chargement..."
|
||||
let hasPrivateData = false;
|
||||
|
||||
// Affiche les données publiques
|
||||
if (state.public_data) {
|
||||
for (const [key, value] of Object.entries(state.public_data)) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'attribute-pair public';
|
||||
el.innerHTML = `<strong>${key} (public):</strong> ${JSON.stringify(services.decodeValue(value))}`;
|
||||
attributesList.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
function injectCss(cssContent: string) {
|
||||
removeCss(); // Ensure that the previous CSS is removed
|
||||
|
||||
currentPageStyle = document.createElement('style');
|
||||
currentPageStyle.type = 'text/css';
|
||||
currentPageStyle.appendChild(document.createTextNode(cssContent));
|
||||
document.head.appendChild(currentPageStyle);
|
||||
// Affiche les données privées
|
||||
for (const attribute of Object.keys(state.pcd_commitment)) {
|
||||
if (attribute === 'roles' || (state.public_data && state.public_data[attribute])) {
|
||||
continue; // Skip les données publiques (déjà fait) et les rôles
|
||||
}
|
||||
|
||||
function removeCss() {
|
||||
if (currentPageStyle) {
|
||||
document.head.removeChild(currentPageStyle);
|
||||
currentPageStyle = null;
|
||||
const decryptedValue = await services.decryptAttribute(processId, state, attribute);
|
||||
|
||||
const el = document.createElement('div');
|
||||
el.className = 'attribute-pair private';
|
||||
|
||||
if (decryptedValue) {
|
||||
hasPrivateData = true;
|
||||
el.innerHTML = `<strong>${attribute} (privé):</strong> ${JSON.stringify(decryptedValue)}`;
|
||||
} else {
|
||||
el.innerHTML = `<strong>${attribute} (privé):</strong> <span style="color: red;">[Déchiffrement impossible / Clé manquante]</span>`;
|
||||
}
|
||||
attributesList.appendChild(el);
|
||||
}
|
||||
|
||||
async function getProcesses(): Promise<Record<string, Process>> {
|
||||
const service = await Services.getInstance();
|
||||
const processes = await service.getProcesses();
|
||||
return processes;
|
||||
if (!hasPrivateData && !(state.public_data && Object.keys(state.public_data).length > 0)) {
|
||||
console.log("[process-element.ts] ℹ️ Aucun attribut (public ou privé) trouvé pour cet état.");
|
||||
attributesList.innerHTML = '<p>Cet état ne contient aucun attribut visible.</p>';
|
||||
}
|
||||
}
|
||||
@ -1,49 +1,40 @@
|
||||
// import processHtml from './process.html?raw';
|
||||
// import processScript from './process.ts?raw';
|
||||
// import processCss from '../../4nk.css?raw';
|
||||
// import { init } from './process';
|
||||
// src/pages/process/process-list-component.ts
|
||||
|
||||
// export class ProcessListComponent extends HTMLElement {
|
||||
// _callback: any;
|
||||
// constructor() {
|
||||
// super();
|
||||
// this.attachShadow({ mode: 'open' });
|
||||
// }
|
||||
import processHtml from './process.html?raw';
|
||||
import processCss from '../../4nk.css?raw';
|
||||
import { init } from './process';
|
||||
|
||||
// connectedCallback() {
|
||||
// console.log('CALLBACK PROCESS LIST PAGE');
|
||||
// this.render();
|
||||
// setTimeout(() => {
|
||||
// init();
|
||||
// }, 500);
|
||||
// }
|
||||
export class ProcessListComponent extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.attachShadow({ mode: 'open' });
|
||||
}
|
||||
|
||||
// set callback(fn) {
|
||||
// if (typeof fn === 'function') {
|
||||
// this._callback = fn;
|
||||
// } else {
|
||||
// console.error('Callback is not a function');
|
||||
// }
|
||||
// }
|
||||
connectedCallback() {
|
||||
this.render();
|
||||
|
||||
// get callback() {
|
||||
// return this._callback;
|
||||
// }
|
||||
try {
|
||||
if (this.shadowRoot) {
|
||||
init(this.shadowRoot);
|
||||
} else {
|
||||
console.error('[ProcessListComponent] 💥 ShadowRoot est nul.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[ProcessListComponent] 💥 Échec de l'init():", e);
|
||||
}
|
||||
}
|
||||
|
||||
// render() {
|
||||
// if (this.shadowRoot)
|
||||
// this.shadowRoot.innerHTML = `
|
||||
// <style>
|
||||
// ${processCss}
|
||||
// </style>${processHtml}
|
||||
// <script type="module">
|
||||
// ${processScript}
|
||||
// </scipt>
|
||||
render() {
|
||||
if (this.shadowRoot) {
|
||||
this.shadowRoot.innerHTML = `
|
||||
<style>${processCss}</style>
|
||||
${processHtml}
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// `;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
// if (!customElements.get('process-list-4nk-component')) {
|
||||
// customElements.define('process-list-4nk-component', ProcessListComponent);
|
||||
// }
|
||||
if (!customElements.get('process-list-4nk-component')) {
|
||||
customElements.define('process-list-4nk-component', ProcessListComponent);
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
<!-- <div class="title-container">
|
||||
<div class="title-container">
|
||||
<h1>Process Selection</h1>
|
||||
</div>
|
||||
|
||||
@ -7,13 +7,17 @@
|
||||
<div class="process-card-description">
|
||||
<div class="input-container">
|
||||
<select multiple data-multi-select-plugin id="autocomplete" placeholder="Filter processes..." class="select-field"></select>
|
||||
|
||||
<label for="autocomplete" class="input-label">Filter processes :</label>
|
||||
|
||||
<div class="selected-processes"></div>
|
||||
</div>
|
||||
|
||||
<div class="process-card-content"></div>
|
||||
</div>
|
||||
|
||||
<div class="process-card-action">
|
||||
<a class="btn" onclick="goToProcessPage()">OK</a>
|
||||
<a class="btn" id="go-to-process-btn">OK</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div> -->
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,5 +1,5 @@
|
||||
import { SignatureElement } from './signature';
|
||||
import signatureCss from '../../../public/style/signature.css?raw'
|
||||
import signatureCss from '../../../style/signature.css?raw'
|
||||
import Services from '../../services/service.js'
|
||||
|
||||
class SignatureComponent extends HTMLElement {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import signatureStyle from '../../../public/style/signature.css?inline';
|
||||
import signatureStyle from '../../../style/signature.css?inline';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
|
||||
718
src/router.ts
718
src/router.ts
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -3,16 +3,31 @@ import axios, { AxiosResponse } from 'axios';
|
||||
export async function storeData(servers: string[], key: string, value: Blob, ttl: number | null): Promise<AxiosResponse | null> {
|
||||
for (const server of servers) {
|
||||
try {
|
||||
// Handle relative paths (for development proxy) vs absolute URLs (for production)
|
||||
// --- DÉBUT DE LA CORRECTION ---
|
||||
// 1. On vérifie d'abord si la donnée existe en appelant le bon service
|
||||
// On passe 'server' au lieu de 'url' pour que testData construise la bonne URL
|
||||
const dataExists = await testData(server, key);
|
||||
|
||||
if (dataExists) {
|
||||
console.log('Data already stored:', key);
|
||||
continue;
|
||||
} else {
|
||||
console.log('Data not stored for server, proceeding to POST:', key, server);
|
||||
}
|
||||
// --- FIN DE LA CORRECTION ---
|
||||
|
||||
|
||||
// Construction de l'URL pour le POST (stockage)
|
||||
// Cette partie était correcte
|
||||
let url: string;
|
||||
if (server.startsWith('/')) {
|
||||
// Relative path - construct manually for proxy
|
||||
// Relative path
|
||||
url = `${server}/store/${encodeURIComponent(key)}`;
|
||||
if (ttl !== null) {
|
||||
url += `?ttl=${ttl}`;
|
||||
}
|
||||
} else {
|
||||
// Absolute URL - use URL constructor
|
||||
// Absolute URL
|
||||
const urlObj = new URL(`${server}/store/${encodeURIComponent(key)}`);
|
||||
if (ttl !== null) {
|
||||
urlObj.searchParams.append('ttl', ttl.toString());
|
||||
@ -20,17 +35,11 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
|
||||
url = urlObj.toString();
|
||||
}
|
||||
|
||||
// Test first that data is not already stored
|
||||
const testResponse = await testData(url, key);
|
||||
if (testResponse) {
|
||||
console.log('Data already stored:', key);
|
||||
continue;
|
||||
} else {
|
||||
console.log('Data not stored for server:', key, server);
|
||||
}
|
||||
// La ligne ci-dessous a été supprimée car le test est fait au-dessus
|
||||
// const testResponse = await testData(url, key); // <-- LIGNE BOGUÉE SUPPRIMÉE
|
||||
|
||||
// Send the encrypted ArrayBuffer as the raw request body.
|
||||
const response = await axios.post(url, value, {
|
||||
// Send the encrypted data as the raw request body.
|
||||
const response = await axios.post(url, value, { // Note: c'est bien un POST sur 'url'
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
},
|
||||
@ -43,7 +52,7 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.status === 409) {
|
||||
return null;
|
||||
return null; // 409 Conflict (Key already exists)
|
||||
}
|
||||
console.error('Error storing data:', error);
|
||||
}
|
||||
@ -51,22 +60,21 @@ export async function storeData(servers: string[], key: string, value: Blob, ttl
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fonction retrieveData (inchangée, elle était correcte)
|
||||
export async function retrieveData(servers: string[], key: string): Promise<ArrayBuffer | null> {
|
||||
for (const server of servers) {
|
||||
try {
|
||||
// Handle relative paths (for development proxy) vs absolute URLs (for production)
|
||||
const url = server.startsWith('/')
|
||||
? `${server}/retrieve/${key}` // Relative path - use as-is for proxy
|
||||
: new URL(`${server}/retrieve/${key}`).toString(); // Absolute URL - construct properly
|
||||
? `${server}/retrieve/${key}`
|
||||
: new URL(`${server}/retrieve/${key}`).toString();
|
||||
|
||||
console.log('Retrieving data', key,' from:', url);
|
||||
// When fetching the data from the server:
|
||||
|
||||
const response = await axios.get(url, {
|
||||
responseType: 'arraybuffer'
|
||||
});
|
||||
|
||||
if (response.status === 200) {
|
||||
// Validate that we received an ArrayBuffer
|
||||
if (response.data instanceof ArrayBuffer) {
|
||||
return response.data;
|
||||
} else {
|
||||
@ -80,8 +88,9 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
if (error.response?.status === 404) {
|
||||
// C'est normal si la donnée n'existe pas
|
||||
console.log(`Data not found on server ${server} for key ${key}`);
|
||||
continue; // Try next server
|
||||
continue;
|
||||
} else if (error.response?.status) {
|
||||
console.error(`Server ${server} error ${error.response.status}:`, error.response.statusText);
|
||||
continue;
|
||||
@ -103,17 +112,27 @@ interface TestResponse {
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
export async function testData(url: string, key: string): Promise<boolean | null> {
|
||||
// --- FONCTION testData CORRIGÉE ---
|
||||
// Elle prend 'server' au lieu de 'url' et construit sa propre URL '/test/...'
|
||||
export async function testData(server: string, key: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await axios.get(url);
|
||||
if (response.status !== 200) {
|
||||
console.error(`Test response status: ${response.status}`);
|
||||
// Construit l'URL /test/...
|
||||
const testUrl = server.startsWith('/')
|
||||
? `${server}/test/${encodeURIComponent(key)}`
|
||||
: new URL(`${server}/test/${encodeURIComponent(key)}`).toString();
|
||||
|
||||
const response = await axios.get(testUrl); // Fait un GET sur /test/...
|
||||
|
||||
// 200 OK = la donnée existe
|
||||
return response.status === 200;
|
||||
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.status === 404) {
|
||||
// 404 Not Found = la donnée n'existe pas. C'est une réponse valide.
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
// Toute autre erreur (serveur offline, 500, etc.)
|
||||
console.error('Error testing data:', error);
|
||||
return null;
|
||||
return false; // On considère que le test a échoué
|
||||
}
|
||||
}
|
||||
@ -100,7 +100,7 @@ export async function displayEmojis(text: string) {
|
||||
|
||||
// Verify Other address
|
||||
export function initAddressInput() {
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
||||
const emojiDisplay = container.querySelector('#emoji-display-2');
|
||||
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
||||
@ -164,17 +164,14 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
||||
|
||||
try {
|
||||
const relayAddress = service.getAllRelays();
|
||||
const createPairingProcessReturn = await service.createPairingProcess(
|
||||
"",
|
||||
[],
|
||||
);
|
||||
const createPairingProcessReturn = await service.createPairingProcess('', []);
|
||||
|
||||
if (!createPairingProcessReturn.updated_process) {
|
||||
throw new Error('createPairingProcess returned an empty new process');
|
||||
}
|
||||
|
||||
try {
|
||||
await service.checkConnections(createPairingProcessReturn.updated_process.current_process, createPairingProcessReturn.updated_process.current_process.states[0].state_id);
|
||||
await service.ensureConnections(createPairingProcessReturn.updated_process.current_process, createPairingProcessReturn.updated_process.current_process.states[0].state_id);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
@ -194,7 +191,6 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
||||
}
|
||||
|
||||
await service.handleApiReturn(createPairingProcessReturn);
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
@ -202,7 +198,7 @@ export async function prepareAndSendPairingTx(): Promise<void> {
|
||||
|
||||
export async function generateQRCode(spAddress: string) {
|
||||
try {
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
const currentUrl = 'https://' + window.location.host;
|
||||
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
||||
const qrCode = container?.querySelector('.qr-code img');
|
||||
@ -215,7 +211,7 @@ export async function generateQRCode(spAddress: string) {
|
||||
export async function generateCreateBtn() {
|
||||
try {
|
||||
// Generate CreateBtn
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
const createBtn = container?.querySelector('.create-btn');
|
||||
if (createBtn) {
|
||||
createBtn.textContent = 'CREATE';
|
||||
@ -223,5 +219,4 @@ export async function generateCreateBtn() {
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
}
|
||||
@ -5,6 +5,10 @@ import {createHtmlPlugin} from 'vite-plugin-html';
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
// import pluginTerminal from 'vite-plugin-terminal';
|
||||
|
||||
export default defineConfig({
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user