Compare commits
No commits in common. "create-account" and "test" have entirely different histories.
create-acc
...
test
@ -5,7 +5,7 @@
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build_wasm": "wasm-pack build --out-dir ../ihm_client_dev1/pkg ../sdk_client --target bundler --dev",
|
||||
"build_wasm": "wasm-pack build --out-dir ../ihm_client/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/",
|
||||
|
@ -599,7 +599,7 @@ body {
|
||||
margin-top: 9vh;
|
||||
margin-left: -1%;
|
||||
text-align: left;
|
||||
width: 100vw;
|
||||
width: 209vh;
|
||||
}
|
||||
|
||||
/* Liste des information sur l'account */
|
||||
@ -1364,62 +1364,3 @@ body {
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
}
|
||||
|
||||
/* ---------------------Style pour le QR code--------------------- */
|
||||
|
||||
.qr-code {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.qr-code:hover {
|
||||
transform: scale(1.5);
|
||||
}
|
||||
|
||||
.qr-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.qr-modal-content {
|
||||
background-color: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.close-qr-modal {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 5px;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.close-qr-modal:hover {
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.qr-code-large {
|
||||
max-width: 300px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.qr-address {
|
||||
margin-top: 10px;
|
||||
word-break: break-all;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
@ -12,6 +12,10 @@ body {
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
background-color: #e9edf1;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
|
||||
@ -145,7 +149,7 @@ body {
|
||||
margin-top: 9vh;
|
||||
margin-left: -1%;
|
||||
text-align: left;
|
||||
width: 100vw;
|
||||
width: 209vh;
|
||||
}
|
||||
|
||||
|
||||
@ -186,38 +190,19 @@ body {
|
||||
}
|
||||
|
||||
|
||||
.group-list .member-container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.group-list .member-container button {
|
||||
margin-left: 40px;
|
||||
padding: 5px;
|
||||
cursor: pointer;
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
border: 0px solid var(--primary-color);
|
||||
border-radius: 50px;
|
||||
position: absolute;
|
||||
top: -25px;
|
||||
right: -25px;
|
||||
}
|
||||
|
||||
.group-list .member-container button:hover {
|
||||
background: var(--accent-color)
|
||||
}
|
||||
|
||||
|
||||
/* Zone de chat */
|
||||
.chat-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background-color:#f1f1f1;
|
||||
background-color: #ffffff;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
|
||||
margin: 1% 0% 0.5% 1%;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
margin: 0px;
|
||||
margin-top: 20px;
|
||||
margin-left: 1%;
|
||||
margin-bottom: -7px;
|
||||
}
|
||||
|
||||
/* En-tête du chat */
|
||||
@ -241,9 +226,15 @@ body {
|
||||
}
|
||||
|
||||
.message-container {
|
||||
max-width: 100%;
|
||||
border-radius: 5px;
|
||||
overflow-wrap: break-word;
|
||||
word-wrap: break-word;
|
||||
background-color: #f1f1f1;
|
||||
display: flex;
|
||||
margin: 8px;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.message-container .message {
|
||||
align-self: flex-start;
|
||||
}
|
||||
@ -255,27 +246,27 @@ body {
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 12px 18px;
|
||||
background-color: #e1e1e1;
|
||||
border-radius: 15px;
|
||||
max-width: 70%;
|
||||
padding: 10px;
|
||||
border-radius: 12px;
|
||||
background:var(--secondary-color);
|
||||
margin: 2px 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 0%;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* Messages de l'utilisateur */
|
||||
.message.user {
|
||||
background: #2196f3;
|
||||
background-color: #3498db;
|
||||
color: white;
|
||||
align-self: flex-end;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 0.7em;
|
||||
opacity: 0.7;
|
||||
margin-left: 0px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
|
||||
/* Amélioration de l'esthétique des messages */
|
||||
/* .message.user:before {
|
||||
content: '';
|
||||
@ -292,8 +283,6 @@ body {
|
||||
background-color: #bdc3c7;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-radius: 10px;
|
||||
margin: 1%;
|
||||
/* Alignement vertical */
|
||||
}
|
||||
|
||||
@ -326,233 +315,6 @@ body {
|
||||
background-color: #1f608d;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
margin: 20px 0px;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
padding: 10px 20px;
|
||||
cursor: pointer;
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
border: 0px solid var(--primary-color);
|
||||
margin-right: 5px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.tabs button:hover {
|
||||
background: var(--secondary-color);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
/* Signature */
|
||||
.signature-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background-color:#f1f1f1;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
|
||||
margin: 1% 0% 0.5% 1%;
|
||||
transition: all 1s ease 0.1s;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.signature-area.hidden {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
display: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.signature-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
border-radius: 10px 10px 0 0;
|
||||
padding-left: 4%;
|
||||
}
|
||||
|
||||
.signature-content {
|
||||
padding: 10px;
|
||||
background-color: var(--secondary-color);
|
||||
color: var(--primary-color);
|
||||
height: 100%;
|
||||
border-radius: 10px;
|
||||
margin: 1%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.signature-description {
|
||||
height: 20%;
|
||||
width: 100%;
|
||||
margin: 0% 10% 0% 10%;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.signature-description li {
|
||||
margin: 1% 0% 1% 0%;
|
||||
list-style: none;
|
||||
padding: 2%;
|
||||
border-radius: 10px;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--secondary-color);
|
||||
width: 20%;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
margin-right: 2%;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.signature-description li .member-list {
|
||||
margin-left: -30%;
|
||||
}
|
||||
|
||||
.signature-description li .member-list li {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.signature-description li .member-list li:hover {
|
||||
background-color: var(--secondary-color);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.signature-documents {
|
||||
height: 80%;
|
||||
width: 100%;
|
||||
margin: 0% 10% 0% 10%;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.signature-documents-header {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 15%;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#request-document-button {
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
margin-left: 5%;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#request-document-button:hover {
|
||||
background-color: var(--accent-color);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#close-signature {
|
||||
cursor: pointer;
|
||||
align-items: center;
|
||||
margin-left: auto;
|
||||
margin-right: 2%;
|
||||
border-radius: 50%;
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: -3%;
|
||||
margin-top: -5%;
|
||||
font-size: 1em;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#close-signature:hover {
|
||||
background-color: var(--secondary-color);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
/* REQUEST MODAL */
|
||||
.request-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: var(--secondary-color);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
.close-modal {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: 1.5em;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.close-modal:hover {
|
||||
color: var(--accent-color);
|
||||
}
|
||||
|
||||
.modal-members {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.modal-members ul li{
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.file-upload-container {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.file-list {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 5px;
|
||||
margin: 5px 0;
|
||||
background: var(--background-color-secondary);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.remove-file {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
padding: 0 5px;
|
||||
}
|
||||
|
||||
.remove-file:hover {
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
#message-input {
|
||||
width: 100%;
|
||||
height: 50px;
|
||||
@ -575,23 +337,3 @@ body {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--primary-color);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--secondary-color);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--accent-color);
|
||||
}
|
40
src/4nk.css
40
src/4nk.css
@ -316,7 +316,7 @@ h1 {
|
||||
margin-top: 0px;
|
||||
}
|
||||
|
||||
.create-btn {
|
||||
.sp-address-btn {
|
||||
margin-bottom: 2em;
|
||||
cursor: pointer;
|
||||
background-color: #d0d0d7;
|
||||
@ -778,41 +778,3 @@ select[data-multi-select-plugin] {
|
||||
.process-card-action {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/**************************************** Select Member Home Page ******************************************************/
|
||||
.custom-select {
|
||||
width: 100%;
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
direction: ltr;
|
||||
background-color: white;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.custom-select option {
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.custom-select option:hover {
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
|
||||
.custom-select::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.custom-select::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
}
|
||||
|
||||
.custom-select::-webkit-scrollbar-thumb {
|
||||
background: #888;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.custom-select::-webkit-scrollbar-thumb:hover {
|
||||
background: #555;
|
||||
}
|
@ -29,7 +29,7 @@
|
||||
<a onclick="navigate('chat')">Chat</a>
|
||||
<a onclick="navigate('signature')">Signatures</a>
|
||||
<a onclick="navigate('process')">Process</a>
|
||||
<a onclick="disconnect()">Disconnect</a>
|
||||
<a onclick="navigate('home')">Disconnect</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -181,40 +181,3 @@ async function createBackUp() {
|
||||
}
|
||||
|
||||
(window as any).createBackUp = createBackUp;
|
||||
|
||||
async function disconnect() {
|
||||
console.log('Disconnecting...');
|
||||
try {
|
||||
localStorage.clear();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase('4nk');
|
||||
request.onsuccess = () => {
|
||||
console.log('IndexedDB deleted successfully');
|
||||
resolve();
|
||||
};
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onblocked = () => {
|
||||
console.log('Database deletion was blocked');
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map(registration => registration.unregister()));
|
||||
console.log('Service worker unregistered');
|
||||
|
||||
navigate('home');
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = window.location.origin;
|
||||
}, 100);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error during disconnect:', error);
|
||||
// force reload
|
||||
window.location.href = window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
(window as any).disconnect = disconnect;
|
@ -1,14 +0,0 @@
|
||||
<div id="creation-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-title">Login</div>
|
||||
<div class="message">
|
||||
Do you want to create a 4NK member?<br />
|
||||
Attempting to create a member with address <br />
|
||||
<strong>{{device1}}</strong> <br />
|
||||
</div>
|
||||
<div class="confirmation-box">
|
||||
<a class="btn confirmation-btn" onclick="confirm()">Confirm</a>
|
||||
<a class="btn refusal-btn" onclick="closeConfirmationModal()">Refuse</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@ -2,7 +2,7 @@ declare global {
|
||||
interface Window {
|
||||
initAccount: () => void;
|
||||
showContractPopup: (contractId: string) => void;
|
||||
showPairing: () => Promise<void>;
|
||||
showPairing: () => void;
|
||||
showWallet: () => void;
|
||||
showData: () => void;
|
||||
addWalletRow: () => void;
|
||||
@ -36,7 +36,6 @@ declare global {
|
||||
generateRecoveryWords: () => string[];
|
||||
exportUserData: () => void;
|
||||
updateActionButtons: () => void;
|
||||
showQRCodeModal: (address: string) => void;
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +45,6 @@ import { Row, WalletRow, DataRow, Notification, Contract, NotificationMessage }
|
||||
import { addressToEmoji } from '../../utils/sp-address.utils';
|
||||
import { getCorrectDOM } from '../../utils/document.utils';
|
||||
import accountStyle from '../../../public/style/account.css?inline';
|
||||
import Services from '../../services/service';
|
||||
|
||||
let isAddingRow = false;
|
||||
let currentRow: HTMLTableRowElement | null = null;
|
||||
@ -199,7 +197,6 @@ class AccountElement extends HTMLElement {
|
||||
window.updateActionButtons = () => this.updateActionButtons();
|
||||
window.openAvatarPopup = () => this.openAvatarPopup();
|
||||
window.closeAvatarPopup = () => this.closeAvatarPopup();
|
||||
window.showQRCodeModal = (address: string) => this.showQRCodeModal(address);
|
||||
|
||||
if (!localStorage.getItem('rows')) {
|
||||
localStorage.setItem('rows', JSON.stringify(defaultRows));
|
||||
@ -555,13 +552,6 @@ private updateTableContent(rows: Row[]): void {
|
||||
<td>${row.column1}</td>
|
||||
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
|
||||
<td>${row.column3}</td>
|
||||
<td>
|
||||
<img src="https://api.qrserver.com/v1/create-qr-code/?size=50x50&data=${encodeURIComponent(row.column1)}"
|
||||
alt="QR Code"
|
||||
title="${row.column1}"
|
||||
class="qr-code"
|
||||
onclick="window.showQRCodeModal('${encodeURIComponent(row.column1)}')">
|
||||
</td>
|
||||
<td>
|
||||
<button class="delete-button" onclick="window.deleteRow(this)">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="16" height="16" fill="red">
|
||||
@ -637,26 +627,29 @@ private deleteRow(button: HTMLButtonElement): void {
|
||||
const table = row.closest('tbody');
|
||||
if (!table) return;
|
||||
|
||||
// Vérifier le nombre de lignes restantes
|
||||
const remainingRows = table.getElementsByTagName('tr').length;
|
||||
if (remainingRows <= 2) {
|
||||
this.showAlert('You must keep at least 2 devices paired');
|
||||
return;
|
||||
}
|
||||
|
||||
const index = Array.from(table.children).indexOf(row);
|
||||
row.style.transition = 'opacity 0.3s, transform 0.3s';
|
||||
// Animation de suppression
|
||||
row.style.transition = 'opacity 0.3s';
|
||||
row.style.opacity = '0';
|
||||
row.style.transform = 'translateX(-100%)';
|
||||
|
||||
setTimeout(() => {
|
||||
// Obtenir l'index avant la suppression
|
||||
const index = Array.from(table.children).indexOf(row);
|
||||
|
||||
// Supprimer la ligne du DOM
|
||||
row.remove();
|
||||
|
||||
// Mettre à jour le localStorage
|
||||
const storageKey = STORAGE_KEYS[currentMode];
|
||||
const rows = JSON.parse(localStorage.getItem(storageKey) || '[]');
|
||||
if (index > -1) {
|
||||
rows.splice(index, 1);
|
||||
localStorage.setItem(storageKey, JSON.stringify(rows));
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
@ -894,6 +887,9 @@ private showContractPopup(contractId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
// Ajouter à l'objet window
|
||||
|
||||
|
||||
// Fonction utilitaire pour cacher tous les contenus
|
||||
private hideAllContent(): void {
|
||||
const contents = ['pairing-content', 'wallet-content', 'process-content', 'data-content'];
|
||||
@ -906,22 +902,25 @@ private hideAllContent(): void {
|
||||
}
|
||||
|
||||
// Fonctions d'affichage des sections
|
||||
private async showPairing(): Promise<void> {
|
||||
const service = await Services.getInstance();
|
||||
const spAddress = await service.getDeviceAddress();
|
||||
private showPairing(): void {
|
||||
|
||||
isAddingRow = false;
|
||||
currentRow = null;
|
||||
currentMode = 'pairing';
|
||||
|
||||
currentMode = 'pairing';
|
||||
// Cacher tous les contenus
|
||||
this.hideAllContent();
|
||||
|
||||
// Mettre à jour le titre
|
||||
const headerElement = this.shadowRoot?.getElementById('parameter-header');
|
||||
if (headerElement) {
|
||||
headerElement.textContent = 'Pairing';
|
||||
}
|
||||
|
||||
|
||||
// Afficher le contenu de pairing
|
||||
const pairingContent = this.shadowRoot?.getElementById('pairing-content');
|
||||
|
||||
if (pairingContent) {
|
||||
pairingContent.style.display = 'block';
|
||||
pairingContent.innerHTML = `
|
||||
@ -933,8 +932,7 @@ private async showPairing(): Promise<void> {
|
||||
<th>SP Address</th>
|
||||
<th>Device Name</th>
|
||||
<th>SP Emojis</th>
|
||||
<th>QR Code</th>
|
||||
<th>Actions</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
@ -945,46 +943,8 @@ private async showPairing(): Promise<void> {
|
||||
</div>
|
||||
`;
|
||||
|
||||
let rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]');
|
||||
|
||||
const deviceExists = rows.some((row: Row) => row.column1 === spAddress);
|
||||
|
||||
if (!deviceExists && spAddress) {
|
||||
const emojis = await addressToEmoji(spAddress);
|
||||
|
||||
try {
|
||||
// Déboguer le processus de pairing
|
||||
const pairingProcessId = await service.getPairingProcessId();
|
||||
console.log('Pairing Process ID:', pairingProcessId);
|
||||
|
||||
const pairingProcess = await service.getProcess(pairingProcessId);
|
||||
console.log('Pairing Process:', pairingProcess);
|
||||
|
||||
const userName = pairingProcess?.states?.[0]?.metadata?.userName
|
||||
|| pairingProcess?.states?.[0]?.metadata?.name
|
||||
|| localStorage.getItem('userName')
|
||||
|
||||
console.log('Username found:', userName);
|
||||
|
||||
const newRow = {
|
||||
column1: spAddress,
|
||||
column2: userName,
|
||||
column3: emojis
|
||||
};
|
||||
rows = [newRow, ...rows];
|
||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
||||
} catch (error) {
|
||||
console.error('Error getting pairing process:', error);
|
||||
const newRow = {
|
||||
column1: spAddress,
|
||||
column2: 'This Device',
|
||||
column3: emojis
|
||||
};
|
||||
rows = [newRow, ...rows];
|
||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
||||
}
|
||||
}
|
||||
|
||||
// Mettre à jour le contenu du tableau
|
||||
const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]');
|
||||
this.updateTableContent(rows);
|
||||
}
|
||||
}
|
||||
@ -1459,28 +1419,6 @@ private initializeEventListeners() {
|
||||
avatarInput.addEventListener('change', this.handleAvatarUpload.bind(this));
|
||||
}
|
||||
}
|
||||
|
||||
private showQRCodeModal(address: string): void {
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'qr-modal';
|
||||
modal.innerHTML = `
|
||||
<div class="qr-modal-content">
|
||||
<span class="close-qr-modal">×</span>
|
||||
<img src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${address}"
|
||||
alt="QR Code Large"
|
||||
class="qr-code-large">
|
||||
<div class="qr-address">${decodeURIComponent(address)}</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
this.shadowRoot?.appendChild(modal);
|
||||
|
||||
const closeBtn = modal.querySelector('.close-qr-modal');
|
||||
closeBtn?.addEventListener('click', () => modal.remove());
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) modal.remove();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('account-element', AccountElement);
|
||||
|
@ -17,12 +17,22 @@ class ChatComponent extends HTMLElement {
|
||||
connectedCallback() {
|
||||
console.log('CALLBACKs');
|
||||
this.render();
|
||||
this.fetchData();
|
||||
|
||||
if (!customElements.get('chat-element')) {
|
||||
customElements.define('chat-element', ChatElement);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -4,23 +4,24 @@
|
||||
|
||||
<div class="tab-container">
|
||||
<div class="tabs">
|
||||
<div class="tab active" data-tab="tab1">Create an account</div>
|
||||
<div class="tab" data-tab="tab2">Add a device for an existing memeber</div>
|
||||
<div class="tab active" data-tab="tab1">Scan QR Code</div>
|
||||
<div class="tab" data-tab="tab2">Scan other device</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="page-container">
|
||||
<div id="tab1" class="card tab-content active">
|
||||
<div class="card-description">Create an account :</div>
|
||||
<div class="card-description">Scan with your other device :</div>
|
||||
<div class="pairing-request"></div>
|
||||
<!-- <div class="card-image qr-code">
|
||||
<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>
|
||||
<button id="copyBtn" class="sp-address-btn"></button>
|
||||
<div class="card-image emoji-display" id="emoji-display"></div>
|
||||
</div>
|
||||
<div class="separator"></div>
|
||||
<div id="tab2" class="card tab-content">
|
||||
<div class="card-description">Add a device for an existing member :</div>
|
||||
<div class="card-description">Scan your other device :</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>
|
||||
@ -30,13 +31,8 @@
|
||||
</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>
|
||||
|
||||
<input type="text" id="addressInput" placeholder="Paste address" />
|
||||
<div id="emoji-display-2"></div>
|
||||
<button id="okButton" style="display: none">OK</button>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -1,7 +1,7 @@
|
||||
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 { displayEmojis, generateQRCode } from '../../utils/sp-address.utils';
|
||||
import { getCorrectDOM } from '../../utils/html.utils';
|
||||
import QrScannerComponent from '../../components/qrcode-scanner/qrcode-scanner-component';
|
||||
export { QrScannerComponent };
|
||||
@ -20,12 +20,8 @@ export async function initHomePage(): Promise<void> {
|
||||
|
||||
const service = await Services.getInstance();
|
||||
const spAddress = await service.getDeviceAddress();
|
||||
// generateQRCode(spAddress);
|
||||
generateCreateBtn ();
|
||||
generateQRCode(spAddress);
|
||||
displayEmojis(spAddress);
|
||||
|
||||
// Add this line to populate the select when the page loads
|
||||
await populateMemberSelect();
|
||||
}
|
||||
|
||||
//// Modal
|
||||
@ -49,46 +45,4 @@ function scanDevice() {
|
||||
if (reader) reader.innerHTML = '<qr-scanner></qr-scanner>';
|
||||
}
|
||||
|
||||
async function populateMemberSelect() {
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
||||
const memberSelect = container.querySelector('#memberSelect') as HTMLSelectElement;
|
||||
|
||||
if (!memberSelect) {
|
||||
console.error('Could not find memberSelect element');
|
||||
return;
|
||||
}
|
||||
|
||||
const service = await Services.getInstance();
|
||||
const members = service.getAllMembersSorted();
|
||||
|
||||
for (const [processId, member] of Object.entries(members)) {
|
||||
const process = await service.getProcess(processId);
|
||||
let memberPublicName;
|
||||
|
||||
if (process) {
|
||||
const publicMemberData = service.getPublicData(process);
|
||||
if (publicMemberData) {
|
||||
const extractedName = publicMemberData['memberPublicName'];
|
||||
if (extractedName !== undefined && extractedName !== null) {
|
||||
memberPublicName = extractedName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!memberPublicName) {
|
||||
memberPublicName = 'Unnamed Member';
|
||||
}
|
||||
|
||||
// Récupérer les emojis pour ce processId
|
||||
const emojis = await addressToEmoji(processId);
|
||||
|
||||
const option = document.createElement('option');
|
||||
option.value = processId;
|
||||
option.textContent = `${memberPublicName} (${emojis})`;
|
||||
memberSelect.appendChild(option);
|
||||
}
|
||||
}
|
||||
|
||||
(window as any).populateMemberSelect = populateMemberSelect;
|
||||
|
||||
(window as any).scanDevice = scanDevice;
|
||||
|
@ -2,12 +2,9 @@ import { addSubscription } from '../../utils/subscription.utils';
|
||||
import Services from '../../services/service';
|
||||
import { getCorrectDOM } from '~/utils/html.utils';
|
||||
import { Process } from 'pkg/sdk_client';
|
||||
import chatStyle from '../../../public/style/chat.css?inline';
|
||||
import { Database } from '../../services/database.service';
|
||||
|
||||
// Initialize function, create initial tokens with itens that are already selected by the user
|
||||
export async function init() {
|
||||
|
||||
const container = getCorrectDOM('process-list-4nk-component') as HTMLElement;
|
||||
const element = container.querySelector('select') as HTMLSelectElement;
|
||||
// Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside
|
||||
@ -39,6 +36,39 @@ export async function init() {
|
||||
search_div.appendChild(autocomplete_list);
|
||||
search_div.appendChild(dropdown_icon);
|
||||
|
||||
const processes = await getProcesses();
|
||||
|
||||
for (const {key, value} of processes) {
|
||||
const processName = await getDescription(key, value);
|
||||
if (processName) {
|
||||
console.log('adding process name to list:', processName);
|
||||
const opt = new Option(processName);
|
||||
opt.value = processName;
|
||||
opt.setAttribute('data-process-id', key);
|
||||
element.add(opt);
|
||||
}
|
||||
}
|
||||
const { autocomplete_options } = getOptions(element);
|
||||
|
||||
if (autocomplete_options.length === 0) {
|
||||
console.log('No existing processes - creating new messaging process');
|
||||
await createMessagingProcess();
|
||||
|
||||
const updatedProcesses = await getProcesses();
|
||||
for (const {key, value} of updatedProcesses) {
|
||||
const processName = await getDescription(key, value);
|
||||
if (processName) {
|
||||
console.log('adding new process to list:', processName);
|
||||
const opt = new Option(processName);
|
||||
opt.value = processName;
|
||||
opt.setAttribute('data-process-id', key);
|
||||
element.add(opt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('Existing processes found - skipping messaging creation');
|
||||
}
|
||||
|
||||
// set the wrapper as child (instead of the element)
|
||||
element.parentNode?.replaceChild(wrapper, element);
|
||||
// set element as child of wrapper
|
||||
@ -158,39 +188,62 @@ function clearAutocompleteList(select: HTMLSelectElement) {
|
||||
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
||||
}
|
||||
|
||||
async function populateAutocompleteList(select: HTMLSelectElement, query: string, dropdown = false) {
|
||||
// Populate the autocomplete list following a given query from the user
|
||||
function populateAutocompleteList(select: HTMLSelectElement, query: string, dropdown = false) {
|
||||
const { autocomplete_options } = getOptions(select);
|
||||
|
||||
let options_to_show = [];
|
||||
let options_to_show;
|
||||
|
||||
const service = await Services.getInstance();
|
||||
const mineArray: string[] = await service.getMyProcesses();
|
||||
const allProcesses = await service.getProcesses();
|
||||
const allArray: string[] = Object.keys(allProcesses).filter(x => !mineArray.includes(x));
|
||||
if (dropdown) {
|
||||
let messagingCounter = 1;
|
||||
const messagingOptions = select.querySelectorAll('option[value="messaging"]');
|
||||
|
||||
options_to_show = autocomplete_options.map(option => {
|
||||
if (option === 'messaging') {
|
||||
// Récupérer l'élément option correspondant au compteur actuel
|
||||
const currentOption = messagingOptions[messagingCounter - 1];
|
||||
const processId = currentOption?.getAttribute('data-process-id');
|
||||
console.log(`Mapping messaging ${messagingCounter} with processId:`, processId);
|
||||
|
||||
const optionText = `messaging ${messagingCounter}`;
|
||||
messagingCounter++;
|
||||
|
||||
// Stocker le processId dans un attribut data sur le select
|
||||
select.setAttribute(`data-messaging-id-${messagingCounter - 1}`, processId || '');
|
||||
|
||||
return optionText;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
} else {
|
||||
options_to_show = autocomplete(query, autocomplete_options);
|
||||
}
|
||||
|
||||
const wrapper = select.parentNode;
|
||||
const input_search = wrapper?.querySelector('.search-container');
|
||||
const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
|
||||
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
||||
const result_size = options_to_show.length;
|
||||
|
||||
const addProcessToList = (processId:string, isMine: boolean) => {
|
||||
if (result_size == 1) {
|
||||
const li = document.createElement('li');
|
||||
li.innerText = processId;
|
||||
li.setAttribute("data-value", processId);
|
||||
|
||||
if (isMine) {
|
||||
li.classList.add("my-process");
|
||||
li.style.cssText = `color: var(--accent-color)`;
|
||||
}
|
||||
|
||||
li.innerText = options_to_show[0];
|
||||
li.setAttribute('data-value', options_to_show[0]);
|
||||
if (li) addSubscription(li, 'click', selectOption);
|
||||
autocomplete_list?.appendChild(li);
|
||||
};
|
||||
|
||||
mineArray.forEach(processId => addProcessToList(processId, true));
|
||||
allArray.forEach(processId => addProcessToList(processId, false));
|
||||
|
||||
if (mineArray.length === 0 && allArray.length === 0) {
|
||||
if (query.length == options_to_show[0].length) {
|
||||
const event = new Event('click');
|
||||
li.dispatchEvent(event);
|
||||
}
|
||||
} else if (result_size > 1) {
|
||||
for (let i = 0; i < result_size; i++) {
|
||||
const li = document.createElement('li');
|
||||
li.innerText = options_to_show[i];
|
||||
li.setAttribute('data-value', options_to_show[i]);
|
||||
if (li) addSubscription(li, 'click', selectOption);
|
||||
autocomplete_list?.appendChild(li);
|
||||
}
|
||||
} else {
|
||||
const li = document.createElement('li');
|
||||
li.classList.add('not-cursor');
|
||||
li.innerText = 'No options found';
|
||||
@ -467,21 +520,8 @@ async function createMessagingProcess(): Promise<void> {
|
||||
throw new Error('Empty relay address list');
|
||||
}
|
||||
const feeRate = 1;
|
||||
setTimeout(async () => {
|
||||
const createProcessReturn = await service.createMessagingProcess(otherMembers, relayAddress.spAddress, feeRate);
|
||||
const updatedProcess = createProcessReturn.updated_process.current_process;
|
||||
if (!updatedProcess) {
|
||||
console.error('Failed to retrieved new messaging process');
|
||||
return;
|
||||
}
|
||||
const processId = updatedProcess.states[0].commited_in;
|
||||
const stateId = updatedProcess.states[0].state_id;
|
||||
await service.handleApiReturn(createProcessReturn);
|
||||
const createPrdReturn = await service.createPrdUpdate(processId, stateId);
|
||||
await service.handleApiReturn(createPrdReturn);
|
||||
const approveChangeReturn = await service.approveChange(processId, stateId);
|
||||
await service.handleApiReturn(approveChangeReturn);
|
||||
}, 500)
|
||||
const apiReturn = await service.createMessagingProcess(otherMembers, relayAddress.spAddress, feeRate);
|
||||
await service.handleApiReturn(apiReturn);
|
||||
}
|
||||
|
||||
async function getDescription(processId: string, process: Process): Promise<string | null> {
|
||||
@ -518,3 +558,15 @@ async function getDescription(processId: string, process: Process): Promise<stri
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getProcesses(): Promise<any[]> {
|
||||
const service = await Services.getInstance();
|
||||
const processes = await service.getProcesses();
|
||||
|
||||
const res = Object.entries(processes).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
|
||||
return res;
|
||||
}
|
||||
|
@ -148,7 +148,7 @@ export async function init(): Promise<void> {
|
||||
await services.restoreSecretsFromDB();
|
||||
|
||||
if (services.isPaired()) {
|
||||
await navigate('chat');
|
||||
await navigate('process');
|
||||
} else {
|
||||
const queryString = window.location.search;
|
||||
const urlParams = new URLSearchParams(queryString);
|
||||
|
@ -1,5 +1,3 @@
|
||||
const EMPTY32BYTES = String('').padStart(64, '0');
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(self.skipWaiting()); // Activate worker immediately
|
||||
});
|
||||
@ -11,24 +9,25 @@ self.addEventListener('activate', (event) => {
|
||||
// Event listener for messages from clients
|
||||
self.addEventListener('message', async (event) => {
|
||||
const data = event.data;
|
||||
console.log(data);
|
||||
if (data.type === 'START') {
|
||||
const fetchNotifications = async () => {
|
||||
const itemsWithFlag = await getAllItemsWithFlag();
|
||||
|
||||
if (data.type === 'SCAN') {
|
||||
try {
|
||||
const myProcessesId = data.payload;
|
||||
if (myProcessesId && myProcessesId.length != 0) {
|
||||
const toDownload = await scanMissingData(myProcessesId);
|
||||
if (toDownload.length != 0) {
|
||||
console.log('Sending TO_DOWNLOAD message');
|
||||
event.source.postMessage({ type: 'TO_DOWNLOAD', data: toDownload});
|
||||
// Process items with the specific flag
|
||||
itemsWithFlag?.forEach((item) => {
|
||||
console.log(item); // Do something with each flagged item
|
||||
});
|
||||
|
||||
event.ports[0].postMessage({
|
||||
type: 'NOTIFICATIONS',
|
||||
data: itemsWithFlag,
|
||||
});
|
||||
};
|
||||
fetchNotifications();
|
||||
setInterval(fetchNotifications, 2 * 60 * 1000);
|
||||
}
|
||||
} else {
|
||||
event.source.postMessage({ status: 'error', message: 'Empty lists' });
|
||||
}
|
||||
} catch (error) {
|
||||
event.source.postMessage({ status: 'error', message: error.message });
|
||||
}
|
||||
} else if (data.type === 'ADD_OBJECT') {
|
||||
|
||||
if (data.type === 'ADD_OBJECT') {
|
||||
try {
|
||||
const { storeName, object, key } = data.payload;
|
||||
const db = await openDatabase();
|
||||
@ -48,44 +47,6 @@ self.addEventListener('message', async (event) => {
|
||||
}
|
||||
});
|
||||
|
||||
async function scanMissingData(processesToScan) {
|
||||
console.log('Scanning for missing data...');
|
||||
const myProcesses = await getProcesses(processesToScan);
|
||||
|
||||
let toDownload = new Set();
|
||||
// Iterate on each process
|
||||
if (myProcesses && myProcesses.length != 0) {
|
||||
for (const process of myProcesses) {
|
||||
// Iterate on states
|
||||
const firstState = process.states[0];
|
||||
const processId = firstState.commited_in;
|
||||
for (const state of process.states) {
|
||||
if (state.state_id === EMPTY32BYTES) continue;
|
||||
// iterate on pcd_commitment
|
||||
for (const [field, hash] of Object.entries(state.pcd_commitment)) {
|
||||
// Skip public fields
|
||||
if (state.public_data[field] !== undefined || field === 'roles') continue;
|
||||
// Check if we have the data in db
|
||||
const existingData = await getBlob(hash);
|
||||
if (!existingData) {
|
||||
toDownload.add(hash);
|
||||
// We also add an entry in diff, in case it doesn't already exist
|
||||
await addDiff(processId, state.state_id, hash, state.roles, field);
|
||||
} else {
|
||||
// We remove it if we have it in the set
|
||||
if (toDownload.delete(hash)) {
|
||||
console.log(`Removing ${hash} from the set`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(toDownload);
|
||||
return Array.from(toDownload);
|
||||
}
|
||||
|
||||
async function openDatabase() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open('4nk', 1);
|
||||
@ -104,59 +65,33 @@ async function openDatabase() {
|
||||
});
|
||||
}
|
||||
|
||||
async function getAllItemsWithFlag() {
|
||||
const db = await openDatabase();
|
||||
|
||||
// Function to get all processes because it is asynchronous
|
||||
async function getAllProcesses() {
|
||||
const db = await openDatabase();
|
||||
const getAllProcesses = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!db) {
|
||||
reject(new Error('Database is not available'));
|
||||
return;
|
||||
}
|
||||
const tx = db.transaction('processes', 'readonly');
|
||||
const store = tx.objectStore('processes');
|
||||
const request = store.getAll();
|
||||
const request = store.openCursor();
|
||||
const processes = [];
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result);
|
||||
request.onsuccess = (event) => {
|
||||
const cursor = event.target.result;
|
||||
if (cursor) {
|
||||
processes.push({ key: cursor.key, ...cursor.value });
|
||||
cursor.continue();
|
||||
} else {
|
||||
resolve(processes);
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(request.error);
|
||||
request.onerror = (event) => {
|
||||
reject(event.target.error);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
async function getProcesses(processIds) {
|
||||
if (!processIds || processIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const db = await openDatabase();
|
||||
if (!db) {
|
||||
throw new Error('Database is not available');
|
||||
}
|
||||
|
||||
const tx = db.transaction('processes', 'readonly');
|
||||
const store = tx.objectStore('processes');
|
||||
|
||||
const requests = Array.from(processIds).map((processId) => {
|
||||
return new Promise((resolve) => {
|
||||
const request = store.get(processId);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => {
|
||||
console.error(`Error fetching process ${processId}:`, request.error);
|
||||
resolve(undefined);
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const results = await Promise.all(requests);
|
||||
return results.filter(result => result !== undefined);
|
||||
}
|
||||
|
||||
async function getAllDiffsNeedValidation() {
|
||||
const db = await openDatabase();
|
||||
|
||||
const allProcesses = await getAllProcesses();
|
||||
const tx = db.transaction('diffs', 'readonly');
|
||||
const store = tx.objectStore('diffs');
|
||||
@ -211,56 +146,3 @@ async function getAllDiffsNeedValidation() {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function getBlob(hash) {
|
||||
const db = await openDatabase();
|
||||
const storeName = 'data';
|
||||
const tx = db.transaction(storeName, 'readonly');
|
||||
const store = tx.objectStore(storeName);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const getRequest = store.get(hash);
|
||||
getRequest.onsuccess = () => resolve(getRequest.result);
|
||||
getRequest.onerror = () => reject(getRequest.error);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
async function addDiff(processId, stateId, hash, roles, field) {
|
||||
const db = await openDatabase();
|
||||
const storeName = 'diffs';
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
const store = tx.objectStore(storeName);
|
||||
|
||||
// Check if the diff already exists
|
||||
const existingDiff = await new Promise((resolve, reject) => {
|
||||
const getRequest = store.get(hash);
|
||||
getRequest.onsuccess = () => resolve(getRequest.result);
|
||||
getRequest.onerror = () => reject(getRequest.error);
|
||||
});
|
||||
|
||||
if (!existingDiff) {
|
||||
const newDiff = {
|
||||
process_id: processId,
|
||||
state_id: stateId,
|
||||
value_commitment: hash,
|
||||
roles: roles,
|
||||
field: field,
|
||||
description: null,
|
||||
previous_value: null,
|
||||
new_value: null,
|
||||
notify_user: false,
|
||||
need_validation: false,
|
||||
validation_status: 'None'
|
||||
};
|
||||
|
||||
const insertResult = await new Promise((resolve, reject) => {
|
||||
const putRequest = store.put(newDiff);
|
||||
putRequest.onsuccess = () => resolve(putRequest.result);
|
||||
putRequest.onerror = () => reject(putRequest.error);
|
||||
});
|
||||
|
||||
return insertResult;
|
||||
}
|
||||
|
||||
return existingDiff;
|
||||
}
|
||||
|
@ -1,20 +1,14 @@
|
||||
import Services from './service';
|
||||
|
||||
export class Database {
|
||||
class Database {
|
||||
private static instance: Database;
|
||||
private db: IDBDatabase | null = null;
|
||||
private dbName: string = '4nk';
|
||||
private dbVersion: number = 1;
|
||||
private serviceWorkerRegistration: ServiceWorkerRegistration | null = null;
|
||||
private messageChannel: MessageChannel | null = null;
|
||||
private messageChannelForGet: MessageChannel | null = null;
|
||||
private serviceWorkerCheckIntervalId: number | null = null;
|
||||
private messageChannel: MessageChannel = new MessageChannel();
|
||||
private messageChannelForGet: MessageChannel = new MessageChannel();
|
||||
private storeDefinitions = {
|
||||
AnkLabels: {
|
||||
name: 'labels',
|
||||
options: { keyPath: 'emoji' },
|
||||
indices: [],
|
||||
},
|
||||
AnkWallet: {
|
||||
name: 'wallet',
|
||||
options: { keyPath: 'pre_id' },
|
||||
@ -39,16 +33,11 @@ export class Database {
|
||||
name: 'diffs',
|
||||
options: { keyPath: 'value_commitment' },
|
||||
indices: [
|
||||
{ name: 'byStateId', keyPath: 'state_id', options: { unique: false } },
|
||||
{ name: 'byMerkleRoot', keyPath: 'new_state_merkle_root', options: { unique: false } },
|
||||
{ name: 'byNeedValidation', keyPath: 'need_validation', options: { unique: false } },
|
||||
{ name: 'byStatus', keyPath: 'validation_status', options: { unique: false } },
|
||||
],
|
||||
},
|
||||
AnkData: {
|
||||
name: 'data',
|
||||
options: {},
|
||||
indices: [],
|
||||
},
|
||||
};
|
||||
|
||||
// Private constructor to prevent direct instantiation from outside
|
||||
@ -82,10 +71,12 @@ export class Database {
|
||||
});
|
||||
};
|
||||
|
||||
request.onsuccess = async () => {
|
||||
request.onsuccess = () => {
|
||||
setTimeout(() => {
|
||||
this.db = request.result;
|
||||
await this.initServiceWorker();
|
||||
this.initServiceWorker();
|
||||
resolve();
|
||||
}, 500);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
@ -110,67 +101,35 @@ export class Database {
|
||||
return objectList;
|
||||
}
|
||||
|
||||
private async initServiceWorker() {
|
||||
if (!('serviceWorker' in navigator)) return; // Ensure service workers are supported
|
||||
|
||||
try {
|
||||
// Get existing service worker registrations
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
if (registrations.length === 0) {
|
||||
// No existing workers: register a new one.
|
||||
this.serviceWorkerRegistration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
||||
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
||||
} else if (registrations.length === 1) {
|
||||
// One existing worker: update it (restart it) without unregistering.
|
||||
this.serviceWorkerRegistration = registrations[0];
|
||||
await this.serviceWorkerRegistration.update();
|
||||
console.log('Service Worker updated');
|
||||
} else {
|
||||
// More than one existing worker: unregister them all and register a new one.
|
||||
console.log('Multiple Service Worker(s) detected. Unregistering all...');
|
||||
await Promise.all(registrations.map(reg => reg.unregister()));
|
||||
console.log('All previous Service Workers unregistered.');
|
||||
this.serviceWorkerRegistration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
||||
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
||||
private createMessageChannel(responseHandler: (event: MessageEvent) => void): MessageChannel {
|
||||
const messageChannel = new MessageChannel();
|
||||
messageChannel.port1.onmessage = responseHandler;
|
||||
return messageChannel;
|
||||
}
|
||||
|
||||
private async initServiceWorker() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
||||
console.log('Service Worker registered with scope:', registration.scope);
|
||||
|
||||
this.serviceWorkerRegistration = registration
|
||||
await this.checkForUpdates();
|
||||
|
||||
// Set up a global message listener for responses from the service worker.
|
||||
navigator.serviceWorker.addEventListener('message', async (event) => {
|
||||
console.log('Received message from service worker:', event.data);
|
||||
await this.handleServiceWorkerMessage(event.data);
|
||||
});
|
||||
|
||||
// Set up a periodic check to ensure the service worker is active and to send a SYNC message.
|
||||
this.serviceWorkerCheckIntervalId = window.setInterval(async () => {
|
||||
const activeWorker = this.serviceWorkerRegistration.active || (await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration));
|
||||
const service = await Services.getInstance();
|
||||
const payload = await service.getMyProcesses();
|
||||
if (payload.length != 0) {
|
||||
activeWorker?.postMessage({ type: 'SCAN', payload });
|
||||
}
|
||||
}, 5000);
|
||||
// Set up the message channels
|
||||
this.messageChannel.port1.onmessage = this.handleAddObjectResponse;
|
||||
this.messageChannelForGet.port1.onmessage = this.handleGetObjectResponse;
|
||||
registration.active?.postMessage(
|
||||
{
|
||||
type: 'START',
|
||||
},
|
||||
[this.messageChannel.port2],
|
||||
);
|
||||
// Optionally, initialize service worker with some data
|
||||
} catch (error) {
|
||||
console.error('Service Worker registration failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to wait for service worker activation
|
||||
private async waitForServiceWorkerActivation(registration: ServiceWorkerRegistration): Promise<ServiceWorker | null> {
|
||||
return new Promise((resolve) => {
|
||||
if (registration.active) {
|
||||
resolve(registration.active);
|
||||
} else {
|
||||
const listener = () => {
|
||||
if (registration.active) {
|
||||
navigator.serviceWorker.removeEventListener('controllerchange', listener);
|
||||
resolve(registration.active);
|
||||
}
|
||||
};
|
||||
navigator.serviceWorker.addEventListener('controllerchange', listener);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async checkForUpdates() {
|
||||
@ -189,92 +148,12 @@ export class Database {
|
||||
}
|
||||
}
|
||||
|
||||
private async handleServiceWorkerMessage(message: any) {
|
||||
switch (message.type) {
|
||||
case 'TO_DOWNLOAD':
|
||||
await this.handleDownloadList(message.data);
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown message type received from service worker:', message);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleDownloadList(downloadList: string[]): void {
|
||||
// Download the missing data
|
||||
let requestedStateId = [];
|
||||
const service = await Services.getInstance();
|
||||
for (const hash of downloadList) {
|
||||
const diff = await service.getDiffByValue(hash);
|
||||
if (!diff) {
|
||||
// This should never happen
|
||||
console.warn(`Missing a diff for hash ${hash}`);
|
||||
continue;
|
||||
}
|
||||
const processId = diff.process_id;
|
||||
const stateId = diff.state_id;
|
||||
const roles = diff.roles;
|
||||
try {
|
||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
||||
if (valueBytes) {
|
||||
// Save data to db
|
||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
||||
await service.saveBlobToDb(hash, blob);
|
||||
document.dispatchEvent(new CustomEvent('newDataReceived', {
|
||||
detail: {
|
||||
processId,
|
||||
stateId,
|
||||
hash,
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
// We first request the data from managers
|
||||
console.log('Request data from managers of the process');
|
||||
// get the diff from db
|
||||
if (!requestedStateId.includes(stateId)) {
|
||||
await service.requestDataFromPeers(processId, [stateId], [roles]);
|
||||
requestedStateId.push(stateId);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleAddObjectResponse = async (event: MessageEvent) => {
|
||||
const data = event.data;
|
||||
console.log('Received response from service worker (ADD_OBJECT):', data);
|
||||
const service = await Services.getInstance();
|
||||
if (data.type === 'NOTIFICATIONS') {
|
||||
const service = await Services.getInstance();
|
||||
service.setNotifications(data.data);
|
||||
} else if (data.type === 'TO_DOWNLOAD') {
|
||||
console.log(`Received missing data ${data}`);
|
||||
// Download the missing data
|
||||
let requestedStateId = [];
|
||||
for (const hash of data.data) {
|
||||
try {
|
||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
||||
if (valueBytes) {
|
||||
// Save data to db
|
||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
||||
await service.saveBlobToDb(hash, blob);
|
||||
} else {
|
||||
// We first request the data from managers
|
||||
console.log('Request data from managers of the process');
|
||||
// get the diff from db
|
||||
const diff = await service.getDiffByValue(hash);
|
||||
const processId = diff.process_id;
|
||||
const stateId = diff.state_id;
|
||||
const roles = diff.roles;
|
||||
if (!requestedStateId.includes(stateId)) {
|
||||
await service.requestDataFromPeers(processId, [stateId], [roles]);
|
||||
requestedStateId.push(stateId);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -283,15 +162,13 @@ export class Database {
|
||||
};
|
||||
|
||||
public addObject(payload: { storeName: string; object: any; key: any }): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Check if the service worker is active
|
||||
if (!this.serviceWorkerRegistration) {
|
||||
// console.warn('Service worker registration is not ready. Waiting...');
|
||||
this.serviceWorkerRegistration = await navigator.serviceWorker.ready;
|
||||
if (!this.serviceWorkerRegistration?.active) {
|
||||
reject(new Error('Service worker is not active'));
|
||||
return;
|
||||
}
|
||||
|
||||
const activeWorker = await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration);
|
||||
|
||||
// Create a message channel for communication
|
||||
const messageChannel = new MessageChannel();
|
||||
|
||||
@ -307,7 +184,7 @@ export class Database {
|
||||
|
||||
// Send the add object request to the service worker
|
||||
try {
|
||||
activeWorker?.postMessage(
|
||||
this.serviceWorkerRegistration.active.postMessage(
|
||||
{
|
||||
type: 'ADD_OBJECT',
|
||||
payload,
|
||||
@ -390,28 +267,6 @@ export class Database {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Request a store by index
|
||||
public async requestStoreByIndex(storeName: string, indexName: string, request: string): Promise<any[]> {
|
||||
const db = await this.getDb();
|
||||
const tx = db.transaction(storeName, 'readonly');
|
||||
const store = tx.objectStore(storeName);
|
||||
const index = store.index(indexName);
|
||||
|
||||
try {
|
||||
return new Promise((resolve, reject) => {
|
||||
const getAllRequest = index.getAll(request);
|
||||
getAllRequest.onsuccess = () => {
|
||||
const allItems = getAllRequest.result;
|
||||
const filtered = allItems.filter(item => item.state_id === request);
|
||||
resolve(filtered);
|
||||
};
|
||||
getAllRequest.onerror = () => reject(getAllRequest.error);
|
||||
});
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Database;
|
||||
|
@ -14,7 +14,6 @@ export default class ModalService {
|
||||
private processId: string | null = null;
|
||||
private constructor() {}
|
||||
private paired_addresses: string[] = [];
|
||||
private modal: HTMLElement | null = null;
|
||||
|
||||
// Method to access the singleton instance of Services
|
||||
public static async getInstance(): Promise<ModalService> {
|
||||
@ -55,21 +54,6 @@ export default class ModalService {
|
||||
}
|
||||
}
|
||||
|
||||
async injectCreationModal(members: any[]) {
|
||||
const container = document.querySelector('#containerId');
|
||||
if (container) {
|
||||
let html = await fetch('/src/components/modal/creation-modal.html').then((res) => res.text());
|
||||
html = html.replace('{{device1}}', await addressToEmoji(members[0]['sp_addresses'][0]));
|
||||
container.innerHTML += html;
|
||||
|
||||
// Dynamically load the header JS
|
||||
const script = document.createElement('script');
|
||||
script.src = '/src/components/modal/confirmation-modal.ts';
|
||||
script.type = 'module';
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
}
|
||||
|
||||
// Device 1 wait Device 2
|
||||
async injectWaitingModal() {
|
||||
const container = document.querySelector('#containerId');
|
||||
@ -111,48 +95,43 @@ export default class ModalService {
|
||||
|
||||
public async openPairingConfirmationModal(roleDefinition: Record<string, RoleDefinition>, processId: string, stateId: string) {
|
||||
let members;
|
||||
if (roleDefinition['pairing']) {
|
||||
const owner = roleDefinition['pairing'];
|
||||
if (roleDefinition['owner']) {
|
||||
const owner = roleDefinition['owner'];
|
||||
members = owner.members;
|
||||
} else {
|
||||
throw new Error('No "pairing" role');
|
||||
throw new Error('No "owner" role');
|
||||
}
|
||||
|
||||
if (members.length != 1) {
|
||||
throw new Error('Must have exactly 1 member');
|
||||
}
|
||||
|
||||
console.log("MEMBERS:", members);
|
||||
// We take all the addresses except our own
|
||||
const service = await Services.getInstance();
|
||||
const localAddress = await service.getDeviceAddress();
|
||||
for (const member of members) {
|
||||
if (member.sp_addresses) {
|
||||
for (const address of member.sp_addresses) {
|
||||
for (const address of member['sp_addresses']) {
|
||||
if (address !== localAddress) {
|
||||
this.paired_addresses.push(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.processId = processId;
|
||||
this.stateId = stateId;
|
||||
|
||||
if (members[0].sp_addresses.length === 1) {
|
||||
await this.injectCreationModal(members);
|
||||
this.modal = document.getElementById('creation-modal');
|
||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
||||
} else {
|
||||
await this.injectModal(members);
|
||||
this.modal = document.getElementById('modal');
|
||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
||||
}
|
||||
const modal = document.getElementById('modal');
|
||||
if (modal) modal.style.display = 'flex';
|
||||
// const newScript = document.createElement('script');
|
||||
// newScript.setAttribute('type', 'module');
|
||||
// newScript.textContent = confirmationModalScript;
|
||||
// document.head.appendChild(newScript).parentNode?.removeChild(newScript);
|
||||
|
||||
if (this.modal) this.modal.style.display = 'flex';
|
||||
// Add correct text
|
||||
|
||||
// Close modal when clicking outside of it
|
||||
window.onclick = (event) => {
|
||||
if (event.target === this.modal) {
|
||||
const modal = document.getElementById('modal');
|
||||
if (event.target === modal) {
|
||||
this.closeConfirmationModal();
|
||||
}
|
||||
};
|
||||
@ -161,12 +140,14 @@ export default class ModalService {
|
||||
console.log('=============> Confirm Login');
|
||||
}
|
||||
async closeLoginModal() {
|
||||
if (this.modal) this.modal.style.display = 'none';
|
||||
const modal = document.getElementById('login-modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
}
|
||||
|
||||
async confirmPairing() {
|
||||
const service = await Services.getInstance();
|
||||
if (this.modal) this.modal.style.display = 'none';
|
||||
const modal = document.getElementById('modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
|
||||
if (service.device1) {
|
||||
console.log("Device 1 detected");
|
||||
@ -185,7 +166,7 @@ export default class ModalService {
|
||||
|
||||
// We send confirmation that we validate the change
|
||||
try {
|
||||
const approveChangeReturn = await service.approveChange(this.processId!, this.stateId!);
|
||||
const approveChangeReturn = service.approveChange(this.processId!, this.stateId!);
|
||||
await service.handleApiReturn(approveChangeReturn);
|
||||
|
||||
await this.injectWaitingModal();
|
||||
@ -205,7 +186,7 @@ export default class ModalService {
|
||||
const newDevice = service.dumpDeviceFromMemory();
|
||||
console.log(newDevice);
|
||||
await service.saveDeviceInDatabase(newDevice);
|
||||
navigate('chat');
|
||||
navigate('process');
|
||||
service.resetState();
|
||||
|
||||
} catch (e) {
|
||||
@ -234,7 +215,7 @@ export default class ModalService {
|
||||
|
||||
// We send confirmation that we validate the change
|
||||
try {
|
||||
const approveChangeReturn = await service.approveChange(this.processId!, this.stateId!);
|
||||
const approveChangeReturn = service.approveChange(this.processId!, this.stateId!);
|
||||
await service.handleApiReturn(approveChangeReturn);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
@ -248,13 +229,14 @@ export default class ModalService {
|
||||
const newDevice = service.dumpDeviceFromMemory();
|
||||
console.log(newDevice);
|
||||
await service.saveDeviceInDatabase(newDevice);
|
||||
navigate('chat');
|
||||
navigate('process');
|
||||
}
|
||||
}
|
||||
|
||||
async closeConfirmationModal() {
|
||||
const service = await Services.getInstance();
|
||||
await service.unpairDevice();
|
||||
if (this.modal) this.modal.style.display = 'none';
|
||||
const modal = document.getElementById('modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
@ -3,33 +3,33 @@ import { INotification } from '~/models/notification.model';
|
||||
import { IProcess } from '~/models/process.model';
|
||||
// import Database from './database';
|
||||
import { initWebsocket, sendMessage } from '../websockets';
|
||||
import { ApiReturn, Device, HandshakeMessage, Member, Process, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client';
|
||||
import { ApiReturn, Device, InitMessage, Member, Process, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client';
|
||||
import ModalService from './modal.service';
|
||||
import Database from './database.service';
|
||||
import { storeData, retrieveData, testData } from './storage.service';
|
||||
import { storeData, retrieveData } from './storage.service';
|
||||
import { BackUp } from '~/models/backup.model';
|
||||
|
||||
export const U32_MAX = 4294967295;
|
||||
|
||||
const BASEURL = `https://demo.4nkweb.com`;
|
||||
const BOOTSTRAPURL = [`${BASEURL}/ws/`];
|
||||
const STORAGEURL = `${BASEURL}/storage`
|
||||
const storageUrl = `/storage`;
|
||||
const BOOTSTRAPURL = [`https://demo.4nkweb.com/ws/`];
|
||||
const DEFAULTAMOUNT = 1000n;
|
||||
const EMPTY32BYTES = String('').padStart(64, '0');
|
||||
|
||||
export default class Services {
|
||||
private static initializing: Promise<Services> | null = null;
|
||||
private static instance: Services;
|
||||
private currentProcess: string | null = null;
|
||||
private pendingUpdates: any | null = null;
|
||||
private currentUpdateMerkleRoot: string | null = null;
|
||||
private localAddress: string | null = null;
|
||||
private pairedAddresses: string[] = [];
|
||||
private sdkClient: any;
|
||||
private myProcesses: Set = new Set();
|
||||
private processes: IProcess[] | null = null;
|
||||
private notifications: any[] | null = null;
|
||||
private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
|
||||
private database: any;
|
||||
private routingInstance!: ModalService;
|
||||
private relayAddresses: { [wsurl: string]: string } = {};
|
||||
private membersList: Record<string, Member> = {};
|
||||
// Private constructor to prevent direct instantiation from outside
|
||||
private constructor() {}
|
||||
|
||||
@ -173,35 +173,32 @@ export default class Services {
|
||||
}
|
||||
|
||||
public async checkConnections(members: Member[]): Promise<void> {
|
||||
// Ensure the amount is available before proceeding
|
||||
try {
|
||||
await this.ensureSufficientAmount();
|
||||
} catch (e) {
|
||||
console.error('Failed to get tokens from relay, check connection');
|
||||
return;
|
||||
}
|
||||
let unconnectedAddresses = [];
|
||||
for (const member of members) {
|
||||
for (const address of member.sp_addresses) {
|
||||
const memberPromises = members.map(async (member) => {
|
||||
const addressPromises = member.sp_addresses.map(async (address) => {
|
||||
const sharedSecret = await this.getSecretForAddress(address);
|
||||
if (!sharedSecret) {
|
||||
unconnectedAddresses.push(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (unconnectedAddresses && unconnectedAddresses.length != 0) {
|
||||
const apiResult = await this.connectAddresses(unconnectedAddresses);
|
||||
await this.handleApiReturn(apiResult);
|
||||
const connectMemberResult = await this.connectMember([{ sp_addresses: [address] }]);
|
||||
await this.handleApiReturn(connectMemberResult);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(addressPromises);
|
||||
});
|
||||
|
||||
await Promise.all(memberPromises);
|
||||
}
|
||||
|
||||
public async connectAddresses(addresses: string[]): Promise<ApiReturn> {
|
||||
if (addresses.length === 0) {
|
||||
throw new Error('Trying to connect to empty addresses list');
|
||||
public async connectMember(members: Member[]): Promise<ApiReturn> {
|
||||
if (members.length === 0) {
|
||||
throw new Error('Trying to connect to empty members list');
|
||||
}
|
||||
|
||||
const members_str = members.map((member) => JSON.stringify(member));
|
||||
|
||||
try {
|
||||
return this.sdkClient.create_connect_transaction(addresses, 1);
|
||||
// Ensure the amount is available before proceeding
|
||||
await this.ensureSufficientAmount();
|
||||
return this.sdkClient.create_connect_transaction(members_str, 1);
|
||||
} catch (e) {
|
||||
console.error('Failed to connect member:', e);
|
||||
throw e;
|
||||
@ -209,8 +206,8 @@ export default class Services {
|
||||
}
|
||||
|
||||
private async ensureSufficientAmount(): Promise<void> {
|
||||
const availableAmt = this.getAmount();
|
||||
const target: BigInt = DEFAULTAMOUNT * BigInt(10);
|
||||
let availableAmt = this.getAmount();
|
||||
const target: BigInt = DEFAULTAMOUNT * BigInt(2);
|
||||
|
||||
if (availableAmt < target) {
|
||||
const faucetMsg = this.createFaucetMessage();
|
||||
@ -238,150 +235,96 @@ export default class Services {
|
||||
throw new Error('Amount is still 0 after 3 attempts');
|
||||
}
|
||||
|
||||
public async createPairingProcess(userName: string, pairWith: string[], relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
||||
public async createMessagingProcess(otherMembers: Member[],relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
||||
if (!this.isPaired()) {
|
||||
throw new Error('Device not paired');
|
||||
}
|
||||
const me = await this.getMemberFromDevice();
|
||||
if (!me) {
|
||||
throw new Error('No paired member in device');
|
||||
}
|
||||
const allMembers: Member[] = otherMembers;
|
||||
allMembers.push({ sp_addresses: me });
|
||||
const meAndOne = [{ sp_addresses: me }, otherMembers.pop()!];
|
||||
const everyOneElse = otherMembers;
|
||||
const messagingTemplate = {
|
||||
description: 'messaging',
|
||||
roles: {
|
||||
public: {
|
||||
members: allMembers,
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: ['description', 'roles'],
|
||||
min_sig_member: 0.0,
|
||||
},
|
||||
],
|
||||
storages: [storageUrl]
|
||||
},
|
||||
owner: {
|
||||
members: meAndOne,
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 1.0,
|
||||
fields: ['description', 'roles'],
|
||||
min_sig_member: 1.0,
|
||||
},
|
||||
],
|
||||
storages: [storageUrl]
|
||||
},
|
||||
users: {
|
||||
members: everyOneElse,
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: ['description', 'roles'],
|
||||
min_sig_member: 0.0,
|
||||
},
|
||||
],
|
||||
storages: [storageUrl]
|
||||
},
|
||||
},
|
||||
};
|
||||
try {
|
||||
return this.sdkClient.create_new_process(JSON.stringify(messagingTemplate), null, relayAddress, feeRate);
|
||||
} catch (e) {
|
||||
throw new Error(`Creating process failed: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async createPairingProcess(pairWith: string[], relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
||||
if (this.sdkClient.is_paired()) {
|
||||
throw new Error('Device already paired');
|
||||
}
|
||||
const myAddress: string = this.sdkClient.get_address();
|
||||
pairWith.push(myAddress);
|
||||
const roles: Record<string, RoleDefinition> = {
|
||||
pairing: {
|
||||
const newKey = this.sdkClient.get_new_keypair();
|
||||
const pairingTemplate = {
|
||||
description: 'pairing',
|
||||
roles: {
|
||||
owner: {
|
||||
members: [{ sp_addresses: pairWith }],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 1.0,
|
||||
fields: ['description', 'counter', 'roles', 'memberPublicName'],
|
||||
fields: ['description', 'roles', 'session_privkey', 'session_pubkey', 'key_parity'],
|
||||
min_sig_member: 1.0,
|
||||
},
|
||||
],
|
||||
storages: [STORAGEURL]
|
||||
storages: [storageUrl]
|
||||
},
|
||||
},
|
||||
session_privkey: newKey['private_key'],
|
||||
session_pubkey: newKey['x_only_public_key'],
|
||||
key_parity: newKey['key_parity'],
|
||||
};
|
||||
const pairingTemplate = {
|
||||
description: 'pairing',
|
||||
counter: 0,
|
||||
};
|
||||
const publicData = {
|
||||
memberPublicName: userName
|
||||
}
|
||||
try {
|
||||
return this.sdkClient.create_new_process(
|
||||
pairingTemplate,
|
||||
roles,
|
||||
publicData,
|
||||
relayAddress,
|
||||
feeRate
|
||||
);
|
||||
return this.sdkClient.create_new_process(JSON.stringify(pairingTemplate), null, relayAddress, feeRate);
|
||||
} catch (e) {
|
||||
throw new Error(`Creating process failed:, ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async createDmProcess(
|
||||
otherMember: string[],
|
||||
): Promise<ApiReturn> {
|
||||
if (otherMember.length === 0) {
|
||||
throw new Error('Can\'t open dm with empty user');
|
||||
}
|
||||
try {
|
||||
console.log('🚀 Début createDmProcess');
|
||||
console.log('👥 Other Member:', otherMember);
|
||||
|
||||
if (!this.isPaired()) {
|
||||
throw new Error('Device not paired');
|
||||
}
|
||||
|
||||
const myAddresses = await this.getMemberFromDevice();
|
||||
console.log('🔑 Mes adresses:', myAddresses);
|
||||
|
||||
if (!myAddresses) {
|
||||
throw new Error('No paired member found');
|
||||
}
|
||||
|
||||
const roles = {
|
||||
demiurge: {
|
||||
members: [
|
||||
{ sp_addresses: myAddresses },
|
||||
],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.01,
|
||||
fields: ['message', 'description', 'roles'],
|
||||
min_sig_member: 0.01,
|
||||
},
|
||||
],
|
||||
storages: [STORAGEURL]
|
||||
}
|
||||
dm: {
|
||||
members: [
|
||||
{ sp_addresses: myAddresses },
|
||||
{ sp_addresses: otherMember }
|
||||
],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.01,
|
||||
fields: ['message', 'description'],
|
||||
min_sig_member: 0.01,
|
||||
},
|
||||
],
|
||||
storages: [STORAGEURL]
|
||||
}
|
||||
}
|
||||
|
||||
const dmTemplate = {
|
||||
description: 'dm',
|
||||
message: '',
|
||||
};
|
||||
|
||||
console.log('📋 Template final:', JSON.stringify(dmTemplate, null, 2));
|
||||
|
||||
const relayAddress = this.getAllRelays()[0]['spAddress'];
|
||||
const feeRate = 1;
|
||||
const publicData = {};
|
||||
|
||||
await this.checkConnections ([{ sp_addresses: otherMember }]);
|
||||
|
||||
const result = this.sdkClient.create_new_process (
|
||||
dmTemplate,
|
||||
roles,
|
||||
publicData,
|
||||
relayAddress,
|
||||
feeRate
|
||||
);
|
||||
|
||||
return result;
|
||||
|
||||
} catch (e) {
|
||||
console.error('❌ Erreur:', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public async updateProcess(process: Process, new_state: any, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> {
|
||||
// If roles is null, we just take the last commited state roles
|
||||
if (!roles) {
|
||||
roles = this.getRoles(process);
|
||||
} else {
|
||||
// We should check that we have the right to change the roles here, or maybe it's better leave it to the wasm
|
||||
console.log('Provided new roles:', JSON.stringify(roles));
|
||||
}
|
||||
console.log(roles);
|
||||
let members = new Set();
|
||||
for (const role of Object.values(roles)) {
|
||||
for (const member of role.members) {
|
||||
members.add(member)
|
||||
}
|
||||
}
|
||||
console.log(members);
|
||||
await this.checkConnections([...members]);
|
||||
try {
|
||||
console.log(process);
|
||||
return this.sdkClient.update_process(process, new_state, roles, {});
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to update process: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Create prd update for current process and update
|
||||
public createPrdUpdate(processId: string, stateId: string): ApiReturn {
|
||||
try {
|
||||
@ -403,25 +346,21 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
public async approveChange(processId: string, stateId: string): Promise<ApiReturn> {
|
||||
const process = await this.getProcess(processId);
|
||||
if (!process) {
|
||||
throw new Error('Failed to get process from db');
|
||||
}
|
||||
public approveChange(processId: string, stateId: string): ApiReturn {
|
||||
try {
|
||||
return this.sdkClient.validate_state(process, stateId);
|
||||
return this.sdkClient.validate_state(processId, stateId);
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to create prd response: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async rejectChange(processId: string, stateId: string): Promise<ApiReturn> {
|
||||
const process = await this.getProcess(processId);
|
||||
if (!process) {
|
||||
throw new Error('Failed to get process from db');
|
||||
public rejectChange(): ApiReturn {
|
||||
if (!this.currentProcess || !this.currentUpdateMerkleRoot) {
|
||||
throw new Error('No current process and/or current update defined');
|
||||
}
|
||||
|
||||
try {
|
||||
return this.sdkClient.refuse_state(process, stateId);
|
||||
return this.sdkClient.refuse_state(this.currentProcess, this.currentUpdateMerkleRoot);
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to create prd response: ${e}`);
|
||||
}
|
||||
@ -494,11 +433,40 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
public async tryFetchDiffValue(diffs: UserDiff[]): Promise<[UserDiff[], Record<string, string>]>{
|
||||
if (diffs.length === 0) {
|
||||
return [[], {}];
|
||||
}
|
||||
|
||||
// We check if we have the value in diffs
|
||||
let retrievedValues: Record<string, string> = {};
|
||||
for (const diff of diffs) {
|
||||
// Check if `new_value` is missing
|
||||
if (diff.new_value === null) {
|
||||
const hash = diff.value_commitment;
|
||||
if (!hash) {
|
||||
console.error('No commitment for diff');
|
||||
}
|
||||
try {
|
||||
const res = await this.fetchValueFromStorage(hash);
|
||||
if (!res) {
|
||||
console.error('Failed to fetch value for hash', hash);
|
||||
} else {
|
||||
diff.new_value = res['value'];
|
||||
retrievedValues[hash] = res['value'];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch new_value for diff: ${JSON.stringify(diff)}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [diffs, retrievedValues];
|
||||
}
|
||||
|
||||
public async handleApiReturn(apiReturn: ApiReturn) {
|
||||
console.log(apiReturn);
|
||||
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
||||
await this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
}
|
||||
|
||||
if (apiReturn.secrets) {
|
||||
@ -530,50 +498,46 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(async () => {
|
||||
if (apiReturn.updated_process) {
|
||||
const updatedProcess = apiReturn.updated_process;
|
||||
|
||||
const processId: string = updatedProcess.process_id;
|
||||
const processId: string = updatedProcess.commitment_tx;
|
||||
|
||||
if (updatedProcess.encrypted_data && Object.keys(updatedProcess.encrypted_data).length != 0) {
|
||||
for (const [hash, cipher] of Object.entries(updatedProcess.encrypted_data)) {
|
||||
console.log(hash);
|
||||
console.log(cipher);
|
||||
const blob = this.hexToBlob(cipher);
|
||||
// Save process to storage
|
||||
try {
|
||||
await this.saveBlobToDb(hash, blob);
|
||||
await this.saveProcess(processId, updatedProcess.current_process);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save process to db
|
||||
await this.saveProcessToDb(processId, updatedProcess.current_process);
|
||||
|
||||
const isPaired = this.isPaired();
|
||||
|
||||
if (updatedProcess.diffs && updatedProcess.diffs.length != 0) {
|
||||
if (updatedProcess.new_diffs.length != 0) {
|
||||
const [updatedDiffs, retrievedValues] = await this.tryFetchDiffValue(updatedProcess.new_diffs);
|
||||
if (Object.entries(retrievedValues).length != 0) {
|
||||
const stateId = updatedDiffs[0].new_state_merkle_root;
|
||||
const processId = updatedDiffs[0].process_id;
|
||||
// We update the process with the value we retrieved
|
||||
const hashToValues = JSON.stringify(retrievedValues);
|
||||
const apiReturn = this.sdkClient.update_process_state(processId, stateId, hashToValues);
|
||||
await this.handleApiReturn(apiReturn);
|
||||
} else {
|
||||
try {
|
||||
await this.saveDiffsToDb(updatedProcess.diffs);
|
||||
await this.saveDiffs(updatedDiffs);
|
||||
} catch (e) {
|
||||
console.error('Failed to save diffs to db:', e);
|
||||
throw e;
|
||||
}
|
||||
if (!isPaired) {
|
||||
console.log(updatedProcess);
|
||||
await this.openPairingConfirmationModal(updatedProcess.current_process.states[0]);
|
||||
await this.openPairingConfirmationModal(updatedDiffs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (apiReturn.push_to_storage && apiReturn.push_to_storage.length != 0) {
|
||||
for (const hash of apiReturn.push_to_storage) {
|
||||
const blob = await this.getBlobFromDb(hash);
|
||||
if (blob) {
|
||||
await this.saveDataToStorage(hash, blob, null);
|
||||
} else {
|
||||
console.error('Failed to get data from db');
|
||||
}
|
||||
|
||||
if (updatedProcess.modified_state) {
|
||||
const responsePrdReturn = this.sdkClient.create_response_prd(processId, updatedProcess.modified_state);
|
||||
await this.handleApiReturn(responsePrdReturn);
|
||||
}
|
||||
}
|
||||
|
||||
@ -585,16 +549,20 @@ export default class Services {
|
||||
if (apiReturn.ciphers_to_send && apiReturn.ciphers_to_send.length != 0) {
|
||||
await this.sendCipherMessages(apiReturn.ciphers_to_send);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
public async openPairingConfirmationModal(firstState: ProcessState) {
|
||||
const roles = firstState.roles;
|
||||
const processId = firstState.commited_in;
|
||||
const stateId = firstState.state_id;
|
||||
public async openPairingConfirmationModal(diffs: UserDiff[]) {
|
||||
const rolesDiff = diffs.find((diff) => diff.field === 'roles');
|
||||
if (!rolesDiff) {
|
||||
throw new Error('Pairing process must have roles');
|
||||
}
|
||||
const processId = rolesDiff.process_id;
|
||||
const stateId = rolesDiff.new_state_merkle_root;
|
||||
try {
|
||||
await this.routingInstance.openPairingConfirmationModal(roles, processId, stateId);
|
||||
await this.routingInstance.openPairingConfirmationModal(rolesDiff.new_value, processId, stateId);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw new Error(`${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -623,23 +591,6 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
public dumpNeuteredDevice(): Device | null {
|
||||
try {
|
||||
return this.sdkClient.dump_neutered_device();
|
||||
} catch (e) {
|
||||
console.error(`Failed to dump device: ${e}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public getPairingProcessId(): string {
|
||||
try {
|
||||
return this.sdkClient.get_pairing_process_id();
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to get pairing process: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
async saveDeviceInDatabase(device: any): Promise<void> {
|
||||
const db = await Database.getInstance();
|
||||
const walletStore = 'wallet';
|
||||
@ -689,40 +640,6 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
isChildRole(parent: any, child: any): boolean {
|
||||
try {
|
||||
this.sdkClient.is_child_role(JSON.stringify(parent), JSON.stringify(child));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
rolesContainsUs(roles: Record<string, RoleDefinition>): boolean {
|
||||
let us;
|
||||
try {
|
||||
us = this.sdkClient.get_member();
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
return this.rolesContainsMember(roles, us.sp_addresses);
|
||||
}
|
||||
|
||||
rolesContainsMember(roles: Record<string, RoleDefinition>, member: string[]): boolean {
|
||||
let res = false;
|
||||
for (const [roleName, roleDef] of Object.entries(roles)) {
|
||||
for (const otherMember of roleDef.members) {
|
||||
if (res) { return true }
|
||||
res = this.compareMembers(member, otherMember.sp_addresses);
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async dumpWallet() {
|
||||
const wallet = await this.sdkClient.dump_wallet();
|
||||
console.log('🚀 ~ Services ~ dumpWallet ~ wallet:', wallet);
|
||||
@ -758,75 +675,46 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
private async removeProcess(processId: string): Promise<void> {
|
||||
const db = await Database.getInstance();
|
||||
const storeName = 'processes';
|
||||
|
||||
try {
|
||||
await db.deleteObject(storeName, processId);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
public async saveProcessToDb(processId: string, process: Process) {
|
||||
public async saveProcess(commitedIn: string, process: Process) {
|
||||
const db = await Database.getInstance();
|
||||
try {
|
||||
await db.addObject({
|
||||
storeName: 'processes',
|
||||
object: process,
|
||||
key: processId,
|
||||
key: commitedIn,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`Failed to save process ${processId}: ${e}`);
|
||||
}
|
||||
throw new Error(`Failed to save process: ${e}`);
|
||||
}
|
||||
|
||||
public async saveBlobToDb(hash: string, data: Blob) {
|
||||
const db = await Database.getInstance();
|
||||
try {
|
||||
await db.addObject({
|
||||
storeName: 'data',
|
||||
object: data,
|
||||
key: hash,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`Failed to save data to db: ${e}`);
|
||||
}
|
||||
}
|
||||
// We check how many copies in storage nodes
|
||||
// We check the storage nodes in the process itself
|
||||
// this.sdkClient.get_storages(commitedIn);
|
||||
const storages = [storageUrl];
|
||||
|
||||
public async getBlobFromDb(hash: string): Promise<Blob | null> {
|
||||
const db = await Database.getInstance();
|
||||
try {
|
||||
return await db.getObject('data', hash);
|
||||
} catch (e) {
|
||||
return null;
|
||||
for (const state of process.states) {
|
||||
if (state.state_id === "") {
|
||||
continue;
|
||||
}
|
||||
if (!state.encrypted_pcd) {
|
||||
console.warn('Empty encrypted pcd, skipping...');
|
||||
continue;
|
||||
}
|
||||
for (const [field, hash] of Object.entries(state.pcd_commitment)) {
|
||||
// get the encrypted value with the field name
|
||||
const value = state.encrypted_pcd[field];
|
||||
await storeData(storages, hash, value, null);
|
||||
}
|
||||
|
||||
public async saveDataToStorage(hash: string, data: Blob, ttl: number | null) {
|
||||
const storages = [STORAGEURL];
|
||||
|
||||
try {
|
||||
await storeData(storages, hash, data, ttl);
|
||||
} catch (e) {
|
||||
console.error(`Failed to store data with hash ${hash}: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async fetchValueFromStorage(hash: string): Promise<any | null> {
|
||||
const storages = [STORAGEURL];
|
||||
const storages = [storageUrl];
|
||||
|
||||
return await retrieveData(storages, hash);
|
||||
}
|
||||
|
||||
public async testDataInStorage(hash: string): Promise<Record<string, boolean | null> | null> {
|
||||
const storages = [STORAGEURL];
|
||||
|
||||
return await testData(storages, hash);
|
||||
}
|
||||
|
||||
public async saveDiffsToDb(diffs: UserDiff[]) {
|
||||
public async saveDiffs(diffs: UserDiff[]) {
|
||||
const db = await Database.getInstance();
|
||||
try {
|
||||
for (const diff of diffs) {
|
||||
@ -853,27 +741,6 @@ export default class Services {
|
||||
return processes;
|
||||
}
|
||||
|
||||
public async getChildrenOfProcess(processId: string): Promise<string[]> {
|
||||
const processes = await this.getProcesses();
|
||||
|
||||
const res = [];
|
||||
for (const [hash, process] of Object.entries(processes)) {
|
||||
const firstState = process.states[0];
|
||||
const pcdCommitment = firstState['pcd_commitment'];
|
||||
try {
|
||||
const parentIdHash = pcdCommitment['parent_id'];
|
||||
const diff = await this.getDiffByValue(parentIdHash);
|
||||
if (diff && diff['new_value'] === processId) {
|
||||
res.push(JSON.stringify(process));
|
||||
}
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public async restoreProcessesFromBackUp(processes: Record<string, Process>) {
|
||||
const db = await Database.getInstance();
|
||||
for (const [commitedIn, process] of Object.entries(processes)) {
|
||||
@ -947,47 +814,6 @@ export default class Services {
|
||||
}
|
||||
}
|
||||
|
||||
async decryptAttribute(processId: string, state: ProcessState, attribute: string): Promise<string | null> {
|
||||
let hash = state.pcd_commitment[attribute];
|
||||
let key = state.keys[attribute];
|
||||
|
||||
// If hash or key is missing, request an update and then retry
|
||||
if (!hash || !key) {
|
||||
await this.requestDataFromPeers(processId, [state.state_id], [state.roles]);
|
||||
|
||||
const maxRetries = 5;
|
||||
const retryDelay = 500; // delay in milliseconds
|
||||
let retries = 0;
|
||||
|
||||
while ((!hash || !key) && retries < maxRetries) {
|
||||
await new Promise(resolve => setTimeout(resolve, retryDelay));
|
||||
// Re-read hash and key after waiting
|
||||
hash = state.pcd_commitment[attribute];
|
||||
key = state.keys[attribute];
|
||||
retries++;
|
||||
}
|
||||
}
|
||||
|
||||
if (hash && key) {
|
||||
const blob = await this.getBlobFromDb(hash);
|
||||
if (blob) {
|
||||
// Decrypt the data
|
||||
const buf = await blob.arrayBuffer();
|
||||
const cipher = new Uint8Array(buf);
|
||||
const keyBlob = this.hexToBlob(key);
|
||||
const keyBuf = await keyBlob.arrayBuffer();
|
||||
|
||||
const clear = this.sdkClient.decrypt_data(new Uint8Array(keyBuf), cipher);
|
||||
if (clear) {
|
||||
// Parse the stringified JSON
|
||||
return JSON.parse(clear);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getNotifications(): any[] | null {
|
||||
// return [
|
||||
// {
|
||||
@ -1072,220 +898,21 @@ export default class Services {
|
||||
this.device2Ready = false;
|
||||
}
|
||||
|
||||
|
||||
// Handle the handshake message
|
||||
public async handleHandshakeMsg(url: string, parsedMsg: any) {
|
||||
public async handleInitMsg(url: string, parsedMsg: any) {
|
||||
try {
|
||||
const handshakeMsg: HandshakeMessage = JSON.parse(parsedMsg);
|
||||
this.updateRelay(url, handshakeMsg.sp_address);
|
||||
const members = handshakeMsg.peers_list;
|
||||
if (this.membersList && Object.keys(this.membersList).length === 0) {
|
||||
// We start from an empty list, just copy it over
|
||||
this.membersList = handshakeMsg.peers_list;
|
||||
} else {
|
||||
// We are incrementing our list
|
||||
for (const [processId, member] of Object.entries(handshakeMsg.peers_list)) {
|
||||
this.membersList[processId] = member as Member;
|
||||
}
|
||||
}
|
||||
|
||||
const initMsg: InitMessage = JSON.parse(parsedMsg);
|
||||
this.updateRelay(url, initMsg.sp_address);
|
||||
const processes: [string, Process][] = JSON.parse(initMsg.processes_list!);
|
||||
// Write processes to db
|
||||
const record = processes.reduce((record, [outPoint, process]) => {
|
||||
record[outPoint] = process;
|
||||
return record;
|
||||
}, {} as Record<string, Process>);
|
||||
setTimeout(async () => {
|
||||
const newProcesses = handshakeMsg.processes_list;
|
||||
if (newProcesses && Object.keys(newProcesses).length !== 0) {
|
||||
for (const [processId, process] of Object.entries(newProcesses)) {
|
||||
const existing = await this.getProcess(processId);
|
||||
if (existing) {
|
||||
// Look for state id we don't know yet
|
||||
let new_states = [];
|
||||
let roles = [];
|
||||
for (const state of process.states) {
|
||||
if (!state.state_id || state.state_id === EMPTY32BYTES) { continue; }
|
||||
if (!this.lookForStateId(existing, state.state_id)) {
|
||||
new_states.push(state.state_id);
|
||||
roles.push(state.roles);
|
||||
}
|
||||
}
|
||||
|
||||
if (new_states.length != 0) {
|
||||
// We request the new states
|
||||
await this.requestDataFromPeers(processId, new_states, roles);
|
||||
}
|
||||
|
||||
// Otherwise we're probably just in the initial loading at page initialization
|
||||
|
||||
// We may learn an update for this process
|
||||
// TODO maybe actually check if what the relay is sending us contains more information than what we have
|
||||
// relay should always have more info than us, but we never know
|
||||
// For now let's keep it simple and let the worker do the job
|
||||
} else {
|
||||
// We add it to db
|
||||
console.log(`Saving ${processId} to db`);
|
||||
await this.saveProcessToDb(processId, process as Process);
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.restoreProcessesFromBackUp(record);
|
||||
}, 500)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse init message:', e);
|
||||
}
|
||||
}
|
||||
|
||||
private lookForStateId(process: Process, stateId: string): boolean {
|
||||
for (const state of process.states) {
|
||||
if (state.state_id === stateId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne la liste de tous les membres ordonnés par leur process id
|
||||
* @returns Un tableau contenant tous les membres
|
||||
*/
|
||||
public getAllMembersSorted(): Record<string, Member> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
|
||||
);
|
||||
}
|
||||
|
||||
public getAllMembers(): Record<string, Member> {
|
||||
return this.membersList;
|
||||
}
|
||||
|
||||
public getAddressesForMemberId(memberId: string): string[] | null {
|
||||
return this.membersList[memberId];
|
||||
}
|
||||
|
||||
public compareMembers(memberA: string[], memberB: string[]): boolean {
|
||||
if (!memberA || !memberB) { return false }
|
||||
if (memberA.length !== memberB.length) { return false }
|
||||
|
||||
const res = memberA.every(item => memberB.includes(item)) && memberB.every(item => memberA.includes(item));
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public async handleCommitError(response: string) {
|
||||
const content = JSON.parse(response);
|
||||
const error = content.error;
|
||||
const errorMsg = error['GenericError'];
|
||||
if (errorMsg === 'State is identical to the previous state') {
|
||||
return;
|
||||
} else if (errorMsg === 'Not enough valid proofs') { return; }
|
||||
// Wait and retry
|
||||
setTimeout(async () => {
|
||||
await this.sendCommitMessage(JSON.stringify(content));
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
|
||||
public getRoles(process: Process): Record<string, RoleDefinition> | null {
|
||||
const lastCommitedState = this.getLastCommitedState(process);
|
||||
if (lastCommitedState && lastCommitedState.roles && Object.keys(lastCommitedState.roles).length != 0) {
|
||||
return lastCommitedState!.roles;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public getPublicData(process: Process): Record<string, any> | null {
|
||||
const lastCommitedState = this.getLastCommitedState(process);
|
||||
if (lastCommitedState && lastCommitedState.public_data) {
|
||||
return lastCommitedState.public_data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public getProcessName(process: Process): string | null {
|
||||
const lastCommitedState = this.getLastCommitedState(process);
|
||||
if (lastCommitedState && lastCommitedState.public_data) {
|
||||
const processName = lastCommitedState!.public_data['processName'];
|
||||
if (processName) { return processName }
|
||||
else { return null }
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getMyProcesses(): Promise<string[]> {
|
||||
try {
|
||||
const processes = await this.getProcesses();
|
||||
|
||||
for (const [processId, process] of Object.entries(processes)) {
|
||||
// We use myProcesses attribute to not reevaluate all processes everytime
|
||||
if (this.myProcesses && this.myProcesses.has(processId)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const roles = this.getRoles(process);
|
||||
|
||||
if (roles && this.rolesContainsUs(roles)) {
|
||||
this.myProcesses.add(processId);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
return Array.from(this.myProcesses);
|
||||
} catch (e) {
|
||||
console.error("Failed to get processes:", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async requestDataFromPeers(processId: string, stateIds: string[], roles: Record<string, RoleDefinition>[]) {
|
||||
console.log('Requesting data from peers');
|
||||
console.log(roles);
|
||||
try {
|
||||
const res = this.sdkClient.request_data(processId, stateIds, roles);
|
||||
await this.handleApiReturn(res);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
public hexToBlob(hexString: string): Blob {
|
||||
if (hexString.length % 2 !== 0) {
|
||||
throw new Error("Invalid hex string: length must be even");
|
||||
}
|
||||
const uint8Array = new Uint8Array(hexString.length / 2);
|
||||
for (let i = 0; i < hexString.length; i += 2) {
|
||||
uint8Array[i / 2] = parseInt(hexString.substr(i, 2), 16);
|
||||
}
|
||||
|
||||
return new Blob([uint8Array], { type: "application/octet-stream" });
|
||||
}
|
||||
|
||||
public async blobToHex(blob: Blob): Promise<string> {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
return Array.from(bytes)
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
public getLastCommitedState(process: Process): ProcessState {
|
||||
if (process.states.length === 0) return null;
|
||||
const processTip = process.states[process.states.length - 1].commited_in;
|
||||
const lastCommitedState = process.states.findLast(state => state.commited_in !== processTip);
|
||||
if (lastCommitedState) {
|
||||
return lastCommitedState;
|
||||
} else {
|
||||
console.error('Can\'t find last commited state');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public isPairingProcess(roles: Record<string, RoleDefinition>): boolean {
|
||||
if (Object.keys(roles).length != 1) { return false }
|
||||
const pairingRole = roles['pairing'];
|
||||
if (pairingRole) {
|
||||
// For now that's enough, we should probably test more things
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,49 +1,40 @@
|
||||
import axios, { AxiosResponse } from 'axios';
|
||||
|
||||
export async function storeData(servers: string[], key: string, value: Blob, ttl: number | null): Promise<AxiosResponse | null> {
|
||||
export async function storeData(servers: string[], key: string, value: any, ttl: number | null): Promise<AxiosResponse | null> {
|
||||
for (const server of servers) {
|
||||
try {
|
||||
// Append key and ttl as query parameters
|
||||
const url = new URL(`${server}/store`);
|
||||
url.searchParams.append('key', key);
|
||||
if (ttl !== null) {
|
||||
url.searchParams.append('ttl', ttl.toString());
|
||||
}
|
||||
|
||||
// Send the encrypted ArrayBuffer as the raw request body.
|
||||
const response = await axios.post(url.toString(), value, {
|
||||
const response = await axios.post(`${server}/store`,
|
||||
{ key, value, ttl },
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
console.log('Data stored successfully:', key);
|
||||
withCredentials: true
|
||||
}
|
||||
);
|
||||
console.log('Data stored successfully:', response.data);
|
||||
if (response.status !== 200) {
|
||||
console.error('Received response status', response.status);
|
||||
continue;
|
||||
}
|
||||
console.log('Stored data:', response.data);
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (error?.response?.status === 409) {
|
||||
return null;
|
||||
}
|
||||
console.error('Error storing data:', error);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function retrieveData(servers: string[], key: string): Promise<ArrayBuffer | null> {
|
||||
export async function retrieveData(servers: string[], key: string): Promise<any | null> {
|
||||
for (const server of servers) {
|
||||
try {
|
||||
// When fetching the data from the server:
|
||||
const response = await axios.get(`${server}/retrieve/${key}`, {
|
||||
responseType: 'arraybuffer'
|
||||
});
|
||||
const response = await axios.get(`${server}/retrieve/${key}`);
|
||||
if (response.status !== 200) {
|
||||
console.error('Received response status', response.status);
|
||||
continue;
|
||||
}
|
||||
// console.log('Retrieved data:', response.data);
|
||||
console.log('Retrieved data:', response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving data:', error);
|
||||
@ -51,31 +42,3 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
interface TestResponse {
|
||||
key: string;
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
export async function testData(servers: string[], key: string): Promise<Record<string, boolean | null> | null> {
|
||||
const res = {};
|
||||
for (const server of servers) {
|
||||
res[server] = null;
|
||||
try {
|
||||
const response = await axios.get(`${server}/test/${key}`);
|
||||
if (response.status !== 200) {
|
||||
console.error(`${server}: Test response status: ${response.status}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const data: TestResponse = response.data;
|
||||
|
||||
res[server] = data.value;
|
||||
} catch (error) {
|
||||
console.error('Error retrieving data:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
@ -104,7 +104,6 @@ export function initAddressInput() {
|
||||
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
||||
const emojiDisplay = container.querySelector('#emoji-display-2');
|
||||
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
||||
const createButton = container.querySelector('#createButton') as HTMLButtonElement;
|
||||
addSubscription(addressInput, 'input', async () => {
|
||||
let address = addressInput.value;
|
||||
|
||||
@ -146,12 +145,6 @@ export function initAddressInput() {
|
||||
onOkButtonClick();
|
||||
});
|
||||
}
|
||||
|
||||
if (createButton) {
|
||||
addSubscription(createButton, 'click', () => {
|
||||
onCreateButtonClick();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function onOkButtonClick() {
|
||||
@ -165,46 +158,24 @@ async function onOkButtonClick() {
|
||||
}
|
||||
}
|
||||
|
||||
async function onCreateButtonClick() {
|
||||
try {
|
||||
await prepareAndSendPairingTx();
|
||||
} catch (e) {
|
||||
console.error(`onCreateButtonClick error: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareAndSendPairingTx(promptName: boolean = false) {
|
||||
export async function prepareAndSendPairingTx(secondDeviceAddress: string) {
|
||||
const service = await Services.getInstance();
|
||||
|
||||
// Device 1 wait Device 2
|
||||
// service.device1 = true;
|
||||
service.device1 = true;
|
||||
|
||||
try {
|
||||
await service.checkConnections([]);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
const sharedSecret = await service.getSecretForAddress(secondDeviceAddress);
|
||||
if (!sharedSecret) {
|
||||
const member = {
|
||||
sp_addresses: [secondDeviceAddress],
|
||||
};
|
||||
const connectMemberResult = await service.connectMember([member]);
|
||||
await service.handleApiReturn(connectMemberResult);
|
||||
}
|
||||
|
||||
// Prompt the user for a username.
|
||||
let userName;
|
||||
if (promptName) {
|
||||
userName = prompt("Please enter your user name:");
|
||||
} else {
|
||||
userName = "";
|
||||
}
|
||||
|
||||
// Create the process after a delay.
|
||||
// Create the process
|
||||
setTimeout(async () => {
|
||||
const relayAddress = service.getAllRelays();
|
||||
|
||||
// Pass the userName as an additional parameter.
|
||||
const createPairingProcessReturn = await service.createPairingProcess(
|
||||
userName,
|
||||
[],
|
||||
relayAddress[0].spAddress,
|
||||
1,
|
||||
userName
|
||||
);
|
||||
const createPairingProcessReturn = await service.createPairingProcess([secondDeviceAddress], relayAddress[0].spAddress, 1);
|
||||
|
||||
if (!createPairingProcessReturn.updated_process) {
|
||||
throw new Error('createPairingProcess returned an empty new process'); // This should never happen
|
||||
@ -221,21 +192,17 @@ export async function generateQRCode(spAddress: string) {
|
||||
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
||||
const qrCode = container?.querySelector('.qr-code img');
|
||||
qrCode?.setAttribute('src', url);
|
||||
|
||||
//Generate Address CopyBtn
|
||||
const address = container?.querySelector('.sp-address-btn');
|
||||
if (address) {
|
||||
address.textContent = 'Copy address';
|
||||
}
|
||||
const copyBtn = container.querySelector('#copyBtn');
|
||||
if (copyBtn) {
|
||||
addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateCreateBtn() {
|
||||
try{
|
||||
//Generate CreateBtn
|
||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
||||
const createBtn = container?.querySelector('.create-btn');
|
||||
if (createBtn) {
|
||||
createBtn.textContent = 'CREATE';
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
}
|
@ -5,15 +5,12 @@ export function cleanSubscriptions(): void {
|
||||
for (const sub of subscriptions) {
|
||||
const el = sub.element;
|
||||
const eventHandler = sub.eventHandler;
|
||||
if (el) {
|
||||
el.removeEventListener(sub.event, eventHandler);
|
||||
}
|
||||
}
|
||||
subscriptions = [];
|
||||
}
|
||||
|
||||
export function addSubscription(element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject): void {
|
||||
if (!element) return;
|
||||
subscriptions.push({ element, event, eventHandler });
|
||||
element.addEventListener(event, eventHandler);
|
||||
}
|
||||
|
@ -29,8 +29,8 @@ export async function initWebsocket(url: string) {
|
||||
const parsedMessage = JSON.parse(msgData);
|
||||
const services = await Services.getInstance();
|
||||
switch (parsedMessage.flag) {
|
||||
case 'Handshake':
|
||||
await services.handleHandshakeMsg(url, parsedMessage.content);
|
||||
case 'Init':
|
||||
await services.handleInitMsg(url, parsedMessage.content);
|
||||
break;
|
||||
case 'NewTx':
|
||||
await services.parseNewTx(parsedMessage.content);
|
||||
@ -38,10 +38,6 @@ export async function initWebsocket(url: string) {
|
||||
case 'Cipher':
|
||||
await services.parseCipher(parsedMessage.content);
|
||||
break;
|
||||
case 'Commit':
|
||||
// Basically if we see this it means we have an error
|
||||
await services.handleCommitError(parsedMessage.content);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Received an invalid message:', error);
|
||||
|
Loading…
x
Reference in New Issue
Block a user