{"id":40927052,"url":"https://github.com/yujidong/Risk-HedgingProtocol","last_synced_at":"2026-01-31T08:00:50.203Z","repository":{"id":328805367,"uuid":"1116797167","full_name":"yujidong/Risk-HedgingProtocol","owner":"yujidong","description":"Trustworthy data trading with game-theoretic pricing, blockchain settlement, and TEE validation. Official implementation for IEEE IoT Journal submission.","archived":false,"fork":false,"pushed_at":"2025-12-15T12:44:15.000Z","size":119,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-12-26T23:39:31.253Z","etag":null,"topics":["blockchain","data-trading","ethereum","game-theory","hardhat","iot","machine-learning","pytorch","sgx","smart-contracts","trusted-execution-environment"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yujidong.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-15T11:52:02.000Z","updated_at":"2025-12-15T12:44:19.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/yujidong/Risk-HedgingProtocol","commit_stats":null,"previous_names":["yujidong/risk-hedgingprotocol"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/yujidong/Risk-HedgingProtocol","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yujidong%2FRisk-HedgingProtocol","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yujidong%2FRisk-HedgingProtocol/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yujidong%2FRisk-HedgingProtocol/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yujidong%2FRisk-HedgingProtocol/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yujidong","download_url":"https://codeload.github.com/yujidong/Risk-HedgingProtocol/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yujidong%2FRisk-HedgingProtocol/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28934612,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-31T07:49:44.436Z","status":"ssl_error","status_checked_at":"2026-01-31T07:49:34.274Z","response_time":128,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blockchain","data-trading","ethereum","game-theory","hardhat","iot","machine-learning","pytorch","sgx","smart-contracts","trusted-execution-environment"],"created_at":"2026-01-22T04:00:22.996Z","updated_at":"2026-01-31T08:00:50.192Z","avatar_url":"https://github.com/yujidong.png","language":"Python","funding_links":[],"categories":["Blockchains"],"sub_categories":["Library OSes and SDKs"],"readme":"# Risk-Hedging Equity Protocol for IoT Data Trading\n\nA complete blockchain-based implementation of the **Trustworthy Data Equity Protocol** combining smart contracts, TEE-secured computation, and AI-powered data analysis for secure IoT data trading.\n\n\u003e **📄 Paper**: This repository contains the official implementation for the paper *\"Trustworthy Data Equity: A Retrospective Risk-Hedging Protocol for High-Entropy IoT Data Assets\"* submitted to **IEEE Internet of Things Journal**.\n\n## Overview\n\nThis project implements an end-to-end decentralized data trading system with three integrated components:\n\n### 🔗 1. Blockchain Smart Contracts\n- **Smart Contract Settlement**: Ethereum-compatible contracts handle order creation, escrow, and atomic payment\n- **Multi-role Architecture**: Separate accounts for Owner, Buyer, Seller, and TEE Signer\n- **Testnet Deployment**: Production-ready deployment on Sepolia, Arbitrum, and Optimism testnets\n- **Comprehensive Benchmarks**: Gas cost and performance analysis across L1/L2 networks\n\n### 🔒 2. TEE (Trusted Execution Environment)\n- **Intel SGX Integration**: Secure model inference in hardware-protected enclaves via Gramine\n- **Performance Benchmarking**: Native vs TEE overhead analysis (~17% inference overhead)\n- **Cloud Deployment**: Automated Azure VM setup scripts for SGX-capable infrastructure\n- **Cryptographic Attestation**: ECDSA signature generation for on-chain verification\n\n### 🤖 3. AI/ML Data Analysis\n- **LSTM Traffic Prediction**: Deep learning models trained on PeMS traffic dataset\n- **Noise Robustness Testing**: Validates protocol resilience to sensor noise and data quality issues\n- **Game Theory Experiments**: Data scarcity and random drop scenario analysis\n- **Automated Visualization**: Comprehensive plotting and results analysis tools\n\n## 🏗️ Project Structure\n\n```\nRisk-HedgingProtocol/\n├── contracts/                    # 📜 Smart Contracts\n│   └── protocol.sol              #    DataEquityProtocol (Solidity)\n│\n├── test/                         # 🧪 Contract Testing\n│   ├── DataEquityProtocol.test.js          # Functional tests\n│   ├── DataEquityProtocol.benchmark.js     # L1 performance benchmarks\n│   └── DataEquityProtocol.benchmark-simple.js\n│\n├── scripts/                      # 🛠️ Utility Scripts\n│   ├── check-all-balances.js    # Multi-account balance checker\n│   ├── compare_benchmarks.py    # Benchmark results comparison\n│   └── run_all_benchmarks.ps1   # Automated test runner\n│\n├── tee/                          # 🔒 TEE Component (NEW!)\n│   ├── tee_benchmark.py         # Main TEE benchmark script\n│   ├── Dockerfile.gramine       # SGX container configuration\n│   ├── tee_benchmark.manifest.template # Gramine SGX manifest\n│   ├── create_azure_vm.ps1      # Azure SGX VM provisioning\n│   ├── run_cloud_test.sh        # Automated TEE testing\n│   ├── data/                    # PEMS08 dataset (shared with ML)\n│   ├── models/                  # Trained LSTM models\n│   ├── results/                 # TEE benchmark results\n│   └── docs/                    # TEE architecture documentation\n│\n├── input/                        # 📊 ML Datasets\n│   └── pems-dataset/            # PeMS traffic dataset (PEMS03/04/07/08)\n│\n├── output/                       # 📈 Experiment Results\n│   ├── data/                    # ML experiment results (JSON)\n│   ├── figures/                 # Visualization plots (PNG)\n│   └── benchmark/               # Blockchain benchmark results\n│\n├── noise_robustness_experiment.py # 🤖 Main ML experiments\n├── game_theory_data_scarcity.py   # Game theory: data scarcity\n├── game_theory_random_drop.py     # Game theory: random drops\n├── visualize_results.py           # Results visualization\n│\n├── hardhat.config.ts             # Hardhat configuration (3 networks)\n├── ACCOUNTS.md                   # Multi-account setup guide\n├── DEPLOYMENT.md                 # Deployment instructions\n└── README.md                     # This file\n```\n\n## Smart Contract Features\n\n### DataEquityProtocol Contract\n\n**Core Functions:**\n- `createOrder()`: Buyer locks funds in escrow with pricing parameters\n- `settleTransaction()`: TEE-signed utility score triggers atomic payment\n- `refund()`: Timeout protection for buyers\n- `setTEESigner()`: Admin function to update TEE public key\n\n**Pricing Model:**\n```\nFinal Payment = p_base + α * k * u\n\nWhere:\n- p_base: Base fee (fixed)\n- α: Equity share coefficient (0 ≤ α ≤ 1)\n- k: Utility-to-money conversion factor\n- u: Data utility score (0 ≤ u ≤ 1, TEE-verified)\n```\n\n**Security:**\n- ECDSA signature verification for TEE attestation\n- ReentrancyGuard protection\n- Ownable access control\n- Nonce-based replay attack prevention\n\n## 🚀 Quick Start Guide\n\n### Prerequisites\n- **Node.js** 22+ and npm 11+ (blockchain development)\n- **Python** 3.9+ with conda (ML experiments)\n- **Docker** (optional, for TEE testing)\n- **Azure Account** (optional, for SGX cloud deployment)\n\n### 1️⃣ Blockchain Setup\n\n```bash\n# Install dependencies\nnpm install\n\n# Compile contracts\nnpx hardhat compile\n\n# Run functional tests\nnpx hardhat test\n\n# Run performance benchmarks (requires testnet ETH)\nnpx hardhat test test/DataEquityProtocol.benchmark.js --network sepolia\n```\n\n### 2️⃣ ML/AI Setup\n\n```bash\n# Create conda environment\nconda env create -f environment.yml\nconda activate risk-hedging\n\n# Run noise robustness experiments\npython noise_robustness_experiment.py\n\n# Run game theory analysis\npython game_theory_data_scarcity.py\npython game_theory_random_drop.py\n\n# Generate visualizations\npython visualize_results.py\n```\n\n### 3️⃣ TEE Setup (Advanced)\n\n```bash\ncd tee/\n\n# Option A: Local testing with dummy data\npython tee_benchmark.py --mode native --iterations 10\n\n# Option B: Cloud SGX deployment\n# 1. Create Azure VM with SGX support\n.\\create_azure_vm.ps1\n\n# 2. Deploy and run tests\n.\\redeploy_all.ps1\n\n# 3. SSH to VM and execute\nssh azureuser@\u003cVM_IP\u003e\nchmod +x run_cloud_test.sh\n./run_cloud_test.sh\n\n# Results will be in tee/results/*.json\n```\n\n## 📊 Complete Workflow Example\n\n### End-to-End Data Trading Simulation\n\n**Step 1: Generate Training Data**\n```bash\n# ML experiments produce utility scores and model performance\npython noise_robustness_experiment.py\n# Output: output/data/*.json\n```\n\n**Step 2: Deploy Smart Contract**\n```bash\n# Set up accounts and deploy to testnet\nnpx hardhat keystore set SEPOLIA_PRIVATE_KEY --dev\nnpx hardhat ignition deploy ignition/modules/DataEquityProtocol.ts --network sepolia\n# Contract address: 0xE0aa880da6822A26C946f9417F7F6380FDf9799F (example)\n```\n\n**Step 3: TEE Utility Evaluation**\n```bash\ncd tee/\n# TEE validates data and signs utility score\npython tee_benchmark.py --mode native\n# Output: Utility score (0.80) + ECDSA signature\n```\n\n**Step 4: On-Chain Settlement**\n```bash\n# Buyer creates order with locked funds\n# TEE submits signed utility score\n# Smart contract verifies signature and executes payment\nnpx hardhat test test/DataEquityProtocol.test.js --network sepolia\n# ✅ Order settled: Seller receives payment based on utility\n```\n\n**Step 5: Analyze Results**\n```bash\n# Compare blockchain benchmarks\npython scripts/compare_benchmarks.py\n\n# Visualize all experimental data\npython visualize_results.py\n```\n\n## 📖 Detailed Usage\n\n## 📖 Detailed Usage\n\n### Blockchain Component\n\n#### Deploy to Public Testnet\n\n```bash\n# Configure accounts (Owner, Buyer, Seller, TEE Signer)\n# See ACCOUNTS.md for multi-account setup guide\nnpx hardhat keystore set SEPOLIA_PRIVATE_KEY\nnpx hardhat keystore set SEPOLIA_PRIVATE_KEY_2\nnpx hardhat keystore set SEPOLIA_PRIVATE_KEY_3\nnpx hardhat keystore set SEPOLIA_PRIVATE_KEY_4\n\n# Check balances\nnpx hardhat run scripts/check-all-balances.js --network sepolia\n\n# Deploy contract\nnpx hardhat ignition deploy ignition/modules/DataEquityProtocol.ts --network sepolia\n\n# Run comprehensive benchmarks\nnpx hardhat test test/DataEquityProtocol.benchmark.js --network sepolia\n```\n\n**Benchmark Results** (Sepolia L1 @ 3 gwei):\n- Deployment: 21,000 gas (~$0.06)\n- Order Creation: 273,077 gas (~$2.46)\n- Settlement: 73,708 gas (~$0.63)\n- Refund: 44,745 gas (~$0.41)\n\nSee [DEPLOYMENT.md](DEPLOYMENT.md) for complete deployment guide.\n\n### AI/ML Component\n\n#### LSTM Noise Robustness Experiments\n\n```bash\n# Train and evaluate LSTM models with noise injection\npython noise_robustness_experiment.py\n\n# Key parameters:\n# - Noise levels: 0%, 10%, 20%, 30%, 40%, 50%\n# - Datasets: PEMS03, PEMS04, PEMS07, PEMS08\n# - Model: 2-layer LSTM (hidden_size=256)\n\n# Output: output/data/*_results.json\n# Metrics: MAE, RMSE, R2 score per noise level\n```\n\n#### Game Theory Experiments\n\n```bash\n# Data scarcity scenarios (50-100% data availability)\npython game_theory_data_scarcity.py\n\n# Random drop scenarios (probability-based data loss)\npython game_theory_random_drop.py\n\n# Generate comparison plots\npython visualize_results.py\n```\n\n### TEE Component\n\n#### Local Testing (Without SGX Hardware)\n\n```bash\ncd tee/\n\n# Create dummy data for testing\npython tee_benchmark.py --mode native --iterations 10 --use-dummy-data\n\n# Output: results/native_*.json\n```\n\n#### Cloud SGX Deployment (Production)\n\n**Prerequisites**:\n- Azure account with quota for DC-series VMs\n- Azure CLI installed and authenticated\n- SSH key pair configured\n\n**Deployment Steps**:\n\n```bash\ncd tee/\n\n# 1. Provision Azure SGX VM\n.\\create_azure_vm.ps1\n# Creates: Standard_DC2s_v3 VM with 8GB SGX EPC\n\n# 2. Deploy code and dependencies\n.\\redeploy_all.ps1\n# Uploads: tee_benchmark.py, data/, models/, configs\n\n# 3. SSH to VM and run tests\nssh azureuser@\u003cVM_IP\u003e\n\n# 4. Run native baseline\ndocker run --rm -v $(pwd):/app tee-benchmark:native python tee_benchmark.py\n\n# 5. Run SGX enclave test\ndocker run --device /dev/sgx_enclave --device /dev/sgx_provision \\\n  -v $(pwd):/app tee-benchmark:sgx gramine-sgx python\n\n# 6. Retrieve results\nexit\nscp azureuser@\u003cVM_IP\u003e:~/results/*.json ./results/\n\n# 7. Stop VM to avoid charges\naz vm deallocate --resource-group web3 --name tee-benchmark-vm\n```\n\n**TEE Performance Results**:\n- Native Inference: 547ms ± 18ms\n- SGX Inference: 642ms ± 5ms (+17.3% overhead)\n- Model Accuracy: Identical (R² = 0.8063)\n- Memory Overhead: +18.2%\n\nSee [tee/docs/ARCHITECTURE.md](tee/docs/ARCHITECTURE.md) for technical details.\n\n## 🧪 Experimental Results\n\n## 🧪 Experimental Results Summary\n\n### 1. Blockchain Performance (Sepolia L1 Testnet)\n\n| Operation | Gas Used | Cost (@3000 gwei) | Time |\n|-----------|----------|-------------------|------|\n| Contract Deployment | 21,000 | $0.06 | ~11s |\n| Order Creation | 273,077 | $2.46 | ~2s |\n| Order Settlement | 73,708 | $0.63 | ~2s |\n| Refund | 44,745 | $0.41 | ~2s |\n| **Complete Trade** | **346,785** | **$3.09** | **~4s** |\n\n💡 **L2 Recommendation**: Deploying to Arbitrum/Optimism can reduce costs by 95% (~$0.15/trade)\n\n### 2. TEE Performance (Azure DC2s_v3 + Intel SGX)\n\n| Metric | Native Docker | Gramine SGX | Overhead |\n|--------|---------------|-------------|----------|\n| Inference Time | 547ms ± 18ms | 642ms ± 5ms | **+17.3%** |\n| Model Accuracy (R²) | 0.8063 | 0.8063 | **Identical** |\n| Memory Usage | 2047 MB | 2420 MB | +18.2% |\n| Signature Generation | 13ms ± 3ms | 8ms ± 2ms | -38% |\n\n🔒 **Key Finding**: Only **17% inference overhead** in real SGX hardware with **identical accuracy**\n\n### 3. AI/ML Noise Robustness\n\n**LSTM Model Performance under Noise:**\n\n| Noise Level | MAE | RMSE | R² Score | Utility Score |\n|-------------|-----|------|----------|---------------|\n| 0% (Clean) | 2.87 | 4.12 | 0.953 | 1.00 |\n| 10% | 3.02 | 4.31 | 0.945 | 0.95 |\n| 20% | 3.24 | 4.58 | 0.932 | 0.89 |\n| 30% | 3.51 | 4.91 | 0.915 | 0.81 |\n| 40% | 3.89 | 5.34 | 0.891 | 0.72 |\n| 50% | 4.42 | 5.98 | 0.852 | 0.61 |\n\n✅ **Protocol Stability**: Maintains reliable utility scores up to 40% noise level\n\n**Game Theory Results**:\n- Data scarcity: Linear degradation from 100% → 50% data availability\n- Random drops: Exponential impact on utility with drop probability \u003e 0.3\n\nAll results available in `output/data/*.json` and `tee/results/*.json`\n\n## 🏛️ System Architecture\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"architecture.svg\" alt=\"System Architecture\" style=\"max-width:100%;height:auto;\" /\u003e\n\u003c/p\u003e\n\n\n## 🧩 Key Components Integration\n\n### Data Flow\n\n1. **Data Generation** (ML Component)\n   - IoT sensors → PeMS traffic dataset\n   - LSTM training \u0026 validation\n   - Noise injection experiments\n   - Output: Utility metrics (R², MAE, RMSE)\n\n2. **TEE Validation** (Security Component)\n   - Load trained LSTM model into SGX enclave\n   - Secure inference on encrypted data\n   - Generate utility score (u = 0.0 to 1.0)\n   - Sign with TEE private key → ECDSA signature\n\n3. **Blockchain Settlement** (Smart Contract)\n   - Buyer creates order: locks `maxDeposit` ETH\n   - Sets pricing: `p_base`, `α`, `k`\n   - TEE submits: `(orderId, utility, signature)`\n   - Contract verifies signature\n   - Calculates: `payment = p_base + α * k * u`\n   - Transfers to Seller, refunds excess to Buyer\n\n### Pricing Formula\n\n```\nP = p_base + α × k × u\n\nWhere:\n- p_base: Base fee (guaranteed minimum payment)\n- α: Equity share [0, 1] (risk-sharing coefficient)\n- k: Utility-to-money conversion factor (scaling parameter)\n- u: Data utility score [0, 1] (TEE-verified quality metric)\n```\n\n**Example**:\n- `p_base = 0.01 ETH`, `α = 0.5`, `k = 0.005 ETH`, `u = 0.95`\n- **Payment** = 0.01 + 0.5 × 0.005 × 0.95 = **0.012375 ETH**\n\n## 🛠️ Technology Stack\n\n**Blockchain:**\n- Solidity 0.8.28 - Smart contract language\n- Hardhat 3.1.0 - Development framework\n- Viem 2.41.2 - Type-safe Ethereum library\n- OpenZeppelin - Security-audited contracts\n- Sepolia/Arbitrum/Optimism - Multi-testnet support\n\n**TEE:**\n- Intel SGX - Hardware-based trusted execution\n- Gramine 1.7+ - SGX library OS\n- Docker - Containerization\n- Azure DC-series - SGX-capable VMs\n\n**AI/ML:**\n- PyTorch 2.5.1 - Deep learning framework\n- CUDA 12.4 - GPU acceleration\n- scikit-learn - ML utilities\n- NumPy/Pandas - Data processing\n- Matplotlib - Visualization\n\n## 🔐 Security Features\n\n1. **TEE Signature Verification**: ECDSA signature validation for utility scores\n2. **Escrow Protection**: Funds locked until settlement or timeout refund\n3. **Replay Attack Prevention**: Unique nonce per transaction\n4. **Reentrancy Guard**: Protection against recursive call attacks\n5. **Access Control**: Owner-only admin functions (Ownable pattern)\n6. **Atomic Settlement**: All-or-nothing payment execution\n\n## 🚧 Future Enhancements\n\n- [ ] Multi-TEE consensus mechanism\n- [ ] Layer 2 deployment (Arbitrum/Optimism mainnet)\n- [ ] Real-time IoT device integration\n- [ ] Dynamic pricing with market-based α\n- [ ] Cross-chain settlement support\n- [ ] Advanced data quality metrics\n\n## 📄 License\n\nMIT License - See [LICENSE](LICENSE)\n\n\n## 🔗 Useful Links\n\n**Testnet Faucets:**\n- Sepolia: https://sepoliafaucet.com/\n- Arbitrum Sepolia: https://bridge.arbitrum.io/\n- Optimism Sepolia: https://app.optimism.io/bridge\n\n**Block Explorers:**\n- Sepolia: https://sepolia.etherscan.io/\n- Arbitrum: https://sepolia.arbiscan.io/\n- Optimism: https://sepolia-optimism.etherscan.io/\n\n**Datasets:**\n- PeMS Traffic: http://pems.dot.ca.gov/\n- Azure SGX Docs: https://learn.microsoft.com/en-us/azure/virtual-machines/dcv3-series\n\n---","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyujidong%2FRisk-HedgingProtocol","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyujidong%2FRisk-HedgingProtocol","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyujidong%2FRisk-HedgingProtocol/lists"}