+/**
+ * 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(json_encode($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']);