folly/folly/crypto/LtHash.h

/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <cstddef>
#include <memory>
#include <vector>

#include <folly/Optional.h>
#include <folly/Range.h>
#include <folly/crypto/Blake2xb.h>
#include <folly/io/IOBuf.h>

namespace folly {
namespace crypto {

namespace detail {
/**
 * Allocates an IOBuf of the given size, aligned on a cache line boundary.
 * Similar to folly::IOBuf::create(), the returned IOBuf has an initial
 * capacity == size and an initial length == 0.
 */
folly::IOBuf allocateCacheAlignedIOBuf(size_t size);

/**
 * Similar to allocateCacheAlignedIOBuf(), but returns a unique_ptr to an IOBuf
 * instead of an IOBuf.
 */
std::unique_ptr<folly::IOBuf> allocateCacheAlignedIOBufUnique(size_t size);

/**
 * Returns true if the given memory address is aligned on a cache line boundary
 * and false if it isn't.
 */
bool isCacheAlignedAddress(const void* addr);

} // namespace detail

/**
 * Templated homomorphic hash, using LtHash (lattice-based crypto).
 * Template parameters: B = element size in bits, N = number of elements.
 *
 * Current constraints (checked at compile time with static asserts):
 * (1) B must be 16, 20 or 32.
 * (2) N must be > 999.
 * (3) when B is 16, N must be divisible by 32.
 * (4) when B is 20, N must be divisible by 24.
 * (5) when B is 32, N must be divisible by 16.
 */
template <std::size_t B, std::size_t N>
class LtHash {};

} // namespace crypto
} // namespace folly

#include <folly/crypto/LtHash-inl.h>

namespace folly {
namespace crypto {

// This is the fastest and smallest specialization and should be
// preferred in most cases. It provides over 200 bits of security
// which should be good enough for most cases.
LtHash16_1024;

// These specializations are available to users who want a higher
// level of cryptographic security. They are slower and larger than
// the one above.
LtHash20_1008;
LtHash32_1024;

} // namespace crypto
} // namespace folly