More Java Code
[iotcloud.git] / src / java / iotcloud / Table.java
index 5efe9b2733c647f531eed80caffd413d9d65c572..5c6ec6b5bfd3fd6d823460e12d5ebe3f556bfb96 100644 (file)
@@ -1,16 +1,21 @@
 package iotcloud;
 import java.util.HashMap;
+import java.util.Arrays;
 import javax.crypto.spec.*;
 import javax.crypto.*;
 
 public class Table {
        int numslots;
-       HashMap table=new HashMap();
+       HashMap<IoTString, IoTString> table=new HashMap<IoTString, IoTString>();
+       SlotBuffer buffer;
        CloudComm cloud;
        private Mac hmac;
+       long sequencenumber;
        
        public Table(String baseurl, String password) {
                initCloud(baseurl, password);
+               buffer = new SlotBuffer();
+               sequencenumber = 1;
        }
 
        private void initCloud(String baseurl, String password) {
@@ -39,6 +44,47 @@ public class Table {
                }
        }
 
+       public void update() {
+               Slot[] newslots=cloud.getSlots(sequencenumber);
+               validateandupdate(newslots);
+       }
+
+       void validateandupdate(Slot[] newslots) {
+               //The cloud communication layer has checked slot HMACs already
+               //before decoding
+
+               if (newslots.length==0)
+                       return;
+
+               long firstseqnum=newslots[0].getSequenceNumber();
+               if (firstseqnum < sequencenumber)
+                       throw new Error("Server sent older slots!");
+
+               checkHMACChain(newslots);
+               
+               if (firstseqnum == (buffer.getNewestSeqNum()+1)) {
+                       //contiguous update
+               } else {
+                       //non-contiguous update
+               }
 
+               
+       }
+
+       void checkHMACChain(Slot[] newslots) {
+               if (newslots[0].getSequenceNumber() == (buffer.getNewestSeqNum()+1)) {
+                       Slot prevslot=buffer.getSlot(buffer.getNewestSeqNum());
+                       Slot currslot=newslots[0];
+                       if (!Arrays.equals(prevslot.getHMAC(), currslot.getPrevHMAC()))
+                               throw new Error("Error in HMAC Chain");
+               }
 
+               for(int i=1; i < newslots.length; i++) {
+                       Slot prevslot=newslots[i-1];
+                       Slot currslot=newslots[i];
+                       if (!Arrays.equals(prevslot.getHMAC(), currslot.getPrevHMAC()))
+                               throw new Error("Error in HMAC Chain");
+               }
+       }
+       
 }