Skip to content

Instantly share code, notes, and snippets.

@OkoliEvans
Created March 27, 2024 04:32
Show Gist options
  • Save OkoliEvans/ac32d3067d00b38b98896555be097ca8 to your computer and use it in GitHub Desktop.
Save OkoliEvans/ac32d3067d00b38b98896555be097ca8 to your computer and use it in GitHub Desktop.
use core::fmt;
use sha2::{ Sha256, Digest };
use std::{
error::Error,
fmt::{Debug, Display},
io,
};
#[derive(Debug, Clone, Copy)]
struct AuctionDetails {}
#[derive(Debug, Clone)]
enum HashError<'a> {
Error_message(&'a str),
}
trait Auction {
fn commit<T: Display>(a: T, b: T) -> Result<Vec<Vec<u8>>, HashError<'static>>;
fn open<T: Display>(
input: T,
commitment: Vec<u8>
) -> Result<bool, HashError<'static>>;
}
impl Auction for AuctionDetails {
fn commit<T: Display>(a: T, b: T) -> Result<Vec<Vec<u8>>, HashError<'static>> {
let mut hash_vector = Vec::new();
let a_hash = hash_fn(a);
let b_hash = hash_fn(b);
hash_vector.push(a_hash);
hash_vector.push(b_hash);
Ok(hash_vector)
}
fn open<T: Display>(
input: T,
commitment: Vec<u8>,
) -> Result<bool, HashError<'static>> {
let input_hash = hash_fn(input);
if input_hash == commitment {
Ok(true)
} else {
Err(HashError::Error_message("Commitment hash discrepancy"))
}
}
}
fn hash_fn<T: Display>(input: T) -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.update(input.to_string());
let hash = hasher.finalize();
hash.to_vec()
}
fn main() {
let mut input = String::new();
println!("Enter first bid: ");
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
let first_bid: u8 = input.trim().parse().expect("Pls enter a valid number");
input.clear();
println!("Enter second bid: ");
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
let second_bid: u8 = input.trim().parse().expect("Please enter a valid number");
let bid_hashes: Vec<Vec<u8>> =
AuctionDetails::commit(first_bid, second_bid).expect("commit function failed");
let first_bid_commit = bid_hashes.clone()[0].to_vec();
let second_bid_commit = bid_hashes.clone()[1].to_vec();
let first_bid_open = AuctionDetails::open(first_bid, first_bid_commit).unwrap();
println!("First bid hash reveal: {}", first_bid_open);
let second_bid_open = AuctionDetails::open(second_bid, second_bid_commit).unwrap();
println!("Second bid reveal: {}", second_bid_open);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment