Skip to content

Commit a304688

Browse files
committed
feat: First version of validator logic.
1 parent 6450676 commit a304688

File tree

11 files changed

+1122
-96
lines changed

11 files changed

+1122
-96
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,5 @@ docs/
1212

1313
# Dotenv file
1414
.env
15+
16+
node_modules/

README.md

Lines changed: 175 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,203 @@
1-
## Foundry
1+
# GenLayer-Inspired Optimistic Consensus Mechanism
22

3-
**Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust.**
3+
This project implements a simplified optimistic consensus mechanism inspired by GenLayer's architecture for Intelligent Contracts powered by Large Language Models (LLMs). The system provides a staking mechanism for ValidatorLogics, optimistic transaction execution, and dispute resolution with fallback to consensus voting.
44

5-
Foundry consists of:
5+
## Architecture Overview
66

7-
- **Forge**: Ethereum testing framework (like Truffle, Hardhat and DappTools).
8-
- **Cast**: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data.
9-
- **Anvil**: Local Ethereum node, akin to Ganache, Hardhat Network.
10-
- **Chisel**: Fast, utilitarian, and verbose solidity REPL.
7+
The system consists of three main components:
118

12-
## Documentation
9+
1. **ERC20TokenMock (GLT)**: Mock ERC20 token used for ValidatorLogic staking
10+
2. **ValidatorLogicBeacon**: Manages ValidatorLogic registration, proxy creation, and selection
11+
3. **GenLayerConsensus**: Handles transaction proposals, optimistic execution, and dispute resolution
1312

14-
https://book.getfoundry.sh/
13+
### Key Features
1514

16-
## Usage
15+
- **ValidatorLogic Staking**: Users can stake GLT tokens to become ValidatorLogics (minimum 1000 GLT)
16+
- **Beacon Proxy Pattern**: Each ValidatorLogic gets a unique proxy contract to hold their stake
17+
- **Optimistic Execution**: Transactions are optimistically approved with 3/5 ValidatorLogic signatures
18+
- **Dispute Resolution**: Any ValidatorLogic can challenge proposals within a 10-block window
19+
- **Mock LLM Validation**: Simulates LLM-based transaction validation
20+
- **Slashing Mechanism**: False challenges result in 10% stake slashing
1721

18-
### Build
22+
## Contract Structure
1923

20-
```shell
21-
$ forge build
22-
```
24+
### ERC20TokenMock.sol
25+
- Standard ERC20 token with minting capability
26+
- Used for ValidatorLogic staking and economic incentives
2327

24-
### Test
28+
### ValidatorLogicProxy.sol
29+
- Beacon proxy contract for individual ValidatorLogics
30+
- Holds ValidatorLogic stake and metadata
31+
- Implements slashing functionality
2532

26-
```shell
27-
$ forge test
28-
```
33+
### ValidatorLogicBeacon.sol
34+
- Manages ValidatorLogic registration and proxy creation
35+
- Implements dPoS-like ValidatorLogic selection
36+
- Handles bonding periods and unstaking
37+
38+
### GenLayerConsensus.sol
39+
- Main consensus contract for transaction processing
40+
- Implements optimistic approval with signature verification
41+
- Handles dispute resolution and voting mechanisms
42+
43+
## Installation and Setup
44+
45+
### Prerequisites
46+
- Foundry (recommended) or Hardhat
47+
- Node.js and npm
48+
49+
### Installation
50+
```bash
51+
# Clone the repository
52+
git clone <repository-url>
53+
cd simplified-consensus
54+
55+
# Install dependencies
56+
forge install
2957

30-
### Format
58+
# Build contracts
59+
forge build
60+
```
3161

32-
```shell
33-
$ forge fmt
62+
### Environment Setup
63+
Create a `.env` file with your private key:
64+
```bash
65+
PRIVATE_KEY=your_private_key_here
3466
```
3567

36-
### Gas Snapshots
68+
## Usage
3769

38-
```shell
39-
$ forge snapshot
70+
### Deployment
71+
```bash
72+
# Deploy all contracts
73+
forge script script/Deploy.s.sol --rpc-url <your_rpc_url> --broadcast
4074
```
4175

42-
### Anvil
76+
### Testing
77+
```bash
78+
# Run all tests
79+
forge test
80+
81+
# Run specific test file
82+
forge test --match-contract GenLayerConsensusTest
83+
84+
# Run fuzz tests
85+
forge test --match-contract GenLayerConsensusFuzzTest
4386

44-
```shell
45-
$ anvil
87+
# Run invariant tests
88+
forge test --match-contract GenLayerConsensusInvariantTest
89+
90+
# Generate coverage report
91+
forge coverage
4692
```
4793

48-
### Deploy
94+
### Key Operations
4995

50-
```shell
51-
$ forge script script/Counter.s.sol:CounterScript --rpc-url <your_rpc_url> --private-key <your_private_key>
96+
#### 1. Register as ValidatorLogic
97+
```solidity
98+
// Approve tokens first
99+
token.approve(address(beacon), stakeAmount);
100+
beacon.registerValidatorLogic(stakeAmount);
52101
```
53102

54-
### Cast
103+
#### 2. Submit Transaction Proposal
104+
```solidity
105+
bytes32 proposalId = consensus.submitProposal("Approve loan for user X based on LLM analysis");
106+
```
55107

56-
```shell
57-
$ cast <subcommand>
108+
#### 3. Sign Proposal for Optimistic Approval
109+
```solidity
110+
bytes32 messageHash = keccak256(abi.encodePacked(proposalId, "SIGN"));
111+
bytes32 ethSignedMessageHash = messageHash.toEthSignedMessageHash();
112+
(uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, ethSignedMessageHash);
113+
bytes memory signature = abi.encodePacked(r, s, v);
114+
consensus.signProposal(proposalId, signature);
58115
```
59116

60-
### Help
117+
#### 4. Challenge Proposal
118+
```solidity
119+
consensus.challengeProposal(proposalId);
120+
```
61121

62-
```shell
63-
$ forge --help
64-
$ anvil --help
65-
$ cast --help
122+
#### 5. Vote on Challenged Proposal
123+
```solidity
124+
bytes32 messageHash = keccak256(abi.encodePacked(proposalId, vote, "VOTE"));
125+
bytes32 ethSignedMessageHash = messageHash.toEthSignedMessageHash();
126+
(uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, ethSignedMessageHash);
127+
bytes memory signature = abi.encodePacked(r, s, v);
128+
consensus.voteOnProposal(proposalId, vote, signature);
66129
```
130+
131+
## Testing Strategy
132+
133+
### Unit Tests
134+
- ValidatorLogic registration and unstaking
135+
- Proposal submission and state transitions
136+
- Optimistic approval flow
137+
- Dispute resolution mechanisms
138+
- Error handling and edge cases
139+
140+
### Fuzz Tests
141+
- Random proposal messages
142+
- Various stake amounts
143+
- Signature verification with different private keys
144+
- Array operations with different sizes
145+
146+
### Invariant Tests
147+
- Total stake never decreases unexpectedly
148+
- ValidatorLogic count consistency
149+
- Token supply consistency
150+
- Proposal state consistency
151+
152+
## Security Considerations
153+
154+
### Implemented Safeguards
155+
1. **Minimum Stake Requirement**: Prevents spam ValidatorLogics
156+
2. **Bonding Period**: Prevents rapid ValidatorLogic churn
157+
3. **Signature Verification**: Ensures only ValidatorLogics can sign/vote
158+
4. **Challenge Window**: Limits dispute timeframe
159+
5. **Slashing Mechanism**: Deters false challenges
160+
6. **Majority Voting**: Ensures fair dispute resolution
161+
162+
### Potential Vulnerabilities and Mitigations
163+
1. **Sybil Attacks**: Mitigated by minimum stake requirement
164+
2. **Signature Replay**: Prevented by unique proposal IDs
165+
3. **Front-running**: Limited by challenge window
166+
4. **ValidatorLogic Collusion**: Addressed by slashing mechanism
167+
168+
## Design Choices and Extensions
169+
170+
### Current Implementation
171+
- **Mock LLM**: Simple hash-based validation for demonstration
172+
- **Fixed Parameters**: Challenge window, required signatures, etc.
173+
- **Simple Selection**: Basic ValidatorLogic selection based on registration order
174+
175+
### Potential Extensions for GenLayer
176+
1. **Oracle Integration**: Replace mock LLM with real oracle calls
177+
2. **Dynamic Parameters**: Adjustable challenge windows and thresholds
178+
3. **Advanced Selection**: Weighted ValidatorLogic selection based on performance
179+
4. **Cross-chain Support**: Extend to multi-chain environments
180+
5. **Layer 2 Integration**: Optimize for L2 scaling solutions
181+
182+
### LLM Integration Points
183+
- **Transaction Validation**: Replace `mockLLMValidation()` with oracle calls
184+
- **Risk Assessment**: Add LLM-based risk scoring for proposals
185+
- **Content Moderation**: Use LLMs for content filtering
186+
- **Automated Responses**: LLM-generated challenge responses
187+
188+
## Contributing
189+
190+
1. Fork the repository
191+
2. Create a feature branch
192+
3. Make your changes
193+
4. Add tests for new functionality
194+
5. Ensure all tests pass
195+
6. Submit a pull request
196+
197+
## License
198+
199+
This project is licensed under the BUSL License - see the LICENSE file for details.
200+
201+
## Acknowledgments
202+
203+
This implementation is inspired by GenLayer's architecture for AI-powered blockchain consensus mechanisms. The design demonstrates how LLMs can be integrated into blockchain systems for intelligent contract execution and validation.

foundry.toml

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
11
[profile.default]
22
src = "src"
33
out = "out"
4-
libs = ["lib"]
4+
libs = ["lib", "node_modules"]
5+
optimizer = true
6+
optimizer_runs = 200
7+
8+
# Remappings for OpenZeppelin contracts
9+
remappings = [
10+
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
11+
"forge-std/=lib/forge-std/src/"
12+
]
13+
14+
[profile.default.fuzz]
15+
runs = 1000
16+
17+
[profile.default.invariant]
18+
runs = 1000
19+
depth = 15
20+
fail_on_revert = false
521

622
# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options

package.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"name": "simplified-consensus",
3+
"version": "1.0.0",
4+
"main": "index.js",
5+
"repository": "[email protected]:xdaniortega/simplified-consensus.git",
6+
"author": "Daniel Ortega <[email protected]>",
7+
"license": "MIT",
8+
"dependencies": {
9+
"@openzeppelin/contracts": "^5.3.0"
10+
}
11+
}

script/Counter.s.sol

Lines changed: 0 additions & 19 deletions
This file was deleted.

src/Counter.sol

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)