momilla commited on
Commit
63b9d0a
1 Parent(s): fd45f56

Upload smart_contracts_audit.py

Browse files
Files changed (1) hide show
  1. smart_contracts_audit.py +390 -0
smart_contracts_audit.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Smart Contracts Audit dataset."""
15
+
16
+
17
+ import os
18
+ import re
19
+ import pandas as pd
20
+ import datasets
21
+ from pyparsing import col
22
+
23
+
24
+ _CITATION = """\
25
+ @misc{storhaug2022smartcontractsaudit,
26
+ title = {Smart Contracts Audit Dataset},
27
+ author={André Storhaug},
28
+ year={2022}
29
+ }
30
+ """
31
+
32
+ _DESCRIPTION = """\
33
+ Smart Contracts Audit Dataset.
34
+ This is a dataset of audited verified (Etherscan.io) Smart Contracts \
35
+ that are deployed to the Ethereum blockchain.
36
+ """
37
+
38
+ # TODO: Add a link to an official homepage for the dataset here
39
+ _HOMEPAGE = "https://andstor.github.io/verified-smart-contracts-audit"
40
+
41
+ # TODO: Add the license for the dataset here if you can find it
42
+ _LICENSE = ""
43
+
44
+ # Add link to the official dataset URLs here
45
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
46
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
47
+ _URLS = {
48
+ "flattened": {
49
+ "dev": [f"data/flattened/validation/part.{part}.parquet" for part in range(2)],
50
+ "test": [f"data/flattened/test/part.{part}.parquet" for part in range(2)],
51
+ "train": [f"data/flattened/train/part.{part}.parquet" for part in range(11)]
52
+ },
53
+ "inflated": {
54
+ "dev": [f"data/inflated/validation/part.{part}.parquet" for part in range(1)],
55
+ "test": [f"data/inflated/test/part.{part}.parquet" for part in range(1)],
56
+ "train": [f"data/inflated/train/part.{part}.parquet" for part in range(5)]
57
+ },
58
+ "metadata": "data/metadata.parquet"
59
+ }
60
+
61
+ # Supported tools and columns config
62
+ _TOOLS = {
63
+ 'flattened': {
64
+ 'all': ["solidetector", "slither", "oyente", "smartcheck"],
65
+ 'solidetector': ["solidetector"],
66
+ 'slither': ['slither'],
67
+ 'oyente': ['oyente'],
68
+ 'smartcheck': ['smartcheck'],
69
+ },
70
+ 'inflated': {
71
+ 'all': ["solidetector"],
72
+ 'solidetector': ["solidetector"],
73
+ }
74
+ }
75
+
76
+ _TOOLS_AUDIT_DESC = {
77
+ 'solidetector': {
78
+ 'level_col': 'severity',
79
+ 'levels': {'High': 3, 'Medium': 2, 'Low': 1 },
80
+ },
81
+ 'slither': {
82
+ 'level_col': 'impact',
83
+ 'levels': {'High': 3, 'Medium': 2, 'Low': 1, 'Informational': -1, 'Optimization': -2},
84
+ },
85
+ 'oyente': {
86
+ 'level_col': 'level',
87
+ 'levels': {'Warning': 3},
88
+ },
89
+ 'smartcheck': {
90
+ 'level_col': 'severity',
91
+ 'levels': {3: 3, 2: 2, 1: 1},
92
+ }
93
+ }
94
+
95
+
96
+ _LEVELS = {
97
+ 'High': 3,
98
+ 'Warning': 3,
99
+ 3: 3,
100
+ 'Medium': 2,
101
+ 2: 2,
102
+ 'Low': 1,
103
+ 1: 1,
104
+ 'Informational': -1,
105
+ 'Optimization': -2,
106
+ }
107
+
108
+ _EMBEDDED_LEVEL = "High"
109
+
110
+ def _check_strings(search_list, input_string):
111
+ return [s in input_string for s in search_list]
112
+
113
+ # Name of the dataset usually match the script name with CamelCase instead of snake_case
114
+ class SmartContractsAudit(datasets.GeneratorBasedBuilder):
115
+ """Smart Contracts Audit Dataset."""
116
+
117
+ VERSION = datasets.Version("1.0.0")
118
+
119
+ # You will be able to load one or the other configurations in the following list with
120
+ # data = datasets.load_dataset('my_dataset', 'all')
121
+ # data = datasets.load_dataset('my_dataset', 'plain_text')
122
+ BUILDER_CONFIGS = [
123
+ datasets.BuilderConfig(name="flattened_all", version=VERSION, description="Flattened data labeled with all tools"),
124
+ datasets.BuilderConfig(name="flattened_all_extended", version=VERSION, description="Flattened data with metadata, labeled with all tools"),
125
+ datasets.BuilderConfig(name="flattened_all_embedded", version=VERSION, description="Flattened data with embedded labeled with all tools"),
126
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="flattened_all_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low", "informational", "optimization"]])(),
127
+
128
+ datasets.BuilderConfig(name="flattened_slither", version=VERSION, description="Flattened data with metadata, labeled with SoliDetector"),
129
+ datasets.BuilderConfig(name="flattened_slither_extended", version=VERSION, description="Flattened data labeled with SoliDetector"),
130
+ datasets.BuilderConfig(name="flattened_slither_embedded", version=VERSION, description="Flattened data with embedded labeled with SoliDetector"),
131
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="flattened_slither_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low", "informational", "optimization"]])(),
132
+
133
+ datasets.BuilderConfig(name="flattened_solidetector", version=VERSION, description="Flattened data with metadata, labeled with SoliDetector"),
134
+ datasets.BuilderConfig(name="flattened_solidetector_extended", version=VERSION, description="Flattened data labeled with SoliDetector"),
135
+ datasets.BuilderConfig(name="flattened_solidetector_embedded", version=VERSION, description="Flattened data with embedded labeled with SoliDetector"),
136
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="flattened_solidetector_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low"]])(),
137
+
138
+ datasets.BuilderConfig(name="flattened_oyente", version=VERSION, description="Flattened data with metadata, labeled with Oyente"),
139
+ datasets.BuilderConfig(name="flattened_oyente_extended", version=VERSION, description="Flattened data labeled with Oyente"),
140
+ datasets.BuilderConfig(name="flattened_oyente_embedded", version=VERSION, description="Flattened data with embedded labeled with Oyente"),
141
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="flattened_oyente_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low"]])(),
142
+
143
+ datasets.BuilderConfig(name="flattened_smartcheck", version=VERSION, description="Flattened data with metadata, labeled with SmartCheck"),
144
+ datasets.BuilderConfig(name="flattened_smartcheck_extended", version=VERSION, description="Flattened data labeled with SmartCheck"),
145
+ datasets.BuilderConfig(name="flattened_smartcheck_embedded", version=VERSION, description="Flattened data with embedded labeled with SmartCheck"),
146
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="flattened_smartcheck_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low"]])(),
147
+
148
+ datasets.BuilderConfig(name="inflated_all", version=VERSION, description="Inflated data labeled with all tools"),
149
+ datasets.BuilderConfig(name="inflated_all_embedded", version=VERSION, description="Inflated data with embedded labeled with all tools"),
150
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="inflated_all_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low"]])(),
151
+
152
+ datasets.BuilderConfig(name="inflated_solidetector", version=VERSION, description="Inflated data labeled with SoliDetector"),
153
+ datasets.BuilderConfig(name="inflated_solidetector_embedded", version=VERSION, description="Inflated data with embedded labeled with SoliDetector"),
154
+ #*(lambda VERSION=VERSION: [ datasets.BuilderConfig(name="inflated_solidetector_embedded_" + lvl, version=VERSION) for lvl in ["high", "medium", "low"]])(),
155
+
156
+ #datasets.BuilderConfig(name="solidetector", version=VERSION, description="Labeling with SoliDetector"),
157
+ #datasets.BuilderConfig(name="solidetector_plain_text", version=VERSION, description="Labeling with SoliDetector plain text version"),
158
+ ]
159
+
160
+ DEFAULT_CONFIG_NAME = "inflated_all" # It's not mandatory to have a default configuration. Just use one if it make sense.
161
+
162
+ def _info(self):
163
+ # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
164
+ data_split = self.config.name.split("_")[0]
165
+ tool = self.config.name.split("_")[1]
166
+
167
+ if "embedded" in self.config.name: # This is an example to show how to have different features for "first_domain" and "second_domain"
168
+ features = datasets.Features(
169
+ {
170
+ "text": datasets.Value("string"),
171
+ "language": datasets.Value("string")
172
+ }
173
+ )
174
+ elif "flattened" in self.config.name: # This is the name of the configuration selected in BUILDER_CONFIGS above
175
+ features = datasets.Features(
176
+ {
177
+ 'contract_name': datasets.Value("string"),
178
+ 'contract_address': datasets.Value("string"),
179
+ 'language': datasets.Value("string"),
180
+ 'source_code': datasets.Value("string"),
181
+ **{ t: datasets.Value("string") for t in _TOOLS[data_split][tool] },
182
+ 'abi': datasets.Value("string"), # JSON string
183
+ 'compiler_version': datasets.Value("string"),
184
+ 'optimization_used': datasets.Value("bool"),
185
+ 'runs': datasets.Value("int64"),
186
+ 'constructor_arguments': datasets.Value("string"),
187
+ 'evm_version': datasets.Value("string"),
188
+ 'library': datasets.Value("string"),
189
+ 'license_type': datasets.Value("string"),
190
+ 'proxy': datasets.Value("bool"),
191
+ 'implementation': datasets.Value("string"),
192
+ 'swarm_source': datasets.Value("string")
193
+ }
194
+ )
195
+ elif "inflated" in self.config.name: # This is an example to show how to have different features for "first_domain" and "second_domain"
196
+ features = datasets.Features(
197
+ {
198
+ 'contract_name': datasets.Value("string"),
199
+ 'file_path': datasets.Value("string"),
200
+ 'contract_address': datasets.Value("string"),
201
+ 'language': datasets.Value("string"),
202
+ 'source_code': datasets.Value("string"),
203
+ **{ t: datasets.Value("string") for t in _TOOLS[data_split][tool] },
204
+ 'compiler_version': datasets.Value("string"),
205
+ 'license_type': datasets.Value("string"),
206
+ 'swarm_source': datasets.Value("string")
207
+ }
208
+ )
209
+
210
+ if "extended" in self.config.name:
211
+ features["tx_count"] = datasets.Value("int64")
212
+ features["balance"] = datasets.Value("string")
213
+
214
+ return datasets.DatasetInfo(
215
+ # This is the description that will appear on the datasets page.
216
+ description=_DESCRIPTION,
217
+ # This defines the different columns of the dataset and their types
218
+ features=features, # Here we define them above because they are different between the two configurations
219
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
220
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
221
+ # supervised_keys=("sentence", "label"),
222
+ # Homepage of the dataset for documentation
223
+ homepage=_HOMEPAGE,
224
+ # License for the dataset if available
225
+ license=_LICENSE,
226
+ # Citation for the dataset
227
+ citation=_CITATION,
228
+ )
229
+
230
+ def _split_generators(self, dl_manager):
231
+ # This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
232
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
233
+
234
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
235
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
236
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
237
+ urls = _URLS[self.config.name.split("_")[0]]
238
+ downloaded_files = dl_manager.download_and_extract(urls)
239
+
240
+ metadata = None
241
+ if "extended" in self.config.name:
242
+ metadata = dl_manager.download_and_extract(_URLS["metadata"])
243
+
244
+ if "flattened" in self.config.name or "inflated" in self.config.name:
245
+ return [
246
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": downloaded_files["train"], "metadata": metadata}),
247
+ datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"files": downloaded_files["dev"], "metadata": metadata}),
248
+ datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"files": downloaded_files["test"], "metadata": metadata}),
249
+ ]
250
+ else:
251
+ return [
252
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": downloaded_files["train"], "metadata": metadata}),
253
+ ]
254
+
255
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
256
+ def _generate_examples(self, files, metadata):
257
+ """Yields examples."""
258
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
259
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
260
+ #data = pd.read_parquet(filepath)
261
+ data_split = self.config.name.split("_")[0]
262
+ tool = self.config.name.split("_")[1]
263
+
264
+ lvl = _EMBEDDED_LEVEL
265
+ #lvl = self.config.name.split("_")[-1].capitalize()
266
+ #if lvl not in _LEVELS:
267
+ # lvl = min(_LEVELS, key=_LEVELS.get)
268
+
269
+ # Load metadata
270
+ if metadata is not None:
271
+ meta = pd.read_parquet(metadata)
272
+
273
+ for path in files:
274
+ if "embedded" in self.config.name:
275
+ columns = ['contract_address', 'source_code', 'language']
276
+ columns.extend(["file_path"] if "inflated" in self.config.name else [])
277
+ columns.extend(_TOOLS[data_split][tool])
278
+ data = pd.read_parquet(path, columns=columns)
279
+ elif "flattened" in self.config.name:
280
+ data = pd.read_parquet(path)
281
+ data['runs'].fillna(0, inplace=True)
282
+ else:
283
+ data = pd.read_parquet(path)
284
+
285
+ # Add metadata
286
+ if metadata is not None:
287
+ data = pd.merge(data, meta, how="left", on="contract_address")
288
+
289
+ for index, row in data.iterrows():
290
+
291
+ if "flattened" in self.config.name:
292
+ # Yields examples as (key, example) tuples
293
+ key = row['contract_address']
294
+ if "embedded" in self.config.name:
295
+ is_vulnerable = False
296
+ is_secure = False
297
+ for t in _TOOLS[data_split][tool]:
298
+ if pd.isnull(row[t]):
299
+ continue
300
+ if row[t] == "[]":
301
+ is_secure = True
302
+ continue
303
+
304
+ vuln_levels = [_TOOLS_AUDIT_DESC[t]["level_col"] + '": "' + k for k,v in _LEVELS.items() if v >= _LEVELS[lvl]]
305
+ if any(_check_strings(vuln_levels, row[t])):
306
+ is_vulnerable = True
307
+ break
308
+ else:
309
+ is_secure = True
310
+ continue
311
+
312
+ label = ""
313
+ if is_vulnerable:
314
+ label = "// VULNERABLE\n"
315
+ elif is_secure:
316
+ label = "// SECURE\n"
317
+ else:
318
+ label = "// UNKNOWN\n"
319
+
320
+ yield key, {
321
+ 'text': label + row['source_code'],
322
+ 'language': row['language'],
323
+ }
324
+ else:
325
+ yield key, {
326
+ 'contract_name': row['contract_name'],
327
+ 'contract_address': row['contract_address'],
328
+ 'language': row['language'],
329
+ 'source_code': row['source_code'],
330
+ **{ t: row[t] for t in _TOOLS[data_split][tool] },
331
+ 'abi': row['abi'],
332
+ 'compiler_version': row['compiler_version'],
333
+ 'optimization_used': row['optimization_used'],
334
+ 'runs': row['runs'],
335
+ 'constructor_arguments': row['constructor_arguments'],
336
+ 'evm_version': row['evm_version'],
337
+ 'library': row['library'],
338
+ 'license_type': row['license_type'],
339
+ 'proxy': row['proxy'],
340
+ 'implementation': row['implementation'],
341
+ 'swarm_source': row['swarm_source'],
342
+ **({'tx_count': row["tx_count"]} if metadata is not None else {}),
343
+ **({'balance': row["balance"]} if metadata is not None else {})
344
+ }
345
+
346
+ elif "inflated" in self.config.name:
347
+ # Yields examples as (key, example) tuples
348
+ key = row['contract_address'] + ":" + row['file_path'] + ":" + str(hash(row['source_code']))
349
+ if "embedded" in self.config.name:
350
+ is_vulnerable = False
351
+ is_secure = False
352
+ for t in _TOOLS[data_split][tool]:
353
+ if pd.isnull(row[t]):
354
+ continue
355
+ if row[t] == "[]":
356
+ is_secure = True
357
+ continue
358
+
359
+ vuln_levels = [_TOOLS_AUDIT_DESC[t]["level_col"] + '": "' + k for k,v in _LEVELS.items() if v >= _LEVELS[lvl]]
360
+ if any(_check_strings(vuln_levels, row[t])):
361
+ is_vulnerable = True
362
+ break
363
+ else:
364
+ is_secure = True
365
+ continue
366
+
367
+ label = ""
368
+ if is_vulnerable:
369
+ label = "// VULNERABLE\n"
370
+ elif is_secure:
371
+ label = "// SECURE\n"
372
+ else:
373
+ label = "// UNKNOWN\n"
374
+
375
+ yield key, {
376
+ 'text': label + row['source_code'],
377
+ 'language': row['language'],
378
+ }
379
+ else:
380
+ yield key, {
381
+ 'contract_name': row['contract_name'],
382
+ 'file_path': row['file_path'],
383
+ 'contract_address': row['contract_address'],
384
+ 'language': row['language'],
385
+ 'source_code': row['source_code'],
386
+ **{ t: row[t] for t in _TOOLS[data_split][tool] },
387
+ 'compiler_version': row['compiler_version'],
388
+ 'license_type': row['license_type'],
389
+ 'swarm_source': row['swarm_source']
390
+ }