Skip to content

Commit

Permalink
Added enhanced security
Browse files Browse the repository at this point in the history
  • Loading branch information
Admin committed Nov 29, 2024
1 parent 405cf29 commit 7d57754
Show file tree
Hide file tree
Showing 7 changed files with 707 additions and 46 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,33 @@ Backr is a decentralized platform built on Ethereum that enables transparent and
- `QuadraticFunding.sol`: Implementation of quadratic funding mechanism
- `PlatformToken.sol`: BACKR token with staking capabilities
- `UserProfile.sol`: User reputation and profile management
- `SecurityControls.sol`: Advanced security mechanisms with emergency management

#### Security Controls Overview

The `SecurityControls` contract provides a comprehensive security framework with multiple layers of protection:

- **Rate Limiting**: Prevents excessive contract interactions by configuring call limits within specific time windows.
- **Multi-Signature Approvals**: Requires multiple authorized parties to approve critical operations, reducing single-point-of-failure risks.
- **Emergency Management**:
- Allows authorized emergency roles to pause the entire contract ecosystem
- Supports multiple emergency triggers without cooldown restrictions
- Provides flexible circuit breaker mechanisms to halt all contract interactions
- Comprehensive logging for all emergency-related actions
- Configurable cooldown periods for fine-tuned emergency response

### Security Features
- Reentrancy guards
- Time-locked execution
- Access control mechanisms
- Minimum liquidity requirements
- Pausable functionality
- **Enhanced Emergency Controls**
- Multiple emergency trigger capabilities
- Flexible circuit breaker mechanism
- Configurable emergency cooldown periods
- Role-based emergency management
- Comprehensive event logging for emergency actions

## Development

Expand Down
70 changes: 70 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Backr TODO List

## High Priority

### Core Infrastructure
- [x] Implement rate limiting for sensitive operations
- [x] Add multi-signature wallet support
- [x] Create emergency response system
- [x] Add fraud detection mechanisms

### User Experience
- [ ] Add project categories and tags for discovery
- [ ] Implement project templates
- [ ] Create dispute resolution system
- [ ] Add profile delegation for team management

## Medium Priority

### Analytics & Reporting
- [ ] Build analytics dashboard for project performance
- [ ] Implement milestone completion tracking
- [ ] Add quadratic funding round analytics
- [ ] Create backer engagement metrics

### Profile Enhancements
- [ ] Add social graph functionality
- [ ] Implement endorsement system
- [ ] Create project portfolio showcase
- [ ] Enable profile verification improvements

### Liquidity Features
- [ ] Add multiple pool tiers
- [ ] Implement flash loan functionality
- [ ] Create liquidity mining incentives
- [ ] Add yield farming opportunities

## Future Considerations

### Badge System
- [ ] Create dynamic badge properties
- [ ] Implement time-limited event badges
- [ ] Add badge trading marketplace
- [ ] Develop badge-based governance weight

### Governance
- [ ] Add delegation capabilities
- [ ] Implement gasless voting
- [ ] Create specialized committees
- [ ] Add proposal templates

### Integration & Expansion
- [ ] Add API endpoints
- [ ] Create webhook system
- [ ] Implement cross-chain functionality
- [ ] Add oracle integration

## Completed Tasks
- [x] Initial smart contract setup
- [x] Basic user profile system
- [x] Core milestone tracking
- [x] Basic quadratic funding mechanism
- [x] Implement rate limiting for sensitive operations
- [x] Add multi-signature wallet support
- [x] Create emergency response system
- [x] Add fraud detection mechanisms

## Notes
- Priority levels may be adjusted based on community feedback
- Security-related tasks should be reviewed by external auditors
- Integration features should be compatible with existing DeFi protocols
5 changes: 5 additions & 0 deletions foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ src = "src"
out = "out"
libs = ["lib"]

# Enable IR-based compilation and optimizer
via_ir = true
optimizer = true
optimizer_runs = 200

# Explicit remappings for OpenZeppelin contracts
remappings = [
"@openzeppelin/=lib/openzeppelin-contracts/",
Expand Down
77 changes: 65 additions & 12 deletions src/Project.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
pragma solidity ^0.8.13;

import "./UserProfile.sol";
import "./SecurityControls.sol";

/// @title Project Contract for Backr Platform
/// @notice Manages project creation, funding, and milestone tracking
contract Project {
contract Project is SecurityControls {
// Structs
struct Milestone {
string description;
Expand Down Expand Up @@ -33,6 +34,14 @@ contract Project {
mapping(uint256 => ProjectDetails) public projects;
uint256 public totalProjects;

// Operation identifiers for rate limiting and multi-sig
bytes32 public constant CREATE_PROJECT_OPERATION = keccak256("CREATE_PROJECT");
bytes32 public constant LARGE_FUNDING_OPERATION = keccak256("LARGE_FUNDING");
bytes32 public constant MILESTONE_COMPLETION_OPERATION = keccak256("MILESTONE_COMPLETION");

// Funding thresholds
uint256 public constant LARGE_FUNDING_THRESHOLD = 10 ether;

// Events
event ProjectCreated(uint256 indexed projectId, address indexed creator, string title);
event MilestoneAdded(uint256 indexed projectId, uint256 milestoneId, string description);
Expand All @@ -50,8 +59,23 @@ contract Project {
error MilestoneAlreadyCompleted();
error InsufficientVotes();

constructor(address _userProfileAddress) {
constructor(address _userProfileAddress) SecurityControls() {
userProfile = UserProfile(_userProfileAddress);

// Grant the deployer the DEFAULT_ADMIN_ROLE
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);

// Configure rate limits
_configureRateLimit(CREATE_PROJECT_OPERATION, 1, 24 hours); // 1 project per 24 hours
_configureRateLimit(MILESTONE_COMPLETION_OPERATION, 10, 1 days); // 10 milestone completions per day

// Initialize emergency settings
emergencyConfig.cooldownPeriod = 12 hours;

// Setup default multi-sig configuration for large funding
address[] memory defaultApprovers = new address[](1);
defaultApprovers[0] = msg.sender;
configureMultiSig(LARGE_FUNDING_OPERATION, 1, defaultApprovers);
}

/// @notice Creates a new project with initial milestones
Expand All @@ -61,12 +85,12 @@ contract Project {
/// @param _milestoneFunding Array of funding requirements for each milestone
/// @param _milestoneVotesRequired Array of required votes for each milestone
function createProject(
string memory _title,
string memory _description,
string[] memory _milestoneDescriptions,
uint256[] memory _milestoneFunding,
uint256[] memory _milestoneVotesRequired
) external {
string calldata _title,
string calldata _description,
string[] calldata _milestoneDescriptions,
uint256[] calldata _milestoneFunding,
uint256[] calldata _milestoneVotesRequired
) external whenNotPaused rateLimitGuard(CREATE_PROJECT_OPERATION) {
if (!userProfile.hasProfile(msg.sender)) revert UserNotRegistered();
if (bytes(_title).length == 0 || _milestoneDescriptions.length == 0) revert InvalidProjectParameters();
if (
Expand Down Expand Up @@ -100,12 +124,24 @@ contract Project {
}
}

/// @notice Contribute funds to a project
/// @param _projectId ID of the project
function contributeToProject(uint256 _projectId) external payable {
/// @notice Contributes funds to a project
function contributeToProject(uint256 _projectId)
external
payable
whenNotPaused
whenCircuitBreakerOff
nonReentrant
{
if (!projects[_projectId].isActive) revert ProjectNotFound();
if (msg.value == 0) revert InsufficientFunds();

// For large funding amounts, require multi-sig approval
if (msg.value >= LARGE_FUNDING_THRESHOLD) {
bytes32 txHash = keccak256(abi.encodePacked(_projectId, msg.sender, msg.value, block.timestamp));
MultiSigConfig storage config = multiSigConfigs[LARGE_FUNDING_OPERATION];
require(config.executed[txHash], "Requires multi-sig approval");
}

ProjectDetails storage project = projects[_projectId];
project.currentFunding += msg.value;

Expand All @@ -115,7 +151,7 @@ contract Project {
/// @notice Vote for milestone completion
/// @param _projectId ID of the project
/// @param _milestoneId ID of the milestone
function voteMilestone(uint256 _projectId, uint256 _milestoneId) external {
function voteMilestone(uint256 _projectId, uint256 _milestoneId) external whenNotPaused whenCircuitBreakerOff {
ProjectDetails storage project = projects[_projectId];
if (!project.isActive) revert ProjectNotFound();
if (_milestoneId >= project.milestoneCount) revert MilestoneNotFound();
Expand Down Expand Up @@ -156,6 +192,8 @@ contract Project {
function getMilestone(uint256 _projectId, uint256 _milestoneId)
external
view
whenNotPaused
whenCircuitBreakerOff
returns (
string memory description,
uint256 fundingRequired,
Expand Down Expand Up @@ -184,11 +222,26 @@ contract Project {
function hasVotedForMilestone(uint256 _projectId, uint256 _milestoneId, address _voter)
external
view
whenNotPaused
whenCircuitBreakerOff
returns (bool)
{
return projects[_projectId].milestones[_milestoneId].hasVoted[_voter];
}

/// @notice Emergency withdrawal of funds
function emergencyWithdraw(uint256 _projectId) external onlyRole(EMERGENCY_ROLE) whenPaused {
ProjectDetails storage project = projects[_projectId];
if (!project.isActive) revert ProjectNotFound();

uint256 amount = project.currentFunding;
project.currentFunding = 0;
project.isActive = false;

(bool success,) = project.creator.call{value: amount}("");
require(success, "Transfer failed");
}

/// @notice Receive function to accept ETH payments
receive() external payable {}
}
Loading

0 comments on commit 7d57754

Please sign in to comment.