354747d723140af0797ba575cc9b441696283abc
[iotcloud.git] / version2 / src / java / iotcloud / Table.java
1 package iotcloud;
2
3 import java.util.Iterator;
4 import java.util.Random;
5 import java.util.Arrays;
6 import java.util.Map;
7 import java.util.Set;
8 import java.util.List;
9 import java.util.Vector;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.nio.ByteBuffer;
15
16 /**
17  * IoTTable data structure.  Provides client interface.
18  * @author Brian Demsky
19  * @version 1.0
20  */
21
22 final public class Table {
23
24
25         /* Constants */
26         static final int FREE_SLOTS = 10; // Number of slots that should be kept free
27         static final int SKIP_THRESHOLD = 10;
28         static final double RESIZE_MULTIPLE = 1.2;
29         static final double RESIZE_THRESHOLD = 0.75;
30         static final int REJECTED_THRESHOLD = 5;
31
32         /* Helper Objects */
33         private SlotBuffer buffer = null;
34         private CloudComm cloud = null;
35         private Random random = null;
36         private TableStatus liveTableStatus = null;
37         private PendingTransaction pendingTransactionBuilder = null; // Pending Transaction used in building a Pending Transaction
38         private Transaction lastPendingTransactionSpeculatedOn = null; // Last transaction that was speculated on from the pending transaction
39         private Transaction firstPendingTransaction = null; // first transaction in the pending transaction list
40
41         /* Variables */
42         private int numberOfSlots = 0;  // Number of slots stored in buffer
43         private int bufferResizeThreshold = 0; // Threshold on the number of live slots before a resize is needed
44         private long liveSlotCount = 0; // Number of currently live slots
45         private long oldestLiveSlotSequenceNumver = 0;  // Smallest sequence number of the slot with a live entry
46         private long localMachineId = 0; // Machine ID of this client device
47         private long sequenceNumber = 0; // Largest sequence number a client has received
48         private int smallestTableStatusSeen = -1; // Smallest Table Status that was seen in the latest slots sent from the server
49         private int largestTableStatusSeen = -1; // Largest Table Status that was seen in the latest slots sent from the server
50         private long localTransactionSequenceNumber = 0; // Local sequence number counter for transactions
51         private long lastTransactionSequenceNumberSpeculatedOn = -1; // the last transaction that was speculated on
52         private long oldestTransactionSequenceNumberSpeculatedOn = -1; // the oldest transaction that was speculated on
53         private long localArbitrationSequenceNumber = 0;
54         private boolean hadPartialSendToServer = false;
55         private boolean attemptedToSendToServer = false;
56
57         /* Data Structures  */
58         private Map<IoTString, KeyValue> committedKeyValueTable = null; // Table of committed key value pairs
59         private Map<IoTString, KeyValue> speculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value
60         private Map<IoTString, KeyValue> pendingTransactionSpeculatedKeyValueTable = null; // Table of speculated key value pairs, if there is a speculative value from the pending transactions
61         private Map<IoTString, NewKey> liveNewKeyTable = null; // Table of live new keys
62         private HashMap<Long, Pair<Long, Liveness>> lastMessageTable = null; // Last message sent by a client machine id -> (Seq Num, Slot or LastMessage);
63         private HashMap<Long, HashSet<RejectedMessage>> rejectedMessageWatchListTable = null; // Table of machine Ids and the set of rejected messages they have not seen yet
64         private Map<IoTString, Long> arbitratorTable = null; // Table of keys and their arbitrators
65         private Map<Pair<Long, Long>, Abort> liveAbortTable = null; // Table live abort messages
66         private Map<Long, Map<Pair<Long, Integer>, TransactionPart>> newTransactionParts = null; // transaction parts that are seen in this latest round of slots from the server
67         private Map<Long, Map<Pair<Long, Integer>, CommitPart>> newCommitParts = null; // commit parts that are seen in this latest round of slots from the server
68         private Map<Long, Long> lastArbitratedTransactionNumberByArbitratorTable = null; // Last transaction sequence number that an arbitrator arbitrated on
69         private Map<Long, Transaction> liveTransactionBySequenceNumberTable = null; // live transaction grouped by the sequence number
70         private Map<Pair<Long, Long>, Transaction> liveTransactionByTransactionIdTable = null; // live transaction grouped by the transaction ID
71         private Map<Long, Map<Long, Commit>> liveCommitsTable = null;
72         private Map<IoTString, Commit> liveCommitsByKeyTable = null;
73         private Map<Long, Long> lastCommitSeenSequenceNumberByArbitratorTable = null;
74         private Vector<Long> rejectedSlotList = null; // List of rejected slots that have yet to be sent to the server
75         private List<Transaction> pendingTransactionQueue = null;
76         private List<ArbitrationRound> pendingSendArbitrationRounds = null;
77         private List<Entry> pendingSendArbitrationEntriesToDelete = null;
78         private Map<Transaction, List<Integer>> transactionPartsSent = null;
79         private Map<Long, TransactionStatus> outstandingTransactionStatus = null;
80         private Map<Long, Abort> liveAbortsGeneratedByLocal = null;
81         private Set<Pair<Long, Long>> offlineTransactionsCommittedAndAtServer = null;
82         private Map<Long, Pair<String, Integer>> localCommunicationTable = null;
83         private Map<Long, Long> lastTransactionSeenFromMachineFromServer = null;
84         private Map<Long, Long> lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = null;
85
86
87
88
89
90         public Table(String baseurl, String password, long _localMachineId, int listeningPort) {
91                 localMachineId = _localMachineId;
92                 cloud = new CloudComm(this, baseurl, password, listeningPort);
93
94                 init();
95         }
96
97         public Table(CloudComm _cloud, long _localMachineId) {
98                 localMachineId = _localMachineId;
99                 cloud = _cloud;
100
101                 init();
102         }
103
104         /**
105          * Init all the stuff needed for for table usage
106          */
107         private void init() {
108
109                 // Init helper objects
110                 random = new Random();
111                 buffer = new SlotBuffer();
112
113                 // Set Variables
114                 oldestLiveSlotSequenceNumver = 1;
115
116                 // init data structs
117                 committedKeyValueTable = new HashMap<IoTString, KeyValue>();
118                 speculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
119                 pendingTransactionSpeculatedKeyValueTable = new HashMap<IoTString, KeyValue>();
120                 liveNewKeyTable = new HashMap<IoTString, NewKey>();
121                 lastMessageTable = new HashMap<Long, Pair<Long, Liveness>>();
122                 rejectedMessageWatchListTable = new HashMap<Long, HashSet<RejectedMessage>>();
123                 arbitratorTable = new HashMap<IoTString, Long>();
124                 liveAbortTable = new HashMap<Pair<Long, Long>, Abort>();
125                 newTransactionParts = new HashMap<Long, Map<Pair<Long, Integer>, TransactionPart>>();
126                 newCommitParts = new HashMap<Long, Map<Pair<Long, Integer>, CommitPart>>();
127                 lastArbitratedTransactionNumberByArbitratorTable = new HashMap<Long, Long>();
128                 liveTransactionBySequenceNumberTable = new HashMap<Long, Transaction>();
129                 liveTransactionByTransactionIdTable = new HashMap<Pair<Long, Long>, Transaction>();
130                 liveCommitsTable = new HashMap<Long, Map<Long, Commit>>();
131                 liveCommitsByKeyTable = new HashMap<IoTString, Commit>();
132                 lastCommitSeenSequenceNumberByArbitratorTable = new HashMap<Long, Long>();
133                 rejectedSlotList = new Vector<Long>();
134                 pendingTransactionQueue = new ArrayList<Transaction>();
135                 pendingSendArbitrationEntriesToDelete = new ArrayList<Entry>();
136                 transactionPartsSent = new HashMap<Transaction, List<Integer>>();
137                 outstandingTransactionStatus = new HashMap<Long, TransactionStatus>();
138                 liveAbortsGeneratedByLocal = new HashMap<Long, Abort>();
139                 offlineTransactionsCommittedAndAtServer = new HashSet<Pair<Long, Long>>();
140                 localCommunicationTable = new HashMap<Long, Pair<String, Integer>>();
141                 lastTransactionSeenFromMachineFromServer = new HashMap<Long, Long>();
142                 pendingSendArbitrationRounds = new ArrayList<ArbitrationRound>();
143                 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator = new HashMap<Long, Long>();
144
145
146                 // Other init stuff
147                 numberOfSlots = buffer.capacity();
148                 setResizeThreshold();
149         }
150
151         // TODO: delete method
152         public synchronized void printSlots() {
153                 long o = buffer.getOldestSeqNum();
154                 long n = buffer.getNewestSeqNum();
155
156                 int[] types = new int[10];
157
158                 int num = 0;
159
160                 int livec = 0;
161                 int deadc = 0;
162                 for (long i = o; i < (n + 1); i++) {
163                         Slot s = buffer.getSlot(i);
164
165                         Vector<Entry> entries = s.getEntries();
166
167                         for (Entry e : entries) {
168                                 if (e.isLive()) {
169                                         int type = e.getType();
170                                         types[type] = types[type] + 1;
171                                         num++;
172                                         livec++;
173                                 } else {
174                                         deadc++;
175                                 }
176                         }
177                 }
178
179                 for (int i = 0; i < 10; i++) {
180                         System.out.println(i + "    " + types[i]);
181                 }
182                 System.out.println("Live count:   " + livec);
183                 System.out.println("Dead count:   " + deadc);
184                 System.out.println("Old:   " + o);
185                 System.out.println("New:   " + n);
186                 System.out.println("Size:   " + buffer.size());
187
188                 // List<IoTString> strList = new ArrayList<IoTString>();
189                 // for (int i = 0; i < 100; i++) {
190                 //      String keyA = "a" + i;
191                 //      String keyB = "b" + i;
192                 //      String keyC = "c" + i;
193                 //      String keyD = "d" + i;
194
195                 //      IoTString iKeyA = new IoTString(keyA);
196                 //      IoTString iKeyB = new IoTString(keyB);
197                 //      IoTString iKeyC = new IoTString(keyC);
198                 //      IoTString iKeyD = new IoTString(keyD);
199
200                 //      strList.add(iKeyA);
201                 //      strList.add(iKeyB);
202                 //      strList.add(iKeyC);
203                 //      strList.add(iKeyD);
204                 // }
205
206
207                 // for (Long l : commitMap.keySet()) {
208                 //      for (Long l2 : commitMap.get(l).keySet()) {
209                 //              for (KeyValue kv : commitMap.get(l).get(l2).getkeyValueUpdateSet()) {
210                 //                      strList.remove(kv.getKey());
211                 //                      System.out.print(kv.getKey() + "    ");
212                 //              }
213                 //      }
214                 // }
215
216                 // System.out.println();
217                 // System.out.println();
218
219                 // for (IoTString s : strList) {
220                 //      System.out.print(s + "    ");
221                 // }
222                 // System.out.println();
223                 // System.out.println(strList.size());
224         }
225
226         /**
227          * Initialize the table by inserting a table status as the first entry into the table status
228          * also initialize the crypto stuff.
229          */
230         public synchronized void initTable() throws ServerException {
231                 cloud.setSalt(); //Set the salt
232
233                 // Create the first insertion into the block chain which is the table status
234                 Slot s = new Slot(this, 1, localMachineId);
235                 TableStatus status = new TableStatus(s, numberOfSlots);
236                 s.addEntry(status);
237                 Slot[] array = cloud.putSlot(s, numberOfSlots);
238
239                 if (array == null) {
240                         array = new Slot[] {s};
241                         // update local block chain
242                         validateAndUpdate(array, true);
243                 } else if (array.length == 1) {
244                         // in case we did push the slot BUT we failed to init it
245                         validateAndUpdate(array, true);
246                 } else {
247                         throw new Error("Error on initialization");
248                 }
249         }
250
251         /**
252          * Rebuild the table from scratch by pulling the latest block chain from the server.
253          */
254         public synchronized void rebuild() throws ServerException {
255                 // Just pull the latest slots from the server
256                 Slot[] newslots = cloud.getSlots(sequenceNumber + 1);
257                 validateAndUpdate(newslots, true);
258         }
259
260 // public String toString() {
261 //      String retString = " Committed Table: \n";
262 //      retString += "---------------------------\n";
263 //      retString += commitedTable.toString();
264
265 //      retString += "\n\n";
266
267 //      retString += " Speculative Table: \n";
268 //      retString += "---------------------------\n";
269 //      retString += speculativeTable.toString();
270
271 //      return retString;
272 // }
273
274         public synchronized void addLocalCommunication(long arbitrator, String hostName, int portNumber) {
275                 localCommunicationTable.put(arbitrator, new Pair<String, Integer>(hostName, portNumber));
276         }
277
278         public synchronized Long getArbitrator(IoTString key) {
279                 return arbitratorTable.get(key);
280         }
281
282         public synchronized void close() {
283                 cloud.close();
284         }
285
286         public synchronized IoTString getCommitted(IoTString key)  {
287                 KeyValue kv = committedKeyValueTable.get(key);
288
289                 if (kv != null) {
290                         return kv.getValue();
291                 } else {
292                         return null;
293                 }
294         }
295
296         public synchronized IoTString getSpeculative(IoTString key) {
297                 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
298
299                 if (kv == null) {
300                         kv = speculatedKeyValueTable.get(key);
301                 }
302
303                 if (kv == null) {
304                         kv = committedKeyValueTable.get(key);
305                 }
306
307                 if (kv != null) {
308                         return kv.getValue();
309                 } else {
310                         return null;
311                 }
312         }
313
314         public synchronized IoTString getCommittedAtomic(IoTString key) {
315                 KeyValue kv = committedKeyValueTable.get(key);
316
317                 if (arbitratorTable.get(key) == null) {
318                         throw new Error("Key not Found.");
319                 }
320
321                 // Make sure new key value pair matches the current arbitrator
322                 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
323                         // TODO: Maybe not throw en error
324                         throw new Error("Not all Key Values Match Arbitrator.");
325                 }
326
327                 if (kv != null) {
328                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
329                         return kv.getValue();
330                 } else {
331                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
332                         return null;
333                 }
334         }
335
336         public synchronized IoTString getSpeculativeAtomic(IoTString key) {
337                 if (arbitratorTable.get(key) == null) {
338                         throw new Error("Key not Found.");
339                 }
340
341                 // Make sure new key value pair matches the current arbitrator
342                 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
343                         // TODO: Maybe not throw en error
344                         throw new Error("Not all Key Values Match Arbitrator.");
345                 }
346
347                 KeyValue kv = pendingTransactionSpeculatedKeyValueTable.get(key);
348
349                 if (kv == null) {
350                         kv = speculatedKeyValueTable.get(key);
351                 }
352
353                 if (kv == null) {
354                         kv = committedKeyValueTable.get(key);
355                 }
356
357                 if (kv != null) {
358                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, kv.getValue()));
359                         return kv.getValue();
360                 } else {
361                         pendingTransactionBuilder.addKVGuard(new KeyValue(key, null));
362                         return null;
363                 }
364         }
365
366         public synchronized boolean update()  {
367                 try {
368                         Slot[] newSlots = cloud.getSlots(sequenceNumber + 1);
369                         validateAndUpdate(newSlots, false);
370                         sendToServer(null);
371
372                         return true;
373                 } catch (Exception e) {
374                         // e.printStackTrace();
375                 }
376
377                 return false;
378         }
379
380         public synchronized boolean createNewKey(IoTString keyName, long machineId) throws ServerException {
381                 while (true) {
382                         if (arbitratorTable.get(keyName) != null) {
383                                 // There is already an arbitrator
384                                 return false;
385                         }
386
387                         NewKey newKey = new NewKey(null, keyName, machineId);
388                         if (sendToServer(newKey)) {
389                                 // If successfully inserted
390                                 return true;
391                         }
392                 }
393         }
394
395         public synchronized void startTransaction() {
396                 // Create a new transaction, invalidates any old pending transactions.
397                 pendingTransactionBuilder = new PendingTransaction(localMachineId);
398         }
399
400         public synchronized void addKV(IoTString key, IoTString value) {
401
402                 // Make sure it is a valid key
403                 if (arbitratorTable.get(key) == null) {
404                         throw new Error("Key not Found.");
405                 }
406
407                 // Make sure new key value pair matches the current arbitrator
408                 if (!pendingTransactionBuilder.checkArbitrator(arbitratorTable.get(key))) {
409                         // TODO: Maybe not throw en error
410                         throw new Error("Not all Key Values Match Arbitrator.");
411                 }
412
413                 // Add the key value to this transaction
414                 KeyValue kv = new KeyValue(key, value);
415                 pendingTransactionBuilder.addKV(kv);
416         }
417
418         public synchronized TransactionStatus commitTransaction() {
419
420                 if (pendingTransactionBuilder.getKVUpdates().size() == 0) {
421                         // transaction with no updates will have no effect on the system
422                         return new TransactionStatus(TransactionStatus.StatusNoEffect, -1);
423                 }
424
425                 // Set the local transaction sequence number and increment
426                 pendingTransactionBuilder.setClientLocalSequenceNumber(localTransactionSequenceNumber);
427                 localTransactionSequenceNumber++;
428
429                 // Create the transaction status
430                 TransactionStatus transactionStatus = new TransactionStatus(TransactionStatus.StatusPending, pendingTransactionBuilder.getArbitrator());
431
432                 // Create the new transaction
433                 Transaction newTransaction = pendingTransactionBuilder.createTransaction();
434                 newTransaction.setTransactionStatus(transactionStatus);
435
436                 if (pendingTransactionBuilder.getArbitrator() != localMachineId) {
437                         // Add it to the queue and invalidate the builder for safety
438                         pendingTransactionQueue.add(newTransaction);
439                 } else {
440                         arbitrateOnLocalTransaction(newTransaction);
441                         updateLiveStateFromLocal();
442                 }
443
444                 pendingTransactionBuilder = new PendingTransaction(localMachineId);
445
446                 try {
447                         sendToServer(null);
448                 } catch (ServerException e) {
449
450                         Set<Long> arbitratorTriedAndFailed = new HashSet<Long>();
451                         for (Iterator<Transaction> iter = pendingTransactionQueue.iterator(); iter.hasNext(); ) {
452                                 Transaction transaction = iter.next();
453
454                                 if (arbitratorTriedAndFailed.contains(transaction.getArbitrator())) {
455                                         // Already contacted this client so ignore all attempts to contact this client
456                                         // to preserve ordering for arbitrator
457                                         continue;
458                                 }
459
460                                 Pair<Boolean, Boolean> sendReturn = sendTransactionToLocal(transaction);
461
462                                 if (sendReturn.getFirst()) {
463                                         // Failed to contact over local
464                                         arbitratorTriedAndFailed.add(transaction.getArbitrator());
465                                 } else {
466                                         // Successful contact or should not contact
467
468                                         if (sendReturn.getSecond()) {
469                                                 // did arbitrate
470                                                 iter.remove();
471                                         }
472                                 }
473                         }
474                 }
475
476                 return transactionStatus;
477         }
478
479         /**
480          * Get the machine ID for this client
481          */
482         public long getMachineId() {
483                 return localMachineId;
484         }
485
486         /**
487          * Decrement the number of live slots that we currently have
488          */
489         public void decrementLiveCount() {
490                 liveSlotCount--;
491         }
492
493         /**
494          * Recalculate the new resize threshold
495          */
496         private void setResizeThreshold() {
497                 int resizeLower = (int) (RESIZE_THRESHOLD * numberOfSlots);
498                 bufferResizeThreshold = resizeLower - 1 + random.nextInt(numberOfSlots - resizeLower);
499         }
500
501         private boolean sendToServer(NewKey newKey) throws ServerException {
502
503                 try {
504                         // While we have stuff that needs inserting into the block chain
505                         while ((pendingTransactionQueue.size() > 0) || (pendingSendArbitrationRounds.size() > 0) || (newKey != null)) {
506
507                                 // Create the slot
508                                 Slot slot = new Slot(this, sequenceNumber + 1, localMachineId, buffer.getSlot(sequenceNumber).getHMAC());
509
510                                 // Try to fill the slot with data
511                                 ThreeTuple<Boolean, Integer, Boolean> fillSlotsReturn = fillSlot(slot, false, newKey);
512                                 boolean needsResize = fillSlotsReturn.getFirst();
513                                 int newSize = fillSlotsReturn.getSecond();
514                                 Boolean insertedNewKey = fillSlotsReturn.getThird();
515
516                                 if (needsResize) {
517                                         // Reset which transaction to send
518                                         for (Transaction transaction : transactionPartsSent.keySet()) {
519                                                 transaction.resetNextPartToSend();
520
521                                                 // Set the transaction sequence number back to nothing
522                                                 if (!transaction.didSendAPartToServer()) {
523                                                         transaction.setSequenceNumber(-1);
524                                                 }
525                                         }
526
527                                         // Clear the sent data since we are trying again
528                                         pendingSendArbitrationEntriesToDelete.clear();
529                                         transactionPartsSent.clear();
530
531                                         // We needed a resize so try again
532                                         fillSlot(slot, true, newKey);
533                                 }
534
535                                 // Try to send to the server
536                                 ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsReturn = sendSlotsToServer(slot, newSize, newKey != null);
537
538                                 // if (sendSlotsReturn.getSecond()) {
539                                 //      System.out.println("Second was true");
540                                 // }
541
542
543                                 if (/*sendSlotsReturn.getSecond() || */sendSlotsReturn.getFirst()) {
544                                         // Did insert into the block chain
545
546                                         if (sendSlotsReturn.getFirst()) {
547                                                 // This slot was what was inserted not a previous slot
548
549                                                 // New Key was successfully inserted into the block chain so dont want to insert it again
550                                                 newKey = null;
551                                         }
552
553                                         // Remove the aborts and commit parts that were sent from the pending to send queue
554                                         for (Iterator<ArbitrationRound> iter = pendingSendArbitrationRounds.iterator(); iter.hasNext(); ) {
555                                                 ArbitrationRound round = iter.next();
556                                                 round.removeParts(pendingSendArbitrationEntriesToDelete);
557
558                                                 if (round.isDoneSending()) {
559                                                         // Sent all the parts
560                                                         iter.remove();
561                                                 }
562                                         }
563
564
565                                         for (Transaction transaction : transactionPartsSent.keySet()) {
566
567                                                 // Update which transactions parts still need to be sent
568                                                 transaction.removeSentParts(transactionPartsSent.get(transaction));
569
570                                                 // Add the transaction status to the outstanding list
571                                                 outstandingTransactionStatus.put(transaction.getSequenceNumber(), transaction.getTransactionStatus());
572
573                                                 // Update the transaction status
574                                                 transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentPartial);
575
576                                                 // Check if all the transaction parts were successfully sent and if so then remove it from pending
577                                                 if (transaction.didSendAllParts()) {
578                                                         transaction.getTransactionStatus().setStatus(TransactionStatus.StatusSentFully);
579                                                         pendingTransactionQueue.remove(transaction);
580                                                 }
581                                         }
582                                 } else {
583                                         // Reset which transaction to send
584                                         for (Transaction transaction : transactionPartsSent.keySet()) {
585                                                 transaction.resetNextPartToSend();
586
587                                                 // Set the transaction sequence number back to nothing
588                                                 if (!transaction.didSendAPartToServer()) {
589                                                         transaction.setSequenceNumber(-1);
590                                                 }
591                                         }
592                                 }
593
594                                 // Clear the sent data in preparation for next send
595                                 pendingSendArbitrationEntriesToDelete.clear();
596                                 transactionPartsSent.clear();
597
598                                 if (sendSlotsReturn.getThird().length != 0) {
599                                         // insert into the local block chain
600                                         validateAndUpdate(sendSlotsReturn.getThird(), true);
601                                 }
602                         }
603                 } catch (ServerException e) {
604
605                         if (e.getType() != ServerException.TypeInputTimeout) {
606                                 // e.printStackTrace();
607
608                                 // Nothing was able to be sent to the server so just clear these data structures
609                                 for (Transaction transaction : transactionPartsSent.keySet()) {
610                                         // Set the transaction sequence number back to nothing
611                                         if (!transaction.didSendAPartToServer()) {
612                                                 transaction.setSequenceNumber(-1);
613                                         }
614                                 }
615                         } else {
616                                 // There was a partial send to the server
617                                 hadPartialSendToServer = true;
618                         }
619
620                         pendingSendArbitrationEntriesToDelete.clear();
621                         transactionPartsSent.clear();
622
623                         throw e;
624                 }
625
626                 return newKey == null;
627         }
628
629         private Pair<Boolean, Boolean> sendTransactionToLocal(Transaction transaction) {
630
631                 // Get the devices local communications
632                 Pair<String, Integer> localCommunicationInformation = localCommunicationTable.get(transaction.getArbitrator());
633
634                 if (localCommunicationInformation == null) {
635                         // Cant talk to that device locally so do nothing
636                         return new Pair<Boolean, Boolean>(false, false);
637                 }
638
639                 // Get the size of the send data
640                 int sendDataSize = Integer.BYTES + Long.BYTES;
641                 for (TransactionPart part : transaction.getParts().values()) {
642                         sendDataSize += part.getSize();
643                 }
644
645                 Long lastArbitrationDataLocalSequenceNumber = (long) - 1;
646                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator()) != null) {
647                         lastArbitrationDataLocalSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(transaction.getArbitrator());
648                 }
649
650                 // Make the send data size
651                 byte[] sendData = new byte[sendDataSize];
652                 ByteBuffer bbEncode = ByteBuffer.wrap(sendData);
653
654                 // Encode the data
655                 bbEncode.putLong(lastArbitrationDataLocalSequenceNumber);
656                 bbEncode.putInt(transaction.getParts().size());
657                 for (TransactionPart part : transaction.getParts().values()) {
658                         part.encode(bbEncode);
659                 }
660
661
662
663
664
665
666
667
668
669
670
671
672                 System.out.println("================================");
673                 System.out.println("Sending Locally");
674                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
675                         System.out.println(kv);
676                 }
677
678
679
680
681
682
683
684
685
686
687
688                 // Send by local
689                 byte[] returnData = cloud.sendLocalData(sendData, localCommunicationInformation.getFirst(), localCommunicationInformation.getSecond());
690
691
692                 System.out.println("--------------------------------");
693                 System.out.println();
694
695                 if (returnData == null) {
696                         // Could not contact server
697                         return new Pair<Boolean, Boolean>(true, false);
698                 }
699
700                 // Decode the data
701                 ByteBuffer bbDecode = ByteBuffer.wrap(returnData);
702                 boolean didCommit = bbDecode.get() == 1;
703                 boolean couldArbitrate = bbDecode.get() == 1;
704                 int numberOfEntries = bbDecode.getInt();
705                 boolean foundAbort = false;
706
707                 for (int i = 0; i < numberOfEntries; i++) {
708                         byte type = bbDecode.get();
709                         if (type == Entry.TypeAbort) {
710                                 Abort abort = (Abort)Abort.decode(null, bbDecode);
711
712                                 if ((abort.getTransactionMachineId() == localMachineId) && (abort.getTransactionClientLocalSequenceNumber() == transaction.getClientLocalSequenceNumber())) {
713                                         foundAbort = true;
714                                 }
715
716                                 processEntry(abort);
717                         } else if (type == Entry.TypeCommitPart) {
718                                 CommitPart commitPart = (CommitPart)CommitPart.decode(null, bbDecode);
719                                 processEntry(commitPart);
720                         }
721                 }
722
723                 updateLiveStateFromLocal();
724
725                 if (couldArbitrate) {
726                         TransactionStatus status =  transaction.getTransactionStatus();
727                         if (didCommit) {
728                                 status.setStatus(TransactionStatus.StatusCommitted);
729                         } else {
730                                 status.setStatus(TransactionStatus.StatusAborted);
731                         }
732                 } else {
733                         if (foundAbort) {
734                                 TransactionStatus status =  transaction.getTransactionStatus();
735                                 status.setStatus(TransactionStatus.StatusAborted);
736                                 return new Pair<Boolean, Boolean>(false, false);
737                         }
738                 }
739
740                 return new Pair<Boolean, Boolean>(false, true);
741         }
742
743         public synchronized byte[] acceptDataFromLocal(byte[] data) {
744                 // Decode the data
745                 ByteBuffer bbDecode = ByteBuffer.wrap(data);
746                 long lastArbitratedSequenceNumberSeen = bbDecode.getLong();
747                 int numberOfParts = bbDecode.getInt();
748
749                 // If we did commit a transaction or not
750                 boolean didCommit = false;
751                 boolean couldArbitrate = false;
752
753                 if (numberOfParts != 0) {
754
755                         // decode the transaction
756                         Transaction transaction = new Transaction();
757                         for (int i = 0; i < numberOfParts; i++) {
758                                 bbDecode.get();
759                                 TransactionPart newPart = (TransactionPart)TransactionPart.decode(null, bbDecode);
760                                 transaction.addPartDecode(newPart);
761                         }
762
763                         // Arbitrate on transaction and pull relevant return data
764                         Pair<Boolean, Boolean> localArbitrateReturn = arbitrateOnLocalTransaction(transaction);
765                         couldArbitrate = localArbitrateReturn.getFirst();
766                         didCommit = localArbitrateReturn.getSecond();
767
768                         updateLiveStateFromLocal();
769
770                         // Transaction was sent to the server so keep track of it to prevent double commit
771                         if (transaction.getSequenceNumber() != -1) {
772                                 offlineTransactionsCommittedAndAtServer.add(transaction.getId());
773                         }
774                 }
775
776                 // The data to send back
777                 int returnDataSize = 0;
778                 List<Entry> unseenArbitrations = new ArrayList<Entry>();
779
780                 // Get the aborts to send back
781                 List<Long> abortLocalSequenceNumbers = new ArrayList<Long >(liveAbortsGeneratedByLocal.keySet());
782                 Collections.sort(abortLocalSequenceNumbers);
783                 for (Long localSequenceNumber : abortLocalSequenceNumbers) {
784                         if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
785                                 continue;
786                         }
787
788                         Abort abort = liveAbortsGeneratedByLocal.get(localSequenceNumber);
789                         unseenArbitrations.add(abort);
790                         returnDataSize += abort.getSize();
791                 }
792
793                 // Get the commits to send back
794                 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(localMachineId);
795                 if (commitForClientTable != null) {
796                         List<Long> commitLocalSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
797                         Collections.sort(commitLocalSequenceNumbers);
798
799                         for (Long localSequenceNumber : commitLocalSequenceNumbers) {
800                                 Commit commit = commitForClientTable.get(localSequenceNumber);
801
802                                 if (localSequenceNumber <= lastArbitratedSequenceNumberSeen) {
803                                         continue;
804                                 }
805
806                                 System.out.println("---");
807                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
808                                         System.out.println("Sending Commit Locally:  " + kv);
809                                 }
810                                 System.out.println("---");
811
812                                 unseenArbitrations.addAll(commit.getParts().values());
813
814                                 for (CommitPart commitPart : commit.getParts().values()) {
815                                         returnDataSize += commitPart.getSize();
816                                 }
817                         }
818                 }
819
820                 // Number of arbitration entries to decode
821                 returnDataSize += 2 * Integer.BYTES;
822
823                 // Boolean of did commit or not
824                 if (numberOfParts != 0) {
825                         returnDataSize += Byte.BYTES;
826                 }
827
828                 // Data to send Back
829                 byte[] returnData = new byte[returnDataSize];
830                 ByteBuffer bbEncode = ByteBuffer.wrap(returnData);
831
832                 if (numberOfParts != 0) {
833                         if (didCommit) {
834                                 bbEncode.put((byte)1);
835                         } else {
836                                 bbEncode.put((byte)0);
837                         }
838                         if (couldArbitrate) {
839                                 bbEncode.put((byte)1);
840                         } else {
841                                 bbEncode.put((byte)0);
842                         }
843                 }
844
845                 bbEncode.putInt(unseenArbitrations.size());
846                 for (Entry entry : unseenArbitrations) {
847                         entry.encode(bbEncode);
848                 }
849
850                 return returnData;
851         }
852
853         private ThreeTuple<Boolean, Boolean, Slot[]> sendSlotsToServer(Slot slot, int newSize, boolean isNewKey)  throws ServerException {
854
855                 boolean attemptedToSendToServerTmp = attemptedToSendToServer;
856                 attemptedToSendToServer = true;
857
858                 boolean inserted = false;
859                 boolean lastTryInserted = false;
860
861                 Slot[] array = cloud.putSlot(slot, newSize);
862                 if (array == null) {
863                         array = new Slot[] {slot};
864                         rejectedSlotList.clear();
865                         inserted = true;
866                 }       else {
867                         if (array.length == 0) {
868                                 throw new Error("Server Error: Did not send any slots");
869                         }
870
871                         // if (attemptedToSendToServerTmp) {
872                         if (hadPartialSendToServer) {
873
874                                 boolean isInserted = false;
875                                 for (Slot s : array) {
876                                         if ((s.getSequenceNumber() == slot.getSequenceNumber()) && (s.getMachineID() == localMachineId)) {
877                                                 isInserted = true;
878                                                 break;
879                                         }
880                                 }
881
882                                 for (Slot s : array) {
883                                         if (isInserted) {
884                                                 break;
885                                         }
886
887                                         // Process each entry in the slot
888                                         for (Entry entry : s.getEntries()) {
889
890                                                 if (entry.getType() == Entry.TypeLastMessage) {
891                                                         LastMessage lastMessage = (LastMessage)entry;
892
893                                                         if ((lastMessage.getMachineID() == localMachineId) && (lastMessage.getSequenceNumber() == slot.getSequenceNumber())) {
894                                                                 isInserted = true;
895                                                                 break;
896                                                         }
897                                                 }
898                                         }
899                                 }
900
901                                 if (!isInserted) {
902                                         rejectedSlotList.add(slot.getSequenceNumber());
903                                         lastTryInserted = false;
904                                 } else {
905                                         lastTryInserted = true;
906                                 }
907                         } else {
908                                 rejectedSlotList.add(slot.getSequenceNumber());
909                                 lastTryInserted = false;
910                         }
911                 }
912
913                 return new ThreeTuple<Boolean, Boolean, Slot[]>(inserted, lastTryInserted, array);
914         }
915
916         /**
917          * Returns false if a resize was needed
918          */
919         private ThreeTuple<Boolean, Integer, Boolean> fillSlot(Slot slot, boolean resize, NewKey newKeyEntry) {
920                 int newSize = 0;
921                 if (liveSlotCount > bufferResizeThreshold) {
922                         resize = true; //Resize is forced
923                 }
924
925                 if (resize) {
926                         newSize = (int) (numberOfSlots * RESIZE_MULTIPLE);
927                         TableStatus status = new TableStatus(slot, newSize);
928                         slot.addEntry(status);
929                 }
930
931                 // Fill with rejected slots first before doing anything else
932                 doRejectedMessages(slot);
933
934                 // Do mandatory rescue of entries
935                 ThreeTuple<Boolean, Boolean, Long> mandatoryRescueReturn = doMandatoryResuce(slot, resize);
936
937                 // Extract working variables
938                 boolean needsResize = mandatoryRescueReturn.getFirst();
939                 boolean seenLiveSlot = mandatoryRescueReturn.getSecond();
940                 long currentRescueSequenceNumber = mandatoryRescueReturn.getThird();
941
942                 if (needsResize && !resize) {
943                         // We need to resize but we are not resizing so return false
944                         return new ThreeTuple<Boolean, Integer, Boolean>(true, null, null);
945                 }
946
947                 boolean inserted = false;
948                 if (newKeyEntry != null) {
949                         newKeyEntry.setSlot(slot);
950                         if (slot.hasSpace(newKeyEntry)) {
951                                 slot.addEntry(newKeyEntry);
952                                 inserted = true;
953                         }
954                 }
955
956                 // Clear the transactions, aborts and commits that were sent previously
957                 transactionPartsSent.clear();
958                 pendingSendArbitrationEntriesToDelete.clear();
959
960                 for (ArbitrationRound round : pendingSendArbitrationRounds) {
961                         boolean isFull = false;
962                         round.generateParts();
963                         List<Entry> parts = round.getParts();
964
965                         // Insert pending arbitration data
966                         for (Entry arbitrationData : parts) {
967
968                                 // If it is an abort then we need to set some information
969                                 if (arbitrationData instanceof Abort) {
970                                         ((Abort)arbitrationData).setSequenceNumber(slot.getSequenceNumber());
971                                 }
972
973                                 if (!slot.hasSpace(arbitrationData)) {
974                                         // No space so cant do anything else with these data entries
975                                         isFull = true;
976                                         break;
977                                 }
978
979                                 // Add to this current slot and add it to entries to delete
980                                 slot.addEntry(arbitrationData);
981                                 pendingSendArbitrationEntriesToDelete.add(arbitrationData);
982                         }
983
984                         if (isFull) {
985                                 break;
986                         }
987                 }
988
989                 // Insert as many transactions as possible while keeping order
990                 for (Transaction transaction : pendingTransactionQueue) {
991
992                         // Set the transaction sequence number if it has yet to be inserted into the block chain
993                         if (!transaction.didSendAPartToServer()) {
994                                 transaction.setSequenceNumber(slot.getSequenceNumber());
995                         }
996
997                         boolean ranOutOfSpace = false;
998
999                         while (true) {
1000                                 TransactionPart part = transaction.getNextPartToSend();
1001
1002                                 if (part == null) {
1003                                         // Ran out of parts to send for this transaction so move on
1004                                         break;
1005                                 }
1006
1007                                 if (slot.hasSpace(part)) {
1008                                         slot.addEntry(part);
1009
1010                                         List<Integer> partsSent = transactionPartsSent.get(transaction);
1011                                         if (partsSent == null) {
1012                                                 partsSent = new ArrayList<Integer>();
1013                                                 transactionPartsSent.put(transaction, partsSent);
1014                                         }
1015
1016                                         partsSent.add(part.getPartNumber());
1017                                         transactionPartsSent.put(transaction, partsSent);
1018
1019                                 } else {
1020                                         ranOutOfSpace = true;
1021                                         break;
1022                                 }
1023                         }
1024
1025                         if (ranOutOfSpace) {
1026                                 break;
1027                         }
1028                 }
1029
1030                 // Fill the remainder of the slot with rescue data
1031                 doOptionalRescue(slot, seenLiveSlot, currentRescueSequenceNumber, resize);
1032
1033                 return new ThreeTuple<Boolean, Integer, Boolean>(false, newSize, inserted);
1034         }
1035
1036         private void doRejectedMessages(Slot s) {
1037                 if (! rejectedSlotList.isEmpty()) {
1038                         /* TODO: We should avoid generating a rejected message entry if
1039                          * there is already a sufficient entry in the queue (e.g.,
1040                          * equalsto value of true and same sequence number).  */
1041
1042                         long old_seqn = rejectedSlotList.firstElement();
1043                         if (rejectedSlotList.size() > REJECTED_THRESHOLD) {
1044                                 long new_seqn = rejectedSlotList.lastElement();
1045                                 RejectedMessage rm = new RejectedMessage(s, localMachineId, old_seqn, new_seqn, false);
1046                                 s.addEntry(rm);
1047                         } else {
1048                                 long prev_seqn = -1;
1049                                 int i = 0;
1050                                 /* Go through list of missing messages */
1051                                 for (; i < rejectedSlotList.size(); i++) {
1052                                         long curr_seqn = rejectedSlotList.get(i);
1053                                         Slot s_msg = buffer.getSlot(curr_seqn);
1054                                         if (s_msg != null)
1055                                                 break;
1056                                         prev_seqn = curr_seqn;
1057                                 }
1058                                 /* Generate rejected message entry for missing messages */
1059                                 if (prev_seqn != -1) {
1060                                         RejectedMessage rm = new RejectedMessage(s, localMachineId, old_seqn, prev_seqn, false);
1061                                         s.addEntry(rm);
1062                                 }
1063                                 /* Generate rejected message entries for present messages */
1064                                 for (; i < rejectedSlotList.size(); i++) {
1065                                         long curr_seqn = rejectedSlotList.get(i);
1066                                         Slot s_msg = buffer.getSlot(curr_seqn);
1067                                         long machineid = s_msg.getMachineID();
1068                                         RejectedMessage rm = new RejectedMessage(s, machineid, curr_seqn, curr_seqn, true);
1069                                         s.addEntry(rm);
1070                                 }
1071                         }
1072                 }
1073         }
1074
1075         private ThreeTuple<Boolean, Boolean, Long> doMandatoryResuce(Slot slot, boolean resize) {
1076                 long newestSequenceNumber = buffer.getNewestSeqNum();
1077                 long oldestSequenceNumber = buffer.getOldestSeqNum();
1078                 if (oldestLiveSlotSequenceNumver < oldestSequenceNumber) {
1079                         oldestLiveSlotSequenceNumver = oldestSequenceNumber;
1080                 }
1081
1082                 long currentSequenceNumber = oldestLiveSlotSequenceNumver;
1083                 boolean seenLiveSlot = false;
1084                 long firstIfFull = newestSequenceNumber + 1 - numberOfSlots;    // smallest seq number in the buffer if it is full
1085                 long threshold = firstIfFull + FREE_SLOTS;      // we want the buffer to be clear of live entries up to this point
1086
1087
1088                 // Mandatory Rescue
1089                 for (; currentSequenceNumber < threshold; currentSequenceNumber++) {
1090                         Slot previousSlot = buffer.getSlot(currentSequenceNumber);
1091                         // Push slot number forward
1092                         if (! seenLiveSlot) {
1093                                 oldestLiveSlotSequenceNumver = currentSequenceNumber;
1094                         }
1095
1096                         if (!previousSlot.isLive()) {
1097                                 continue;
1098                         }
1099
1100                         // We have seen a live slot
1101                         seenLiveSlot = true;
1102
1103                         // Get all the live entries for a slot
1104                         Vector<Entry> liveEntries = previousSlot.getLiveEntries(resize);
1105
1106                         // Iterate over all the live entries and try to rescue them
1107                         for (Entry liveEntry : liveEntries) {
1108                                 if (slot.hasSpace(liveEntry)) {
1109
1110                                         // Enough space to rescue the entry
1111                                         slot.addEntry(liveEntry);
1112                                 } else if (currentSequenceNumber == firstIfFull) {
1113                                         //if there's no space but the entry is about to fall off the queue
1114                                         System.out.println("B"); //?
1115                                         return new ThreeTuple<Boolean, Boolean, Long>(true, seenLiveSlot, currentSequenceNumber);
1116
1117                                 }
1118                         }
1119                 }
1120
1121                 // Did not resize
1122                 return new ThreeTuple<Boolean, Boolean, Long>(false, seenLiveSlot, currentSequenceNumber);
1123         }
1124
1125         private void  doOptionalRescue(Slot s, boolean seenliveslot, long seqn, boolean resize) {
1126                 /* now go through live entries from least to greatest sequence number until
1127                  * either all live slots added, or the slot doesn't have enough room
1128                  * for SKIP_THRESHOLD consecutive entries*/
1129                 int skipcount = 0;
1130                 long newestseqnum = buffer.getNewestSeqNum();
1131                 search:
1132                 for (; seqn <= newestseqnum; seqn++) {
1133                         Slot prevslot = buffer.getSlot(seqn);
1134                         //Push slot number forward
1135                         if (!seenliveslot)
1136                                 oldestLiveSlotSequenceNumver = seqn;
1137
1138                         if (!prevslot.isLive())
1139                                 continue;
1140                         seenliveslot = true;
1141                         Vector<Entry> liveentries = prevslot.getLiveEntries(resize);
1142                         for (Entry liveentry : liveentries) {
1143                                 if (s.hasSpace(liveentry))
1144                                         s.addEntry(liveentry);
1145                                 else {
1146                                         skipcount++;
1147                                         if (skipcount > SKIP_THRESHOLD)
1148                                                 break search;
1149                                 }
1150                         }
1151                 }
1152         }
1153
1154         /**
1155          * Checks for malicious activity and updates the local copy of the block chain.
1156          */
1157         private void validateAndUpdate(Slot[] newSlots, boolean acceptUpdatesToLocal) {
1158
1159                 // The cloud communication layer has checked slot HMACs already before decoding
1160                 if (newSlots.length == 0) {
1161                         return;
1162                 }
1163
1164                 // Reset the table status declared sizes
1165                 smallestTableStatusSeen = -1;
1166                 largestTableStatusSeen = -1;
1167
1168
1169                 // Make sure all slots are newer than the last largest slot this client has seen
1170                 long firstSeqNum = newSlots[0].getSequenceNumber();
1171                 if (firstSeqNum <= sequenceNumber) {
1172                         throw new Error("Server Error: Sent older slots!");
1173                 }
1174
1175                 // Create an object that can access both new slots and slots in our local chain
1176                 // without committing slots to our local chain
1177                 SlotIndexer indexer = new SlotIndexer(newSlots, buffer);
1178
1179                 // Check that the HMAC chain is not broken
1180                 checkHMACChain(indexer, newSlots);
1181
1182                 // Set to keep track of messages from clients
1183                 HashSet<Long> machineSet = new HashSet<Long>(lastMessageTable.keySet());
1184
1185                 // Process each slots data
1186                 for (Slot slot : newSlots) {
1187                         processSlot(indexer, slot, acceptUpdatesToLocal, machineSet);
1188                 }
1189
1190                 // If there is a gap, check to see if the server sent us everything.
1191                 if (firstSeqNum != (sequenceNumber + 1)) {
1192
1193                         // Check the size of the slots that were sent down by the server.
1194                         // Can only check the size if there was a gap
1195                         checkNumSlots(newSlots.length);
1196
1197                         // Since there was a gap every machine must have pushed a slot or must have
1198                         // a last message message.  If not then the server is hiding slots
1199                         if (!machineSet.isEmpty()) {
1200                                 throw new Error("Missing record for machines: " + machineSet);
1201                         }
1202                 }
1203
1204                 // Update the size of our local block chain.
1205                 commitNewMaxSize();
1206
1207                 // Commit new to slots to the local block chain.
1208                 for (Slot slot : newSlots) {
1209
1210                         // Insert this slot into our local block chain copy.
1211                         buffer.putSlot(slot);
1212
1213                         // Keep track of how many slots are currently live (have live data in them).
1214                         liveSlotCount++;
1215                 }
1216
1217                 // Get the sequence number of the latest slot in the system
1218                 sequenceNumber = newSlots[newSlots.length - 1].getSequenceNumber();
1219
1220                 updateLiveStateFromServer();
1221
1222                 // No Need to remember after we pulled from the server
1223                 offlineTransactionsCommittedAndAtServer.clear();
1224
1225                 // This is invalidated now
1226                 hadPartialSendToServer = false;
1227         }
1228
1229         private void updateLiveStateFromServer() {
1230                 // Process the new transaction parts
1231                 processNewTransactionParts();
1232
1233                 // Do arbitration on new transactions that were received
1234                 arbitrateFromServer();
1235
1236                 // Update all the committed keys
1237                 boolean didCommitOrSpeculate = updateCommittedTable();
1238
1239                 // Delete the transactions that are now dead
1240                 updateLiveTransactionsAndStatus();
1241
1242                 // Do speculations
1243                 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1244                 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1245         }
1246
1247         private void updateLiveStateFromLocal() {
1248                 // Update all the committed keys
1249                 boolean didCommitOrSpeculate = updateCommittedTable();
1250
1251                 // Delete the transactions that are now dead
1252                 updateLiveTransactionsAndStatus();
1253
1254                 // Do speculations
1255                 didCommitOrSpeculate |= updateSpeculativeTable(didCommitOrSpeculate);
1256                 updatePendingTransactionSpeculativeTable(didCommitOrSpeculate);
1257         }
1258
1259         /**
1260          * Check the size of the block chain to make sure there are enough slots sent back by the server.
1261          * This is only called when we have a gap between the slots that we have locally and the slots
1262          * sent by the server therefore in the slots sent by the server there will be at least 1 Table
1263          * status message
1264          */
1265         private void checkNumSlots(int numberOfSlots) {
1266
1267                 // We only have 1 size so we must have this many slots
1268                 if (largestTableStatusSeen == smallestTableStatusSeen) {
1269                         if (numberOfSlots != smallestTableStatusSeen) {
1270                                 throw new Error("Server Error: Server did not send all slots.  Expected: " + smallestTableStatusSeen + " Received:" + numberOfSlots);
1271                         }
1272                 } else {
1273                         // We have more than 1
1274                         if (numberOfSlots < smallestTableStatusSeen) {
1275                                 throw new Error("Server Error: Server did not send all slots.  Expected at least: " + smallestTableStatusSeen + " Received:" + numberOfSlots);
1276                         }
1277                 }
1278         }
1279
1280         /**
1281          * Update the size of of the local buffer if it is needed.
1282          */
1283         private void commitNewMaxSize() {
1284
1285                 int currMaxSize = 0;
1286
1287                 if (largestTableStatusSeen == -1) {
1288                         // No table status seen so the current max size does not change
1289                         currMaxSize = numberOfSlots;
1290                 } else {
1291                         currMaxSize = largestTableStatusSeen;
1292                 }
1293
1294                 // Resize the local slot buffer
1295                 if (numberOfSlots != currMaxSize) {
1296                         buffer.resize(currMaxSize);
1297                 }
1298
1299                 // Change the number of local slots to the new size
1300                 numberOfSlots = currMaxSize;
1301
1302                 // Recalculate the resize threshold since the size of the local buffer has changed
1303                 setResizeThreshold();
1304         }
1305
1306         /**
1307          * Process the new transaction parts from this latest round of slots received from the server
1308          */
1309         private void processNewTransactionParts() {
1310
1311                 if (newTransactionParts.size() == 0) {
1312                         // Nothing new to process
1313                         return;
1314                 }
1315
1316                 // Iterate through all the machine Ids that we received new parts for
1317                 for (Long machineId : newTransactionParts.keySet()) {
1318                         Map<Pair<Long, Integer>, TransactionPart> parts = newTransactionParts.get(machineId);
1319
1320                         // Iterate through all the parts for that machine Id
1321                         for (Pair<Long, Integer> partId : parts.keySet()) {
1322                                 TransactionPart part = parts.get(partId);
1323
1324                                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(part.getArbitratorId());
1325                                 if ((lastTransactionNumber != null) && (lastTransactionNumber >= part.getSequenceNumber())) {
1326                                         // Set dead the transaction part
1327                                         part.setDead();
1328                                         continue;
1329                                 }
1330
1331                                 // Get the transaction object for that sequence number
1332                                 Transaction transaction = liveTransactionBySequenceNumberTable.get(part.getSequenceNumber());
1333
1334                                 if (transaction == null) {
1335                                         // This is a new transaction that we dont have so make a new one
1336                                         transaction = new Transaction();
1337
1338                                         // Insert this new transaction into the live tables
1339                                         liveTransactionBySequenceNumberTable.put(part.getSequenceNumber(), transaction);
1340                                         liveTransactionByTransactionIdTable.put(part.getTransactionId(), transaction);
1341                                 }
1342
1343                                 // Add that part to the transaction
1344                                 transaction.addPartDecode(part);
1345                         }
1346                 }
1347
1348                 // Clear all the new transaction parts in preparation for the next time the server sends slots
1349                 newTransactionParts.clear();
1350         }
1351
1352         private void arbitrateFromServer() {
1353
1354                 if (liveTransactionBySequenceNumberTable.size() == 0) {
1355                         // Nothing to arbitrate on so move on
1356                         return;
1357                 }
1358
1359                 // Get the transaction sequence numbers and sort from oldest to newest
1360                 List<Long> transactionSequenceNumbers = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1361                 Collections.sort(transactionSequenceNumbers);
1362
1363                 // Collection of key value pairs that are
1364                 Map<IoTString, KeyValue> speculativeTableTmp = new HashMap<IoTString, KeyValue>();
1365
1366                 // The last transaction arbitrated on
1367                 long lastTransactionCommitted = -1;
1368                 Set<Abort> generatedAborts = new HashSet<Abort>();
1369
1370                 for (Long transactionSequenceNumber : transactionSequenceNumbers) {
1371                         Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1372
1373                         // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1374                         if (transaction.getArbitrator() != localMachineId) {
1375                                 continue;
1376                         }
1377
1378                         if (offlineTransactionsCommittedAndAtServer.contains(transaction.getId())) {
1379                                 // We have seen this already locally so dont commit again
1380                                 continue;
1381                         }
1382
1383
1384                         if (!transaction.isComplete()) {
1385                                 // Will arbitrate in incorrect order if we continue so just break
1386                                 // Most likely this
1387                                 break;
1388                         }
1389
1390                         // update the largest transaction seen by arbitrator from server
1391                         if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) == null) {
1392                                 lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1393                         } else {
1394                                 Long lastTransactionSeenFromMachine = lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId());
1395                                 if (transaction.getClientLocalSequenceNumber() > lastTransactionSeenFromMachine) {
1396                                         lastTransactionSeenFromMachineFromServer.put(transaction.getMachineId(), transaction.getClientLocalSequenceNumber());
1397                                 }
1398                         }
1399
1400                         if (transaction.evaluateGuard(committedKeyValueTable, speculativeTableTmp, null)) {
1401                                 // Guard evaluated as true
1402
1403                                 // Update the local changes so we can make the commit
1404                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1405                                         speculativeTableTmp.put(kv.getKey(), kv);
1406                                 }
1407
1408                                 // Update what the last transaction committed was for use in batch commit
1409                                 lastTransactionCommitted = transaction.getSequenceNumber();
1410
1411                         } else {
1412                                 // Guard evaluated was false so create abort
1413
1414                                 // Create the abort
1415                                 Abort newAbort = new Abort(null,
1416                                                            transaction.getClientLocalSequenceNumber(),
1417                                                            transaction.getSequenceNumber(),
1418                                                            transaction.getMachineId(),
1419                                                            transaction.getArbitrator(),
1420                                                            localArbitrationSequenceNumber);
1421                                 localArbitrationSequenceNumber++;
1422
1423                                 generatedAborts.add(newAbort);
1424
1425                                 // Insert the abort so we can process
1426                                 processEntry(newAbort);
1427                         }
1428                 }
1429
1430                 Commit newCommit = null;
1431
1432                 // If there is something to commit
1433                 if (speculativeTableTmp.size() != 0) {
1434
1435                         // Create the commit and increment the commit sequence number
1436                         newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, lastTransactionCommitted);
1437                         localArbitrationSequenceNumber++;
1438
1439                         // Add all the new keys to the commit
1440                         for (KeyValue kv : speculativeTableTmp.values()) {
1441                                 newCommit.addKV(kv);
1442                         }
1443
1444                         // create the commit parts
1445                         newCommit.createCommitParts();
1446
1447                         // Append all the commit parts to the end of the pending queue waiting for sending to the server
1448
1449                         // Insert the commit so we can process it
1450                         for (CommitPart commitPart : newCommit.getParts().values()) {
1451                                 processEntry(commitPart);
1452                         }
1453                 }
1454
1455
1456                 if ((newCommit != null) || (generatedAborts.size() > 0)) {
1457                         ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, generatedAborts);
1458                         pendingSendArbitrationRounds.add(arbitrationRound);
1459
1460                         if (compactArbitrationData()) {
1461                                 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1462                                 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1463                                         processEntry(commitPart);
1464                                 }
1465                         }
1466                 }
1467         }
1468
1469         private Pair<Boolean, Boolean> arbitrateOnLocalTransaction(Transaction transaction) {
1470
1471                 // Check if this machine arbitrates for this transaction if not then we cant arbitrate this transaction
1472                 if (transaction.getArbitrator() != localMachineId) {
1473                         return new Pair<Boolean, Boolean>(false, false);
1474                 }
1475
1476                 if (!transaction.isComplete()) {
1477                         // Will arbitrate in incorrect order if we continue so just break
1478                         // Most likely this
1479                         return new Pair<Boolean, Boolean>(false, false);
1480                 }
1481
1482                 if (transaction.getMachineId() != localMachineId) {
1483                         // dont do this check for local transactions
1484                         if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) != null) {
1485                                 if (lastTransactionSeenFromMachineFromServer.get(transaction.getMachineId()) > transaction.getClientLocalSequenceNumber()) {
1486                                         // We've have already seen this from the server
1487
1488                                         System.out.println("Local Arbitrate Seen Already from server, rejected");
1489                                         return new Pair<Boolean, Boolean>(false, false);
1490                                 }
1491                         }
1492                 }
1493
1494                 if (transaction.evaluateGuard(committedKeyValueTable, null, null)) {
1495                         // Guard evaluated as true
1496
1497                         // Create the commit and increment the commit sequence number
1498                         Commit newCommit = new Commit(localArbitrationSequenceNumber, localMachineId, -1);
1499                         localArbitrationSequenceNumber++;
1500
1501                         // Update the local changes so we can make the commit
1502                         for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1503                                 newCommit.addKV(kv);
1504                         }
1505
1506                         // create the commit parts
1507                         newCommit.createCommitParts();
1508
1509                         // Append all the commit parts to the end of the pending queue waiting for sending to the server
1510                         ArbitrationRound arbitrationRound = new ArbitrationRound(newCommit, new HashSet<Abort>());
1511                         pendingSendArbitrationRounds.add(arbitrationRound);
1512
1513                         if (compactArbitrationData()) {
1514                                 ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1515                                 for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1516                                         processEntry(commitPart);
1517                                 }
1518                         } else {
1519                                 // Insert the commit so we can process it
1520                                 for (CommitPart commitPart : newCommit.getParts().values()) {
1521                                         processEntry(commitPart);
1522                                 }
1523                         }
1524
1525                         if (transaction.getMachineId() == localMachineId) {
1526                                 TransactionStatus status = transaction.getTransactionStatus();
1527                                 if (status != null) {
1528                                         status.setStatus(TransactionStatus.StatusCommitted);
1529                                 }
1530                         }
1531
1532                         updateLiveStateFromLocal();
1533                         return new Pair<Boolean, Boolean>(true, true);
1534                 } else {
1535
1536                         if (transaction.getMachineId() == localMachineId) {
1537                                 // For locally created messages update the status
1538
1539                                 // Guard evaluated was false so create abort
1540                                 TransactionStatus status = transaction.getTransactionStatus();
1541                                 if (status != null) {
1542                                         status.setStatus(TransactionStatus.StatusAborted);
1543                                 }
1544                         } else {
1545
1546                                 Set addAbortSet = new HashSet<Abort>();
1547
1548
1549                                 // Create the abort
1550                                 Abort newAbort = new Abort(null,
1551                                                            transaction.getClientLocalSequenceNumber(),
1552                                                            -1,
1553                                                            transaction.getMachineId(),
1554                                                            transaction.getArbitrator(),
1555                                                            localArbitrationSequenceNumber);
1556                                 localArbitrationSequenceNumber++;
1557
1558                                 addAbortSet.add(newAbort);
1559
1560
1561                                 // Append all the commit parts to the end of the pending queue waiting for sending to the server
1562                                 ArbitrationRound arbitrationRound = new ArbitrationRound(null, addAbortSet);
1563                                 pendingSendArbitrationRounds.add(arbitrationRound);
1564
1565                                 if (compactArbitrationData()) {
1566                                         ArbitrationRound newArbitrationRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1567                                         for (CommitPart commitPart : newArbitrationRound.getCommit().getParts().values()) {
1568                                                 processEntry(commitPart);
1569                                         }
1570                                 }
1571                         }
1572
1573                         updateLiveStateFromLocal();
1574                         return new Pair<Boolean, Boolean>(true, false);
1575                 }
1576         }
1577
1578         /**
1579          * Compacts the arbitration data my merging commits and aggregating aborts so that a single large push of commits can be done instead of many small updates
1580          */
1581         private boolean compactArbitrationData() {
1582
1583
1584                 if (pendingSendArbitrationRounds.size() < 2) {
1585                         // Nothing to compact so do nothing
1586                         return false;
1587                 }
1588
1589                 ArbitrationRound lastRound = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - 1);
1590                 if (lastRound.didSendPart()) {
1591                         return false;
1592                 }
1593
1594                 boolean hadCommit = (lastRound.getCommit() == null);
1595                 boolean gotNewCommit = false;
1596
1597                 int numberToDelete = 1;
1598                 while (numberToDelete < pendingSendArbitrationRounds.size()) {
1599                         ArbitrationRound round = pendingSendArbitrationRounds.get(pendingSendArbitrationRounds.size() - numberToDelete - 1);
1600
1601                         if (round.isFull() || round.didSendPart()) {
1602                                 // Stop since there is a part that cannot be compacted and we need to compact in order
1603                                 break;
1604                         }
1605
1606                         if (round.getCommit() == null) {
1607
1608                                 // Try compacting aborts only
1609                                 int newSize = round.getCurrentSize() + lastRound.getAbortsCount();
1610                                 if (newSize > ArbitrationRound.MAX_PARTS) {
1611                                         // Cant compact since it would be too large
1612                                         break;
1613                                 }
1614                                 lastRound.addAborts(round.getAborts());
1615                         } else {
1616
1617                                 // Create a new larger commit
1618                                 Commit newCommit = Commit.merge(lastRound.getCommit(), round.getCommit(), localArbitrationSequenceNumber);
1619                                 localArbitrationSequenceNumber++;
1620
1621                                 // Create the commit parts so that we can count them
1622                                 newCommit.createCommitParts();
1623
1624                                 // Calculate the new size of the parts
1625                                 int newSize = newCommit.getNumberOfParts();
1626                                 newSize += lastRound.getAbortsCount();
1627                                 newSize += round.getAbortsCount();
1628
1629                                 if (newSize > ArbitrationRound.MAX_PARTS) {
1630                                         // Cant compact since it would be too large
1631                                         break;
1632                                 }
1633
1634                                 // Set the new compacted part
1635                                 lastRound.setCommit(newCommit);
1636                                 lastRound.addAborts(round.getAborts());
1637                                 gotNewCommit = true;
1638                         }
1639
1640                         numberToDelete++;
1641                 }
1642
1643                 if (numberToDelete != 1) {
1644                         // If there is a compaction
1645
1646                         // Delete the previous pieces that are now in the new compacted piece
1647                         if (numberToDelete == pendingSendArbitrationRounds.size()) {
1648                                 pendingSendArbitrationRounds.clear();
1649                         } else {
1650                                 for (int i = 0; i < numberToDelete; i++) {
1651                                         pendingSendArbitrationRounds.remove(pendingSendArbitrationRounds.size() - 1);
1652                                 }
1653                         }
1654
1655                         // Add the new compacted into the pending to send list
1656                         pendingSendArbitrationRounds.add(lastRound);
1657
1658                         // Should reinsert into the commit processor
1659                         if (hadCommit && gotNewCommit) {
1660                                 return true;
1661                         }
1662                 }
1663
1664                 return false;
1665         }
1666
1667         /**
1668          * Update all the commits and the committed tables, sets dead the dead transactions
1669          */
1670         private boolean updateCommittedTable() {
1671
1672                 if (newCommitParts.size() == 0) {
1673                         // Nothing new to process
1674                         return false;
1675                 }
1676
1677                 // Iterate through all the machine Ids that we received new parts for
1678                 for (Long machineId : newCommitParts.keySet()) {
1679                         Map<Pair<Long, Integer>, CommitPart> parts = newCommitParts.get(machineId);
1680
1681                         // Iterate through all the parts for that machine Id
1682                         for (Pair<Long, Integer> partId : parts.keySet()) {
1683                                 CommitPart part = parts.get(partId);
1684
1685                                 // Get the transaction object for that sequence number
1686                                 Map<Long, Commit> commitForClientTable = liveCommitsTable.get(part.getMachineId());
1687
1688                                 if (commitForClientTable == null) {
1689                                         // This is the first commit from this device
1690                                         commitForClientTable = new HashMap<Long, Commit>();
1691                                         liveCommitsTable.put(part.getMachineId(), commitForClientTable);
1692                                 }
1693
1694                                 Commit commit = commitForClientTable.get(part.getSequenceNumber());
1695
1696                                 if (commit == null) {
1697                                         // This is a new commit that we dont have so make a new one
1698                                         commit = new Commit();
1699
1700                                         // Insert this new commit into the live tables
1701                                         commitForClientTable.put(part.getSequenceNumber(), commit);
1702                                 }
1703
1704                                 // Add that part to the commit
1705                                 commit.addPartDecode(part);
1706                         }
1707                 }
1708
1709                 // Clear all the new commits parts in preparation for the next time the server sends slots
1710                 newCommitParts.clear();
1711
1712                 // If we process a new commit keep track of it for future use
1713                 boolean didProcessANewCommit = false;
1714
1715                 // Process the commits one by one
1716                 for (Long arbitratorId : liveCommitsTable.keySet()) {
1717
1718                         // Get all the commits for a specific arbitrator
1719                         Map<Long, Commit> commitForClientTable = liveCommitsTable.get(arbitratorId);
1720
1721                         // Sort the commits in order
1722                         List<Long> commitSequenceNumbers = new ArrayList<Long>(commitForClientTable.keySet());
1723                         Collections.sort(commitSequenceNumbers);
1724
1725                         // Go through each new commit one by one
1726                         for (int i = 0; i < commitSequenceNumbers.size(); i++) {
1727                                 Long commitSequenceNumber = commitSequenceNumbers.get(i);
1728                                 Commit commit = commitForClientTable.get(commitSequenceNumber);
1729
1730                                 // Special processing if a commit is not complete
1731                                 if (!commit.isComplete()) {
1732                                         if (i == (commitSequenceNumbers.size() - 1)) {
1733                                                 // If there is an incomplete commit and this commit is the latest one seen then this commit cannot be processed and there are no other commits
1734                                                 break;
1735                                         } else {
1736                                                 // This is a commit that was already dead but parts of it are still in the block chain (not flushed out yet).
1737                                                 // Delete it and move on
1738                                                 commit.setDead();
1739                                                 commitForClientTable.remove(commit.getSequenceNumber());
1740                                                 continue;
1741                                         }
1742                                 }
1743
1744                                 // Get the last commit seen from this arbitrator
1745                                 long lastCommitSeenSequenceNumber = -1;
1746                                 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
1747                                         lastCommitSeenSequenceNumber = lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId());
1748                                 }
1749
1750                                 // Update the last arbitration data that we have seen so far
1751                                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId()) != null) {
1752
1753                                         long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(commit.getMachineId());
1754                                         if (commit.getSequenceNumber() > lastArbitrationSequenceNumber) {
1755                                                 // Is larger
1756                                                 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
1757                                         }
1758                                 } else {
1759                                         // Never seen any data from this arbitrator so record the first one
1760                                         lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(commit.getMachineId(), commit.getSequenceNumber());
1761                                 }
1762
1763                                 // We have already seen this commit before so need to do the full processing on this commit
1764                                 if (commit.getSequenceNumber() <= lastCommitSeenSequenceNumber) {
1765
1766                                         // Update the last transaction that was updated if we can
1767                                         if (commit.getTransactionSequenceNumber() != -1) {
1768                                                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
1769
1770                                                 // Update the last transaction sequence number that the arbitrator arbitrated on
1771                                                 if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
1772                                                         lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
1773                                                 }
1774                                         }
1775
1776                                         continue;
1777                                 }
1778
1779                                 // If we got here then this is a brand new commit and needs full processing
1780
1781                                 // Get what commits should be edited, these are the commits that have live values for their keys
1782                                 Set<Commit> commitsToEdit = new HashSet<Commit>();
1783                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1784                                         commitsToEdit.add(liveCommitsByKeyTable.get(kv.getKey()));
1785                                 }
1786                                 commitsToEdit.remove(null); // remove null since it could be in this set
1787
1788                                 // Update each previous commit that needs to be updated
1789                                 for (Commit previousCommit : commitsToEdit) {
1790
1791                                         // Only bother with live commits (TODO: Maybe remove this check)
1792                                         if (previousCommit.isLive()) {
1793
1794                                                 // Update which keys in the old commits are still live
1795                                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1796                                                         previousCommit.invalidateKey(kv.getKey());
1797                                                 }
1798
1799                                                 // if the commit is now dead then remove it
1800                                                 if (!previousCommit.isLive()) {
1801                                                         commitForClientTable.remove(previousCommit);
1802                                                 }
1803                                         }
1804                                 }
1805
1806                                 // Update the last seen sequence number from this arbitrator
1807                                 if (lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId()) != null) {
1808                                         if (commit.getSequenceNumber() > lastCommitSeenSequenceNumberByArbitratorTable.get(commit.getMachineId())) {
1809                                                 lastCommitSeenSequenceNumberByArbitratorTable.put(commit.getMachineId(), commit.getSequenceNumber());
1810                                         }
1811                                 }
1812
1813
1814
1815                                 // Update the last transaction that was updated if we can
1816                                 if (commit.getTransactionSequenceNumber() != -1) {
1817                                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(commit.getMachineId());
1818
1819                                         // Update the last transaction sequence number that the arbitrator arbitrated on
1820                                         if ((lastTransactionNumber == null) || (lastTransactionNumber < commit.getTransactionSequenceNumber())) {
1821                                                 lastArbitratedTransactionNumberByArbitratorTable.put(commit.getMachineId(), commit.getTransactionSequenceNumber());
1822                                         }
1823                                 }
1824
1825                                 // We processed a new commit that we havent seen before
1826                                 didProcessANewCommit = true;
1827
1828
1829
1830                                 System.out.println("============");
1831                                 // Update the committed table of keys and which commit is using which key
1832                                 for (KeyValue kv : commit.getKeyValueUpdateSet()) {
1833                                         System.out.println("Committing:  " + kv);
1834                                         committedKeyValueTable.put(kv.getKey(), kv);
1835                                         liveCommitsByKeyTable.put(kv.getKey(), commit);
1836                                 }
1837                                 System.out.println("--------------");
1838                                 System.out.println();
1839                         }
1840                 }
1841
1842                 return didProcessANewCommit;
1843         }
1844
1845         /**
1846          * Create the speculative table from transactions that are still live and have come from the cloud
1847          */
1848         private boolean updateSpeculativeTable(boolean didProcessNewCommits) {
1849                 if (liveTransactionBySequenceNumberTable.keySet().size() == 0) {
1850                         // There is nothing to speculate on
1851                         return false;
1852                 }
1853
1854                 // Create a list of the transaction sequence numbers and sort them from oldest to newest
1855                 List<Long> transactionSequenceNumbersSorted = new ArrayList<Long>(liveTransactionBySequenceNumberTable.keySet());
1856                 Collections.sort(transactionSequenceNumbersSorted);
1857
1858                 boolean hasGapInTransactionSequenceNumbers = transactionSequenceNumbersSorted.get(0) != oldestTransactionSequenceNumberSpeculatedOn;
1859
1860
1861                 if (hasGapInTransactionSequenceNumbers || didProcessNewCommits) {
1862                         // If there is a gap in the transaction sequence numbers then there was a commit or an abort of a transaction
1863                         // OR there was a new commit (Could be from offline commit) so a redo the speculation from scratch
1864
1865                         // Start from scratch
1866                         speculatedKeyValueTable.clear();
1867                         lastTransactionSequenceNumberSpeculatedOn = -1;
1868                         oldestTransactionSequenceNumberSpeculatedOn = -1;
1869
1870                 }
1871
1872                 // Remember the front of the transaction list
1873                 oldestTransactionSequenceNumberSpeculatedOn = transactionSequenceNumbersSorted.get(0);
1874
1875                 // Find where to start arbitration from
1876                 int startIndex = transactionSequenceNumbersSorted.indexOf(lastTransactionSequenceNumberSpeculatedOn) + 1;
1877
1878                 if (startIndex >= transactionSequenceNumbersSorted.size()) {
1879                         // Make sure we are not out of bounds
1880                         return false; // did not speculate
1881                 }
1882
1883                 Set<Long> incompleteTransactionArbitrator = new HashSet<Long>();
1884                 boolean didSkip = true;
1885
1886                 for (int i = startIndex; i < transactionSequenceNumbersSorted.size(); i++) {
1887                         long transactionSequenceNumber = transactionSequenceNumbersSorted.get(i);
1888                         Transaction transaction = liveTransactionBySequenceNumberTable.get(transactionSequenceNumber);
1889
1890                         if (!transaction.isComplete()) {
1891                                 // If there is an incomplete transaction then there is nothing we can do
1892                                 // add this transactions arbitrator to the list of arbitrators we should ignore
1893                                 incompleteTransactionArbitrator.add(transaction.getArbitrator());
1894                                 didSkip = true;
1895                                 continue;
1896                         }
1897
1898                         if (incompleteTransactionArbitrator.contains(transaction.getArbitrator())) {
1899                                 continue;
1900                         }
1901
1902                         lastTransactionSequenceNumberSpeculatedOn = transactionSequenceNumber;
1903
1904                         if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, null)) {
1905                                 // Guard evaluated to true so update the speculative table
1906                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1907                                         speculatedKeyValueTable.put(kv.getKey(), kv);
1908                                 }
1909                         }
1910                 }
1911
1912                 if (didSkip) {
1913                         // Since there was a skip we need to redo the speculation next time around
1914                         lastTransactionSequenceNumberSpeculatedOn = -1;
1915                         oldestTransactionSequenceNumberSpeculatedOn = -1;
1916                 }
1917
1918                 // We did some speculation
1919                 return true;
1920         }
1921
1922         /**
1923          * Create the pending transaction speculative table from transactions that are still in the pending transaction buffer
1924          */
1925         private void updatePendingTransactionSpeculativeTable(boolean didProcessNewCommitsOrSpeculate) {
1926                 if (pendingTransactionQueue.size() == 0) {
1927                         // There is nothing to speculate on
1928                         return;
1929                 }
1930
1931
1932                 if (didProcessNewCommitsOrSpeculate || (firstPendingTransaction != pendingTransactionQueue.get(0))) {
1933                         // need to reset on the pending speculation
1934                         lastPendingTransactionSpeculatedOn = null;
1935                         firstPendingTransaction = pendingTransactionQueue.get(0);
1936                         pendingTransactionSpeculatedKeyValueTable.clear();
1937                 }
1938
1939                 // Find where to start arbitration from
1940                 int startIndex = pendingTransactionQueue.indexOf(firstPendingTransaction) + 1;
1941
1942                 if (startIndex >= pendingTransactionQueue.size()) {
1943                         // Make sure we are not out of bounds
1944                         return;
1945                 }
1946
1947                 for (int i = startIndex; i < pendingTransactionQueue.size(); i++) {
1948                         Transaction transaction = pendingTransactionQueue.get(i);
1949
1950                         lastPendingTransactionSpeculatedOn = transaction;
1951
1952                         if (transaction.evaluateGuard(committedKeyValueTable, speculatedKeyValueTable, pendingTransactionSpeculatedKeyValueTable)) {
1953                                 // Guard evaluated to true so update the speculative table
1954                                 for (KeyValue kv : transaction.getKeyValueUpdateSet()) {
1955                                         pendingTransactionSpeculatedKeyValueTable.put(kv.getKey(), kv);
1956                                 }
1957                         }
1958                 }
1959         }
1960
1961         /**
1962          * Set dead and remove from the live transaction tables the transactions that are dead
1963          */
1964         private void updateLiveTransactionsAndStatus() {
1965
1966                 // Go through each of the transactions
1967                 for (Iterator<Map.Entry<Long, Transaction>> iter = liveTransactionBySequenceNumberTable.entrySet().iterator(); iter.hasNext();) {
1968                         Transaction transaction = iter.next().getValue();
1969
1970                         // Check if the transaction is dead
1971                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(transaction.getArbitrator());
1972                         if ((lastTransactionNumber != null) && (lastTransactionNumber >= transaction.getSequenceNumber())) {
1973
1974                                 // Set dead the transaction
1975                                 transaction.setDead();
1976
1977                                 // Remove the transaction from the live table
1978                                 iter.remove();
1979                                 liveTransactionByTransactionIdTable.remove(transaction.getId());
1980                         }
1981                 }
1982
1983                 // Go through each of the transactions
1984                 for (Iterator<Map.Entry<Long, TransactionStatus>> iter = outstandingTransactionStatus.entrySet().iterator(); iter.hasNext();) {
1985                         TransactionStatus status = iter.next().getValue();
1986
1987                         // Check if the transaction is dead
1988                         Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(status.getTransactionArbitrator());
1989                         if ((lastTransactionNumber != null) && (lastTransactionNumber >= status.getTransactionSequenceNumber())) {
1990
1991                                 // Set committed
1992                                 status.setStatus(TransactionStatus.StatusCommitted);
1993
1994                                 // Remove
1995                                 iter.remove();
1996                         }
1997                 }
1998         }
1999
2000         /**
2001          * Process this slot, entry by entry.  Also update the latest message sent by slot
2002          */
2003         private void processSlot(SlotIndexer indexer, Slot slot, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2004
2005                 // Update the last message seen
2006                 updateLastMessage(slot.getMachineID(), slot.getSequenceNumber(), slot, acceptUpdatesToLocal, machineSet);
2007
2008                 // Process each entry in the slot
2009                 for (Entry entry : slot.getEntries()) {
2010                         switch (entry.getType()) {
2011
2012                         case Entry.TypeCommitPart:
2013                                 processEntry((CommitPart)entry);
2014                                 break;
2015
2016                         case Entry.TypeAbort:
2017                                 processEntry((Abort)entry);
2018                                 break;
2019
2020                         case Entry.TypeTransactionPart:
2021                                 processEntry((TransactionPart)entry);
2022                                 break;
2023
2024                         case Entry.TypeNewKey:
2025                                 processEntry((NewKey)entry);
2026                                 break;
2027
2028                         case Entry.TypeLastMessage:
2029                                 processEntry((LastMessage)entry, machineSet);
2030                                 break;
2031
2032                         case Entry.TypeRejectedMessage:
2033                                 processEntry((RejectedMessage)entry, indexer);
2034                                 break;
2035
2036                         case Entry.TypeTableStatus:
2037                                 processEntry((TableStatus)entry);
2038                                 break;
2039
2040                         default:
2041                                 throw new Error("Unrecognized type: " + entry.getType());
2042                         }
2043                 }
2044         }
2045
2046         /**
2047          * Update the last message that was sent for a machine Id
2048          */
2049         private void processEntry(LastMessage entry, HashSet<Long> machineSet) {
2050                 // Update what the last message received by a machine was
2051                 updateLastMessage(entry.getMachineID(), entry.getSequenceNumber(), entry, false, machineSet);
2052         }
2053
2054         /**
2055          * Add the new key to the arbitrators table and update the set of live new keys (in case of a rescued new key message)
2056          */
2057         private void processEntry(NewKey entry) {
2058
2059                 // Update the arbitrator table with the new key information
2060                 arbitratorTable.put(entry.getKey(), entry.getMachineID());
2061
2062                 // Update what the latest live new key is
2063                 NewKey oldNewKey = liveNewKeyTable.put(entry.getKey(), entry);
2064                 if (oldNewKey != null) {
2065                         // Delete the old new key messages
2066                         oldNewKey.setDead();
2067                 }
2068         }
2069
2070         /**
2071          * Process new table status entries and set dead the old ones as new ones come in.
2072          * keeps track of the largest and smallest table status seen in this current round
2073          * of updating the local copy of the block chain
2074          */
2075         private void processEntry(TableStatus entry) {
2076                 int newNumSlots = entry.getMaxSlots();
2077
2078                 if (liveTableStatus != null) {
2079                         // We have a larger table status so the old table status is no longer alive
2080                         liveTableStatus.setDead();
2081                 }
2082
2083                 // Make this new table status the latest alive table status
2084                 liveTableStatus = entry;
2085
2086                 if ((smallestTableStatusSeen == -1) || (newNumSlots < smallestTableStatusSeen)) {
2087                         smallestTableStatusSeen = newNumSlots;
2088                 }
2089
2090                 if ((largestTableStatusSeen == -1) || (newNumSlots > largestTableStatusSeen)) {
2091                         largestTableStatusSeen = newNumSlots;
2092                 }
2093         }
2094
2095         /**
2096          * Check old messages to see if there is a block chain violation. Also
2097          */
2098         private void processEntry(RejectedMessage entry, SlotIndexer indexer) {
2099                 long oldSeqNum = entry.getOldSeqNum();
2100                 long newSeqNum = entry.getNewSeqNum();
2101                 boolean isequal = entry.getEqual();
2102                 long machineId = entry.getMachineID();
2103
2104
2105                 // Check if we have messages that were supposed to be rejected in our local block chain
2106                 for (long seqNum = oldSeqNum; seqNum <= newSeqNum; seqNum++) {
2107
2108                         // Get the slot
2109                         Slot slot = indexer.getSlot(seqNum);
2110
2111                         if (slot != null) {
2112                                 // If we have this slot make sure that it was not supposed to be a rejected slot
2113
2114                                 long slotMachineId = slot.getMachineID();
2115                                 if (isequal != (slotMachineId == machineId)) {
2116                                         throw new Error("Server Error: Trying to insert rejected message for slot " + seqNum);
2117                                 }
2118                         }
2119                 }
2120
2121
2122                 // Create a list of clients to watch until they see this rejected message entry.
2123                 HashSet<Long> deviceWatchSet = new HashSet<Long>();
2124                 for (Map.Entry<Long, Pair<Long, Liveness>> lastMessageEntry : lastMessageTable.entrySet()) {
2125
2126                         // Machine ID for the last message entry
2127                         long lastMessageEntryMachineId = lastMessageEntry.getKey();
2128
2129                         // We've seen it, don't need to continue to watch.  Our next
2130                         // message will implicitly acknowledge it.
2131                         if (lastMessageEntryMachineId == localMachineId) {
2132                                 continue;
2133                         }
2134
2135                         Pair<Long, Liveness> lastMessageValue = lastMessageEntry.getValue();
2136                         long entrySequenceNumber = lastMessageValue.getFirst();
2137
2138                         if (entrySequenceNumber < newSeqNum) {
2139
2140                                 // Add this rejected message to the set of messages that this machine ID did not see yet
2141                                 addWatchList(lastMessageEntryMachineId, entry);
2142
2143                                 // This client did not see this rejected message yet so add it to the watch set to monitor
2144                                 deviceWatchSet.add(lastMessageEntryMachineId);
2145                         }
2146                 }
2147
2148                 if (deviceWatchSet.isEmpty()) {
2149                         // This rejected message has been seen by all the clients so
2150                         entry.setDead();
2151                 } else {
2152                         // We need to watch this rejected message
2153                         entry.setWatchSet(deviceWatchSet);
2154                 }
2155         }
2156
2157         /**
2158          * Check if this abort is live, if not then save it so we can kill it later.
2159          * update the last transaction number that was arbitrated on.
2160          */
2161         private void processEntry(Abort entry) {
2162
2163                 // Abort has not been seen by the client it is for yet so we need to keep track of it
2164                 Abort previouslySeenAbort = liveAbortTable.put(entry.getAbortId(), entry);
2165                 if (previouslySeenAbort != null) {
2166                         previouslySeenAbort.setDead(); // Delete old version of the abort since we got a rescued newer version
2167                 }
2168
2169                 if (entry.getTransactionArbitrator() == localMachineId) {
2170                         liveAbortsGeneratedByLocal.put(entry.getArbitratorLocalSequenceNumber(), entry);
2171                 }
2172
2173                 if ((entry.getSequenceNumber() != -1) && (lastMessageTable.get(entry.getTransactionMachineId()).getFirst() >= entry.getSequenceNumber())) {
2174
2175                         // The machine already saw this so it is dead
2176                         entry.setDead();
2177                         liveAbortTable.remove(entry.getAbortId());
2178
2179                         if (entry.getTransactionArbitrator() == localMachineId) {
2180                                 liveAbortsGeneratedByLocal.remove(entry.getArbitratorLocalSequenceNumber());
2181                         }
2182
2183                         return;
2184                 }
2185
2186
2187                 if (entry.getTransactionSequenceNumber() != -1) {
2188                         // update the transaction status if it was sent to the server
2189                         TransactionStatus status = outstandingTransactionStatus.remove(entry.getTransactionSequenceNumber());
2190                         if (status != null) {
2191                                 status.setStatus(TransactionStatus.StatusAborted);
2192                         }
2193                 }
2194
2195                 // Update the last arbitration data that we have seen so far
2196                 if (lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator()) != null) {
2197
2198                         long lastArbitrationSequenceNumber = lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.get(entry.getTransactionArbitrator());
2199                         if (entry.getSequenceNumber() > lastArbitrationSequenceNumber) {
2200                                 // Is larger
2201                                 lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2202                         }
2203
2204                 } else {
2205                         // Never seen any data from this arbitrator so record the first one
2206                         lastArbitrationDataLocalSequenceNumberSeenFromArbitrator.put(entry.getTransactionArbitrator(), entry.getSequenceNumber());
2207                 }
2208
2209
2210                 // Set dead a transaction if we can
2211                 Transaction transactionToSetDead = liveTransactionByTransactionIdTable.remove(new Pair<Long, Long>(entry.getTransactionMachineId(), entry.getTransactionClientLocalSequenceNumber()));
2212                 if (transactionToSetDead != null) {
2213                         liveTransactionBySequenceNumberTable.remove(transactionToSetDead.getSequenceNumber());
2214                 }
2215
2216                 // Update the last transaction sequence number that the arbitrator arbitrated on
2217                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getTransactionArbitrator());
2218                 if ((lastTransactionNumber == null) || (lastTransactionNumber < entry.getTransactionSequenceNumber())) {
2219
2220                         // Is a valid one
2221                         if (entry.getTransactionSequenceNumber() != -1) {
2222                                 lastArbitratedTransactionNumberByArbitratorTable.put(entry.getTransactionArbitrator(), entry.getTransactionSequenceNumber());
2223                         }
2224                 }
2225         }
2226
2227         /**
2228          * Set dead the transaction part if that transaction is dead and keep track of all new parts
2229          */
2230         private void processEntry(TransactionPart entry) {
2231                 // Check if we have already seen this transaction and set it dead OR if it is not alive
2232                 Long lastTransactionNumber = lastArbitratedTransactionNumberByArbitratorTable.get(entry.getArbitratorId());
2233                 if ((lastTransactionNumber != null) && (lastTransactionNumber >= entry.getSequenceNumber())) {
2234                         // This transaction is dead, it was already committed or aborted
2235                         entry.setDead();
2236                         return;
2237                 }
2238
2239                 // This part is still alive
2240                 Map<Pair<Long, Integer>, TransactionPart> transactionPart = newTransactionParts.get(entry.getMachineId());
2241
2242                 if (transactionPart == null) {
2243                         // Dont have a table for this machine Id yet so make one
2244                         transactionPart = new HashMap<Pair<Long, Integer>, TransactionPart>();
2245                         newTransactionParts.put(entry.getMachineId(), transactionPart);
2246                 }
2247
2248                 // Update the part and set dead ones we have already seen (got a rescued version)
2249                 TransactionPart previouslySeenPart = transactionPart.put(entry.getPartId(), entry);
2250                 if (previouslySeenPart != null) {
2251                         previouslySeenPart.setDead();
2252                 }
2253         }
2254
2255         /**
2256          * Process new commit entries and save them for future use.  Delete duplicates
2257          */
2258         private void processEntry(CommitPart entry) {
2259                 Map<Pair<Long, Integer>, CommitPart> commitPart = newCommitParts.get(entry.getMachineId());
2260
2261                 if (commitPart == null) {
2262                         // Don't have a table for this machine Id yet so make one
2263                         commitPart = new HashMap<Pair<Long, Integer>, CommitPart>();
2264                         newCommitParts.put(entry.getMachineId(), commitPart);
2265                 }
2266
2267                 // Update the part and set dead ones we have already seen (got a rescued version)
2268                 CommitPart previouslySeenPart = commitPart.put(entry.getPartId(), entry);
2269                 if (previouslySeenPart != null) {
2270                         previouslySeenPart.setDead();
2271                 }
2272         }
2273
2274         /**
2275          * Update the last message seen table.  Update and set dead the appropriate RejectedMessages as clients see them.
2276          * Updates the live aborts, removes those that are dead and sets them dead.
2277          * Check that the last message seen is correct and that there is no mismatch of our own last message or that
2278          * other clients have not had a rollback on the last message.
2279          */
2280         private void updateLastMessage(long machineId, long seqNum, Liveness liveness, boolean acceptUpdatesToLocal, HashSet<Long> machineSet) {
2281
2282                 // We have seen this machine ID
2283                 machineSet.remove(machineId);
2284
2285                 // Get the set of rejected messages that this machine Id is has not seen yet
2286                 HashSet<RejectedMessage> watchset = rejectedMessageWatchListTable.get(machineId);
2287
2288                 // If there is a rejected message that this machine Id has not seen yet
2289                 if (watchset != null) {
2290
2291                         // Go through each rejected message that this machine Id has not seen yet
2292                         for (Iterator<RejectedMessage> rmit = watchset.iterator(); rmit.hasNext(); ) {
2293
2294                                 RejectedMessage rm = rmit.next();
2295
2296                                 // If this machine Id has seen this rejected message...
2297                                 if (rm.getNewSeqNum() <= seqNum) {
2298
2299                                         // Remove it from our watchlist
2300                                         rmit.remove();
2301
2302                                         // Decrement machines that need to see this notification
2303                                         rm.removeWatcher(machineId);
2304                                 }
2305                         }
2306                 }
2307
2308                 // Set dead the abort
2309                 for (Iterator<Map.Entry<Pair<Long, Long>, Abort>> i = liveAbortTable.entrySet().iterator(); i.hasNext();) {
2310                         Abort abort = i.next().getValue();
2311
2312                         if ((abort.getTransactionMachineId() == machineId) && (abort.getSequenceNumber() <= seqNum)) {
2313                                 abort.setDead();
2314                                 i.remove();
2315
2316                                 if (abort.getTransactionArbitrator() == localMachineId) {
2317                                         liveAbortsGeneratedByLocal.remove(abort.getArbitratorLocalSequenceNumber());
2318                                 }
2319                         }
2320                 }
2321
2322
2323
2324                 if (machineId == localMachineId) {
2325                         // Our own messages are immediately dead.
2326                         if (liveness instanceof LastMessage) {
2327                                 ((LastMessage)liveness).setDead();
2328                         } else if (liveness instanceof Slot) {
2329                                 ((Slot)liveness).setDead();
2330                         } else {
2331                                 throw new Error("Unrecognized type");
2332                         }
2333                 }
2334
2335                 // Get the old last message for this device
2336                 Pair<Long, Liveness> lastMessageEntry = lastMessageTable.put(machineId, new Pair<Long, Liveness>(seqNum, liveness));
2337                 if (lastMessageEntry == null) {
2338                         // If no last message then there is nothing else to process
2339                         return;
2340                 }
2341
2342                 long lastMessageSeqNum = lastMessageEntry.getFirst();
2343                 Liveness lastEntry = lastMessageEntry.getSecond();
2344
2345                 // If it is not our machine Id since we already set ours to dead
2346                 if (machineId != localMachineId) {
2347                         if (lastEntry instanceof LastMessage) {
2348                                 ((LastMessage)lastEntry).setDead();
2349                         } else if (lastEntry instanceof Slot) {
2350                                 ((Slot)lastEntry).setDead();
2351                         } else {
2352                                 throw new Error("Unrecognized type");
2353                         }
2354                 }
2355
2356                 // Make sure the server is not playing any games
2357                 if (machineId == localMachineId) {
2358
2359                         if (hadPartialSendToServer) {
2360                                 // We were not making any updates and we had a machine mismatch
2361                                 if (lastMessageSeqNum > seqNum && !acceptUpdatesToLocal) {
2362                                         throw new Error("Server Error: Mismatch on local machine sequence number, needed at least: " +  lastMessageSeqNum  + " got: " + seqNum);
2363                                 }
2364
2365                         } else {
2366                                 // We were not making any updates and we had a machine mismatch
2367                                 if (lastMessageSeqNum != seqNum && !acceptUpdatesToLocal) {
2368                                         throw new Error("Server Error: Mismatch on local machine sequence number, needed: " +  lastMessageSeqNum + " got: " + seqNum);
2369                                 }
2370                         }
2371                 } else {
2372                         if (lastMessageSeqNum > seqNum) {
2373                                 throw new Error("Server Error: Rollback on remote machine sequence number");
2374                         }
2375                 }
2376         }
2377
2378         /**
2379          * Add a rejected message entry to the watch set to keep track of which clients have seen that
2380          * rejected message entry and which have not.
2381          */
2382         private void addWatchList(long machineId, RejectedMessage entry) {
2383                 HashSet<RejectedMessage> entries = rejectedMessageWatchListTable.get(machineId);
2384                 if (entries == null) {
2385                         // There is no set for this machine ID yet so create one
2386                         entries = new HashSet<RejectedMessage>();
2387                         rejectedMessageWatchListTable.put(machineId, entries);
2388                 }
2389                 entries.add(entry);
2390         }
2391
2392         /**
2393          * Check if the HMAC chain is not violated
2394          */
2395         private void checkHMACChain(SlotIndexer indexer, Slot[] newSlots) {
2396                 for (int i = 0; i < newSlots.length; i++) {
2397                         Slot currSlot = newSlots[i];
2398                         Slot prevSlot = indexer.getSlot(currSlot.getSequenceNumber() - 1);
2399                         if (prevSlot != null &&
2400                                 !Arrays.equals(prevSlot.getHMAC(), currSlot.getPrevHMAC()))
2401                                 throw new Error("Server Error: Invalid HMAC Chain" + currSlot + " " + prevSlot);
2402                 }
2403         }
2404 }