/*
 * Copyright (C) 2021 - 2026, Stephan Mueller <smueller@chronox.de>
 *
 * License: see LICENSE file in root directory
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
 * WHICH ARE HEREBY 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 NOT ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#ifndef JITTERENTROPY_SHA3_H
#define JITTERENTROPY_SHA3_H

#include "jitterentropy-internal.h"

#ifdef __cplusplus
extern "C"
{
#endif

#define JENT_SHA3_SIZE_BLOCK(bits)	((1600 - 2 * bits) >> 3)

#define JENT_SHA3_256_SIZE_BLOCK                                               \
	JENT_SHA3_SIZE_BLOCK(JENT_SHA3_256_SIZE_DIGEST_BITS)

#define JENT_XDRBG_SIZE_STATE		64

struct jent_sha_ctx {
	uint64_t state[25];
	uint8_t partial[JENT_SHA3_256_SIZE_BLOCK];
	size_t msg_len;
	uint8_t r;
	uint8_t rword;
	/*
	 * This implementation only supports up to rate-size digests for XOFs,
	 * thus the data type can be appropriately small.
	 */
	uint8_t digestsize;
	uint8_t padding;
	uint8_t initially_seeded:1;
};

#define JENT_SHA_MAX_CTX_SIZE	(sizeof(struct jent_sha_ctx))
#define HASH_CTX_ON_STACK(name)						       \
	struct jent_sha_ctx name

static inline unsigned int jent_sha3_rate(void *hash_state)
{
	struct jent_sha_ctx *ctx = hash_state;

	return ctx->r;
}

void jent_sha3_256_init(struct jent_sha_ctx *ctx);
void jent_sha3_update(struct jent_sha_ctx *ctx, const uint8_t *in,
		      size_t inlen);
void jent_sha3_final(struct jent_sha_ctx *ctx, uint8_t *digest);
int jent_sha3_alloc(void **hash_state);
void jent_sha3_dealloc(void *hash_state);
int jent_sha3_tester(void);

void jent_shake256_init(struct jent_sha_ctx *ctx);
static inline void jent_shake256_set_digestsize(struct jent_sha_ctx *ctx,
						unsigned int digestsize)
{
	ctx->digestsize = (uint8_t)digestsize;
}
void jent_drbg_generate_block(struct jent_sha_ctx *ctx, uint8_t *dst,
			      size_t dst_len);

#ifdef __cplusplus
}
#endif

#endif /* JITTERENTROPY_SHA3_H */
