Skip to content

Commit c040295

Browse files
authored
Merge pull request #34 from ewdlop/ewdlop-patch-27
Create GossipProtocol.sol
2 parents 5eb5e3d + 096d934 commit c040295

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

App/Claude/GossipProtocol.sol

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// SPDX-License-Identifier: MIT
2+
pragma solidity ^0.8.0;
3+
4+
// Note: A full gossip protocol requires node-to-node communication
5+
// which isn't directly possible in Solidity. This is a simplified
6+
// centralized simulation.
7+
8+
contract GossipProtocol {
9+
struct NodeState {
10+
uint256 heartbeat;
11+
uint256 timestamp;
12+
bool isAlive;
13+
}
14+
15+
// Node registry
16+
mapping(address => NodeState) public nodeStates;
17+
address[] public nodes;
18+
19+
// Event for state updates
20+
event StateUpdated(address node, uint256 heartbeat, uint256 timestamp);
21+
22+
// Register as a node
23+
function register() public {
24+
if (!isRegistered(msg.sender)) {
25+
nodes.push(msg.sender);
26+
}
27+
28+
nodeStates[msg.sender] = NodeState({
29+
heartbeat: 0,
30+
timestamp: block.timestamp,
31+
isAlive: true
32+
});
33+
}
34+
35+
// Update own state (increment heartbeat)
36+
function updateState() public {
37+
require(isRegistered(msg.sender), "Node not registered");
38+
39+
NodeState storage state = nodeStates[msg.sender];
40+
state.heartbeat += 1;
41+
state.timestamp = block.timestamp;
42+
43+
emit StateUpdated(msg.sender, state.heartbeat, state.timestamp);
44+
}
45+
46+
// Gossip about another node's state
47+
function gossip(address aboutNode, uint256 heartbeat, uint256 timestamp) public {
48+
require(isRegistered(msg.sender), "Gossiper not registered");
49+
require(isRegistered(aboutNode), "Subject node not registered");
50+
51+
NodeState storage knownState = nodeStates[aboutNode];
52+
53+
// Only update if the gossip has newer information
54+
if (heartbeat > knownState.heartbeat) {
55+
knownState.heartbeat = heartbeat;
56+
knownState.timestamp = timestamp;
57+
58+
emit StateUpdated(aboutNode, heartbeat, timestamp);
59+
}
60+
}
61+
62+
// Check if a node is registered
63+
function isRegistered(address node) public view returns (bool) {
64+
return nodeStates[node].timestamp > 0;
65+
}
66+
67+
// Get the state of all known nodes
68+
function getAllNodeStates() public view returns (address[] memory, uint256[] memory, bool[] memory) {
69+
uint256[] memory heartbeats = new uint256[](nodes.length);
70+
bool[] memory alive = new bool[](nodes.length);
71+
72+
for (uint256 i = 0; i < nodes.length; i++) {
73+
NodeState memory state = nodeStates[nodes[i]];
74+
heartbeats[i] = state.heartbeat;
75+
76+
// Mark as not alive if no updates in the last 5 minutes
77+
alive[i] = (block.timestamp - state.timestamp) < 5 minutes;
78+
}
79+
80+
return (nodes, heartbeats, alive);
81+
}
82+
}

0 commit comments

Comments
 (0)