-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminer.cpp
More file actions
63 lines (52 loc) · 2.02 KB
/
miner.cpp
File metadata and controls
63 lines (52 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
// A simple structure representing a Bitcoin-style Block Header
struct BlockHeader {
int version = 1;
std::string prevHash = "00000000000000000000000000000000";
std::string merkleRoot = "a1b2c3d4e5f6g7h8i9j0";
long timestamp = std::time(0);
int difficulty = 4; // Number of leading zeros required
long nonce = 0; // The variable we change to "mine"
};
// A mock hash function to simulate the hashing process
std::string simpleHash(std::string data) {
unsigned long hash = 5381;
for (char c : data) {
hash = ((hash << 5) + hash) + c; // djb2 algorithm
}
std::stringstream ss;
ss << std::hex << hash;
return ss.str();
}
void mineBlock(BlockHeader& header) {
std::string hash = "";
std::string target(header.difficulty, '0'); // e.g., "0000"
std::cout << "Mining started with difficulty: " << header.difficulty << "...\n";
auto start = std::chrono::high_resolution_clock::now();
while (true) {
// Construct a string of the header data
std::string headerData = std::to_string(header.version) + header.prevHash +
header.merkleRoot + std::to_string(header.nonce);
hash = simpleHash(headerData);
// Check if the hash starts with our target zeros
if (hash.substr(0, header.difficulty) == target) {
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "\n[SUCCESS] Block Mined!\n";
std::cout << "Hash: " << hash << "\n";
std::cout << "Nonce: " << header.nonce << "\n";
std::cout << "Time taken: " << diff.count() << " seconds\n";
break;
}
header.nonce++; // Try the next number
if (header.nonce % 100000 == 0) std::cout << "."; // Progress indicator
}
}
int main() {
BlockHeader newBlock;
mineBlock(newBlock);
return 0;
}