|
| 1 | +package mpc |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/fystack/mpcium/pkg/logger" |
| 8 | + "github.com/hashicorp/consul/api" |
| 9 | +) |
| 10 | + |
| 11 | +// ReshareCoordinator handles coordination between nodes during resharing |
| 12 | +type ReshareCoordinator struct { |
| 13 | + kv *api.KV |
| 14 | + prefix string |
| 15 | + nodeID string |
| 16 | + readyPath string |
| 17 | +} |
| 18 | + |
| 19 | +// NewReshareCoordinator creates a new coordinator for resharing |
| 20 | +func NewReshareCoordinator(consulClient *api.Client, walletID string, nodeID string) *ReshareCoordinator { |
| 21 | + prefix := fmt.Sprintf("reshare/%s", walletID) |
| 22 | + readyPath := fmt.Sprintf("%s/ready/%s", prefix, nodeID) |
| 23 | + |
| 24 | + return &ReshareCoordinator{ |
| 25 | + kv: consulClient.KV(), |
| 26 | + prefix: prefix, |
| 27 | + nodeID: nodeID, |
| 28 | + readyPath: readyPath, |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// SignalReady marks this node as ready for resharing |
| 33 | +func (c *ReshareCoordinator) SignalReady() error { |
| 34 | + p := &api.KVPair{ |
| 35 | + Key: c.readyPath, |
| 36 | + Value: []byte("ready"), |
| 37 | + } |
| 38 | + |
| 39 | + _, err := c.kv.Put(p, nil) |
| 40 | + if err != nil { |
| 41 | + return fmt.Errorf("failed to signal ready: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + logger.Info("Node signaled ready for resharing", "nodeID", c.nodeID) |
| 45 | + return nil |
| 46 | +} |
| 47 | + |
| 48 | +// WaitForAll waits until all participants are ready |
| 49 | +func (c *ReshareCoordinator) WaitForAll(participants []string) error { |
| 50 | + deadline := time.Now().Add(30 * time.Second) |
| 51 | + |
| 52 | + for { |
| 53 | + allReady := true |
| 54 | + for _, p := range participants { |
| 55 | + readyPath := fmt.Sprintf("%s/ready/%s", c.prefix, p) |
| 56 | + pair, _, err := c.kv.Get(readyPath, nil) |
| 57 | + if err != nil { |
| 58 | + return fmt.Errorf("failed to check ready state: %w", err) |
| 59 | + } |
| 60 | + if pair == nil { |
| 61 | + allReady = false |
| 62 | + break |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if allReady { |
| 67 | + logger.Info("All participants ready for resharing", |
| 68 | + "nodeID", c.nodeID, |
| 69 | + "participants", participants) |
| 70 | + return nil |
| 71 | + } |
| 72 | + |
| 73 | + if time.Now().After(deadline) { |
| 74 | + return fmt.Errorf("timeout waiting for participants") |
| 75 | + } |
| 76 | + |
| 77 | + time.Sleep(1 * time.Second) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +// Cleanup removes coordination data |
| 82 | +func (c *ReshareCoordinator) Cleanup() error { |
| 83 | + _, err := c.kv.DeleteTree(c.prefix, nil) |
| 84 | + if err != nil { |
| 85 | + return fmt.Errorf("failed to cleanup coordination data: %w", err) |
| 86 | + } |
| 87 | + return nil |
| 88 | +} |
0 commit comments