brunneis commited on
Commit
5fe2042
1 Parent(s): eae5d4c

First commit

Browse files
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:22-bookworm-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && \
6
+ apt-get install -y python3 python3-pip build-essential && \
7
+ apt-get clean && \
8
+ rm -rf /var/lib/apt/lists/*
9
+
10
+ COPY requirements.txt .
11
+ RUN pip install --no-cache-dir --break-system-packages -U pip && \
12
+ pip install --no-cache-dir --break-system-packages -r requirements.txt
13
+
14
+ COPY hardhat hardhat
15
+ WORKDIR /app/hardhat
16
+ RUN npm install && \
17
+ npx hardhat compile && \
18
+ rm -rf contracts test cache
19
+
20
+ WORKDIR /app
21
+ COPY api .
22
+ COPY init_tasks.py env.sh ./
23
+ ARG HF_DATASET
24
+ RUN python3 init_tasks.py
25
+
26
+ ENTRYPOINT ["./scripts/start-api.sh"]
README.md CHANGED
@@ -5,6 +5,7 @@ colorFrom: pink
5
  colorTo: indigo
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
5
  colorTo: indigo
6
  sdk: docker
7
  pinned: false
8
+ app_port: 63958
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api/auth/basic.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from typing import List, Tuple
5
+
6
+
7
+ class StaticBasicAuthMiddleware:
8
+ def __init__(self, auth_tuples: List[Tuple[str, str]]):
9
+ raise NotImplementedError
api/auth/token.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from typing import List
5
+
6
+ import falcon
7
+
8
+
9
+ class StaticTokenAuthMiddleware:
10
+ def __init__(self, tokens: List[str]):
11
+ self._tokens = set(tokens)
12
+
13
+ def process_request(self, request, _):
14
+ if request.method == 'OPTIONS':
15
+ return
16
+
17
+ if request.path == '/':
18
+ return
19
+
20
+ token = request.get_header('Authorization')
21
+ if token is None or token.split(' ')[-1] not in self._tokens:
22
+ raise falcon.HTTPUnauthorized
api/config.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ ---
api/engine.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+
5
+ import os
6
+ import subprocess
7
+
8
+
9
+ def evaluate_solution(task_id: str, solution: str):
10
+ initial_dir = os.getcwd()
11
+ task_dir = task_id.replace('/', '_')
12
+ task_path = 'tasks/' + task_dir
13
+ os.chdir(task_path)
14
+
15
+ with open('contracts/Task.sol', 'w') as f:
16
+ f.write(solution)
17
+ try:
18
+ subprocess.run(['npx', 'hardhat', 'test'], check=True)
19
+ return True
20
+ except subprocess.CalledProcessError:
21
+ return False
22
+ finally:
23
+ os.chdir(initial_dir)
api/main.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import falcon
5
+ import yaml
6
+ from resources.root import RootResource
7
+
8
+ with open('./config.yaml', 'r') as stream:
9
+ config = yaml.safe_load(stream)
10
+
11
+ app = falcon.App(
12
+ middleware=[],
13
+ cors_enable=True,
14
+ )
15
+
16
+ app.add_route('/', RootResource())
api/resources/root.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from threading import Lock
5
+
6
+ import falcon
7
+ from engine import evaluate_solution
8
+
9
+
10
+ class RootResource:
11
+ def __init__(self):
12
+ self.main_lock = Lock()
13
+ self.task_locks = {}
14
+
15
+ def on_post(self, request, response):
16
+ payload = request.media
17
+
18
+ bad_request = ('task_id' not in payload or 'solution' not in payload)
19
+ if bad_request:
20
+ response.status = falcon.HTTP_400
21
+ response.media = {
22
+ 'error': 'task_id or solution are missing',
23
+ }
24
+ return
25
+
26
+ task_id = payload['task_id']
27
+ solution = payload['solution']
28
+
29
+ with self.main_lock:
30
+ if task_id not in self.task_locks:
31
+ self.task_locks[task_id] = Lock()
32
+
33
+ with self.task_locks[task_id]:
34
+ passed = evaluate_solution(task_id, solution)
35
+
36
+ response.media = {'passed': passed}
api/scripts/start-api.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd $(dirname $0)/..
3
+ source env.sh
4
+
5
+ uwsgi \
6
+ --master \
7
+ --http 0.0.0.0:63958 \
8
+ --wsgi-file main.py \
9
+ --callable app \
10
+ --processes 1 \
11
+ --threads $API_THREADS_COUNT
hardhat/.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules
2
+ .env
3
+
4
+ # Hardhat files
5
+ /cache
6
+ /artifacts
7
+
8
+ # TypeChain files
9
+ /typechain
10
+ /typechain-types
11
+
12
+ # solidity-coverage files
13
+ /coverage
14
+ /coverage.json
15
+
16
+ # Hardhat Ignition default folder for deployments against a local node
17
+ ignition/deployments/chain-31337
hardhat/contracts/Lock.sol ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.24;
3
+
4
+ // Uncomment this line to use console.log
5
+ // import "hardhat/console.sol";
6
+
7
+ contract Lock {
8
+ uint public unlockTime;
9
+ address payable public owner;
10
+
11
+ event Withdrawal(uint amount, uint when);
12
+
13
+ constructor(uint _unlockTime) payable {
14
+ require(
15
+ block.timestamp < _unlockTime,
16
+ "Unlock time should be in the future"
17
+ );
18
+
19
+ unlockTime = _unlockTime;
20
+ owner = payable(msg.sender);
21
+ }
22
+
23
+ function withdraw() public {
24
+ // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal
25
+ // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);
26
+
27
+ require(block.timestamp >= unlockTime, "You can't withdraw yet");
28
+ require(msg.sender == owner, "You aren't the owner");
29
+
30
+ emit Withdrawal(address(this).balance, block.timestamp);
31
+
32
+ owner.transfer(address(this).balance);
33
+ }
34
+ }
hardhat/hardhat.config.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require("@nomicfoundation/hardhat-toolbox");
2
+
3
+ /** @type import('hardhat/config').HardhatUserConfig */
4
+ module.exports = {
5
+ solidity: "0.8.24",
6
+ networks: {
7
+ hardhat: {
8
+ blockGasLimit: 1000000000,
9
+ },
10
+ },
11
+ };
hardhat/package.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "devDependencies": {
3
+ "hardhat": "^2.22.8",
4
+ "@nomicfoundation/hardhat-toolbox": "^5.0.0"
5
+ }
6
+ }
hardhat/test/Lock.js ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const {
2
+ time,
3
+ loadFixture,
4
+ } = require("@nomicfoundation/hardhat-toolbox/network-helpers");
5
+ const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs");
6
+ const { expect } = require("chai");
7
+
8
+ describe("Lock", function () {
9
+ // We define a fixture to reuse the same setup in every test.
10
+ // We use loadFixture to run this setup once, snapshot that state,
11
+ // and reset Hardhat Network to that snapshot in every test.
12
+ async function deployOneYearLockFixture() {
13
+ const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60;
14
+ const ONE_GWEI = 1_000_000_000;
15
+
16
+ const lockedAmount = ONE_GWEI;
17
+ const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS;
18
+
19
+ // Contracts are deployed using the first signer/account by default
20
+ const [owner, otherAccount] = await ethers.getSigners();
21
+
22
+ const Lock = await ethers.getContractFactory("Lock");
23
+ const lock = await Lock.deploy(unlockTime, { value: lockedAmount });
24
+
25
+ return { lock, unlockTime, lockedAmount, owner, otherAccount };
26
+ }
27
+
28
+ describe("Deployment", function () {
29
+ it("Should set the right unlockTime", async function () {
30
+ const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture);
31
+
32
+ expect(await lock.unlockTime()).to.equal(unlockTime);
33
+ });
34
+
35
+ it("Should set the right owner", async function () {
36
+ const { lock, owner } = await loadFixture(deployOneYearLockFixture);
37
+
38
+ expect(await lock.owner()).to.equal(owner.address);
39
+ });
40
+
41
+ it("Should receive and store the funds to lock", async function () {
42
+ const { lock, lockedAmount } = await loadFixture(
43
+ deployOneYearLockFixture
44
+ );
45
+
46
+ expect(await ethers.provider.getBalance(lock.target)).to.equal(
47
+ lockedAmount
48
+ );
49
+ });
50
+
51
+ it("Should fail if the unlockTime is not in the future", async function () {
52
+ // We don't use the fixture here because we want a different deployment
53
+ const latestTime = await time.latest();
54
+ const Lock = await ethers.getContractFactory("Lock");
55
+ await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith(
56
+ "Unlock time should be in the future"
57
+ );
58
+ });
59
+ });
60
+
61
+ describe("Withdrawals", function () {
62
+ describe("Validations", function () {
63
+ it("Should revert with the right error if called too soon", async function () {
64
+ const { lock } = await loadFixture(deployOneYearLockFixture);
65
+
66
+ await expect(lock.withdraw()).to.be.revertedWith(
67
+ "You can't withdraw yet"
68
+ );
69
+ });
70
+
71
+ it("Should revert with the right error if called from another account", async function () {
72
+ const { lock, unlockTime, otherAccount } = await loadFixture(
73
+ deployOneYearLockFixture
74
+ );
75
+
76
+ // We can increase the time in Hardhat Network
77
+ await time.increaseTo(unlockTime);
78
+
79
+ // We use lock.connect() to send a transaction from another account
80
+ await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith(
81
+ "You aren't the owner"
82
+ );
83
+ });
84
+
85
+ it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () {
86
+ const { lock, unlockTime } = await loadFixture(
87
+ deployOneYearLockFixture
88
+ );
89
+
90
+ // Transactions are sent using the first signer by default
91
+ await time.increaseTo(unlockTime);
92
+
93
+ await expect(lock.withdraw()).not.to.be.reverted;
94
+ });
95
+ });
96
+
97
+ describe("Events", function () {
98
+ it("Should emit an event on withdrawals", async function () {
99
+ const { lock, unlockTime, lockedAmount } = await loadFixture(
100
+ deployOneYearLockFixture
101
+ );
102
+
103
+ await time.increaseTo(unlockTime);
104
+
105
+ await expect(lock.withdraw())
106
+ .to.emit(lock, "Withdrawal")
107
+ .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg
108
+ });
109
+ });
110
+
111
+ describe("Transfers", function () {
112
+ it("Should transfer the funds to the owner", async function () {
113
+ const { lock, unlockTime, lockedAmount, owner } = await loadFixture(
114
+ deployOneYearLockFixture
115
+ );
116
+
117
+ await time.increaseTo(unlockTime);
118
+
119
+ await expect(lock.withdraw()).to.changeEtherBalances(
120
+ [owner, lock],
121
+ [lockedAmount, -lockedAmount]
122
+ );
123
+ });
124
+ });
125
+ });
126
+ });
init_tasks.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import os
5
+ import shutil
6
+ from os import environ as env
7
+
8
+ from datasets import load_dataset
9
+
10
+
11
+ def create_task_projects():
12
+ dataset = load_dataset(env['HF_DATASET'], split='test')
13
+
14
+ base_dir = 'hardhat'
15
+ for row in dataset:
16
+ task_id = row['task_id']
17
+ test_content = row['test']
18
+ canonical_solution = row['canonical_solution']
19
+
20
+ task_dir = os.path.join('tasks', task_id.replace('/', '_'))
21
+
22
+ if os.path.exists(task_dir):
23
+ shutil.rmtree(task_dir)
24
+ os.makedirs(task_dir)
25
+
26
+ for item in os.listdir(base_dir):
27
+ if item == 'hardhat.config.js':
28
+ continue
29
+ src = os.path.join(base_dir, item)
30
+ dst = os.path.join(task_dir, item)
31
+ os.symlink(os.path.abspath(src), dst)
32
+
33
+ shutil.copy(os.path.join(base_dir, 'hardhat.config.js'), task_dir)
34
+
35
+ os.makedirs(os.path.join(task_dir, 'contracts'), exist_ok=True)
36
+ os.makedirs(os.path.join(task_dir, 'test'), exist_ok=True)
37
+
38
+ with open(os.path.join(task_dir, 'contracts', 'Task.sol'), 'w') as f:
39
+ f.write(canonical_solution)
40
+
41
+ with open(os.path.join(task_dir, 'test', 'Task.js'), 'w') as f:
42
+ f.write(test_content)
43
+
44
+
45
+ if __name__ == '__main__':
46
+ create_task_projects()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ datasets
2
+ falcon
3
+ uwsgi
4
+ pyyaml