pow-equix-wasm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # pow-equix-wasm
2
+
3
+ Preuve de travail **Equi-X** (celle que Tor utilise contre les dénis de service)
4
+ compilée en WebAssembly : **un seul module de 45 Kio** résout la preuve dans le
5
+ navigateur, sur plusieurs cœurs, et la vérifie côté serveur en quelques centaines
6
+ de microsecondes.
7
+
8
+ - **Démo et calibrage** : <https://contribulibre.github.io/pow-equix-wasm/>
9
+ - **Paquet npm** : [`pow-equix-wasm`](https://www.npmjs.com/package/pow-equix-wasm)
10
+
11
+ > *English summary: Equi-X proof of work (from Tor's Arti project) as a single
12
+ > WebAssembly module. It solves in the browser across Web Workers (cancellable,
13
+ > with progress) and verifies server-side in ~0.2 ms per part. The build is
14
+ > reproducible byte for byte. LGPL-3.0.*
15
+
16
+ ## Pourquoi Equi-X plutôt que SHA-256
17
+
18
+ Une preuve SHA-256 (façon hashcash) se calcule des milliers de fois plus vite sur
19
+ une carte graphique ou une puce de minage que dans un navigateur. Equi-X tire au
20
+ sort un nouveau programme HashX à chaque essai et demande environ 1,8 Mio de
21
+ mémoire par essai : l’avantage d’un attaquant équipé tombe à un facteur de
22
+ l’ordre de 20 face à un navigateur. La vérification, elle, reste très bon marché.
23
+
24
+ ## Protocole
25
+
26
+ Le défi d’un essai est `graine ‖ compteur` (compteur u32 petit-boutiste). La
27
+ graine appartient à l’appelant : en général un domaine propre à son protocole,
28
+ un octet nul, puis l’empreinte SHA-256 de la requête à protéger
29
+ (`construireGraine`). Une preuve calculée pour une requête ne vaut donc rien pour
30
+ une autre.
31
+
32
+ - Equi-X trouve en moyenne deux solutions par défi. Une solution est retenue si
33
+ `blake2b-256(défi ‖ solution)`, lu en u32 gros-boutiste, multiplié par
34
+ l’**effort**, ne dépasse pas 2³² − 1 : c’est la règle d’effort de Tor (`hs_pow`).
35
+ - Une preuve réunit **`nombre` parts** de 20 octets (`compteur ‖ solution`), aux
36
+ compteurs strictement croissants. Plusieurs petites preuves plutôt qu’une
37
+ grande rendent l’attente régulière (écart type relatif en `1/√nombre`).
38
+ - Probabilité qu’un essai aboutisse : environ `1 − e^(−2/effort)`, soit 86 %
39
+ pour l’effort 1, 62 % pour 2, 12 % pour 16 (`probabiliteEssai`).
40
+
41
+ ## Utilisation
42
+
43
+ ```ts
44
+ import { ModuleEquix, construireGraine, hexadecimal, resoudre } from 'pow-equix-wasm'
45
+
46
+ // Navigateur : le module est un fichier du paquet, que le bundler publie (ici Vite).
47
+ import urlEquix from 'pow-equix-wasm/equix.wasm?url'
48
+ const octets = new Uint8Array(await (await fetch(urlEquix)).arrayBuffer())
49
+
50
+ const graine = await construireGraine('mon-service/1', JSON.stringify(requete))
51
+ const annulation = new AbortController()
52
+ const { parts, essais } = await resoudre({
53
+ octets, graine, effort: 1, nombre: 4,
54
+ signal: annulation.signal,
55
+ onProgression: ({ essais, parts, memoireOctets }) => { /* … */ },
56
+ })
57
+ envoyer({ ...requete, preuve: hexadecimal(parts) })
58
+ ```
59
+
60
+ Côté serveur (Bun, Node, Deno), la même bibliothèque vérifie :
61
+
62
+ ```ts
63
+ import { readFile } from 'node:fs/promises'
64
+ import { ModuleEquix, construireGraine, depuisHexadecimal } from 'pow-equix-wasm'
65
+
66
+ const module = await ModuleEquix.instancier(await readFile(new URL(import.meta.resolve('pow-equix-wasm/equix.wasm'))))
67
+ const graine = await construireGraine('mon-service/1', JSON.stringify(requeteSansPreuve))
68
+ const valide = module.verifier(graine, depuisHexadecimal(preuve) ?? new Uint8Array(), 1, 4)
69
+ ```
70
+
71
+ Une page qui ne peut rien télécharger (ouverte en `file://`, script unique) peut
72
+ intégrer le module en base64 :
73
+
74
+ ```ts
75
+ import { octetsEquix } from 'pow-equix-wasm/octets'
76
+ const octets = octetsEquix()
77
+ ```
78
+
79
+ Ce qui reste à la charge de l’appelant, et que le paquet ne fait pas :
80
+ refuser les preuves rejouées, vérifier la fraîcheur de la requête (horodatage
81
+ dans le contenu haché) et limiter le débit des vérifications.
82
+
83
+ ### Web Workers
84
+
85
+ `resoudre` répartit les compteurs entre des Web Workers créés depuis un Blob
86
+ (aucun fichier supplémentaire à publier) : par défaut un par cœur annoncé, huit
87
+ au plus, et jamais plus que d’essais attendus. Si les Web Workers sont refusés
88
+ (politique de sécurité, `file://` dans certains navigateurs), le calcul continue
89
+ sur le fil courant, essai par essai. `fils: 0` force ce mode.
90
+
91
+ ## Mesures
92
+
93
+ Linux x86_64, un fil, module WebAssembly :
94
+
95
+ | | Chromium | Bun 1.4 |
96
+ |---|---|---|
97
+ | un essai | ≈ 410 ms | ≈ 400 ms |
98
+ | vérification d’une part | ≈ 230 µs | ≈ 250 µs |
99
+ | mémoire par fil | ≈ 1,8 Mio de zone de travail (2,9 Mio pour l’instance) | |
100
+
101
+ Les temps varient fortement d’un appareil à l’autre : c’est tout l’objet de la
102
+ page de démo, qui mesure sur l’appareil utilisé le temps d’une preuve (médiane,
103
+ 90ᵉ centile), la mémoire par fil et le coût de la vérification, et exporte le
104
+ tout en JSON pour comparer plusieurs appareils.
105
+
106
+ ## Construction reproductible
107
+
108
+ Le module est construit, jamais versionné : `dist/` et `site/` sont produits
109
+ par la CI.
110
+
111
+ - Rust figé par `rust-toolchain.toml`, dépendances verrouillées par `Cargo.lock`
112
+ (`cargo build --locked`), chemins locaux effacés du binaire
113
+ (`--remap-path-prefix`), pas de compilation incrémentale.
114
+ - `bun run verify:reproductible` reconstruit depuis une copie des sources placée
115
+ ailleurs et exige un module identique à l’octet près.
116
+ - Chaque release GitHub donne le SHA-256 du module publié ; pour le vérifier :
117
+ `bun run build && bun run verify:reproductible --attendu <sha256>`.
118
+
119
+ ```sh
120
+ bun install
121
+ bun run check # tests Rust et TS, construction, démo, reproductibilité
122
+ bun run demo # construit puis sert la démo sur http://127.0.0.1:4600/
123
+ ```
124
+
125
+ Il faut Rust (via rustup, qui installe seul la version figée et la cible
126
+ `wasm32-unknown-unknown`) et Bun.
127
+
128
+ ## Publication
129
+
130
+ - **Démo** : chaque push sur `main` la publie sur GitHub Pages (réglage du dépôt :
131
+ *Settings → Pages → Source : GitHub Actions*).
132
+ - **npm** : pousser un tag `vX.Y.Z` égal à la version de `package.json`. Le
133
+ workflow vérifie tout, publie sans aucun secret (publication de confiance
134
+ npm par OIDC, avec provenance signée), puis crée la release GitHub avec
135
+ `equix.wasm` et son empreinte.
136
+
137
+ ## Organisation
138
+
139
+ - `crates/pow-equix` : défi, résolution et vérification en Rust ; réutilisable en
140
+ natif (option `compilateur` pour générer du code machine HashX, par exemple
141
+ dans une application Tauri).
142
+ - `crates/pow-equix-wasm` : interface C minimale vers WebAssembly, sans
143
+ wasm-bindgen.
144
+ - `src/index.ts` : chargeur, Web Workers, annulation, progression, vérification.
145
+ - `demo/` : page de démo et de calibrage.
146
+
147
+ ## Licence
148
+
149
+ LGPL-3.0 (voir `LICENSE` et `COPYING`). Le module intègre les crates `equix` et
150
+ `hashx` du projet [Arti](https://gitlab.torproject.org/tpo/core/arti) de Tor,
151
+ elles-mêmes sous LGPL-3.0, d’après les algorithmes de tevador.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "rustc": "rustc 1.93.1 (01f6ddf75 2026-02-11)",
4
+ "octets": 44968,
5
+ "sha256": "f6c72e8e6b48386c23b6d1259c1739fef0711b11ffa692bcaed3e40a5a41c840"
6
+ }
Binary file
@@ -0,0 +1,94 @@
1
+ /**
2
+ * pow-equix-wasm : preuve de travail Equi-X pour le web.
3
+ *
4
+ * Un seul module WebAssembly résout (navigateur, Web Workers) et vérifie
5
+ * (serveur Bun, Node ou Deno). Ce fichier ne dépend ni du DOM ni d’un
6
+ * bundler : chaque environnement fournit les octets du module comme il peut
7
+ * (`fetch` de `pow-equix-wasm/equix.wasm`, lecture de fichier, ou
8
+ * `pow-equix-wasm/octets` qui les intègre en base64).
9
+ *
10
+ * Protocole : le défi d’un essai est `graine ‖ compteur` (u32 petit-boutiste).
11
+ * Une preuve réunit `nombre` parts de 20 octets, `compteur ‖ solution Equi-X`,
12
+ * aux compteurs strictement croissants ; chaque solution doit passer la règle
13
+ * d’effort de Tor (`hs_pow`). Voir README.md.
14
+ */
15
+ export declare const VERSION_FORMAT = 1;
16
+ export declare const GRAINE_MAX = 256;
17
+ export declare const TAILLE_SOLUTION = 16;
18
+ export declare const TAILLE_PART: number;
19
+ export declare const PARTS_MAX = 64;
20
+ /** Au-delà, l’effort n’a plus de sens : une chance sur 2³² par solution. */
21
+ export declare const EFFORT_MAX: number;
22
+ export declare function effortValide(effort: number): boolean;
23
+ export declare function nombreValide(nombre: number): boolean;
24
+ /** Un module Equi-X instancié. Une instance n’est pas réentrante : un appel à la fois. */
25
+ export declare class ModuleEquix {
26
+ private readonly exports;
27
+ private constructor();
28
+ static instancier(source: BufferSource | WebAssembly.Module): Promise<ModuleEquix>;
29
+ /** Mémoire linéaire actuellement réservée par le module, en octets. */
30
+ get memoireOctets(): number;
31
+ private tampon;
32
+ /** Vérifie une preuve complète ; quelques centaines de microsecondes par part. */
33
+ verifier(graine: Uint8Array, parts: Uint8Array, effort: number, nombre: number): boolean;
34
+ /** Un essai de résolution : la solution retenue pour ce compteur, ou null. */
35
+ essayer(graine: Uint8Array, compteur: number, effort: number): Uint8Array | null;
36
+ }
37
+ /**
38
+ * Graine conseillée : le domaine (UTF-8), un octet nul, puis l’empreinte SHA-256
39
+ * du contenu à protéger. Le domaine sépare les protocoles : une preuve calculée
40
+ * pour l’un ne vaut rien pour l’autre.
41
+ */
42
+ export declare function construireGraine(domaine: string, contenu: string | Uint8Array): Promise<Uint8Array>;
43
+ /**
44
+ * Probabilité qu’un essai aboutisse. Equi-X donne en moyenne deux solutions par
45
+ * défi, chacune retenue avec une chance sur `effort` : 1 − e^(−2/effort),
46
+ * légèrement réduit par les défis sans programme HashX valide. Mesuré : 0,858
47
+ * pour l’effort 1, 0,623 pour 2, 0,119 pour 16.
48
+ */
49
+ export declare function probabiliteEssai(effort: number): number;
50
+ /** Nombre moyen d’essais pour une preuve de `nombre` parts. */
51
+ export declare function essaisAttendus(effort: number, nombre: number): number;
52
+ export declare function hexadecimal(octets: Uint8Array): string;
53
+ export declare function depuisHexadecimal(texte: string): Uint8Array | null;
54
+ export interface Progression {
55
+ /** Essais cumulés, tous fils confondus. */
56
+ essais: number;
57
+ /** Parts trouvées, au plus `nombre`. */
58
+ parts: number;
59
+ /** Mémoire WebAssembly cumulée des fils en cours, en octets. */
60
+ memoireOctets: number;
61
+ }
62
+ export interface OptionsResolution {
63
+ /** Octets du module, transmis tels quels aux Web Workers. */
64
+ octets: Uint8Array;
65
+ graine: Uint8Array;
66
+ effort: number;
67
+ nombre: number;
68
+ onProgression?: (progression: Progression) => void;
69
+ signal?: AbortSignal;
70
+ /**
71
+ * Nombre de Web Workers ; par défaut un par cœur annoncé, huit au plus, et
72
+ * jamais plus que d’essais attendus : un fil sans essai à mener ne ferait que
73
+ * disputer le processeur aux autres. 0 force le calcul sur le fil courant.
74
+ */
75
+ fils?: number;
76
+ /** Fabrique de Web Worker, remplaçable (tests, politique de sécurité particulière). */
77
+ creerTravailleur?: () => Worker;
78
+ }
79
+ export interface Resolution {
80
+ parts: Uint8Array;
81
+ essais: number;
82
+ /** Nombre de fils effectivement utilisés ; 0 pour le fil courant. */
83
+ fils: number;
84
+ /** Mémoire WebAssembly maximale cumulée de tous les fils, en octets. */
85
+ memoireOctets: number;
86
+ }
87
+ /** Nombre de fils par défaut : un par cœur annoncé, huit au plus. */
88
+ export declare function filsParDefaut(): number;
89
+ /**
90
+ * Résout une preuve dans des Web Workers, un compteur sur `fils` chacun. Sans
91
+ * Web Worker disponible ou autorisé, le calcul se fait sur le fil courant,
92
+ * essai par essai, en rendant la main entre deux essais.
93
+ */
94
+ export declare function resoudre(options: OptionsResolution): Promise<Resolution>;
package/dist/index.js ADDED
@@ -0,0 +1,248 @@
1
+ // src/index.ts
2
+ var VERSION_FORMAT = 1;
3
+ var GRAINE_MAX = 256;
4
+ var TAILLE_SOLUTION = 16;
5
+ var TAILLE_PART = 4 + TAILLE_SOLUTION;
6
+ var PARTS_MAX = 64;
7
+ var EFFORT_MAX = 2 ** 32 - 1;
8
+ function exportsValides(exports) {
9
+ return exports.memory instanceof WebAssembly.Memory && ["tampon_adresse", "tampon_taille", "graine_max", "version_format", "verifier", "essayer"].every((nom) => typeof exports[nom] === "function");
10
+ }
11
+ function effortValide(effort) {
12
+ return Number.isInteger(effort) && effort >= 1 && effort <= EFFORT_MAX;
13
+ }
14
+ function nombreValide(nombre) {
15
+ return Number.isInteger(nombre) && nombre >= 1 && nombre <= PARTS_MAX;
16
+ }
17
+ function graineValide(graine) {
18
+ return graine.length >= 1 && graine.length <= GRAINE_MAX;
19
+ }
20
+
21
+ class ModuleEquix {
22
+ exports;
23
+ constructor(exports) {
24
+ this.exports = exports;
25
+ }
26
+ static async instancier(source) {
27
+ const module = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source);
28
+ const instance = await WebAssembly.instantiate(module, {});
29
+ if (!exportsValides(instance.exports))
30
+ throw new Error("Module Equi-X invalide.");
31
+ if (instance.exports.version_format() !== VERSION_FORMAT)
32
+ throw new Error("Module Equi-X d’une autre version du format.");
33
+ if (instance.exports.graine_max() !== GRAINE_MAX)
34
+ throw new Error("Module Equi-X incompatible avec ce chargeur.");
35
+ return new ModuleEquix(instance.exports);
36
+ }
37
+ get memoireOctets() {
38
+ return this.exports.memory.buffer.byteLength;
39
+ }
40
+ tampon() {
41
+ return new Uint8Array(this.exports.memory.buffer, this.exports.tampon_adresse(), this.exports.tampon_taille());
42
+ }
43
+ verifier(graine, parts, effort, nombre) {
44
+ if (!graineValide(graine) || !nombreValide(nombre) || !effortValide(effort) || parts.length !== nombre * TAILLE_PART)
45
+ return false;
46
+ const tampon = this.tampon();
47
+ tampon.set(graine, 0);
48
+ tampon.set(parts, GRAINE_MAX);
49
+ return this.exports.verifier(graine.length, effort >>> 0, nombre) === 1;
50
+ }
51
+ essayer(graine, compteur, effort) {
52
+ if (!graineValide(graine) || !effortValide(effort))
53
+ throw new Error("Graine ou effort invalide.");
54
+ this.tampon().set(graine, 0);
55
+ if (this.exports.essayer(graine.length, effort >>> 0, compteur >>> 0) !== 1)
56
+ return null;
57
+ return this.tampon().slice(GRAINE_MAX, GRAINE_MAX + TAILLE_SOLUTION);
58
+ }
59
+ }
60
+ async function construireGraine(domaine, contenu) {
61
+ const encodeur = new TextEncoder;
62
+ const prefixe = encodeur.encode(domaine);
63
+ const octets = typeof contenu === "string" ? encodeur.encode(contenu) : new Uint8Array(contenu);
64
+ const empreinte = new Uint8Array(await crypto.subtle.digest("SHA-256", octets));
65
+ const graine = new Uint8Array(prefixe.length + 1 + empreinte.length);
66
+ graine.set(prefixe, 0);
67
+ graine.set(empreinte, prefixe.length + 1);
68
+ if (!graineValide(graine))
69
+ throw new Error(`Domaine trop long : la graine ne doit pas dépasser ${GRAINE_MAX} octets.`);
70
+ return graine;
71
+ }
72
+ function probabiliteEssai(effort) {
73
+ return 0.99 * (1 - Math.exp(-2 / Math.max(1, effort)));
74
+ }
75
+ function essaisAttendus(effort, nombre) {
76
+ return nombre / probabiliteEssai(effort);
77
+ }
78
+ function hexadecimal(octets) {
79
+ return Array.from(octets, (octet) => octet.toString(16).padStart(2, "0")).join("");
80
+ }
81
+ function depuisHexadecimal(texte) {
82
+ if (texte.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(texte))
83
+ return null;
84
+ const octets = new Uint8Array(texte.length / 2);
85
+ for (let index = 0;index < octets.length; index++)
86
+ octets[index] = Number.parseInt(texte.slice(index * 2, index * 2 + 2), 16);
87
+ return octets;
88
+ }
89
+ function corpsTravailleur() {
90
+ const portee = self;
91
+ portee.onmessage = async (evenement) => {
92
+ const { octets, graine, effort, debut, pas, graineMax } = evenement.data;
93
+ try {
94
+ const { instance } = await WebAssembly.instantiate(octets, {});
95
+ const exports = instance.exports;
96
+ for (let compteur = debut;compteur <= 4294967295; compteur += pas) {
97
+ new Uint8Array(exports.memory.buffer, exports.tampon_adresse(), graine.length).set(graine);
98
+ const trouve = exports.essayer(graine.length, effort, compteur) === 1;
99
+ const solution = trouve ? new Uint8Array(exports.memory.buffer, exports.tampon_adresse() + graineMax, 16).slice() : null;
100
+ portee.postMessage({ type: "essai", compteur, solution, memoire: exports.memory.buffer.byteLength });
101
+ }
102
+ portee.postMessage({ type: "erreur", message: "Compteurs épuisés." });
103
+ } catch (erreur) {
104
+ portee.postMessage({ type: "erreur", message: erreur instanceof Error ? erreur.message : String(erreur) });
105
+ }
106
+ };
107
+ }
108
+ var urlTravailleur;
109
+ function travailleurParDefaut() {
110
+ urlTravailleur ??= URL.createObjectURL(new Blob([`(${corpsTravailleur.toString()})()`], { type: "text/javascript" }));
111
+ return new Worker(urlTravailleur);
112
+ }
113
+ function erreurAnnulation(signal) {
114
+ return signal.reason ?? new DOMException("Calcul annulé.", "AbortError");
115
+ }
116
+ function filsParDefaut() {
117
+ const coeurs = typeof navigator !== "undefined" && Number.isInteger(navigator.hardwareConcurrency) ? navigator.hardwareConcurrency : 1;
118
+ return Math.max(1, Math.min(8, coeurs));
119
+ }
120
+ function assembler(trouvees, nombre) {
121
+ const parts = new Uint8Array(nombre * TAILLE_PART);
122
+ const vue = new DataView(parts.buffer);
123
+ const compteurs = [...trouvees.keys()].sort((gauche, droite) => gauche - droite).slice(0, nombre);
124
+ compteurs.forEach((compteur, index) => {
125
+ vue.setUint32(index * TAILLE_PART, compteur, true);
126
+ parts.set(trouvees.get(compteur), index * TAILLE_PART + 4);
127
+ });
128
+ return parts;
129
+ }
130
+
131
+ class ErreurTravailleur extends Error {
132
+ }
133
+ async function resoudre(options) {
134
+ const { graine, effort, nombre, signal } = options;
135
+ if (!graineValide(graine) || !effortValide(effort) || !nombreValide(nombre))
136
+ throw new Error("Paramètres de preuve invalides.");
137
+ signal?.throwIfAborted();
138
+ const fils = options.fils === undefined ? Math.min(filsParDefaut(), Math.ceil(essaisAttendus(effort, nombre))) : Math.max(0, Math.floor(options.fils));
139
+ const disponible = typeof Worker === "function" && typeof Blob === "function" && typeof URL.createObjectURL === "function";
140
+ const creer = options.creerTravailleur ?? (disponible ? travailleurParDefaut : undefined);
141
+ if (fils > 0 && creer) {
142
+ try {
143
+ return await resoudreEnParallele(options, creer, fils);
144
+ } catch (erreur) {
145
+ if (signal?.aborted || !(erreur instanceof ErreurTravailleur))
146
+ throw erreur;
147
+ }
148
+ }
149
+ return resoudreSurCeFil(options);
150
+ }
151
+ async function resoudreSurCeFil(options) {
152
+ const { graine, effort, nombre, signal, onProgression } = options;
153
+ const module = await ModuleEquix.instancier(options.octets);
154
+ const trouvees = new Map;
155
+ let essais = 0;
156
+ for (let compteur = 0;trouvees.size < nombre; compteur++) {
157
+ signal?.throwIfAborted();
158
+ const solution = module.essayer(graine, compteur, effort);
159
+ essais++;
160
+ if (solution)
161
+ trouvees.set(compteur, solution);
162
+ onProgression?.({ essais, parts: trouvees.size, memoireOctets: module.memoireOctets });
163
+ if (trouvees.size < nombre)
164
+ await new Promise((resolve) => setTimeout(resolve, 0));
165
+ }
166
+ signal?.throwIfAborted();
167
+ return { parts: assembler(trouvees, nombre), essais, fils: 0, memoireOctets: module.memoireOctets };
168
+ }
169
+ function resoudreEnParallele(options, creer, fils) {
170
+ const { graine, effort, nombre, signal, onProgression } = options;
171
+ return new Promise((resolve, reject) => {
172
+ const travailleurs = [];
173
+ const memoires = new Map;
174
+ const trouvees = new Map;
175
+ let essais = 0;
176
+ let memoireMax = 0;
177
+ let fini = false;
178
+ const terminer = () => {
179
+ fini = true;
180
+ for (const travailleur of travailleurs)
181
+ travailleur.terminate();
182
+ signal?.removeEventListener("abort", annuler);
183
+ };
184
+ const annuler = () => {
185
+ if (fini)
186
+ return;
187
+ terminer();
188
+ reject(erreurAnnulation(signal));
189
+ };
190
+ const echouer = (message) => {
191
+ if (fini)
192
+ return;
193
+ terminer();
194
+ reject(new ErreurTravailleur(message));
195
+ };
196
+ signal?.addEventListener("abort", annuler, { once: true });
197
+ try {
198
+ for (let index = 0;index < fils; index++) {
199
+ const travailleur = creer();
200
+ travailleurs.push(travailleur);
201
+ travailleur.onerror = (evenement) => {
202
+ evenement.preventDefault?.();
203
+ echouer(evenement.message || "Web Worker Equi-X indisponible.");
204
+ };
205
+ travailleur.onmessage = (evenement) => {
206
+ if (fini)
207
+ return;
208
+ const message = evenement.data;
209
+ if (message.type === "erreur")
210
+ return echouer(message.message ?? "Erreur du Web Worker Equi-X.");
211
+ essais++;
212
+ if (message.memoire)
213
+ memoires.set(index, message.memoire);
214
+ const memoire = [...memoires.values()].reduce((somme, valeur) => somme + valeur, 0);
215
+ memoireMax = Math.max(memoireMax, memoire);
216
+ if (message.solution && message.compteur !== undefined)
217
+ trouvees.set(message.compteur, message.solution);
218
+ onProgression?.({ essais, parts: Math.min(trouvees.size, nombre), memoireOctets: memoire });
219
+ if (trouvees.size >= nombre) {
220
+ terminer();
221
+ resolve({ parts: assembler(trouvees, nombre), essais, fils, memoireOctets: memoireMax });
222
+ }
223
+ };
224
+ travailleur.postMessage({ octets: options.octets.slice().buffer, graine, effort, debut: index, pas: fils, graineMax: GRAINE_MAX });
225
+ }
226
+ } catch (erreur) {
227
+ echouer(erreur instanceof Error ? erreur.message : String(erreur));
228
+ }
229
+ });
230
+ }
231
+ export {
232
+ EFFORT_MAX,
233
+ GRAINE_MAX,
234
+ ModuleEquix,
235
+ PARTS_MAX,
236
+ TAILLE_PART,
237
+ TAILLE_SOLUTION,
238
+ VERSION_FORMAT,
239
+ construireGraine,
240
+ depuisHexadecimal,
241
+ effortValide,
242
+ essaisAttendus,
243
+ filsParDefaut,
244
+ hexadecimal,
245
+ nombreValide,
246
+ probabiliteEssai,
247
+ resoudre
248
+ };
@@ -0,0 +1,4 @@
1
+ /** Octets du module Equi-X, décodés à chaque appel (une copie neuve). */
2
+ export declare function octetsEquix(): Uint8Array
3
+ /** Empreinte SHA-256 du module intégré. */
4
+ export declare const SHA256_EQUIX: string