-
Notifications
You must be signed in to change notification settings - Fork 3
/
pbft.js
1751 lines (1571 loc) · 60.3 KB
/
pbft.js
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* jshint globalstrict: true */
/* jshint browser: true */
/* jshint devel: true */
/* jshint jquery: true */
/* global util */
'use strict';
var pbft = {};
(function() {
/* Begin PBFT algorithm logic */
// Number of servers participating in PBFT.
var NUM_SERVERS = 5;
// Number of clients whose requests are serviced.
var NUM_CLIENTS = 1;
// This is 'f' described in the paper, i.e., the number of Byzantine (arbitrary)
// failures that the algorithm can progress correctly with.
var NUM_TOLERATED_BYZANTINE_FAULTS = 1;
//f+1
var MINIMAL_APPROVE = Math.floor((NUM_SERVERS-1)/3) + 1;
// Public variable, indicating how many nodes to draw.
pbft.NUM_NODES = NUM_SERVERS + NUM_CLIENTS;
// Messages have a latency randomly selected in the range
// [MIN_RPC_LATENCY, MAX_RPC_LATENCY]
var MIN_RPC_LATENCY = 18000;
var MAX_RPC_LATENCY = 22000;
// View change timeouts are randomly selected in the range
// [VIEW_CHANGE_TIMEOUT, 2 * VIEW_CHANGE_TIMEOUT].
var VIEW_CHANGE_TIMEOUT = 80000;
//client multicast timer default
var CLIENT_MULTICAST_TIMER = 300000;
const NODE_STATE = {
/* Prefix with pbft to avoid collision with other algorithms
* that use the same names for CSS classes. */
PRIMARY: 'pbft_primary',
BACKUP: 'pbft_backup',
CHANGING_VIEW: 'pbft_changing_view',
CRASHED: 'pbft_crashed',
CLIENT: 'pbft_client',
UNKNOWN: 'pbft_unknown'
}
const MESSAGE_TYPE = {
CLIENT_REQUEST: 'client_request',
PRE_PREPARE: 'pre_prepare_msg',
PREPARE: 'pbft_prepare_msg',
COMMIT: 'commit_msg',
CLIENT_REPLY: 'client_reply',
VIEW_CHANGE: 'view_change_msg',
NEW_VIEW: 'new_view_msg',
CHECKPOINT: 'checkpoint_msg'
}
/**
* Translate ID in range [1, NUM_SERVERS] to initial server state.
* Backups participate in PBFT; clients make requests to the backups.
* | ---- backups ---- | ---- clients ---- |
* 0 NUM_SERVERS NUM_NODES
*/
var serverIdToState = function (id) {
if (0 <= id && id < NUM_SERVERS) {
return NODE_STATE.BACKUP;
}
if (id < pbft.NUM_NODES) {
return NODE_STATE.CLIENT;
}
return NODE_STATE.UNKNOWN;
}
pbft.makePeers = function(numPeers) {
var peers = [];
for (var j = 0; j < numPeers; j += 1) {
peers.push(j);
}
return peers;
}
var sendMessage = function(model, message) {
message.authentic = model.servers[message.from].authentic;
message.sendTime = model.time;
message.recvTime = (message.from == message.to) ? model.time + 1000 :
model.time + MIN_RPC_LATENCY +
Math.random() * (MAX_RPC_LATENCY - MIN_RPC_LATENCY);
model.messages.push(message);
};
var sendRequest = function(model, request) {
request.direction = 'request';
sendMessage(model, request);
};
var rules = {};
pbft.rules = rules;
var makeViewChangeAlarm = function(now, server) {
server.viewChangeTimeout = VIEW_CHANGE_TIMEOUT * server.viewChangeAttempt;
return now + (Math.random() + 1) * (server.viewChangeTimeout);
};
/**
* Make an array, containing arrays for for each peer. This is useful when
* tracking a queue of things happening for each peer (e.g. broadcasting a
* message).
*/
var makePeerArrays = function() {
return util.makeArrayOfArrays(pbft.NUM_NODES);
}
// Public API.
pbft.server = function(id, peers) {
return {
/* id ranges from `0` to `NUM_NODES - 1`. server.id represents "i"
* when the paper refers to message formats. */
id: id,
/* peers is an array holding IDs of all peer servers, including itself.
* These range from `0` to `NUM_NODES - 1`. */
peers: peers,
state: serverIdToState(id),
/* Holds the last sequence number used in a message sent out from this server. */
lastUsedSequenceNumber: -1,
/* Contains committed messages. */
log: [],
/* Describes the view that the server is in, as described in the paper. */
view: 0,
/* The next time that the server will time out and begin a view change.
* Set to infinity means no timeout. */
viewChangeAlarm: util.Inf,
/* Record of the highest valid view change reques this server has received,
* to ensure views are monotonically increasing. */
highestViewChangeReceived: 0,
/* The attempt number of the next view change. Used to calculate the next view
* that this server should try to move towards (allowing skipping past up to f
* malicious servers that block the view change). */
viewChangeAttempt: 1,
/* By default at VIEW_CHANGE_TIMEOUT. Set when making a new view change timeout
* to increase the timeout after each failed attempt. */
viewChangeTimeout: VIEW_CHANGE_TIMEOUT,
/* Flag to indicate whether this server will produce authentic messages, assuming
* peers can check the authenticity of the server based on the message. */
authentic: true,
/* Queue of messages that are waiting to be executed (i.e. that the server knows
* about). Different from queuedClientRequests in that queuedClientRequests is
* consumed by the primary when starting pre-prepare for the request, but the
* request maintains a record in clientRequestsToExecute, which is only consumed
* once the request is actually executed. This means that a primary that failed
* after starting a pre-prepare can still observe that a request still needs to
* be processed, and time out so that another primary can try. */
clientRequestsToExecute: [],
/* Local queue at the server of requests to process queuedClientRequests. If a
* request has been recorded in clientRequestsToExecute, and there has not been
* attempt to execute the request in the current view, the primary adds requests
* from clientRequestsToExecute to queuedClientRequests. */
queuedClientRequests: [],
/* After reading from queuedClientRequests, a primary queues copies of the client
* message to send as pre-prepares to servers in clientMessagesToSend. This stores
* the messages indexed first by the server's view number, and then by its peers'
* IDs. */
clientMessagesToSend: {},
/* Record of the peers that this server has sent prePrepare requests to, for a
* particular (v, n) combination (view, sequence number). This is needed so that
* the server sends the prePrepare to its peers only once. */
prePrepareRequestsSent: {},
/* The pre-prepare requests received and accepted as valid at this server. */
acceptedPrePrepares: {},
/* Record of the peers that this server has sent prepare requests to, for a
* particular (v, n) combination. This is needed so that the server sends the
* prepares to its peers only once. */
sentPrepareRequests: {},
/* The prepare requests that this server has received and accepted. */
acceptedPrepares: {},
/* After reading from acceptedPrepares, the server queues commit messages
* to send to each peer for each accepted prepare message, for all (v, n)
* combinations. */
preparedMessagesToCommit: {},
/* Record of the peers that this server has sent commit requests to, for a
* particular (v, n) combination. This is needed so that the server sends
* commits to its peers only once. */
sentCommitRequests: {},
/* The commit requests that this server has received and accepted. */
receivedCommitRequests: {},
/* Record of the messages that this server has considered committed and
* pushed to its log. Needed so that the server pushes messages for a
* given (n, v) combination to its log only once. */
pushedLogMessages: {},
/* Record of the view change requests that this server has sent to its
* peers for a given view. This is needed so that the server sends view
* change requests to another view only once. */
viewChangeRequestsSent: {},
/* The valid view change requests that this server has received. */
viewChangeRequestsReceived: {},
/* Record of the new view requests that this server has sent to its
* peers for a given view. This is needed so that the server (which is
* becoming primary and sending the newView request) sends new view
* requests to its peers only once. */
newViewRequestsSent: {},
/* TODO: for use in the complete version of view change logic.
* (see the TODO in the sendViewChange function. */
// prePreparedMessageProofs: {},
// checkpointProof: {},
/* Implies if the server has been compromised and is a Byzantine server.
* Under such scenario the server will replace all message contents with
* its own `byzantineSecret` string */
isInByzantineMode: false,
byzantineSecret: "b",
//fields for client
latestPrime: 0,
clientMulticastTimer: util.Inf,
clientRequestTimestamp: 0,
clientReplyCount: 0,
};
};
var updateHighestViewChangeReceived = function(server, v) {
server.highestViewChangeReceived = (v > server.highestViewChangeReceived) ?
v : server.highestViewChangeReceived;
}
var getLatestCheckpointSequenceNumber = function(server) {
// TODO
return 0;
}
rules.startPrePrepare = function(model, server) {
server.clientMessagesToSend[server.view] = server.clientMessagesToSend[server.view] || makePeerArrays();
/* If we are primary and we haven't tried in this view to execute a pending request,
* try it now. */
if ((server.id == (server.view % NUM_SERVERS)) &&
(server.clientRequestsToExecute.length !== 0)) {
server.clientRequestsToExecute.forEach(function(request) {
var foundRequestAttempt = false;
for (let [n, requests] of Object.entries(server.prePrepareRequestsSent[server.view])) {
/* If we sent a pre-prepare in this view to ourselves for this request. */
if (requests[server.id][0] && requests[server.id][0].m == request) {
foundRequestAttempt = true;
}
}
if (!foundRequestAttempt) {
server.queuedClientRequests.push(request);
}
});
}
if ((server.id == (server.view % NUM_SERVERS)) &&
(server.queuedClientRequests.length !== 0)) {
/* Increment the sequence number every time we start a new pre-prepare
* request. This ensures a unique sequence number for requests
* made in the same view, so total ordering can be realized. */
server.lastUsedSequenceNumber += 1;
/* Extract the request from the queue the client sent the request to. */
var request = server.queuedClientRequests.shift();
/* Queue the messages to be sent to other servers (see where this is read in
* sendPrePrepare). */
server.clientMessagesToSend[server.view].forEach(function(peerMessageQueue) {
peerMessageQueue.push(request);
});
}
};
// Makes message digest a bit more realistic and fancier.
var hashCode = function(m) {
// Incoming message might be of type "number".
if (typeof m !== "string") {
m = m.toString();
}
var hash = 0;
if (m.length == 0) return hash;
for (var i = 0; i < m.length; i++) {
var char = m.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash.toString(); // We work with strings throughout to make things easier.
}
/* Returns the original message or a byzantine version if server
* has `isInByzantineMode` set to true */
var checkAndGetMessage = function(server, message) {
var sequence = message.split(':')[1];
if (server.isInByzantineMode) {
message = server.byzantineSecret + ':' + sequence;
}
return message;
}
rules.sendPrePrepare = function(model, server, peer) {
server.clientMessagesToSend[server.view] = server.clientMessagesToSend[server.view] || makePeerArrays();
server.prePrepareRequestsSent[server.view] = server.prePrepareRequestsSent[server.view] || {};
server.prePrepareRequestsSent[server.view][server.lastUsedSequenceNumber]
= server.prePrepareRequestsSent[server.view][server.lastUsedSequenceNumber] || makePeerArrays();
if ((server.id == (server.view % NUM_SERVERS)) &&
(server.clientMessagesToSend[server.view][peer].length !== 0) &&
(server.prePrepareRequestsSent[server.view][server.lastUsedSequenceNumber][peer].length === 0)) {
var message = checkAndGetMessage(server, server.clientMessagesToSend[server.view][peer][0]);
var request = {
from: server.id,
to: peer,
type: MESSAGE_TYPE.PRE_PREPARE,
v: server.view,
n: server.lastUsedSequenceNumber,
/* Indicator of whether the pre-prepare message has a valid client signature.
* In Byzantine mode, the server will rewrite the value of the message with the
* character 'b', and overwrite the digest, before sending the pre-prepare.
* In doing this, assuming the server cannot subvert the cryptographic
* techniques used, the client signature which was attached to the original
* message (see section 4.2 of the PBFT paper, http://pmg.csail.mit.edu/papers/osdi99.pdf)
* becomes invalid for the rewritten message contents in the pre-prepare.
* Instead of computing signatures using real keys, the he flag
* `hasValidClientSignature` indicates this condition for demonstration
* purposes, and is used to check later whether a server should accept a
* pre-prepare message (see handlePrePrepareRequest). */
hasValidClientSignature: !server.isInByzantineMode,
/* Digest of the message which is part of the validation on receiver. */
d: hashCode(message),
/* The message content is sent at the same time as the pre-prepare. */
m: message,
};
server.prePrepareRequestsSent[server.view][server.lastUsedSequenceNumber][peer].push(request);
server.clientMessagesToSend[server.view][peer].shift();
sendRequest(model, request);
}
};
var handlePrePrepareRequest = function(model, server, request) {
server.acceptedPrePrepares[request.v] = server.acceptedPrePrepares[request.v] || {};
server.acceptedPrePrepares[request.v][request.n] = server.acceptedPrePrepares[request.v][request.n] || [];
// Signature check before pushing the pre-prepare message.
if (request.d !== hashCode(request.m)) {
console.log(`Preprepare request ${request} rejected due to wrong digest.
Expecting: ${hashCode(request.m)}; Got: ${request.d}.`);
return;
}
if ((!request.authentic || !request.hasValidClientSignature) && !server.isInByzantineMode && request.from !== server.id) {
console.log(`Preprepare request ${request} from unathenticated source rejected.`);
return;
}
if (server.acceptedPrePrepares[request.v][request.n].length !== 0 &&
hashCode(request.m) !== server.acceptedPrePrepares[request.v][request.n][0]) {
console.log(`Preprepare request of same view, sequence numbeer for a different digest already accepted. Not accepting.`)
return;
}
/* Backups may only have found out about the request to execute through
* the pre-prepare from the primary, so they queue it here if they do
* not have it already. */
if (!server.clientRequestsToExecute.includes(request.m)) {
server.clientRequestsToExecute.push(request.m);
}
server.acceptedPrePrepares[request.v][request.n].push(request);
var msg = request.v + "," + request.n + "," + request.m;
server.log.push({v: request.v, n: request.n, m: msg, status: "pre-prepared"});
server.log.sort((a, b) => {
// Order log messages by (v, n) tuple
if (a.v == b.v) {
return a.n - b.n;
} else {
return a.v - b.v;
}
});
};
rules.sendPrepares = function(model, server, peer) {
server.acceptedPrePrepares[server.view] = server.acceptedPrePrepares[server.view] || {};
server.sentPrepareRequests[server.view] = server.sentPrepareRequests[server.view] || {};
for (let [n, requests] of Object.entries(server.acceptedPrePrepares[server.view])) {
server.sentPrepareRequests[server.view][n] = server.sentPrepareRequests[server.view][n] || makePeerArrays();
/* Check that only one pre-prepare was ever sent. */
console.assert(requests.length <= 1);
if ((requests.length === 1) &&
(server.sentPrepareRequests[server.view][n][peer].length === 0) &&
(!(server.view % NUM_SERVERS == server.id)) /* Primary does not send prepares. */
) {
/* We should only be preparing a message that was pre-prepared in the same view. */
console.assert(server.view === requests[0].v);
var request = {
from: server.id,
to: peer,
type: MESSAGE_TYPE.PREPARE,
v: server.view,
n: n,
d: requests[0].d, // Use the pre-prepare message's digest.
};
sendRequest(model, request);
server.sentPrepareRequests[server.view][n][peer].push(request);
}
}
};
// Returns the latest client message server has received
// in a preprepare request given the view number and
// sequence number. Returns null if it never got any.
var extractLatestMessage = function(server, v, n) {
// First two conditions are sanity checks.
if (!(v in server.acceptedPrePrepares) ||
!(n in server.acceptedPrePrepares[v]) ||
!(0 in server.acceptedPrePrepares[v][n])) {
return null;
}
return checkAndGetMessage(server, server.acceptedPrePrepares[v][n][0].m);
}
var handlePrepareRequest = function(model, server, request) {
server.acceptedPrepares[request.v] = server.acceptedPrepares[request.v] || {};
server.acceptedPrepares[request.v][request.n] = server.acceptedPrepares[request.v][request.n] || makePeerArrays();
// Signature check before pushing the prepare message.
var msg = extractLatestMessage(server, request.v, request.n);
if (msg === null) {
console.log("Server received prepare request without any preprepared messages.");
return;
}
if (request.d !== hashCode(msg)) {
console.log(`Prepare request ${request} rejected due to wrong digest.
Expecting: ${hashCode(msg)}; Got: ${request.d}.`);
return;
}
if (!request.authentic && !server.isInByzantineMode && request.from !== server.id) {
console.log(`Prepare request ${request} from unathenticated source rejected.`);
return;
}
server.acceptedPrepares[request.v][request.n][request.from].push(request);
};
/**
* Helper function to get the number of unique peers that received a message
* of type PREPARE.
*/
var getUniqueNumPrepareRequestsReceived = function(peerPrepareRequests) {
if (peerPrepareRequests == undefined) {
return 0;
}
var count = 0;
peerPrepareRequests.forEach(function(peerRequestQueue) {
if (peerRequestQueue.length !== 0 &&
peerRequestQueue[0].type == MESSAGE_TYPE.PREPARE) {
count += 1;
}
}, count);
return count;
};
rules.startCommit = function(model, server) {
server.preparedMessagesToCommit[server.view] = server.preparedMessagesToCommit[server.view] || {};
server.acceptedPrepares[server.view] = server.acceptedPrepares[server.view] || {};
for (let [n, requests] of Object.entries(server.acceptedPrepares[server.view])) {
server.preparedMessagesToCommit[server.view][n] = server.preparedMessagesToCommit[server.view][n] || [];
/* The below condition checks the "prepared" predicate mentioned in the
* paper. Note that only 2f PREPAREs are required from different replicas
* (including itself). */
if ((getUniqueNumPrepareRequestsReceived(requests) >=
(2 * NUM_TOLERATED_BYZANTINE_FAULTS)) &&
(server.preparedMessagesToCommit[server.view][n].length == 0)) {
var requestToCommit = getFirstRequest(requests)[0];
server.preparedMessagesToCommit[server.view][n].push(requestToCommit);
server.log.forEach(function(entry) {
if (entry.v === requestToCommit.v && n == requestToCommit.n) {
if (entry.status == "pre-prepared") {
entry.status = "prepared"
}
}
});
}
}
};
rules.sendCommits = function(model, server, peer) {
server.preparedMessagesToCommit[server.view] = server.preparedMessagesToCommit[server.view] || {};
server.sentCommitRequests[server.view] = server.sentCommitRequests[server.view] || {};
for (let [n, requests] of Object.entries(server.preparedMessagesToCommit[server.view])) {
console.assert(requests.length <= 1);
server.sentCommitRequests[server.view][n] = server.sentCommitRequests[server.view][n] || makePeerArrays();
if ((requests.length === 1) &&
(server.sentCommitRequests[server.view][n][peer].length === 0)
) {
var request = {
from: server.id,
to: peer,
type: MESSAGE_TYPE.COMMIT,
v: server.view,
n: n,
d: hashCode(extractLatestMessage(server, server.view, n)), // Recompute digest.
};
/* Sequence number of the request must match the sequence numbeer we
* are indexing the `preparedMessagesToCommit` object by. */
console.assert(n == request.n);
sendRequest(model, request);
server.sentCommitRequests[server.view][n][peer].push(request);
}
}
};
var handleCommitRequest = function(model, server, request) {
server.receivedCommitRequests[request.v] = server.receivedCommitRequests[request.v] || {};
server.receivedCommitRequests[request.v][request.n] = server.receivedCommitRequests[request.v][request.n] || makePeerArrays();
// Signature check before pushing the commit request.
var msg = extractLatestMessage(server, request.v, request.n);
if (msg === null) {
console.log("Server received commit request without any preprepared messages.");
return;
}
if (request.d !== hashCode(msg)) {
console.log(`Commit request ${request} rejected due to wrong digest.
Expecting: ${hashCode(msg)}; Got: ${request.d}.`);
return;
}
if (!request.authentic && !server.isInByzantineMode && request.from !== server.id) {
console.log(`Preprepare request ${request} from unathenticated source rejected.`);
return;
}
server.receivedCommitRequests[request.v][request.n][request.from].push(request);
};
/**
* Helper function to get the number of unique peers that received a message
* of type COMMIT.
*/
var getUniqueNumCommitRequestsReceived = function(peerCommitRequests) {
if (peerCommitRequests == undefined) {
return 0;
}
var count = 0;
peerCommitRequests.forEach(function(peerRequestQueue) {
if (peerRequestQueue.length !== 0 &&
peerRequestQueue[0].type == MESSAGE_TYPE.COMMIT) {
count += 1;
}
}, count);
return count;
};
/**
* Helper function to return the first array of request queues that has
* received a request.
*/
var getFirstRequest = function(requestQueues) {
for (var i = 0; i < requestQueues.length; i++) {
if (requestQueues[i].length !== 0) {
return requestQueues[i];
}
}
return null;
}
rules.addCommitsToLog = function(model, server) {
server.receivedCommitRequests[server.view] = server.receivedCommitRequests[server.view] || {};
server.pushedLogMessages[server.view] = server.pushedLogMessages[server.view] || {};
Object.keys(server.receivedCommitRequests[server.view]).forEach(function(n) {
server.receivedCommitRequests[server.view][n] = server.receivedCommitRequests[server.view][n] || makePeerArrays();
server.pushedLogMessages[server.view][n] = server.pushedLogMessages[server.view][n] || [];
if ((getUniqueNumCommitRequestsReceived(server.receivedCommitRequests[server.view][n]) >=
(2 * NUM_TOLERATED_BYZANTINE_FAULTS) + 1) &&
(server.pushedLogMessages[server.view][n].length == 0)) {
var rq = getFirstRequest(server.receivedCommitRequests[server.view][n])[0];
var m = undefined;
for (let [n, requests] of Object.entries(server.acceptedPrePrepares[server.view])) {
if (n == rq.n && requests[0].v == rq.v) {
m = requests[0].m;
break;
}
}
/* Right now, this can happen if say a pre-prepare message from the new
* primary made it to a peer, before the new-view message. In this case,
* the peer won't have accepted the pre-prepare in the same view. */
if (m === undefined) {
console.warn("server " + server.id + "missed pre-prepare for message with view " + rq.v + " and sequence number " + rq.n);
return;
}
/* If the request was satisfied, remove it from queuedClientRequests. If
* there are no more requests, we can remove the timeout, or reset the
* timeout if there are still requests to process. */
for (var i = 0; i < server.queuedClientRequests.length; i++) {
if (server.queuedClientRequests[i] == m) {
server.queuedClientRequests.splice(i, 1);
}
}
for (var i = 0; i < server.clientRequestsToExecute.length; i++) {
if (server.clientRequestsToExecute[i] == m) {
server.clientRequestsToExecute.splice(i, 1);
if (server.clientRequestsToExecute.length == 0) {
server.viewChangeAlarm = util.Inf;
} else {
server.viewChangeAlarm = makeViewChangeAlarm(model.time, server);
}
}
}
server.log.forEach(function(entry) {
if (entry.v === rq.v && entry.n == rq.n) {
entry.status = "committed"
}
});
var msg = rq.v + "," + rq.n + "," + m;
server.pushedLogMessages[server.view][n].push(msg);
var reply = {
from: server.id,
to: util.pbftGetClient(model),
v: server.view,
timestamp: m.split(":")[1],
r: m.split(":")[0],
type: MESSAGE_TYPE.CLIENT_REPLY,
};
sendRequest(model, reply);
}
});
};
rules.sendClientReply = function(model, server, peer) {
// TODO
}
rules.startViewChangeTimeout = function(model, server) {
/* Only reset the timeout if it wasn't already running. This prevents
* repeatedly restarting over and over. */
if (server.viewChangeAlarm !== util.Inf) {
return;
}
/* If we're currently trying to change the view, and we've received one
* valid view change request from every peer, we start the timeout again,
* active until we receive a valid new view request from the new primary. */
var viewChangeStarted = server.state == NODE_STATE.CHANGING_VIEW &&
(getUniqueNumViewChangeRequestsReceived(
server.viewChangeRequestsReceived[server.view +
server.viewChangeAttempt]
) >= ((2 * NUM_TOLERATED_BYZANTINE_FAULTS) + 1));
/* If a message from the client is waiting to be processed, we will need to
* change view if the message is not processed fast enough. */
var clientRequestsWaitingToExecute = server.clientRequestsToExecute.length !== 0;
if (viewChangeStarted || clientRequestsWaitingToExecute) {
server.viewChangeAlarm = makeViewChangeAlarm(model.time, server);
}
};
/**
* Check if server that had set a view change alarm timed out,
* and if so, begin a new view change. */
rules.startNewViewChange = function(model, server) {
if (server.state == NODE_STATE.CRASHED) {
return;
}
if (server.viewChangeAlarm <= model.time) {
if (server.state == NODE_STATE.CHANGING_VIEW) {
/* Increasing the attempt number means that if we failed to move to the
* next view, we can try again to move to the next view after that. */
server.viewChangeAttempt += 1;
}
/* As mentioned in the paper, if a server decided to start a view change, the
* timeout is stopped until 2f+1 view change requests are received, and
* restarted once 2f+1 view change requests are received. */
server.viewChangeAlarm = util.Inf;
/* We must change the state to CHANGING_VIEW so that a server trying to
* move to the next view does not respond to messages other than
* VIEW-CHANGE, NEW-VIEW, or CHECKPOINT. */
server.state = NODE_STATE.CHANGING_VIEW;
}
};
rules.sendViewChange = function(model, server, peer) {
var nextView = server.view + server.viewChangeAttempt;
server.viewChangeRequestsSent[nextView] = server.viewChangeRequestsSent[nextView] || makePeerArrays();
if (server.state == NODE_STATE.CHANGING_VIEW &&
server.viewChangeRequestsSent[nextView][peer].length == 0) {
/* TODO(rfairley): Must compute C and P and attach these to the view
* change request (the set of committed but not checkpointed requests
* this server has processed, and the set of prepared but not
* committed requests this server has a record of). */
var message = {
from: server.id,
to: peer,
type: MESSAGE_TYPE.VIEW_CHANGE,
v: nextView,
n: getLatestCheckpointSequenceNumber(server),
C: server.checkpointProof, /* TODO: see above */
P: server.prePreparedMessageProofs, /* TODO: see above */
};
server.viewChangeRequestsSent[nextView][peer].push(message);
sendRequest(model, message);
}
};
var handleViewChangeRequest = function(model, server, request) {
if (!request.authentic && request.from !== server.id) {
return;
}
server.viewChangeRequestsReceived[request.v] = server.viewChangeRequestsReceived[request.v] || makePeerArrays();
server.viewChangeRequestsReceived[request.v][request.from].push(request);
updateHighestViewChangeReceived(server, request.v);
};
/**
* Helper function to get the number of unique peers that received a message
* of type VIEW_CHANGE.
*/
var getUniqueNumViewChangeRequestsReceived = function(peerViewChangeRequests) {
if (peerViewChangeRequests == undefined) {
return 0;
}
var count = 0;
peerViewChangeRequests.forEach(function(requests) {
if (requests.length !== 0 &&
requests[0].type == MESSAGE_TYPE.VIEW_CHANGE) {
count += 1;
}
}, count);
return count;
};
rules.sendNewView = function(model, server, peer) {
server.newViewRequestsSent[server.highestViewChangeReceived] = server.newViewRequestsSent[server.highestViewChangeReceived] || makePeerArrays();
if ((getUniqueNumViewChangeRequestsReceived(
server.viewChangeRequestsReceived[server.highestViewChangeReceived]
) >= (2 * NUM_TOLERATED_BYZANTINE_FAULTS + 1)) &&
(server.id == (server.highestViewChangeReceived % NUM_SERVERS)) &&
(server.newViewRequestsSent[server.highestViewChangeReceived][peer].length === 0)) {
var message = {
from: server.id,
to: peer,
type: MESSAGE_TYPE.NEW_VIEW,
v: server.highestViewChangeReceived,
V: server.viewChangeRequestsReceived[server.highestViewChangeReceived],
};
sendRequest(model, message);
server.view = server.highestViewChangeReceived;
/* Even though this node is going to be PRIMARY next, we first set it to
* BACKUP so that the becomePrimary function is the only function that
* can set nodes to a PRIMARY state. */
server.state = NODE_STATE.BACKUP;
server.newViewRequestsSent[server.highestViewChangeReceived][peer].push(message);
}
};
var handleNewViewRequest = function(model, server, request) {
if (!request.authentic && !server.isInByzantineMode && request.from !== server.id) {
return;
}
if (server.clientRequestsWaitingToExecute === 0) {
server.viewChangeAlarm = util.Inf;
} else {
/* If we're waiting for a client request to be processed, set a new
* timeout. */
server.viewChangeAlarm = makeViewChangeAlarm(model.time, server);
}
if (request.v >= server.view && request.V.length >= (2 * NUM_TOLERATED_BYZANTINE_FAULTS + 1)) {
server.view = request.v;
server.state = NODE_STATE.BACKUP;
server.viewChangeAttempt = 1;
}
/* TODO: the sequence number should be reset upon entering a new view.
* This is causing problems now, for now just let it strictly increase. */
//server.lastUsedSequenceNumber = -1;
};
rules.sendCheckpoint = function(model, server, peer) {
// TODO
};
/* Check if the server should be marked as primary. Note that changing
* the server's state to 'primary' does not change anything in terms of
* how it responds to requests when compared to those of type 'backup'.
* The primary designation is only used to differentiate the primary
* server in the visual display, e.g. using the getLeader function. */
rules.becomePrimary = function(model, server) {
var count = 0;
for (var i = 0; i < model.servers.length; i++) {
if ((model.servers[i].view % NUM_SERVERS) == server.id) {
count += 1;
}
}
if (count >= (2 * NUM_TOLERATED_BYZANTINE_FAULTS + 1) &&
server.state == NODE_STATE.BACKUP) { // Make sure the server is not NODE_STATE.CHANGING_VIEW.
var oldPrimary = pbft.getLeader();
if (oldPrimary !== null) {
oldPrimary.state = NODE_STATE.BACKUP;
}
server.state = NODE_STATE.PRIMARY;
}
}
var handleCheckpointRequest = function(model, server, request) {
// TODO
};
var handleClientRequestRequest = function(model, server, request) {
/* Servers don't respond to requests other than view-change, change-view
* or checkpoint when view changing. */
if (server.state.CHANGING_VIEW) {
return;
}
if (server.isInByzantineMode) {
request.value = server.byzantineSecret;
}
var clientRequestContents = request.value + ":" + request.timestamp;
if (!server.clientRequestsToExecute.includes(clientRequestContents)) {
if (server.id == server.view % NUM_SERVERS) {
server.clientRequestsToExecute.push(clientRequestContents);
} else if (request.from === util.pbftGetClient(model)) {
server.clientRequestsToExecute.push(clientRequestContents);
// Forward to primary, if not the primary and the message came
// from the client.
request.from = server.id;
request.to = server.view % NUM_SERVERS;
sendMessage(model, request);
}
}
}
var handleClientReplyRequest = function(model, server, request) {//daniel
if(request.authentic && request.timestamp == server.clientRequestTimestamp){//authentic and timestamp matches
server.clientReplyCount++;
}
updateHighestViewChangeReceived(server, request.v);
server.latestPrime = server.highestViewChangeReceived % NUM_SERVERS;
}
var handleServerMessage = function(model, server, message) {
if (message.type == MESSAGE_TYPE.CLIENT_REQUEST) {
handleClientRequestRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.PRE_PREPARE) {
handlePrePrepareRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.PREPARE) {
handlePrepareRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.COMMIT) {
handleCommitRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.VIEW_CHANGE) {
handleViewChangeRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.NEW_VIEW) {
handleNewViewRequest(model, server, message);
}
if (message.type == MESSAGE_TYPE.CHECKPOINT) {
handleCheckpointRequest(model, server, message);
}
}
var handleClientMessage = function(model, server, message) {
if (message.type == MESSAGE_TYPE.CLIENT_REPLY) {
handleClientReplyRequest(model, server, message);
}
}
var handleMessage = function(model, server, message) {
switch(server.state) {
case NODE_STATE.BACKUP:
case NODE_STATE.PRIMARY:
case NODE_STATE.CHANGING_VIEW: {
/* The primary and backup are treated exactly the same
* when handling requests. Each server has their own local
* view of who the primary is, based on their view number. */
handleServerMessage(model, server, message);
break;
}
case NODE_STATE.CLIENT: {
handleClientMessage(model, server, message);
break;
}
default: {
/* We do nothing for crashed or unknown servers. */
break;
}
}
};
var executeServerRules = function(model, server) {
rules.startNewViewChange(model, server);
rules.startViewChangeTimeout(model, server);
rules.becomePrimary(model, server);
rules.startPrePrepare(model, server);
rules.startCommit(model, server);
rules.addCommitsToLog(model, server);
}
var executeClientRules = function(model, server) {
pbft.clientRequestTimedOut(model,server);
pbft.clientRequestNumberCheck(model,server);
}
var executeRules = function(model, server) {
switch(server.state) {
case NODE_STATE.PRIMARY:
case NODE_STATE.BACKUP:
case NODE_STATE.CHANGING_VIEW: {
executeServerRules(model, server);
break;
}
case NODE_STATE.CLIENT: {
executeClientRules(model, server);
break;
}
default: {
break;
}
}
}
var sendServerMessages = function(model, server, peer) {
rules.sendPrePrepare(model, server, peer);
rules.sendPrepares(model, server, peer);
rules.sendCommits(model, server, peer);
rules.sendViewChange(model, server, peer);
rules.sendNewView(model, server, peer);
rules.sendCheckpoint(model, server, peer);
}
var sendMessages = function(model, server, peer) {
switch(model.servers[peer].state) {
case NODE_STATE.PRIMARY:
case NODE_STATE.BACKUP:
case NODE_STATE.CHANGING_VIEW:
// Still send messages to crashed nodes
case NODE_STATE.CRASHED: {
sendServerMessages(model, server, peer);
break;
}
default: {
break;
}
}
}
// Public function.
pbft.update = function(model) {
model.servers.forEach(function(server) {
executeRules(model, server);
server.peers.forEach(function(peer) {