2 error_reporting(E_ALL | E_STRICT);
4 define('HASH_ALGO', MHASH_RIPEMD320);
5 define('BLOCK_SIZE', 100);
6 define('NONCE_INCREMENT', 0.0000000000000001);
7 define('START_TIME', microtime(TRUE));
8 define('CHECK_POINT', 'chash.pos');
11 $foundHashes = array();
16 * @author Roland Haeder <roland@mxchange.org>
17 * @copyright Copyright (c) 2013 by Core Developer Team
18 * @license See LICENSE (public-domain)
22 * Calculates a simple but stronger hash from given string. No salts are being
25 * @param $str The string to be hashed
26 * @return $hash The hash from string $str
28 function hashString ($str) {
29 // Calculate strong hash from given string
30 $hash = mhash(HASH_ALGO, $str);
32 // Return it hexadecimal-encoded
33 return bin2hex($hash);
37 * Double-hashes given string. This is done by hashing the given string and
38 * then hashing the generated hash again.
40 * @param $str The string to be hashed 4 times
41 * @return $hash The generated hash
43 function doubleHashString ($str) {
44 // Generate hash from given hash
45 $hash = hashString(hashString($str));
52 * Calculates a "modula-hash" based given two hashes.
54 * @param $hash1 Hash 1
55 * @param $hash2 Hash 2
57 function modulaHash ($hash1, $hash2) {
58 // Both must have same length
59 assert(strlen($hash1) === strlen($hash2));
64 // "Walk" trough first hash and get every 2 byte of both hashes
65 for ($idx = 0; $idx < strlen($hash1); $idx += 2) {
69 // Get both hash parts and convert to ASCII number
70 $part1 = hexdec(substr($hash1, $idx, 2));
71 $part2 = hexdec(substr($hash2, $idx, 2));
74 * If part1 is larget part2, part1 is divident and vise-versa. But don't do it
77 if (($part1 > $part2) && ($part2 > 0)) {
78 // 'part1' is larger than 'part2'
79 $mod = $part1 % $part2;
80 } elseif (($part1 < $part2) && ($part1 > 0)) {
81 // 'part2' is larger than 'part1'
82 $mod = $part2 % $part1;
85 // "Invert" the result against 255
88 // Encode to hex, pre-pad it with zeros and add to new hash
89 $modulaHash .= padHex($mod);
92 // Modula hash must have same length as input hash
93 assert(strlen($modulaHash) === strlen($hash1));
100 * Calculates a "sqrt-hash" based given two hashes and single-hash it
102 * @param $hash1 Hash 1
103 * @param $hash2 Hash 2
105 function sqrtHash ($hash1, $hash2) {
106 // Both must have same length
107 assert(strlen($hash1) === strlen($hash2));
112 // "Walk" trough first hash and get every 2 byte of both hashes
113 for ($idx = 0; $idx < strlen($hash1); $idx += 2) {
117 // Get both hash parts and convert to ASCII number
118 $part1 = hexdec(substr($hash1, $idx, 2));
119 $part2 = hexdec(substr($hash2, $idx, 2));
121 // Calculate square root of both parts being multiplied and round up, then "invert" it against 255
122 $sqrt = intval(255 - ceil(sqrt($part1 * $part2)));
124 // Encode to hex, pre-pad it with zeros and add to new hash
125 $sqrtHash .= padHex($sqrt);
128 // "sqrt-hash" must have same length as input hash
129 assert(strlen($sqrtHash) === strlen($hash1));
131 // Hash reversed "sqrt-hash" again and return it
132 return hashString(strrev($sqrtHash));
136 * Converts a number between 0 and 255 into a zero-padded hexadecimal string
138 * @param $num Number between 0 and 255
139 * @return $hex Hexadecimal string, padded with zeros
141 function padHex ($num) {
142 // Must be a integer number and between 0 and 255
143 assert(is_int($num));
148 $hex = str_pad(dechex($num), 2, '0', STR_PAD_LEFT);
155 * Calculates sum from given hash
157 * @param $hash Hash to calculate sum from
158 * @return $sum Sum from given hash
160 function calculateSumFromHash ($hash) {
161 // Everything starts with zero ...
165 for ($idx = 0; $idx < (strlen($hash) / 2); $idx++) {
167 $sum = $sum + (hexdec(substr($hash, $idx, 2)) * $idx & 256);
175 * Calculates new nonce
177 * @param $nonce Old nonce to be used
178 * @return $newNonce New nonce
180 function calculateNonce ($nonce) {
181 // Linear incrementation
182 $newNonce = $nonce + NONCE_INCREMENT;
189 * Calculate "genesis" hashes, please note that these "genesis strings" are now
190 * known to the public as you can read them here in source code and therefore I
191 * will not use them for the real genesis hashes.
194 // A famous quote from Deus Ex 2 - Invisible War
195 doublehashString('"Informations must be free." - AI Helios from Deus Ex'),
196 // My name + URL of my first StatusNet instance
197 doubleHashString('Roland Haeder, https://status.mxchange.org'),
198 // A famous quote from Linus Torwalds
199 doubleHashString('"Software is like sex. Its better when its free." - Linus Torwalds'),
200 // Possible truth ;-)
201 doubleHashString('September 11 is a big lie.'),
204 doubleHashString('GNU is Not Uni*.'),
205 // WINE is not an emulator
206 doubleHashString('WINE Is Not an Emulator.'),
207 // FlightGear - Fly free!
208 doubleHashString('FlightGear - Fly free!'),
209 // Linus Torwalds Quote
210 doubleHashString('Your code is shit.. your argument is shit.'),
213 // Calculate "modula hash" from 1st/4th and 2nd/3rd
214 $modulaHashes = array(
216 modulaHash($hashes[0], $hashes[3]),
217 modulaHash($hashes[1], $hashes[2]),
220 modulaHash($hashes[4], $hashes[7]),
221 modulaHash($hashes[5], $hashes[6]),
224 // Calculate "sqrt hash"
226 sqrtHash($modulaHashes[0], $modulaHashes[1]),
227 sqrtHash($modulaHashes[2], $modulaHashes[3])
230 // Calulcate modula hash
231 $modulaHash = doubleHashString(modulaHash($sqrtHashes[0], $sqrtHashes[1]));
234 print ('hashes=' . print_r($hashes, TRUE));
235 print ('modulaHashes=' . print_r($modulaHashes, TRUE));
236 print ('sqrtHashes=' . print_r($sqrtHashes, TRUE));
237 print ('modulaHash=' . $modulaHash . PHP_EOL);
239 // Total reward + hashes
244 // Is the check point there?
245 if (is_readable(CHECK_POINT)) {
247 $checkPoint = file_get_contents(CHECK_POINT);
250 $data = explode(':', $checkPoint);
253 assert(count($data) == 3);
255 // 1st element is nonce, 2nd hash, 3rd found hashes
256 $nonce = base64_decode($data[0]);
257 $modulaHash = $data[1];
258 $foundHashes = unserialize(base64_decode($data[2]));
260 // Create nonce (small)
261 $nonce = 1 / mt_rand();
265 print ('modulaHash=' . $modulaHash . PHP_EOL);
266 print ('nonce=' . $nonce . PHP_EOL);
267 print ('found=' . count($foundHashes) . PHP_EOL);
271 // Init hash-per-block counter and hashrate
275 // Wait for BLOCK_SIZE iterations (= found hashes). This is one block
276 $timeBlock = microtime(TRUE);
277 $timeDisplay = $timeBlock;
278 $timeFlush = $timeBlock;
280 // Time waited for a good block again (no iteration)
283 while (count($foundHashes) <= BLOCK_SIZE) {
284 // Create hash from modulaHash ("genesis hash") and nonce
285 $nonceHash = doubleHashString($modulaHash . $nonce);
288 $sumNonce = calculateSumFromHash($nonceHash);
289 $sumModula = calculateSumFromHash($modulaHash);
295 // Now start the "mining" ...
296 $timeHash = microtime(TRUE);
297 while ($sumNonce >= $sumModula) {
298 // Calculate new nonce
299 $nonce = calculateNonce($nonce);
302 $nonceHash = doubleHashString($modulaHash . $nonce);
305 $sumNonce = calculateSumFromHash($nonceHash);
307 // Time spend in loop
308 $testTime = abs(microtime(TRUE) - $timeDisplay);
310 // Calculate hashrate/sec
311 $hashrate = 1 / $testTime * $iterSecond * 2;
314 if ($testTime >= 1) {
316 print ('hashrate=' . $hashrate . ' hashes/sec,iterSecond=' . $iterSecond . ' iterations/sec' . PHP_EOL);
319 $timeDisplay = microtime(TRUE);
323 // Time spend from last flush
324 $testTime = abs(microtime(TRUE) - $timeFlush);
326 // Only once per 10 seconds
327 if ($testTime >= 10) {
329 print ('FLUSHING: ' . count($foundHashes) . ' total found.' . PHP_EOL);
332 file_put_contents(CHECK_POINT, base64_encode($nonce) . ':' . $modulaHash . ':' . base64_encode(serialize($foundHashes)));
334 $timeFlush = microtime(TRUE);
340 //print ('nonce=' . $nonce . ',iter=' . $iter . PHP_EOL);
341 //print ('nonceHash=' . $nonceHash . PHP_EOL);
342 //print ('sumNonce=' . $sumNonce . PHP_EOL);
343 //print ('sumModula=' . $sumModula . PHP_EOL);
346 // If the iteration is zero, then no hash is found
349 $timeBadHashes += abs(microtime(TRUE) - $timeHash);
352 //print('BAD:nonce=' . $nonce . PHP_EOL);
354 // Nothing found, so calculate new nonce
355 $nonce = calculateNonce($nonce);
359 // Add amount of hashes per block (double-hash)
360 $hashesPerBlock += $iter * 2 + 2;
363 array_push($foundHashes, array(
364 'modula_hash' => $modulaHash,
367 'hashes_block' => $hashesPerBlock,
368 'nonce_hash' => $nonceHash
372 print ('FOUND: nonceHash=' . $nonceHash . ',nonce=' . $nonce . ',iter=' . $iter . PHP_EOL);
375 // Use nonceHash as next modula hash
376 $modulaHash = $nonceHash;
379 // Time taken for one block
380 $timeBlock = abs(microtime(TRUE) - $timeBlock);
383 $reward = abs($timeBlock - $timeBadHashes) / $hashrate * $hashesPerBlock / BLOCK_SIZE * 1000;
384 print ('timeBlock=' . $timeBlock . ',timeBadHashes=' . $timeBadHashes . ',hashesPerBlock=' . $hashesPerBlock .',reward=' . $reward . PHP_EOL);
387 $totalHashes += $hashesPerBlock;
390 $foundHashes = array();
392 // Calculate new nonce
393 $nonce = calculateNonce($nonce);
395 // Add reward to total
396 $totalReward += $reward;
398 // Calculate average block value
399 $blockValue = $totalReward / $totalBlocks * $totalHashes / (BLOCK_SIZE * $totalBlocks);
401 // Calculate reward per hour (= 3600 seconds)
402 $rewardPerHour = $totalReward / abs(microtime(TRUE) - START_TIME) * 3600;
404 print ('totalReward=' . $totalReward . ',blockValue=' . $blockValue . ',rewardPerHour=' . $rewardPerHour . PHP_EOL);