High-Level Interface¶
Compiler.types module¶
This module defines all types available 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¶
All basic can be used as vectors, that is one instance representing several values, with all operations being executed element-wise. For example, the following computes ten multiplications of integers input by party 0 and 1:
sint.get_input_from(0, size=10) * sint.get_input_from(1, size=10)
Secret integer in the protocol-specific domain. |
|
Clear integer in same domain as secure computation (depends on protocol). |
|
Clear 64-bit integer. |
|
Secret fixed-point number represented as secret integer, by multiplying with |
|
Clear fixed-point number represented as clear integer. |
|
Secret floating-point number. |
|
Secret \(\mathrm{GF}(2^n)\) value. |
|
Clear \(\mathrm{GF}(2^n)\) value. |
Container types¶
Single value in memory. |
|
Array accessible by public index. |
|
Matrix. |
|
Multidimensional array. |
- class Compiler.types.Array(length, value_type, address=None, debug=None, alloc=True)[source]¶
Array accessible by public index. That is,
a[i]
works for an arraya
andi
being aregint
,cint
, or a Python integer.- Parameters
length – compile-time integer (int) or
None
for unknown length (need to specifyaddress
)value_type – basic type
address – if given (regint/int), the array will not be allocated
You can convert between arrays and register vectors by using slice indexing. This allows for element-wise operations as long as supported by the basic type. The following adds 10 secret integers from the first two parties:
a = sint.Array(10) a.input_from(0) b = sint.Array(10) b.input_from(1) a[:] += b[:]
- assign(other, base=0)[source]¶
Assignment.
- Parameters
other – vector/Array/Matrix/MultiArray/iterable of compatible type and smaller size
base – index to start assignment at
- assign_all(value, use_threads=True, conv=True)[source]¶
Assign the same value to all entries.
- Parameters
value – convertible to basic type
- assign_part_vector(other, base=0)¶
Assignment.
- Parameters
other – vector/Array/Matrix/MultiArray/iterable of compatible type and smaller size
base – index to start assignment at
- assign_vector(other, base=0)¶
Assignment.
- Parameters
other – vector/Array/Matrix/MultiArray/iterable of compatible type and smaller size
base – index to start assignment at
- classmethod create_from(l)[source]¶
Convert Python iterator or vector to array. Basic type will be taken from first element, further elements must to be convertible to that.
- expand_to_vector(index, size)[source]¶
Create vector from single entry.
- Parameters
index – regint/cint/int
size – int
- get_part(base, size)[source]¶
Part array.
- Parameters
base – start index (regint/cint/int)
size – integer
- Returns
Array of same type
- 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)
- maybe_get(condition, index)[source]¶
Return entry if condition is true.
- Parameters
condition – 0/1 (regint/cint/int)
index – regint/cint/int
- maybe_set(condition, index, value)[source]¶
Change entry if condition is true.
- Parameters
condition – 0/1 (regint/cint/int)
index – regint/cint/int
value – updated value
- print_reveal_nested(end='\n')[source]¶
Reveal and print as list.
- Parameters
end – string to print after (default: line break)
- read_from_file(start)[source]¶
Read content from
Persistence/Transactions-P<playerno>.data
. Precision must be the same as when storing if applicable.- Parameters
start – starting position in number of shares from beginning (int/regint/cint)
- Returns
destination for final position, -1 for eof reached, or -2 for file not found (regint)
- reveal_nested()¶
Reveal as list.
- reveal_to(player)[source]¶
Reveal secret array to
player
.- Parameters
player – public integer (int/regint/cint)
- Returns
personal
containing an array
- reveal_to_binary_output(player=None)[source]¶
Reveal to binary output if supported by type.
- Param
player to reveal to (default all)
- reveal_to_clients(clients)¶
Reveal contents to list of clients.
- Parameters
clients – list or array of client identifiers
- class Compiler.types.Matrix(rows, columns, value_type, debug=None, address=None)[source]¶
Matrix.
- Parameters
rows – compile-time (int)
columns – compile-time (int)
value_type – basic type of entries
- assign(other)¶
Assign container to content. Not implemented for floating-point.
- Parameters
other – container of matching size and type
- assign_all(value)¶
Assign the same value to all entries.
- Parameters
value – convertible to relevant basic type
- assign_part_vector(vector, base=0)¶
Assign vector from range of the first dimension, including all entries in further dimensions.
- Parameters
vector – updated entries
base – index in first dimension (regint/cint/int)
- assign_vector(vector, base=0)¶
Assign vector to content. Not implemented for floating-point.
- Parameters
vector – vector of matching size convertible to relevant basic type
base – compile-time (int)
- assign_vector_by_indices(vector, *indices)¶
Assign vector to entries with potential asterisks. See
get_vector_by_indices()
for an example.
- diag()¶
Matrix diagonal.
- direct_mul(other, reduce=True, indices=None)¶
Matrix multiplication in the virtual machine.
- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- 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)¶
Matrix multiplication in the virtual machine.
- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
- Returns
- direct_mul_trans(other, reduce=True, indices=None)¶
Matrix multiplication with the transpose of
other
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- Returns
Matrix as vector of relevant type (row-major)
- direct_trans_mul(other, reduce=True, indices=None)¶
Matrix multiplication with the transpose of
self
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- Returns
Matrix as vector of relevant type (row-major)
- dot(other, res_params=None, n_threads=None)¶
Matrix-matrix and matrix-vector multiplication.
- Parameters
self – two-dimensional
other – Matrix or Array of matching size and type
n_threads – number of threads (default: all in same thread)
- get_part(start, size)¶
Part multi-array.
- Parameters
start – first-dimension index (regint/cint/int)
size – int
- get_part_vector(base=0, size=None)¶
Vector from range of the first dimension, including all entries in further dimensions.
- Parameters
base – index in first dimension (regint/cint/int)
size – size in first dimension (int)
- get_slice_vector(slice)¶
Vector from range of indicies of the first dimension, including all entries in further dimensions.
- Parameters
slice – regint array
- get_vector(base=0, size=None)¶
Return vector with content. Not implemented for floating-point.
- Parameters
base – public (regint/cint/int)
size – compile-time (int)
- get_vector_by_indices(*indices)¶
Vector with potential asterisks. The potential retrieves all entry where the first dimension index is 0, and the third dimension index is 1:
a.get_vector_by_indices(0, None, 1)
- iadd(other)¶
Element-wise addition in place.
- Parameters
other – container of matching size and type
- input_from(player, budget=None, raw=False)¶
Fill with inputs from player if supported by type.
- Parameters
player – public (regint/cint/int)
- mul_trans(other)¶
Matrix multiplication with transpose of
other
.- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- mul_trans_to(other, res, n_threads=None)¶
Matrix multiplication with the transpose of
other
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
res – matrix of matching dimension to store result
n_threads – number of threads (default: single thread)
- plain_mul(other, res=None)¶
Alternative matrix multiplication.
- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- print_reveal_nested(end='\n')¶
Reveal and print as nested list.
- Parameters
end – string to print after (default: line break)
- randomize(*args)¶
Randomize according to data type.
- read_from_file(start)¶
Read content from
Persistence/Transactions-P<playerno>.data
. Precision must be the same as when storing if applicable.- Parameters
start – starting position in number of shares from beginning (int/regint/cint)
- Returns
destination for final position, -1 for eof reached, or -2 for file not found (regint)
- reveal_list()¶
Reveal as list.
- reveal_nested()¶
Reveal as nested list.
- reveal_to_binary_output(player=None)¶
Reveal to binary output if supported by type.
- Param
player to reveal to (default all)
- reveal_to_clients(clients)¶
Reveal contents to list of clients.
- Parameters
clients – list or array of client identifiers
- same_shape()¶
- Returns
new multidimensional array with same shape and basic type
- schur(other)¶
Element-wise product.
- Parameters
other – container of matching size and type
- Returns
container of same shape and type as
self
- set_column(index, vector)[source]¶
Change column.
- Parameters
index – regint/cint/int
vector – short enought vector of compatible type
- trace()¶
Matrix trace.
- trans_mul(other, reduce=True, res=None)¶
Matrix multiplication with transpose of
self
- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- trans_mul_to(other, res, n_threads=None)¶
Matrix multiplication with the transpose of
self
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
res – matrix of matching dimension to store result
n_threads – number of threads (default: single thread)
- transpose()¶
Matrix transpose.
- Parameters
self – two-dimensional
- write_to_file(position=None)¶
Write shares of integer representation to
Persistence/Transactions-P<playerno>.data
.- Parameters
position – start position (int/regint/cint), defaults to end of file
- class Compiler.types.MemValue(value, address=None)[source]¶
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.- Parameters
value – basic type or int (will be converted to regint)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- square()¶
Square.
- class Compiler.types.MultiArray(sizes, value_type, debug=None, address=None, alloc=True)[source]¶
Multidimensional array. The access operator (
a[i]
) allows to a multi-dimensional array of dimension one less or a simple array for a two-dimensional array.- Parameters
sizes – shape (compile-time list of integers)
value_type – basic type of entries
You can convert between arrays and register vectors by using slice indexing. This allows for element-wise operations as long as supported by the basic type. The following has the first two parties input a 10x10 secret integer matrix followed by storing the element-wise multiplications in the same data structure:
a = sint.Tensor([3, 10, 10]) a[0].input_from(0) a[1].input_from(1) a[2][:] = a[0][:] * a[1][:]
- assign(other)¶
Assign container to content. Not implemented for floating-point.
- Parameters
other – container of matching size and type
- assign_all(value)¶
Assign the same value to all entries.
- Parameters
value – convertible to relevant basic type
- assign_part_vector(vector, base=0)¶
Assign vector from range of the first dimension, including all entries in further dimensions.
- Parameters
vector – updated entries
base – index in first dimension (regint/cint/int)
- assign_vector(vector, base=0)¶
Assign vector to content. Not implemented for floating-point.
- Parameters
vector – vector of matching size convertible to relevant basic type
base – compile-time (int)
- assign_vector_by_indices(vector, *indices)¶
Assign vector to entries with potential asterisks. See
get_vector_by_indices()
for an example.
- diag()¶
Matrix diagonal.
- direct_mul(other, reduce=True, indices=None)¶
Matrix multiplication in the virtual machine.
- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- 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)¶
Matrix multiplication in the virtual machine.
- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
- Returns
- direct_mul_trans(other, reduce=True, indices=None)¶
Matrix multiplication with the transpose of
other
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- Returns
Matrix as vector of relevant type (row-major)
- direct_trans_mul(other, reduce=True, indices=None)¶
Matrix multiplication with the transpose of
self
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
indices – 4-tuple of
regint
vectors for index selection (default is complete multiplication)
- Returns
Matrix as vector of relevant type (row-major)
- dot(other, res_params=None, n_threads=None)¶
Matrix-matrix and matrix-vector multiplication.
- Parameters
self – two-dimensional
other – Matrix or Array of matching size and type
n_threads – number of threads (default: all in same thread)
- get_part(start, size)¶
Part multi-array.
- Parameters
start – first-dimension index (regint/cint/int)
size – int
- get_part_vector(base=0, size=None)¶
Vector from range of the first dimension, including all entries in further dimensions.
- Parameters
base – index in first dimension (regint/cint/int)
size – size in first dimension (int)
- get_slice_vector(slice)¶
Vector from range of indicies of the first dimension, including all entries in further dimensions.
- Parameters
slice – regint array
- get_vector(base=0, size=None)¶
Return vector with content. Not implemented for floating-point.
- Parameters
base – public (regint/cint/int)
size – compile-time (int)
- get_vector_by_indices(*indices)¶
Vector with potential asterisks. The potential retrieves all entry where the first dimension index is 0, and the third dimension index is 1:
a.get_vector_by_indices(0, None, 1)
- iadd(other)¶
Element-wise addition in place.
- Parameters
other – container of matching size and type
- input_from(player, budget=None, raw=False)¶
Fill with inputs from player if supported by type.
- Parameters
player – public (regint/cint/int)
- mul_trans(other)¶
Matrix multiplication with transpose of
other
.- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- mul_trans_to(other, res, n_threads=None)¶
Matrix multiplication with the transpose of
other
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
res – matrix of matching dimension to store result
n_threads – number of threads (default: single thread)
- plain_mul(other, res=None)¶
Alternative matrix multiplication.
- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- print_reveal_nested(end='\n')¶
Reveal and print as nested list.
- Parameters
end – string to print after (default: line break)
- randomize(*args)¶
Randomize according to data type.
- read_from_file(start)¶
Read content from
Persistence/Transactions-P<playerno>.data
. Precision must be the same as when storing if applicable.- Parameters
start – starting position in number of shares from beginning (int/regint/cint)
- Returns
destination for final position, -1 for eof reached, or -2 for file not found (regint)
- reveal_list()¶
Reveal as list.
- reveal_nested()¶
Reveal as nested list.
- reveal_to_binary_output(player=None)¶
Reveal to binary output if supported by type.
- Param
player to reveal to (default all)
- reveal_to_clients(clients)¶
Reveal contents to list of clients.
- Parameters
clients – list or array of client identifiers
- same_shape()¶
- Returns
new multidimensional array with same shape and basic type
- schur(other)¶
Element-wise product.
- Parameters
other – container of matching size and type
- Returns
container of same shape and type as
self
- trace()¶
Matrix trace.
- trans_mul(other, reduce=True, res=None)¶
Matrix multiplication with transpose of
self
- Parameters
self – two-dimensional
other – two-dimensional container of matching type and size
- trans_mul_to(other, res, n_threads=None)¶
Matrix multiplication with the transpose of
self
in the virtual machine.- Parameters
self –
Matrix
/ 2-dimensionalMultiArray
other –
Matrix
/ 2-dimensionalMultiArray
res – matrix of matching dimension to store result
n_threads – number of threads (default: single thread)
- transpose()¶
Matrix transpose.
- Parameters
self – two-dimensional
- write_to_file(position=None)¶
Write shares of integer representation to
Persistence/Transactions-P<playerno>.data
.- Parameters
position – start position (int/regint/cint), defaults to end of file
- class Compiler.types.cfix(**kwargs)[source]¶
Clear fixed-point number represented as clear integer. It supports basic arithmetic (
+, -, *, /
), returning eithercfix
if the other operand is public (cfix/regint/cint/int) orsfix
if the other operand is an sfix. It also support comparisons (==, !=, <, <=, >, >=
), returning eitherregint
orsbitint
.- Parameters
v – cfix/float/int
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- binary_output(*args, **kwargs)[source]¶
Write double-precision floating-point number to
Player-Data/Binary-Output-P<playerno>-<threadno>
.- Parameters
player – only output on given player (default all)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- 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)
- Param
vector size (int)
- 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
andcfix
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)
- square()¶
Square.
- class Compiler.types.cfloat(**kwargs)[source]¶
Helper class for printing revealed sfloats.
- class Compiler.types.cgf2n(val=None, size=None)[source]¶
Clear \(\mathrm{GF}(2^n)\) value. n is chosen at runtime. A number operators are supported (
+, -, *, /, **, ^, &, |, ~, ==, !=, <<, >>
), returning eithercgf2n
if the other operand is public (cgf2n/regint/int) orsgf2n
if the other operand is secret. The following operators require the other operand to be a compile-time integer:**, <<, >>
.*, /, **
refer to field multiplication and division.- Parameters
val – initialization (cgf2n/cint/regint/int or list thereof)
size – vector size (int), defaults to 1 or size of list
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- binary_output(*args, **kwargs)¶
Write 64-bit signed integer to
Player-Data/Binary-Output-P<playerno>-<threadno>
.- Parameters
player – only output on given player (default all)
- bit_and(other)¶
AND in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- 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)
- bit_not()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
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)¶
Swapping in \(\mathrm{GF}(2^n)\). Similar to
_int.if_else()
.
- half_adder(other)¶
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)
- if_else(a, b)¶
MUX in \(\mathrm{GF}(2^n)\) circuits. Similar to
_int.if_else()
.
- classmethod malloc(size, creator_tape=None)¶
Allocate memory (statically).
- Parameters
size – compile-time (int)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- print_reg_plain(*args, **kwargs)¶
Output.
- reveal()¶
Identity.
- square()¶
Square.
- class Compiler.types.cint(**kwargs)[source]¶
Clear integer in same domain as secure computation (depends on protocol). A number operators are supported (
+, -, *, /, //, **, %, ^, &, |, ~, ==, !=, <<, >>
), returning eithercint
if the other operand is public (cint/regint/int) orsint
if the other operand issint
. Comparison operators (==, !=, <, <=, >, >=
) are also supported, returningregint()
. Comparisons and~
require that the value is within the global bit length. The same holds forabs()
./
runs field division if the modulus is a prime while//
runs integer floor division.**
requires the exponent to be compile-time integer or the base to be two.- Parameters
val – initialization (cint/regint/int/cgf2n or list thereof)
size – vector size (int), defaults to 1 or size of list
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- binary_output(*args, **kwargs)¶
Write 64-bit signed integer to
Player-Data/Binary-Output-P<playerno>-<threadno>
.- Parameters
player – only output on given player (default all)
- static bit_adder(*args, **kwargs)¶
Binary adder in arithmetic circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
AND in arithmetic circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod bit_compose(bits)¶
Compose value from bits.
- Parameters
bits – iterable of any type implementing left shift
- bit_decompose(*args, **kwargs)[source]¶
Clear bit decomposition.
- Parameters
bit_length – number of bits (default is global bit length)
- Returns
list of cint
- bit_not()¶
NOT in arithmetic circuits.
- bit_or(other)¶
OR in arithmetic circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
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)¶
Swapping in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
(a, b)
ifself
is 0,(b, a)
ifself
is 1, and undefined otherwise- Return type
depending on operands, secret if any of them is
- half_adder(other)¶
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)¶
MUX on bit in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
a if
self
is 1, b ifself
is 0, undefined otherwise- Return type
depending on operands, secret if any of them is
- less_than(*args, **kwargs)[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
- classmethod malloc(size, creator_tape=None)¶
Allocate memory (statically).
- Parameters
size – compile-time (int)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- print_reg_plain(*args, **kwargs)¶
Output.
- 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)
size – vector size (default 1)
- Returns
cint (if n=1) or list of cint
- reveal()¶
Identity.
- square()¶
Square.
- class Compiler.types.localint(value=None)[source]¶
Local integer that must prevented from leaking into the secure computation. Uses regint internally.
- Parameters
value – initialization, convertible to regint
- class Compiler.types.personal(player, value)[source]¶
Value known to one player. Supports operations with public values and personal values known to the same player. Can be used with
print_ln_to()
.- Parameters
player – player (int)
value – cleartext value (cint, cfix, cfloat) or array thereof
- class Compiler.types.regint(**kwargs)[source]¶
Clear 64-bit integer. Unlike
cint
this is always a 64-bit integer. The type supports the following operations withregint
or Python integers, always returningregint
:+, -, *, %, /, //, **, ^, &, |, <<, >>, ==, !=, <, <=, >, >=
. For operations with other types, see the respective descriptions. Both/
and//
stand for floor division.- Parameters
val – initialization (cint/cgf2n/regint/int or list thereof)
size – vector size (int), defaults to 1 or size of list
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- binary_output(player=None)[source]¶
Write 64-bit signed integer to
Player-Data/Binary-Output-P<playerno>-<threadno>
.- Parameters
player – only output on given player (default all)
- static bit_adder(*args, **kwargs)¶
Binary adder in arithmetic circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
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_decompose(*args, **kwargs)[source]¶
Clear bit decomposition.
- Parameters
bit_length – number of bits (defaults to global bit length)
- Returns
list of regint
- bit_not()¶
NOT in arithmetic circuits.
- bit_or(other)¶
OR in arithmetic circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
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)¶
Swapping in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
(a, b)
ifself
is 0,(b, a)
ifself
is 1, and undefined otherwise- Return type
depending on operands, secret if any of them is
- classmethod get_random(*args, **kwargs)[source]¶
Public insecure randomness.
- Parameters
bit_length – number of bits (int)
size – vector size (int, default 1)
- half_adder(other)¶
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)¶
MUX on bit in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
a if
self
is 1, b ifself
is 0, undefined otherwise- Return type
depending on operands, secret if any of them is
- classmethod inc(size, base=0, step=1, repeat=1, wrap=None)[source]¶
Produce
regint
vector with certain patterns. This is particularly useful forSubMultiArray.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)
- classmethod malloc(size, creator_tape=None)¶
Allocate memory (statically).
- Parameters
size – compile-time (int)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible 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)
size – vector size (default 1)
- Returns
regint (if n=1) or list of regint
- square()¶
Square.
- class Compiler.types.sfix(**kwargs)[source]¶
Secret fixed-point number represented as secret integer, by multiplying with
2^f
and then rounding. Seesint
for security considerations of the underlying integer operations. The secret integer is stored as thev
member.It supports basic arithmetic (
+, -, *, /
), returningsfix
, and comparisons (==, !=, <, <=, >, >=
), returningsbitint
. The other operand can be any of sfix/sint/cfix/regint/cint/int/float. It also supportsabs()
and**
, the latter for integer exponents.Note that the default precision (16 bits after the dot, 31 bits in total) only allows numbers up to \(2^{31-16-1} \approx 16000\). You can increase this using
set_precision()
.- Params _v
int/float/regint/cint/sint/sfloat
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- compute_reciprocal(*args, **kwargs)¶
Secret fixed-point reciprocal.
- 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)
size – vector size (int, default 1)
- 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
size – vector size (int, default 1)
- classmethod input_tensor_from(player, shape)¶
Input tensor secretly from player.
- Parameters
player – int/regint/cint
shape – tensor shape
- classmethod input_tensor_from_client(client_id, shape)¶
Input tensor secretly from client.
- Parameters
client_id – client identifier (public)
shape – tensor shape
- classmethod input_tensor_via(player, content)¶
Input tensor-like data via a player. This overwrites the input file for the relevant player. The following returns an
sint
matrix of dimension 2 by 2:M = [[1, 2], [3, 4]] sint.input_tensor_via(0, M)
Make sure to copy
Player-Data/Input-P<player>-0
if running on another host.
- classmethod load_mem(*args, **kwargs)¶
Load from memory by public address.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- classmethod read_from_file(*args, **kwargs)¶
Read shares from
Persistence/Transactions-P<playerno>.data
. Precision must be the same as when storing.- 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 receive_from_client(*args, **kwargs)¶
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
size – vector size (default 1)
- reveal()¶
Reveal secret fixed-point number.
- Returns
relevant clear type
- reveal_to(player)[source]¶
Reveal secret value to
player
.- Parameters
player – public integer (int/regint/cint)
- Returns
- classmethod reveal_to_clients(clients, values)¶
Reveal securely to clients.
- Parameters
clients – client ids (list or array)
values – list of values of this class
- round_nearest = False¶
Whether to round deterministically to nearest instead of probabilistically, e.g. after fixed-point multiplication.
- classmethod set_precision(f, k=None)¶
Set the precision of the integer representation. Note that some operations are undefined when the precision of
sfix
andcfix
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)
- square()¶
Square.
- store_in_mem(address)¶
Store in memory by public address.
Send shares of integer representations of a list of values to a specified client socket.
- Parameters
client_id – regint
values – list of values of this type
- classmethod write_to_file(shares, position=None)¶
Write shares of integer representation to
Persistence/Transactions-P<playerno>.data
.- Parameters
shares – (list or iterable of sfix)
position – start position (int/regint/cint), defaults to end of file
- class Compiler.types.sfloat(**kwargs)[source]¶
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.The type supports basic arithmetic (
+, -, *, /
), returningsfloat
, and comparisons (==, !=, <, <=, >, >=
), returningsint
. The other operand can be any of sint/cfix/regint/cint/int/float.- Parameters
v – initialization (sfloat/sfix/float/int/sint/cint/regint)
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- classmethod get_input_from(*args, **kwargs)[source]¶
Secret floating-point input.
- Parameters
player – public (regint/cint/int)
size – vector size (int, default 1)
- classmethod input_tensor_from(player, shape)¶
Input tensor secretly from player.
- Parameters
player – int/regint/cint
shape – tensor shape
- classmethod input_tensor_from_client(client_id, shape)¶
Input tensor secretly from client.
- Parameters
client_id – client identifier (public)
shape – tensor shape
- classmethod input_tensor_via(player, content)¶
Input tensor-like data via a player. This overwrites the input file for the relevant player. The following returns an
sint
matrix of dimension 2 by 2:M = [[1, 2], [3, 4]] sint.input_tensor_via(0, M)
Make sure to copy
Player-Data/Input-P<player>-0
if running on another host.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- square()¶
Square.
- class Compiler.types.sgf2n(val=None, size=None)[source]¶
Secret \(\mathrm{GF}(2^n)\) value. n is chosen at runtime. A number operators are supported (
+, -, *, /, **, ^, ~, ==, !=, <<
),sgf2n
. Operators generally work with cgf2n/regint/cint/int, except**, <<
, which require a compile-time integer./
refers to field division.*, /, **
refer to field multiplication and division.- Parameters
val – initialization (sgf2n/cgf2n/regint/int/cint or list thereof)
size – vector size (int), defaults to 1 or size of list
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- bit_and(other)¶
AND in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod bit_compose(bits)¶
Compose value from bits.
- Parameters
bits – iterable of any type convertible to sint
- bit_decompose(*args, **kwargs)[source]¶
Secret bit decomposition.
- Parameters
bit_length – number of bits
step – use every
step
-th bit
- Returns
list of sgf2n
- bit_not()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
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)¶
Swapping in \(\mathrm{GF}(2^n)\). Similar to
_int.if_else()
.
- classmethod dot_product(*args, **kwargs)¶
Secret dot product.
- Parameters
x – Iterable of secret values
y – Iterable of secret values of same length and type
- Return type
same as inputs
- equal(other, bit_length=None, expand=1)[source]¶
Secret comparison.
- Parameters
other – sgf2n/cgf2n/regint/int
- Returns
0/1 (sgf2n)
- classmethod get_input_from(*args, **kwargs)¶
Secret input from player.
- Parameters
player – public (regint/cint/int)
size – vector size (int, default 1)
- classmethod get_random_bit(*args, **kwargs)¶
Secret random bit according to security model.
- Returns
0/1 50-50
- Parameters
size – vector size (int, default 1)
- classmethod get_random_input_mask_for(*args, **kwargs)¶
Secret random input mask according to security model.
- Returns
mask (sint), mask (personal cint)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_inverse(*args, **kwargs)¶
Secret random inverse tuple according to security model.
- Returns
\((a, a^{-1})\)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_square(*args, **kwargs)¶
Secret random square according to security model.
- Returns
\((a, a^2)\)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_triple(*args, **kwargs)¶
Secret random triple according to security model.
- Returns
\((a, b, ab)\)
- Parameters
size – vector size (int, default 1)
- half_adder(other)¶
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)
- if_else(a, b)¶
MUX in \(\mathrm{GF}(2^n)\) circuits. Similar to
_int.if_else()
.
- classmethod input_tensor_from(player, shape)¶
Input tensor secretly from player.
- Parameters
player – int/regint/cint
shape – tensor shape
- classmethod input_tensor_from_client(client_id, shape)¶
Input tensor secretly from client.
- Parameters
client_id – client identifier (public)
shape – tensor shape
- classmethod input_tensor_via(player, content)¶
Input tensor-like data via a player. This overwrites the input file for the relevant player. The following returns an
sint
matrix of dimension 2 by 2:M = [[1, 2], [3, 4]] sint.input_tensor_via(0, M)
Make sure to copy
Player-Data/Input-P<player>-0
if running on another host.
- classmethod malloc(size, creator_tape=None)¶
Allocate memory (statically).
- Parameters
size – compile-time (int)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- not_equal(other, bit_length=None)[source]¶
Secret comparison.
- Parameters
other – sgf2n/cgf2n/regint/int
- Returns
0/1 (sgf2n)
- reveal(*args, **kwargs)¶
Reveal secret value publicly.
- Return type
relevant clear type
- 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)
- square(*args, **kwargs)¶
Secret square.
- class Compiler.types.sint(**kwargs)[source]¶
Secret integer in the protocol-specific domain. It supports operations with
sint
,cint
,regint
, and Python integers. Operations where one of the operands is ansint
either result in ansint
or ansintbit
, the latter for comparisons.The following operations work as expected in the computation domain (modulo a prime or a power of two):
+, -, *
./
denotes the field division modulo a prime. It will reveal if the divisor is zero. Comparisons operators (==, !=, <, <=, >, >=
) assume that the element in the computation domain represents a signed integer in a restricted range, see below. The same holds forabs()
, shift operators (<<, >>
), modulo (%
), and exponentation (**
). Modulo only works if the right-hand operator is a compile-time power of two, and exponentiation only works if the base is two or if the exponent is a compile-time integer.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()
andprogram.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.
- Parameters
val – initialization (sint/cint/regint/int/cgf2n or list thereof, sbits/sbitvec/sfix, or
personal
)size – vector size (int), defaults to 1 or size of list
When converting
sbits
, the result is a vector of bits, and when convertingsbitvec
, the result is a vector of values with bit length equal the length of the input.Initializing from a
personal
value implies the relevant party inputting their value securely.- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod Matrix(rows, columns, *args, **kwargs)¶
Type-dependent matrix. Example:
a = sint.Matrix(10, 10)
- classmethod MemValue(value)¶
- classmethod Tensor(shape)¶
Type-dependent tensor of any dimension:
a = sfix.Tensor([10, 10])
- static bit_adder(*args, **kwargs)¶
Binary adder in arithmetic circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
AND in arithmetic circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod bit_compose(bits)¶
Compose value from bits.
- Parameters
bits – iterable of any type convertible to sint
- bit_not()¶
NOT in arithmetic circuits.
- bit_or(other)¶
OR in arithmetic circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
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)¶
Swapping in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
(a, b)
ifself
is 0,(b, a)
ifself
is 1, and undefined otherwise- Return type
depending on operands, secret if any of them is
- classmethod dot_product(*args, **kwargs)¶
Secret dot product.
- Parameters
x – Iterable of secret values
y – Iterable of secret values of same length and type
- Return type
same as inputs
- equal(*args, **kwargs)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- classmethod get_dabit(*args, **kwargs)[source]¶
Bit in arithmetic and binary circuit according to security model
- classmethod get_input_from(*args, **kwargs)[source]¶
Secret input.
- Parameters
player – public (regint/cint/int)
size – vector size (int, default 1)
- classmethod get_random(*args, **kwargs)[source]¶
Secret random ring element according to security model.
- Parameters
size – vector size (int, default 1)
- classmethod get_random_bit(*args, **kwargs)¶
Secret random bit according to security model.
- Returns
0/1 50-50
- Parameters
size – vector size (int, default 1)
- classmethod get_random_input_mask_for(*args, **kwargs)¶
Secret random input mask according to security model.
- Returns
mask (sint), mask (personal cint)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_int(*args, **kwargs)[source]¶
Secret random n-bit number according to security model.
- Parameters
bits – compile-time integer (int)
size – vector size (int, default 1)
- classmethod get_random_inverse(*args, **kwargs)¶
Secret random inverse tuple according to security model.
- Returns
\((a, a^{-1})\)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_square(*args, **kwargs)¶
Secret random square according to security model.
- Returns
\((a, a^2)\)
- Parameters
size – vector size (int, default 1)
- classmethod get_random_triple(*args, **kwargs)¶
Secret random triple according to security model.
- Returns
\((a, b, ab)\)
- Parameters
size – vector size (int, default 1)
- greater_equal(other, bit_length=None, security=None)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- greater_than(*args, **kwargs)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- half_adder(other)¶
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)¶
MUX on bit in arithmetic circuits.
- Parameters
a/b – any type supporting the necessary operations
- Returns
a if
self
is 1, b ifself
is 0, undefined otherwise- Return type
depending on operands, secret if any of them is
- classmethod input_tensor_from(player, shape)¶
Input tensor secretly from player.
- Parameters
player – int/regint/cint
shape – tensor shape
- classmethod input_tensor_from_client(client_id, shape)¶
Input tensor secretly from client.
- Parameters
client_id – client identifier (public)
shape – tensor shape
- classmethod input_tensor_via(player, content)¶
Input tensor-like data via a player. This overwrites the input file for the relevant player. The following returns an
sint
matrix of dimension 2 by 2:M = [[1, 2], [3, 4]] sint.input_tensor_via(0, M)
Make sure to copy
Player-Data/Input-P<player>-0
if running on another host.
- int_div(*args, **kwargs)[source]¶
Secret integer division.
- Parameters
other – sint
bit_length – bit length of input (default: global bit length)
- left_shift(other, bit_length=None, security=None)¶
Secret left shift.
- Parameters
other – secret or public integer (sint/cint/regint/int)
bit_length – bit length of input (default: global bit length)
- less_equal(other, bit_length=None, security=None)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- less_than(*args, **kwargs)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- classmethod malloc(size, creator_tape=None)¶
Allocate memory (statically).
- Parameters
size – compile-time (int)
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- mod2m(*args, **kwargs)[source]¶
Secret modulo power of two.
- Parameters
m – secret or public integer (sint/cint/regint/int)
bit_length – bit length of input (default: global bit length)
- not_equal(other, bit_length=None, security=None)¶
Secret comparison (signed).
- Parameters
other – sint/cint/regint/int
bit_length – bit length of input (default: global bit length)
- Returns
0/1 (sintbit)
- pow2(*args, **kwargs)[source]¶
Secret power of two.
- Parameters
bit_length – bit length of input (default: global bit length)
- private_division(divisor, active=True, dividend_length=None, divisor_length=None)[source]¶
Private integer division as per Veugen and Abspoel
- Parameters
divisor – public (cint/regint) or personal value thereof
active – whether to check on the party knowing the divisor (active security)
dividend_length – bit length of the dividend (default: global bit length)
dividend_length – bit length of the divisor (default: global bit length)
- 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)
size – vector size of values (default 1)
- Returns
sint (if n=1) or list of sint
- classmethod receive_from_client(*args, **kwargs)[source]¶
Securely obtain shares of values input by a client. This uses the triple-based input protocol introduced by Damgård et al.
- Parameters
n – number of inputs (int)
client_id – regint
size – vector size (default 1)
- Returns
list of sint
- reveal(*args, **kwargs)¶
Reveal secret value publicly.
- Return type
relevant clear type
- reveal_to(*args, **kwargs)[source]¶
Reveal secret value to
player
.- Parameters
player – public integer (int/regint/cint)
- Returns
- classmethod reveal_to_clients(clients, values)[source]¶
Reveal securely to clients.
- Parameters
clients – client ids (list or array)
values – list of sint to reveal
- right_shift(*args, **kwargs)¶
Secret right shift.
- Parameters
other – secret or public integer (sint/cint/regint/int)
bit_length – bit length of input (default: global bit length)
- round(*args, **kwargs)[source]¶
Truncate and maybe round secret
k
-bit integer bym
bits.m
can be secret ifnearest
is false, in which case the truncation will be exact. For publicm
,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
- square(*args, **kwargs)¶
Secret square.
Send shares of a list of values to a specified client socket.
- Parameters
client_id – regint
values – list 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.
Computation using these types will always be executed as a binary circuit. See Protocol Pairs for the exact protocols.
- class Compiler.GC.types.cbits(value=None, n=None, size=None)[source]¶
Clear bits register. Helper type with limited functionality.
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- bit_and(other)¶
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()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
XOR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod get_type(length)¶
Returns a fixed-length type.
- half_adder(other)¶
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)
- if_else(x, y)¶
Vectorized oblivious selection:
sb32 = sbits.get_type(32) print_ln('%s', sb32(3).if_else(sb32(5), sb32(2)).reveal())
This will output 1.
- class Compiler.GC.types.sbit(*args, **kwargs)[source]¶
Single secret bit.
- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- static bit_adder(*args, **kwargs)¶
Binary adder in binary circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
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()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
XOR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod get_input_from(player, n_bits=None)¶
Secret input from
player
.- Param
player (int)
- classmethod get_type(length)¶
Returns a fixed-length type.
- half_adder(other)¶
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.GC.types.sbitfix(**kwargs)[source]¶
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
Note that the default precision (16 bits after the dot, 31 bits in total) only allows numbers up to \(2^{31-16-1} \approx 16000\). You can increase this using
set_precision()
.- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- add(*args, **kwargs)¶
Secret fixed-point addition.
- Parameters
other – sfix/cfix/sint/cint/regint/int
- compute_reciprocal(*args, **kwargs)¶
Secret fixed-point reciprocal.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- reveal()¶
Reveal secret fixed-point number.
- Returns
relevant clear type
- round_nearest = False¶
Whether to round deterministically to nearest instead of probabilistically, e.g. after fixed-point multiplication.
- 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
andcfix
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)
- square()¶
Square.
- store_in_mem(address)¶
Store in memory by public address.
- class Compiler.GC.types.sbitfixvec(value=None, *args, **kwargs)[source]¶
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 Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- add(*args, **kwargs)¶
Secret fixed-point addition.
- Parameters
other – sfix/cfix/sint/cint/regint/int
- compute_reciprocal(*args, **kwargs)¶
Secret fixed-point reciprocal.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- reveal()¶
Reveal secret fixed-point number.
- Returns
relevant clear type
- round_nearest = False¶
Whether to round deterministically to nearest instead of probabilistically, e.g. after fixed-point multiplication.
- 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
andcfix
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)
- square()¶
Square.
- store_in_mem(address)¶
Store in memory by public address.
- class Compiler.GC.types.sbitint(*args, **kwargs)[source]¶
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 Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- classmethod bit_adder(a, b, carry_in=0, get_carry=False)¶
Binary adder in binary circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
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()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
XOR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod get_input_from(player, n_bits=None)¶
Secret input from
player
.- Param
player (int)
- classmethod get_type(n, other=None)[source]¶
Returns a signed integer type with fixed length.
- Parameters
n – length
- static half_adder(a, b)¶
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)
- if_else(x, y)¶
Vectorized oblivious selection:
sb32 = sbits.get_type(32) print_ln('%s', sb32(3).if_else(sb32(5), sb32(2)).reveal())
This will output 1.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- square()¶
Square.
- class Compiler.GC.types.sbitintvec(elements=None, length=None, input_length=None)[source]¶
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
- classmethod get_type(n)¶
Create type for fixed-length vector of registers of secret bits.
As with
sbitvec
, you can access the rows by memberv
and the columns by callingelements
.
- max(other)¶
Maximum.
- Parameters
other – any compatible type
- min(other)¶
Minimum.
- Parameters
other – any compatible type
- popcnt()¶
Population count / Hamming weight.
- Returns
sbitintvec
of required length
- square()¶
Square.
- class Compiler.GC.types.sbits(*args, **kwargs)[source]¶
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
andsint
.- classmethod Array(size, *args, **kwargs)¶
Type-dependent array. Example:
a = sint.Array(10)
- classmethod MemValue(value)¶
- static bit_adder(*args, **kwargs)[source]¶
Binary adder in binary circuits.
- Parameters
a – summand (list of 0/1 in compatible type)
b – summand (list of 0/1 in compatible type)
carry_in – input carry (default 0)
get_carry – add final carry to output
- Returns
list of 0/1 in relevant type
- bit_and(other)¶
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()¶
NOT in binary circuits.
- bit_or(other)¶
OR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Returns
type depends on inputs (secret if any of them is)
- bit_xor(other)¶
XOR in binary circuits.
- Parameters
self/other – 0 or 1 (any compatible type)
- Return type
depending on inputs (secret if any of them is)
- classmethod get_input_from(player, n_bits=None)[source]¶
Secret input from
player
.- Param
player (int)
- classmethod get_type(length)¶
Returns a fixed-length type.
- half_adder(other)¶
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)
- if_else(x, y)¶
Vectorized oblivious selection:
sb32 = sbits.get_type(32) print_ln('%s', sb32(3).if_else(sb32(5), sb32(2)).reveal())
This will output 1.
- class Compiler.GC.types.sbitvec(elements=None, length=None, input_length=None)[source]¶
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 callingelements
.There are three ways to create an instance:
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]
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]
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 memberv
and the columns by callingelements
.
- 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.accept_client_connection(port)[source]¶
Accept client connection on specific port base.
- Parameters
port – port base (int/regint/cint)
- Returns
client id
- 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.check_point()[source]¶
Force MAC checks in current thread and all idle threads if the current thread is the main thread. This implies a break point.
- Compiler.library.crash(condition=None)[source]¶
Crash virtual machine.
- Parameters
condition – crash if true (default: true)
- 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 asArray
or declaring registers asglobal
. 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
Note that you cannot overwrite data structures such as
Array
in a loop even when usingglobal
. Useassign()
instead.
- Compiler.library.for_range_multithread(n_threads, n_parallel, n_loops, thread_mem_req={})[source]¶
Execute
n_loops
loop bodies in up ton_threads
threads, up ton_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 the optimization is rather rudimentary for runtime
n_loops
(regint/cint). Consider usingfor_range_parallel()
in this case. Using further control flow constructions inside other thanfor_range_opt()
(e.g,for_range()
) breaks the optimization.- 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): ...
Multidimensional ranges are supported as well. The following executes
f(0, 0)
tof(4, 2)
in parallel according to the budget.@for_range_opt([5, 3]) def f(i, j): ...
- Compiler.library.for_range_opt_multithread(n_threads, n_loops)[source]¶
Execute
n_loops
loop bodies in up ton_threads
threads, in parallel up to an optimization budget per thread similar tofor_range_opt()
. Note that optimization is rather rudimentary for runtimen_loops
(regint/cint). Consider usingfor_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)
tof(2, 0)
in one thread andf(2, 1)
tof(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 ton_parallel
loop bodies in parallel. Using any other control flow instruction inside the loop breaks the optimization.- Parameters
n_parallel – compile-time (int)
n_loops – regint/cint/int or list of int
Example:
@for_range_parallel(n_parallel, n_loops) def _(i): a[i] = a[i] * a[i]
Multidimensional ranges are supported as well. The following executes
f(0, 0)
tof(4, 2)
, two calls in parallel.@for_range_parallel(2, [5, 3]) def f(i, j): ...
- 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_player_id()[source]¶
- Returns
player number
- Return type
localint (cannot be used for computation)
- Compiler.library.get_threshold()[source]¶
The threshold is the maximal number of corrupted players.
- Return type
- 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. Use
MemValue
to assign values that live beyond.- Parameters
condition – regint/cint/int
Usage:
y = MemValue(0) @if_e(x > 0) def _(): y.write(1) @else_ def _(): y.write(0)
- Compiler.library.listen_for_clients(port)[source]¶
Listen for clients on specific port base.
- Parameters
port – port base (int/regint/cint)
- Compiler.library.map_sum_opt(n_threads, n_loops, types)[source]¶
Multi-threaded sum reduction. The following computes a sum of ten squares in three threads:
@map_sum_opt(3, 10, [sint]) def summer(i): return sint(i) ** 2 result = summer()
- Parameters
n_threads – number of threads (int)
n_loops – number of loop runs (regint/cint/int)
types – return type, must match the return statement in the loop
- Compiler.library.map_sum_simple(n_threads, n_loops, type, size)[source]¶
Vectorized multi-threaded sum reduction. The following computes a 100 sums of ten squares in three threads:
@map_sum_simple(3, 10, sint, 100) def summer(i): return sint(regint.inc(100, i, 0)) ** 2 result = summer()
- Parameters
n_threads – number of threads (int)
n_loops – number of loop runs (regint/cint/int)
type – return type, must match the return statement in the loop
size – vector size, must match the return statement in the loop
- Compiler.library.multithread(n_threads, n_items=None, max_size=None)[source]¶
Distribute the computation of
n_items
ton_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
)max_size – maximum size to be processed at once (default: no limit)
The following executes
f(0, 8)
,f(8, 8)
, andf(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 ofargs
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 inprint_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.runtime_error(msg='', *args)[source]¶
Print an error message and abort the runtime. Parameters work as in
print_ln()
- Compiler.library.runtime_error_if(condition, msg='', *args)[source]¶
Conditionally print an error message and abort the runtime.
- Parameters
condition – regint/cint/int/cbit
msg – message
args – list of public values to fit
%s
in the message
- 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.tree_reduce(function, sequence)[source]¶
Round-efficient reduction. The following computes the maximum of the list
l
:m = tree_reduce(lambda x, y: x.max(y), l)
- Parameters
function – reduction function taking two arguments
sequence – list, vector, or array
- Compiler.library.tree_reduce_multithread(n_threads, function, vector)[source]¶
Round-efficient reduction in several threads. The following code computes the maximum of an array in 10 threads:
tree_reduce_multithread(10, lambda x, y: x.max(y), a)
- Parameters
n_threads – number of threads (int)
function – reduction function taking exactly two arguments
vector – register vector or array
- 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 explicitly.
- 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.InvertSqrt(self, *args, **kwargs)¶
Reciprocal square root approximation by Lu et al.
- 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 useslog2_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 withexp2_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 consecutive 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[0].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.
A simple network for MNIST using two dense layers can be trained as follows:
sgd = ml.SGD([ml.Dense(60000, 784, 128, activation='relu'),
ml.Dense(60000, 128, 10),
ml.MultiOutput(60000, 10)], n_epochs,
report_loss=True)
sgd.layers[0].X.input_from(0)
sgd.layers[1].Y.input_from(1)
sgd.reset()
sgd.run()
See this repository for scripts importing MNIST training data and further examples.
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.
- class Compiler.ml.Adam(layers, n_epochs=1, approx=False, amsgrad=False, normalize=False)[source]¶
Bases:
Optimizer
Adam/AMSgrad optimizer.
- Parameters
layers – layers of linear graph
approx – use approximation for inverse square root (bool)
amsgrad – use AMSgrad (bool)
- class Compiler.ml.Add(inputs)[source]¶
Bases:
NoVariableLayer
Fixed-point addition layer.
- Parameters
inputs – two input layers with same shape (tuple/list)
- class Compiler.ml.Argmax(shape)[source]¶
Bases:
NoVariableLayer
Fixed-point Argmax layer.
- Parameters
shape – input shape (tuple/list of two int)
- class Compiler.ml.BatchNorm(shape, approx=True, args=None)[source]¶
Bases:
Layer
Fixed-point batch normalization layer.
- Parameters
shape – input/output shape (tuple/list of four int)
approx – use approximate square root
- class Compiler.ml.Concat(inputs, dimension)[source]¶
Bases:
NoVariableLayer
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]¶
Bases:
DenseBase
Fixed-point dense (matrix multiplication) layer.
- Parameters
N – number of examples
d_in – input dimension
d_out – output dimension
- class Compiler.ml.Dropout(N, d1, d2=1, alpha=0.5)[source]¶
Bases:
NoVariableLayer
Dropout layer.
- Parameters
N – number of examples
d1 – total dimension
alpha – probability (power of two)
- class Compiler.ml.FixAveragePool2d(input_shape, output_shape, filter_size, strides=(1, 1))[source]¶
Bases:
FixBase
,AveragePool2d
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]¶
Bases:
Conv2d
,FixBase
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 inttf_weight_format – weight shape format is (height, width, input channels, output channels) instead of the default (output channels, height, width, input channels)
- class Compiler.ml.FusedBatchNorm(shape, inputs=None)[source]¶
Bases:
Layer
Fixed-point fused batch normalization layer (inference only).
- 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]¶
Bases:
NoVariableLayer
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]¶
Bases:
MultiOutputBase
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(report_loss=None)[source]¶
Bases:
object
Base class for graphs of layers.
- eval(**kwargs)[source]¶
Compute evaluation after training.
- Parameters
data – sample data (
Compiler.types.Matrix
with one row per sample)top – return top prediction instead of probability distribution
- forward(**kwargs)[source]¶
Compute graph.
- Parameters
N – batch size (used if batch not given)
batch – indices for computation (
Array
or list)keep_intermediate – do not free memory of intermediate results after use
- property layers¶
Get all layers.
- class Compiler.ml.Output(N, debug=False, approx=False)[source]¶
Bases:
NoVariableLayer
Fixed-point logistic regression output layer.
- Parameters
N – number of examples
approx –
False
(default) or parameter forapprox_sigmoid
- class Compiler.ml.Relu(shape, inputs=None)[source]¶
Bases:
ElementWiseLayer
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.
- class Compiler.ml.ReluMultiOutput(N, d_out, approx=False, debug=False)[source]¶
Bases:
MultiOutputBase
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]¶
Bases:
Optimizer
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]¶
Bases:
ElementWiseLayer
Fixed-point square layer.
- Parameters
shape – input/output shape (tuple/list of int)
- Compiler.ml.argmax(x)[source]¶
Compute index of maximum element.
- Parameters
x – iterable
- Returns
sint
- Compiler.ml.mr(A, n_iterations, stop=False)[source]¶
Iterative matrix inverse approximation.
- Parameters
A – matrix to invert
n_iterations – maximum number of iterations
stop – whether to stop when converged (implies revealing)
- Compiler.ml.solve_linear(A, b, n_iterations, progress=False, n_threads=None, stop=False, already_symmetric=False, precond=False)[source]¶
Iterative linear solution approximation for \(Ax=b\).
- Parameters
progress – print some information on the progress (implies revealing)
n_threads – number of threads to use
stop – whether to stop when converged (implies revealing)
- Compiler.ml.approx_sigmoid(*args, **kwargs)¶
Piece-wise approximate sigmoid as in Hong 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, 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:
0x4a43f8804b0ad882fa493be44dff80f562d661a05647c15166d71ebff8c6ffa7 0xf0d7aa0ab2d92d580bb080e17cbb52627932ba37f085d3931270d31c39357067
Note that
sint
tosbitvec
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 asprogram
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()
andfor_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
- 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
- property security¶
The statistical security parameter for non-linear functions.
- use_dabit¶
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
isNone
- 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
isNone
- 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
isNone
- property use_trunc_pr¶
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)