Very noisy line (for web applications).
[core.git] / contrib / chash / chash.php
index a1e91c28c568cc741185092e906a2af57598c1fb..c37216ab3bb3826443e2a9ae03496c2da1db9cef 100644 (file)
@@ -1,6 +1,34 @@
 <?php
 error_reporting(E_ALL | E_STRICT);
 
+define('START_TIME'            , microtime(TRUE));
+define('CHECK_POINT'           , 'chash.pos');
+
+// Hashes needed to complete a "block"
+$GLOBALS['block_size']          = 100;
+$GLOBALS['none_increment']      = (1 / pow(10, 20));
+
+// Hashing algorythm
+$GLOBALS['hash_algo']           = MHASH_SHA256;
+
+// Automatic saving interval in seconds
+$GLOBALS['flush_file_time']     = 30;
+
+/*
+ * How long (in seconds) to try to find a proper hash until the best root hash
+ * is taken.
+ */
+$GLOBALS['restart_search_time'] = 1800;
+
+// Hashes per call
+$GLOBALS['hash_cycles'] = 5;
+
+// Total restarts
+$GLOBALS['total_restarts'] = 0;
+
+// Found hashes
+$GLOBALS['found_hashes'] = array(0 => array());
+
 /**
  * Continued-hashing
  *
@@ -18,22 +46,28 @@ error_reporting(E_ALL | E_STRICT);
  */
 function hashString ($str) {
        // Calculate strong hash from given string
-       $hash = mhash(MHASH_RIPEMD320, $str);
+       $hash = mhash($GLOBALS['hash_algo'], $str);
 
        // Return it hexadecimal-encoded
        return bin2hex($hash);
 }
 
 /**
- * Double-hashes given string. This is done by hashing the given string and
+ * Multiple-hashes given string. This is done by hashing the given string and
  * then hashing the generated hash again.
  *
  * @param      $str    The string to be hashed 4 times
  * @return     $hash   The generated hash
  */
-function doubleHashString ($str) {
+function multipleHashString ($str) {
        // Generate hash from given hash
-       $hash = hashString(hashString($str));
+       $hash = hashString($str);
+
+       // Now over-hash it
+       for ($idx = 0; $idx < ($GLOBALS['hash_cycles'] - 1); $idx++) {
+               // Over-hash the given hash
+               $hash = hashString($hash);
+       } // END - for
 
        // Return it
        return $hash;
@@ -49,6 +83,9 @@ function modulaHash ($hash1, $hash2) {
        // Both must have same length
        assert(strlen($hash1) === strlen($hash2));
 
+       // Init propability array with 256 zeros
+       $propability = array_fill(0, 256, 0);
+
        // Init new hash
        $modulaHash = '';
 
@@ -61,6 +98,9 @@ function modulaHash ($hash1, $hash2) {
                $part1 = hexdec(substr($hash1, $idx, 2));
                $part2 = hexdec(substr($hash2, $idx, 2));
 
+               // Debug message
+               //* NOISY-DEBUG: */ print 'part1=' . $part1 . ',part2=' . $part2 . PHP_EOL;
+
                /*
                 * If part1 is larget part2, part1 is divident and vise-versa. But don't do it
                 * if one is zero
@@ -68,18 +108,43 @@ function modulaHash ($hash1, $hash2) {
                if (($part1 > $part2) && ($part2 > 0)) {
                        // 'part1' is larger than 'part2'
                        $mod = $part1 % $part2;
-               } elseif (($part1 < $part2) && ($part1 > 0)) {
+               } elseif (($part2 > $part1) && ($part1 > 0)) {
                        // 'part2' is larger than 'part1'
                        $mod = $part2 % $part1;
                }
 
-               // "Invert" the result against 255
+               // $mod is now mostly a small number so try to "improve" it
+               //* NOISY-DEBUG: */ print 'mod[' . gettype($mod) . ']=' . $mod . ' - BEFORE!' . PHP_EOL;
+               $mod = (int) round(sqrt($mod * ($part1 + $part2 + $mod ^ 7) / 3));
+               //* NOISY-DEBUG: */ print 'mod[' . gettype($mod) . ']=' . $mod . ' - AFTER!' . PHP_EOL;
+
+               // Make sure it is valid
+               assert($mod >= 0);
+               assert($mod <= 255);
+
+               // "Invert" the result against 255 as zeros are not good for later calculations
                $mod = 255 - $mod;
 
+               // Add it to propability array for debugging
+               $propability[$mod]++;
+
                // Encode to hex, pre-pad it with zeros and add to new hash
                $modulaHash .= padHex($mod);
        } // END - for
 
+       // Debug propability array
+       $cnt = 0;
+       foreach ($propability as $value) {
+               // Is the value larger than one, means the number has been found at least once?
+               if ($value > 0) {
+                       // Then count it
+                       $cnt++;
+               } // END - if
+       } // END - foreach
+
+       // Debug message
+       //* NOISY-DEBUG: */ print('cnt=' . $cnt . '/' . strlen($hash1) / 2 . PHP_EOL);
+
        // Modula hash must have same length as input hash
        assert(strlen($modulaHash) === strlen($hash1));
 
@@ -142,40 +207,158 @@ function padHex ($num) {
        return $hex;
 }
 
+/**
+ * Calculates sum from given hash
+ *
+ * @param      $hash   Hash to calculate sum from
+ * @return     $sum    Sum from given hash
+ */
+function calculateSumFromHash ($hash) {
+       // Everything starts with zero ...
+       $sum = 0;
+
+       // Loop through hash
+       for ($idx = 0; $idx < (strlen($hash) / 2); $idx++) {
+               // And add it
+               $sum = $sum + hexdec(substr($hash, $idx, 2));
+       } // END - for
+
+       // And return it
+       return $sum;
+}
+
+/**
+ * Calculates new nonce
+ *
+ * @return     void
+ */
+function calculateNonce () {
+       // Linear incrementation
+       $GLOBALS['nonce'] += $GLOBALS['none_increment'];
+}
+
+/**
+ * Writes/flushes check-point file
+ *
+ * @param      $hash   Modula hash (or hash to save)
+ * @return     void
+ */
+function flushCheckPointFile ($hash) {
+       // Display message
+       print ('FLUSHING: Writing ' . count($GLOBALS['found_hashes']) . ' blocks ...' . PHP_EOL);
+
+       // Start timer
+       $timer = microtime(TRUE);
+
+       // Flush data
+       file_put_contents(
+               CHECK_POINT,
+               $GLOBALS['total_blocks'] . ':' .
+               $GLOBALS['total_reward'] . ':' .
+               $GLOBALS['total_hashes'] . ':' .
+               $GLOBALS['total_found'] . ':' .
+               $GLOBALS['total_restarts'] . ':' .
+               $GLOBALS['hash_cycles'] . ':' .
+               base64_encode((float) $GLOBALS['nonce']) . ':' .
+               $hash . ':' .
+               $GLOBALS['root_hash'] . ':' .
+               base64_encode(gzcompress(serialize($GLOBALS['found_hashes'])))
+       );
+
+       // Set time
+       $GLOBALS['time_flush'] = microtime(TRUE);
+       print ('FLUSHING: Took ' . ($GLOBALS['time_flush'] - $timer) . ' seconds.' . PHP_EOL);
+}
+
+/**
+ * Adds a found hash and flushes the checkpoint file
+ *
+ * @param      $hash   Hash to save
+ */
+function addFoundHash ($hash) {
+       // Increment counter
+       $GLOBALS['total_found']++;
+
+       // Add hash to array
+       array_push($GLOBALS['found_hashes'][$GLOBALS['total_blocks']], array(
+               'modula_hash'  => $GLOBALS['modula_hash'],
+               'genesis_hash' => $GLOBALS['genesis_hash'],
+               'root_hash'    => $GLOBALS['root_hash'],
+               'nonce'        => (float) $GLOBALS['nonce'],
+               'iter'         => $GLOBALS['iteration'],
+               'hashes_block' => $GLOBALS['hashes_block'],
+               'hash_cycles'  => $GLOBALS['hash_cycles'],
+               'nonce_hash'   => $hash
+       ));
+
+       // Found hash:
+       print ('FOUND: hash=' . $hash . ',nonce=' . $GLOBALS['nonce'] . ',total_found=' . $GLOBALS['total_found'] . PHP_EOL);
+
+       // Set time as a new hash was found
+       $GLOBALS['found_time'] = microtime(TRUE);
+
+       // Flush check-point file after new hash is found
+       flushCheckPointFile($hash);
+
+       // Use nonceHash as next modula hash
+       setModulaHash($hash);
+}
+
+/**
+ * Initializes nonce
+ *
+ * @return     void
+ */
+function initNonce () {
+       $GLOBALS['nonce'] = 1 / (mt_rand() ^ pi());
+       print (__FUNCTION__ . ': nonce=' . $GLOBALS['nonce'] . PHP_EOL);
+}
+
+/**
+ * Sets modula hash and calculates sum of it
+ *
+ * @param      $hash   Hash to set as "modula hash"
+ * @return     void
+ */
+function setModulaHash ($hash) {
+       $GLOBALS['modula_hash'] = $hash;
+       $GLOBALS['sum_modula']  = calculateSumFromHash($GLOBALS['modula_hash']);
+}
+
 /*
  * Calculate "genesis" hashes, please note that these "genesis strings" are now
  * known to the public as you can read them here in source code and therefore I
  * will not use them for the real genesis hashes.
  */
-$hashes = array(
+$gensisHashes = array(
        // A famous quote from Deus Ex 2 - Invisible War
-       doublehashString('"Informations must be free." - AI Helios'),
+       multiplehashString('"Informations must be free." - AI Helios from Deus Ex'),
        // My name + URL of my first StatusNet instance
-       doubleHashString('Roland Haeder, http://status.mxchange.org'),
+       multipleHashString('Roland Haeder, https://status.mxchange.org'),
        // A famous quote from Linus Torwalds
-       doubleHashString('"Software is like sex. Its better when its free." - Linus Torwalds'),
-       // Possible truth ;-)
-       doubleHashString('September 11 is a big lie.'),
+       multipleHashString('"Software is like sex. Its better when its free." - Linus Torwalds'),
+       // Well ...
+       multipleHashString('September 11 is a big lie.'),
 
        // GNU is not Uni*
-       doubleHashString('GNU is Not Uni*.'),
+       multipleHashString('GNU is Not Uni*.'),
        // WINE is not an emulator
-       doubleHashString('WINE Is Not an Emulator.'),
+       multipleHashString('WINE Is Not an Emulator.'),
        // FlightGear - Fly free!
-       doubleHashString('FlightGear - Fly free!'),
-       // Linus Torwalds Quote
-       doubleHashString('Your code is shit.. your argument is shit.'),
+       multipleHashString('FlightGear - Fly free!'),
+       // Quote from Linus Torwalds
+       multipleHashString('Your code is shit. Your argument is shit.'),
 );
 
 // Calculate "modula hash" from 1st/4th and 2nd/3rd
 $modulaHashes = array(
        // "Block" 0
-       modulaHash($hashes[0], $hashes[3]),
-       modulaHash($hashes[1], $hashes[2]),
+       modulaHash($gensisHashes[0], $gensisHashes[3]),
+       modulaHash($gensisHashes[1], $gensisHashes[2]),
 
        // "Block" 1
-       modulaHash($hashes[4], $hashes[7]),
-       modulaHash($hashes[5], $hashes[6]),
+       modulaHash($gensisHashes[4], $gensisHashes[7]),
+       modulaHash($gensisHashes[5], $gensisHashes[6]),
 );
 
 // Calculate "sqrt hash"
@@ -185,13 +368,252 @@ $sqrtHashes = array(
 );
 
 // Calulcate modula hash
-$modulaHash = modulaHash($sqrtHashes[0], $sqrtHashes[1]);
+setModulaHash(multipleHashString(modulaHash($sqrtHashes[0], $sqrtHashes[1])));
+
+// This is also the "genesis" hash and first root hash
+$GLOBALS['genesis_hash'] = $GLOBALS['modula_hash'];
+$GLOBALS['root_hash']    = $GLOBALS['modula_hash'];
 
 // Output results
-print ('hashes=' . print_r($hashes, TRUE));
+print ('hashes=' . print_r($gensisHashes, TRUE));
 print ('modulaHashes=' . print_r($modulaHashes, TRUE));
 print ('sqrtHashes=' . print_r($sqrtHashes, TRUE));
-print ('modulaHash=' . $modulaHash . PHP_EOL);
+print ('modulaHash=' . $GLOBALS['modula_hash'] . PHP_EOL);
+
+// Total reward + hashes
+$GLOBALS['total_reward']   = 0;
+$GLOBALS['total_hashes']   = 0;
+$GLOBALS['total_found']    = 0;
+$GLOBALS['total_blocks']   = 0;
+$GLOBALS['found_time']     = microtime(TRUE);
+
+// Is the check point there?
+if (is_readable(CHECK_POINT)) {
+       // Then load it
+       $checkPoint = file_get_contents(CHECK_POINT);
+
+       // Explode it
+       $data = explode(':', $checkPoint);
+
+       // Assert on count
+       assert(count($data) == 10);
+
+       // 1st element is nonce, 2nd hash, 3rd found hashes
+       $GLOBALS['total_blocks']   = $data[0];
+       $GLOBALS['total_reward']   = $data[1];
+       $GLOBALS['total_hashes']   = $data[2];
+       $GLOBALS['total_found']    = $data[3];
+       $GLOBALS['total_restarts'] = $data[4];
+       $GLOBALS['hash_cycles']    = intval($data[5]);
+       $GLOBALS['nonce']          = (float) base64_decode($data[6]);
+       $GLOBALS['root_hash']      = $data[8];
+       $GLOBALS['found_hashes']   = unserialize(gzuncompress(base64_decode($data[9])));
+
+       // Set modula hash
+       setModulaHash($data[7]);
+} else {
+       // Create nonce (small)
+       initNonce();
+}
+
+// Output again
+print ('modulaHash=' . $GLOBALS['modula_hash'] . PHP_EOL);
+print ('nonce=' . $GLOBALS['nonce'] . PHP_EOL);
+print ('found=' . count($GLOBALS['found_hashes'][$GLOBALS['total_blocks']]) . PHP_EOL);
+
+// Start "mining"
+while (TRUE) {
+       // Init hash-per-block counter and hashrate
+       $GLOBALS['hashes_block'] = 0;
+       $hashrate = 0;
+
+       // Wait for block_size iterations (= found hashes). This is one block
+       $timeBlock   = microtime(TRUE);
+       $timeDisplay = $timeBlock;
+       $GLOBALS['time_flush'] = $timeBlock;
+
+       // Time waited for a good block again (no iteration)
+       $timeBadHashes = 0;
+
+       while (count($GLOBALS['found_hashes'][$GLOBALS['total_blocks']]) <= $GLOBALS['block_size']) {
+               // Create hash from modulaHash ("genesis hash") and nonce
+               $nonceHash = multipleHashString($GLOBALS['nonce'] . $GLOBALS['modula_hash']);
+
+               // Calculate sums
+               $sumNonce  = calculateSumFromHash($nonceHash);
+
+               // Init counter
+               $GLOBALS['iteration'] = 0;
+               $GLOBALS['iteration_second'] = 0;
+
+               // Now start the "mining" ...
+               $timeHash = microtime(TRUE);
+               while ($sumNonce < $GLOBALS['sum_modula']) {
+                       // Calculate new nonce
+                       calculateNonce();
+
+                       // And hash again
+                       $nonceHash = multipleHashString($GLOBALS['nonce'] . $GLOBALS['modula_hash']);
+
+                       // Calculate sums
+                       $sumNonce  = calculateSumFromHash($nonceHash);
+
+                       // Time spend in loop
+                       $testTime = abs(microtime(TRUE) - $timeDisplay);
+
+                       // Calculate hashrate/sec
+                       $hashrate = 1 / $testTime * $GLOBALS['iteration_second'] * $GLOBALS['hash_cycles'];
+
+                       // Only every second
+                       if ($testTime >= 1) {
+                               // Display hash rate
+                               print ('hashrate=' . round($hashrate) . ' hashes/sec,iterSecond=' . $GLOBALS['iteration_second'] . ' iterations/sec' . PHP_EOL);
+
+                               // Reset timer
+                               $timeDisplay = microtime(TRUE);
+                               $GLOBALS['iteration_second']  = 0;
+                       } // END - if
+
+                       // Time spend from last flush
+                       $testTime = abs(microtime(TRUE) - $GLOBALS['time_flush']);
+
+                       // Only once per 10 seconds
+                       if ($testTime >= $GLOBALS['flush_file_time']) {
+                               // Flush check-point file
+                               flushCheckPointFile($GLOBALS['modula_hash']);
+                       } // END - if
+
+                       // Time spend from last found block
+                       $testTime = abs(microtime(TRUE) - $GLOBALS['found_time']);
+
+                       // Is the last found time to far away?
+                       if ($testTime >= $GLOBALS['restart_search_time']) {
+                               // Count up restart
+                               $GLOBALS['total_restarts']++;
+
+                               // Output message
+                               print('total_restarts=' . $GLOBALS['total_restarts'] . ' - Restarting ...');
+
+                               // Count all root (genesis) hashes
+                               $rootHashes = array();
+                               foreach ($GLOBALS['found_hashes'] as $block) {
+                                       // "Walk" through all blocks
+                                       foreach ($block as $hash) {
+                                               if (!isset($hash['root_hash'])) {
+                                                       // Bad file
+                                                       die('INCONSISTENCY: hash=' . print_r($hash, TRUE));
+                                               } // END - if
+
+                                               if (isset($rootHashes[$hash['root_hash']])) {
+                                                       // Count up
+                                                       $rootHashes[$hash['root_hash']]++;
+                                               } else {
+                                                       // First entry found
+                                                       $rootHashes[$hash['root_hash']] = 1;
+                                               }
+                                       } // END - foreach
+                               } // END - foreach
+
+                               // Find best root hash
+                               $bestRootHash = '';
+                               $bestRootCount = 0;
+                               foreach ($rootHashes as $hash => $count) {
+                                       // Debug message
+                                       //* NOISY-DEBUG: */ print ('hash=' . $hash . ',count=' . $count . ',bestRootHash=' . $bestRootHash . ',bestRootCount=' . $bestRootCount . PHP_EOL);
+
+                                       // Is a better one found?
+                                       if ($count > $bestRootCount) {
+                                               // Remember it
+                                               $bestRootHash  = $hash;
+                                               $bestRootCount = $count;
+                                       } // END - if
+                               } // END - foreach
+
+                               // Output message
+                               print ('bestRootHash=' . $bestRootHash . ',bestRootCount=' . $bestRootCount . PHP_EOL);
+
+                               // Search for latest best root hash
+                               foreach ($GLOBALS['found_hashes'] as $block) {
+                                       // "Walk" through whole block and search for first appearance of best root hash
+                                       foreach ($block as $idx => $hash) {
+                                               // Is the root hash there?
+                                               if ($hash['root_hash'] == $bestRootHash) {
+                                                       // Set found modula hash as new root and current modula hash
+                                                       $GLOBALS['root_hash']   = $hash['nonce_hash'];
+                                                       setModulaHash($hash['nonce_hash']);
+                                                       print ('idx=' . $idx . ',modulaHash=' . $GLOBALS['root_hash'] . ' - Is now new root hash!' . PHP_EOL);
+
+                                                       // Reset "found time" (when a hash was found)
+                                                       $GLOBALS['found_time'] = microtime(TRUE);
+
+                                                       // Re-initialize nonce
+                                                       initNonce();
+
+                                                       // Abort search
+                                                       break;
+                                               } // END - if
+                                       } // END - for
+                               } // END - foreach
+                       } // END - if
+
+                       // Next round
+                       $GLOBALS['iteration']++;
+                       $GLOBALS['iteration_second']++;
+                       //print ('nonce=' . $GLOBALS['nonce'] . ',iteration=' . $GLOBALS['iteration'] . PHP_EOL);
+                       //print ('nonceHash=' . $nonceHash . PHP_EOL);
+                       //print ('sumNonce=' . $sumNonce . PHP_EOL);
+                       //print ('sumModula=' . $GLOBALS['sum_modula'] . PHP_EOL);
+               } // END - while
+
+               // If the iteration is zero, then no hash is found
+               if ($GLOBALS['iteration'] == 0) {
+                       // Bad hash found
+                       $timeBadHashes += abs(microtime(TRUE) - $timeHash);
+
+                       // And next round
+                       print('BAD:nonce=' . $GLOBALS['nonce'] . PHP_EOL);
+
+                       // Nothing found, so calculate new nonce
+                       calculateNonce();
+                       continue;
+               } // END - if
+
+               // Add amount of hashes per block (multiple-hash)
+               $GLOBALS['hashes_block'] += $GLOBALS['iteration'] * $GLOBALS['hash_cycles'] + $GLOBALS['hash_cycles'];
+
+               // Push found hash
+               addFoundHash($nonceHash);
+       } // END - while
+
+       // Time taken for one
+       $timeBlock = abs(microtime(TRUE) - $timeBlock);
+
+       // Calculate reward
+       $reward = abs($timeBlock - $timeBadHashes) / $hashrate * $GLOBALS['hashes_block'] / $GLOBALS['block_size'] * 1000;
+       print ('timeBlock=' . $timeBlock . ',timeBadHashes=' . $timeBadHashes . ',hashesPerBlock=' . $GLOBALS['hashes_block'] .',reward=' . $reward . PHP_EOL);
+
+       // Block completed
+       $GLOBALS['total_hashes'] += $GLOBALS['hashes_block'];
+       $GLOBALS['total_blocks']++;
+       $GLOBALS['hashes_block'] = 0;
+
+       // Init next block
+       $GLOBALS['found_hashes'][$GLOBALS['total_blocks']] = array();
+
+       // Calculate new nonce
+       calculateNonce();
+
+       // Add reward to total
+       $GLOBALS['total_reward'] += $reward;
+
+       // Calculate average block value
+       $blockValue = $GLOBALS['total_reward'] / $GLOBALS['total_blocks'] * $GLOBALS['total_hashes'] / ($GLOBALS['block_size'] * $GLOBALS['total_blocks']);
+
+       // Calculate reward per hour (= 3600 seconds)
+       $rewardPerHour = $GLOBALS['total_reward'] / abs(microtime(TRUE) - START_TIME) * 3600;
+
+       print ('totalReward=' . $GLOBALS['total_reward'] . ',blockValue=' . $blockValue . ',rewardPerHour=' . $rewardPerHour . PHP_EOL);
+} // END - while
 
 // [EOF]
 ?>