aboutsummaryrefslogtreecommitdiff
path: root/wasm/solver.c
diff options
context:
space:
mode:
Diffstat (limited to 'wasm/solver.c')
-rw-r--r--wasm/solver.c51
1 files changed, 51 insertions, 0 deletions
diff --git a/wasm/solver.c b/wasm/solver.c
new file mode 100644
index 0000000..f1c4fa6
--- /dev/null
+++ b/wasm/solver.c
@@ -0,0 +1,51 @@
+#include "sha256.h"
+
+unsigned char challenge[32];
+
+char validate_hash(unsigned char *hash, unsigned char zero_bit_count) {
+ unsigned char q = zero_bit_count / 8;
+ unsigned char r = zero_bit_count % 8;
+
+ for (unsigned char i = 0; i < q; i++) {
+ if (hash[i] != 0) {
+ return 0;
+ }
+ }
+ if (r > 0) {
+ unsigned char mask = (unsigned char)(0xFF << (8 - r));
+ if (hash[q] & mask) {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+unsigned char *get_challenge_ptr() {
+ return challenge;
+}
+
+unsigned long long solve(unsigned char difficulty) {
+ unsigned long long nonce;
+ SHA256_CTX context;
+
+ unsigned char hash[32];
+
+ nonce = 0;
+
+ while(1) {
+ sha256_init(&context);
+ sha256_update(&context, challenge, sizeof(challenge));
+ sha256_update(&context, (unsigned char*)(&nonce), sizeof(nonce));
+ sha256_final(&context, hash);
+
+ if(validate_hash(hash, difficulty)) {
+ // we did it!!
+ break;
+ }
+
+ nonce++;
+ }
+
+ return nonce;
+}