OSDN Git Service

Increase number of refine loops.
[mhash384/mhash384.git] / tools / GenTables / src / gen_table_mix.c
1 /* ----------------------------------------------------------------------------------------------- */
2 /* MHash-384 - Generate tables utility program                                                     */
3 /* Copyright(c) 2016 LoRd_MuldeR <mulder2@gmx.de>                                                  */
4 /*                                                                                                 */
5 /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software   */
6 /* and associated documentation files(the "Software"), to deal in the Software without             */
7 /* restriction, including without limitation the rights to use, copy, modify, merge, publish,      */
8 /* distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the */
9 /* Software is furnished to do so, subject to the following conditions:                            */
10 /*                                                                                                 */
11 /* The above copyright notice and this permission notice shall be included in all copies or        */
12 /* substantial portions of the Software.                                                           */
13 /*                                                                                                 */
14 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING   */
15 /* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND      */
16 /* NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,     */
17 /* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  */
18 /* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.         */
19 /* ----------------------------------------------------------------------------------------------- */
20
21 #include "common.h"
22 #include "thread_utils.h"
23 #include "twister.h"
24 #include "boxmuller.h"
25
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <string.h>
29 #include <time.h>
30 #include <stdbool.h>
31 #include <io.h>
32
33 //-----------------------------------------------------------------------------
34 // Const
35 //-----------------------------------------------------------------------------
36
37 #define HASH_LEN 384
38
39 #define DISTANCE_MIN 45
40
41 #define ROW_NUM 997                     /*total number of rows*/
42 #define ROW_LEN (HASH_LEN / CHAR_BIT)   /*number of indices per row*/
43
44 #define __DISTANCE_STR(X) #X
45 #define _DISTANCE_STR(X) __DISTANCE_STR(X)
46 #define DISTANCE_STR _DISTANCE_STR(DISTANCE_MIN)
47
48 #define MAGIC_NUMBER 0x76A3D06509A73016ui64
49
50 //-----------------------------------------------------------------------------
51 // Globals
52 //-----------------------------------------------------------------------------
53
54 static uint8_t g_table[ROW_NUM][HASH_LEN];
55
56 static size_t g_spinpos = 0;
57 static char SPINNER[4] = { '/', '-', '\\', '|' };
58
59 //-----------------------------------------------------------------------------
60 // Utility Functions
61 //-----------------------------------------------------------------------------
62
63 static inline void swap(uint8_t *const row_buffer, const size_t a, const size_t b)
64 {
65         const uint8_t temp = row_buffer[a];
66         row_buffer[a] = row_buffer[b];
67         row_buffer[b] = temp;
68 }
69
70 static inline void random_permutation(twister_t *const rand, uint8_t *const row_buffer)
71 {
72         for (uint32_t i = 0; i < ROW_LEN; ++i)
73         {
74                 row_buffer[i] = ((uint8_t)i);
75         }
76         for (uint32_t i = 0; i < ROW_LEN - 1U; ++i)
77         {
78                 swap(row_buffer, i, next_rand_range(rand, ROW_LEN - i) + i);
79         }
80 }
81
82 static inline void swap_multiple_random(twister_t *const rand, uint8_t *const row_buffer, const size_t count)
83 {
84         bool map[ROW_LEN];
85         memset(&map[0], 0, sizeof(bool) * ROW_LEN);
86         for (size_t i = 0U; i < count; ++i)
87         {
88                 size_t a, b;
89                 do
90                 {
91                         a = next_rand_range(rand, ROW_LEN);
92                         b = next_rand_range(rand, ROW_LEN);
93                 } 
94                 while(map[a] || (a == b));
95                 map[a] = map[b] = true;
96                 swap(row_buffer, a, b);
97         }
98 }
99
100 static inline void rotate_row(uint8_t *const row_buffer)
101 {
102         const uint8_t temp = row_buffer[0];
103         for (uint32_t k = 0U; k < ROW_LEN - 1U; ++k)
104         {
105                 row_buffer[k] = row_buffer[k + 1U];
106         }
107         row_buffer[ROW_LEN - 1U] = temp;
108 }
109
110 static inline void reverse_row(uint8_t *const row_buffer)
111 {
112         size_t j = ROW_LEN - 1U;
113         for (size_t i = 0U; i < ROW_LEN / 2U; ++i)
114         {
115                 swap(row_buffer, i, j--);
116         }
117 }
118
119 static inline uint32_t check_permutation(const size_t index, const uint8_t *const row_buffer)
120 {
121         uint32_t error = 0U;
122         for (size_t i = 0; i < ROW_LEN; ++i)
123         {
124                 if (row_buffer[i] == ((uint8_t)i))
125                 {
126                         ++error;
127                 }
128         }
129         if(error)
130         {
131                 return ROW_LEN + error;
132         }
133         for (size_t i = 0; i < index; ++i)
134         {
135                 uint32_t distance = 0U;
136                 for (size_t j = 0; j < ROW_LEN; ++j)
137                 {
138                         if (g_table[i][j] != row_buffer[j])
139                         {
140                                 distance++;
141                         }
142                 }
143                 if (distance < DISTANCE_MIN)
144                 {
145                         error = max_ui32(error, DISTANCE_MIN - distance);
146                 }
147         }
148         return error;
149 }
150
151 static void print_row(const uint8_t *const row_buffer)
152 {
153         for (size_t i = 0; i < ROW_LEN; ++i)
154         {
155                 printf(i ? ",%02X" : "%02X", row_buffer[i]);
156         }
157         puts("");
158 }
159
160 static inline void permutation_to_shuffle_indices(const uint8_t *const row_buffer, uint8_t *const indices_out)
161 {
162         uint8_t reference[ROW_LEN];
163         for (uint32_t i = 0U; i < ROW_LEN; ++i)
164         {
165                 reference[i] = ((uint8_t)i);
166         }
167         for (uint32_t i = 0U; i < ROW_LEN; ++i)
168         {
169                 indices_out[i] = UINT8_MAX;
170                 for (uint32_t j = i; j < ROW_LEN; ++j)
171                 {
172                         if (reference[j] == row_buffer[i])
173                         {
174                                 swap(&reference[0], i, j);
175                                 indices_out[i] = ((uint8_t)j);
176                                 break;
177                         }
178                 }
179         }
180         for (uint32_t i = 0; i < ROW_LEN; ++i)
181         {
182                 if ((indices_out[i] == UINT8_MAX) || (reference[i] != row_buffer[i]))
183                 {
184                         puts("ERROR: Failed to derive shuffle indices!\n");
185                 }
186         }
187 }
188
189 static dump_table(FILE *out)
190 {
191         fprintf(out, "uint8_t MHASH_384_TABLE_MIX[%u][MHASH_384_LEN] =\n{\n", ROW_NUM);
192         for (size_t i = 0; i < ROW_NUM; i++)
193         {
194                 uint8_t shuffle_indices[ROW_LEN];
195                 permutation_to_shuffle_indices(&g_table[i][0], &shuffle_indices[0]);
196                 fputs("\t{ ", out);
197                 for (size_t j = 0; j < ROW_LEN; j++)
198                 {
199                         if (j > 0)
200                         {
201                                 fputc(',', out);
202                         }
203                         fprintf(out, "0x%02X", shuffle_indices[j]);
204                 }
205                 fprintf(out, " }%s /*%03u*/\n", (i != (ROW_NUM - 1)) ? "," : " ", (uint32_t)i);
206         }
207         fputs("};\n", out);
208 }
209
210 //-----------------------------------------------------------------------------
211 // Save / Load
212 //-----------------------------------------------------------------------------
213
214 static bool save_table_data(const wchar_t *const filename, const size_t rows_completed_in)
215 {
216         FILE *const file = _wfopen(filename, L"wb");
217         if (file)
218         {
219                 bool success = true;
220                 const uint64_t magic_number = MAGIC_NUMBER;
221                 const uint32_t hash_len = HASH_LEN, distance_min = DISTANCE_MIN, rows_completed = (uint32_t)rows_completed_in;
222                 fwrite(&magic_number, sizeof(uint64_t), 1, file);
223                 fwrite(&hash_len, sizeof(uint32_t), 1, file);
224                 fwrite(&distance_min, sizeof(uint32_t), 1, file);
225                 fwrite(&rows_completed, sizeof(uint32_t), 1, file);
226                 for (uint32_t i = 0; i < rows_completed; ++i)
227                 {
228                         const uint32_t checksum = adler32(&g_table[i][0], ROW_LEN);
229                         fwrite(&checksum, sizeof(uint32_t), 1, file);
230                         fwrite(&g_table[i][0], sizeof(uint8_t), ROW_LEN, file);
231                 }
232                 if (ferror(file))
233                 {
234                         printf("ERROR: Failed to write table data!\n");
235                         success = false;
236                 }
237                 fclose(file);
238                 return success;
239         }
240         else
241         {
242                 printf("ERROR: Failed to open table file for writing!\n");
243                 return false;
244         }
245 }
246
247 static bool load_table_data(const wchar_t *const filename, size_t *const rows_completed_out)
248 {
249         FILE *const file = _wfopen(filename, L"rb");
250         if (file)
251         {
252                 bool success = true;
253                 uint64_t magic_number;
254                 uint32_t hash_len, distance_min, rows_completed;
255                 fread(&magic_number, sizeof(uint64_t), 1, file);
256                 fread(&hash_len, sizeof(uint32_t), 1, file);
257                 fread(&distance_min, sizeof(uint32_t), 1, file);
258                 fread(&rows_completed, sizeof(uint32_t), 1, file);
259                 if (ferror(file) || feof(file))
260                 {
261                         printf("ERROR: Failed to read the table header!\n");
262                         success = false;
263                         goto failed;
264                 }
265                 if (magic_number != MAGIC_NUMBER)
266                 {
267                         printf("ERROR: Table file format could not be recognized!\n");
268                         success = false;
269                         goto failed;
270                 }
271                 if ((hash_len != HASH_LEN) || (distance_min != DISTANCE_MIN) || (rows_completed > ROW_NUM))
272                 {
273                         printf("ERROR: Table properties are incompatibe with this instance!\n");
274                         success = false;
275                         goto failed;
276                 }
277                 for (size_t i = 0; i < rows_completed; ++i)
278                 {
279                         uint32_t checksum_expected;
280                         if ((fread(&checksum_expected, sizeof(uint32_t), 1, file) != 1) || (fread(&g_table[i][0], sizeof(uint8_t), ROW_LEN, file) != ROW_LEN))
281                         {
282                                 printf("ERROR: Failed to read table data from file!\n");
283                                 success = false;
284                                 goto failed;
285                         }
286                         if (adler32(&g_table[i][0], ROW_LEN) != checksum_expected)
287                         {
288                                 printf("ERROR: Table checksum does *not* match table contents!\n");
289                                 success = false;
290                                 goto failed;
291                         }
292                         if (check_permutation(i, &g_table[i][0]) != 0)
293                         {
294                                 printf("ERROR: Table distance verification has failed!\n");
295                                 success = false;
296                                 goto failed;
297                         }
298                 }
299         failed:
300                 fclose(file);
301                 if (success && rows_completed_out)
302                 {
303                         *rows_completed_out = (size_t)rows_completed;
304                 }
305                 return success;
306         }
307         else
308         {
309                 printf("ERROR: Failed to open table file for reading!\n");
310                 return false;
311         }
312 }
313 //-----------------------------------------------------------------------------
314 // MAIN
315 //-----------------------------------------------------------------------------
316
317 int wmain(int argc, wchar_t *argv[])
318 {
319         FILE *file_out = NULL;
320         size_t initial_row_index = 0;
321         char time_string[64];
322
323         printf("MHash GenTableMIX [%s]\n\n", __DATE__);
324         printf("HashLen: %d, Distance Min: %d\n\n", HASH_LEN, DISTANCE_MIN);
325
326         if ((HASH_LEN % (8 * sizeof(uint32_t))) != 0)
327         {
328                 crit_exit("FATAL: Hash length must be a multiple of 32 bits!");
329         }
330
331         if (argc < 2)
332         {
333                 printf("Table file not specified!\n\n");
334                 printf("Usage:\n");
335                 printf("   GenTables_MIX.exe <table_file>\n\n");
336                 return 1;
337         }
338
339         twister_t rand;
340         rand_init(&rand, make_seed());
341
342         bxmller_t bxmller;
343         gaussian_noise_init(&bxmller);
344
345         if (_waccess(argv[1], 4) == 0)
346         {
347                 printf("Loading existing table data and proceeding...\n");
348                 if (!load_table_data(argv[1], &initial_row_index))
349                 {
350                         return 1;
351                 }
352         }
353
354         for (size_t i = initial_row_index; i < ROW_NUM; ++i)
355         {
356                 printf("Row %03u of %03u [%c]", (uint32_t)(i + 1U), ROW_NUM, SPINNER[g_spinpos]);
357                 uint8_t counter = 0U;
358                 time_t ref_time = time(NULL);
359                 uint8_t temp[ROW_LEN];
360                 for (;;)
361                 {
362                         random_permutation(&rand, &g_table[i][0]);
363                         uint32_t error = check_permutation(i, &g_table[i][0]);
364                         printf("\b\b\b[%c]", '!');
365                         for (uint32_t rand_init = 0U; rand_init < 99991U; ++rand_init)
366                         {
367                                 random_permutation(&rand, &temp[0]);
368                                 const uint32_t error_next = check_permutation(i, &temp[0]);
369                                 if (error_next < error)
370                                 {
371                                         memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
372                                         if (!((error = error_next) > 0U))
373                                         {
374                                                 goto success;
375                                         }
376                                 }
377                         }
378                         if (error > 0U)
379                         {
380                                 for (size_t retry = 0U; retry < 9973U; ++retry)
381                                 {
382                                         bool improved = false;
383                                         for (uint32_t rotate = 0U; rotate < ROW_LEN; ++rotate)
384                                         {
385                                                 rotate_row(&g_table[i][0]);
386                                                 const uint32_t error_next = check_permutation(i, &g_table[i][0]);
387                                                 if (error_next < error)
388                                                 {
389                                                         improved = true;
390                                                         if (!((error = error_next) > 0U))
391                                                         {
392                                                                 goto success;
393                                                         }
394                                                         break;
395                                                 }
396                                                 reverse_row(&g_table[i][0]);
397                                                 const uint32_t error_next_rev = check_permutation(i, &g_table[i][0]);
398                                                 if (error_next_rev >= error)
399                                                 {
400                                                         reverse_row(&g_table[i][0]); /*revert*/
401                                                 }
402                                                 else
403                                                 {
404                                                         improved = true;
405                                                         if (!((error = error_next_rev) > 0U))
406                                                         {
407                                                                 goto success;
408                                                         }
409                                                         break;
410                                                 }
411                                         }
412                                         for (uint32_t swap_x = 0; swap_x < ROW_LEN; ++swap_x)
413                                         {
414                                                 for (uint32_t swap_y = swap_x + 1U; swap_y < ROW_LEN; ++swap_y)
415                                                 {
416                                                         swap(&g_table[i][0], swap_x, swap_y);
417                                                         const uint32_t error_next = check_permutation(i, &g_table[i][0]);
418                                                         if (error_next >= error)
419                                                         {
420                                                                 swap(&g_table[i][0], swap_x, swap_y); /*revert*/
421                                                         }
422                                                         else
423                                                         {
424                                                                 improved = true;
425                                                                 if (!((error = error_next) > 0U))
426                                                                 {
427                                                                         goto success;
428                                                                 }
429                                                         }
430                                                 }
431                                         }
432                                         for (uint32_t loop = 0; loop < 99991U; ++loop)
433                                         {
434                                                 const uint32_t swap_count = gaussian_noise_next(&rand, &bxmller, 8.0, 2U, (ROW_LEN / 2U));
435                                                 if (!(++counter))
436                                                 {
437                                                         const time_t curr_time = time(NULL);
438                                                         if (curr_time - ref_time >= 180i64)
439                                                         {
440                                                                 ref_time = curr_time;
441                                                                 rand_init(&rand, make_seed());
442                                                                 printf("\b\b\b[%c]", '$');
443                                                         }
444                                                         else
445                                                         {
446                                                                 printf("\b\b\b[%c]", SPINNER[g_spinpos]);
447                                                                 g_spinpos = (g_spinpos + 1) % 4;
448                                                         }
449                                                 }
450                                                 for (uint32_t round = 0; round < 97U; ++round)
451                                                 {
452                                                         memcpy(&temp[0], &g_table[i][0], sizeof(uint8_t) * ROW_LEN);
453                                                         swap_multiple_random(&rand, &temp[0], swap_count);
454                                                         const uint32_t error_next = check_permutation(i, &temp[0]);
455                                                         if (error_next < error)
456                                                         {
457                                                                 memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
458                                                                 improved = true;
459                                                                 if (!((error = error_next) > 0U))
460                                                                 {
461                                                                         goto success;
462                                                                 }
463                                                         }
464                                                 }
465                                         }
466                                         if (!improved)
467                                         {
468                                                 break; /*early termination*/
469                                         }
470                                 }
471                         }
472                         else
473                         {
474                                 break; /*success*/
475                         }
476                 }
477
478         success:
479                 get_time_str(time_string, 64);
480                 printf("\b\b\b[#] - %s\n", time_string);
481
482                 if (!save_table_data(argv[1], i + 1U))
483                 {
484                         return 1; /*failed to save current table data*/
485                 }
486         }
487
488         printf("\n-----\n\n");
489
490         dump_table(stdout);
491         if (fopen_s(&file_out, "table_MIX." DISTANCE_STR ".txt", "w") == 0)
492         {
493                 dump_table(file_out);
494                 fclose(file_out);
495         }
496
497         printf("\n-----\n\n");
498
499         printf("COMPLETED.\n\n");
500         return getchar();
501 }