├── docs ├── MatrixAI.jpeg ├── user_guide.md ├── architecture.md └── API_reference.md ├── src ├── tests │ ├── __init__.py │ ├── test_risk_assessment.py │ ├── test_reputation.py │ ├── test_identity.py │ └── test_smart_contracts.py ├── utils │ ├── __init__.py │ ├── visualization.py │ └── data_processing.py ├── core │ ├── identity │ │ ├── __init__.py │ │ ├── user_roles.py │ │ ├── token_manager.py │ │ ├── cryptography.py │ │ └── identity_manager.py │ ├── smart_contracts │ │ ├── contract.sol │ │ ├── __init__.py │ │ └── deployment.py │ ├── risk_assessment │ │ ├── __init__.py │ │ ├── risk_analyzer.py │ │ └── anomaly_detection.py │ └── reputation │ │ ├── __init__.py │ │ ├── scoring_algorithm.py │ │ └── reputation_manager.py └── main │ ├── config.py │ ├── __init__.py │ ├── logger.py │ └── app.py ├── .github └── ISSUE_TEMPLATE │ ├── custom.md │ ├── feature_request.md │ └── bug_report.md ├── requirements.txt ├── .gitignore ├── examples ├── example_risk_assessment.py └── example_identity.py ├── scripts ├── run_tests.sh ├── setup_environment.sh └── deploy.sh ├── LICENSE └── README.md /docs/MatrixAI.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KOSASIH/MatrixAI-Core/HEAD/docs/MatrixAI.jpeg -------------------------------------------------------------------------------- /src/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # src/tests/__init__.py 2 | """ 3 | Unit and integration tests for the application modules. 4 | """ 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # requirements.txt 2 | 3 | # Core dependencies 4 | pandas>=1.3.0 5 | numpy>=1.21.0 6 | 7 | # For identity management (example) 8 | flask>=2.0.0 9 | flask_sqlalchemy>=2.5.1 10 | 11 | # For risk assessment (example) 12 | scikit-learn>=0.24.0 13 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # src/utils/__init__.py 2 | 3 | from .data_processing import ( 4 | load_data, 5 | clean_data, 6 | normalize_data, 7 | split_data, 8 | ) 9 | 10 | from .visualization import ( 11 | plot_histogram, 12 | plot_scatter, 13 | plot_correlation_matrix, 14 | ) 15 | -------------------------------------------------------------------------------- /src/core/identity/__init__.py: -------------------------------------------------------------------------------- 1 | # src/core/identity/__init__.py 2 | 3 | from .identity_manager import IdentityManager 4 | from .cryptography import Cryptography 5 | from .token_manager import TokenManager 6 | from .user_roles import UserRoles 7 | 8 | __all__ = ['IdentityManager', 'Cryptography', 'TokenManager', 'User Roles'] 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__/ 3 | *.py[cod] 4 | *.pyo 5 | *.pyd 6 | *.egg-info/ 7 | dist/ 8 | build/ 9 | 10 | # Node.js 11 | node_modules/ 12 | npm-debug.log 13 | 14 | # Environment variables 15 | .env 16 | 17 | # IDEs 18 | .vscode/ 19 | .idea/ 20 | *.swp 21 | *.swo 22 | 23 | # Logs 24 | *.log 25 | 26 | # Temporary files 27 | tmp/ 28 | temp/ 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /examples/example_risk_assessment.py: -------------------------------------------------------------------------------- 1 | # examples/example_risk_assessment.py 2 | 3 | from src.risk_assessment import RiskAssessment, InvalidDataError 4 | 5 | def main(): 6 | # Create an instance of RiskAssessment 7 | risk_assessment = RiskAssessment() 8 | 9 | # Example: Assessing Risk 10 | try: 11 | risk_data = { 12 | "credit_score": 650, 13 | "income": 50000, 14 | "debt": 15000, 15 | "employment_status": "employed" 16 | } 17 | risk_score = risk_assessment.assess_risk(risk_data) 18 | print(f"Risk Score: {risk_score}") 19 | 20 | # Example: Categorizing Risk 21 | risk_category = risk_assessment.categorize_risk(risk_score) 22 | print(f"Risk Category: {risk_category}") 23 | 24 | except InvalidDataError as e: 25 | print(f"Risk assessment failed: {e}") 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /scripts/run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # run_tests.sh - Script to run all tests 4 | 5 | set -e # Exit immediately if a command exits with a non-zero status 6 | 7 | # Define variables 8 | TEST_DIR="src/tests" # Directory containing tests 9 | LOG_FILE="test_results.log" # Log file for test results 10 | 11 | # Function to log messages 12 | log() { 13 | echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" 14 | } 15 | 16 | log "Running tests..." 17 | 18 | # Activate the virtual environment 19 | if [ -d "venv" ]; then 20 | source "venv/bin/activate" 21 | else 22 | log "Virtual environment not found. Please run setup_environment.sh first." 23 | exit 1 24 | fi 25 | 26 | # Run tests and log results 27 | pytest "$TEST_DIR" > "$LOG_FILE" 2>&1 28 | 29 | if [ $? -eq 0 ]; then 30 | log "All tests passed successfully." 31 | else 32 | log "Some tests failed. Check the log file for details: $LOG_FILE" 33 | exit 1 34 | fi 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 KOSASIH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/example_identity.py: -------------------------------------------------------------------------------- 1 | # examples/example_identity.py 2 | 3 | from src.identity import IdentityManager, UserAlreadyExistsError, UserNotFoundError 4 | 5 | def main(): 6 | # Create an instance of IdentityManager 7 | identity_manager = IdentityManager() 8 | 9 | # Example: User Registration 10 | try: 11 | user_id = identity_manager.register_user("john_doe", "password123", "john@example.com") 12 | print(f"User registered successfully with ID: {user_id}") 13 | except UserAlreadyExistsError as e: 14 | print(f"Registration failed: {e}") 15 | 16 | # Example: User Authentication 17 | try: 18 | user = identity_manager.authenticate_user("john_doe", "password123") 19 | print(f"User authenticated successfully: {user}") 20 | except UserNotFoundError as e: 21 | print(f"Authentication failed: {e}") 22 | 23 | # Example: Fetch User Profile 24 | try: 25 | profile = identity_manager.get_user_profile(user_id) 26 | print(f"User Profile: {profile}") 27 | except UserNotFoundError as e: 28 | print(f"Profile retrieval failed: {e}") 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /scripts/setup_environment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # setup_environment.sh - Environment setup script 4 | 5 | set -e # Exit immediately if a command exits with a non-zero status 6 | 7 | # Define variables 8 | VENV_DIR="venv" # Virtual environment directory 9 | REQUIREMENTS_FILE="requirements.txt" # Requirements file 10 | ENV_FILE=".env" # Environment file 11 | 12 | # Function to log messages 13 | log() { 14 | echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" 15 | } 16 | 17 | log "Setting up the environment..." 18 | 19 | # Create a virtual environment 20 | if [ ! -d "$VENV_DIR" ]; then 21 | log "Creating virtual environment..." 22 | python3 -m venv "$VENV_DIR" 23 | else 24 | log "Virtual environment already exists." 25 | fi 26 | 27 | # Activate the virtual environment 28 | source "$VENV_DIR/bin/activate" 29 | 30 | # Install dependencies 31 | log "Installing dependencies..." 32 | pip install -r "$REQUIREMENTS_FILE" 33 | 34 | # Create .env file if it doesn't exist 35 | if [ ! -f "$ENV_FILE" ]; then 36 | log "Creating environment file: $ENV_FILE" 37 | echo "DATABASE_URL=your_database_url" > "$ENV_FILE" 38 | echo "SECRET_KEY=your_secret_key" >> "$ENV_FILE" 39 | echo "DEBUG=True" >> "$ENV_FILE" 40 | else 41 | log "Environment file already exists." 42 | fi 43 | 44 | log "Environment setup completed successfully." 45 | -------------------------------------------------------------------------------- /src/utils/visualization.py: -------------------------------------------------------------------------------- 1 | # src/utils/visualization.py 2 | 3 | import matplotlib.pyplot as plt 4 | import seaborn as sns 5 | import pandas as pd 6 | 7 | def plot_histogram(df: pd.DataFrame, column: str, bins: int = 30) -> None: 8 | """Plot a histogram for a specified column in the DataFrame.""" 9 | plt.figure(figsize=(10, 6)) 10 | plt.hist(df[column], bins=bins, color='blue', alpha=0.7) 11 | plt.title(f'Histogram of {column}') 12 | plt.xlabel(column) 13 | plt.ylabel('Frequency') 14 | plt.grid(axis='y', alpha=0.75) 15 | plt.show() 16 | 17 | def plot_scatter(df: pd.DataFrame, x_column: str, y_column: str) -> None: 18 | """Plot a scatter plot for two specified columns in the DataFrame.""" 19 | plt.figure(figsize=(10, 6)) 20 | plt.scatter(df[x_column], df[y_column], alpha=0.6) 21 | plt.title(f'Scatter Plot of {x_column} vs {y_column}') 22 | plt.xlabel(x_column) 23 | plt.ylabel(y_column) 24 | plt.grid() 25 | plt.show() 26 | 27 | def plot_correlation_matrix(df: pd.DataFrame) -> None: 28 | """Plot a correlation matrix heatmap for the DataFrame.""" 29 | plt.figure(figsize=(12, 8)) 30 | correlation = df.corr() 31 | sns.heatmap(correlation, annot=True, fmt=".2f", cmap='coolwarm', square=True, cbar_kws={"shrink": .8}) 32 | plt.title('Correlation Matrix') 33 | plt.show() 34 | -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # deploy.sh - Deployment script for the application 4 | 5 | set -e # Exit immediately if a command exits with a non-zero status 6 | 7 | # Define variables 8 | APP_DIR="/path/to/your/app" # Change this to your application directory 9 | ENV_FILE=".env" # Environment file 10 | LOG_FILE="deploy.log" # Log file for deployment 11 | 12 | # Function to log messages 13 | log() { 14 | echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE" 15 | } 16 | 17 | # Load environment variables 18 | if [ -f "$APP_DIR/$ENV_FILE" ]; then 19 | export $(grep -v '^#' "$APP_DIR/$ENV_FILE" | xargs) 20 | else 21 | log "Environment file not found: $APP_DIR/$ENV_FILE" 22 | exit 1 23 | fi 24 | 25 | log "Starting deployment..." 26 | 27 | # Navigate to the application directory 28 | cd "$APP_DIR" 29 | 30 | # Pull the latest code from the repository 31 | log "Pulling latest code from repository..." 32 | git pull origin main 33 | 34 | # Install dependencies 35 | log "Installing dependencies..." 36 | pip install -r requirements.txt 37 | 38 | # Run database migrations 39 | log "Running database migrations..." 40 | python manage.py migrate 41 | 42 | # Start the application (example for a Flask app) 43 | log "Starting the application..." 44 | nohup python app.py > app.log 2>&1 & 45 | 46 | log "Deployment completed successfully." 47 | -------------------------------------------------------------------------------- /src/core/identity/user_roles.py: -------------------------------------------------------------------------------- 1 | # src/core/identity/user_roles.py 2 | 3 | class UserRoles: 4 | """Class for managing user roles and permissions.""" 5 | 6 | ROLES = { 7 | 'admin': 'Administrator with full access', 8 | 'editor': 'User with editing permissions', 9 | 'viewer': 'User with read-only access' 10 | } 11 | 12 | def __init__(self): 13 | self.user_roles = {} # In-memory storage for user roles 14 | 15 | def assign_role(self, username, role): 16 | """Assign a role to a user.""" 17 | if role not in self.ROLES: 18 | raise ValueError("Invalid role specified.") 19 | self.user_roles[username] = role 20 | return {"message": f"Role '{role}' assigned to user '{username}'."} 21 | 22 | def get_user_role(self, username): 23 | """Get the role of a user.""" 24 | return self.user_roles.get(username, "No role assigned") 25 | 26 | def has_permission(self, username, permission): 27 | """Check if a user has a specific permission.""" 28 | role = self.get_user_role(username) 29 | if role == 'admin': 30 | return True # Admin has all permissions 31 | elif role == 'editor' and permission in ['edit', 'view']: 32 | return True 33 | elif role == 'viewer' and permission == 'view': 34 | return True 35 | return False 36 | -------------------------------------------------------------------------------- /src/core/identity/token_manager.py: -------------------------------------------------------------------------------- 1 | # src/core/identity/token_manager.py 2 | 3 | import jwt 4 | import datetime 5 | import logging 6 | from flask import current_app 7 | 8 | class TokenManager: 9 | """Class for managing JWT tokens.""" 10 | 11 | def __init__(self): 12 | self.secret_key = current_app.config['SECRET_KEY'] 13 | self.algorithm = 'HS256' 14 | self.expiration_time = 3600 # Token expiration time in seconds (1 hour) 15 | 16 | def generate_token(self, username): 17 | """Generate a JWT token for a user.""" 18 | expiration = datetime.datetime.utcnow() + datetime.timedelta(seconds=self.expiration_time) 19 | token = jwt.encode({ 20 | 'sub': username, 21 | 'exp': expiration 22 | }, self.secret_key, algorithm=self.algorithm) 23 | logging.info("Token generated for user: %s", username) 24 | return token 25 | 26 | def verify_token(self, token): 27 | """Verify a JWT token.""" 28 | try: 29 | payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm]) 30 | logging.info("Token verified successfully for user: %s", payload['sub']) 31 | return payload['sub'] 32 | except jwt.ExpiredSignatureError: 33 | logging.warning("Token has expired.") 34 | return None 35 | except jwt.InvalidTokenError: 36 | logging.warning("Invalid token.") 37 | return None 38 | -------------------------------------------------------------------------------- /src/utils/data_processing.py: -------------------------------------------------------------------------------- 1 | # src/utils/data_processing.py 2 | 3 | import pandas as pd 4 | from sklearn.model_selection import train_test_split 5 | from sklearn.preprocessing import MinMaxScaler, StandardScaler 6 | 7 | def load_data(file_path: str) -> pd.DataFrame: 8 | """Load data from a CSV file.""" 9 | try: 10 | data = pd.read_csv(file_path) 11 | return data 12 | except Exception as e: 13 | raise ValueError(f"Error loading data: {e}") 14 | 15 | def clean_data(df: pd.DataFrame, drop_na: bool = True) -> pd.DataFrame: 16 | """Clean the DataFrame by dropping or filling missing values.""" 17 | if drop_na: 18 | return df.dropna() 19 | else: 20 | return df.fillna(df.mean()) 21 | 22 | def normalize_data(df: pd.DataFrame, method: str = 'minmax') -> pd.DataFrame: 23 | """Normalize the DataFrame using specified method.""" 24 | if method == 'minmax': 25 | scaler = MinMaxScaler() 26 | elif method == 'standard': 27 | scaler = StandardScaler() 28 | else: 29 | raise ValueError("Normalization method must be 'minmax' or 'standard'.") 30 | 31 | return pd.DataFrame(scaler.fit_transform(df), columns=df.columns) 32 | 33 | def split_data(df: pd.DataFrame, target_column: str, test_size: float = 0.2) -> tuple: 34 | """Split the DataFrame into features and target, then into training and testing sets.""" 35 | X = df.drop(columns=[target_column]) 36 | y = df[target_column] 37 | return train_test_split(X, y, test_size=test_size, random_state=42) 38 | -------------------------------------------------------------------------------- /src/main/config.py: -------------------------------------------------------------------------------- 1 | # src/main/config.py 2 | 3 | import os 4 | 5 | class Config: 6 | """Base configuration settings for the application.""" 7 | 8 | # General settings 9 | DEBUG = os.getenv('DEBUG', 'False') == 'True' 10 | SECRET_KEY = os.getenv('SECRET_KEY', 'your_secret_key_here') 11 | LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper() 12 | 13 | # Database settings 14 | SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', 'sqlite:///matrixai.db') 15 | SQLALCHEMY_TRACK_MODIFICATIONS = False # Disable track modifications for performance 16 | 17 | # API settings 18 | API_VERSION = os.getenv('API_VERSION', 'v1') 19 | MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # Limit request size to 16 MB 20 | 21 | # CORS settings 22 | CORS_ORIGINS = os.getenv('CORS_ORIGINS', '*') # Allow all origins by default 23 | 24 | class DevelopmentConfig(Config): 25 | """Development configuration settings.""" 26 | DEBUG = True 27 | SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DATABASE_URI', 'sqlite:///dev_matrixai.db') 28 | 29 | class TestingConfig(Config): 30 | """Testing configuration settings.""" 31 | TESTING = True 32 | SQLALCHEMY_DATABASE_URI = os.getenv('TEST_DATABASE_URI', 'sqlite:///test_matrixai.db') 33 | 34 | class ProductionConfig(Config): 35 | """Production configuration settings.""" 36 | SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', 'sqlite:///matrixai.db') 37 | 38 | # Configuration selection based on environment variable 39 | config_type = os.getenv('FLASK_ENV', 'development').lower() 40 | if config_type == 'production': 41 | Config = ProductionConfig 42 | elif config_type == 'testing': 43 | Config = TestingConfig 44 | else: 45 | Config = DevelopmentConfig 46 | -------------------------------------------------------------------------------- /src/main/__init__.py: -------------------------------------------------------------------------------- 1 | # src/main/__init__.py 2 | 3 | """ 4 | MatrixAI-Core Main Package 5 | 6 | This package serves as the core of the MatrixAI decentralized trust verification system. 7 | It includes the main application logic, configuration settings, logging utilities, and 8 | API endpoints for user identity verification, risk assessment, and reputation management. 9 | 10 | Version: 0.2.0 11 | Author: Your Name 12 | Email: your-email@example.com 13 | License: MIT 14 | """ 15 | 16 | import os 17 | import logging 18 | 19 | # Package metadata 20 | __version__ = "0.2.0" 21 | __author__ = "Your Name" 22 | __email__ = "your-email@example.com" 23 | __license__ = "MIT" 24 | 25 | # Set up advanced logging 26 | def setup_logging(): 27 | """Set up logging configuration with advanced features.""" 28 | log_level = os.getenv('LOG_LEVEL', 'INFO').upper() 29 | logging.basicConfig( 30 | level=log_level, 31 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 32 | handlers=[ 33 | logging.StreamHandler(), 34 | logging.FileHandler('matrixai.log'), 35 | logging.handlers.RotatingFileHandler( 36 | 'matrixai_rotating.log', maxBytes=10*1024*1024, backupCount=5 37 | ) 38 | ] 39 | ) 40 | logging.info("Logging is set up with level: %s", log_level) 41 | 42 | # Initialize logging 43 | setup_logging() 44 | 45 | # Import application components 46 | from .app import app # Import the Flask app 47 | from .config import Config # Import configuration settings 48 | from .logger import setup_logging # Import logging setup 49 | 50 | # Initialize the application 51 | def create_app(): 52 | """Create and configure the Flask application.""" 53 | app = Flask(__name__) 54 | app.config.from_object(Config) 55 | setup_logging() 56 | return app 57 | 58 | # Initialize the application instance 59 | app = create_app() 60 | -------------------------------------------------------------------------------- /docs/user_guide.md: -------------------------------------------------------------------------------- 1 | # User and Developer Guide 2 | 3 | ## Introduction 4 | 5 | This guide provides instructions for both users and developers on how to effectively use and contribute to the MatrixAI-Core system. 6 | 7 | ## User Guide 8 | 9 | ### 1. Creating an Account 10 | 11 | 1. Go to the MatrixAI-Core website and click on "Sign Up". 12 | 2. Fill in the registration form with your username, email, and password. 13 | 3. Verify your email address by clicking on the link sent to you. 14 | 15 | ### 2. Managing Your Identity 16 | 17 | 1. Log in to your account and navigate to the "Identity" section. 18 | 2. Update your profile information, such as your username or email. 19 | 3. Manage your identity verification status. 20 | 21 | ### 3. Viewing Your Reputation Score 22 | 23 | 1. Log in to your account and navigate to the "Reputation" section. 24 | 2. View your current reputation score and its history. 25 | 26 | ## Developer Guide 27 | 28 | ### 1. Setting Up the Development Environment 29 | 30 | 1. Clone the MatrixAI-Core repository: `git clone https://github.com/KOSASIH/MatrixAI-Core.git` 31 | 2. Install the required dependencies: `pip install -r requirements.txt` 32 | 3. Set up the environment: `./scripts/setup_environment.sh` 33 | 34 | ### 2. Contributing to the Codebase 35 | 36 | 1. Read the [Contributing Guidelines](CONTRIBUTING.md) for more information. 37 | 2. Create a new branch for your changes: `git checkout -b feature/new-feature` 38 | 3. Make your changes and commit them: `git commit -m "Added new feature"` 39 | 4. Create a pull request to merge your changes. 40 | 41 | ### 3. Using the API 42 | 43 | 1. Read the [API Reference](API_reference.md) for a comprehensive overview of the available endpoints. 44 | 2. Use the API to integrate MatrixAI-Core with your application. 45 | 46 | ## Conclusion 47 | 48 | This user and developer guide provides a comprehensive overview of how to use and contribute to the MatrixAI-Core system. For further assistance or questions, please reach out to [your-email@example.com]. 49 | -------------------------------------------------------------------------------- /src/main/logger.py: -------------------------------------------------------------------------------- 1 | # src/main/logger.py 2 | 3 | import logging 4 | import os 5 | import sys 6 | from logging.handlers import RotatingFileHandler, SMTPHandler 7 | 8 | def setup_logging(): 9 | """Set up logging configuration with advanced features.""" 10 | log_level = os.getenv('LOG_LEVEL', 'INFO').upper() 11 | 12 | # Create a logger 13 | logger = logging.getLogger() 14 | logger.setLevel(log_level) 15 | 16 | # Create console handler for output to stdout 17 | console_handler = logging.StreamHandler(sys.stdout) 18 | console_handler.setLevel(log_level) 19 | console_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 20 | console_handler.setFormatter(console_formatter) 21 | logger.addHandler(console_handler) 22 | 23 | # Create file handler for logging to a file 24 | file_handler = RotatingFileHandler('matrixai.log', maxBytes=10*1024*1024, backupCount=5) 25 | file_handler.setLevel(log_level) 26 | file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 27 | file_handler.setFormatter(file_formatter) 28 | logger.addHandler(file_handler) 29 | 30 | # Optional: Email notifications for critical errors 31 | if os.getenv('MAIL_SERVER'): 32 | mail_handler = SMTPHandler( 33 | mailhost=(os.getenv('MAIL_SERVER'), int(os.getenv('MAIL_PORT', 25))), 34 | fromaddr=os.getenv('MAIL_FROM'), 35 | toaddrs=os.getenv('MAIL_TO').split(','), 36 | subject='Critical Error in MatrixAI-Core', 37 | credentials=(os.getenv('MAIL_USERNAME'), os.getenv('MAIL_PASSWORD')), 38 | secure=None 39 | ) 40 | mail_handler.setLevel(logging.ERROR) 41 | mail_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s\n%(message)s') 42 | mail_handler.setFormatter(mail_formatter) 43 | logger.addHandler(mail_handler) 44 | 45 | logging.info("Logging is set up with level: %s", log_level) 46 | 47 | # Example usage of the logger 48 | if __name__ == "__main__": 49 | setup_logging() 50 | logging.info("Logger is set up and ready to use.") 51 | -------------------------------------------------------------------------------- /src/core/smart_contracts/contract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/access/Ownable.sol"; 5 | import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; 6 | import "@openzeppelin/contracts/utils/Strings.sol"; 7 | 8 | contract MySmartContract is Ownable, Initializable { 9 | using Strings for uint256; 10 | 11 | event ValueChanged(uint256 indexed oldValue, uint256 indexed newValue); 12 | event ContractUpgraded(address indexed newImplementation); 13 | 14 | uint256 private value; 15 | 16 | // Optional: Store a version number for the contract 17 | string public version; 18 | 19 | // Optional: Mapping to store additional data 20 | mapping(address => uint256) public balances; 21 | 22 | // Initializer function for upgradable contracts 23 | function initialize(uint256 initialValue, string memory contractVersion) public initializer { 24 | value = initialValue; 25 | version = contractVersion; 26 | } 27 | 28 | function setValue(uint256 newValue) public onlyOwner { 29 | uint256 oldValue = value; 30 | value = newValue; 31 | emit ValueChanged(oldValue, newValue); 32 | } 33 | 34 | function getValue() public view returns (uint256) { 35 | return value; 36 | } 37 | 38 | function deposit() public payable { 39 | require(msg.value > 0, "Must send ETH to deposit"); 40 | balances[msg.sender] += msg.value; 41 | } 42 | 43 | function withdraw(uint256 amount) public { 44 | require(balances[msg.sender] >= amount, "Insufficient balance"); 45 | balances[msg.sender] -= amount; 46 | payable(msg.sender).transfer(amount); 47 | } 48 | 49 | function getBalance() public view returns (uint256) { 50 | return balances[msg.sender]; 51 | } 52 | 53 | // Function to upgrade the contract (for demonstration purposes) 54 | function upgradeContract(address newImplementation) public onlyOwner { 55 | require(newImplementation != address(0), "Invalid address"); 56 | emit ContractUpgraded(newImplementation); 57 | // Logic to upgrade the contract would go here (e.g., using a proxy pattern) 58 | } 59 | 60 | // Utility function to get the contract version 61 | function getVersion() public view returns (string memory) { 62 | return version; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /docs/architecture.md: -------------------------------------------------------------------------------- 1 | # System Architecture Overview 2 | 3 | ## Introduction 4 | 5 | The MatrixAI-Core system architecture is designed to provide a robust, scalable, and secure framework for decentralized trust verification. The architecture leverages a combination of blockchain technology, artificial intelligence, and modular design principles to ensure high performance and reliability. 6 | 7 | ## Components 8 | 9 | ### 1. User Interface (UI) 10 | 11 | - **Web Application**: A responsive web application that allows users to interact with the MatrixAI system, manage their identities, and view their reputation scores. 12 | - **Mobile Application**: A mobile app for on-the-go access to identity verification and risk assessment features. 13 | 14 | ### 2. Backend Services 15 | 16 | - **Identity Verification Service**: Handles user identity creation, verification, and management using cryptographic techniques. 17 | - **Risk Assessment Engine**: Analyzes user behavior and interactions to assess risk levels and detect anomalies. 18 | - **Reputation Management System**: Calculates and updates user reputation scores based on interactions and feedback. 19 | 20 | ### 3. Blockchain Layer 21 | 22 | - **Smart Contracts**: Deployed on a blockchain to automate transactions and enforce rules without intermediaries. 23 | - **Decentralized Storage**: Utilizes decentralized storage solutions for secure and tamper-proof data storage. 24 | 25 | ### 4. AI and Machine Learning 26 | 27 | - **Risk Analysis Algorithms**: Machine learning models that evaluate user behavior and predict potential risks. 28 | - **Reputation Scoring Algorithms**: AI-driven algorithms that dynamically adjust reputation scores based on user interactions. 29 | 30 | ## Data Flow 31 | 32 | 1. Users interact with the UI to create or manage their identities. 33 | 2. The UI communicates with the backend services to process requests. 34 | 3. The Identity Verification Service verifies user identities and stores data on the blockchain. 35 | 4. The Risk Assessment Engine continuously monitors user behavior and updates risk levels. 36 | 5. The Reputation Management System calculates and updates reputation scores based on user interactions. 37 | 6. Smart contracts facilitate secure transactions and enforce rules. 38 | 39 | ## Conclusion 40 | 41 | The MatrixAI-Core architecture is designed to be modular and extensible, allowing for future enhancements and integrations. This architecture ensures that the system remains secure, efficient, and user-friendly. 42 | -------------------------------------------------------------------------------- /src/core/risk_assessment/__init__.py: -------------------------------------------------------------------------------- 1 | # src/core/risk_assessment/__init__.py 2 | 3 | import logging 4 | 5 | from .risk_analyzer import RiskAnalyzer 6 | from .anomaly_detection import AnomalyDetector 7 | 8 | __all__ = ['RiskAnalyzer', 'AnomalyDetector'] 9 | 10 | # Set up logging for the risk assessment module 11 | logging.basicConfig( 12 | level=logging.INFO, 13 | format='%(asctime)s - %(levelname)s - %(message)s', 14 | handlers=[ 15 | logging.FileHandler("risk_assessment.log"), 16 | logging.StreamHandler() 17 | ] 18 | ) 19 | 20 | # Module version 21 | __version__ = "1.0.0" 22 | 23 | def initialize_risk_assessment(): 24 | """Initialize the risk assessment module.""" 25 | logging.info("Initializing the Risk Assessment module.") 26 | risk_analyzer = RiskAnalyzer() 27 | anomaly_detector = AnomalyDetector() 28 | logging.info("Risk Assessment module initialized successfully.") 29 | return risk_analyzer, anomaly_detector 30 | 31 | def load_data(file_path): 32 | """Load data from a CSV file.""" 33 | try: 34 | data = pd.read_csv(file_path) 35 | logging.info("Data loaded successfully from %s", file_path) 36 | return data 37 | except Exception as e: 38 | logging.error("Error loading data from %s: %s", file_path, str(e)) 39 | raise 40 | 41 | def preprocess_data(data, target_column): 42 | """Preprocess data for analysis.""" 43 | try: 44 | features = data.drop(columns=[target_column]) 45 | target = data[target_column] 46 | logging.info("Data preprocessed successfully.") 47 | return features, target 48 | except KeyError as e: 49 | logging.error("Error in preprocessing data: %s", str(e)) 50 | raise 51 | 52 | def save_model(model, file_path): 53 | """Save the trained model to a file.""" 54 | import joblib 55 | try: 56 | joblib.dump(model, file_path) 57 | logging.info("Model saved successfully to %s", file_path) 58 | except Exception as e: 59 | logging.error("Error saving model to %s: %s", file_path, str(e)) 60 | raise 61 | 62 | def load_model(file_path): 63 | """Load a trained model from a file.""" 64 | import joblib 65 | try: 66 | model = joblib.load(file_path) 67 | logging.info("Model loaded successfully from %s", file_path) 68 | return model 69 | except Exception as e: 70 | logging.error("Error loading model from %s: %s", file_path, str(e)) 71 | raise 72 | -------------------------------------------------------------------------------- /src/core/reputation/__init__.py: -------------------------------------------------------------------------------- 1 | # reputation/__init__.py 2 | 3 | import logging 4 | import os 5 | import json 6 | 7 | # Set up logging for the reputation module 8 | def setup_logging(log_file='reputation.log', log_level=logging.INFO): 9 | """Set up logging configuration.""" 10 | logging.basicConfig( 11 | level=log_level, 12 | format='%(asctime)s - %(levelname)s - %(message)s', 13 | handlers=[ 14 | logging.FileHandler(log_file), 15 | logging.StreamHandler() 16 | ] 17 | ) 18 | logging.info("Logging initialized.") 19 | 20 | # Load configuration from a JSON file 21 | def load_config(config_file='config.json'): 22 | """Load configuration settings from a JSON file.""" 23 | if os.path.exists(config_file): 24 | with open(config_file, 'r') as f: 25 | config = json.load(f) 26 | logging.info("Configuration loaded from %s.", config_file) 27 | return config 28 | else: 29 | logging.warning("Configuration file %s not found. Using default settings.", config_file) 30 | return {} 31 | 32 | # Initialize the reputation module 33 | def initialize_reputation_module(config_file='config.json'): 34 | """Initialize the reputation module with logging and configuration.""" 35 | setup_logging() 36 | config = load_config(config_file) 37 | logging.info("Reputation module initialized with version %s.", __version__) 38 | return config 39 | 40 | __version__ = "1.0.0" 41 | 42 | # Example of a function to validate configuration settings 43 | def validate_config(config): 44 | """Validate the loaded configuration settings.""" 45 | required_keys = ['default_algorithm', 'log_level'] 46 | for key in required_keys: 47 | if key not in config: 48 | logging.error("Missing required configuration key: %s", key) 49 | raise ValueError(f"Missing required configuration key: {key}") 50 | logging.info("Configuration validated successfully.") 51 | 52 | # Example of a function to set default values for configuration 53 | def set_default_config(): 54 | """Set default configuration values.""" 55 | default_config = { 56 | 'default_algorithm': 'SimpleAverageScore', 57 | 'log_level': 'INFO' 58 | } 59 | with open('config.json', 'w') as f: 60 | json.dump(default_config, f, indent=4) 61 | logging.info("Default configuration created.") 62 | 63 | # Check if the config file exists, if not create it 64 | if not os.path.exists('config.json'): 65 | set_default_config() 66 | -------------------------------------------------------------------------------- /src/tests/test_risk_assessment.py: -------------------------------------------------------------------------------- 1 | # src/tests/test_risk_assessment.py 2 | 3 | import pytest 4 | from src.core.risk_assessment import RiskAssessment, InvalidUser DataError 5 | 6 | @pytest.fixture 7 | def risk_assessment(): 8 | """Fixture to create an instance of RiskAssessment for testing.""" 9 | return RiskAssessment() 10 | 11 | def test_assess_low_risk(risk_assessment): 12 | """Test assessing a user with low risk.""" 13 | user_data = {"credit_score": 750, "transaction_history": "good"} 14 | risk = risk_assessment.assess(user_data) 15 | assert risk == "low" 16 | 17 | def test_assess_medium_risk(risk_assessment): 18 | """Test assessing a user with medium risk.""" 19 | user_data = {"credit_score": 650, "transaction_history": "average"} 20 | risk = risk_assessment.assess(user_data) 21 | assert risk == "medium" 22 | 23 | def test_assess_high_risk(risk_assessment): 24 | """Test assessing a user with high risk.""" 25 | user_data = {"credit_score": 500, "transaction_history": "poor"} 26 | risk = risk_assessment.assess(user_data) 27 | assert risk == "high" 28 | 29 | def test_assess_invalid_user_data(risk_assessment): 30 | """Test assessing with invalid user data.""" 31 | invalid_user_data = {"credit_score": "not_a_number", "transaction_history": "good"} 32 | with pytest.raises(InvalidUser DataError): 33 | risk_assessment.assess(invalid_user_data) 34 | 35 | def test_assess_missing_credit_score(risk_assessment): 36 | """Test assessing a user with missing credit score.""" 37 | user_data = {"transaction_history": "good"} 38 | with pytest.raises(InvalidUser DataError): 39 | risk_assessment.assess(user_data) 40 | 41 | def test_assess_missing_transaction_history(risk_assessment): 42 | """Test assessing a user with missing transaction history.""" 43 | user_data = {"credit_score": 700} 44 | with pytest.raises(InvalidUser DataError): 45 | risk_assessment.assess(user_data) 46 | 47 | def test_assess_edge_case_high_credit_score(risk_assessment): 48 | """Test assessing a user with an edge case high credit score.""" 49 | user_data = {"credit_score": 850, "transaction_history": "excellent"} 50 | risk = risk_assessment.assess(user_data) 51 | assert risk == "low" 52 | 53 | def test_assess_edge_case_low_credit_score(risk_assessment): 54 | """Test assessing a user with an edge case low credit score.""" 55 | user_data = {"credit_score": 300, "transaction_history": "very poor"} 56 | risk = risk_assessment.assess(user_data) 57 | assert risk == "high" 58 | -------------------------------------------------------------------------------- /docs/API_reference.md: -------------------------------------------------------------------------------- 1 | # API Reference 2 | 3 | ## Overview 4 | 5 | The MatrixAI-Core API provides a set of endpoints for interacting with the identity verification, risk assessment, and reputation management services. All API requests and responses are in JSON format. 6 | 7 | ## Base URL 8 | 9 | [https://api.matrixai-core.example.com/v1](https://api.matrixai-core.example.com/v1) 10 | 11 | 12 | ## Authentication 13 | 14 | All API requests require an API key. Include the API key in the request header: 15 | 16 | ``` 17 | Authorization: Bearer YOUR_API_KEY 18 | ``` 19 | 20 | 21 | ## Endpoints 22 | 23 | ### 1. User Identity 24 | 25 | #### Create User Identity 26 | 27 | - **POST** `/identity/create` 28 | - **Description**: Creates a new user identity. 29 | - **Request Body**: 30 | ```json 31 | { 32 | "username": "string", 33 | "email": "string", 34 | "password": "string" 35 | } 36 | ``` 37 | - **Response**: 38 | ```json 39 | { 40 | "status": "success", 41 | "userId": "string" 42 | } 43 | ``` 44 | 45 | #### Verify User Identity 46 | 47 | - **POST** `/identity/verify` 48 | - **Description**: Verifies a user's identity. 49 | - **Request Body**: 50 | ```json 51 | { 52 | "userId": "string", 53 | "verificationCode": "string" 54 | } 55 | ``` 56 | - **Response**: 57 | ```json 58 | { 59 | "status": "verified" 60 | } 61 | ``` 62 | 63 | ### 2. Risk Assessment 64 | 65 | #### Get Risk Level 66 | 67 | - **GET** `/risk/level/{userId}` 68 | - **Description**: Retrieves the current risk level for a user. 69 | - **Response**: 70 | ```json 71 | { 72 | "userId": "string", 73 | "riskLevel": "low|medium|high" 74 | } 75 | ``` 76 | 77 | ### 3. Reputation Management 78 | 79 | #### Get Reputation Score 80 | 81 | - **GET** `/reputation/score/{userId}` 82 | - **Description**: Retrieves the reputation score for a user. 83 | - **Response**: 84 | ```json 85 | { 86 | "userId": "string", 87 | "reputationScore": "number" 88 | } 89 | ``` 90 | 91 | ## Error Handling 92 | 93 | All error responses will include a status code and a message. For example: 94 | 95 | ```json 96 | { 97 | "status": "error", 98 | "message": "Invalid request" 99 | } 100 | ``` 101 | 102 | # Conclusion 103 | This API reference provides a comprehensive overview of the available endpoints in the MatrixAI-Core system. For further details or updates, please refer to the official documentation. 104 | -------------------------------------------------------------------------------- /src/tests/test_reputation.py: -------------------------------------------------------------------------------- 1 | # src/tests/test_reputation.py 2 | 3 | import pytest 4 | from src.core.reputation import ReputationManager, UserNotFoundError 5 | 6 | @pytest.fixture 7 | def reputation_manager(): 8 | """Fixture to create an instance of ReputationManager for testing.""" 9 | return ReputationManager() 10 | 11 | def test_initialize_reputation(reputation_manager): 12 | """Test initializing a user's reputation.""" 13 | user_id = "user_123" 14 | reputation_manager.initialize_reputation(user_id) 15 | assert reputation_manager.get_reputation(user_id) == 0 16 | 17 | def test_update_reputation_positive(reputation_manager): 18 | """Test updating a user's reputation positively.""" 19 | user_id = "user_123" 20 | reputation_manager.initialize_reputation(user_id) 21 | reputation_manager.update_reputation(user_id, 10) 22 | assert reputation_manager.get_reputation(user_id) == 10 23 | 24 | def test_update_reputation_negative(reputation_manager): 25 | """Test updating a user's reputation negatively.""" 26 | user_id = "user_123" 27 | reputation_manager.initialize_reputation(user_id) 28 | reputation_manager.update_reputation(user_id, -5) 29 | assert reputation_manager.get_reputation(user_id) == -5 30 | 31 | def test_update_reputation_multiple_updates(reputation_manager): 32 | """Test multiple updates to a user's reputation.""" 33 | user_id = "user_123" 34 | reputation_manager.initialize_reputation(user_id) 35 | reputation_manager.update_reputation(user_id, 10) 36 | reputation_manager.update_reputation(user_id, -3) 37 | reputation_manager.update_reputation(user_id, 5) 38 | assert reputation_manager.get_reputation(user_id) == 12 # 10 - 3 + 5 39 | 40 | def test_get_reputation_user_not_found(reputation_manager): 41 | """Test getting reputation for a non-existent user.""" 42 | with pytest.raises(UserNotFoundError): 43 | reputation_manager.get_reputation("non_existent_user") 44 | 45 | def test_initialize_reputation_already_exists(reputation_manager): 46 | """Test initializing reputation for a user that already exists.""" 47 | user_id = "user_123" 48 | reputation_manager.initialize_reputation(user_id) 49 | with pytest.raises(ValueError): 50 | reputation_manager.initialize_reputation(user_id) 51 | 52 | def test_update_reputation_user_not_found(reputation_manager): 53 | """Test updating reputation for a non-existent user.""" 54 | with pytest.raises(UserNotFoundError): 55 | reputation_manager.update_reputation("non_existent_user", 10) 56 | 57 | def test_reputation_bounds(reputation_manager): 58 | """Test that reputation does not exceed defined bounds.""" 59 | user_id = "user_123" 60 | reputation_manager.initialize_reputation(user_id) 61 | reputation_manager.update_reputation(user_id, 100) # Assuming max reputation is 100 62 | assert reputation_manager.get_reputation(user_id) <= 100 63 | 64 | reputation_manager.update_reputation(user_id, -200) # Assuming min reputation is -100 65 | assert reputation_manager.get_reputation(user_id) >= -100 66 | -------------------------------------------------------------------------------- /src/core/identity/cryptography.py: -------------------------------------------------------------------------------- 1 | # src/core/identity/cryptography.py 2 | 3 | import bcrypt 4 | import os 5 | import logging 6 | from hashlib import pbkdf2_hmac 7 | 8 | class Cryptography: 9 | """Class for cryptographic functions.""" 10 | 11 | def __init__(self): 12 | self.salt_length = 16 # Length of the salt 13 | self.iterations = 100000 # Number of iterations for PBKDF2 14 | self.hash_algorithm = 'sha256' # Hash algorithm for PBKDF2 15 | 16 | def generate_salt(self): 17 | """Generate a random salt.""" 18 | salt = os.urandom(self.salt_length) 19 | return salt 20 | 21 | def hash_password(self, password): 22 | """Hash a password using bcrypt and PBKDF2.""" 23 | if not password: 24 | logging.error("Password cannot be empty.") 25 | raise ValueError("Password cannot be empty.") 26 | 27 | # Generate a salt 28 | salt = self.generate_salt() 29 | # Hash the password using PBKDF2 30 | password_hash = pbkdf2_hmac( 31 | self.hash_algorithm, 32 | password.encode('utf-8'), 33 | salt, 34 | self.iterations 35 | ) 36 | # Combine salt and hash for storage 37 | hashed_password = salt + password_hash 38 | logging.info("Password hashed successfully.") 39 | return hashed_password 40 | 41 | def verify_password(self, password, hashed): 42 | """Verify a password against a hashed password.""" 43 | if not hashed: 44 | logging.error("Hashed password cannot be empty.") 45 | raise ValueError("Hashed password cannot be empty.") 46 | 47 | # Extract the salt from the stored hash 48 | salt = hashed[:self.salt_length] 49 | stored_hash = hashed[self.salt_length:] 50 | 51 | # Hash the provided password with the extracted salt 52 | password_hash = pbkdf2_hmac( 53 | self.hash_algorithm, 54 | password.encode('utf-8'), 55 | salt, 56 | self.iterations 57 | ) 58 | 59 | if password_hash == stored_hash: 60 | logging.info("Password verification successful.") 61 | return True 62 | logging.warning("Password verification failed.") 63 | return False 64 | 65 | def hash_with_bcrypt(self, password): 66 | """Hash a password using bcrypt.""" 67 | if not password: 68 | logging.error("Password cannot be empty.") 69 | raise ValueError("Password cannot be empty.") 70 | 71 | hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) 72 | logging.info("Password hashed with bcrypt successfully.") 73 | return hashed.decode('utf-8') 74 | 75 | def verify_with_bcrypt(self, password, hashed): 76 | """Verify a password against a bcrypt hashed password.""" 77 | if bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8')): 78 | logging.info("Password verification with bcrypt successful.") 79 | return True 80 | logging.warning("Password verification with bcrypt failed.") 81 | return False 82 | -------------------------------------------------------------------------------- /src/main/app.py: -------------------------------------------------------------------------------- 1 | # src/main/app.py 2 | 3 | from flask import Flask, jsonify, request 4 | from flask_sqlalchemy import SQLAlchemy 5 | from config import Config 6 | from logger import setup_logging 7 | import logging 8 | 9 | # Initialize the Flask application 10 | app = Flask(__name__) 11 | app.config.from_object(Config) 12 | 13 | # Set up logging 14 | setup_logging() 15 | 16 | # Initialize the database 17 | db = SQLAlchemy(app) 18 | 19 | # Database model for User 20 | class User(db.Model): 21 | """User model for storing user information.""" 22 | id = db.Column(db.Integer, primary_key=True) 23 | username = db.Column(db.String(80), unique=True, nullable=False) 24 | email = db.Column(db.String(120), unique=True, nullable=False) 25 | password_hash = db.Column(db.String(128), nullable=False) 26 | 27 | def __repr__(self): 28 | return f'' 29 | 30 | @app.route('/') 31 | def home(): 32 | return jsonify({"message": "Welcome to MatrixAI-Core API!"}) 33 | 34 | @app.route('/health', methods=['GET']) 35 | def health_check(): 36 | return jsonify({"status": "healthy"}), 200 37 | 38 | @app.route('/users', methods=['POST']) 39 | def create_user(): 40 | """Create a new user.""" 41 | data = request.get_json() 42 | username = data.get('username') 43 | email = data.get('email') 44 | password = data.get('password') 45 | 46 | if not username or not email or not password: 47 | logging.warning("Missing user data: %s", data) 48 | return jsonify({"error": "Missing username, email, or password"}), 400 49 | 50 | # Check if user already exists 51 | existing_user = User.query.filter((User .username == username) | (User .email == email)).first() 52 | if existing_user: 53 | logging.warning("User already exists: %s", username) 54 | return jsonify({"error": "User already exists"}), 409 55 | 56 | # Create new user 57 | new_user = User(username=username, email=email, password_hash=password) # Hash the password in a real app 58 | db.session.add(new_user) 59 | db.session.commit() 60 | 61 | logging.info("User created: %s", username) 62 | return jsonify({"message": "User created successfully", "userId": new_user.id}), 201 63 | 64 | @app.route('/users/', methods=['GET']) 65 | def get_user(user_id): 66 | """Retrieve user information by ID.""" 67 | user = User.query.get(user_id) 68 | if not user: 69 | logging.warning("User not found: %d", user_id) 70 | return jsonify({"error": "User not found"}), 404 71 | 72 | return jsonify({ 73 | "id": user.id, 74 | "username": user.username, 75 | "email": user.email 76 | }), 200 77 | 78 | @app.errorhandler(404) 79 | def not_found(error): 80 | """Handle 404 errors.""" 81 | return jsonify({"error": "Not found"}), 404 82 | 83 | @app.errorhandler(500) 84 | def internal_error(error): 85 | """Handle 500 errors.""" 86 | logging.error("Internal server error: %s", error) 87 | return jsonify({"error": "Internal server error"}), 500 88 | 89 | if __name__ == '__main__': 90 | with app.app_context(): 91 | db.create_all() # Create database tables 92 | app.run(host='0.0.0.0', port=5000) 93 | -------------------------------------------------------------------------------- /src/tests/test_identity.py: -------------------------------------------------------------------------------- 1 | # src/tests/test_identity.py 2 | 3 | import pytest 4 | from src.core.identity import IdentityManager, UserAlreadyExistsError, UserNotFoundError, InvalidCredentialsError 5 | 6 | @pytest.fixture 7 | def identity_manager(): 8 | """Fixture to create an instance of IdentityManager for testing.""" 9 | return IdentityManager() 10 | 11 | def test_register_user(identity_manager): 12 | """Test user registration.""" 13 | user_id = identity_manager.register_user("test_user", "password123") 14 | assert user_id is not None 15 | user = identity_manager.get_user(user_id) 16 | assert user["username"] == "test_user" 17 | assert user["user_id"] == user_id 18 | 19 | def test_register_user_already_exists(identity_manager): 20 | """Test registering a user that already exists.""" 21 | identity_manager.register_user("test_user", "password123") 22 | with pytest.raises(UserAlreadyExistsError): 23 | identity_manager.register_user("test_user", "password123") 24 | 25 | def test_authenticate_user_success(identity_manager): 26 | """Test successful user authentication.""" 27 | identity_manager.register_user("test_user", "password123") 28 | assert identity_manager.authenticate("test_user", "password123") is True 29 | 30 | def test_authenticate_user_failure(identity_manager): 31 | """Test authentication failure with wrong password.""" 32 | identity_manager.register_user("test_user", "password123") 33 | assert identity_manager.authenticate("test_user", "wrong_password") is False 34 | 35 | def test_authenticate_user_not_found(identity_manager): 36 | """Test authentication for a non-existent user.""" 37 | with pytest.raises(UserNotFoundError): 38 | identity_manager.authenticate("non_existent_user", "password123") 39 | 40 | def test_get_user(identity_manager): 41 | """Test retrieving user information.""" 42 | user_id = identity_manager.register_user("test_user", "password123") 43 | user = identity_manager.get_user(user_id) 44 | assert user["username"] == "test_user" 45 | assert user["user_id"] == user_id 46 | 47 | def test_get_user_not_found(identity_manager): 48 | """Test retrieving a non-existent user.""" 49 | with pytest.raises(UserNotFoundError): 50 | identity_manager.get_user("non_existent_user_id") 51 | 52 | def test_change_password(identity_manager): 53 | """Test changing a user's password.""" 54 | identity_manager.register_user("test_user", "password123") 55 | identity_manager.change_password("test_user", "new_password123") 56 | assert identity_manager.authenticate("test_user", "new_password123") is True 57 | assert identity_manager.authenticate("test_user", "password123") is False 58 | 59 | def test_change_password_user_not_found(identity_manager): 60 | """Test changing password for a non-existent user.""" 61 | with pytest.raises(UserNotFoundError): 62 | identity_manager.change_password("non_existent_user", "new_password123") 63 | 64 | def test_change_password_invalid_credentials(identity_manager): 65 | """Test changing password with invalid current password.""" 66 | identity_manager.register_user("test_user", "password123") 67 | with pytest.raises(InvalidCredentialsError): 68 | identity_manager.change_password("test_user", "wrong_password") 69 | -------------------------------------------------------------------------------- /src/tests/test_smart_contracts.py: -------------------------------------------------------------------------------- 1 | # src/tests/test_smart_contracts.py 2 | 3 | import pytest 4 | from src.core.smart_contracts import SmartContractManager, ContractNotFoundError, InvalidContractError 5 | 6 | @pytest.fixture 7 | def contract_manager(): 8 | """Fixture to create an instance of SmartContractManager for testing.""" 9 | return SmartContractManager() 10 | 11 | def test_deploy_contract(contract_manager): 12 | """Test deploying a new smart contract.""" 13 | contract_code = "function test() { return true; }" 14 | contract_id = contract_manager.deploy_contract(contract_code) 15 | assert contract_id is not None 16 | assert contract_manager.get_contract(contract_id)["code"] == contract_code 17 | 18 | def test_deploy_invalid_contract(contract_manager): 19 | """Test deploying an invalid smart contract.""" 20 | invalid_contract_code = "invalid code" 21 | with pytest.raises(InvalidContractError): 22 | contract_manager.deploy_contract(invalid_contract_code) 23 | 24 | def test_execute_contract(contract_manager): 25 | """Test executing a deployed smart contract.""" 26 | contract_code = "function test() { return true; }" 27 | contract_id = contract_manager.deploy_contract(contract_code) 28 | result = contract_manager.execute_contract(contract_id, "test") 29 | assert result is True 30 | 31 | def test_execute_non_existent_contract(contract_manager): 32 | """Test executing a non-existent smart contract.""" 33 | with pytest.raises(ContractNotFoundError): 34 | contract_manager.execute_contract("non_existent_contract_id", "test") 35 | 36 | def test_get_contract(contract_manager): 37 | """Test retrieving a deployed smart contract.""" 38 | contract_code = "function test() { return true; }" 39 | contract_id = contract_manager.deploy_contract(contract_code) 40 | contract = contract_manager.get_contract(contract_id) 41 | assert contract["id"] == contract_id 42 | assert contract["code"] == contract_code 43 | 44 | def test_get_non_existent_contract(contract_manager): 45 | """Test retrieving a non-existent smart contract.""" 46 | with pytest.raises(ContractNotFoundError): 47 | contract_manager.get_contract("non_existent_contract_id") 48 | 49 | def test_update_contract(contract_manager): 50 | """Test updating an existing smart contract.""" 51 | contract_code = "function test() { return true; }" 52 | contract_id = contract_manager.deploy_contract(contract_code) 53 | new_contract_code = "function test() { return false; }" 54 | contract_manager.update_contract(contract_id, new_contract_code) 55 | assert contract_manager.get_contract(contract_id)["code"] == new_contract_code 56 | 57 | def test_update_non_existent_contract(contract_manager): 58 | """Test updating a non-existent smart contract.""" 59 | with pytest.raises(ContractNotFoundError): 60 | contract_manager.update_contract("non_existent_contract_id", "new code") 61 | 62 | def test_execute_contract_with_invalid_function(contract_manager): 63 | """Test executing a contract with an invalid function name.""" 64 | contract_code = "function test() { return true; }" 65 | contract_id = contract_manager.deploy_contract(contract_code) 66 | with pytest.raises(ValueError): 67 | contract_manager.execute_contract(contract_id, "non_existent_function") 68 | -------------------------------------------------------------------------------- /src/core/reputation/scoring_algorithm.py: -------------------------------------------------------------------------------- 1 | # reputation/scoring_algorithm.py 2 | 3 | import numpy as np 4 | import logging 5 | 6 | class ScoringAlgorithm: 7 | """Base class for scoring algorithms.""" 8 | def calculate_score(self, data: dict) -> float: 9 | """Calculate the reputation score based on input data.""" 10 | raise NotImplementedError("Subclasses should implement this method.") 11 | 12 | class SimpleAverageScore(ScoringAlgorithm): 13 | """Simple average scoring algorithm.""" 14 | def calculate_score(self, data: dict) -> float: 15 | """Calculate score as the average of the values in the data dictionary.""" 16 | if not data: 17 | logging.warning("No data provided for scoring.") 18 | return 0.0 19 | try: 20 | score = np.mean(list(data.values())) 21 | logging.info("Calculated Simple Average Score: %.2f", score) 22 | return score 23 | except Exception as e: 24 | logging.error("Error calculating Simple Average Score: %s", str(e)) 25 | return 0.0 26 | 27 | class WeightedScore(ScoringAlgorithm): 28 | """Weighted scoring algorithm.""" 29 | def calculate_score(self, data: dict, weights: dict = None) -> float: 30 | """Calculate score as a weighted sum of the values in the data dictionary.""" 31 | if weights is None: 32 | weights = {key: 1 for key in data.keys()} # Default weights 33 | try: 34 | score = sum(data[key] * weights.get(key, 0) for key in data.keys()) 35 | logging.info("Calculated Weighted Score: %.2f", score) 36 | return score 37 | except Exception as e: 38 | logging.error("Error calculating Weighted Score: %s", str(e)) 39 | return 0.0 40 | 41 | class ExponentialDecayScore(ScoringAlgorithm): 42 | """Exponential decay scoring algorithm.""" 43 | def calculate_score(self, data: dict, decay_rate: float = 0.1) -> float: 44 | """Calculate score using an exponential decay formula.""" 45 | if not data: 46 | logging.warning("No data provided for scoring.") 47 | return 0.0 48 | try: 49 | scores = [value * np.exp(-decay_rate * idx) for idx, value in enumerate(data.values())] 50 | final_score = sum(scores) 51 | logging.info("Calculated Exponential Decay Score: %.2f", final_score) 52 | return final_score 53 | except Exception as e: 54 | logging.error("Error calculating Exponential Decay Score: %s", str(e)) 55 | return 0.0 56 | 57 | class CustomScore(ScoringAlgorithm): 58 | """Custom scoring algorithm that allows for user-defined scoring logic.""" 59 | def __init__(self, scoring_function): 60 | self.scoring_function = scoring_function 61 | 62 | def calculate_score(self, data: dict) -> float: 63 | """Calculate score using a custom scoring function.""" 64 | if not callable(self.scoring_function): 65 | logging.error("Provided scoring function is not callable.") 66 | return 0.0 67 | try: 68 | score = self.scoring_function(data) 69 | logging.info("Calculated Custom Score: %.2f", score) 70 | return score 71 | except Exception as e: 72 | logging.error("Error calculating Custom Score: %s", str(e)) 73 | return 0.0 74 | -------------------------------------------------------------------------------- /src/core/identity/identity_manager.py: -------------------------------------------------------------------------------- 1 | # src/core/identity/identity_manager.py 2 | 3 | import logging 4 | from .cryptography import Cryptography 5 | from .token_manager import TokenManager 6 | from .user_roles import UserRoles 7 | 8 | class IdentityManager: 9 | """Class to manage identity verification and user management.""" 10 | 11 | def __init__(self): 12 | self.cryptography = Cryptography() 13 | self.token_manager = TokenManager() 14 | self.user_roles = UserRoles() 15 | self.users = {} # In-memory user storage for demonstration 16 | 17 | def register_user(self, username, password): 18 | """Register a new user with encrypted password.""" 19 | if username in self.users: 20 | logging.warning("User already exists: %s", username) 21 | return {"error": "User already exists"}, 409 22 | 23 | password_hash = self.cryptography.hash_password(password) 24 | self.users[username] = { 25 | "password_hash": password_hash, 26 | "verified": False, 27 | "role": None # Role will be assigned later 28 | } 29 | logging.info("User registered: %s", username) 30 | return {"message": "User registered successfully"}, 201 31 | 32 | def verify_user(self, username, password): 33 | """Verify user credentials.""" 34 | user = self.users.get(username) 35 | if not user: 36 | logging.warning("User not found: %s", username) 37 | return {"error": "User not found"}, 404 38 | 39 | if self.cryptography.verify_password(password, user["password_hash"]): 40 | user["verified"] = True 41 | logging.info("User verified: %s", username) 42 | return {"message": "User verified successfully"}, 200 43 | else: 44 | logging.warning("Invalid password for user: %s", username) 45 | return {"error": "Invalid password"}, 401 46 | 47 | def assign_role(self, username, role): 48 | """Assign a role to a user.""" 49 | if username not in self.users: 50 | logging.warning("User not found: %s", username) 51 | return {"error": "User not found"}, 404 52 | 53 | try: 54 | self.user_roles.assign_role(username, role) 55 | self.users[username]["role"] = role 56 | logging.info("Role '%s' assigned to user: %s", role, username) 57 | return {"message": f"Role '{role}' assigned to user '{username}'."}, 200 58 | except ValueError as e: 59 | logging.error("Error assigning role: %s", str(e)) 60 | return {"error": str(e)}, 400 61 | 62 | def generate_token(self, username): 63 | """Generate a JWT token for a user.""" 64 | if username not in self.users or not self.users[username]["verified"]: 65 | logging.warning("Cannot generate token for unverified user: %s", username) 66 | return {"error": "User not verified"}, 403 67 | 68 | token = self.token_manager.generate_token(username) 69 | logging.info("Token generated for user: %s", username) 70 | return {"token": token}, 200 71 | 72 | def is_user_verified(self, username): 73 | """Check if the user is verified.""" 74 | user = self.users.get(username) 75 | if user and user["verified"]: 76 | return True 77 | return False 78 | 79 | def get_user_role(self, username): 80 | """Get the role of a user.""" 81 | user = self.users.get(username) 82 | if user: 83 | return user.get("role", "No role assigned") 84 | return None 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Stanford Blockchain](https://img.shields.io/badge/Stanford_Blockchain-Program-8B0000?style=flat&logo=bitcoin)](https://cyber.stanford.edu/) 2 | [![Stanford Center for Blockchain Research](https://img.shields.io/badge/Stanford_Center_for_Blockchain_Research-Member-FF4500?style=flat&logo=ethereum)](https://cbr.stanford.edu/) 3 | 4 | 5 |

MatrixAI by KOSASIH is licensed under Creative Commons Attribution 4.0 International

6 | 7 | # MatrixAI-Core 8 | MatrixAI-Core is the foundational repository for the MatrixAI decentralized trust verification system, designed for the Pi Network. This core module encompasses the essential algorithms, smart contracts, and decentralized identity frameworks that power real-time risk assessment, reputation scoring, and secure identity verification. Built with a focus on security, scalability, and community governance, MatrixAI-Core serves as the backbone for creating a trustworthy and efficient ecosystem, enabling seamless interactions and transactions within the Pi Network. Join us in building a safer, more reliable decentralized future! 9 | 10 | # MatrixAI-Core 11 | 12 | ## Project Overview 13 | 14 | MatrixAI-Core is the foundational repository for the MatrixAI decentralized trust verification system, designed specifically for the Pi Network. This project leverages advanced artificial intelligence and blockchain technology to create a secure, transparent, and user-centric environment for verifying identities and transactions. 15 | 16 | ### Key Features 17 | 18 | - **AI-Driven Risk Assessment**: Real-time monitoring and analysis of user behavior to detect anomalies and mitigate risks. 19 | - **Decentralized Identity Verification**: Secure and private identity verification using cryptographic proofs. 20 | - **Dynamic Reputation Scoring**: A reputation system that evolves based on user interactions, promoting trust and accountability. 21 | - **Smart Contract Automation**: Integration with smart contracts for efficient and secure transaction processing. 22 | - **Community-Driven Governance**: Empowering users to propose and vote on system updates. 23 | 24 | ## Getting Started 25 | 26 | ### Prerequisites 27 | 28 | - Python 3.7 or higher 29 | - Node.js (for smart contract development) 30 | - Git 31 | 32 | ### Installation 33 | 34 | 1. Clone the repository: 35 | ```bash 36 | 1 git clone https://github.com/KOSASIH/MatrixAI-Core.git 37 | 2 cd MatrixAI-Core 38 | ``` 39 | 40 | 2. Install the required Python packages: 41 | 42 | ```bash 43 | 1 pip install -r requirements.txt 44 | ``` 45 | 46 | 3. Set up the environment: 47 | 48 | ```bash 49 | 1 ./scripts/setup_environment.sh 50 | ``` 51 | 52 | ## Running the Application 53 | To start the application, run: 54 | 55 | ```bash 56 | 1 python src/main/app.py 57 | ``` 58 | 59 | ## Running Tests 60 | To run the tests, execute: 61 | 62 | ```bash 63 | 1 ./scripts/run_tests.sh 64 | ``` 65 | 66 | # Contributing 67 | We welcome contributions! Please read our Contributing Guidelines for more information. 68 | 69 | # License 70 | This project is licensed under the MIT License. See the LICENSE file for details. 71 | 72 | -------------------------------------------------------------------------------- /src/core/smart_contracts/__init__.py: -------------------------------------------------------------------------------- 1 | # src/core/smart_contracts/__init__.py 2 | 3 | import logging 4 | from .deployment import deploy_contract, compile_contract 5 | from .contract import MySmartContract 6 | 7 | # Configure logging 8 | logging.basicConfig(level=logging.INFO) 9 | logger = logging.getLogger(__name__) 10 | 11 | __all__ = ['deploy_contract', 'compile_contract', 'MySmartContract'] 12 | 13 | class SmartContractManager: 14 | """Manager for deploying and interacting with smart contracts.""" 15 | 16 | def __init__(self, web3_instance, contract_interface): 17 | self.web3 = web3_instance 18 | self.contract_interface = contract_interface 19 | self.contract_instance = None 20 | 21 | def deploy(self, initial_value: int): 22 | """Deploy the smart contract.""" 23 | try: 24 | contract_address = deploy_contract(self.web3, self.contract_interface, initial_value) 25 | self.contract_instance = self.web3.eth.contract(address=contract_address, abi=self.contract_interface['abi']) 26 | logger.info(f"Smart contract deployed at address: {contract_address}") 27 | return contract_address 28 | except Exception as e: 29 | logger.error(f"Failed to deploy contract: {str(e)}") 30 | raise 31 | 32 | def set_value(self, new_value: int): 33 | """Set a new value in the smart contract.""" 34 | if not self.contract_instance: 35 | logger.error("Contract instance is not initialized. Please deploy the contract first.") 36 | return 37 | 38 | try: 39 | account = self.web3.eth.accounts[0] 40 | transaction = self.contract_instance.functions.setValue(new_value).buildTransaction({ 41 | 'chainId': 1, # Mainnet 42 | 'gas': 200000, 43 | 'gasPrice': self.web3.toWei('50', 'gwei'), 44 | 'nonce': self.web3.eth.getTransactionCount(account), 45 | }) 46 | 47 | signed_txn = self.web3.eth.account.signTransaction(transaction, private_key=os.getenv("PRIVATE_KEY")) 48 | tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) 49 | tx_receipt = self.web3.eth.waitForTransactionReceipt(tx_hash) 50 | 51 | logger.info(f"Value set to {new_value}. Transaction receipt: {tx_receipt}") 52 | except Exception as e: 53 | logger.error(f"Failed to set value: {str(e)}") 54 | raise 55 | 56 | def get_value(self): 57 | """Get the current value from the smart contract.""" 58 | if not self.contract_instance: 59 | logger.error("Contract instance is not initialized. Please deploy the contract first.") 60 | return None 61 | 62 | try: 63 | current_value = self.contract_instance.functions.getValue().call() 64 | logger.info(f"Current value retrieved: {current_value}") 65 | return current_value 66 | except Exception as e: 67 | logger.error(f"Failed to retrieve value: {str(e)}") 68 | return None 69 | 70 | # Example usage 71 | if __name__ == "__main__": 72 | from web3 import Web3 73 | from dotenv import load_dotenv 74 | import os 75 | 76 | # Load environment variables 77 | load_dotenv() 78 | 79 | # Connect to the Ethereum network 80 | w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID")) 81 | 82 | # Compile the contract 83 | contract_interface = compile_contract() 84 | 85 | # Initialize the SmartContractManager 86 | manager = SmartContractManager(w3, contract_interface) 87 | 88 | # Deploy the contract with an initial value 89 | initial_value = 100 90 | manager.deploy(initial_value) 91 | 92 | # Set a new value 93 | manager.set_value(200) 94 | 95 | # Get the current value 96 | current_value = manager.get_value() 97 | -------------------------------------------------------------------------------- /src/core/risk_assessment/risk_analyzer.py: -------------------------------------------------------------------------------- 1 | # src/core/risk_assessment/risk_analyzer.py 2 | 3 | import numpy as np 4 | import pandas as pd 5 | import logging 6 | from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier 7 | from sklearn.model_selection import train_test_split, GridSearchCV 8 | from sklearn.metrics import classification_report, confusion_matrix 9 | from sklearn.preprocessing import StandardScaler 10 | 11 | class RiskAnalyzer: 12 | """Class for analyzing risk using various algorithms.""" 13 | 14 | def __init__(self, model_type='RandomForest'): 15 | self.model_type = model_type 16 | self.model = self._initialize_model() 17 | self.scaler = StandardScaler() 18 | logging.info(f"RiskAnalyzer initialized with {self.model_type}.") 19 | 20 | def _initialize_model(self): 21 | """Initialize the model based on the specified type.""" 22 | if self.model_type == 'RandomForest': 23 | return RandomForestClassifier(n_estimators=100, random_state=42) 24 | elif self.model_type == 'GradientBoosting': 25 | return GradientBoostingClassifier(n_estimators=100, random_state=42) 26 | else: 27 | logging.error("Unsupported model type: %s", self.model_type) 28 | raise ValueError(f"Unsupported model type: {self.model_type}") 29 | 30 | def train_model(self, data, target): 31 | """Train the risk analysis model.""" 32 | X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) 33 | X_train_scaled = self.scaler.fit_transform(X_train) 34 | self.model.fit(X_train_scaled, y_train) 35 | 36 | # Evaluate the model 37 | self.evaluate_model(X_test, y_test) 38 | 39 | def evaluate_model(self, X_test, y_test): 40 | """Evaluate the trained model.""" 41 | X_test_scaled = self.scaler.transform(X_test) 42 | predictions = self.model.predict(X_test_scaled) 43 | report = classification_report(y_test, predictions) 44 | cm = confusion_matrix(y_test, predictions) 45 | 46 | logging.info("Model evaluation completed.") 47 | logging.info("Classification Report:\n%s", report) 48 | logging.info("Confusion Matrix:\n%s", cm) 49 | 50 | def predict_risk(self, new_data): 51 | """Predict risk for new data.""" 52 | new_data_scaled = self.scaler.transform(new_data) 53 | predictions = self.model.predict(new_data_scaled) 54 | logging.info("Risk predictions made for new data.") 55 | return predictions 56 | 57 | def feature_importance(self, feature_names): 58 | """Get feature importance from the trained model.""" 59 | importance = self.model.feature_importances_ 60 | feature_importance = pd.DataFrame({'Feature': feature_names, 'Importance': importance}) 61 | feature_importance = feature_importance.sort_values(by='Importance', ascending=False) 62 | logging.info("Feature importance calculated.") 63 | return feature_importance 64 | 65 | def hyperparameter_tuning(self, data, target, param_grid): 66 | """Perform hyperparameter tuning using GridSearchCV.""" 67 | X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42) 68 | X_train_scaled = self.scaler.fit_transform(X_train) 69 | 70 | grid_search = GridSearchCV(self.model, param_grid, cv=5, scoring='accuracy') 71 | grid_search.fit(X_train_scaled, y_train) 72 | 73 | best_params = grid_search.best_params_ 74 | best_score = grid_search.best_score_ 75 | logging.info("Hyperparameter tuning completed.") 76 | logging.info("Best Parameters: %s", best_params) 77 | logging.info("Best Cross-Validation Score: %.2f", best_score) 78 | 79 | # Update the model with the best parameters 80 | self.model.set_params(**best_params) 81 | self.train_model(data, target) # Re-train with the best parameters 82 | -------------------------------------------------------------------------------- /src/core/smart_contracts/deployment.py: -------------------------------------------------------------------------------- 1 | # src/core/smart_contracts/deployment.py 2 | 3 | import json 4 | import os 5 | import logging 6 | from web3 import Web3 7 | from solcx import compile_standard, install_solc 8 | from dotenv import load_dotenv 9 | 10 | # Load environment variables 11 | load_dotenv() 12 | 13 | # Configure logging 14 | logging.basicConfig(level=logging.INFO) 15 | logger = logging.getLogger(__name__) 16 | 17 | # Install the specific version of Solidity if not already installed 18 | install_solc('0.8.0') 19 | 20 | def compile_contract(): 21 | """Compile the Solidity contract.""" 22 | with open("src/core/smart_contracts/contract.sol", "r") as file: 23 | contract_source = file.read() 24 | 25 | compiled_sol = compile_standard({ 26 | "language": "Solidity", 27 | "sources": { 28 | "contract.sol": { 29 | "content": contract_source 30 | } 31 | }, 32 | "settings": { 33 | "outputSelection": { 34 | "*": { 35 | "*": ["*"] 36 | } 37 | } 38 | } 39 | }) 40 | 41 | contract_interface = compiled_sol['contracts']['contract.sol']['MySmartContract'] 42 | return contract_interface 43 | 44 | def deploy_contract(w3: Web3, contract_interface, initial_value: int, version: str): 45 | """Deploy the smart contract to the blockchain.""" 46 | try: 47 | # Get the contract ABI and bytecode 48 | abi = contract_interface['abi'] 49 | bytecode = contract_interface['evm']['bytecode']['object'] 50 | 51 | # Create the contract instance 52 | MySmartContract = w3.eth.contract(abi=abi, bytecode=bytecode) 53 | 54 | # Get the account to deploy the contract 55 | account = w3.eth.accounts[0] 56 | 57 | # Build the transaction 58 | transaction = MySmartContract.constructor(initial_value, version).buildTransaction({ 59 | 'chainId': 1, # Mainnet 60 | 'gas': 2000000, 61 | 'gasPrice': w3.toWei('50', 'gwei'), 62 | 'nonce': w3.eth.getTransactionCount(account), 63 | }) 64 | 65 | # Sign the transaction 66 | signed_txn = w3.eth.account.signTransaction(transaction, private_key=os.getenv("PRIVATE_KEY")) 67 | 68 | # Send the transaction 69 | tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) 70 | 71 | # Wait for the transaction to be mined 72 | tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) 73 | 74 | logger.info(f"Contract deployed at address: {tx_receipt.contractAddress}") 75 | return tx_receipt.contractAddress 76 | except Exception as e: 77 | logger.error(f"Failed to deploy contract: {str(e)}") 78 | raise 79 | 80 | def upgrade_contract(w3: Web3, contract_address: str, new_implementation: str): 81 | """Upgrade the smart contract to a new implementation.""" 82 | try: 83 | # Logic to upgrade the contract would go here (e.g., using a proxy pattern) 84 | logger.info(f"Upgrading contract at {contract_address} to new implementation at {new_implementation}") 85 | # This is a placeholder for actual upgrade logic 86 | # In a real scenario, you would interact with a proxy contract to change the implementation 87 | except Exception as e: 88 | logger.error(f"Failed to upgrade contract: {str(e)}") 89 | raise 90 | 91 | if __name__ == "__main__": 92 | # Connect to the Ethereum network 93 | w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID")) 94 | 95 | # Compile the contract 96 | contract_interface = compile_contract() 97 | 98 | # Deploy the contract with an initial value and version 99 | initial_value = 100 100 | version = "1.0.0" 101 | contract_address = deploy_contract(w3, contract_interface, initial_value, version) 102 | 103 | # Example of upgrading the contract (this is a placeholder) 104 | new_implementation = "0xNewImplementationAddress" # Replace with actual address 105 | upgrade_contract(w3, contract_address, new_implementation) 106 | -------------------------------------------------------------------------------- /src/core/reputation/reputation_manager.py: -------------------------------------------------------------------------------- 1 | # reputation/reputation_manager.py 2 | 3 | import logging 4 | import pandas as pd 5 | from .scoring_algorithm import ScoringAlgorithm 6 | 7 | class ReputationManager: 8 | """Class for managing reputation scores.""" 9 | 10 | def __init__(self, scoring_algorithm: ScoringAlgorithm): 11 | self.scoring_algorithm = scoring_algorithm 12 | self.scores = pd.DataFrame(columns=['entity', 'score']) 13 | logging.info("ReputationManager initialized with %s.", self.scoring_algorithm.__class__.__name__) 14 | 15 | def add_entity(self, entity: str, data: dict): 16 | """Add an entity and its associated data for scoring.""" 17 | try: 18 | score = self.scoring_algorithm.calculate_score(data) 19 | self.scores = self.scores.append({'entity': entity, 'score': score}, ignore_index=True) 20 | logging.info("Entity %s added with score: %.2f", entity, score) 21 | except Exception as e: 22 | logging.error("Error adding entity %s: %s", entity, str(e)) 23 | 24 | def add_entities(self, entities: dict): 25 | """Add multiple entities and their associated data for scoring.""" 26 | for entity, data in entities.items(): 27 | self.add_entity(entity, data) 28 | 29 | def get_score(self, entity: str): 30 | """Get the reputation score for a specific entity.""" 31 | score_row = self.scores[self.scores['entity'] == entity] 32 | if not score_row.empty: 33 | score = score_row['score'].values[0] 34 | logging.info("Retrieved score for %s: %.2f", entity, score) 35 | return score 36 | else: 37 | logging.warning("Entity %s not found.", entity) 38 | return None 39 | 40 | def get_all_scores(self): 41 | """Get all reputation scores.""" 42 | logging.info("Retrieved all scores.") 43 | return self.scores 44 | 45 | def update_entity_score(self, entity: str, new_data: dict): 46 | """Update the score for an existing entity.""" 47 | if entity in self.scores['entity'].values: 48 | try: 49 | new_score = self.scoring_algorithm.calculate_score(new_data) 50 | self.scores.loc[self.scores['entity'] == entity, 'score'] = new_score 51 | logging.info("Updated score for %s: %.2f", entity, new_score) 52 | except Exception as e: 53 | logging.error("Error updating score for %s: %s", entity, str(e)) 54 | else: 55 | logging.warning("Entity %s not found for update.", entity) 56 | 57 | def remove_entity(self, entity: str): 58 | """Remove an entity from the reputation scores.""" 59 | if entity in self.scores['entity'].values: 60 | self.scores = self.scores[self.scores['entity'] != entity] 61 | logging.info("Entity %s removed from scores.", entity) 62 | else: 63 | logging.warning("Entity %s not found for removal.", entity) 64 | 65 | def batch_update_scores(self, updates: dict): 66 | """Batch update scores for multiple entities.""" 67 | for entity, new_data in updates.items(): 68 | self.update_entity_score(entity, new_data) 69 | 70 | def save_scores(self, file_path: str): 71 | """Save the current scores to a CSV file.""" 72 | try: 73 | self.scores.to_csv(file_path, index=False) 74 | logging.info("Scores saved to %s.", file_path) 75 | except Exception as e: 76 | logging.error("Error saving scores to %s: %s", file_path, str(e)) 77 | 78 | def load_scores(self, file_path: str): 79 | """Load scores from a CSV file.""" 80 | try: 81 | loaded_scores = pd.read_csv(file_path) 82 | if 'entity' in loaded_scores.columns and 'score' in loaded_scores.columns: 83 | self.scores = loaded_scores 84 | logging.info("Scores loaded from %s.", file_path) 85 | else: 86 | logging.error("Invalid format in %s. Required columns: 'entity', 'score'.", file_path) 87 | except Exception as e: 88 | logging.error("Error loading scores from %s: %s", file_path, str(e)) 89 | -------------------------------------------------------------------------------- /src/core/risk_assessment/anomaly_detection.py: -------------------------------------------------------------------------------- 1 | # src/core/risk_assessment/anomaly_detection.py 2 | 3 | import numpy as np 4 | import pandas as pd 5 | import logging 6 | from sklearn.ensemble import IsolationForest, LocalOutlierFactor 7 | from sklearn.preprocessing import StandardScaler 8 | from sklearn.metrics import classification_report, confusion_matrix 9 | 10 | class AnomalyDetector: 11 | """Class for detecting anomalies in data using various algorithms.""" 12 | 13 | def __init__(self, model_type='IsolationForest'): 14 | self.model_type = model_type 15 | self.model = self._initialize_model() 16 | self.scaler = StandardScaler() 17 | logging.info(f"AnomalyDetector initialized with {self.model_type}.") 18 | 19 | def _initialize_model(self): 20 | """Initialize the model based on the specified type.""" 21 | if self.model_type == 'IsolationForest': 22 | return IsolationForest(contamination=0.05, random_state=42) 23 | elif self.model_type == 'LocalOutlierFactor': 24 | return LocalOutlierFactor(n_neighbors=20) 25 | else: 26 | logging.error("Unsupported model type: %s", self.model_type) 27 | raise ValueError(f"Unsupported model type: {self.model_type}") 28 | 29 | def fit(self, data): 30 | """Fit the anomaly detection model to the data.""" 31 | scaled_data = self.scaler.fit_transform(data) 32 | self.model.fit(scaled_data) 33 | logging.info("Anomaly detection model fitted to data.") 34 | 35 | def detect_anomalies(self, new_data): 36 | """Detect anomalies in new data.""" 37 | scaled_data = self.scaler.transform(new_data) 38 | if self.model_type == 'IsolationForest': 39 | predictions = self.model.predict(scaled_data) 40 | anomalies = np.where(predictions == -1, True, False) 41 | elif self.model_type == 'LocalOutlierFactor': 42 | predictions = self.model.fit_predict(scaled_data) 43 | anomalies = np.where(predictions == -1, True, False) 44 | else: 45 | logging.error("Unsupported model type: %s", self.model_type) 46 | raise ValueError(f"Unsupported model type: {self.model_type}") 47 | 48 | logging.info("Anomalies detected in new data.") 49 | return anomalies 50 | 51 | def get_anomaly_scores(self, new_data): 52 | """Get anomaly scores for new data.""" 53 | scaled_data = self.scaler.transform(new_data) 54 | if self.model_type == 'IsolationForest': 55 | scores = self.model.decision_function(scaled_data) 56 | elif self.model_type == 'LocalOutlierFactor': 57 | scores = -self.model.negative_outlier_factor_ 58 | else: 59 | logging.error("Unsupported model type: %s", self.model_type) 60 | raise ValueError(f"Unsupported model type: {self.model_type}") 61 | 62 | logging.info("Anomaly scores calculated.") 63 | return scores 64 | 65 | def evaluate_model(self, true_labels, predictions): 66 | """Evaluate the anomaly detection model.""" 67 | report = classification_report(true_labels, predictions) 68 | cm = confusion_matrix(true_labels, predictions) 69 | 70 | logging.info("Model evaluation completed.") 71 | logging.info("Classification Report:\n%s", report) 72 | logging.info("Confusion Matrix:\n%s", cm) 73 | 74 | def hyperparameter_tuning(self, data, contamination_range): 75 | """Perform hyperparameter tuning for Isolation Forest.""" 76 | if self.model_type != 'IsolationForest': 77 | logging.error("Hyperparameter tuning is only supported for Isolation Forest.") 78 | raise ValueError("Hyperparameter tuning is only supported for Isolation Forest.") 79 | 80 | best_contamination = None 81 | best_score = -np.inf 82 | 83 | for contamination in contamination_range: 84 | model = IsolationForest(contamination=contamination, random_state=42) 85 | scaled_data = self.scaler.fit_transform(data) 86 | model.fit(scaled_data) 87 | 88 | # Evaluate the model using cross-validation 89 | predictions = model.predict(scaled_data) 90 | score = np.mean(predictions == -1) # Proportion of detected anomalies 91 | 92 | if score > best_score: 93 | best_score = score 94 | best_contamination = contamination 95 | 96 | logging.info("Hyperparameter tuning completed.") 97 | logging.info("Best Contamination: %.2f", best_contamination) 98 | logging.info("Best Score: %.2f", best_score) 99 | 100 | # Update the model with the best contamination 101 | self.model = IsolationForest(contamination=best_contamination, random_state=42) 102 | self.fit(data) # Re-fit the model with the best contamination 103 | --------------------------------------------------------------------------------