Skip to content

Commit e7fb5ab

Browse files
committed
Initial commit
0 parents  commit e7fb5ab

15 files changed

Lines changed: 526 additions & 0 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
name: Build and Release
2+
3+
on:
4+
push:
5+
branches: [main]
6+
pull_request:
7+
branches: [main]
8+
9+
permissions:
10+
contents: write
11+
12+
jobs:
13+
build-and-release:
14+
runs-on: ubuntu-latest
15+
steps:
16+
- uses: actions/checkout@v3
17+
18+
- name: Set up Python
19+
uses: actions/setup-python@v4
20+
with:
21+
python-version: '3.11'
22+
23+
- name: Set up Docker Buildx
24+
uses: docker/setup-buildx-action@v2
25+
26+
- name: Build Docker image
27+
uses: docker/build-push-action@v4
28+
with:
29+
context: .
30+
load: true
31+
tags: |
32+
refiner:${{ github.run_number }}
33+
refiner:latest
34+
cache-from: type=gha
35+
cache-to: type=gha,mode=max
36+
37+
- name: Export image to file
38+
run: |
39+
docker save refiner:latest | gzip > refiner-${{ github.run_number }}.tar.gz
40+
41+
- name: Generate release body
42+
run: |
43+
echo "Image SHA256: $(sha256sum refiner-${{ github.run_number }}.tar.gz | cut -d' ' -f1)" >> release_body.txt
44+
45+
- name: Upload image
46+
uses: actions/upload-artifact@v4
47+
with:
48+
name: refiner-image
49+
path: refiner-${{ github.run_number }}.tar.gz
50+
51+
- name: Create Release and Upload Assets
52+
uses: softprops/action-gh-release@v1
53+
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
54+
env:
55+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
56+
with:
57+
tag_name: v${{ github.run_number }}
58+
name: Release v${{ github.run_number }}
59+
body_path: release_body.txt
60+
draft: false
61+
prerelease: false
62+
files: |
63+
./refiner-${{ github.run_number }}.tar.gz
64+
65+
- name: Log build result
66+
if: always()
67+
run: |
68+
if [ ${{ job.status }} == "success" ]; then
69+
echo "Build and release completed successfully"
70+
else
71+
echo "Build and release failed"
72+
fi

.gitignore

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
*.pem
2+
*.tar.gz
3+
__pycache__/
4+
*.pyc
5+
6+
/input/user.json
7+
8+
/output/db.libsql
9+
10+
.idea/
11+
.DS_Store

Dockerfile

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
FROM python:3.12-slim
2+
3+
WORKDIR /app
4+
5+
COPY . /app
6+
7+
# Install any needed packages specified in requirements.txt
8+
RUN pip install --no-cache-dir -r requirements.txt
9+
10+
CMD ["python", "-m", "refiner"]

LICENSE

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
The MIT License (MIT)
2+
Copyright © 2024 Corsali, Inc. dba Vana
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5+
6+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7+
8+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# Vana Satya Proof of Contribution - Python Template
2+
3+
This repository serves as a template for creating a [proof of contribution](https://docs.vana.org/docs/proof-of-contribution/) tasks using Python. It is executed on Vana's Satya Network, a group of highly confidential and secure compute nodes that can validate data without revealing its contents to the node operator.
4+
5+
## Overview
6+
7+
This template provides a basic structure for building proof tasks that:
8+
9+
1. Read input files from the `/input` directory.
10+
2. Process the data securely, running any necessary validations to prove the data authentic, unique, high quality, etc.
11+
3. Write proof results to the `/output/results.json` file in the following format:
12+
13+
```json
14+
{
15+
"dlp_id": 1234, // DLP ID is found in the Root Network contract after the DLP is registered
16+
"valid": false, // A single boolean to summarize if the file is considered valid in this DLP
17+
"score": 0.7614457831325301, // A score between 0 and 1 for the file, used to determine how valuable the file is. This can be an aggregation of the individual scores below.
18+
"authenticity": 1.0, // A score between 0 and 1 to rate if the file has been tampered with
19+
"ownership": 1.0, // A score between 0 and 1 to verify the ownership of the file
20+
"quality": 0.6024096385542169, // A score between 0 and 1 to show the quality of the file
21+
"uniqueness": 0, // A score between 0 and 1 to show unique the file is, compared to others in the DLP
22+
"attributes": { // Custom attributes added to the proof to provide extra context, written offchain in IPFS
23+
"total_score": 0.5,
24+
"score_threshold": 0.83,
25+
"email_verified": true
26+
},
27+
"metadata": { // Custom attributes added to the proof to provide extra context, written onchain
28+
"dlp_id": 1234
29+
}
30+
}
31+
```
32+
33+
The project is designed to work with Intel TDX (Trust Domain Extensions), providing hardware-level isolation and security guarantees for confidential computing workloads.
34+
35+
## Project Structure
36+
37+
- `my_proof/`: Contains the main proof logic
38+
- `proof.py`: Implements the proof generation logic
39+
- `__main__.py`: Entry point for the proof execution
40+
- `models/`: Data models for the proof system
41+
- `input/`: Contains a sample input file for testing. In production, the Satya node will mount the decrypted data point to the /input directory of the docker container
42+
- `output/`: Results output from the container is written here, this is passed to the Satya node after execution
43+
- `Dockerfile`: Defines the container image for the proof task
44+
- `requirements.txt`: Python package dependencies
45+
46+
## Getting Started
47+
48+
To use this template:
49+
50+
1. Fork this repository
51+
2. Modify the `my_proof/proof.py` file to implement your specific proof logic
52+
3. Update the project dependencies in `requirements.txt` if needed
53+
4. Commit your changes and push to your repository
54+
55+
## Customizing the Proof Logic
56+
57+
The main proof logic is implemented in `my_proof/proof.py`. To customize it, update the `Proof.generate()` function to change how input files are processed.
58+
59+
The proof can be configured using environment variables, eg:
60+
61+
- `USER_EMAIL`: The email address of the data contributor, to verify data ownership
62+
63+
If you want to use a language other than Python, you can modify the Dockerfile to install the necessary dependencies and build the proof task in the desired language.
64+
65+
## Local Development
66+
67+
To run the proof locally for testing, you can use Docker:
68+
69+
```bash
70+
docker build -t refiner .
71+
docker run \
72+
--rm \
73+
--volume $(pwd)/input:/input \
74+
--volume $(pwd)/output:/output \
75+
refiner
76+
```
77+
78+
## Running with Intel TDX
79+
80+
Intel TDX (Trust Domain Extensions) provides hardware-based memory encryption and integrity protection for virtual machines. To run this container in a TDX-enabled environment, follow your infrastructure provider's specific instructions for deploying confidential containers.
81+
82+
Common volume mounts and environment variables:
83+
84+
```bash
85+
docker run \
86+
--rm \
87+
--volume /path/to/input:/input \
88+
--volume /path/to/output:/output \
89+
90+
my-proof
91+
```
92+
93+
Remember to populate the `/input` directory with the files you want to process.
94+
95+
## Security Features
96+
97+
This template leverages several security features:
98+
99+
1. **Hardware-based Isolation**: The proof runs inside a TDX-protected environment, isolating it from the rest of the system
100+
2. **Input/Output Isolation**: Input and output directories are mounted separately, ensuring clear data flow boundaries
101+
3. **Minimal Container**: Uses a minimal Python base image to reduce attack surface
102+
103+
## Customization
104+
105+
Feel free to modify any part of this template to fit your specific needs. The goal is to provide a starting point that can be easily adapted to various proof tasks.
106+
107+
## Contributing
108+
109+
If you have suggestions for improving this template, please open an issue or submit a pull request.
110+
111+
## License
112+
113+
[MIT License](LICENSE)
114+
115+
116+
117+
- raw data in /input directory
118+
- encrypt with DLP public key
119+
-
120+
- upload refined data to Pinata
121+
- /output
122+
- schema.json
123+
- ipfs URL
124+
- data.db
125+
- data.db.encrypted -> encrypted w/ derived encryption key
126+
127+

input/user.zip

417 Bytes
Binary file not shown.

refiner/__init__.py

Whitespace-only changes.

refiner/__main__.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import json
2+
import logging
3+
import os
4+
import sys
5+
import traceback
6+
import zipfile
7+
from typing import Dict, Any
8+
9+
from refiner.refine import Refiner
10+
11+
INPUT_DIR, OUTPUT_DIR = '/input', '/output'
12+
13+
logging.basicConfig(level=logging.INFO, format='%(message)s')
14+
15+
16+
def load_config() -> Dict[str, Any]:
17+
"""Load refinement configuration from environment variables."""
18+
config = {
19+
'input_dir': INPUT_DIR,
20+
'output_dir': OUTPUT_DIR,
21+
}
22+
logging.info(f"Using config: {json.dumps(config, indent=2)}")
23+
return config
24+
25+
26+
def run() -> None:
27+
"""Transform all input files into the database."""
28+
config = load_config()
29+
input_files_exist = os.path.isdir(INPUT_DIR) and bool(os.listdir(INPUT_DIR))
30+
31+
if not input_files_exist:
32+
raise FileNotFoundError(f"No input files found in {INPUT_DIR}")
33+
extract_input()
34+
35+
refiner = Refiner(config)
36+
refiner.transform()
37+
38+
logging.info("Data transformation complete")
39+
40+
41+
def extract_input() -> None:
42+
"""
43+
If the input directory contains any zip files, extract them
44+
:return:
45+
"""
46+
for input_filename in os.listdir(INPUT_DIR):
47+
input_file = os.path.join(INPUT_DIR, input_filename)
48+
49+
if zipfile.is_zipfile(input_file):
50+
with zipfile.ZipFile(input_file, 'r') as zip_ref:
51+
zip_ref.extractall(INPUT_DIR)
52+
53+
54+
if __name__ == "__main__":
55+
try:
56+
run()
57+
except Exception as e:
58+
logging.error(f"Error during data transformation: {e}")
59+
traceback.print_exc()
60+
sys.exit(1)

refiner/models/refined_models.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from datetime import datetime
2+
from sqlalchemy import Column, String, Integer, Float, ForeignKey, DateTime
3+
from sqlalchemy.ext.declarative import declarative_base
4+
from sqlalchemy.orm import relationship
5+
6+
# Base model for SQLAlchemy
7+
Base = declarative_base()
8+
9+
# Define database models - the schema is generated using these
10+
class UserRefined(Base):
11+
__tablename__ = 'users'
12+
13+
user_id = Column(String, primary_key=True)
14+
email = Column(String, nullable=False, unique=True)
15+
name = Column(String, nullable=False)
16+
locale = Column(String, nullable=False)
17+
created_at = Column(DateTime, nullable=False)
18+
19+
storage_metrics = relationship("StorageMetric", back_populates="user")
20+
auth_sources = relationship("AuthSource", back_populates="user")
21+
22+
class StorageMetric(Base):
23+
__tablename__ = 'storage_metrics'
24+
25+
metric_id = Column(Integer, primary_key=True, autoincrement=True)
26+
user_id = Column(String, ForeignKey('users.user_id'), nullable=False)
27+
percent_used = Column(Float, nullable=False)
28+
recorded_at = Column(DateTime, nullable=False, default=datetime.utcnow)
29+
30+
user = relationship("UserRefined", back_populates="storage_metrics")
31+
32+
class AuthSource(Base):
33+
__tablename__ = 'auth_sources'
34+
35+
auth_id = Column(Integer, primary_key=True, autoincrement=True)
36+
user_id = Column(String, ForeignKey('users.user_id'), nullable=False)
37+
source = Column(String, nullable=False)
38+
collection_date = Column(DateTime, nullable=False)
39+
data_type = Column(String, nullable=False)
40+
41+
user = relationship("UserRefined", back_populates="auth_sources")

refiner/models/unrefined_models.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import Optional
2+
from pydantic import BaseModel
3+
4+
5+
class Profile(BaseModel):
6+
name: str
7+
locale: str
8+
9+
class Storage(BaseModel):
10+
percentUsed: float
11+
12+
class Metadata(BaseModel):
13+
source: str
14+
collectionDate: str
15+
dataType: str
16+
17+
class User(BaseModel):
18+
userId: str
19+
email: str
20+
timestamp: int
21+
profile: Profile
22+
storage: Optional[Storage] = None
23+
metadata: Optional[Metadata] = None

0 commit comments

Comments
 (0)