File size: 7,990 Bytes
27b5d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Dataset of Slither audited Solidity Smart Contracts."""

import json

import datasets
import pandas as pd

_LABELS = {
    'all': [
        'uninitialized-state','constant-function-asm', 'locked-ether',
        'incorrect-shift', 'divide-before-multiply', 'unused-return',
        'write-after-write', 'reentrancy-no-eth', 'unchecked-lowlevel',
        'incorrect-equality', 'weak-prng', 'arbitrary-send',
        'uninitialized-local', 'reentrancy-eth', 'shadowing-abstract',
        'controlled-delegatecall', 'unchecked-transfer', 'erc20-interface',
        'controlled-array-length', 'tautology', 'shadowing-state',
        'tx-origin', 'unprotected-upgrade', 'suicidal',
        'boolean-cst', 'unchecked-send', 'msg-value-loop',
        'erc721-interface', 'constant-function-state', 'delegatecall-loop',
        'mapping-deletion', 'reused-constructor', 'uninitialized-storage',
        'public-mappings-nested', 'array-by-reference','backdoor',
        'rtlo', 'name-reused','safe'],
    'big': ['access-control', 'arithmetic', 'other', 'reentrancy', 'safe', 'unchecked-calls'],
    'small': ['access-control', 'arithmetic', 'other', 'reentrancy', 'safe', 'unchecked-calls', 'locked-ether', 'bad-randomness', 'double-spending']
}


_CITATION = """\
@misc{rossini2022slitherauditedcontracts,
    title = {Slither Audited Smart Contracts Dataset},
    author={Martina Rossini},
    year={2022}
}
"""


_DESCRIPTION = """\
This dataset contains source code and deployed bytecode for Solidity Smart Contracts \
that have been verified on Etherscan.io, along with a classification of their vulnerabilities \
according to the Slither static analysis framework.
"""

_HOMEPAGE = "https://github.com/mwritescode/slither-audited-smart-contracts"

_LICENSE = "MIT"


_URLS = {
    "raw": [f"data/raw/contracts{i}.parquet" for i in range(9)],
    "label_mappings": "data/label_mappings.json",
    "big-splits": "data/big-splits.csv",
    "small-splits": "data/small-splits.csv"
}


class SlitherAuditedSmartContracts(datasets.GeneratorBasedBuilder):
    """Slither Audited Smart Contracts dataset, including source code and deployed bytecode"""

    VERSION = datasets.Version("1.1.0")

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('slither-audited-smart-contracts', 'all-plain-text')
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="all-plain-text", version=VERSION, description="Complete dataset with plain-text slither results"),
        datasets.BuilderConfig(name="all-multilabel", version=VERSION, description="Complete dataset with slither results as sequence of labels"),
        datasets.BuilderConfig(name="big-plain-text", version=VERSION, description="Dataset containing only labels having numerous examples with plain-text slither results"),
        datasets.BuilderConfig(name="big-multilabel", version=VERSION, description="Dataset containing only labels having numerous examples with slither results as a sequence of labels"),
        datasets.BuilderConfig(name="small-plain-text", version=VERSION, description="Dataset containing only labels having few examples with plain-text slither results"),
        datasets.BuilderConfig(name="small-multilabel", version=VERSION, description="Dataset containing only labels having few examples with slither results as a sequence of labels")
    ]

    def _info(self):
        if "plain-text" in self.config.name: 
            features = datasets.Features(
                {
                    "address": datasets.Value("string"),
                    "source_code": datasets.Value("string"),
                    "bytecode": datasets.Value("string"),
                    "slither": datasets.Value("string"),
                }
            )
        else: 
            features = datasets.Features(
                {
                    "address": datasets.Value("string"),
                    "source_code": datasets.Value("string"),
                    "bytecode": datasets.Value("string"),
                    "slither": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=_LABELS[self.config.name.split('-')[0]]
                        )
                    )
                    
                }
            )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features, 
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        data_dir = dl_manager.download_and_extract(_URLS)

        generators = [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": data_dir,
                    "split": "train"
                },
            )]
        if self.config.name.split('-')[0] != 'all':
            generators += [
                datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepath": data_dir,
                    "split": "test"
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "filepath": data_dir,
                    "split": "val"
                },
            )]
        return generators

    def __elaborate_results(self, slither_res, mappings):
        if not slither_res["results"]:
            contract_class = ["safe"]
        else:
            contract_class = [elem["check"] for elem in slither_res["results"]["detectors"]]
            if self.config.name.split('-')[0] != 'all':
                with open(mappings, 'r') as mappings_file:
                    class_mappings = json.load(mappings_file)
                contract_class = list(set([class_mappings[cls] for cls in contract_class]) - {'ignore'})
                if len(contract_class) == 0:
                    contract_class = ['safe']
        return contract_class


    def _generate_examples(self, filepath, split):
        prefix = self.config.name.split('-')[0]
        split_file = filepath[f"{prefix}-splits"] if prefix != 'all' else None

        for chunk in filepath['raw']:
            data = pd.read_parquet(chunk)
            if split_file:
                split_addrs = pd.read_csv(split_file).query('split == @split')['contracts']
                data = data[data['contracts'].isin(split_addrs)]

            for idx, row in data.iterrows():
                if 'plain-text' in self.config.name:
                    yield idx, {
                        "address": row['contracts'],
                        "source_code": row['source_code'],
                        "bytecode": row['bytecode'],
                        "slither": row['results'],
                    }
                else:
                    slither = json.loads(row['results'])
                    contract_classes = self.__elaborate_results(slither, filepath['label_mappings'])
                    yield idx, {
                        "address": row['contracts'],
                        "source_code": row['source_code'],
                        "bytecode": row['bytecode'],
                        "slither": contract_classes,
                    }