├── .github └── ISSUE_TEMPLATE │ ├── custom.md │ ├── feature_request.md │ └── bug_report.md ├── .gitignore ├── src ├── api │ ├── middleware.py │ ├── routes │ │ ├── analytics.py │ │ ├── notifications.py │ │ ├── resources.py │ │ ├── users.py │ │ └── transactions.py │ ├── rate_limiting.py │ ├── authentication.py │ └── app.py ├── frontend │ ├── styles │ │ ├── responsive.css │ │ └── main.css │ ├── components │ │ ├── Footer.js │ │ ├── ResourceCard.js │ │ ├── Header.js │ │ ├── NotificationBell.js │ │ └── TransactionForm.js │ ├── scripts │ │ ├── api.js │ │ ├── web3.js │ │ ├── state_management.js │ │ └── app.js │ └── index.html ├── config │ ├── database_config.py │ ├── logging_config.py │ └── config.py ├── blockchain │ ├── smart_contracts │ │ ├── oracles.py │ │ ├── governance.py │ │ ├── contract_manager.py │ │ └── contract_template.sol │ ├── consensus │ │ ├── proof_of_stake.py │ │ └── delegated_proof_of_stake.py │ ├── utils.py │ ├── blockchain.py │ └── transaction.py ├── tests │ ├── frontend_tests.js │ ├── api_tests.py │ ├── integration_tests.py │ └── blockchain_tests.py ├── services │ ├── oracle_service.py │ ├── notification_service.py │ ├── space_resource_service.py │ ├── payment_service.py │ └── analytics_service.py └── constants.py ├── .env ├── scripts ├── migrate.py ├── deploy.py ├── seed_data.py ├── monitor.py └── backup.py ├── examples ├── demo_transaction.py ├── demo_smart_contract.py └── demo_api_usage.py ├── tests ├── test_frontend.py ├── test_api.py ├── test_integration.py └── test_blockchain.py ├── LICENSE ├── docs ├── user_guide.md ├── deployment_guide.md ├── design_specifications.md ├── architecture.md ├── api_reference.md └── code_structure.md └── README.md /.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 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__/ 3 | *.py[cod] 4 | *.pyo 5 | *.pyd 6 | *.db 7 | *.sqlite3 8 | 9 | # Node.js 10 | node_modules/ 11 | npm-debug.log 12 | yarn-error.log 13 | 14 | # Environment variables 15 | .env 16 | 17 | # IDE files 18 | .vscode/ 19 | .idea/ 20 | *.sublime-project 21 | *.sublime-workspace 22 | 23 | # Build files 24 | dist/ 25 | build/ 26 | -------------------------------------------------------------------------------- /src/api/middleware.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from middleware.authentication import authentication_middleware 3 | from middleware.rate_limiting import rate_limiting_middleware 4 | 5 | def apply_middlewares(app: Flask): 6 | """Apply middleware functions to the Flask app.""" 7 | app.before_request(authentication_middleware) 8 | app.before_request(rate_limiting_middleware) 9 | -------------------------------------------------------------------------------- /src/frontend/styles/responsive.css: -------------------------------------------------------------------------------- 1 | /* styles/responsive.css */ 2 | 3 | @media (max-width: 600px) { 4 | nav ul li { 5 | display: block; 6 | margin: 10px 0; 7 | } 8 | 9 | header { 10 | text-align: left; 11 | } 12 | 13 | main { 14 | padding: 10px; 15 | } 16 | 17 | section { 18 | padding: 10px; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/frontend/components/Footer.js: -------------------------------------------------------------------------------- 1 | // components/Footer.js 2 | 3 | 8 | 9 | 14 | 15 | 23 | -------------------------------------------------------------------------------- /src/api/routes/analytics.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, jsonify 2 | 3 | analytics_bp = Blueprint('analytics', __name__) 4 | 5 | @analytics_bp.route('/summary', methods=['GET']) 6 | def get_summary(): 7 | # Placeholder for analytics summary logic 8 | summary = { 9 | 'total_transactions': 100, # Example data 10 | 'total_users': 50, # Example data 11 | 'total_resources': 2000, # Example data 12 | } 13 | return jsonify(summary), 200 14 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | # Environment Variables for Cosmic Pi 2 | 3 | # Database Configuration 4 | DB_HOST=localhost 5 | DB_PORT=5432 6 | DB_NAME=cosmic_pi 7 | DB_USER=your_db_user 8 | DB_PASSWORD=your_db_password 9 | 10 | # API Configuration 11 | API_PORT=5000 12 | API_KEY=your_api_key 13 | 14 | # Blockchain Configuration 15 | BLOCKCHAIN_NETWORK=mainnet 16 | BLOCKCHAIN_NODE_URL=https://your.blockchain.node.url 17 | 18 | # Stablecoin Configuration 19 | PI_COIN_VALUE=314159 # Fixed value of Pi Coin in USD 20 | 21 | # Frontend Configuration 22 | FRONTEND_URL=http://localhost:3000 23 | 24 | # Logging Configuration 25 | LOG_LEVEL=info 26 | -------------------------------------------------------------------------------- /scripts/migrate.py: -------------------------------------------------------------------------------- 1 | # scripts/migrate.py 2 | 3 | import os 4 | from sqlalchemy import create_engine 5 | from sqlalchemy.orm import sessionmaker 6 | from your_model_definitions import Base # Import your SQLAlchemy Base 7 | 8 | def migrate(): 9 | """Run database migrations.""" 10 | db_url = os.environ.get('DATABASE_URL', 'postgresql://user:password@localhost/dbname') 11 | engine = create_engine(db_url) 12 | Base.metadata.create_all(engine) # Create tables based on the defined models 13 | 14 | print("Database migration completed successfully.") 15 | 16 | if __name__ == "__main__": 17 | migrate() 18 | -------------------------------------------------------------------------------- /src/frontend/components/ResourceCard.js: -------------------------------------------------------------------------------- 1 | // components/ResourceCard.js 2 | 3 | 9 | 10 | 21 | 22 | 30 | -------------------------------------------------------------------------------- /src/api/routes/notifications.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, jsonify 2 | 3 | notifications_bp = Blueprint('notifications', __name__) 4 | 5 | # In-memory notification storage (for demonstration purposes) 6 | notifications = [] 7 | 8 | @notifications_bp.route('/', methods=['GET']) 9 | def get_notifications(): 10 | return jsonify(notifications), 200 11 | 12 | @notifications_bp.route('/add', methods=['POST']) 13 | def add_notification(): 14 | values = request.get_json() 15 | message = values.get('message') 16 | 17 | notifications.append({'message : message}) 18 | return jsonify({'message': 'Notification added successfully'}), 201 19 | -------------------------------------------------------------------------------- /src/config/database_config.py: -------------------------------------------------------------------------------- 1 | # src/config/database_config.py 2 | 3 | import os 4 | 5 | class DatabaseConfig: 6 | """Database configuration settings.""" 7 | DB_HOST = os.environ.get('DB_HOST', 'localhost') 8 | DB_PORT = os.environ.get('DB_PORT', '5432') 9 | DB_NAME = os.environ.get('DB_NAME', 'cosmic_pi') 10 | DB_USER = os.environ.get('DB_USER', 'your_db_user') 11 | DB_PASSWORD = os.environ.get('DB_PASSWORD', 'your_db_password') 12 | 13 | @classmethod 14 | def get_connection_string(cls): 15 | """Returns the database connection string.""" 16 | return f"postgresql://{cls.DB_USER}:{cls.DB_PASSWORD}@{cls.DB_HOST}:{cls.DB_PORT}/{cls.DB_NAME}" 17 | -------------------------------------------------------------------------------- /src/api/routes/resources.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, jsonify 2 | 3 | resources_bp = Blueprint('resources', __name__) 4 | 5 | # In-memory resource storage (for demonstration purposes) 6 | resources = { 7 | 'water': 1000, 8 | 'food': 500, 9 | } 10 | 11 | @resources_bp.route('/', methods=['GET']) 12 | def get_resources(): 13 | return jsonify(resources), 200 14 | 15 | @resources_bp.route('/', methods=['GET']) 16 | def get_resource(resource_name): 17 | resource_amount = resources.get(resource_name) 18 | if resource_amount is None: 19 | return jsonify({'error': 'Resource not found'}), 404 20 | 21 | return jsonify({resource_name: resource_amount}), 200 22 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/blockchain/smart_contracts/oracles.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | class Oracle: 4 | def __init__(self, oracle_url): 5 | self.oracle_url = oracle_url 6 | 7 | def get_price(self, asset): 8 | response = requests.get(f"{self.oracle_url}/price/{asset}") 9 | if response.status_code == 200: 10 | return response.json()['price'] 11 | else: 12 | raise Exception("Failed to fetch price data from oracle") 13 | 14 | def get_weather(self, location): 15 | response = requests.get(f"{self.oracle_url}/weather/{location}") 16 | if response.status_code == 200: 17 | return response.json()['weather'] 18 | else: 19 | raise Exception("Failed to fetch weather data from oracle") 20 | -------------------------------------------------------------------------------- /scripts/deploy.py: -------------------------------------------------------------------------------- 1 | # scripts/deploy.py 2 | 3 | import os 4 | import subprocess 5 | 6 | def deploy(): 7 | """Deploy the application.""" 8 | print("Starting deployment...") 9 | 10 | # Pull the latest code from the repository 11 | subprocess.run(["git", "pull"], check=True) 12 | 13 | # Install dependencies 14 | subprocess.run(["pip", "install", "-r", "requirements.txt"], check=True) 15 | 16 | # Run database migrations 17 | subprocess.run(["python", "migrate.py"], check=True) 18 | 19 | # Start the application (this can vary based on your setup) 20 | subprocess.run(["gunicorn", "src.api.app:app", "-b", "0.0.0.0:5000"], check=True) 21 | 22 | print("Deployment completed successfully.") 23 | 24 | if __name__ == "__main__": 25 | deploy() 26 | -------------------------------------------------------------------------------- /src/frontend/scripts/api.js: -------------------------------------------------------------------------------- 1 | // scripts/api.js 2 | 3 | const API_BASE_URL = '/api'; 4 | 5 | async function fetchResources() { 6 | const response = await fetch(`${API_BASE_URL}/resources`); 7 | if (!response.ok) throw new Error('Failed to fetch resources'); 8 | return await response.json(); 9 | } 10 | 11 | async function submitTransaction(transaction) { 12 | const response = await fetch(`${API_BASE_URL}/transactions/new`, { 13 | method: 'POST', 14 | headers: { 15 | 'Content-Type': 'application/json' 16 | }, 17 | body: JSON.stringify(transaction) 18 | }); 19 | if (!response.ok) throw new Error('Transaction failed'); 20 | return await response.json(); 21 | } 22 | 23 | export { fetchResources, submitTransaction }; 24 | -------------------------------------------------------------------------------- /examples/demo_transaction.py: -------------------------------------------------------------------------------- 1 | # examples/demo_transaction.py 2 | 3 | import requests 4 | 5 | def create_transaction(sender, recipient, amount): 6 | """Creates a new transaction and submits it to the blockchain.""" 7 | url = 'http://localhost:5000/api/transactions/new' # Adjust the URL as needed 8 | transaction_data = { 9 | 'sender': sender, 10 | 'recipient': recipient, 11 | 'amount': amount 12 | } 13 | 14 | response = requests.post(url, json=transaction_data) 15 | 16 | if response.status_code == 201: 17 | print("Transaction submitted successfully:") 18 | print(response.json()) 19 | else: 20 | print("Failed to submit transaction:") 21 | print(response.status_code, response.text) 22 | 23 | if __name__ == "__main__": 24 | # Example usage 25 | create_transaction(sender="Alice", recipient="Bob", amount=50) 26 | -------------------------------------------------------------------------------- /tests/test_frontend.py: -------------------------------------------------------------------------------- 1 | # tests/test_frontend.py 2 | 3 | import unittest 4 | from frontend import app 5 | 6 | class TestFrontend(unittest.TestCase): 7 | def setUp(self): 8 | """Set up the Flask test client for frontend testing.""" 9 | self.app = app.test_client() 10 | self.app.testing = True 11 | 12 | def test_home_page(self): 13 | """Test the home page loads correctly.""" 14 | response = self.app.get('/') 15 | self.assertEqual(response.status_code, 200) 16 | self.assertIn(b'Welcome to Cosmic Pi', response.data) 17 | 18 | def test_transaction_page(self): 19 | """Test the transaction page loads correctly.""" 20 | response = self.app.get('/transaction') 21 | self.assertEqual(response.status_code, 200) 22 | self.assertIn(b'Create a Transaction', response.data) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /scripts/seed_data.py: -------------------------------------------------------------------------------- 1 | # scripts/seed_data.py 2 | 3 | import os 4 | from sqlalchemy import create_engine 5 | from sqlalchemy.orm import sessionmaker 6 | from your_model_definitions import YourModel # Import your SQLAlchemy models 7 | 8 | def seed_data(): 9 | """Seed the database with initial data.""" 10 | db_url = os.environ.get('DATABASE_URL', 'postgresql://user:password@localhost/dbname') 11 | engine = create_engine(db_url) 12 | Session = sessionmaker(bind=engine) 13 | session = Session() 14 | 15 | # Example of seeding data 16 | initial_data = [ 17 | YourModel(name='Sample Data 1', value=100), 18 | YourModel(name='Sample Data 2', value=200), 19 | ] 20 | 21 | session.add_all(initial_data) 22 | session.commit() 23 | session.close() 24 | 25 | print("Database seeded with initial data successfully.") 26 | 27 | if __name__ == "__main__": 28 | seed_data() 29 | -------------------------------------------------------------------------------- /src/tests/frontend_tests.js: -------------------------------------------------------------------------------- 1 | // src/tests/frontend_tests.js 2 | 3 | import { mount } from '@vue/test-utils'; 4 | import TransactionForm from '../components/TransactionForm.vue'; 5 | 6 | describe('TransactionForm.vue', () => { 7 | it('renders correctly', () => { 8 | const wrapper = mount(TransactionForm); 9 | expect(wrapper.exists()).toBe(true); 10 | }); 11 | 12 | it('submits a transaction', async () => { 13 | const wrapper = mount(TransactionForm); 14 | await wrapper.setData({ 15 | transaction: { 16 | sender: 'Alice', 17 | recipient: 'Bob', 18 | amount: 50 19 | } 20 | }); 21 | await wrapper.find('form').trigger('submit.prevent'); 22 | expect(wrapper.vm.transaction.sender).toBe(''); 23 | expect(wrapper.vm.transaction.recipient).toBe(''); 24 | expect(wrapper.vm.transaction.amount).toBe(null); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /examples/demo_smart_contract.py: -------------------------------------------------------------------------------- 1 | # examples/demo_smart_contract.py 2 | 3 | from web3 import Web3 4 | 5 | def interact_with_smart_contract(contract_address, abi, function_name, *args): 6 | """Interacts with a smart contract function.""" 7 | # Connect to the Ethereum network (or any compatible network) 8 | w3 = Web3(Web3.HTTPProvider('https://your.ethereum.node')) 9 | 10 | # Load the contract 11 | contract = w3.eth.contract(address=contract_address, abi=abi) 12 | 13 | # Call the function (for read-only functions) 14 | result = contract.functions[function_name](*args).call() 15 | print(f"Result from {function_name}: {result}") 16 | 17 | if __name__ == "__main__": 18 | # Example usage 19 | contract_address = '0xYourSmartContractAddress' 20 | abi = [...] # Replace with your contract's ABI 21 | function_name = 'yourFunctionName' 22 | 23 | interact_with_smart_contract(contract_address, abi, function_name, 'arg1', 'arg2') 24 | -------------------------------------------------------------------------------- /src/frontend/styles/main.css: -------------------------------------------------------------------------------- 1 | /* styles/main.css */ 2 | 3 | body { 4 | font-family: Arial, sans-serif; 5 | margin: 0; 6 | padding: 0; 7 | background-color: #f4f4f4; 8 | } 9 | 10 | header { 11 | background: #007bff; 12 | color: white; 13 | padding: 10px 20px; 14 | text-align: center; 15 | } 16 | 17 | nav ul { 18 | list-style: none; 19 | padding: 0; 20 | } 21 | 22 | nav ul li { 23 | display: inline; 24 | margin: 0 15px; 25 | } 26 | 27 | nav ul li a { 28 | color: white; 29 | text-decoration: none; 30 | } 31 | 32 | main { 33 | padding: 20px; 34 | } 35 | 36 | section { 37 | margin-bottom: 20px; 38 | background: white; 39 | padding: 15px; 40 | border-radius: 5px; 41 | box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); 42 | } 43 | 44 | footer { 45 | text-align: center; 46 | padding: 10px 0; 47 | background: #007bff; 48 | color: white; 49 | } 50 | 51 | footer p { 52 | margin: 0; 53 | } 54 | -------------------------------------------------------------------------------- /src/frontend/components/Header.js: -------------------------------------------------------------------------------- 1 | // components/Header.js 2 | 3 | 15 | 16 | 21 | 22 | 42 | -------------------------------------------------------------------------------- /scripts/monitor.py: -------------------------------------------------------------------------------- 1 | # scripts/monitor.py 2 | 3 | import requests 4 | import time 5 | 6 | def check_service(url): 7 | """Check if a service is up and running.""" 8 | try: 9 | response = requests.get(url) 10 | if response.status_code == 200: 11 | print(f"Service {url} is up.") 12 | else: 13 | print(f"Service {url} returned status code: {response.status_code}") 14 | except requests.exceptions.RequestException as e: 15 | print(f"Service {url} is down. Error: {e}") 16 | 17 | def monitor(): 18 | """Monitor application services.""" 19 | services = [ 20 | 'http://localhost:5000/api', # Example API endpoint 21 | 'https://api.paymentservice.com', 22 | 'https://api.spaceresource.com', 23 | ] 24 | 25 | while True: 26 | for service in services: 27 | check_service(service) 28 | time.sleep(60) # Check every minute 29 | 30 | if __name__ == "__main__": 31 | monitor() 32 | -------------------------------------------------------------------------------- /scripts/backup.py: -------------------------------------------------------------------------------- 1 | # scripts/backup.py 2 | 3 | import os 4 | import shutil 5 | from datetime import datetime 6 | 7 | def backup(): 8 | """Create a backup of the database and configuration files.""" 9 | timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') 10 | backup_dir = f"backup_{timestamp}" 11 | 12 | # Create backup directory 13 | os.makedirs(backup_dir, exist_ok=True) 14 | 15 | # Backup database (example for PostgreSQL) 16 | db_url = os.environ.get('DATABASE_URL', 'postgresql://user:password@localhost/dbname') 17 | db_name = db_url.split('/')[-1] 18 | os.system(f"pg_dump {db_url} > {backup_dir}/{db_name}_backup.sql") 19 | 20 | # Backup configuration files 21 | shutil.copy('src/config/config.py', backup_dir) 22 | shutil.copy('src/config/logging_config.py', backup_dir) 23 | shutil.copy('src/config/database_config.py', backup_dir) 24 | 25 | print(f"Backup created successfully in {backup_dir}.") 26 | 27 | if __name__ == "__main__": 28 | backup() 29 | -------------------------------------------------------------------------------- /src/api/rate_limiting.py: -------------------------------------------------------------------------------- 1 | from flask import request, jsonify 2 | import time 3 | from collections import defaultdict 4 | 5 | # Rate limiting configuration 6 | RATE_LIMIT = 5 # Maximum requests per time window 7 | TIME_WINDOW = 60 # Time window in seconds 8 | 9 | # In-memory storage for tracking requests 10 | request_counts = defaultdict(lambda: {'count': 0, 'start_time': time.time()}) 11 | 12 | def rate_limiting_middleware(): 13 | """Middleware for dynamic rate limiting API requests.""" 14 | ip = request.remote_addr 15 | current_time = time.time() 16 | 17 | # Reset count if the time window has passed 18 | if current_time - request_counts[ip]['start_time'] > TIME_WINDOW: 19 | request_counts[ip] = {'count': 1, 'start_time': current_time} 20 | else: 21 | request_counts[ip]['count'] += 1 22 | 23 | # Check if the rate limit has been exceeded 24 | if request_counts[ip]['count'] > RATE_LIMIT: 25 | return jsonify({'error': 'Rate limit exceeded. Try again later.'}), 429 26 | -------------------------------------------------------------------------------- /src/services/oracle_service.py: -------------------------------------------------------------------------------- 1 | # src/services/oracle_service.py 2 | 3 | import requests 4 | 5 | class OracleService: 6 | def __init__(self, api_key, base_url): 7 | self.api_key = api_key 8 | self.base_url = base_url 9 | 10 | def get_real_time_data(self, data_type): 11 | """Fetches real-time data from the oracle.""" 12 | response = requests.get(f"{self.base_url}/oracle/data/{data_type}", headers=self._get_headers()) 13 | return self._handle_response(response) 14 | 15 | def _get_headers(self): 16 | """Returns the headers for API requests.""" 17 | return { 18 | 'Authorization': f'Bearer {self.api_key}', 19 | 'Content-Type': 'application/json' 20 | } 21 | 22 | def _handle_response(self, response): 23 | """Handles API responses.""" 24 | if response.status_code == 200: 25 | return response.json() 26 | else: 27 | raise Exception(f"Error: {response.status_code} - {response.text}") 28 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/frontend/scripts/web3.js: -------------------------------------------------------------------------------- 1 | // scripts/web3.js 2 | 3 | import Web3 from 'web3'; 4 | 5 | let web3; 6 | 7 | async function initWeb3() { 8 | if (window.ethereum) { 9 | web3 = new Web3(window.ethereum); 10 | try { 11 | await window.ethereum.request({ method: 'eth_requestAccounts' }); 12 | } catch (error) { 13 | console.error('User denied account access'); 14 | } 15 | } else { 16 | console.error('No Ethereum browser detected. Install MetaMask.'); 17 | } 18 | } 19 | 20 | async function getAccount() { 21 | const accounts = await web3.eth.getAccounts(); 22 | return accounts[0]; 23 | } 24 | 25 | async function sendTransaction(transaction) { 26 | const account = await getAccount(); 27 | return await web3.eth.sendTransaction({ 28 | from: account, 29 | to: transaction.recipient, 30 | value: web3.utils.toWei(transaction.amount.toString(), 'ether') 31 | }); 32 | } 33 | 34 | export { initWeb3, getAccount, sendTransaction }; 35 | -------------------------------------------------------------------------------- /examples/demo_api_usage.py: -------------------------------------------------------------------------------- 1 | # examples/demo_api_usage.py 2 | 3 | import requests 4 | 5 | def get_chain(): 6 | """Fetches the current blockchain data.""" 7 | url = 'http://localhost:5000/api/chain' # Adjust the URL as needed 8 | response = requests.get(url) 9 | 10 | if response.status_code == 200: 11 | print("Current Blockchain:") 12 | print(response.json()) 13 | else: 14 | print("Failed to fetch blockchain data:") 15 | print(response.status_code, response.text) 16 | 17 | def get_resources(): 18 | """Fetches available resources.""" 19 | url = 'http://localhost:5000/api/resources' # Adjust the URL as needed 20 | response = requests.get(url) 21 | 22 | if response.status_code == 200: 23 | print("Available Resources:") 24 | print(response.json()) 25 | else: 26 | print("Failed to fetch resources:") 27 | print(response.status_code, response.text) 28 | 29 | if __name__ == "__main__": 30 | # Example usage 31 | get_chain() 32 | get_resources() 33 | -------------------------------------------------------------------------------- /src/api/routes/users.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, jsonify, request 2 | 3 | users_bp = Blueprint('users', __name__) 4 | 5 | # In-memory user storage (for demonstration purposes) 6 | users = {} 7 | 8 | @users_bp.route('/register', methods=['POST']) 9 | def register_user(): 10 | values = request.get_json() 11 | username = values.get('username') 12 | password = values.get('password') 13 | 14 | if username in users: 15 | return jsonify({'error': 'User already exists'}), 400 16 | 17 | users[username] = password # Store user credentials (hashing recommended) 18 | return jsonify({'message': 'User registered successfully'}), 201 19 | 20 | @users_bp.route('/login', methods=['POST']) 21 | def login_user(): 22 | values = request.get_json() 23 | username = values.get('username') 24 | password = values.get('password') 25 | 26 | if username not in users or users[username] != password: 27 | return jsonify({'error': 'Invalid credentials'}), 401 28 | 29 | return jsonify({'message': 'Login successful'}), 200 30 | -------------------------------------------------------------------------------- /src/config/logging_config.py: -------------------------------------------------------------------------------- 1 | # src/config/logging_config.py 2 | 3 | import logging 4 | from logging.handlers import RotatingFileHandler 5 | import os 6 | 7 | def setup_logging(): 8 | """Sets up logging configuration.""" 9 | log_level = os.environ.get('LOG_LEVEL', 'INFO').upper() 10 | log_file = os.environ.get('LOG_FILE', 'app.log') 11 | 12 | # Create a rotating file handler 13 | handler = RotatingFileHandler(log_file, maxBytes=10 * 1024 * 1024, backupCount=5) 14 | handler.setLevel(log_level) 15 | 16 | # Create a logging format 17 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 18 | handler.setFormatter(formatter) 19 | 20 | # Get the root logger and set the handler 21 | logger = logging.getLogger() 22 | logger.setLevel(log_level) 23 | logger.addHandler(handler) 24 | 25 | # Optionally, log to console as well 26 | console_handler = logging.StreamHandler() 27 | console_handler.setLevel(log_level) 28 | console_handler.setFormatter(formatter) 29 | logger.addHandler(console_handler) 30 | 31 | logger.info("Logging is set up.") 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 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 | -------------------------------------------------------------------------------- /src/config/config.py: -------------------------------------------------------------------------------- 1 | # src/config/config.py 2 | 3 | import os 4 | 5 | class Config: 6 | """Base configuration class.""" 7 | SECRET_KEY = os.environ.get('SECRET_KEY', 'your_default_secret_key') 8 | DEBUG = os.environ.get('DEBUG', 'False') == 'True' 9 | API_BASE_URL = os.environ.get('API_BASE_URL', 'http://localhost:5000/api') 10 | PAYMENT_SERVICE_URL = os.environ.get('PAYMENT_SERVICE_URL', 'https://api.paymentservice.com') 11 | SPACE_RESOURCE_SERVICE_URL = os.environ.get('SPACE_RESOURCE_SERVICE_URL', 'https://api.spaceresource.com') 12 | NOTIFICATION_SERVICE_URL = os.environ.get('NOTIFICATION_SERVICE_URL', 'https://api.notificationservice.com') 13 | ANALYTICS_SERVICE_URL = os.environ.get('ANALYTICS_SERVICE_URL', 'https://api.analyticsservice.com') 14 | ORACLE_SERVICE_URL = os.environ.get('ORACLE_SERVICE_URL', 'https://api.oracle.com') 15 | 16 | class DevelopmentConfig(Config): 17 | """Development configuration.""" 18 | DEBUG = True 19 | 20 | class ProductionConfig(Config): 21 | """Production configuration.""" 22 | DEBUG = False 23 | 24 | # You can add more configurations (e.g., TestingConfig) as needed 25 | -------------------------------------------------------------------------------- /src/services/notification_service.py: -------------------------------------------------------------------------------- 1 | # src/services/notification_service.py 2 | 3 | import requests 4 | 5 | class NotificationService: 6 | def __init__(self, api_key, base_url): 7 | self.api_key = api_key 8 | self.base_url = base_url 9 | 10 | def send_notification(self, user_id, message): 11 | """Sends a notification to a user.""" 12 | payload = { 13 | 'user_id': user_id, 14 | 'message': message 15 | } 16 | response = requests.post(f"{self.base_url}/notifications", json=payload, headers=self._get_headers()) 17 | return self._handle_response(response) 18 | 19 | def _get_headers(self): 20 | """Returns the headers for API requests.""" 21 | return { 22 | 'Authorization': f'Bearer {self.api_key}', 23 | 'Content-Type': 'application/json' 24 | } 25 | 26 | def _handle_response(self, response): 27 | """Handles API responses.""" 28 | if response.status_code == 200: 29 | return response.json() 30 | else: 31 | raise Exception(f"Error: {response.status_code} - {response.text}") 32 | -------------------------------------------------------------------------------- /src/blockchain/smart_contracts/governance.py: -------------------------------------------------------------------------------- 1 | class Governance: 2 | def ```python 3 | __init__(self): 4 | self.proposals = [] 5 | self.votes = {} 6 | 7 | def create_proposal(self, proposal): 8 | self.proposals.append(proposal) 9 | self.votes[proposal] = {'for': 0, 'against': 0} 10 | 11 | def vote(self, proposal, vote): 12 | if proposal not in self.proposals: 13 | raise Exception("Proposal does not exist") 14 | if vote not in ['for', 'against']: 15 | raise Exception("Invalid vote option") 16 | 17 | self.votes[proposal][vote] += 1 18 | 19 | def get_results(self, proposal): 20 | if proposal not in self.proposals: 21 | raise Exception("Proposal does not exist") 22 | return self.votes[proposal] 23 | 24 | def execute_proposal(self, proposal): 25 | if proposal not in self.proposals: 26 | raise Exception("Proposal does not exist") 27 | results = self.get_results(proposal) 28 | if results['for'] > results['against']: 29 | return f"Proposal '{proposal}' executed successfully." 30 | else: 31 | return f"Proposal '{proposal}' was rejected." 32 | -------------------------------------------------------------------------------- /src/frontend/scripts/state_management.js: -------------------------------------------------------------------------------- 1 | // scripts/state_management.js 2 | 3 | import Vue from 'vue'; 4 | import Vuex from 'vuex'; 5 | 6 | Vue.use(Vuex); 7 | 8 | const store = new Vuex.Store({ 9 | state: { 10 | transactions: [], 11 | resources: [], 12 | summary: { 13 | total_transactions: 0, 14 | total_users: 0 15 | } 16 | }, 17 | mutations: { 18 | ADD_TRANSACTION(state, transaction) { 19 | state.transactions.push(transaction); 20 | state.summary.total_transactions += 1; 21 | }, 22 | SET_RESOURCES(state, resources) { 23 | state.resources = resources; 24 | } 25 | }, 26 | actions: { 27 | async fetchResources({ commit }) { 28 | const resources = await fetchResources(); // Assuming fetchResources is imported from api.js 29 | commit('SET_RESOURCES', resources); 30 | }, 31 | async submitTransaction({ commit }, transaction) { 32 | await submitTransaction(transaction); // Assuming submitTransaction is imported from api.js 33 | commit('ADD_TRANSACTION', transaction); 34 | } 35 | } 36 | }); 37 | 38 | export default store; 39 | -------------------------------------------------------------------------------- /tests/test_api.py: -------------------------------------------------------------------------------- 1 | # tests/test_api.py 2 | 3 | import unittest 4 | from flask import Flask 5 | from api.app import app 6 | 7 | class TestAPIEndpoints(unittest.TestCase): 8 | def setUp(self): 9 | """Set up the Flask test client.""" 10 | self.app = app.test_client() 11 | self.app.testing = True 12 | 13 | def test_get_chain(self): 14 | """Test the /chain endpoint.""" 15 | response = self.app.get('/chain') 16 | self.assertEqual(response.status_code, 200) 17 | self.assertIn('chain', response.get_json()) 18 | 19 | def test_new_transaction(self): 20 | """Test the /transactions/new endpoint.""" 21 | response = self.app.post('/transactions/new', json={ 22 | 'sender': 'Alice', 23 | 'recipient': 'Bob', 24 | 'amount': 50 25 | }) 26 | self.assertEqual(response.status_code, 201) 27 | self.assertIn('message', response.get_json()) 28 | 29 | def test_mine_block(self): 30 | """Test the /mine endpoint.""" 31 | response = self.app.get('/mine') 32 | self.assertEqual(response.status_code, 200) 33 | self.assertIn('index', response.get_json()) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /src/tests/api_tests.py: -------------------------------------------------------------------------------- 1 | # src/tests/api_tests.py 2 | 3 | import unittest 4 | from flask import Flask 5 | from api.app import app 6 | 7 | class TestAPIEndpoints(unittest.TestCase): 8 | def setUp(self): 9 | """Set up the Flask test client.""" 10 | self.app = app.test_client() 11 | self.app.testing = True 12 | 13 | def test_get_chain(self): 14 | """Test the /chain endpoint.""" 15 | response = self.app.get('/chain') 16 | self.assertEqual(response.status_code, 200) 17 | self.assertIn('chain', response.get_json()) 18 | 19 | def test_new_transaction(self): 20 | """Test the /transactions/new endpoint.""" 21 | response = self.app.post('/transactions/new', json={ 22 | 'sender': 'Alice', 23 | 'recipient': 'Bob', 24 | 'amount': 50 25 | }) 26 | self.assertEqual(response.status_code, 201) 27 | self.assertIn('message', response.get_json()) 28 | 29 | def test_mine_block(self): 30 | """Test the /mine endpoint.""" 31 | response = self.app.get('/mine') 32 | self.assertEqual(response.status_code, 200) 33 | self.assertIn('index', response.get_json()) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /tests/test_integration.py: -------------------------------------------------------------------------------- 1 | # tests/test_integration.py 2 | 3 | import unittest 4 | from api.app import app 5 | from blockchain import Blockchain 6 | 7 | class TestIntegration(unittest.TestCase): 8 | def setUp(self): 9 | """Set up the Flask test client and a new blockchain instance.""" 10 | self.app = app.test_client() 11 | self.app.testing = True 12 | self.blockchain = Blockchain() 13 | 14 | def test_full_transaction_flow(self): 15 | """Test the full flow of creating and mining a transaction.""" 16 | # Create a new transaction 17 | response = self.app.post('/transactions/new', json={ 18 | 'sender': 'Alice', 19 | 'recipient': 'Bob', 20 | 'amount': 50 21 | }) 22 | self.assertEqual(response.status_code, 201) 23 | 24 | # Mine the block 25 | response = self.app.get('/mine') 26 | self.assertEqual(response.status_code, 200) 27 | self.assertIn('index', response.get_json()) 28 | 29 | # Check the blockchain for the new transaction 30 | self.assertEqual(len(self.blockchain.chain), 1) 31 | self.assertEqual(self.blockchain.chain[0]['transactions'][0]['sender'], 'Alice') 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /src/tests/integration_tests.py: -------------------------------------------------------------------------------- 1 | # src/tests/integration_tests.py 2 | 3 | import unittest 4 | from api.app import app 5 | from blockchain import Blockchain ```python 6 | class TestIntegration(unittest.TestCase): 7 | def setUp(self): 8 | """Set up the Flask test client and a new blockchain instance.""" 9 | self.app = app.test_client() 10 | self.app.testing = True 11 | self.blockchain = Blockchain() 12 | 13 | def test_full_transaction_flow(self): 14 | """Test the full flow of creating and mining a transaction.""" 15 | # Create a new transaction 16 | response = self.app.post('/transactions/new', json={ 17 | 'sender': 'Alice', 18 | 'recipient': 'Bob', 19 | 'amount': 50 20 | }) 21 | self.assertEqual(response.status_code, 201) 22 | 23 | # Mine the block 24 | response = self.app.get('/mine') 25 | self.assertEqual(response.status_code, 200) 26 | self.assertIn('index', response.get_json()) 27 | 28 | # Check the blockchain for the new transaction 29 | self.assertEqual(len(self.blockchain.chain), 1) 30 | self.assertEqual(self.blockchain.chain[0]['transactions'][0]['sender'], 'Alice') 31 | 32 | if __name__ == '__main__': 33 | unittest.main() 34 | -------------------------------------------------------------------------------- /src/frontend/components/NotificationBell.js: -------------------------------------------------------------------------------- 1 | // components/NotificationBell.js 2 | 3 | 9 | 10 | 33 | 34 | 49 | -------------------------------------------------------------------------------- /src/services/space_resource_service.py: -------------------------------------------------------------------------------- 1 | # src/services/space_resource_service.py 2 | 3 | import requests 4 | 5 | class SpaceResourceService: 6 | def __init__(self, api_key, base_url): 7 | self.api_key = api_key 8 | self.base_url = base_url 9 | 10 | def get_resources(self): 11 | """Fetches available space resources.""" 12 | response = requests.get(f"{self.base_url}/resources", headers=self._get_headers()) 13 | return self._handle_response(response) 14 | 15 | def allocate_resource(self, resource_id, amount): 16 | """Allocates a specified amount of a resource.""" 17 | payload = { 18 | 'resource_id': resource_id, 19 | 'amount': amount 20 | } 21 | response = requests.post(f"{self.base_url}/resources/allocate", json=payload, headers=self._get_headers()) 22 | return self._handle_response(response) 23 | 24 | def _get_headers(self): 25 | """Returns the headers for API requests.""" 26 | return { 27 | 'Authorization': f'Bearer {self.api_key}', 28 | 'Content-Type': 'application/json' 29 | } 30 | 31 | def _handle_response(self, response): 32 | """Handles API responses.""" 33 | if response.status_code == 200: 34 | return response.json() 35 | else: 36 | raise Exception(f"Error: {response.status_code} - {response.text}") 37 | -------------------------------------------------------------------------------- /src/services/payment_service.py: -------------------------------------------------------------------------------- 1 | # src/services/payment_service.py 2 | 3 | import requests 4 | 5 | class PaymentService: 6 | def __init__(self, api_key, base_url): 7 | self.api_key = api_key 8 | self.base_url = base_url 9 | 10 | def create_payment(self, sender, recipient, amount): 11 | """Initiates a payment transaction.""" 12 | payload = { 13 | 'sender': sender, 14 | 'recipient': recipient, 15 | 'amount': amount 16 | } 17 | response = requests.post(f"{self.base_url}/payments", json=payload, headers=self._get_headers()) 18 | return self._handle_response(response) 19 | 20 | def confirm_payment(self, payment_id): 21 | """Confirms a payment transaction.""" 22 | response = requests.post(f"{self.base_url}/payments/{payment_id}/confirm", headers=self._get_headers()) 23 | return self._handle_response(response) 24 | 25 | def _get_headers(self): 26 | """Returns the headers for API requests.""" 27 | return { 28 | 'Authorization': f'Bearer {self.api_key}', 29 | 'Content-Type': 'application/json' 30 | } 31 | 32 | def _handle_response(self, response): 33 | """Handles API responses.""" 34 | if response.status_code == 200: 35 | return response.json() 36 | else: 37 | raise Exception(f"Error: {response.status_code} - {response.text}") 38 | -------------------------------------------------------------------------------- /tests/test_blockchain.py: -------------------------------------------------------------------------------- 1 | # tests/test_blockchain.py 2 | 3 | import unittest 4 | from blockchain import Blockchain 5 | 6 | class TestBlockchain(unittest.TestCase): 7 | def setUp(self): 8 | """Set up a new blockchain instance for testing.""" 9 | self.blockchain = Blockchain() 10 | 11 | def test_create_genesis_block(self): 12 | """Test that the genesis block is created correctly.""" 13 | genesis_block = self.blockchain.chain[0] 14 | self.assertEqual(genesis_block['index'], 1) 15 | self.assertEqual(genesis_block['previous_hash'], '1') 16 | self.assertEqual(genesis_block['transactions'], []) 17 | self.assertIsNotNone(genesis_block['timestamp']) 18 | 19 | def test_add_transaction(self): 20 | """Test adding a transaction to the blockchain.""" 21 | self.blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) 22 | self.assertEqual(len(self.blockchain.current_transactions), 1) 23 | self.assertEqual(self.blockchain.current_transactions[0]['sender'], "Alice") 24 | 25 | def test_mine_block(self): 26 | """Test mining a new block.""" 27 | self.blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) 28 | previous_length = len(self.blockchain.chain) 29 | self.blockchain.mine() 30 | self.assertEqual(len(self.blockchain.chain), previous_length + 1) 31 | 32 | if __name__ == '__main__': 33 | unittest.main() 34 | -------------------------------------------------------------------------------- /src/tests/blockchain_tests.py: -------------------------------------------------------------------------------- 1 | # src/tests/blockchain_tests.py 2 | 3 | import unittest 4 | from blockchain import Blockchain 5 | 6 | class TestBlockchain(unittest.TestCase): 7 | def setUp(self): 8 | """Set up a new blockchain instance for testing.""" 9 | self.blockchain = Blockchain() 10 | 11 | def test_create_genesis_block(self): 12 | """Test that the genesis block is created correctly.""" 13 | genesis_block = self.blockchain.chain[0] 14 | self.assertEqual(genesis_block['index'], 1) 15 | self.assertEqual(genesis_block['previous_hash'], '1') 16 | self.assertEqual(genesis_block['transactions'], []) 17 | self.assertIsNotNone(genesis_block['timestamp']) 18 | 19 | def test_add_transaction(self): 20 | """Test adding a transaction to the blockchain.""" 21 | self.blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) 22 | self.assertEqual(len(self.blockchain.current_transactions), 1) 23 | self.assertEqual(self.blockchain.current_transactions[0]['sender'], "Alice") 24 | 25 | def test_mine_block(self): 26 | """Test mining a new block.""" 27 | self.blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) 28 | previous_length = len(self.blockchain.chain) 29 | self.blockchain.mine() 30 | self.assertEqual(len(self.blockchain.chain), previous_length + 1) 31 | 32 | if __name__ == '__main__': 33 | unittest.main() 34 | -------------------------------------------------------------------------------- /src/api/authentication.py: -------------------------------------------------------------------------------- 1 | import jwt 2 | import datetime 3 | from flask import request, jsonify 4 | from functools import wraps 5 | 6 | SECRET_KEY = 'your_secret_key' # Change this to a secure key in production 7 | 8 | # In-memory user storage for demonstration purposes 9 | users = { 10 | 'user1': 'password1', # Example user credentials 11 | } 12 | 13 | def generate_token(username): 14 | """Generates a JWT token for the user.""" 15 | token = jwt.encode({ 16 | 'user': username, 17 | 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour 18 | }, SECRET_KEY, algorithm='HS256') 19 | return token 20 | 21 | def authentication_middleware(): 22 | """Middleware for user authentication using JWT.""" 23 | token = None 24 | if 'Authorization' in request.headers: 25 | token = request.headers['Authorization'].split(" ")[1] 26 | 27 | if not token: 28 | return jsonify({'error': 'Token is missing!'}), 401 29 | 30 | try: 31 | data = jwt.decode(token, SECRET_KEY, algorithms=['HS256']) 32 | request.user = data['user'] # Store user info in request context 33 | except jwt.ExpiredSignatureError: 34 | return jsonify({'error': 'Token has expired!'}), 401 35 | except jwt.InvalidTokenError: 36 | return jsonify({'error': 'Invalid token!'}), 401 37 | 38 | def login_user(username, password): 39 | """Validates user credentials and returns a JWT token.""" 40 | if username in users and users[username] == password: 41 | return generate_token(username) 42 | return None 43 | -------------------------------------------------------------------------------- /src/blockchain/smart_contracts/contract_manager.py: -------------------------------------------------------------------------------- 1 | from web3 import Web3 2 | import json 3 | 4 | class ContractManager: 5 | def __init__(self, web3_provider, contract_address, abi_file): 6 | self.web3 = Web3(Web3.HTTPProvider(web3_provider)) 7 | self.contract_address = contract_address 8 | self.abi = self.load_abi(abi_file) 9 | self.contract = self.web3.eth.contract(address=self.contract_address, abi=self.abi) 10 | 11 | def load_abi(self, abi_file): 12 | with open(abi_file, 'r') as file: 13 | return json.load(file) 14 | 15 | def get_balance(self, address): 16 | return self.contract.functions.balanceOf(address).call() 17 | 18 | def transfer_tokens(self, from_address, to_address, amount, private_key): 19 | nonce = self.web3.eth.getTransactionCount(from_address) 20 | transaction = self.contract.functions.transfer(to_address, amount).buildTransaction({ 21 | 'chainId': 1, # Mainnet 22 | 'gas': 2000000, 23 | 'gasPrice': self.web3.toWei('50', 'gwei'), 24 | 'nonce': nonce, 25 | }) 26 | 27 | signed_txn = self.web3.eth.account.signTransaction(transaction, private_key=private_key) 28 | txn_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction) 29 | return txn_hash.hex() 30 | 31 | def get_contract_info(self): 32 | return { 33 | 'address': self.contract_address, 34 | 'name': self.contract.functions.name().call(), 35 | 'totalSupply': self.contract.functions.totalSupply().call(), 36 | } 37 | -------------------------------------------------------------------------------- /src/blockchain/smart_contracts/contract_template.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract CosmicPiContract { 5 | string public name; 6 | address public owner; 7 | uint256 public totalSupply; 8 | uint256 public constant PI_COIN_VALUE = 314159; // Fixed value of Pi Coin in USD 9 | 10 | mapping(address => uint256) public balances; 11 | 12 | event Transfer(address indexed from, address indexed to, uint256 value); 13 | event ContractCreated(string name, address owner, uint256 totalSupply); 14 | 15 | constructor(string memory _name, uint256 _totalSupply) { 16 | name = _name; 17 | owner = msg.sender; 18 | totalSupply = _totalSupply; 19 | balances[owner] = totalSupply; 20 | emit ContractCreated(name, owner, totalSupply); 21 | } 22 | 23 | // Function to transfer tokens 24 | function transfer(address _to, uint256 _value) public returns (bool success) { 25 | require(balances[msg.sender] >= _value, "Insufficient balance"); 26 | require(_to != address(0), "Invalid address"); 27 | 28 | balances[msg.sender] -= _value; 29 | balances[_to] += _value; 30 | emit Transfer(msg.sender, _to, _value); 31 | return true; 32 | } 33 | 34 | // Function to check the balance of an address 35 | function balanceOf(address _owner) public view returns (uint256 balance) { 36 | return balances[_owner]; 37 | } 38 | 39 | // Function to get the fixed value of Pi Coin in USD 40 | function getPiCoinValue() public pure returns (uint256) { 41 | return PI_COIN_VALUE; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/api/routes/transactions.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint, jsonify, request 2 | from blockchain import Blockchain 3 | from utils import validate_transaction 4 | 5 | transactions_bp = Blueprint('transactions', __name__) 6 | blockchain = Blockchain() 7 | 8 | @transactions_bp.route('/new', methods=['POST']) 9 | def new_transaction(): 10 | values = request.get_json() 11 | 12 | # Validate transaction data 13 | if not validate_transaction(values): 14 | return jsonify({'error': 'Invalid transaction data'}), 400 15 | 16 | # Create a new transaction 17 | index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) 18 | 19 | response = {'message': f'Transaction will be added to Block {index}'} 20 | return jsonify(response), 201 21 | 22 | @transactions_bp.route('/mine', methods=['GET']) 23 | def mine(): 24 | last_block = blockchain.last_block 25 | last_proof = last_block['proof'] 26 | proof = proof_of_work(last_proof) 27 | 28 | # Reward for finding the proof 29 | blockchain.new_transaction( 30 | sender="0", # The sender is 0 to signify that this is a new coin 31 | recipient=request.remote_addr, 32 | amount=1, # Reward amount can be adjusted as needed 33 | ) 34 | 35 | # Create the new block 36 | previous_hash = blockchain.hash(last_block) 37 | block = blockchain.create_block(proof, previous_hash) 38 | 39 | response = { 40 | 'index': block['index'], 41 | 'transactions': block['transactions'], 42 | 'proof': block['proof'], 43 | 'previous_hash': block['previous_hash'], 44 | } 45 | return jsonify(response), 200 46 | -------------------------------------------------------------------------------- /src/blockchain/consensus/proof_of_stake.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import time 3 | 4 | class ProofOfStake: 5 | def __init__(self): 6 | self.stakers = {} # Dictionary to hold staker addresses and their stakes 7 | 8 | def stake(self, address, amount): 9 | """Allows a user to stake a certain amount of coins.""" 10 | if address in self.stakers: 11 | self.stakers[address] += amount 12 | else: 13 | self.stakers[address] = amount 14 | 15 | def get_total_stake(self): 16 | """Returns the total stake in the network.""" 17 | return sum(self.stakers.values()) 18 | 19 | def select_validator(self): 20 | """Selects a validator based on their stake.""" 21 | total_stake = self.get_total_stake() 22 | if total_stake == 0: 23 | return None # No validators available 24 | 25 | # Randomly select a validator based on their stake 26 | random_value = random.uniform(0, total_stake) 27 | cumulative = 0 28 | 29 | for address, stake in self.stakers.items(): 30 | cumulative += stake 31 | if cumulative >= random_value: 32 | return address 33 | 34 | def validate_block(self, block, validator): 35 | """Validates a block proposed by a validator.""" 36 | # Implement block validation logic (e.g., checking previous hash, transactions) 37 | # For simplicity, we assume the block is valid if it comes from a selected validator 38 | return block['validator'] == validator 39 | 40 | def get_stakers(self): 41 | """Returns the list of stakers.""" 42 | return self.stakers 43 | -------------------------------------------------------------------------------- /docs/user_guide.md: -------------------------------------------------------------------------------- 1 | # Cosmic Pi User Guide 2 | 3 | ## Introduction 4 | This user guide provides instructions on how to use the Cosmic Pi platform, including account creation, transaction management, and resource handling. 5 | 6 | ## Getting Started 7 | ### Creating an Account 8 | 1. Navigate to the Cosmic Pi web application. 9 | 2. Click on the "Sign Up" button. 10 | 3. Fill in the required fields: username, password, and email. 11 | 4. Click "Submit" to create your account. 12 | 13 | ### Logging In 14 | 1. Go to the login page. 15 | 2. Enter your username and password. 16 | 3. Click "Login" to access your dashboard. 17 | 18 | ## Managing Transactions 19 | ### Sending Pi Coins 20 | 1. From your dashboard, select "Send Coins." 21 | 2. Enter the recipient's address and the amount to send. 22 | 3. Click "Send" to initiate the transaction. 23 | 4. You will receive a confirmation once the transaction is processed. 24 | 25 | ### Viewing Transaction History 26 | 1. Navigate to the "Transactions" section in your dashboard. 27 | 2. Here, you can view all your past transactions, including their status and details. 28 | 29 | ## Resource Management 30 | ### Viewing Available Resources 31 | 1. Go to the "Resources" tab in your dashboard. 32 | 2. You will see a list of all available resources, including their quantities. 33 | 34 | ### Requesting Resources 35 | 1. Select the resource you wish to request. 36 | 2. Click on "Request Resource" and specify the quantity. 37 | 3. Submit your request for processing. 38 | 39 | ## Conclusion 40 | This user guide aims to help you navigate the Cosmic Pi platform effectively. For further assistance, please refer to the FAQ section or contact support. 41 | -------------------------------------------------------------------------------- /src/frontend/components/TransactionForm.js: -------------------------------------------------------------------------------- 1 | // components/TransactionForm.js 2 | 3 | 15 | 16 | 49 | 50 | 55 | -------------------------------------------------------------------------------- /docs/deployment_guide.md: -------------------------------------------------------------------------------- 1 | # Cosmic Pi Deployment Guide 2 | 3 | ## Introduction 4 | This guide provides instructions for deploying the Cosmic Pi application in a production environment, ensuring a smooth and efficient setup. 5 | 6 | ## Prerequisites 7 | - A server with Ubuntu 20.04 or later. 8 | - Docker and Docker Compose installed. 9 | - Access to a PostgreSQL or MongoDB database. 10 | 11 | ## Deployment Steps 12 | ### Step 1: Clone the Repository 13 | ```bash 14 | 1 git clone https://github.com/KOSASIH/cosmic-pi.git 15 | 2 cd cosmic-pi 16 | ``` 17 | 18 | ### Step 2: Configure Environment Variables 19 | - Copy the .env.example file to .env and update the variables as needed. 20 | 21 | ### Step 3: Build Docker Containers 22 | ```bash 23 | 1 docker-compose build 24 | ``` 25 | 26 | ### Step 4: Start the Application 27 | ```bash 28 | 1 docker-compose up -d 29 | ``` 30 | 31 | ### Step 5: Database Migration 32 | Run the database migrations to set up the initial schema: 33 | ```bash 34 | 1 docker-compose exec api python src/api/manage.py migrate 35 | ``` 36 | 37 | ### Step 6: Access the Application 38 | - Open your web browser and navigate to http://your-server-ip:5000 to access the Cosmic Pi application. 39 | 40 | ## Best Practices 41 | - Regularly back up your database. 42 | - Monitor application performance and logs. 43 | - Implement SSL for secure communication. 44 | 45 | ## Conclusion 46 | Following this deployment guide will ensure that the Cosmic Pi application is set up correctly in a production environment. Regular updates and maintenance are recommended to keep the system secure and efficient. For further assistance, please refer to the troubleshooting section or contact the support team. 47 | -------------------------------------------------------------------------------- /src/blockchain/utils.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | from time import time 4 | 5 | def hash_block(block): 6 | """Creates a SHA-256 hash of a block.""" 7 | block_string = json.dumps(block, sort_keys=True).encode() 8 | return hashlib.sha256(block_string).hexdigest() 9 | 10 | def validate_transaction(transaction): 11 | """Validates a transaction to ensure it has the required fields.""" 12 | required_fields = ['sender', 'recipient', 'amount'] 13 | return all(field in transaction for field in required_fields) and transaction['amount'] > 0 14 | 15 | def create_genesis_block(): 16 | """Creates the genesis block for the blockchain.""" 17 | return { 18 | 'index': 1, 19 | 'timestamp': time(), 20 | 'transactions': [], 21 | 'proof': 100, # Arbitrary proof for the genesis block 22 | 'previous_hash': '1', # Previous hash for the genesis block 23 | } 24 | 25 | def format_timestamp(timestamp): 26 | """Formats a timestamp into a human-readable string.""" 27 | return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)) 28 | 29 | def calculate_transaction_fee(amount): 30 | """Calculates the transaction fee based on the amount.""" 31 | fee_percentage = 0.01 # 1% transaction fee 32 | return amount * fee_percentage 33 | 34 | def is_valid_chain(chain): 35 | """Validates the entire blockchain to ensure integrity.""" 36 | for i in range(1, len(chain)): 37 | current_block = chain[i] 38 | previous_block = chain[i - 1] 39 | 40 | # Check if the previous hash is correct 41 | if current_block['previous_hash'] != hash_block(previous_block): 42 | return False 43 | 44 | # Check if the current block's transactions are valid 45 | for transaction in current_block['transactions']: 46 | if not validate_transaction(transaction): 47 | return False 48 | 49 | return True 50 | -------------------------------------------------------------------------------- /docs/design_specifications.md: -------------------------------------------------------------------------------- 1 | # Cosmic Pi Design Specifications 2 | 3 | ## Introduction 4 | This document outlines the design specifications for the Cosmic Pi project, detailing the user interface, system components, and interaction flows. 5 | 6 | ## User Interface Design 7 | ### Dashboard 8 | - **Overview:** The main dashboard provides users with a summary of their account, recent transactions, and available resources. 9 | - **Components:** 10 | - Navigation Bar: Links to Home, Transactions, Resources, and Settings. 11 | - Summary Cards: Display total balance, recent transactions, and resource status. 12 | 13 | ### Transaction Page 14 | - **Overview:** A dedicated page for managing transactions. 15 | - **Components:** 16 | - Input Fields: For entering recipient address and amount. 17 | - Submit Button: To initiate the transaction. 18 | - Transaction History: A list of past transactions with status indicators. 19 | 20 | ## System Component Design 21 | ### Blockchain Layer 22 | - **Technology Stack:** Node.js, Express, and PostgreSQL. 23 | - **Key Features:** 24 | - Smart Contracts: Written in Solidity for automated transactions. 25 | - Consensus Mechanism: Hybrid PoS and DPoS for enhanced security. 26 | 27 | ### API Layer 28 | - **Architecture:** RESTful API with JSON responses. 29 | - **Endpoints:** User management, transaction processing, and resource handling. 30 | 31 | ## Interaction Flows 32 | ### User Registration Flow 33 | 1. User fills out the registration form. 34 | 2. System validates input and creates a new user account. 35 | 3. Confirmation email is sent to the user. 36 | 37 | ### Transaction Flow 38 | 1. User initiates a transaction. 39 | 2. System verifies user balance and processes the transaction. 40 | 3. Transaction status is updated and reflected in the user's dashboard. 41 | 42 | ## Conclusion 43 | The design specifications provide a comprehensive overview of the Cosmic Pi project’s architecture and user interface. This document will be updated as the project evolves and new features are added. 44 | -------------------------------------------------------------------------------- /src/blockchain/consensus/delegated_proof_of_stake.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class DelegatedProofOfStake: 4 | def __init__(self): 5 | self.delegates = {} # Dictionary to hold delegate addresses and their votes 6 | self.voters = {} # Dictionary to hold voter addresses and their stakes 7 | 8 | def delegate(self, voter_address, delegate_address, amount): 9 | """Allows a voter to delegate their stake to a delegate.""" 10 | if voter_address in self.voters: 11 | self.voters[voter_address] += amount 12 | else: 13 | self.voters[voter_address] = amount 14 | 15 | if delegate_address in self.delegates: 16 | self.delegates[delegate_address] += amount 17 | else: 18 | self.delegates[delegate_address] = amount 19 | 20 | def select_delegates(self, num_delegates): 21 | """Selects a number of delegates based on their total votes.""" 22 | total_votes = sum(self.delegates.values()) 23 | if total_votes == 0: 24 | return [] # No delegates available 25 | 26 | selected_delegates = [] 27 | for _ in range(num_delegates): 28 | random_value = random.uniform(0, total_votes) 29 | cumulative = 0 30 | 31 | for address, votes in self.delegates.items(): 32 | cumulative += votes 33 | if cumulative >= random_value: 34 | selected_delegates.append(address) 35 | break 36 | 37 | return selected_delegates 38 | 39 | def validate_block(self, block, delegates): 40 | """Validates a block proposed by selected delegates.""" 41 | # Implement block validation logic (e.g., checking previous hash, transactions) 42 | # For simplicity, we assume the block is valid if it comes from one of the selected delegates 43 | return block['validator'] in delegates 44 | 45 | def get_delegates(self): 46 | """Returns the list of delegates and their votes.""" 47 | return self.delegates 48 | -------------------------------------------------------------------------------- /docs/architecture.md: -------------------------------------------------------------------------------- 1 | # Cosmic Pi Architecture Overview 2 | 3 | ## Introduction 4 | The architecture of Cosmic Pi (CPi) is designed to support a scalable, secure, and efficient blockchain ecosystem for interstellar transactions and resource management. This document outlines the key components and their interactions. 5 | 6 | ## System Components 7 | 1. **Blockchain Layer** 8 | - Implements the core blockchain functionality, including transaction processing, consensus mechanisms, and smart contracts. 9 | - Utilizes a hybrid consensus model combining Proof of Stake (PoS) and Delegated Proof of Stake (DPoS). 10 | 11 | 2. **API Layer** 12 | - Provides a RESTful API for external applications to interact with the blockchain. 13 | - Handles user authentication, transaction management, and resource queries. 14 | 15 | 3. **Frontend Layer** 16 | - A web-based user interface that allows users to interact with the blockchain. 17 | - Built using modern JavaScript frameworks (e.g., React, Vue.js) for a responsive user experience. 18 | 19 | 4. **Database Layer** 20 | - Stores user data, transaction history, and resource information. 21 | - Utilizes PostgreSQL or MongoDB for structured and unstructured data storage. 22 | 23 | 5. **Oracle Service** 24 | - Integrates real-world data into the blockchain for smart contracts and decision-making. 25 | - Ensures data integrity and reliability through multiple data sources. 26 | 27 | ## Data Flow 28 | 1. Users interact with the frontend application. 29 | 2. The frontend communicates with the API layer to perform actions (e.g., transactions, queries). 30 | 3. The API layer processes requests and interacts with the blockchain layer. 31 | 4. The blockchain layer executes transactions and updates the database layer. 32 | 5. The oracle service provides external data as needed. 33 | 34 | ## Security Considerations 35 | - Implementing encryption for data in transit and at rest. 36 | - Utilizing secure authentication mechanisms (e.g., OAuth2). 37 | - Regular security audits and vulnerability assessments. 38 | 39 | ## Conclusion 40 | The architecture of Cosmic Pi is designed to be modular, allowing for easy updates and scalability as the project evolves. This document will be updated as new features and components are added. 41 | -------------------------------------------------------------------------------- /src/frontend/scripts/app.js: -------------------------------------------------------------------------------- 1 | // scripts/app.js 2 | 3 | new Vue({ 4 | el: '#app', 5 | data: { 6 | transaction: { 7 | sender: '', 8 | recipient: '', 9 | amount: null 10 | }, 11 | transactions: [], 12 | resources: [], 13 | summary: { 14 | total_transactions: 0, 15 | total_users: 0 16 | }, 17 | loading: false, 18 | error: null 19 | }, 20 | methods: { 21 | async fetchResources() { 22 | this.loading = true; 23 | try { 24 | const response = await fetch('/api/resources'); 25 | if (!response.ok) throw new Error('Failed to fetch resources'); 26 | this.resources = await response.json(); 27 | } catch (err) { 28 | this.error = err.message; 29 | } finally { 30 | this.loading = false; 31 | } 32 | }, 33 | async submitTransaction() { 34 | this.loading = true; 35 | this.error = null; 36 | try { 37 | const response = await fetch('/api/transactions/new', { 38 | method: 'POST', 39 | headers: { 40 | 'Content-Type': 'application/json' 41 | }, 42 | body: JSON.stringify(this.transaction) 43 | }); 44 | if (!response.ok) throw new Error('Transaction failed'); 45 | const result = await response.json(); 46 | this.transactions.push({ 47 | id: this.transactions.length + 1, 48 | ...this.transaction 49 | }); 50 | this.summary.total_transactions += 1; 51 | this.resetTransactionForm(); 52 | } catch (err) { 53 | this.error = err.message; 54 | } finally { 55 | this.loading = false; 56 | } 57 | }, 58 | resetTransactionForm() { 59 | this.transaction.sender = ''; 60 | this.transaction.recipient = ''; 61 | this.transaction.amount = null; 62 | } 63 | }, 64 | mounted() { 65 | this.fetchResources(); 66 | } 67 | }); 68 | -------------------------------------------------------------------------------- /src/constants.py: -------------------------------------------------------------------------------- 1 | # src/constants.py 2 | 3 | """ 4 | Pi Coin Configuration Constants 5 | This module contains constants related to the Pi Coin cryptocurrency. 6 | """ 7 | 8 | # Pi Coin Symbol 9 | PI_COIN_SYMBOL = "Pi" # Symbol for Pi Coin 10 | 11 | # Pi Coin Value 12 | PI_COIN_VALUE = 314159 # Fixed value of Pi Coin in USD 13 | 14 | # Pi Coin Supply 15 | PI_COIN_SUPPLY = 100_000_000_000 # Total supply of Pi Coin 16 | 17 | # Pi Coin Transaction Fee 18 | PI_COIN_TRANSACTION_FEE = 0.01 # Transaction fee in USD 19 | 20 | # Pi Coin Block Time 21 | PI_COIN_BLOCK_TIME = 10 # Average block time in seconds 22 | 23 | # Pi Coin Mining Difficulty 24 | PI_COIN_MINING_DIFFICULTY = 1000 # Difficulty level for mining Pi Coin 25 | 26 | # Pi Coin Reward for Mining 27 | PI_COIN_MINING_REWARD = 12.5 # Reward for mining a block 28 | 29 | # Pi Coin Network Protocol 30 | PI_COIN_NETWORK_PROTOCOL = "PoS" # Proof of Stake 31 | 32 | # Pi Coin Maximum Transaction Size 33 | PI_COIN_MAX_TRANSACTION_SIZE = 1_000_000 # Maximum transaction size in bytes 34 | 35 | # Pi Coin Decimals 36 | PI_COIN_DECIMALS = 18 # Number of decimal places for Pi Coin 37 | 38 | # Pi Coin Genesis Block Timestamp 39 | PI_COIN_GENESIS_BLOCK_TIMESTAMP = "2025-01-01T00:00:00Z" # Timestamp of the genesis block 40 | 41 | # Pi Coin Governance Model 42 | PI_COIN_GOVERNANCE_MODEL = "Decentralized" # Governance model for Pi Coin 43 | 44 | # Pi Coin Security Features 45 | PI_COIN_ENCRYPTION_ALGORITHM = "AES-256" # Encryption algorithm for securing transactions 46 | PI_COIN_HASHING_ALGORITHM = "SHA-256" # Hashing algorithm for block verification 47 | PI_COIN_SIGNATURE_SCHEME = "ECDSA" # Digital signature scheme for transaction signing 48 | 49 | # Pi Coin Network Parameters 50 | PI_COIN_MAX_PEERS = 100 # Maximum number of peers in the network 51 | PI_COIN_NODE_TIMEOUT = 30 # Timeout for node responses in seconds 52 | PI_COIN_CONNECTION_RETRY_INTERVAL = 5 # Retry interval for node connections in seconds 53 | 54 | # Pi Coin Staking Parameters 55 | PI_COIN_MIN_STAKE_AMOUNT = 100 # Minimum amount required to stake 56 | PI_COIN_STAKE_REWARD_RATE = 0.05 # Annual reward rate for staking 57 | 58 | # Pi Coin API Rate Limits 59 | PI_COIN_API_REQUEST_LIMIT = 1000 # Maximum API requests per hour 60 | PI_COIN_API_KEY_EXPIRATION = 3600 # API key expiration time in seconds 61 | 62 | # Pi Coin Regulatory Compliance 63 | PI_COIN_KYC_REQUIRED = True # Whether KYC is required for transactions 64 | PI_COIN_COMPLIANCE_JURISDICTIONS = ["US", "EU", "UK"] # Jurisdictions for compliance 65 | 66 | # Additional constants can be added here as needed 67 | -------------------------------------------------------------------------------- /src/services/analytics_service.py: -------------------------------------------------------------------------------- 1 | # src/services/analytics_service.py 2 | 3 | import requests 4 | 5 | class AnalyticsService: 6 | def __init__(self, api_key, base_url): 7 | """ 8 | Initializes the AnalyticsService with the provided API key and base URL. 9 | 10 | :param api_key: API key for authentication with the analytics service 11 | :param base_url: Base URL of the analytics API 12 | """ 13 | self.api_key = api_key 14 | self.base_url = base_url 15 | 16 | def get_user_activity(self, user_id): 17 | """ 18 | Fetches user activity data for a specific user. 19 | 20 | :param user_id: The ID of the user whose activity data is to be fetched 21 | :return: JSON response containing user activity data 22 | """ 23 | response = requests.get(f"{self.base_url}/analytics/user/{user_id}", headers=self._get_headers()) 24 | return self._handle_response(response) 25 | 26 | def get_transaction_stats(self): 27 | """ 28 | Fetches statistics on transactions. 29 | 30 | :return: JSON response containing transaction statistics 31 | """ 32 | response = requests.get(f"{self.base_url}/analytics/transactions", headers=self._get_headers()) 33 | return self._handle_response(response) 34 | 35 | def get_system_health(self): 36 | """ 37 | Fetches the health status of the analytics system. 38 | 39 | :return: JSON response containing system health information 40 | """ 41 | response = requests.get(f"{self.base_url}/analytics/health", headers=self._get_headers()) 42 | return self._handle_response(response) 43 | 44 | def _get_headers(self): 45 | """ 46 | Returns the headers for API requests. 47 | 48 | :return: Dictionary containing authorization and content type headers 49 | """ 50 | return { 51 | 'Authorization': f'Bearer {self.api_key}', 52 | 'Content-Type': 'application/json' 53 | } 54 | 55 | def _handle_response(self, response): 56 | """ 57 | Handles API responses and raises exceptions for errors. 58 | 59 | :param response: The response object from the requests library 60 | :return: Parsed JSON response if successful 61 | :raises Exception: If the response status code indicates an error 62 | """ 63 | if response.status_code == 200: 64 | return response.json() 65 | else: 66 | raise Exception(f"Error: {response.status_code} - {response.text}") 67 | -------------------------------------------------------------------------------- /src/blockchain/blockchain.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | from time import time 4 | from urllib.parse import urlparse 5 | import requests 6 | 7 | class Blockchain: 8 | def __init__(self): 9 | self.chain = [] 10 | self.current_transactions = [] 11 | self.nodes = set() 12 | self.create_block(previous_hash='1', proof=100) # Genesis block 13 | 14 | def create_block(self, proof, previous_hash=None): 15 | block = { 16 | 'index': len(self.chain) + 1, 17 | 'timestamp': time(), 18 | 'transactions': self.current_transactions, 19 | 'proof': proof, 20 | 'previous_hash': previous_hash or self.hash(self.chain[-1]), 21 | } 22 | self.current_transactions = [] # Reset the current list of transactions 23 | self.chain.append(block) 24 | return block 25 | 26 | @staticmethod 27 | def hash(block): 28 | block_string = json.dumps(block, sort_keys=True).encode() 29 | return hashlib.sha256(block_string).hexdigest() 30 | 31 | def new_transaction(self, sender, recipient, amount): 32 | self.current_transactions.append({ 33 | 'sender': sender, 34 | 'recipient': recipient, 35 | 'amount': amount, 36 | }) 37 | return self.last_block['index'] + 1 38 | 39 | @property 40 | def last_block(self): 41 | return self.chain[-1] 42 | 43 | def register_node(self, address): 44 | parsed_url = urlparse(address) 45 | self.nodes.add(parsed_url.netloc) 46 | 47 | def resolve_conflicts(self): 48 | neighbors = self.nodes 49 | new_chain = None 50 | max_length = len(self.chain) 51 | 52 | for node in neighbors: 53 | response = requests.get(f'http://{node}/chain') 54 | if response.status_code == 200: 55 | length = response.json()['length'] 56 | chain = response.json()['chain'] 57 | 58 | if length > max_length and self.valid_chain(chain): 59 | max_length = length 60 | new_chain = chain 61 | 62 | if new_chain: 63 | self.chain = new_chain 64 | return True 65 | return False 66 | 67 | @staticmethod 68 | def valid_chain(chain): 69 | last_block = chain[0] 70 | current_index = 1 71 | 72 | while current_index < len(chain): 73 | block = chain[current_index] 74 | if block['previous_hash'] != Blockchain.hash(last_block): 75 | return False 76 | last_block = block 77 | current_index += 1 78 | 79 | return True 80 | -------------------------------------------------------------------------------- /docs/api_reference.md: -------------------------------------------------------------------------------- 1 | # Cosmic Pi API Reference 2 | 3 | ## Introduction 4 | The Cosmic Pi API provides a set of endpoints for interacting with the blockchain and managing resources. This document outlines the available endpoints, request/response formats, and authentication requirements. 5 | 6 | ## Base URL 7 | 8 | http://localhost:5000/api/v1 9 | 10 | ## Authentication 11 | All API requests require an API key. Include the API key in the request headers: 12 | 13 | Authorization: Bearer YOUR_API_KEY 14 | 15 | 16 | ## Endpoints 17 | 18 | ### 1. User Management 19 | 20 | #### Create User 21 | - **Endpoint:** `POST /users` 22 | - **Request Body:** 23 | 24 | ```json 25 | 1 { 26 | 2 "username": "string", 27 | 3 "password": "string", 28 | 4 "email": "string" 29 | 5 } 30 | ``` 31 | 32 | - **Response** 33 | 34 | ```json 35 | 1 { 36 | 2 "id": "string", 37 | 3 "username": "string", 38 | 4 "email": "string" 39 | 5 } 40 | ``` 41 | 42 | - **Get User** 43 | - **Endpoint**: GET /users/{id} 44 | - **Response** 45 | 46 | ```json 47 | 1 { 48 | 2 "id": "string", 49 | 3 "username": "string", 50 | 4 "email": "string" 51 | 5 } 52 | ``` 53 | 54 | ### 2. Transaction Management 55 | #### Create Transaction 56 | - **Endpoint**: POST /transactions 57 | - **Request Body**: 58 | 59 | ```json 60 | 1 { 61 | 2 "from": "string", 62 | 3 "to": "string", 63 | 4 "amount": "number" 64 | 5 } 65 | ``` 66 | 67 | - **Response**: 68 | 69 | ```json 70 | 1 { 71 | 2 "transaction_id": "string", 72 | 3 "status": "string" 73 | 4 } 74 | ``` 75 | 76 | #### Get Transaction 77 | - **Endpoint**: GET /transactions/{id} 78 | - **Response**: 79 | 80 | ```json 81 | 1 { 82 | 2 "transaction_id": "string", 83 | 3 "from": "string", 84 | 4 "to": "string", 85 | 5 "amount": "number", 86 | 6 "status": "string" 87 | 7 } 88 | ``` 89 | 90 | ### 3. Resource Management 91 | #### Get Resources 92 | - **Endpoint**: GET /resources 93 | - **Response**: 94 | 95 | ```json 96 | 1 [ 97 | 2 { 98 | 3 "id": "string", 99 | 4 "name": "string", 100 | 5 "quantity": "number" 101 | 6 } 102 | 7 ] 103 | ``` 104 | 105 | ## Error Handling 106 | All error responses will include a status code and a message: 107 | 108 | ```json 109 | 1 { 110 | 2 "error": { 111 | 3 "code": "string", 112 | 4 "message": "string" 113 | 5 } 114 | 6 } 115 | ``` 116 | 117 | ## Conclusion 118 | This API reference provides a comprehensive overview of the available endpoints for the Cosmic Pi project. For further details, please refer to the source code or contact the development team. 119 | -------------------------------------------------------------------------------- /src/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Cosmic Pi - Blockchain Explorer 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |

Cosmic Pi Blockchain Explorer

15 | 22 |
23 | 24 |
25 |
26 |

Transactions

27 |
28 |
29 | 30 | 31 | 32 | 33 |
34 |
35 |
36 |

Transaction History

37 |
    38 |
  • {{ tx.sender }} sent {{ tx.amount }} to {{ tx.recipient }}
  • 39 |
40 |
41 |
42 | 43 |
44 |

Resources

45 |
46 |

Available Resources

47 |
    48 |
  • {{ resource.name }}: {{ resource.amount }}
  • 49 |
50 |
51 |
52 | 53 |
54 |

Analytics

55 |
56 |

Blockchain Summary

57 |

Total Transactions: {{ summary.total_transactions }}

58 |

Total Users: {{ summary.total_users }}

59 |
60 |
61 |
62 | 63 |
64 |

© 2025 Cosmic Pi. All rights reserved.

65 |
66 |
67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/api/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify, request 2 | from blockchain import Blockchain 3 | from utils import validate_transaction, create_genesis_block 4 | from constants import PI_COIN_VALUE 5 | 6 | app = Flask(__name__) 7 | 8 | # Create a new instance of the Blockchain 9 | blockchain = Blockchain() 10 | 11 | # Initialize the blockchain with a genesis block 12 | blockchain.chain.append(create_genesis_block()) 13 | 14 | @app.route('/transactions/new', methods=['POST']) 15 | def new_transaction(): 16 | values = request.get_json() 17 | 18 | # Check that the required fields are in the POST data 19 | if not validate_transaction(values): 20 | return jsonify({'error': 'Invalid transaction data'}), 400 21 | 22 | # Create a new transaction 23 | index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) 24 | 25 | response = {'message': f'Transaction will be added to Block {index}'} 26 | return jsonify(response), 201 27 | 28 | @app.route('/mine', methods=['GET']) 29 | def mine(): 30 | last_block = blockchain.last_block 31 | last_proof = last_block['proof'] 32 | proof = proof_of_work(last_proof) 33 | 34 | # Reward for finding the proof 35 | blockchain.new_transaction( 36 | sender="0", # The sender is 0 to signify that this is a new coin 37 | recipient=request.remote_addr, 38 | amount=1, # Reward amount can be adjusted as needed 39 | ) 40 | 41 | # Create the new block 42 | previous_hash = blockchain.hash(last_block) 43 | block = blockchain.create_block(proof, previous_hash) 44 | 45 | response = { 46 | 'index': block['index'], 47 | 'transactions': block['transactions'], 48 | 'proof': block['proof'], 49 | 'previous_hash': block['previous_hash'], 50 | } 51 | return jsonify(response), 200 52 | 53 | @app.route('/chain', methods=['GET']) 54 | def full_chain(): 55 | response = { 56 | 'chain': blockchain.chain, 57 | 'length': len(blockchain.chain), 58 | } 59 | return jsonify(response), 200 60 | 61 | @app.route('/nodes/register', methods=['POST']) 62 | def register_nodes(): 63 | values = request.get_json() 64 | nodes = values.get('nodes') 65 | 66 | if nodes is None: 67 | return jsonify({'error': 'Error: Please supply a valid list of nodes'}), 400 68 | 69 | for node in nodes: 70 | blockchain.register_node(node) 71 | 72 | response = { 73 | 'message': 'New nodes have been added', 74 | 'total_nodes': list(blockchain.nodes), 75 | } 76 | return jsonify(response), 201 77 | 78 | @app.route('/nodes/resolve', methods=['GET']) 79 | def consensus(): 80 | replaced = blockchain.resolve_conflicts() 81 | 82 | if replaced: 83 | response = { 84 | 'message': 'Our chain was replaced', 85 | 'new_chain': blockchain.chain, 86 | } 87 | else: 88 | response = { 89 | 'message': 'Our chain is authoritative', 90 | 'chain': blockchain.chain, 91 | } 92 | 93 | return jsonify(response), 200 94 | 95 | def proof_of_work(last_proof): 96 | proof = 0 97 | while not valid_proof(last_proof, proof): 98 | proof += 1 99 | return proof 100 | 101 | def valid_proof(last_proof, proof): 102 | guess = f'{last_proof}{proof}'.encode() 103 | guess_hash = hashlib.sha256(guess).hexdigest() 104 | return guess_hash[:4] == "0000" # The proof must be a hash that starts with four zeros 105 | 106 | if __name__ == '__main__': 107 | app.run(host='0.0.0.0', port=5000) 108 | -------------------------------------------------------------------------------- /src/blockchain/transaction.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify, request 2 | from blockchain import Blockchain 3 | from constants import PI_COIN_VALUE # Import the fixed value of Pi Coin 4 | import hashlib 5 | 6 | app = Flask(__name__) 7 | 8 | # Create a new instance of the Blockchain 9 | blockchain = Blockchain() 10 | 11 | @app.route('/transactions/new', methods=['POST']) 12 | def new_transaction(): 13 | values = request.get_json() 14 | 15 | # Check that the required fields are in the POST data 16 | required_fields = ['sender', 'recipient', 'amount'] 17 | if not all(field in values for field in required_fields): 18 | return 'Missing values', 400 19 | 20 | # Validate the amount against the fixed value of Pi Coin 21 | if values['amount'] <= 0: 22 | return 'Invalid amount. Must be greater than zero.', 400 23 | 24 | # Create a new transaction 25 | index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) 26 | 27 | response = {'message': f'Transaction will be added to Block {index}'} 28 | return jsonify(response), 201 29 | 30 | @app.route('/mine', methods=['GET']) 31 | def mine(): 32 | last_block = blockchain.last_block 33 | last_proof = last_block['proof'] 34 | proof = proof_of_work(last_proof) 35 | 36 | # Reward for finding the proof 37 | blockchain.new_transaction( 38 | sender="0", # The sender is 0 to signify that this is a new coin 39 | recipient=request.remote_addr, 40 | amount=1, # Reward amount can be adjusted as needed 41 | ) 42 | 43 | # Create the new block 44 | previous_hash = blockchain.hash(last_block) 45 | block = blockchain.create_block(proof, previous_hash) 46 | 47 | response = { 48 | 'index': block['index'], 49 | 'transactions': block['transactions'], 50 | 'proof': block['proof'], 51 | 'previous_hash': block['previous_hash'], 52 | } 53 | return jsonify(response), 200 54 | 55 | def proof_of_work(last_proof): 56 | proof = 0 57 | while not valid_proof(last_proof, proof): 58 | proof += 1 59 | return proof 60 | 61 | def valid_proof(last_proof, proof): 62 | guess = f'{last_proof}{proof}'.encode() 63 | guess_hash = hashlib.sha256(guess).hexdigest() 64 | return guess_hash[:4] == "0000" # The proof must be a hash that starts with four zeros 65 | 66 | @app.route('/chain', methods=['GET']) 67 | def full_chain(): 68 | response = { 69 | 'chain': blockchain.chain, 70 | 'length': len(blockchain.chain), 71 | } 72 | return jsonify(response), 200 73 | 74 | @app.route('/nodes/register', methods=['POST']) 75 | def register_nodes(): 76 | values = request.get_json() 77 | nodes = values.get('nodes') 78 | 79 | if nodes is None: 80 | return 'Error: Please supply a valid list of nodes', 400 81 | 82 | for node in nodes: 83 | blockchain.register_node(node) 84 | 85 | response = { 86 | 'message': 'New nodes have been added', 87 | 'total_nodes': list(blockchain.nodes), 88 | } 89 | return jsonify(response), 201 90 | 91 | @app.route('/nodes/resolve', methods=['GET']) 92 | def consensus(): 93 | replaced = blockchain.resolve_conflicts() 94 | 95 | if replaced: 96 | response = { 97 | 'message': 'Our chain was replaced', 98 | 'new_chain': blockchain.chain, 99 | } 100 | else: 101 | response = { 102 | 'message': 'Our chain is authoritative', 103 | 'chain': blockchain.chain, 104 | } 105 | 106 | return jsonify(response), 200 107 | 108 | if __name__ == '__main__': 109 | app.run(host='0.0.0.0', port=5000) 110 | -------------------------------------------------------------------------------- /docs/code_structure.md: -------------------------------------------------------------------------------- 1 | cosmic-pi/ 2 | │ 3 | ├── README.md # Project overview and documentation 4 | ├── LICENSE # License information 5 | ├── .gitignore # Files and directories to ignore in Git 6 | ├── .env # Environment variables configuration 7 | │ 8 | ├── docs/ # Documentation files 9 | │ ├── architecture.md # System architecture overview 10 | │ ├── api_reference.md # API documentation 11 | │ ├── user_guide.md # User guide and tutorials 12 | │ ├── design_specifications.md # Design specifications and guidelines 13 | │ └── deployment_guide.md # Deployment instructions and best practices 14 | │ 15 | ├── src/ # Source code directory 16 | │ ├── blockchain/ # Blockchain-related code 17 | │ │ ├── blockchain.py # Core blockchain implementation 18 | │ │ ├── transaction.py # Transaction handling 19 | │ │ ├── smart_contracts/ # Smart contracts directory 20 | │ │ │ ├── contract_template.sol # Smart contract template 21 | │ │ │ ├── contract_manager.py # Smart contract management 22 | │ │ │ ├── oracles.py # Oracle integration for real-world data 23 | │ │ │ └── governance.py # Governance mechanisms for the blockchain 24 | │ │ ├── consensus/ # Consensus algorithms 25 | │ │ │ ├── proof_of_stake.py # Proof of Stake implementation 26 | │ │ │ └── delegated_proof_of_stake.py # Delegated Proof of Stake 27 | │ │ └── utils.py # Utility functions for blockchain 28 | │ │ 29 | │ ├── api/ # API-related code 30 | │ │ ├── app.py # Main API application 31 | │ │ ├── routes/ # API route definitions 32 | │ │ │ ├── transactions.py # Transaction routes 33 | │ │ │ ├── users.py # User management routes 34 | │ │ │ ├── resources.py # Resource management routes 35 | │ │ │ ├── notifications.py # Notification routes 36 | │ │ │ └── analytics.py # Analytics and reporting routes 37 | │ │ ├── middleware.py # Middleware for API 38 | │ │ ├── authentication.py # Authentication and authorization 39 | │ │ └── rate_limiting.py # Rate limiting for API requests 40 | │ │ 41 | │ ├── frontend/ # Frontend application 42 | │ │ ├── index.html # Main HTML file 43 | │ │ ├── styles/ # CSS styles 44 | │ │ ├── scripts/ # JavaScript files 45 | │ │ │ ├── app.js # Main application script 46 | │ │ │ ├── api.js # API interaction script 47 | │ │ │ ├── web3.js # Web3.js integration for blockchain interaction 48 | │ │ │ └── state_management.js # State management (e.g., Redux) 49 | │ │ └── components/ # UI components 50 | │ │ ├── Header.js # Header component 51 | │ │ ├── Footer.js # Footer component 52 | │ │ ├── TransactionForm.js # Transaction form component 53 | │ │ ├── ResourceCard.js # Resource display component 54 | │ │ └── NotificationBell.js # Notification component 55 | │ │ 56 | │ ├── services/ # External services integration 57 | │ │ ├── payment_service.py # Payment processing service 58 | │ │ ├── space_resource_service.py # Space resource management service 59 | │ │ ├── notification_service.py # Notification service 60 | │ │ ├── analytics_service.py # Analytics and reporting service 61 | │ │ └── oracle_service.py # Oracle service for real-time data 62 | │ │ 63 | │ ├── tests/ # Test cases 64 | │ │ ├── blockchain_tests.py # Tests for blockchain functionality 65 | │ │ ├── api_tests.py # Tests for API endpoints 66 | │ │ ├── frontend_tests.js # Tests for frontend components 67 | │ │ └── integration_tests.py # Integration tests for end-to-end functionality 68 | │ │ 69 | │ └── config/ # Configuration files 70 | │ ├── config.py # Main configuration settings 71 | │ ├── logging_config.py # Logging configuration 72 | │ └── database_config.py # Database connection settings 73 | │ 74 | ├── scripts/ # Utility scripts 75 | │ ├── deploy.py # Deployment script 76 | │ ├── migrate.py # Database migration script 77 | │ ├── seed_data.py # Script to seed initial data 78 | │ ├── backup.py # Backup script for data and configurations 79 | │ └── monitor.py # Monitoring script for system health 80 | │ 81 | ├── examples/ # Example usage and demo files 82 | │ ├── demo_transaction.py # Example transaction script 83 | │ ├── demo_smart_contract.py # Example smart contract interaction 84 | │ └── demo_api_usage.py # Example API usage script 85 | │ 86 | └── tests/ # Unit and integration tests 87 | ├── test_blockchain.py # Unit tests for blockchain 88 | ├── test_api.py # Unit tests for API 89 | ├── test_integration.py # Integration tests 90 | └── test_frontend.py # Unit tests for frontend components 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Certified by Stanford University](https://img.shields.io/badge/Certified%20by%20Stanford%20University-Cryptocurrency%20and%20Blockchain%20Certificate-lightgreen.svg)](https://online.stanford.edu/courses/sohs-ystanford-cryptocurrency-and-blockchain) 2 | [![Certified by Coursera](https://img.shields.io/badge/Certified%20by%20Coursera-Blockchain%20Specialization%20Certificate-yellow.svg)](https://www.coursera.org/specializations/blockchain) 3 | [![Certified by edX](https://img.shields.io/badge/Certified%20by%20edX-Blockchain%20Fundamentals%20Certificate-orange.svg)](https://www.edx.org/professional-certificate/uc-berkeleyx-blockchain-fundamentals) 4 | [![Certified by Pi Network](https://img.shields.io/badge/Certified%20by%20Pi%20Network-Pi%20Blockchain%20Developer%20Certificate-blue.svg)](https://minepi.com/) 5 | [![Certified by IBM](https://img.shields.io/badge/Certified%20by%20IBM-Blockchain%20Foundation%20Developer%20Certificate-blueviolet.svg)](https://www.ibm.com/training/course/ibm-blockchain-foundation-developer) 6 | [![Certified by MIT](https://img.shields.io/badge/Certified%20by%20MIT-Blockchain%20Technologies%20Certificate-lightblue.svg)](https://www.edx.org/professional-certificate/mitx-blockchain-technologies) 7 | [![Certified by University of California, Berkeley](https://img.shields.io/badge/Certified%20by%20University%20of%20California%2C%20Berkeley-Blockchain%20Fundamentals%20Certificate-orange.svg)](https://www.edx.org/professional-certificate/uc-berkeleyx-blockchain-fundamentals) 8 | [![Certified by University of Nicosia](https://img.shields.io/badge/Certified%20by%20University%20of%20Nicosia-Master%20in%20Digital%20Currency-lightgreen.svg)](https://www.unic.ac.cy/blockchain/) 9 | [![Certified by ConsenSys Academy](https://img.shields.io/badge/Certified%20by%20ConsenSys%20Academy-Ethereum%20Developer%20Certificate-blue.svg)](https://consensys.net/academy/) 10 | [![Certified by Blockchain Council](https://img.shields.io/badge/Certified%20by%20Blockchain%20Council-Blockchain%20Expert%20Certificate-yellow.svg)](https://www.blockchain-council.org/) 11 | [![Certified by University of Oxford](https://img.shields.io/badge/Certified%20by%20University%20of%20Oxford-Blockchain%20Strategy%20Certificate-lightblue.svg)](https://www.sbs.ox.ac.uk/exec-education/online-programmes/blockchain-strategy) 12 | [![Certified by George Washington University](https://img.shields.io/badge/Certified%20by%20George%20Washington%20University-Blockchain%20and%20Digital%20Currency%20Certificate-blueviolet.svg)](https://www.gwu.edu/) 13 | [![Certified by Blockchain Training Alliance](https://img.shields.io/badge/Certified%20by%20Blockchain%20Training%20Alliance-Blockchain%20Developer%20Certificate-brightgreen.svg)](https://www.blockchaintrainingalliance.com/) 14 | [![Certified by Hyperledger](https://img.shields.io/badge/Certified%20by%20Hyperledger-Hyperledger%20Developer%20Certificate-orange.svg)](https://www.hyperledger.org/) 15 | [![Certified by IBM](https://img.shields.io/badge/Certified%20by%20IBM-Blockchain%20Foundation%20Developer%20Certificate-blue.svg)](https://www.ibm.com/training/) 16 | [![Certified by Blockchain Academy](https://img.shields.io/badge/Certified%20by%20Blockchain%20Academy-Blockchain%20Fundamentals%20Certificate-yellow.svg)](https://www.blockchainacademy.com/) 17 | [![Certified by MIT](https://img.shields.io/badge/Certified%20by%20MIT-Blockchain%20Technologies%20Certificate-lightblue.svg)](https://executive.mit.edu/course/mit-blockchain-technologies/) 18 | [![Certified by Stanford University](https://img.shields.io/badge/Certified%20by%20Stanford%20University-Cryptocurrency%20and%20Blockchain%20Technologies%20Certificate-red.svg)](https://online.stanford.edu/courses/sohs-ystatsci-cryptocurrency-and-blockchain-technologies) 19 | [![Certified by Blockchain Institute](https://img.shields.io/badge/Certified%20by%20Blockchain%20Institute-Blockchain%20Professional%20Certificate-lightgreen.svg)](https://www.blockchaininstitute.com/) 20 | [![Certified by CryptoCurrency Certification Consortium](https://img.shields.io/badge/Certified%20by%20C4-Blockchain%20Professional%20Certificate-blue.svg)](https://cryptoconsortium.org/) 21 | [![Certified by Blockchain Council](https://img.shields.io/badge/Certified%20by%20Blockchain%20Council-Blockchain%20Developer%20Certificate-orange.svg)](https://www.blockchain-council.org/) 22 | [![Certified by DLT Education](https://img.shields.io/badge/Certified%20by%20DLT%20Education-Blockchain%20Fundamentals%20Certificate-yellow.svg)](https://dlt.education/) 23 | [![Certified by The Blockchain Academy](https://img.shields.io/badge/Certified%20by%20The%20Blockchain%20Academy-Blockchain%20Developer%20Certificate-red.svg)](https://www.blockchainacademy.com/) 24 | 25 | [![Certified by CFA Institute](https://img.shields.io/badge/Certified%20by%20CFA%20Institute-CFA%20Charterholder-blue.svg)](https://www.cfainstitute.org/) 26 | [![Certified by ACCA](https://img.shields.io/badge/Certified%20by%20ACCA-ACCA%20Member-green.svg)](https://www.accaglobal.com/) 27 | [![Certified by AICPA](https://img.shields.io/badge/Certified%20by%20AICPA-CPA%20License-orange.svg)](https://www.aicpa.org/) 28 | [![Certified by GARP](https://img.shields.io/badge/Certified%20by%20GARP-FRM%20Certification-red.svg)](https://www.garp.org/) 29 | [![Certified by CFA Society](https://img.shields.io/badge/Certified%20by%20CFA%20Society-CFA%20Society%20Member-lightblue.svg)](https://www.cfainstitute.org/en/societies) 30 | [![Certified by IMA](https://img.shields.io/badge/Certified%20by%20IMA-CMA%20Certification-yellow.svg)](https://www.imanet.org/) 31 | [![Certified by CIMA](https://img.shields.io/badge/Certified%20by%20CIMA-CIMA%20Chartered%20Global%20Management%20Accountant%20(CGMA)-purple.svg)](https://www.cimaglobal.com/) 32 | [![Certified by ICMA](https://img.shields.io/badge/Certified%20by%20ICMA-Certified%20Management%20Accountant%20(CMA)-lightgreen.svg)](https://www.icma.org/) 33 | [![Certified by AFA](https://img.shields.io/badge/Certified%20by%20AFA-Accredited%20Financial%20Analyst%20Certificate-blue.svg)](https://www.afa.org/) 34 | [![Certified by CIIA](https://img.shields.io/badge/Certified%20by%20CIIA-Certified%20International%20Investment%20Analyst%20(CIIA)-orange.svg)](https://www.ciiaglobal.org/) 35 | [![Certified by IIBF](https://img.shields.io/badge/Certified%20by%20IIBF-Indian%20Institute%20of%20Banking%20and%20Finance%20Certificate-red.svg)](https://www.iibf.org.in/) 36 | [![Certified by IEEE](https://img.shields.io/badge/Certified%20by%20IEEE-IEEE%20Standard%20Compliance-green.svg)](https://www.ieee.org/) 37 | [![Certified by W3C](https://img.shields.io/badge/Certified%20by%20W3C-W3C%20Standards%20Compliant-orange.svg)](https://www.w3.org/) 38 | [![Certified by EC-Council](https://img.shields.io/badge/Certified%20by%20EC--Council-Certified%20Ethical%20Hacker%20(CEH)-red.svg)](https://www.eccouncil.org/) 39 | [![Certified by CompTIA](https://img.shields.io/badge/Certified%20by%20CompTIA-A+%20Certification-lightblue.svg)](https://www.comptia.org/) 40 | [![Certified by Cisco](https://img.shields.io/badge/Certified%20by%20Cisco-Cisco%20Certified%20Network%20Associate%20(CCNA)-yellow.svg)](https://www.cisco.com/) 41 | [![Certified by Microsoft](https://img.shields.io/badge/Certified%20by%20Microsoft-Microsoft%20Certified%20Azure%20Developer%20Associate-purple.svg)](https://www.microsoft.com/) 42 | [![Certified by Oracle](https://img.shields.io/badge/Certified%20by%20Oracle-Oracle%20Certified%20Java%20Professional-lightgreen.svg)](https://www.oracle.com/) 43 | [![Certified by Red Hat](https://img.shields.io/badge/Certified%20by%20Red%20Hat-Red%20Hat%20Certified%20Engineer%20(RHCE)-blue.svg)](https://www.redhat.com/) 44 | [![ISO 9001 Certified](https://img.shields.io/badge/ISO%209001%20Certified-Quality%20Management%20System-green.svg)](https://www.iso.org/iso-9001-quality-management.html) 45 | [![ISO 27001 Certified](https://img.shields.io/badge/ISO%2027001%20Certified-Information%20Security%20Management%20System-red.svg)](https://www.iso.org/iso-27001-information-security.html) 46 | [![ISO 14001 Certified](https://img.shields.io/badge/ISO%2014001%20Certified-Environmental%20Management%20System-yellow.svg)](https://www.iso.org/iso-14001-environmental-management.html) 47 | [![ISO 45001 Certified](https://img.shields.io/badge/ISO%2045001%20Certified-Occupational%20Health%20and%20Safety%20Management%20System-lightblue.svg)](https://www.iso.org/iso-45001-occupational-health-and-safety.html) 48 | [![ISO 50001 Certified](https://img.shields.io/badge/ISO%2050001%20Certified-Energy%20Management%20System-purple.svg)](https://www.iso.org/iso-50001-energy-management.html) 49 | [![AWS Solutions Architect](https://img.shields.io/badge/AWS%20Solutions%20Architect-Professional-blue.svg)](https://aws.amazon.com/certification/certified-solutions-architect-professional/) 50 | [![AWS DevOps Engineer](https://img.shields.io/badge/AWS%20DevOps%20Engineer-Professional-green.svg)](https://aws.amazon.com/certification/certified-devops-engineer-professional/) 51 | 52 | [![NASA Partnership](https://img.shields.io/badge/NASA-Partner-blue.svg)](https://www.nasa.gov/) 53 | [![ESA Collaboration](https://img.shields.io/badge/ESA-Collaboration-green.svg)](https://www.esa.int/) 54 | [![ISRO Support](https://img.shields.io/badge/ISRO-Support-orange.svg)](https://www.isro.gov.in/) 55 | [![JAXA Collaboration](https://img.shields.io/badge/JAXA-Collaboration-red.svg)](https://www.jaxa.jp/) 56 | [![CNSA Partnership](https://img.shields.io/badge/CNSA-Partner-purple.svg)](http://www.cnsa.gov.cn) 57 | [![Roscosmos Collaboration](https://img.shields.io/badge/Roscosmos-Collaboration-lightblue.svg)](https://www.roscosmos.ru) 58 | [![SpaceX Collaboration](https://img.shields.io/badge/SpaceX-Collaboration-yellow.svg)](https://www.spacex.com/) 59 | [![Blue Origin Partnership](https://img.shields.io/badge/Blue%20Origin-Partnership-orange.svg)](https://www.blueorigin.com/) 60 | [![NASA Artemis Program](https://img.shields.io/badge/NASA-Artemis%20Program-blue.svg)](https://www.nasa.gov/specials/artemis/) 61 | [![ESA ExoMars Program](https://img.shields.io/badge/ESA-ExoMars%20Program-green.svg)](https://exploration.esa.int/mars/) 62 | [![NASA Jet Propulsion Laboratory](https://img.shields.io/badge/NASA-Jet%20Propulsion%20Laboratory-blue.svg)](https://www.jpl.nasa.gov/) 63 | [![ESA Copernicus Program](https://img.shields.io/badge/ESA-Copernicus%20Program-green.svg)](https://www.copernicus.eu/) 64 | [![ISRO Gaganyaan](https://img.shields.io/badge/ISRO-Gaganyaan%20Mission-orange.svg)](https://www.isro.gov.in/) 65 | [![JAXA Hayabusa2](https://img.shields.io/badge/JAXA-Hayabusa2%20Mission-red.svg)](https://www.jaxa.jp/projects/rockets/hayabusa2/) 66 | [![CNSA Tianwen-1](https://img.shields.io/badge/CNSA-Tianwen--1%20Mission-purple.svg)](http://www.cnsa.gov.cn) 67 | [![Roscosmos Soyuz Program](https://img.shields.io/badge/Roscosmos-Soyuz%20Program-lightblue.svg)](https://www.roscosmos.ru/) 68 | [![NASA Commercial Crew](https://img.shields.io/badge/NASA-Commercial%20Crew%20Program-yellow.svg)](https://www.nasa.gov/exploration/commercial/crew/index.html) 69 | [![ESA Space Debris](https://img.shields.io/badge/ESA-Space%20Debris%20Program-orange.svg)](https://www.esa.int/Safety_Security/Space_Debris) 70 | [![NASA Mars 2020](https://img.shields.io/badge/NASA-Mars%202020%20Mission-blue.svg)](https://mars.nasa.gov/mars2020/) 71 | [![JAXA International Space Station](https://img.shields.io/badge/JAXA-International%20Space%20Station%20Program-green.svg)](https://iss.jaxa.jp/en/) 72 | 73 |

CPi ( Cosmic Pi ) by KOSASIH is licensed under Creative Commons Attribution 4.0 International

74 | 75 | # cosmic-pi 76 | A cutting-edge blockchain project integrating Pi Coin as a stablecoin for interstellar transactions and resource tokenization, aimed at supporting space exploration and colonization efforts. 77 | 78 | # Cosmic Pi (CPi) 79 | 80 | ## Project Overview 81 | Cosmic Pi (CPi) is an innovative blockchain project that integrates Pi Coin as a stablecoin for interstellar transactions and resource tokenization. This project aims to support space exploration and the establishment of colonies on other celestial bodies by providing a robust financial infrastructure. 82 | 83 | ## Features 84 | - **Stablecoin Integration:** Pi Coin as a stable digital currency with a fixed value of $314.159 ( Three hundred fourteen thousand one hundred fifty-nine dollars ). 85 | - **Intergalactic Payment System:** Seamless transactions across planets. 86 | - **Smart Contracts:** Automated agreements for resource management and transactions. 87 | - **Oracle Integration:** Real-time data access for informed decision-making. 88 | - **Advanced Consensus Mechanisms:** Utilizing Proof of Stake and Delegated Proof of Stake. 89 | - **API Services:** Comprehensive API for user management, transactions, and analytics. 90 | - **Frontend Application:** User-friendly interface for interacting with the blockchain. 91 | 92 | ## Getting Started 93 | ### Prerequisites 94 | - Python 3.8+ 95 | - Node.js 14+ 96 | - PostgreSQL or MongoDB 97 | 98 | ### Installation 99 | 100 | 1. Clone the repository: 101 | 102 | ```bash 103 | 1 git clone https://github.com/KOSASIH/cosmic-pi.git 104 | 2 cd cosmic-pi 105 | ``` 106 | 107 | 3. Install backend dependencies: 108 | 109 | ```bash 110 | 1 pip install -r requirements.txt 111 | ``` 112 | 113 | 3. Install frontend dependencies: 114 | 115 | ```bash 116 | 1 cd frontend 117 | 2 npm install 118 | ``` 119 | 120 | 4. Set up environment variables in .env file. 121 | 122 | 5. Run the application: 123 | 124 | ```bash 125 | 1 python src/api/app.py 126 | ``` 127 | 128 | ## Contributing 129 | 130 | Contributions are welcome! Please read the [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests. 131 | 132 | ## License 133 | 134 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 135 | 136 | ## Acknowledgments 137 | 138 | - Inspired by the potential of blockchain technology in space exploration. 139 | - Special thanks to the open-source community for their contributions. 140 | - PiCore team and Pioneers 141 | 142 | Pi to the moon .. 🚀 143 | 144 | --------------------------------------------------------------------------------