feat: submit and store benchmark type

This commit is contained in:
Aravinth Manivannan 2023-02-01 18:18:50 +05:30
parent 49abe1eb65
commit 0fa21911f0
Signed by: realaravinth
GPG Key ID: AD9F0F08E855ED88
6 changed files with 89 additions and 14 deletions

View File

@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS survey_bench_type (
name VARCHAR(30) UNIQUE NOT NULL,
ID SERIAL PRIMARY KEY NOT NULL
);
INSERT INTO survey_bench_type (name) VALUES ('wasm');
INSERT INTO survey_bench_type (name) VALUES ('js');
CREATE OR REPLACE FUNCTION id_in_survey_bench_type(iname varchar)
RETURNS int LANGUAGE SQL AS $$
SELECT ID FROM survey_bench_type WHERE name = name;
$$;
ALTER TABLE survey_responses
ADD COLUMN submission_bench_type_id INTEGER references survey_bench_type(ID) NOT NULL
DEFAULT id_in_survey_bench_type('wasm');

View File

@ -169,6 +169,28 @@ pub struct Submission {
pub device_software_recognised: String,
pub threads: i32,
pub benches: Vec<Bench>,
pub submission_type: SubmissionType,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SubmissionType {
Wasm,
Js,
}
impl ToString for SubmissionType {
fn to_string(&self) -> String {
let s = serde_json::to_string(&self).unwrap();
(&s[1..(s.len() - 1)]).to_string()
}
}
impl FromStr for SubmissionType {
type Err = serde_json::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(&format!("\"{}\"", s))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -177,12 +199,11 @@ pub struct SubmissionProof {
pub proof: String,
}
fn is_session_authenticated(r: &HttpRequest, mut pl: &mut Payload) -> bool {
fn is_session_authenticated(r: &HttpRequest, pl: &mut Payload) -> bool {
use actix_web::FromRequest;
matches!(
Session::from_request(r, pl).into_inner().map(|x| {
let val = x.get::<String>(SURVEY_USER_ID);
println!("{:#?}", val);
val
}),
Ok(Ok(Some(_)))
@ -222,20 +243,25 @@ async fn submit(
let resp_id = sqlx::query_as!(
ID,
"INSERT INTO survey_responses (
user_id,
campaign_id,
device_user_provided,
device_software_recognised,
threads,
submitted_at
) VALUES ($1, $2, $3, $4, $5, $6)
user_id,
campaign_id,
device_user_provided,
device_software_recognised,
threads,
submitted_at,
submission_bench_type_id
) VALUES (
$1, $2, $3, $4, $5, $6,
(SELECT ID FROM survey_bench_type WHERE name = $7)
)
RETURNING ID;",
&user_id,
&campaign_id,
&payload.device_user_provided,
&payload.device_software_recognised,
&payload.threads,
&now
&now,
&payload.submission_type.to_string(),
)
.fetch_one(&data.db)
.await?;
@ -314,3 +340,14 @@ async fn fetch(data: AppData, path: web::Path<String>) -> ServiceResult<impl Res
.await?;
Ok(HttpResponse::Ok().json(config))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn survey_response_type_no_panic_test() {
assert_eq!(SubmissionType::Wasm.to_string(), "wasm".to_string());
assert_eq!(SubmissionType::Js.to_string(), "js".to_string());
}
}

View File

@ -19,6 +19,7 @@ import ROUTES from "../api/v1/routes";
import genJsonPaylod from "../utils/genJsonPayload";
import isBlankString from "../utils/isBlankString";
import createError from "../components/error/";
import { get_bench_type } from "./prove";
export const index = () => {
const ADV = <HTMLButtonElement>document.getElementById("advance");
@ -67,12 +68,13 @@ export const index = () => {
};
const submitBench = async () => {
const submission_type = await get_bench_type();
const payload: Submission = {
device_user_provided: deviceName,
threads: window.navigator.hardwareConcurrency,
device_software_recognised: window.navigator.userAgent,
benches: res,
submission_type,
};
const resp = await fetch(

View File

@ -10,7 +10,18 @@
*/
import * as p from "@mcaptcha/pow_sha256-polyfill";
import { PoWConfig } from "./types";
import { PoWConfig, SubmissionType } from "./types";
export const get_bench_type = async (): Promise<SubmissionType> => {
console.log(`Wasm support says ${WasmSupported}`);
let submission_type: SubmissionType;
if (WasmSupported) {
submission_type = SubmissionType.wasm;
} else {
submission_type = SubmissionType.js;
}
return submission_type;
};
/**
* proove work
@ -21,8 +32,9 @@ const prove = async (config: PoWConfig): Promise<number> => {
console.log(`Wasm support says ${WasmSupported}`);
let duration: number;
if (WasmSupported) {
const wasm = require("@mcaptcha/pow-wasm");
const wasm = await require("@mcaptcha/pow-wasm");
const t0 = performance.now();
console.log(JSON.stringify(wasm))
wasm.gen_pow(config.salt, config.string, config.difficulty_factor);
const t1 = performance.now();
duration = t1 - t0;

View File

@ -32,7 +32,7 @@ onmessage = async (event) => {
salt: SALT,
};
let duration = await prove(config);
const duration = await prove(config);
const msg: Bench = {
difficulty: difficulty_factor,

View File

@ -25,6 +25,7 @@ export type Submission = {
device_software_recognised: String;
threads: number;
benches: Array<Bench>;
submission_type: SubmissionType;
};
export type SubmissionProof = {
@ -41,3 +42,8 @@ export type PoWConfig = {
difficulty_factor: number;
salt: string;
};
export enum SubmissionType {
wasm = "wasm",
js = "js",
}