High-Level Interface

Compiler.types module

This module defines all types availabe in high-level programs. These include basic types such as secret integers or floating-point numbers and container types. A single instance of the former uses one or more so-called registers in the virtual machine while the latter use the so-called memory. For every register type, there is a corresponding dedicated memory.

Registers are used for computation, allocated on an ongoing basis, and thread-specific. The memory is allocated statically and shared between threads. This means that memory-based types such as Array can be used to transfer information between threads. Note that creating memory-based types outside the main thread is not supported.

If viewing this documentation in processed form, many function signatures appear generic because of the use of decorators. See the source code for the correct signature.

Basic types

Basic types contain many special methods such as __add__(). This is used for operator overloading in Python. It is not recommend to use them, use the plain operators instead, such as + instead of __add__(). See https://docs.python.org/3/reference/datamodel.html#special-method-names for a translation to operators.

In some operations such as secure comparison, the secure computation protocols allows for more parameters than just the operands which influence the performance. In this case, we provide an alias for better code readability. For example, sint.greater_than() is an alias of sint.__gt__(). When using operator overloading, the parameters default to the globally defined ones.

Methods of basic types generally return instances of the respective type.

Note that the data model of Python operates with reverse operators such as __radd__(). This means that if for the usual operator of the first operand does not support the second operand, the reverse operator of the second operand is used. For example, _clear.__sub__() does not support secret values as second operand but _secret.__rsub__() does support clear values, so cint(3) - sint(2) will result in a secret integer of value 1.

sint Secret integer in the protocol-specific domain.
cint Clear integer in same domain as secure computation (depends on protocol).
regint Clear 64-bit integer.
sfix Secret fixed-point number represented as secret integer.
cfix Clear fixed-point number represented as clear integer.
sfloat Secret floating-point number.
sgf2n Secret \(\mathrm{GF}(2^n)\) value.
cgf2n Clear \(\mathrm{GF}(2^n)\) value.

Container types

MemValue Single value in memory.
Array Array accessible by public index.
Matrix Matrix.
MultiArray Multidimensional array.
class Compiler.types.Array(length, value_type, address=None, debug=None, alloc=True)[source]

Bases: object

Array accessible by public index.

__add__(other)[source]

Vector addition.

Parameters:other – vector or container of same length and type that supports operations with type of this array
__getitem__(index)[source]

Reading from array.

Parameters:index – public (regint/cint/int/slice)
Returns:array if slice is given, basic type otherwise
__init__(length, value_type, address=None, debug=None, alloc=True)[source]
Parameters:
  • length – compile-time integer (int) or None for unknown length
  • value_type – basic type
  • address – if given (regint/int), the array will not be allocated
__mul__(value)[source]

Vector multiplication.

Parameters:other – vector or container of same length and type that supports operations with type of this array
__pow__(value)[source]

Vector power-of computation.

Parameters:other – compile-time integer (int)
__radd__(other)

Vector addition.

Parameters:other – vector or container of same length and type that supports operations with type of this array
__rmul__(value)

Vector multiplication.

Parameters:other – vector or container of same length and type that supports operations with type of this array
__setitem__(index, value)[source]

Writing to array.

Parameters:
  • index – public (regint/cint/int)
  • value – convertible for relevant basic type
__str__()[source]

Return str(self).

__sub__(other)[source]

Vector subtraction.

Parameters:other – vector or container of same length and type that supports operations with type of this array
assign_all(value, use_threads=True, conv=True)[source]

Assign the same value to all entries.

Parameters:value – convertible to basic type
classmethod create_from(l)[source]

Convert Python iterator to array. Basic type will be taken from first element, further elements must to be convertible to that.

get_part_vector(base=0, size=None)

Return vector with content.

Parameters:
  • base – starting point (regint/cint/int)
  • size – length (compile-time int)
get_vector(base=0, size=None)[source]

Return vector with content.

Parameters:
  • base – starting point (regint/cint/int)
  • size – length (compile-time int)
input_from(player, budget=None, raw=False)[source]

Fill with inputs from player if supported by type.

Parameters:player – public (regint/cint/int)
reveal()[source]

Reveal the whole array.

Returns:Array of relevant clear type.
reveal_list()[source]

Reveal as list.

reveal_nested()

Reveal as list.

shuffle()[source]

Insecure shuffle in place.

class Compiler.types.Matrix(rows, columns, value_type, debug=None, address=None)[source]

Bases: Compiler.types.MultiArray

Matrix.

__init__(rows, columns, value_type, debug=None, address=None)[source]
Parameters:
  • rows – compile-time (int)
  • columns – compile-time (int)
  • value_type – basic type of entries
class Compiler.types.MemValue(value, address=None)[source]

Bases: Compiler.types._mem

Single value in memory. This is useful to transfer information between threads. Operations are automatically read from memory if required, this means you can use any operation with MemValue objects as if they were a basic type.

__init__(value, address=None)[source]
Parameters:value – basic type or int (will be converted to regint)
read()[source]

Read value.

Returns:relevant basic type instance
reveal()[source]

Reveal value.

Returns:relevant clear type
write(value)[source]

Write value.

Parameters:value – convertible to relevant basic type
class Compiler.types.MultiArray(sizes, value_type, debug=None, address=None, alloc=True)[source]

Bases: Compiler.types.SubMultiArray

Multidimensional array.

__init__(sizes, value_type, debug=None, address=None, alloc=True)[source]
Parameters:
  • sizes – shape (compile-time list of integers)
  • value_type – basic type of entries
class Compiler.types.SubMultiArray(sizes, value_type, address, index, debug=None)[source]

Bases: object

Multidimensional array functionality.

__add__(other)[source]

Element-wise addition.

Parameters:other – container of matching size and type
Returns:container of same shape and type as self
__getitem__(index)[source]

Part access.

Parameters:index – public (regint/cint/int)
Returns:Array if one-dimensional, SubMultiArray otherwise
__init__(sizes, value_type, address, index, debug=None)[source]

Do not call this, use MultiArray instead.

__len__()[source]

Size of top dimension.

__mul__(other)[source]

Matrix-matrix and matrix-vector multiplication.

Parameters:
  • self – two-dimensional
  • other – Matrix or Array of matching size and type
__radd__(other)

Element-wise addition.

Parameters:other – container of matching size and type
Returns:container of same shape and type as self
__setitem__(index, other)[source]

Part assignment.

Parameters:
  • index – public (regint/cint/int)
  • other – container of matching size and type
__str__()[source]

Return str(self).

assign(other)[source]

Assign container to content. Not implemented for floating-point.

Parameters:other – container of matching size and type
assign_all(value)[source]

Assign the same value to all entries.

Parameters:value – convertible to relevant basic type
assign_vector(vector, base=0)[source]

Assign vector to content. Not implemented for floating-point.

Parameters:
  • vector – vector of matching size convertible to relevant basic type
  • base – compile-time (int)
direct_mul(other, reduce=True, indices=None)[source]

Matrix multiplication in the virtual machine.

Parameters:
Returns:

Matrix as vector of relevant type (row-major)

The following executes a matrix multiplication selecting every third row of A:

A = sfix.Matrix(7, 4)
B = sfix.Matrix(4, 5)
C = sfix.Matrix(3, 5)
C.assign_vector(A.direct_mul(B, indices=(regint.inc(3, 0, 3),
                                         regint.inc(4),
                                         regint.inc(4),
                                         regint.inc(5)))
direct_mul_to_matrix(other)[source]

Matrix multiplication in the virtual machine.

Parameters:
Returns:

Matrix

direct_mul_trans(other, reduce=True, indices=None)[source]

Matrix multiplication with the transpose of other in the virtual machine.

Parameters:
Returns:

Matrix as vector of relevant type (row-major)

direct_trans_mul(other, reduce=True, indices=None)[source]

Matrix multiplication with the transpose of self in the virtual machine.

Parameters:
Returns:

Matrix as vector of relevant type (row-major)

get_vector(base=0, size=None)[source]

Return vector with content. Not implemented for floating-point.

Parameters:
  • base – public (regint/cint/int)
  • size – compile-time (int)
iadd(other)[source]

Element-wise addition in place.

Parameters:other – container of matching size and type
input_from(player, budget=None, raw=False)[source]

Fill with inputs from player if supported by type.

Parameters:player – public (regint/cint/int)
mul_trans(other)[source]

Matrix multiplication with transpose of other.

Parameters:
  • self – two-dimensional
  • other – two-dimensional container of matching type and size
plain_mul(other, res=None)[source]

Alternative matrix multiplication.

Parameters:
  • self – two-dimensional
  • other – two-dimensional container of matching type and size
reveal_list()[source]

Reveal as list.

reveal_nested()[source]

Reveal as nested list.

same_shape()[source]
Returns:new multidimensional array with same shape and basic type
schur(other)[source]

Element-wise product.

Parameters:other – container of matching size and type
Returns:container of same shape and type as self
trans_mul(other, reduce=True, res=None)[source]

Matrix multiplication with transpose of self

Parameters:
  • self – two-dimensional
  • other – two-dimensional container of matching type and size
transpose()[source]

Matrix transpose.

Parameters:self – two-dimensional
class Compiler.types._bit[source]

Bases: object

Binary functionality.

bit_and(other)[source]

AND in binary circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Return type:depending on inputs (secret if any of them is)
bit_not()[source]

NOT in binary circuits.

bit_xor(other)[source]

XOR in binary circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Return type:depending on inputs (secret if any of them is)
half_adder(other)[source]

Half adder in binary circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Returns:binary sum, carry
Return type:depending on inputs (secret if any of them is)
class Compiler.types._clear(*args, **kwargs)[source]

Bases: Compiler.types._register

Clear domain-dependent type.

__and__(other)[source]

Bit-wise AND of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__eq__(other)[source]

Equality check of public values.

Parameters:other – convertible type (at least same as self and regint/int)
Returns:0/1 (regint)
__ne__(other)[source]

Equality check of public values.

Parameters:other – convertible type (at least same as self and regint/int)
Returns:0/1 (regint)
__or__(other)[source]

Bit-wise OR of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__rand__(other)

Bit-wise AND of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__ror__(other)

Bit-wise OR of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__rsub__(other)[source]

Subtraction of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__rtruediv__(other)[source]

Field division of public values. Not available for computation modulo a power of two.

Parameters:other – convertible type (at least same as self and regint/int)
__rxor__(other)

Bit-wise XOR of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__sub__(other)[source]

Subtraction of public values.

Parameters:other – convertible type (at least same as self and regint/int)
__truediv__(other)[source]

Field division of public values. Not available for computation modulo a power of two.

Parameters:other – convertible type (at least same as self and regint/int)
__xor__(other)[source]

Bit-wise XOR of public values.

Parameters:other – convertible type (at least same as self and regint/int)
add(other)[source]

Addition of public values.

Parameters:other – convertible type (at least same as self and regint/int)
mul(other)[source]

Multiplication of public values.

Parameters:other – convertible type (at least same as self and regint/int)
print_reg_plain(*args, **kwargs)[source]

Output.

reveal()[source]

Identity.

class Compiler.types._fix(**kwargs)[source]

Bases: Compiler.types._single

Secret fixed point type.

__init__(**kwargs)[source]
Params _v:int/float/regint/cint/sint/sfloat
__neg__(*args, **kwargs)[source]

Secret fixed-point negation.

__rtruediv__(*args, **kwargs)[source]

Secret fixed-point division.

Parameters:other – sfix/cfix/sint/cint/regint/int
__truediv__(*args, **kwargs)[source]

Secret fixed-point division.

Parameters:other – sfix/cfix/sint/cint/regint/int
add(*args, **kwargs)[source]

Secret fixed-point addition.

Parameters:other – sfix/cfix/sint/cint/regint/int
compute_reciprocal(*args, **kwargs)[source]

Secret fixed-point reciprocal.

classmethod from_sint(other, k=None, f=None)[source]

Convert secret integer.

Parameters:other – sint
mul(other)[source]

Secret fixed-point multiplication.

Parameters:other – sfix/cfix/sint/cint/regint/int
reveal()[source]

Reveal secret fixed-point number.

Returns:relevant clear type
classmethod set_precision(f, k=None)[source]

Set the precision of the integer representation. Note that some operations are undefined when the precision of sfix and cfix differs. The initial defaults are chosen to allow the best optimization of probabilistic truncation in computation modulo 2^64 (2*k < 64). Generally, 2*k must be at most the integer length for rings and at most m-s-1 for computation modulo an m-bit prime and statistical security s (default 40).

Parameters:
  • f – bit length of decimal part (initial default 16)
  • k – whole bit length of fixed point, defaults to twice f if not given (initial default 31)
class Compiler.types._gf2n[source]

Bases: Compiler.types._bit

\(\mathrm{GF}(2^n)\) functionality.

bit_not()[source]

NOT in binary circuits.

bit_xor(other)[source]

XOR in \(\mathrm{GF}(2^n)\) circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Return type:depending on inputs (secret if any of them is)
cond_swap(a, b, t=None)[source]

Swapping in \(\mathrm{GF}(2^n)\). Similar to _int.if_else().

if_else(a, b)[source]

MUX in \(\mathrm{GF}(2^n)\) circuits. Similar to _int.if_else().

class Compiler.types._int[source]

Bases: object

Integer functionality.

bit_and(other)[source]

AND in arithmetic circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Return type:depending on inputs (secret if any of them is)
bit_not()[source]

NOT in arithmetic circuits.

bit_xor(other)[source]

XOR in arithmetic circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Returns:type depends on inputs (secret if any of them is)
cond_swap(a, b)[source]

Swapping in arithmetic circuits.

Parameters:a/b – any type supporting the necessary operations
Returns:(a, b) if self is 0, (b, a) if self is 1, and undefined otherwise
Return type:depending on operands, secret if any of them is
half_adder(other)[source]

Half adder in arithmetic circuits.

Parameters:self/other – 0 or 1 (any compatible type)
Returns:binary sum, carry
Return type:depending on inputs, secret if any is
if_else(a, b)[source]

MUX on bit in arithmetic circuits.

Parameters:a/b – any type supporting the necessary operations
Returns:a if self is 1, b if self is 0, undefined otherwise
Return type:depending on operands, secret if any of them is
class Compiler.types._mem[source]

Bases: Compiler.types._number

class Compiler.types._number[source]

Bases: object

Number functionality.

__abs__()[source]

Absolute value.

__add__(other)[source]

Optimized addition.

Parameters:other – any compatible type
__mul__(other)[source]

Optimized multiplication.

Parameters:other – any compatible type
__pow__(*args, **kwargs)[source]

Exponentation through square-and-multiply.

Parameters:exp – any type allowing bit decomposition
__radd__(other)

Optimized addition.

Parameters:other – any compatible type
__rmul__(other)

Optimized multiplication.

Parameters:other – any compatible type
max(other)[source]

Maximum.

Parameters:other – any compatible type
min(other)[source]

Minimum.

Parameters:other – any compatible type
square()[source]

Square.

class Compiler.types._register(*args, **kwargs)[source]

Bases: Compiler.program.Register, Compiler.types._number, Compiler.types._structure

static bit_compose(bits)[source]

Compose value from bits.

Parameters:bits – iterable of any type implementing left shift
classmethod malloc(size, creator_tape=None)[source]

Allocate memory (statically).

Parameters:size – compile-time (int)
class Compiler.types._secret(**kwargs)[source]

Bases: Compiler.types._register

__rsub__(other)[source]

Secret subtraction.

Parameters:other – any compatible type
__rtruediv__(*args, **kwargs)[source]

Secret field division.

Parameters:other – any compatible type
__sub__(other)[source]

Secret subtraction.

Parameters:other – any compatible type
__truediv__(*args, **kwargs)[source]

Secret field division.

Parameters:other – any compatible type
add(other)[source]

Secret addition.

Parameters:other – any compatible type
classmethod dot_product(*args, **kwargs)[source]

Secret dot product.

Parameters:
  • x – Iterable of secret values
  • y – Iterable of secret values of same length and type
Return type:

same as inputs

classmethod get_input_from(*args, **kwargs)[source]

Secret input from player.

Parameters:player – public (regint/cint/int)
classmethod get_random_bit(*args, **kwargs)[source]

Secret random bit according to security model.

Returns:0/1 50-50
classmethod get_random_inverse(*args, **kwargs)[source]

Secret random inverse tuple according to security model.

Returns:\((a, a^{-1})\)
classmethod get_random_square(*args, **kwargs)[source]

Secret random square according to security model.

Returns:\((a, a^2)\)
classmethod get_random_triple(*args, **kwargs)[source]

Secret random triple according to security model.

Returns:\((a, b, ab)\)
mul(*args, **kwargs)[source]

Secret multiplication. Either both operands have the same size or one size 1 for a value-vector multiplication.

Parameters:other – any compatible type
reveal(*args, **kwargs)[source]

Reveal secret value publicly.

Return type:relevant clear type
reveal_to(*args, **kwargs)[source]

Reveal secret value to player. Result written to Player-Data/Private-Output-P<player>

Parameters:player – int
Returns:value to be used with print_ln_to()
square(*args, **kwargs)[source]

Secret square.

class Compiler.types._single[source]

Bases: Compiler.types._number, Compiler.types._structure

Representation as single integer preserving the order

__eq__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__ge__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__gt__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__le__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__len__()[source]

Vector length.

__lt__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__ne__(*args, **kwargs)[source]

Comparison.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
Returns:0/1
Return type:same as internal representation
__rsub__(other)[source]

Subtraction.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
__sub__(*args, **kwargs)[source]

Subtraction.

Parameters:other – appropriate public or secret (incl. sint/cint/regint/int)
classmethod dot_product(x, y, res_params=None)[source]

Secret dot product.

Parameters:
  • x – iterable of appropriate secret type
  • y – iterable of appropriate secret type and same length
classmethod receive_from_client(n, client_id, message_type=0)[source]

Securely obtain shares of values input by a client. Assumes client has already converted values to integer representation.

Parameters:
  • n – number of inputs (int)
  • client_id – regint
round_nearest = False

Whether to round deterministically to nearest instead of probabilistically, e.g. after fixed-point multiplication.

class Compiler.types._structure[source]

Bases: object

Interface for type-dependent container types.

classmethod Array(size, *args, **kwargs)[source]

Type-dependent array. Example:

a = sint.Array(10)
classmethod Matrix(rows, columns, *args, **kwargs)[source]

Type-dependent matrix. Example:

a = sint.Matrix(10, 10)
classmethod MemValue(value)

Type-dependent memory value.

class Compiler.types.cfix(**kwargs)[source]

Bases: Compiler.types._number, Compiler.types._structure

Clear fixed-point number represented as clear integer.

__eq__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__ge__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__gt__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__init__(**kwargs)[source]
Parameters:v – cfix/float/int
__le__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__lt__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__ne__(*args, **kwargs)[source]

Clear fixed-point comparison.

Parameters:other – cfix/cint/regint/int
Returns:0/1
Return type:regint
__neg__(*args, **kwargs)[source]

Clear fixed-point negation.

__rsub__(other)[source]

Clear fixed-point subtraction.

Parameters:other – cfix/cint/regint/int
__sub__(*args, **kwargs)[source]

Clear fixed-point subtraction.

Parameters:other – cfix/cint/regint/int
__truediv__(*args, **kwargs)[source]

Clear fixed-point division.

Parameters:other – cfix/cint/regint/int
add(*args, **kwargs)[source]

Clear fixed-point addition.

Parameters:other – cfix/cint/regint/int
mul(*args, **kwargs)[source]

Clear fixed-point multiplication.

Parameters:other – cfix/cint/regint/int/sint
print_plain()[source]

Clear fixed-point output.

classmethod read_from_socket(*args, **kwargs)[source]

Receive clear fixed-point value(s) from client. The client needs to convert the values to the right integer representation.

Parameters:
  • client_id – Client id (regint)
  • n – number of values (default 1)
Returns:

cfix (if n=1) or list of cfix

classmethod set_precision(f, k=None)[source]

Set the precision of the integer representation. Note that some operations are undefined when the precision of sfix and cfix differs. The initial defaults are chosen to allow the best optimization of probabilistic truncation in computation modulo 2^64 (2*k < 64). Generally, 2*k must be at most the integer length for rings and at most m-s-1 for computation modulo an m-bit prime and statistical security s (default 40).

Parameters:
  • f – bit length of decimal part (initial default 16)
  • k – whole bit length of fixed point, defaults to twice f if not given (initial default 31)
classmethod write_to_socket(*args, **kwargs)[source]

Send a list of clear fixed-point values to a client (represented as clear integers).

Parameters:
  • client_id – Client id (regint)
  • values – list of cint
class Compiler.types.cfloat(v, p=None, z=None, s=None, nan=0)[source]

Bases: object

Helper class for printing revealed sfloats.

__init__(v, p=None, z=None, s=None, nan=0)[source]

Parameters as with sfloat but public.

print_float_plain()[source]

Output.

class Compiler.types.cgf2n(val=None, size=None)[source]

Bases: Compiler.types._clear, Compiler.types._gf2n

Clear \(\mathrm{GF}(2^n)\) value. n is 40 or 128, depending on USE_GF2N_LONG compile-time variable.

__init__(val=None, size=None)[source]
Parameters:
  • val – initialization (cgf2n/cint/regint/int or list thereof)
  • size – vector size (int), defaults to 1 or size of list
__invert__(*args, **kwargs)[source]

Clear bit-wise inversion.

__lshift__(*args, **kwargs)[source]

Left shift.

Parameters:other – compile-time (int)
__mul__(other)[source]

Clear \(\mathrm{GF}(2^n)\) multiplication.

Parameters:other – cgf2n/regint/int
__neg__()[source]

Identity.

__rshift__(*args, **kwargs)[source]

Right shift.

Parameters:other – compile-time (int)
classmethod bit_compose(bits, step=None)[source]

Clear \(\mathrm{GF}(2^n)\) bit composition.

Parameters:
  • bits – list of cgf2n
  • step – set every step-th bit in output (defaults to 1)
bit_decompose(*args, **kwargs)[source]

Clear bit decomposition.

Parameters:
  • bit_length – number of bits (defaults to global \(\mathrm{GF}(2^n)\) bit length)
  • step – extract every step-th bit (defaults to 1)
class Compiler.types.cint(val=None, size=None)[source]

Bases: Compiler.types._clear, Compiler.types._int

Clear integer in same domain as secure computation (depends on protocol).

__abs__()[source]

Clear absolute.

__eq__(*args, **kwargs)[source]

Clear equality test.

Parameters:other – cint/regint/int
Returns:0/1 (regint)
__ge__(other)[source]

Clear 64-bit comparison.

Parameters:other – cint/regint/int
Returns:0/1 (regint)
__gt__(other)[source]

Clear 64-bit comparison.

Parameters:other – cint/regint/int
Returns:0/1 (regint)
__init__(val=None, size=None)[source]
Parameters:
  • val – initialization (cint/regint/int/cgf2n or list thereof)
  • size – vector size (int), defaults to 1 or size of list
__invert__(*args, **kwargs)[source]

Clear inversion using global bit length.

__le__(other)[source]

Clear 64-bit comparison.

Parameters:other – cint/regint/int
Returns:0/1 (regint)
__lshift__(other)[source]

Clear left shift.

Parameters:other – cint/regint/int
__lt__(other)[source]

Clear 64-bit comparison.

Parameters:other – cint/regint/int
Returns:0/1 (regint)
__mod__(other)[source]

Clear modulo.

Parameters:other – cint/regint/int
__neg__()[source]

Clear negation.

__rlshift__(*args, **kwargs)[source]

Clear shift.

Parameters:other – cint/regint/int
__rmod__(other)[source]

Clear modulo.

Parameters:other – cint/regint/int
__rpow__(base)[source]

Clear power of two.

Parameters:other – 2
__rrshift__(*args, **kwargs)[source]

Clear shift.

Parameters:other – cint/regint/int
__rshift__(other)[source]

Clear right shift.

Parameters:other – cint/regint/int
bit_decompose(*args, **kwargs)[source]

Clear bit decomposition.

Parameters:bit_length – number of bits (default is global bit length)
Returns:list of cint
digest(num_bytes)[source]

Clear hashing (libsodium default).

legendre()[source]

Clear Legendre symbol computation.

less_than(other, bit_length)[source]

Clear comparison for particular bit length.

Parameters:
  • other – cint/regint/int
  • bit_length – signed bit length of inputs
Returns:

0/1 (regint), undefined if inputs outside range

mod2m(*args, **kwargs)[source]

Clear modulo a power of two.

Parameters:other – cint/regint/int
print_if(string)[source]

Output if value is non-zero.

Parameters:string – Python string
classmethod read_from_socket(*args, **kwargs)[source]

Receive clear value(s) from client.

Parameters:
  • client_id – Client id (regint)
  • n – number of values (default 1)
Returns:

cint (if n=1) or list of cint

right_shift(*args, **kwargs)[source]

Clear shift.

Parameters:other – cint/regint/int
to_regint(*args, **kwargs)[source]

Convert to regint.

Parameters:n_bits – bit length (int)
Returns:regint
classmethod write_to_socket(*args, **kwargs)[source]

Send a list of clear values to a client.

Parameters:
  • client_id – Client id (regint)
  • values – list of cint
class Compiler.types.localint(value=None)[source]

Bases: object

Local integer that must prevented from leaking into the secure computation. Uses regint internally.

__init__(value=None)[source]
Parameters:value – initialization, convertible to regint
output()[source]

Output.

class Compiler.types.regint(**kwargs)[source]

Bases: Compiler.types._register, Compiler.types._int

Clear 64-bit integer. Unlike cint this is always a 64-bit integer.

__and__(other)[source]

Clear bit-wise AND.

Parameters:other – regint/cint/int
__eq__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__floordiv__(other)[source]

Clear integer division (rounding to floor).

Parameters:other – regint/cint/int
__ge__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__gt__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__init__(**kwargs)[source]
Parameters:
  • val – initialization (cint/cgf2n/regint/int or list thereof)
  • size – vector size (int), defaults to 1 or size of list
__le__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__lshift__(other)[source]

Clear shift.

Parameters:other – regint/cint/int
__lt__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__mod__(other)[source]

Clear modulo computation.

Parameters:other – regint/cint/int
__ne__(other)[source]

Clear comparison.

Parameters:other – regint/cint/int
Returns:0/1
__neg__()[source]

Clear negation.

__or__(other)[source]

Clear bit-wise OR.

Parameters:other – regint/cint/int
__rand__(other)

Clear bit-wise AND.

Parameters:other – regint/cint/int
__rfloordiv__(other)[source]

Clear integer division (rounding to floor).

Parameters:other – regint/cint/int
__rlshift__(other)[source]

Clear shift.

Parameters:other – regint/cint/int
__rmod__(other)[source]

Clear modulo computation.

Parameters:other – regint/cint/int
__ror__(other)

Clear bit-wise OR.

Parameters:other – regint/cint/int
__rpow__(other)[source]

Clear power of two computation.

Parameters:other – regint/cint/int
Return type:cint
__rrshift__(other)[source]

Clear shift.

Parameters:other – regint/cint/int
__rshift__(other)[source]

Clear shift.

Parameters:other – regint/cint/int
__rsub__(other)[source]

Clear subtraction.

Parameters:other – regint/cint/int
__rtruediv__(other)

Clear integer division (rounding to floor).

Parameters:other – regint/cint/int
__rxor__(other)

Clear bit-wise XOR.

Parameters:other – regint/cint/int
__sub__(other)[source]

Clear subtraction.

Parameters:other – regint/cint/int
__truediv__(other)

Clear integer division (rounding to floor).

Parameters:other – regint/cint/int
__xor__(other)[source]

Clear bit-wise XOR.

Parameters:other – regint/cint/int
add(other)[source]

Clear addition.

Parameters:other – regint/cint/int
static bit_compose(bits)[source]

Clear bit composition.

Parameters:bits – list of regint/cint/int
bit_decompose(*args, **kwargs)[source]

Clear bit decomposition.

Parameters:bit_length – number of bits (defaults to global bit length)
Returns:list of regint
classmethod get_random(*args, **kwargs)[source]

Public insecure randomness.

Parameters:bit_length – number of bits (int)
classmethod inc(size, base=0, step=1, repeat=1, wrap=None)[source]

Produce regint vector with certain patterns. This is particularly useful for SubMultiArray.direct_mul().

Parameters:
  • size – Result size
  • base – First value
  • step – Increase step
  • repeat – Repeate this many times
  • wrap – Start over after this many increases

The following produces (1, 1, 1, 3, 3, 3, 5, 5, 5, 7):

regint.inc(10, 1, 2, 3)
mod2m(*args, **kwargs)[source]

Clear modulo a power of two.

Return type:cint
mul(other)[source]

Clear multiplication.

Parameters:other – regint/cint/int
classmethod pop(*args, **kwargs)[source]

Pop from stack.

print_if(string)[source]

Output string if value is non-zero.

Parameters:string – Python string
print_reg_plain()[source]

Output.

classmethod push(*args, **kwargs)[source]

Push to stack.

Parameters:value – any convertible type
classmethod read_from_socket(*args, **kwargs)[source]

Receive clear integer value(s) from client.

Parameters:
  • client_id – Client id (regint)
  • n – number of values (default 1)
Returns:

regint (if n=1) or list of regint

reveal()[source]

Identity.

shuffle()[source]

Returns insecure shuffle of vector.

classmethod write_to_socket(*args, **kwargs)[source]

Send a list of clear integers to a client.

Parameters:
  • client_id – Client id (regint)
  • values – list of regint
class Compiler.types.sfix(**kwargs)[source]

Bases: Compiler.types._fix

Secret fixed-point number represented as secret integer. This uses integer operations internally, see sint for security considerations.

classmethod dot_product(x, y, res_params=None)[source]

Secret dot product.

Parameters:
  • x – iterable of appropriate secret type
  • y – iterable of appropriate secret type and same length
classmethod get_input_from(*args, **kwargs)[source]

Secret fixed-point input.

Parameters:player – public (regint/cint/int)
classmethod get_random(*args, **kwargs)[source]

Uniform secret random number around centre of bounds. Actual range can be smaller but never larger.

Parameters:
  • lower – float
  • upper – float
reveal_to(player)[source]

Reveal secret value to player. Raw representation possibly written to Player-Data/Private-Output-P<player>.

Parameters:player – public integer (int/regint/cint)
Returns:value to be used with print_ln_to()
class Compiler.types.sfloat(**kwargs)[source]

Bases: Compiler.types._number, Compiler.types._structure

Secret floating-point number. Represents \((1 - 2s) \cdot (1 - z)\cdot v \cdot 2^p\).

v: significand

p: exponent

z: zero flag

s: sign bit

This uses integer operations internally, see sint for security considerations.

__eq__(*args, **kwargs)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__ge__(other)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__gt__(other)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__init__(**kwargs)[source]
Parameters:v – initialization (sfloat/sfix/float/int/sint/cint/regint)
__le__(other)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__lt__(*args, **kwargs)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__ne__(other)[source]

Secret floating-point comparison.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
Returns:0/1 (sint)
__neg__(*args, **kwargs)[source]

Secret floating-point negation.

__rsub__(other)[source]

Secret floating-point subtraction.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
__rtruediv__(other)[source]

Secret floating-point division.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
__sub__(other)[source]

Secret floating-point subtraction.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
__truediv__(other)[source]

Secret floating-point division.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
add(*args, **kwargs)[source]

Secret floating-point addition.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
classmethod get_input_from(*args, **kwargs)[source]

Secret floating-point input.

Parameters:player – public (regint/cint/int)
mul(*args, **kwargs)[source]

Secret floating-point multiplication.

Parameters:other – sfloat/float/sfix/sint/cint/regint/int
reveal()[source]

Reveal secret floating-point number.

Returns:cfloat
round_to_int()[source]

Secret floating-point rounding to integer.

Returns:sint
class Compiler.types.sgf2n(val=None, size=None)[source]

Bases: Compiler.types._secret, Compiler.types._gf2n

Secret \(\mathrm{GF}(2^n)\) value.

__and__(*args, **kwargs)[source]

Secret bit-wise AND.

Parameters:other – sg2fn/cgf2n/regint/int
__eq__(other, bit_length=None, expand=1)

Secret comparison.

Parameters:other – sgf2n/cgf2n/regint/int
Returns:0/1 (sgf2n)
__init__(val=None, size=None)[source]
Parameters:
  • val – initialization (sgf2n/cgf2n/regint/int/cint or list thereof)
  • size – vector size (int), defaults to 1 or size of list
__invert__(*args, **kwargs)[source]

Secret bit-wise inversion.

__lshift__(*args, **kwargs)[source]

Secret left shift py public value.

Parameters:other – regint/cint/int
__ne__(other, bit_length=None)

Secret comparison.

Parameters:other – sgf2n/cgf2n/regint/int
Returns:0/1 (sgf2n)
__neg__()[source]

Identity.

__rand__(*args, **kwargs)

Secret bit-wise AND.

Parameters:other – sg2fn/cgf2n/regint/int
__rxor__(other)

Secret bit-wise XOR.

Parameters:other – sg2fn/cgf2n/regint/int
__xor__(other)[source]

Secret bit-wise XOR.

Parameters:other – sg2fn/cgf2n/regint/int
add(other)[source]

Secret \(\mathrm{GF}(2^n)\) addition (XOR).

Parameters:other – sg2fn/cgf2n/regint/int
bit_decompose(*args, **kwargs)[source]

Secret bit decomposition.

Parameters:
  • bit_length – number of bits
  • step – use every step-th bit
Returns:

list of sgf2n

equal(other, bit_length=None, expand=1)[source]

Secret comparison.

Parameters:other – sgf2n/cgf2n/regint/int
Returns:0/1 (sgf2n)
mul(other)[source]

Secret \(\mathrm{GF}(2^n)\) multiplication.

Parameters:other – sg2fn/cgf2n/regint/int
not_equal(other, bit_length=None)[source]

Secret comparison.

Parameters:other – sgf2n/cgf2n/regint/int
Returns:0/1 (sgf2n)
right_shift(*args, **kwargs)[source]

Secret right shift by public value:

Parameters:
  • other – compile-time (int)
  • bit_length – number of bits of self (defaults to \(\mathrm{GF}(2^n)\) bit length)
class Compiler.types.sint(val=None, size=None)[source]

Bases: Compiler.types._secret, Compiler.types._int

Secret integer in the protocol-specific domain.

Most non-linear operations require compile-time parameters for bit length and statistical security. They default to the global parameters set by program.set_bit_length() and program.set_security(). The acceptable minimum for statistical security is considered to be 40. The defaults for the parameters is output at the beginning of the compilation.

If the computation domain is modulo a power of two, the operands will be truncated to the bit length, and the security parameter does not matter. Modulo prime, the behaviour is undefined and potentially insecure if the operands are longer than the bit length.

__abs__(*args, **kwargs)[source]

Secret absolute. Uses global parameters for comparison.

__eq__(*args, **kwargs)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__ge__(other, bit_length=None, security=None)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__gt__(*args, **kwargs)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__init__(val=None, size=None)[source]
Parameters:
  • val – initialization (sint/cint/regint/int/cgf2n or list thereof)
  • size – vector size (int), defaults to 1 or size of list
__le__(other, bit_length=None, security=None)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__lshift__(other, bit_length=None, security=None)[source]

Secret left shift.

Parameters:other – secret or public integer (sint/cint/regint/int)
__lt__(*args, **kwargs)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__mod__(*args, **kwargs)[source]

Secret modulo computation. Uses global parameters for bit length and security.

Parameters:modulus – power of two (int)
__ne__(other, bit_length=None, security=None)[source]

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
__neg__(*args, **kwargs)[source]

Secret negation.

__rlshift__(other)[source]

Secret left shift. Bit length of self uses global value.

Parameters:other – secret or public integer (sint/cint/regint/int)
__rpow__(*args, **kwargs)[source]

Secret power computation. Base must be two. Uses global parameters for bit length and security.

__rrshift__(*args, **kwargs)[source]

Secret right shift.

Parameters:other – secret or public integer (sint/cint/regint/int) of globale bit length if secret
__rshift__(*args, **kwargs)[source]

Secret right shift.

Parameters:other – secret or public integer (sint/cint/regint/int)
bit_decompose(*args, **kwargs)[source]

Secret bit decomposition.

equal(*args, **kwargs)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
classmethod get_dabit(*args, **kwargs)[source]

Bit in arithmetic and binary circuit according to security model

classmethod get_edabit(*args, **kwargs)[source]

Bits in arithmetic and binary circuit

classmethod get_input_from(*args, **kwargs)[source]

Secret input.

Parameters:player – public (regint/cint/int)
classmethod get_random(*args, **kwargs)[source]

Secret random ring element according to security model.

classmethod get_random_int(*args, **kwargs)[source]

Secret random n-bit number according to security model.

Parameters:bits – compile-time integer (int)
greater_equal(other, bit_length=None, security=None)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
greater_than(*args, **kwargs)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
int_div(*args, **kwargs)[source]

Secret integer division.

Parameters:other – sint
left_shift(other, bit_length=None, security=None)

Secret left shift.

Parameters:other – secret or public integer (sint/cint/regint/int)
less_equal(other, bit_length=None, security=None)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
less_than(*args, **kwargs)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
mod2m(*args, **kwargs)[source]

Secret modulo power of two.

Parameters:m – secret or public integer (sint/cint/regint/int)
not_equal(other, bit_length=None, security=None)

Secret comparison (signed).

Parameters:other – sint/cint/regint/int
Returns:0/1 (sint)
pow2(*args, **kwargs)[source]

Secret power of two.

classmethod read_from_file(start, n_items)[source]

Read shares from Persistence/Transactions-P<playerno>.data.

Parameters:
  • start – starting position in number of shares from beginning (int/regint/cint)
  • n_items – number of items (int)
Returns:

destination for final position, -1 for eof reached, or -2 for file not found (regint)

Returns:

list of shares

classmethod read_from_socket(*args, **kwargs)[source]

Receive secret-shared value(s) from client.

Parameters:
  • client_id – Client id (regint)
  • n – number of values (default 1)
Returns:

sint (if n=1) or list of sint

classmethod receive_from_client(n, client_id, message_type=0)[source]

Securely obtain shares of values input by a client.

Parameters:
  • n – number of inputs (int)
  • client_id – regint
reveal_to(*args, **kwargs)[source]

Reveal secret value to player. Result potentially written to Player-Data/Private-Output-P<player>.

Parameters:player – public integer (int/regint/cint):
Returns:value to be used with print_ln_to()
right_shift(*args, **kwargs)

Secret right shift.

Parameters:other – secret or public integer (sint/cint/regint/int)
round(*args, **kwargs)[source]

Truncate and maybe round secret k-bit integer by m bits. m can be secret if nearest is false, in which case the truncation will be exact. For public m, nearest chooses between nearest rounding (rounding half up) and probablistic truncation.

Parameters:
  • k – int
  • m – secret or compile-time integer (sint/int)
  • kappa – statistical security parameter (int)
  • nearest – bool
  • signed – bool
classmethod write_shares_to_socket(*args, **kwargs)[source]

Send shares of a list of values to a specified client socket.

Parameters:
  • client_id – regint
  • values – list of sint
static write_to_file(shares)[source]

Write shares to Persistence/Transactions-P<playerno>.data (appending at the end).

Param:shares (list or iterable of sint)

Compiler.GC.types module

This modules contains basic types for binary circuits. The fixed-length types obtained by get_type(n) are the preferred way of using them, and in some cases required in connection with container types.

class Compiler.GC.types.bits(value=None, n=None, size=None)[source]

Bases: Compiler.program.Register, Compiler.types._structure, Compiler.types._bit

Base class for binary registers.

classmethod get_type(length)[source]

Returns a fixed-length type.

class Compiler.GC.types.cbits(value=None, n=None, size=None)[source]

Bases: Compiler.GC.types.bits

Clear bits register. Helper type with limited functionality.

class Compiler.GC.types.sbit(*args, **kwargs)[source]

Bases: Compiler.GC.types.bit, Compiler.GC.types.sbits

Single secret bit.

if_else(x, y)[source]

Non-vectorized oblivious selection:

sb32 = sbits.get_type(32)
print_ln('%s', sbit(1).if_else(sb32(5), sb32(2)).reveal())

This will output 5.

class Compiler.GC.types.sbitfix(**kwargs)[source]

Bases: Compiler.types._fix

Secret signed integer in one binary register. Use set_precision() to change the precision.

Example:

print_ln('add: %s', (sbitfix(0.5) + sbitfix(0.3)).reveal())
print_ln('mul: %s', (sbitfix(0.5) * sbitfix(0.3)).reveal())
print_ln('sub: %s', (sbitfix(0.5) - sbitfix(0.3)).reveal())
print_ln('lt: %s', (sbitfix(0.5) < sbitfix(0.3)).reveal())

will output roughly:

add: 0.800003
mul: 0.149994
sub: 0.199997
lt: 0
classmethod get_input_from(player)[source]

Secret input from player.

Param:player (int)
classmethod set_precision(f, k=None)[source]

Set the precision of the integer representation. Note that some operations are undefined when the precision of sfix and cfix differs. The initial defaults are chosen to allow the best optimization of probabilistic truncation in computation modulo 2^64 (2*k < 64). Generally, 2*k must be at most the integer length for rings and at most m-s-1 for computation modulo an m-bit prime and statistical security s (default 40).

Parameters:
  • f – bit length of decimal part (initial default 16)
  • k – whole bit length of fixed point, defaults to twice f if not given (initial default 31)
class Compiler.GC.types.sbitfixvec(value=None, *args, **kwargs)[source]

Bases: Compiler.types._fix

Vector of fixed-point numbers for parallel binary computation.

Use set_precision() to change the precision.

Example:

a = sbitfixvec([sbitfix(0.3), sbitfix(0.5)])
b = sbitfixvec([sbitfix(0.4), sbitfix(0.6)])
c = (a + b).elements()
print_ln('add: %s, %s', c[0].reveal(), c[1].reveal())
c = (a * b).elements()
print_ln('mul: %s, %s', c[0].reveal(), c[1].reveal())
c = (a - b).elements()
print_ln('sub: %s, %s', c[0].reveal(), c[1].reveal())
c = (a < b).bit_decompose()
print_ln('lt: %s, %s', c[0].reveal(), c[1].reveal())

This should output roughly:

add: 0.699997, 1.10001
mul: 0.119995, 0.300003
sub: -0.0999908, -0.100021
lt: 1, 1
classmethod get_input_from(player)[source]

Secret input from player.

Param:player (int)
classmethod set_precision(f, k=None)[source]

Set the precision of the integer representation. Note that some operations are undefined when the precision of sfix and cfix differs. The initial defaults are chosen to allow the best optimization of probabilistic truncation in computation modulo 2^64 (2*k < 64). Generally, 2*k must be at most the integer length for rings and at most m-s-1 for computation modulo an m-bit prime and statistical security s (default 40).

Parameters:
  • f – bit length of decimal part (initial default 16)
  • k – whole bit length of fixed point, defaults to twice f if not given (initial default 31)
class Compiler.GC.types.sbitint(*args, **kwargs)[source]

Bases: Compiler.types._bitint, Compiler.types._number, Compiler.GC.types.sbits, Compiler.GC.types._sbitintbase

Secret signed integer in one binary register. Use get_type() to specify the bit length:

si32 = sbitint.get_type(32)
print_ln('add: %s', (si32(5) + si32(3)).reveal())
print_ln('sub: %s', (si32(5) - si32(3)).reveal())
print_ln('mul: %s', (si32(5) * si32(3)).reveal())
print_ln('lt: %s', (si32(5) < si32(3)).reveal())

This should output:

add: 8
sub: 2
mul: 15
lt: 0
classmethod get_type(n, other=None)[source]

Returns a signed integer type with fixed length.

Parameters:n – length
pow2(k)[source]

Computer integer power of two.

Parameters:k – bit length of input
class Compiler.GC.types.sbitintvec(elements=None, length=None, input_length=None)[source]

Bases: Compiler.GC.types.sbitvec, Compiler.types._number, Compiler.types._bitint, Compiler.GC.types._sbitintbase

Vector of signed integers for parallel binary computation:

sb32 = sbits.get_type(32)
siv32 = sbitintvec.get_type(32)
a = siv32([sb32(3), sb32(5)])
b = siv32([sb32(4), sb32(6)])
c = (a + b).elements()
print_ln('add: %s, %s', c[0].reveal(), c[1].reveal())
c = (a * b).elements()
print_ln('mul: %s, %s', c[0].reveal(), c[1].reveal())
c = (a - b).elements()
print_ln('sub: %s, %s', c[0].reveal(), c[1].reveal())
c = (a < b).bit_decompose()
print_ln('lt: %s, %s', c[0].reveal(), c[1].reveal())

This should output:

add: 7, 11
mul: 12, 30
sub: -1, 11
lt: 1, 1
pow2(k)[source]

Computer integer power of two.

Parameters:k – bit length of input
class Compiler.GC.types.sbits(*args, **kwargs)[source]

Bases: Compiler.GC.types.bits

Secret bits register. This type supports basic bit-wise operations:

sb32 = sbits.get_type(32)
a = sb32(3)
b = sb32(5)
print_ln('XOR: %s', (a ^ b).reveal())
print_ln('AND: %s', (a & b).reveal())
print_ln('NOT: %s', (~a).reveal())

This will output the following:

XOR: 6
AND: 1
NOT: -4

Instances can be also be initalized from regint and sint.

classmethod get_input_from(player, n_bits=None)[source]

Secret input from player.

Param:player (int)
if_else(x, y)[source]

Vectorized oblivious selection:

sb32 = sbits.get_type(32)
print_ln('%s', sb32(3).if_else(sb32(5), sb32(2)).reveal())

This will output 1.

popcnt()[source]

Population count / Hamming weight.

Returns:sbits of required length
to_sint(n_bits)[source]

Convert the n_bits least significant bits to sint.

class Compiler.GC.types.sbitvec(elements=None, length=None, input_length=None)[source]

Bases: Compiler.types._vec

Vector of registers of secret bits, effectively a matrix of secret bits. This facilitates parallel arithmetic operations in binary circuits. Container types are not supported, use sbitvec.get_type for that.

You can access the rows by member v and the columns by calling elements.

There are three ways to create an instance:

  1. By transposition:

    sb32 = sbits.get_type(32)
    x = sbitvec([sb32(5), sb32(3), sb32(0)])
    print_ln('%s', [x.v[0].reveal(), x.v[1].reveal(), x.v[2].reveal()])
    print_ln('%s', [x.elements()[0].reveal(), x.elements()[1].reveal()])
    

    This should output:

    [3, 2, 1]
    [5, 3]
    
  2. Without transposition:

    sb32 = sbits.get_type(32)
    x = sbitvec.from_vec([sb32(5), sb32(3)])
    print_ln('%s', [x.v[0].reveal(), x.v[1].reveal()])
    

    This should output:

    [5, 3]
    
  3. From sint:

    y = sint(5)
    x = sbitvec(y, 3, 3)
    print_ln('%s', [x.v[0].reveal(), x.v[1].reveal(), x.v[2].reveal()])
    

    This should output:

    [1, 0, 1]
    
classmethod get_type(n)[source]

Create type for fixed-length vector of registers of secret bits.

As with sbitvec, you can access the rows by member v and the columns by calling elements.

popcnt()[source]

Population count / Hamming weight.

Returns:sbitintvec of required length

Compiler.library module

This module defines functions directly available in high-level programs, in particularly providing flow control and output.

Compiler.library.break_point(name='')[source]

Insert break point. This makes sure that all following code will be executed after preceding code.

Parameters:name – Name for identification (optional)
Compiler.library.do_while(loop_fn, g=None)[source]

Do-while loop. The loop is stopped if the return value is zero. It must be public. The following executes exactly once:

@do_while
def _():
    ...
    return regint(0)
Compiler.library.for_range(start, stop=None, step=None)[source]

Decorator to execute loop bodies consecutively. Arguments work as in Python range(), but they can by any public integer. Information has to be passed out via container types such as Array or declaring registers as global. Note that changing Python data structures such as lists within the loop is not possible, but the compiler cannot warn about this.

Parameters:start/stop/step – regint/cint/int

Example:

a = sint.Array(n)
x = sint(0)
@for_range(n)
def _(i):
    a[i] = i
    global x
    x += 1
Compiler.library.for_range_multithread(n_threads, n_parallel, n_loops, thread_mem_req={})[source]

Execute n_loops loop bodies in up to n_threads threads, up to n_parallel in parallel per thread.

Parameters:
  • n_threads/n_parallel – compile-time (int)
  • n_loops – regint/cint/int
Compiler.library.for_range_opt(n_loops, budget=None)[source]

Execute loop bodies in parallel up to an optimization budget. This prevents excessive loop unrolling. The budget is respected even with nested loops. Note that optimization is rather rudimentary for runtime n_loops (regint/cint). Consider using for_range_parallel() in this case.

Parameters:
  • n_loops – int/regint/cint
  • budget – number of instructions after which to start optimization (default is 100,000)

Example:

@for_range_opt(n)
def _(i):
    ...
Compiler.library.for_range_opt_multithread(n_threads, n_loops)[source]

Execute n_loops loop bodies in up to n_threads threads, in parallel up to an optimization budget per thread similar to for_range_opt(). Note that optimization is rather rudimentary for runtime n_loops (regint/cint). Consider using for_range_multithread() in this case.

Parameters:
  • n_threads – compile-time (int)
  • n_loops – regint/cint/int

The following will execute loop bodies 0-9 in one thread, 10-19 in another etc:

@for_range_opt_multithread(8, 80)
def _(i):
    ...

Multidimensional ranges are supported as well. The following executes f(0, 0) to f(2, 0) in one thread and f(2, 1) to f(4, 2) in another.

@for_range_opt_multithread(2, [5, 3])
def f(i, j):
    ...
Compiler.library.for_range_parallel(n_parallel, n_loops)[source]

Decorator to execute a loop n_loops up to n_parallel loop bodies in parallel.

Parameters:
  • n_parallel – compile-time (int)
  • n_loops – regint/cint/int

Example:

@for_range_parallel(n_parallel, n_loops)
def _(i):
    a[i] = a[i] * a[i]
Compiler.library.foreach_enumerate(a)[source]

Run-time loop over public data. This uses Player-Data/Public-Input/<progname>. Example:

@foreach_enumerate([2, 8, 3])
def _(i, j):
    print_ln('%s: %s', i, j)

This will output:

0: 2
1: 8
2: 3
Compiler.library.get_arg(*args, **kwargs)[source]

Returns the thread argument.

Compiler.library.get_number_of_players()[source]
Returns:the number of players
Return type:regint
Compiler.library.get_player_id()[source]
Returns:player number
Return type:localint (cannot be used for computation)
Compiler.library.get_thread_number(*args, **kwargs)[source]

Returns the thread number.

Compiler.library.get_threshold()[source]

The threshold is the maximal number of corrupted players.

Return type:regint
Compiler.library.if_(condition)[source]

Conditional execution without else block.

Parameters:condition – regint/cint/int

Usage:

@if_(x > 0)
def _():
    ...
Compiler.library.if_e(condition)[source]

Conditional execution with else block.

Parameters:condition – regint/cint/int

Usage:

@if_e(x > 0)
def _():
    ...
@else_
def _():
    ...
Compiler.library.multithread(n_threads, n_items=None, max_size=None)[source]

Distribute the computation of n_items to n_threads threads, but leave the in-thread repetition up to the user.

Parameters:
  • n_threads – compile-time (int)
  • n_items – regint/cint/int (default: n_threads)

The following executes f(0, 8), f(8, 8), and f(16, 9) in three different threads:

@multithread(8, 25)
def f(base, size):
    ...
Compiler.library.print_float_precision(n)[source]

Set the precision for floating-point printing.

Parameters:n – number of digits (int)
Compiler.library.print_ln(s='', *args)[source]

Print line, with optional args for adding variables/registers with %s. By default only player 0 outputs, but the -I command-line option changes that.

Parameters:
  • s – Python string with same number of %s as length of args
  • args – list of public values (regint/cint/int/cfix/cfloat/localint)

Example:

print_ln('a is %s.', a.reveal())
Compiler.library.print_ln_if(cond, ss, *args)[source]

Print line if cond is true. The further arguments are treated as in print_str()/print_ln().

Parameters:
  • cond – regint/cint/int/localint
  • ss – Python string
  • args – list of public values

Example:

print_ln_if(get_player_id() == 0, 'Player 0 here')
Compiler.library.print_ln_to(player, ss, *args)[source]

Print line at player only. Note that printing is disabled by default except at player 0. Activate interactive mode with -I to enable it for all players.

Parameters:
  • player – int
  • ss – Python string
  • args – list of values known to player

Example:

print_ln_to(player, 'output for %s: %s', player, x.reveal_to(player))
Compiler.library.print_str(s, *args)[source]

Print a string, with optional args for adding variables/registers with %s.

Compiler.library.print_str_if(cond, ss, *args)[source]

Print string conditionally. See print_ln_if() for details.

Compiler.library.public_input()[source]

Public input read from Programs/Public-Input/<progname>.

Compiler.library.runtime_error(msg='', *args)[source]

Print an error message and abort the runtime. Parameters work as in print_ln()

Compiler.library.start_timer(timer_id=0)[source]

Start timer. Timer 0 runs from the start of the program. The total time of all used timers is output at the end. Fails if already running.

Parameters:timer_id – compile-time (int)
Compiler.library.stop_timer(timer_id=0)[source]

Stop timer. Fails if not running.

Parameters:timer_id – compile-time (int)
Compiler.library.while_do(condition, *args)[source]

While-do loop. The decorator requires an initialization, and the loop body function must return a suitable input for condition.

Parameters:
  • condition – function returning public integer (regint/cint/int)
  • args – arguments given to condition and loop body

The following executes an ten-fold loop:

@while_do(lambda x: x < 10, regint(0))
def f(i):
    ...
    return i + 1

Compiler.mpc_math module

Module for math operations.

Implements trigonometric and logarithmic functions.

This has to imported explicitely.

Compiler.mpc_math.atan(*args, **kwargs)

Returns the arctangent (sfix) of any given fractional value.

Parameters:x – fractional input (sfix).
Returns:arctan of x (sfix).
Compiler.mpc_math.acos(x)[source]

Returns the arccosine (sfix) of any given fractional value.

Parameters:x – fractional input (sfix). \(-1 \le x \le 1\)
Returns:arccos of x (sfix).
Compiler.mpc_math.asin(x)[source]

Returns the arcsine (sfix) of any given fractional value.

Parameters:x – fractional input (sfix). valid interval is \(-1 \le x \le 1\)
Returns:arcsin of x (sfix).
Compiler.mpc_math.cos(*args, **kwargs)

Returns the cosine of any given fractional value.

Parameters:x – fractional input (sfix, sfloat)
Returns:cos of x (sfix, sfloat)
Compiler.mpc_math.exp2_fx(self, *args, **kwargs)

Power of two for fixed-point numbers.

Parameters:
  • a – exponent for \(2^a\) (sfix)
  • zero_output – whether to output zero for very small values. If not, the result will be undefined.
Returns:

\(2^a\) if it is within the range. Undefined otherwise

Compiler.mpc_math.log2_fx(self, *args, **kwargs)

Returns the result of \(\log_2(x)\) for any unbounded number. This is achieved by changing x into \(f \cdot 2^n\) where f is bounded by \([0.5, 1]\). Then the polynomials are used to calculate \(\log_2(f)\), which is then just added to \(n\).

Parameters:x – input for \(\log_2\) (sfix, sint).
Returns:(sfix) the value of \(\log_2(x)\)
Compiler.mpc_math.log_fx(x, b)[source]

Returns the value of the expression \(\log_b(x)\) where x is secret shared. It uses log2_fx() to calculate the expression \(\log_b(2) \cdot \log_2(x)\).

Parameters:
  • x – (sfix, sint) secret shared coefficient for log.
  • b – (float) base for log operation.
Returns:

(sfix) the value of \(log_b(x)\).

Compiler.mpc_math.pow_fx(x, y)[source]

Returns the value of the expression \(x^y\) where both inputs are secret shared. It uses log2_fx() together with exp2_fx() to calculate the expression \(2^{y \log_2(x)}\).

Parameters:
  • x – (sfix) secret shared base.
  • y – (sfix, clear types) secret shared exponent.
Returns:

\(x^y\) (sfix) if positive and in range

Compiler.mpc_math.sin(*args, **kwargs)

Returns the sine of any given fractional value.

Parameters:x – fractional input (sfix, sfloat)
Returns:sin of x (sfix, sfloat)
Compiler.mpc_math.sqrt(self, *args, **kwargs)

Returns the square root (sfix) of any given fractional value as long as it can be rounded to a integral value with f bits of decimal precision.

Parameters:x – fractional input (sfix).
Returns:square root of x (sfix).
Compiler.mpc_math.tan(*args, **kwargs)

Returns the tangent of any given fractional value.

Parameters:x – fractional input (sfix, sfloat)
Returns:tan of x (sfix, sfloat)

Compiler.ml module

This module contains machine learning functionality. It is work in progress, so you must expect things to change. The only tested functionality for training is using consective dense/fully-connected layers. This includes logistic regression. It can be run as follows:

sgd = ml.SGD([ml.Dense(n_examples, n_features, 1),
              ml.Output(n_examples, approx=True)], n_epochs,
             report_loss=True)
sgd.layers[0].X.input_from(0)
sgd.layers[1].Y.input_from(1)
sgd.reset()
sgd.run()

This loads measurements from party 0 and labels (0/1) from party 1. After running, the model is stored in sgd.layers[0].W and sgd.layers[1].b. The approx parameter determines whether to use an approximate sigmoid function. Setting it to 5 uses a five-piece approximation instead of a three-piece one. Inference can be run as follows:

data = sfix.Matrix(n_test, n_features)
data.input_from(0)
res = sgd.eval(data)
print_ln('Results: %s', [x.reveal() for x in res])

For inference/classification, this module offers the layers necessary for neural networks such as DenseNet, ResNet, and SqueezeNet. A minimal example using input from player 0 and model from player 1 looks as follows:

graph = Optimizer()
graph.layers = layers
layers[0].X.input_from(0)
for layer in layers:
    layer.input_from(1)
graph.forward(1)
res = layers[-1].Y

See the readme for an example of how to run MP-SPDZ on TensorFlow graphs.

See also this repository for an example of how to train a model for MNIST.

class Compiler.ml.Add(inputs)[source]

Fixed-point addition layer.

Parameters:inputs – two input layers with same shape (tuple/list)
class Compiler.ml.Argmax(shape)[source]

Fixed-point Argmax layer.

Parameters:shape – input shape (tuple/list of two int)
class Compiler.ml.Concat(inputs, dimension)[source]

Fixed-point concatentation layer.

Parameters:
  • inputs – two input layers (tuple/list)
  • dimension – dimension for concatenation (must be 3)
class Compiler.ml.Dense(N, d_in, d_out, d=1, activation='id', debug=False)[source]

Fixed-point dense (matrix multiplication) layer.

Parameters:
  • N – number of examples
  • d_in – input dimension
  • d_out – output dimension
class Compiler.ml.FixAveragePool2d(input_shape, output_shape, filter_size, strides=(1, 1))[source]

Fixed-point 2D AvgPool layer.

Parameters:
  • input_shape – input shape (tuple/list of four int)
  • output_shape – output shape (tuple/list of four int)
  • filter_size – filter size (tuple/list of two int)
  • strides – strides (tuple/list of two int)
class Compiler.ml.FixConv2d(input_shape, weight_shape, bias_shape, output_shape, stride, padding='SAME', tf_weight_format=False, inputs=None)[source]

Fixed-point 2D convolution layer.

Parameters:
  • input_shape – input shape (tuple/list of four int)
  • weight_shape – weight shape (tuple/list of four int)
  • bias_shape – bias shape (tuple/list of one int)
  • output_shape – output shape (tuple/list of four int)
  • stride – stride (tuple/list of two int)
  • padding'SAME' (default), 'VALID', or tuple/list of two int
  • tf_weight_format – weight shape format is (height, width, input channels, output channels) instead of the default (output channels, height, widght, input channels)
class Compiler.ml.FusedBatchNorm(shape, inputs=None)[source]

Fixed-point fused batch normalization layer.

Parameters:shape – input/output shape (tuple/list of four int)
class Compiler.ml.MaxPool(shape, strides=(1, 2, 2, 1), ksize=(1, 2, 2, 1), padding='VALID')[source]

Fixed-point MaxPool layer.

Parameters:
  • shape – input shape (tuple/list of four int)
  • strides – strides (tuple/list of four int, first and last must be 1)
  • ksize – kernel size (tuple/list of four int, first and last must be 1)
  • padding'VALID' (default) or 'SAME'
class Compiler.ml.MultiOutput(N, d_out, approx=False, debug=False)[source]

Output layer for multi-class classification with softmax and cross entropy.

Parameters:
  • N – number of examples
  • d_out – number of classes
  • approx – use ReLU division instead of softmax for the loss
class Compiler.ml.Optimizer[source]

Base class for graphs of layers.

layers

Get all layers.

set_layers_with_inputs(layers)[source]

Construct graph from inputs members of list of layers.

class Compiler.ml.Output(N, debug=False, approx=False)[source]

Fixed-point logistic regression output layer.

Parameters:
  • N – number of examples
  • approxFalse (default) or parameter for approx_sigmoid
class Compiler.ml.Relu(shape, inputs=None)[source]

Fixed-point ReLU layer.

Parameters:shape – input/output shape (tuple/list of int)
static f(x)

ReLU function (maximum of input and zero).

static f_prime(x)

ReLU derivative.

prime_type

alias of Compiler.types.sint

class Compiler.ml.ReluMultiOutput(N, d_out, approx=False, debug=False)[source]

Output layer for multi-class classification with back-propagation based on ReLU division.

Parameters:
  • N – number of examples
  • d_out – number of classes
class Compiler.ml.SGD(layers, n_epochs, debug=False, report_loss=None)[source]

Stochastic gradient descent.

Parameters:
  • layers – layers of linear graph
  • n_epochs – number of epochs for training
  • report_loss – disclose and print loss
class Compiler.ml.Square(shape, inputs=None)[source]

Fixed-point square layer.

Parameters:shape – input/output shape (tuple/list of int)
prime_type

alias of Compiler.types.sfix

Compiler.ml.argmax(x)[source]

Compute index of maximum element.

Parameters:x – iterable
Returns:sint
Compiler.ml.relu(x)[source]

ReLU function (maximum of input and zero).

Compiler.ml.relu_prime(x)[source]

ReLU derivative.

Compiler.ml.sigmoid(x)[source]

Sigmoid function.

Parameters:x – sfix
Compiler.ml.sigmoid_prime(x)[source]

Sigmoid derivative.

Parameters:x – sfix
Compiler.ml.approx_sigmoid(*args, **kwargs)

Piece-wise approximate sigmoid as in Dahl et al.

Parameters:
  • x – input
  • n – number of pieces, 3 (default) or 5

Compiler.circuit module

This module contains functionality using circuits in the so-called Bristol Fashion format. You can download a few examples including the ones used below into Programs/Circuits as follows:

make Programs/Circuits
class Compiler.circuit.Circuit(name)[source]

Use a Bristol Fashion circuit in a high-level program. The following example adds signed 64-bit inputs from two different parties and prints the result:

from circuit import Circuit
sb64 = sbits.get_type(64)
adder = Circuit('adder64')
a, b = [sbitvec(sb64.get_input_from(i)) for i in (0, 1)]
print_ln('%s', adder(a, b).elements()[0].reveal())

Circuits can also be executed in parallel as the following example shows:

from circuit import Circuit
sb128 = sbits.get_type(128)
key = sb128(0x2b7e151628aed2a6abf7158809cf4f3c)
plaintext = sb128(0x6bc1bee22e409f96e93d7e117393172a)
n = 1000
aes128 = Circuit('aes_128')
ciphertexts = aes128(sbitvec([key] * n), sbitvec([plaintext] * n))
ciphertexts.elements()[n - 1].reveal().print_reg()

This executes AES-128 1000 times in parallel and then outputs the last result, which should be 0x3ad77bb40d7a3660a89ecaf32466ef97, one of the test vectors for AES-128.

class Compiler.circuit.ieee_float(value)[source]

This gives access IEEE754 floating-point operations using Bristol Fashion circuits. The following example computes the standard deviation of 10 integers input by each of party 0 and 1:

from circuit import ieee_float

values = []

for i in range(2):
    for j in range(10):
        values.append(sbitint.get_type(64).get_input_from(i))

fvalues = [ieee_float(x) for x in values]

avg = sum(fvalues) / ieee_float(len(fvalues))
var = sum(x * x for x in fvalues) / ieee_float(len(fvalues)) - avg * avg
stddev = var.sqrt()

print_ln('avg: %s', avg.reveal())
print_ln('var: %s', var.reveal())
print_ln('stddev: %s', stddev.reveal())
Compiler.circuit.sha3_256(x)[source]

This function implements SHA3-256 for inputs of up to 1080 bits:

from circuit import sha3_256
a = sbitvec.from_vec([])
b = sbitvec(sint(0xcc), 8)
for x in a, b:
    sha3_256(x).elements()[0].reveal().print_reg()

This should output the first two test vectors of SHA3-256 in byte-reversed order:

0x5375f6fb6aa989b0c287a923afe81e79ff875921cacc956666d71ebff8c6ffa7
0x17c7e0d65c285af8406d4f21c071851a312b739a8ecdf25c1270d31c39357067

Note that sint to sbitvec conversion is only implemented for computation modulo a power of two.

Compiler.program module

This module contains the building blocks of the compiler such as code blocks and registers. Most relevant is the central Program object that holds various properties of the computation.

class Compiler.program.Program(args, options=<class 'Compiler.program.defaults'>)[source]

A program consists of a list of tapes representing the whole computation.

When compiling an .mpc file, the single instances is available as program in order. When compiling directly from Python code, an instance has to be created before running any instructions.

join_tapes(thread_numbers)[source]

Wait for completion of tapes. See new_tape() for an example.

Parameters:thread_numbers – list of thread numbers
new_tape(function, args=[], name=None, single_thread=False)[source]

Create a new tape from a function. See multithread() and for_range_opt_multithread() for easier-to-use higher-level functionality. The following runs two threads defined by two different functions:

def f():
    ...
def g():
    ...
tapes = [program.new_tape(x) for x in (f, g)]
thread_numbers = program.run_tapes(tapes)
program.join_tapes(threads_numbers)
Parameters:
  • function – Python function defining the thread
  • args – arguments to the function
  • name – name used for files
  • single_thread – Boolean indicating whether tape will never be run in parallel to itself
Returns:

tape handle

options_from_args()[source]

Set a number of options from the command-line arguments.

public_input(x)[source]

Append a value to the public input file.

run_tapes(args)[source]

Run tapes in parallel. See new_tape() for an example.

Parameters:args – list of tape handles or tuples of tape handle and extra argument (for get_arg())
Returns:list of thread numbers
security

The statistical security parameter for non-linear functions.

set_bit_length(bit_length)[source]

Change the integer bit length for non-linear functions.

use_dabit = None

Setting whether to use daBits for non-linear functionality.

use_edabit(change=None)[source]

Setting whether to use edaBits for non-linear functionality (default: false).

Parameters:change – change setting if not None
Returns:setting if change is None
use_split(change=None)[source]

Setting whether to use local arithmetic-binary share conversion for non-linear functionality (default: false).

Parameters:change – change setting if not None
Returns:setting if change is None
use_square(change=None)[source]

Setting whether to use preprocessed square tuples (default: false).

Parameters:change – change setting if not None
Returns:setting if change is None
use_trunc_pr = None

Setting whether to use special probabilistic truncation.

Compiler.oram module

This module contains an implementation of the tree-based oblivious RAM as proposed by Shi et al. as well as the straight-forward construction using linear scanning. Unlike Array, this allows access by a secret index:

a = OptimalORAM(1000)
i = sint.get_input_from(0)
a[i] = sint.get_input_from(1)
Compiler.oram.OptimalORAM(size, *args, **kwargs)[source]

Create an ORAM instance suitable for the size based on experiments.

Parameters:
  • size – number of elements
  • value_typesint (default) / sg2fn