From 15b088f48111ef2bb02e2dc09053c226fe8d1bce Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sat, 19 Nov 2022 20:34:57 -0500 Subject: [PATCH] *Add timestamp checking to not store old data --- src/DHTDataBase.ts | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/DHTDataBase.ts b/src/DHTDataBase.ts index 7e018ae..24e0abc 100644 --- a/src/DHTDataBase.ts +++ b/src/DHTDataBase.ts @@ -78,6 +78,7 @@ export default class DHTDataBase extends EventEmitter { getPeerData(id: Buffer | string) { return this.getPeerField(id, "data"); } + getPeerTimestamp(id: Buffer | string) { return this.getPeerField(id, "timestamp"); } @@ -159,12 +160,18 @@ export default class DHTDataBase extends EventEmitter { signature && crypto.verify(b4a.from(`${timestamp}${rawData}`), signature, id) ) { + if ((timestamp || 0) <= this.getPeerTimestamp(id)) { + debug(`Received old data for peer ${id}`); + return; + } + const data = rawData ? orderedJSON.parse(rawData) : null; this._setPeer(id, data, timestamp, signature); this.emit("peer-data", data, id); this._recalculate(); return; } + debug(`Invalid signature received for peer ${id}`); } else if (type === Type.CONNECTED) { const { id: toId } = decoded; @@ -281,11 +288,16 @@ export default class DHTDataBase extends EventEmitter { // If we're already tracking them if (this._hasSeenPeer(id)) { - // See what data we already have for them - // Add their existing data to what we got from the bootstrap - const existingPeerData = this.getPeerData(id); - peerData = { ...existingPeerData, ...peerData }; - this._setPeer(id, peerData, timestamp, signature); + // Ensure we don't have old data + if ((timestamp || 0) > this.getPeerTimestamp(id)) { + // See what data we already have for them + // Add their existing data to what we got from the bootstrap + const existingPeerData = this.getPeerData(id); + peerData = { ...existingPeerData, ...peerData }; + this._setPeer(id, peerData, timestamp, signature); + } else { + debug(`Received old data for peer ${id}`); + } } } else { debug(`Invalid signature received for peer ${id}`);