-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
392 lines (322 loc) · 12.6 KB
/
node.go
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
// Package node provides the main entry point for the Helium library.
// It defines the Node type, which implements the parties in the MHE-based
// MPC procotoles.
//
// The current implementation specifically targets the helper-assisted setting,
// in which a single helper node coordinates the execution of the setup and compute
// phases, and serves as an aggregator and circuit evaluator.
package node
import (
"errors"
"fmt"
"log"
"slices"
"github.com/ChristianMct/helium/circuits"
"github.com/ChristianMct/helium/objectstore"
"github.com/ChristianMct/helium/protocols"
"github.com/ChristianMct/helium/services/compute"
"github.com/ChristianMct/helium/services/setup"
"github.com/ChristianMct/helium/sessions"
"github.com/tuneinsight/lattigo/v5/core/rlwe"
"golang.org/x/net/context"
)
// Node represents a Helium node. It is the main entry point for the Helium library.
// The node is responsible for managing the setup and compute services, and instantiates the transport layer.
//
// Two types of nodes are supported in the current implementation:
// - the helper node coordinates the execution of the setup and compute phases,
// and serves a an aggregator and circuit evaluator. The helper node must have an
// address.
// - the peer nodes connect to the helper node and provide their protocol shares and
// encrypted inputs to the compuation. Peer nodes do not need to have an address.
type Node struct {
addr Address
id, helperID sessions.NodeID
nodeList List
// sessStore and state
sessStore *sessions.Store
objectstore.ObjectStore
upstream Coordinator
// transport
transport Transport
// services
setup *setup.Service
compute *compute.Service
// postsetupHandler func(*pkg.SessionStore, compute.PublicKeyBackend) error
// precomputeHandler func(*pkg.SessionStore, compute.PublicKeyBackend) error
setupDone chan struct{}
}
// New creates a new Helium node from the provided config and node list.
// The method returns an error if the config is invalid or if the node list is empty.
func New(config Config, nodeList List) (node *Node, err error) {
node = new(Node)
if err := ValidateConfig(config, nodeList); err != nil {
return nil, fmt.Errorf("invalid config: %w", err)
}
node.id = config.ID
node.addr = config.Address
node.helperID = config.HelperID
node.nodeList = nodeList
// object store
node.ObjectStore, err = objectstore.NewObjectStoreFromConfig(config.ObjectStoreConfig)
if err != nil {
return nil, err
}
// session
node.sessStore = sessions.NewStore()
for _, sp := range config.SessionParameters {
_, err = node.createNewSession(sp)
if err != nil {
return nil, err
}
}
// services
node.setup, err = setup.NewSetupService(node.id, node, config.SetupConfig, node.ObjectStore)
if err != nil {
return nil, fmt.Errorf("failed to load the setup service: %w", err)
}
node.compute, err = compute.NewComputeService(node.id, node, config.ComputeConfig, node.setup)
if err != nil {
return nil, fmt.Errorf("failed to load the compute service: %w", err)
}
// internal
// node.postsetupHandler = func(sessStore *pkg.SessionStore, pkb compute.PublicKeyBackend) error { return nil }
// node.precomputeHandler = func(sessStore *pkg.SessionStore, pkb compute.PublicKeyBackend) error { return nil }
node.setupDone = make(chan struct{})
return node, err
}
// Run runs the node with the provided app under the given context.
// The method returns channels to send circuit descriptors and receive circuit outputs.
//
// In the current implementation:
// - the method runs the setup and compute phases sequentially.
// - only the helper node can issue circuit descriptors.
// - loading and verification of the state from persistent storage is not implemented.
func (node *Node) Run(ctx context.Context, app App, ip compute.InputProvider, upstream Coordinator, trans Transport) (cdescs chan<- circuits.Descriptor, outs <-chan circuits.Output, err error) {
node.upstream = upstream
node.transport = trans
// recovers the session
sess, exists := node.GetSessionFromContext(ctx)
if !exists {
return nil, nil, fmt.Errorf("session `%s` does not exist", sess.ID)
}
ctx = sessions.ContextWithNodeID(ctx, node.id)
// App loading
// registers the app's circuits and infer the setup description
err = node.compute.RegisterCircuits(app.Circuits)
if err != nil {
return nil, nil, fmt.Errorf("could not register all circuits: %w", err)
}
if app.SetupDescription == nil {
return nil, nil, fmt.Errorf("app must provide a setup description") // TODO: inference of setup description from registered circuits.
}
sigList := setup.DescriptionToSignatureList(*app.SetupDescription)
cds := make(chan circuits.Descriptor)
or := make(chan circuits.Output)
sc, err := newServicesCoordinator(ctx, node.upstream)
if err != nil {
return nil, nil, fmt.Errorf("error creating a service coordinator: %w", err)
}
st := newServicesTransport(trans)
// go node.sendShares(ctx)
go func() {
err := node.setup.Run(ctx, sc.setupCoordinator, &st.setupTransport)
if err != nil {
panic(err)
}
close(node.setupDone)
}()
// runs the setup phase
if node.IsHelperNode() {
// TODO: load and verify state from persistent storage
node.Logf("running setup phase: %d signatures to run", len(sigList))
for _, sig := range sigList {
sig := sig
err := node.setup.RunSignature(ctx, sig)
if err != nil {
panic(err)
}
}
node.Logf("all signatures run, closing setup downstream")
close(sc.setupCoordinator.incoming)
}
go func() {
err := node.compute.Run(ctx, ip, or, sc.computeCoordinator, &st.computeTransport)
if err != nil {
panic(err)
}
}()
if node.IsHelperNode() {
<-node.setupDone
node.Logf("setup done, starting compute phase")
go func() {
for cd := range cds {
node.Logf("new circuit descriptor: %s", cd)
cev := compute.Event{CircuitEvent: &circuits.Event{EventType: circuits.Started, Descriptor: cd}}
sc.computeCoordinator.incoming <- cev
}
node.Logf("user closed circuit discription channel, closing downstream")
close(sc.computeCoordinator.incoming)
}()
}
return cds, or, nil
}
// Transport interface implementation
// GetAggregationOutput returns the aggregation output for a given protocol descriptor.
// If this node is the helper node, the method retrieves the output from the services.
// If this node is a peer node, the method retrieves the output from the helper node.
func (node *Node) GetAggregationOutput(ctx context.Context, pd protocols.Descriptor) (*protocols.AggregationOutput, error) {
if node.id == node.helperID {
switch {
case pd.Signature.Type.IsSetup():
return node.setup.GetAggregationOutput(ctx, pd)
default:
return nil, fmt.Errorf("unknown protocol type")
}
}
return nil, fmt.Errorf("get aggregation output not implemented for ligh nodes")
}
// PutCiphertext registers a new ciphertext for the compute service.
// If this node is the helper node, the method registers the ciphertext with the service.
// If this node is a peer node, the method sends the ciphertext to the helper node.
func (node *Node) PutCiphertext(ctx context.Context, ct sessions.Ciphertext) error {
if node.id == node.helperID {
return node.compute.PutCiphertext(ctx, ct)
}
return fmt.Errorf("put ciphertext not implemented for ligh nodes")
}
// GetCiphertext returns a ciphertext from the compute service.
// If this node is the helper node, the method retrieves the ciphertext from the service.
// If this node is a peer node, the method retrieves the ciphertext from the helper node.
func (node *Node) GetCiphertext(ctx context.Context, ctID sessions.CiphertextID) (*sessions.Ciphertext, error) {
if node.id == node.helperID {
return node.compute.GetCiphertext(ctx, ctID)
}
return nil, fmt.Errorf("get ciphertext not implemented for ligh nodes")
}
// WaitForSetupDone blocks until the setup phase is done.
func (node *Node) WaitForSetupDone(ctx context.Context) error {
select {
case <-node.setupDone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// NodeList returns the list of nodes known to the node.
func (node *Node) NodeList() List {
return slices.Clone(node.nodeList)
}
// ID returns the node's ID.
func (node *Node) ID() sessions.NodeID {
return node.id
}
// Address returns the node's address.
func (node *Node) Address() Address {
return node.addr
}
// HasAddress returns true if the node has an address.
func (node *Node) HasAddress() bool {
return node.addr != ""
}
// IsHelperNode returns true if the node is the helper node.
func (node *Node) IsHelperNode() bool {
return node.id == node.helperID
}
// SessionProvider interface implementation
// GetSessionFromID returns the session with the given ID.
func (node *Node) GetSessionFromID(sessionID sessions.ID) (*sessions.Session, bool) {
return node.sessStore.GetSessionFromID(sessionID)
}
// GetSessionFromContext returns the session by extracting the session id from the
// provided context.
func (node *Node) GetSessionFromContext(ctx context.Context) (*sessions.Session, bool) {
sessID, has := sessions.IDFromContext(ctx)
if !has {
return nil, false
}
return node.GetSessionFromID(sessID)
}
// Logf writes a log line with the provided message.
func (node *Node) Logf(msg string, v ...any) {
log.Printf("%s | [node] %s\n", node.id, fmt.Sprintf(msg, v...))
}
// func (node *Node) RegisterPostsetupHandler(h func(*pkg.SessionStore, compute.PublicKeyBackend) error) {
// node.postsetupHandler = h
// }
// func (node *Node) RegisterPrecomputeHandler(h func(*pkg.SessionStore, compute.PublicKeyBackend) error) {
// node.precomputeHandler = h
// }
// pkg.PublicKeyBackend interface implementation
// GetCollectivePublicKey returns the collective public key.
func (node *Node) GetCollectivePublicKey(ctx context.Context) (*rlwe.PublicKey, error) {
if err := node.WaitForSetupDone(ctx); err != nil {
return nil, fmt.Errorf("error waiting for setup completion: %w", err)
}
return node.setup.GetCollectivePublicKey(ctx)
}
// GetGaloisKey returns the Galois keys for galois element galEl.
func (node *Node) GetGaloisKey(ctx context.Context, galEl uint64) (*rlwe.GaloisKey, error) {
if err := node.WaitForSetupDone(ctx); err != nil {
return nil, fmt.Errorf("error waiting for setup completion: %w", err)
}
return node.setup.GetGaloisKey(ctx, galEl)
}
// GetRelinearizationKey returns the relinearization key.
func (node *Node) GetRelinearizationKey(ctx context.Context) (*rlwe.RelinearizationKey, error) {
if err := node.WaitForSetupDone(ctx); err != nil {
return nil, fmt.Errorf("error waiting for setup completion: %w", err)
}
return node.setup.GetRelinearizationKey(ctx)
}
// Coordinator interface implementation
// Register is called by the transport upon connection of a new peer node.
func (node *Node) Register(peer sessions.NodeID) error {
if peer == node.id {
return nil // TODO specific to helper-assisted setting
}
return errors.Join(node.setup.Register(peer), node.compute.Register(peer))
}
// Unregister is called by the transport upon disconnection of a peer node.
func (node *Node) Unregister(peer sessions.NodeID) error {
return errors.Join(node.setup.Unregister(peer), node.compute.Unregister(peer))
}
// FHEProvider interface implementation
// GetParameters returns the parameters from the context's session.
func (node *Node) GetParameters(ctx context.Context) (sessions.FHEParameters, error) {
return node.compute.GetParameters(ctx)
}
// // GetEncoder returns a lattigo encoder from the context's session.
// func (node *Node) GetEncoder(ctx context.Context) (*bgv.Encoder, error) {
// return node.compute.GetEncoder(ctx)
// }
// GetEncryptor returns a lattigo encryptor from the context's session.
// The encryptor is initialized with the collective public key.
func (node *Node) GetEncryptor(ctx context.Context) (*rlwe.Encryptor, error) {
return node.compute.GetEncryptor(ctx)
}
// GetDecryptor returns a lattigo decryptor from the context's session.
// The decryptor is initialized with the node's secret key.
func (node *Node) GetDecryptor(ctx context.Context) (*rlwe.Decryptor, error) {
return node.compute.GetDecryptor(ctx)
}
func (node *Node) createNewSession(sessParams sessions.Parameters) (sess *sessions.Session, err error) {
sess, err = node.sessStore.NewRLWESession(sessParams, node.id)
if err != nil {
return sess, err
}
return sess, nil
}
func (node *Node) PutOperand(opl circuits.OperandLabel, op *circuits.Operand) error {
return node.compute.PutOperand(opl, op)
}
func (node *Node) GetOperand(opl circuits.OperandLabel) (*circuits.Operand, bool) {
return node.compute.GetOperand(opl)
}
// func (node *Node) sendShares(ctx context.Context) {
// for share := range node.outgoingShares {
// if err := node.transport.PutShare(ctx, share); err != nil {
// node.Logf("error while sending share: %s", err)
// }
// }
// }