Update to Anubis v1.28.2 (#1)
This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals. ## Approach The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable. The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations. ## Customizations kept - Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`. - `web/static/img/ATTRIBUTIONS.txt` stays deleted. - Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`. - Short README (the old `anubisc` typo is fixed). - Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose. - Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted. - `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages. - `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it. ## Deploy notes - **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop. - **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`). - Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in. ## Verification - `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`. - `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped). - Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:   - Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression. - `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone. Please review and merge when ready. I will not merge this myself. Reviewed-on: #1 Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
This commit was merged in pull request #1.
This commit is contained in:
1 parent
eb3e46d8d0
commit
caf4d72880
529 files changed
+33015
-6659
No files matched your search
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "anubis"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
wee_alloc = "0.4"
|
||||
@@ -0,0 +1,60 @@
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
extern crate wee_alloc;
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod hostimport {
|
||||
use crate::{DATA_BUFFER, DATA_LENGTH};
|
||||
|
||||
#[link(wasm_import_module = "anubis")]
|
||||
unsafe extern "C" {
|
||||
/// The runtime expects this function to be defined. It is called whenever the Anubis check
|
||||
/// worker processes about 1024 hashes. This can be a no-op if you want.
|
||||
fn anubis_update_nonce(nonce: u32);
|
||||
}
|
||||
|
||||
/// Safe wrapper to `anubis_update_nonce`.
|
||||
pub fn update_nonce(nonce: u32) {
|
||||
unsafe {
|
||||
anubis_update_nonce(nonce);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn data_ptr() -> *const u8 {
|
||||
let challenge = &DATA_BUFFER;
|
||||
challenge.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn set_data_length(len: u32) {
|
||||
let mut data_length = DATA_LENGTH.lock().unwrap();
|
||||
*data_length = len as usize;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod hostimport {
|
||||
pub fn update_nonce(_nonce: u32) {
|
||||
// This is intentionally blank
|
||||
}
|
||||
}
|
||||
|
||||
/// The data buffer is a bit weird in that it doesn't have an explicit length as it can
|
||||
/// and will change depending on the challenge input that was sent by the server.
|
||||
/// However, it can only fit 4096 bytes of data (one amd64 machine page). This is
|
||||
/// slightly overkill for the purposes of an Anubis check, but it's fine to assume
|
||||
/// that the browser can afford this much ram usage.
|
||||
///
|
||||
/// Callers should fetch the base data pointer, write up to 4096 bytes, and then
|
||||
/// `set_data_length` the number of bytes they have written
|
||||
///
|
||||
/// This is also functionally a write-only buffer, so it doesn't really matter that
|
||||
/// the length of this buffer isn't exposed.
|
||||
pub static DATA_BUFFER: LazyLock<[u8; 4096]> = LazyLock::new(|| [0; 4096]);
|
||||
pub static DATA_LENGTH: LazyLock<Mutex<usize>> = LazyLock::new(|| Mutex::new(0));
|
||||
|
||||
pub use hostimport::update_nonce;
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "argon2id"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.5"
|
||||
|
||||
anubis = { path = "../../anubis" }
|
||||
|
||||
[lints.clippy]
|
||||
nursery = { level = "warn", priority = -1 }
|
||||
pedantic = { level = "warn", priority = -1 }
|
||||
unwrap_used = "warn"
|
||||
uninlined_format_args = "allow"
|
||||
missing_panics_doc = "allow"
|
||||
missing_errors_doc = "allow"
|
||||
cognitive_complexity = "allow"
|
||||
@@ -0,0 +1,171 @@
|
||||
use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
|
||||
use argon2::Argon2;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Argon2id result and verification hashes are 32 bytes (256 bits). These are stored in
|
||||
/// static buffers due to the fact that you cannot easily pass data from host space to
|
||||
/// WebAssembly space.
|
||||
pub static RESULT_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
pub static VERIFICATION_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
/// Core validation function. Compare each bit in the hash by progressively masking bits until
|
||||
/// some are found to not be matching.
|
||||
///
|
||||
/// There are probably more clever ways to do this, likely involving lookup tables or something
|
||||
/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
|
||||
/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
|
||||
fn validate(hash: &[u8], difficulty: u32) -> bool {
|
||||
let mut remaining = difficulty;
|
||||
for &byte in hash {
|
||||
// If we're out of bits to check, exit. This is all good.
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// If there are more than 8 bits remaining, the entire byte should be a
|
||||
// zero. This fast-path compares the byte to 0 and if it matches, subtract
|
||||
// 8 bits.
|
||||
if remaining >= 8 {
|
||||
if byte != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining -= 8;
|
||||
} else {
|
||||
// Otherwise mask off individual bits and check against them.
|
||||
let mask = 0xFF << (8 - remaining);
|
||||
if (byte & mask) != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining = 0;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Computes the Argon2id hash for the given nonce.
|
||||
///
|
||||
/// The challenge bytes are used directly as the Argon2id password and the nonce is used as
|
||||
/// the salt, rather than hashing a hex-formatted `challenge || nonce` string as the
|
||||
/// JavaScript implementation does. Operating on the raw challenge bytes avoids the
|
||||
/// formatting round-trip.
|
||||
///
|
||||
/// The nonce is also randomly encoded in either big or little endian depending on the last
|
||||
/// byte of the data buffer in an effort to make it more annoying to automate with GPUs.
|
||||
fn compute_hash(nonce: u32) -> [u8; 32] {
|
||||
let data = &DATA_BUFFER;
|
||||
let data_len = *DATA_LENGTH.lock().unwrap();
|
||||
let data_slice: &[u8] = &data[..data_len];
|
||||
let use_le = data_slice.last().copied().unwrap_or(0) >= 128;
|
||||
let mut result = [0u8; 32];
|
||||
|
||||
let nonce = nonce as u64;
|
||||
|
||||
let nonce = if use_le {
|
||||
nonce.to_le_bytes()
|
||||
} else {
|
||||
nonce.to_be_bytes()
|
||||
};
|
||||
|
||||
let argon2 = Argon2::default();
|
||||
argon2
|
||||
.hash_password_into(&data_slice, &nonce, &mut result)
|
||||
.unwrap();
|
||||
result
|
||||
}
|
||||
|
||||
/// This function is the main entrypoint for the Anubis proof of work implementation.
|
||||
///
|
||||
/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
|
||||
/// The definition of what goes in the data buffer is an exercise for the implementor, but
|
||||
/// for Argon2id we store the challenge as "raw bytes". The data buffer is intentionally
|
||||
/// oversized so that the challenge value can be expanded in the future.
|
||||
///
|
||||
/// `difficulty` is the number of leading bits that must match `0` in order for the
|
||||
/// challenge to be successfully passed. This will be validated by the server.
|
||||
///
|
||||
/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
|
||||
/// appended to the challenge value in order to find a hash matching the specified
|
||||
/// difficulty.
|
||||
///
|
||||
/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
|
||||
/// every iteration of the proof of work loop. This will vary by how many threads are
|
||||
/// running the proof-of-work check, and also functions as a thread ID. This prevents
|
||||
/// wasting CPU time retrying a hash+nonce pair that likely won't work.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
|
||||
let mut nonce = initial_nonce;
|
||||
|
||||
loop {
|
||||
let hash = compute_hash(nonce);
|
||||
|
||||
if validate(&hash, difficulty) {
|
||||
// If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
|
||||
// can pick it up.
|
||||
let mut result = RESULT_HASH.lock().unwrap();
|
||||
result.copy_from_slice(&hash);
|
||||
return nonce;
|
||||
}
|
||||
|
||||
let old_nonce = nonce;
|
||||
nonce = nonce.wrapping_add(iterand);
|
||||
|
||||
// Report progress each time the search crosses into a new 1024-value window of the
|
||||
// nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
|
||||
// the total work done across all worker threads, which the client turns into a
|
||||
// progress bar and hashrate. Comparing the shifted window (rather than the original
|
||||
// `nonce > old_nonce + 1023`) reports correctly for any `iterand` and stays correct
|
||||
// across the u32 wraparound. (Only the nonce-0 worker's callback is live; the caller
|
||||
// silences the rest.)
|
||||
if (nonce >> 10) != (old_nonce >> 10) {
|
||||
update_nonce(nonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function is called by the server in order to validate a proof-of-work challenge.
|
||||
/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
|
||||
/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
|
||||
///
|
||||
/// If everything is good, it returns true. Otherwise, it returns false.
|
||||
///
|
||||
/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
|
||||
/// for now.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
|
||||
let computed = compute_hash(nonce);
|
||||
let valid = validate(&computed, difficulty);
|
||||
if !valid {
|
||||
return false;
|
||||
}
|
||||
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
computed == *verification
|
||||
}
|
||||
|
||||
// These functions exist to give pointers and lengths to the runtime around the Anubis
|
||||
// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
|
||||
// has statically allocated at compile time without having to assume how the Rust compiler
|
||||
// is going to lay it out.
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_ptr() -> *const u8 {
|
||||
let challenge = RESULT_HASH.lock().unwrap();
|
||||
challenge.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_size() -> usize {
|
||||
RESULT_HASH.lock().unwrap().len()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_ptr() -> *const u8 {
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
verification.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_size() -> usize {
|
||||
VERIFICATION_HASH.lock().unwrap().len()
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "hashx"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
equix = "0.6"
|
||||
hashx = "0.8"
|
||||
|
||||
anubis = { path = "../../anubis" }
|
||||
|
||||
[lints.clippy]
|
||||
nursery = { level = "warn", priority = -1 }
|
||||
pedantic = { level = "warn", priority = -1 }
|
||||
unwrap_used = "warn"
|
||||
uninlined_format_args = "allow"
|
||||
missing_panics_doc = "allow"
|
||||
missing_errors_doc = "allow"
|
||||
cognitive_complexity = "allow"
|
||||
@@ -0,0 +1,172 @@
|
||||
use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
|
||||
use hashx::HashX;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// HashX result and verification hashes are 32 bytes (256 bits). These are stored in static
|
||||
/// buffers due to the fact that you cannot easily pass data from host space to WebAssembly
|
||||
/// space.
|
||||
pub static RESULT_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
pub static VERIFICATION_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
/// Core validation function. Compare each bit in the hash by progressively masking bits until
|
||||
/// some are found to not be matching.
|
||||
///
|
||||
/// There are probably more clever ways to do this, likely involving lookup tables or something
|
||||
/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
|
||||
/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
|
||||
fn validate(hash: &[u8], difficulty: u32) -> bool {
|
||||
let mut remaining = difficulty;
|
||||
for &byte in hash {
|
||||
// If we're out of bits to check, exit. This is all good.
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// If there are more than 8 bits remaining, the entire byte should be a
|
||||
// zero. This fast-path compares the byte to 0 and if it matches, subtract
|
||||
// 8 bits.
|
||||
if remaining >= 8 {
|
||||
if byte != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining -= 8;
|
||||
} else {
|
||||
// Otherwise mask off individual bits and check against them.
|
||||
let mask = 0xFF << (8 - remaining);
|
||||
if (byte & mask) != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining = 0;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Build a `HashX` instance for the current challenge.
|
||||
///
|
||||
/// HashX rejects a small fraction of seeds (`Error::ProgramConstraints`). Rather than trap
|
||||
/// on those, derive a usable instance deterministically: the overwhelmingly common case is
|
||||
/// that the challenge bytes are accepted as-is, but if they are rejected we append an
|
||||
/// incrementing little-endian counter to the challenge until `HashX::new` accepts the seed.
|
||||
/// The client and server run this identical code, so they always agree on which seed — and
|
||||
/// therefore which program — is in use. The probability of needing even one retry is well
|
||||
/// under a percent, so the common path is unchanged on the wire.
|
||||
fn make_hashx() -> HashX {
|
||||
let data = &DATA_BUFFER;
|
||||
let data_len = *DATA_LENGTH.lock().unwrap();
|
||||
let data_slice: &[u8] = &data[..data_len];
|
||||
|
||||
if let Ok(h) = HashX::new(data_slice) {
|
||||
return h;
|
||||
}
|
||||
|
||||
let mut seed = Vec::with_capacity(data_slice.len() + 4);
|
||||
let mut counter: u32 = 0;
|
||||
loop {
|
||||
seed.clear();
|
||||
seed.extend_from_slice(data_slice);
|
||||
seed.extend_from_slice(&counter.to_le_bytes());
|
||||
if let Ok(h) = HashX::new(&seed) {
|
||||
return h;
|
||||
}
|
||||
counter = counter.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// This function is the main entrypoint for the Anubis proof of work implementation.
|
||||
///
|
||||
/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
|
||||
/// The definition of what goes in the data buffer is an exercise for the implementor, but
|
||||
/// for SHA-256 we store the hash as "raw bytes". The data buffer is intentionally oversized
|
||||
/// so that the challenge value can be expanded in the future.
|
||||
///
|
||||
/// `difficulty` is the number of leading bits that must match `0` in order for the
|
||||
/// challenge to be successfully passed. This will be validated by the server.
|
||||
///
|
||||
/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
|
||||
/// appended to the challenge value in order to find a hash matching the specified
|
||||
/// difficulty.
|
||||
///
|
||||
/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
|
||||
/// every iteration of the proof of work loop. This will vary by how many threads are
|
||||
/// running the proof-of-work check, and also functions as a thread ID. This prevents
|
||||
/// wasting CPU time retrying a hash+nonce pair that likely won't work.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
|
||||
let h = make_hashx();
|
||||
let mut nonce: u32 = initial_nonce;
|
||||
|
||||
loop {
|
||||
let hash = h.hash_to_bytes(nonce as u64);
|
||||
|
||||
if validate(&hash, difficulty) {
|
||||
// If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
|
||||
// can pick it up.
|
||||
let mut result = RESULT_HASH.lock().unwrap();
|
||||
result.copy_from_slice(&hash);
|
||||
return nonce;
|
||||
}
|
||||
|
||||
let old_nonce = nonce;
|
||||
nonce = nonce.wrapping_add(iterand);
|
||||
|
||||
// Report progress each time the search crosses into a new 1024-value window of the
|
||||
// nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
|
||||
// the total work done across all worker threads, which the client turns into a
|
||||
// progress bar and hashrate. Comparing the shifted window reports correctly for any
|
||||
// `iterand` and stays correct across the u32 wraparound. (Only the nonce-0 worker's
|
||||
// callback is live; the caller silences the rest.)
|
||||
if (nonce >> 10) != (old_nonce >> 10) {
|
||||
update_nonce(nonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function is called by the server in order to validate a proof-of-work challenge.
|
||||
/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
|
||||
/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
|
||||
///
|
||||
/// If everything is good, it returns true. Otherwise, it returns false.
|
||||
///
|
||||
/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
|
||||
/// for now.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
|
||||
let h = make_hashx();
|
||||
let computed = h.hash_to_bytes(nonce as u64);
|
||||
let valid = validate(&computed, difficulty);
|
||||
if !valid {
|
||||
return false;
|
||||
}
|
||||
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
computed == *verification
|
||||
}
|
||||
|
||||
// These functions exist to give pointers and lengths to the runtime around the Anubis
|
||||
// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
|
||||
// has statically allocated at compile time without having to assume how the Rust compiler
|
||||
// is going to lay it out.
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_ptr() -> *const u8 {
|
||||
let challenge = RESULT_HASH.lock().unwrap();
|
||||
challenge.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_size() -> usize {
|
||||
RESULT_HASH.lock().unwrap().len()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_ptr() -> *const u8 {
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
verification.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_size() -> usize {
|
||||
VERIFICATION_HASH.lock().unwrap().len()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "sha256"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
sha2 = "0.11"
|
||||
|
||||
anubis = { path = "../../anubis" }
|
||||
|
||||
[lints.clippy]
|
||||
nursery = { level = "warn", priority = -1 }
|
||||
pedantic = { level = "warn", priority = -1 }
|
||||
unwrap_used = "warn"
|
||||
uninlined_format_args = "allow"
|
||||
missing_panics_doc = "allow"
|
||||
missing_errors_doc = "allow"
|
||||
cognitive_complexity = "allow"
|
||||
@@ -0,0 +1,168 @@
|
||||
use anubis::{DATA_BUFFER, DATA_LENGTH, update_nonce};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// SHA-256 hashes are 32 bytes (256 bits). These are stored in static buffers due to the
|
||||
/// fact that you cannot easily pass data from host space to WebAssembly space.
|
||||
pub static RESULT_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
pub static VERIFICATION_HASH: LazyLock<Mutex<[u8; 32]>> = LazyLock::new(|| Mutex::new([0; 32]));
|
||||
|
||||
/// Core validation function. Compare each bit in the hash by progressively masking bits until
|
||||
/// some are found to not be matching.
|
||||
///
|
||||
/// There are probably more clever ways to do this, likely involving lookup tables or something
|
||||
/// really fun like that. However in my testing this lets us get up to 200 kilohashes per second
|
||||
/// on my Ryzen 7950x3D, up from about 50 kilohashes per second in JavaScript.
|
||||
fn validate(hash: &[u8], difficulty: u32) -> bool {
|
||||
let mut remaining = difficulty;
|
||||
for &byte in hash {
|
||||
// If we're out of bits to check, exit. This is all good.
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// If there are more than 8 bits remaining, the entire byte should be a
|
||||
// zero. This fast-path compares the byte to 0 and if it matches, subtract
|
||||
// 8 bits.
|
||||
if remaining >= 8 {
|
||||
if byte != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining -= 8;
|
||||
} else {
|
||||
// Otherwise mask off individual bits and check against them.
|
||||
let mask = 0xFF << (8 - remaining);
|
||||
if (byte & mask) != 0 {
|
||||
return false;
|
||||
}
|
||||
remaining = 0;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Computes hash for given nonce.
|
||||
///
|
||||
/// This differs from the JavaScript implementations by constructing the hash differently. In
|
||||
/// JavaScript implementations, the SHA-256 input is the result of appending the nonce as an
|
||||
/// integer to the hex-formatted challenge, eg:
|
||||
///
|
||||
/// sha256(`${challenge}${nonce}`);
|
||||
///
|
||||
/// This **does work**, however I think that this can be done a bit better by operating on the
|
||||
/// challenge bytes _directly_ and treating the nonce as a salt.
|
||||
///
|
||||
/// The nonce is also randomly encoded in either big or little endian depending on the last
|
||||
/// byte of the data buffer in an effort to make it more annoying to automate with GPUs.
|
||||
fn compute_hash(nonce: u32) -> [u8; 32] {
|
||||
let data = &DATA_BUFFER;
|
||||
let data_len = *DATA_LENGTH.lock().unwrap();
|
||||
let data_slice: &[u8] = &data[..data_len];
|
||||
let use_le = data_slice.last().copied().unwrap_or(0) >= 128;
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(data_slice);
|
||||
hasher.update(if use_le {
|
||||
nonce.to_le_bytes()
|
||||
} else {
|
||||
nonce.to_be_bytes()
|
||||
});
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
/// This function is the main entrypoint for the Anubis proof of work implementation.
|
||||
///
|
||||
/// This expects `DATA_BUFFER` to be prepopulated with the challenge value as "raw bytes".
|
||||
/// The definition of what goes in the data buffer is an exercise for the implementor, but
|
||||
/// for SHA-256 we store the hash as "raw bytes". The data buffer is intentionally oversized
|
||||
/// so that the challenge value can be expanded in the future.
|
||||
///
|
||||
/// `difficulty` is the number of leading bits that must match `0` in order for the
|
||||
/// challenge to be successfully passed. This will be validated by the server.
|
||||
///
|
||||
/// `initial_nonce` is the initial value of the nonce (number used once). This nonce will be
|
||||
/// appended to the challenge value in order to find a hash matching the specified
|
||||
/// difficulty.
|
||||
///
|
||||
/// `iterand` (noun form of iterate) is the amount that the nonce should be increased by
|
||||
/// every iteration of the proof of work loop. This will vary by how many threads are
|
||||
/// running the proof-of-work check, and also functions as a thread ID. This prevents
|
||||
/// wasting CPU time retrying a hash+nonce pair that likely won't work.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_work(difficulty: u32, initial_nonce: u32, iterand: u32) -> u32 {
|
||||
let mut nonce = initial_nonce;
|
||||
|
||||
loop {
|
||||
let hash = compute_hash(nonce);
|
||||
|
||||
if validate(&hash, difficulty) {
|
||||
// If the challenge worked, copy the bytes into `RESULT_HASH` so the runtime
|
||||
// can pick it up.
|
||||
let mut result = RESULT_HASH.lock().unwrap();
|
||||
result.copy_from_slice(&hash);
|
||||
return nonce;
|
||||
}
|
||||
|
||||
let old_nonce = nonce;
|
||||
nonce = nonce.wrapping_add(iterand);
|
||||
|
||||
// Report progress each time the search crosses into a new 1024-value window of the
|
||||
// nonce space, i.e. roughly every 1024 nonce values. The reported nonce approximates
|
||||
// the total work done across all worker threads, which the client turns into a
|
||||
// progress bar and hashrate. Comparing the shifted window (rather than the original
|
||||
// `nonce > old_nonce + 1023`) reports correctly for any `iterand` and stays correct
|
||||
// across the u32 wraparound. (Only the nonce-0 worker's callback is live; the caller
|
||||
// silences the rest.)
|
||||
if (nonce >> 10) != (old_nonce >> 10) {
|
||||
update_nonce(nonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function is called by the server in order to validate a proof-of-work challenge.
|
||||
/// This expects `DATA_BUFFER` to be set to the challenge value and `VERIFICATION_HASH` to
|
||||
/// be set to the "raw bytes" of the SHA-256 hash that the client calculated.
|
||||
///
|
||||
/// If everything is good, it returns true. Otherwise, it returns false.
|
||||
///
|
||||
/// XXX(Xe): this could probably return an error code for what step fails, but this is fine
|
||||
/// for now.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn anubis_validate(nonce: u32, difficulty: u32) -> bool {
|
||||
let computed = compute_hash(nonce);
|
||||
let valid = validate(&computed, difficulty);
|
||||
if !valid {
|
||||
return false;
|
||||
}
|
||||
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
computed == *verification
|
||||
}
|
||||
|
||||
// These functions exist to give pointers and lengths to the runtime around the Anubis
|
||||
// checks, this allows JavaScript and Go to safely manipulate the memory layout that Rust
|
||||
// has statically allocated at compile time without having to assume how the Rust compiler
|
||||
// is going to lay it out.
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_ptr() -> *const u8 {
|
||||
let challenge = RESULT_HASH.lock().unwrap();
|
||||
challenge.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn result_hash_size() -> usize {
|
||||
RESULT_HASH.lock().unwrap().len()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_ptr() -> *const u8 {
|
||||
let verification = VERIFICATION_HASH.lock().unwrap();
|
||||
verification.as_ptr()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn verification_hash_size() -> usize {
|
||||
VERIFICATION_HASH.lock().unwrap().len()
|
||||
}
|
||||
Executable
+116
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
shopt -s nullglob
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
|
||||
|
||||
src_dirs=(./wasm/pow ./wasm/anubis)
|
||||
dst_dirs=(./web/static/wasm/simd128 ./web/static/wasm/baseline)
|
||||
|
||||
# rustc enables reference-types, multivalue and friends by default for
|
||||
# wasm32-unknown-unknown. With reference-types on, LLVM encodes the call_indirect
|
||||
# table index as an overlong LEB128 (80 80 80 80 00) rather than the MVP's single
|
||||
# reserved 0x00 byte. Engines predating the proposal read one byte, see 0x80, and
|
||||
# refuse to compile the module:
|
||||
#
|
||||
# CompileError: expected table index 0, found 128
|
||||
#
|
||||
# Clearing the features with -Ctarget-feature is not enough, because the shipped
|
||||
# std rlibs are already encoded that way; fixing it at the source would mean
|
||||
# rebuilding std on nightly. Instead each module is round-tripped through wasm-opt
|
||||
# against the feature set that its oldest supported browser actually implements.
|
||||
# That re-emits the MVP call_indirect encoding, and makes wasm-opt reject the
|
||||
# module outright if it ever picks up a feature not on the list, so a toolchain
|
||||
# upgrade becomes a loud build failure rather than a browser that cannot start.
|
||||
#
|
||||
# Keep this a pure decode/re-encode with no optimization passes: the wasm build of
|
||||
# wasm-opt exhausts its stack on -O2, and we would rather not have an optimizer
|
||||
# rewriting proof-of-work code.
|
||||
#
|
||||
# Chrome shipped sign-ext and mutable-globals in 74, bulk-memory and
|
||||
# nontrapping-fptoint in 75, multivalue in 85 and simd in 91.
|
||||
baseline_features="-mvp --enable-sign-ext --enable-mutable-globals --enable-bulk-memory --enable-nontrapping-float-to-int"
|
||||
simd128_features="${baseline_features} --enable-multivalue --enable-simd"
|
||||
|
||||
run_wasm_opt() {
|
||||
if command -v wasm-opt 2>&1 >/dev/null; then
|
||||
wasm-opt "$@"
|
||||
elif command -v wasmtime 2>&1 >/dev/null; then
|
||||
wasmtime run -W exceptions=y --dir . ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
|
||||
elif node_runs_wasm; then
|
||||
node --no-warnings ./wasm/scripts/execer.mjs ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
|
||||
else
|
||||
go run ./utils/cmd/wazero-exec ./utils/wasm/wasm2js/wasm-opt_130.wasm "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
copy_modules() {
|
||||
local src="${1}" dst="${2}"
|
||||
|
||||
local files=("${src}"/*.wasm)
|
||||
if [ "${#files[@]}" -eq 0 ]; then
|
||||
echo "cargo built no modules in ${src}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -vf "${files[@]}" "${dst}"
|
||||
}
|
||||
|
||||
# reencode DIR FEATURE_FLAGS... rewrites every module in DIR against FEATURE_FLAGS.
|
||||
reencode() {
|
||||
local dir="${1}"
|
||||
shift
|
||||
|
||||
local files=("${dir}"/*.wasm)
|
||||
if [ "${#files[@]}" -eq 0 ]; then
|
||||
echo "no modules to re-encode in ${dir}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local out err
|
||||
for fname in "${files[@]}"; do
|
||||
out="$(mktemp "${fname}.XXXXXX")"
|
||||
err="$(mktemp)"
|
||||
# stderr is held back because wasm-opt warns on every module that no passes
|
||||
# were specified.
|
||||
if ! run_wasm_opt "$@" "${fname}" -o "${out}" 2>"${err}"; then
|
||||
cat "${err}" >&2
|
||||
rm -f "${out}" "${err}"
|
||||
echo "wasm-opt rejected ${fname}" >&2
|
||||
exit 1
|
||||
fi
|
||||
rm -f "${err}"
|
||||
mv -f "${out}" "${fname}"
|
||||
done
|
||||
}
|
||||
|
||||
# Newest source file timestamp (unix seconds).
|
||||
newest_src="$(mtimes "${src_dirs[@]}" -type f | sort -n | tail -1)"
|
||||
|
||||
# Oldest destination file timestamp (unix seconds). Empty if no outputs exist yet
|
||||
# (e.g. the output dirs haven't been created, in which case find would error out).
|
||||
oldest_dst="$(mtimes "${dst_dirs[@]}" -type f -name '*.wasm' 2>/dev/null | sort -n | head -1 || true)"
|
||||
|
||||
if all_populated '*.wasm' "${dst_dirs[@]}" && [ -n "$oldest_dst" ] && awk "BEGIN { exit !($newest_src <= $oldest_dst) }"; then
|
||||
echo "wasm artifacts are up to date, skipping build"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
mkdir -p ./web/static/wasm/{simd128,baseline}
|
||||
|
||||
cargo clean --quiet
|
||||
|
||||
# With simd128
|
||||
RUSTFLAGS='-C target-feature=+simd128' cargo build --quiet --release --target wasm32-unknown-unknown
|
||||
copy_modules ./target/wasm32-unknown-unknown/release ./web/static/wasm/simd128
|
||||
reencode ./web/static/wasm/simd128 ${simd128_features}
|
||||
|
||||
cargo clean --quiet
|
||||
|
||||
# Without simd128
|
||||
cargo build --quiet --release --target wasm32-unknown-unknown
|
||||
copy_modules ./target/wasm32-unknown-unknown/release ./web/static/wasm/baseline
|
||||
reencode ./web/static/wasm/baseline ${baseline_features}
|
||||
|
||||
cargo clean --quiet
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
shopt -s nullglob
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
|
||||
|
||||
WASM2JS_VERSION="130"
|
||||
WASM2JS_FLAGS="-all --strip-debug --rse --rereloop --optimize-for-js --flatten --dce --dfo --fpcast-emu --denan --dealign --remove-imports --remove-unused-names --remove-unused-brs --reorder-functions --reorder-locals --strip-target-features --untee --vacuum -s 4 -ffm -lmu -tnh -iit -n"
|
||||
src_dirs=(./web/static/wasm/baseline)
|
||||
dst_dirs=(./web/js/gen/wasm2js)
|
||||
|
||||
# Newest source file timestamp (unix seconds).
|
||||
newest_src="$(mtimes "${src_dirs[@]}" -type f | sort -n | tail -1)"
|
||||
|
||||
# Oldest destination file timestamp (unix seconds). Empty if no outputs exist yet
|
||||
# (e.g. the output dirs haven't been created, in which case find would error out).
|
||||
oldest_dst="$(mtimes "${dst_dirs[@]}" -type f -name '*.wasm.js' 2>/dev/null | sort -n | head -1 || true)"
|
||||
|
||||
if all_populated '*.wasm.js' "${dst_dirs[@]}" && [ -n "$oldest_dst" ] && awk "BEGIN { exit !($newest_src <= $oldest_dst) }"; then
|
||||
echo "wasm2js artifacts are up to date, skipping build"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_wasm2js() {
|
||||
if command -v wasm2js 2>&1 >/dev/null; then
|
||||
echo ">> wasm2js (sys) ${*}"
|
||||
wasm2js $WASM2JS_FLAGS $*
|
||||
elif command -v wasmtime 2>&1 >/dev/null; then
|
||||
echo ">> wasm2js (wasmtime) ${*}"
|
||||
wasmtime run -W exceptions=y --dir . ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
|
||||
elif node_runs_wasm; then
|
||||
echo ">> node execer.mjs ${*}"
|
||||
node --no-warnings ./wasm/scripts/execer.mjs ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
|
||||
else
|
||||
echo ">> wasm2js (wazero-exec, slow) ${*}"
|
||||
go run ./utils/cmd/wazero-exec ./utils/wasm/wasm2js/wasm2js_130.wasm $WASM2JS_FLAGS $*
|
||||
fi
|
||||
}
|
||||
|
||||
mkdir -p ./web/js/gen/wasm2js
|
||||
|
||||
srcs=(./web/static/wasm/baseline/*.wasm)
|
||||
if [ "${#srcs[@]}" -eq 0 ]; then
|
||||
echo "no modules in ./web/static/wasm/baseline, run wasm/scripts/build_wasm.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for fname in "${srcs[@]}"; do
|
||||
output="./web/js/gen/wasm2js/$(basename "${fname}").js"
|
||||
run_wasm2js "${fname}" -o "${output}"
|
||||
# wasm2js emits an import of the anubis host module on line 1; replace it with
|
||||
# a stub. Rewriting through a temp file rather than sed -i because BSD sed
|
||||
# reads the next argument as a mandatory backup suffix and GNU sed does not.
|
||||
tmp="$(mktemp)"
|
||||
sed '1s$.*$const anubis = { anubis_update_nonce: (_ignored) => { } };$' "${output}" >"${tmp}"
|
||||
mv -f "${tmp}" "${output}"
|
||||
done
|
||||
@@ -0,0 +1,27 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { WASI } from "node:wasi";
|
||||
import { argv, cwd, env, exit } from "node:process";
|
||||
|
||||
const [wasmBinName, ...wasmArgs] = argv.slice(2);
|
||||
|
||||
if (!wasmBinName) {
|
||||
console.error("usage: node execer.mjs <bin.wasm> [args...]");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
const wasi = new WASI({
|
||||
version: "preview1",
|
||||
args: [wasmBinName, ...wasmArgs],
|
||||
env,
|
||||
preopens: {
|
||||
"/": cwd(),
|
||||
},
|
||||
returnOnExit: true,
|
||||
});
|
||||
|
||||
const wasm = await WebAssembly.compile(
|
||||
await readFile(wasmBinName),
|
||||
);
|
||||
const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
|
||||
|
||||
exit(wasi.start(instance));
|
||||
@@ -0,0 +1,38 @@
|
||||
# shellcheck shell=bash
|
||||
|
||||
# BSD `find` has no `-printf` flag, so you have to get file timestamps from
|
||||
# `stat`. Beautifully, both `stat` implementations differ in how these
|
||||
# timestamps are extracted. Figure out which flag you need with a small test
|
||||
# because people can run BSD coreutils (or busybox?).
|
||||
if stat -f '%m' . >/dev/null 2>&1; then
|
||||
stat_mtime_args=(-f '%m')
|
||||
else
|
||||
stat_mtime_args=(-c '%Y')
|
||||
fi
|
||||
|
||||
# Implements the subset of `find -printf` that's actually needed here.
|
||||
mtimes() {
|
||||
find "$@" -exec stat "${stat_mtime_args[@]}" {} +
|
||||
}
|
||||
|
||||
# all_populated PATTERN DIR... succeeds when every DIR holds at least one file
|
||||
# matching PATTERN. Timestamps alone can't answer "are the artifacts there?":
|
||||
# a run that dies partway through leaves one output directory filled and the
|
||||
# next one empty, and every source file is older than whatever that run managed
|
||||
# to write. Check that the files exist before believing the clock.
|
||||
all_populated() {
|
||||
local pattern="${1}"
|
||||
shift
|
||||
|
||||
local dir
|
||||
for dir in "$@"; do
|
||||
compgen -G "${dir}/${pattern}" >/dev/null || return 1
|
||||
done
|
||||
}
|
||||
|
||||
# node_runs_wasm succeeds when node is installed and can be trusted to run the
|
||||
# binaryen modules. On the riscv64 CI host (isa rv64imafdcsu) it cannot: node
|
||||
# dies with SIGILL partway through wasm-opt, every time.
|
||||
node_runs_wasm() {
|
||||
command -v node >/dev/null 2>&1 && [ "$(uname -m)" != "riscv64" ]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package wasm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVerificationLimit(t *testing.T) {
|
||||
releases := make([]func(), 0, 4)
|
||||
for range 4 {
|
||||
release, err := acquireVerification(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releases = append(releases, release)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, release := range releases {
|
||||
release()
|
||||
}
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
if release, err := acquireVerification(ctx); !errors.Is(err, context.DeadlineExceeded) {
|
||||
if release != nil {
|
||||
release()
|
||||
}
|
||||
t.Fatalf("fifth verification not bounded: %v", err)
|
||||
}
|
||||
releases[0]()
|
||||
releases = releases[1:]
|
||||
release, err := acquireVerification(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
releases = append(releases, release)
|
||||
}
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
package wasm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/tetratelabs/wazero"
|
||||
"github.com/tetratelabs/wazero/api"
|
||||
)
|
||||
|
||||
var (
|
||||
validationTime = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "anubis_wasm_validation_time",
|
||||
Help: "The time taken for the validation function to run per checker (nanoseconds)",
|
||||
Buckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 31), 32),
|
||||
}, []string{"fname"})
|
||||
|
||||
validationCount = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "anubis_wasm_validation",
|
||||
Help: "The number of times the validation logic has been run and its success rate",
|
||||
}, []string{"fname", "success"})
|
||||
|
||||
ErrNotEnoughData = errors.New("wasm: not enough data being written")
|
||||
ErrTooMuchData = errors.New("wasm: too much data being written")
|
||||
)
|
||||
|
||||
var verificationSlots = make(chan struct{}, 4)
|
||||
|
||||
func acquireVerification(ctx context.Context) (func(), error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
select {
|
||||
case verificationSlots <- struct{}{}:
|
||||
return func() { <-verificationSlots }, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
const pageSize = 65536
|
||||
|
||||
type Runner struct {
|
||||
r wazero.Runtime
|
||||
code wazero.CompiledModule
|
||||
fname string
|
||||
}
|
||||
|
||||
func NewRunner(ctx context.Context, fname string, fin io.ReadCloser) (*Runner, error) {
|
||||
data, err := io.ReadAll(fin)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wasm: can't read from fin: %w", err)
|
||||
}
|
||||
|
||||
cfg := wazero.NewRuntimeConfig().WithMemoryLimitPages(512)
|
||||
|
||||
r := wazero.NewRuntimeWithConfig(ctx, cfg)
|
||||
|
||||
_, err = r.NewHostModuleBuilder("anubis").
|
||||
NewFunctionBuilder().
|
||||
WithFunc(func(context.Context, uint32) {}).
|
||||
Export("anubis_update_nonce").
|
||||
Instantiate(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wasm: can't export anubis_update_nonce: %w", err)
|
||||
}
|
||||
|
||||
code, err := r.CompileModule(ctx, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wasm: can't compile module: %w", err)
|
||||
}
|
||||
|
||||
result := &Runner{
|
||||
r: r,
|
||||
code: code,
|
||||
fname: fname,
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *Runner) checkExports(module api.Module) error {
|
||||
funcs := []string{
|
||||
"anubis_work",
|
||||
"anubis_validate",
|
||||
"data_ptr",
|
||||
"set_data_length",
|
||||
"result_hash_ptr",
|
||||
"result_hash_size",
|
||||
"verification_hash_ptr",
|
||||
"verification_hash_size",
|
||||
}
|
||||
|
||||
var errs []error
|
||||
|
||||
for _, fun := range funcs {
|
||||
if module.ExportedFunction(fun) == nil {
|
||||
errs = append(errs, fmt.Errorf("function %s is not defined", fun))
|
||||
}
|
||||
}
|
||||
|
||||
if len(errs) != 0 {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runner) anubisWork(ctx context.Context, module api.Module, difficulty, initialNonce, iterand uint32) (uint32, error) {
|
||||
results, err := module.ExportedFunction("anubis_work").Call(ctx, uint64(difficulty), uint64(initialNonce), uint64(iterand))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) anubisValidate(ctx context.Context, module api.Module, nonce, difficulty uint32) (bool, error) {
|
||||
results, err := module.ExportedFunction("anubis_validate").Call(ctx, uint64(nonce), uint64(difficulty))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Rust booleans are 1 if true
|
||||
return results[0] == 1, nil
|
||||
}
|
||||
|
||||
func (r *Runner) dataPtr(ctx context.Context, module api.Module) (uint32, error) {
|
||||
results, err := module.ExportedFunction("data_ptr").Call(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) setDataLength(ctx context.Context, module api.Module, length uint32) error {
|
||||
_, err := module.ExportedFunction("set_data_length").Call(ctx, uint64(length))
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Runner) resultHashPtr(ctx context.Context, module api.Module) (uint32, error) {
|
||||
results, err := module.ExportedFunction("result_hash_ptr").Call(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) resultHashSize(ctx context.Context, module api.Module) (uint32, error) {
|
||||
results, err := module.ExportedFunction("result_hash_size").Call(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) verificationHashPtr(ctx context.Context, module api.Module) (uint32, error) {
|
||||
results, err := module.ExportedFunction("verification_hash_ptr").Call(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) verificationHashSize(ctx context.Context, module api.Module) (uint32, error) {
|
||||
results, err := module.ExportedFunction("verification_hash_size").Call(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return uint32(results[0]), nil
|
||||
}
|
||||
|
||||
func (r *Runner) writeData(ctx context.Context, module api.Module, data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return ErrNotEnoughData
|
||||
}
|
||||
|
||||
if len(data) > 4096 {
|
||||
return ErrTooMuchData
|
||||
}
|
||||
|
||||
length := uint32(len(data))
|
||||
|
||||
dataPtr, err := r.dataPtr(ctx, module)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't read data pointer: %w", err)
|
||||
}
|
||||
|
||||
if !module.Memory().Write(dataPtr, data) {
|
||||
return fmt.Errorf("[unexpected] can't write memory, is data out of range??")
|
||||
}
|
||||
|
||||
if err := r.setDataLength(ctx, module, length); err != nil {
|
||||
return fmt.Errorf("can't set data length: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runner) readResult(ctx context.Context, module api.Module) ([]byte, error) {
|
||||
length, err := r.resultHashSize(ctx, module)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get result hash size: %w", err)
|
||||
}
|
||||
|
||||
ptr, err := r.resultHashPtr(ctx, module)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get result hash pointer: %w", err)
|
||||
}
|
||||
|
||||
buf, ok := module.Memory().Read(ptr, length)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("[unexpected] can't read from memory, is something out of range??")
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func (r *Runner) run(ctx context.Context, data []byte, difficulty, initialNonce, iterand uint32) (uint32, []byte, api.Module, error) {
|
||||
mod, err := r.r.InstantiateModule(ctx, r.code, wazero.NewModuleConfig().WithName(r.fname))
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("can't instantiate module: %w", err)
|
||||
}
|
||||
|
||||
if err := r.checkExports(mod); err != nil {
|
||||
return 0, nil, mod, err
|
||||
}
|
||||
|
||||
if err := r.writeData(ctx, mod, data); err != nil {
|
||||
return 0, nil, mod, err
|
||||
}
|
||||
|
||||
nonce, err := r.anubisWork(ctx, mod, difficulty, initialNonce, iterand)
|
||||
if err != nil {
|
||||
return 0, nil, mod, fmt.Errorf("can't run work function: %w", err)
|
||||
}
|
||||
|
||||
hash, err := r.readResult(ctx, mod)
|
||||
if err != nil {
|
||||
return 0, nil, mod, fmt.Errorf("can't read result: %w", err)
|
||||
}
|
||||
|
||||
return nonce, hash, mod, nil
|
||||
}
|
||||
|
||||
func (r *Runner) Run(ctx context.Context, data []byte, difficulty, initialNonce, iterand uint32) (uint32, []byte, error) {
|
||||
nonce, hash, mod, err := r.run(ctx, data, difficulty, initialNonce, iterand)
|
||||
if mod != nil {
|
||||
if err := mod.Close(ctx); err != nil {
|
||||
return 0, nil, fmt.Errorf("can't close wasm module: %w", err)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("can't run %s: %w", r.fname, err)
|
||||
}
|
||||
|
||||
return nonce, hash, nil
|
||||
}
|
||||
|
||||
func (r *Runner) verify(ctx context.Context, data, verify []byte, nonce, difficulty uint32) (bool, api.Module, error) {
|
||||
// Verify permits multiple in-flight calls, so each transient module must be anonymous.
|
||||
// wazero rejects a second live module registered under the same non-empty name.
|
||||
mod, err := r.r.InstantiateModule(ctx, r.code, wazero.NewModuleConfig().WithName(""))
|
||||
if err != nil {
|
||||
return false, nil, fmt.Errorf("can't instantiate module: %w", err)
|
||||
}
|
||||
|
||||
if err := r.checkExports(mod); err != nil {
|
||||
return false, mod, err
|
||||
}
|
||||
|
||||
if err := r.writeData(ctx, mod, data); err != nil {
|
||||
return false, mod, err
|
||||
}
|
||||
|
||||
if err := r.writeVerification(ctx, mod, verify); err != nil {
|
||||
return false, mod, err
|
||||
}
|
||||
|
||||
ok, err := r.anubisValidate(ctx, mod, nonce, difficulty)
|
||||
if err != nil {
|
||||
return false, mod, fmt.Errorf("can't validate hash %x from challenge %x, nonce %d and difficulty %d: %w", verify, data, nonce, difficulty, err)
|
||||
}
|
||||
|
||||
return ok, mod, nil
|
||||
}
|
||||
|
||||
func (r *Runner) Verify(ctx context.Context, data, verify []byte, nonce, difficulty uint32) (bool, error) {
|
||||
release, err := acquireVerification(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer release()
|
||||
t0 := time.Now()
|
||||
ok, mod, err := r.verify(ctx, data, verify, nonce, difficulty)
|
||||
if mod != nil {
|
||||
if err := mod.Close(ctx); err != nil {
|
||||
return false, fmt.Errorf("can't close wasm module: %w", err)
|
||||
}
|
||||
}
|
||||
validationTime.WithLabelValues(r.fname).Observe(float64(time.Since(t0)))
|
||||
validationCount.WithLabelValues(r.fname, strconv.FormatBool(ok)).Inc()
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (r *Runner) writeVerification(ctx context.Context, module api.Module, data []byte) error {
|
||||
length, err := r.verificationHashSize(ctx, module)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get verification hash size: %w", err)
|
||||
}
|
||||
|
||||
if length != uint32(len(data)) {
|
||||
return fmt.Errorf("data is too big, want %d bytes, got: %d", length, len(data))
|
||||
}
|
||||
|
||||
ptr, err := r.verificationHashPtr(ctx, module)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get verification hash pointer: %w", err)
|
||||
}
|
||||
|
||||
if !module.Memory().Write(ptr, data) {
|
||||
return fmt.Errorf("[unexpected] can't write memory, is data out of range??")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package wasm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/web"
|
||||
"github.com/tetratelabs/wazero"
|
||||
)
|
||||
|
||||
func abiTest(t testing.TB, kind, fname string, difficulty uint32) {
|
||||
fin, err := web.Static.Open("static/wasm/" + kind + "/" + fname)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close() //nolint:errcheck
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
runner, err := NewRunner(ctx, fname, fin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
h := sha256.New()
|
||||
fmt.Fprint(h, t.Name()) //nolint:errcheck
|
||||
data := h.Sum(nil)
|
||||
|
||||
nonce, hash, mod, err := runner.run(ctx, data, difficulty, 0, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := runner.writeVerification(ctx, mod, hash); err != nil {
|
||||
t.Fatalf("can't write verification: %v", err)
|
||||
}
|
||||
|
||||
ok, err := runner.anubisValidate(ctx, mod, nonce, difficulty)
|
||||
if err != nil {
|
||||
t.Fatalf("can't run validation: %v", err)
|
||||
}
|
||||
|
||||
if !ok {
|
||||
t.Error("validation failed")
|
||||
}
|
||||
|
||||
t.Logf("used %d pages of wasm memory (%d bytes)", mod.Memory().Size()/pageSize, mod.Memory().Size())
|
||||
}
|
||||
|
||||
func TestAlgos(t *testing.T) {
|
||||
fnames, err := fs.ReadDir(web.Static, "static/wasm/baseline")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, kind := range []string{"baseline", "simd128"} {
|
||||
for _, fname := range fnames {
|
||||
t.Run(kind+"/"+fname.Name(), func(t *testing.T) {
|
||||
if testing.Short() && fname.Name() == "argon2id.wasm" && runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
|
||||
t.Skipf("skipping argon2id on %s in short mode because wazero has no compiler for it and the interpreter is too slow", runtime.GOARCH)
|
||||
}
|
||||
abiTest(t, kind, fname.Name(), 4)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func bench(b *testing.B, kind, fname string, difficulties []uint32) {
|
||||
b.Helper()
|
||||
|
||||
fin, err := web.Static.Open("static/wasm/" + kind + "/" + fname)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer fin.Close() //nolint:errcheck
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
b.Cleanup(cancel)
|
||||
|
||||
runner, err := NewRunner(ctx, fname, fin)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
h := sha256.New()
|
||||
fmt.Fprint(h, "This is an example value that exists only to test the system.") //nolint:errcheck
|
||||
data := h.Sum(nil)
|
||||
|
||||
_, _, mod, err := runner.run(ctx, data, 0, 0, 1)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
for _, difficulty := range difficulties {
|
||||
b.Run(fmt.Sprintf("difficulty/%d", difficulty), func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
difficulty := difficulty
|
||||
_, err := runner.anubisWork(ctx, mod, difficulty, 0, 1)
|
||||
if err != nil {
|
||||
b.Fatalf("can't do test work run: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkArgon2ID(b *testing.B) {
|
||||
for _, kind := range []string{"baseline", "simd128"} {
|
||||
b.Run(kind, func(b *testing.B) {
|
||||
bench(b, kind, "argon2id.wasm", []uint32{4, 6, 8})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkHashX(b *testing.B) {
|
||||
for _, kind := range []string{"baseline", "simd128"} {
|
||||
b.Run(kind, func(b *testing.B) {
|
||||
bench(b, kind, "hashx.wasm", []uint32{4, 6, 8})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSHA256(b *testing.B) {
|
||||
for _, kind := range []string{"baseline", "simd128"} {
|
||||
b.Run(kind, func(b *testing.B) {
|
||||
bench(b, kind, "sha256.wasm", []uint32{4, 6, 8, 10, 12, 14, 16})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerConcurrentVerify(t *testing.T) {
|
||||
fin, err := web.Static.Open("static/wasm/simd128/hashx.wasm")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close() //nolint:errcheck
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
runner, err := NewRunner(ctx, "hashx.wasm", fin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sum := sha256.Sum256([]byte("concurrent HashX verification regression"))
|
||||
nonce, hash, err := runner.Run(ctx, sum[:], 1, 0, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const workers = 16
|
||||
start := make(chan struct{})
|
||||
errs := make(chan error, workers)
|
||||
for range workers {
|
||||
go func() {
|
||||
<-start
|
||||
ok, err := runner.Verify(ctx, sum[:], hash, nonce, 1)
|
||||
if err == nil && !ok {
|
||||
err = errors.New("valid HashX proof was rejected")
|
||||
}
|
||||
errs <- err
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
for range workers {
|
||||
if err := <-errs; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkValidate(b *testing.B) {
|
||||
fnames, err := fs.ReadDir(web.Static, "static/wasm/simd128")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
h := sha256.New()
|
||||
fmt.Fprint(h, "This is an example value that exists only to test the system.") //nolint:errcheck
|
||||
data := h.Sum(nil)
|
||||
|
||||
for _, fname := range fnames {
|
||||
fname := fname.Name()
|
||||
|
||||
difficulty := uint32(1)
|
||||
|
||||
switch fname {
|
||||
case "sha256.wasm":
|
||||
difficulty = 16
|
||||
}
|
||||
|
||||
b.Run(fname, func(b *testing.B) {
|
||||
fin, err := web.Static.Open("static/wasm/simd128/" + fname)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer fin.Close() //nolint:errcheck
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
b.Cleanup(cancel)
|
||||
|
||||
runner, err := NewRunner(ctx, fname, fin)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
nonce, hash, mod, err := runner.run(ctx, data, difficulty, 0, 1)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
if err := runner.writeVerification(ctx, mod, hash); err != nil {
|
||||
b.Fatalf("can't write verification: %v", err)
|
||||
}
|
||||
|
||||
for b.Loop() {
|
||||
_, err := runner.anubisValidate(ctx, mod, nonce, difficulty)
|
||||
if err != nil {
|
||||
b.Fatalf("can't run validation: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerDataHardening(t *testing.T) {
|
||||
fnames, err := fs.ReadDir(web.Static, "static/wasm/simd128")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, fname := range fnames {
|
||||
fname := fname.Name()
|
||||
t.Run(fname, func(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "simple okay",
|
||||
data: make([]byte, 4096),
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "not enough",
|
||||
data: make([]byte, 0),
|
||||
err: ErrNotEnoughData,
|
||||
},
|
||||
{
|
||||
name: "too much",
|
||||
data: make([]byte, 8192),
|
||||
err: ErrTooMuchData,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
fin, err := web.Static.Open("static/wasm/simd128/" + fname)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fin.Close() //nolint:errcheck
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
runner, err := NewRunner(ctx, fname, fin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mod, err := runner.r.InstantiateModule(ctx, runner.code, wazero.NewModuleConfig().WithName(runner.fname))
|
||||
if err != nil {
|
||||
t.Fatalf("can't instantiate module: %v", err)
|
||||
}
|
||||
|
||||
if err := runner.writeData(t.Context(), mod, tt.data); !errors.Is(err, tt.err) {
|
||||
t.Logf("wanted error: %v", tt.err)
|
||||
t.Logf("got error: %v", err)
|
||||
t.Error()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user