Continued with chash:
[core.git] / contrib / chash / lib / functions.php
1 <?php
2 /**
3  * Calculates a simple but stronger hash from given string. No salts are being
4  * added here.
5  *
6  * @param       $str    The string to be hashed
7  * @return      $hash   The hash from string $str
8  */
9 function hashString ($str) {
10         // Calculate strong hash from given string
11         $hash = Scrypt::hash($str, $GLOBALS['salt'], $GLOBALS['difficulty']);
12
13         // Return it directly
14         return $hash;
15 }
16
17 /**
18  * Multiple-hashes given string. This is done by hashing the given string and
19  * then hashing the generated hash again.
20  *
21  * @param       $str    The string to be hashed 4 times
22  * @return      $hash   The generated hash
23  */
24 function multipleHashString ($str) {
25         // Generate hash from given hash
26         $hash = hashString($str);
27
28         // Now over-hash it
29         for ($idx = 0; $idx < ($GLOBALS['hash_cycles'] - 1); $idx++) {
30                 // Over-hash the given hash
31                 $hash = hashString($hash);
32         } // END - for
33
34         // Return it
35         return $hash;
36 }
37
38 /**
39  * Calculates sum from given hash
40  *
41  * @param       $hash   Hash to calculate sum from
42  * @return      $sum    Sum from given hash
43  */
44 function calculateSumFromHash ($hash) {
45         // Everything starts with zero ...
46         //* NOISY-DEBUG: */ printf('[%s:%d]: hash(%d)=%s - CALLED!'. PHP_EOL, __FUNCTION__, __LINE__, strlen($hash), $hash);
47         $sum = 0;
48
49         // Part of the hash is not decodeable
50         $decodeA = explode('$', $hash);
51         $decode = $decodeA[4];
52
53         // Loop through hash
54         //* NOISY-DEBUG: */ printf('[%s:%d]: decode=%s' . PHP_EOL, __FUNCTION__, __LINE__, $decode);
55         for ($idx = 0; $idx < (strlen($decode) / 2); $idx++) {
56                 // And add it
57                 $sum = $sum + hexdec(substr($decode, $idx, 2));
58         } // END - for
59
60         // And return it
61         //* NOISY-DEBUG: */ printf('[%s:%d]: sum=%d - EXIT!' . PHP_EOL, __FUNCTION__, __LINE__, $sum);
62         return $sum;
63 }
64
65 /**
66  * Calculates new nonce
67  *
68  * @return      void
69  */
70 function calculateNonce () {
71         // Linear incrementation
72         $GLOBALS['nonce'] += $GLOBALS['none_increment'];
73 }
74
75 /**
76  * Writes/flushes check-point file
77  *
78  * @param       $hash   Found hash or gensis hash
79  * @return      void
80  */
81 function flushCheckPointFile ($hash) {
82         // Display message
83         print ('FLUSHING: Writing ' . count($GLOBALS['found_hashes']) . ' blocks ...' . PHP_EOL);
84
85         // Start timer
86         $timer = microtime(true);
87
88         // Flush data
89         file_put_contents(
90                 CHECKPOINT_FILE,
91                 $GLOBALS['total_blocks'] . '|' .
92                 $GLOBALS['total_reward'] . '|' .
93                 $GLOBALS['total_hashes'] . '|' .
94                 $GLOBALS['total_found'] . '|' .
95                 $GLOBALS['total_restarts'] . '|' .
96                 $GLOBALS['hash_cycles'] . '|' .
97                 $GLOBALS['salt'] . '|' .
98                 $GLOBALS['difficulty'] . '|' .
99                 base64_encode((float) $GLOBALS['nonce']) . '|' .
100                 $hash . '|' .
101                 $GLOBALS['root_hash'] . '|' .
102                 base64_encode(gzcompress(json_encode($GLOBALS['found_hashes'])))
103         );
104
105         // Set time
106         $GLOBALS['time_flush'] = microtime(true);
107         print ('FLUSHING: Took ' . ($GLOBALS['time_flush'] - $timer) . ' seconds.' . PHP_EOL);
108 }
109
110 /**
111  * Adds a found hash and flushes the checkpoint file
112  *
113  * @param       $hash   Hash to save
114  */
115 function addFoundHash ($hash) {
116         // Increment counter
117         $GLOBALS['total_found']++;
118
119         // Add hash to array
120         array_push($GLOBALS['found_hashes'][$GLOBALS['total_blocks']], [
121                 'current_hash' => $GLOBALS['current_hash'],
122                 'root_hash'    => $GLOBALS['root_hash'],
123                 'nonce'        => (float) $GLOBALS['nonce'],
124                 'iter'         => $GLOBALS['iteration'],
125                 'hashes_block' => $GLOBALS['hashes_block'],
126                 'hash_cycles'  => $GLOBALS['hash_cycles'],
127                 'difficulty'   => $GLOBALS['difficulty'],
128                 'nonce_hash'   => $hash,
129         ]);
130
131         // Found hash:
132         print ('FOUND: hash=' . $hash . ',nonce=' . $GLOBALS['nonce'] . ',total_found=' . $GLOBALS['total_found'] . PHP_EOL);
133
134         // Set time as a new hash was found
135         $GLOBALS['found_time'] = microtime(true);
136
137         // Flush check-point file after new hash is found
138         flushCheckPointFile($hash);
139 }
140
141 /**
142  * Initializes nonce
143  *
144  * @return      void
145  */
146 function initNonce () {
147         $GLOBALS['nonce'] = 1 / (mt_rand() ^ (1 / pi()));
148         print (__FUNCTION__ . ': nonce=' . $GLOBALS['nonce'] . PHP_EOL);
149 }
150
151 /**
152  * Sums all hex parts of the hash to one final sum
153  *
154  * @param       $hash   Hex-hash to sum
155  * @return      Sum of hash
156  */
157 function sumHash ($hash) {
158         // Init it
159         $sum = 0;
160
161         for ($i = 0; $i < (strlen($hash) / 2); $i++) {
162                 $sum += hexdec(substr($hash, $i, 2));
163         }
164
165         return $sum;
166 }
167
168 /**
169  * Loads check-point file, if found
170  *
171  * @return      void
172  */
173 function loadCheckpointFile () {
174         // Is the check point there?
175         if (is_readable(CHECKPOINT_FILE)) {
176                 // Then load it
177                 $checkPoint = file_get_contents(CHECKPOINT_FILE);
178
179                 // Explode it
180                 $data = explode('|', $checkPoint);
181
182                 // Assert on count
183                 assert(count($data) == 10);
184
185                 // 1st element is nonce, 2nd hash, 3rd found hashes
186                 $GLOBALS['total_blocks']   = $data[0];
187                 $GLOBALS['total_reward']   = $data[1];
188                 $GLOBALS['total_hashes']   = $data[2];
189                 $GLOBALS['total_found']    = $data[3];
190                 $GLOBALS['total_restarts'] = $data[4];
191                 $GLOBALS['hash_cycles']    = intval($data[5]);
192                 $GLOBALS['salt']           = $data[6];
193                 $GLOBALS['difficulty']     = $data[7];
194                 $GLOBALS['nonce']          = (float) base64_decode($data[8]);
195                 $GLOBALS['current_hash']   = $data[9];
196                 $GLOBALS['root_hash']      = $data[9];
197                 $GLOBALS['found_hashes']   = json_decode(gzuncompress(base64_decode($data[11])), TRUE);
198         } // END - if
199 }