Skip to content

Instantly share code, notes, and snippets.

@quin2
Created May 7, 2019 06:59
Show Gist options
  • Select an option

  • Save quin2/04a0003a349e5fdbb971264dd93a95b6 to your computer and use it in GitHub Desktop.

Select an option

Save quin2/04a0003a349e5fdbb971264dd93a95b6 to your computer and use it in GitHub Desktop.
Proof-of-concept cryptocurrency miner written in C
//implements a basic proof-of-work system in C. Code by quin2
/*
note: mining in this case is pretty easy beacuse our hash algo isn't computationally intensive, plus we're not
encoding a whole lot of data
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct block
{
int index;
int timestamp;
int balence;
int proof;
unsigned long lasthash;
};
//encodes blocks, because C hates strings
void stringify(char *in, struct block toConvert){
sprintf(
in,
"index:%d\ntimestamp:%d\nbalence:%d\nproof:%d\nlasthash:%lu\n",
toConvert.index,
toConvert.timestamp,
toConvert.balence,
toConvert.proof,
toConvert.lasthash
);
}
//handles string hashing
unsigned long hash(unsigned char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
//finds proof nonce so hash will end with 00000
int findProof(struct block toMine){
toMine.proof = 0;
while(1){
//check for valid proof
char mid1[150];
stringify(mid1, toMine);
unsigned char *mid = (unsigned char*)mid1;
unsigned long guess = hash(mid);
//check for trailing 0's...
int sum = 0, resid = 1;
for(int i = 0; i < 6; i++){
if((guess / resid) % 10 == 0) sum++;
resid = resid * 10;
}
if(sum == 5) break;
toMine.proof = toMine.proof + 1;
}
return toMine.proof;
}
int main(int argc, char *argv[]){
//fake 'genesis' block
struct block myBlock;
unsigned long last = 15591343936234076685U;
myBlock.index = 0; myBlock.timestamp = 1557014863; myBlock.balence = 50; myBlock.proof = 0; myBlock.lasthash = last;
int answer = findProof(myBlock);
printf("%d\n", answer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment