Compare commits

...

4 Commits

Author SHA1 Message Date
Tommy Verrall a231c6ac4e Merge branch 'develop' into tommy/update-example-nymify 2023-11-06 14:53:27 +01:00
Tommy Verrall 4f4e0bd5e8 Merge branch 'dependabot/go_modules/wasm/mix-fetch/go-mix-conn/golang.org/x/net-0.17.0' into tommy/update-example-nymify 2023-10-18 11:36:04 +02:00
Tommy Verrall 4e823ef79d amend a few things
- reintroduce the doFetch after changing code swept it away...
- prevent multiple submission at the same time
- remove toggle for the time being
2023-10-16 13:03:05 +02:00
Tommy Verrall b20b943d74 amend example
. themify to the nym content
. use process.env files to drive connections to desired throuhput
. use gui based toggle to return json data or plain html
2023-10-16 11:36:58 +02:00
5 changed files with 581 additions and 324 deletions
+8
View File
@@ -0,0 +1,8 @@
HIDDEN_GATEWAY_OWNER=
HIDDEN_GATEWAY_EXPLICIT_IP=
HIDDEN_GATEWAY_HOST=
HIDDEN_GATEWAY_SPHINX_KEY=
HIDDEN_GATEWAY_IDENTITY_KEY=
PREFFERED_NETWORK_REQUESTER=""
PREFERRED_GATEWAY=
PREFERRED_VALIDATOR=https://sandbox-nym-api1.nymtech.net/api
+188 -19
View File
@@ -1,27 +1,196 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<head> <meta charset="UTF-8" />
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>NYM MixFetch Demo</title>
<title>Nym MixFetch Demo</title>
<script src="bootstrap.js"></script> <script src="bootstrap.js"></script>
</head> <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
<link
rel="stylesheet"
href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css"
/>
<style>
body {
font-family: "Arial", sans-serif;
background-color: #fb6e4e;
padding: 50px 0;
align-items: center;
font-family: "Arial", sans-serif;
background-color: #000000;
background-image: url("https://nymtech.net/uploads/Header_22516d90f6.svg");
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
padding: 50px 0;
align-items: center;
}
<body> .container {
<h1> Mix Fetch Demo</h1> background-color: #212428;
<div> color: #f2f2f2;
<label>Target Host: </label> box-shadow: 0px 2px 4px -1px rgba(0, 0, 0, 0.2),
<input type="text" size = "60" id="fetch_payload" value="..."> 0px 4px 5px 0px rgba(0, 0, 0, 0.14),
<button id="fetch-button"> Fetch </button> 0px 1px 10px 0px rgba(0, 0, 0, 0.12);
</div> background-image: linear-gradient(
rgba(255, 255, 255, 0.09),
rgba(255, 255, 255, 0.09)
);
margin: 0 auto 25px;
padding: 50px;
flex-direction: column;
max-width: 1200px;
box-sizing: border-box;
flex-shrink: 0;
position: static;
background-image: none;
box-shadow: none;
justify-content: space-between;
align-items: center;
position: relative;
}
h1 {
font-size: 28px;
margin-bottom: 40px;
font-weight: bold;
text-align: center;
background-color: #f2f2f2;
padding: 10px;
border-radius: 5px;
}
<hr> .mb-3 {
<p> margin-bottom: 30px;
<span id="output"></span> }
</p>
</body> .form-label {
font-weight: bold;
margin-bottom: 10px;
}
</html> .btn-primary,
.btn-primary:hover,
.btn-primary:active,
.btn-primary:visited {
background-color: hsl(11, 96%, 65%) !important;
color: black;
font-weight: bold;
}
.ui-accordion .ui-accordion-header {
background-color: hsl(0, 39%, 19%);
border: color(from color srgb r g b);
font-size: 20px;
padding: auto;
transition: background-color 0.4s ease;
margin: 0 0 20px 0;
align-items: center;
}
.ui-accordion .ui-accordion-header:hover {
background-color: hsl(0, 61%, 58%);
}
.ui-accordion .ui-accordion-content {
border-top: none;
align-items: center;
padding: 20px;
}
.logo-container {
text-align: center;
margin-bottom: 30px;
}
#nym-logo {
width: 150px;
height: auto;
}
</style>
</head>
<div class="logo-container">
<img
src="https://nymtech.net/icons/nym_logo.svg"
alt="Nym Logo"
id="nym-logo"
/>
</div>
<body>
<div class="container" id="accordion1">
<h3>Mix Fetch Demo</h3>
<div>
<div class="mb-6">
<label for="urlInput" class="form-label">Target Host:</label>
<input
type="text"
class="form-control"
id="fetch_payload"
placeholder="Enter URL"
/>
</div>
<br />
<!-- comment out for the time being..
<div class="mb-6">
<label class="form-label">Return JSON:</label>
<div class="form-check form-switch">
<input
class="form-check-input"
type="checkbox"
id="returnJsonToggle"
checked
/>
<label class="form-check-label" for="returnJsonToggle"
>Yes/No</label
>
</div>
</div> -->
<br />
<button class="btn btn-primary w-100" id="fetch-button">Fetch</button>
</div>
</div>
<div class="container" id="accordion2">
<h3>Result</h3>
<div>
<div class="mb-6">
<p>
<span id="output"></span>
</p>
</div>
</div>
</div>
<script>
$(function () {
$("#accordion1").accordion({
heightStyle: "content",
collapsible: true,
active: false,
animate: {
duration: 400,
easing: "easeInOutQuart",
},
});
$("#accordion2").accordion({
heightStyle: "content",
collapsible: true,
active: false,
animate: {
duration: 400,
easing: "easeInOutQuart",
},
});
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
+91 -49
View File
@@ -13,55 +13,90 @@
// limitations under the License. // limitations under the License.
class WebWorkerClient { class WebWorkerClient {
worker = null; worker = null;
constructor() { constructor(onComplete) {
this.worker = new Worker('./worker.js'); this.worker = new Worker("./worker.js");
this.worker.onmessage = (ev) => { this.worker.onmessage = (ev) => {
if (ev.data && ev.data.kind) { if (ev.data && ev.data.kind) {
switch (ev.data.kind) { switch (ev.data.kind) {
case 'DisplayString': case "DisplayString":
const { rawString } = ev.data.args; const { rawString } = ev.data.args;
displayReceivedRawString(rawString) displayReceivedRawString(rawString);
break; break;
}
}
};
}
doFetch = (target) => {
if (!this.worker) {
console.error('Could not send message because worker does not exist');
return;
} }
if(onComplete) {
onComplete();
}
}
};
}
this.worker.postMessage({ doFetch = (target) => {
kind: 'FetchPayload', if (!this.worker) {
args: { console.error("Could not send message because worker does not exist");
target, return;
},
});
} }
this.worker.postMessage({
kind: "FetchPayload",
args: {
target,
},
});
};
} }
let client = null; let client = null;
async function main() { async function main() {
client = new WebWorkerClient(); client = new WebWorkerClient(() => {
fetchButton.disabled = false;
});
const fetchButton = document.querySelector('#fetch-button'); const fetchButton = document.querySelector("#fetch-button");
fetchButton.onclick = function () {
doFetch(); fetchButton.onclick = function (e) {
if (fetchButton.disabled) {
alert("Processing... Please wait!");
return;
} }
document.getElementById("output").innerHTML = "";
if ($("#fetch_payload").val().trim() === "") {
e.preventDefault();
let errorDiv = document.createElement("div");
let paragraph = document.createElement("p");
paragraph.style.color = "red";
paragraph.innerText = "Please enter a valid request!!";
errorDiv.appendChild(paragraph);
document.getElementById("output").appendChild(errorDiv);
return false;
}
fetchButton.disabled = true;
client.doFetch($("#fetch_payload").val().trim());
};
} }
async function doFetch() { async function doFetch() {
const payload = document.getElementById('fetch_payload').value; document
await client.doFetch(payload) .getElementById("fetch-button")
.addEventListener("click", async () => {
const url = document.getElementById("fetch_payload").value;
//introduce toggle in the future
//const returnJson = document.getElementById("returnJsonToggle").checked;
displaySend(`clicked the button and the payload is: ${payload}...`); try {
await client.doFetch(url);
} catch (error) {
console.error("There was a problem fetching the data:", error);
}
});
} }
/** /**
@@ -70,27 +105,34 @@ async function doFetch() {
* @param {string} message * @param {string} message
*/ */
function displaySend(message) { function displaySend(message) {
let timestamp = new Date().toISOString().substr(11, 12); let timestamp = new Date().toISOString().substr(11, 12);
let sendDiv = document.createElement('div'); let sendDiv = document.createElement("div");
let paragraph = document.createElement('p'); let paragraph = document.createElement("p");
paragraph.setAttribute('style', 'color: blue'); paragraph.style.color = "blue";
let paragraphContent = document.createTextNode(timestamp + ' sent >>> ' + message); paragraph.innerText = timestamp + " sent >>> " + message;
paragraph.appendChild(paragraphContent);
sendDiv.appendChild(paragraph); sendDiv.appendChild(paragraph);
document.getElementById('output').appendChild(sendDiv); document.getElementById("output").appendChild(sendDiv);
} }
function displayReceivedRawString(raw) { function displayReceivedRawString(raw) {
let timestamp = new Date().toISOString().substr(11, 12); let timestamp = new Date().toISOString().substr(11, 12);
let receivedDiv = document.createElement('div'); let receivedDiv = document.createElement("div");
let paragraph = document.createElement('p'); receivedDiv.style.overflow = "auto";
paragraph.setAttribute('style', 'color: green'); receivedDiv.style.wordWrap = "break-word";
let paragraphContent = document.createTextNode(timestamp + ' received >>> ' + raw);
paragraph.appendChild(paragraphContent); let paragraph = document.createElement("p");
receivedDiv.appendChild(paragraph); paragraph.style.color = "green";
document.getElementById('output').appendChild(receivedDiv); paragraph.style.fontWeight = "bold";
paragraph.innerText = timestamp + " received >>> " + JSON.stringify(raw);
receivedDiv.appendChild(paragraph);
document.getElementById("output").appendChild(receivedDiv);
let lineBreak = document.createElement("br");
document.getElementById("output").appendChild(lineBreak);
} }
main(); main();
+59 -34
View File
@@ -1,37 +1,62 @@
const CopyWebpackPlugin = require('copy-webpack-plugin'); const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require('path'); const dotenv = require("dotenv").config().parsed;
const path = require("path");
const webpack = require("webpack");
module.exports = { module.exports = {
performance: { performance: {
hints: false, hints: false,
maxEntrypointSize: 512000, maxEntrypointSize: 512000,
maxAssetSize: 512000 maxAssetSize: 512000,
}, },
entry: { entry: {
bootstrap: './bootstrap.js', bootstrap: "./bootstrap.js",
worker: './worker.js', worker: "./worker.js",
}, },
output: { output: {
path: path.resolve(__dirname, 'dist'), path: path.resolve(__dirname, "dist"),
filename: '[name].js', filename: "[name].js",
}, },
mode: 'development', mode: "development",
// mode: 'production', // mode: 'production',
plugins: [ plugins: [
new CopyWebpackPlugin({ new CopyWebpackPlugin({
patterns: [ patterns: [
'index.html', "index.html",
{ {
from: '../pkg/*.(js|wasm)', from: "../pkg/*.(js|wasm)",
to: '[name][ext]', to: "[name][ext]",
}, },
{ {
from: '../go-mix-conn/build/*.(js|wasm)', from: "../go-mix-conn/build/*.(js|wasm)",
to: '[name][ext]', to: "[name][ext]",
}, },
], ],
}), }),
new webpack.DefinePlugin({
], "process.env.HIDDEN_GATEWAY_OWNER": JSON.stringify(
experiments: { syncWebAssembly: true }, dotenv.HIDDEN_GATEWAY_OWNER
),
"process.env.HIDDEN_GATEWAY_EXPLICIT_IP": JSON.stringify(
dotenv.HIDDEN_GATEWAY_EXPLICIT_IP
),
"process.env.HIDDEN_GATEWAY_HOST": JSON.stringify(
dotenv.HIDDEN_GATEWAY_HOST
),
"process.env.HIDDEN_GATEWAY_SPHINX_KEY": JSON.stringify(
dotenv.HIDDEN_GATEWAY_SPHINX_KEY
),
"process.env.HIDDEN_GATEWAY_IDENTITY_KEY": JSON.stringify(
dotenv.HIDDEN_GATEWAY_IDENTITY_KEY
),
"process.env.PREFFERED_NETWORK_REQUESTER": JSON.stringify(
dotenv.PREFFERED_NETWORK_REQUESTER
),
"process.env.PREFERRED_GATEWAY": JSON.stringify(dotenv.PREFERRED_GATEWAY),
"process.env.PREFERRED_VALIDATOR": JSON.stringify(
dotenv.PREFERRED_VALIDATOR
),
}),
],
experiments: { syncWebAssembly: true },
}; };
+235 -222
View File
@@ -12,31 +12,32 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
const RUST_WASM_URL = "mix_fetch_wasm_bg.wasm" const RUST_WASM_URL = "mix_fetch_wasm_bg.wasm";
const GO_WASM_URL = "go_conn.wasm" const GO_WASM_URL = "go_conn.wasm";
importScripts('mix_fetch_wasm.js'); importScripts("mix_fetch_wasm.js");
importScripts('wasm_exec.js'); importScripts("wasm_exec.js");
console.log('Initializing worker'); console.log("Initializing worker");
// wasm_bindgen creates a global variable (with the exports attached) that is in scope after `importScripts` // wasm_bindgen creates a global variable (with the exports attached) that is in scope after `importScripts`
const { const {
default_debug, default_debug,
no_cover_debug, no_cover_debug,
NymClient, NymClient,
set_panic_hook, set_panic_hook,
Config, Config,
GatewayEndpointConfig, GatewayEndpointConfig,
ClientStorage, ClientStorage,
MixFetchConfig, MixFetchConfig,
send_client_data, send_client_data,
start_new_mixnet_connection, start_new_mixnet_connection,
setupMixFetch, setupMixFetch,
disconnectMixFetch, disconnectMixFetch,
setupMixFetchWithConfig, setupMixFetchWithConfig,
mix_fetch_initialised, mix_fetch_initialised,
finish_mixnet_connection} = wasm_bindgen; finish_mixnet_connection,
} = wasm_bindgen;
let client = null; let client = null;
let tester = null; let tester = null;
@@ -44,93 +45,101 @@ const go = new Go(); // Defined in wasm_exec.js
var goWasm; var goWasm;
async function logFetchResult(res) { async function logFetchResult(res) {
console.log(res) let text = await res.text();
let text = await res.text() console.log("HEADERS: ", ...res.headers);
console.log("HEADERS: ", ...res.headers) console.log("STATUS: ", res.status);
console.log("STATUS: ", res.status) console.log("STATUS TEXT: ", res.statusText);
console.log("STATUS TEXT: ", res.statusText) console.log("OK: ", res.ok);
console.log("OK: ", res.ok) console.log("TYPE: ", res.type);
console.log("TYPE: ", res.type) console.log("URL: ", res.url);
console.log("URL: ", res.url) console.log("BODYUSED: ", res.bodyUsed);
console.log("BODYUSED: ", res.bodyUsed) console.log("REDIRECTED: ", res.redirected);
console.log("REDIRECTED: ", res.redirected) console.log("TEXT: ", text);
console.log("TEXT: ", text)
try {
console.log(text);
self.postMessage({ self.postMessage({
kind: 'DisplayString', kind: "DisplayString",
args: { args: {
rawString: text, rawString: text,
}, },
}); });
} catch (error) {
console.error("Error: ", error);
}
} }
async function wasm_bindgenSetup() { async function wasm_bindgenSetup() {
const preferredGateway = "6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; const preferredGateway = env.process.PREFERRED_GATEWAY;
const validator = 'https://qa-nym-api.qa.nymte.ch/api'; const validator = env.process.PREFERRED_VALIDATOR;
// local // local
const mixFetchNetworkRequesterAddress= "2o47bhnXWna6VEyt4mXMGQQAbXfpKmX7BkjkxUz8uQVi.6uQGnCqSczpXwh86NdbsCoDDXuqZQM9Uwko8GE7uC9g8@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; const mixFetchNetworkRequesterAddress =
// const mixFetchNetworkRequesterAddress= "GqiGWmKRCbGQFSqH88BzLKijvZgipnqhmbNFsmkZw84t.4L8sXFuAUyUYyHZYgMdM3AtiusKnYUft6Pd8e41rrCHA@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; env.process.PREFFERED_NETWORK_REQUESTER;
// const mixFetchNetworkRequesterAddress= "GqiGWmKRCbGQFSqH88BzLKijvZgipnqhmbNFsmkZw84t.4L8sXFuAUyUYyHZYgMdM3AtiusKnYUft6Pd8e41rrCHA@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM";
// STEP 1. construct config // STEP 1. construct config
// those are just some examples, there are obviously more permutations; // those are just some examples, there are obviously more permutations;
// note, the extra optional argument is of the following type: // note, the extra optional argument is of the following type:
// /* // /*
// export interface MixFetchConfigOpts { // export interface MixFetchConfigOpts {
// id?: string; // id?: string;
// nymApi?: string; // nymApi?: string;
// nyxd?: string; // nyxd?: string;
// debug?: DebugWasm; // debug?: DebugWasm;
// } // }
// */ // */
// //
// const debug = no_cover_debug() // const debug = no_cover_debug()
// //
// #1 // #1
// const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { id: 'my-awesome-mix-fetch-client', nymApi: validator, debug: debug} ); // const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { id: 'my-awesome-mix-fetch-client', nymApi: validator, debug: debug} );
// #2 // #2
// const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { nymApi: validator, debug: debug} ); // const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { nymApi: validator, debug: debug} );
// #3 // #3
// const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { id: 'my-awesome-mix-fetch-client' } ); // const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { id: 'my-awesome-mix-fetch-client' } );
// //
// #4 // #4
const differentDebug = default_debug() const differentDebug = default_debug();
const updatedTraffic = differentDebug.traffic; const updatedTraffic = differentDebug.traffic;
updatedTraffic.use_extended_packet_size = true updatedTraffic.use_extended_packet_size = true;
updatedTraffic.average_packet_delay_ms = 666; updatedTraffic.average_packet_delay_ms = 666;
differentDebug.traffic = updatedTraffic; differentDebug.traffic = updatedTraffic;
const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, { debug: differentDebug } ); const config = new MixFetchConfig(mixFetchNetworkRequesterAddress, {
// debug: differentDebug,
// // STEP 2. setup the client });
// // note, the extra optional argument is of the following type: //
// /* // // STEP 2. setup the client
// export interface MixFetchOptsSimple { // // note, the extra optional argument is of the following type:
// preferredGateway?: string; // /*
// storagePassphrase?: string; // export interface MixFetchOptsSimple {
// } // preferredGateway?: string;
// */ // storagePassphrase?: string;
// #1 // }
await setupMixFetchWithConfig(config) // */
// // #1
// #2 await setupMixFetchWithConfig(config);
// await setupMixFetchWithConfig(config, { storagePassphrase: "foomp" }) //
// // #2
// #3 // await setupMixFetchWithConfig(config, { storagePassphrase: "foomp" })
// await setupMixFetchWithConfig(config, { storagePassphrase: "foomp", preferredGateway }) //
// #3
// await setupMixFetchWithConfig(config, { storagePassphrase: "foomp", preferredGateway })
} }
async function nativeSetup() { async function nativeSetup() {
// const preferredGateway = "6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; const preferredGateway = process.env.PREFERRED_GATEWAY;
// const validator = 'https://qa-nym-api.qa.nymte.ch/api'; const validator = process.env.PREFERRED_VALIDATOR;
// local // local
// const preferredNetworkRequester= "2o47bhnXWna6VEyt4mXMGQQAbXfpKmX7BkjkxUz8uQVi.6uQGnCqSczpXwh86NdbsCoDDXuqZQM9Uwko8GE7uC9g8@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; const preferredNetworkRequester = process.env.PREFFERED_NETWORK_REQUESTER;
// const preferredNetworkRequester= "GqiGWmKRCbGQFSqH88BzLKijvZgipnqhmbNFsmkZw84t.4L8sXFuAUyUYyHZYgMdM3AtiusKnYUft6Pd8e41rrCHA@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM"; // const preferredNetworkRequester= "GqiGWmKRCbGQFSqH88BzLKijvZgipnqhmbNFsmkZw84t.4L8sXFuAUyUYyHZYgMdM3AtiusKnYUft6Pd8e41rrCHA@6qQYb4ArXANU6HJDxzH4PFCUqYb39Dae2Gem2KpxescM";
// those are just some examples, there are obviously more permutations; // those are just some examples, there are obviously more permutations;
// note, the extra optional argument is of the following type: // note, the extra optional argument is of the following type:
/* /*
export interface MixFetchOpts extends MixFetchOptsSimple { export interface MixFetchOpts extends MixFetchOptsSimple {
clientId?: string; clientId?: string;
nymApiUrl?: string; nymApiUrl?: string;
@@ -147,165 +156,169 @@ async function nativeSetup() {
and `DebugWasmOverride` is a rather nested struct that you can look up yourself : ) and `DebugWasmOverride` is a rather nested struct that you can look up yourself : )
*/ */
// #1 // #1
// await setupMixFetch(preferredNetworkRequester) // await setupMixFetch(preferredNetworkRequester)
// #2 // #2
// await setupMixFetch(preferredNetworkRequester, { nymApiUrl: validator }) // await setupMixFetch(preferredNetworkRequester, { nymApiUrl: validator })
// // #3 // // #3
const noCoverTrafficOverride = { const noCoverTrafficOverride = {
traffic: { disableMainPoissonPacketDistribution: true }, traffic: { disableMainPoissonPacketDistribution: true },
coverTraffic: { disableLoopCoverTrafficStream: true }, coverTraffic: { disableLoopCoverTrafficStream: true },
} };
const mixFetchOverride = { const mixFetchOverride = {
requestTimeoutMs: 10000 requestTimeoutMs: 10000,
} };
const extra = { const extra = {
hiddenGateways: [ hiddenGateways: [
{ {
owner: "LoveIslandEnjoyer", owner: process.env.HIDDEN_GATEWAY_OWNER,
host: "gateway1.nymtech.net", explicitIp: process.env.HIDDEN_GATEWAY_EXPLICIT_IP,
explicitIp: "213.219.38.119", host: process.env.HIDDEN_GATEWAY_HOST,
identityKey: "E3mvZTHQCdBvhfr178Swx9g4QG3kkRUun7YnToLMcMbM", sphinxKey: process.env.HIDDEN_GATEWAY_SPHINX_KEY,
sphinxKey: "CYcrjoJ8GT7Dp54zViUyyRUfegeRCyPifWQZHRgMZrfX" identityKey: process.env.HIDDEN_GATEWAY_IDENTITY_KEY,
} },
] ],
} };
await setupMixFetch({ await setupMixFetch({
// preferredNetworkRequester, preferredNetworkRequester,
preferredGateway: "E3mvZTHQCdBvhfr178Swx9g4QG3kkRUun7YnToLMcMbM", preferredGateway: preferredGateway,
storagePassphrase: "foomp", storagePassphrase: "foomp",
forceTls: true, forceTls: true,
// nymApiUrl: validator, nymApiUrl: validator,
clientId: "my-client", clientId: "my-client",
clientOverride: noCoverTrafficOverride, clientOverride: noCoverTrafficOverride,
mixFetchOverride, mixFetchOverride,
extra extra,
}) });
} }
async function testMixFetch() { async function testMixFetch() {
console.log('Instantiating Mix Fetch...'); console.log("Instantiating Mix Fetch...");
// await wasm_bindgenSetup() // await wasm_bindgenSetup()
await nativeSetup() await nativeSetup();
console.log("Mix Fetch client running!");
console.log('Mix Fetch client running!'); // Set callback to handle messages passed to the worker.
self.onmessage = async (event) => {
if (event.data && event.data.kind) {
switch (event.data.kind) {
case "FetchPayload": {
const { target } = event.data.args;
const url = target;
// Set callback to handle messages passed to the worker. // const args = { mode: "ors", redirect: "manual", signal }
self.onmessage = async event => { const args = {
if (event.data && event.data.kind) { mode: "unsafe-ignore-cors",
switch (event.data.kind) { headers: {
case 'FetchPayload': { "Content-Type": "application/json",
const {target} = event.data.args; },
const url = target; };
// const args = { mode: "ors", redirect: "manual", signal } try {
const args = { mode: "unsafe-ignore-cors" } console.log("using mixFetch...");
const mixFetchRes = await mixFetch(url, args);
console.log(">>> MIX FETCH");
await logFetchResult(mixFetchRes);
console.log("done");
} catch (e) {
console.error("mix fetch request failure: ", e);
}
try { // console.log("will disconnect");
console.log('using mixFetch...'); // await disconnectMixFetch()
const mixFetchRes = await mixFetch(url, args) //
console.log(">>> MIX FETCH") // try {
await logFetchResult(mixFetchRes) // console.log('using mixFetch...');
// const mixFetchRes = await mixFetch(url, args)
// console.log(">>> MIX FETCH")
// await logFetchResult(mixFetchRes)
//
// console.log('done')
//
// } catch(e) {
// console.error("mix fetch request failure: ", e)
// }
console.log('done') // try {
// console.log('using normal Fetch...');
} catch(e) { // const fetchRes = await fetch(url, args)
console.error("mix fetch request failure: ", e) // console.log(">>> NORMAL FETCH")
} // await logFetchResult(fetchRes)
// } catch(e) {
// console.log("will disconnect"); // console.error("fetch request failure: ", e)
// await disconnectMixFetch() // }
//
// try {
// console.log('using mixFetch...');
// const mixFetchRes = await mixFetch(url, args)
// console.log(">>> MIX FETCH")
// await logFetchResult(mixFetchRes)
//
// console.log('done')
//
// } catch(e) {
// console.error("mix fetch request failure: ", e)
// }
// try {
// console.log('using normal Fetch...');
// const fetchRes = await fetch(url, args)
// console.log(">>> NORMAL FETCH")
// await logFetchResult(fetchRes)
// } catch(e) {
// console.error("fetch request failure: ", e)
// }
}
}
} }
}; }
}
};
} }
// TODO: look into https://www.aaron-powell.com/posts/2019-02-08-golang-wasm-5-compiling-with-webpack/ // TODO: look into https://www.aaron-powell.com/posts/2019-02-08-golang-wasm-5-compiling-with-webpack/
async function loadGoWasm() { async function loadGoWasm() {
const resp = await fetch(GO_WASM_URL); const resp = await fetch(GO_WASM_URL);
if ('instantiateStreaming' in WebAssembly) { if ("instantiateStreaming" in WebAssembly) {
const wasmObj = await WebAssembly.instantiateStreaming(resp, go.importObject) const wasmObj = await WebAssembly.instantiateStreaming(
goWasm = wasmObj.instance resp,
go.run(goWasm) go.importObject
} else { );
const bytes = await resp.arrayBuffer() goWasm = wasmObj.instance;
const wasmObj = await WebAssembly.instantiate(bytes, go.importObject) go.run(goWasm);
goWasm = wasmObj.instance } else {
go.run(goWasm) const bytes = await resp.arrayBuffer();
} const wasmObj = await WebAssembly.instantiate(bytes, go.importObject);
goWasm = wasmObj.instance;
go.run(goWasm);
}
} }
function setupRsGoBridge() { function setupRsGoBridge() {
// (note: reason for intermediate `__rs_go_bridge__` object is to decrease global scope bloat // (note: reason for intermediate `__rs_go_bridge__` object is to decrease global scope bloat
// and to discourage users from trying to call those methods directly) // and to discourage users from trying to call those methods directly)
self.__rs_go_bridge__ = {} self.__rs_go_bridge__ = {};
self.__rs_go_bridge__.send_client_data = send_client_data self.__rs_go_bridge__.send_client_data = send_client_data;
self.__rs_go_bridge__.start_new_mixnet_connection = start_new_mixnet_connection self.__rs_go_bridge__.start_new_mixnet_connection =
self.__rs_go_bridge__.mix_fetch_initialised = mix_fetch_initialised start_new_mixnet_connection;
self.__rs_go_bridge__.finish_mixnet_connection = finish_mixnet_connection self.__rs_go_bridge__.mix_fetch_initialised = mix_fetch_initialised;
self.__rs_go_bridge__.finish_mixnet_connection = finish_mixnet_connection;
} }
async function main() { async function main() {
console.log(">>>>>>>>>>>>>>>>>>>>> JS WORKER MAIN START"); console.log(">>>>>>>>>>>>>>>>>>>>> JS WORKER MAIN START");
// load rust WASM package // load rust WASM package
await wasm_bindgen(RUST_WASM_URL); await wasm_bindgen(RUST_WASM_URL);
console.log('Loaded RUST WASM'); console.log("Loaded RUST WASM");
// load go WASM package // load go WASM package
await loadGoWasm(); await loadGoWasm();
console.log("Loaded GO WASM"); console.log("Loaded GO WASM");
// sets up better stack traces in case of in-rust panics // sets up better stack traces in case of in-rust panics
set_panic_hook(); set_panic_hook();
setupRsGoBridge(); setupRsGoBridge();
goWasmSetLogging("trace") goWasmSetLogging("trace");
// test mixFetch // test mixFetch
await testMixFetch(); await testMixFetch();
// //
// // run test on simplified and dedicated tester: // // run test on simplified and dedicated tester:
// // await testWithTester() // // await testWithTester()
// //
// // hook-up the whole client for testing // // hook-up the whole client for testing
// // await testWithNymClient() // // await testWithNymClient()
// //
// // 'Normal' client setup (to send 'normal' messages) // // 'Normal' client setup (to send 'normal' messages)
// // await normalNymClientUsage() // // await normalNymClientUsage()
// //
console.log(">>>>>>>>>>>>>>>>>>>>> JS WORKER MAIN END") console.log(">>>>>>>>>>>>>>>>>>>>> JS WORKER MAIN END");
} }
// Let's get started! // Let's get started!
main(); main();