Add peer creation time tracking and enhance DEAD peer handling

This commit is contained in:
ImBenji
2025-08-28 23:00:14 +01:00
parent 1b0ee56d79
commit 73afa2f7a3
2 changed files with 97 additions and 6 deletions

View File

@@ -69,6 +69,9 @@ Future<WireGuardPeer> createPeer() async {
// Add peer to WireGuard
await Process.run('wg', ['set', 'wg0', 'peer', publicKey.trim(), 'allowed-ips', '$ip/32']);
// Track peer creation time
await _trackPeerCreation(publicKey.trim());
return WireGuardPeer(
privateKey: privateKey,
publicKey: publicKey.trim(),
@@ -83,6 +86,10 @@ Future<bool> deletePeer(String publicKey) async {
print('Error removing peer: ${result.stderr}');
return false;
}
// Clean up peer creation tracking
await _cleanupPeerCreation(publicKey);
return true;
}
@@ -134,3 +141,56 @@ Future<String> _getNextIP() async {
}
throw Exception('No available IPs');
}
/// Tracks when a peer was created
Future<void> _trackPeerCreation(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
Map<String, dynamic> creationTimes = {};
if (await file.exists()) {
final content = await file.readAsString();
creationTimes = jsonDecode(content);
}
creationTimes[publicKey] = DateTime.now().millisecondsSinceEpoch;
await file.writeAsString(jsonEncode(creationTimes));
} catch (e) {
print('Error tracking peer creation: $e');
}
}
/// Gets the creation time for a peer
Future<DateTime?> getPeerCreationTime(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
if (!await file.exists()) return null;
final content = await file.readAsString();
final creationTimes = jsonDecode(content) as Map<String, dynamic>;
final timestamp = creationTimes[publicKey];
if (timestamp == null) return null;
return DateTime.fromMillisecondsSinceEpoch(timestamp);
} catch (e) {
print('Error getting peer creation time: $e');
return null;
}
}
/// Cleans up peer creation tracking when peer is deleted
Future<void> _cleanupPeerCreation(String publicKey) async {
try {
final file = File('/tmp/peer_creation_times.json');
if (!await file.exists()) return;
final content = await file.readAsString();
final creationTimes = jsonDecode(content) as Map<String, dynamic>;
creationTimes.remove(publicKey);
await file.writeAsString(jsonEncode(creationTimes));
} catch (e) {
print('Error cleaning up peer creation tracking: $e');
}
}