/*
  fortuna_accumulator.c
  Fortuna cryptographic PRNG
  As seen in Ferguson and Schneier "Practical Cryptography"
  Greg Parker     gparker@cs.stanford.edu     2003-11-16
*/
/**********
 * Copyright (c) 2003-2004 Greg Parker.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GREG PARKER ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **********/

#include "includes.h"
#include "assert.h"
#include "fortuna.h"
#include "fortuna_locl.h"


typedef struct fortuna_t {
    generator_t gen;
    accumulator_t acc;
    uint32_t reseedCount;
    uint32_t lastReseedInTicks;
    uint32_t minReseedDelayInTicks;
} fortuna_t;


fortuna_t *fortuna_create(void)
{
    fortuna_t *f;
    assert(AES_BLOCK_SIZE * 2 == SHA256_DIGEST_LENGTH);
    
    f = nonarena_malloc(sizeof(fortuna_t));
    if (!f) return NULL;

    generator_init(&f->gen);
    accumulator_init(&f->acc);

    f->reseedCount = 0;
    f->lastReseedInTicks = 0;
    f->minReseedDelayInTicks = SysTicksPerSecond() / 10; // approx 0.1 sec

    return f;
}

void fortuna_get_bytes(fortuna_t *f, uint8_t *outBytes, unsigned int byteCount)
{
    int reseeded = 0;
    fortuna_log("fortuna: fortuna_get_bytes");

    // Reseed periodically:
    // * always reseed for the first readout
    // * otherwise, reseed only if pool[0] has enough data 
    //   and never more often than 0.1 seconds.
    if (f->reseedCount == 0  ||  
        (accumulator_pool_is_useful(&f->acc, 0)  &&  
         TimGetTicks() >= f->lastReseedInTicks + f->minReseedDelayInTicks)) 
    {
        uint8_t newseed[POOL_COUNT * KEY_BYTES];
        uint8_t *dst = newseed;
        uint8_t i;
        uint32_t mask;
        f->reseedCount++;

        // Include pool i every 2^i reseeds
        // Include pool i if (mask & reseedCount) == 0
        // First reseed (reseedCount == 1) uses only pool 0.
        // Pool 0 is included every reseed.
        mask = 0;
        for (i = 0; i < POOL_COUNT; i++) {
            if ((f->reseedCount & mask) != 0) break;
            fortuna_log("fortuna: extracting pool %d", i);
            accumulator_extract_pool(&f->acc, i, dst);
            dst += KEY_BYTES;
            mask = (mask << 1) | 1;
        }

        // Bytes [newseed..dst) are ready to be fed into the generator
        fortuna_log("fortuna: reseeding");
        generator_reseed(&f->gen, newseed, dst - newseed);
        reseeded = 1;
    }

    fortuna_log("fortuna: generating %d bytes (r %d)", byteCount, reseeded);
    generator_emit_bytes(&f->gen, outBytes, byteCount);
    fortuna_log("fortuna: get_bytes done");
}


void fortuna_put_bytes(fortuna_t *f, uint8_t sourceID, uint8_t poolID, uint8_t *inBytes, unsigned int byteCount)
{
    accumulator_add_bytes(&f->acc, sourceID, poolID, inBytes, byteCount);
}
