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 device_software_recognised: String,
pub threads: i32, pub threads: i32,
pub benches: Vec<Bench>, 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)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -177,12 +199,11 @@ pub struct SubmissionProof {
pub proof: String, 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; use actix_web::FromRequest;
matches!( matches!(
Session::from_request(r, pl).into_inner().map(|x| { Session::from_request(r, pl).into_inner().map(|x| {
let val = x.get::<String>(SURVEY_USER_ID); let val = x.get::<String>(SURVEY_USER_ID);
println!("{:#?}", val);
val val
}), }),
Ok(Ok(Some(_))) Ok(Ok(Some(_)))
@ -222,20 +243,25 @@ async fn submit(
let resp_id = sqlx::query_as!( let resp_id = sqlx::query_as!(
ID, ID,
"INSERT INTO survey_responses ( "INSERT INTO survey_responses (
user_id, user_id,
campaign_id, campaign_id,
device_user_provided, device_user_provided,
device_software_recognised, device_software_recognised,
threads, threads,
submitted_at submitted_at,
) VALUES ($1, $2, $3, $4, $5, $6) submission_bench_type_id
) VALUES (
$1, $2, $3, $4, $5, $6,
(SELECT ID FROM survey_bench_type WHERE name = $7)
)
RETURNING ID;", RETURNING ID;",
&user_id, &user_id,
&campaign_id, &campaign_id,
&payload.device_user_provided, &payload.device_user_provided,
&payload.device_software_recognised, &payload.device_software_recognised,
&payload.threads, &payload.threads,
&now &now,
&payload.submission_type.to_string(),
) )
.fetch_one(&data.db) .fetch_one(&data.db)
.await?; .await?;
@ -314,3 +340,14 @@ async fn fetch(data: AppData, path: web::Path<String>) -> ServiceResult<impl Res
.await?; .await?;
Ok(HttpResponse::Ok().json(config)) 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 genJsonPaylod from "../utils/genJsonPayload";
import isBlankString from "../utils/isBlankString"; import isBlankString from "../utils/isBlankString";
import createError from "../components/error/"; import createError from "../components/error/";
import { get_bench_type } from "./prove";
export const index = () => { export const index = () => {
const ADV = <HTMLButtonElement>document.getElementById("advance"); const ADV = <HTMLButtonElement>document.getElementById("advance");
@ -67,12 +68,13 @@ export const index = () => {
}; };
const submitBench = async () => { const submitBench = async () => {
const submission_type = await get_bench_type();
const payload: Submission = { const payload: Submission = {
device_user_provided: deviceName, device_user_provided: deviceName,
threads: window.navigator.hardwareConcurrency, threads: window.navigator.hardwareConcurrency,
device_software_recognised: window.navigator.userAgent, device_software_recognised: window.navigator.userAgent,
benches: res, benches: res,
submission_type,
}; };
const resp = await fetch( const resp = await fetch(

View file

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

View file

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

View file

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