akaaafk commited on
Commit
c226b05
·
verified ·
1 Parent(s): 456d198

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmark/IOAI/IOAI2025/Individual-Contest/Pixel/Pixel.ipynb +643 -0
  2. benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Radar.ipynb +564 -0
  3. benchmark/IOL/ioling_hf/reports/answer_given_rationale/Qwen_Qwen3-4B-Instruct-2507__v14_hakhun_manual_derivation_n4.md +232 -0
  4. benchmark/IOL/ioling_hf/reports/curation_queue/index.html +0 -0
  5. benchmark/IOL/ioling_hf/reports/curation_queue/queue.json +712 -0
  6. benchmark/IOL/ioling_hf/reports/evaluation/qwen3_4b_base_unseen_v14_sources_pass8.json +0 -0
  7. benchmark/IOL/ioling_hf/reports/evaluation/qwen3_4b_instruct_base_v14_val_pass8.json +0 -0
  8. benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v2_unseen_v14_sources_pass8.json +0 -0
  9. benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v3_15sources_train_one_per_source_pass8.json +0 -0
  10. benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v3_15sources_val_pass8.json +0 -0
  11. benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_8x4k.json +0 -0
  12. benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_nothink_8x4k.json +0 -0
  13. benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_nothink_finalonly_8x4k.json +0 -0
  14. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/LICENSE +7 -0
  15. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/METADATA +259 -0
  16. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/RECORD +14 -0
  17. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/top_level.txt +2 -0
  18. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/_compat.py +45 -0
  19. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/bindings.py +117 -0
  20. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/bn.py +1047 -0
  21. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/cipher.py +603 -0
  22. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/compile.py +94 -0
  23. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/ec.py +787 -0
  24. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/ecdsa.py +250 -0
  25. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/hmac.py +177 -0
  26. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/pack.py +318 -0
  27. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytest-4.6.5.dist-info/WHEEL +6 -0
  28. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Abidjan +0 -0
  29. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Accra +0 -0
  30. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Addis_Ababa +0 -0
  31. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Algiers +0 -0
  32. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Asmara +0 -0
  33. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Asmera +0 -0
  34. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bamako +0 -0
  35. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bangui +0 -0
  36. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Banjul +0 -0
  37. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bissau +0 -0
  38. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Blantyre +0 -0
  39. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Brazzaville +0 -0
  40. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Dakar +0 -0
  41. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Dar_es_Salaam +0 -0
  42. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Djibouti +0 -0
  43. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Douala +0 -0
  44. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/El_Aaiun +0 -0
  45. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Freetown +0 -0
  46. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Gaborone +0 -0
  47. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Harare +0 -0
  48. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Johannesburg +0 -0
  49. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Juba +0 -0
  50. benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Kampala +0 -0
benchmark/IOAI/IOAI2025/Individual-Contest/Pixel/Pixel.ipynb ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "362e9f36-2300-4851-8f49-b952e62a2c78",
6
+ "metadata": {},
7
+ "source": [
8
+ "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
9
+ "\n",
10
+ "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
11
+ "\n",
12
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Pixel/Pixel.ipynb)"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "id": "4509a190",
18
+ "metadata": {},
19
+ "source": [
20
+ "# Pixel Efficiency\n",
21
+ "\n",
22
+ "## 1. Problem Description\n",
23
+ "\n",
24
+ "You are a student in wildlife biology, working on a groundbreaking research project at the Starr Park Research Center. Your team has deployed thousands of camera traps across remote wilderness areas to monitor endangered species populations. However, the satellite internet connections in these remote locations have extremely limited bandwidth. Your job is to write code that identifies the most critical pixels in each wildlife photograph so that only the essential visual information needs to be transmitted back to headquarters.\n",
25
+ "\n",
26
+ "<img src=\"./figs/Pixel Fig 1.png\" width=\"400\">\n",
27
+ "\n",
28
+ "## 2. Dataset\n",
29
+ "\n",
30
+ "The dataset consists of a training set and a test set. Datasets are loaded using `load_from_disk`, and are in the format of `datasets`. Test set is not visible to the contestants.\n",
31
+ "\n",
32
+ "In the dataset there are the following fields:\n",
33
+ "\n",
34
+ "- `image`: the image are RGB full color images in PIL format, the size of each image is (224, 224)\n",
35
+ "- `name`: the animal species label\n",
36
+ "- `idx`: unique identifiers used to track the records.\n",
37
+ "\n",
38
+ "1. **Training Set (`train_dataset` folder)**:\n",
39
+ " - The training set is used for training your models/ doing experimentations on and can be accessed and downloaded directly during the competition.\n",
40
+ " - There are 700 images in the training set.\n",
41
+ "\n",
42
+ "2. **Test Set (`test_dataset` folder)**: \n",
43
+ " - These follow the same format as the training set but do not contain the `name` field.\n",
44
+ " - There are 698 images in test set, which had been separated into 2 testing sets within the ratio of 3:7, i.e. 30% of the data would be used to calculate the Leaderboard A score, another 70% data would be used to calculate the Leaderboard B score.\n",
45
+ " - The testing set is used to calculate the Leaderboard A score and the Leaderboard B score and is not directly accessible during the competition. Contestants can access the result on Leaderboard A , but cannot access the result on Leaderboard B. The final score would be counted using Leaderboard B only. The subsets for Leaderboard A and Leaderboard B are completely distinct.\n",
46
+ " \n",
47
+ "\n",
48
+ "## 3. Task\n",
49
+ "You are given a dataset of animal photographs and a CLIP model that can do a zero-shot classification of animal species. To conserve bandwidth, you need to retain at most **6.25%** of the pixels of each image, while keeping classification accuracy as high as possible.\n",
50
+ "\n",
51
+ "More specifically, your task is to return **one rectangle mask** for each image, which contain a single rectangular area indicating the area to keep. Each mask is defined by two coordinate tuples: one for the top-left corner and one for the bottom-right corner of the rectangle. Below is a visualization of what the image would look like after applying a rectangular mask using the process from the baseline:\n",
52
+ "\n",
53
+ "<img src=\"./figs/Pixel Fig 2.png\" width=\"400\">\n",
54
+ "\n",
55
+ "**Coordinate Convention:**\n",
56
+ "- Top-left corner coordinates are **inclusive** (the pixel at this position is included in the mask) \n",
57
+ "- Bottom-right corner coordinates are **exclusive** (the pixel at this position is NOT included in the mask)\n",
58
+ "\n",
59
+ "For example, if you specify coordinates `((10, 20), (15, 25))`, the mask will cover pixels from row 10 to 14 (inclusive) and column 20 to 24 (inclusive), for a total area of 25 pixels.\n",
60
+ "\n",
61
+ "As an illustration, if an image size is 3x3 and we wanted to keep only the top-right pixel using coordinates `((0, 2), (1, 3))`, the resulting binary mask would be:\n",
62
+ "\n",
63
+ "```\n",
64
+ "[[0, 0, 1],\n",
65
+ " [0, 0, 0],\n",
66
+ " [0, 0, 0]]\n",
67
+ "```\n",
68
+ "\n",
69
+ "Below is a summary of the requirements for your masks:\n",
70
+ "\n",
71
+ "- Return one rectangle mask defined by coordinate tuples: `((top, left), (bottom, right))`\n",
72
+ "- Top-left corner coordinates are inclusive, bottom-right corner coordinates are exclusive\n",
73
+ "- The rectangle mask should cover at most *6.25%* of the original pixels (minimum 93.75% reduction of the original pixels)\n",
74
+ "- All images are of size (224, 224), so coordinate values should be within the range [0, 224]\n",
75
+ "\n",
76
+ "\n",
77
+ "Images would be masked using the mask you created, outside the masked rectangle, all pixels outside the masked rectangle will be replaced with RGB(0, 0, 0) (black) values. The masked image will be then passed through the CLIP model during evaluation, and your task is to keep the classification accuracy of the CLIP model on these masked images as high as possible. **An additional `other` class would be added into the classes for classification** to ensure that your masked image retains actual useful information for the researchers back at Starr Park Headquarters. So for example, if your image doesn't contain any animal information, the model will predict the `others` class instead of predicting a random animal and having a chance of getting it correct.\n",
78
+ "\n",
79
+ "You need to work only with the provided CLIP model and dataset. As a reminder, CLIP generates representations for both text and image, and it can compute a similarity score between them. So if you have ten animal classes, CLIP can look at the provided image and decide which text (class) is closest to the image. \n",
80
+ "\n",
81
+ "To ensure that your solution would handle the traffic of images for the research center, your code should run in **UNDER 8 MINUTES for the 698 images in the test dataset**. It is recommended that you test your solution on the training set first, which contain 700 images, to understand how much time your solution takes (testing set would take slightly longer due to dataset loading).\n",
82
+ "\n",
83
+ "## 4. Submission\n",
84
+ "\n",
85
+ "Contestants need to submit a notebook file named `submission.ipynb`. The file should output a `.jsonl` file titled `submission.jsonl`, which contains all the generated masks for the dataset split. Each mask in the `submission.jsonl` file should be stored as a tuple of two coordinate tuples: `((top, left), (bottom, right))`, where the top-left corner is inclusive and the bottom-right corner is exclusive.\n",
86
+ "\n",
87
+ "Contestants don't need to separate test sets into Leaderboard A and Leaderboard B, the evaluation machine will read `submission.jsonl` and automatically calculate the scores for Leaderboard A and Leaderboard B based on the prediction results and true labels. \n",
88
+ "\n",
89
+ "The submission files must strictly follow the above format and naming; otherwise, the system will not be able to read them correctly. \n",
90
+ "\n",
91
+ "## 5. Score\n",
92
+ "\n",
93
+ "The evaluation metric will be **classification accuracy**, defined as the proportion of correctly predicted samples over the total number of evaluated samples.\n",
94
+ "\n",
95
+ "Your score is the zero-shot classification accuracy of CLIP on the masked test images. **If a submitted mask for an image is invalid (wrong shape, more than 6.25% pixels retained, etc.), that image is counted as incorrect. A sample script is provided to compute the training split score.**\n",
96
+ "\n",
97
+ "\n",
98
+ "## 6. Baseline and Training Set\n",
99
+ "\n",
100
+ "- Below you can find the baseline solution.\n",
101
+ "- The dataset is in `training_set` folder.\n",
102
+ "- The highest score by the Scientific Committee for this task is 0.83 in Leader Board B, this score is used for score unification.\n",
103
+ "- The baseline score by the Scientific Committee for this task is 0.19 in Leader Board B, this score is used for score unification."
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "execution_count": null,
109
+ "id": "9d1ad03b-ba1e-4c24-b866-fe6a138b58c9",
110
+ "metadata": {},
111
+ "outputs": [],
112
+ "source": [
113
+ "import random\n",
114
+ "import numpy as np\n",
115
+ "import torch\n",
116
+ "\n",
117
+ "seed = 42\n",
118
+ "\n",
119
+ "random.seed(seed) # Python built-in random\n",
120
+ "np.random.seed(seed) # NumPy\n",
121
+ "torch.manual_seed(seed) # PyTorch (CPU)\n",
122
+ "torch.cuda.manual_seed(seed) # PyTorch (single GPU)\n",
123
+ "torch.cuda.manual_seed_all(seed) # PyTorch (all GPUs)\n",
124
+ "\n",
125
+ "# Ensures deterministic behavior\n",
126
+ "torch.backends.cudnn.deterministic = True\n",
127
+ "torch.backends.cudnn.benchmark = False"
128
+ ]
129
+ },
130
+ {
131
+ "cell_type": "markdown",
132
+ "id": "af37a8ed",
133
+ "metadata": {},
134
+ "source": [
135
+ "### Dependencies and Config Variables"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": null,
141
+ "id": "23b68a41",
142
+ "metadata": {},
143
+ "outputs": [],
144
+ "source": [
145
+ "import os\n",
146
+ "import matplotlib.pyplot as plt\n",
147
+ "import numpy as np\n",
148
+ "from collections import Counter\n",
149
+ "from PIL import Image\n",
150
+ "from tqdm import tqdm\n",
151
+ "import glob\n",
152
+ "import json\n",
153
+ "import math\n",
154
+ "import torch\n",
155
+ "import matplotlib.pyplot as plt\n",
156
+ "from datasets import load_dataset, load_from_disk\n",
157
+ "from transformers import CLIPProcessor, CLIPModel\n",
158
+ "from PIL import Image\n",
159
+ "from tqdm.auto import tqdm \n",
160
+ "\n",
161
+ "TRAIN_PATH = \"./training_set/\"\n",
162
+ "# The training set is deployed automatically in the testing machine. \n",
163
+ "# You notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n",
164
+ "\n",
165
+ "MODEL_PATH = \"./clip-vit-large-patch14\"\n",
166
+ "# The clip model is deployed automatically in the testing machine. \n",
167
+ "# You notebook can access the MODEL_PATH even if you do not mount it along with notebook.\n",
168
+ "\n",
169
+ "DATASET_PATH = TRAIN_PATH + \"train_dataset\"\n",
170
+ "SPLIT = \"train\"\n",
171
+ "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
172
+ "BACKGROUND_CLASS = \"other\" # Class used to catch masked images that have no useful information, preventing completely off masks from \"guessing\" the answer from the 10 classes\n",
173
+ "\n",
174
+ "# Image and Masking Configuration\n",
175
+ "HEIGHT = 224\n",
176
+ "WIDTH = 224\n",
177
+ "RETAIN_RATIO = 0.0625 # Retain 6.25% of pixels\n",
178
+ "MEAN_COLOR = (0, 0, 0) # RGB mean values for masked out areas\n"
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "markdown",
183
+ "id": "b888c040",
184
+ "metadata": {},
185
+ "source": [
186
+ "### Dataset loading\n",
187
+ "\n",
188
+ "Let's first load the dataset in and see what's in it:\n"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "execution_count": null,
194
+ "id": "857ab7ff",
195
+ "metadata": {},
196
+ "outputs": [],
197
+ "source": [
198
+ "# Load the dataset\n",
199
+ "print(\"Loading dataset...\")\n",
200
+ "dataset_whole = load_from_disk(DATASET_PATH)\n",
201
+ "dataset = dataset_whole[SPLIT]\n",
202
+ "\n",
203
+ "# Print first item to check available fields\n",
204
+ "print(\"\\nFirst item keys:\")\n",
205
+ "print(dataset_whole[SPLIT][0].keys())\n",
206
+ "\n",
207
+ "# Show basic dataset statistics without converting fields yet\n",
208
+ "print(f\"\\nDataset loaded successfully!\")\n",
209
+ "print(f\"Total samples: {len(dataset)}\")\n",
210
+ "\n",
211
+ "print(f\"\\nSample item structure:\")\n",
212
+ "sample_item = dataset[0]\n",
213
+ "print(f\" Keys: {list(sample_item.keys())}\")\n",
214
+ "print(f\" Image type: {type(sample_item['image'])}\")\n",
215
+ "print(f\" Image size: {sample_item['image'].size}\")\n",
216
+ "print(f\" Index: {sample_item['idx']}\")\n",
217
+ "\n"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "id": "37c2dbfa",
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "# Visualize first 10 samples\n",
228
+ "fig, axes = plt.subplots(2, 5, figsize=(15, 8))\n",
229
+ "axes = axes.flatten()\n",
230
+ "\n",
231
+ "print(\"Visualizing first 10 samples...\")\n",
232
+ "\n",
233
+ "for i in range(10):\n",
234
+ " sample = dataset[i]\n",
235
+ " image = sample['image']\n",
236
+ " label = sample['name']\n",
237
+ " \n",
238
+ " axes[i].imshow(image)\n",
239
+ " axes[i].set_title(f\"{label}\\n\", fontsize=12)\n",
240
+ " axes[i].axis('off')\n",
241
+ "\n",
242
+ "plt.tight_layout()\n",
243
+ "plt.suptitle('First 10 Samples from Dataset', fontsize=16, y=1.02)\n",
244
+ "plt.show()\n"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "markdown",
249
+ "id": "24cee96a",
250
+ "metadata": {},
251
+ "source": [
252
+ "### Model\n",
253
+ "\n",
254
+ "Now let's load the model and see some predictions:"
255
+ ]
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "execution_count": null,
260
+ "id": "fd92b376",
261
+ "metadata": {},
262
+ "outputs": [],
263
+ "source": [
264
+ "print(f\"Loading CLIP model and processor: {MODEL_PATH}...\")\n",
265
+ "model = CLIPModel.from_pretrained(MODEL_PATH).to(DEVICE)\n",
266
+ "processor = CLIPProcessor.from_pretrained(MODEL_PATH)\n",
267
+ "print(\"Model and processor loaded successfully.\")"
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "execution_count": null,
273
+ "id": "a2e25924",
274
+ "metadata": {},
275
+ "outputs": [],
276
+ "source": [
277
+ "image = dataset[0]['image']\n",
278
+ "# Visualize the image with its true label\n",
279
+ "plt.figure(figsize=(8, 6))\n",
280
+ "plt.imshow(image)\n",
281
+ "plt.title(f\"Sample Image\\nTrue Label: {dataset[0]['name']}\", fontsize=14)\n",
282
+ "plt.axis('off')\n",
283
+ "plt.show()\n",
284
+ "\n",
285
+ "\n",
286
+ "labels = sorted(list(set(dataset['name']))) + [BACKGROUND_CLASS]\n",
287
+ "text_inputs = processor(text=labels, return_tensors=\"pt\", padding=True).to(DEVICE)\n",
288
+ "image_processed = processor(images=image, return_tensors=\"pt\").to(DEVICE)\n",
289
+ "pixel_values = image_processed['pixel_values']\n",
290
+ "outputs_full = model(pixel_values=pixel_values, **text_inputs)\n",
291
+ "logits_full = outputs_full.logits_per_image # Shape: (1, num_styles)\n",
292
+ "predicted_index_full = logits_full.argmax(dim=-1).item()\n",
293
+ "\n",
294
+ "print(f\"Predicted label: {labels[predicted_index_full]}\")\n"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "markdown",
299
+ "id": "54467f0c",
300
+ "metadata": {},
301
+ "source": [
302
+ "### Baseline: A trivial masking method\n",
303
+ "\n",
304
+ "We will now be implementing a trivial masking solution, one that randomly masks out 90% of the pixels."
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": null,
310
+ "id": "0ee24b90",
311
+ "metadata": {},
312
+ "outputs": [],
313
+ "source": [
314
+ "def generate_center_crop_coordinates(image):\n",
315
+ " \"\"\"\n",
316
+ " Generate coordinates for a center crop mask.\n",
317
+ " \n",
318
+ " Returns:\n",
319
+ " tuple: ((top, left), (bottom, right)) coordinates for the crop\n",
320
+ " \"\"\"\n",
321
+ " H, W = image.size\n",
322
+ " total_px = H * W\n",
323
+ " k = int(total_px * RETAIN_RATIO)\n",
324
+ " \n",
325
+ " # Calculate side length of the square crop\n",
326
+ " side_length = int(np.sqrt(k))\n",
327
+ " \n",
328
+ " # Calculate center coordinates\n",
329
+ " center_h, center_w = H // 2, W // 2\n",
330
+ " \n",
331
+ " # Calculate crop boundaries\n",
332
+ " half_side = side_length // 2\n",
333
+ " top = max(0, center_h - half_side)\n",
334
+ " left = max(0, center_w - half_side)\n",
335
+ " bottom = min(H, top + side_length)\n",
336
+ " right = min(W, left + side_length)\n",
337
+ " \n",
338
+ " return ((top, left), (bottom, right))\n",
339
+ "\n",
340
+ "def generate_mask_from_coordinates(image, coordinates):\n",
341
+ " \"\"\"\n",
342
+ " Generate a binary mask from crop coordinates.\n",
343
+ " \n",
344
+ " Parameters:\n",
345
+ " image: PIL Image\n",
346
+ " coordinates: tuple of ((top, left), (bottom, right))\n",
347
+ " \n",
348
+ " Returns:\n",
349
+ " numpy array: Binary mask with 1s in the crop area\n",
350
+ " \"\"\"\n",
351
+ " H, W = image.size\n",
352
+ " mask = np.zeros((H, W), dtype=np.int8)\n",
353
+ " \n",
354
+ " (top, left), (bottom, right) = coordinates\n",
355
+ " mask[top:bottom, left:right] = 1\n",
356
+ " \n",
357
+ " return mask"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": null,
363
+ "id": "e87f8f85",
364
+ "metadata": {},
365
+ "outputs": [],
366
+ "source": [
367
+ "def apply_mask_with_mean(image, mask, mean_rgb=MEAN_COLOR):\n",
368
+ " \"\"\"\n",
369
+ " Apply arbitrary binary mask to image, replacing masked areas with mean values\n",
370
+ "\n",
371
+ " Parameters:\n",
372
+ " - image: PIL Image (224x224)\n",
373
+ " - mask: Binary numpy array or PIL Image (224x224) where 0 is the area to drop and 1 is the area to keep\n",
374
+ " - mean_rgb: RGB mean values to use (default: from config)\n",
375
+ "\n",
376
+ " Returns: Modified PIL Image\n",
377
+ " \"\"\"\n",
378
+ " # Convert images to numpy arrays\n",
379
+ " img_array = np.array(image).copy()\n",
380
+ "\n",
381
+ " # Ensure mask is numpy array\n",
382
+ " if isinstance(mask, Image.Image):\n",
383
+ " mask_array = np.array(mask.convert('L')) > 127 # Convert to binary\n",
384
+ " else:\n",
385
+ " mask_array = mask > 0\n",
386
+ "\n",
387
+ " # Reshape mask for broadcasting with RGB\n",
388
+ " mask_3d = np.stack([mask_array] * 3, axis=2)\n",
389
+ "\n",
390
+ " # Convert mean values to 0-255 range\n",
391
+ " mean_values = np.array([int(m * 255) for m in mean_rgb])\n",
392
+ " # Apply mask - replace areas where mask is 0 (drop) with mean values, keep areas where mask is 1\n",
393
+ " img_array = np.where(mask_3d, img_array, mean_values.reshape(1, 1, 3))\n",
394
+ "\n",
395
+ " return Image.fromarray(img_array.astype(np.uint8))"
396
+ ]
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "execution_count": null,
401
+ "id": "a84ed28b",
402
+ "metadata": {},
403
+ "outputs": [],
404
+ "source": [
405
+ "image = dataset[0]['image']\n",
406
+ "# Visualize the image with its true label\n",
407
+ "plt.figure(figsize=(8, 6))\n",
408
+ "plt.imshow(image)\n",
409
+ "plt.title(f\"Sample Image\\nTrue Label: {dataset[0]['name']}\", fontsize=14)\n",
410
+ "plt.axis('off')\n",
411
+ "plt.show()\n",
412
+ "\n",
413
+ "\n",
414
+ "labels = sorted(list(set(dataset['name']))) + [BACKGROUND_CLASS]\n",
415
+ "text_inputs = processor(text=labels, return_tensors=\"pt\", padding=True).to(DEVICE)\n",
416
+ "\n",
417
+ "mask = generate_mask_from_coordinates(image, generate_center_crop_coordinates(image))\n",
418
+ "image_masked = apply_mask_with_mean(image, mask)\n",
419
+ "\n",
420
+ "plt.figure(figsize=(8, 6))\n",
421
+ "plt.imshow(image_masked)\n",
422
+ "plt.title(f\"Masked Image\\nTrue Label: {dataset[0]['name']}\", fontsize=14)\n",
423
+ "plt.axis('off')\n",
424
+ "plt.show()\n",
425
+ "\n",
426
+ "image_processed = processor(images=image_masked, return_tensors=\"pt\").to(DEVICE)\n",
427
+ "pixel_values = image_processed['pixel_values']\n",
428
+ "outputs_full = model(pixel_values=pixel_values, **text_inputs)\n",
429
+ "logits_full = outputs_full.logits_per_image # Shape: (1, num_styles)\n",
430
+ "predicted_index_full = logits_full.argmax(dim=-1).item()\n",
431
+ "\n",
432
+ "print(f\"Predicted label: {labels[predicted_index_full]}\")"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "markdown",
437
+ "id": "d6987536",
438
+ "metadata": {},
439
+ "source": [
440
+ "### Exporting the masks\n"
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "code",
445
+ "execution_count": null,
446
+ "id": "8aa65a80",
447
+ "metadata": {},
448
+ "outputs": [],
449
+ "source": [
450
+ "#DATA_PATH is the secret environment variable to point the address of the validation set and test set on the testing machine. \n",
451
+ "#Contestants cannot access this address locally.\n",
452
+ "import os\n",
453
+ "if os.environ.get('DATA_PATH'):\n",
454
+ " TEST_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
455
+ "else:\n",
456
+ " TEST_PATH = \"\" # Fallback for local testing\n",
457
+ "\n",
458
+ "dataset = load_from_disk(TEST_PATH + \"test_dataset\")\n",
459
+ "split = \"test\"\n",
460
+ "dataset = dataset[split]"
461
+ ]
462
+ },
463
+ {
464
+ "cell_type": "code",
465
+ "execution_count": null,
466
+ "id": "5cae01f0",
467
+ "metadata": {},
468
+ "outputs": [],
469
+ "source": [
470
+ "## Exporting results and validating on full dataset\n",
471
+ "RETAIN_RATIO = 0.0625\n",
472
+ "\n",
473
+ "masks = {}\n",
474
+ "for item in tqdm(dataset):\n",
475
+ " image = item['image']\n",
476
+ "\n",
477
+ " ## you should replace mask generation with your function\n",
478
+ " coordinates = generate_center_crop_coordinates(image)\n",
479
+ " \n",
480
+ " # don't need to change below, it's just saving to file\n",
481
+ " idx = item['idx']\n",
482
+ " # For validation, we still need to generate the full mask\n",
483
+ " mask = generate_mask_from_coordinates(image, coordinates)\n",
484
+ " assert mask.shape == (224, 224), \"Mask should be 224x224\"\n",
485
+ " assert mask.sum() <= RETAIN_RATIO * 224 * 224, \"You should leave only 6.25% of pixels\"\n",
486
+ " \n",
487
+ " # Save only the coordinates (topleft, bottomright) instead of the full mask\n",
488
+ " masks[idx] = coordinates\n",
489
+ "\n",
490
+ "# Save as JSONL (one JSON object per line) - much safer than pickle\n",
491
+ "with open('submission.jsonl', 'w') as f:\n",
492
+ " for idx, coordinates in masks.items():\n",
493
+ " json.dump({\"idx\": idx, \"coordinates\": coordinates}, f)\n",
494
+ " f.write('\\n')\n",
495
+ "\n",
496
+ "print(\"Masks saved to masks.jsonl\")"
497
+ ]
498
+ },
499
+ {
500
+ "cell_type": "markdown",
501
+ "id": "ed60e044",
502
+ "metadata": {},
503
+ "source": [
504
+ "### Validation"
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "code",
509
+ "execution_count": null,
510
+ "id": "3d1ef680",
511
+ "metadata": {},
512
+ "outputs": [],
513
+ "source": [
514
+ "# # Validation code for generated masks\n",
515
+ "\n",
516
+ "# def check_validity(coordinates):\n",
517
+ "# \"\"\"\n",
518
+ "# Check if coordinates are valid according to the requirements.\n",
519
+ "# Returns True if valid, False otherwise.\n",
520
+ "# \"\"\"\n",
521
+ "# try:\n",
522
+ "# # Check if coordinates is a tuple of two tuples\n",
523
+ "# if not isinstance(coordinates, tuple) or len(coordinates) != 2:\n",
524
+ "# print(f\"Coordinates is not a tuple of two tuples\")\n",
525
+ "# return False\n",
526
+ " \n",
527
+ "# (top, left), (bottom, right) = coordinates\n",
528
+ " \n",
529
+ "# # Check if all coordinates are integers\n",
530
+ "# if not all(isinstance(coord, (int, np.integer)) for coord in [top, left, bottom, right]):\n",
531
+ "# print(f\"Coordinates are not integers\")\n",
532
+ "# return False\n",
533
+ " \n",
534
+ "# # Check if coordinates are within image bounds\n",
535
+ "# # For slicing mask[top:bottom, left:right], valid ranges are:\n",
536
+ "# # top, left: [0, 223] (inclusive)\n",
537
+ "# # bottom, right: [1, 224] (inclusive) since we need top < bottom and left < right\n",
538
+ "# if not (0 <= top < 224 and 0 <= left < 224 and 1 <= bottom <= 224 and 1 <= right <= 224):\n",
539
+ "# print(f\"Coordinates are not within image bounds\")\n",
540
+ "# return False\n",
541
+ " \n",
542
+ "# # Check if top-left is actually top-left of bottom-right (proper ordering)\n",
543
+ "# if not (top < bottom and left < right):\n",
544
+ "# print(f\"Top-left is not actually top-left of bottom-right\")\n",
545
+ "# return False\n",
546
+ " \n",
547
+ "# # Check that the crop area doesn't exceed RETAIN_RATIO\n",
548
+ "# crop_area = (bottom - top) * (right - left)\n",
549
+ "# max_area = RETAIN_RATIO * 224 * 224\n",
550
+ "# if crop_area > max_area:\n",
551
+ "# print(f\"Crop area {crop_area} exceeds max area {max_area}\")\n",
552
+ "# return False\n",
553
+ " \n",
554
+ "# return True\n",
555
+ "# except Exception:\n",
556
+ "# return False\n",
557
+ "\n",
558
+ "\n",
559
+ "\n",
560
+ "\n",
561
+ "# def validate_masks(masks):\n",
562
+ "# \"\"\"Simple validation of generated masks on the dataset\"\"\"\n",
563
+ "# correct = 0\n",
564
+ "# total = 0\n",
565
+ "\n",
566
+ "# labels = sorted(list(set(dataset['name']))) + ['other']\n",
567
+ "# text_inputs = processor(text=labels, return_tensors=\"pt\", padding=True).to(DEVICE)\n",
568
+ "\n",
569
+ "# with torch.no_grad():\n",
570
+ "# for item in tqdm(dataset, desc=\"Validating masks\"):\n",
571
+ "# idx = item['idx']\n",
572
+ "# if idx not in masks:\n",
573
+ "# continue\n",
574
+ "\n",
575
+ "# if not check_validity(masks[idx]):\n",
576
+ "# continue\n",
577
+ " \n",
578
+ "# mask_coordinates = masks[idx]\n",
579
+ "# image = item['image']\n",
580
+ "# true_label = item['name']\n",
581
+ " \n",
582
+ "# # Apply mask to image\n",
583
+ "# if image.mode != \"RGB\":\n",
584
+ "# image = image.convert(\"RGB\")\n",
585
+ " \n",
586
+ "# mask = generate_mask_from_coordinates(image, mask_coordinates)\n",
587
+ "\n",
588
+ "# # Apply mask with mean color replacement\n",
589
+ "# img_array = np.array(image).copy()\n",
590
+ "# mask_array = mask > 0\n",
591
+ "# mask_3d = np.stack([mask_array] * 3, axis=2)\n",
592
+ "# mean_values = np.array([0, 0, 0]) # Black mean color\n",
593
+ "# img_array = np.where(mask_3d, img_array, mean_values.reshape(1, 1, 3))\n",
594
+ "# masked_image = Image.fromarray(img_array.astype(np.uint8))\n",
595
+ " \n",
596
+ "# # Get prediction on masked image\n",
597
+ "# image_processed = processor(images=masked_image, return_tensors=\"pt\").to(DEVICE)\n",
598
+ "# pixel_values = image_processed['pixel_values']\n",
599
+ "# outputs = model(pixel_values=pixel_values, **text_inputs)\n",
600
+ "# logits = outputs.logits_per_image\n",
601
+ "# predicted_idx = logits.argmax(dim=-1).item()\n",
602
+ "# predicted_label = labels[predicted_idx]\n",
603
+ " \n",
604
+ "# # Check if prediction is correct\n",
605
+ "# if predicted_label == true_label:\n",
606
+ "# correct += 1\n",
607
+ "# total += 1\n",
608
+ " \n",
609
+ "# accuracy = correct / total if total > 0 else 0\n",
610
+ "# print(f\"Validation Results:\")\n",
611
+ "# print(f\"Total samples: {total}\")\n",
612
+ "# print(f\"Correct predictions: {correct}\")\n",
613
+ "# print(f\"Accuracy: {accuracy:.4f} ({accuracy*100:.2f}%)\")\n",
614
+ " \n",
615
+ "# return accuracy\n",
616
+ "\n",
617
+ "# # Run validation\n",
618
+ "# accuracy = validate_masks(masks)\n"
619
+ ]
620
+ }
621
+ ],
622
+ "metadata": {
623
+ "kernelspec": {
624
+ "display_name": "Python 3 (ipykernel)",
625
+ "language": "python",
626
+ "name": "python3"
627
+ },
628
+ "language_info": {
629
+ "codemirror_mode": {
630
+ "name": "ipython",
631
+ "version": 3
632
+ },
633
+ "file_extension": ".py",
634
+ "mimetype": "text/x-python",
635
+ "name": "python",
636
+ "nbconvert_exporter": "python",
637
+ "pygments_lexer": "ipython3",
638
+ "version": "3.12.9"
639
+ }
640
+ },
641
+ "nbformat": 4,
642
+ "nbformat_minor": 5
643
+ }
benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Radar.ipynb ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
8
+ "\n",
9
+ "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
10
+ "\n",
11
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Radar/Radar.ipynb)"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "markdown",
16
+ "metadata": {},
17
+ "source": [
18
+ "# Radar\n",
19
+ "\n",
20
+ "## 1. Problem Description \n",
21
+ "\n",
22
+ "Radar is a key technology in wireless communication, with widespread applications such as self-driving cars. It typically involves an antenna that transmits specific signals and receives their reflections from objects in the environment. By processing these signals, the system determines the angular direction, distance, and velocity of target objects.\n",
23
+ "\n",
24
+ "In real-world applications, radar signal processing is challenging due to noise and reflections from non-target objects in the surroundings. For example, when attempting to detect pedestrians, the radar may also receive reflections from trees or other background objects, which can degrade accuracy. Your task is to use AI to analyze the signals received by the radar and identify the presence of a human at each position.\n",
25
+ "\n",
26
+ "In this task, we provide an **indoor radar experiment dataset**, and your objective is to develop a model that performs **radar semantic segmentation**. \n",
27
+ "\n",
28
+ "\n",
29
+ "## 2. Dataset\n",
30
+ "\n",
31
+ "To measure objects surrounding a radar, the following key parameters are used:\n",
32
+ "\n",
33
+ "- **Range**: The straight-line distance between the radar and an object.\n",
34
+ "- **Azimuth**: The horizontal angle (left to right) between the radar and the object.\n",
35
+ "- **Elevation**: The vertical angle (up or down) of the object relative to the radar.\n",
36
+ "- **Velocity**: The speed at which the object is moving toward or away from the radar.\n",
37
+ "\n",
38
+ "<img src=\"./figs/Radar Fig 1.png\" width=\"300\">\n",
39
+ "\n",
40
+ "\n",
41
+ "The radar data is processed into multiple **heatmaps**, each encoding the **received signal strength** at various positions and directions.\n",
42
+ "\n",
43
+ "- **Static heatmaps** emphasize reflections from **stationary** objects.\n",
44
+ "- **Dynamic heatmaps** highlight changes caused by **moving** objects.\n",
45
+ "\n",
46
+ "When no object is present at a specific location, the signal consists mostly of background noise and appears weak. In contrast, reflections from an object increase signal intensity, enabling detection of the object.\n",
47
+ "\n",
48
+ "For example, the **static range-azimuth heatmap** represents signal strength across different distances (**range**) and horizontal angles (**azimuth**), mainly reflected by stationary objects.\n",
49
+ "\n",
50
+ "Each sample in the dataset is stored in a `.mat.pt` file as a tensor of shape $7 \\times 50 \\times 181$, where:\n",
51
+ "\n",
52
+ "- 7 is the number of maps (6 heatmaps + 1 semantic label map),\n",
53
+ "- 50 represents range bins (distance),\n",
54
+ "- 181 represents angular or velocity bins, covering angles from \\-90° to \\+90° in either the horizontal or vertical plane. You can assume that the velocity bins are also remapped from \\-90° to \\+90° for visualization consistency.\n",
55
+ "- each heatmap intensity value is normalized to [0, 1], representing received signal strength.\n",
56
+ "\n",
57
+ "The 6 heatmaps are structured as follows:\n",
58
+ "\n",
59
+ "- **Index 0**: Static range-azimuth heatmap\n",
60
+ "- **Index 1**: Dynamic range-azimuth heatmap\n",
61
+ "- **Index 2**: Static range-elevation heatmap\n",
62
+ "- **Index 3**: Dynamic range-elevation heatmap\n",
63
+ "- **Index 4**: Static range-velocity heatmap\n",
64
+ "- **Index 5**: Dynamic range-velocity heatmap\n",
65
+ "\n",
66
+ "All values in heatmaps are **normalized**, so no unit conversion is required.\n",
67
+ "\n",
68
+ "The **map at Index 6** is the semantic label map, stored in range-azimuth format. \n",
69
+ "\n",
70
+ "- **-1**: Background (no target)\n",
71
+ "- **0**: Suitcase\n",
72
+ "- **1**: Chair\n",
73
+ "- **2**: Human\n",
74
+ "- **3**: Wall\n",
75
+ "\n",
76
+ "This is the visualization of 1.mat.pt in training_set:\n",
77
+ "\n",
78
+ "<img src=\"./figs/Radar Fig 2.png\" width=\"675\">\n",
79
+ "\n",
80
+ "Here is part of a sample from the dataset:\n",
81
+ "\n",
82
+ "<img src=\"./figs/Radar Fig 3.png\" width=\"675\">\n",
83
+ "\n",
84
+ "\n",
85
+ "Data scale: 1800 samples in the training set, 500 samples in the validation set, and 500 samples in the test set.\n",
86
+ "\n",
87
+ "## 3\\. Task\n",
88
+ "\n",
89
+ "Your task is to develop a model that takes the **first six heatmaps** (indices 0 to 5) as input, and predicts the **semantic label map** (index 6) as the output. The goal is to accurately identify what the target is(-1 to 3) at each location in the radar’s field of view.\n",
90
+ "\n",
91
+ "1. **Input**: A tensor of shape $6 \\times 50 \\times 181$, representing six radar heatmaps.\n",
92
+ "2. **Output**: A tensor of shape $50 \\times 181$, representing the target semantic label map.\n",
93
+ "\n",
94
+ "\n",
95
+ "## 4\\. Submission \n",
96
+ "\n",
97
+ "Please submit a file named `submission.ipynb`. The output is a zip file named \"submission.zip\", which contains two tables `submission_val.csv` and `submission_test.csv` corresponding to the prediction results of the validation set and the test set respectively.\n",
98
+ "\n",
99
+ "**Note:** The output table should have a header, the data in the table is not the actual solved data, it is only used as an example of the submission format.\n",
100
+ "\n",
101
+ "| filename | pixel_0 | pixel_1 | ... | pixel_9049 |\n",
102
+ "| :------: | :-----: | ------- | --- | ---------- |\n",
103
+ "| 1.mat.pt | -1 | -1 | ... | -1 |\n",
104
+ "| ... | ... | ... | ... | ... |\n",
105
+ "\n",
106
+ "## 5\\. Score\n",
107
+ "\n",
108
+ "The score is based on the **accuracy of label recognition**. Correctly identifying target points is weighted more heavily than correctly identifying background points. \n",
109
+ "\n",
110
+ "### Scoring Criteria: \n",
111
+ "\n",
112
+ "* Each correctly identified **background pixel** earns **1 point**. \n",
113
+ "\n",
114
+ "* Each correctly identified **non-background pixel** earns **50 points**. \n",
115
+ "\n",
116
+ "* The final score is normalized to a **0-1 point** by comparing it to the maximum possible score. \n",
117
+ "\n",
118
+ "### Formula:\n",
119
+ "$$\n",
120
+ "Score = \\frac{|C_{0,correct}| \\times 1 + |C_{1,correct}| \\times bonus}{|C_0| \\times 1 + |C_1| \\times bonus}\n",
121
+ "$$\n",
122
+ "where:\n",
123
+ "\n",
124
+ "$$\n",
125
+ "\\begin{aligned}\n",
126
+ "I &= \\{1, 2, \\dots, 50\\times 181\\}\\\\\n",
127
+ "C_0 &= \\{i \\in I \\mid y_i = -1\\}\\\\\n",
128
+ "C_1 &= \\{i \\in I \\mid y_i \\neq -1\\}\\\\\n",
129
+ "C_{0,correct} &= \\{i \\in C_0 \\mid p_i = y_i\\}\\\\\n",
130
+ "C_{1,correct} &= \\{i \\in C_1 \\mid p_i = y_i\\}\\\\\n",
131
+ "\\end{aligned}\n",
132
+ "$$\n",
133
+ "\n",
134
+ "\n",
135
+ "### Example\n",
136
+ "\n",
137
+ "For a $3\\times3$ heatmap, assume the Ground Truth is:\n",
138
+ "\n",
139
+ "$$\n",
140
+ "\\begin{bmatrix}\n",
141
+ "-1 & -1 & -1 \\\\\n",
142
+ "1 & 2 & 3 \\\\\n",
143
+ "-1 & -1 & -1\n",
144
+ "\\end{bmatrix}\n",
145
+ "$$\n",
146
+ "\n",
147
+ "The intenteded result is:\n",
148
+ "\n",
149
+ "$$\n",
150
+ "\\begin{bmatrix}\n",
151
+ "-1 & 1 & -1 \\\\\n",
152
+ "-1 & 2 & -1 \\\\\n",
153
+ "-1 & 3 & -1\n",
154
+ "\\end{bmatrix}\n",
155
+ "$$\n",
156
+ "\n",
157
+ "Then there are four correctly identified `-1` and one correctly identified `2`. Your score is 4 + 50 = 54 points. The maximum possible score is 6 + 50 * 3 = 156, that is, the score for six background pixels and three non-background pixels. Your normalized score is 54 / 156 = 0.346.\n",
158
+ "\n",
159
+ "$$\n",
160
+ "Score = \\frac{4 \\times 1 + 1 \\times 50}{6 \\times 1 + 3 \\times 50}=0.346\n",
161
+ "$$\n",
162
+ "\n",
163
+ "## 6. Baseline and Training Set\n",
164
+ "\n",
165
+ "- Below you can find the baseline solution.\n",
166
+ "- The dataset is in `training_set` folder.\n",
167
+ "- The highest score by the Scientific Committee for this task is 0.90 in Leaderboard B, this score is used for score unification.\n",
168
+ "- The baseline score by the Scientific Committee for this task is 0.67 in Leaderboard B, this score is used for score unification."
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "markdown",
173
+ "metadata": {},
174
+ "source": [
175
+ "### Data Loading"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": null,
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": [
184
+ "import random\n",
185
+ "import numpy as np\n",
186
+ "import torch\n",
187
+ "\n",
188
+ "seed = 42\n",
189
+ "\n",
190
+ "random.seed(seed) # Python built-in random\n",
191
+ "np.random.seed(seed) # NumPy\n",
192
+ "torch.manual_seed(seed) # PyTorch (CPU)\n",
193
+ "torch.cuda.manual_seed(seed) # PyTorch (single GPU)\n",
194
+ "torch.cuda.manual_seed_all(seed) # PyTorch (all GPUs)\n",
195
+ "\n",
196
+ "# Ensures deterministic behavior\n",
197
+ "torch.backends.cudnn.deterministic = True\n",
198
+ "torch.backends.cudnn.benchmark = False"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "execution_count": null,
204
+ "metadata": {},
205
+ "outputs": [],
206
+ "source": [
207
+ "import os\n",
208
+ "import torch\n",
209
+ "from torch.utils.data import Dataset, DataLoader\n",
210
+ "from sklearn.model_selection import train_test_split\n",
211
+ "\n",
212
+ "class CustomDataset(Dataset):\n",
213
+ " def __init__(self, file_paths, transform=None):\n",
214
+ " self.file_paths = file_paths\n",
215
+ " self.transform = transform\n",
216
+ " self.file_names = [os.path.basename(path) for path in file_paths]\n",
217
+ "\n",
218
+ " def __len__(self):\n",
219
+ " return len(self.file_paths)\n",
220
+ "\n",
221
+ " def __getitem__(self, idx):\n",
222
+ " data = torch.load(self.file_paths[idx], weights_only=True)\n",
223
+ " \n",
224
+ " images = data[:6] \n",
225
+ " labels = data[6] \n",
226
+ " \n",
227
+ " images = images.float() \n",
228
+ " labels = labels.long() \n",
229
+ " labels = labels + 1\n",
230
+ "\n",
231
+ " if self.transform:\n",
232
+ " images = self.transform(images)\n",
233
+ " labels = self.transform(labels)\n",
234
+ " \n",
235
+ " return images, labels, self.file_names[idx]\n",
236
+ "\n",
237
+ "class CustomDataset_test(Dataset):\n",
238
+ " def __init__(self, file_paths, transform=None):\n",
239
+ " self.file_paths = file_paths\n",
240
+ " self.transform = transform\n",
241
+ " self.file_names = [os.path.basename(path) for path in file_paths]\n",
242
+ "\n",
243
+ " def __len__(self):\n",
244
+ " return len(self.file_paths)\n",
245
+ "\n",
246
+ " def __getitem__(self, idx):\n",
247
+ " data = torch.load(self.file_paths[idx], weights_only=True)\n",
248
+ " \n",
249
+ " images = data[:6] \n",
250
+ " \n",
251
+ " images = images.float() \n",
252
+ "\n",
253
+ " if self.transform:\n",
254
+ " images = self.transform(images)\n",
255
+ " \n",
256
+ " return images, self.file_names[idx]\n",
257
+ "\n",
258
+ "def generate_file_paths(base_path):\n",
259
+ " file_paths = []\n",
260
+ " for frame in os.listdir(base_path):\n",
261
+ " frame_path = os.path.join(base_path, frame)\n",
262
+ " if frame_path.endswith('.mat.pt'):\n",
263
+ " file_paths.append(frame_path)\n",
264
+ " return [path for path in file_paths if os.path.exists(path)]\n",
265
+ "\n",
266
+ "def load_data(base_path, batch_size=4, num_workers=2, test_size=0.2):\n",
267
+ " file_paths = generate_file_paths(base_path)\n",
268
+ " \n",
269
+ " train_paths, test_paths = train_test_split(file_paths, test_size=test_size, random_state=42)\n",
270
+ " \n",
271
+ " train_dataset = CustomDataset(file_paths=train_paths)\n",
272
+ " test_dataset = CustomDataset(file_paths=test_paths)\n",
273
+ " \n",
274
+ " train_loader = DataLoader(\n",
275
+ " train_dataset, \n",
276
+ " batch_size=batch_size, \n",
277
+ " shuffle=True, \n",
278
+ " num_workers=num_workers, \n",
279
+ " drop_last=True\n",
280
+ " )\n",
281
+ " \n",
282
+ " test_loader = DataLoader(\n",
283
+ " test_dataset, \n",
284
+ " batch_size=batch_size, \n",
285
+ " shuffle=False, \n",
286
+ " num_workers=num_workers, \n",
287
+ " drop_last=True\n",
288
+ " )\n",
289
+ " \n",
290
+ " return train_loader, test_loader"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "metadata": {},
296
+ "source": [
297
+ "### Model Definition and Training"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": null,
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "import torch\n",
307
+ "import torch.nn as nn\n",
308
+ "import torch.optim as optim\n",
309
+ "\n",
310
+ "class MyModel(nn.Module):\n",
311
+ " def __init__(self):\n",
312
+ " super(MyModel, self).__init__()\n",
313
+ " self.conv1 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3, padding=1) \n",
314
+ " self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1) \n",
315
+ " self.conv3 = nn.Conv2d(in_channels=32, out_channels=5, kernel_size=3, padding=1)\n",
316
+ "\n",
317
+ " self.relu = nn.ReLU()\n",
318
+ "\n",
319
+ " def forward(self, x):\n",
320
+ " x = self.relu(self.conv1(x))\n",
321
+ " x = self.relu(self.conv2(x))\n",
322
+ " x = self.conv3(x) \n",
323
+ " return x\n",
324
+ "\n",
325
+ "def train(model, train_loader, test_loader, optimizer, criterion, num_epochs=100):\n",
326
+ " train_losses = []\n",
327
+ " val_losses = []\n",
328
+ " \n",
329
+ " for epoch in range(num_epochs):\n",
330
+ " model.train()\n",
331
+ " epoch_loss = 0.0\n",
332
+ " batch_count = 0\n",
333
+ " \n",
334
+ " for images, labels, _ in train_loader:\n",
335
+ " images = images.cuda() if torch.cuda.is_available() else images\n",
336
+ " labels = labels.cuda() if torch.cuda.is_available() else labels\n",
337
+ " \n",
338
+ " outputs = model(images)\n",
339
+ " outputs = outputs.view(outputs.size(0), outputs.size(1), -1) # [B, C, H*W]\n",
340
+ " labels = labels.view(labels.size(0), -1) # [B, H*W]\n",
341
+ " loss = criterion(outputs, labels)\n",
342
+ " \n",
343
+ " optimizer.zero_grad()\n",
344
+ " loss.backward()\n",
345
+ " optimizer.step()\n",
346
+ " \n",
347
+ " epoch_loss += loss.item()\n",
348
+ " batch_count += 1\n",
349
+ " \n",
350
+ " avg_train_loss = epoch_loss / batch_count\n",
351
+ " train_losses.append(avg_train_loss)\n",
352
+ " \n",
353
+ " model.eval()\n",
354
+ " val_loss = 0.0\n",
355
+ " val_batch_count = 0\n",
356
+ " \n",
357
+ " with torch.no_grad():\n",
358
+ " for images, labels, _ in test_loader:\n",
359
+ " images = images.cuda() if torch.cuda.is_available() else images\n",
360
+ " labels = labels.cuda() if torch.cuda.is_available() else labels\n",
361
+ " \n",
362
+ " outputs = model(images)\n",
363
+ " outputs = outputs.view(outputs.size(0), outputs.size(1), -1)\n",
364
+ " labels = labels.view(labels.size(0), -1)\n",
365
+ " loss = criterion(outputs, labels)\n",
366
+ " \n",
367
+ " val_loss += loss.item()\n",
368
+ " val_batch_count += 1\n",
369
+ " \n",
370
+ " avg_val_loss = val_loss / val_batch_count\n",
371
+ " val_losses.append(avg_val_loss)\n",
372
+ " \n",
373
+ " if (epoch+1) % 2 == 0:\n",
374
+ " print(f'Epoch [{epoch+1}/{num_epochs}], '\n",
375
+ " f'Train Loss: {avg_train_loss:.4f}, '\n",
376
+ " f'Val Loss: {avg_val_loss:.4f}')\n",
377
+ " \n",
378
+ " return train_losses, val_losses\n",
379
+ "TRAIN_PATH = \"./\"\n",
380
+ "# The training set is deployed automatically in the testing machine. \n",
381
+ "# You notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n",
382
+ "data_path = TRAIN_PATH + 'training_set'\n",
383
+ "\n",
384
+ "train_loader, test_loader = load_data(\n",
385
+ " base_path=data_path,\n",
386
+ " batch_size=4, \n",
387
+ " num_workers=2,\n",
388
+ " test_size=0.2\n",
389
+ ")\n",
390
+ "\n",
391
+ "model = MyModel()\n",
392
+ "if torch.cuda.is_available():\n",
393
+ " model = model.cuda()\n",
394
+ "\n",
395
+ "criterion = nn.CrossEntropyLoss()\n",
396
+ "optimizer = optim.Adam(model.parameters(), lr=0.001) \n",
397
+ "\n",
398
+ "train_losses, val_losses = train(\n",
399
+ " model=model,\n",
400
+ " train_loader=train_loader,\n",
401
+ " test_loader=test_loader,\n",
402
+ " optimizer=optimizer,\n",
403
+ " criterion=criterion,\n",
404
+ " num_epochs=40\n",
405
+ ")"
406
+ ]
407
+ },
408
+ {
409
+ "cell_type": "markdown",
410
+ "metadata": {},
411
+ "source": [
412
+ "### Generate CSV for Submission"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": null,
418
+ "metadata": {},
419
+ "outputs": [],
420
+ "source": [
421
+ "# Run inference on validation set and testing set\n",
422
+ "from torch.utils.data import DataLoader\n",
423
+ "import pandas as pd\n",
424
+ "\n",
425
+ "def run_inference(model, data_loader):\n",
426
+ " \"\"\"Run inference and return predictions with filenames\"\"\"\n",
427
+ " model.eval()\n",
428
+ " predictions = []\n",
429
+ " filenames = []\n",
430
+ " \n",
431
+ " with torch.no_grad():\n",
432
+ " for images, file_names in data_loader:\n",
433
+ " images = images.cuda() if torch.cuda.is_available() else images\n",
434
+ " \n",
435
+ " outputs = model(images)\n",
436
+ " preds = torch.argmax(outputs, dim=1)\n",
437
+ " \n",
438
+ " # Convert predictions back to original label range [-1, 3]\n",
439
+ " preds = preds - 1\n",
440
+ " \n",
441
+ " # Flatten predictions for each sample\n",
442
+ " for i, pred in enumerate(preds):\n",
443
+ " predictions.append(pred.cpu().numpy().flatten())\n",
444
+ " filenames.append(file_names[i])\n",
445
+ " \n",
446
+ " return predictions, filenames\n",
447
+ "\n",
448
+ "#DATA_PATH is the secret environment variable to point the address of the validation set and test set on the testing machine. \n",
449
+ "#You cannot access this address locally.\n",
450
+ "if os.environ.get('DATA_PATH'):\n",
451
+ " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
452
+ "else:\n",
453
+ " DATA_PATH = \"\" # Fallback for local testing\n",
454
+ "# Load validation set\n",
455
+ "val_paths = generate_file_paths(DATA_PATH + 'validation_set')\n",
456
+ "val_dataset = CustomDataset_test(file_paths=val_paths)\n",
457
+ "val_loader = DataLoader(\n",
458
+ " val_dataset,\n",
459
+ " batch_size=1,\n",
460
+ " shuffle=False,\n",
461
+ " num_workers=2\n",
462
+ ")\n",
463
+ "\n",
464
+ "# Load testing set\n",
465
+ "test_paths = generate_file_paths(DATA_PATH + 'testing_set')\n",
466
+ "test_dataset = CustomDataset_test(file_paths=test_paths)\n",
467
+ "test_loader = DataLoader(\n",
468
+ " test_dataset,\n",
469
+ " batch_size=1,\n",
470
+ " shuffle=False,\n",
471
+ " num_workers=2\n",
472
+ ")\n",
473
+ "\n",
474
+ "# Run inference on validation set\n",
475
+ "print(\"Running inference on validation set...\")\n",
476
+ "val_predictions, val_filenames = run_inference(model, val_loader)\n",
477
+ "\n",
478
+ "# Save validation results to CSV\n",
479
+ "val_results = []\n",
480
+ "for filename, pred in zip(val_filenames, val_predictions):\n",
481
+ " # Create a row with filename and flattened predictions\n",
482
+ " row = {'filename': filename}\n",
483
+ " for i, p in enumerate(pred):\n",
484
+ " row[f'pixel_{i}'] = p\n",
485
+ " val_results.append(row)\n",
486
+ "\n",
487
+ "val_df = pd.DataFrame(val_results)\n",
488
+ "val_df.to_csv('submission_val.csv', index=False)\n",
489
+ "print(f\"Validation results saved to output_validation.csv with shape: {val_df.shape}\")\n",
490
+ "\n",
491
+ "# Run inference on testing set\n",
492
+ "print(\"Running inference on testing set...\")\n",
493
+ "test_predictions, test_filenames = run_inference(model, test_loader)\n",
494
+ "\n",
495
+ "# Save testing results to CSV\n",
496
+ "test_results = []\n",
497
+ "for filename, pred in zip(test_filenames, test_predictions):\n",
498
+ " # Create a row with filename and flattened predictions\n",
499
+ " row = {'filename': filename}\n",
500
+ " for i, p in enumerate(pred):\n",
501
+ " row[f'pixel_{i}'] = p\n",
502
+ " test_results.append(row)\n",
503
+ "\n",
504
+ "test_df = pd.DataFrame(test_results)\n",
505
+ "test_df.to_csv('submission_test.csv', index=False)\n",
506
+ "print(f\"Testing results saved to output_testing.csv with shape: {test_df.shape}\")\n",
507
+ "\n",
508
+ "print(\"\\nInference completed! Results saved to:\")\n",
509
+ "print(\"- submission_val.csv (for validation set leaderboard)\")\n",
510
+ "print(\"- submission_test.csv (for testing set leaderboard)\")"
511
+ ]
512
+ },
513
+ {
514
+ "cell_type": "markdown",
515
+ "metadata": {},
516
+ "source": [
517
+ "### Create .zip File"
518
+ ]
519
+ },
520
+ {
521
+ "cell_type": "code",
522
+ "execution_count": null,
523
+ "metadata": {},
524
+ "outputs": [],
525
+ "source": [
526
+ "import zipfile\n",
527
+ "import os\n",
528
+ "\n",
529
+ "# Define the files to zip and the zip file name.\n",
530
+ "files_to_zip = ['submission_val.csv', 'submission_test.csv']\n",
531
+ "zip_filename = 'submission.zip'\n",
532
+ "\n",
533
+ "# Create a zip file\n",
534
+ "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
535
+ " for file in files_to_zip:\n",
536
+ " # Add the file to the zip fil\n",
537
+ " zipf.write(file, os.path.basename(file))\n",
538
+ "\n",
539
+ "print(f'{zip_filename} Created successfully!')"
540
+ ]
541
+ }
542
+ ],
543
+ "metadata": {
544
+ "kernelspec": {
545
+ "display_name": "Python 3 (ipykernel)",
546
+ "language": "python",
547
+ "name": "python3"
548
+ },
549
+ "language_info": {
550
+ "codemirror_mode": {
551
+ "name": "ipython",
552
+ "version": 3
553
+ },
554
+ "file_extension": ".py",
555
+ "mimetype": "text/x-python",
556
+ "name": "python",
557
+ "nbconvert_exporter": "python",
558
+ "pygments_lexer": "ipython3",
559
+ "version": "3.12.9"
560
+ }
561
+ },
562
+ "nbformat": 4,
563
+ "nbformat_minor": 4
564
+ }
benchmark/IOL/ioling_hf/reports/answer_given_rationale/Qwen_Qwen3-4B-Instruct-2507__v14_hakhun_manual_derivation_n4.md ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Answer-Given Rationale Probe
2
+
3
+ - generated: `2026-07-12T02:14:37.885128+00:00`
4
+ - model: `Qwen/Qwen3-4B-Instruct-2507`
5
+ - data: `data/rl/ioling_qwen3_4b_manual_v14_expanded_clean`
6
+ - samples: `40` across `10` records
7
+ - exact final-box samples: `1.000`
8
+ - valid final-box samples: `1.000`
9
+ - truncation rate: `0.000`
10
+ - mean rationale chars: `994.9`
11
+
12
+ ## Per Record
13
+
14
+ | record | samples | exact boxes | valid boxes | best score | mean rationale chars |
15
+ | --- | ---: | ---: | ---: | ---: | ---: |
16
+ | iol-2018-individual-p2-sub-a-atomic-a.1 | 4 | 4 | 4 | 1.000 | 1140.2 |
17
+ | iol-2018-individual-p2-sub-a-atomic-a.2 | 4 | 4 | 4 | 1.000 | 1143.8 |
18
+ | iol-2018-individual-p2-sub-a-atomic-a.3 | 4 | 4 | 4 | 1.000 | 1078.5 |
19
+ | iol-2018-individual-p2-sub-a-atomic-a.4 | 4 | 4 | 4 | 1.000 | 914.0 |
20
+ | iol-2018-individual-p2-sub-a-atomic-a.5 | 4 | 4 | 4 | 1.000 | 921.2 |
21
+ | iol-2018-individual-p2-sub-a-atomic-a.6 | 4 | 4 | 4 | 1.000 | 921.0 |
22
+ | iol-2018-individual-p2-sub-b-atomic-b.1 | 4 | 4 | 4 | 1.000 | 757.8 |
23
+ | iol-2018-individual-p2-sub-b-atomic-b.2 | 4 | 4 | 4 | 1.000 | 1031.2 |
24
+ | iol-2018-individual-p2-sub-b-atomic-b.3 | 4 | 4 | 4 | 1.000 | 959.0 |
25
+ | iol-2018-individual-p2-sub-b-atomic-b.4 | 4 | 4 | 4 | 1.000 | 1081.8 |
26
+
27
+ ## Sample Outputs
28
+
29
+ ### `iol-2018-individual-p2-sub-a-atomic-a.1` sample `0`
30
+
31
+ - score: `1.0`
32
+ - exact: `1.0`
33
+ - final box valid: `True`
34
+
35
+ ```text
36
+ - "nɤ" is second-person singular, requiring the present-tense suffix -u in place of past -ʔ, as shown in example 2 where "nɤ ʒip tuʔ ne" uses past tense with t-...-ʔ.
37
+ - "ʒip" means "sleep", as confirmed in example 2: "nɤ ʒip tuʔ ne — Did you(sg) sleep?" with past tense.
38
+ - In present tense, second-person singular uses -u, as in example 5: "nɤbə ati cʰam tuʔ ne" uses past tense with -ʔ, contrasting with present "nɤ ʒip ku ne" where -u appears.
39
+ - The suffix -u marks second-person singular present tense, as shown in example 3: "ŋabə ati lapkʰi tɤʔ ne" (past) vs. logic of present formation.
40
+ - Example 10: "ati kəmə ŋa lapkʰi tʰɤ ne" uses tʰ- for present tense with third-person object, showing tense and agreement segmentation.
41
+ - The structure "nɤ ʒip ku ne" matches known present-tense second-person singular form with "sleep" and present agreement -u, as no subject-object hierarchy reversal occurs.
42
+
43
+ \boxed{a.1: Do you(sg) sleep?}
44
+ ```
45
+
46
+ ### `iol-2018-individual-p2-sub-a-atomic-a.1` sample `1`
47
+
48
+ - score: `1.0`
49
+ - exact: `1.0`
50
+ - final box valid: `True`
51
+
52
+ ```text
53
+ - In sentence 2, "nɤ ʒip tuʔ ne" translates to "Did you(sg) sleep?", showing that ʒip with second-person singular subject takes past tense form tuʔ, indicating that present tense uses k- and past uses t- or tʰ- depending on person hierarchy.
54
+ - Sentence 5, "nɤbə ŋa lapkʰi rɤ ne", shows first-person singular subject with -bə, and past tense predicate with rɤ, confirming that second-person singular has -u suffix in present and -u or -an in agreement when relevant.
55
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", uses third-person subject ati with present tense tʰɤ, aligning with the rule that if the object outranks the subject, present tense uses r- or tʰ-; here, the object ŋa is third and outranks the subject ati.
56
+ - Sentence 3, "ŋabə ati lapkʰi tɤʔ ne", has first-person singular subject with -bə and past tense predicate tɤʔ, indicating that present tense uses k- and past uses t- or tʰ- depending on person dominance.
57
+ - In sentence 6, "tarum kəmə nuʔrum cʰam ki ne", the present tense predicate ki appears with a third-person subject tarum, confirming that present tense forms use k- or kəmə with appropriate agreement.
58
+ - Sentence 1, "nɤ ʒip ku ne", matches the structure of sentence 2, where second-person singular subject nɤ with sleep verb ʒip uses present tense k- and suffix -u, resulting in ku.
59
+
60
+ \boxed{a.1: Do you(sg) sleep?}
61
+ ```
62
+
63
+ ### `iol-2018-individual-p2-sub-a-atomic-a.1` sample `2`
64
+
65
+ - score: `1.0`
66
+ - exact: `1.0`
67
+ - final box valid: `True`
68
+
69
+ ```text
70
+ - In sentence 2, "nɤ ʒip tuʔ ne" translates to "Did you(sg) sleep?", showing that ʒip with second-person singular subject uses past tense with tʰ- and present with k- depending on subject-object ranking.
71
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", uses third-person subject "he" and object "me", with past tense suffix tʰ- indicating object outranks subject.
72
+ - Sentence 1, "nɤ ʒip ku ne", has second-person subject with present tense verb "sleep"; second-person singular uses suffix -u, matching the pattern in sentence 2 where ʒip with second-person subject uses -u in present tense.
73
+ - In sentence 5, "nirum kəmə nɤ cʰam tiʔ ne", second-person singular subject with verb "know" uses -u suffix in present tense, confirming -u is used when subject is second-person singular and present tense is used.
74
+ - Sentence 8, "nɤbə ati cʰam tuʔ ne", shows first-person singular subject with "see" in past tense, where -bə is used with past tense verb showing subject outranks object.
75
+ - Sentence 10 uses "lapkʰi" (see) with third-person subject and object, resulting in tʰ- suffix, consistent with object outranking subject in past tense.
76
+
77
+ \boxed{a.1: Do you(sg) sleep?}
78
+ ```
79
+
80
+ ### `iol-2018-individual-p2-sub-a-atomic-a.1` sample `3`
81
+
82
+ - score: `1.0`
83
+ - exact: `1.0`
84
+ - final box valid: `True`
85
+
86
+ ```text
87
+ - In sentence 2, "nɤ ʒip tuʔ ne" translates to "Did you(sg) sleep?", showing that second-person singular with present tense sleep uses -u suffix derivation.
88
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", uses past tense with object outranking subject, yielding tʰ-; in contrast, sentence 3 uses present tense with k- and -u, confirming present tense applies to "sleep" with second-person subject.
89
+ - "nɤ" is second-person singular, and in sentence 2, it combines with "ʒip" in past tense to form "tuʔ", indicating that "ʒip" with second-person singular must take -u in present tense.
90
+ - In sentence 5, "nɤbə" is first-person singular with transitive verb, and uses -bə suffix; in contrast, "nɤ" without -bə remains second-person, supporting that -bə is only for first/second persons with transitive verbs in past tense.
91
+ - The present tense marker "k-" appears with second-person singular verb forms in sentence 2 and implied in sentence 1, confirming k- + -u = "ku" for present second-person speech.
92
+ - "ku" in "nɤ ʒip ku ne" matches the structure of "nɤ ʒip tuʔ ne" (past) with only the tense marker differing, confirming k- + -u is used for present tense with second-person subject and sleep.
93
+
94
+ \boxed{a.1: Do you(sg) sleep?}
95
+ ```
96
+
97
+ ### `iol-2018-individual-p2-sub-a-atomic-a.2` sample `0`
98
+
99
+ - score: `1.0`
100
+ - exact: `1.0`
101
+ - final box valid: `True`
102
+
103
+ ```text
104
+ - In sentence 3, "nuʔrum kəmə ati lapkʰi kan ne" uses tʰ- and -i, showing that when first-person plural (us) is the object and third-person (he) is the subject, past tense with first-person plural agreement applies.
105
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", has tʰ- and -ɤ, indicating third-person subject with first-person object, where object outranks subject, resulting in past tense with first-person singular agreement.
106
+ - Sentence 4, "nirum kəmə tarum lan ki ne", uses k- and -u, showing second-person subject with object outranking subject; the present tense surface form implies k- despite object rank.
107
+ - Sentence 2, "ati kəmə nirum lapkʰi tʰi ne", mirrors sentence 10 in structure: third-person subject (ati), first-person object (nirum), and past tense with -i, confirming object outranks subject and first-person plural agreement.
108
+ - Sentence 8, "tarum kəmə nuʔrum cʰam ran ne", shows past tense with tʰ- and -an, indicating second-person plural object outranks subject, which triggers tʰ- form in past, consistent with object ranking.
109
+ - The presence of tʰ- in past tense with first-person plural agreement (-i) in multiple examples confirms that object-ranking rules override subject personality in tense assignment.
110
+
111
+ \boxed{a.2: Did he see us?}
112
+ ```
113
+
114
+ ### `iol-2018-individual-p2-sub-a-atomic-a.2` sample `1`
115
+
116
+ - score: `1.0`
117
+ - exact: `1.0`
118
+ - final box valid: `True`
119
+
120
+ ```text
121
+ - In sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", the third-person subject "ati" and first-person object "ŋa" show past tense with tʰ- due to object outranking subject.
122
+ - Sentence 3, "ŋabə ati lapkʰi tɤʔ ne", uses -bə for first-person subject and t- agreement, indicating present tense with subject ranking over object.
123
+ - Sentence 8, "nɤbə ati cʰam tuʔ ne", employs -bə for first-person subject and -u agreement, matching subject-object ranking where object outranks subject in past.
124
+ - Sentence 5, "nirum kəmə nɤ cʰam tiʔ ne", features third-person object "nɤ" and second-person subject "nirum", requiring tʰ- due to object outranking subject in past.
125
+ - Sentence 6, "tarum kəmə nuʔrum cʰam ran ne", has plural subject "tarum" and object "nuʔrum", using tʰ- consistently when object outranks subject.
126
+ - Sentence 4, "nirum kəmə tarum lan ki ne", shows no agreement suffix change despite plural subject-object pair, confirming tʰ- only when object outranks subject in past tense.
127
+
128
+ \boxed{a.2: Did he see us?}
129
+ ```
130
+
131
+ ### `iol-2018-individual-p2-sub-a-atomic-a.2` sample `2`
132
+
133
+ - score: `1.0`
134
+ - exact: `1.0`
135
+ - final box valid: `True`
136
+
137
+ ```text
138
+ - In sentence 10, 'ati kəmə ŋa lapkʰi tʰɤ ne', the third-person subject 'ati' outranks the first-person object 'ŋa', triggering past tense with tʰ- and first-person-plural agreement -i, matching the structure of sentence 3.
139
+ - Sentence 3, 'ŋabə ati lapkʰi tɤʔ ne', uses first-person subject with -bə and past tense -tɤʔ, indicating subject-first with subject ranking above object, confirmed by the use of t- before agreement.
140
+ - Sentence 5, 'nirum kəmə nɤ cʰam tiʔ ne', shows second-person plural subject 'nirum' with -u agreement, but the agreement is -an due to object outranking subject, showing inconsistency unless it's second-person plural with -an.
141
+ - In sentence 6, 'nuʔrum kəmə ati lapkʰi kan ne', 'ati' is third-person subject, 'nuʔrum' is second-person plural object, with past tense tʰ- and -an agreement, confirming object outranks subject.
142
+ - Sentence 4, 'nirum kəmə tarum lan ki ne', uses second-person plural subject with -an agreement, despite 'tarum' being third-person, indicating that agreement depends on object rank, not subject identity.
143
+ - Sentence 7, 'nirum kəmə nuʔrum cʰam ran ne', uses second-person plural subject and object 'nuʔrum' outranking it, triggering past tense tʰ- and -an agreement, confirming that object outranks subject in past tense.
144
+
145
+ \boxed{a.2: Did he see us?}
146
+ ```
147
+
148
+ ### `iol-2018-individual-p2-sub-a-atomic-a.2` sample `3`
149
+
150
+ - score: `1.0`
151
+ - exact: `1.0`
152
+ - final box valid: `True`
153
+
154
+ ```text
155
+ - In sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", the third-person subject "he" (ati) sees the first-person object "me" (ŋa), and the past tense marker tʰ- appears due to object outranking subject.
156
+ - Sentence 3 uses "ŋabə ati lapkʰi rɤ ne" for "Did I see him?", showing first-person subject (ŋa) with -bə, and past tense r- when object outranks subject.
157
+ - Sentence 8, "nɤbə ati cʰam tuʔ ne", employs "you(sg) know him", confirming that -bə marks first-person subject and -u applies to second-person object in past tense.
158
+ - Sentence 2, "ati kəmə nirum lapkʰi tʰi ne", parallels sentence 10 with "he" (ati) as subject and "us" (nirum) as object, showing past tense tʰ- due to object outranking subject.
159
+ - The agreement suffix -i occurs when first-person plural participates, as in "nirum kəmə ati lapkʰi kan ne" (Do you(pl) see him?), where "nirum" is first-person plural.
160
+ - In "ati kəmə nirum lapkʰi tʰi ne", "tʰi" is past tense with object outranking subject, matching "tʰɤ" in sentence 10, confirming consistency in tense marking based on subject-object hierarchy.
161
+
162
+ \boxed{a.2: Did he see us?}
163
+ ```
164
+
165
+ ### `iol-2018-individual-p2-sub-a-atomic-a.3` sample `0`
166
+
167
+ - score: `1.0`
168
+ - exact: `1.0`
169
+ - final box valid: `True`
170
+
171
+ ```text
172
+ - The subject "tarum" (they) is third-person plural, and the object "nuʔrum" (you-pl) is second-person plural, confirming object outranks subject, triggering present form with r-.
173
+ - The verb "cʰam" means "know", and its agreement with second-person plural object requires -an suffix, evidenced by "nuʔrum cʰam ran" matching "Do you(pl) know us?" in structure.
174
+ - In sentence 9, "tarum kəmə nirum lapkʰi ri ne" translates to "Do they see us?", showing third-person subject with object outranking, using present r- form with -an agreement.
175
+ - Sentence 4, "nirum kəmə tarum lan ki ne", shows second-person plural subject with third-person object, using r- due to object outranking, supporting present tense marking.
176
+ - Sentence 8, "nɤbə ati cʰam tuʔ ne" translates to "Did you(sg) know him?", showing singular object outranks subject, using past tense with tʰ- and -u agreement.
177
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne" uses past tense with tʰ- and object outranking, proving tense and agreement depend on relative person rank, not subject alone.
178
+
179
+ \boxed{a.3: Do they know you(pl)?}
180
+ ```
181
+
182
+ ### `iol-2018-individual-p2-sub-a-atomic-a.3` sample `1`
183
+
184
+ - score: `1.0`
185
+ - exact: `1.0`
186
+ - final box valid: `True`
187
+
188
+ ```text
189
+ - In sentence 3, "tarum kəmə nuʔrum cʰam ran ne", the object "nuʔrum" (you(pl)) outranks the subject "tarum" (they), triggering present tense with r- in "cʰam ran".
190
+ - The suffix "ran" matches the second-person plural agreement -an, confirming object precedence over subject in tense marking.
191
+ - Sentences 6 and 8 show that when object outranks subject, present tense uses r- (e.g., "cʰam ran" vs. "cʰam ki" in sentence 4).
192
+ - Sentence 4 contrasts "nirum kəmə tarum lan ki ne" (Do we know you(pl)?) with "tarum kəmə nuʔrum cʰam ran ne", showing object-ranking-induced present tense via r- and -an agreement.
193
+ - The verb "cʰam" (know) paired with "ran" in present tense confirms the rule that object outranking subject causes r- instead of tʰ- or k-.
194
+ - Sentence 8, "nɤbə ati cʰam tuʔ ne" (Did you(sg) know him?), uses tʰ- with object (him), indicating third-person object ranking, whereas "cʰam ran" in sentence 3 uses r- with second-person-plural object, confirming tense choice based on object rank.
195
+
196
+ \boxed{a.3: Do they know you(pl)?}
197
+ ```
198
+
199
+ ### `iol-2018-individual-p2-sub-a-atomic-a.3` sample `2`
200
+
201
+ - score: `1.0`
202
+ - exact: `1.0`
203
+ - final box valid: `True`
204
+
205
+ ```text
206
+ - In sentence 3, "tarum kəmə nuʔrum cʰam ran ne", "tarum" is third-person plural subject, and "nuʔrum" is second-person plural object, showing object outranks subject.
207
+ - The object outranks the subject, so present tense uses r- (as in "ran" instead of "tʰan"), confirming present tense marker r- in the predicate.
208
+ - "nuʔrum" uses -um with second-person plural, indicating agreement suffix -an, consistent with second-person plural object being second in hierarchy.
209
+ - The predicate "cʰam" means "know", and in sentence 4, "nirum kəmə tarum lan ki ne" uses "lan" (beat), showing "cʰam" is paired with "know" in Hakhun.
210
+ - In sentence 8, "nɤbə ati cʰam tuʔ ne" = "Did you(sg) know him?", showing cʰam with first-person singular subject and object outranking, triggering past tense tʰ-; thus, present tense with object outranking uses r-.
211
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", uses tʰɤ (past) due to object outranking subject, but in sentence 3, "ran" is present, indicating tense matches object precedence, not subject.
212
+
213
+ \boxed{a.3: Do they know you(pl)?}
214
+ ```
215
+
216
+ ### `iol-2018-individual-p2-sub-a-atomic-a.3` sample `3`
217
+
218
+ - score: `1.0`
219
+ - exact: `1.0`
220
+ - final box valid: `True`
221
+
222
+ ```text
223
+ - In sentence 3, "tarum kəmə nuʔrum cʰam ran ne", "tarum" is third-person plural subject, and "nuʔrum" is second-person plural object, confirming object outranks subject which triggers present tense marker r-.
224
+ - The presence of "cʰam" as the lexical verb "know" is confirmed by sentence 8: "nɤbə ati cʰam tuʔ ne" translates to "Did you(sg) know him?", showing consistent use of cʰam.
225
+ - Sentence 9, "tarum kəmə nirum lapkʰi ri ne", shows third-person plural subject with second-person plural object in "nirum", and uses "r" in "ri", aligning with object-ranking present tense marker.
226
+ - Sentence 5, "nirum kəmə nɤ cʰam tiʔ ne", features second-person plural subject and first-person singular object, where object ranks lower, using past tense tʰ- with -i agreement, indicating tense is tied to rank.
227
+ - Sentence 4, "nirum kəmə tarum lan ki ne", has second-person plural subject and third-person plural object, resulting in past tense tʰ- (ki) due to object outranking, matching the rule for present tense with object-ranking.
228
+ - Sentence 10, "ati kəmə ŋa lapkʰi tʰɤ ne", has third-person subject and first-person object; object outranks, so past tense tʰ- is used, confirming tense is determined by subject-object rank.
229
+
230
+ \boxed{a.3: Do they know you(pl)?}
231
+ ```
232
+
benchmark/IOL/ioling_hf/reports/curation_queue/index.html ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/curation_queue/queue.json ADDED
@@ -0,0 +1,712 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "source_problem_id": "2003-individual-1",
4
+ "title": "Transcendental Algebra",
5
+ "year": 2003,
6
+ "round": "individual",
7
+ "problem_number": 1,
8
+ "problem_confidence": "ocr_heading",
9
+ "solution_confidence": "ocr_heading",
10
+ "problem_images": [
11
+ "images/2003-individual-1-problem-p1.png",
12
+ "images/2003-individual-1-problem-p2.png"
13
+ ],
14
+ "solution_images": [
15
+ "images/2003-individual-1-solution-p1.png",
16
+ "images/2003-individual-1-solution-p2.png"
17
+ ],
18
+ "manual_override_path": "data/manual_overrides/2003-individual-1.json"
19
+ },
20
+ {
21
+ "source_problem_id": "2003-individual-2",
22
+ "title": "Arabic Arithmetic",
23
+ "year": 2003,
24
+ "round": "individual",
25
+ "problem_number": 2,
26
+ "problem_confidence": "ocr_heading",
27
+ "solution_confidence": "ocr_heading",
28
+ "problem_images": [
29
+ "images/2003-individual-2-problem-p2.png"
30
+ ],
31
+ "solution_images": [
32
+ "images/2003-individual-2-solution-p2.png",
33
+ "images/2003-individual-2-solution-p3.png"
34
+ ],
35
+ "manual_override_path": "data/manual_overrides/2003-individual-2.json"
36
+ },
37
+ {
38
+ "source_problem_id": "2003-individual-3",
39
+ "title": "Basque Dates",
40
+ "year": 2003,
41
+ "round": "individual",
42
+ "problem_number": 3,
43
+ "problem_confidence": "ocr_heading",
44
+ "solution_confidence": "ocr_heading",
45
+ "problem_images": [
46
+ "images/2003-individual-3-problem-p2.png",
47
+ "images/2003-individual-3-problem-p3.png"
48
+ ],
49
+ "solution_images": [
50
+ "images/2003-individual-3-solution-p3.png",
51
+ "images/2003-individual-3-solution-p4.png"
52
+ ],
53
+ "manual_override_path": "data/manual_overrides/2003-individual-3.json"
54
+ },
55
+ {
56
+ "source_problem_id": "2003-individual-4",
57
+ "title": "Adyghe",
58
+ "year": 2003,
59
+ "round": "individual",
60
+ "problem_number": 4,
61
+ "problem_confidence": "ocr_heading",
62
+ "solution_confidence": "ocr_heading",
63
+ "problem_images": [
64
+ "images/2003-individual-4-problem-p3.png",
65
+ "images/2003-individual-4-problem-p4.png"
66
+ ],
67
+ "solution_images": [
68
+ "images/2003-individual-4-solution-p4.png"
69
+ ],
70
+ "manual_override_path": "data/manual_overrides/2003-individual-4.json"
71
+ },
72
+ {
73
+ "source_problem_id": "2003-individual-5",
74
+ "title": "French",
75
+ "year": 2003,
76
+ "round": "individual",
77
+ "problem_number": 5,
78
+ "problem_confidence": "ocr_heading",
79
+ "solution_confidence": "ocr_heading",
80
+ "problem_images": [
81
+ "images/2003-individual-5-problem-p4.png"
82
+ ],
83
+ "solution_images": [
84
+ "images/2003-individual-5-solution-p4.png"
85
+ ],
86
+ "manual_override_path": "data/manual_overrides/2003-individual-5.json"
87
+ },
88
+ {
89
+ "source_problem_id": "2003-team-1",
90
+ "title": "Tocharian",
91
+ "year": 2003,
92
+ "round": "team",
93
+ "problem_number": 1,
94
+ "problem_confidence": "ocr_heading",
95
+ "solution_confidence": "ocr_heading",
96
+ "problem_images": [
97
+ "images/2003-team-1-problem-p1.png",
98
+ "images/2003-team-1-problem-p2.png"
99
+ ],
100
+ "solution_images": [
101
+ "images/2003-team-1-solution-p1.png"
102
+ ],
103
+ "manual_override_path": "data/manual_overrides/2003-team-1.json"
104
+ },
105
+ {
106
+ "source_problem_id": "2003-team-2",
107
+ "title": "Subscripts",
108
+ "year": 2003,
109
+ "round": "team",
110
+ "problem_number": 2,
111
+ "problem_confidence": "ocr_heading",
112
+ "solution_confidence": "ocr_heading",
113
+ "problem_images": [
114
+ "images/2003-team-2-problem-p2.png"
115
+ ],
116
+ "solution_images": [
117
+ "images/2003-team-2-solution-p1.png",
118
+ "images/2003-team-2-solution-p2.png"
119
+ ],
120
+ "manual_override_path": "data/manual_overrides/2003-team-2.json"
121
+ },
122
+ {
123
+ "source_problem_id": "2003-team-3",
124
+ "title": "Verbs",
125
+ "year": 2003,
126
+ "round": "team",
127
+ "problem_number": 3,
128
+ "problem_confidence": "ocr_heading",
129
+ "solution_confidence": "ocr_heading",
130
+ "problem_images": [
131
+ "images/2003-team-3-problem-p2.png"
132
+ ],
133
+ "solution_images": [
134
+ "images/2003-team-3-solution-p2.png"
135
+ ],
136
+ "manual_override_path": "data/manual_overrides/2003-team-3.json"
137
+ },
138
+ {
139
+ "source_problem_id": "2004-individual-1",
140
+ "title": "Kayapo",
141
+ "year": 2004,
142
+ "round": "individual",
143
+ "problem_number": 1,
144
+ "problem_confidence": "heading",
145
+ "solution_confidence": "ocr_heading",
146
+ "problem_images": [
147
+ "images/2004-individual-1-problem-p1.png"
148
+ ],
149
+ "solution_images": [
150
+ "images/2004-individual-1-solution-p1.png"
151
+ ],
152
+ "manual_override_path": "data/manual_overrides/2004-individual-1.json"
153
+ },
154
+ {
155
+ "source_problem_id": "2004-individual-2",
156
+ "title": "Swift News Agency",
157
+ "year": 2004,
158
+ "round": "individual",
159
+ "problem_number": 2,
160
+ "problem_confidence": "heading",
161
+ "solution_confidence": "ocr_heading",
162
+ "problem_images": [
163
+ "images/2004-individual-2-problem-p1.png",
164
+ "images/2004-individual-2-problem-p2.png"
165
+ ],
166
+ "solution_images": [
167
+ "images/2004-individual-2-solution-p1.png",
168
+ "images/2004-individual-2-solution-p2.png"
169
+ ],
170
+ "manual_override_path": "data/manual_overrides/2004-individual-2.json"
171
+ },
172
+ {
173
+ "source_problem_id": "2004-individual-3",
174
+ "title": "Latin",
175
+ "year": 2004,
176
+ "round": "individual",
177
+ "problem_number": 3,
178
+ "problem_confidence": "heading",
179
+ "solution_confidence": "ocr_heading",
180
+ "problem_images": [
181
+ "images/2004-individual-3-problem-p2.png",
182
+ "images/2004-individual-3-problem-p3.png"
183
+ ],
184
+ "solution_images": [
185
+ "images/2004-individual-3-solution-p2.png"
186
+ ],
187
+ "manual_override_path": "data/manual_overrides/2004-individual-3.json"
188
+ },
189
+ {
190
+ "source_problem_id": "2004-individual-4",
191
+ "title": "Lakhota",
192
+ "year": 2004,
193
+ "round": "individual",
194
+ "problem_number": 4,
195
+ "problem_confidence": "heading",
196
+ "solution_confidence": "ocr_heading",
197
+ "problem_images": [
198
+ "images/2004-individual-4-problem-p3.png",
199
+ "images/2004-individual-4-problem-p4.png"
200
+ ],
201
+ "solution_images": [
202
+ "images/2004-individual-4-solution-p2.png",
203
+ "images/2004-individual-4-solution-p3.png"
204
+ ],
205
+ "manual_override_path": "data/manual_overrides/2004-individual-4.json"
206
+ },
207
+ {
208
+ "source_problem_id": "2004-individual-5",
209
+ "title": "Chuvash",
210
+ "year": 2004,
211
+ "round": "individual",
212
+ "problem_number": 5,
213
+ "problem_confidence": "heading",
214
+ "solution_confidence": "ocr_heading",
215
+ "problem_images": [
216
+ "images/2004-individual-5-problem-p4.png"
217
+ ],
218
+ "solution_images": [
219
+ "images/2004-individual-5-solution-p3.png",
220
+ "images/2004-individual-5-solution-p4.png",
221
+ "images/2004-individual-5-solution-p5.png"
222
+ ],
223
+ "manual_override_path": "data/manual_overrides/2004-individual-5.json"
224
+ },
225
+ {
226
+ "source_problem_id": "2005-individual-1",
227
+ "title": "Tzotzil",
228
+ "year": 2005,
229
+ "round": "individual",
230
+ "problem_number": 1,
231
+ "problem_confidence": "ocr_heading",
232
+ "solution_confidence": "ocr_heading",
233
+ "problem_images": [
234
+ "images/2005-individual-1-problem-p1.png",
235
+ "images/2005-individual-1-problem-p2.png"
236
+ ],
237
+ "solution_images": [
238
+ "images/2005-individual-1-solution-p1.png",
239
+ "images/2005-individual-1-solution-p2.png"
240
+ ],
241
+ "manual_override_path": "data/manual_overrides/2005-individual-1.json"
242
+ },
243
+ {
244
+ "source_problem_id": "2005-individual-2",
245
+ "title": "Lango",
246
+ "year": 2005,
247
+ "round": "individual",
248
+ "problem_number": 2,
249
+ "problem_confidence": "ocr_heading",
250
+ "solution_confidence": "ocr_heading",
251
+ "problem_images": [
252
+ "images/2005-individual-2-problem-p2.png"
253
+ ],
254
+ "solution_images": [
255
+ "images/2005-individual-2-solution-p2.png"
256
+ ],
257
+ "manual_override_path": "data/manual_overrides/2005-individual-2.json"
258
+ },
259
+ {
260
+ "source_problem_id": "2005-individual-3",
261
+ "title": "Mansi",
262
+ "year": 2005,
263
+ "round": "individual",
264
+ "problem_number": 3,
265
+ "problem_confidence": "ocr_heading",
266
+ "solution_confidence": "ocr_heading",
267
+ "problem_images": [
268
+ "images/2005-individual-3-problem-p2.png",
269
+ "images/2005-individual-3-problem-p3.png"
270
+ ],
271
+ "solution_images": [
272
+ "images/2005-individual-3-solution-p2.png",
273
+ "images/2005-individual-3-solution-p3.png"
274
+ ],
275
+ "manual_override_path": "data/manual_overrides/2005-individual-3.json"
276
+ },
277
+ {
278
+ "source_problem_id": "2005-individual-4",
279
+ "title": "Yoruba",
280
+ "year": 2005,
281
+ "round": "individual",
282
+ "problem_number": 4,
283
+ "problem_confidence": "ocr_heading",
284
+ "solution_confidence": "ocr_heading",
285
+ "problem_images": [
286
+ "images/2005-individual-4-problem-p3.png",
287
+ "images/2005-individual-4-problem-p4.png"
288
+ ],
289
+ "solution_images": [
290
+ "images/2005-individual-4-solution-p3.png",
291
+ "images/2005-individual-4-solution-p4.png"
292
+ ],
293
+ "manual_override_path": "data/manual_overrides/2005-individual-4.json"
294
+ },
295
+ {
296
+ "source_problem_id": "2005-individual-5",
297
+ "title": "Lithuanian",
298
+ "year": 2005,
299
+ "round": "individual",
300
+ "problem_number": 5,
301
+ "problem_confidence": "ocr_heading",
302
+ "solution_confidence": "ocr_heading",
303
+ "problem_images": [
304
+ "images/2005-individual-5-problem-p4.png"
305
+ ],
306
+ "solution_images": [
307
+ "images/2005-individual-5-solution-p4.png"
308
+ ],
309
+ "manual_override_path": "data/manual_overrides/2005-individual-5.json"
310
+ },
311
+ {
312
+ "source_problem_id": "2007-individual-1",
313
+ "title": "Braille",
314
+ "year": 2007,
315
+ "round": "individual",
316
+ "problem_number": 1,
317
+ "problem_confidence": "heading",
318
+ "solution_confidence": "page_index",
319
+ "problem_images": [
320
+ "images/2007-individual-1-problem-p1.png",
321
+ "images/2007-individual-1-problem-p2.png"
322
+ ],
323
+ "solution_images": [
324
+ "images/2007-individual-1-solution-p1.png"
325
+ ],
326
+ "manual_override_path": "data/manual_overrides/2007-individual-1.json"
327
+ },
328
+ {
329
+ "source_problem_id": "2007-team-1",
330
+ "title": "Hawaiian",
331
+ "year": 2007,
332
+ "round": "team",
333
+ "problem_number": 1,
334
+ "problem_confidence": "team_full_document",
335
+ "solution_confidence": "team_full_document",
336
+ "problem_images": [
337
+ "images/2007-team-1-problem-p1.png",
338
+ "images/2007-team-1-problem-p2.png"
339
+ ],
340
+ "solution_images": [
341
+ "images/2007-team-1-solution-p1.png"
342
+ ],
343
+ "manual_override_path": "data/manual_overrides/2007-team-1.json"
344
+ },
345
+ {
346
+ "source_problem_id": "2008-team-1",
347
+ "title": "Fanqie",
348
+ "year": 2008,
349
+ "round": "team",
350
+ "problem_number": 1,
351
+ "problem_confidence": "team_full_document",
352
+ "solution_confidence": "team_full_document",
353
+ "problem_images": [
354
+ "images/2008-team-1-problem-p1.png",
355
+ "images/2008-team-1-problem-p2.png",
356
+ "images/2008-team-1-problem-p3.png"
357
+ ],
358
+ "solution_images": [
359
+ "images/2008-team-1-solution-p1.png",
360
+ "images/2008-team-1-solution-p2.png"
361
+ ],
362
+ "manual_override_path": "data/manual_overrides/2008-team-1.json"
363
+ },
364
+ {
365
+ "source_problem_id": "2009-team-1",
366
+ "title": "Vietnamese",
367
+ "year": 2009,
368
+ "round": "team",
369
+ "problem_number": 1,
370
+ "problem_confidence": "team_full_document",
371
+ "solution_confidence": "team_full_document",
372
+ "problem_images": [
373
+ "images/2009-team-1-problem-p1.png",
374
+ "images/2009-team-1-problem-p2.png",
375
+ "images/2009-team-1-problem-p3.png",
376
+ "images/2009-team-1-problem-p4.png"
377
+ ],
378
+ "solution_images": [
379
+ "images/2009-team-1-solution-p1.png",
380
+ "images/2009-team-1-solution-p2.png",
381
+ "images/2009-team-1-solution-p3.png",
382
+ "images/2009-team-1-solution-p4.png",
383
+ "images/2009-team-1-solution-p5.png",
384
+ "images/2009-team-1-solution-p6.png",
385
+ "images/2009-team-1-solution-p7.png",
386
+ "images/2009-team-1-solution-p8.png",
387
+ "images/2009-team-1-solution-p9.png",
388
+ "images/2009-team-1-solution-p10.png"
389
+ ],
390
+ "manual_override_path": "data/manual_overrides/2009-team-1.json"
391
+ },
392
+ {
393
+ "source_problem_id": "2010-team-1",
394
+ "title": "Mongolian",
395
+ "year": 2010,
396
+ "round": "team",
397
+ "problem_number": 1,
398
+ "problem_confidence": "team_full_document",
399
+ "solution_confidence": "team_full_document",
400
+ "problem_images": [
401
+ "images/2010-team-1-problem-p1.png",
402
+ "images/2010-team-1-problem-p2.png"
403
+ ],
404
+ "solution_images": [
405
+ "images/2010-team-1-solution-p1.png",
406
+ "images/2010-team-1-solution-p2.png"
407
+ ],
408
+ "manual_override_path": "data/manual_overrides/2010-team-1.json"
409
+ },
410
+ {
411
+ "source_problem_id": "2011-team-1",
412
+ "title": "Sanskrit Poetry",
413
+ "year": 2011,
414
+ "round": "team",
415
+ "problem_number": 1,
416
+ "problem_confidence": "team_full_document",
417
+ "solution_confidence": "team_full_document",
418
+ "problem_images": [
419
+ "images/2011-team-1-problem-p1.png",
420
+ "images/2011-team-1-problem-p2.png",
421
+ "images/2011-team-1-problem-p3.png",
422
+ "images/2011-team-1-problem-p4.png",
423
+ "images/2011-team-1-problem-p5.png",
424
+ "images/2011-team-1-problem-p6.png",
425
+ "images/2011-team-1-problem-p7.png"
426
+ ],
427
+ "solution_images": [
428
+ "images/2011-team-1-solution-p1.png"
429
+ ],
430
+ "manual_override_path": "data/manual_overrides/2011-team-1.json"
431
+ },
432
+ {
433
+ "source_problem_id": "2012-team-1",
434
+ "title": "Lao",
435
+ "year": 2012,
436
+ "round": "team",
437
+ "problem_number": 1,
438
+ "problem_confidence": "team_full_document",
439
+ "solution_confidence": "team_full_document",
440
+ "problem_images": [
441
+ "images/2012-team-1-problem-p1.png"
442
+ ],
443
+ "solution_images": [
444
+ "images/2012-team-1-solution-p1.png"
445
+ ],
446
+ "manual_override_path": "data/manual_overrides/2012-team-1.json"
447
+ },
448
+ {
449
+ "source_problem_id": "2014-team-1",
450
+ "title": "Armenian",
451
+ "year": 2014,
452
+ "round": "team",
453
+ "problem_number": 1,
454
+ "problem_confidence": "team_full_document",
455
+ "solution_confidence": "team_full_document",
456
+ "problem_images": [
457
+ "images/2014-team-1-problem-p1.png",
458
+ "images/2014-team-1-problem-p2.png",
459
+ "images/2014-team-1-problem-p3.png",
460
+ "images/2014-team-1-problem-p4.png"
461
+ ],
462
+ "solution_images": [
463
+ "images/2014-team-1-solution-p1.png",
464
+ "images/2014-team-1-solution-p2.png",
465
+ "images/2014-team-1-solution-p3.png"
466
+ ],
467
+ "manual_override_path": "data/manual_overrides/2014-team-1.json"
468
+ },
469
+ {
470
+ "source_problem_id": "2015-team-1",
471
+ "title": "Northern Sotho",
472
+ "year": 2015,
473
+ "round": "team",
474
+ "problem_number": 1,
475
+ "problem_confidence": "team_full_document",
476
+ "solution_confidence": "team_full_document",
477
+ "problem_images": [
478
+ "images/2015-team-1-problem-p1.png",
479
+ "images/2015-team-1-problem-p2.png",
480
+ "images/2015-team-1-problem-p3.png"
481
+ ],
482
+ "solution_images": [
483
+ "images/2015-team-1-solution-p1.png"
484
+ ],
485
+ "manual_override_path": "data/manual_overrides/2015-team-1.json"
486
+ },
487
+ {
488
+ "source_problem_id": "2016-team-1",
489
+ "title": "Taa",
490
+ "year": 2016,
491
+ "round": "team",
492
+ "problem_number": 1,
493
+ "problem_confidence": "team_full_document",
494
+ "solution_confidence": "team_full_document",
495
+ "problem_images": [
496
+ "images/2016-team-1-problem-p1.png"
497
+ ],
498
+ "solution_images": [
499
+ "images/2016-team-1-solution-p1.png"
500
+ ],
501
+ "manual_override_path": "data/manual_overrides/2016-team-1.json"
502
+ },
503
+ {
504
+ "source_problem_id": "2017-team-1",
505
+ "title": "Emoji/Indonesian",
506
+ "year": 2017,
507
+ "round": "team",
508
+ "problem_number": 1,
509
+ "problem_confidence": "team_full_document",
510
+ "solution_confidence": "team_full_document",
511
+ "problem_images": [
512
+ "images/2017-team-1-problem-p1.png",
513
+ "images/2017-team-1-problem-p2.png",
514
+ "images/2017-team-1-problem-p3.png",
515
+ "images/2017-team-1-problem-p4.png"
516
+ ],
517
+ "solution_images": [
518
+ "images/2017-team-1-solution-p1.png",
519
+ "images/2017-team-1-solution-p2.png",
520
+ "images/2017-team-1-solution-p3.png"
521
+ ],
522
+ "manual_override_path": "data/manual_overrides/2017-team-1.json"
523
+ },
524
+ {
525
+ "source_problem_id": "2018-team-1",
526
+ "title": "Mẽbêngôkre, Xavante and Krĩkatí",
527
+ "year": 2018,
528
+ "round": "team",
529
+ "problem_number": 1,
530
+ "problem_confidence": "team_full_document",
531
+ "solution_confidence": "team_full_document",
532
+ "problem_images": [
533
+ "images/2018-team-1-problem-p1.png",
534
+ "images/2018-team-1-problem-p2.png",
535
+ "images/2018-team-1-problem-p3.png",
536
+ "images/2018-team-1-problem-p4.png"
537
+ ],
538
+ "solution_images": [
539
+ "images/2018-team-1-solution-p1.png",
540
+ "images/2018-team-1-solution-p2.png",
541
+ "images/2018-team-1-solution-p3.png",
542
+ "images/2018-team-1-solution-p4.png",
543
+ "images/2018-team-1-solution-p5.png"
544
+ ],
545
+ "manual_override_path": "data/manual_overrides/2018-team-1.json"
546
+ },
547
+ {
548
+ "source_problem_id": "2019-team-1",
549
+ "title": "Rhythmic Gymnastics",
550
+ "year": 2019,
551
+ "round": "team",
552
+ "problem_number": 1,
553
+ "problem_confidence": "team_full_document",
554
+ "solution_confidence": "team_full_document",
555
+ "problem_images": [
556
+ "images/2019-team-1-problem-p1.png",
557
+ "images/2019-team-1-problem-p2.png",
558
+ "images/2019-team-1-problem-p3.png",
559
+ "images/2019-team-1-problem-p4.png",
560
+ "images/2019-team-1-problem-p5.png"
561
+ ],
562
+ "solution_images": [
563
+ "images/2019-team-1-solution-p1.png",
564
+ "images/2019-team-1-solution-p2.png"
565
+ ],
566
+ "manual_override_path": "data/manual_overrides/2019-team-1.json"
567
+ },
568
+ {
569
+ "source_problem_id": "2021-team-1",
570
+ "title": "Garífuna, Lokono and Kari’ña",
571
+ "year": 2021,
572
+ "round": "team",
573
+ "problem_number": 1,
574
+ "problem_confidence": "team_full_document",
575
+ "solution_confidence": "team_full_document",
576
+ "problem_images": [
577
+ "images/2021-team-1-problem-p1.png",
578
+ "images/2021-team-1-problem-p2.png",
579
+ "images/2021-team-1-problem-p3.png",
580
+ "images/2021-team-1-problem-p4.png",
581
+ "images/2021-team-1-problem-p5.png",
582
+ "images/2021-team-1-problem-p6.png",
583
+ "images/2021-team-1-problem-p7.png",
584
+ "images/2021-team-1-problem-p8.png",
585
+ "images/2021-team-1-problem-p9.png",
586
+ "images/2021-team-1-problem-p10.png",
587
+ "images/2021-team-1-problem-p11.png",
588
+ "images/2021-team-1-problem-p12.png",
589
+ "images/2021-team-1-problem-p13.png"
590
+ ],
591
+ "solution_images": [
592
+ "images/2021-team-1-solution-p1.png",
593
+ "images/2021-team-1-solution-p2.png",
594
+ "images/2021-team-1-solution-p3.png",
595
+ "images/2021-team-1-solution-p4.png"
596
+ ],
597
+ "manual_override_path": "data/manual_overrides/2021-team-1.json"
598
+ },
599
+ {
600
+ "source_problem_id": "2022-team-1",
601
+ "title": "Manchu",
602
+ "year": 2022,
603
+ "round": "team",
604
+ "problem_number": 1,
605
+ "problem_confidence": "team_full_document",
606
+ "solution_confidence": "team_full_document",
607
+ "problem_images": [
608
+ "images/2022-team-1-problem-p2.png",
609
+ "images/2022-team-1-problem-p3.png",
610
+ "images/2022-team-1-problem-p4.png",
611
+ "images/2022-team-1-problem-p5.png",
612
+ "images/2022-team-1-problem-p6.png",
613
+ "images/2022-team-1-problem-p7.png",
614
+ "images/2022-team-1-problem-p8.png",
615
+ "images/2022-team-1-problem-p9.png",
616
+ "images/2022-team-1-problem-p10.png"
617
+ ],
618
+ "solution_images": [
619
+ "images/2022-team-1-solution-p1.png",
620
+ "images/2022-team-1-solution-p2.png",
621
+ "images/2022-team-1-solution-p3.png",
622
+ "images/2022-team-1-solution-p4.png"
623
+ ],
624
+ "manual_override_path": "data/manual_overrides/2022-team-1.json"
625
+ },
626
+ {
627
+ "source_problem_id": "2023-team-1",
628
+ "title": "Murrinh-patha",
629
+ "year": 2023,
630
+ "round": "team",
631
+ "problem_number": 1,
632
+ "problem_confidence": "team_full_document",
633
+ "solution_confidence": "team_full_document",
634
+ "problem_images": [
635
+ "images/2023-team-1-problem-p1.png",
636
+ "images/2023-team-1-problem-p2.png",
637
+ "images/2023-team-1-problem-p3.png",
638
+ "images/2023-team-1-problem-p4.png",
639
+ "images/2023-team-1-problem-p5.png",
640
+ "images/2023-team-1-problem-p6.png",
641
+ "images/2023-team-1-problem-p7.png",
642
+ "images/2023-team-1-problem-p8.png",
643
+ "images/2023-team-1-problem-p9.png"
644
+ ],
645
+ "solution_images": [
646
+ "images/2023-team-1-solution-p1.png",
647
+ "images/2023-team-1-solution-p2.png",
648
+ "images/2023-team-1-solution-p3.png"
649
+ ],
650
+ "manual_override_path": "data/manual_overrides/2023-team-1.json"
651
+ },
652
+ {
653
+ "source_problem_id": "2024-team-1",
654
+ "title": "Lexicostatistics",
655
+ "year": 2024,
656
+ "round": "team",
657
+ "problem_number": 1,
658
+ "problem_confidence": "team_full_document",
659
+ "solution_confidence": "team_full_document",
660
+ "problem_images": [
661
+ "images/2024-team-1-problem-p1.png",
662
+ "images/2024-team-1-problem-p2.png",
663
+ "images/2024-team-1-problem-p3.png",
664
+ "images/2024-team-1-problem-p4.png",
665
+ "images/2024-team-1-problem-p5.png",
666
+ "images/2024-team-1-problem-p6.png",
667
+ "images/2024-team-1-problem-p7.png",
668
+ "images/2024-team-1-problem-p8.png",
669
+ "images/2024-team-1-problem-p9.png"
670
+ ],
671
+ "solution_images": [
672
+ "images/2024-team-1-solution-p1.png",
673
+ "images/2024-team-1-solution-p2.png",
674
+ "images/2024-team-1-solution-p3.png",
675
+ "images/2024-team-1-solution-p4.png",
676
+ "images/2024-team-1-solution-p5.png",
677
+ "images/2024-team-1-solution-p6.png",
678
+ "images/2024-team-1-solution-p7.png",
679
+ "images/2024-team-1-solution-p8.png",
680
+ "images/2024-team-1-solution-p9.png",
681
+ "images/2024-team-1-solution-p10.png",
682
+ "images/2024-team-1-solution-p11.png",
683
+ "images/2024-team-1-solution-p12.png"
684
+ ],
685
+ "manual_override_path": "data/manual_overrides/2024-team-1.json"
686
+ },
687
+ {
688
+ "source_problem_id": "2025-team-1",
689
+ "title": "Camling and Bantawa",
690
+ "year": 2025,
691
+ "round": "team",
692
+ "problem_number": 1,
693
+ "problem_confidence": "team_full_document",
694
+ "solution_confidence": "team_full_document",
695
+ "problem_images": [
696
+ "images/2025-team-1-problem-p1.png",
697
+ "images/2025-team-1-problem-p2.png",
698
+ "images/2025-team-1-problem-p3.png",
699
+ "images/2025-team-1-problem-p4.png",
700
+ "images/2025-team-1-problem-p5.png",
701
+ "images/2025-team-1-problem-p6.png",
702
+ "images/2025-team-1-problem-p7.png",
703
+ "images/2025-team-1-problem-p8.png",
704
+ "images/2025-team-1-problem-p9.png"
705
+ ],
706
+ "solution_images": [
707
+ "images/2025-team-1-solution-p1.png",
708
+ "images/2025-team-1-solution-p2.png"
709
+ ],
710
+ "manual_override_path": "data/manual_overrides/2025-team-1.json"
711
+ }
712
+ ]
benchmark/IOL/ioling_hf/reports/evaluation/qwen3_4b_base_unseen_v14_sources_pass8.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/evaluation/qwen3_4b_instruct_base_v14_val_pass8.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v2_unseen_v14_sources_pass8.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v3_15sources_train_one_per_source_pass8.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/evaluation/sft_rule_rich_v3_15sources_val_pass8.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_8x4k.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_nothink_8x4k.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/IOL/ioling_hf/reports/rl_strict_probes/Qwen_Qwen3.6-35B-A3B-FP8__manual_v9_atomic_prior_nothink_finalonly_8x4k.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/LICENSE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Copyright Jason R. Coombs
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/METADATA ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: configparser
3
+ Version: 4.0.2
4
+ Summary: Updated configparser from Python 3.7 for Python 2.6+.
5
+ Home-page: https://github.com/jaraco/configparser/
6
+ Author: Łukasz Langa
7
+ Author-email: lukasz@langa.pl
8
+ Maintainer: Jason R. Coombs
9
+ Maintainer-email: jaraco@jaraco.com
10
+ License: UNKNOWN
11
+ Keywords: configparser ini parsing conf cfg configuration file
12
+ Platform: any
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 2.7
17
+ Classifier: Programming Language :: Python :: 3
18
+ Requires-Python: >=2.6
19
+ Provides-Extra: docs
20
+ Requires-Dist: sphinx ; extra == 'docs'
21
+ Requires-Dist: jaraco.packaging (>=3.2) ; extra == 'docs'
22
+ Requires-Dist: rst.linker (>=1.9) ; extra == 'docs'
23
+ Provides-Extra: testing
24
+ Requires-Dist: pytest (!=3.7.3,>=3.5) ; extra == 'testing'
25
+ Requires-Dist: pytest-checkdocs (>=1.2) ; extra == 'testing'
26
+ Requires-Dist: pytest-flake8 ; extra == 'testing'
27
+ Requires-Dist: pytest-black-multipy ; extra == 'testing'
28
+
29
+ .. image:: https://img.shields.io/pypi/v/configparser.svg
30
+ :target: https://pypi.org/project/configparser
31
+
32
+ .. image:: https://img.shields.io/pypi/pyversions/configparser.svg
33
+
34
+ .. image:: https://img.shields.io/travis/jaraco/configparser/master.svg
35
+ :target: https://travis-ci.org/jaraco/configparser
36
+
37
+ .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
38
+ :target: https://github.com/ambv/black
39
+ :alt: Code style: Black
40
+
41
+ .. .. image:: https://img.shields.io/appveyor/ci/jaraco/configparser/master.svg
42
+ .. :target: https://ci.appveyor.com/project/jaraco/configparser/branch/master
43
+
44
+ .. image:: https://readthedocs.org/projects/configparser/badge/?version=latest
45
+ :target: https://configparser.readthedocs.io/en/latest/?badge=latest
46
+
47
+ .. image:: https://tidelift.com/badges/package/pypi/configparser
48
+ :target: https://tidelift.com/subscription/pkg/pypi-configparser?utm_source=pypi-configparser&utm_medium=readme
49
+
50
+
51
+ The ancient ``ConfigParser`` module available in the standard library 2.x has
52
+ seen a major update in Python 3.2. This is a backport of those changes so that
53
+ they can be used directly in Python 2.6 - 3.5.
54
+
55
+ To use the ``configparser`` backport instead of the built-in version on both
56
+ Python 2 and Python 3, simply import it explicitly as a backport::
57
+
58
+ from backports import configparser
59
+
60
+ If you'd like to use the backport on Python 2 and the built-in version on
61
+ Python 3, use that invocation instead::
62
+
63
+ import configparser
64
+
65
+ For detailed documentation consult the vanilla version at
66
+ http://docs.python.org/3/library/configparser.html.
67
+
68
+ Why you'll love ``configparser``
69
+ --------------------------------
70
+
71
+ Whereas almost completely compatible with its older brother, ``configparser``
72
+ sports a bunch of interesting new features:
73
+
74
+ * full mapping protocol access (`more info
75
+ <http://docs.python.org/3/library/configparser.html#mapping-protocol-access>`_)::
76
+
77
+ >>> parser = ConfigParser()
78
+ >>> parser.read_string("""
79
+ [DEFAULT]
80
+ location = upper left
81
+ visible = yes
82
+ editable = no
83
+ color = blue
84
+
85
+ [main]
86
+ title = Main Menu
87
+ color = green
88
+
89
+ [options]
90
+ title = Options
91
+ """)
92
+ >>> parser['main']['color']
93
+ 'green'
94
+ >>> parser['main']['editable']
95
+ 'no'
96
+ >>> section = parser['options']
97
+ >>> section['title']
98
+ 'Options'
99
+ >>> section['title'] = 'Options (editable: %(editable)s)'
100
+ >>> section['title']
101
+ 'Options (editable: no)'
102
+
103
+ * there's now one default ``ConfigParser`` class, which basically is the old
104
+ ``SafeConfigParser`` with a bunch of tweaks which make it more predictable for
105
+ users. Don't need interpolation? Simply use
106
+ ``ConfigParser(interpolation=None)``, no need to use a distinct
107
+ ``RawConfigParser`` anymore.
108
+
109
+ * the parser is highly `customizable upon instantiation
110
+ <http://docs.python.org/3/library/configparser.html#customizing-parser-behaviour>`__
111
+ supporting things like changing option delimiters, comment characters, the
112
+ name of the DEFAULT section, the interpolation syntax, etc.
113
+
114
+ * you can easily create your own interpolation syntax but there are two powerful
115
+ implementations built-in (`more info
116
+ <http://docs.python.org/3/library/configparser.html#interpolation-of-values>`__):
117
+
118
+ * the classic ``%(string-like)s`` syntax (called ``BasicInterpolation``)
119
+
120
+ * a new ``${buildout:like}`` syntax (called ``ExtendedInterpolation``)
121
+
122
+ * fallback values may be specified in getters (`more info
123
+ <http://docs.python.org/3/library/configparser.html#fallback-values>`__)::
124
+
125
+ >>> config.get('closet', 'monster',
126
+ ... fallback='No such things as monsters')
127
+ 'No such things as monsters'
128
+
129
+ * ``ConfigParser`` objects can now read data directly `from strings
130
+ <http://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read_string>`__
131
+ and `from dictionaries
132
+ <http://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read_dict>`__.
133
+ That means importing configuration from JSON or specifying default values for
134
+ the whole configuration (multiple sections) is now a single line of code. Same
135
+ goes for copying data from another ``ConfigParser`` instance, thanks to its
136
+ mapping protocol support.
137
+
138
+ * many smaller tweaks, updates and fixes
139
+
140
+ A few words about Unicode
141
+ -------------------------
142
+
143
+ ``configparser`` comes from Python 3 and as such it works well with Unicode.
144
+ The library is generally cleaned up in terms of internal data storage and
145
+ reading/writing files. There are a couple of incompatibilities with the old
146
+ ``ConfigParser`` due to that. However, the work required to migrate is well
147
+ worth it as it shows the issues that would likely come up during migration of
148
+ your project to Python 3.
149
+
150
+ The design assumes that Unicode strings are used whenever possible [1]_. That
151
+ gives you the certainty that what's stored in a configuration object is text.
152
+ Once your configuration is read, the rest of your application doesn't have to
153
+ deal with encoding issues. All you have is text [2]_. The only two phases when
154
+ you should explicitly state encoding is when you either read from an external
155
+ source (e.g. a file) or write back.
156
+
157
+ Versioning
158
+ ----------
159
+
160
+ This project uses `semver <https://semver.org/spec/v2.0.0.html>`_ to
161
+ communicate the impact of various releases while periodically syncing
162
+ with the upstream implementation in CPython.
163
+ `The changelog <https://github.com/jaraco/configparser/blob/master/CHANGES.rst>`_
164
+ serves as a reference indicating which versions incorporate
165
+ which upstream functionality.
166
+
167
+ Prior to the ``4.0.0`` release, `another scheme
168
+ <https://github.com/jaraco/configparser/blob/3.8.1/README.rst#versioning>`_
169
+ was used to associate the CPython and backports releases.
170
+
171
+ Maintenance
172
+ -----------
173
+
174
+ This backport was originally authored by Łukasz Langa, the current vanilla
175
+ ``configparser`` maintainer for CPython and is currently maintained by
176
+ Jason R. Coombs:
177
+
178
+ * `configparser repository <https://github.com/jaraco/configparser>`_
179
+
180
+ * `configparser issue tracker <https://github.com/jaraco/configparser/issues>`_
181
+
182
+ Security Contact
183
+ ----------------
184
+
185
+ To report a security vulnerability, please use the
186
+ `Tidelift security contact <https://tidelift.com/security>`_.
187
+ Tidelift will coordinate the fix and disclosure.
188
+
189
+ Conversion Process
190
+ ------------------
191
+
192
+ This section is technical and should bother you only if you are wondering how
193
+ this backport is produced. If the implementation details of this backport are
194
+ not important for you, feel free to ignore the following content.
195
+
196
+ ``configparser`` is converted using `python-future
197
+ <http://python-future.org>`_. The project takes the following
198
+ branching approach:
199
+
200
+ * the ``3.x`` branch holds unchanged files synchronized from the upstream
201
+ CPython repository. The synchronization is currently done by manually copying
202
+ the required files and stating from which CPython changeset they come from.
203
+
204
+ * the ``master`` branch holds a version of the ``3.x`` code with some tweaks
205
+ that make it independent from libraries and constructions unavailable on 2.x.
206
+ Code on this branch still *must* work on the corresponding Python 3.x but
207
+ will also work on Python 2.6 and 2.7 (including PyPy). You can check this
208
+ running the supplied unit tests with ``tox``.
209
+
210
+ The process works like this:
211
+
212
+ 1. In the ``3.x`` branch, run ``pip-run -- sync-upstream.py``, which
213
+ downloads the latest stable release of Python and copies the relevant
214
+ files from there into their new locations here and then commits those
215
+ changes with a nice reference to the relevant upstream commit hash.
216
+
217
+ 2. I check for new names in ``__all__`` and update imports in
218
+ ``configparser.py`` accordingly. I run the tests on Python 3. Commit.
219
+
220
+ 3. I merge the new commit to ``master``. I run ``tox``. Commit.
221
+
222
+ 4. If there are necessary changes, I do them now (on ``master``). Note that
223
+ the changes should be written in the syntax subset supported by Python
224
+ 2.6.
225
+
226
+ 5. I run ``tox``. If it works, I update the docs and release the new version.
227
+ Otherwise, I go back to point 3. I might use ``pasteurize`` to suggest me
228
+ required changes but usually I do them manually to keep resulting code in
229
+ a nicer form.
230
+
231
+
232
+ Footnotes
233
+ ---------
234
+
235
+ .. [1] To somewhat ease migration, passing bytestrings is still supported but
236
+ they are converted to Unicode for internal storage anyway. This means
237
+ that for the vast majority of strings used in configuration files, it
238
+ won't matter if you pass them as bytestrings or Unicode. However, if you
239
+ pass a bytestring that cannot be converted to Unicode using the naive
240
+ ASCII codec, a ``UnicodeDecodeError`` will be raised. This is purposeful
241
+ and helps you manage proper encoding for all content you store in
242
+ memory, read from various sources and write back.
243
+
244
+ .. [2] Life gets much easier when you understand that you basically manage
245
+ **text** in your application. You don't care about bytes but about
246
+ letters. In that regard the concept of content encoding is meaningless.
247
+ The only time when you deal with raw bytes is when you write the data to
248
+ a file. Then you have to specify how your text should be encoded. On
249
+ the other end, to get meaningful text from a file, the application
250
+ reading it has to know which encoding was used during its creation. But
251
+ once the bytes are read and properly decoded, all you have is text. This
252
+ is especially powerful when you start interacting with multiple data
253
+ sources. Even if each of them uses a different encoding, inside your
254
+ application data is held in abstract text form. You can program your
255
+ business logic without worrying about which data came from which source.
256
+ You can freely exchange the data you store between sources. Only
257
+ reading/writing files requires encoding your text to bytes.
258
+
259
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ backports/__init__.py,sha256=elt6uFwbaEv80X8iGWsCJ_w_n_h1X8repgOoNrN0Syg,212
2
+ backports/__init__.pyc,,
3
+ backports/configparser/__init__.py,sha256=thhQqB1qWNKf-F3CpZFYsjC8YT-_I_vF0w4JiuQfiWI,56628
4
+ backports/configparser/__init__.pyc,,
5
+ backports/configparser/helpers.py,sha256=TxT00ldsHvIciQpml1YaoHfdtTl033Km6ywwT-U2nRc,7543
6
+ backports/configparser/helpers.pyc,,
7
+ configparser-4.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
8
+ configparser-4.0.2.dist-info/LICENSE,sha256=pV4v_ptEmY5iHVHYwJS-0JrMS1I27nPX3zlaM7o8GP0,1050
9
+ configparser-4.0.2.dist-info/METADATA,sha256=oDqeXQXq8JhFEDHKDOBmbUtXmQ3CiiXB1Mr4UheTZ8Y,10910
10
+ configparser-4.0.2.dist-info/RECORD,,
11
+ configparser-4.0.2.dist-info/WHEEL,sha256=8zNYZbwQSXoB9IfXOjPfeNwvAsALAjffgk27FqvCWbo,110
12
+ configparser-4.0.2.dist-info/top_level.txt,sha256=mIs8gajd7cvEWhVluv4u6ocaHw_TJ9rOrpkZEFv-7Hc,23
13
+ configparser.py,sha256=4VADEswCwzy_RDVgvje3BmZhD6iwo3k4EkUZcgzLD4M,1546
14
+ configparser.pyc,,
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/configparser-4.0.2.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ backports
2
+ configparser
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/_compat.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cffi
2
+ import warnings
3
+
4
+
5
+ class OpenSSLVersion:
6
+ V1_0 = "1_0"
7
+ V1_1 = "1_1"
8
+
9
+
10
+ def get_abi_lib():
11
+ ffi = cffi.FFI()
12
+ ffi.cdef("unsigned long OpenSSL_version_num();")
13
+ ffi.cdef("unsigned long SSLeay();")
14
+ lib = ffi.dlopen("crypto")
15
+ return lib
16
+
17
+
18
+ def get_openssl_version(lib=None, warn=False):
19
+ """Returns the OpenSSL version that is used for bindings."""
20
+
21
+ if lib is None:
22
+ lib = get_abi_lib()
23
+
24
+ try:
25
+ full_version = lib.OpenSSL_version_num()
26
+ except AttributeError:
27
+ full_version = lib.SSLeay()
28
+
29
+ version = full_version >> 20
30
+ if version == 0x101:
31
+ return OpenSSLVersion.V1_1
32
+ elif version == 0x100:
33
+ if warn:
34
+ warnings.warn(
35
+ "Support for the system OpenSSL version (0x%x) is pending deprecation. "
36
+ "Please upgrade to OpenSSL v1.1" % version)
37
+ return OpenSSLVersion.V1_0
38
+ else:
39
+ # If the version is not 1.0 or 1.1, assume its a later one, and optimistically
40
+ # assume it doesn't horribly break the interface this time.
41
+ if warn:
42
+ warnings.warn(
43
+ "System OpenSSL version is not supported: %d. "
44
+ "Attempting to use in OpenSSL v1.1 mode." % version)
45
+ return OpenSSLVersion.V1_1
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/bindings.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import platform
5
+ import cffi
6
+ import sys
7
+
8
+ try:
9
+ from ._petlib import ffi, lib
10
+ _FFI = ffi
11
+ _C = lib
12
+
13
+ except BaseException:
14
+ print("Support not loading the library to build docs without compiling.")
15
+ _C = None
16
+ _FFI = None
17
+
18
+
19
+ from ._compat import get_openssl_version, OpenSSLVersion # pylint: disable=unused-import
20
+ _OPENSSL_VERSION = get_openssl_version(_C)
21
+
22
+
23
+ # Store constants
24
+ class Const:
25
+ POINT_CONVERSION_COMPRESSED = 2,
26
+ POINT_CONVERSION_UNCOMPRESSED = 4,
27
+ POINT_CONVERSION_HYBRID = 6
28
+
29
+
30
+ _inited = False
31
+
32
+
33
+ def version():
34
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
35
+ cstr = _C.SSLeay_version(_C.SSLEAY_VERSION)
36
+ else:
37
+ cstr = _C.OpenSSL_version(_C.OPENSSL_VERSION)
38
+
39
+ return str(_FFI.string(cstr))
40
+
41
+
42
+ def get_errors():
43
+ errors = []
44
+ err = _C.ERR_get_error()
45
+ while err != 0:
46
+ errors += [err]
47
+ err = _C.ERR_get_error()
48
+ assert isinstance(errors, list)
49
+ return errors
50
+
51
+
52
+ class InitCiphers(object):
53
+ # pylint: disable=global-statement
54
+
55
+ def __init__(self):
56
+ global _inited
57
+ self.on = False
58
+ self._C = _C
59
+ if not _inited:
60
+ _C.OPENSSL_init()
61
+ _C.init_ciphers()
62
+ _inited = True
63
+ self.on = True
64
+
65
+ def __del__(self):
66
+ global _inited
67
+ if _inited and self.on and self._C:
68
+ _inited = False
69
+ self._C.cleanup_ciphers()
70
+
71
+
72
+ if _C and _FFI:
73
+ _ciphers = InitCiphers()
74
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
75
+ if _C.CRYPTO_get_locking_callback() == _FFI.NULL:
76
+ _C.setup_ssl_threads()
77
+
78
+
79
+ def test_double_load():
80
+ _c2 = InitCiphers()
81
+ del _c2
82
+ # Nothing bad should happen
83
+
84
+
85
+ def test_version():
86
+ print(version())
87
+ assert version()
88
+
89
+
90
+ def test_errors():
91
+ assert get_errors() == []
92
+
93
+
94
+ def test_locks():
95
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
96
+ assert _C.CRYPTO_get_locking_callback() != _FFI.NULL
97
+
98
+
99
+ def test_multithread():
100
+ import threading
101
+ from .ec import EcPt, EcGroup
102
+
103
+ G = EcGroup()
104
+ g = G.generator()
105
+ o = G.order()
106
+ g2 = o.random() * g
107
+ g2_s = g2.export()
108
+
109
+ def worker():
110
+ for _ in range(100):
111
+ EcPt.from_binary(g2_s, G)
112
+
113
+ threads = []
114
+ for _ in range(100):
115
+ t = threading.Thread(target=worker)
116
+ threads.append(t)
117
+ t.start()
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/bn.py ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bindings import _FFI, _C, get_errors
2
+
3
+ from functools import wraps
4
+ from copy import copy, deepcopy
5
+ from binascii import hexlify, unhexlify # pylint: disable=unused-import
6
+
7
+ # Py2/3 compatibility
8
+ try:
9
+ from builtins import int # pylint: disable=redefined-builtin
10
+ from builtins import object # pylint: disable=redefined-builtin
11
+ except BaseException: # pylint: disable=bare-except
12
+ print("Cannot mock for docs")
13
+
14
+ try:
15
+ from future.utils import python_2_unicode_compatible
16
+ except Exception as e: # pylint: disable=broad-except
17
+ # An identity decorator
18
+ def python_2_unicode_compatible(x): return x
19
+
20
+ import pytest
21
+
22
+
23
+ def force_Bn(n):
24
+ """A decorator that coerces the nth input to be a Big Number"""
25
+
26
+ def convert_nth(f):
27
+ # pylint: disable=star-args
28
+ @wraps(f)
29
+ def new_f(*args, **kwargs):
30
+ new_args = args
31
+ try:
32
+ if not n < len(args) or args[n].bn: # isinstance(args[n], Bn):
33
+ new_args = args
34
+ except BaseException:
35
+ # if not n < len(args):
36
+ # new_args = args
37
+
38
+ if isinstance(args[n], int):
39
+ r = Bn.from_num(args[n])
40
+ new_args = list(args)
41
+ new_args[n] = r
42
+ new_args = tuple(new_args)
43
+ else:
44
+ return NotImplemented
45
+
46
+ return f(*new_args, **kwargs)
47
+
48
+ return new_f
49
+ return convert_nth
50
+
51
+
52
+ def _check(return_val):
53
+ """Checks the return code of the C calls"""
54
+ if __debug__:
55
+ if isinstance(return_val, int) and return_val == 1:
56
+ return
57
+ if isinstance(return_val, bool) and return_val == True:
58
+ return
59
+
60
+ if return_val == True and return_val == 1:
61
+ return
62
+
63
+ errs = get_errors()
64
+ raise Exception("BN exception: %s" % errs)
65
+
66
+
67
+ class BnCtx(object):
68
+ """ A Bn Context for use by the petlib library """
69
+
70
+ __slots__ = ['bnctx', '_C']
71
+
72
+ def __init__(self):
73
+ self._C = _C
74
+ self.bnctx = self._C.BN_CTX_new()
75
+ _check(self.bnctx != _FFI.NULL)
76
+
77
+ def __del__(self):
78
+ if self.bnctx is not None:
79
+ self._C.BN_CTX_free(self.bnctx)
80
+
81
+
82
+ class BnCtxNULL(BnCtx):
83
+ """ A Bn Context for use by the petlib library """
84
+
85
+ __slots__ = ['bnctx', '_C']
86
+
87
+ def __init__(self):
88
+ self._C = _C
89
+ self.bnctx = _FFI.NULL
90
+
91
+ def __del__(self):
92
+ pass
93
+
94
+
95
+ import threading
96
+ _thread_local = threading.local()
97
+
98
+
99
+ def get_ctx():
100
+ global _thread_local
101
+
102
+ try:
103
+ return _thread_local.ctx
104
+ except BaseException:
105
+ _thread_local.ctx = BnCtx()
106
+ return _thread_local.ctx
107
+
108
+
109
+ @python_2_unicode_compatible
110
+ class Bn(object):
111
+ """The core Big Number class.
112
+ It supports all comparisons (<, <=, ==, !=, >=, >),
113
+ arithmetic operations (+, -, %, /, divmod, pow)
114
+ and copy operations (copy and deep copy). The right-hand
115
+ side operand may be a small native python integer (<2^64). """
116
+
117
+ __C = _C
118
+
119
+ # We know this class will keep minimal state
120
+ __slots__ = ['bn']
121
+
122
+ # -- static methods
123
+
124
+ @staticmethod
125
+ def from_num(num):
126
+ if isinstance(num, int):
127
+ return Bn(num)
128
+ elif isinstance(num, Bn):
129
+ return num
130
+ else:
131
+ # raise TypeError("Cannot coerce %s into a BN." % num)
132
+ return NotImplemented
133
+
134
+ @staticmethod
135
+ def from_decimal(sdec):
136
+ """Creates a Big Number from a decimal string.
137
+
138
+ Args:
139
+ sdec (string): numeric string possibly starting with minus.
140
+
141
+ See Also:
142
+ str() produces a decimal string from a big number.
143
+
144
+ Example:
145
+ >>> hundred = Bn.from_decimal("100")
146
+ >>> str(hundred)
147
+ '100'
148
+
149
+ """
150
+
151
+ ptr = _FFI.new("BIGNUM **")
152
+ read_bytes = _C.BN_dec2bn(ptr, sdec.encode("utf8"))
153
+ if read_bytes != len(sdec):
154
+ raise Exception("BN Error")
155
+
156
+ ret = Bn()
157
+ _C.BN_copy(ret.bn, ptr[0])
158
+ _C.BN_clear_free(ptr[0])
159
+ return ret
160
+
161
+ @staticmethod
162
+ def from_hex(shex):
163
+ """Creates a Big Number from a hexadecimal string.
164
+
165
+ Args:
166
+ shex (string): hex (0-F) string possibly starting with minus.
167
+
168
+ See Also:
169
+ hex() produces a hexadecimal representation of a big number.
170
+
171
+ Example:
172
+ >>> Bn.from_hex("FF")
173
+ 255
174
+ """
175
+
176
+ ptr = _FFI.new("BIGNUM **")
177
+ read_bytes = _C.BN_hex2bn(ptr, shex.encode("utf8"))
178
+ if read_bytes != len(shex):
179
+ raise Exception("BN Error")
180
+
181
+ ret = Bn()
182
+ _C.BN_copy(ret.bn, ptr[0])
183
+ _C.BN_clear_free(ptr[0])
184
+ return ret
185
+
186
+ @staticmethod
187
+ def from_binary(sbin):
188
+ """Creates a Big Number from a byte sequence representing the number in Big-endian 8 byte atoms. Only positive values can be represented as byte sequence, and the library user should store the sign bit separately.
189
+
190
+ Args:
191
+ sbin (string): a byte sequence.
192
+
193
+ Example:
194
+ >>> byte_seq = unhexlify(b"010203")
195
+ >>> Bn.from_binary(byte_seq)
196
+ 66051
197
+ >>> (1 * 256**2) + (2 * 256) + 3
198
+ 66051
199
+ """
200
+ ret = Bn()
201
+ _C.BN_bin2bn(sbin, len(sbin), ret.bn)
202
+ return ret
203
+
204
+ @staticmethod
205
+ def get_prime(bits, safe=1):
206
+ """
207
+ Builds a prime Big Number of length bits.
208
+
209
+ Args:
210
+ bits (int) -- the number of bits.
211
+ safe (int) -- 1 for a safe prime, otherwise 0.
212
+
213
+ """
214
+ _check(0 < bits < 10000)
215
+ _check(safe in [0, 1])
216
+
217
+ ret = Bn()
218
+ _check(
219
+ _C.BN_generate_prime_ex(
220
+ ret.bn,
221
+ bits,
222
+ safe,
223
+ _FFI.NULL,
224
+ _FFI.NULL,
225
+ _FFI.NULL))
226
+ return ret
227
+
228
+ ## -- methods
229
+
230
+ _upper_bound = 2**(64 - 1)
231
+
232
+ def __init__(self, num=0):
233
+ 'Allocate a Big Number structure, initialized with a small integer or zero.'
234
+ self.bn = _C.BN_new()
235
+
236
+ if num == 0:
237
+ return
238
+
239
+ if __debug__:
240
+ _check(0 <= abs(num) <= self._upper_bound)
241
+ _check(isinstance(num, int))
242
+
243
+ # Assign
244
+ if num != 0:
245
+ ret = _C.BN_set_word(self.bn, abs(num))
246
+ if __debug__:
247
+ _check(ret)
248
+ if ret != 1:
249
+ raise Exception("Bn Exception.")
250
+
251
+ if num < 0:
252
+ self._set_neg(1)
253
+
254
+ def _set_neg(self, sign=1):
255
+ # """Sets the sign to "-" (1) or "+" (0)"""
256
+ if not (sign == 0 or sign == 1):
257
+ raise Exception("Sign has to be 0 or 1.")
258
+ _C.BN_set_negative(self.bn, sign)
259
+
260
+ def copy(self):
261
+ """Returns a copy of the Bn object."""
262
+ return self.__copy__()
263
+
264
+ def __copy__(self):
265
+ # 'Copies the big number. Support for copy module'
266
+ other = Bn()
267
+ _C.BN_copy(other.bn, self.bn)
268
+ return other
269
+
270
+ def __deepcopy__(self, memento):
271
+ # 'Deepcopy is the same as copy'
272
+ # pylint: disable=unused-argument
273
+ return self.__copy__()
274
+
275
+ def __del__(self):
276
+ # 'Deallocate all resources of the big number'
277
+ self.__C.BN_clear_free(self.bn)
278
+
279
+ def __inner_cmp__(self, other):
280
+ # 'Irel comparison function'
281
+ # if __debug__:
282
+ # _check( type(other) == Bn )
283
+ try:
284
+ sig = int(_C.BN_cmp(self.bn, other.bn))
285
+ return sig
286
+ except AttributeError:
287
+ return self.__inner_cmp__(Bn.from_num(other))
288
+
289
+ def __lt__(self, other):
290
+ return self.__inner_cmp__(other) < 0
291
+
292
+ def __le__(self, other):
293
+ return self.__inner_cmp__(other) <= 0
294
+
295
+ def __eq__(self, other):
296
+ return self.__inner_cmp__(other) == 0
297
+
298
+ def __ne__(self, other):
299
+ return self.__inner_cmp__(other) != 0
300
+
301
+ def __gt__(self, other):
302
+ return self.__inner_cmp__(other) > 0
303
+
304
+ def __ge__(self, other):
305
+ return self.__inner_cmp__(other) >= 0
306
+
307
+ def bool(self):
308
+ 'Turn Bn into boolean. False if zero, True otherwise.'
309
+ return self.__bool__()
310
+
311
+ def __bool__(self):
312
+ # 'Turn into boolean'
313
+ return not (self == Bn(0))
314
+
315
+ # Python 2 compatibility
316
+ def __nonzero__(self):
317
+ return self.__bool__()
318
+
319
+ # Export in different representations
320
+
321
+ def repr(self):
322
+ 'The representation of the number as a decimal string'
323
+ return self.__repr__()
324
+
325
+ def __repr__(self):
326
+ # 'The representation of the number as a decimal string'
327
+ buf = _C.BN_bn2dec(self.bn)
328
+ s = bytes(_FFI.string(buf))
329
+ _C.OPENSSL_free(buf)
330
+ return s.decode('utf8')
331
+
332
+ def int(self):
333
+ """A native python integer representation of the Big Number.
334
+ Synonym for int(bn).
335
+ """
336
+ return self.__int__()
337
+
338
+ def __int__(self):
339
+ return int(self.__repr__())
340
+
341
+ def __index__(self):
342
+ return int(self.__repr__())
343
+
344
+ def hex(self):
345
+ """The representation of the string in hexadecimal.
346
+ Synonym for hex(n)."""
347
+ return self.__hex__()
348
+
349
+ def __hex__(self):
350
+ # """The representation of the string in hexadecimal"""
351
+ buf = _C.BN_bn2hex(self.bn)
352
+ s = bytes(_FFI.string(buf))
353
+ _C.OPENSSL_free(buf)
354
+ return s.decode("utf8")
355
+
356
+ def binary(self):
357
+ """Returns a byte sequence storing the absolute value of the Big
358
+ Number in Big-Endian format (with 8 bit atoms). You need to extact the sign separately.
359
+
360
+ Example:
361
+ >>> bin = Bn(66051).binary()
362
+ >>> hexlify(bin) == b'010203'
363
+ True
364
+ """
365
+ if self < 0:
366
+ raise Exception("Cannot represent negative numbers")
367
+ size = _C.bn_num_bytes(self.bn)
368
+ bin_string = _FFI.new("unsigned char[]", size)
369
+
370
+ l = _C.BN_bn2bin(self.bn, bin_string)
371
+ assert int(l) == size
372
+ return bytes(_FFI.buffer(bin_string)[:])
373
+
374
+ def random(self):
375
+ """Returns a cryptographically strong random number 0 <= rnd < self.
376
+
377
+ Example:
378
+ >>> r = Bn(100).random()
379
+ >>> 0 <= r < 100
380
+ True
381
+
382
+ """
383
+ rnd = Bn()
384
+ err = _C.BN_rand_range(rnd.bn, self.bn)
385
+ if __debug__:
386
+ _check(err)
387
+ return rnd
388
+
389
+ # ---------- Arithmetic --------------
390
+
391
+ def int_neg(self):
392
+ """Returns the negative of this number. Synonym with -self.
393
+
394
+ Example:
395
+
396
+ >>> one100 = Bn(100)
397
+ >>> one100.int_neg()
398
+ -100
399
+ >>> -one100
400
+ -100
401
+
402
+ """
403
+ return self.__neg__()
404
+
405
+ def int_add(self, other):
406
+ """Returns the sum of this number with another. Synonym for self + other.
407
+
408
+ Example:
409
+
410
+ >>> one100 = Bn(100)
411
+ >>> two100 = Bn(200)
412
+ >>> two100.int_add(one100) # Function syntax
413
+ 300
414
+ >>> two100 + one100 # Operator syntax
415
+ 300
416
+
417
+ """
418
+ return self.__add__(other)
419
+
420
+ def __radd__(self, other):
421
+ return self.__add__(other)
422
+
423
+ def __add__(self, other):
424
+ try:
425
+ r = Bn()
426
+ err = _C.BN_add(r.bn, self.bn, other.bn)
427
+
428
+ if __debug__:
429
+ _check(err)
430
+ return r
431
+ except AttributeError:
432
+ return self.__add__(Bn.from_num(other))
433
+
434
+ def int_sub(self, other):
435
+ """Returns the difference between this number and another.
436
+ Synonym for self - other.
437
+
438
+ Example:
439
+
440
+ >>> one100 = Bn(100)
441
+ >>> two100 = Bn(200)
442
+ >>> two100.int_sub(one100) # Function syntax
443
+ 100
444
+ >>> two100 - one100 # Operator syntax
445
+ 100
446
+
447
+ """
448
+ return self - other
449
+
450
+ def __rsub__(self, other):
451
+ return Bn(other) - self
452
+
453
+ def __sub__(self, other):
454
+ try:
455
+ r = Bn()
456
+ err = _C.BN_sub(r.bn, self.bn, other.bn)
457
+
458
+ if __debug__:
459
+ _check(err)
460
+
461
+ return r
462
+ except AttributeError:
463
+ return self.__sub__(Bn.from_num(other))
464
+
465
+ def int_mul(self, other):
466
+ """Returns the product of this number with another.
467
+ Synonym for self * other.
468
+
469
+ Example:
470
+
471
+ >>> one100 = Bn(100)
472
+ >>> two100 = Bn(200)
473
+ >>> one100.int_mul(two100) # Function syntax
474
+ 20000
475
+ >>> one100 * two100 # Operator syntax
476
+ 20000
477
+
478
+ """
479
+ return self.__mul__(other)
480
+
481
+ def __rmul__(self, other):
482
+ return self.__mul__(other)
483
+
484
+ def __mul__(self, other):
485
+
486
+ try:
487
+ r = Bn()
488
+ local_ctx = get_ctx()
489
+ err = _C.BN_mul(r.bn, self.bn, other.bn, local_ctx.bnctx)
490
+
491
+ if __debug__:
492
+ _check(err)
493
+
494
+ return r
495
+ except AttributeError:
496
+ other = Bn.from_num(other)
497
+ if other is NotImplemented:
498
+ return NotImplemented
499
+ return self.__mul__(other)
500
+
501
+
502
+ # ------------------ Mod arithmetic -------------------------
503
+
504
+
505
+ def mod_add(self, other, m):
506
+ """
507
+ mod_add(other, m)
508
+ Returns the sum of self and other modulo m.
509
+
510
+ Example:
511
+
512
+ >>> Bn(10).mod_add(Bn(2), Bn(11)) # Only function notation available
513
+ 1
514
+
515
+ """
516
+ try:
517
+ r = Bn()
518
+ local_ctx = get_ctx()
519
+ err = _C.BN_mod_add(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)
520
+ if __debug__:
521
+ _check(err)
522
+
523
+ return r
524
+ except AttributeError:
525
+ return self.mod_add(Bn.from_num(other), Bn.from_num(m))
526
+
527
+ def mod_sub(self, other, m):
528
+ """
529
+ mod_sub(other, m)
530
+ Returns the difference of self and other modulo m.
531
+
532
+ Example:
533
+
534
+ >>> Bn(10).mod_sub(Bn(2), Bn(11)) # Only function notation available
535
+ 8
536
+
537
+ """
538
+
539
+ try:
540
+ r = Bn()
541
+ local_ctx = get_ctx()
542
+ err = _C.BN_mod_sub(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)
543
+
544
+ if __debug__:
545
+ _check(err)
546
+
547
+ return r
548
+ except AttributeError:
549
+ return self.mod_sub(Bn.from_num(other), Bn.from_num(m))
550
+
551
+ def mod_mul(self, other, m):
552
+ """
553
+ mod_mul(other, m)
554
+ Return the product of self and other modulo m.
555
+
556
+ Example:
557
+
558
+ >>> Bn(10).mod_mul(Bn(2), Bn(11)) # Only function notation available
559
+ 9
560
+
561
+ """
562
+ try:
563
+ r = Bn()
564
+ local_ctx = get_ctx()
565
+ err = _C.BN_mod_mul(r.bn, self.bn, other.bn, m.bn, local_ctx.bnctx)
566
+
567
+ if __debug__:
568
+ _check(err)
569
+
570
+ return r
571
+ except AttributeError:
572
+ return self.mod_mul(Bn.from_num(other), Bn.from_num(m))
573
+
574
+ def mod_inverse(self, m):
575
+ """
576
+ mod_inverse(m)
577
+ Compute the inverse mod m, such that self * res == 1 mod m.
578
+
579
+ Example:
580
+
581
+ >>> Bn(10).mod_inverse(m = Bn(11)) # Only function notation available
582
+ 10
583
+ >>> Bn(10).mod_mul(Bn(10), m = Bn(11)) == Bn(1)
584
+ True
585
+
586
+ """
587
+
588
+ try:
589
+ res = Bn()
590
+ local_ctx = get_ctx()
591
+ err = _C.BN_mod_inverse(res.bn, self.bn, m.bn, local_ctx.bnctx)
592
+
593
+ if err == _FFI.NULL:
594
+ errs = get_errors()
595
+
596
+ if errs == [50770023]:
597
+ raise Exception("No inverse")
598
+
599
+ elif errs == [50782316]:
600
+ raise Exception("No inverse")
601
+
602
+ else:
603
+ raise Exception("Unknown error: %s" % errs)
604
+
605
+ return res
606
+ except AttributeError:
607
+ return self.mod_inverse(Bn.from_num(m))
608
+
609
+ def mod_pow(self, other, m, ctx=None):
610
+ """ Performs the modular exponentiation of self ** other % m.
611
+
612
+ Example:
613
+ >>> one100 = Bn(100)
614
+ >>> one100.mod_pow(2, 3) # Modular exponentiation
615
+ 1
616
+
617
+ """
618
+ return self.__pow__(other, m, ctx=ctx)
619
+
620
+ def divmod(self, other):
621
+ """Returns the integer division and remainder of this number by another.
622
+ Synonym for (div, mod) = divmod(self, other)"""
623
+ return self.__divmod__(other)
624
+
625
+ def __rdivmod__(self, other):
626
+ return Bn(other).__divmod__(self)
627
+
628
+ def __divmod__(self, other):
629
+ try:
630
+ dv = Bn()
631
+ rem = Bn()
632
+ local_ctx = get_ctx()
633
+ ret = _C.BN_div(dv.bn, rem.bn, self.bn, other.bn, local_ctx.bnctx)
634
+ if __debug__:
635
+ _check(ret)
636
+ return (dv, rem)
637
+ except AttributeError:
638
+ return self.__divmod__(Bn.from_num(other))
639
+
640
+ def int_div(self, other):
641
+ """Returns the integer division of this number by another.
642
+ Synonym of self / other.
643
+
644
+ Example:
645
+
646
+ >>> one100 = Bn(100)
647
+ >>> two100 = Bn(200)
648
+ >>> two100.int_div(one100) # Function syntax
649
+ 2
650
+ >>> two100 / one100 # Operator syntax
651
+ 2
652
+
653
+ """
654
+ return self.__div__(other)
655
+
656
+ def __rdiv__(self, other):
657
+ return Bn(other).__div__(self)
658
+
659
+ def __div__(self, other):
660
+ dv, _ = divmod(self, other)
661
+ return dv
662
+
663
+ def mod(self, other):
664
+ """Returns the remainder of this number modulo another.
665
+ Synonym for self % other.
666
+
667
+ Example:
668
+
669
+ >>> one100 = Bn(100)
670
+ >>> two100 = Bn(200)
671
+ >>> two100.mod(one100) # Function syntax
672
+ 0
673
+ >>> two100 % one100 # Operator syntax
674
+ 0
675
+
676
+
677
+ """
678
+ return self.__mod__(other)
679
+
680
+ def __rmod__(self, other):
681
+ return Bn(other).__mod__(self)
682
+
683
+ def __mod__(self, other):
684
+
685
+ try:
686
+ rem = Bn()
687
+
688
+ local_ctx = get_ctx()
689
+ err = _C.BN_nnmod(rem.bn, self.bn, other.bn, local_ctx.bnctx)
690
+
691
+ if __debug__:
692
+ _check(err)
693
+ return rem
694
+ except AttributeError:
695
+ self.__mod__(Bn.from_num(other))
696
+
697
+ def __rtruediv__(self, other):
698
+ return Bn(other).__truediv__(self)
699
+
700
+ def __truediv__(self, other):
701
+ return self.__div__(other)
702
+
703
+ def __rfloordiv__(self, other):
704
+ return Bn(other).__floordiv__(self)
705
+
706
+ def __floordiv__(self, other):
707
+ return self.__div__(other)
708
+
709
+ def __rpow__(self, other):
710
+ return Bn(other).__pow__(self)
711
+
712
+ def pow(self, other, modulo=None, ctx=None):
713
+ """Returns the number raised to the power other optionally modulo a third number.
714
+ Synonym with pow(self, other, modulo).
715
+
716
+ Example:
717
+
718
+ >>> one100 = Bn(100)
719
+ >>> one100.pow(2) # Function syntax
720
+ 10000
721
+ >>> one100 ** 2 # Operator syntax
722
+ 10000
723
+ >>> one100.pow(2, 3) # Modular exponentiation
724
+ 1
725
+
726
+ """
727
+ if modulo:
728
+ return self.__pow__(other, modulo, ctx)
729
+ else:
730
+ return self ** other
731
+
732
+ def __pow__(self, other, modulo=None, ctx=None):
733
+
734
+ try:
735
+ res = Bn()
736
+
737
+ if ctx is None:
738
+ ctx = BnCtx()
739
+
740
+ if modulo is None:
741
+ _check(_C.BN_exp(res.bn, self.bn, other.bn, ctx.bnctx))
742
+ else:
743
+ _check(
744
+ _C.BN_mod_exp(
745
+ res.bn,
746
+ self.bn,
747
+ other.bn,
748
+ modulo.bn,
749
+ ctx.bnctx))
750
+
751
+ return res
752
+ except BaseException:
753
+ other = Bn.from_num(other)
754
+ if modulo is not None:
755
+ modulo = Bn.from_num(modulo)
756
+ return self.__pow__(other, modulo, ctx)
757
+
758
+ def is_prime(self):
759
+ """Returns True if the number is prime, with negligible prob. of error."""
760
+
761
+ res = int(_C.BN_is_prime_ex(self.bn, 0, get_ctx().bnctx, _FFI.NULL))
762
+ if res == 0:
763
+ return False
764
+ if res == 1:
765
+ return True
766
+ raise Exception("Primality test failure %s" % int(res))
767
+
768
+ def is_odd(self):
769
+ """Returns True if the number is odd."""
770
+
771
+ return bool(_C.bn_is_odd(self.bn))
772
+
773
+ def is_bit_set(self, n):
774
+ """Returns True if the nth bit is set"""
775
+ return int(_C.BN_is_bit_set(self.bn, n))
776
+
777
+ def num_bits(self):
778
+ """Returns the number of bits representing this Big Number"""
779
+ return int(_C.BN_num_bits(self.bn))
780
+
781
+ # Implement negative
782
+ def __neg__(self):
783
+ # pylint: disable=protected-access
784
+ global zero
785
+ ret = copy(self)
786
+ if ret >= zero:
787
+ ret._set_neg(1)
788
+ else:
789
+ ret._set_neg(0)
790
+ return ret
791
+
792
+ def __hash__(self):
793
+ return int(self).__hash__()
794
+
795
+ # Unsuported
796
+ # object.__lshift__(self, other)
797
+ # object.__rshift__(self, other)
798
+ # object.__and__(self, other)
799
+ # object.__xor__(self, other)
800
+ # object.__or__(self, other)
801
+
802
+ # ---------- Tests ------------
803
+
804
+
805
+ # Some globals
806
+ zero = Bn(0)
807
+
808
+
809
+ def test_bn_constructors():
810
+ assert Bn.from_decimal("100") == 100
811
+ assert Bn.from_decimal("-100") == -100
812
+
813
+ with pytest.raises(Exception) as excinfo:
814
+ Bn.from_decimal("100ABC")
815
+ assert 'BN Error' in str(excinfo.value)
816
+
817
+ with pytest.raises(Exception) as excinfo:
818
+ Bn.from_hex("100ABCZ")
819
+ assert 'BN Error' in str(excinfo.value)
820
+
821
+ assert Bn.from_hex(Bn(-100).hex()) == -100
822
+ assert Bn(15).hex() == Bn(15).hex()
823
+
824
+ with pytest.raises(Exception) as excinfo:
825
+ Bn(-100).binary()
826
+ assert 'negative' in str(excinfo.value)
827
+
828
+ #assert Bn.from_binary(Bn(-100).binary()) == 100
829
+ assert Bn.from_binary(Bn(100).binary()) == Bn(100)
830
+ assert Bn.from_binary(Bn(100).binary()) == 100
831
+
832
+ with pytest.raises(Exception) as excinfo:
833
+ s = 10**10
834
+ Bn(s)
835
+ assert 'does not fit' in str(excinfo.value)
836
+
837
+ with pytest.raises(Exception) as excinfo:
838
+ _check(False)
839
+ assert 'BN' in str(excinfo.value)
840
+
841
+ #assert Bn.from_binary(Bn(-100).binary()) != Bn(50)
842
+ assert int(Bn(-100)) == -100
843
+
844
+ assert repr(Bn(5)) == Bn(5).repr() == "5"
845
+ assert range(10)[Bn(4)] == 4
846
+
847
+ d = {Bn(5): 5, Bn(6): 6}
848
+ assert Bn(5) in d
849
+
850
+
851
+ def test_bn_prime():
852
+ p = Bn.get_prime(128)
853
+ assert p > Bn(0)
854
+ assert p.is_prime()
855
+ assert not Bn(16).is_prime()
856
+ assert p.num_bits() > 127
857
+
858
+
859
+ def test_bn_arithmetic():
860
+ assert (Bn(1) + Bn(1) == Bn(2))
861
+ assert (Bn(1).int_add(Bn(1)) == Bn(2))
862
+
863
+ assert (Bn(1) + 1 == Bn(2))
864
+ # assert (1 + Bn(1) == Bn(2))
865
+
866
+ assert (Bn(1) + Bn(-1) == Bn(0))
867
+ assert (Bn(10) + Bn(10) == Bn(20))
868
+ assert (Bn(-1) * Bn(-1) == Bn(1))
869
+ assert (Bn(-1).int_mul(Bn(-1)) == Bn(1))
870
+
871
+ assert (Bn(10) * Bn(10) == Bn(100))
872
+ assert (Bn(10) - Bn(10) == Bn(0))
873
+ assert (Bn(10) - Bn(100) == Bn(-90))
874
+ assert (Bn(10) + (-Bn(10)) == Bn(0))
875
+ s = -Bn(100)
876
+ assert (Bn(10) + s == Bn(-90))
877
+ assert (Bn(10) - (-Bn(10)) == Bn(20))
878
+ assert -Bn(-10) == 10
879
+ assert Bn(-10).int_neg() == 10
880
+
881
+ assert divmod(Bn(10), Bn(3)) == (Bn(3), Bn(1))
882
+ assert Bn(10).divmod(Bn(3)) == (Bn(3), Bn(1))
883
+
884
+ assert Bn(10) / Bn(3) == Bn(3)
885
+ assert Bn(10) // Bn(3) == Bn(3)
886
+ assert Bn(10).int_div(Bn(3)) == Bn(3)
887
+
888
+ assert Bn(10) % Bn(3) == Bn(1)
889
+ assert Bn(10).mod(Bn(3)) == Bn(1)
890
+
891
+ assert Bn(2) ** Bn(8) == Bn(2 ** 8)
892
+ assert pow(Bn(2), Bn(8), Bn(27)) == Bn(2 ** 8 % 27)
893
+
894
+ pow(Bn(10), Bn(10)).binary()
895
+
896
+ assert pow(Bn(2), 8, 27) == 2 ** 8 % 27
897
+
898
+ assert Bn(3).mod_inverse(16) == 11
899
+
900
+ with pytest.raises(Exception) as excinfo:
901
+ Bn(3).mod_inverse(0)
902
+ print("Got inverse")
903
+ assert 'No inverse' in str(excinfo.value)
904
+
905
+ with pytest.raises(Exception) as excinfo:
906
+ x = Bn(0).mod_inverse(Bn(13))
907
+ print("!!! Got inverse", x)
908
+ assert 'No inverse' in str(excinfo.value)
909
+
910
+ # with pytest.raises(Exception) as excinfo:
911
+ # x = Bn(0).mod_inverse(Bn(13))
912
+ # print("Got inverse", x)
913
+ #assert 'No inverse' in str(excinfo.value)
914
+
915
+ assert Bn(10).mod_add(10, 15) == (10 + 10) % 15
916
+ assert Bn(10).mod_sub(100, 15) == (10 - 100) % 15
917
+ assert Bn(10).mod_mul(10, 15) == (10 * 10) % 15
918
+ assert Bn(-1).bool()
919
+
920
+
921
+ def test_bn_right_arithmetic():
922
+ assert (1 + Bn(1) == Bn(2))
923
+
924
+ assert (-1 * Bn(-1) == Bn(1))
925
+
926
+ assert (10 * Bn(10) == Bn(100))
927
+ assert (10 - Bn(10) == Bn(0))
928
+ assert (10 - Bn(100) == Bn(-90))
929
+ assert (10 + (-Bn(10)) == Bn(0))
930
+ s = -Bn(100)
931
+ assert (10 + s == Bn(-90))
932
+ assert (10 - (-Bn(10)) == Bn(20))
933
+
934
+ assert divmod(10, Bn(3)) == (Bn(3), Bn(1))
935
+
936
+ assert 10 / Bn(3) == Bn(3)
937
+ assert 10 // Bn(3) == Bn(3)
938
+
939
+ assert 10 % Bn(3) == Bn(1)
940
+ assert 2 ** Bn(8) == Bn(2 ** 8)
941
+
942
+ assert 100 == Bn(100)
943
+
944
+ pow(10, Bn(10))
945
+
946
+
947
+ def test_bn_allocate():
948
+ # Test allocation
949
+ n0 = Bn(10)
950
+ assert True
951
+
952
+ assert str(Bn()) == "0"
953
+ assert str(Bn(1)) == "1"
954
+ assert str(Bn(-1)) == "-1"
955
+
956
+ assert Bn(15).hex() == "0F"
957
+ assert Bn(-15).hex() == "-0F"
958
+
959
+ assert int(Bn(5)) == 5
960
+ assert Bn(5).int() == 5
961
+
962
+ assert 0 <= Bn(15).random() < 15
963
+
964
+ # Test copy
965
+ o0 = copy(n0)
966
+ o1 = deepcopy(n0)
967
+
968
+ assert o0 == n0
969
+ assert o1 == n0
970
+
971
+ # Test nonzero
972
+ assert not Bn()
973
+ assert not Bn(0)
974
+ assert Bn(1)
975
+ assert Bn(100)
976
+
977
+
978
+ def test_bn_cmp():
979
+ assert Bn(1) < Bn(2)
980
+ assert Bn(1) <= Bn(2)
981
+ assert Bn(2) <= Bn(2)
982
+ assert Bn(2) == Bn(2)
983
+ assert Bn(2) <= Bn(3)
984
+ assert Bn(2) < Bn(3)
985
+
986
+
987
+ def test_extras():
988
+ two = Bn(2)
989
+ two2 = two.copy()
990
+ assert two == two2
991
+
992
+
993
+ def test_odd():
994
+ assert Bn(1).is_odd()
995
+ assert Bn(1).is_bit_set(0)
996
+ assert not Bn(1).is_bit_set(1)
997
+
998
+ assert Bn(3).is_odd()
999
+ assert Bn(3).is_bit_set(0)
1000
+ assert Bn(3).is_bit_set(1)
1001
+
1002
+ assert not Bn(0).is_odd()
1003
+ assert not Bn(2).is_odd()
1004
+
1005
+ assert Bn(100).is_bit_set(Bn(100).num_bits() - 1)
1006
+
1007
+
1008
+ def test_check():
1009
+ with pytest.raises(Exception) as excinfo:
1010
+ _check(False)
1011
+ assert 'BN' in str(excinfo.value)
1012
+
1013
+ with pytest.raises(Exception) as excinfo:
1014
+ _check(-1)
1015
+ assert 'BN' in str(excinfo.value)
1016
+
1017
+ with pytest.raises(Exception) as excinfo:
1018
+ _check(0)
1019
+ assert 'BN' in str(excinfo.value)
1020
+
1021
+
1022
+ def test_timing_exp():
1023
+ p = Bn.from_decimal("158261031819091141711717027498980088325079888681498417129323009913367867128038610210948802263526234270043507882496188624614467036250990588401775690578042934008692254417273606807265961724843618743242066301529332478013432957153823449143202719186309012133210922613102725038632605463022887306439116579645787938883")
1024
+ psmall = Bn.from_decimal(
1025
+ "90123082853250477832412338337738008391831682960497136029451532639902615425459")
1026
+
1027
+ xs = [p.random() for _ in range(1000)]
1028
+ ys = [p.random() for _ in range(1000)]
1029
+
1030
+ import time
1031
+
1032
+ print
1033
+ t0 = time.time()
1034
+ X = [xi.mod_mul(yi, psmall) for (xi, yi) in zip(xs, ys)]
1035
+ t1 = time.time()
1036
+ print("Mod_mul time: %.2fms" % ((t1 - t0) * 1000.0 / 1000.0))
1037
+
1038
+ t0 = time.time()
1039
+ X = [xi.pow(yi, p) for (xi, yi) in zip(xs, ys)]
1040
+ t1 = time.time()
1041
+ print(" Pow time: %.2fms" % ((t1 - t0) * 1000.0 / 1000.0))
1042
+
1043
+ ctx = BnCtx()
1044
+ t0 = time.time()
1045
+ X = [xi.pow(yi, p, ctx) for (xi, yi) in zip(xs, ys)]
1046
+ t1 = time.time()
1047
+ print("Pow ctx time: %.2fms" % ((t1 - t0) * 1000.0 / 1000.0))
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/cipher.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bindings import _FFI, _C, _OPENSSL_VERSION, OpenSSLVersion
2
+
3
+ import pytest
4
+
5
+
6
+ def _check(return_val):
7
+ """Checks the return code of the C calls"""
8
+ if isinstance(return_val, int) and return_val == 1:
9
+ return
10
+ if isinstance(return_val, bool) and return_val == True:
11
+ return
12
+
13
+ raise Exception(
14
+ "Cipher exception: Unknown type %s or value %s" %
15
+ (str(
16
+ type(return_val)),
17
+ str(return_val)))
18
+
19
+
20
+ class Cipher(object):
21
+ """A class representing a symmetric cipher and mode.
22
+
23
+ Example:
24
+ An example of encryption and decryption using AES in counter mode.
25
+
26
+ >>> from os import urandom
27
+ >>> aes = Cipher("AES-128-CTR") # Init AES in Counter mode
28
+ >>> key = urandom(16)
29
+ >>> iv = urandom(16)
30
+ >>>
31
+ >>> # Get a CipherOperation object for encryption
32
+ >>> enc = aes.enc(key, iv)
33
+ >>> ref = b"Hello World"
34
+ >>> ciphertext = enc.update(ref)
35
+ >>> ciphertext += enc.finalize()
36
+ >>>
37
+ >>> # Get a CipherOperation object for decryption
38
+ >>> dec = aes.dec(key, iv)
39
+ >>> plaintext = dec.update(ciphertext)
40
+ >>> plaintext += dec.finalize()
41
+ >>> plaintext == ref # Check resulting plaintest matches referece one.
42
+ True
43
+
44
+ """
45
+
46
+ __slots__ = ["alg", "gcm"]
47
+
48
+ def __init__(self, name, _alg=None):
49
+ """Initialize the cipher by name."""
50
+
51
+ if _alg:
52
+ self.alg = _alg
53
+ self.gcm = True
54
+ return
55
+ else:
56
+
57
+ self.alg = _C.EVP_get_cipherbyname(name.encode("utf8"))
58
+ self.gcm = False
59
+ if self.alg == _FFI.NULL:
60
+ raise Exception("Unknown cipher: %s" % name)
61
+
62
+ if "gcm" in name.lower():
63
+ self.gcm = True
64
+
65
+ if "ccm" in name.lower():
66
+ raise Exception("CCM mode not supported")
67
+
68
+ def len_IV(self):
69
+ """Return the Initialization Vector length in bytes."""
70
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
71
+ return int(self.alg.iv_len)
72
+ else:
73
+ return int(_C.EVP_CIPHER_iv_length(self.alg))
74
+
75
+ def len_key(self):
76
+ """Return the secret key length in bytes."""
77
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
78
+ return int(self.alg.key_len)
79
+ else:
80
+ return int(_C.EVP_CIPHER_key_length(self.alg))
81
+
82
+ def len_block(self):
83
+ """Return the block size in bytes."""
84
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
85
+ return int(self.alg.block_size)
86
+ else:
87
+ return int(_C.EVP_CIPHER_block_size(self.alg))
88
+
89
+ def get_nid(self):
90
+ """Return the OpenSSL nid of the cipher and mode."""
91
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
92
+ return int(self.alg.nid)
93
+ else:
94
+ return int(_C.EVP_CIPHER_nid(self.alg))
95
+
96
+ def op(self, key, iv, enc=1):
97
+ """Initializes a cipher operation, either encrypt or decrypt
98
+ and returns a CipherOperation object
99
+
100
+ Args:
101
+ key (str): the block cipher symmetric key. Length depends on block cipher choice.
102
+ iv (str): an Initialization Vector of up to the block size. (Can be shorter.)
103
+ enc (int): set to 1 to perform encryption, or 0 to perform decryption.
104
+
105
+ """
106
+ c_op = CipherOperation(enc)
107
+ _check(len(key) == self.len_key())
108
+ _check(enc in [0, 1])
109
+
110
+ if not self.gcm:
111
+ _check(len(iv) == self.len_IV())
112
+ _check(_C.EVP_CipherInit_ex(c_op.ctx,
113
+ self.alg, _FFI.NULL, key, iv, enc))
114
+
115
+ else:
116
+ _check(_C.EVP_CipherInit_ex(c_op.ctx,
117
+ self.alg, _FFI.NULL, _FFI.NULL, _FFI.NULL, enc))
118
+
119
+ # assert len(iv) <= self.len_block()
120
+
121
+ _check(_C.EVP_CIPHER_CTX_ctrl(c_op.ctx,
122
+ _C.EVP_CTRL_GCM_SET_IVLEN, len(iv), _FFI.NULL))
123
+
124
+ _C.EVP_CIPHER_CTX_ctrl(
125
+ c_op.ctx, _C.EVP_CTRL_GCM_SET_IV_FIXED, -1, iv)
126
+ _C.EVP_CIPHER_CTX_ctrl(c_op.ctx, _C.EVP_CTRL_GCM_IV_GEN, 0, iv)
127
+
128
+ _check(_C.EVP_CipherInit_ex(c_op.ctx,
129
+ _FFI.NULL, _FFI.NULL, key, iv, enc))
130
+
131
+ c_op.cipher = self
132
+ return c_op
133
+
134
+ def enc(self, key, iv):
135
+ """Initializes an encryption engine with the cipher with a specific key and Initialization Vector (IV).
136
+ Returns the CipherOperation engine.
137
+
138
+ Args:
139
+ key (str): the block cipher symmetric key. Length depends on block cipher choice.
140
+ iv (str): an Initialization Vector of up to the block size. (Can be shorter.)
141
+
142
+ """
143
+ return self.op(key, iv, enc=1)
144
+
145
+ def dec(self, key, iv):
146
+ """Initializes a decryption engine with the cipher with a specific key and Initialization Vector (IV).
147
+ Returns the CipherOperation engine.
148
+
149
+ Args:
150
+ key (str): the block cipher symmetric key. Length depends on block cipher choice.
151
+ iv (str): an Initialization Vector of up to the block size. (Can be shorter.)
152
+
153
+ """
154
+ return self.op(key, iv, enc=0)
155
+
156
+ def __del__(self):
157
+ pass
158
+
159
+ # --------- AES GCM special functions ---------------
160
+
161
+ @staticmethod
162
+ def aes_128_gcm():
163
+ """Returns a pre-initalized AES-GCM cipher with 128 bits key size"""
164
+ return Cipher(None, _C.EVP_aes_128_gcm())
165
+
166
+ @staticmethod
167
+ def aes_192_gcm():
168
+ """Returns a pre-initalized AES-GCM cipher with 192 bits key size"""
169
+ return Cipher(None, _C.EVP_aes_192_gcm())
170
+
171
+ @staticmethod
172
+ def aes_256_gcm():
173
+ """Returns a pre-initalized AES-GCM cipher with 256 bits key size"""
174
+ return Cipher(None, _C.EVP_aes_256_gcm())
175
+
176
+ def quick_gcm_enc(self, key, iv, msg, assoc=None, tagl=16):
177
+ """One operation GCM encryption.
178
+
179
+ Args:
180
+ key (str): the AES symmetric key. Length depends on block cipher choice.
181
+ iv (str): an Initialization Vector of up to the block size. (Can be shorter.)
182
+ msg (str): the message to encrypt.
183
+ assoc (str): associated data that will be integrity protected, but not encrypted.
184
+ tagl (int): the length of the tag, up to the block length.
185
+
186
+ Example:
187
+ Use of `quick_gcm_enc` and `quick_gcm_dec` for AES-GCM operations.
188
+
189
+ >>> from os import urandom # Secure OS random source
190
+ >>> aes = Cipher("aes-128-gcm") # Initialize AES-GCM with 128 bit keys
191
+ >>> iv = urandom(16)
192
+ >>> key = urandom(16)
193
+ >>> # Encryption using AES-GCM returns a ciphertext and a tag
194
+ >>> ciphertext, tag = aes.quick_gcm_enc(key, iv, b"Hello")
195
+ >>> # Decrytion using AES-GCM
196
+ >>> p = aes.quick_gcm_dec(key, iv, ciphertext, tag)
197
+ >>> assert p == b'Hello'
198
+
199
+ """
200
+ enc = self.enc(key, iv)
201
+ if assoc:
202
+ enc.update_associated(assoc)
203
+ ciphertext = enc.update(msg)
204
+ ciphertext += enc.finalize()
205
+ tag = enc.get_tag(tagl)
206
+
207
+ return (ciphertext, tag)
208
+
209
+ def quick_gcm_dec(self, key, iv, cip, tag, assoc=None):
210
+ """One operation GCM decrypt. See usage example in "quick_gcm_enc".
211
+ Throws an exception on failure of decryption
212
+
213
+ Args:
214
+ key (str): the AES symmetric key. Length depends on block cipher choice.
215
+ iv (str): an Initialization Vector of up to the block size. (Can be shorter.)
216
+ cip (str): the ciphertext to decrypt.
217
+ tag (int): the integrity tag.
218
+ assoc (str): associated data that will be integrity protected, but not encrypted.
219
+
220
+ """
221
+ dec = self.dec(key, iv)
222
+ if assoc:
223
+ dec.update_associated(assoc)
224
+
225
+ dec.set_tag(tag)
226
+ plain = dec.update(cip)
227
+
228
+ try:
229
+ plain += dec.finalize()
230
+ except BaseException:
231
+ raise Exception("Cipher: decryption failed.")
232
+ return plain
233
+
234
+
235
+ class CipherOperation(object):
236
+
237
+ __slots__ = ["ctx", "cipher", "xenc"]
238
+
239
+ def __init__(self, xenc):
240
+ self.ctx = _C.EVP_CIPHER_CTX_new()
241
+ self.cipher = None
242
+ self.xenc = xenc
243
+
244
+ def update(self, data):
245
+ """Processes some data, and returns a partial result."""
246
+ block_len = self.cipher.len_block()
247
+ alloc_len = len(data) + block_len + 1
248
+ outl = _FFI.new("int *")
249
+ outl[0] = alloc_len
250
+ out = _FFI.new("unsigned char[]", alloc_len)
251
+
252
+ _check(_C.EVP_CipherUpdate(self.ctx, out, outl, data, len(data)))
253
+
254
+ ret = bytes(_FFI.buffer(out)[:int(outl[0])])
255
+ return ret
256
+
257
+ def finalize(self):
258
+ """Finalizes the operation and may return some additional data.
259
+ Throws an exception if the authenticator tag is different from the expected value.
260
+
261
+ Example:
262
+ Example of the exception thrown when an invalid tag is provided.
263
+
264
+ >>> from os import urandom
265
+ >>> aes = Cipher.aes_128_gcm() # Define an AES-GCM cipher
266
+ >>> iv = urandom(16)
267
+ >>> key = urandom(16)
268
+ >>> ciphertext, tag = aes.quick_gcm_enc(key, iv, b"Hello")
269
+ >>>
270
+ >>> dec = aes.dec(key, iv) # Get a decryption CipherOperation
271
+ >>> dec.set_tag(urandom(len(tag))) # Provide an invalid tag.
272
+ >>> plaintext = dec.update(ciphertext) # Feed in the ciphertext for decryption.
273
+ >>> try:
274
+ ... dec.finalize() # Check and Finalize.
275
+ ... except:
276
+ ... print("Failure")
277
+ Failure
278
+
279
+ Throws an exception since integrity check fails due to the invalid tag.
280
+
281
+ """
282
+ block_len = self.cipher.len_block()
283
+ alloc_len = block_len
284
+ outl = _FFI.new("int *")
285
+ outl[0] = alloc_len
286
+ out = _FFI.new("unsigned char[]", alloc_len)
287
+
288
+ try:
289
+ _check(_C.EVP_CipherFinal_ex(self.ctx, out, outl))
290
+ if outl[0] == 0:
291
+ return b''
292
+
293
+ ret = bytes(_FFI.buffer(out)[:int(outl[0])])
294
+ return ret
295
+ except BaseException:
296
+ raise Exception("Cipher: decryption failed.")
297
+
298
+ def update_associated(self, data):
299
+ """Processes some GCM associated data, and returns nothing."""
300
+
301
+ if self.xenc == 0:
302
+ self.set_tag(b"\00" * 16)
303
+
304
+ outl = _FFI.new("int *")
305
+ _check(_C.EVP_CipherUpdate(self.ctx, _FFI.NULL, outl, data, len(data)))
306
+ _check(outl[0] == len(data))
307
+
308
+ def get_tag(self, tag_len=16):
309
+ """Get the GCM authentication tag. Execute after finalizing the encryption.
310
+
311
+ Example:
312
+ AES-GCM encryption usage:
313
+
314
+ >>> from os import urandom
315
+ >>> aes = Cipher.aes_128_gcm() # Initialize AES cipher
316
+ >>> key = urandom(16)
317
+ >>> iv = urandom(16)
318
+ >>> enc = aes.enc(key, iv) # Get an encryption CipherOperation
319
+ >>> enc.update_associated(b"Hello") # Include some associated data
320
+ >>> ciphertext = enc.update(b"World!") # Include some plaintext
321
+ >>> nothing = enc.finalize() # Finalize
322
+ >>> tag = enc.get_tag(16) # Get the AES-GCM tag
323
+
324
+ """
325
+ tag = _FFI.new("unsigned char []", tag_len)
326
+ ret = _C.EVP_CIPHER_CTX_ctrl(
327
+ self.ctx, _C.EVP_CTRL_GCM_GET_TAG, tag_len, tag)
328
+ _check(ret)
329
+ s = bytes(_FFI.buffer(tag)[:])
330
+ return s
331
+
332
+ def set_tag(self, tag):
333
+ """Specify the GCM authenticator tag. Must be done before finalizing decryption
334
+
335
+ Example:
336
+ AES-GCM decryption and check:
337
+
338
+ >>> aes = Cipher.aes_128_gcm() # Define an AES-GCM cipher
339
+ >>> ciphertext, tag = (b'dV\\xb9:\\xd0\\xbe', b'pA\\xbe?\\xfc\\xd1&\\x03\\x1438\\xc5\\xf8In\\xaa')
340
+ >>> dec = aes.dec(key=b"A"*16, iv=b"A"*16) # Get a decryption CipherOperation
341
+ >>> dec.update_associated(b"Hello") # Feed in the non-secret assciated data.
342
+ >>> plaintext = dec.update(ciphertext) # Feed in the ciphertext for decryption.
343
+ >>> dec.set_tag(tag) # Provide the AES-GCM tag for integrity.
344
+ >>> nothing = dec.finalize() # Check and finalize.
345
+ >>> assert plaintext == b'World!'
346
+
347
+ """
348
+ _check(
349
+ _C.EVP_CIPHER_CTX_ctrl(
350
+ self.ctx,
351
+ _C.EVP_CTRL_GCM_SET_TAG,
352
+ len(tag),
353
+ tag))
354
+
355
+ def __del__(self):
356
+ _C.EVP_CIPHER_CTX_free(self.ctx)
357
+
358
+
359
+ # When testing ignore extra variables
360
+ # pylint: disable=unused-variable,redefined-outer-name
361
+
362
+ def test_aes_init():
363
+ aes = Cipher("AES-128-CBC")
364
+ assert aes.alg != _FFI.NULL
365
+ assert aes.len_IV() == 16
366
+ assert aes.len_block() == 16
367
+ assert aes.len_key() == 16
368
+ assert aes.get_nid() == 419
369
+ del aes
370
+
371
+
372
+ def test_errors():
373
+ with pytest.raises(Exception) as excinfo:
374
+ aes = Cipher("AES-128-XXF")
375
+ assert 'Unknown' in str(excinfo.value)
376
+
377
+
378
+ def test_aes_enc():
379
+ aes = Cipher("AES-128-CBC")
380
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
381
+
382
+ ref = b"Hello World" * 10000
383
+
384
+ ciphertext = enc.update(ref)
385
+ ciphertext += enc.finalize()
386
+
387
+ dec = aes.op(key=b"A" * 16, iv=b"A" * 16, enc=0)
388
+ plaintext = dec.update(ciphertext)
389
+ plaintext += dec.finalize()
390
+ assert plaintext == ref
391
+
392
+
393
+ def test_aes_ctr():
394
+ aes = Cipher("AES-128-CTR")
395
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
396
+
397
+ ref = b"Hello World" * 10000
398
+
399
+ ciphertext = enc.update(ref)
400
+ ciphertext += enc.finalize()
401
+
402
+ dec = aes.op(key=b"A" * 16, iv=b"A" * 16, enc=0)
403
+ plaintext = dec.update(ciphertext)
404
+ plaintext += dec.finalize()
405
+ assert plaintext == ref
406
+
407
+
408
+ def test_aes_ops():
409
+ aes = Cipher("AES-128-CTR")
410
+ enc = aes.enc(key=b"A" * 16, iv=b"A" * 16)
411
+
412
+ ref = b"Hello World" * 10000
413
+
414
+ ciphertext = enc.update(ref)
415
+ ciphertext += enc.finalize()
416
+
417
+ dec = aes.dec(key=b"A" * 16, iv=b"A" * 16)
418
+ plaintext = dec.update(ciphertext)
419
+ plaintext += dec.finalize()
420
+ assert plaintext == ref
421
+
422
+
423
+ def test_aes_gcm_encrypt():
424
+ aes = Cipher.aes_128_gcm()
425
+ assert aes.gcm
426
+
427
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
428
+
429
+ enc.update_associated(b"Hello")
430
+ ciphertext = enc.update(b"World!")
431
+ c2 = enc.finalize()
432
+ assert c2 == b''
433
+
434
+ tag = enc.get_tag(16)
435
+ assert len(tag) == 16
436
+
437
+
438
+ def test_aes_gcm_encrypt_192():
439
+ aes = Cipher.aes_192_gcm()
440
+ assert aes.gcm
441
+
442
+ enc = aes.op(key=b"A" * 24, iv=b"A" * 16)
443
+
444
+ enc.update_associated(b"Hello")
445
+ ciphertext = enc.update(b"World!")
446
+ c2 = enc.finalize()
447
+ assert c2 == b''
448
+
449
+ tag = enc.get_tag(16)
450
+ assert len(tag) == 16
451
+
452
+
453
+ def test_aes_gcm_encrypt_256():
454
+ aes = Cipher.aes_256_gcm()
455
+ assert aes.gcm
456
+
457
+ enc = aes.op(key=b"A" * 32, iv=b"A" * 16)
458
+
459
+ enc.update_associated(b"Hello")
460
+ ciphertext = enc.update(b"World!")
461
+ c2 = enc.finalize()
462
+ assert c2 == b''
463
+
464
+ tag = enc.get_tag(16)
465
+ assert len(tag) == 16
466
+
467
+
468
+ @pytest.fixture
469
+ def aesenc():
470
+ aes = Cipher.aes_128_gcm()
471
+ assert aes.gcm
472
+
473
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
474
+
475
+ enc.update_associated(b"Hello")
476
+ ciphertext = enc.update(b"World!")
477
+ c2 = enc.finalize()
478
+ assert c2 == b''
479
+
480
+ tag = enc.get_tag(16)
481
+ assert len(tag) == 16
482
+
483
+ return (aes, enc, ciphertext, tag)
484
+
485
+
486
+ def test_gcm_dec(aesenc):
487
+ aes, enc, ciphertext, tag = aesenc
488
+ dec = aes.dec(key=b"A" * 16, iv=b"A" * 16)
489
+ dec.update_associated(b"Hello")
490
+ plaintext = dec.update(ciphertext)
491
+
492
+ dec.set_tag(tag)
493
+
494
+ dec.finalize()
495
+
496
+ assert plaintext == b"World!"
497
+
498
+
499
+ def test_gcm_dec_badassoc(aesenc):
500
+ aes, enc, ciphertext, tag = aesenc
501
+
502
+ dec = aes.dec(key=b"A" * 16, iv=b"A" * 16)
503
+ dec.update_associated(b"H4llo")
504
+ plaintext = dec.update(ciphertext)
505
+
506
+ dec.set_tag(tag)
507
+
508
+ with pytest.raises(Exception) as excinfo:
509
+ dec.finalize()
510
+ assert "Cipher" in str(excinfo.value)
511
+
512
+
513
+ def test_gcm_dec_badkey(aesenc):
514
+ aes, enc, ciphertext, tag = aesenc
515
+
516
+ dec = aes.dec(key=b"B" * 16, iv=b"A" * 16)
517
+ dec.update_associated(b"Hello")
518
+ plaintext = dec.update(ciphertext)
519
+
520
+ dec.set_tag(tag)
521
+
522
+ with pytest.raises(Exception) as excinfo:
523
+ dec.finalize()
524
+ assert "Cipher" in str(excinfo.value)
525
+
526
+
527
+ def test_gcm_dec_badiv(aesenc):
528
+ aes, enc, ciphertext, tag = aesenc
529
+ dec = aes.dec(key=b"A" * 16, iv=b"B" * 16)
530
+ dec.update_associated(b"Hello")
531
+ plaintext = dec.update(ciphertext)
532
+
533
+ dec.set_tag(tag)
534
+
535
+ with pytest.raises(Exception) as excinfo:
536
+ dec.finalize()
537
+ assert "Cipher" in str(excinfo.value)
538
+
539
+
540
+ def test_aes_gcm_byname():
541
+ aes = Cipher("aes-128-gcm")
542
+ assert aes.gcm
543
+
544
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
545
+
546
+ enc.update_associated(b"Hello")
547
+ ciphertext = enc.update(b"World!")
548
+ c2 = enc.finalize()
549
+ assert c2 == b''
550
+
551
+ tag = enc.get_tag(16)
552
+ assert len(tag) == 16
553
+
554
+ dec = aes.dec(key=b"A" * 16, iv=b"A" * 16)
555
+ dec.update_associated(b"Hello")
556
+ plaintext = dec.update(ciphertext)
557
+
558
+ dec.set_tag(tag)
559
+
560
+ dec.finalize()
561
+
562
+ assert plaintext == b"World!"
563
+
564
+
565
+ def test_aes_gcm_different_IV():
566
+ aes = Cipher("aes-128-gcm")
567
+
568
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
569
+ enc.update_associated(b"Hello")
570
+ ciphertext = enc.update(b"World!")
571
+ c2 = enc.finalize()
572
+ tag = enc.get_tag(16)
573
+
574
+ enc = aes.op(key=b"A" * 16, iv=b"A" * 16)
575
+ enc.update_associated(b"Hello")
576
+ ciphertext2 = enc.update(b"World!")
577
+ c2 = enc.finalize()
578
+ tag2 = enc.get_tag(16)
579
+
580
+ enc = aes.op(key=b"A" * 16, iv=b"B" * 16)
581
+ enc.update_associated(b"Hello")
582
+ ciphertext3 = enc.update(b"World!")
583
+ c2 = enc.finalize()
584
+ tag3 = enc.get_tag(16)
585
+
586
+ assert ciphertext == ciphertext2
587
+ assert ciphertext != ciphertext3
588
+
589
+
590
+ def test_quick():
591
+ aes = Cipher("aes-128-gcm")
592
+ c, t = aes.quick_gcm_enc(b"A" * 16, b"A" * 16, b"Hello")
593
+ p = aes.quick_gcm_dec(b"A" * 16, b"A" * 16, c, t)
594
+ assert p == b"Hello"
595
+
596
+
597
+ def test_quick_assoc():
598
+ aes = Cipher("aes-128-gcm")
599
+ c, t = aes.quick_gcm_enc(b"A" * 16, b"A" * 16, b"Hello", assoc=b"blah")
600
+ p = aes.quick_gcm_dec(b"A" * 16, b"A" * 16, c, t, assoc=b"blah")
601
+ assert p == b"Hello"
602
+
603
+ # pylint: enable=unused-variable,redefined-outer-name
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/compile.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import platform
5
+ import cffi
6
+
7
+
8
+ CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
9
+ OPENSSL_BINDINGS_PATH = os.path.join(CURRENT_PATH, '_cffi_src/openssl')
10
+ COMPAT_FILE_PATH = os.path.join(CURRENT_PATH, '_compat.py')
11
+
12
+
13
+ # Load the OpenSSL version utility.
14
+ with open(COMPAT_FILE_PATH) as compat_file:
15
+ exec(compat_file.read()) # pylint: disable=exec-used
16
+
17
+
18
+ if platform.system() == "Windows":
19
+ # Windows building instructions:
20
+ # * Ensure you compile with a 64bit lib and toolchain
21
+ # (run vcvarsx86_amd64.bat)
22
+ # * Ensure the OpenSSL 64 bit lib is on the path.
23
+ # (PATH=C:\OpenSSL-Win64\bin;%PATH%)
24
+ libraries = ["libeay32"]
25
+ include_dirs = [r"."]
26
+ extra_compile_args = []
27
+
28
+ # if "VCINSTALLDIR" not in os.environ:
29
+ # raise Exception(r"Cannot find the Visual Studio %VCINSTALLDIR% variable. Ensure you ran the appropriate vcvars.bat script.")
30
+
31
+ # if "OPENSSL_CONF" not in os.environ:
32
+ # raise Exception(r"Cannot find the Visual Studio %OPENSSL_CONF% variable. Ensure you install OpenSSL for Windows.")
33
+
34
+ openssl_conf = os.environ["OPENSSL_CONF"]
35
+ openssl_bin, conf_name = os.path.split(openssl_conf)
36
+ openssl_base, bin_name = os.path.split(openssl_bin)
37
+ assert bin_name == "bin"
38
+ include_dirs += [os.path.join(openssl_base, "include")]
39
+ library_dirs = [
40
+ openssl_base, os.path.join(
41
+ openssl_base, "lib"), os.path.join(
42
+ openssl_base, "bin")]
43
+ link_args = []
44
+
45
+ else:
46
+ # Asume we are running on a posix system
47
+ # LINUX: libraries=["crypto"],
48
+ # extra_compile_args=['-Wno-deprecated-declarations']
49
+ link_args = []
50
+ libraries = ["crypto"]
51
+ extra_compile_args = ['-Wno-deprecated-declarations']
52
+ if platform.system() == "Darwin":
53
+ include_dirs = ['/usr/local/opt/openssl@1.1/include',
54
+ '/usr/local/opt/openssl/include',
55
+ '/usr/local/ssl/include']
56
+ library_dirs = ['/usr/local/opt/openssl@1.1/lib',
57
+ '/usr/local/opt/openssl/lib',
58
+ '/usr/local/ssl/lib']
59
+
60
+ # Ensure that our dynamic ABI-based version finding code in
61
+ # _compat.get_openssl_version also tries to load the
62
+ # brew-installed openssl libraries first.
63
+ os.environ["DYLD_LIBRARY_PATH"] = str.join(":", library_dirs)
64
+ else:
65
+ include_dirs = []
66
+ library_dirs = []
67
+ # link_args = ['libcrypto.so']
68
+
69
+
70
+ def get_openssl_bindings(filename):
71
+ src_path = os.path.join(OPENSSL_BINDINGS_PATH, filename)
72
+ with open(src_path) as src_file:
73
+ return src_file.read()
74
+
75
+
76
+ openssl_version_code = get_openssl_version(warn=True) # pylint: disable=undefined-variable
77
+ openssl_bindings_defs = get_openssl_bindings(
78
+ 'openssl_v%s.h' % openssl_version_code)
79
+ openssl_bindings_src = get_openssl_bindings(
80
+ 'openssl_v%s.c' % openssl_version_code)
81
+
82
+ _FFI = cffi.FFI()
83
+ _FFI.set_source("petlib._petlib", openssl_bindings_src,
84
+ libraries=libraries,
85
+ extra_compile_args=extra_compile_args,
86
+ include_dirs=include_dirs,
87
+ library_dirs=library_dirs,
88
+ extra_link_args=link_args)
89
+ _FFI.cdef(openssl_bindings_defs)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ print("Compiling petlib for OpenSSL version %s..." % openssl_version_code)
94
+ _FFI.compile()
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/ec.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bindings import _FFI, _C, Const
2
+ from .bn import Bn, force_Bn, get_ctx
3
+
4
+ from copy import copy
5
+ from binascii import hexlify
6
+ from hashlib import sha512
7
+
8
+ try:
9
+ from builtins import int # pylint: disable=redefined-builtin
10
+ from builtins import object # pylint: disable=redefined-builtin
11
+ except BaseException: # pylint: disable=bare-except
12
+ print('Cannot mock for docs')
13
+
14
+ try:
15
+ from future.utils import python_2_unicode_compatible
16
+ except Exception: # pylint: disable=broad-except
17
+ # An identity decorator
18
+ def python_2_unicode_compatible(x): return x
19
+
20
+ import pytest
21
+
22
+ _debug = True
23
+
24
+
25
+ def _check(return_val):
26
+ """Checks the return code of the C calls"""
27
+ if __debug__:
28
+ if isinstance(return_val, int) and return_val == 1:
29
+ return
30
+ if isinstance(return_val, bool) and return_val == True:
31
+ return
32
+
33
+ if return_val == 1 or return_val == True:
34
+ return
35
+
36
+ raise Exception("EC exception")
37
+
38
+
39
+ class EcGroup(object):
40
+
41
+ @staticmethod
42
+ def list_curves():
43
+ """Return a dictionary of name id (int) to curve names (str).
44
+
45
+ Example:
46
+ >>> curves = EcGroup.list_curves()
47
+ >>> curves[713]
48
+ 'NIST/SECG curve over a 224 bit prime field'
49
+
50
+ """
51
+ size_t = int(_C.EC_get_builtin_curves(_FFI.NULL, 0))
52
+ _check(0 < size_t)
53
+ names = _FFI.new("EC_builtin_curve[]", size_t)
54
+ _C.EC_get_builtin_curves(names, size_t)
55
+
56
+ all_curves = []
57
+ for i in range(size_t):
58
+ all_curves += [(int(names[i].nid),
59
+ str(_FFI.string(names[i].comment).decode("utf8")))]
60
+ return dict(all_curves)
61
+
62
+ def __init__(self, nid=713, optimize_mult=True):
63
+ """Build an EC group from the Open SSL nid. By default use NIST p224, which in OpenSSL 64bit supports constant-time operations."""
64
+ self.ecg = _C.EC_GROUP_new_by_curve_name(nid)
65
+
66
+ self.gen = None
67
+ self.ord = None
68
+ self.inf = None
69
+
70
+ if optimize_mult:
71
+ _check(_C.EC_GROUP_precompute_mult(self.ecg, get_ctx().bnctx))
72
+
73
+ def parameters(self):
74
+ """Returns a dictionary with the parameters (a,b and p) of the curve.
75
+
76
+ Example:
77
+ >>> params = EcGroup(713).parameters()
78
+ >>> params["a"]
79
+ 26959946667150639794667015087019630673557916260026308143510066298878
80
+ >>> params["b"]
81
+ 18958286285566608000408668544493926415504680968679321075787234672564
82
+ >>> params["p"]
83
+ 26959946667150639794667015087019630673557916260026308143510066298881
84
+
85
+ """
86
+ p, a, b = Bn(), Bn(), Bn()
87
+ _check(
88
+ _C.EC_GROUP_get_curve_GFp(
89
+ self.ecg,
90
+ p.bn,
91
+ a.bn,
92
+ b.bn,
93
+ get_ctx().bnctx))
94
+ return {"p": p, "a": a, "b": b}
95
+
96
+ def generator(self):
97
+ """Returns the generator of the EC group."""
98
+
99
+ if self.gen is None:
100
+ g = EcPt(self)
101
+ internal_g = _C.EC_GROUP_get0_generator(self.ecg)
102
+ _check(_C.EC_POINT_copy(g.pt, internal_g))
103
+ self.gen = g
104
+
105
+ return self.gen
106
+
107
+ def infinite(self):
108
+ """Returns a point at infinity.
109
+
110
+ Example:
111
+ >>> G = EcGroup()
112
+ >>> G.generator() + G.infinite() == G.generator() ## Should hold.
113
+ True
114
+
115
+ """
116
+ if self.inf is None:
117
+ zero = EcPt(self)
118
+ _check(_C.EC_POINT_set_to_infinity(self.ecg, zero.pt))
119
+ self.inf = zero
120
+ return self.inf
121
+
122
+ def order(self):
123
+ """Returns the order of the group as a Big Number.
124
+
125
+ Example:
126
+ >>> G = EcGroup()
127
+ >>> G.order() * G.generator() == G.infinite() ## Should hold.
128
+ True
129
+
130
+ """
131
+
132
+ if self.ord is None:
133
+ o = Bn()
134
+ _check(_C.EC_GROUP_get_order(self.ecg, o.bn, get_ctx().bnctx))
135
+ self.ord = o
136
+
137
+ return self.ord
138
+
139
+ def sum(self, elems):
140
+ """ Sum efficiently a number of elements """
141
+
142
+ result = copy(elems[0]) # EcPt(self)
143
+
144
+ for el in elems[1:]:
145
+ err = _C.EC_POINT_add(
146
+ self.ecg,
147
+ result.pt,
148
+ result.pt,
149
+ el.pt,
150
+ get_ctx().bnctx)
151
+
152
+ if __debug__:
153
+ _check(err)
154
+
155
+ return result
156
+
157
+ def wsum(self, weights, elems):
158
+ """ Sum efficiently a number of elements each multiplied by a bn in weights """
159
+
160
+ res = EcPt(self)
161
+
162
+ if __debug__:
163
+ assert len(weights) == len(elems)
164
+ assert all(isinstance(e, Bn) for e in weights)
165
+ assert all(isinstance(e, EcPt) for e in elems)
166
+
167
+ all_ws = [e.bn for e in weights]
168
+ all_es = [e.pt for e in elems]
169
+ err = _C.EC_POINTs_mul(
170
+ self.ecg,
171
+ res.pt,
172
+ _FFI.NULL,
173
+ len(all_es),
174
+ all_es,
175
+ all_ws,
176
+ get_ctx().bnctx)
177
+
178
+ if __debug__:
179
+ _check(err)
180
+
181
+ return res
182
+
183
+ def __eq__(self, other):
184
+ res = _C.EC_GROUP_cmp(self.ecg, other.ecg, get_ctx().bnctx)
185
+ return res == 0
186
+
187
+ def __ne__(self, other):
188
+ return not self.__eq__(other)
189
+
190
+ def __repr__(self):
191
+ return "EcGroup(%s)" % self.nid()
192
+
193
+ def nid(self):
194
+ """Returns the Open SSL group ID"""
195
+ return int(_C.EC_GROUP_get_curve_name(self.ecg))
196
+
197
+ def __del__(self):
198
+ if _C:
199
+ _C.EC_GROUP_free(self.ecg)
200
+
201
+ def check_point(self, pt):
202
+ """Ensures the point is on the curve.
203
+
204
+ Example:
205
+ >>> G = EcGroup()
206
+ >>> G.check_point(G.generator())
207
+ True
208
+ >>> G.check_point(G.infinite())
209
+ True
210
+
211
+ """
212
+ res = int(_C.EC_POINT_is_on_curve(self.ecg, pt.pt, get_ctx().bnctx))
213
+ return res == 1
214
+
215
+ def hash_to_point(self, hinput):
216
+ """Hash a string into an EC Point."""
217
+ p = self.parameters()["p"]
218
+
219
+ pt = EcPt(self)
220
+ xhash = hinput
221
+ y = 1
222
+ ret = 0
223
+
224
+ while ret == 0:
225
+ xhash = sha512(xhash).digest()
226
+ x = Bn.from_binary(xhash) % p
227
+ ret = _C.EC_POINT_set_compressed_coordinates_GFp(
228
+ self.ecg, pt.pt, x.bn, y, get_ctx().bnctx)
229
+
230
+ assert self.check_point(pt)
231
+ _check(ret)
232
+ return pt
233
+
234
+ def get_points_from_x(self, x):
235
+ """ Returns the two EC points with the given x coordinate. """
236
+
237
+ pt0 = EcPt(self)
238
+ pt1 = EcPt(self)
239
+
240
+ ret0 = _C.EC_POINT_set_compressed_coordinates_GFp(
241
+ self.ecg, pt0.pt, x.bn, True, get_ctx().bnctx)
242
+ ret1 = _C.EC_POINT_set_compressed_coordinates_GFp(
243
+ self.ecg, pt1.pt, x.bn, False, get_ctx().bnctx)
244
+
245
+ assert self.check_point(pt0) and self.check_point(pt1)
246
+ _check(ret0)
247
+ _check(ret1)
248
+
249
+ return (pt0, pt1)
250
+
251
+
252
+ # Class constants
253
+ try:
254
+ POINT_CONVERSION_UNCOMPRESSED = _C.POINT_CONVERSION_UNCOMPRESSED
255
+ POINT_CONVERSION_COMPRESSED = _C.POINT_CONVERSION_COMPRESSED
256
+ except BaseException:
257
+ POINT_CONVERSION_UNCOMPRESSED = None
258
+ POINT_CONVERSION_COMPRESSED = None
259
+
260
+
261
+ @python_2_unicode_compatible
262
+ class EcPt(object):
263
+ """An EC point, supporting point addition, doubling
264
+ and multiplication with a scalar
265
+ """
266
+ __slots__ = ["pt", "group"]
267
+
268
+ @staticmethod
269
+ def from_binary(sbin, group):
270
+ """Create a point from a byte sequence.
271
+
272
+ Example:
273
+ >>> G = EcGroup()
274
+ >>> byte_string = G.generator().export() # Export EC point as byte string
275
+ >>> EcPt.from_binary(byte_string, G) == G.generator() # Import EC point from binary string
276
+ True
277
+
278
+ """
279
+ new_pt = EcPt(group)
280
+ err = _C.EC_POINT_oct2point(
281
+ group.ecg,
282
+ new_pt.pt,
283
+ sbin,
284
+ len(sbin),
285
+ get_ctx().bnctx)
286
+ _check(err)
287
+
288
+ return new_pt
289
+
290
+ def __init__(self, group):
291
+ self.group = group
292
+ self.pt = _C.EC_POINT_new(group.ecg)
293
+
294
+ def __copy__(self):
295
+ new_point = EcPt(self.group)
296
+ err = _C.EC_POINT_copy(new_point.pt, self.pt)
297
+ if __debug__:
298
+ _check(err)
299
+ return new_point
300
+
301
+ def pt_add(self, other):
302
+ """Adds two points together. Synonym with self + other.
303
+
304
+ Example:
305
+ >>> g = EcGroup().generator()
306
+ >>> g.pt_add(g) == (g + g) == (2 * g) == g.pt_double() # Equivalent formulations
307
+ True
308
+ """
309
+ return self.__add__(other)
310
+
311
+ def pt_add_inplace(self, other):
312
+ """Adds two points together and puts the result in self.pt.
313
+
314
+ """
315
+ return self.__add_inplace__(other)
316
+
317
+ def __add__(self, other):
318
+ if __debug__:
319
+ _check(isinstance(other, EcPt))
320
+ _check(other.group == self.group)
321
+
322
+ result = EcPt(self.group)
323
+ err = _C.EC_POINT_add(
324
+ self.group.ecg,
325
+ result.pt,
326
+ self.pt,
327
+ other.pt,
328
+ get_ctx().bnctx)
329
+
330
+ if __debug__:
331
+ _check(err)
332
+
333
+ return result
334
+
335
+ def __add_inplace__(self, other):
336
+ if __debug__:
337
+ _check(isinstance(other, EcPt))
338
+ _check(other.group == self.group)
339
+
340
+ err = _C.EC_POINT_add(
341
+ self.group.ecg,
342
+ self.pt,
343
+ self.pt,
344
+ other.pt,
345
+ _FFI.NULL)
346
+
347
+ if __debug__:
348
+ _check(err)
349
+
350
+ def pt_double(self):
351
+ """Doubles the point. equivalent to "self + self"."""
352
+ result = EcPt(self.group)
353
+ _check(
354
+ _C.EC_POINT_dbl(
355
+ self.group.ecg,
356
+ result.pt,
357
+ self.pt,
358
+ get_ctx().bnctx))
359
+ return result
360
+
361
+ def pt_double_inplace(self):
362
+ """Doubles the point and mutates it to hold the result."""
363
+ _check(
364
+ _C.EC_POINT_dbl(
365
+ self.group.ecg,
366
+ self.pt,
367
+ self.pt,
368
+ get_ctx().bnctx))
369
+
370
+ def pt_neg(self):
371
+ """Returns the negative of the point. Synonym with -self.
372
+
373
+ Example:
374
+ >>> G = EcGroup()
375
+ >>> g = G.generator()
376
+ >>> g + (-g) == G.infinite() # Unary negative operator.
377
+ True
378
+ >>> g - g == G.infinite() # Binary negative operator.
379
+ True
380
+
381
+ """
382
+ return self.__neg__()
383
+
384
+ def pt_neg_inplace(self):
385
+ """Mutates the point to hold the negative value of the point.
386
+
387
+ """
388
+ return self.__neg_inplace__()
389
+
390
+ def __sub__(self, other):
391
+ # """ Simulates (abuses notation) subtraction as addition with a negative point."""
392
+ return self + (-other)
393
+
394
+ def __neg__(self):
395
+ # result = copy(self)
396
+
397
+ result = EcPt(self.group)
398
+ err = _C.EC_POINT_copy(result.pt, self.pt)
399
+ if __debug__:
400
+ _check(err)
401
+
402
+ err = _C.EC_POINT_invert(self.group.ecg, result.pt, get_ctx().bnctx)
403
+ if __debug__:
404
+ _check(err)
405
+ return result
406
+
407
+ def __neg_inplace__(self):
408
+ # result = copy(self)
409
+
410
+ err = _C.EC_POINT_invert(self.group.ecg, self.pt, get_ctx().bnctx)
411
+ if __debug__:
412
+ _check(err)
413
+
414
+ def pt_mul(self, scalar):
415
+ """Returns the product of the point with a scalar (not commutative). Synonym with scalar * self.
416
+
417
+ Example:
418
+ >>> G = EcGroup()
419
+ >>> g = G.generator()
420
+ >>> 100 * g == g.pt_mul(100) # Operator and function notation mean the same
421
+ True
422
+ >>> G.order() * g == G.infinite() # Scalar mul. by the order returns the identity element.
423
+ True
424
+
425
+ """
426
+ return self.__rmul__(scalar)
427
+
428
+ def pt_mul_inplace(self, scalar):
429
+ """ Multiplies a scalar with a point and mutates the point to hold the result.
430
+
431
+ """
432
+ return self.__rmul_inplace__(scalar)
433
+
434
+ # @force_Bn(1)
435
+ def __rmul__(self, other):
436
+ try:
437
+ result = EcPt(self.group)
438
+ err = _C.EC_POINT_mul(
439
+ self.group.ecg,
440
+ result.pt,
441
+ _FFI.NULL,
442
+ self.pt,
443
+ other.bn,
444
+ get_ctx().bnctx)
445
+ if __debug__:
446
+ _check(err)
447
+ return result
448
+ except AttributeError:
449
+ return self.__rmul__(Bn.from_num(other))
450
+
451
+ # @force_Bn(1)
452
+ def __rmul_inplace__(self, other):
453
+ try:
454
+ err = _C.EC_POINT_mul(
455
+ self.group.ecg,
456
+ self.pt,
457
+ _FFI.NULL,
458
+ self.pt,
459
+ other.bn,
460
+ _FFI.NULL)
461
+ if __debug__:
462
+ _check(err)
463
+ except AttributeError:
464
+ return self.__rmul_inplace__(Bn.from_num(other))
465
+
466
+ def pt_eq(self, other):
467
+ """Returns a boolean denoting whether the points are equal. Synonym with self == other.
468
+
469
+ Example:
470
+ >>> G = EcGroup()
471
+ >>> g = G.generator()
472
+ >>> 40 * g + 60 * g == 100 * g
473
+ True
474
+ >>> g == 2 * g
475
+ False
476
+
477
+ """
478
+ return self.__eq__(other)
479
+
480
+ def __eq__(self, other):
481
+ if __debug__:
482
+ _check(isinstance(other, EcPt))
483
+ _check(other.group == self.group)
484
+ r = int(
485
+ _C.EC_POINT_cmp(
486
+ self.group.ecg,
487
+ self.pt,
488
+ other.pt,
489
+ get_ctx().bnctx))
490
+ return r == 0
491
+
492
+ def __ne__(self, other):
493
+ return not self.__eq__(other)
494
+
495
+ def __del__(self):
496
+ if _C:
497
+ _C.EC_POINT_clear_free(self.pt)
498
+
499
+ def __hash__(self):
500
+ return self.export().__hash__()
501
+
502
+ def export(self, form=POINT_CONVERSION_COMPRESSED):
503
+ """export(form=POINT_CONVERSION_COMPRESSED)
504
+
505
+ Returns a string binary representation of the point in compressed coordinates.
506
+
507
+ Example:
508
+ >>> G = EcGroup()
509
+ >>> byte_string = G.generator().export()
510
+ >>> print(hexlify(byte_string).decode("utf8"))
511
+ 02b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21
512
+
513
+ """
514
+ size = _C.EC_POINT_point2oct(self.group.ecg, self.pt, form,
515
+ _FFI.NULL, 0, get_ctx().bnctx)
516
+ buf = _FFI.new("unsigned char[]", size)
517
+ _C.EC_POINT_point2oct(self.group.ecg, self.pt, form,
518
+ buf, size, get_ctx().bnctx)
519
+ output = bytes(_FFI.buffer(buf)[:])
520
+ return output
521
+
522
+ def is_infinite(self):
523
+ """Returns True if this point is at infinity, otherwise False.
524
+
525
+ Example:
526
+ >>> G = EcGroup()
527
+ >>> g, o = G.generator(), G.order()
528
+ >>> (o * g).is_infinite()
529
+ True
530
+
531
+ """
532
+ return self == self.group.infinite()
533
+
534
+ def get_affine(self):
535
+ """Return the affine coordinates (x,y) of this EC Point.
536
+
537
+ Example:
538
+ >>> G = EcGroup()
539
+ >>> g = G.generator()
540
+ >>> x, y = g.get_affine()
541
+ >>> x
542
+ 19277929113566293071110308034699488026831934219452440156649784352033
543
+ >>> y
544
+ 19926808758034470970197974370888749184205991990603949537637343198772
545
+
546
+ """
547
+ if self == self.group.infinite():
548
+ raise Exception("EC Infinity has no affine coordinates.")
549
+ x = Bn()
550
+ y = Bn()
551
+ _check(_C.EC_POINT_get_affine_coordinates_GFp(self.group.ecg,
552
+ self.pt, x.bn, y.bn, get_ctx().bnctx))
553
+ return (x, y)
554
+
555
+ def __str__(self):
556
+ return hexlify(self.export()).decode("utf8")
557
+
558
+ def __repr__(self):
559
+ return "EcPt(%s)" % self.__str__()
560
+
561
+
562
+ # Ignore some lint warning in tests
563
+ # pylint: disable=unused-variable
564
+
565
+ def test_ec_list_group():
566
+ c = EcGroup.list_curves()
567
+ assert len(c) > 0
568
+ assert 713 in c
569
+ assert 410 in c
570
+
571
+
572
+ def test_ec_build_group():
573
+ G = EcGroup(409)
574
+ assert G.nid() == 409
575
+ H = EcGroup(410)
576
+ assert G.check_point(G.generator())
577
+ assert not H.check_point(G.generator())
578
+ order = G.order()
579
+ assert str(
580
+ order) == "6277101735386680763835789423176059013767194773182842284081"
581
+ assert G == G
582
+ assert not (G == H)
583
+ assert G != H
584
+ assert not (G != G)
585
+ assert "a" in G.parameters()
586
+
587
+ h1 = G.hash_to_point(b"Hello2")
588
+
589
+
590
+ def test_ec_from_x():
591
+ G = EcGroup(409)
592
+
593
+ g = G.generator()
594
+ x, y = g.get_affine()
595
+
596
+ g1, g2 = G.get_points_from_x(x)
597
+ assert g == g1 or g == g2
598
+
599
+
600
+ def test_ec_arithmetic():
601
+ G = EcGroup(713)
602
+ g = G.generator()
603
+ assert g + g == g + g
604
+ assert g + g == g.pt_double()
605
+ assert g + g == Bn(2) * g
606
+ assert g + g == 2 * g
607
+
608
+ assert g + g != g + g + g
609
+ assert g + (-g) == G.infinite()
610
+ d = {}
611
+ d[2 * g] = 2
612
+ assert d[2 * g] == 2
613
+
614
+ # Test long names
615
+ assert (g + g).pt_eq(g + g)
616
+ assert g + g == g.pt_add(g)
617
+ assert -g == g.pt_neg()
618
+ assert 10 * g == g.pt_mul(10)
619
+
620
+ assert len(str(g)) > 0
621
+
622
+
623
+ def test_ec_io():
624
+ G = EcGroup(713)
625
+ g = G.generator()
626
+
627
+ x, y = g.get_affine()
628
+ assert len(g.export()) == 29
629
+ i = G.infinite()
630
+ assert len(i.export()) == 1
631
+ assert EcPt.from_binary(g.export(), G) == g
632
+ assert EcPt.from_binary(i.export(), G) == i
633
+
634
+
635
+ def test_ec_sum():
636
+ G = EcGroup(713)
637
+ g = G.generator()
638
+ assert G.sum([g] * 10) == (10 * g)
639
+
640
+ order = G.order()
641
+ h = order.random() * g
642
+ assert G.wsum([Bn(10), Bn(20)], [g, h]) == 10 * g + 20 * h
643
+
644
+
645
+ def test_pt_add_inplace():
646
+ G = EcGroup(713)
647
+ g = G.generator()
648
+ """
649
+ Does pt_add_inplace add correctly?
650
+ """
651
+ a = g.pt_add(g)
652
+ g.pt_add_inplace(g)
653
+ assert a == g
654
+
655
+ """
656
+ Does it save the result in the same memory location?
657
+ """
658
+ a = G.generator()
659
+ b = a
660
+ a.pt_add_inplace(a)
661
+ assert id(b) == id(a)
662
+
663
+
664
+ def test_pt_double_inplace():
665
+ G = EcGroup(713)
666
+ g = G.generator()
667
+ """
668
+ Does pt_double_inplace double correctly?
669
+ """
670
+ a = g.pt_double()
671
+ g.pt_double_inplace()
672
+ assert a == g
673
+
674
+ """
675
+ Does it save the result in the same memory location?
676
+ """
677
+ a = G.generator()
678
+ b = a
679
+ a.pt_double_inplace()
680
+ assert id(b) == id(a)
681
+
682
+
683
+ def test_pt_mul_inplace():
684
+ G = EcGroup(713)
685
+ g = G.generator()
686
+ """
687
+ Does pt_mul_inplace multiply correctly?
688
+ """
689
+ a = g.pt_mul(5)
690
+ g.pt_mul_inplace(5)
691
+ assert a == g
692
+
693
+ """
694
+ Does it save the result in the same memory location?
695
+ """
696
+ a = G.generator()
697
+ b = a
698
+ a.pt_mul_inplace(5)
699
+ assert id(b) == id(a)
700
+
701
+
702
+ def test_pt_neg_inplace():
703
+ G = EcGroup(713)
704
+ g = G.generator()
705
+ """
706
+ Does pt_neg_inplace negate correctly?
707
+ """
708
+ a = g.pt_neg()
709
+ g.pt_neg_inplace()
710
+ assert a == g
711
+
712
+ """
713
+ Does it save the result in the same memory location?
714
+ """
715
+ a = G.generator()
716
+ b = a
717
+ a.pt_neg_inplace()
718
+ assert id(b) == id(a)
719
+
720
+
721
+ def test_ec_affine_inf():
722
+ G = EcGroup(713)
723
+ inf = G.infinite()
724
+
725
+ with pytest.raises(Exception) as excinfo:
726
+ inf.get_affine()
727
+ assert 'EC Infinity' in str(excinfo.value)
728
+
729
+
730
+ def test_ec_bin_translation():
731
+ from timeit import default_timer as timer
732
+
733
+ G = EcGroup()
734
+ o = G.order()
735
+ g = G.generator()
736
+ pt1000 = [o.random() * g for _ in range(1000)]
737
+
738
+ exp = []
739
+ for pt in pt1000:
740
+ exp += [pt.export()]
741
+
742
+ t0 = timer()
743
+ for ept in exp:
744
+ EcPt.from_binary(ept, G)
745
+ t1 = timer()
746
+ print("\nParsed compressed Pt: %2.4f" % (t1 - t0))
747
+
748
+ exp = []
749
+ for pt in pt1000:
750
+ exp += [pt.export(POINT_CONVERSION_UNCOMPRESSED)]
751
+
752
+ t0 = timer()
753
+ for ept in exp:
754
+ EcPt.from_binary(ept, G)
755
+ t1 = timer()
756
+ print("\nParsed uncompressed Pt: %2.4f" % (t1 - t0))
757
+
758
+
759
+ import platform
760
+
761
+
762
+ @pytest.mark.xfail(platform.system() in ["Windows", "Darwin"],
763
+ reason="No const time mult in Win / OS X OpenSSL")
764
+ def test_p224_const_timing():
765
+ import time
766
+ print("Platform: " + platform.system())
767
+
768
+ # Note: NIST / SECG p224 is nid: 713/712 (p192 is nid:711)
769
+ G = EcGroup(713)
770
+ g = G.generator()
771
+ order = G.order()
772
+ h = order.random() * g
773
+
774
+ repreats = 100
775
+ t = []
776
+ for x in range(0, 200, 20):
777
+ o = Bn(2) ** x
778
+ tests = [o.random() for _ in range(repreats)]
779
+
780
+ t0 = time.clock()
781
+ for y in tests:
782
+ dud = y * h
783
+ t += [time.clock() - t0]
784
+ print(x, t[-1] / repreats)
785
+ assert abs(t[0] - t[-1]) < 5.0 / 100
786
+
787
+ # pylint: enable=unused-variable
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/ecdsa.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ A library providing signature and verification functions for the ECDSA scheme.
2
+
3
+ Example:
4
+ How to use ``do_ecdsa_sign`` and ``do_ecdsa_verify`` to sign and verify a string:
5
+
6
+ >>> from hashlib import sha1
7
+ >>> # Generate a signature / verification key pair.
8
+ >>> G = EcGroup()
9
+ >>> sig_key = G.order().random()
10
+ >>> ver_key = sig_key * G.generator()
11
+ >>> # Hash the (potentially long) message into a short digest.
12
+ >>> digest = sha1(b"Hello World!").digest()
13
+ >>> # Sign and verify signature
14
+ >>> sig = do_ecdsa_sign(G, sig_key, digest)
15
+ >>> do_ecdsa_verify(G, ver_key, sig, digest)
16
+ True
17
+
18
+ Fast signatures can be constructed using ``do_ecdsa_setup``:
19
+
20
+ >>> from hashlib import sha1
21
+ >>> # Generate a signature / verification key pair.
22
+ >>> G = EcGroup()
23
+ >>> sig_key = G.order().random()
24
+ >>> ver_key = sig_key * G.generator()
25
+ >>> # Hash the (potentially long) message into a short digest.
26
+ >>> digest = sha1(b"Hello World!").digest()
27
+ >>> # Sign and verify signature
28
+ >>> kinv_rp = do_ecdsa_setup(G, sig_key)
29
+ >>> sig = do_ecdsa_sign(G, sig_key, digest, kinv_rp = kinv_rp)
30
+ >>> do_ecdsa_verify(G, ver_key, sig, digest)
31
+ True
32
+
33
+ """
34
+
35
+
36
+ from .bindings import _FFI, _C, _OPENSSL_VERSION, OpenSSLVersion
37
+
38
+ from .ec import EcGroup, _check
39
+ from .bn import Bn, get_ctx
40
+
41
+
42
+ def do_ecdsa_setup(G, priv):
43
+ """Compute the parameters kinv and rp to (optionally) speed up ECDSA signing."""
44
+
45
+ ec_key = _C.EC_KEY_new()
46
+ _check(_C.EC_KEY_set_group(ec_key, G.ecg))
47
+ _check(_C.EC_KEY_set_private_key(ec_key, priv.bn))
48
+
49
+ ptr_kinv = _FFI.new("BIGNUM **")
50
+ ptr_rp = _FFI.new("BIGNUM **")
51
+
52
+ _check(_C.ECDSA_sign_setup(ec_key, get_ctx().bnctx, ptr_kinv, ptr_rp))
53
+
54
+ kinv = Bn()
55
+ _C.BN_copy(kinv.bn, ptr_kinv[0])
56
+ _C.BN_clear_free(ptr_kinv[0])
57
+
58
+ rp = Bn()
59
+ _C.BN_copy(rp.bn, ptr_rp[0])
60
+ _C.BN_clear_free(ptr_rp[0])
61
+
62
+ return kinv, rp
63
+
64
+
65
+ def do_ecdsa_sign(G, priv, data, kinv_rp=None):
66
+ """A quick function to ECDSA sign a hash.
67
+
68
+ Args:
69
+ G (EcGroup): the group in which math is done.
70
+ priv (Bn): the secret key.
71
+ data (str): the string to sign.
72
+ kinv_rp (opaque): optional setup parameters.
73
+
74
+ Returns:
75
+ Bn, Bn: The (r, s) signature
76
+
77
+ """
78
+ ec_key = _C.EC_KEY_new()
79
+ _check(_C.EC_KEY_set_group(ec_key, G.ecg))
80
+ _check(_C.EC_KEY_set_private_key(ec_key, priv.bn))
81
+ # _check( _C.EC_KEY_precompute_mult(ec_key, _FFI.NULL) )
82
+
83
+ if kinv_rp is None:
84
+ ecdsa_sig = _C.ECDSA_do_sign(data, len(data), ec_key)
85
+
86
+ else:
87
+ kinv, rp = kinv_rp
88
+ ecdsa_sig = _C.ECDSA_do_sign_ex(
89
+ data, len(data), kinv.bn, rp.bn, ec_key)
90
+
91
+ r = Bn()
92
+ s = Bn()
93
+
94
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
95
+ _C.BN_copy(r.bn, ecdsa_sig.r)
96
+ _C.BN_copy(s.bn, ecdsa_sig.s)
97
+ else:
98
+ rptr = _FFI.new("BIGNUM **")
99
+ sptr = _FFI.new("BIGNUM **")
100
+
101
+ _C.ECDSA_SIG_get0(ecdsa_sig, rptr, sptr)
102
+ _C.BN_copy(r.bn, rptr[0])
103
+ _C.BN_copy(s.bn, sptr[0])
104
+
105
+ _C.ECDSA_SIG_free(ecdsa_sig)
106
+ _C.EC_KEY_free(ec_key)
107
+
108
+ return (r, s)
109
+
110
+
111
+ def do_ecdsa_verify(G, pub, sig, data):
112
+ """A quick function to ECDSA verify a hash.
113
+
114
+ Args:
115
+ G (EcGroup): the group in which math is done.
116
+ pub (EcPt): the secret key
117
+ sig (Bn, Bn): the (r,s) signature
118
+ data (str): the string to sign
119
+
120
+ Returns:
121
+ bool: A Boolean indicating whether the signature verifies.
122
+ """
123
+
124
+ r, s = sig
125
+
126
+ ec_key = _C.EC_KEY_new()
127
+ _check(_C.EC_KEY_set_group(ec_key, G.ecg))
128
+ _check(_C.EC_KEY_set_public_key(ec_key, pub.pt))
129
+ _check(_C.EC_KEY_precompute_mult(ec_key, get_ctx().bnctx))
130
+
131
+ ec_sig = _C.ECDSA_SIG_new()
132
+
133
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
134
+ _C.BN_copy(ec_sig.r, r.bn)
135
+ _C.BN_copy(ec_sig.s, s.bn)
136
+ else:
137
+ _check(_C.ECDSA_SIG_set0_petlib(ec_sig, r.bn, s.bn))
138
+
139
+ try:
140
+ result = int(_C.ECDSA_do_verify(data, len(data), ec_sig, ec_key))
141
+ if result == -1:
142
+ raise Exception("ECDSA Error")
143
+
144
+ finally:
145
+ _C.EC_KEY_free(ec_key)
146
+ _C.ECDSA_SIG_free(ec_sig)
147
+
148
+ return bool(result)
149
+
150
+
151
+ def get_ecdsa_keys(G, sig, data):
152
+ """ Returns the two possible public keys corresponding to this signature.
153
+
154
+ Args:
155
+ G (EcGroup): the group in which math is done.
156
+ data (str): the string to sign
157
+ sign (Bn, Bn): the (r,s) signature
158
+
159
+ Returns:
160
+ pub1, pub2: The two candidate public keys
161
+
162
+ """
163
+
164
+ (r, s) = sig
165
+ g = G.generator()
166
+ R1, R2 = G.get_points_from_x(r)
167
+
168
+ r_inv = r.mod_inverse(G.order())
169
+ z = Bn.from_binary(data)
170
+
171
+ if not (0 < z < G.order()):
172
+ raise Exception("Digest too long")
173
+
174
+ K1 = r_inv * (s * R1 - z * g)
175
+ K2 = r_inv * (s * R2 - z * g)
176
+
177
+ return K1, K2
178
+
179
+
180
+ def test_ecdsa():
181
+ G = EcGroup()
182
+ priv = G.order().random()
183
+ g = G.generator()
184
+ sig = do_ecdsa_sign(G, priv, b"Hello")
185
+ assert do_ecdsa_verify(G, priv * g, sig, b"Hello")
186
+
187
+
188
+ def test_get_ecdsa_keys():
189
+ G = EcGroup()
190
+ g = G.generator()
191
+
192
+ priv = G.order().random()
193
+ pub = priv * g
194
+
195
+ sig = do_ecdsa_sign(G, priv, b"Hello")
196
+ assert do_ecdsa_verify(G, priv * g, sig, b"Hello")
197
+
198
+ pk1, pk2 = get_ecdsa_keys(G, sig, b"Hello")
199
+ assert pk1 == pub or pk2 == pub
200
+
201
+
202
+ def test_ecdsa_fail():
203
+ G = EcGroup()
204
+ priv = G.order().random()
205
+ g = G.generator()
206
+ sig = do_ecdsa_sign(G, priv, b"Hello")
207
+
208
+ assert not do_ecdsa_verify(G, priv * g, sig, b"Hellx")
209
+
210
+
211
+ def test_ecdsa_timing():
212
+ repreats = 1000
213
+
214
+ from hashlib import sha1
215
+ import time
216
+
217
+ G = EcGroup()
218
+ sig_key = G.order().random()
219
+ ver_key = sig_key * G.generator()
220
+
221
+ digest = sha1(b"Hello World!").digest()
222
+
223
+ print
224
+ t = []
225
+
226
+ x = "Sign. plain"
227
+ t0 = time.clock()
228
+ for y in range(repreats):
229
+ sig = do_ecdsa_sign(G, sig_key, digest)
230
+ t += [time.clock() - t0]
231
+
232
+ print("%s:\t%2.2f/sec" % (x, 1.0 / (float(t[-1]) / repreats)))
233
+
234
+ x = "Sign. with setup"
235
+ t0 = time.clock()
236
+ kinv_rp = do_ecdsa_setup(G, sig_key)
237
+ for y in range(repreats):
238
+ sig = do_ecdsa_sign(G, sig_key, digest, kinv_rp=kinv_rp)
239
+ t += [time.clock() - t0]
240
+
241
+ print("%s:\t%2.2f/sec" % (x, 1.0 / (float(t[-1]) / repreats)))
242
+
243
+ x = "Verification"
244
+ t0 = time.clock()
245
+ kinv_rp = do_ecdsa_setup(G, sig_key)
246
+ for y in range(repreats):
247
+ do_ecdsa_verify(G, ver_key, sig, digest)
248
+ t += [time.clock() - t0]
249
+
250
+ print("%s:\t%2.2f/sec" % (x, 1.0 / (float(t[-1]) / repreats)))
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/hmac.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bindings import _FFI, _C, _OPENSSL_VERSION, OpenSSLVersion
2
+
3
+ from binascii import hexlify
4
+
5
+ import pytest
6
+
7
+
8
+ def _check(return_val):
9
+ """Checks the return code of the C calls"""
10
+ if isinstance(return_val, int) and return_val == 1:
11
+ return
12
+ if isinstance(return_val, bool) and return_val == True:
13
+ return
14
+
15
+ raise Exception("HMAC exception")
16
+
17
+
18
+ def secure_compare(a1, a2):
19
+ """A constant-time comparison function. Returns True if the two strings are equal and False otherwise.
20
+
21
+ Args:
22
+ a1 (str): the first string
23
+ a2 (str): the second string
24
+
25
+ Returns:
26
+ bool: whether the two stings are equal.
27
+ """
28
+ _check(isinstance(a1, type(a2)))
29
+
30
+ if len(a1) != len(a2):
31
+ return False
32
+
33
+ x = _C.CRYPTO_memcmp(a1, a2, len(a1))
34
+ if int(x) == 0:
35
+ return True
36
+
37
+ return False
38
+
39
+
40
+ class Hmac(object):
41
+ """Initialize the HMAC by name with a key.
42
+
43
+ Args:
44
+ name: the name of the hash function to be used.
45
+ key: the cryptographic symmetric key of the HMAC.
46
+
47
+ Returns:
48
+ An HMAC instance, ready to accept data to MAC.
49
+
50
+ Example:
51
+
52
+ >>> h = Hmac(b"sha512", b"Jefe")
53
+ >>> h.update(b"what do ya want ")
54
+ >>> h.update(b"for nothing?")
55
+ >>> d = h.digest()
56
+ >>> len(d)
57
+ 64
58
+ >>> hexlify(d)[:10] == b"164b7a7bfc"
59
+ True
60
+
61
+ """
62
+
63
+ def __init__(self, name, key):
64
+ self.mac_ctx = None
65
+ md = _C.EVP_get_digestbyname(name)
66
+ if md == _FFI.NULL:
67
+ raise Exception("HMAC Error loading function %s" % name)
68
+
69
+ self.outsize = _C.EVP_MD_size(md)
70
+ if _OPENSSL_VERSION == OpenSSLVersion.V1_0:
71
+ self.mac_ctx = _FFI.new("HMAC_CTX *")
72
+ _C.HMAC_CTX_init(self.mac_ctx)
73
+ else:
74
+ self.mac_ctx = _C.HMAC_CTX_new()
75
+
76
+ _check(_C.HMAC_Init_ex(self.mac_ctx, key, len(key), md, _FFI.NULL))
77
+ self.active = True
78
+
79
+ def update(self, data):
80
+ """Update the HMAC with some data to authenticate.
81
+
82
+ Args:
83
+ data: the data to add to the MAC.
84
+
85
+ Note: you must not call update after you finalize the HMAC.
86
+
87
+ Raises:
88
+ Exception: if called after the HMAC has been finalized.
89
+ """
90
+ if not self.active:
91
+ raise Exception("HMAC already finalized!")
92
+ _check(_C.HMAC_Update(self.mac_ctx, data, len(data)))
93
+
94
+ def digest(self):
95
+ """Output the HMAC digest as a binary string.
96
+
97
+ Returns:
98
+ The digest as a binary data string.
99
+ """
100
+ if not self.active:
101
+ raise Exception("HMAC already finalized!")
102
+
103
+ self.active = False
104
+ out_md = _FFI.new("unsigned char[]", self.outsize)
105
+ out_len = _FFI.new("unsigned int *")
106
+ _check(_C.HMAC_Final(self.mac_ctx, out_md, out_len))
107
+
108
+ if int(out_len[0]) != self.outsize:
109
+ raise Exception("HMAC Unexpected length")
110
+
111
+ return bytes(_FFI.buffer(out_md)[:])
112
+
113
+ def __del__(self):
114
+ if self.mac_ctx is not None and _OPENSSL_VERSION == OpenSSLVersion.V1_1:
115
+ _C.HMAC_CTX_free(self.mac_ctx)
116
+
117
+
118
+ def test_init():
119
+ h = Hmac(b"md5", b"Hello")
120
+ h.update(b"hello")
121
+ d = h.digest()
122
+ assert d
123
+ assert len(d) == 128 / 8
124
+
125
+
126
+ def test_vectors():
127
+ """
128
+ Key = 4a656665 ("Jefe")
129
+ Data = 7768617420646f2079612077616e7420 ("what do ya want ")
130
+ 666f72206e6f7468696e673f ("for nothing?")
131
+
132
+ HMAC-SHA-224 = a30e01098bc6dbbf45690f3a7e9e6d0f
133
+ 8bbea2a39e6148008fd05e44
134
+ HMAC-SHA-256 = 5bdcc146bf60754e6a042426089575c7
135
+ 5a003f089d2739839dec58b964ec3843
136
+ HMAC-SHA-384 = af45d2e376484031617f78d2b58a6b1b
137
+ 9c7ef464f5a01b47e42ec3736322445e
138
+ 8e2240ca5e69e2c78b3239ecfab21649
139
+ HMAC-SHA-512 = 164b7a7bfcf819e2e395fbe73b56e0a3
140
+ 87bd64222e831fd610270cd7ea250554
141
+ 9758bf75c05a994a6d034f65f8f0e6fd
142
+ caeab1a34d4a6b4b636e070a38bce737
143
+ """
144
+
145
+ h = Hmac(b"sha512", b"Jefe")
146
+ assert 512 / 8 == h.outsize
147
+ h.update(b"what do ya want ")
148
+ h.update(b"for nothing?")
149
+ d = h.digest()
150
+
151
+ with pytest.raises(Exception) as excinfo:
152
+ h.update(b"some more")
153
+ assert 'finalized' in str(excinfo.value)
154
+
155
+ with pytest.raises(Exception) as excinfo:
156
+ h.digest()
157
+ assert 'finalized' in str(excinfo.value)
158
+
159
+ with pytest.raises(Exception) as excinfo:
160
+ h = Hmac(b"sha999", b"Jefe")
161
+ assert 'Error' in str(excinfo.value)
162
+
163
+ ans1 = hexlify(d)
164
+ ans2 = b"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
165
+
166
+ assert len(ans1) == len(ans2)
167
+ assert ans1 == ans2
168
+
169
+
170
+ def test_cmp():
171
+ assert secure_compare(b"Hello", b"Hello")
172
+ assert not secure_compare(b"Hello", b"Hellx")
173
+ assert not secure_compare(b"Hello", b"Hell")
174
+
175
+ with pytest.raises(Exception) as excinfo:
176
+ assert not secure_compare(b"Hello", 2)
177
+ assert 'HMAC' in str(excinfo.value)
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/petlib/pack.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The module provides functions to pack and unpack petlib Bn, EcGroup, and EcPt
2
+ strucures.
3
+
4
+ Example:
5
+ >>> # Define a custom class, encoder and decoder
6
+ >>> class CustomType:
7
+ ... def __eq__(self, other):
8
+ ... return isinstance(other, CustomType)
9
+ >>>
10
+ >>> def enc_custom(obj):
11
+ ... return b''
12
+ >>>
13
+ >>> def dec_custom(data):
14
+ ... return CustomType()
15
+ >>>
16
+ >>> register_coders(CustomType, 10, enc_custom, dec_custom)
17
+ >>>
18
+ >>> # Define a structure
19
+ >>> G = EcGroup()
20
+ >>> custom_obj = CustomType()
21
+ >>> test_data = [G, G.generator(), G.order(), custom_obj]
22
+ >>>
23
+ >>> # Encode and decode custom structure
24
+ >>> packed = encode(test_data)
25
+ >>> x = decode(packed)
26
+ >>> assert x == test_data
27
+
28
+ """
29
+
30
+ import msgpack
31
+
32
+ from .ec import EcGroup, EcPt
33
+ from .bn import Bn
34
+
35
+ __all__ = ["encode", "decode", "register_coders"]
36
+
37
+ _pack_reg = {}
38
+ _unpack_reg = {}
39
+
40
+
41
+ def register_coders(cls, num, enc_func, dec_func):
42
+ """ Register a new type for encoding and decoding.
43
+ Take a class type, a number, an encoding and a decoding function."""
44
+
45
+ if num in _unpack_reg or cls in _pack_reg:
46
+ raise Exception("Class or number already in use.")
47
+
48
+ coders = (cls, num, enc_func, dec_func)
49
+ _pack_reg[cls] = coders
50
+ _unpack_reg[num] = coders
51
+
52
+
53
+ def bn_enc(obj):
54
+ if obj < 0:
55
+ neg = b"-"
56
+ data = (-obj).binary()
57
+ else:
58
+ neg = b"+"
59
+ data = obj.binary()
60
+ return neg + data
61
+
62
+
63
+ def bn_dec(data):
64
+ num = Bn.from_binary(data[1:])
65
+ # Accomodate both Python 2 and Python 3
66
+ if data[0] == ord("-") or data[0] == "-":
67
+ return -num
68
+ return num
69
+
70
+
71
+ def ecg_enc(obj):
72
+ # Serialize EcGroup objects
73
+ nid = obj.nid()
74
+ packed_nid = msgpack.packb(nid)
75
+ return packed_nid
76
+
77
+
78
+ def ecg_dec(data):
79
+ # Decode EcGroup
80
+ nid = msgpack.unpackb(data)
81
+ return EcGroup(nid)
82
+
83
+
84
+ def ecpt_enc(obj):
85
+ # Serialize EcPt objects
86
+ nid = obj.group.nid()
87
+ data = obj.export()
88
+ packed_data = msgpack.packb((nid, data))
89
+ return packed_data
90
+
91
+
92
+ def ecpt_dec(data):
93
+ # Decode EcPt
94
+ nid, ptdata = msgpack.unpackb(data)
95
+ return EcPt.from_binary(ptdata, EcGroup(nid))
96
+
97
+
98
+ def _init_coders():
99
+ global _pack_reg, _unpack_reg
100
+ _pack_reg, _unpack_reg = {}, {}
101
+ register_coders(Bn, 0, bn_enc, bn_dec)
102
+ register_coders(EcGroup, 1, ecg_enc, ecg_dec)
103
+ register_coders(EcPt, 2, ecpt_enc, ecpt_dec)
104
+
105
+
106
+ # Register default coders
107
+ _init_coders()
108
+
109
+
110
+ def default(obj):
111
+ # Serialize Bn objects
112
+ for T in _pack_reg:
113
+ if isinstance(obj, T):
114
+ _, num, enc, _ = _pack_reg[T]
115
+ return msgpack.ExtType(num, enc(obj))
116
+
117
+ raise TypeError("Unknown type: %r" % (type(obj),))
118
+
119
+
120
+ def make_encoder(out_encoder=None):
121
+ if out_encoder is None:
122
+ return default
123
+ else:
124
+ def new_encoder(obj):
125
+ try:
126
+ encoded = default(obj)
127
+ return encoded
128
+ except BaseException:
129
+ return out_encoder(obj)
130
+ return new_encoder
131
+
132
+
133
+ def ext_hook(code, data):
134
+ if code in _unpack_reg:
135
+ _, _, _, dec = _unpack_reg[code]
136
+ return dec(data)
137
+
138
+ # Other
139
+ return msgpack.ExtType(code, data)
140
+
141
+
142
+ def make_decoder(custom_decoder=None):
143
+ if custom_decoder is None:
144
+ return ext_hook
145
+ else:
146
+ def new_decoder(code, data):
147
+ out = ext_hook(code, data)
148
+ if not isinstance(out, msgpack.ExtType):
149
+ return out
150
+ else:
151
+ return custom_decoder(code, data)
152
+ return new_decoder
153
+
154
+
155
+ def encode(structure, custom_encoder=None):
156
+ """ Encode a structure containing petlib objects to a binary format. May define a custom encoder for user classes. """
157
+ encoder = make_encoder(custom_encoder)
158
+ packed_data = msgpack.packb(structure, default=encoder, use_bin_type=True)
159
+ return packed_data
160
+
161
+
162
+ def decode(packed_data, custom_decoder=None):
163
+ """ Decode a binary byte sequence into a structure containing pelib objects. May define a custom decoder for custom classes. """
164
+ decoder = make_decoder(custom_decoder)
165
+ structure = msgpack.unpackb(
166
+ packed_data,
167
+ ext_hook=decoder,
168
+ encoding='utf-8')
169
+ return structure
170
+
171
+ # --- TESTS ---
172
+
173
+
174
+ def test_basic():
175
+ x = [b'spam', u'egg']
176
+ packed = msgpack.packb(x, use_bin_type=True)
177
+ y = msgpack.unpackb(packed, encoding='utf-8')
178
+ assert x == y
179
+
180
+
181
+ def test_bn():
182
+ bn1, bn2 = Bn(1), Bn(2)
183
+ test_data = [bn1, bn2, -bn1, -bn2]
184
+ packed = msgpack.packb(test_data, default=default, use_bin_type=True)
185
+ x = msgpack.unpackb(packed, ext_hook=ext_hook, encoding='utf-8')
186
+ assert x == test_data
187
+
188
+
189
+ def test_ecgroup():
190
+ G = EcGroup()
191
+ test_data = [G]
192
+ packed = msgpack.packb(test_data, default=default, use_bin_type=True)
193
+ x = msgpack.unpackb(packed, ext_hook=ext_hook, encoding='utf-8')
194
+ assert x == test_data
195
+
196
+
197
+ def test_ecpt():
198
+ G = EcGroup()
199
+ test_data = [G.generator()]
200
+ packed = msgpack.packb(test_data, default=default, use_bin_type=True)
201
+ x = msgpack.unpackb(packed, ext_hook=ext_hook, encoding='utf-8')
202
+ assert x == test_data
203
+
204
+
205
+ def test_mixed():
206
+ G = EcGroup()
207
+ test_data = [G, G.generator(), G.order()]
208
+ packed = msgpack.packb(test_data, default=default, use_bin_type=True)
209
+ x = msgpack.unpackb(packed, ext_hook=ext_hook, encoding='utf-8')
210
+ assert x == test_data
211
+
212
+
213
+ def test_enc_dec():
214
+ G = EcGroup()
215
+ test_data = [G, G.generator(), G.order()]
216
+ packed = encode(test_data)
217
+ x = decode(packed)
218
+ assert x == test_data
219
+
220
+
221
+ def test_enc_dec_dict():
222
+ G = EcGroup()
223
+ # , G.generator():"1", "2":G.order()}
224
+ test_data = {G.order(): [G, G.generator()]}
225
+ packed = encode(test_data)
226
+ x = decode(packed)
227
+ assert x[G.order()] == test_data[G.order()]
228
+
229
+
230
+ def test_enc_dec_custom():
231
+
232
+ # Define a custom class, encoder and decoder
233
+ class CustomClass:
234
+ def __eq__(self, other):
235
+ return isinstance(other, CustomClass)
236
+
237
+ def enc_CustomClass(obj):
238
+ if isinstance(obj, CustomClass):
239
+ return msgpack.ExtType(11, b'')
240
+ raise TypeError("Unknown type: %r" % (obj,))
241
+
242
+ def dec_CustomClass(code, data):
243
+ if code == 11:
244
+ return CustomClass()
245
+
246
+ return msgpack.ExtType(code, data)
247
+
248
+ # Define a structure
249
+ G = EcGroup()
250
+ custom_obj = CustomClass()
251
+ test_data = [G, G.generator(), G.order(), custom_obj]
252
+
253
+ # Encode and decode custom structure
254
+ packed = encode(test_data, enc_CustomClass)
255
+ x = decode(packed, dec_CustomClass)
256
+ assert x == test_data
257
+
258
+
259
+ def test_streaming():
260
+
261
+ # Define a custom class, encoder and decoder
262
+ class CustomClass2:
263
+ def __eq__(self, other):
264
+ return isinstance(other, CustomClass2)
265
+
266
+ def enc_CustomClass(obj):
267
+ if isinstance(obj, CustomClass2):
268
+ return msgpack.ExtType(12, b'')
269
+ raise TypeError("Unknown type: %r" % (obj,))
270
+
271
+ def dec_CustomClass(code, data):
272
+ if code == 12:
273
+ return CustomClass2()
274
+
275
+ return msgpack.ExtType(code, data)
276
+
277
+ # Define a structure
278
+ G = EcGroup()
279
+ custom_obj = CustomClass2()
280
+ test_data = [G, G.generator(), G.order(), custom_obj]
281
+ packed1 = encode(test_data, enc_CustomClass)
282
+ packed2 = encode(test_data, enc_CustomClass)
283
+
284
+ data = packed1 + packed2
285
+
286
+ decoder = make_decoder(dec_CustomClass)
287
+ Up = msgpack.Unpacker(ext_hook=decoder)
288
+ Up.feed(data)
289
+ for o in Up:
290
+ assert o == test_data
291
+
292
+
293
+ def test_docstring():
294
+ # Define a custom class, encoder and decoder
295
+ class CustomType:
296
+ def __eq__(self, other):
297
+ return isinstance(other, CustomType)
298
+
299
+ def enc_custom(obj):
300
+ return b''
301
+
302
+ def dec_custom(data):
303
+ return CustomType()
304
+
305
+ _init_coders()
306
+ register_coders(CustomType, 14, enc_custom, dec_custom)
307
+ assert CustomType in _pack_reg
308
+
309
+ # Define a structure
310
+ G = EcGroup()
311
+ custom_obj = CustomType()
312
+ test_data = [G, G.generator(), G.order(), custom_obj]
313
+
314
+ # Encode and decode custom structure
315
+ packed = encode(test_data)
316
+ x = decode(packed)
317
+ assert x == test_data
318
+ _init_coders()
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytest-4.6.5.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.33.4)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Abidjan ADDED
Binary file (148 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Accra ADDED
Binary file (816 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Addis_Ababa ADDED
Binary file (251 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Algiers ADDED
Binary file (735 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Asmara ADDED
Binary file (251 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Asmera ADDED
Binary file (251 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bamako ADDED
Binary file (148 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bangui ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Banjul ADDED
Binary file (148 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Bissau ADDED
Binary file (194 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Blantyre ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Brazzaville ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Dakar ADDED
Binary file (148 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Dar_es_Salaam ADDED
Binary file (251 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Djibouti ADDED
Binary file (251 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Douala ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/El_Aaiun ADDED
Binary file (2.3 kB). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Freetown ADDED
Binary file (148 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Gaborone ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Harare ADDED
Binary file (149 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Johannesburg ADDED
Binary file (246 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Juba ADDED
Binary file (653 Bytes). View file
 
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Africa/Kampala ADDED
Binary file (251 Bytes). View file