gestumblinde

Gestumblinde - reference implementation of SLH-DSA
git clone git://www.tkruger.se/gestumblinde.git
Log | Files | Refs | README

utils.c (1989B)


      1 #include "utils.h"
      2 
      3 int read_array(uint8_t **data, size_t *ndata, const json_t *array) {
      4   size_t n = json_array_size(array);
      5   uint8_t *res = malloc(n);
      6 
      7   size_t i;
      8   for (i = 0; i < n; i++) {
      9     json_int_t a = json_integer_value(json_array_get(array, i));
     10     if (a > 0xff) {
     11       free(res);
     12       return -1;
     13     }
     14 
     15     assert(a < 256);
     16     res[i] = (uint8_t)a;
     17   }
     18 
     19   *data = res;
     20   *ndata = n;
     21 
     22   return 0;
     23 }
     24 
     25 int read_key_array(void *data, const size_t ndata, const char *key,
     26                    json_t *tv) {
     27   json_t *json_get = json_object_get(tv, key);
     28   if (json_get == NULL) {
     29     return -1;
     30   }
     31 
     32   uint8_t *dd;
     33   size_t ndd;
     34 
     35   if (read_array(&dd, &ndd, json_get)) {
     36     return -2;
     37   }
     38 
     39   if (ndata < ndd) {
     40     free(dd);
     41     return -3;
     42   }
     43 
     44   memcpy(data, dd, ndd);
     45 
     46   if (ndata > ndd) {
     47     memset((char *)data + ndd, 0, ndata - ndd);
     48   }
     49 
     50   free(dd);
     51 
     52   return 0;
     53 }
     54 
     55 int read_key_aoa(void *data, const size_t ndata, const char *key, json_t *tv) {
     56   json_t *json_get = json_object_get(tv, key);
     57   if (json_get == NULL) {
     58     return -1;
     59   }
     60 
     61   uint8_t *cdata = data;
     62 
     63   size_t n = json_array_size(json_get);
     64 
     65   uint8_t *ap;
     66   size_t nap;
     67 
     68   size_t i;
     69   for (i = 0; i < n; i++) {
     70     json_t *a = json_array_get(json_get, i);
     71 
     72     if (read_array(&ap, &nap, a) != 0) {
     73       fprintf(stderr, "JSON read_array error.");
     74       exit(1);
     75     }
     76 
     77     memcpy(cdata, ap, nap); // buffer of:able!
     78     cdata += nap;
     79     free(ap);
     80   }
     81 
     82   return 0;
     83 }
     84 
     85 uint64_t read_key_uint64(const char *key, const json_t *tv) {
     86   json_t *json_get = json_object_get(tv, key);
     87   assert(json_get != NULL); // crash and burn
     88 
     89   return ((uint64_t)json_integer_value(json_get));
     90 }
     91 
     92 // TODO: allow for big numbers as idx_tree
     93 idx_tree_t read_key_idx_tree(const char *key, const json_t *tv) {
     94   json_t *json_get = json_object_get(tv, key);
     95   assert(json_get != NULL); // crash and burn
     96 
     97   idx_tree_t r;
     98   r.valhb = 0; // max 2^64 address in test vectors
     99   r.vallb = json_integer_value(json_get);
    100 
    101   return r;
    102 }