Containers

The containers/ directory provides vector-like container abstractions used to store plaintext and secret-shared values within cdough.

Contents:

  • a_shared_vector.h – Arithmetic shared vector container.

  • b_shared_vector.h – Boolean shared vector container.

  • class_access_vector.h – Vector base providing element-wise operator overloads.

  • e_vector.h – Vector-of-vector wrapper for replicated sharing schemes.

  • encoded_vector.h – Generic encoded vector implementation.

  • encoding.h – Encoding trait helpers.

  • gf2e_overloads.h – Placeholder NTL::GF2E operator overloads (assert if called).

  • mapped_iterator.h – Iterator adaptor for custom containers.

  • dummy_vector.h – Dummy vector for tests and benchmarks.

  • mapping_access_vector.h – Mapping access vector implementation.

  • permutation.h – Container for local and secret-shared permutations.

  • shared_vector.h – Abstract (untyped) secret-shared vector implementation.

  • vector.h – Convenience alias to the default vector type.

  • matrix/ – Plaintext and secure matrix containers.

  • tabular/ - Encoded Table and Column classes.

template<typename T>
class Vector

cdough’s wrapper of std::vector<T> that provides vectorized plaintext operations. A mock vector implementation which stores no data and returns nothing (or garbage) for all operations. Most functions do nothing at all, or just compute the appropriate length that their correct equivalent would output. This is useful for testing and profiling, since it is extremely fast and performs no data movement.

Template Parameters:
  • T – The type of elements in the Vector (e.g., int, long, long long, etc.)

  • T – The nominal element type

Public Types

using value_type = T
using value_type = T
using IteratorType = MappedIterator<T, typename std::vector<T>::iterator, typename std::vector<VectorSizeType>::iterator>
using value_type = T
using IteratorType = MappedIterator<T, typename std::vector<T>::iterator, typename std::vector<VectorSizeType>::iterator>

Public Functions

inline void setPrecision(const int fixed_point_precision)

Sets the fixed-point precision.

Parameters:

fixed_point_precision – - the number of fixed-point fractional bits.

inline size_t getPrecision() const

Gets the fixed-point precision.

inline void matchPrecision(const Vector<T> &other)

Helper that sets this vector’s precision to match another Vector.

Parameters:

other – The Vector whose precision should be copied.

inline size_t total_size() const
Returns:

The total number of elements in the vector.

inline std::vector<T>::iterator begin()

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the first element.

inline std::vector<T>::iterator end()

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the last element.

inline Vector simple_subset_reference(const int _start_index, const int _step, const int _end_index) const

             This is the generic function in order create a new mapping for this vector.
             Note: that the function does not allocate a new memory location for data.
             Note: the mapping maps from the new index space to the original index space for
data. In other words, composition will not work; new mapping pattern replaces the previous one.

Parameters:
  • _subset_offset – the index of the first element of the original vector to apply the pattern.

  • _subset_step – the index difference between the mapped to elements within each chunks.

  • _subset_included_size – the maximum size of each included chunk.

  • _subset_excluded_size – the maximum size of each excluded chunk. (included and excluded chunks alternate after offset).

  • _subset_direction – the direction of choosing elements (increasing index = 1) (decreasing index = -1).

  • _subset_repetition – number of times to repeat same mapped-to-elements after each other.

  • _subset_cycles – number of times concatenate the whole mapped-to-elements in the new reference.

  • _subset_offset – the index of the first element of the original vector to apply the pattern. (default = 0)

  • _subset_step – the index of the difference between each two included elements. (default = 1)

  • _subset_included_size – the size of the elements on which the pattern is applied. (default = total_size())

Returns:

Vector that points to the same memory location as the new one but different mapping for the indices. Remaps the index space to choose a number of elements of the current vector. Note: returned Vector points to the same memory location.

Returns:

Vector that has different index mapping to the original vector elements.

inline Vector simple_subset_reference(const int _start_index, const int _step) const
inline Vector simple_subset_reference(const int _start_index) const
inline Vector alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const

Applies an alternating pattern to include and exclude elements. It applies the pattern starting with the element with index = _subset_offset. It then keeps alternating elements as included in the pattern of or excluded from the pattern using the _subset_included_size and the _subset_excluded_size for each included or excluded chunk.

Parameters:
  • _subset_offset – the index of the first element to apply the pattern.

  • _subset_step – the difference two each two included elements within the included the chunks.

  • _subset_included_size – the size of a number of elements that we choosing from.

  • _subset_excluded_size – the size of a number of elements that we are totally not choosing.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector reversed_alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
inline Vector repeated_subset_reference(const size_t _subset_repetition) const

Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.

Parameters:

_subset_repetition – the number of times each element is repeated.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector cyclic_subset_reference(const size_t _subset_cycles) const

Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.

Parameters:

_subset_cycles – the number of cycles the new indexing mapping will contain.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector directed_subset_reference(const size_t _subset_direction) const

Applies a new mapping indexing that controls the order in which the elements accessed.

Parameters:

_subset_direction – set to (1) to keep current order or (-1) to reverse the order.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector simple_bit_compress(size_t start, size_t step, size_t end, size_t repetition) const

This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.

Parameters:
  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline void simple_bit_compress(Vector &res, size_t position) const

simple_bit_compress, optimized for the (i, 1, i, 1) case. This version further operates on a passed vector, rather than returning a new Vector.

Parameters:
  • res – vector to compress into

  • position – single bit position to compress (= start = end)

inline void simple_bit_decompress(const Vector &other, size_t start, size_t step, size_t end, size_t repetition)

Function to reverse the simple_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

inline void simple_bit_decompress(const Vector &other, const T &position)

Optimized version of simple_bit_compress for the single- position case.

Note: in testing, setBitMask was not noticeably faster than setBitValue

Parameters:
  • other – vector to decompress into this

  • position – the bit position to decompress

inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const

This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that step index difference apart are chosen. If direction is set to 1, picking starts from lowest significant bits. If it is set to -1, picking starts from most significant bits.

Parameters:
  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first.

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size) const
inline void alternating_bit_decompress(const Vector &other, size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const

Function to reverse the alternating_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first.

inline Vector(size_t _size, T _init_val = 0)

             This constructor allows for creating a new vector by just passing initialization
             parameters for inner `data` variable.
             @tparam T is a generic type to allow for different constructors for the variable
data.

Parameters:
  • args – is the packed parameters passed to data initializer. Creates a Vector of size values initialize to init_val (0 by default).

  • size – The size of the new Vector.

inline Vector(std::vector<T> &&_other)

Move constructor

Parameters:

other – The std::vector<T> whose elements will be moved to the new Vector.

inline Vector(std::vector<T> &_other)

Copy constructor

Parameters:

other – The std::vector<T> whose elements will be copied to the new Vector.

inline Vector(std::initializer_list<T> &&elements)

Constructs a new Vector from a list of T elements.

Parameters:

elements – The list of elements of the new Vector.

inline Vector(const Vector &other)

This is a shallow copy constructor.

WARNING: The new vector will point to the same memory location used by

other. To copy the data into a separate memory location, create a new vector first then use assignment operator.

Parameters:

other – The vector that contains the std::vector<T> pointer to be copied.

inline Vector(std::shared_ptr<VectorDataBase<T>> other)
inline Vector &operator=(const Vector &&other)

This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the other vector to the this vector. Assumes other

has the same size as this vector.

NOTE: This method works relatively to the current batch.

Parameters:

other – The Vector that contains the values to be assigned to this vector.

Returns:

A reference to this vector after modification.

inline Vector &operator=(const Vector &other)

This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the other vector to this vector. Assumes other has the same size as this vector.

Parameters:

other – the Vector that contains the values to be copied.

Returns:

A reference to this Vector after modification.

template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other)

Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.

inline Vector simple_subset(size_t start, size_t size) const

Returns a new vector that contains all elements in the range [start, end].

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • end – The index of the last element to be included in the output vector.

Returns:

A new vector that contains the selected elements.

inline void mask(const T &n)

Masks each element in this vector by doing a bitwise logical AND with n.

Parameters:

n – The mask.

inline void zero()

Sets every element of this vector to zero.

inline Vector bit_level_shift(int log_level_size) const

Creates a new Vector whose i-th element is generated by:

  1. splitting the bit representation of the i-th element of this Vector into parts of size level_size, and

  2. setting all bits of the least significant half of each part equal to the LSB of the most significant part.

NOTE: This method is used in secure greater-than and works relatively to the current batch.

Moved from private so we can test this method externally.

Parameters:

log_level_size – log2 of the maximum chunk size (indexes into LEVEL_MASKS)

Returns:

A new vector that contains elements generated as described above.

inline size_t size() const

NOTE: This method works relatively to the current batch.

Returns:

The number of elements in the vector.

inline Vector operator+(const Vector &y) const

Elementwise plaintext addition.

inline Vector operator-(const Vector &y) const

Elementwise plaintext subtraction.

inline Vector operator*(const Vector &y) const

Elementwise plaintext multiplication.

inline Vector operator/(const Vector &y) const

Elementwise plaintext division.

inline Vector operator-() const

Elementwise plaintext negation.

inline Vector operator&(const Vector &y) const

Elementwise plaintext bitwise AND.

inline Vector operator|(const Vector &y) const

Elementwise plaintext bitwise OR.

inline Vector operator^(const Vector &y) const

Elementwise plaintext bitwise XOR.

inline Vector operator~() const

Elementwise plaintext boolean complement.

inline Vector operator!() const

Elementwise plaintext boolean negation.

inline Vector operator==(const Vector &y) const

Elementwise plaintext equality comparison.

inline Vector operator!=(const Vector &y) const

Elementwise plaintext inequality comparison.

inline Vector operator>(const Vector &y) const

Elementwise plaintext greater-than comparison.

inline Vector operator>=(const Vector &y) const

Elementwise plaintext greater-or-equal comparison.

inline Vector operator<(const Vector &y) const

Elementwise plaintext less-than comparison.

inline Vector operator<=(const Vector &y) const

Elementwise plaintext less-or-equal comparison.

template<typename OtherType>
inline Vector operator+(const OtherType &other) const
template<typename OtherType>
inline Vector operator-(const OtherType &other) const
template<typename OtherType>
inline Vector operator*(const OtherType &other) const
template<typename OtherType>
inline Vector operator/(const OtherType &other) const
template<typename OtherType>
inline Vector operator%(const OtherType &other) const
template<typename OtherType>
inline Vector operator&(const OtherType &other) const
template<typename OtherType>
inline Vector operator|(const OtherType &other) const
template<typename OtherType>
inline Vector operator^(const OtherType &other) const
template<typename OtherType>
inline Vector operator>>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<<(const OtherType &other) const
template<typename OtherType>
inline Vector operator>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<(const OtherType &other) const
template<typename OtherType>
inline Vector operator==(const OtherType &other) const
template<typename OtherType>
inline Vector operator!=(const OtherType &other) const
template<typename OtherType>
inline Vector operator+=(const OtherType &other)
template<typename OtherType>
inline Vector operator-=(const OtherType &other)
template<typename OtherType>
inline Vector operator*=(const OtherType &other)
template<typename OtherType>
inline Vector operator&=(const OtherType &other)
template<typename OtherType>
inline Vector operator|=(const OtherType &other)
template<typename OtherType>
inline Vector operator^=(const OtherType &other)
inline Vector ltz() const

Elementwise plaintext less-than-zero comparison.

inline Vector extend_lsb() const

Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.

inline Vector extract_valid(Vector valid)
inline T &operator[](int index)

Returns a mutable reference to the element at the given index

.

NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

A mutable reference to the element at the given index.

inline const T &operator[](int index) const

Returns an immutable reference of the element at the given index

.

NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

Returns a read-only reference of the element at the given index.

inline bool same_as(const Vector<T> &other) const

             Unpacks bits in the elements of `this` vector to create a new vector of size `n`
whose i-th element equals the (i/n)-th bit of the (in)-th element of this vector.

Parameters:
  • n – The number of bits to ‘unpack’.

  • other – The vector to compare this with.

Returns:

A new Vector that contains n single-bit elements constructed as described above. Checks if the two input vectors (this and other) contain the same elements.

Returns:

True if this vector contains the same elements with other, False otherwise.

inline bool starts_with(const Vector<T> &prefix)

Checks if the vector prefix is a prefix of this vector.

Parameters:

prefix

Returns:

true if the argument is a prefix

Returns:

false otherwise

inline void setPrecision(const int fixed_point_precision)
inline size_t getPrecision() const
inline Vector(std::shared_ptr<std::vector<T>> _data, std::shared_ptr<std::vector<VectorSizeType>> _mapping = nullptr)

Empty constructor

inline Vector(std::vector<T> &&_other)

Move constructor

Parameters:

_other

inline Vector(std::vector<T> &_other)

Copy constructor from vector

Parameters:

_other

inline Vector(VectorSizeType _size, T _init_val = {})

Creates a Vector of size values initialize to init_val (0 by default).

Parameters:
  • _size – The size of the new Vector.

  • _init_val

inline Vector(std::initializer_list<T> &&elements)

Constructs a new Vector from a list of T elements.

Parameters:

elements – The list of elements of the new Vector.

template<std::floating_point FP>
inline Vector(const std::vector<FP> &_other, int fixed_point_precision = 16)

Constructor that converts a vector of floating-point numbers to a vector of integers.

Template Parameters:

FP – - The floating-point type to convert from.

Parameters:
  • _other – - The vector of floating-point numbers to convert.

  • fixed_point_precision – - The number of fractional bits to use for the fixed-point conversion. Default is 16.

template<std::ranges::input_range IR>
inline Vector(IR _other)

Copy constructor from range

Parameters:

_other – The input_range whose elements will be copied to the new Vector.

inline Vector(const Vector &other)
inline Vector(Vector &other)
inline Vector bit_arithmetic_right_shift(int shift_size) const
inline Vector bit_logical_right_shift(int shift_size) const
inline Vector bit_left_shift(int shift_size) const
inline Vector bit_xor() const
inline void prefix_sum()
inline void prefix_sum(const T &(*op)(const T&, const T&))
inline Vector chunkedSum(const VectorSizeType aggSize = 0) const
inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &end) const
inline void reset_batch()
inline void set_batch(const VectorSizeType &_start_ind, const VectorSizeType &_end_ind)
inline VectorSizeType total_size() const
inline IteratorType begin() const
inline IteratorType end() const
inline std::vector<T> as_std_vector() const

Return an empty C++ vector of the given length.

Returns:

std::vector<T>

inline std::vector<T> _get_internal_data() const

Return an empty C++ vector of the given length.

Returns:

std::vector<T>

inline std::span<T> span()

Return an empty span.

Returns:

std::span<T>

inline std::span<T> batch_span()
inline std::span<const T> batch_span() const
inline bool has_mapping() const
inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step, const VectorSizeType _end_index) const

Return a dummy vector of the correct size.

Parameters:
  • _start_index

  • _step

  • _end_index

Returns:

Vector

inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step) const
inline Vector simple_subset_reference(const VectorSizeType _start_index) const
inline Vector slice(const size_t start, const size_t end) const
inline Vector slice(const size_t start) const
inline Vector included_reference(const Vector flag) const

Return a bounded dummy vector. Since included_reference is data-dependent, we can’t provide a cardinality-accurate dummy version.

Parameters:

flag

Returns:

Vector

inline Vector alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const
inline Vector reversed_alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const
inline Vector repeated_subset_reference(const VectorSizeType _subset_repetition) const
inline Vector cyclic_subset_reference(const VectorSizeType _subset_cycles) const
inline Vector directed_subset_reference(const int _subset_direction) const
inline Vector simple_bit_compress(int start, int step, int end, int repetition) const
inline void pack_from(const Vector &source, int position)
inline void simple_bit_decompress(const Vector &other, int start, int step, int end, int repetition)
inline void unpack_from(const Vector &source, const T &position)
inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction) const
inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size) const
inline void alternating_bit_decompress(const Vector &other, const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction) const
inline Vector<T> materialize() const

Dummy vectors have no mapping, so just return this vector.

Returns:

Vector<T>

inline void materialize_inplace()
inline Vector mapping_reference(std::vector<VectorSizeType> map) const

Respect the size of the mapping reference.

Parameters:

map

Returns:

Vector

template<typename S>
inline Vector mapping_reference(std::vector<S> map) const
template<typename S>
inline Vector mapping_reference(Vector<S> map) const
template<typename S = VectorSizeType>
inline void apply_mapping(std::vector<S> new_mapping)

To apply a mapping for a dummy vector, we only update the length.

Template Parameters:

S

Parameters:

new_mapping

inline void reverse()
inline Vector &operator=(const Vector &&other)
inline Vector &operator=(const Vector &other)
template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other)
inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &size) const
inline void mask(const T &n)
inline void zero()
inline Vector bit_level_shift(int log_level_size) const
inline Vector reverse_bit_level_shift(int log_level_size) const
inline VectorSizeType size() const
inline void resize(size_t n)
inline void tail(size_t n)
inline void concatenate(const Vector &other)
inline Vector operator+(const Vector &y) const
inline Vector operator-(const Vector &y) const
inline Vector operator*(const Vector &y) const
inline Vector operator/(const Vector &y) const
inline Vector operator-() const
inline Vector operator&(const Vector &y) const
inline Vector operator|(const Vector &y) const
inline Vector operator^(const Vector &y) const
inline Vector operator~() const
inline Vector operator!() const
inline Vector operator==(const Vector &y) const
inline Vector operator!=(const Vector &y) const
inline Vector operator>(const Vector &y) const
inline Vector operator>=(const Vector &y) const
inline Vector operator<(const Vector &y) const
inline Vector operator<=(const Vector &y) const
template<typename OtherType>
inline Vector operator+(const OtherType &other) const
template<typename OtherType>
inline Vector operator-(const OtherType &other) const
template<typename OtherType>
inline Vector operator*(const OtherType &other) const
template<typename OtherType>
inline Vector operator/(const OtherType &other) const
template<typename OtherType>
inline Vector operator%(const OtherType &other) const
template<typename OtherType>
inline Vector operator&(const OtherType &other) const
template<typename OtherType>
inline Vector operator|(const OtherType &other) const
template<typename OtherType>
inline Vector operator^(const OtherType &other) const
template<typename OtherType>
inline Vector operator>>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<<(const OtherType &other) const
template<typename OtherType>
inline Vector operator>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<(const OtherType &other) const
template<typename OtherType>
inline Vector operator==(const OtherType &other) const
template<typename OtherType>
inline Vector operator!=(const OtherType &other) const
template<typename OtherType>
inline Vector operator+=(const OtherType &other)
template<typename OtherType>
inline Vector operator-=(const OtherType &other)
template<typename OtherType>
inline Vector operator*=(const OtherType &other)
template<typename OtherType>
inline Vector operator/=(const OtherType &other)
template<typename OtherType>
inline Vector operator%=(const OtherType &other)
template<typename OtherType>
inline Vector operator&=(const OtherType &other)
template<typename OtherType>
inline Vector operator|=(const OtherType &other)
template<typename OtherType>
inline Vector operator^=(const OtherType &other)
inline Vector ltz() const
inline Vector extend_lsb() const
inline Vector extract_valid(Vector valid)
inline std::pair<Vector, Vector> divrem(const T d)
inline T &operator[](const VectorSizeType &index)
inline const T &operator[](const VectorSizeType &index) const
inline Vector dot_product(const Vector &other, const VectorSizeType aggSize = 0) const
inline bool same_as(const Vector<T> &other, bool print_warn = true) const

All dummy vectors are equal.

Parameters:
  • other

  • print_warn

Returns:

true Always returns true.

inline bool starts_with(const Vector<T> &prefix)

All dummy vectors are prefixes of each other. TODO: check size at least?

Parameters:

prefix

Returns:

true Always returns true.

inline Vector(std::shared_ptr<std::vector<T>> _data, std::shared_ptr<std::vector<VectorSizeType>> _mapping = nullptr)

Construct a vector pointing to specific data and mapping Mostly used internally

Default mapping is the identity (null pointer)

inline Vector(std::vector<T> &&_other)

Move constructor

Parameters:

_other – The std::vector<T> whose elements will be moved to the new Vector.

inline Vector(std::vector<T> &_other)

Copy constructor from vector

Parameters:

_other – The std::vector<T> whose elements will be copied to the new Vector.

inline explicit Vector(VectorSizeType _size, T _init_val = {})

Creates a Vector of size values initialize to init_val (0 by default).

Parameters:
  • _size – The size of the new Vector.

  • _init_val – default-initialized value

inline Vector(std::initializer_list<T> &&elements)

Constructs a new Vector from a list of T elements.

Parameters:

elements – The list of elements of the new Vector.

template<std::ranges::input_range IR>
inline Vector(IR _other)

Copy constructor from range

Parameters:

_other – The input_range whose elements will be copied to the new Vector.

inline Vector(const Vector &other)

This is a shallow copy constructor.

WARNING: The new vector will point to the same memory location used by

other. To copy the data into a separate memory location, create a new vector first then use assignment operator.

Parameters:

other – The vector that contains the std::vector<T> pointer to be copied.

inline Vector(Vector &other)

This is a shallow copy constructor.

WARNING: The new vector will point to the same memory location used by

other. To copy the data into a separate memory location, create a new vector first then use assignment operator.

Parameters:

other – The vector that contains the std::vector<T> pointer to be copied.

inline Vector construct_like() const

Creates a new Vector with the same structure as this Vector, but with newly allocated empty vectors of the same size.

Returns:

A new Vector with the same structure but empty contents.

inline Vector construct_like(const size_t &size) const

Creates a new Vector with the same structure as this Vector, but with newly allocated empty vectors of a different size.

Parameters:

size – The size of the new Vector.

Returns:

A new Vector with the same structure but empty contents.

template<std::floating_point FP>
inline Vector(const std::vector<FP> &_other, int fixed_point_precision = 16)

Constructor that converts a vector of floating-point numbers to a vector of integers.

Template Parameters:

FP – - The floating-point type to convert from.

Parameters:
  • _other – - The vector of floating-point numbers to convert.

  • fixed_point_size_the – number of fractional bits to use for the fixed-point conversion. Default is 16.

inline void setPrecision(const int fixed_point_precision)

Sets the fixed-point precision.

Parameters:

fixed_point_precision – - the number of fixed-point fractional bits.

inline size_t getPrecision() const

Gets the fixed-point precision.

inline Vector bit_arithmetic_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, use bit_logical_right_shift

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_logical_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, use bit_arithmetic_right_shift NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_left_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector left-shifted by shift_size

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to left-shift each element of this Vector.

Returns:

A new Vector that contains the left-shifted elements.

inline Vector bit_xor() const

Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of this Vector, 0 <= i < size()

. (Basically parity check of each element.)

NOTE: This method works relatively to the current batch.

Returns:

A new Vector that contains single-bit elements generated as described above.

inline void prefix_sum()

Compute a prefix sum of this vector. Operates in place; for immutable operation, first copy into a new vector.

inline void prefix_sum(const T &(*op)(const T&, const T&))

Arbitrary-operation prefix “sum”. Operation should be associative.

inline Vector chunkedSum(const VectorSizeType aggSize = 0) const

Sums each consecutive aggSize vector elements and returns a new vector containing the aggregated sums.

Parameters:

aggSize – The number of elements to aggregate in each sum.

Returns:

A new Vector that contains the aggregated sums.

inline Vector dot_product(const Vector &other, const VectorSizeType aggSize = 0) const

Computes the dot product of this vector with another vector, aggregating results in chunks of aggSize. Each aggSize consecutive elements contribute to an exactly on dot product element in the result. The size of the resulting vector is determined by the aggSize parameter.

Parameters:
  • other – The other vector to compute the dot product with.

  • aggSize – The number of elements to do dotproduct on for each result element.

Returns:

A new Vector containing the aggregated dot product results.

inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &end) const

Returns a new vector containing elements in the range [start, end] that are step

positions apart.

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • step – The distance between two consecutive elements.

  • end – The maximum possible index of the last element to be included in the output vector.

Returns:

A new vector that contains the selected elements.

inline void reset_batch()

Sets the current batch equal to the whole vector.

inline void set_batch(const VectorSizeType &_start_ind, const VectorSizeType &_end_ind)

Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.

Parameters:
  • _start_ind – The index of the first element in the current batch.

  • _end_ind – The index of the last element in the current batch.

inline VectorSizeType total_size() const
Returns:

The total number of elements in the vector.

inline IteratorType begin() const

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the first element.

inline IteratorType end() const

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the last element.

inline const T back() const
inline std::vector<T> as_std_vector() const

Return a new C++ vector with the same data. This is not a reference to the underlying storage.

Returns:

std::vector<T>

inline std::vector<T> _get_internal_data() const

Return the underlying storage of this Vector.

Returns:

std::vector<T>

inline std::span<T> span()

Return a span with a view of the underlying data.

Returns:

std::span<T>

inline std::span<T> batch_span()

Return an unmapped span to the current batch. Useful for protocols that need direct access to the underlying storage.

Returns:

std::span<T>

inline std::span<const T> batch_span() const

Const version of the above.

Returns:

std::span<const T>

inline bool has_mapping() const

Checks whether a mapping exists inside this Vector. Note that this function only checks for existence; thus, a vector with the trivial mapping would return true here.

Returns:

true if the Vector has a mapping

Returns:

false if it does not

inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step, const VectorSizeType _end_index) const

Remaps the vector to reference a subset of the original vector. Returned Vector points to the same underlying storage.

Note: end index is inclusive. To access a single element, use

simple_subset_reference(i, 1,

i)

.

Parameters:
  • _start_index

  • _step

  • _end_indexinclusive end index

Returns:

Vector

inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step) const

Simple subset reference with implicit end index (at the end of the Vector).

Parameters:
  • _start_index

  • _step

Returns:

Vector

inline Vector simple_subset_reference(const VectorSizeType _start_index) const

Simple subset reference with implicit step size (1) and end.

Parameters:

_start_index

Returns:

Vector

inline Vector slice(const size_t start, const size_t end) const

Take a slice of a vector. This is the same as simple_subset_reference, but the end index is EXCLUSIVE. It also only supports a step size of 1.

The resulting slice will have size end - start. slice expresses natural ranges, e.g., slice(x, x + s) represents the slice starting at x having size s.

  • slice(x) is equivalent to simple_subset_reference(x)

  • slice(x, y) is equivalent to simple_subset_reference(x, 1, y - 1)

Parameters:
  • start

  • endexclusive end index

Returns:

Vector

inline Vector slice(const size_t start) const

Take a slice with an implicit end index (at the end of the Vector).

Parameters:

start

Returns:

Vector

inline Vector included_reference(const Vector flag) const

Return a view of this vector with only the nonzero positions of flag included. For example, if the base vector is [ 1 2 3 4 5 6 ] and the flag vector is [ 0 0 1 1 0 1 ] then this access pattern returns [ 3 4 6 ].

If flag is shorter than this vector, assume all remaining flag values are zero.

NOTE: should we ever need to parallelize this operation, it can be implemented by

  • (parallel) prefix sum over flag vector

  • multiply prefix sum with original flag vector, placing -1 at all locations where flag=0 and the prefix sum value where flag=1

  • (parallel) copy from non-negative indices

I think this actually needs to be an exclusive_sum, not inclusive but this can also be implemented by seeding the prefix sum with -1.

Parameters:

flag

Returns:

Vector

inline Vector alternating_subset_reference(const VectorSizeType _subset_included_size, const VectorSizeType _subset_excluded_size) const

Applies an alternating pattern to include and exclude elements. Keep alternating elements as included in the pattern or excluded from the pattern using the _subset_included_size and the _subset_excluded_size for each included or excluded chunk.

Parameters:
  • _subset_included_size – the size of a number of elements that we choosing from.

  • _subset_excluded_size – the size of a number of elements that we are totally not choosing.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector alternating_subset_reference(const VectorSizeType subset_size) const
inline Vector reversed_alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const

The same as above, but counting from the end of the Vector.

Parameters:
  • _subset_included_size

  • _subset_excluded_size

Returns:

Vector

inline Vector repeated_subset_reference(const VectorSizeType _subset_repetition) const

Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.

Parameters:

_subset_repetition – the number of times each element is repeated.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector repeated_subset_reference(const VectorSizeType _elements_count, const VectorSizeType _subset_repetition) const

Applies a new indexing mapping to the current vector so that each subset of elements is repeated a number of times consecutively.

Parameters:
  • _elements_count – the number of elements in each subset.

  • _subset_repetition – the number of times each subset is repeated.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector cyclic_subset_reference(const VectorSizeType _subset_cycles) const

Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.

Parameters:

_subset_cycles – the number of cycles the new indexing mapping will contain.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector directed_subset_reference(const int _subset_direction) const

Applies a new mapping indexing that controls the order in which the elements accessed.

Parameters:

_subset_direction – set to (1) to keep current order or (-1) to reverse the order.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector simple_bit_compress(int start, int step, int end, int repetition) const

This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.

Parameters:
  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline void simple_bit_decompress(const Vector &other, int start, int step, int end, int repetition)

Function to reverse the simple_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

inline void extract_bit_from_vector(const Vector &source, const int &position)
inline void pack_from(const Vector &source, const int &position)

Extracts the bit at a given position from each element of the source Vector and stores it in this Vector

Parameters:
  • source – The Vector to take bits from

  • position – The bit position to take

inline void unpack_from(const Vector &source, const T &position)

The inverse of pack_from, takes a packed Vector and puts its bits at a position in this Vector. WARNING: Requires that batch_start be a multiple of the bit-length of a share ffor proper alignment.

Parameters:
  • source – The packed Vector to take bits from

  • position – The bit position to put the bits in

inline std::vector<Vector> bit_decomposition() const

This function decomposes each element of the current vector into its bits and appends them into k vectors, where k is the number of bits in the type T. Each of the output vectors contains the bits at a certain index from all elements in the input vector.

Returns:

a vector of k vectors, each containing the bits at a certain index.

inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction = 1) const

This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that step index difference apart are chosen. If direction is set to 1, picking starts from lowest significant bits. If it is set to -1, picking starts from most significant bits.

Parameters:
  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first. (default: 1, LSB first.)

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline void alternating_bit_decompress(const Vector &other, const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction = 1) const

Function to reverse the alternating_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first. (default: 1)

inline Vector<T> materialize() const

Materialize a vector which might have an access pattern applied. If there is no mapping, just return the vector. Otherwise, copy the mapped vector into a new vector (which will have no map).

Useful for communication primitives, which require unmapped vectors.

Returns:

Vector<T>

inline void materialize_inplace()

Materialize a Vector in place: construct a new Vector, copy the data over from this Vector into the new one, and reset the mapping. Externally, this function has no side effects, but may be necessary before communicating Vectors.

If this Vector does not have a mapping, it is already materialized, so we do nothing.

inline Vector mapping_reference(std::vector<VectorSizeType> map) const

Create a mapping reference, where the std::vector argument map will become the new map. Not allowed if a mapping is already applied.

Parameters:

map – std::vector specifying the new map

Returns:

Vector

template<typename S>
inline Vector mapping_reference(std::vector<S> map) const

Create a mapping reference with a std::vector<S> map, for arbitrary type S.

Template Parameters:

S

Parameters:

map

Returns:

Vector

template<typename S>
inline Vector mapping_reference(Vector<S> map) const

Create a mapping reference, where the Vector argument map will become the new map. Not allowed if a mapping is already applied.

Parameters:

map – cdough Vector specifying the new map

Returns:

Vector

template<typename S = VectorSizeType>
inline void apply_mapping(std::vector<S> new_mapping)

Compose mappings. Apply the new mapping on top of an existing mapping, should one exist.

Specifically, assume x is the underlying storage. Then let x1 be the vector with mapping m1 applied; x1[i] = x[m1[i]].

Applying map m2 with this function gives x2, such that x2[i] = x[m1[m2[i]]].

The new mapping specified must be the same size as, or smaller than, the old one (this function cannot expand a vector).

Template Parameters:

S

Parameters:

new_mapping

inline void reverse()

Use iterators to reverse this Vector in place.

inline Vector &operator=(const Vector &&other)

This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the other vector to the this vector. Assumes other

has the same size as this vector.

NOTE: This method works relatively to the current batch.

Parameters:

other – The Vector that contains the values to be assigned to this vector.

Returns:

A reference to this vector after modification.

inline Vector &operator=(const Vector &other)

This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the other vector to this vector. Assumes other has the same size as this vector.

Parameters:

other – the Vector that contains the values to be copied.

Returns:

A reference to this Vector after modification.

template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other)

Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.

inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &size) const

Returns a new vector that contains all elements in the range [start, start + size].

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • size – The number of elements to include

Returns:

A new vector that contains the selected elements.

inline void mask(const T &n)

Masks each element in this vector by doing a bitwise logical AND with n. TODO: factor out into common macro for other operations using define_binary_vector_element_assignment_op

Parameters:

n – The mask.

inline void zero()

Sets every element of this vector to zero. Don’t modify the mapping. (If a mapping is applied, only mapped values will be zero’d.)

NOTE: this method works relative to the current batch.

inline VectorSizeType size() const

NOTE: This method works relatively to the current batch.

Returns:

The number of elements in the vector.

inline void resize(size_t n)

Resize this vector.

  • If a mapping is applied, resize both the mapping and the underlying data. Point new indices to new storage.

  • If no mapping is applied, just resize the underlying data.

This method resets the current batch.

Parameters:

n

inline void tail(size_t n)

Resize this vector to its last \(n\) elements. If there is a mapping, erase all but the last \(n\) elements of the mapping. Otherwise, erase the underlying data. For the head of a Vector, just use resize.

Parameters:

n

inline void concatenate(const Vector &other)

Concatenate this vector with other by resizing this and placing other into the new positions.

Parameters:

other

inline Vector operator+(const Vector &y) const

Elementwise plaintext addition.

inline Vector operator-(const Vector &y) const

Elementwise plaintext subtraction.

inline Vector operator*(const Vector &y) const

Elementwise plaintext multiplication.

inline Vector operator/(const Vector &y) const

Elementwise plaintext division.

inline Vector operator-() const

Elementwise plaintext negation.

inline Vector operator&(const Vector &y) const

Elementwise plaintext bitwise AND.

inline Vector operator|(const Vector &y) const

Elementwise plaintext bitwise OR.

inline Vector operator^(const Vector &y) const

Elementwise plaintext bitwise XOR.

inline Vector operator~() const

Elementwise plaintext boolean complement.

inline Vector operator!() const

Elementwise plaintext boolean negation.

inline Vector operator==(const Vector &y) const

Elementwise plaintext equality comparison.

inline Vector operator!=(const Vector &y) const

Elementwise plaintext inequality comparison.

inline Vector operator>(const Vector &y) const

Elementwise plaintext greater-than comparison.

inline Vector operator>=(const Vector &y) const

Elementwise plaintext greater-or-equal comparison.

inline Vector operator<(const Vector &y) const

Elementwise plaintext less-than comparison.

inline Vector operator<=(const Vector &y) const

Elementwise plaintext less-or-equal comparison.

template<typename S>
inline Vector operator+(const S other) const
template<typename S>
inline Vector operator-(const S other) const
template<typename S>
inline Vector operator*(const S other) const
template<typename S>
inline Vector operator/(const S other) const
template<typename S>
inline Vector operator%(const S other) const
template<typename S>
inline Vector operator&(const S other) const
template<typename S>
inline Vector operator|(const S other) const
template<typename S>
inline Vector operator^(const S other) const
template<typename S>
inline Vector operator>>(const S other) const
template<typename S>
inline Vector operator<<(const S other) const
template<typename S>
inline Vector operator>(const S other) const
template<typename S>
inline Vector operator<(const S other) const
template<typename S>
inline Vector operator>=(const S other) const
template<typename S>
inline Vector operator<=(const S other) const
template<typename S>
inline Vector operator==(const S other) const
template<typename S>
inline Vector operator!=(const S other) const
inline Vector operator+=(const Vector &other)
inline Vector operator-=(const Vector &other)
inline Vector operator*=(const Vector &other)
inline Vector operator%=(const Vector &other)
inline Vector operator/=(const Vector &other)
inline Vector operator&=(const Vector &other)
inline Vector operator|=(const Vector &other)
inline Vector operator^=(const Vector &other)
template<typename S>
inline Vector operator+=(const S other)
template<typename S>
inline Vector operator-=(const S other)
template<typename S>
inline Vector operator*=(const S other)
template<typename S>
inline Vector operator%=(const S other)
template<typename S>
inline Vector operator/=(const S other)
template<typename S>
inline Vector operator&=(const S other)
template<typename S>
inline Vector operator|=(const S other)
template<typename S>
inline Vector operator^=(const S other)
inline Vector ltz() const

Elementwise plaintext less-than-zero comparison.

inline Vector extend_lsb() const

Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.

inline Vector extract_valid(Vector valid)

Extract the valid elements from a Vector, as denoted by the passed flag vector. Basically a selection function. Used in table operations to filter out invalid rows.

Parameters:

valid

Returns:

Vector

inline std::pair<Vector, Vector> divrem(const T d)

Perform division-with remainder in a single loop, to optimize cache performance.

Parameters:

d

Returns:

std::pair<Vector, Vector> a pair of (quotient, remainder)

inline T &operator[](const VectorSizeType &index)

Returns a mutable reference to the element at the given index. NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

A mutable reference to the element at the given index.

inline const T &operator[](const VectorSizeType &index) const

Returns an immutable reference of the element at the given index.

NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

Returns a read-only reference of the element at the given index.

inline bool same_as(const Vector<T> &other, bool print_warn = true) const

Checks if the two input vectors (this and other) contain the same elements.

Parameters:
  • other

  • print_warn – Print a warning if the Vectors do not match. Useful for test scripts but should be disabled in protocols or production code. This setting can also be controlled at compile time by the directive DEBUG_VECTOR_SAME_AS. (Default: true)

Returns:

true the Vectors are the same

Returns:

false they are not

inline bool starts_with(const Vector<T> &prefix)

Checks if the vector prefix is a prefix of this vector.

Parameters:

prefix

Returns:

true if the argument is a prefix

Returns:

false otherwise

inline bool contains(const T element)
inline bool all_true()

Returns true if all elements of this vector are truthy, and false otherwise.

Returns:

true

Returns:

false

inline Vector matrixRightMultiplyWithColumnMatrixVectorized(Vector rhs, const size_t lhs_rows, const size_t lhs_cols, const size_t rhs_rows, const size_t rhs_cols) const

Matrix right multiplication with a column matrix, vectorized version. Both this and rhs must not have any mapping applied.

Parameters:
  • rhs – The right-hand side column matrix, stored as a vector.

  • lhs_rows – Number of rows in the left-hand side matrix (this).

  • lhs_cols – Number of columns in the left-hand side matrix (this).

  • rhs_rows – Number of rows in the right-hand side column matrix (rhs).

  • rhs_cols – Number of columns in the right-hand side column matrix (rhs).

Returns:

Vector The resulting matrix after multiplication, stored as a vector output is in row-major order.

inline Vector conv2DVectorized(Vector rhs, const size_t instancesCount, const size_t inputHeight, const size_t inputWidth, const size_t filterHeight, const size_t filterWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const

2D convolution, vectorized implementation.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels:

[f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]

Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 output with 2 channels: [f(0,0), g(0,0), f(0,1), g(0,1), f(1,0), g(1,0), f(1,1), g(1,1)]

Parameters:
  • rhs – The filter vector.

  • instancesCount – Number of instances in the input.

  • inputHeight – Height of each input instance.

  • inputWidth – Width of each input instance.

  • filterHeight – Height of the filter.

  • filterWidth – Width of the filter.

  • strideHeight – Stride along height.

  • strideWidth – Stride along width.

  • paddingHeight – Padding along height.

  • paddingWidth – Padding along width.

inline Vector conv2DLeftVectorization(const size_t instancesCount, const size_t inputHeight, const size_t inputWidth, const size_t filterHeight, const size_t filterWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const

2D convolution left vectorization.

It extracts elements needed for 2D convolution from an lhs and order them in a way that allows for efficient matrix multiplication with the filter rhs.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.

Input example: For example, for 2x2 input with 2 channels: [ch1(0,0), ch1(0,1), ch1(0,2), ch1(0,3), ch1(1,0), ch2(1,1), ch1(1,2), ch1(1,3)]

Output Example for (2,2) filter, (1,1) stride, (0,0) padding: [ch1(0,0), ch1(0,1), ch1(1,0), ch1(1,1), ch1(0,1), ch1(0,2), ch1(1,1), ch1(1,2), ch1(0,2), ch1(0,3), ch1(1,2), ch1(1,3)]

Parameters:
  • instancesCount – Number of instances in the input.

  • inputHeight – Height of each input instance.

  • inputWidth – Width of each input instance.

  • filterHeight – Height of the filter.

  • filterWidth – Width of the filter.

  • strideHeight – Stride along height.

  • strideWidth – Stride along width.

  • paddingHeight – Padding along height.

  • paddingWidth – Padding along width.

inline Vector sumPoolingVectorized(const size_t instancesCount, const size_t channels, const size_t inputHeight, const size_t inputWidth, const size_t poolHeight, const size_t poolWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const

2D sum pooling, vectorized implementation.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth * channels. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Output layout: same layout as input but with different height and width.

Parameters:
  • instancesCount – Number of instances in the input.

  • channels – Number of channels per instance.

  • inputHeight – Height of each input instance.

  • inputWidth – Width of each input instance.

  • poolHeight – Height of the pooling window.

  • poolWidth – Width of the pooling window.

  • strideHeight – Stride along height.

  • strideWidth – Stride along width.

  • paddingHeight – Padding along height.

  • paddingWidth – Padding along width.

inline Vector matrixSeparateChannels(const size_t channels) const

Separate interleaved channels in a matrix.

Input layout: The input consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}

Output layout: The output consists of separated channels concatenated in the same vector. {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}

Parameters:

channels – Number of channels in the input matrix.

Returns:

Vector The resulting vector with separated channels.

inline Vector matrixInterleaveChannels(const size_t channels) const

Interleave channels in a matrix. It takes a matrix where channels are separated and make it such that channels are interleaved.

Input layout: The input consists of separated channels concatenated in the same vector. {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}

Output layout: The output consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}

Parameters:

channels – Number of channels in the input matrix.

Returns:

Vector The resulting vector with interleaved channels.

inline Vector gtez() const

Elementwise plaintext greater-or-equal-zero comparison.

Returns:

Vector The resulting vector containing the comparison bits.

Public Members

std::shared_ptr<VectorDataBase<T>> data

A (shared) pointer to the actual vector contents.

NOTE: Shallow copying of this object creates two instances that share the same data.

Public Static Attributes

static const int LEVEL_MASK_SIZE = 7
static const uint64_t constexpr LEVEL_MASKS[LEVEL_MASK_SIZE] = {0xffffffffffffffff, 0xaaaaaaaaaaaaaaaa, 0x4444444444444444, 0x1010101010101010, 0x0100010001000100, 0x0001000000010000, 0x0000000100000000,}

Mask for level 2^i (64 bits). Gives LSB of the most significant half of each chunk.

Private Types

using Unsigned_type = typename std::make_unsigned<T>::type
using Unsigned_type = typename std::make_unsigned<T>::type
using Unsigned_type = typename UnsignedTypeSelector<T>::type

An alias for unsigned T.

Private Functions

inline Vector reverse_bit_level_shift(int level_size) const

Creates a new Vector whose i-th element is generated by:

  1. splitting the bit representation of the i-th element of this Vector into parts of size level_size, and

  2. setting all bits of the most significant half of each part equal to the MSB of the least significant half.

NOTE: This method is bit_level_shift but from right to left, and is used in the parallel prefix adder for boolean addition.

Parameters:

level_size – The number of bits (2^k, k>0) of each part within the bit representation of an element.

Returns:

A new vector that contains elements generated as described above.

inline Vector bit_arithmetic_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, use bit_logical_right_shift

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_logical_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, use bit_arithmetic_right_shift NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_left_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector left-shifted by shift_size

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to left-shift each element of this Vector.

Returns:

A new Vector that contains the left-shifted elements.

inline Vector bit_xor() const

Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of this Vector, 0 <= i < size()

. (Basically parity check of each element.)

NOTE: This method works relatively to the current batch.

Returns:

A new Vector that contains single-bit elements generated as described above.

inline Vector simple_subset(int start, int step, int end) const

Returns a new vector containing elements in the range [start, end] that are step

positions apart.

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • step – The distance between two consecutive elements.

  • end – The maximum possible index of the last element to be included in the output vector.

Returns:

A new vector that contains the selected elements.

inline void reset_batch()

Sets the current batch equal to the whole vector.

inline void set_batch(int _start_ind, int _end_ind)

Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.

Parameters:
  • _start_ind – The index of the first element in the current batch.

  • _end_ind – The index of the last element in the current batch.

Private Members

int batch_start = 0
int batch_end = 0
const int MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits
size_t precision = 0

Fixed-point precision (number of fractional bits)

VectorSizeType length = 0
T element

A single element of the correct type so that we can properly handle the overload of operator[] which returns a T&. Note that this means dummy Vectors do actually store a single element, which may persist across calls (but is not guaranteed to do so). Code like.

a[0] = 5

will store 5 in the first index of a. Later on, accessing a different element of a may or may not return 5.

const size_t MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits

Number of bits to represent T.

VectorSizeType batch_start = 0

The start index of the batch that is currently being processed

VectorSizeType batch_end = 0

The end index of the batch that is currently being processed

std::shared_ptr<std::vector<T>> data

A (shared) pointer to the actual vector contents. NOTE: Shallow copying of this object creates two instances that share the same data.

std::shared_ptr<std::vector<VectorSizeType>> mapping

A (shared) pointer to the vector storing the index mapping for this vector. Can be null, in which case the mapping is defaulted to the identity mapping

Friends

friend class EVector
friend class service::RunTime
friend class cdough::service::Task_1
friend class cdough::service::Task_2
friend class cdough::service::Task_ARGS_RTR_1
friend class cdough::service::Task_ARGS_RTR_2
friend class cdough::service::Task_ARGS_VOID_1
friend class cdough::service::Task_ARGS_VOID_2
friend class EVector
friend class cdough::service::Task_1
friend class cdough::service::Task_2
friend class cdough::service::Task_ARGS_RTR_1
friend class cdough::service::Task_ARGS_RTR_2
friend class cdough::service::Task_ARGS_VOID_1
friend class cdough::service::Task_ARGS_VOID_2
friend class EVector
friend class cdough::service::Task_1
friend class cdough::service::Task_2
friend class cdough::service::Task_ARGS_RTR_1
friend class cdough::service::Task_ARGS_RTR_2
friend class cdough::service::Task_ARGS_VOID_1
friend class cdough::service::Task_ARGS_VOID_2
template<typename T, typename Container, typename Engine>
class SharedVector : public cdough::EncodedVector

A secret-shared vector with share and container types. A SharedVector is an “encoded view” of a plaintext vector as seen from an untrusted party. Different parties in a MPC protocol have different “views” of the same plaintext vector and views may vary significantly across protocols. Currently, cdough supports two techniques to construct a SharedVector: arithmetic and boolean secret sharing. Using these techniques, a secret value \(s\) is encoded using \(n > 1\) random “shares” such that:

  • \(s = s_1 + s_2 + ... + s_n~\texttt{mod}~2^\ell\), where \(\ell\) is the length of \(s\) in bits (Arithmetic)

  • \(s = s_1 \oplus s_2 \oplus ... \oplus s_n\), where \(\oplus\) denotes the bitwise XOR operation (Boolean)

Let \(v = \{4, 12, 84\}\) be a plaintext vector that is secret-shared by 2 parties using arithmetic sharing. From the viewpoint of each party, vector \(v\) will look like this:

\[\begin{split}\begin{align} v = \{-1, 12, 100\} \quad & \textit{(encoded view of party 1)}\\ v = \{5, 0, -16]\} \quad & \textit{(encoded view of party 2)} \end{align}\end{split}\]

These two vectors are in practice SharedVectors containing random numbers that add up to the numbers in the original vector (which remains hidden from the parties). To reconstruct the original vector in this example, the parties must “open” their SharedVector to a single entity (i.e., a learner) to apply the elementwise addition. The methods to construct and open SharedVectors are defined in Protocol.

Template Parameters:
  • Share – Share data type.

  • Container – Share container type.

  • Engine – Secure computation engine type.

Subclassed by cdough::ASharedVector< T, AInnerContainer< T >, RunTime >, cdough::ASharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::ASharedVector< int, cdough::EVector< int, E::replicationNumber >, Eng >, cdough::ASharedVector< int, cdough::EVector< int, E::replicationNumber >, Engine >, cdough::BSharedVector< T, BInnerContainer< T >, RunTime >, cdough::BSharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::BSharedVector< T, Container, Engine >, cdough::BSharedVector< int, cdough::EVector< int, E::replicationNumber >, Eng >, cdough::BSharedVector< int, cdough::EVector< int, E::replicationNumber >, Engine >, cdough::BSharedVector< PadWidth< typename E::ShareT >, cdough::EVector< PadWidth< typename E::ShareT >, E::replicationNumber >, Engine >

Public Functions

inline explicit SharedVector(size_t _size, const Encoding &eType, Engine &eng)

Creates a SharedVector of size _size and initializes it with zeros.

Parameters:
  • _size – The size of the SharedVector.

  • eType – The encoding of the SharedVector.

  • eng – The secure computation engine.

inline explicit SharedVector(size_t _size, const std::string &_input_file, const Encoding &eType, Engine &eng)

Creates a SharedVector of size _size and initializes it with the contents of the file _input_file.

Parameters:
  • _size – The size of the SharedVector.

  • _input_file – The file containing the contents of the SharedVector.

  • eType – The encoding of the SharedVector.

  • eng – The secure computation engine.

inline void outputSecretShares(const std::string &_output_file)

Writes the secret shares of the shared vector to a file.

Parameters:

_output_file – The file to write the secret shares to.

inline explicit SharedVector(const Container &_shares, const Encoding &eType, Engine &eng)

This is a shallow copy constructor from Container.

Parameters:
  • _shares – The Container whose contents will be pointed at by the SharedVector.

  • eType – encoding

  • eng – The secure computation engine.

inline SharedVector(SharedVector &&secretShares) noexcept

This is a move constructor from SharedVector.

Parameters:

secretShares – The SharedVector whose contents will be moved to the new SharedVector.

inline SharedVector(SharedVector &secretShares)
inline explicit SharedVector(EncodedVector &_shares, Engine &eng)

Copy constructor from EncodedVector.

Parameters:
  • _shares – The EncodedVector object whose contents will be copied to the new SharedVector.

  • eng – The secure computation engine.

inline virtual ~SharedVector()
inline Vector<T> open() const

Opens the shared vector to all computing parties. For malicious protocols, also runs checks.

Returns:

The opened (plaintext) vector.

inline void print() const
inline virtual VectorSizeType size() const
Returns:

The size of the shared vector in number of elements.

inline void zero()
inline void resize(size_t n)

Resize a shared vector. If the new vector is larger, the tail end will be initialized to zero. If the new vector is smaller, the end of the current vector will be removed (head semantics).

Parameters:

n

inline void tail(size_t n)

Resize this vector have its last n elements. Does not copy.

Parameters:

n

inline void concatenate(const SharedVector &other)

Concatenate this vector with other by resizing this and placing other into the new positions.

Parameters:

other

inline SharedVector slice(size_t start, size_t end)
inline SharedVector slice(size_t start)
inline SharedVector subset(size_t start, size_t step)
inline SharedVector subset(size_t start, size_t step, size_t end)
inline SharedVector reversed_view()
inline std::unique_ptr<SharedVector> deepcopy()

Create a deep copy (allocate new space and copy all elements) of a shared vector.

Returns:

std::unique_ptr<SharedVector>

inline SharedVector &operator=(const SharedVector &other)

Copy-assignment between shared vector. Copies shares from other into this. Pass to the engine to enable multithreaded execution.

Parameters:

other

Returns:

SharedVector&

inline SharedVector &operator=(SharedVector &&other)

Move-assignment between shared vectors. Takes ownership of other’s vector. This is not passed to the engine because no data is copied.

Parameters:

other

Returns:

SharedVector&

template<typename T2, typename E2>
inline SharedVector &operator=(const SharedVector<T2, E2, Engine> &other)

Cast-and-copy assignment. Create a SharedVector from another one of a different underlying type. (Replication number and encoding must still match.) This allows us to up/down-cast vectors.

Template Parameters:

T2

Parameters:

other

Returns:

SharedVector&

inline Container asContainer() const

Transforms this vector into an Container object.

NOTE: This method is useful for developers who need access to the underlying shares of the

SharedVector that are only exposed through the Container. Use it if you are certain about what you are doing.

Returns:

An Container object with the same contents as this shared vector.

inline Engine &getEngine()

Get the secure computation engine.

Returns:

Engine&

inline void prefix_sum()

Compute a prefix sum over this shared vector.

WARNING: this does not call down to the protocol primitive but instead performs a local prefix sum over the actual underlying vector. This will not cause any issues now, since for all current protocols, add_a is trivial. But this is not necessarily true in general.

inline SharedVector shuffle()
inline void reverse()
inline virtual void setPrecision(const int fixed_point_precision)

Sets the fixed-point precision.

Parameters:

fixed_point_precision – - the number of fixed-point fractional bits.

inline virtual size_t getPrecision() const

Gets the fixed-point precision.

Public Members

Container vector
Engine &engine

Private Types

using B_t = BSharedVector<T, Container, Engine>
template<typename Share, typename EVector, typename Engine>
class ASharedVector : public cdough::SharedVector<Share, EVector, Engine>

A SharedVector that contains arithmetic shares and supports secure arithmetic operations.

Template Parameters:
  • Share – Share data type.

  • EVector – Share container type.

  • Engine – Secure computation engine type.

Public Types

using EngineType = Engine
using B = BSharedVector<Share, EVector, Engine>

Type alias for an equivalent BSharedVector.

Public Functions

inline explicit ASharedVector(size_t _size, Engine &eng)

Creates an ASharedVector of size _size and initializes it with zeros.

Note: This constructor is deprecated from public API [last resort].

Parameters:
  • _size – The size of the ASharedVector.

  • eng – The secure computation engine.

inline explicit ASharedVector(size_t _size, const std::string &_input_file, Engine &eng)

Creates an ASharedVector of size _size and initializes it with secret shares in the given file.

Parameters:
  • _size – The size of the ASharedVector.

  • _input_file – The file that contains the secret shares.

  • eng – The secure computation engine.

inline explicit ASharedVector(EVector &_shares, Engine &eng)

This is a shallow copy constructor from EVector contents.

Parameters:
  • _shares – The EVector whose contents will be pointed by the ASharedVector.

  • eng – The secure computation engine.

inline ASharedVector(EVector &&_shares, Engine &eng)

This is a move constructor from EVector contents.

Parameters:
  • _shares – The EVector whose contents will be moved to the new ASharedVector.

  • eng – The secure computation engine.

inline ASharedVector(ASharedVector &&other) noexcept

This is a move constructor from another ASharedVector.

Parameters:

other – The ASharedVector whose contents will be moved to the new ASharedVector.

inline ASharedVector(const ASharedVector &other)

This is a copy constructor from another ASharedVector.

Parameters:

other – The ASharedVector whose contents will be moved to the new ASharedVector.

inline explicit ASharedVector(SharedVector<Share, EVector, Engine> &_shares)

Copy constructor from SharedVector contents.

Parameters:

_shares – The SharedVector object whose contents will be copied to the new ASharedVector.

inline ASharedVector(std::unique_ptr<ASharedVector> &&base)

Move constructor that creates an ASharedVector from a unique pointer to an EncodedVector object.

Parameters:

base – The pointer to the SharedVector object whose contents will be moved to the new ASharedVector.

inline ASharedVector(std::unique_ptr<ASharedVector> &base)

Shallow copy constructor that creates an ASharedVector from a unique pointer to an EncodedVector object.

Parameters:

base – The SharedVector object whose contents will be pointed by the new ASharedVector.

inline explicit ASharedVector(ASharedVector *_base)

Move constructor that creates an ASharedVector from a pointer to another ASharedVector

object.

NOTE: This constructor is implicitly called by the two constructors above.

Parameters:

_base – The ASharedVector that will be moved as a whole (contents + state) to the new ASharedVector.

inline ASharedVector construct_like(std::optional<size_t> size = {}) const

Construct a new ASharedVector object like another ASharedVector but with a different size.

Parameters:

size – The size of the new ASharedVector.

Returns:

ASharedVector The newly constructed ASharedVector.

ASharedVector &operator=(const ASharedVector&) = default
ASharedVector &operator=(ASharedVector&&) = default
inline virtual ~ASharedVector()
template<typename ...T>
inline ASharedVector simple_subset_reference(T... args) const

Reuse underlying SharedVector implementation for access patterns.

template<typename ...T>
inline ASharedVector alternating_subset_reference(T... args) const
template<typename ...T>
inline ASharedVector reversed_alternating_subset_reference(T... args) const
template<typename ...T>
inline ASharedVector repeated_subset_reference(T... args) const
template<typename ...T>
inline ASharedVector cyclic_subset_reference(T... args) const
template<typename ...T>
inline ASharedVector directed_subset_reference(T... args) const
template<typename ...T>
inline ASharedVector included_reference(T... args) const
template<typename ...T>
inline ASharedVector mapping_reference(T... args) const
template<typename ...T>
inline ASharedVector slice(T... args) const
template<typename ...T>
inline ASharedVector matrixSeparateChannels(T... args) const
template<typename ...T>
inline ASharedVector matrixInterleaveChannels(T... args) const
template<typename ...T>
inline ASharedVector conv2DLeftVectorization(T... args) const
inline std::unique_ptr<B> a2b() const

Convert from ASharedVector to BSharedVector. Each party redistributes boolean shares of their additive shares, then uses a boolean addition circuit to “add” those shares back together. In the end we are left with an XOR-sharing of the same value.

Other protocols, such as using preprocessed shared bits, are possible.

inline std::unique_ptr<B> a2b_packed_sign() const

Convert from ASharedVector to BSharedVector, but only for the most significant bit of each element (sign).

Note: size of the resulting BSharedVector is n/MAX_BITS_NUMBER.

Returns:

std::unique_ptr the resulting BSharedVector containing only the MSBs.

inline std::unique_ptr<ASharedVector> operator+(const ASharedVector &other) const

Elementwise secure arithmetic addition. Returns a unique ptr.

inline std::unique_ptr<ASharedVector> operator-(const ASharedVector &other) const

Elementwise secure arithmetic subtraction. Returns a unique ptr.

inline std::unique_ptr<ASharedVector> operator*(const ASharedVector &other) const

Elementwise secure arithmetic multiplication. Returns a unique ptr.

inline std::unique_ptr<ASharedVector> operator-() const

Elementwise secure arithmetic negation. Returns a unique ptr.

inline std::unique_ptr<ASharedVector> operator+(Share y) const
inline std::unique_ptr<ASharedVector> operator-(Share y) const
inline std::unique_ptr<ASharedVector> operator*(Share y) const
inline std::unique_ptr<ASharedVector> operator>(Share y) const
inline std::unique_ptr<ASharedVector> operator<(Share y) const
inline std::unique_ptr<ASharedVector> operator>=(Share y) const
inline std::unique_ptr<ASharedVector> operator<=(Share y) const
inline std::unique_ptr<ASharedVector> operator==(Share y) const
inline std::unique_ptr<ASharedVector> operator!=(Share y) const
template<std::floating_point FP>
inline std::unique_ptr<ASharedVector> operator*(FP y) const

Multiply by a public floating-point constant (local, no MPC protocol). Scales the float to a fixed-point integer using this vector’s precision, multiplies each share locally, and truncates.

inline ASharedVector operator+=(const ASharedVector &y)
inline ASharedVector operator-=(const ASharedVector &y)
inline ASharedVector operator*=(const ASharedVector &y)
inline void operator+=(Share y)
inline void operator-=(Share y)
inline void operator*=(Share y)
inline std::unique_ptr<ASharedVector> operator/(const Share &c) const

Division by public constant. Call the underlying protocol’s div_const_a functionality, then perform error correction (if configured to do so using the compiler directive USE_DIVISION_CORRECTION).

Parameters:

c

Returns:

std::unique_ptr<ASharedVector>

inline std::unique_ptr<BSharedVector<Share, EVector, Engine>> operator/(const ASharedVector &other) const

Auto-conversion private elementwise division. Since our current integer division algorithm only supports BSharedVector inputs, convert this and other to binary before calling BSharedVector::operator/. Do not convert the result back.

Parameters:

other

Returns:

std::unique_ptr<BSharedVector>

inline std::unique_ptr<ASharedVector> dot_product(const ASharedVector &other, const size_t aggSize) const

Computes the dot product of this vector with another vector. Each aggSize consecutive elements contribute to an exactly on dot product element in the result. The size of the resulting vector is determined by the aggSize parameter.

NOTE: This function is efficient when doing dot products with small aggSize values, For larger aggSize values including the entire vector in the dot product, we will need to to do batching different in the engine. Currently, whole vector dot product will be executed single-threaded because each threads takes multiple.

Parameters:
  • other – The second operand of the dot product.

  • aggSize – The size of each dot product.

Returns:

A unique pointer to a new ASharedVector that contains the result of the dot product.

inline std::unique_ptr<ASharedVector> matrixRightMultiplyWithColumnMatrixVectorized(const ASharedVector &other, const size_t lhs_rows, const size_t lhs_cols, const size_t rhs_rows, const size_t rhs_cols) const

Secure matrix right multiplication with a column matrix, vectorized implementation. Expects the left-hand side matrix to be in row-major order. Expects the right-hand side matrix to be in column-major order.

Parameters:
  • other – The right-hand side column matrix.

  • lhs_rows – Number of rows in the left-hand side matrix.

  • lhs_cols – Number of columns in the left-hand side matrix.

  • rhs_rows – Number of rows in the right-hand side matrix.

  • rhs_cols – Number of columns in the right-hand side matrix.

Returns:

std::unique_ptr<ASharedVector>

inline std::unique_ptr<ASharedVector> conv2DVectorized(const ASharedVector &other, const size_t instancesCount, const size_t inputHeight, const size_t inputWidth, const size_t filterHeight, const size_t filterWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const

Secure 2D convolution, vectorized implementation.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels:

[f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]

Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 output with 2 channels: [f(0,0), g(0,0), f(0,1), g(0,1), f(1,0), g(1,0), f(1,1), g(1,1)]

Parameters:
  • other – The filter matrix.

  • instancesCount – Number of instances in the input batch.

  • inputHeight – Height of each input instance.

  • inputWidth – Width of each input instance.

  • filterHeight – Height of each filter channel.

  • filterWidth – Width of each filter channel.

  • strideHeight – Stride height.

  • strideWidth – Stride width.

  • paddingHeight – Padding height.

  • paddingWidth – Padding width.

Returns:

std::unique_ptr<ASharedVector>

inline std::unique_ptr<ASharedVector> sumPoolingVectorized(const size_t instancesCount, const size_t channels, const size_t inputHeight, const size_t inputWidth, const size_t poolHeight, const size_t poolWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const

Secure sum pooling. Aggregates values within pooling windows by summing them. Aggregation is performed over multiple instances with multiple channels. Each layer is pooled independently.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth * channels. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Output layout: same layout as input but with different height and width.

Parameters:
  • instancesCount – Number of instances in the input batch.

  • channels – Number of channels in each instance.

  • inputHeight – Height of each input instance.

  • inputWidth – Width of each input instance.

  • poolHeight – Height of the pooling window.

  • poolWidth – Width of the pooling window.

  • strideHeight – Stride height.

  • strideWidth – Stride width.

  • paddingHeight – Padding height.

  • paddingWidth – Padding width.

Returns:

std::unique_ptr<ASharedVector> The resulting pooled ASharedVector.

inline void inplace_invert()

Negate this vector in place.

inline std::unique_ptr<ASharedVector> operator>(const ASharedVector &other) const

Secure comparison: greater than. Note: If you do not need secure multiplication/addition after comparison, consider using BSharedVector instead. It uses conversion and BSharedVector’s comparison operator under the hood. It keeps the results in the ASharedVector world after comparison.

Parameters:

other – The other ASharedVector to compare against.

Returns:

std::unique_ptr<ASharedVector>

inline std::unique_ptr<ASharedVector> operator<(const ASharedVector &other) const
inline std::unique_ptr<ASharedVector> operator>=(const ASharedVector &other) const
inline std::unique_ptr<ASharedVector> operator<=(const ASharedVector &other) const
inline std::unique_ptr<ASharedVector> operator==(const ASharedVector &other) const
inline std::unique_ptr<ASharedVector> operator!=(const ASharedVector &other) const
inline std::unique_ptr<ASharedVector> gtez() const

Secure comparison: greater than or equal to zero. Note: If you do not need secure multiplication/addition after comparison, consider using BSharedVector instead. It uses conversion and BSharedVector’s comparison operator under the hood. It keeps the results in the ASharedVector world after comparison.

Returns:

std::unique_ptr<ASharedVector>

inline ASharedVector chunkedSum(const size_t aggSize = 0) const

Compute chunked sums over groups of consecutive elements. Simply calls down to the underlying EVector’s chunkedSum method.

Parameters:

aggSize – The number of elements to aggregate in each sum.

Returns:

ASharedVector containing the chunked sums.

template<typename Share, typename EVector, typename Engine>
class BSharedVector : public cdough::SharedVector<Share, EVector, Engine>

A SharedVector that contains boolean shares and supports secure boolean operations.

Template Parameters:
  • Share – Share data type.

  • EVector – Share container type.

  • Engine – Secure computation engine type.

Public Types

using SharedVector_t = SharedVector<Share, EVector, Engine>
using EngineType = Engine

Public Functions

inline unique_B rca(const BSharedVector<Share, EVector, Engine> &b, const bool carry_in = false) const
inline unique_B rca_packed_sign(const BSharedVector<Share, EVector, Engine> &b, bool carry_in = false) const
inline unique_B ppa(const BSharedVector<Share, EVector, Engine> &b, const bool carry_in = false) const
inline unique_B binary_adder(const BSharedVector<Share, EVector, Engine> &a, const BSharedVector<Share, EVector, Engine> &b, bool carry_in) const
inline void pack_from(const BSharedVector &source, const int &position)

Bit packing. Operates in place by packing the bit at index position from BSharedVector source into this BSharedVector.

Parameters:
  • source

  • position

inline void unpack_from(const BSharedVector &source, const int &position)

Bit unpacking. Operates in place by unpacking the bit at index position from BSharedVector source into this.

Parameters:
  • source

  • position

inline std::vector<BSharedVector> bit_decomposition() const

Decomposes each element of this BSharedVector into its bits, returning a vector of BSharedVectors, each containing one bit position across all elements.

Returns:

A vector of BSharedVectors, where the i-th BSharedVector contains the i-th bits of each element in this.

inline void bit_arithmetic_right_shift(const BSharedVector &in, const int &shift_size)

Arithmetic right shift. Operates in place by putting the output into this. Respects the sign bit.

Parameters:
  • in – input

  • shift_size – The number of bits to right-shift each element of this vector.

inline void bit_logical_right_shift(const BSharedVector &in, const int &shift_size)

Logical right shift. Operates in place. Does not respect the sign bit.

Parameters:
  • in – input

  • shift_size – The number of bits to right-shift each element of this vector.

inline void bit_left_shift(const BSharedVector &in, const int &shift_size)

Bit left shift. Operates in place. Does not respect the sign bit.

Parameters:
  • in

  • shift_size

inline void bit_xor(const BSharedVector &in)

Compute the parity of the input BSharedVector and place the result into this.

Parameters:

in – input shared vector

inline void extend_lsb(const BSharedVector &in)

Elementwise LSB extension. This method operates in place, copying the LSB of each in element into this.

Parameters:

in

inline auto popcount() const

Returns the popcount (AKA Hamming weight) of this as a std::unique_ptr to a ASharedVector. Uses a round-optimal concatenation approach, unpacking this into the LSB of a new BSharedVector and then taking its chunkedSum.

Returns:

A pointer to a new ASharedVector with the popcount of this

inline explicit BSharedVector(size_t _size, Engine &eng)

Creates a BSharedVector of size _size and initializes it with zeros.

Note: This constructor is deprecated from public API [last resort].

Parameters:

_size – The size of the BSharedVector.

inline explicit BSharedVector(size_t _size, const std::string &_input_file, Engine &eng)

Creates a BSharedVector of size _size and initializes it with secret shares in the given file.

Parameters:
  • _size – The size of the BSharedVector.

  • _input_file – The file that contains the secret shares.

inline explicit BSharedVector(EVector &_shares, Engine &eng)

This is a shallow copy constructor from EVector.

Parameters:
  • _shares – The EVector whose contents will be pointed by the BSharedVector.

  • eng – The engine to be used.

inline BSharedVector(EVector &&_shares, Engine &eng)

This is a move constructor from EVector.

Parameters:
  • _shares – The EVector whose contents will be moved to the new BSharedVector.

  • eng – The engine to be used.

inline BSharedVector(BSharedVector &&other)

This is a move constructor from another BSharedVector.

Parameters:

other – The BSharedVector whose contents will be moved to the new BSharedVector.

inline BSharedVector(const BSharedVector &other)

This is a copy constructor from another BSharedVector.

Parameters:

other – The BSharedVector whose contents will be copied to the new BSharedVector.

inline explicit BSharedVector(SharedVector<Share, EVector, Engine> &_shares)

Copy constructor from a SharedVector.

Parameters:

_shares – The SharedVector object whose contents will be copied to the new BSharedVector.

inline BSharedVector(std::unique_ptr<BSharedVector> &&base)

Move constructor that creates a BSharedVector from a unique pointer to a SharedVector object.

Parameters:

base – The pointer to the SharedVector object whose contents will be moved to the new BSharedVector.

inline BSharedVector(std::unique_ptr<BSharedVector> &base)

Shallow copy constructor that creates a BSharedVector from a unique pointer to a SharedVector object.

Parameters:

base – The SharedVector object whose contents will be pointed by the new BSharedVector.

inline explicit BSharedVector(BSharedVector *_base)

Move constructor that creates a BSharedVector from a pointer to another BSharedVector

object.

NOTE: This constructor is implicitly called by the two constructors above.

Parameters:

_base – The BSharedVector that will be moved as a whole (contents + state) to the new BSharedVector.

inline BSharedVector construct_like(std::optional<size_t> size = {}) const

Construct a new BSharedVector object like another BSharedVector but with a different size.

Parameters:

size – The size of the new BSharedVector.

Returns:

ASharedVector The newly constructed BSharedVector.

BSharedVector &operator=(const BSharedVector&) = default
BSharedVector &operator=(BSharedVector&&) = default
inline virtual ~BSharedVector()
inline auto b2a_bit() const

Convert the LSB of each element of this BSharedVector to an arithmetic sharing. This is substantially more efficient than a full-width conversion and suffices for most applications.

Returns:

ASharedVector

inline std::unique_ptr<ASharedVector<Share, EVector, Engine>> b2a() const

Full-width conversion from BSharedVector to ASharedVector. Generates an online shared-bit correlation (random value shared in both domains), and then uses a boolean adder to mask.

The first loop is technically preprocessing, which would speed things up a lot.

Returns:

ASharedVector

inline ASharedVector<Share, EVector, Engine> insecure_b2a() const

This is a conversion from BSharedVector to ASharedVector. It is insecure. It is only used in the generation of dummy permutations.

Public Static Attributes

static const size_t MAX_BITS_NUMBER = std::numeric_limits<std::make_unsigned_t<Share>>::digits
static const size_t LOG_MAX_BITS_NUMBER = std::bit_width(MAX_BITS_NUMBER - 1)

Private Types

using unique_B = std::unique_ptr<BSharedVector>

Private Functions

inline double model_rca(double latency, double bandwidth, size_t n) const
inline double model_ppa(double latency, double bandwidth, size_t n) const
template<typename Share, int ReplicationNumber, int Bitwidth = 0>
class EVector

EVector is an abstraction similar to the EncodedVector, i.e., an “encoded view” of a plaintext vector as seen by an untrusted party. In contrast to EncodedVector, EVector provides access to the underlying encodings of the secret values.

While EncodedVector targets end-users, EVector is the abstraction provided to Protocol developers who need access to the underlying encodings in order to define new secure primitives, such as Protocol::add_a(), Protocol::and_b(), etc.

Template Parameters:
  • Share – Share type.

  • ReplicationNumber – The number of shares that each party sees for each secret value.

  • Bitwidth – The bitwidth of the underlying Data type. Default is 0 (e.g. 8 for uint8_t).

Public Types

using ShareT = Share

Public Functions

inline EVector(std::vector<Vector<Share>> contents)

Provides an interface to initialize the data object with existing data.

NOTE: the copy constructor of

Vector<T> is shallow; if this is initialized by another Vector<T> object, both will point to data in the same memory location.

Parameters:

contents – The vector of vectors to initialize the data object with.

inline EVector(std::vector<Vector<Share>> contents, size_t fixed_point_precision)

Initializes the EVector with a given vector of vectors and a fixed-point precision.

Parameters:
  • contents – - The vector of vectors to initialize the data object with.

  • fixed_point_precision – - The fixed-point fractional bits to set for this EVector.

inline EVector(std::initializer_list<Vector<Share>> l)

Initializes the EVector with a given initializer list of Vector<Share>.

Parameters:

l – The initializer list to initialize the EVector with.

Throws:

std::invalid_argument – if the size of the initializer list doesn’t match ReplicationNumber.

inline explicit EVector(size_t size)

EVector<T,N> constructor that allocates ReplicationNumber new Vectors, each one of size size.

Parameters:

size – The size of Vector<T> in this EVector<T,N>.

inline EVector(const EVector &other)

This is a shallow copy constructor (i.e., only copies the vector pointer but not its contents).

WARNING: The new vector will point to the same memory location as used by

other. To copy the data into a separate memory location, create a new vector first then use the assignment operator.

Parameters:

other – The other EVector whose contents this vector will point to.

inline EVector &operator=(const EVector &&other)

This is a deep move assignment. Applies the move assignment operator to Vector<T>. Assigns the values of the current batch from the other vector to the current batch of this vector. Assumes other has the same size and replication factor as this vector.

Parameters:

other – The EVector containing the values that this vector must point to.

Returns:

A reference to this EVector after modification.

inline void setPrecision(const int fixed_point_precision)

Sets the fixed-point precision.

Parameters:

fixed_point_precision – - the number of fixed-point fractional bits.

inline size_t getPrecision() const

Gets the fixed-point precision.

inline void matchPrecision(const EVector &other)

Helper that sets this vector’s precision to match another EVector.

Parameters:

other – The EVector whose precision should be copied.

inline void output(const std::string &_output_file_path)
inline EVector &operator=(const EVector &other)

This is a deep copy assignment. Applies the copy assignment operator to Vector<T>. Copies the values of the current batch from the other vector to the current batch of this vector. Assumes other has the same size and replication factor as this vector.

Parameters:

other – The EVector that contains the values to be copied.

Returns:

A reference to this EVector after modification.

template<typename Other, int R, int Tag2>
inline EVector &operator=(const cdough::EVector<Other, R, Tag2> &other)

Type-conversion assignment.

Template Parameters:
  • Other – type of the other EVector

  • R – replication number

Parameters:

other

Returns:

EVector&

inline EVector(size_t size, const std::string &_input_file_path)

EVector<T,N> constructor that allocates ReplicationNumber new Vectors, each one of size size, and initializes them with the contents of the file _input_file_path. The file contains the secret shares of the EVector. Each line in the file contains ReplicationNumber values separated by a space.

Parameters:
  • size – The size of Vector<T> in this EVector<T,N>.

  • _input_file_path – The path to the file containing the contents of the EVector.

inline size_t size() const

Returns the current batch size, i.e., the number of secret values that are being processed in the current round. The default batch size is the actual vector size.

NOTE: cdough parties apply operations on EVectors in batches. Each batch corresponds to a range of elements in the vector.

Returns:

The current batch size.

inline int getReplicationNumber() const
inline EVector construct_like() const

Creates a new EVector with the same structure as this EVector, but with newly allocated empty vectors of the same size.

Returns:

A new EVector with the same structure but empty contents.

inline EVector construct_like(size_t size) const

Creates a new EVector with the same structure as this EVector, but with newly allocated empty vectors of a different size.

Parameters:

size – The size of the new EVector’s vectors.

Returns:

A new EVector with the same structure but empty contents.

template<typename ...T>
inline void pack_from(const EVector &other, const T&... args)
template<typename ...T>
inline void unpack_from(const EVector &other, const T&... args)
template<typename ...T>
inline void concatenate(const EVector &other, const T&... args)
template<typename ...T>
inline void alternating_bit_decompress(EVector &other, T... args)
template<typename ...T>
inline void simple_bit_decompress(EVector &other, T... args)
template<typename ...T>
inline EVector alternating_bit_compress(T... args) const
template<typename ...T>
inline EVector alternating_subset_reference(T... args) const
template<typename ...T>
inline EVector bit_arithmetic_right_shift(T... args) const
template<typename ...T>
inline EVector bit_left_shift(T... args) const
template<typename ...T>
inline EVector bit_logical_right_shift(T... args) const
template<typename ...T>
inline EVector bit_xor(T... args) const
template<typename ...T>
inline EVector cyclic_subset_reference(T... args) const
template<typename ...T>
inline EVector directed_subset_reference(T... args) const
template<typename ...T>
inline EVector extend_lsb(T... args) const
template<typename ...T>
inline EVector ltz(T... args) const
template<typename ...T>
inline EVector repeated_subset_reference(T... args) const
template<typename ...T>
inline EVector reversed_alternating_subset_reference(T... args) const
template<typename ...T>
inline EVector simple_bit_compress(T... args) const
template<typename ...T>
inline EVector simple_subset_reference(T... args) const
template<typename ...T>
inline EVector slice(T... args) const
template<typename ...T>
inline EVector simple_subset(T... args) const
template<typename ...T>
inline EVector included_reference(T... args) const
template<typename ...T>
inline EVector mapping_reference(T... args) const
template<typename ...T>
inline EVector materialize(T... args) const
template<typename ...T>
inline EVector chunkedSum(T... args) const
template<typename ...T>
inline EVector sumPoolingVectorized(T... args) const
template<typename ...T>
inline EVector matrixSeparateChannels(T... args) const
template<typename ...T>
inline EVector matrixInterleaveChannels(T... args) const
template<typename ...T>
inline EVector conv2DLeftVectorization(T... args) const
template<typename ...T>
inline EVector dot_product(const EVector &other, T... args) const
template<typename ...T>
inline EVector matrixRightMultiplyWithColumnMatrixVectorized(const EVector &other, T... args) const
template<typename ...T>
inline EVector conv2DVectorized(const EVector &other, T... args) const
template<typename ...T>
inline std::vector<EVector> bit_decomposition(T... args) const
template<typename ...T>
inline void mask(T... args)
template<typename ...T>
inline void prefix_sum(T... args)
template<typename ...T>
inline void resize(T... args)
template<typename ...T>
inline void set_batch(T... args)
template<typename ...T>
inline void reset_batch(T... args)
template<typename ...T>
inline void tail(T... args)
template<typename ...T>
inline void zero(T... args)
template<typename ...T>
inline void apply_mapping(T... args)
template<typename ...T>
inline void reverse(T... args)
template<typename ...T>
inline void materialize_inplace(T... args)
inline bool has_mapping() const
inline Vector<Share> &operator()(int column)

Returns a mutable reference to a column of the EVector. EVector is implemented as a column-first 2D vector, where:

  • row i corresponds to k >= 1 encodings of the i-th secret value, 0 <= i < n.

  • column j stores the j-th encoding, 0 <= j < k, of each secret value in the vector.

The above column-first representation aims to facilitate the implementation of vectorized secure primitives. The number of secret values n in EVector is defined by the user but the number of encodings k per secret value depends on the Protocol. For example, in Replicated_3PC, each secret value \(s\) is encoded with three shares \(s_1\), \(s_2\), and \(s_3\) and each party receives k=2 of the 3 shares, namely:

  • Party 0 receives shares \(s_1\) and \(s_2\).

  • Party 1 receives shares \(s_2\) and \(s_3\).

  • Party 2 receives shares \(s_3\) and \(s_1\).

Assuming a plaintext vector \(v = \{s^1, s^2, ..., s^{n}\}\) with n values that are secret-shared by three parties, the respective EVectors in Replicated_3PC look as shown below:

  • \(v = \{~\{s^1_1, s^2_1,~...~s^{n}_1\},~\{s^1_2, s^2_2,~...,~s^{n}_2\}~\}\) (Party 1)

  • \(v = \{~\{s^1_2, s^2_2,~...~s^{n}_2\},~\{s^1_3, s^2_3,~...,~s^{n}_3\}~\}\) (Party 2)

  • \(v = \{~\{s^1_3, s^2_3,~...~s^{n}_3\},~\{s^1_1, s^2_1,~...,~s^{n}_1\}~\}\) (Party 3)

In this case, calling \(v(1)\) from Party 2 will return a reference to the internal vector at index j=1 that includes the third share \(s_3\) of each secret value:

  • \(\{s^1_3, s^2_3,~...,~s^{n}_3\}\)

Parameters:

column – The column index.

Returns:

A mutable reference to a vector of encodings at the given index.

inline const Vector<Share> &operator()(int column) const

Returns a read-only reference to a column of the EVector. For more information, see the version of the same operator that returns a mutable reference.

Parameters:

column – The column index.

Returns:

A read-only reference to a vector of encodings at the given index.

template<typename OtherType>
inline EVector operator+(const OtherType &other) const
template<typename OtherType>
inline EVector operator-(const OtherType &other) const
template<typename OtherType>
inline EVector operator*(const OtherType &other) const
template<typename OtherType>
inline EVector operator/(const OtherType &other) const
template<typename OtherType>
inline EVector operator&(const OtherType &other) const
template<typename OtherType>
inline EVector operator|(const OtherType &other) const
template<typename OtherType>
inline EVector operator^(const OtherType &other) const
template<typename OtherType>
inline EVector operator>>(const OtherType &other) const
template<typename OtherType>
inline EVector operator<<(const OtherType &other) const
template<typename OtherType>
inline EVector operator<(const OtherType &other) const
template<typename OtherType>
inline EVector operator>(const OtherType &other) const
template<typename OtherType>
inline EVector operator>=(const OtherType &other) const
template<typename OtherType>
inline EVector operator<=(const OtherType &other) const
template<typename OtherType>
inline EVector operator==(const OtherType &other) const
template<typename OtherType>
inline EVector operator!=(const OtherType &other) const
inline EVector operator+(const EVector &other) const
inline EVector operator-(const EVector &other) const
inline EVector operator*(const EVector &other) const
inline EVector operator/(const EVector &other) const
inline EVector operator&(const EVector &other) const
inline EVector operator|(const EVector &other) const
inline EVector operator^(const EVector &other) const
inline EVector operator>>(const EVector &other) const
inline EVector operator<<(const EVector &other) const
inline EVector operator<(const EVector &other) const
inline EVector operator>(const EVector &other) const
inline EVector operator==(const EVector &other) const
inline EVector operator!=(const EVector &other) const
inline EVector &operator+=(const EVector &other)
inline EVector &operator-=(const EVector &other)
inline EVector &operator&=(const EVector &other)
inline EVector &operator|=(const EVector &other)
inline EVector &operator^=(const EVector &other)
inline EVector operator-() const
inline EVector operator~() const
inline EVector operator!() const

Public Static Attributes

static const int replicationNumber = ReplicationNumber

Protected Functions

inline size_t total_size() const

Returns the size of EVector

, i.e., the total number of secret values in the original (plaintext) vector.

NOTE: The output of

total_size() cannot be less than the output of size().

Returns:

The size of EVector.

Protected Attributes

std::vector<Vector<Share>> contents

Private Members

size_t precision

Friends

friend class BSharedVector
friend class ASharedVector
friend class service::RunTime
friend class cdough::service::Task_1
friend class cdough::service::Task_2
friend class EVector
friend class Protocol
template<typename EVector, typename Engine>
class ElementwisePermutation

Public Functions

inline ElementwisePermutation(size_t size, Engine &engine)

Default constructor which creates an identity permutation of a given size.

By default, this constructs an arithmetic sharing of the identity permutation. This constructor simply calls the next constructor with the default AShared sharing type.

Parameters:

size – The size of the permutation.

inline ElementwisePermutation(size_t size, Encoding encoding, Engine &engine)

Constructor which creates an identity permutation of a given size with a given encoding.

Parameters:
  • size – The size of the permutation.

  • encoding – The encoding type of the underlying SharedVector (arithmetic or binary).

inline ElementwisePermutation(ElementwisePermutation &permutation)

Copy constructor which takes another ElementwisePermutation as input.

Parameters:

permutation – The permutation to copy.

template<typename Share, typename argEVector>
inline ElementwisePermutation(const SharedVector<Share, argEVector, Engine> &v)

Constructor which takes a SharedVector as input and assigns it to the underlying SharedVector

.

The second template argument is named argEVector to distinguish it from the

EVector that this class is templated by. This function copies the underlying data to a 32 bit SharedVector, which requires that the input vector has a bitwidth <= 32.

Parameters:

v – The SharedVector to copy.

inline ElementwisePermutation &operator=(const ElementwisePermutation &other)

Copy assignment operator.

Note: does not affect the engine because assignmnent concerns values only.

Parameters:

other – The permutation to copy.

template<typename Share, typename argEVector>
inline ElementwisePermutation &operator=(const SharedVector<Share, argEVector, Engine> &other)

Assignment operator from a SharedVector The second template argument is named argEVector to distinguish it from the EVector that this class is templated by. This function copies the underlying data to a 32 bit SharedVector, which requires that the input vector has a bitwidth <= 32.

Note: does not affect the engine because assignmnent concerns values only.

Parameters:

other – The SharedVector to copy.

inline size_t size()

Gets the size of the underlying SharedVector.

inline ASharedPerm getASharedPerm()

Gets the underlying SharedVector as an ASharedVector.

inline BSharedPerm getBSharedPerm()

Gets the underlying SharedVector as an BSharedVector.

inline cdough::Encoding getEncoding()

Gets the encoding type of the underlying SharedVector.

inline Vector<int> open()

Open the underlying SharedVector.

inline ElementwisePermutation shuffle()

Shuffle the underlying SharedVector

Returns:

The shuffled permutation.

inline ElementwisePermutation reverse()

Reverse the direction of the permutation.

Each element (with some value x) will now become size - 1 - x. Multiply by -1 then add (size - 1).

Returns:

A permutation such that when applied to a vector, the permuted vector will be the reverse of the vector permuted under the original permutation.

inline ElementwisePermutation invert()

Find the inverse of the permutation (different than applying an inverse permutation).

Returns:

The inverse of the permutation.

inline ElementwisePermutation b2a()

Convert a binary shared ElementwisePermutation to an arithmetic shared ElementwisePermutation

.

Apply a random permutation, open the result, secret share it arithmetically, then unapply the random permutation.

Returns:

An ElementwisePermutation with an arithmetic sharing of the input permutation.

inline ElementwisePermutation negate()

Convert a permutation with negative location values to one with positive location values.

The input is has values from -1 to -n. We want to negate them (so 1 to n) and then shift down by 1 (0 to n-1).

Returns:

An ElementwisePermutation with the correct range of values.

Public Members

SharedPerm sharedVector

Private Types

using SharedPerm = SharedVector<int, cdough::EVector<int, EVector::replicationNumber>, Engine>
using ASharedPerm = ASharedVector<int, cdough::EVector<int, EVector::replicationNumber>, Engine>
using BSharedPerm = BSharedVector<int, cdough::EVector<int, EVector::replicationNumber>, Engine>

Tabular

template<typename Share, typename EVector, typename Engine>
class SharedColumn : public cdough::relational::EncodedColumn

A secret-shared column with share and container types.

Template Parameters:
  • Share – Share data type.

  • EVector – Container data type.

  • Engine – Secure computation engine type.

Public Functions

inline explicit SharedColumn(size_t _size, const Encoding &eType)

Allocates a shared column with the given encoding and initializes it with zeros.

Parameters:
  • _size – The column’s size in number of elements.

  • eType – The column’s encoding (e.g., A-Shared, B-Shared, etc.).

inline explicit SharedColumn(std::unique_ptr<EncodedVector> &&_shares, const std::string &col_name = "")

Move constructor from an encoded vector.

Parameters:
  • _shares – The encoded vector whose contents will be moved to the new column.

  • col_name – new name for the column

inline SharedColumn(std::unique_ptr<EncodedColumn> &&other)

Move constructor from an encoded column.

Parameters:

other – The encoded column whose contents will be moved to the new column.

inline virtual SharedColumn &operator=(std::unique_ptr<EncodedColumn> &&other) override

Move assignment operator (shallow move) from an encoded column.

Parameters:

other – The encoded column whose contents will be moved to the new column.

inline virtual void zero() override

Zero out this column.

inline virtual ~SharedColumn()
inline virtual size_t size() const override
Returns:

The column’s size in number of elements.

inline virtual size_t getPrecision() const override
Returns:

The column’s fixed-point precision (from the underlying encoded vector).

inline virtual std::unique_ptr<EncodedColumn> deepcopy() override

Make a deep copy of this column. Deep-copies the underlying vector.

Returns:

std::unique_ptr<EncodedColumn>

inline virtual std::unique_ptr<EncodedColumn> ltz() override

Elementwise less-than-zero of a BShared column. Will cause an assertion error if called on an AShared column.

Returns:

std::unique_ptr<EncodedColumn>

inline virtual std::unique_ptr<EncodedColumn> operator+(const EncodedColumn &other) const override

Boolean adder or Arithmetic add/subtract.

inline virtual std::unique_ptr<EncodedColumn> operator-(const EncodedColumn &other) const override

Elementwise secure arithmetic subtraction.

Parameters:

other – The second operand of subtraction.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise subtractions.

inline virtual std::unique_ptr<EncodedColumn> operator+(int64_t other) const override

Boolean adder or Arithmetic add/subtract with constant.

inline virtual std::unique_ptr<EncodedColumn> operator-(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator/(const EncodedColumn &other) const override

Private division between two columns. The division algorithm only supports BShared inputs, so automatically convert (by calling a2b) if any input is AShared. Output will always be BShared.

Parameters:

other

Returns:

std::unique_ptr<EncodedColumn> encoded as a BShared column

inline virtual std::unique_ptr<EncodedColumn> operator*(const EncodedColumn &other) const override

Column * Column.

inline virtual std::unique_ptr<EncodedColumn> operator*(int64_t other) const override

Column * Constant.

inline virtual std::unique_ptr<EncodedColumn> operator-() const override

Unary negation.

inline virtual std::unique_ptr<EncodedColumn> operator/(int64_t y) const override

Public division with constant.

inline virtual EncodedColumn &operator+=(const EncodedColumn &other) override

Binary assignment operators over AShared columns.

inline virtual EncodedColumn &operator-=(const EncodedColumn &other) override
inline virtual EncodedColumn &operator*=(const EncodedColumn &other) override
inline EncodedColumn &operator+=(const std::unique_ptr<EncodedColumn> &&other)
inline EncodedColumn &operator-=(const std::unique_ptr<EncodedColumn> &&other)
inline EncodedColumn &operator*=(const std::unique_ptr<EncodedColumn> &&other)
inline virtual std::unique_ptr<EncodedColumn> operator&(const EncodedColumn &other) const override

Binary operators between BShared columns.

inline virtual std::unique_ptr<EncodedColumn> operator&&(const EncodedColumn &other) const override
inline virtual std::unique_ptr<EncodedColumn> operator|(const EncodedColumn &other) const override

Elementwise secure bitwise OR.

Parameters:

other – The second operand of OR.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise ORs.

inline virtual std::unique_ptr<EncodedColumn> operator||(const EncodedColumn &other) const override
inline virtual std::unique_ptr<EncodedColumn> operator^(const EncodedColumn &other) const override

Elementwise secure bitwise XOR.

Parameters:

other – The second operand of XOR.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise XORs.

inline virtual EncodedColumn &operator&=(const EncodedColumn &other) override

Assignment operators between BShared columns.

inline virtual EncodedColumn &operator|=(const EncodedColumn &other) override
inline virtual EncodedColumn &operator^=(const EncodedColumn &other) override
inline EncodedColumn &operator&=(const std::unique_ptr<EncodedColumn> &&other)
inline EncodedColumn &operator|=(const std::unique_ptr<EncodedColumn> &&other)
inline EncodedColumn &operator^=(const std::unique_ptr<EncodedColumn> &&other)
inline virtual std::unique_ptr<EncodedColumn> operator&(int64_t other) const override

Binary operators with an element.

inline virtual std::unique_ptr<EncodedColumn> operator^(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator|(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator~() const override

Unary operators on BShared columns.

inline virtual std::unique_ptr<EncodedColumn> operator!() const override

Elementwise secure boolean negation.

Returns:

A unique pointer to an EncodedColumn with all results of this EncodedColumn negated.

inline virtual std::unique_ptr<EncodedColumn> operator>>(int64_t y) const override

Shift operators on BShared columns.

inline virtual std::unique_ptr<EncodedColumn> operator<<(int64_t y) const override

Elementwise shifts.

Parameters:

y – shift amount

Returns:

std::unique_ptr<EncodedColumn>

inline virtual std::unique_ptr<EncodedColumn> operator>(const EncodedColumn &other) const override

Elementwise secure greater-than.

Parameters:

other – The second operand of greater-than.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-than comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator<(const EncodedColumn &other) const override

Elementwise secure less-than.

Parameters:

other – The second operand of less-than.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-than comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator>=(const EncodedColumn &other) const override

Elementwise secure greater-or-equal.

Parameters:

other – The second operand of greater-or-equal.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-or-equal comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator<=(const EncodedColumn &other) const override

Elementwise secure less-or-equal.

Parameters:

other – The second operand of less-or-equal.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-or-equal comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator==(const EncodedColumn &other) const override

Elementwise secure equality.

Parameters:

other – The second operand of equality.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise equality comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator!=(const EncodedColumn &other) const override

Elementwise secure inequality.

Parameters:

other – The second operand of inequality.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise inequality comparisons.

inline virtual std::unique_ptr<EncodedColumn> operator>(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator<(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator>=(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator<=(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator==(int64_t other) const override
inline virtual std::unique_ptr<EncodedColumn> operator!=(int64_t other) const override

Public Static Attributes

static const int replicationNumber = EVector::replicationNumber

Protected Functions

inline virtual void resize(size_t n) override
inline virtual void tail(size_t n) override
inline void concatenate(SVector &other)

Private Types

using SVector = SharedVector<Share, EVector, Engine>

Friends

friend class EncodedTable
template<typename Share, typename SharedColumn, typename A, typename B, typename EncodedVector, typename DataTable>
class EncodedTable

An EncodedTable is a relational table that contains encoded data organized in columns. cdough users can perform vectorized secure operations directly on table columns via a Pandas-like interface, as shown below:

// cdough program (executed by an untrusted party)
t["col3"] = t["col1"] * t["col2"];

The above line performs a secure elementwise multiplication between two columns col1 and col2 in table t and stores the result in a third column col3.

Template Parameters:
  • SharedColumn – Secret-shared column type.

  • A – A-shared vector type.

  • B – B-shared vector type.

  • EncodedVector – Encoded vector type.

  • DataTable – Plaintext table type.

Public Types

using Engine = typename A::EngineType

Public Functions

inline EncodedTable(const std::string &_tableName, const std::vector<std::string> &_columns, int _rows, Engine &eng)

Constructs a table and initializes it with zeros.

Parameters:
  • _tableName – The name of the table.

  • _columns – The column names.

  • _rows – The number of rows to allocate.

  • eng – The engine to use for this table.

inline EncodedTable(std::vector<std::shared_ptr<EncodedColumn>> &&contents, Engine &eng)

Constructs a table from encoded columns.

Parameters:

contents – The table columns.

inline EncodedTable(const EncodedTable &other)

Copy constructor.

inline EncodedTable &operator=(const EncodedTable &other)

Copy assignment operator.

inline EncodedTable &operator=(EncodedTable &&other) noexcept

Move assignment operator.

inline void configureValid()

Configured the valid column. If it does not exist, create it. If it does exist, re-initialize and make all rows valid.

template<typename T>
inline void filter(T &&e)

Update the valid column based on the value of a provided column or expression (i.e., bitwise-and the input with valid)

This accepts either a column, or a unique pointer to a column.

Template Parameters:

T

Parameters:

e – the expression to filter on. Rows evaluating to a boolean true will remain valid; those evaluating to a boolean false will be marked invalid.

template<typename T>
inline void filter(std::unique_ptr<T> e)

Update the valid column based on the value of an expression, passed as a unique pointer. Compound operators are only supported on columns, not pointers to columns, so dereference.

Template Parameters:

T

Parameters:

e

inline B *getValidVector()

Get the valid vector.

Returns:

BSharedVector *

inline EncodedColumn &operator[](const std::string &name)

Returns a mutable reference to the column with the given name.

Parameters:

name – The name of the column.

Returns:

A reference to the column (throws an error if the column is not found).

inline B asBSharedVector(const std::string &name)

Get column name as a BSharedVector.

Parameters:

name

Returns:

B

inline A asASharedVector(const std::string &name)

Get column name as an ASharedVector.

Parameters:

name

Returns:

A

inline B::SharedVector_t asSharedVector(const std::string &name)

Get column name as an untyped SharedVector.

Parameters:

name

Returns:

B::SharedVector_t

inline void inputSecretShares(const std::string &columnName, const std::string &inputFile)

Reads secret shares for a column from a file. The file contain one line for each element in the column. Each line contains the replicated secret shares separated by a space. Note: this function does not affect valid bit.

Parameters:
  • columnName – The name of the column.

  • inputFile – The file containing the secret shares.

inline void inputCSVTableData(const std::string &_file_path, int _input_party)

Reads secret shares for a column from a file. The file contains a csv table with the data.

Parameters:
  • _file_path – The file containing the table data.

  • _input_party – The party that has the file.

inline void inputCSVTableSecretShares(const std::string &_file_path)

Reads table secret shares from a csv file. Each column is secret shared using columns names as follows: [column_name]_[replication_index]. For example, column “A” with replication index 0 is secret shared using column name “[A]_0” and same for “[A]_1”, “[A]_2”, etc. depending on the replication number for the protocol. Note: this function updates the valid bit so that unread rows are assigned zero.

Parameters:

_file_path – The file containing the table secret shares.

inline void outputCSVTableSecretShares(const std::string &_file_path)

Outputs the table secret shares to a csv file. Each column is outputted using columns names as follows: [column_name]_[replication_index]. For example, column “A” with replication index 0 is outputted using column name “[A]_0” and same for “[A]_1”, “[A]_2”, etc. depending on the replication number for the protocol.

TODO: create directory if does not exist

Parameters:

_file_path – The file to write the table secret shares to.

inline void outputSecretShares(const std::string &columnName, const std::string &outputFile)

Output the secret shares of a column to a file. The file will contain one line for each element in the column. Each line will contain the replicated secret shares separated by a space.

Parameters:
  • columnName – The name of the column.

  • outputFile – The file to write the secret shares to.

inline void finalize(bool do_shuffle = true)

Shuffle the table and mask invalid rows. Call finalize before revealing the outputs to untrusted parties.

Parameters:

do_shuffle – whether to shuffle the table before revealing. default true. If not shuffled (or sorted in a known order), inference attacks may be possible.

inline DataTable open()

Opens the encoded table to all computing parties.

Returns:

The opened (plaintext) table.

inline LabeledDataTable open_with_schema(bool remove_invalid = true)

Opens the encoded table to all computing parties and includes the schema.

Returns:

A LabeledDataTable pair (a.k.a. pair<DataTable, vector<string>>) Access the column-major data via the first element of the pair, and the schema via the second. Both will be in the same order

inline void addColumns(const std::vector<std::string> &columns_, int rows_)

Creates table columns based on a schema.

Parameters:
  • columns_ – The schema.

  • rows_ – The column length.

inline void addColumns(const std::vector<std::string> &columns_)

Create table columns given a list of names. All rows will have the same length as the current table.

Parameters:

columns_

inline void addColumn(const std::string &column, const int rows_, std::optional<int> precision = std::nullopt)

Allocates a column of a given size and initializes it with zeros.

The default column encoding is A-shared. To create a B-shared column, you must enclose the column’s name with square brackets, i.e. column=[name].

Parameters:
  • column – The name of the column to allocate.

  • rows_ – The column size in number of elements.

  • precision – Fixed-point precision (default 0).

inline void addColumn(const std::string &column)

Add a single column with the given name, with the default number of rows.

Parameters:

column

inline void deleteColumns(const std::vector<std::string> cols)

Remove provided columns from the table.

Parameters:

cols – Vector of column names to remove

inline void project(const std::vector<std::string> cols)

Projection operation, i.e. only keep columns in the provided list.

Parameters:

cols – Vector of column names to keep

inline std::string name() const
Returns:

The table name.

inline size_t size() const
Returns:

The table cardinality.

inline std::map<std::string, std::shared_ptr<EncodedColumn>> getSchema() const

Get the schema.

Returns:

std::map<std::string, std::shared_ptr<EncodedColumn>>

inline std::vector<std::string> getColumnNames()

Get the column names.

Returns:

std::vector<std::string>

inline SortInput_t prepare_sort_input(const std::vector<std::pair<std::string, SortOrder>> &spec, const std::vector<std::string> &to_be_sorted_columns, const SortingProtocol protocol = DEFAULT_SORT_PROTO)

Prepare the sorting input for the given specification.

Parameters:
  • spec – The names of the columns to sort by along with a sorting direction.

  • to_be_sorted_columns – The non-sort columns to be sorted according to the sort columns.

  • protocol – The sorting protocol to use.

Returns:

SortInput_t The sorting input to be passed to table_sort.

inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec)

Sorts this table in place given a specification of columns and sorting directions using the default sorting protocol.

Parameters:

spec – The names of the columns to sort by along with a sorting direction.

Returns:

EncodedTable&

inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec, const SortingProtocol protocol)

Sorts this table in place given a specification of columns and sorting directions.

Parameters:
  • spec – The names of the columns to sort by along with a sorting direction.

  • protocol – The sorting protocol to use.

Returns:

EncodedTable&

inline EncodedTable &sort(const std::vector<std::string> columns, SortOrder allOrder = ASC)

Sort all given columns in the same direction using the default sorting protocol.

Parameters:
  • columns – The list of BSharedVColumns to sort on.

  • allOrder – The direction to sort all sort columns.

Returns:

EncodedTable&

inline EncodedTable &sort(const std::vector<std::string> columns, SortOrder allOrder, const SortingProtocol protocol)

Sort all given columns in the same direction.

Parameters:
  • columns – The list of BSharedVColumns to sort on.

  • allOrder – The direction to sort all sort columns.

  • protocol – The sorting protocol to use.

Returns:

EncodedTable&

inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec, const std::vector<std::string> &to_be_sorted_columns, const SortingProtocol protocol = DEFAULT_SORT_PROTO)

Sort the table given a specification.

Parameters:
  • spec – The names of the columns to sort by along with a sorting direction.

  • to_be_sorted_columns – The non-sort columns to be sorted according to the sort columns.

  • protocol – The sorting protocol to use.

Returns:

EncodedTable&

inline std::pair<int, int> get_perm_counts(const std::vector<std::pair<std::string, SortOrder>> spec, const SortingProtocol protocol = DEFAULT_SORT_PROTO)

Get the permutation counts for the given specification.

Parameters:

spec – The specification of the columns to sort by along with a sorting direction.

Returns:

The number of permutations and pairs required.

inline EncodedTable &shuffle()

Shuffles each column according to the same permutation.

inline EncodedTable &convert_a2b(const std::string &input_a, const std::string &output_b)

Convert column input_a to binary and store the result in output_b

Parameters:
  • input_a

  • output_b

Returns:

EncodedTable&

inline EncodedTable &convert_b2a_bit(const std::string &input_b, const std::string &output_a)

Convert the single-bit column input_b to arithmetic and store the result in output_a

Parameters:
  • input_b

  • output_a

Returns:

EncodedTable&

inline EncodedTable &aggregate(const std::vector<std::string> &_keys, AggregationSpec agg_spec, AggregationOptions opt = {})

perform odd-even aggregation.

Parameters:
  • _keys – column names to perform aggregation over (i.e., group by)

  • agg_spec – the aggregation specification, a vector of tuples of (input, output, function).

  • opt – See AggregationOptions

Returns:

EncodedTable&

inline EncodedTable &distinct(const std::vector<std::string> &_keys, const std::string &_res)

Distinct operation on provided columns. Requires equivalent rows to be adjacent to be considered for the distinct.

Parameters:
  • _keys – Column names on which to run distinct

  • _res – Column name to mark the result

Returns:

EncodedTable&

inline EncodedTable &distinct(const std::vector<std::string> &_keys)

Single-argument wrapper around the base distinct operation. Performs other operations required for the distinct to work correctly.

Parameters:

_keys – Column names on which to run distinct

Returns:

EncodedTable&

inline EncodedTable &tumbling_window(const std::string &_time_a, const Share &window_size, const std::string &_res)

Compute a tumbling window on the table.

Parameters:
  • _time_a

  • window_size

  • _res

Returns:

EncodedTable&

inline EncodedTable &gap_session_window(const std::vector<std::string> &_keys, const std::string &_time_a, const std::string &_time_b, const std::string &_window_id, const Share &_gap, const bool &_do_sorting = true)

Compute a gap session window on the table.

Parameters:
  • _keys

  • _time_a

  • _time_b

  • _window_id

  • _gap

  • _do_sorting

Returns:

EncodedTable&

inline EncodedTable &threshold_session_window(const std::vector<std::string> &_keys, const std::string &_function_res, const std::string &_time_b, const std::string &_window_id, const Share &_threshold, const bool _do_sorting = true, const bool _mark_valid = true)

Compute a threshold session window on the table.

Parameters:
  • _keys

  • _function_res

  • _time_b

  • _window_id

  • _threshold

  • _do_sorting

  • _mark_valid

Returns:

EncodedTable&

inline void prefix_sum(std::string key)

Compute an (arithmetic) prefix sum on the column key. NOTE: this ignores the valid vector, so may include invalid rows in the prefix sum. Only call this function if all rows are guaranteed to be valid, or invalid rows have already been zeroed out.

Parameters:

key

inline EncodedTable &zero(const std::vector<std::string> &keys)

Zero out the specified columns.

Parameters:

keys

Returns:

EncodedTable&

inline void head(size_t n)

Resize this table to have n rows. Warn if n is larger than the current size.

NOTE: this does not create a copy. For that, use deepcopy first.

Parameters:

n

inline void tail(const size_t n)

Resize this table to only have its last n rows. Warn if n is larger than the current size.

NOTE: this does not create a copy. For that, use deepcopy first.

Parameters:

n

inline void cut(size_t start, size_t end)

Destructively resize this table to only have rows in the range [start, end).

NOTE: this modifies the table in place. For a non-destructive version, use deepcopy first.

Parameters:
  • start – Start index (inclusive)

  • end – End index (exclusive)

inline void resize(size_t n)

Resize this table to have n rows. If n is larger than the current size, extend the table with invalid rows.

Parameters:

n

inline void pad_power_of_two(Share pad_value = 0)

Resize this table to the next power-of-two size. Required for aggregation, bitonic sort / merge.

By default, just resize the table, setting all padded values to 0. However, can optionally pad with a specified value; this is necessary for e.g. bitonic merge.

inline void deleteTable()

Delete the table. Memory will be released; it cannot be used again.

Used in larger queries where a table is no longer needed. Preferably, handle this automatically using scoping.

inline void renameColumn(std::string old_name, std::string new_name)

Rename a column in the EncodedTable.

This function allows you to change the name of an existing column in the table’s schema. It checks for the existence of the old column name and ensures that the new column name does not already exist in the schema.

Usage:

EncodedTable table(...);
table.renameColumn("old_column_name", "new_column_name");

Parameters:
  • old_name – The current name of the column to be renamed.

  • new_name – The new name to assign to the column.

Throws:
  • std::runtime_error – if the old column name does not exist.

  • std::runtime_error – if the new column name already exists.

inline EncodedTable deepcopy()

Deep copy the table. Useful if you want to make changes to a table but also maintain the original data.

inline EncodedTable concatenate(EncodedTable &other, bool power_of_two = false)

concatenate two tables by appending. Rows from other are placed below those from the current table. Shared columns (i.e., those with the same column name) are merged. An additional column, [~TABLE_ID], will be added to denote which original table a given row came from.

A new table will be created and returned; the existing tables will be unaffected.

If columns with the same name exist in both tables, but are not join keys, one of them should be renamed to prevent conflicts.

Parameters:
  • other – the table to append

  • power_of_two – whether to add the table out to the next power of two

Returns:

EncodedTable&

EncodedTable inner_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})

Inner join.

Parameters:
  • right

  • keys

  • agg_spec

  • opt

Returns:

TABLE_T

EncodedTable left_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
Parameters:
  • right

  • keys

  • agg_spec

  • opt

Returns:

TABLE_T

EncodedTable right_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
Parameters:
  • right

  • keys

  • agg_spec

  • opt

Returns:

TABLE_T

EncodedTable full_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
Parameters:
  • right

  • keys

  • agg_spec

  • opt

Returns:

TABLE_T

EncodedTable semi_join(EncodedTable &right, std::vector<std::string> keys)

Semi-join between this table and right. Under the hood, performs right.inner_join(this). See the paper for more details on why this is correct.

Parameters:
  • right

  • keys

Returns:

TABLE_T

EncodedTable anti_join(EncodedTable &right, std::vector<std::string> keys)

Anti-join between this table and right. Under the hood, perms right.right_outer_join(this), along with some special handling of the valid bit. See the paper for more details on why this is correct.

Parameters:
  • right

  • keys

Returns:

TABLE_T

EncodedTable uu_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {}, const SortingProtocol protocol = DEFAULT_SORT_PROTO)

Unique key inner join. Execute a more optimized algorithm which only works if both tables have unique (compound) keys. Under oblivious compute, this condition of course cannot be checked, so it is the responsibility of the developer to verify application of this function is appropriate. Calling uu_join on tables with non-unique keys will return incorrect results.

This effectively performs a private set intersection over keys.

Parameters:
  • right

  • keys

  • agg_spec – Aggregation specification used for listing columns to copy from left table to output.

  • opt – aggregation options

  • protocol – which sorting protocol to use

Returns:

TABLE_T

EncodedTable cartesian_join(EncodedTable &right, std::string key)

Perform a Cartesian product (quadratic) join between this and right. Used for benchmarking; for most applications, use inner_join. All columns are copied from both tables. A warning will be printed if duplicate columns exist. Columns from the left table take precedence.

This function only supports a join on a single column. The VALID bit is automatically updated based on the results of the join. The output table will have exactly L.size() * R.size() rows. No constraints are placed on the join keys.

In general, this method is functionally equivalent to

L.inner_join(right, { key }, ...)

assuming the only aggregations are copy<> calls.

Warning. The resulting intermediate table may be too large to fit inside a standard C++ vector. If this happens, the system will throw an exception of type std::length_error.

Parameters:
  • right

  • key

Returns:

EncodedTable

inline EncodedTable &extend_lsb(const std::string &_b_col)

Extend the LSB of a column. All other bits are ignored. A value ending with a binary 1 will become all 1s; namely, -1 for signed types. values ending with a 0 will become 0. This function should be used to convert boolean 0/1 values into bitmasks, for selectively modifying certain columns.

However, for actually hiding of invalid values, see mask, above, to set those columns to the table-defined masking value.

Parameters:

_b_col – Column name to extend LSB for.

Returns:

EncodedTable&

inline EncodedTable &mask()

Mask all columns using the VALID column.

Returns:

EncodedTable&

Public Members

Engine &engine
std::string tableName

Name of this table. Used for output and organization.

Public Static Functions

static inline bool isReserved(const std::string name)

Checks if a column is reserved/internal or not.

Returns:

bool

static inline bool isBShared(const std::string name)

Checks if a column with name name

contains boolean shares.

NOTE: Names of columns that include boolean shares are within square brackets, i.e.,

[column_name].

Parameters:

name – The name of the column.

Returns:

True if the column is B-shared, False otherwise.

static inline Vector<Share> get_column(std::pair<DataTable, std::vector<std::string>> table, std::string c)

Given an opened, labeled table, return the associated column. NOTE: Once we replace LabeledDataTable with a better-implemented class this can go away.

We need this to be a member function because it needs to know the correct template arguments for DataTable and Share.

Given an opened, labeled table, return the associated column. We need this to be a member function because it needs to know the correct template arguments for DataTable and Share.

TODO: Replace LabeledDataTable with a better-implemented class so this can go away.

Parameters:
  • table

  • c – column name

Returns:

* Vector<Share>

Private Types

using LabeledDataTable = std::pair<DataTable, std::vector<std::string>>
using AggregationSpec = std::vector<std::tuple<std::string, std::string, AggregationSelector<A, B>>>
using uniqA = std::unique_ptr<A>
using uniqB = std::unique_ptr<B>
using __EVector = typename Engine::template AInnerContainer<Share>
using SortInput_t = SortInput<Share, __EVector, Engine>

Private Functions

inline EncodedTable &mask(const std::string &mask_column_name, const std::vector<std::string> &keys)

Mask the contents of multiple columns using the type’s mask value (usually the maximum value). This is useful for obliviously hiding rows that are not selected for output by some prior process.

Rows which have a 1 in the mask column will remain untouched. Rows which have a 0 in the mask column will be set to MASK_VALUE.

Will NOT mask the mask-column itself.

Parameters:
  • mask_column_name – the column to use as the mask

  • keys – which other columns to mask

Returns:

EncodedTable&

inline EncodedTable &mask(const std::string &mask_column_name)

Mask all columns (except the mask itself)

Parameters:

mask_column_name

Returns:

EncodedTable&

EncodedTable _join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec, JoinOptions opt)

Internal join implementation.

Arbitrary join between this table and right. assumes primary key-foreign key relationship, but does not enforce.

Used to implement EncodedTable::inner_join, EncodedTable::left_outer_join, EncodedTable::right_outer_join, EncodedTable::full_outer_join, EncodedTable::semi_join, and EncodedTable::anti_join

Parameters:
  • right – the other table

  • keys – the set of key(s) to join on, with a primary (this table) / foreign key (right table) relationship

  • agg_spec – an aggregation specification, a vector of tuples consisting of {input-column, output-column, aggregation-type}

  • opt – See JoinOptions

Returns:

TABLE_T

template<typename T>
inline void copy_column_typed(EncodedTable &t, std::string from, std::string to, VectorSizeType start_index = 0)

Copy column from table t into this table. This table’s schema is assumed to already contain a column of the correct name.

Template Parameters:

T – the type of the vector ASharedVector or BSharedVector

Parameters:
  • t – source table

  • from – the table to copy from

  • to – column name to copy

  • start_index – the row in this table where the copied column should be placed (default 0)

inline void copy_column(EncodedTable &t, std::string from, std::string to, VectorSizeType start_index = 0)

Untyped copy column - see copy_column_typed<T>

Parameters:
  • t

  • from

  • to

  • start_index

inline void copy_column(EncodedTable &t, std::string name, VectorSizeType start_index = 0)

Copy column name from table t into this table using the same name.

Parameters:
  • t

  • name

  • start_index

Private Members

std::map<std::string, std::shared_ptr<EncodedColumn>> schema
size_t rows
Share MASK_VALUE = std::numeric_limits<Share>::max()
bool deleted = false

Utilities & Base Classes

class EncodedVector

A EncodedVector is the main programming abstraction in cdough. All secure operators are applied to encoded vectors, i.e., they take one or more encoded vectors as input and generate one or more encoded vectors as output. cdough computing parties perform secure operations on their encoded vectors as if they were performing plaintext operations on the original (secret) vectors. For example, given two secret vectors v1 and v2, cdough parties can execute the elementwise addition of the secret vectors by simply running v1 + v2 using their local encoded vectors. This way, the cdough program looks identical to the respective plaintext program, as shown below:

Plaintext program (not secure)

  // Executed by a trusted party
  auto w = v1 + v2;   // These are C++ vectors and '+' is the elementwise plaintext addition
cdough program (secure)
  // Executed by an untrusted party
  auto w = v1 + v2;   // These are EncodedVectors and '+' is the elementwise secure addition

Subclassed by cdough::SharedVector< Share, EVector, Engine >, cdough::SharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::SharedVector< T, E, Engine >, cdough::SharedVector< T, Container, Engine >

Public Functions

inline EncodedVector(const Encoding &eType)

Constructor

Parameters:

eType – The vector’s encoding (e.g., A-shared, B-shared, etc.)

inline virtual ~EncodedVector()
virtual VectorSizeType size() const = 0
virtual void setPrecision(const int fixed_point_precision) = 0

Gets the fixed-point precision. Virtual to let subclasses override.

virtual size_t getPrecision() const = 0

Gets the fixed-point precision. Virtual to let subclasses override.

Public Members

Encoding encoding

The vector’s encoding (e.g., A-shared, B-shared, etc.)

Friends

friend class EncodedColumn
class EncodedColumn

An encoded table column that supports vectorized secure operations. Internally stores an encoded vector, and passes all operations down to that vector.

Subclassed by cdough::relational::SharedColumn< T, GenericInnerContainer< T >, RunTime >, cdough::relational::SharedColumn< Share, EVector, Engine >

Public Functions

inline virtual ~EncodedColumn()
virtual size_t size() const = 0
Returns:

The column’s size in number of elements.

virtual size_t getPrecision() const = 0

Gets the fixed-point precision. Virtual to let subclasses override.

virtual void zero() = 0
virtual std::unique_ptr<EncodedColumn> deepcopy() = 0
virtual std::unique_ptr<EncodedColumn> ltz() = 0
virtual std::unique_ptr<EncodedColumn> operator+(const EncodedColumn &other) const = 0

Elementwise secure arithmetic addition.

Parameters:

other – The second operand of addition.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise additions.

virtual std::unique_ptr<EncodedColumn> operator+(int64_t other) const = 0
virtual EncodedColumn &operator+=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator-(const EncodedColumn &other) const = 0

Elementwise secure arithmetic subtraction.

Parameters:

other – The second operand of subtraction.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise subtractions.

virtual std::unique_ptr<EncodedColumn> operator-(int64_t other) const = 0
virtual EncodedColumn &operator-=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator-() const = 0

Elementwise secure arithmetic negation.

Returns:

A unique pointer to an EncodedColumn with all elements of this EncodedColumn negated.

virtual std::unique_ptr<EncodedColumn> operator*(const EncodedColumn &other) const = 0

Elementwise secure arithmetic multiplication.

Parameters:

other – The second operand of multiplication.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise multiplications.

virtual std::unique_ptr<EncodedColumn> operator*(int64_t other) const = 0
virtual EncodedColumn &operator*=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator/(const EncodedColumn &other) const = 0

Elementwise secure schoolbook (binary) division.

Parameters:

other

Returns:

std::unique_ptr<EncodedColumn>

virtual std::unique_ptr<EncodedColumn> operator/(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator^(const EncodedColumn &other) const = 0

Elementwise secure bitwise XOR.

Parameters:

other – The second operand of XOR.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise XORs.

virtual std::unique_ptr<EncodedColumn> operator^(int64_t other) const = 0
virtual EncodedColumn &operator^=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator&(const EncodedColumn &other) const = 0

Elementwise secure bitwise AND.

Parameters:

other – The second operand of AND.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise ANDs.

virtual std::unique_ptr<EncodedColumn> operator&(int64_t other) const = 0
virtual EncodedColumn &operator&=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator&&(const EncodedColumn &other) const = 0
virtual std::unique_ptr<EncodedColumn> operator|(const EncodedColumn &other) const = 0

Elementwise secure bitwise OR.

Parameters:

other – The second operand of OR.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise ORs.

virtual std::unique_ptr<EncodedColumn> operator|(int64_t other) const = 0
virtual EncodedColumn &operator|=(const EncodedColumn &other) = 0
virtual std::unique_ptr<EncodedColumn> operator||(const EncodedColumn &other) const = 0
virtual std::unique_ptr<EncodedColumn> operator~() const = 0

Elementwise secure boolean completion.

Returns:

A unique pointer to an EncodedColumn with all elements of this EncodedColumn complemented.

virtual std::unique_ptr<EncodedColumn> operator!() const = 0

Elementwise secure boolean negation.

Returns:

A unique pointer to an EncodedColumn with all results of this EncodedColumn negated.

virtual std::unique_ptr<EncodedColumn> operator<<(int64_t y) const = 0

Elementwise shifts.

Parameters:

y – shift amount

Returns:

std::unique_ptr<EncodedColumn>

virtual std::unique_ptr<EncodedColumn> operator>>(int64_t y) const = 0
virtual std::unique_ptr<EncodedColumn> operator==(const EncodedColumn &other) const = 0

Elementwise secure equality.

Parameters:

other – The second operand of equality.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise equality comparisons.

virtual std::unique_ptr<EncodedColumn> operator==(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator!=(const EncodedColumn &other) const = 0

Elementwise secure inequality.

Parameters:

other – The second operand of inequality.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise inequality comparisons.

virtual std::unique_ptr<EncodedColumn> operator!=(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator>(const EncodedColumn &other) const = 0

Elementwise secure greater-than.

Parameters:

other – The second operand of greater-than.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-than comparisons.

virtual std::unique_ptr<EncodedColumn> operator>(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator>=(const EncodedColumn &other) const = 0

Elementwise secure greater-or-equal.

Parameters:

other – The second operand of greater-or-equal.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-or-equal comparisons.

virtual std::unique_ptr<EncodedColumn> operator>=(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator<(const EncodedColumn &other) const = 0

Elementwise secure less-than.

Parameters:

other – The second operand of less-than.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-than comparisons.

virtual std::unique_ptr<EncodedColumn> operator<(int64_t other) const = 0
virtual std::unique_ptr<EncodedColumn> operator<=(const EncodedColumn &other) const = 0

Elementwise secure less-or-equal.

Parameters:

other – The second operand of less-or-equal.

Returns:

A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-or-equal comparisons.

virtual std::unique_ptr<EncodedColumn> operator<=(int64_t other) const = 0
virtual EncodedColumn &operator=(std::unique_ptr<EncodedColumn> &&other) = 0

Column assignment.

Parameters:

other – The unique pointer to the column whose contents will be moved to this column.

Returns:

A reference to this column after modification.

Public Members

Encoding encoding

The column’s encoding (e.g., A-shared, B-shared, etc.)

std::unique_ptr<EncodedVector> contents

The column’s contents (i.e., an encoded vector).

std::string name

The column’s name

Protected Functions

virtual void tail(size_t) = 0
virtual void resize(size_t) = 0

Friends

friend class EncodedTable
namespace cdough

Enums

enum Encoding

Vector encoding types.

Values:

enumerator AShared
enumerator BShared
namespace cdough
template<typename T, std::random_access_iterator D, std::random_access_iterator M>
class MappedIterator
#include <mapped_iterator.h>

Public Types

using difference_type = std::ptrdiff_t
using value_type = T

Public Functions

inline MappedIterator()
inline MappedIterator(std::vector<T>::iterator _dataIter, std::vector<VectorSizeType>::iterator _mappingIter)
inline MappedIterator(std::vector<T>::iterator _dataIter)
inline T &operator*() const
inline T &operator[](difference_type i) const
inline MappedIterator &operator++()
inline MappedIterator operator++(int)
inline MappedIterator &operator--()
inline MappedIterator operator--(int)
inline MappedIterator &operator+=(difference_type n)
inline MappedIterator operator+(difference_type n) const
inline MappedIterator &operator-=(difference_type n)
inline MappedIterator operator-(difference_type n) const
inline difference_type operator-(const MappedIterator &other) const
inline bool operator<(const MappedIterator &other) const
inline bool operator>(const MappedIterator &other) const
inline bool operator<=(const MappedIterator &other) const
inline bool operator>=(const MappedIterator &other) const
inline bool operator==(const MappedIterator &other) const

Private Members

D dataIter
std::optional<M> mappingIter

Friends

inline friend MappedIterator operator+(difference_type n, const MappedIterator &other)

Defines

define_binary_vector_op(_op_)
define_unary_vector_op(_op_)
define_binary_vector_element_op(_op_)
define_binary_vector_assignment_op(_op_)
namespace cdough

Functions

template<typename T>
static inline T getBit(const T &share, int bitIndex)

Extracts the bit at bitIndex from the given element. Use dedicated hardware instruction if available.

Parameters:
  • share – The vector element whose bit we want to extract.

  • bitIndex – The zero-based index (0 is the LSB).

Returns:

The extracted bit as a single-bit T element.

template<typename T>
static inline void setBit(T &share, const T &bit, int bitIndex)

Sets the bit at bitIndex in element share equal to the LSB of element bit.

Parameters:
  • share – The element whose bit we want to update.

  • bit – The element whose LSB must be copied into share.

  • bitIndex – The zero-based index (0 is the LSB) of the bit to be updated in element share.

template<typename T>
static inline void clrBit(T &share, int bitIndex)

Clear the bit at position bitIndex (i.e., set it to zero)

Template Parameters:

T

Parameters:
  • share

  • bitIndex

template<typename T>
static inline void setBitValue(T &share, const T &value, int bitIndex)

Set the the bit at the given index to the value provided.

Template Parameters:

T

Parameters:
  • share – Vector element to modify

  • value – binary value to set the specified bit to

  • bitIndex – which bit to modify

template<typename T>
static inline void setBitMask(T &share, const bool &value, const std::make_unsigned_t<T> &mask)

Conditionally set bits in share, masked by mask, based on the boolean value flag.

Optimized version from https://graphics.stanford.edu/~seander/bithacks.html

It’s not immediately clear to me that this is faster, but perhaps better on certain processors, or with certain optimizations enabled.

Parameters:
  • share – the element to operate on

  • value – whether the bits should be set or cleared

  • mask – which bits to modify

template<typename Share>
static Vector<Share> compare_rows(const std::vector<Vector<Share>*> &x_vec, const std::vector<Vector<Share>*> &y_vec, const std::vector<bool> &inverse)

Same as BSharedVector::compare_rows() but works with plaintext data. Used for testing.

Compares two MxN arrays row-wise by applying M greater-than comparisons on N keys.

NOTE: The i-th row, let l, from the left array is greater than the i-th row, let r, from the right array if l’s first key is greater than r’s first key, or the first keys are the same and l’s second key is greater than r’s second key, or the first two keys are the same and so forth, for all keys.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • inverse – A vector of N boolean values that denotes the order of comparison per key (if inverse[i]=True, then rows from x_vec and y_vec are swapped in the comparison on the i-th column.

Returns:

A new vector that contains the result bits of the M greater-than comparisons.

template<typename Share>
static void swap(std::vector<Vector<Share>*> &x_vec, std::vector<Vector<Share>*> &y_vec, const Vector<Share> &bits)

Same as BSharedVector::swap() but works with plaintext data. Used for testing.

Swaps rows of two MxN arrays in place using the provided bits.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).

template<typename Share>
static void swap(Vector<Share> &x_vec, Vector<Share> &y_vec, const Vector<Share> &bits)

Same as BSharedVector::swap() but works with plaintext data. Used for testing.

Swaps rows of two MxN arrays in place using the provided bits.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).

template<typename T>
class Vector
#include <class_access_vector.h>

cdough’s wrapper of std::vector<T> that provides vectorized plaintext operations. A mock vector implementation which stores no data and returns nothing (or garbage) for all operations. Most functions do nothing at all, or just compute the appropriate length that their correct equivalent would output. This is useful for testing and profiling, since it is extremely fast and performs no data movement.

Template Parameters:
  • T – The type of elements in the Vector (e.g., int, long, long long, etc.)

  • T – The nominal element type

Public Types

using value_type = T

Public Functions

inline void setPrecision(const int fixed_point_precision)

Sets the fixed-point precision.

Parameters:

fixed_point_precision – - the number of fixed-point fractional bits.

inline size_t getPrecision() const

Gets the fixed-point precision.

inline void matchPrecision(const Vector<T> &other)

Helper that sets this vector’s precision to match another Vector.

Parameters:

other – The Vector whose precision should be copied.

inline size_t total_size() const
Returns:

The total number of elements in the vector.

inline std::vector<T>::iterator begin()

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the first element.

inline std::vector<T>::iterator end()

NOTE: This method is used by the communicator.

Returns:

An iterator pointing to the last element.

inline Vector simple_subset_reference(const int _start_index, const int _step, const int _end_index) const

             This is the generic function in order create a new mapping for this vector.
             Note: that the function does not allocate a new memory location for data.
             Note: the mapping maps from the new index space to the original index space for
data. In other words, composition will not work; new mapping pattern replaces the previous one.

Parameters:
  • _subset_offset – the index of the first element of the original vector to apply the pattern.

  • _subset_step – the index difference between the mapped to elements within each chunks.

  • _subset_included_size – the maximum size of each included chunk.

  • _subset_excluded_size – the maximum size of each excluded chunk. (included and excluded chunks alternate after offset).

  • _subset_direction – the direction of choosing elements (increasing index = 1) (decreasing index = -1).

  • _subset_repetition – number of times to repeat same mapped-to-elements after each other.

  • _subset_cycles – number of times concatenate the whole mapped-to-elements in the new reference.

  • _subset_offset – the index of the first element of the original vector to apply the pattern. (default = 0)

  • _subset_step – the index of the difference between each two included elements. (default = 1)

  • _subset_included_size – the size of the elements on which the pattern is applied. (default = total_size())

Returns:

Vector that points to the same memory location as the new one but different mapping for the indices. Remaps the index space to choose a number of elements of the current vector. Note: returned Vector points to the same memory location.

Returns:

Vector that has different index mapping to the original vector elements.

inline Vector simple_subset_reference(const int _start_index, const int _step) const
inline Vector simple_subset_reference(const int _start_index) const
inline Vector alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const

Applies an alternating pattern to include and exclude elements. It applies the pattern starting with the element with index = _subset_offset. It then keeps alternating elements as included in the pattern of or excluded from the pattern using the _subset_included_size and the _subset_excluded_size for each included or excluded chunk.

Parameters:
  • _subset_offset – the index of the first element to apply the pattern.

  • _subset_step – the difference two each two included elements within the included the chunks.

  • _subset_included_size – the size of a number of elements that we choosing from.

  • _subset_excluded_size – the size of a number of elements that we are totally not choosing.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector reversed_alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
inline Vector repeated_subset_reference(const size_t _subset_repetition) const

Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.

Parameters:

_subset_repetition – the number of times each element is repeated.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector cyclic_subset_reference(const size_t _subset_cycles) const

Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.

Parameters:

_subset_cycles – the number of cycles the new indexing mapping will contain.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector directed_subset_reference(const size_t _subset_direction) const

Applies a new mapping indexing that controls the order in which the elements accessed.

Parameters:

_subset_direction – set to (1) to keep current order or (-1) to reverse the order.

Returns:

Vector that points to the same memory location as the original vector but with different index mapping.

inline Vector simple_bit_compress(size_t start, size_t step, size_t end, size_t repetition) const

This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.

Parameters:
  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline void simple_bit_compress(Vector &res, size_t position) const

simple_bit_compress, optimized for the (i, 1, i, 1) case. This version further operates on a passed vector, rather than returning a new Vector.

Parameters:
  • res – vector to compress into

  • position – single bit position to compress (= start = end)

inline void simple_bit_decompress(const Vector &other, size_t start, size_t step, size_t end, size_t repetition)

Function to reverse the simple_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to be included (lowest significant).

  • step – difference in index between each two consecutive bits.

  • end – index of the last bit bit to be included (most significant)

  • repetition – number of times each bit will be included.

inline void simple_bit_decompress(const Vector &other, const T &position)

Optimized version of simple_bit_compress for the single- position case.

Note: in testing, setBitMask was not noticeably faster than setBitValue

Parameters:
  • other – vector to decompress into this

  • position – the bit position to decompress

inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const

This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that step index difference apart are chosen. If direction is set to 1, picking starts from lowest significant bits. If it is set to -1, picking starts from most significant bits.

Parameters:
  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first.

Returns:

a new Vector that has only the chosen bits in its elements (less size than input).

inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size) const
inline void alternating_bit_decompress(const Vector &other, size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const

Function to reverse the alternating_bit_compress function. it takes an already compressed Vector and assign from it the corresponding bits to the this called on Vector.

Parameters:
  • other – the vector that has the compressed bits.

  • start – index of the first bit to start the included/excluded chunks pattern.

  • step – difference between each two consecutive bits in each included chunk.

  • included_size – size of each included chunk.

  • excluded_size – size of each excluded chunk.

  • direction – direction for picking up the bits in each included_size chunk. 1 means least significant first. -1 means most significant first.

inline Vector(size_t _size, T _init_val = 0)

             This constructor allows for creating a new vector by just passing initialization
             parameters for inner `data` variable.
             @tparam T is a generic type to allow for different constructors for the variable
data.

Parameters:
  • args – is the packed parameters passed to data initializer. Creates a Vector of size values initialize to init_val (0 by default).

  • size – The size of the new Vector.

inline Vector(std::vector<T> &&_other)

Move constructor

Parameters:

other – The std::vector<T> whose elements will be moved to the new Vector.

inline Vector(std::vector<T> &_other)

Copy constructor

Parameters:

other – The std::vector<T> whose elements will be copied to the new Vector.

inline Vector(std::initializer_list<T> &&elements)

Constructs a new Vector from a list of T elements.

Parameters:

elements – The list of elements of the new Vector.

inline Vector(const Vector &other)

This is a shallow copy constructor.

WARNING: The new vector will point to the same memory location used by

other. To copy the data into a separate memory location, create a new vector first then use assignment operator.

Parameters:

other – The vector that contains the std::vector<T> pointer to be copied.

inline Vector(std::shared_ptr<VectorDataBase<T>> other)
inline Vector &operator=(const Vector &&other)

This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the other vector to the this vector. Assumes other

has the same size as this vector.

NOTE: This method works relatively to the current batch.

Parameters:

other – The Vector that contains the values to be assigned to this vector.

Returns:

A reference to this vector after modification.

inline Vector &operator=(const Vector &other)

This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the other vector to this vector. Assumes other has the same size as this vector.

Parameters:

other – the Vector that contains the values to be copied.

Returns:

A reference to this Vector after modification.

template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other)

Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.

inline Vector simple_subset(size_t start, size_t size) const

Returns a new vector that contains all elements in the range [start, end].

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • end – The index of the last element to be included in the output vector.

Returns:

A new vector that contains the selected elements.

inline void mask(const T &n)

Masks each element in this vector by doing a bitwise logical AND with n.

Parameters:

n – The mask.

inline void zero()

Sets every element of this vector to zero.

inline Vector bit_level_shift(int log_level_size) const

Creates a new Vector whose i-th element is generated by:

  1. splitting the bit representation of the i-th element of this Vector into parts of size level_size, and

  2. setting all bits of the least significant half of each part equal to the LSB of the most significant part.

NOTE: This method is used in secure greater-than and works relatively to the current batch.

Moved from private so we can test this method externally.

Parameters:

log_level_size – log2 of the maximum chunk size (indexes into LEVEL_MASKS)

Returns:

A new vector that contains elements generated as described above.

inline size_t size() const

NOTE: This method works relatively to the current batch.

Returns:

The number of elements in the vector.

inline Vector operator+(const Vector &y) const

Elementwise plaintext addition.

inline Vector operator-(const Vector &y) const

Elementwise plaintext subtraction.

inline Vector operator*(const Vector &y) const

Elementwise plaintext multiplication.

inline Vector operator/(const Vector &y) const

Elementwise plaintext division.

inline Vector operator-() const

Elementwise plaintext negation.

inline Vector operator&(const Vector &y) const

Elementwise plaintext bitwise AND.

inline Vector operator|(const Vector &y) const

Elementwise plaintext bitwise OR.

inline Vector operator^(const Vector &y) const

Elementwise plaintext bitwise XOR.

inline Vector operator~() const

Elementwise plaintext boolean complement.

inline Vector operator!() const

Elementwise plaintext boolean negation.

inline Vector operator==(const Vector &y) const

Elementwise plaintext equality comparison.

inline Vector operator!=(const Vector &y) const

Elementwise plaintext inequality comparison.

inline Vector operator>(const Vector &y) const

Elementwise plaintext greater-than comparison.

inline Vector operator>=(const Vector &y) const

Elementwise plaintext greater-or-equal comparison.

inline Vector operator<(const Vector &y) const

Elementwise plaintext less-than comparison.

inline Vector operator<=(const Vector &y) const

Elementwise plaintext less-or-equal comparison.

template<typename OtherType>
inline Vector operator+(const OtherType &other) const
template<typename OtherType>
inline Vector operator-(const OtherType &other) const
template<typename OtherType>
inline Vector operator*(const OtherType &other) const
template<typename OtherType>
inline Vector operator/(const OtherType &other) const
template<typename OtherType>
inline Vector operator%(const OtherType &other) const
template<typename OtherType>
inline Vector operator&(const OtherType &other) const
template<typename OtherType>
inline Vector operator|(const OtherType &other) const
template<typename OtherType>
inline Vector operator^(const OtherType &other) const
template<typename OtherType>
inline Vector operator>>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<<(const OtherType &other) const
template<typename OtherType>
inline Vector operator>(const OtherType &other) const
template<typename OtherType>
inline Vector operator<(const OtherType &other) const
template<typename OtherType>
inline Vector operator==(const OtherType &other) const
template<typename OtherType>
inline Vector operator!=(const OtherType &other) const
template<typename OtherType>
inline Vector operator+=(const OtherType &other)
template<typename OtherType>
inline Vector operator-=(const OtherType &other)
template<typename OtherType>
inline Vector operator*=(const OtherType &other)
template<typename OtherType>
inline Vector operator&=(const OtherType &other)
template<typename OtherType>
inline Vector operator|=(const OtherType &other)
template<typename OtherType>
inline Vector operator^=(const OtherType &other)
inline Vector ltz() const

Elementwise plaintext less-than-zero comparison.

inline Vector extend_lsb() const

Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.

inline Vector extract_valid(Vector valid)
inline T &operator[](int index)

Returns a mutable reference to the element at the given index

.

NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

A mutable reference to the element at the given index.

inline const T &operator[](int index) const

Returns an immutable reference of the element at the given index

.

NOTE: This method works relatively to the current batch.

Parameters:

index – The index of the target element.

Returns:

Returns a read-only reference of the element at the given index.

inline bool same_as(const Vector<T> &other) const

             Unpacks bits in the elements of `this` vector to create a new vector of size `n`
whose i-th element equals the (i/n)-th bit of the (in)-th element of this vector.

Parameters:
  • n – The number of bits to ‘unpack’.

  • other – The vector to compare this with.

Returns:

A new Vector that contains n single-bit elements constructed as described above. Checks if the two input vectors (this and other) contain the same elements.

Returns:

True if this vector contains the same elements with other, False otherwise.

inline bool starts_with(const Vector<T> &prefix)

Checks if the vector prefix is a prefix of this vector.

Parameters:

prefix

Returns:

true if the argument is a prefix

Returns:

false otherwise

Public Members

std::shared_ptr<VectorDataBase<T>> data

A (shared) pointer to the actual vector contents.

NOTE: Shallow copying of this object creates two instances that share the same data.

Public Static Attributes

static const int LEVEL_MASK_SIZE = 7
static const uint64_t constexpr LEVEL_MASKS[LEVEL_MASK_SIZE] = {0xffffffffffffffff, 0xaaaaaaaaaaaaaaaa, 0x4444444444444444, 0x1010101010101010, 0x0100010001000100, 0x0001000000010000, 0x0000000100000000,}

Mask for level 2^i (64 bits). Gives LSB of the most significant half of each chunk.

Private Types

using Unsigned_type = typename std::make_unsigned<T>::type

Private Functions

inline Vector reverse_bit_level_shift(int level_size) const

Creates a new Vector whose i-th element is generated by:

  1. splitting the bit representation of the i-th element of this Vector into parts of size level_size, and

  2. setting all bits of the most significant half of each part equal to the MSB of the least significant half.

NOTE: This method is bit_level_shift but from right to left, and is used in the parallel prefix adder for boolean addition.

Parameters:

level_size – The number of bits (2^k, k>0) of each part within the bit representation of an element.

Returns:

A new vector that contains elements generated as described above.

inline Vector bit_arithmetic_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, use bit_logical_right_shift

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_logical_right_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector right-shifted by shift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, use bit_arithmetic_right_shift NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to right-shift each element of this Vector.

Returns:

A new Vector that contains the right-shifted elements.

inline Vector bit_left_shift(int shift_size) const

Creates a new Vector that contains all elements of this Vector left-shifted by shift_size

.

NOTE: This method works relatively to the current batch.

Parameters:

shift_size – The number of bits to left-shift each element of this Vector.

Returns:

A new Vector that contains the left-shifted elements.

inline Vector bit_xor() const

Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of this Vector, 0 <= i < size()

. (Basically parity check of each element.)

NOTE: This method works relatively to the current batch.

Returns:

A new Vector that contains single-bit elements generated as described above.

inline Vector simple_subset(int start, int step, int end) const

Returns a new vector containing elements in the range [start, end] that are step

positions apart.

NOTE: This method works relatively to the current batch.

Parameters:
  • start – The index of the first element to be included in the output vector.

  • step – The distance between two consecutive elements.

  • end – The maximum possible index of the last element to be included in the output vector.

Returns:

A new vector that contains the selected elements.

inline void reset_batch()

Sets the current batch equal to the whole vector.

inline void set_batch(int _start_ind, int _end_ind)

Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.

Parameters:
  • _start_ind – The index of the first element in the current batch.

  • _end_ind – The index of the last element in the current batch.

Private Members

int batch_start = 0
int batch_end = 0
const int MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits
size_t precision = 0

Fixed-point precision (number of fractional bits)

Friends

friend class EVector
friend class service::RunTime
friend class cdough::service::Task_1
friend class cdough::service::Task_2
friend class cdough::service::Task_ARGS_RTR_1
friend class cdough::service::Task_ARGS_RTR_2
friend class cdough::service::Task_ARGS_VOID_1
friend class cdough::service::Task_ARGS_VOID_2
namespace service

Defines

define_binary_vector_op(_op_)

Define a binary operation between two vectors, such as a - b.

define_unary_vector_op(_op_)

Define a unary operation with one vector, such as ~a.

define_binary_vector_element_op(_op_)

Define a binary operation with a vector and an element, such as a * 2.

define_binary_vector_assignment_op(_op_)

Define a Vector assignment operator with a Vector, such as a &= b.

define_binary_vector_element_assignment_op(_op_)

Define a Vector assignment operator with an element, such as a += 1.

_bextr_u64(x, y, z)
namespace cdough

Functions

template<typename T>
static inline T getBit(const T &share, int bitIndex)

Extracts the bit at bitIndex from the given element. Use a dedicated hardware instruction if available (x86 SSE only).

Parameters:
  • share – The vector element whose bit we want to extract.

  • bitIndex – The zero-based index (0 is the LSB).

Returns:

The extracted bit as a single-bit T element.

template<typename T>
static inline void setBit(T &share, const T &bit, int bitIndex)

Sets the bit at bitIndex in element share equal to the LSB of element bit.

Parameters:
  • share – The element whose bit we want to update.

  • bit – The element whose LSB must be copied into share.

  • bitIndex – The zero-based index (0 is the LSB) of the bit to be updated in element share.

template<typename T>
static inline void clrBit(T &share, int bitIndex)

Clear the bit at position bitIndex (i.e., set it to zero)

Template Parameters:

T

Parameters:
  • share

  • bitIndex

template<typename T>
static inline void setBitValue(T &share, const T &value, int bitIndex)

Set the the bit at the given index to the value provided.

Template Parameters:

T

Parameters:
  • share – Vector element to modify

  • value – binary value to set the specified bit to

  • bitIndex – which bit to modify

template<typename T>
static inline void setBitMask(T &share, const bool &value, const std::make_unsigned_t<T> &mask)

Conditionally set bits in share, masked by mask, based on the boolean value flag.

Optimized version from https://graphics.stanford.edu/~seander/bithacks.html

It’s not immediately clear to me that this is faster, but perhaps better on certain processors, or with certain optimizations enabled.

Parameters:
  • share – the element to operate on

  • value – whether the bits should be set or cleared

  • mask – which bits to modify

template<typename Share>
static Vector<Share> compare_rows(const std::vector<Vector<Share>*> &x_vec, const std::vector<Vector<Share>*> &y_vec, const std::vector<bool> &inverse)

Same as BSharedVector::compare_rows() but works with plaintext data. Used for testing.

Compares two MxN arrays row-wise by applying M greater-than comparisons on N keys.

NOTE: The i-th row, let l, from the left array is greater than the i-th row, let r, from the right array if l’s first key is greater than r’s first key, or the first keys are the same and l’s second key is greater than r’s second key, or the first two keys are the same and so forth, for all keys.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • inverse – A vector of N boolean values that denotes the order of comparison per key (if inverse[i]=True, then rows from x_vec and y_vec are swapped in the comparison on the i-th column.

Returns:

A new vector that contains the result bits of the M greater-than comparisons.

template<typename Share>
static void swap(std::vector<Vector<Share>*> &x_vec, std::vector<Vector<Share>*> &y_vec, const Vector<Share> &bits)

Same as BSharedVector::swap() but works with plaintext data. Used for testing.

Swaps rows of two MxN arrays in place using the provided bits.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).

template<typename Share>
static void swap(Vector<Share> &x_vec, Vector<Share> &y_vec, const Vector<Share> &bits)

Same as BSharedVector::swap() but works with plaintext data. Used for testing.

Swaps rows of two MxN arrays in place using the provided bits.

Template Parameters:

Share – Share data type.

Parameters:
  • x_vec – The left column-first array with M rows and N columns.

  • y_vec – The right column-first array with M rows and N columns.

  • bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).

template<typename T>
struct is_ntl_gf2e : public std::false_type
#include <mapping_access_vector.h>
template<>
struct is_ntl_gf2e<NTL::GF2E> : public std::false_type, public std::true_type
#include <mapping_access_vector.h>
template<typename T>
class Vector
#include <class_access_vector.h>
namespace service

Defines

define_binary_vector_op(_op_)

Defines a dummy binary operator.

define_unary_vector_op(_op_)

Defines a dummy unary operator.

define_binary_vector_element_op(_op_)

Defines a dummy binary operator between a Vector and some other type.

define_binary_vector_assignment_op(_op_)

Defines a dummy binary assignment operator.

namespace cdough

Functions

template<typename Share>
static Vector<Share> compare_rows(const std::vector<Vector<Share>*> &x_vec, const std::vector<Vector<Share>*> &y_vec, const std::vector<bool> &inverse)

Return an arbitrary row as a dummy Vector.

Template Parameters:

Share

Parameters:
  • x_vec

  • y_vec

  • inverse

Returns:

Vector<Share>

template<typename Share>
static void swap(std::vector<Vector<Share>*> &x_vec, std::vector<Vector<Share>*> &y_vec, const Vector<Share> &bits)
template<typename Share>
static void swap(Vector<Share> &x_vec, Vector<Share> &y_vec, const Vector<Share> &bits)
template<typename T>
class Vector
#include <class_access_vector.h>
namespace service
namespace NTL

Functions

inline GF2E operator&(const GF2E &lhs, const GF2E&)
inline GF2E operator|(const GF2E &lhs, const GF2E&)
inline GF2E operator^(const GF2E &lhs, const GF2E&)
inline GF2E operator&(const GF2E &lhs, long)
inline GF2E operator|(const GF2E &lhs, long)
inline GF2E operator^(const GF2E &lhs, long)
inline GF2E &operator&=(GF2E &lhs, const GF2E&)
inline GF2E &operator|=(GF2E &lhs, const GF2E&)
inline GF2E &operator^=(GF2E &lhs, const GF2E&)
inline GF2E &operator&=(GF2E &lhs, long)
inline GF2E &operator|=(GF2E &lhs, long)
inline GF2E &operator^=(GF2E &lhs, long)
inline GF2E operator~(const GF2E &value)
inline bool operator!(const GF2E &value)
inline GF2E operator%(const GF2E &lhs, const GF2E&)
inline GF2E operator%(const GF2E &lhs, long)
inline GF2E &operator%=(GF2E &lhs, const GF2E&)
inline GF2E &operator%=(GF2E &lhs, long)
inline GF2E operator>>(const GF2E &lhs, long)
inline GF2E operator<<(const GF2E &lhs, long)
inline GF2E &operator>>=(GF2E &lhs, long)
inline GF2E &operator<<=(GF2E &lhs, long)
inline bool operator>(const GF2E&, const GF2E&)
inline bool operator>=(const GF2E&, const GF2E&)
inline bool operator<(const GF2E&, const GF2E&)
inline bool operator<=(const GF2E&, const GF2E&)
inline bool operator>(const GF2E&, long)
inline bool operator>=(const GF2E&, long)
inline bool operator<(const GF2E&, long)
inline bool operator<=(const GF2E&, long)

Matrix

namespace cdough
namespace matrix

Typedefs

template<typename T, template<typename> class V>
using PlainMatrix = cdough::matrix::hybrid::PlainMatrix<T, V>
template<typename T, template<typename> class V>
using SecureMatrix = cdough::matrix::hybrid::SecureMatrix<T, V>
using HeightWidth = cdough::matrix::hybrid::HeightWidth

Defines

define_binary_matrix_matrix_op(_op_)
define_binary_matrix_element_op(_op_)
define_binary_matrix_matrix_inplace_op(_op_)
define_binary_matrix_element_inplace_op(_op_)
namespace cdough
namespace matrix
namespace hybrid

Typedefs

using HeightWidth = std::pair<size_t, size_t>
template<typename T, template<typename> class V, template<typename, template<typename> class> class ImplementedMatrix>
class Matrix
#include <matrix.h>

Matrix class.

This class provides the common Matrix interface between both secure and plaintext matrices. The Matrix class is a wrapper around a 1D data abstraction. The matrix utilizes its computational capabilities from the underlying vector type.

Note: we should not use for-loop functions in this class because the secure matrix inherits from it.

Template Parameters:
  • T – Data type

  • V – Vector type

  • ImplementedMatrix – The derived matrix class

Public Types

using ElementType = T
template<typename U>
using VectorType = V<U>

Public Functions

inline Matrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)

Construct a new Matrix object.

Parameters:
  • data – 1D data vector

  • rows – Number of rows

  • cols – Number of columns

  • columnWise – Whether the data is stored in column-wise order

inline virtual ~Matrix()
inline size_t rows() const

Get number of rows.

Returns:

size_t Number of rows

inline size_t cols() const

Get number of columns.

Returns:

size_t Number of columns

inline const V<T> &data() const

Get underlying data vector (const)

Returns:

const V<T>& for the Underlying data vector

inline V<T> &data()

Get underlying data vector.

Returns:

V<T>& for the Underlying data vector

inline bool isColumnWise() const

Check if the matrix is stored in column-wise order.

Returns:

true if the matrix is column-wise, false otherwise

inline ImplementedMatrix<T, V> matrixRightMultiplyWithColumnMatrixVectorized(const ImplementedMatrix<T, V> &rhs) const

Vectorized Matrix right multiplication with a column matrix. Expects the left-hand side matrix to be in row-major order. Expects the right-hand side matrix to be in column-major order.

Parameters:

rhs – The right-hand side column matrix.

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> matrixRightMultiplyVectorized(const ImplementedMatrix<T, V> &rhs)

Vectorized matrix right multiplication with a matrix. Expects the left-hand side matrix to be in row-major order.

Parameters:

rhs – The right-hand side matrix.

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> conv2DVectorized(const ImplementedMatrix<T, V> &rhs, size_t instancesCount, const HeightWidth &filterSize, const HeightWidth &stride, const HeightWidth &padding) const

Secure 2D convolution. Expects the input matrix to be in row-major order. Expects the filter matrix to be in row-major order. Assumes input to has 1 channel (equivalent to many but interleaved). Output has multiple channels.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location. For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels [f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]

Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location. For example, for 2x2 output with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Parameters:
  • rhs – The filter matrix.

  • instancesCount – Number of instances in the input batch.

  • filterSize – Height and width of the filter.

  • stride – Height and width of the stride.

  • padding – Height and width of the padding.

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> fullyConnectedVectorized(const ImplementedMatrix<T, V> &weights, const ImplementedMatrix<T, V> &bias) const

Vectorized fully connected layer. Expects the input matrix to be in row-major order. Expects the weights matrix to be in column-major order. Expects the bias matrix to be in row-major order.

It performs matrix multiplication between input and weights, then adds the bias to each instance in the output. res = input.matMult(weights) + bias

Parameters:
  • weights – The weights matrix.

  • bias – The bias matrix.

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> avgPoolingVectorized(size_t instancesCount, size_t channelsNum, const HeightWidth &inputSize, const HeightWidth &filterSize, const HeightWidth &stride, const HeightWidth &padding) const

Average Pooling, vectorized implementation.

Expects the input matrix to be in row-major order.

Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.

For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]

Parameters:
  • instancesCount – Number of instances in the input batch.

  • channelsNum – Number of channels in the input.

  • inputSize – Height and width of each input channel.

  • filterSize – Height and width of the pooling filter.

  • stride – Height and width of the stride.

  • padding – Height and width of the padding.

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> reLUVectorized() const

Vectorized ReLU activation, vectorized implementation.

Returns:

ImplementedMatrix<T, V> The resulting matrix after ReLU

inline const ImplementedMatrix<T, V> reshapeRef(size_t rows, size_t columns) const

Reshape the matrix to new dimensions (rows, columns) It does not change the underlying data or create a copy. It changes the dimensions only. It returns a new matrix object referencing the same data memory location.

Parameters:
  • rows – New number of rows

  • columns – New number of columns

Returns:

ImplementedMatrix<T, V> The reshaped matrix

inline ImplementedMatrix<T, V> separateChannels(size_t channels) const

separateChannels vectorized implementation. It takes a matrix where channels are interleaved and make it such that each channel is separated.

Input layout: The input consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}

Output layout: {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}

Parameters:

channels – Number of channels to separate

Returns:

ImplementedMatrix<T, V> The resulting matrix

inline ImplementedMatrix<T, V> interleaveChannels(size_t channels) const

interleaveChannels vectorized implementation. It takes a matrix where channels are separated and make it such that channels are interleaved.

Input layout: {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}

Output layout: The output consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}

Parameters:

channels – Number of channels to diffuse

Returns:

ImplementedMatrix<T, V> The resulting matrix

template<typename T2>
inline auto operator+(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator-(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator*(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator>(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator<(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator>=(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator<=(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator==(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto operator!=(const ImplementedMatrix<T2, V> &y) const
template<typename T2>
inline auto &operator+=(const ImplementedMatrix<T2, V> &y)
template<typename T2>
inline auto &operator-=(const ImplementedMatrix<T2, V> &y)
template<typename T2>
inline auto &operator*=(const ImplementedMatrix<T2, V> &y)

Protected Attributes

V<T> data_
size_t rows_
size_t cols_
bool columnWise_ = false
namespace cdough
namespace matrix
namespace hybrid
template<typename T, template<typename> class V>
class PlainMatrix : public cdough::matrix::hybrid::Matrix<T, V, PlainMatrix>
#include <plain_matrix.h>

Plain Matrix class.

This class implements a plaintext matrix.

Template Parameters:
  • T – Data type

  • V – Vector type

Public Functions

inline PlainMatrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)

Construct a new Plain Matrix object.

Parameters:
  • data – 1D data vector

  • rows – Number of rows

  • cols – Number of columns

  • columnWise – Whether the data is stored in column-wise order

inline PlainMatrix(size_t rows, size_t cols, const bool &columnWise = false)

Construct a new Plain Matrix object.

Parameters:
  • rows – Number of rows

  • cols – Number of columns

  • columnWise – Whether the data is stored in column-wise order

inline virtual ~PlainMatrix()
inline auto same_as(const PlainMatrix &other) const

Check if two matrices are the same.

Parameters:

other – The other matrix to compare with

Returns:

true if the matrices are the same, false otherwise

inline void print() const

Prints the matrix.

Public Static Functions

template<typename Generator>
static inline PlainMatrix RandomMatrix(Generator &generator, size_t rows, size_t cols, const T &mod = std::numeric_limits<T>::max())

Generate a random plain matrix, output can be modulo mod if specified.

Template Parameters:

Generator – Randomness generator type

Parameters:
  • generator – Randomness generator

  • rows – Number of rows

  • cols – Number of columns

  • mod – Modulus for the random values

Returns:

PlainMatrix<T, V> The generated random matrix

template<typename Generator>
static inline PlainMatrix RandomColumnMatrix(Generator &generator, size_t rows, size_t cols, const T &mod = std::numeric_limits<T>::max())

Generate a random plain column-wise matrix.

Template Parameters:

Generator – Randomness generator type

Parameters:
  • generator – Randomness generator

  • rows – Number of rows

  • cols – Number of columns

  • mod – Modulus for the random values

Returns:

PlainMatrix<T, V> The generated random column-wise matrix

namespace cdough
namespace matrix
namespace hybrid
template<typename T, template<typename> class V>
class SecureMatrix : public cdough::matrix::hybrid::Matrix<T, V, SecureMatrix>
#include <secure_matrix.h>

Secure Matrix class.

This class implements a secure matrix.

Template Parameters:
  • T – Data type

  • V – Vector type

Public Functions

inline SecureMatrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)

Construct a new Secure Matrix object.

Parameters:
  • data – 1D data vector

  • rows – Number of rows

  • cols – Number of columns

  • columnWise – Whether the data is stored in column-wise order

inline virtual ~SecureMatrix()
inline void setPrecision(size_t precision)

Set the precision for fixed-point representation.

Parameters:

precision – Number of bits for the fractional part

inline auto open() const

Open the secure matrix and return a plaintext matrix.

Returns:

PlainMatrix<T, V> The opened plaintext matrix

inline V<T> getContents() const

Get the contents of the secure matrix as a vector.

Returns:

V<T> The data vector of the secure matrix