Skip to content

Commit

Permalink
Merge pull request #9 from chainwayxyz/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
ekrembal authored Nov 28, 2023
2 parents 3eb70e0 + 2127799 commit 6916a08
Show file tree
Hide file tree
Showing 15 changed files with 358 additions and 72 deletions.
2 changes: 2 additions & 0 deletions .clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
type-complexity-threshold = 9999
too-many-arguments-threshold = 20
16 changes: 16 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/bin/sh

# Format the code
make fmt

# Apply fixes
make fix

# Run checks
make check

# If checks fail, prevent the commit
if [ $? -ne 0 ]; then
echo "Checks failed. Commit aborted."
exit 1
fi
45 changes: 45 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: Rust CI

on:
push:
branches: "main"
pull_request:
branches: "main"

env:
CARGO_TERM_COLOR: always

jobs:
fmt-and-clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Swatinem/[email protected]
- name: Version info
run: |
rustc --version
cargo clippy --version
- name: Fmt check
run: |
if ! cargo fmt -- --check ; then
echo "Formatting errors detected, apply make fmt."
exit 1
fi
- name: Clippy check
run: |
if ! cargo clippy -- -D warnings ; then
echo "Clippy warnings detected, apply proper fixes."
exit 1
fi
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Swatinem/[email protected]
- name: Run Tests
run: |
if ! cargo test ; then
echo "Tests failed."
exit 1
fi
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ edition = "2021"
[dependencies]
bitcoin = "0.31.0"
rand = "0.8.5"

[dev-dependencies]
bitcoin-scriptexec = { git = "https://github.com/ekrembal/rust-bitcoin-scriptexec" }
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.PHONY: set-hook fmt fix check

set-hook:
chmod u+x .githooks/*
git config core.hooksPath .githooks

fmt:
cargo fmt

fix:
cargo clippy --fix --allow-dirty --allow-staged

check:
cargo fmt -- --check
cargo clippy -- -D warnings
10 changes: 5 additions & 5 deletions bristol/test.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
278356 78623
2 32 32
1 32
2 5
2 1 2
1 1

2 1 10 15 16 NOT
2 1 15 17 18 NOT
2 1 0 1 3 NOT
2 1 2 3 4 NOT


90 changes: 74 additions & 16 deletions src/circuit.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::collections::HashMap;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::iter::zip;
use std::rc::Rc;

use crate::utils::read_lines;
use crate::{
Expand All @@ -11,37 +14,76 @@ pub struct Circuit {
pub input_sizes: Vec<usize>,
pub output_sizes: Vec<usize>,
pub gates: Vec<Box<dyn GateTrait>>,
pub wires: Vec<Wire>,
pub wires: Vec<Rc<RefCell<Wire>>>,
}

impl Default for Circuit {
fn default() -> Self {
Self::new()
}
}

impl Circuit {
pub fn new() -> Self {
return Circuit {
Circuit {
input_sizes: vec![32, 32],
output_sizes: vec![32],
gates: vec![Box::new(NotGate::new(vec![], vec![]))],
wires: vec![],
};
}
}
}

impl CircuitTrait for Circuit {
fn evaluate(&self) {}
fn evaluate(&mut self, inputs: Vec<Vec<bool>>) -> Vec<Vec<bool>> {
assert_eq!(inputs.len(), self.input_sizes.len());
let mut combined_inputs = Vec::new();
for (a, b) in zip(inputs, self.input_sizes.clone()) {
assert_eq!(a.len(), b);
combined_inputs.extend(a);
}
for (i, value) in combined_inputs.iter().enumerate() {
self.wires[i].try_borrow_mut().unwrap().selector = Some(*value);
}
//self.gates[0].set_input_wires();
//self.wires[0].try_borrow_mut().unwrap().selector = Some(true);
//self.wires[1].try_borrow_mut().unwrap().selector = Some(true);
for gate in self.gates.as_mut_slice() {
gate.evaluate();
}
let mut output = Vec::new();
let total_output_size = self.output_sizes.iter().sum::<usize>();
let mut output_index = self.wires.len() - total_output_size;
for os in self.output_sizes.clone() {
let mut output_vec = Vec::new();
for i in output_index..(output_index + os) {
let value = self.wires[i].try_borrow_mut().unwrap().selector.unwrap();
output_vec.push(value);
}
output_index += os;
output.push(output_vec);
}
output
}

fn from_bristol(file: &str) -> Self {
let mut nog: usize = 0; // number of gates
let mut now: usize = 0; // number of wires
let mut input_sizes = Vec::<usize>::new();
let mut output_sizes = Vec::<usize>::new();
let mut gates = Vec::<Box<dyn GateTrait>>::new();
let mut wire_indices = HashMap::new();
let mut wire_indices = BTreeMap::new();

for (i, line) in read_lines(file).unwrap().enumerate() {
if let Ok(line_str) = line {
if i == 0 {
let mut words = line_str.split_whitespace();
nog = words.next().unwrap().parse().unwrap();
now = words.next().unwrap().parse().unwrap();
for i in 0..now {
let wire = Wire::new(i);
wire_indices.insert(i, Rc::new(RefCell::new(wire)));
}
} else if i == 1 {
let mut words = line_str.split_whitespace();
for _ in 0..words.next().unwrap().parse().unwrap() {
Expand All @@ -54,24 +96,22 @@ impl CircuitTrait for Circuit {
let x: usize = words.next().unwrap().parse().unwrap();
output_sizes.push(x);
}
} else if line_str != "" {
} else if !line_str.is_empty() {
let mut words = line_str.split_whitespace();
let noi = words.next().unwrap().parse().unwrap(); // number of inputs
let noo = words.next().unwrap().parse().unwrap(); // number of outputs
let input_wires = (0..noi)
.map(|_| {
wire_indices
.entry(words.next().unwrap().parse::<usize>().unwrap())
.or_insert(Wire::new())
.to_owned()
let k = words.next().unwrap().parse::<usize>().unwrap();
let x = wire_indices.get(&k).unwrap().clone();
x
})
.collect();
let output_wires = (0..noo)
.map(|_| {
wire_indices
.entry(words.next().unwrap().parse::<usize>().unwrap())
.or_insert(Wire::new())
.to_owned()
let k = words.next().unwrap().parse::<usize>().unwrap();
let x = wire_indices.get(&k).unwrap().clone();
x
})
.collect();
let gate_type = words.next().unwrap();
Expand Down Expand Up @@ -104,12 +144,16 @@ impl CircuitTrait for Circuit {
assert_eq!(nog, gates.len());
assert_eq!(wire_indices.keys().min().unwrap().to_owned(), 0);
assert_eq!(wire_indices.keys().max().unwrap().to_owned(), now - 1);
assert!(input_sizes.iter().sum::<usize>() + output_sizes.iter().sum::<usize>() <= now);

return Circuit {
input_sizes,
output_sizes,
gates,
wires: wire_indices.values().cloned().collect::<Vec<Wire>>(),
wires: wire_indices
.values()
.cloned()
.collect::<Vec<Rc<RefCell<Wire>>>>(),
};
}

Expand All @@ -119,6 +163,7 @@ impl CircuitTrait for Circuit {
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::{bool_array_to_number, number_to_bool_array};

#[test]
fn test_circuit() {
Expand All @@ -131,4 +176,17 @@ mod tests {
let circuit = Circuit::from_bristol("bristol/add.txt");
assert!(circuit.output_sizes[0] == 64);
}

#[test]
fn test_add_circuit() {
let mut circuit = Circuit::from_bristol("bristol/add.txt");
let a1 = 633;
let a2 = 15;
let b1 = number_to_bool_array(a1, 64);
let b2 = number_to_bool_array(a2, 64);

let o = circuit.evaluate(vec![b1, b2]);
let output = bool_array_to_number(o.get(0).unwrap().to_vec());
assert_eq!(output, a1 + a2);
}
}
Loading

0 comments on commit 6916a08

Please sign in to comment.