Skip to content

Commit

Permalink
Reorganise web resources
Browse files Browse the repository at this point in the history
  • Loading branch information
fl0rek committed Oct 24, 2023
1 parent 835b4eb commit e6c9161
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 81 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ nmt-rs = { workspace = true }
rand = { version = "0.8.5", optional = true }
ruint = { version = "1.8.0", features = ["serde"] }
serde = { version = "1.0.164", features = ["derive"] }
serde_repr = { version = "0.1", optional = true }
serde_repr = "0.1"
sha2 = "0.10.7"
tendermint = { workspace = true, features = ["std", "rust-crypto"] }
tendermint-proto = { workspace = true }
Expand All @@ -44,5 +44,5 @@ serde_json = "1.0.97"

[features]
default = ["p2p"]
p2p = ["dep:libp2p-identity", "dep:multiaddr", "dep:serde_repr"]
p2p = ["dep:libp2p-identity", "dep:multiaddr"]
test-utils = ["dep:ed25519-consensus", "dep:rand"]
5 changes: 3 additions & 2 deletions types/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use anyhow::{Context, Result};
#[cfg(not(target_arch = "wasm32"))]
use clap::ValueEnum;
use libp2p::Multiaddr;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[cfg_attr(not(target_arch = "wasm32"), derive(ValueEnum))]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
#[repr(u8)]
pub enum Network {
Arabica,
Mocha,
Expand Down
1 change: 1 addition & 0 deletions wasm-node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ tracing-wasm = "0.2.1"
wasm-bindgen = "0.2.87"
wasm-bindgen-futures = "0.4.37"
web-sys = { version = "0.3.64", features = ["console"]}
serde_json = "1.0.107"

[dev-dependencies]
wasm-bindgen-test = "0.3.34"
Expand Down
1 change: 1 addition & 0 deletions wasm-node/pkg/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*
29 changes: 29 additions & 0 deletions wasm-node/rsc/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>celestia-node-rs</title>
<script type="module" src="/js/run_node.js"></script>
</head>
<body>
<h1>Celestia Node</h1>
<h2>Network</h2>
<select id="network_id">
<option value="0">Arabica</option>
<option value="1">Mocha</option>
<option value="2">Private</option>
</select>
<h2>Bootnodes</h2>
<textarea id="bootnodes" cols=80 rows=10>
</textarea>
<h2>Genesis Hash</h2>
<input type="text" id="genesis" size=80 />

<button id="start">Start!</button>

<h3>Status</h3>
<h4>PeerId</h4><div id="peer_id"></div>
<h4>Syncer</h4><div id="syncer"></div>
<h4>Peers</h4><div id="peers"></div>
</body>
</html>
44 changes: 44 additions & 0 deletions wasm-node/rsc/run_node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
Error.stackTraceLimit = 99;

import init, { setup, Network, WasmNode, WasmNodeConfig, canonical_network_bootnodes, network_genesis } from "/wasm/wasm_node.js";

// initialize wasm
await init();
// setup logging and console panic hook
await setup();

const response = await fetch('/cfg.json');
const json = await response.json();

console.log("Received config:", json);

const network = json.network;
let bootnodes = json.bootnodes
if (bootnodes.length === 0) {
bootnodes = canonical_network_bootnodes(network);
}
const genesis = network_genesis(network);

document.getElementById("network_id").value = network;
document.getElementById("genesis").value = genesis;
document.getElementById("bootnodes").value = bootnodes.join("\n");

document.getElementById("start").addEventListener("click", async function(ev) {
document.getElementById("start").setAttribute("disabled", "disabled");

const network = Number(document.getElementById("network_id").value);
const genesis = document.getElementById("genesis").value;
const bootnodes = document.getElementById("bootnodes").value.split("\n");

console.log("starting with:", network, bootnodes, genesis);

const config = new WasmNodeConfig(network, genesis, bootnodes);
window.node = await new WasmNode(config);

setInterval(async function() {
document.getElementById("peer_id").innerText = JSON.stringify(await window.node.local_peer_id());
document.getElementById("syncer").innerText = JSON.stringify(await window.node.syncer_info());
document.getElementById("peers").innerText = JSON.stringify(await window.node.connected_peers());
}, 1000);

}, false);
102 changes: 26 additions & 76 deletions wasm-node/src/bin/serve.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use anyhow::Result;
use axum::body;
use axum::extract::State;
use axum::http::Uri;
use axum::extract::{Path, State};
use axum::http::{header, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use clap::Parser;
use libp2p::Multiaddr;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use tokio::{spawn, time};
Expand All @@ -22,10 +22,14 @@ pub struct WasmNodeArgs {
pub bootnodes: Vec<Multiaddr>,
}

#[derive(rust_embed::RustEmbed)]
#[derive(RustEmbed)]
#[folder = "pkg"]
struct WasmPackage;

#[derive(RustEmbed)]
#[folder = "rsc"]
struct StaticResources;

#[derive(Debug, Clone, Parser)]
struct Args {
/// Network to connect.
Expand All @@ -52,7 +56,9 @@ async fn main() -> Result<()> {

let app = Router::new()
.route("/", get(serve_index_html))
.fallback(serve_wasm_pkg)
.route("/js/*script", get(serve_embedded_path::<StaticResources>))
.route("/wasm/*binary", get(serve_embedded_path::<WasmPackage>))
.route("/cfg.json", get(serve_config))
.with_state(state);

spawn(axum::Server::bind(&args.listen_addr).serve(app.into_make_service()));
Expand All @@ -62,9 +68,14 @@ async fn main() -> Result<()> {
}
}

async fn serve_wasm_pkg(uri: Uri) -> Result<Response, StatusCode> {
let path = uri.path().trim_start_matches('/').to_string();
if let Some(content) = WasmPackage::get(&path) {
async fn serve_index_html() -> Result<impl IntoResponse, StatusCode> {
serve_embedded_path::<StaticResources>(Path("index.html".to_string())).await
}

async fn serve_embedded_path<Source: RustEmbed>(
Path(path): Path<String>,
) -> Result<Response, StatusCode> {
if let Some(content) = Source::get(&path) {
let mime = mime_guess::from_path(&path).first_or_octet_stream();
Ok(Response::builder()
.header(header::CONTENT_TYPE, mime.as_ref())
Expand All @@ -75,72 +86,11 @@ async fn serve_wasm_pkg(uri: Uri) -> Result<Response, StatusCode> {
}
}

async fn serve_index_html(_state: State<WasmNodeArgs>) -> Result<impl IntoResponse, StatusCode> {
//let args = serde_json::to_string(&state.0).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

Ok(Html(format!(
r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>celestia-node-rs</title>
<script type="module">
Error.stackTraceLimit = 99;
import init, {{ setup, Network, WasmNode, WasmNodeConfig, canonical_network_bootnodes, network_genesis }} from "/wasm_node.js";
// initialize wasm
await init();
// setup logging and console panic hook
await setup();
let network = Network.Mocha;
let bootnodes = canonical_network_bootnodes(network);
let genesis = network_genesis(network);
document.getElementById("network_id").value = network;
document.getElementById("genesis").value = genesis;
document.getElementById("bootnodes").value = bootnodes.join("\n");
document.getElementById("start").addEventListener("click", async function(ev) {{
document.getElementById("start").setAttribute("disabled", "disabled");
let network = Number(document.getElementById("network_id").value);
let genesis = document.getElementById("genesis").value;
let bootnodes = document.getElementById("bootnodes").value.split("\n");
console.log("starting with:", network, bootnodes, genesis);
let config = new WasmNodeConfig(network, genesis, bootnodes);
window.node = await new WasmNode(config);
setInterval(async function() {{
document.getElementById("syncer").innerText = JSON.stringify(await window.node.syncer_info());
}}, 500);
}}, false);
</script>
</head>
<body>
<h1>Celestia Node</h1>
<h2>Network</h2>
<select id="network_id">
<option value="0">Arabica</option>
<option value="1">Mocha</option>
<option value="2">Private</option>
</select>
<h2>Bootnodes</h2>
<textarea id="bootnodes" cols=80 rows=10>
</textarea>
<h2>Genesis Hash</h2>
<input type="text" id="genesis" size=80 />
<button id="start">Start!</button>
<h3>Status</div>
<div id="syncer"></div>
</body>
</html>
"#
)))
async fn serve_config(state: State<WasmNodeArgs>) -> Result<Response, StatusCode> {
let args = serde_json::to_string(&state.0).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

Ok(Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.body(body::boxed(body::Full::from(args)))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?)
}
2 changes: 1 addition & 1 deletion wasm-node/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use celestia_types::hash::Hash;
use js_sys::{Array, JsString};
use libp2p::identity::Keypair;
use libp2p::{identity, Multiaddr};
use serde_wasm_bindgen::{from_value, to_value};
use serde_wasm_bindgen::to_value;
use tracing::info;
use wasm_bindgen::prelude::*;

Expand Down

0 comments on commit e6c9161

Please sign in to comment.