/
protocol.go
312 lines (256 loc) · 9.88 KB
/
protocol.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
// TODO: Finish writing proper comments in this file.
package checkpoint
import (
"bytes"
"time"
es "github.com/go-errors/errors"
"github.com/filecoin-project/mir/pkg/dsl"
"github.com/filecoin-project/mir/pkg/logging"
"github.com/filecoin-project/mir/pkg/modules"
apppbdsl "github.com/filecoin-project/mir/pkg/pb/apppb/dsl"
checkpointpbdsl "github.com/filecoin-project/mir/pkg/pb/checkpointpb/dsl"
checkpointpbmsgs "github.com/filecoin-project/mir/pkg/pb/checkpointpb/msgs"
checkpointpbtypes "github.com/filecoin-project/mir/pkg/pb/checkpointpb/types"
cryptopbdsl "github.com/filecoin-project/mir/pkg/pb/cryptopb/dsl"
eventpbdsl "github.com/filecoin-project/mir/pkg/pb/eventpb/dsl"
eventpbtypes "github.com/filecoin-project/mir/pkg/pb/eventpb/types"
hasherpbdsl "github.com/filecoin-project/mir/pkg/pb/hasherpb/dsl"
transportpbevents "github.com/filecoin-project/mir/pkg/pb/transportpb/events"
trantorpbdsl "github.com/filecoin-project/mir/pkg/pb/trantorpb/dsl"
trantorpbtypes "github.com/filecoin-project/mir/pkg/pb/trantorpb/types"
"github.com/filecoin-project/mir/pkg/timer/types"
tt "github.com/filecoin-project/mir/pkg/trantor/types"
t "github.com/filecoin-project/mir/pkg/types"
"github.com/filecoin-project/mir/pkg/util/maputil"
"github.com/filecoin-project/mir/pkg/util/membutil"
)
const (
DefaultResendPeriod = types.Duration(time.Second)
)
type State struct {
// State snapshot associated with this checkpoint.
StateSnapshot *trantorpbtypes.StateSnapshot
// Hash of the state snapshot data associated with this checkpoint.
StateSnapshotHash []byte
// Set of nodes' valid checkpoint Signatures (these will make up a checkpoint certificate).
Signatures map[t.NodeID][]byte
// Set of nodes from which a (potentially invalid) Checkpoint messages has been received
// (used to ignore duplicate messages).
SigReceived map[t.NodeID]struct{}
// Set of Checkpoint messages that were received ahead of time.
PendingMessages map[t.NodeID]*checkpointpbtypes.Checkpoint
// Flag ensuring that the stable checkpoint is only Announced once.
// Set to true when announcing a stable checkpoint for the first time.
// When true, stable checkpoints are not Announced anymore.
Announced bool
}
// NewModule allocates and returns a new instance of the ModuleParams associated with sequence number sn.
func NewModule(
moduleConfig ModuleConfig,
params *ModuleParams,
logger logging.Logger) modules.PassiveModule {
state := &State{
StateSnapshot: &trantorpbtypes.StateSnapshot{
AppData: nil,
EpochData: &trantorpbtypes.EpochData{
EpochConfig: params.EpochConfig,
ClientProgress: nil, // This will be filled by a separate event.
LeaderPolicy: params.LeaderPolicyData,
PreviousMembership: params.Membership,
},
},
Announced: false,
Signatures: make(map[t.NodeID][]byte),
SigReceived: make(map[t.NodeID]struct{}),
PendingMessages: make(map[t.NodeID]*checkpointpbtypes.Checkpoint),
}
m := dsl.NewModule(moduleConfig.Self)
apppbdsl.UponSnapshot(m, func(appData []uint8) error {
// Treat nil data as an empty byte slice.
if appData == nil {
appData = []byte{}
}
// Save the received app snapshot if there is none yet.
if state.StateSnapshot.AppData == nil {
state.StateSnapshot.AppData = appData
if state.SnapshotReady() {
if err := processStateSnapshot(m, state, moduleConfig); err != nil {
return err
}
}
}
return nil
})
hasherpbdsl.UponResultOne(m, func(digest []uint8, _ *struct{}) error {
// Save the received snapshot hash
state.StateSnapshotHash = digest
// Request signature
sigData := serializeCheckpointForSig(params.EpochConfig.EpochNr, params.EpochConfig.FirstSn, state.StateSnapshotHash)
cryptopbdsl.SignRequest(m, moduleConfig.Crypto, sigData, &struct{}{})
return nil
})
cryptopbdsl.UponSignResult(m, func(sig []uint8, _ *struct{}) error {
// Save received own checkpoint signature
state.Signatures[params.OwnID] = sig
state.SigReceived[params.OwnID] = struct{}{}
// In case the node's own signature is enough to reach quorum, announce the stable checkpoint.
// This can happen in a small system where no failures are tolerated.
if state.Stable(params) {
announceStable(m, params, state, moduleConfig)
}
// Send a checkpoint message to all nodes.
chkpMessage := checkpointpbmsgs.Checkpoint(moduleConfig.Self, params.EpochConfig.EpochNr, params.EpochConfig.FirstSn, state.StateSnapshotHash, sig)
sortedMembership := maputil.GetSortedKeys(params.Membership.Nodes)
eventpbdsl.TimerRepeat(m,
"timer",
[]*eventpbtypes.Event{transportpbevents.SendMessage(moduleConfig.Net, chkpMessage, sortedMembership)},
params.ResendPeriod,
tt.RetentionIndex(params.EpochConfig.EpochNr),
)
logger.Log(logging.LevelDebug, "Sending checkpoint message",
"epoch", params.EpochConfig.EpochNr,
"dataLen", len(state.StateSnapshot.AppData),
"memberships", len(state.StateSnapshot.EpochData.EpochConfig.Memberships),
)
// Apply pending Checkpoint messages
for s, msg := range state.PendingMessages {
if err := applyCheckpointReceived(m, params, state, moduleConfig, s, msg.Epoch, msg.Sn, msg.SnapshotHash, msg.Signature, logger); err != nil {
logger.Log(logging.LevelWarn, "Error applying pending Checkpoint message", "error", err, "msg", msg)
return err
}
}
state.PendingMessages = nil
return nil
})
cryptopbdsl.UponSigVerified(m, func(nodeId t.NodeID, err error, c *verificationContext) error {
if err != nil {
logger.Log(logging.LevelWarn, "Ignoring Checkpoint message. Invalid signature.", "source", nodeId, "error", err)
return nil
}
// Note the reception of a valid Checkpoint message from node `source`.
state.Signatures[nodeId] = c.signature
// If, after having applied this message, the checkpoint became stable, produce the necessary events.
if state.Stable(params) {
announceStable(m, params, state, moduleConfig)
}
return nil
})
trantorpbdsl.UponClientProgress(m, func(progress map[tt.ClientID]*trantorpbtypes.DeliveredTXs) error {
// Save the received client progress if there is none yet.
if state.StateSnapshot.EpochData.ClientProgress == nil {
state.StateSnapshot.EpochData.ClientProgress = &trantorpbtypes.ClientProgress{
Progress: progress,
}
if state.SnapshotReady() {
if err := processStateSnapshot(m, state, moduleConfig); err != nil {
return err
}
}
}
return nil
})
checkpointpbdsl.UponCheckpointReceived(m, func(from t.NodeID, epoch tt.EpochNr, sn tt.SeqNr, snapshotHash []uint8, signature []uint8) error {
return applyCheckpointReceived(m, params, state, moduleConfig, from, epoch, sn, snapshotHash, signature, logger)
})
return m
}
func processStateSnapshot(m dsl.Module, state *State, mc ModuleConfig) error {
// Serialize the snapshot.
snapshotData, err := serializeSnapshotForHash(state.StateSnapshot)
if err != nil {
return es.Errorf("failed serializing state snapshot: %w", err)
}
// Initiate computing the hash of the snapshot.
hasherpbdsl.RequestOne(m,
mc.Hasher,
snapshotData,
&struct{}{},
)
return nil
}
func announceStable(m dsl.Module, p *ModuleParams, state *State, mc ModuleConfig) {
// Only announce the stable checkpoint once.
if state.Announced {
return
}
state.Announced = true
// Assemble a multisig certificate from the received valid signatures.
cert := make(map[t.NodeID][]byte)
for node, sig := range state.Signatures {
cert[node] = sig
}
// Announce the stable checkpoint to the ordering protocol.
checkpointpbdsl.StableCheckpoint(m, mc.Ord, p.EpochConfig.FirstSn, state.StateSnapshot, cert)
}
func applyCheckpointReceived(m dsl.Module,
p *ModuleParams,
state *State,
moduleConfig ModuleConfig,
from t.NodeID,
epoch tt.EpochNr,
sn tt.SeqNr,
snapshotHash []uint8,
signature []uint8,
logger logging.Logger) error {
if sn != p.EpochConfig.FirstSn {
logger.Log(logging.LevelWarn, "invalid sequence number %v, expected %v as first sequence number.\n", sn, p.EpochConfig.FirstSn)
return nil
}
if epoch != p.EpochConfig.EpochNr {
logger.Log(logging.LevelWarn, "invalid epoch number %v, expected %v.\n", epoch, p.EpochConfig.EpochNr)
return nil
}
// check if from is part of the membership
if _, ok := p.Membership.Nodes[from]; !ok {
logger.Log(logging.LevelWarn, "sender %s is not a member.\n", from)
return nil
}
// Notify the protocol about the progress of the from node.
// If no progress is made for a configured number of epochs,
// the node is considered to be a straggler and is sent a stable checkpoint to catch uparams.
checkpointpbdsl.EpochProgress(m, moduleConfig.Ord, from, epoch)
// If checkpoint is already stable, ignore message.
if state.Stable(p) {
return nil
}
// Check snapshot hash
if state.StateSnapshotHash == nil {
// The message is received too early, put it aside
state.PendingMessages[from] = &checkpointpbtypes.Checkpoint{
Epoch: epoch,
Sn: sn,
SnapshotHash: snapshotHash,
Signature: signature,
}
return nil
} else if !bytes.Equal(state.StateSnapshotHash, snapshotHash) {
// Snapshot hash mismatch
logger.Log(logging.LevelWarn, "Ignoring Checkpoint message. Mismatching state snapshot hash.", "from", from)
return nil
}
// Ignore duplicate messages.
if _, ok := state.SigReceived[from]; ok {
return nil
}
state.SigReceived[from] = struct{}{}
// Verify signature of the sender.
sigData := serializeCheckpointForSig(p.EpochConfig.EpochNr, p.EpochConfig.FirstSn, state.StateSnapshotHash)
cryptopbdsl.VerifySig(m,
moduleConfig.Crypto,
sigData,
signature,
from,
&verificationContext{signature: signature},
)
return nil
}
func (state *State) SnapshotReady() bool {
return state.StateSnapshot.AppData != nil &&
state.StateSnapshot.EpochData.ClientProgress != nil
}
func (state *State) Stable(p *ModuleParams) bool {
return state.SnapshotReady() && membutil.HaveStrongQuorum(p.Membership, maputil.GetKeys(state.Signatures))
}
type verificationContext struct {
signature []uint8
}