diff --git a/src/server.py b/src/server.py --- a/src/server.py +++ b/src/server.py @@ -41,7 +41,7 @@ class Server: self._ss.bind(("", conf.port)) self._ss.listen(1) - self._lastWrite=-1 + self._lastIndex=-1 self._dataFile=None def serve(self): @@ -62,7 +62,10 @@ class Server: outcoming.writeMsg({"command": "ack"}) elif jsonData["command"]=="req": - outcoming.writeMsg(*self._requestHash(jsonData)) + if jsonData["dataType"]=="data": + outcoming.writeMsg(*self._requestData(jsonData["index"])) + else: + outcoming.writeMsg(*self._requestHash(jsonData["index"])) elif jsonData["command"]=="send" and jsonData["dataType"]=="data": outcoming.writeMsg(*self._receiveData(jsonData,binData)) @@ -76,13 +79,23 @@ class Server: return True - def _requestHash(self,jsonData): - log.info("received request for node #{0}".format(jsonData["index"])) - assert jsonData["index"]<len(self._tree.store) - nodeHash=self._tree.store[jsonData["index"]] + def _requestHash(self,index): + log.info("received request for node #{0}".format(index)) + assert index<len(self._tree.store) + nodeHash=self._tree.store[index] + + jsonResponse={"command":"send", "index":index, "dataType":"hash"} + binResponse=nodeHash - jsonResponse={"command":"send", "index":jsonData["index"], "dataType":"hash"} - binResponse=nodeHash + return (jsonResponse,binResponse) + + def _requestData(self,index): + log.info("received request for data block #{0}".format(index)) + + jsonResponse={"command":"send", "index":index, "dataType":"data"} + if self._lastIndex+1!=index: + self._dataFile.seek(index*self.BLOCK_SIZE) + binResponse=self._dataFile.read(self.BLOCK_SIZE) return (jsonResponse,binResponse) @@ -92,12 +105,12 @@ class Server: if not self._dataFile: self._dataFile=open(self._filename, mode="rb+") i=jsonData["index"] - if self._lastWrite+1!=i: - self._dataFile.seek(i * self.BLOCK_SIZE) + if self._lastIndex+1!=i: + self._dataFile.seek(i*self.BLOCK_SIZE) self._dataFile.write(binData) - self._lastWrite=i + self._lastIndex=i if self._treeFile: - self._newLeaves[i + self._tree.leafStart]= hashlib.sha256(binData).digest()[HashTree.HASH_LEN:] + self._newLeaves[i+self._tree.leafStart]=hashlib.sha256(binData).digest()[HashTree.HASH_LEN:] return ({"command": "ack", "index": i},)