sunscreen 0.8.1

A Fully Homomorphic Encryption (FHE) compiler supporting the Brakerski/Fan-Vercauteren (BFV) scheme.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use petgraph::stable_graph::NodeIndex;
use serde::{Deserialize, Serialize};
use sunscreen_backend::compile_inplace;
use sunscreen_compiler_common::{
    CompilationResult, Context, EdgeInfo, NodeInfo, Operation as OperationTrait,
};
use sunscreen_fhe_program::{
    FheProgram, Literal as FheProgramLiteral, Operation as FheProgramOperation, SchemeType,
};
use sunscreen_runtime::{InnerPlaintext, Params};

use std::cell::RefCell;

#[derive(Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
/**
 * Represents a literal node's data.
 */
pub enum Literal {
    /**
     * An unsigned 64-bit integer.
     */
    U64(u64),

    /**
     * An encoded plaintext value.
     */
    Plaintext(InnerPlaintext),
}

#[derive(Clone, Debug, Hash, Deserialize, Serialize, PartialEq, Eq)]
/**
 * Represents an operation occurring in the frontend AST.
 */
pub enum FheOperation {
    /**
     * This node indicates loading a cipher text from an input.
     */
    InputCiphertext,

    /**
     * This node indicates loading a plaintext from an input.
     */
    InputPlaintext,

    /**
     * Addition.
     */
    Add,

    /**
     * Add a ciphertext and plaintext value.
     */
    AddPlaintext,

    /**
     * Subtraction.
     */
    Sub,

    /**
     * Subtract a plaintext.
     */
    SubPlaintext,

    /**
     * Unary negation (i.e. given x, compute -x)
     */
    Negate,

    /**
     * Multiplication.
     */
    Multiply,

    /**
     * Multiply a ciphertext by a plaintext.
     */
    MultiplyPlaintext,

    /**
     * A literal that serves as an operand to other operations.
     */
    Literal(Literal),

    /**
     * Rotate left.
     */
    RotateLeft,

    /**
     * Rotate right.
     */
    RotateRight,

    /**
     * In the BFV scheme, swap rows in the Batched vectors.
     */
    SwapRows,

    /**
     * This node indicates the previous node's result should be a result of the [`fhe_program`](crate::fhe_program).
     */
    Output,
}

impl OperationTrait for FheOperation {
    fn is_binary(&self) -> bool {
        matches!(
            self,
            FheOperation::Add
                | FheOperation::Multiply
                | FheOperation::Sub
                | FheOperation::RotateLeft
                | FheOperation::RotateRight
                | FheOperation::SubPlaintext
                | FheOperation::AddPlaintext
                | FheOperation::MultiplyPlaintext
        )
    }

    fn is_commutative(&self) -> bool {
        matches!(
            self,
            FheOperation::Add
                | FheOperation::Multiply
                | FheOperation::AddPlaintext
                | FheOperation::MultiplyPlaintext
        )
    }

    fn is_unary(&self) -> bool {
        matches!(self, FheOperation::Negate | FheOperation::SwapRows)
    }

    fn is_unordered(&self) -> bool {
        false
    }

    fn is_ordered(&self) -> bool {
        false
    }
}

/**
 * The context for constructing the [`fhe_program`](crate::fhe_program) graph during compilation.
 *
 * This is an implementation detail of the
 * [`fhe_program`](crate::fhe_program) macro, and you shouldn't need
 * to construct one.
 */
pub type FheContext = Context<FheOperation, Params>;

/**
 *
 */
pub type FheFrontendCompilation = CompilationResult<FheOperation>;

thread_local! {
    /**
     * Contains the graph of an FHE program during compilation. An
     * implementation detail and not for public consumption.
     */
    pub static CURRENT_FHE_CTX: RefCell<Option<&'static mut FheContext>> = RefCell::new(None);
}

/**
 * Runs the specified closure, injecting the current
 * [`fhe_program`](crate::fhe_program) context.
 */
pub fn with_fhe_ctx<F, R>(f: F) -> R
where
    F: FnOnce(&mut FheContext) -> R,
{
    CURRENT_FHE_CTX.with(|ctx| {
        let mut option = ctx.borrow_mut();
        let ctx = option
            .as_mut()
            .expect("Called Ciphertext::new() outside of a context.");

        f(ctx)
    })
}

/**
 * Defines transformations to FHE program graphs.
 */
pub trait FheContextOps {
    /**
     * Add an encrypted input to this context.
     */
    fn add_ciphertext_input(&mut self) -> NodeIndex;

    /**
     * Add a plaintext input to this context.
     */
    fn add_plaintext_input(&mut self) -> NodeIndex;

    /**
     * Adds a plaintext literal to the
     * [`fhe_program`](crate::fhe_program) graph.
     */
    fn add_plaintext_literal(&mut self, plaintext: InnerPlaintext) -> NodeIndex;

    /**
     * Add a subtraction to this context.
     */
    fn add_subtraction(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Add a subtraction to this context.
     */
    fn add_subtraction_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Adds a negation to this context.
     */
    fn add_negate(&mut self, x: NodeIndex) -> NodeIndex;

    /**
     * Add an addition to this context.
     */
    fn add_addition(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Adds an addition to a plaintext.
     */
    fn add_addition_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Add a multiplication to this context.
     */
    fn add_multiplication(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Add a multiplication to this context.
     */
    fn add_multiplication_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Adds a literal to this context.
     */
    fn add_literal(&mut self, literal: Literal) -> NodeIndex;

    /**
     * Add a rotate left.
     */
    fn add_rotate_left(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;

    /**
     * Add a rotate right.
     */
    fn add_rotate_right(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex;
    /**
     * Adds a row swap.
     */
    fn add_swap_rows(&mut self, x: NodeIndex) -> NodeIndex;

    /**
     * Add a node that captures the previous node as an output.
     */
    fn add_output(&mut self, i: NodeIndex) -> NodeIndex;
}

impl FheContextOps for FheContext {
    fn add_ciphertext_input(&mut self) -> NodeIndex {
        self.add_node(FheOperation::InputCiphertext)
    }

    fn add_plaintext_input(&mut self) -> NodeIndex {
        self.add_node(FheOperation::InputPlaintext)
    }

    fn add_plaintext_literal(&mut self, plaintext: InnerPlaintext) -> NodeIndex {
        self.add_node(FheOperation::Literal(Literal::Plaintext(plaintext)))
    }

    fn add_subtraction(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::Sub, left, right)
    }

    fn add_subtraction_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::SubPlaintext, left, right)
    }

    fn add_negate(&mut self, x: NodeIndex) -> NodeIndex {
        self.add_unary_operation(FheOperation::Negate, x)
    }

    fn add_addition(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::Add, left, right)
    }

    fn add_addition_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::AddPlaintext, left, right)
    }

    fn add_multiplication(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::Multiply, left, right)
    }

    fn add_multiplication_plaintext(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::MultiplyPlaintext, left, right)
    }

    fn add_literal(&mut self, literal: Literal) -> NodeIndex {
        // See if we already have a node for the given literal. If so, just return it.
        // If not, make a new one.
        let existing_literal =
            self.graph
                .node_indices()
                .find(|&i| match &self.graph[i].operation {
                    FheOperation::Literal(x) => *x == literal,
                    _ => false,
                });

        match existing_literal {
            Some(x) => x,
            None => self.add_node(FheOperation::Literal(literal)),
        }
    }

    fn add_rotate_left(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::RotateLeft, left, right)
    }

    fn add_rotate_right(&mut self, left: NodeIndex, right: NodeIndex) -> NodeIndex {
        self.add_binary_operation(FheOperation::RotateRight, left, right)
    }

    fn add_swap_rows(&mut self, x: NodeIndex) -> NodeIndex {
        self.add_unary_operation(FheOperation::SwapRows, x)
    }

    fn add_output(&mut self, i: NodeIndex) -> NodeIndex {
        self.add_unary_operation(FheOperation::Output, i)
    }
}

/**
 * Extends FheFrontendCompilation to add a backend compilation method.
 */
pub trait FheCompile {
    /**
     * Performs frontend compilation of this intermediate representation into a backend [`FheProgram`],
     * then perform backend compilation and return the result.
     */
    fn compile(&self) -> FheProgram;
}

impl FheCompile for FheFrontendCompilation {
    fn compile(&self) -> FheProgram {
        let mut fhe_program = FheProgram::new(SchemeType::Bfv);

        let mapped_graph = self.0.map(
            |id, n| match &n.operation {
                FheOperation::Add => NodeInfo::new(FheProgramOperation::Add),
                FheOperation::InputCiphertext => {
                    // HACKHACK: Input nodes are always added first to the graph in the order
                    // they're specified as function arguments. We should not depend on this.
                    NodeInfo::new(FheProgramOperation::InputCiphertext(id.index()))
                }
                FheOperation::InputPlaintext => {
                    // HACKHACK: Input nodes are always added first to the graph in the order
                    // they're specified as function arguments. We should not depend on this.
                    NodeInfo::new(FheProgramOperation::InputPlaintext(id.index()))
                }
                FheOperation::Literal(Literal::U64(x)) => {
                    NodeInfo::new(FheProgramOperation::Literal(FheProgramLiteral::U64(*x)))
                }
                FheOperation::Literal(Literal::Plaintext(x)) => {
                    // It's okay to unwrap here because fhe_program compilation will
                    // catch the panic and return a compilation error.
                    NodeInfo::new(FheProgramOperation::Literal(FheProgramLiteral::Plaintext(
                        x.to_bytes().expect("Failed to serialize plaintext."),
                    )))
                }
                FheOperation::Sub => NodeInfo::new(FheProgramOperation::Sub),
                FheOperation::SubPlaintext => NodeInfo::new(FheProgramOperation::SubPlaintext),
                FheOperation::Negate => NodeInfo::new(FheProgramOperation::Negate),
                FheOperation::Multiply => NodeInfo::new(FheProgramOperation::Multiply),
                FheOperation::MultiplyPlaintext => {
                    NodeInfo::new(FheProgramOperation::MultiplyPlaintext)
                }
                FheOperation::Output => NodeInfo::new(FheProgramOperation::OutputCiphertext),
                FheOperation::RotateLeft => NodeInfo::new(FheProgramOperation::ShiftLeft),
                FheOperation::RotateRight => NodeInfo::new(FheProgramOperation::ShiftRight),
                FheOperation::SwapRows => NodeInfo::new(FheProgramOperation::SwapRows),
                FheOperation::AddPlaintext => NodeInfo::new(FheProgramOperation::AddPlaintext),
            },
            |_, e| match e {
                EdgeInfo::Left => EdgeInfo::Left,
                EdgeInfo::Right => EdgeInfo::Right,
                EdgeInfo::Unary => EdgeInfo::Unary,
                EdgeInfo::Unordered => unreachable!("FHE programs have no unordered edges."),
                EdgeInfo::Ordered(_) => unreachable!("FHE programs have no ordered edges."),
            },
        );

        fhe_program.graph = CompilationResult(mapped_graph);

        compile_inplace(fhe_program)
    }
}