id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,286,000 | contract.py | NioTheFirst_ScType/slither/printers/summary/contract.py | """
Module printing summary of the contract
"""
import collections
from slither.printers.abstract_printer import AbstractPrinter
from slither.utils import output
from slither.utils.colors import blue, green, magenta
class ContractSummary(AbstractPrinter):
ARGUMENT = "contract-summary"
HELP = "Print a summary of the contracts"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#contract-summary"
def output(self, _filename): # pylint: disable=too-many-locals
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
all_contracts = []
for c in self.contracts:
if c.is_top_level:
continue
is_upgradeable_proxy = c.is_upgradeable_proxy
is_upgradeable = c.is_upgradeable
additional_txt_info = ""
if is_upgradeable_proxy:
additional_txt_info += " (Upgradeable Proxy)"
if is_upgradeable:
additional_txt_info += " (Upgradeable)"
if c in self.slither.contracts_derived:
additional_txt_info += " (Most derived contract)"
txt += blue(f"\n+ Contract {c.name}{additional_txt_info}\n")
additional_fields = output.Output(
"",
additional_fields={
"is_upgradeable_proxy": is_upgradeable_proxy,
"is_upgradeable": is_upgradeable,
"is_most_derived": c in self.slither.contracts_derived,
},
)
# Order the function with
# contract_declarer -> list_functions
public = [
(f.contract_declarer.name, f)
for f in c.functions
if (not f.is_shadowed and not f.is_constructor_variables)
]
collect = collections.defaultdict(list)
for a, b in public:
collect[a].append(b)
public = list(collect.items())
for contract, functions in public:
txt += blue(f" - From {contract}\n")
functions = sorted(functions, key=lambda f: f.full_name)
for function in functions:
if function.visibility in ["external", "public"]:
txt += green(f" - {function.full_name} ({function.visibility})\n")
if function.visibility in ["internal", "private"]:
txt += magenta(f" - {function.full_name} ({function.visibility})\n")
if function.visibility not in [
"external",
"public",
"internal",
"private",
]:
txt += f" - {function.full_name} Â ({function.visibility})\n"
additional_fields.add(
function, additional_fields={"visibility": function.visibility}
)
all_contracts.append((c, additional_fields.data))
self.info(txt)
res = self.generate_output(txt)
for contract, additional_fields in all_contracts:
res.add(contract, additional_fields=additional_fields)
return res
| 3,327 | Python | .py | 75 | 30.333333 | 95 | 0.54039 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,001 | slithir_ssa.py | NioTheFirst_ScType/slither/printers/summary/slithir_ssa.py | """
Module printing summary of the contract
"""
from slither.printers.abstract_printer import AbstractPrinter
class PrinterSlithIRSSA(AbstractPrinter):
ARGUMENT = "slithir-ssa"
HELP = "Print the slithIR representation of the functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#slithir-ssa"
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
for contract in self.contracts:
if contract.is_top_level:
continue
txt += f"Contract {contract.name}" + "\n"
for function in contract.functions:
txt += f"\tFunction {function.canonical_name}" + "\n"
for node in function.nodes:
if node.expression:
txt += f"\t\tExpression: {node.expression}" + "\n"
if node.irs_ssa:
txt += "\t\tIRs:" + "\n"
for ir in node.irs_ssa:
txt += f"\t\t\t{ir}" + "\n"
for modifier in contract.modifiers:
txt += f"\tModifier {modifier.canonical_name}" + "\n"
for node in modifier.nodes:
txt += str(node) + "\n"
if node.expression:
txt += f"\t\tExpression: {node.expression}" + "\n"
if node.irs_ssa:
txt += "\t\tIRs:" + "\n"
for ir in node.irs_ssa:
txt += f"\t\t\t{ir}" + "\n"
self.info(txt)
res = self.generate_output(txt)
return res
| 1,711 | Python | .py | 41 | 27.585366 | 90 | 0.491882 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,002 | constructor_calls.py | NioTheFirst_ScType/slither/printers/summary/constructor_calls.py | """
Module printing summary of the contract
"""
from slither.core.source_mapping.source_mapping import Source
from slither.printers.abstract_printer import AbstractPrinter
from slither.utils import output
class ConstructorPrinter(AbstractPrinter):
WIKI = "https://github.com/crytic/slither/wiki/Printer-documentation#constructor-calls"
ARGUMENT = "constructor-calls"
HELP = "Print the constructors executed"
def _get_soruce_code(self, cst):
src_mapping: Source = cst.source_mapping
content = self.slither.source_code[src_mapping.filename.absolute]
start = src_mapping.start
end = src_mapping.start + src_mapping.length
initial_space = src_mapping.starting_column
return " " * initial_space + content[start:end]
def output(self, _filename):
info = ""
for contract in self.slither.contracts_derived:
stack_name = []
stack_definition = []
cst = contract.constructors_declared
if cst:
stack_name.append(contract.name)
stack_definition.append(self._get_soruce_code(cst))
for inherited_contract in contract.inheritance:
cst = inherited_contract.constructors_declared
if cst:
stack_name.append(inherited_contract.name)
stack_definition.append(self._get_soruce_code(cst))
if len(stack_name) > 0:
info += "\n########" + "#" * len(contract.name) + "########\n"
info += "####### " + contract.name + " #######\n"
info += "########" + "#" * len(contract.name) + "########\n\n"
info += "## Constructor Call Sequence" + "\n"
for name in stack_name[::-1]:
info += "\t- " + name + "\n"
info += "\n## Constructor Definitions" + "\n"
count = len(stack_definition) - 1
while count >= 0:
info += "\n### " + stack_name[count] + "\n"
info += "\n" + str(stack_definition[count]) + "\n"
count = count - 1
self.info(info)
res = output.Output(info)
return res
| 2,292 | Python | .py | 47 | 35.87234 | 92 | 0.545985 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,003 | function_ids.py | NioTheFirst_ScType/slither/printers/summary/function_ids.py | """
Module printing summary of the contract
"""
from slither.printers.abstract_printer import AbstractPrinter
from slither.utils.function import get_function_id
from slither.utils.myprettytable import MyPrettyTable
class FunctionIds(AbstractPrinter):
ARGUMENT = "function-id"
HELP = "Print the keccak256 signature of the functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#function-id"
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
all_tables = []
for contract in self.slither.contracts_derived:
txt += f"\n{contract.name}:\n"
table = MyPrettyTable(["Name", "ID"])
for function in contract.functions:
if function.is_shadowed or function.is_constructor_variables:
continue
if function.visibility in ["public", "external"]:
function_id = get_function_id(function.solidity_signature)
table.add_row([function.solidity_signature, f"{function_id:#0{10}x}"])
for variable in contract.state_variables:
if variable.visibility in ["public"]:
sig = variable.solidity_signature
function_id = get_function_id(sig)
table.add_row([sig, f"{function_id:#0{10}x}"])
txt += str(table) + "\n"
all_tables.append((contract.name, table))
self.info(txt)
res = self.generate_output(txt)
for name, table in all_tables:
res.add_pretty_table(table, name)
return res
| 1,698 | Python | .py | 39 | 32.769231 | 90 | 0.606667 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,004 | inheritance_graph.py | NioTheFirst_ScType/slither/printers/inheritance/inheritance_graph.py | """
Module printing the inheritance graph
The inheritance graph shows the relation between the contracts
and their functions/modifiers/public variables.
The output is a dot file named filename.dot
"""
from slither.core.declarations.contract import Contract
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.printers.abstract_printer import AbstractPrinter
from slither.utils.inheritance_analysis import (
detect_c3_function_shadowing,
detect_state_variable_shadowing,
)
def _get_pattern_func(func):
# Html pattern, each line is a row in a table
func_name = func.full_name
pattern = '<TR><TD align="left"> %s</TD></TR>'
pattern_shadow = '<TR><TD align="left"><font color="#FFA500"> %s</font></TD></TR>'
if func.shadows:
return pattern_shadow % func_name
return pattern % func_name
def _get_port_id(var, contract):
return f"{var.name}{contract.name}"
class PrinterInheritanceGraph(AbstractPrinter):
ARGUMENT = "inheritance-graph"
HELP = "Export the inheritance graph of each contract to a dot file"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#inheritance-graph"
def __init__(self, slither, logger):
super().__init__(slither, logger)
inheritance = [x.inheritance for x in slither.contracts]
self.inheritance = {item for sublist in inheritance for item in sublist}
self.overshadowing_state_variables = {}
shadows = detect_state_variable_shadowing(slither.contracts)
for overshadowing_instance in shadows:
overshadowing_state_var = overshadowing_instance[1]
overshadowed_state_var = overshadowing_instance[3]
# Add overshadowing variable entry.
if overshadowing_state_var not in self.overshadowing_state_variables:
self.overshadowing_state_variables[overshadowing_state_var] = set()
self.overshadowing_state_variables[overshadowing_state_var].add(overshadowed_state_var)
def _get_pattern_var(self, var):
# Html pattern, each line is a row in a table
var_name = var.name
pattern = '<TR><TD align="left"> %s</TD></TR>'
pattern_contract = (
'<TR><TD align="left"> %s<font color="blue" POINT-SIZE="10"> (%s)</font></TD></TR>'
)
pattern_shadow = '<TR><TD align="left"><font color="red"> %s</font></TD></TR>'
pattern_contract_shadow = '<TR><TD align="left"><font color="red"> %s</font><font color="blue" POINT-SIZE="10"> (%s)</font></TD></TR>'
if isinstance(var.type, UserDefinedType) and isinstance(var.type.type, Contract):
if var in self.overshadowing_state_variables:
return pattern_contract_shadow % (var_name, var.type.type.name)
return pattern_contract % (var_name, var.type.type.name)
if var in self.overshadowing_state_variables:
return pattern_shadow % var_name
return pattern % var_name
@staticmethod
def _get_indirect_shadowing_information(contract):
"""
Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists.
:param var: The variable to collect shadowing information for.
:param contract: The contract in which this variable is being analyzed.
:return: Returns a string describing variable shadowing for the given variable. None if no shadowing exists.
"""
# If this variable is an overshadowing variable, we'll want to return information describing it.
result = []
indirect_shadows = detect_c3_function_shadowing(contract)
for winner, colliding_functions in indirect_shadows.items():
collision_steps = ", ".join(
[f.contract_declarer.name for f in colliding_functions]
+ [winner.contract_declarer.name]
)
result.append(
f"'{winner.full_name}' collides in inherited contracts {collision_steps} where {winner.contract_declarer.name} is chosen."
)
return "\n".join(result)
def _summary(self, contract):
"""
Build summary using HTML
"""
ret = ""
# Add arrows (number them if there is more than one path so we know order of declaration for inheritance).
if len(contract.immediate_inheritance) == 1:
ret += f"{contract.name} -> {contract.immediate_inheritance[0]};\n"
else:
for i, immediate_inheritance in enumerate(contract.immediate_inheritance):
ret += f'{contract.name} -> {immediate_inheritance} [ label="{i + 1}" ];\n'
# Functions
visibilities = ["public", "external"]
public_functions = [
_get_pattern_func(f)
for f in contract.functions
if not f.is_constructor
and not f.is_constructor_variables
and f.contract_declarer == contract
and f.visibility in visibilities
]
public_functions = "".join(public_functions)
private_functions = [
_get_pattern_func(f)
for f in contract.functions
if not f.is_constructor
and not f.is_constructor_variables
and f.contract_declarer == contract
and f.visibility not in visibilities
]
private_functions = "".join(private_functions)
# Modifiers
modifiers = [
_get_pattern_func(m) for m in contract.modifiers if m.contract_declarer == contract
]
modifiers = "".join(modifiers)
# Public variables
public_variables = [
self._get_pattern_var(v)
for v in contract.state_variables_declared
if v.visibility in visibilities
]
public_variables = "".join(public_variables)
private_variables = [
self._get_pattern_var(v)
for v in contract.state_variables_declared
if v.visibility not in visibilities
]
private_variables = "".join(private_variables)
# Obtain any indirect shadowing information for this node.
indirect_shadowing_information = self._get_indirect_shadowing_information(contract)
# Build the node label
ret += f'{contract.name}[shape="box"'
ret += 'label=< <TABLE border="0">'
ret += f'<TR><TD align="center"><B>{contract.name}</B></TD></TR>'
if public_functions:
ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>'
ret += f"{public_functions}"
if private_functions:
ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>'
ret += f"{private_functions}"
if modifiers:
ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>'
ret += f"{modifiers}"
if public_variables:
ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>'
ret += f"{public_variables}"
if private_variables:
ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>'
ret += f"{private_variables}"
if indirect_shadowing_information:
ret += (
'<TR><TD><BR/></TD></TR><TR><TD align="left" border="1"><font color="#777777" point-size="10">%s</font></TD></TR>'
% indirect_shadowing_information.replace("\n", "<BR/>")
)
ret += "</TABLE> >];\n"
return ret
def output(self, filename):
"""
Output the graph in filename
Args:
filename(string)
"""
if filename in ("", "."):
filename = "inheritance-graph.dot"
if not filename.endswith(".dot"):
filename += ".inheritance-graph.dot"
info = "Inheritance Graph: " + filename + "\n"
self.info(info)
content = 'digraph "" {\n'
for c in self.contracts:
if c.is_top_level:
continue
content += self._summary(c) + "\n"
content += "}"
with open(filename, "w", encoding="utf8") as f:
f.write(content)
res = self.generate_output(info)
res.add_file(filename, content)
return res
| 8,331 | Python | .py | 176 | 37.517045 | 145 | 0.613074 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,005 | inheritance.py | NioTheFirst_ScType/slither/printers/inheritance/inheritance.py | """
Module printing the inheritance relation
The inheritance shows the relation between the contracts
"""
from slither.printers.abstract_printer import AbstractPrinter
from slither.utils.colors import blue, green
class PrinterInheritance(AbstractPrinter):
ARGUMENT = "inheritance"
HELP = "Print the inheritance relations between contracts"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#inheritance"
def _get_child_contracts(self, base):
# Generate function to get all child contracts of a base contract
for child in self.contracts:
if base in child.inheritance:
yield child
def output(self, filename):
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
info = "Inheritance\n"
info += blue("Child_Contract -> ") + green("Immediate_Base_Contracts")
info += green(" [Not_Immediate_Base_Contracts]")
result = {"child_to_base": {}}
for child in self.contracts:
if child.is_top_level:
continue
info += blue(f"\n+ {child.name}\n")
result["child_to_base"][child.name] = {"immediate": [], "not_immediate": []}
if child.inheritance:
immediate = child.immediate_inheritance
not_immediate = [i for i in child.inheritance if i not in immediate]
info += " -> " + green(", ".join(map(str, immediate))) + "\n"
result["child_to_base"][child.name]["immediate"] = list(map(str, immediate))
if not_immediate:
info += ", [" + green(", ".join(map(str, not_immediate))) + "]\n"
result["child_to_base"][child.name]["not_immediate"] = list(
map(str, not_immediate)
)
info += green("\n\nBase_Contract -> ") + blue("Immediate_Child_Contracts") + "\n"
info += blue(" [Not_Immediate_Child_Contracts]") + "\n"
result["base_to_child"] = {}
for base in self.contracts:
if base.is_top_level:
continue
info += green(f"\n+ {base.name}") + "\n"
children = list(self._get_child_contracts(base))
result["base_to_child"][base.name] = {"immediate": [], "not_immediate": []}
if children:
immediate = [child for child in children if base in child.immediate_inheritance]
not_immediate = [child for child in children if not child in immediate]
info += " -> " + blue(", ".join(map(str, immediate))) + "\n"
result["base_to_child"][base.name]["immediate"] = list(map(str, immediate))
if not_immediate:
info += ", [" + blue(", ".join(map(str, not_immediate))) + "]" + "\n"
result["base_to_child"][base.name]["not_immediate"] = list(map(str, immediate))
self.info(info)
res = self.generate_output(info, additional_fields=result)
return res
| 3,117 | Python | .py | 61 | 39.229508 | 99 | 0.56997 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,006 | call_graph.py | NioTheFirst_ScType/slither/printers/call/call_graph.py | """
Module printing the call graph
The call graph shows for each function,
what are the contracts/functions called.
The output is a dot file named filename.dot
"""
from collections import defaultdict
from slither.printers.abstract_printer import AbstractPrinter
from slither.core.declarations.solidity_variables import SolidityFunction
from slither.core.declarations.function import Function
from slither.core.variables.variable import Variable
def _contract_subgraph(contract):
return f"cluster_{contract.id}_{contract.name}"
# return unique id for contract function to use as node name
def _function_node(contract, function):
return f"{contract.id}_{function.name}"
# return unique id for solidity function to use as node name
def _solidity_function_node(solidity_function):
return f"{solidity_function.name}"
# return dot language string to add graph edge
def _edge(from_node, to_node):
return f'"{from_node}" -> "{to_node}"'
# return dot language string to add graph node (with optional label)
def _node(node, label=None):
return " ".join(
(
f'"{node}"',
f'[label="{label}"]' if label is not None else "",
)
)
# pylint: disable=too-many-arguments
def _process_internal_call(
contract,
function,
internal_call,
contract_calls,
solidity_functions,
solidity_calls,
):
if isinstance(internal_call, (Function)):
contract_calls[contract].add(
_edge(
_function_node(contract, function),
_function_node(contract, internal_call),
)
)
elif isinstance(internal_call, (SolidityFunction)):
solidity_functions.add(
_node(_solidity_function_node(internal_call)),
)
solidity_calls.add(
_edge(
_function_node(contract, function),
_solidity_function_node(internal_call),
)
)
def _render_external_calls(external_calls):
return "\n".join(external_calls)
def _render_internal_calls(contract, contract_functions, contract_calls):
lines = []
lines.append(f"subgraph {_contract_subgraph(contract)} {{")
lines.append(f'label = "{contract.name}"')
lines.extend(contract_functions[contract])
lines.extend(contract_calls[contract])
lines.append("}")
return "\n".join(lines)
def _render_solidity_calls(solidity_functions, solidity_calls):
lines = []
lines.append("subgraph cluster_solidity {")
lines.append('label = "[Solidity]"')
lines.extend(solidity_functions)
lines.extend(solidity_calls)
lines.append("}")
return "\n".join(lines)
def _process_external_call(
contract,
function,
external_call,
contract_functions,
external_calls,
all_contracts,
):
external_contract, external_function = external_call
if not external_contract in all_contracts:
return
# add variable as node to respective contract
if isinstance(external_function, (Variable)):
contract_functions[external_contract].add(
_node(
_function_node(external_contract, external_function),
external_function.name,
)
)
external_calls.add(
_edge(
_function_node(contract, function),
_function_node(external_contract, external_function),
)
)
# pylint: disable=too-many-arguments
def _process_function(
contract,
function,
contract_functions,
contract_calls,
solidity_functions,
solidity_calls,
external_calls,
all_contracts,
):
contract_functions[contract].add(
_node(_function_node(contract, function), function.name),
)
for internal_call in function.internal_calls:
_process_internal_call(
contract,
function,
internal_call,
contract_calls,
solidity_functions,
solidity_calls,
)
for external_call in function.high_level_calls:
_process_external_call(
contract,
function,
external_call,
contract_functions,
external_calls,
all_contracts,
)
def _process_functions(functions):
contract_functions = defaultdict(set) # contract -> contract functions nodes
contract_calls = defaultdict(set) # contract -> contract calls edges
solidity_functions = set() # solidity function nodes
solidity_calls = set() # solidity calls edges
external_calls = set() # external calls edges
all_contracts = set()
for function in functions:
all_contracts.add(function.contract_declarer)
for function in functions:
_process_function(
function.contract_declarer,
function,
contract_functions,
contract_calls,
solidity_functions,
solidity_calls,
external_calls,
all_contracts,
)
render_internal_calls = ""
for contract in all_contracts:
render_internal_calls += _render_internal_calls(
contract, contract_functions, contract_calls
)
render_solidity_calls = _render_solidity_calls(solidity_functions, solidity_calls)
render_external_calls = _render_external_calls(external_calls)
return render_internal_calls + render_solidity_calls + render_external_calls
class PrinterCallGraph(AbstractPrinter):
ARGUMENT = "call-graph"
HELP = "Export the call-graph of the contracts to a dot file"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#call-graph"
def output(self, filename):
"""
Output the graph in filename
Args:
filename(string)
"""
all_contracts_filename = ""
if not filename.endswith(".dot"):
if filename in ("", "."):
filename = ""
else:
filename += "."
all_contracts_filename = f"{filename}all_contracts.call-graph.dot"
if filename == ".dot":
all_contracts_filename = "all_contracts.dot"
info = ""
results = []
with open(all_contracts_filename, "w", encoding="utf8") as f:
info += f"Call Graph: {all_contracts_filename}\n"
# Avoid duplicate functions due to different compilation unit
all_functionss = [
compilation_unit.functions for compilation_unit in self.slither.compilation_units
]
all_functions = [item for sublist in all_functionss for item in sublist]
all_functions_as_dict = {
function.canonical_name: function for function in all_functions
}
content = "\n".join(
["strict digraph {"] + [_process_functions(all_functions_as_dict.values())] + ["}"]
)
f.write(content)
results.append((all_contracts_filename, content))
for derived_contract in self.slither.contracts_derived:
derived_output_filename = f"{filename}{derived_contract.name}.call-graph.dot"
with open(derived_output_filename, "w", encoding="utf8") as f:
info += f"Call Graph: {derived_output_filename}\n"
content = "\n".join(
["strict digraph {"] + [_process_functions(derived_contract.functions)] + ["}"]
)
f.write(content)
results.append((derived_output_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in results:
res.add_file(filename_result, content)
return res
| 7,767 | Python | .py | 209 | 28.779904 | 99 | 0.635612 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,007 | dominator.py | NioTheFirst_ScType/slither/printers/functions/dominator.py | from slither.printers.abstract_printer import AbstractPrinter
class Dominator(AbstractPrinter):
ARGUMENT = "dominator"
HELP = "Export the dominator tree of each functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#dominator"
def output(self, filename):
"""
_filename is not used
Args:
_filename(string)
"""
info = ""
all_files = []
for contract in self.contracts:
for function in contract.functions + contract.modifiers:
if filename:
new_filename = f"{filename}-{contract.name}-{function.full_name}.dot"
else:
new_filename = f"dominator-{contract.name}-{function.full_name}.dot"
info += f"Export {new_filename}\n"
content = function.dominator_tree_to_dot(new_filename)
all_files.append((new_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in all_files:
res.add_file(filename_result, content)
return res
| 1,153 | Python | .py | 27 | 31.777778 | 89 | 0.607335 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,008 | authorization.py | NioTheFirst_ScType/slither/printers/functions/authorization.py | """
Module printing summary of the contract
"""
from slither.printers.abstract_printer import AbstractPrinter
from slither.core.declarations.function import Function
from slither.utils.myprettytable import MyPrettyTable
class PrinterWrittenVariablesAndAuthorization(AbstractPrinter):
ARGUMENT = "vars-and-auth"
HELP = "Print the state variables written and the authorization of the functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#variables-written-and-authorization"
@staticmethod
def get_msg_sender_checks(function):
all_functions = function.all_internal_calls() + [function] + function.modifiers
all_nodes = [f.nodes for f in all_functions if isinstance(f, Function)]
all_nodes = [item for sublist in all_nodes for item in sublist]
all_conditional_nodes = [
n for n in all_nodes if n.contains_if() or n.contains_require_or_assert()
]
all_conditional_nodes_on_msg_sender = [
str(n.expression)
for n in all_conditional_nodes
if "msg.sender" in [v.name for v in n.solidity_variables_read]
]
return all_conditional_nodes_on_msg_sender
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
all_tables = []
for contract in self.contracts:
if contract.is_top_level:
continue
txt += f"\nContract {contract.name}\n"
table = MyPrettyTable(
["Function", "State variables written", "Conditions on msg.sender"]
)
for function in contract.functions:
state_variables_written = [v.name for v in function.all_state_variables_written()]
msg_sender_condition = self.get_msg_sender_checks(function)
table.add_row(
[
function.name,
str(sorted(state_variables_written)),
str(sorted(msg_sender_condition)),
]
)
all_tables.append((contract.name, table))
txt += str(table) + "\n"
self.info(txt)
res = self.generate_output(txt)
for name, table in all_tables:
res.add_pretty_table(table, name)
return res
| 2,412 | Python | .py | 56 | 32.125 | 114 | 0.607768 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,009 | cfg.py | NioTheFirst_ScType/slither/printers/functions/cfg.py | from slither.printers.abstract_printer import AbstractPrinter
class CFG(AbstractPrinter):
ARGUMENT = "cfg"
HELP = "Export the CFG of each functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#cfg"
def output(self, filename):
"""
_filename is not used
Args:
_filename(string)
"""
info = ""
all_files = []
for contract in self.contracts:
if contract.is_top_level:
continue
for function in contract.functions + contract.modifiers:
if filename:
new_filename = f"{filename}-{contract.name}-{function.full_name}.dot"
else:
new_filename = f"{contract.name}-{function.full_name}.dot"
info += f"Export {new_filename}\n"
content = function.slithir_cfg_to_dot_str()
with open(new_filename, "w", encoding="utf8") as f:
f.write(content)
all_files.append((new_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in all_files:
res.add_file(filename_result, content)
return res
| 1,271 | Python | .py | 31 | 29.290323 | 89 | 0.573864 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,010 | echidna.py | NioTheFirst_ScType/slither/printers/guidance/echidna.py | import json
from collections import defaultdict
from typing import Dict, List, Set, Tuple, NamedTuple, Union
from slither.analyses.data_dependency.data_dependency import is_dependent
from slither.core.cfg.node import Node
from slither.core.declarations import Function
from slither.core.declarations.solidity_variables import (
SolidityVariableComposed,
SolidityFunction,
SolidityVariable,
)
from slither.core.expressions import NewContract
from slither.core.slither_core import SlitherCore
from slither.core.variables.state_variable import StateVariable
from slither.core.variables.variable import Variable
from slither.printers.abstract_printer import AbstractPrinter
from slither.slithir.operations import (
Member,
Operation,
SolidityCall,
LowLevelCall,
HighLevelCall,
EventCall,
Send,
Transfer,
InternalDynamicCall,
InternalCall,
TypeConversion,
)
from slither.slithir.operations.binary import Binary
from slither.slithir.variables import Constant
from slither.visitors.expression.constants_folding import ConstantFolding
def _get_name(f: Union[Function, Variable]) -> str:
# Return the name of the function or variable
if isinstance(f, Function):
if f.is_fallback or f.is_receive:
return "()"
return f.solidity_signature
def _extract_payable(slither: SlitherCore) -> Dict[str, List[str]]:
ret: Dict[str, List[str]] = {}
for contract in slither.contracts:
payable_functions = [_get_name(f) for f in contract.functions_entry_points if f.payable]
if payable_functions:
ret[contract.name] = payable_functions
return ret
def _extract_solidity_variable_usage(
slither: SlitherCore, sol_var: SolidityVariable
) -> Dict[str, List[str]]:
ret: Dict[str, List[str]] = {}
for contract in slither.contracts:
functions_using_sol_var = []
for f in contract.functions_entry_points:
for v in f.all_solidity_variables_read():
if v == sol_var:
functions_using_sol_var.append(_get_name(f))
break
if functions_using_sol_var:
ret[contract.name] = functions_using_sol_var
return ret
def _is_constant(f: Function) -> bool: # pylint: disable=too-many-branches
"""
Heuristic:
- If view/pure with Solidity >= 0.4 -> Return true
- If it contains assembly -> Return false (SlitherCore doesn't analyze asm)
- Otherwise check for the rules from
https://solidity.readthedocs.io/en/v0.5.0/contracts.html?highlight=pure#view-functions
with an exception: internal dynamic call are not correctly handled, so we consider them as non-constant
:param f:
:return:
"""
if f.view or f.pure:
if not f.contract.compilation_unit.solc_version.startswith("0.4"):
return True
if f.payable:
return False
if not f.is_implemented:
return False
if f.contains_assembly:
return False
if f.all_state_variables_written():
return False
for ir in f.all_slithir_operations():
if isinstance(ir, InternalDynamicCall):
return False
if isinstance(ir, (EventCall, NewContract, LowLevelCall, Send, Transfer)):
return False
if isinstance(ir, SolidityCall) and ir.function in [
SolidityFunction("selfdestruct(address)"),
SolidityFunction("suicide(address)"),
]:
return False
if isinstance(ir, HighLevelCall):
if isinstance(ir.function, Variable) or ir.function.view or ir.function.pure:
# External call to constant functions are ensured to be constant only for solidity >= 0.5
if f.contract.compilation_unit.solc_version.startswith("0.4"):
return False
else:
return False
if isinstance(ir, InternalCall):
# Storage write are not properly handled by all_state_variables_written
if any(parameter.is_storage for parameter in ir.function.parameters):
return False
return True
def _extract_constant_functions(slither: SlitherCore) -> Dict[str, List[str]]:
ret: Dict[str, List[str]] = {}
for contract in slither.contracts:
cst_functions = [_get_name(f) for f in contract.functions_entry_points if _is_constant(f)]
cst_functions += [
v.solidity_signature for v in contract.state_variables if v.visibility in ["public"]
]
if cst_functions:
ret[contract.name] = cst_functions
return ret
def _extract_assert(slither: SlitherCore) -> Dict[str, List[str]]:
ret: Dict[str, List[str]] = {}
for contract in slither.contracts:
functions_using_assert = []
for f in contract.functions_entry_points:
for v in f.all_solidity_calls():
if v == SolidityFunction("assert(bool)"):
functions_using_assert.append(_get_name(f))
break
if functions_using_assert:
ret[contract.name] = functions_using_assert
return ret
# Create a named tuple that is serialization in json
def json_serializable(cls):
# pylint: disable=unnecessary-comprehension
# TODO: the next line is a quick workaround to prevent pylint from crashing
# It can be removed once https://github.com/PyCQA/pylint/pull/3810 is merged
my_super = super
def as_dict(self):
yield {
name: value for name, value in zip(self._fields, iter(my_super(cls, self).__iter__()))
}
cls.__iter__ = as_dict
return cls
@json_serializable
class ConstantValue(NamedTuple): # pylint: disable=inherit-non-class,too-few-public-methods
# Here value should be Union[str, int, bool]
# But the json lib in Echidna does not handle large integer in json
# So we convert everything to string
value: str
type: str
def _extract_constants_from_irs( # pylint: disable=too-many-branches,too-many-nested-blocks
irs: List[Operation],
all_cst_used: List[ConstantValue],
all_cst_used_in_binary: Dict[str, List[ConstantValue]],
context_explored: Set[Node],
):
for ir in irs:
if isinstance(ir, Binary):
for r in ir.read:
if isinstance(r, Constant):
all_cst_used_in_binary[str(ir.type)].append(
ConstantValue(str(r.value), str(r.type))
)
if isinstance(ir.variable_left, Constant) and isinstance(ir.variable_right, Constant):
if ir.lvalue:
type_ = ir.lvalue.type
cst = ConstantFolding(ir.expression, type_).result()
all_cst_used.append(ConstantValue(str(cst.value), str(type_)))
if isinstance(ir, TypeConversion):
if isinstance(ir.variable, Constant):
all_cst_used.append(ConstantValue(str(ir.variable.value), str(ir.type)))
continue
for r in ir.read:
# Do not report struct_name in a.struct_name
if isinstance(ir, Member):
continue
if isinstance(r, Constant):
all_cst_used.append(ConstantValue(str(r.value), str(r.type)))
if isinstance(r, StateVariable):
if r.node_initialization:
if r.node_initialization.irs:
if r.node_initialization in context_explored:
continue
context_explored.add(r.node_initialization)
_extract_constants_from_irs(
r.node_initialization.irs,
all_cst_used,
all_cst_used_in_binary,
context_explored,
)
def _extract_constants(
slither: SlitherCore,
) -> Tuple[Dict[str, Dict[str, List]], Dict[str, Dict[str, Dict]]]:
# contract -> function -> [ {"value": value, "type": type} ]
ret_cst_used: Dict[str, Dict[str, List[ConstantValue]]] = defaultdict(dict)
# contract -> function -> binary_operand -> [ {"value": value, "type": type ]
ret_cst_used_in_binary: Dict[str, Dict[str, Dict[str, List[ConstantValue]]]] = defaultdict(dict)
for contract in slither.contracts:
for function in contract.functions_entry_points:
all_cst_used: List = []
all_cst_used_in_binary: Dict = defaultdict(list)
context_explored = set()
context_explored.add(function)
_extract_constants_from_irs(
function.all_slithir_operations(),
all_cst_used,
all_cst_used_in_binary,
context_explored,
)
# Note: use list(set()) instead of set
# As this is meant to be serialized in JSON, and JSON does not support set
if all_cst_used:
ret_cst_used[contract.name][_get_name(function)] = list(set(all_cst_used))
if all_cst_used_in_binary:
ret_cst_used_in_binary[contract.name][_get_name(function)] = {
k: list(set(v)) for k, v in all_cst_used_in_binary.items()
}
return ret_cst_used, ret_cst_used_in_binary
def _extract_function_relations(
slither: SlitherCore,
) -> Dict[str, Dict[str, Dict[str, List[str]]]]:
# contract -> function -> [functions]
ret: Dict[str, Dict[str, Dict[str, List[str]]]] = defaultdict(dict)
for contract in slither.contracts:
ret[contract.name] = defaultdict(dict)
written = {
_get_name(function): function.all_state_variables_written()
for function in contract.functions_entry_points
}
read = {
_get_name(function): function.all_state_variables_read()
for function in contract.functions_entry_points
}
for function in contract.functions_entry_points:
ret[contract.name][_get_name(function)] = {
"impacts": [],
"is_impacted_by": [],
}
for candidate, varsWritten in written.items():
if any((r in varsWritten for r in function.all_state_variables_read())):
ret[contract.name][_get_name(function)]["is_impacted_by"].append(candidate)
for candidate, varsRead in read.items():
if any((r in varsRead for r in function.all_state_variables_written())):
ret[contract.name][_get_name(function)]["impacts"].append(candidate)
return ret
def _have_external_calls(slither: SlitherCore) -> Dict[str, List[str]]:
"""
Detect the functions with external calls
:param slither:
:return:
"""
ret: Dict[str, List[str]] = defaultdict(list)
for contract in slither.contracts:
for function in contract.functions_entry_points:
if function.all_high_level_calls() or function.all_low_level_calls():
ret[contract.name].append(_get_name(function))
if contract.name in ret:
ret[contract.name] = list(set(ret[contract.name]))
return ret
def _use_balance(slither: SlitherCore) -> Dict[str, List[str]]:
"""
Detect the functions with external calls
:param slither:
:return:
"""
ret: Dict[str, List[str]] = defaultdict(list)
for contract in slither.contracts:
for function in contract.functions_entry_points:
for ir in function.all_slithir_operations():
if isinstance(ir, SolidityCall) and ir.function == SolidityFunction(
"balance(address)"
):
ret[contract.name].append(_get_name(function))
if contract.name in ret:
ret[contract.name] = list(set(ret[contract.name]))
return ret
def _with_fallback(slither: SlitherCore) -> Set[str]:
ret: Set[str] = set()
for contract in slither.contracts:
for function in contract.functions_entry_points:
if function.is_fallback:
ret.add(contract.name)
return ret
def _with_receive(slither: SlitherCore) -> Set[str]:
ret: Set[str] = set()
for contract in slither.contracts:
for function in contract.functions_entry_points:
if function.is_receive:
ret.add(contract.name)
return ret
def _call_a_parameter(slither: SlitherCore) -> Dict[str, List[Dict]]:
"""
Detect the functions with external calls
:param slither:
:return:
"""
# contract -> [ (function, idx, interface_called) ]
ret: Dict[str, List[Dict]] = defaultdict(list)
for contract in slither.contracts: # pylint: disable=too-many-nested-blocks
for function in contract.functions_entry_points:
try:
for ir in function.all_slithir_operations():
if isinstance(ir, HighLevelCall):
for idx, parameter in enumerate(function.parameters):
if is_dependent(ir.destination, parameter, function):
ret[contract.name].append(
{
"function": _get_name(function),
"parameter_idx": idx,
"signature": _get_name(ir.function),
}
)
if isinstance(ir, LowLevelCall):
for idx, parameter in enumerate(function.parameters):
if is_dependent(ir.destination, parameter, function):
ret[contract.name].append(
{
"function": _get_name(function),
"parameter_idx": idx,
"signature": None,
}
)
except Exception as e:
if slither.no_fail:
continue
raise e
return ret
class Echidna(AbstractPrinter):
ARGUMENT = "echidna"
HELP = "Export Echidna guiding information"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#echidna"
def output(self, filename): # pylint: disable=too-many-locals
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
payable = _extract_payable(self.slither)
timestamp = _extract_solidity_variable_usage(
self.slither, SolidityVariableComposed("block.timestamp")
)
block_number = _extract_solidity_variable_usage(
self.slither, SolidityVariableComposed("block.number")
)
msg_sender = _extract_solidity_variable_usage(
self.slither, SolidityVariableComposed("msg.sender")
)
msg_gas = _extract_solidity_variable_usage(
self.slither, SolidityVariableComposed("msg.gas")
)
assert_usage = _extract_assert(self.slither)
cst_functions = _extract_constant_functions(self.slither)
(cst_used, cst_used_in_binary) = _extract_constants(self.slither)
functions_relations = _extract_function_relations(self.slither)
constructors = {
contract.name: contract.constructor.full_name
for contract in self.slither.contracts
if contract.constructor
}
external_calls = _have_external_calls(self.slither)
call_parameters = _call_a_parameter(self.slither)
use_balance = _use_balance(self.slither)
with_fallback = list(_with_fallback(self.slither))
with_receive = list(_with_receive(self.slither))
d = {
"payable": payable,
"timestamp": timestamp,
"block_number": block_number,
"msg_sender": msg_sender,
"msg_gas": msg_gas,
"assert": assert_usage,
"constant_functions": cst_functions,
"constants_used": cst_used,
"constants_used_in_binary": cst_used_in_binary,
"functions_relations": functions_relations,
"constructors": constructors,
"have_external_calls": external_calls,
"call_a_parameter": call_parameters,
"use_balance": use_balance,
"solc_versions": [unit.solc_version for unit in self.slither.compilation_units],
"with_fallback": with_fallback,
"with_receive": with_receive,
}
self.info(json.dumps(d, indent=4))
res = self.generate_output(json.dumps(d, indent=4))
return res
| 16,864 | Python | .py | 381 | 33.356955 | 107 | 0.607341 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,011 | evm_cfg_builder.py | NioTheFirst_ScType/slither/analyses/evm/evm_cfg_builder.py | import logging
from slither.exceptions import SlitherError
logger = logging.getLogger("ConvertToEVM")
def load_evm_cfg_builder():
try:
# Avoiding the addition of evm_cfg_builder as permanent dependency
# pylint: disable=import-outside-toplevel
from evm_cfg_builder.cfg import CFG
return CFG
except ImportError:
logger.error("To use evm features, you need to install evm-cfg-builder")
logger.error("Documentation: https://github.com/crytic/evm_cfg_builder")
logger.error("Installation: pip install evm-cfg-builder")
# pylint: disable=raise-missing-from
raise SlitherError("evm-cfg-builder not installed.")
| 689 | Python | .py | 15 | 39.333333 | 80 | 0.720896 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,012 | convert.py | NioTheFirst_ScType/slither/analyses/evm/convert.py | import logging
from slither.core.declarations import Contract, Function
from slither.core.cfg.node import Node
from slither.utils.function import get_function_id
from slither.exceptions import SlitherError
from slither.analyses.evm.evm_cfg_builder import load_evm_cfg_builder
logger = logging.getLogger("ConvertToEVM")
KEY_EVM_INS = "EVM_INSTRUCTIONS"
def get_evm_instructions(obj):
assert isinstance(obj, (Function, Contract, Node))
if KEY_EVM_INS not in obj.context:
CFG = load_evm_cfg_builder()
slither = obj.slither
if not slither.crytic_compile:
raise SlitherError("EVM features require to compile with crytic-compile")
contract_info = {}
function_info = {}
node_info = {}
if isinstance(obj, Node):
contract_info["contract"] = obj.function.contract
elif isinstance(obj, Function):
contract_info["contract"] = obj.contract
else:
contract_info["contract"] = obj
# Get contract runtime bytecode, srcmap and cfg
contract_info["bytecode_runtime"] = slither.crytic_compile.bytecode_runtime(
contract_info["contract"].name
)
contract_info["srcmap_runtime"] = slither.crytic_compile.srcmap_runtime(
contract_info["contract"].name
)
contract_info["cfg"] = CFG(contract_info["bytecode_runtime"])
# Get contract init bytecode, srcmap and cfg
contract_info["bytecode_init"] = slither.crytic_compile.bytecode_init(
contract_info["contract"].name
)
contract_info["srcmap_init"] = slither.crytic_compile.srcmap_init(
contract_info["contract"].name
)
contract_info["cfg_init"] = CFG(contract_info["bytecode_init"])
# Get evm instructions
if isinstance(obj, Contract):
# Get evm instructions for contract
obj.context[KEY_EVM_INS] = _get_evm_instructions_contract(contract_info)
elif isinstance(obj, Function):
# Get evm instructions for function
function_info["function"] = obj
function_info["contract_info"] = contract_info
obj.context[KEY_EVM_INS] = _get_evm_instructions_function(function_info)
else:
# Get evm instructions for node
node_info["node"] = obj
# CFG and srcmap depend on function being constructor or not
if node_info["node"].function.is_constructor:
cfg = contract_info["cfg_init"]
srcmap = contract_info["srcmap_init"]
else:
cfg = contract_info["cfg"]
srcmap = contract_info["srcmap_runtime"]
node_info["cfg"] = cfg
node_info["srcmap"] = srcmap
node_info["contract"] = contract_info["contract"]
node_info["slither"] = slither
obj.context[KEY_EVM_INS] = _get_evm_instructions_node(node_info)
return obj.context.get(KEY_EVM_INS, [])
def _get_evm_instructions_contract(contract_info):
# Combine the instructions of constructor and the rest of the contract
return contract_info["cfg_init"].instructions + contract_info["cfg"].instructions
def _get_evm_instructions_function(function_info):
function = function_info["function"]
# CFG depends on function being constructor or not
if function.is_constructor:
cfg = function_info["contract_info"]["cfg_init"]
# _dispatcher is the only function recognised by evm-cfg-builder in bytecode_init.
# _dispatcher serves the role of the constructor in init code,
# given that there are no other functions.
# Todo: Could rename it appropriately in evm-cfg-builder
# by detecting that init bytecode is being parsed.
name = "_dispatcher"
func_hash = ""
else:
cfg = function_info["contract_info"]["cfg"]
name = function.name
# Get first four bytes of function singature's keccak-256 hash used as function selector
func_hash = str(hex(get_function_id(function.full_name)))
function_evm = _get_function_evm(cfg, name, func_hash)
if function_evm is None:
to_log = "Function " + function.name + " not found in the EVM code"
logger.error(to_log)
raise SlitherError("Function " + function.name + " not found in the EVM code")
function_ins = []
for basic_block in sorted(function_evm.basic_blocks, key=lambda x: x.start.pc):
for ins in basic_block.instructions:
function_ins.append(ins)
return function_ins
def _get_evm_instructions_node(node_info):
# Get evm instructions for node's contract
contract_pcs = generate_source_to_evm_ins_mapping(
node_info["cfg"].instructions,
node_info["srcmap"],
node_info["slither"],
node_info["contract"].source_mapping.filename.absolute,
)
contract_file = (
node_info["slither"]
.source_code[node_info["contract"].source_mapping.filename.absolute]
.encode("utf-8")
)
# Get evm instructions corresponding to node's source line number
node_source_line = (
contract_file[0 : node_info["node"].source_mapping.start].count("\n".encode("utf-8")) + 1
)
node_pcs = contract_pcs.get(node_source_line, [])
node_ins = []
for pc in node_pcs:
node_ins.append(node_info["cfg"].get_instruction_at(pc))
return node_ins
def _get_function_evm(cfg, function_name, function_hash):
for function_evm in cfg.functions:
# Match function hash
if function_evm.name[:2] == "0x" and function_evm.name == function_hash:
return function_evm
# Match function name
if function_evm.name[:2] != "0x" and function_evm.name.split("(")[0] == function_name:
return function_evm
return None
# pylint: disable=too-many-locals
def generate_source_to_evm_ins_mapping(evm_instructions, srcmap_runtime, slither, filename):
"""
Generate Solidity source to EVM instruction mapping using evm_cfg_builder:cfg.instructions
and solc:srcmap_runtime
Returns: Solidity source to EVM instruction mapping
"""
source_to_evm_mapping = {}
file_source = slither.source_code[filename].encode("utf-8")
prev_mapping = []
for idx, mapping in enumerate(srcmap_runtime):
# Parse srcmap_runtime according to its format
# See https://solidity.readthedocs.io/en/v0.5.9/miscellaneous.html#source-mappings
# In order to compress these source mappings especially for bytecode, the following rules are used:
# If a field is empty, the value of the preceding element is used.
# If a : is missing, all following fields are considered empty.
mapping_item = mapping.split(":")
mapping_item += prev_mapping[len(mapping_item) :]
for i, _ in enumerate(mapping_item):
if mapping_item[i] == "":
mapping_item[i] = int(prev_mapping[i])
offset, _length, file_id, _ = mapping_item
prev_mapping = mapping_item
if file_id == "-1":
# Internal compiler-generated code snippets to be ignored
# See https://github.com/ethereum/solidity/issues/6119#issuecomment-467797635
continue
offset = int(offset)
line_number = file_source[0:offset].count("\n".encode("utf-8")) + 1
# Append evm instructions to the corresponding source line number
# Note: Some evm instructions in mapping are not necessarily in program execution order
# Note: The order depends on how solc creates the srcmap_runtime
source_to_evm_mapping.setdefault(line_number, []).append(evm_instructions[idx].pc)
return source_to_evm_mapping
| 7,797 | Python | .py | 160 | 40.125 | 107 | 0.656876 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,013 | data_dependency.py | NioTheFirst_ScType/slither/analyses/data_dependency/data_dependency.py | """
Compute the data depenency between all the SSA variables
"""
from collections import defaultdict
from typing import Union, Set, Dict, TYPE_CHECKING
from slither.core.declarations import (
Contract,
Enum,
Function,
SolidityFunction,
SolidityVariable,
SolidityVariableComposed,
Structure,
)
from slither.core.declarations.solidity_import_placeholder import SolidityImportPlaceHolder
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.core.variables.variable import Variable
from slither.slithir.operations import Index, OperationWithLValue, InternalCall, Operation
from slither.slithir.variables import (
Constant,
LocalIRVariable,
ReferenceVariable,
ReferenceVariableSSA,
StateIRVariable,
TemporaryVariableSSA,
TupleVariableSSA,
)
from slither.core.solidity_types.type import Type
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
###################################################################################
###################################################################################
# region User APIs
###################################################################################
###################################################################################
Variable_types = Union[Variable, SolidityVariable]
Context_types = Union[Contract, Function]
def is_dependent(
variable: Variable_types,
source: Variable_types,
context: Context_types,
only_unprotected: bool = False,
) -> bool:
"""
Args:
variable (Variable)
source (Variable)
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
if isinstance(variable, Constant):
return False
if variable == source:
return True
context_dict = context.context
if only_unprotected:
return (
variable in context_dict[KEY_NON_SSA_UNPROTECTED]
and source in context_dict[KEY_NON_SSA_UNPROTECTED][variable]
)
return variable in context_dict[KEY_NON_SSA] and source in context_dict[KEY_NON_SSA][variable]
def is_dependent_ssa(
variable: Variable_types,
source: Variable_types,
context: Context_types,
only_unprotected: bool = False,
) -> bool:
"""
Args:
variable (Variable)
taint (Variable)
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
context_dict = context.context
if isinstance(variable, Constant):
return False
if variable == source:
return True
if only_unprotected:
return (
variable in context_dict[KEY_SSA_UNPROTECTED]
and source in context_dict[KEY_SSA_UNPROTECTED][variable]
)
return variable in context_dict[KEY_SSA] and source in context_dict[KEY_SSA][variable]
GENERIC_TAINT = {
SolidityVariableComposed("msg.sender"),
SolidityVariableComposed("msg.value"),
SolidityVariableComposed("msg.data"),
SolidityVariableComposed("tx.origin"),
}
def is_tainted(
variable: Variable_types,
context: Context_types,
only_unprotected: bool = False,
ignore_generic_taint: bool = False,
) -> bool:
"""
Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if isinstance(variable, Constant):
return False
compilation_unit = context.compilation_unit
taints = compilation_unit.context[KEY_INPUT]
if not ignore_generic_taint:
taints |= GENERIC_TAINT
return variable in taints or any(
is_dependent(variable, t, context, only_unprotected) for t in taints
)
def is_tainted_ssa(
variable: Variable_types,
context: Context_types,
only_unprotected: bool = False,
ignore_generic_taint: bool = False,
):
"""
Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if isinstance(variable, Constant):
return False
compilation_unit = context.compilation_unit
taints = compilation_unit.context[KEY_INPUT_SSA]
if not ignore_generic_taint:
taints |= GENERIC_TAINT
return variable in taints or any(
is_dependent_ssa(variable, t, context, only_unprotected) for t in taints
)
def get_dependencies(
variable: Variable_types,
context: Context_types,
only_unprotected: bool = False,
) -> Set[Variable]:
"""
Return the variables for which `variable` depends on.
:param variable: The target
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: set(Variable)
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_NON_SSA_UNPROTECTED].get(variable, set())
return context.context[KEY_NON_SSA].get(variable, set())
def get_all_dependencies(
context: Context_types, only_unprotected: bool = False
) -> Dict[Variable, Set[Variable]]:
"""
Return the dictionary of dependencies.
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: Dict(Variable, set(Variable))
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_NON_SSA_UNPROTECTED]
return context.context[KEY_NON_SSA]
def get_dependencies_ssa(
variable: Variable_types,
context: Context_types,
only_unprotected: bool = False,
) -> Set[Variable]:
"""
Return the variables for which `variable` depends on (SSA version).
:param variable: The target (must be SSA variable)
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: set(Variable)
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_SSA_UNPROTECTED].get(variable, set())
return context.context[KEY_SSA].get(variable, set())
def get_all_dependencies_ssa(
context: Context_types, only_unprotected: bool = False
) -> Dict[Variable, Set[Variable]]:
"""
Return the dictionary of dependencies.
:param context: Either a function (interprocedural) or a contract (inter transactional)
:param only_unprotected: True if consider only protected functions
:return: Dict(Variable, set(Variable))
"""
assert isinstance(context, (Contract, Function))
assert isinstance(only_unprotected, bool)
if only_unprotected:
return context.context[KEY_SSA_UNPROTECTED]
return context.context[KEY_SSA]
# endregion
###################################################################################
###################################################################################
# region Module constants
###################################################################################
###################################################################################
KEY_SSA = "DATA_DEPENDENCY_SSA"
KEY_NON_SSA = "DATA_DEPENDENCY"
# Only for unprotected functions
KEY_SSA_UNPROTECTED = "DATA_DEPENDENCY_SSA_UNPROTECTED"
KEY_NON_SSA_UNPROTECTED = "DATA_DEPENDENCY_UNPROTECTED"
KEY_INPUT = "DATA_DEPENDENCY_INPUT"
KEY_INPUT_SSA = "DATA_DEPENDENCY_INPUT_SSA"
# endregion
###################################################################################
###################################################################################
# region Debug
###################################################################################
###################################################################################
def pprint_dependency(caller_context: Context_types) -> None:
print("#### SSA ####")
context = caller_context.context
for k, values in context[KEY_SSA].items():
print(f"{k} ({id(k)}):")
for v in values:
print(f"\t- {v}")
print("#### NON SSA ####")
for k, values in context[KEY_NON_SSA].items():
print(f"{k} ({hex(id(k))}):")
for v in values:
print(f"\t- {v} ({hex(id(v))})")
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
def compute_dependency(compilation_unit: "SlitherCompilationUnit") -> None:
compilation_unit.context[KEY_INPUT] = set()
compilation_unit.context[KEY_INPUT_SSA] = set()
for contract in compilation_unit.contracts:
compute_dependency_contract(contract, compilation_unit)
def compute_dependency_contract(
contract: Contract, compilation_unit: "SlitherCompilationUnit"
) -> None:
if KEY_SSA in contract.context:
return
contract.context[KEY_SSA] = {}
contract.context[KEY_SSA_UNPROTECTED] = {}
for function in contract.functions + list(contract.modifiers):
compute_dependency_function(function)
propagate_function(contract, function, KEY_SSA, KEY_NON_SSA)
propagate_function(contract, function, KEY_SSA_UNPROTECTED, KEY_NON_SSA_UNPROTECTED)
# pylint: disable=expression-not-assigned
if function.visibility in ["public", "external"]:
[compilation_unit.context[KEY_INPUT].add(p) for p in function.parameters]
[compilation_unit.context[KEY_INPUT_SSA].add(p) for p in function.parameters_ssa]
propagate_contract(contract, KEY_SSA, KEY_NON_SSA)
propagate_contract(contract, KEY_SSA_UNPROTECTED, KEY_NON_SSA_UNPROTECTED)
def propagate_function(
contract: Contract, function: Function, context_key: str, context_key_non_ssa: str
) -> None:
transitive_close_dependencies(function, context_key, context_key_non_ssa)
# Propage data dependency
data_depencencies = function.context[context_key]
for (key, values) in data_depencencies.items():
if not key in contract.context[context_key]:
contract.context[context_key][key] = set(values)
else:
contract.context[context_key][key].union(values)
def transitive_close_dependencies(
context: Context_types, context_key: str, context_key_non_ssa: str
) -> None:
# transitive closure
changed = True
keys = context.context[context_key].keys()
while changed:
changed = False
to_add = defaultdict(set)
[ # pylint: disable=expression-not-assigned
[
to_add[key].update(context.context[context_key][item] - {key} - items)
for item in items & keys
]
for key, items in context.context[context_key].items()
]
for k, v in to_add.items():
# Because we dont have any check on the update operation
# We might update an empty set with an empty set
if v:
changed = True
context.context[context_key][k] |= v
context.context[context_key_non_ssa] = convert_to_non_ssa(context.context[context_key])
def propagate_contract(contract: Contract, context_key: str, context_key_non_ssa: str) -> None:
transitive_close_dependencies(contract, context_key, context_key_non_ssa)
def add_dependency(lvalue: Variable, function: Function, ir: Operation, is_protected: bool) -> None:
if not lvalue in function.context[KEY_SSA]:
function.context[KEY_SSA][lvalue] = set()
if not is_protected:
function.context[KEY_SSA_UNPROTECTED][lvalue] = set()
if isinstance(ir, Index):
read = [ir.variable_left]
elif isinstance(ir, InternalCall):
read = ir.function.return_values_ssa
else:
read = ir.read
# pylint: disable=expression-not-assigned
[function.context[KEY_SSA][lvalue].add(v) for v in read if not isinstance(v, Constant)]
if not is_protected:
[
function.context[KEY_SSA_UNPROTECTED][lvalue].add(v)
for v in read
if not isinstance(v, Constant)
]
def compute_dependency_function(function: Function) -> None:
if KEY_SSA in function.context:
return
function.context[KEY_SSA] = {}
function.context[KEY_SSA_UNPROTECTED] = {}
is_protected = function.is_protected()
for node in function.nodes:
for ir in node.irs_ssa:
if isinstance(ir, OperationWithLValue) and ir.lvalue:
if isinstance(ir.lvalue, LocalIRVariable) and ir.lvalue.is_storage:
continue
if isinstance(ir.lvalue, ReferenceVariable):
lvalue = ir.lvalue.points_to
if lvalue:
add_dependency(lvalue, function, ir, is_protected)
add_dependency(ir.lvalue, function, ir, is_protected)
function.context[KEY_NON_SSA] = convert_to_non_ssa(function.context[KEY_SSA])
function.context[KEY_NON_SSA_UNPROTECTED] = convert_to_non_ssa(
function.context[KEY_SSA_UNPROTECTED]
)
def convert_variable_to_non_ssa(v: Variable_types) -> Variable_types:
if isinstance(
v,
(
LocalIRVariable,
StateIRVariable,
TemporaryVariableSSA,
ReferenceVariableSSA,
TupleVariableSSA,
),
):
return v.non_ssa_version
assert isinstance(
v,
(
Constant,
SolidityVariable,
Contract,
Enum,
SolidityFunction,
Structure,
Function,
Type,
SolidityImportPlaceHolder,
TopLevelVariable,
),
)
return v
def convert_to_non_ssa(
data_depencies: Dict[Variable_types, Set[Variable_types]]
) -> Dict[Variable_types, Set[Variable_types]]:
# Need to create new set() as its changed during iteration
ret: Dict[Variable_types, Set[Variable_types]] = {}
for (k, values) in data_depencies.items():
var = convert_variable_to_non_ssa(k)
if not var in ret:
ret[var] = set()
ret[var] = ret[var].union({convert_variable_to_non_ssa(v) for v in values})
return ret
| 15,186 | Python | .py | 382 | 33.431937 | 100 | 0.62131 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,014 | are_variables_written.py | NioTheFirst_ScType/slither/analyses/write/are_variables_written.py | """
Detect if all the given variables are written in all the paths of the function
"""
from collections import defaultdict
from typing import Dict, Set, List
from slither.core.cfg.node import NodeType, Node
from slither.core.declarations import SolidityFunction
from slither.core.variables.variable import Variable
from slither.slithir.operations import (
Index,
Member,
OperationWithLValue,
SolidityCall,
Length,
)
from slither.slithir.variables import ReferenceVariable, TemporaryVariable
class State: # pylint: disable=too-few-public-methods
def __init__(self):
# Map node -> list of variables set
# Were each variables set represents a configuration of a path
# If two paths lead to the exact same set of variables written, we dont need to explore both
# We need to keep different set per path, because we want to capture stuff like
# if (..){
# v = 10
# }
# Here in the endIF node, v can be written, or can be not written. If we were merging the paths
# We would lose this information
# In other words, in each in the list represents a set of path that has the same outcome
self.nodes: Dict[Node, List[Set[Variable]]] = defaultdict(list)
# pylint: disable=too-many-branches
def _visit(
node: Node,
state: State,
variables_written: Set[Variable],
variables_to_write: List[Variable],
):
"""
Explore all the nodes to look for values not written when the node's function return
Fixpoint reaches if no new written variables are found
:param node:
:param state:
:param variables_to_write:
:return:
"""
refs = {}
variables_written = set(variables_written)
for ir in node.irs:
if isinstance(ir, SolidityCall):
# TODO convert the revert to a THROW node
if ir.function in [
SolidityFunction("revert(string)"),
SolidityFunction("revert()"),
]:
return []
if not isinstance(ir, OperationWithLValue):
continue
if isinstance(ir, (Index, Member)):
refs[ir.lvalue] = ir.variable_left
if isinstance(ir, Length):
refs[ir.lvalue] = ir.value
if ir.lvalue and not isinstance(ir.lvalue, (TemporaryVariable, ReferenceVariable)):
variables_written.add(ir.lvalue)
lvalue = ir.lvalue
while isinstance(lvalue, ReferenceVariable):
if lvalue not in refs:
break
if refs[lvalue] and not isinstance(
refs[lvalue], (TemporaryVariable, ReferenceVariable)
):
variables_written.add(refs[lvalue])
lvalue = refs[lvalue]
ret = []
if not node.sons and node.type not in [NodeType.THROW, NodeType.RETURN]:
ret += [v for v in variables_to_write if v not in variables_written]
# Explore sons if
# - Before is none: its the first time we explored the node
# - variables_written is not before: it means that this path has a configuration of set variables
# that we haven't seen yet
before = state.nodes[node] if node in state.nodes else None
if before is None or variables_written not in before:
state.nodes[node].append(variables_written)
for son in node.sons:
ret += _visit(son, state, variables_written, variables_to_write)
return ret
def are_variables_written(function, variables_to_write):
"""
Return the list of variable that are not written at the end of the function
Args:
function (Function)
variables_to_write (list Variable): variable that must be written
Returns:
list(Variable): List of variable that are not written (sublist of variables_to_write)
"""
return list(set(_visit(function.entry_point, State(), set(), variables_to_write)))
| 3,910 | Python | .py | 94 | 34.223404 | 103 | 0.666404 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,015 | __main__.py | NioTheFirst_ScType/slither/tools/upgradeability/__main__.py | import argparse
import inspect
import json
import logging
import sys
from typing import List, Any, Type, Dict, Tuple, Union, Sequence, Optional
from crytic_compile import cryticparser
from slither import Slither
from slither.core.declarations import Contract
from slither.exceptions import SlitherException
from slither.utils.colors import red
from slither.utils.output import output_to_json
from slither.tools.upgradeability.checks import all_checks
from slither.tools.upgradeability.checks.abstract_checks import (
AbstractCheck,
CheckClassification,
)
from slither.tools.upgradeability.utils.command_line import (
output_detectors_json,
output_wiki,
output_detectors,
output_to_markdown,
)
logging.basicConfig()
logger: logging.Logger = logging.getLogger("Slither")
logger.setLevel(logging.INFO)
def parse_args(check_classes: List[Type[AbstractCheck]]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Slither Upgradeability Checks. For usage information see https://github.com/crytic/slither/wiki/Upgradeability-Checks.",
usage="slither-check-upgradeability contract.sol ContractName",
)
group_checks = parser.add_argument_group("Checks")
parser.add_argument("contract.sol", help="Codebase to analyze")
parser.add_argument("ContractName", help="Contract name (logic contract)")
parser.add_argument("--proxy-name", help="Proxy name")
parser.add_argument("--proxy-filename", help="Proxy filename (if different)")
parser.add_argument("--new-contract-name", help="New contract name (if changed)")
parser.add_argument(
"--new-contract-filename", help="New implementation filename (if different)"
)
parser.add_argument(
"--json",
help='Export the results as a JSON file ("--json -" to export to stdout)',
action="store",
default=False,
)
group_checks.add_argument(
"--detect",
help="Comma-separated list of detectors, defaults to all, "
f"available detectors: {', '.join(d.ARGUMENT for d in check_classes)}",
action="store",
dest="detectors_to_run",
default="all",
)
group_checks.add_argument(
"--list-detectors",
help="List available detectors",
action=ListDetectors,
nargs=0,
default=False,
)
group_checks.add_argument(
"--exclude",
help="Comma-separated list of detectors that should be excluded",
action="store",
dest="detectors_to_exclude",
default=None,
)
group_checks.add_argument(
"--exclude-informational",
help="Exclude informational impact analyses",
action="store_true",
default=False,
)
group_checks.add_argument(
"--exclude-low",
help="Exclude low impact analyses",
action="store_true",
default=False,
)
group_checks.add_argument(
"--exclude-medium",
help="Exclude medium impact analyses",
action="store_true",
default=False,
)
group_checks.add_argument(
"--exclude-high",
help="Exclude high impact analyses",
action="store_true",
default=False,
)
parser.add_argument(
"--markdown-root",
help="URL for markdown generation",
action="store",
default="",
)
parser.add_argument(
"--wiki-detectors", help=argparse.SUPPRESS, action=OutputWiki, default=False
)
parser.add_argument(
"--list-detectors-json",
help=argparse.SUPPRESS,
action=ListDetectorsJson,
nargs=0,
default=False,
)
parser.add_argument("--markdown", help=argparse.SUPPRESS, action=OutputMarkdown, default=False)
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
###################################################################################
###################################################################################
# region checks
###################################################################################
###################################################################################
def _get_checks() -> List[Type[AbstractCheck]]:
detectors_ = [getattr(all_checks, name) for name in dir(all_checks)]
detectors: List[Type[AbstractCheck]] = [
c for c in detectors_ if inspect.isclass(c) and issubclass(c, AbstractCheck)
]
return detectors
def choose_checks(
args: argparse.Namespace, all_check_classes: List[Type[AbstractCheck]]
) -> List[Type[AbstractCheck]]:
detectors_to_run = []
detectors = {d.ARGUMENT: d for d in all_check_classes}
if args.detectors_to_run == "all":
detectors_to_run = all_check_classes
if args.detectors_to_exclude:
detectors_excluded = args.detectors_to_exclude.split(",")
for detector in detectors:
if detector in detectors_excluded:
detectors_to_run.remove(detectors[detector])
else:
for detector in args.detectors_to_run.split(","):
if detector in detectors:
detectors_to_run.append(detectors[detector])
else:
raise Exception(f"Error: {detector} is not a detector")
detectors_to_run = sorted(detectors_to_run, key=lambda x: x.IMPACT)
return detectors_to_run
if args.exclude_informational:
detectors_to_run = [
d for d in detectors_to_run if d.IMPACT != CheckClassification.INFORMATIONAL
]
if args.exclude_low:
detectors_to_run = [d for d in detectors_to_run if d.IMPACT != CheckClassification.LOW]
if args.exclude_medium:
detectors_to_run = [d for d in detectors_to_run if d.IMPACT != CheckClassification.MEDIUM]
if args.exclude_high:
detectors_to_run = [d for d in detectors_to_run if d.IMPACT != CheckClassification.HIGH]
# detectors_to_run = sorted(detectors_to_run, key=lambda x: x.IMPACT)
return detectors_to_run
class ListDetectors(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
checks = _get_checks()
output_detectors(checks)
parser.exit()
class ListDetectorsJson(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
checks = _get_checks()
detector_types_json = output_detectors_json(checks)
print(json.dumps(detector_types_json))
parser.exit()
class OutputMarkdown(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self,
parser: Any,
args: Any,
values: Optional[Union[str, Sequence[Any]]],
option_string: Any = None,
) -> None: # pylint: disable=signature-differs
checks = _get_checks()
assert isinstance(values, str)
output_to_markdown(checks, values)
parser.exit()
class OutputWiki(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self,
parser: Any,
args: Any,
values: Optional[Union[str, Sequence[Any]]],
option_string: Any = None,
) -> Any: # pylint: disable=signature-differs
checks = _get_checks()
assert isinstance(values, str)
output_wiki(checks, values)
parser.exit()
def _run_checks(detectors: List[AbstractCheck]) -> List[Dict]:
results_ = [d.check() for d in detectors]
results_ = [r for r in results_ if r]
results = [item for sublist in results_ for item in sublist] # flatten
return results
def _checks_on_contract(
detectors: List[Type[AbstractCheck]], contract: Contract
) -> Tuple[List[Dict], int]:
detectors_ = [
d(logger, contract)
for d in detectors
if (not d.REQUIRE_PROXY and not d.REQUIRE_CONTRACT_V2)
]
return _run_checks(detectors_), len(detectors_)
def _checks_on_contract_update(
detectors: List[Type[AbstractCheck]], contract_v1: Contract, contract_v2: Contract
) -> Tuple[List[Dict], int]:
detectors_ = [
d(logger, contract_v1, contract_v2=contract_v2) for d in detectors if d.REQUIRE_CONTRACT_V2
]
return _run_checks(detectors_), len(detectors_)
def _checks_on_contract_and_proxy(
detectors: List[Type[AbstractCheck]], contract: Contract, proxy: Contract
) -> Tuple[List[Dict], int]:
detectors_ = [d(logger, contract, proxy=proxy) for d in detectors if d.REQUIRE_PROXY]
return _run_checks(detectors_), len(detectors_)
# endregion
###################################################################################
###################################################################################
# region Main
###################################################################################
###################################################################################
# pylint: disable=too-many-statements,too-many-branches,too-many-locals
def main() -> None:
json_results: Dict = {
"proxy-present": False,
"contract_v2-present": False,
"detectors": [],
}
detectors = _get_checks()
args = parse_args(detectors)
detectors_to_run = choose_checks(args, detectors)
v1_filename = vars(args)["contract.sol"]
number_detectors_run = 0
try:
variable1 = Slither(v1_filename, **vars(args))
# Analyze logic contract
v1_name = args.ContractName
v1_contracts = variable1.get_contract_from_name(v1_name)
if len(v1_contracts) != 1:
info = f"Contract {v1_name} not found in {variable1.filename}"
logger.error(red(info))
if args.json:
output_to_json(args.json, str(info), json_results)
return
v1_contract = v1_contracts[0]
detectors_results, number_detectors = _checks_on_contract(detectors_to_run, v1_contract)
json_results["detectors"] += detectors_results
number_detectors_run += number_detectors
# Analyze Proxy
proxy_contract = None
if args.proxy_name:
if args.proxy_filename:
proxy = Slither(args.proxy_filename, **vars(args))
else:
proxy = variable1
proxy_contracts = proxy.get_contract_from_name(args.proxy_name)
if len(proxy_contracts) != 1:
info = f"Proxy {args.proxy_name} not found in {proxy.filename}"
logger.error(red(info))
if args.json:
output_to_json(args.json, str(info), json_results)
return
proxy_contract = proxy_contracts[0]
json_results["proxy-present"] = True
detectors_results, number_detectors = _checks_on_contract_and_proxy(
detectors_to_run, v1_contract, proxy_contract
)
json_results["detectors"] += detectors_results
number_detectors_run += number_detectors
# Analyze new version
if args.new_contract_name:
if args.new_contract_filename:
variable2 = Slither(args.new_contract_filename, **vars(args))
else:
variable2 = variable1
v2_contracts = variable2.get_contract_from_name(args.new_contract_name)
if len(v2_contracts) != 1:
info = (
f"New logic contract {args.new_contract_name} not found in {variable2.filename}"
)
logger.error(red(info))
if args.json:
output_to_json(args.json, str(info), json_results)
return
v2_contract = v2_contracts[0]
json_results["contract_v2-present"] = True
if proxy_contract:
detectors_results, _ = _checks_on_contract_and_proxy(
detectors_to_run, v2_contract, proxy_contract
)
json_results["detectors"] += detectors_results
detectors_results, number_detectors = _checks_on_contract_update(
detectors_to_run, v1_contract, v2_contract
)
json_results["detectors"] += detectors_results
number_detectors_run += number_detectors
# If there is a V2, we run the contract-only check on the V2
detectors_results, number_detectors = _checks_on_contract(detectors_to_run, v2_contract)
json_results["detectors"] += detectors_results
number_detectors_run += number_detectors
to_log = f'{len(json_results["detectors"])} findings, {number_detectors_run} detectors run'
logger.info(to_log)
if args.json:
output_to_json(args.json, None, json_results)
except SlitherException as slither_exception:
logger.error(str(slither_exception))
if args.json:
output_to_json(args.json, str(slither_exception), json_results)
return
# endregion
| 13,249 | Python | .py | 317 | 33.741325 | 141 | 0.608753 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,016 | command_line.py | NioTheFirst_ScType/slither/tools/upgradeability/utils/command_line.py | from typing import List, Union, Dict, Type
from slither.tools.upgradeability.checks.abstract_checks import classification_txt, AbstractCheck
from slither.utils.myprettytable import MyPrettyTable
def output_wiki(detector_classes: List[Type[AbstractCheck]], filter_wiki: str) -> None:
# Sort by impact, confidence, and name
detectors_list = sorted(
detector_classes, key=lambda element: (element.IMPACT, element.ARGUMENT)
)
for detector in detectors_list:
if filter_wiki not in detector.WIKI:
continue
argument = detector.ARGUMENT
impact = classification_txt[detector.IMPACT]
title = detector.WIKI_TITLE
description = detector.WIKI_DESCRIPTION
exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
recommendation = detector.WIKI_RECOMMENDATION
print(f"\n## {title}")
print("### Configuration")
print(f"* Check: `{argument}`")
print(f"* Severity: `{impact}`")
print("\n### Description")
print(description)
if exploit_scenario:
print("\n### Exploit Scenario:")
print(exploit_scenario)
print("\n### Recommendation")
print(recommendation)
def output_detectors(detector_classes: List[Type[AbstractCheck]]) -> None:
detectors_list = []
for detector in detector_classes:
argument = detector.ARGUMENT
help_info = detector.HELP
impact = detector.IMPACT
require_proxy = detector.REQUIRE_PROXY
require_v2 = detector.REQUIRE_CONTRACT_V2
detectors_list.append((argument, help_info, impact, require_proxy, require_v2))
table = MyPrettyTable(["Num", "Check", "What it Detects", "Impact", "Proxy", "Contract V2"])
# Sort by impact, confidence, and name
detectors_list = sorted(detectors_list, key=lambda element: (element[2], element[0]))
idx = 1
for (argument, help_info, impact, proxy, v2) in detectors_list:
table.add_row(
[
str(idx),
argument,
help_info,
classification_txt[impact],
"X" if proxy else "",
"X" if v2 else "",
]
)
idx = idx + 1
print(table)
def output_to_markdown(detector_classes: List[Type[AbstractCheck]], _filter_wiki: str) -> None:
def extract_help(cls: AbstractCheck) -> str:
if cls.WIKI == "":
return cls.HELP
return f"[{cls.HELP}]({cls.WIKI})"
detectors_list = []
for detector in detector_classes:
argument = detector.ARGUMENT
help_info = extract_help(detector)
impact = detector.IMPACT
require_proxy = detector.REQUIRE_PROXY
require_v2 = detector.REQUIRE_CONTRACT_V2
detectors_list.append((argument, help_info, impact, require_proxy, require_v2))
# Sort by impact, confidence, and name
detectors_list = sorted(detectors_list, key=lambda element: (element[2], element[0]))
idx = 1
for (argument, help_info, impact, proxy, v2) in detectors_list:
print(
f"{idx} | `{argument}` | {help_info} | {classification_txt[impact]} | {'X' if proxy else ''} | {'X' if v2 else ''}"
)
idx = idx + 1
def output_detectors_json(
detector_classes: List[Type[AbstractCheck]],
) -> List[Dict[str, Union[str, int]]]:
detectors_list = []
for detector in detector_classes:
argument = detector.ARGUMENT
help_info = detector.HELP
impact = detector.IMPACT
wiki_url = detector.WIKI
wiki_description = detector.WIKI_DESCRIPTION
wiki_exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
wiki_recommendation = detector.WIKI_RECOMMENDATION
detectors_list.append(
(
argument,
help_info,
impact,
wiki_url,
wiki_description,
wiki_exploit_scenario,
wiki_recommendation,
)
)
# Sort by impact, confidence, and name
detectors_list = sorted(detectors_list, key=lambda element: (element[2], element[0]))
idx = 1
table: List[Dict[str, Union[str, int]]] = []
for (
argument,
help_info,
impact,
wiki_url,
description,
exploit,
recommendation,
) in detectors_list:
table.append(
{
"index": idx,
"check": argument,
"title": help_info,
"impact": classification_txt[impact],
"wiki_url": wiki_url,
"description": description,
"exploit_scenario": exploit,
"recommendation": recommendation,
}
)
idx = idx + 1
return table
| 4,819 | Python | .py | 125 | 29.176 | 127 | 0.600769 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,017 | variable_initialization.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/variable_initialization.py | from slither.tools.upgradeability.checks.abstract_checks import (
CheckClassification,
AbstractCheck,
)
class VariableWithInit(AbstractCheck):
ARGUMENT = "variables-initialized"
IMPACT = CheckClassification.HIGH
HELP = "State variables with an initial value"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#state-variable-initialized"
WIKI_TITLE = "State variable initialized"
# region wiki_description
WIKI_DESCRIPTION = """
Detect state variables that are initialized.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable = 10;
}
```
Using `Contract` will the delegatecall proxy pattern will lead `variable` to be 0 when called through the proxy.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Using initialize functions to write initial values in state variables.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
results = []
for s in self.contract.state_variables_ordered:
if s.initialized and not (s.is_constant or s.is_immutable):
info = [s, " is a state variable with an initial value.\n"]
json = self.generate_result(info)
results.append(json)
return results
| 1,415 | Python | .py | 39 | 30.974359 | 112 | 0.710526 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,018 | abstract_checks.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/abstract_checks.py | import abc
from logging import Logger
from typing import Optional, List, Dict, Union, Callable
from slither.core.declarations import Contract
from slither.utils.colors import green, yellow, red
from slither.utils.comparable_enum import ComparableEnum
from slither.utils.output import Output, SupportedOutput
class IncorrectCheckInitialization(Exception):
pass
class CheckClassification(ComparableEnum):
HIGH = 0
MEDIUM = 1
LOW = 2
INFORMATIONAL = 3
UNIMPLEMENTED = 999
classification_colors: Dict[CheckClassification, Callable[[str], str]] = {
CheckClassification.INFORMATIONAL: green,
CheckClassification.LOW: yellow,
CheckClassification.MEDIUM: yellow,
CheckClassification.HIGH: red,
}
classification_txt = {
CheckClassification.INFORMATIONAL: "Informational",
CheckClassification.LOW: "Low",
CheckClassification.MEDIUM: "Medium",
CheckClassification.HIGH: "High",
}
class AbstractCheck(metaclass=abc.ABCMeta):
ARGUMENT = ""
HELP = ""
IMPACT: CheckClassification = CheckClassification.UNIMPLEMENTED
WIKI = ""
WIKI_TITLE = ""
WIKI_DESCRIPTION = ""
WIKI_EXPLOIT_SCENARIO = ""
WIKI_RECOMMENDATION = ""
REQUIRE_CONTRACT = False
REQUIRE_PROXY = False
REQUIRE_CONTRACT_V2 = False
def __init__(
self,
logger: Logger,
contract: Contract,
proxy: Optional[Contract] = None,
contract_v2: Optional[Contract] = None,
) -> None:
self.logger = logger
self.contract = contract
self.proxy = proxy
self.contract_v2 = contract_v2
if not self.ARGUMENT:
raise IncorrectCheckInitialization(f"NAME is not initialized {self.__class__.__name__}")
if not self.HELP:
raise IncorrectCheckInitialization(f"HELP is not initialized {self.__class__.__name__}")
if not self.WIKI:
raise IncorrectCheckInitialization(f"WIKI is not initialized {self.__class__.__name__}")
if not self.WIKI_TITLE:
raise IncorrectCheckInitialization(
f"WIKI_TITLE is not initialized {self.__class__.__name__}"
)
if not self.WIKI_DESCRIPTION:
raise IncorrectCheckInitialization(
f"WIKI_DESCRIPTION is not initialized {self.__class__.__name__}"
)
if not self.WIKI_EXPLOIT_SCENARIO and self.IMPACT not in [
CheckClassification.INFORMATIONAL
]:
raise IncorrectCheckInitialization(
f"WIKI_EXPLOIT_SCENARIO is not initialized {self.__class__.__name__}"
)
if not self.WIKI_RECOMMENDATION:
raise IncorrectCheckInitialization(
f"WIKI_RECOMMENDATION is not initialized {self.__class__.__name__}"
)
if self.REQUIRE_PROXY and self.REQUIRE_CONTRACT_V2:
# This is not a fundatemenal issues
# But it requires to change __main__ to avoid running two times the detectors
txt = f"REQUIRE_PROXY and REQUIRE_CONTRACT_V2 needs change in __main___ {self.__class__.__name__}"
raise IncorrectCheckInitialization(txt)
if self.IMPACT not in [
CheckClassification.LOW,
CheckClassification.MEDIUM,
CheckClassification.HIGH,
CheckClassification.INFORMATIONAL,
]:
raise IncorrectCheckInitialization(
f"IMPACT is not initialized {self.__class__.__name__}"
)
if self.REQUIRE_CONTRACT_V2 and contract_v2 is None:
raise IncorrectCheckInitialization(
f"ContractV2 is not initialized {self.__class__.__name__}"
)
if self.REQUIRE_PROXY and proxy is None:
raise IncorrectCheckInitialization(
f"Proxy is not initialized {self.__class__.__name__}"
)
@abc.abstractmethod
def _check(self) -> List[Output]:
"""TODO Documentation"""
return []
def check(self) -> List[Dict]:
all_outputs = self._check()
# Keep only dictionaries
all_results = [r.data for r in all_outputs]
if all_results:
if self.logger:
info = "\n"
for result in all_results:
info += result["description"]
info += f"Reference: {self.WIKI}"
self._log(info)
return all_results
def generate_result(
self,
info: Union[str, List[Union[str, SupportedOutput]]],
additional_fields: Optional[Dict] = None,
) -> Output:
output = Output(
info, additional_fields, markdown_root=self.contract.compilation_unit.core.markdown_root
)
output.data["check"] = self.ARGUMENT
return output
def _log(self, info: str) -> None:
if self.logger:
self.logger.info(self.color(info))
@property
def color(self) -> Callable[[str], str]:
return classification_colors[self.IMPACT]
| 5,037 | Python | .py | 128 | 30.382813 | 110 | 0.631331 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,019 | initialization.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/initialization.py | import logging
from slither.core.declarations import Function
from slither.slithir.operations import InternalCall
from slither.tools.upgradeability.checks.abstract_checks import (
AbstractCheck,
CheckClassification,
)
from slither.utils.colors import red
logger = logging.getLogger("Slither-check-upgradeability")
class MultipleInitTarget(Exception):
pass
def _has_initialize_modifier(function: Function):
if not function.modifiers:
return False
return any((m.name == "initializer") for m in function.modifiers)
def _get_initialize_functions(contract):
return [
f
for f in contract.functions
if (f.name == "initialize" or _has_initialize_modifier(f)) and f.is_implemented
]
def _get_all_internal_calls(function):
all_ir = function.all_slithir_operations()
return [
i.function
for i in all_ir
if isinstance(i, InternalCall) and i.function_name == "initialize"
]
def _get_most_derived_init(contract):
init_functions = [f for f in contract.functions if not f.is_shadowed and f.name == "initialize"]
if len(init_functions) > 1:
if len([f for f in init_functions if f.contract_declarer == contract]) == 1:
return next((f for f in init_functions if f.contract_declarer == contract))
raise MultipleInitTarget
if init_functions:
return init_functions[0]
return None
class InitializablePresent(AbstractCheck):
ARGUMENT = "init-missing"
IMPACT = CheckClassification.INFORMATIONAL
HELP = "Initializable is missing"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initializable-is-missing"
WIKI_TITLE = "Initializable is missing"
# region wiki_description
WIKI_DESCRIPTION = """
Detect if a contract `Initializable` is present.
"""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Review manually the contract's initialization..
Consider using a `Initializable` contract to follow [standard practice](https://docs.openzeppelin.com/upgrades/2.7/writing-upgradeable).
"""
# endregion wiki_recommendation
def _check(self):
initializable = self.contract.file_scope.get_contract_from_name("Initializable")
if initializable is None:
info = [
"Initializable contract not found, the contract does not follow a standard initalization schema.\n"
]
json = self.generate_result(info)
return [json]
return []
class InitializableInherited(AbstractCheck):
ARGUMENT = "init-inherited"
IMPACT = CheckClassification.INFORMATIONAL
HELP = "Initializable is not inherited"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initializable-is-not-inherited"
WIKI_TITLE = "Initializable is not inherited"
# region wiki_description
WIKI_DESCRIPTION = """
Detect if `Initializable` is inherited.
"""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Review manually the contract's initialization. Consider inheriting `Initializable`.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
initializable = self.contract.file_scope.get_contract_from_name("Initializable")
# See InitializablePresent
if initializable is None:
return []
if initializable not in self.contract.inheritance:
info = [self.contract, " does not inherit from ", initializable, ".\n"]
json = self.generate_result(info)
return [json]
return []
class InitializableInitializer(AbstractCheck):
ARGUMENT = "initializer-missing"
IMPACT = CheckClassification.INFORMATIONAL
HELP = "initializer() is missing"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initializer-is-missing"
WIKI_TITLE = "initializer() is missing"
# region wiki_description
WIKI_DESCRIPTION = """
Detect the lack of `Initializable.initializer()` modifier.
"""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Review manually the contract's initialization. Consider inheriting a `Initializable.initializer()` modifier.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
initializable = self.contract.file_scope.get_contract_from_name("Initializable")
# See InitializablePresent
if initializable is None:
return []
# See InitializableInherited
if initializable not in self.contract.inheritance:
return []
initializer = self.contract.get_modifier_from_canonical_name("Initializable.initializer()")
if initializer is None:
info = ["Initializable.initializer() does not exist.\n"]
json = self.generate_result(info)
return [json]
return []
class MissingInitializerModifier(AbstractCheck):
ARGUMENT = "missing-init-modifier"
IMPACT = CheckClassification.HIGH
HELP = "initializer() is not called"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initializer-is-not-called"
WIKI_TITLE = "initializer() is not called"
# region wiki_description
WIKI_DESCRIPTION = """
Detect if `Initializable.initializer()` is called.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
function initialize() public{
///
}
}
```
`initialize` should have the `initializer` modifier to prevent someone from initializing the contract multiple times.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Use `Initializable.initializer()`.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
initializable = self.contract.file_scope.get_contract_from_name("Initializable")
# See InitializablePresent
if initializable is None:
return []
# See InitializableInherited
if initializable not in self.contract.inheritance:
return []
initializer = self.contract.get_modifier_from_canonical_name("Initializable.initializer()")
# InitializableInitializer
if initializer is None:
return []
results = []
all_init_functions = _get_initialize_functions(self.contract)
for f in all_init_functions:
if initializer not in f.modifiers:
info = [f, " does not call the initializer modifier.\n"]
json = self.generate_result(info)
results.append(json)
return results
class MissingCalls(AbstractCheck):
ARGUMENT = "missing-calls"
IMPACT = CheckClassification.HIGH
HELP = "Missing calls to init functions"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initialize-functions-are-not-called"
WIKI_TITLE = "Initialize functions are not called"
# region wiki_description
WIKI_DESCRIPTION = """
Detect missing calls to initialize functions.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Base{
function initialize() public{
///
}
}
contract Derived is Base{
function initialize() public{
///
}
}
```
`Derived.initialize` does not call `Base.initialize` leading the contract to not be correctly initialized.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Ensure all the initialize functions are reached by the most derived initialize function.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
results = []
# TODO: handle MultipleInitTarget
try:
most_derived_init = _get_most_derived_init(self.contract)
except MultipleInitTarget:
logger.error(red(f"Too many init targets in {self.contract}"))
return []
if most_derived_init is None:
return []
all_init_functions = _get_initialize_functions(self.contract)
all_init_functions_called = _get_all_internal_calls(most_derived_init) + [most_derived_init]
missing_calls = [f for f in all_init_functions if not f in all_init_functions_called]
for f in missing_calls:
info = ["Missing call to ", f, " in ", most_derived_init, ".\n"]
json = self.generate_result(info)
results.append(json)
return results
class MultipleCalls(AbstractCheck):
ARGUMENT = "multiple-calls"
IMPACT = CheckClassification.HIGH
HELP = "Init functions called multiple times"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initialize-functions-are-called-multiple-times"
WIKI_TITLE = "Initialize functions are called multiple times"
# region wiki_description
WIKI_DESCRIPTION = """
Detect multiple calls to a initialize function.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Base{
function initialize(uint) public{
///
}
}
contract Derived is Base{
function initialize(uint a, uint b) public{
initialize(a);
}
}
contract DerivedDerived is Derived{
function initialize() public{
initialize(0);
initialize(0, 1 );
}
}
```
`Base.initialize(uint)` is called two times in `DerivedDerived.initialize` execution, leading to a potential corruption.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Call only one time every initialize function.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
results = []
# TODO: handle MultipleInitTarget
try:
most_derived_init = _get_most_derived_init(self.contract)
except MultipleInitTarget:
# Should be already reported by MissingCalls
# logger.error(red(f'Too many init targets in {self.contract}'))
return []
if most_derived_init is None:
return []
all_init_functions_called = _get_all_internal_calls(most_derived_init) + [most_derived_init]
double_calls = list(
{f for f in all_init_functions_called if all_init_functions_called.count(f) > 1}
)
for f in double_calls:
info = [f, " is called multiple times in ", most_derived_init, ".\n"]
json = self.generate_result(info)
results.append(json)
return results
class InitializeTarget(AbstractCheck):
ARGUMENT = "initialize-target"
IMPACT = CheckClassification.INFORMATIONAL
HELP = "Initialize function that must be called"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initialize-function"
WIKI_TITLE = "Initialize function"
# region wiki_description
WIKI_DESCRIPTION = """
Show the function that must be called at deployment.
This finding does not have an immediate security impact and is informative.
"""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Ensure that the function is called at deployment.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
def _check(self):
# TODO: handle MultipleInitTarget
try:
most_derived_init = _get_most_derived_init(self.contract)
except MultipleInitTarget:
# Should be already reported by MissingCalls
# logger.error(red(f'Too many init targets in {self.contract}'))
return []
if most_derived_init is None:
return []
info = [
self.contract,
" needs to be initialized by ",
most_derived_init,
".\n",
]
json = self.generate_result(info)
return [json]
| 12,131 | Python | .py | 318 | 31.647799 | 136 | 0.68661 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,020 | variables_order.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/variables_order.py | from slither.tools.upgradeability.checks.abstract_checks import (
CheckClassification,
AbstractCheck,
)
class MissingVariable(AbstractCheck):
ARGUMENT = "missing-variables"
IMPACT = CheckClassification.MEDIUM
HELP = "Variable missing in the v2"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#missing-variables"
WIKI_TITLE = "Missing variables"
# region wiki_description
WIKI_DESCRIPTION = """
Detect variables that were present in the original contracts but are not in the updated one.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract V1{
uint variable1;
uint variable2;
}
contract V2{
uint variable1;
}
```
The new version, `V2` does not contain `variable1`.
If a new variable is added in an update of `V2`, this variable will hold the latest value of `variable2` and
will be corrupted.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Do not change the order of the state variables in the updated contract.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_CONTRACT_V2 = True
def _check(self):
contract1 = self.contract
contract2 = self.contract_v2
order1 = [
variable
for variable in contract1.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
order2 = [
variable
for variable in contract2.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
results = []
for idx, _ in enumerate(order1):
variable1 = order1[idx]
if len(order2) <= idx:
info = ["Variable missing in ", contract2, ": ", variable1, "\n"]
json = self.generate_result(info)
results.append(json)
return results
class DifferentVariableContractProxy(AbstractCheck):
ARGUMENT = "order-vars-proxy"
IMPACT = CheckClassification.HIGH
HELP = "Incorrect vars order with the proxy"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#incorrect-variables-with-the-proxy"
WIKI_TITLE = "Incorrect variables with the proxy"
# region wiki_description
WIKI_DESCRIPTION = """
Detect variables that are different between the contract and the proxy.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable1;
}
contract Proxy{
address variable1;
}
```
`Contract` and `Proxy` do not have the same storage layout. As a result the storage of both contracts can be corrupted.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Avoid variables in the proxy. If a variable is in the proxy, ensure it has the same layout than in the contract.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_PROXY = True
def _contract1(self):
return self.contract
def _contract2(self):
return self.proxy
def _check(self):
contract1 = self._contract1()
contract2 = self._contract2()
order1 = [
variable
for variable in contract1.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
order2 = [
variable
for variable in contract2.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
results = []
for idx, _ in enumerate(order1):
if len(order2) <= idx:
# Handle by MissingVariable
return results
variable1 = order1[idx]
variable2 = order2[idx]
if (variable1.name != variable2.name) or (variable1.type != variable2.type):
info = [
"Different variables between ",
contract1,
" and ",
contract2,
"\n",
]
info += ["\t ", variable1, "\n"]
info += ["\t ", variable2, "\n"]
json = self.generate_result(info)
results.append(json)
return results
class DifferentVariableContractNewContract(DifferentVariableContractProxy):
ARGUMENT = "order-vars-contracts"
HELP = "Incorrect vars order with the v2"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#incorrect-variables-with-the-v2"
WIKI_TITLE = "Incorrect variables with the v2"
# region wiki_description
WIKI_DESCRIPTION = """
Detect variables that are different between the original contract and the updated one.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable1;
}
contract ContractV2{
address variable1;
}
```
`Contract` and `ContractV2` do not have the same storage layout. As a result the storage of both contracts can be corrupted.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Respect the variable order of the original contract in the updated contract.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_PROXY = False
REQUIRE_CONTRACT_V2 = True
def _contract2(self):
return self.contract_v2
class ExtraVariablesProxy(AbstractCheck):
ARGUMENT = "extra-vars-proxy"
IMPACT = CheckClassification.MEDIUM
HELP = "Extra vars in the proxy"
WIKI = (
"https://github.com/crytic/slither/wiki/Upgradeability-Checks#extra-variables-in-the-proxy"
)
WIKI_TITLE = "Extra variables in the proxy"
# region wiki_description
WIKI_DESCRIPTION = """
Detect variables that are in the proxy and not in the contract.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable1;
}
contract Proxy{
uint variable1;
uint variable2;
}
```
`Proxy` contains additional variables. A future update of `Contract` is likely to corrupt the proxy.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Avoid variables in the proxy. If a variable is in the proxy, ensure it has the same layout than in the contract.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_PROXY = True
def _contract1(self):
return self.contract
def _contract2(self):
return self.proxy
def _check(self):
contract1 = self._contract1()
contract2 = self._contract2()
order1 = [
variable
for variable in contract1.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
order2 = [
variable
for variable in contract2.state_variables_ordered
if not (variable.is_constant or variable.is_immutable)
]
results = []
if len(order2) <= len(order1):
return []
idx = len(order1)
while idx < len(order2):
variable2 = order2[idx]
info = ["Extra variables in ", contract2, ": ", variable2, "\n"]
json = self.generate_result(info)
results.append(json)
idx = idx + 1
return results
class ExtraVariablesNewContract(ExtraVariablesProxy):
ARGUMENT = "extra-vars-v2"
HELP = "Extra vars in the v2"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#extra-variables-in-the-v2"
WIKI_TITLE = "Extra variables in the v2"
# region wiki_description
WIKI_DESCRIPTION = """
Show new variables in the updated contract.
This finding does not have an immediate security impact and is informative.
"""
# endregion wiki_description
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Ensure that all the new variables are expected.
"""
# endregion wiki_recommendation
IMPACT = CheckClassification.INFORMATIONAL
REQUIRE_CONTRACT = True
REQUIRE_PROXY = False
REQUIRE_CONTRACT_V2 = True
def _contract2(self):
return self.contract_v2
| 8,456 | Python | .py | 244 | 27.979508 | 124 | 0.665154 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,021 | functions_ids.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/functions_ids.py | from slither.exceptions import SlitherError
from slither.tools.upgradeability.checks.abstract_checks import (
AbstractCheck,
CheckClassification,
)
from slither.utils.function import get_function_id
def get_signatures(c):
functions = c.functions
functions = [
f.full_name
for f in functions
if f.visibility in ["public", "external"] and not f.is_constructor and not f.is_fallback
]
variables = c.state_variables
variables = [
variable.name + "()" for variable in variables if variable.visibility in ["public"]
]
return list(set(functions + variables))
def _get_function_or_variable(contract, signature):
f = contract.get_function_from_full_name(signature)
if f:
return f
for variable in contract.state_variables:
# Todo: can lead to incorrect variable in case of shadowing
if variable.visibility in ["public"]:
if variable.name + "()" == signature:
return variable
raise SlitherError(f"Function id checks: {signature} not found in {contract.name}")
class IDCollision(AbstractCheck):
ARGUMENT = "function-id-collision"
IMPACT = CheckClassification.HIGH
HELP = "Functions ids collision"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#functions-ids-collisions"
WIKI_TITLE = "Functions ids collisions"
# region wiki_description
WIKI_DESCRIPTION = """
Detect function id collision between the contract and the proxy.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
function gsf() public {
// ...
}
}
contract Proxy{
function tgeo() public {
// ...
}
}
```
`Proxy.tgeo()` and `Contract.gsf()` have the same function id (0x67e43e43).
As a result, `Proxy.tgeo()` will shadow Contract.gsf()`.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Rename the function. Avoid public functions in the proxy.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_PROXY = True
def _check(self):
signatures_implem = get_signatures(self.contract)
signatures_proxy = get_signatures(self.proxy)
signatures_ids_implem = {get_function_id(s): s for s in signatures_implem}
signatures_ids_proxy = {get_function_id(s): s for s in signatures_proxy}
results = []
for (k, _) in signatures_ids_implem.items():
if k in signatures_ids_proxy:
if signatures_ids_implem[k] != signatures_ids_proxy[k]:
implem_function = _get_function_or_variable(
self.contract, signatures_ids_implem[k]
)
proxy_function = _get_function_or_variable(self.proxy, signatures_ids_proxy[k])
info = [
"Function id collision found: ",
implem_function,
" ",
proxy_function,
"\n",
]
json = self.generate_result(info)
results.append(json)
return results
class FunctionShadowing(AbstractCheck):
ARGUMENT = "function-shadowing"
IMPACT = CheckClassification.HIGH
HELP = "Functions shadowing"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#functions-shadowing"
WIKI_TITLE = "Functions shadowing"
# region wiki_description
WIKI_DESCRIPTION = """
Detect function shadowing between the contract and the proxy.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
function get() public {
// ...
}
}
contract Proxy{
function get() public {
// ...
}
}
```
`Proxy.get` will shadow any call to `get()`. As a result `get()` is never executed in the logic contract and cannot be updated.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Rename the function. Avoid public functions in the proxy.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_PROXY = True
def _check(self):
signatures_implem = get_signatures(self.contract)
signatures_proxy = get_signatures(self.proxy)
signatures_ids_implem = {get_function_id(s): s for s in signatures_implem}
signatures_ids_proxy = {get_function_id(s): s for s in signatures_proxy}
results = []
for (k, _) in signatures_ids_implem.items():
if k in signatures_ids_proxy:
if signatures_ids_implem[k] == signatures_ids_proxy[k]:
implem_function = _get_function_or_variable(
self.contract, signatures_ids_implem[k]
)
proxy_function = _get_function_or_variable(self.proxy, signatures_ids_proxy[k])
info = [
"Function shadowing found: ",
implem_function,
" ",
proxy_function,
"\n",
]
json = self.generate_result(info)
results.append(json)
return results
| 5,427 | Python | .py | 145 | 28.765517 | 127 | 0.618948 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,022 | constant.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/constant.py | from slither.tools.upgradeability.checks.abstract_checks import (
AbstractCheck,
CheckClassification,
)
class WereConstant(AbstractCheck):
ARGUMENT = "were-constant"
IMPACT = CheckClassification.HIGH
HELP = "Variables that should be constant"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#variables-that-should-be-constant"
WIKI_TITLE = "Variables that should be constant"
# region wiki_description
WIKI_DESCRIPTION = """
Detect state variables that should be `constant̀`.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable1;
uint constant variable2;
uint variable3;
}
contract ContractV2{
uint variable1;
uint variable2;
uint variable3;
}
```
Because `variable2` is not anymore a `constant`, the storage location of `variable3` will be different.
As a result, `ContractV2` will have a corrupted storage layout.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Do not remove `constant` from a state variables during an update.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_CONTRACT_V2 = True
def _check(self):
contract_v1 = self.contract
contract_v2 = self.contract_v2
state_variables_v1 = contract_v1.state_variables
state_variables_v2 = contract_v2.state_variables
v2_additional_variables = len(state_variables_v2) - len(state_variables_v1)
v2_additional_variables = max(v2_additional_variables, 0)
# We keep two index, because we need to have them out of sync if v2
# has additional non constant variables
idx_v1 = 0
idx_v2 = 0
results = []
while idx_v1 < len(state_variables_v1):
state_v1 = contract_v1.state_variables[idx_v1]
if len(state_variables_v2) <= idx_v2:
break
state_v2 = contract_v2.state_variables[idx_v2]
if state_v2:
if state_v1.is_constant:
if not state_v2.is_constant:
# If v2 has additional non constant variables, we need to skip them
if (
state_v1.name != state_v2.name or state_v1.type != state_v2.type
) and v2_additional_variables > 0:
v2_additional_variables -= 1
idx_v2 += 1
continue
info = [state_v1, " was constant, but ", state_v2, "is not.\n"]
json = self.generate_result(info)
results.append(json)
idx_v1 += 1
idx_v2 += 1
return results
class BecameConstant(AbstractCheck):
ARGUMENT = "became-constant"
IMPACT = CheckClassification.HIGH
HELP = "Variables that should not be constant"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#variables-that-should-not-be-constant"
WIKI_TITLE = "Variables that should not be constant"
# region wiki_description
WIKI_DESCRIPTION = """
Detect state variables that should not be `constant̀`.
"""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
uint variable1;
uint variable2;
uint variable3;
}
contract ContractV2{
uint variable1;
uint constant variable2;
uint variable3;
}
```
Because `variable2` is now a `constant`, the storage location of `variable3` will be different.
As a result, `ContractV2` will have a corrupted storage layout.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Do not make an existing state variable `constant`.
"""
# endregion wiki_recommendation
REQUIRE_CONTRACT = True
REQUIRE_CONTRACT_V2 = True
def _check(self):
contract_v1 = self.contract
contract_v2 = self.contract_v2
state_variables_v1 = contract_v1.state_variables
state_variables_v2 = contract_v2.state_variables
v2_additional_variables = len(state_variables_v2) - len(state_variables_v1)
v2_additional_variables = max(v2_additional_variables, 0)
# We keep two index, because we need to have them out of sync if v2
# has additional non constant variables
idx_v1 = 0
idx_v2 = 0
results = []
while idx_v1 < len(state_variables_v1):
state_v1 = contract_v1.state_variables[idx_v1]
if len(state_variables_v2) <= idx_v2:
break
state_v2 = contract_v2.state_variables[idx_v2]
if state_v2:
if state_v1.is_constant:
if not state_v2.is_constant:
# If v2 has additional non constant variables, we need to skip them
if (
state_v1.name != state_v2.name or state_v1.type != state_v2.type
) and v2_additional_variables > 0:
v2_additional_variables -= 1
idx_v2 += 1
continue
elif state_v2.is_constant:
info = [state_v1, " was not constant but ", state_v2, " is.\n"]
json = self.generate_result(info)
results.append(json)
idx_v1 += 1
idx_v2 += 1
return results
| 5,612 | Python | .py | 143 | 29.839161 | 111 | 0.616461 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,023 | all_checks.py | NioTheFirst_ScType/slither/tools/upgradeability/checks/all_checks.py | # pylint: disable=unused-import
from slither.tools.upgradeability.checks.initialization import (
InitializablePresent,
InitializableInherited,
InitializableInitializer,
MissingInitializerModifier,
MissingCalls,
MultipleCalls,
InitializeTarget,
)
from slither.tools.upgradeability.checks.functions_ids import IDCollision, FunctionShadowing
from slither.tools.upgradeability.checks.variable_initialization import VariableWithInit
from slither.tools.upgradeability.checks.variables_order import (
MissingVariable,
DifferentVariableContractProxy,
DifferentVariableContractNewContract,
ExtraVariablesProxy,
ExtraVariablesNewContract,
)
from slither.tools.upgradeability.checks.constant import WereConstant, BecameConstant
| 769 | Python | .py | 20 | 34.85 | 92 | 0.849664 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,024 | __main__.py | NioTheFirst_ScType/slither/tools/properties/__main__.py | import argparse
import logging
import sys
from typing import Any
from crytic_compile import cryticparser
from slither import Slither
from slither.tools.properties.properties.erc20 import generate_erc20, ERC20_PROPERTIES
from slither.tools.properties.addresses.address import (
Addresses,
OWNER_ADDRESS,
USER_ADDRESS,
ATTACKER_ADDRESS,
)
from slither.utils.myprettytable import MyPrettyTable
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
logger = logging.getLogger("Slither")
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
logger.addHandler(ch)
logger.handlers[0].setFormatter(formatter)
logger.propagate = False
def _all_scenarios() -> str:
txt = "\n"
txt += "#################### ERC20 ####################\n"
for k, value in ERC20_PROPERTIES.items():
txt += f"{k} - {value.description}\n"
return txt
def _all_properties() -> MyPrettyTable:
table = MyPrettyTable(["Num", "Description", "Scenario"])
idx = 0
for scenario, value in ERC20_PROPERTIES.items():
for prop in value.properties:
table.add_row([str(idx), prop.description, scenario])
idx = idx + 1
return table
class ListScenarios(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
logger.info(_all_scenarios())
parser.exit()
class ListProperties(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
logger.info(_all_properties())
parser.exit()
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(
description="Demo",
usage="slither-demo filename",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"filename", help="The filename of the contract or truffle directory to analyze."
)
parser.add_argument("--contract", help="The targeted contract.")
parser.add_argument(
"--scenario",
help="Test a specific scenario. Use --list-scenarios to see the available scenarios. Default Transferable",
default="Transferable",
)
parser.add_argument(
"--list-scenarios",
help="List available scenarios",
action=ListScenarios,
nargs=0,
default=False,
)
parser.add_argument(
"--list-properties",
help="List available properties",
action=ListProperties,
nargs=0,
default=False,
)
parser.add_argument(
"--address-owner", help=f"Owner address. Default {OWNER_ADDRESS}", default=None
)
parser.add_argument(
"--address-user", help=f"Owner address. Default {USER_ADDRESS}", default=None
)
parser.add_argument(
"--address-attacker",
help=f"Attacker address. Default {ATTACKER_ADDRESS}",
default=None,
)
# Add default arguments from crytic-compile
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
def main() -> None:
args = parse_args()
# Perform slither analysis on the given filename
slither = Slither(args.filename, **vars(args))
contracts = slither.get_contract_from_name(args.contract)
if len(contracts) != 1:
if len(slither.contracts) == 1:
contract = slither.contracts[0]
else:
if args.contract is None:
to_log = "Specify the target: --contract ContractName"
else:
to_log = f"{args.contract} not found"
logger.error(to_log)
return
else:
contract = contracts[0]
addresses = Addresses(args.address_owner, args.address_user, args.address_attacker)
generate_erc20(contract, args.scenario, addresses)
if __name__ == "__main__":
main()
| 4,232 | Python | .py | 120 | 29.016667 | 115 | 0.659147 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,025 | utils.py | NioTheFirst_ScType/slither/tools/properties/utils.py | import logging
from pathlib import Path
from slither.utils.colors import green, yellow
logger = logging.getLogger("Slither")
def write_file(
output_dir: Path,
filename: str,
content: str,
allow_overwrite: bool = True,
discard_if_exist: bool = False,
) -> None:
"""
Write the content into output_dir/filename
:param output_dir:
:param filename:
:param content:
:param allow_overwrite: If true, allows to overwrite existing file (default: true). Emit warning if overwrites
:param discard_if_exist: If true, it will not emit warning or overwrite the file if it exists, (default: False)
:return:
"""
file_to_write = Path(output_dir, filename)
if file_to_write.exists():
if discard_if_exist:
return
if not allow_overwrite:
logger.info(yellow(f"{file_to_write} already exist and will not be overwritten"))
return
logger.info(yellow(f"Overwrite {file_to_write}"))
else:
logger.info(green(f"Write {file_to_write}"))
with open(file_to_write, "w", encoding="utf8") as f:
f.write(content)
| 1,130 | Python | .py | 32 | 29.5625 | 115 | 0.670018 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,026 | generate_properties.py | NioTheFirst_ScType/slither/tools/properties/solidity/generate_properties.py | import logging
from pathlib import Path
from typing import Tuple
from slither.core.declarations import Contract
from slither.tools.properties.addresses.address import Addresses
from slither.tools.properties.utils import write_file
logger = logging.getLogger("Slither")
def generate_solidity_properties(
contract: Contract, type_property: str, solidity_properties: str, output_dir: Path
) -> Path:
solidity_import = 'import "./interfaces.sol";\n'
solidity_import += f'import "../{contract.source_mapping.filename.short}";'
test_contract_name = f"Properties{contract.name}{type_property}"
solidity_content = (
f"{solidity_import}\ncontract {test_contract_name} is CryticInterface,{contract.name}"
)
solidity_content += f"{{\n\n{solidity_properties}\n}}\n"
filename = f"{test_contract_name}.sol"
write_file(output_dir, filename, solidity_content)
return Path(filename)
def generate_test_contract(
contract: Contract,
type_property: str,
output_dir: Path,
property_file: Path,
initialization_recommendation: str,
) -> Tuple[str, str]:
test_contract_name = f"Test{contract.name}{type_property}"
properties_name = f"Properties{contract.name}{type_property}"
content = ""
content += f'import "./{property_file}";\n'
content += f"contract {test_contract_name} is {properties_name} {{\n"
content += "\tconstructor() public{\n"
content += "\t\t// Existing addresses:\n"
content += "\t\t// - crytic_owner: If the contract has an owner, it must be crytic_owner\n"
content += "\t\t// - crytic_user: Legitimate user\n"
content += "\t\t// - crytic_attacker: Attacker\n"
content += "\t\t// \n"
content += initialization_recommendation
content += "\t\t// \n"
content += "\t\t// \n"
content += "\t\t// Update the following if totalSupply and balanceOf are external functions or state variables:\n\n"
content += "\t\tinitialTotalSupply = totalSupply();\n"
content += "\t\tinitialBalance_owner = balanceOf(crytic_owner);\n"
content += "\t\tinitialBalance_user = balanceOf(crytic_user);\n"
content += "\t\tinitialBalance_attacker = balanceOf(crytic_attacker);\n"
content += "\t}\n}\n"
filename = f"{test_contract_name}.sol"
write_file(output_dir, filename, content, allow_overwrite=False)
return filename, test_contract_name
def generate_solidity_interface(output_dir: Path, addresses: Addresses):
content = f"""
contract CryticInterface{{
address internal crytic_owner = address({addresses.owner});
address internal crytic_user = address({addresses.user});
address internal crytic_attacker = address({addresses.attacker});
uint internal initialTotalSupply;
uint internal initialBalance_owner;
uint internal initialBalance_user;
uint internal initialBalance_attacker;
}}"""
# Static file, we discard if it exists as it should never change
write_file(output_dir, "interfaces.sol", content, discard_if_exist=True)
| 3,009 | Python | .py | 63 | 43.301587 | 120 | 0.713798 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,027 | address.py | NioTheFirst_ScType/slither/tools/properties/addresses/address.py | from typing import Optional
# These are the default values in truffle
# https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console
OWNER_ADDRESS = "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"
USER_ADDRESS = "0xf17f52151EbEF6C7334FAD080c5704D77216b732"
ATTACKER_ADDRESS = "0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef"
class Addresses: # pylint: disable=too-few-public-methods
def __init__(
self,
owner: Optional[str] = None,
user: Optional[str] = None,
attacker: Optional[str] = None,
):
self.owner = owner if owner else OWNER_ADDRESS
self.user = user if user else USER_ADDRESS
self.attacker = attacker if attacker else ATTACKER_ADDRESS
| 740 | Python | .py | 16 | 41.0625 | 97 | 0.747573 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,028 | properties.py | NioTheFirst_ScType/slither/tools/properties/properties/properties.py | from enum import Enum
from typing import NamedTuple
class PropertyType(Enum):
CODE_QUALITY = 1
LOW_SEVERITY = 2
MEDIUM_SEVERITY = 3
HIGH_SEVERITY = 4
class PropertyReturn(Enum):
SUCCESS = 1
FAIL_OR_THROW = 2
FAIL = 3
THROW = 4
class PropertyCaller(Enum):
OWNER = 1
SENDER = 2
ATTACKER = 3
ALL = 4 # If all the actors should call the function. Typically if the test uses msg.sender
ANY = 5 # If the caller does not matter
class Property(NamedTuple): # pylint: disable=inherit-non-class,too-few-public-methods
name: str
content: str
type: PropertyType
return_type: PropertyReturn
is_unit_test: bool
caller: PropertyCaller # Only for unit tests. Echidna will try all the callers
is_property_test: bool
description: str
def property_to_solidity(p: Property):
return f"\tfunction {p.name} public returns(bool){{{p.content}\n\t}}\n"
| 929 | Python | .py | 29 | 27.655172 | 96 | 0.706742 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,029 | erc20.py | NioTheFirst_ScType/slither/tools/properties/properties/erc20.py | import logging
from collections import namedtuple
from pathlib import Path
from typing import Tuple, List
from crytic_compile.platform.abstract_platform import AbstractPlatform
from crytic_compile.platform import Type as PlatformType
from slither.core.declarations import Contract
from slither.tools.properties.addresses.address import Addresses
from slither.tools.properties.platforms.echidna import generate_echidna_config
from slither.tools.properties.properties.ercs.erc20.properties.burn import (
ERC20_NotBurnable,
ERC20_Burnable,
)
from slither.tools.properties.properties.ercs.erc20.properties.initialization import ERC20_CONFIG
from slither.tools.properties.properties.ercs.erc20.properties.mint import ERC20_NotMintable
from slither.tools.properties.properties.ercs.erc20.properties.mint_and_burn import (
ERC20_NotMintableNotBurnable,
)
from slither.tools.properties.properties.ercs.erc20.properties.transfer import (
ERC20_Transferable,
ERC20_Pausable,
)
from slither.tools.properties.properties.ercs.erc20.unit_tests.truffle import generate_truffle_test
from slither.tools.properties.properties.properties import (
property_to_solidity,
Property,
)
from slither.tools.properties.solidity.generate_properties import (
generate_solidity_properties,
generate_test_contract,
generate_solidity_interface,
)
from slither.utils.colors import red, green
logger = logging.getLogger("Slither")
PropertyDescription = namedtuple("PropertyDescription", ["properties", "description"])
ERC20_PROPERTIES = {
"Transferable": PropertyDescription(ERC20_Transferable, "Test the correct tokens transfer"),
"Pausable": PropertyDescription(ERC20_Pausable, "Test the pausable functionality"),
"NotMintable": PropertyDescription(ERC20_NotMintable, "Test that no one can mint tokens"),
"NotMintableNotBurnable": PropertyDescription(
ERC20_NotMintableNotBurnable, "Test that no one can mint or burn tokens"
),
"NotBurnable": PropertyDescription(ERC20_NotBurnable, "Test that no one can burn tokens"),
"Burnable": PropertyDescription(
ERC20_Burnable,
'Test the burn of tokens. Require the "burn(address) returns()" function',
),
}
def generate_erc20(
contract: Contract, type_property: str, addresses: Addresses
): # pylint: disable=too-many-locals
"""
Generate the ERC20 tests
Files generated:
- interfaces.sol: generic crytic interface
- Properties[CONTRACTNAME].sol: erc20 properties
- Test[CONTRACTNAME].sol: Target, its constructor needs to be manually updated
- If truffle
- migrations/x_Test[CONTRACTNAME].js
- test/crytic/InitializationTest[CONTRACTNAME].js: unit tests to check that the contract is correctly configured
- test/crytic/Test[CONTRACTNAME].js: ERC20 checks
- echidna_config.yaml: configuration file
:param addresses:
:param contract:
:param type_property: One of ERC20_PROPERTIES.keys()
:return:
"""
if contract.compilation_unit.core.crytic_compile is None:
logging.error("Please compile with crytic-compile")
return
if contract.compilation_unit.core.crytic_compile.type not in [
PlatformType.TRUFFLE,
PlatformType.SOLC,
PlatformType.BUILDER,
]:
logging.error(
f"{contract.compilation_unit.core.crytic_compile.type} not yet supported by slither-prop"
)
return
# Check if the contract is an ERC20 contract and if the functions have the correct visibility
errors = _check_compatibility(contract)
if errors:
logger.error(red(errors))
return
erc_properties = ERC20_PROPERTIES.get(type_property, None)
if erc_properties is None:
logger.error(f"{type_property} unknown. Types available {ERC20_PROPERTIES.keys()}")
return
properties = erc_properties.properties
# Generate the output directory
output_dir = _platform_to_output_dir(contract.compilation_unit.core.crytic_compile.platform)
output_dir.mkdir(exist_ok=True)
# Get the properties
solidity_properties, unit_tests = _get_properties(contract, properties)
# Generate the contract containing the properties
generate_solidity_interface(output_dir, addresses)
property_file = generate_solidity_properties(
contract, type_property, solidity_properties, output_dir
)
# Generate the Test contract
initialization_recommendation = _initialization_recommendation(type_property)
contract_filename, contract_name = generate_test_contract(
contract,
type_property,
output_dir,
property_file,
initialization_recommendation,
)
# Generate Echidna config file
echidna_config_filename = generate_echidna_config(
Path(contract.compilation_unit.core.crytic_compile.target).parent, addresses
)
unit_test_info = ""
# If truffle, generate unit tests
if contract.compilation_unit.core.crytic_compile.type == PlatformType.TRUFFLE:
unit_test_info = generate_truffle_test(contract, type_property, unit_tests, addresses)
logger.info("################################################")
logger.info(green(f"Update the constructor in {Path(output_dir, contract_filename)}"))
if unit_test_info:
logger.info(green(unit_test_info))
logger.info(green("To run Echidna:"))
txt = f"\t echidna-test {contract.compilation_unit.core.crytic_compile.target} "
txt += f"--contract {contract_name} --config {echidna_config_filename}"
logger.info(green(txt))
def _initialization_recommendation(type_property: str) -> str:
content = ""
content += "\t\t// Add below a minimal configuration:\n"
content += "\t\t// - crytic_owner must have some tokens \n"
content += "\t\t// - crytic_user must have some tokens \n"
content += "\t\t// - crytic_attacker must have some tokens \n"
if type_property in ["Pausable"]:
content += "\t\t// - The contract must be paused \n"
if type_property in ["NotMintable", "NotMintableNotBurnable"]:
content += "\t\t// - The contract must not be mintable \n"
if type_property in ["NotBurnable", "NotMintableNotBurnable"]:
content += "\t\t// - The contract must not be burnable \n"
content += "\n"
content += "\n"
return content
# TODO: move this to crytic-compile
def _platform_to_output_dir(platform: AbstractPlatform) -> Path:
if platform.TYPE in [PlatformType.TRUFFLE, platform.TYPE == PlatformType.BUILDER]:
return Path(platform.target, "contracts", "crytic")
if platform.TYPE == PlatformType.SOLC:
return Path(platform.target).parent
return Path()
def _check_compatibility(contract):
errors = ""
if not contract.is_erc20():
errors = f"{contract} is not ERC20 compliant. Consider checking the contract with slither-check-erc"
return errors
transfer = contract.get_function_from_signature("transfer(address,uint256)")
if transfer.visibility != "public":
errors = f"slither-prop requires {transfer.canonical_name} to be public. Please change the visibility"
transfer_from = contract.get_function_from_signature("transferFrom(address,address,uint256)")
if transfer_from.visibility != "public":
if errors:
errors += "\n"
errors += f"slither-prop requires {transfer_from.canonical_name} to be public. Please change the visibility"
approve = contract.get_function_from_signature("approve(address,uint256)")
if approve.visibility != "public":
if errors:
errors += "\n"
errors += f"slither-prop requires {approve.canonical_name} to be public. Please change the visibility"
return errors
def _get_properties(contract, properties: List[Property]) -> Tuple[str, List[Property]]:
solidity_properties = ""
if contract.compilation_unit.crytic_compile.type == PlatformType.TRUFFLE:
solidity_properties += "\n".join([property_to_solidity(p) for p in ERC20_CONFIG])
solidity_properties += "\n".join([property_to_solidity(p) for p in properties])
unit_tests = [p for p in properties if p.is_unit_test]
return solidity_properties, unit_tests
| 8,234 | Python | .py | 172 | 42.383721 | 120 | 0.727386 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,030 | mint.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/properties/mint.py | from slither.tools.properties.properties.properties import (
PropertyType,
PropertyReturn,
Property,
PropertyCaller,
)
ERC20_NotMintable = [
Property(
name="crytic_supply_constant_ERC20PropertiesNotMintable()",
description="The total supply does not increase.",
content="""
\t\treturn initialTotalSupply >= this.totalSupply();""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ANY,
),
]
| 565 | Python | .py | 19 | 24.052632 | 67 | 0.693578 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,031 | mint_and_burn.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/properties/mint_and_burn.py | from slither.tools.properties.properties.properties import (
Property,
PropertyType,
PropertyReturn,
PropertyCaller,
)
ERC20_NotMintableNotBurnable = [
Property(
name="crytic_supply_constant_ERC20PropertiesNotMintableNotBurnable()",
description="The total supply does not change.",
content="""
\t\treturn initialTotalSupply == this.totalSupply();""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ANY,
),
]
| 585 | Python | .py | 19 | 25.105263 | 78 | 0.704425 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,032 | initialization.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/properties/initialization.py | from slither.tools.properties.properties.properties import (
Property,
PropertyType,
PropertyReturn,
PropertyCaller,
)
ERC20_CONFIG = [
Property(
name="init_total_supply()",
description="The total supply is correctly initialized.",
content="""
\t\treturn this.totalSupply() >= 0 && this.totalSupply() == initialTotalSupply;""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ANY,
),
Property(
name="init_owner_balance()",
description="Owner's balance is correctly initialized.",
content="""
\t\treturn initialBalance_owner == this.balanceOf(crytic_owner);""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ANY,
),
Property(
name="init_user_balance()",
description="User's balance is correctly initialized.",
content="""
\t\treturn initialBalance_user == this.balanceOf(crytic_user);""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ANY,
),
Property(
name="init_attacker_balance()",
description="Attacker's balance is correctly initialized.",
content="""
\t\treturn initialBalance_attacker == this.balanceOf(crytic_attacker);""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ANY,
),
Property(
name="init_caller_balance()",
description="All the users have a positive balance.",
content="""
\t\treturn this.balanceOf(msg.sender) >0 ;""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ALL,
),
# Note: there is a potential overflow on the addition, but we dont consider it
Property(
name="init_total_supply_is_balances()",
description="The total supply is the user and owner balance.",
content="""
\t\treturn this.balanceOf(crytic_owner) + this.balanceOf(crytic_user) + this.balanceOf(crytic_attacker) == this.totalSupply();""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=False,
caller=PropertyCaller.ANY,
),
]
| 2,656 | Python | .py | 75 | 28.373333 | 130 | 0.657752 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,033 | transfer.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/properties/transfer.py | from slither.tools.properties.properties.properties import (
Property,
PropertyType,
PropertyReturn,
PropertyCaller,
)
ERC20_Transferable = [
Property(
name="crytic_zero_always_empty_ERC20Properties()",
description="The address 0x0 should not receive tokens.",
content="""
\t\treturn this.balanceOf(address(0x0)) == 0;""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ANY,
),
Property(
name="crytic_approve_overwrites()",
description="Allowance can be changed.",
content="""
\t\tbool approve_return;
\t\tapprove_return = approve(crytic_user, 10);
\t\trequire(approve_return);
\t\tapprove_return = approve(crytic_user, 20);
\t\trequire(approve_return);
\t\treturn this.allowance(msg.sender, crytic_user) == 20;""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_less_than_total_ERC20Properties()",
description="Balance of one user must be less or equal to the total supply.",
content="""
\t\treturn this.balanceOf(msg.sender) <= this.totalSupply();""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_totalSupply_consistant_ERC20Properties()",
description="Balance of the crytic users must be less or equal to the total supply.",
content="""
\t\treturn this.balanceOf(crytic_owner) + this.balanceOf(crytic_user) + this.balanceOf(crytic_attacker) <= this.totalSupply();""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ANY,
),
Property(
name="crytic_revert_transfer_to_zero_ERC20PropertiesTransferable()",
description="Using transfer to send tokens to the address 0x0 will revert.",
content="""
\t\tif (this.balanceOf(msg.sender) == 0){
\t\t\trevert();
\t\t}
\t\treturn transfer(address(0x0), this.balanceOf(msg.sender));""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.FAIL_OR_THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_revert_transferFrom_to_zero_ERC20PropertiesTransferable()",
description="Using transferFrom to send tokens to the address 0x0 will revert.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\tif (balance == 0){
\t\t\trevert();
\t\t}
\t\tapprove(msg.sender, balance);
\t\treturn transferFrom(msg.sender, address(0x0), this.balanceOf(msg.sender));""",
type=PropertyType.CODE_QUALITY,
return_type=PropertyReturn.FAIL_OR_THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_self_transferFrom_ERC20PropertiesTransferable()",
description="Self transfering tokens using transferFrom works as expected.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\tbool approve_return = approve(msg.sender, balance);
\t\tbool transfer_return = transferFrom(msg.sender, msg.sender, balance);
\t\treturn (this.balanceOf(msg.sender) == balance) && approve_return && transfer_return;""",
type=PropertyType.HIGH_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_self_transferFrom_to_other_ERC20PropertiesTransferable()",
description="Transfering tokens to other address using transferFrom works as expected.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\tbool approve_return = approve(msg.sender, balance);
\t\taddress other = crytic_user;
\t\tif (other == msg.sender) {
\t\t\tother = crytic_owner;
\t\t}
\t\tbool transfer_return = transferFrom(msg.sender, other, balance);
\t\treturn (this.balanceOf(msg.sender) == 0) && approve_return && transfer_return;""",
type=PropertyType.HIGH_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_self_transfer_ERC20PropertiesTransferable()",
description="Self transfering tokens using transfer works as expected.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\tbool transfer_return = transfer(msg.sender, balance);
\t\treturn (this.balanceOf(msg.sender) == balance) && transfer_return;""",
type=PropertyType.HIGH_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_transfer_to_other_ERC20PropertiesTransferable()",
description="Transfering tokens to other address using transfer works as expected.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\taddress other = crytic_user;
\t\tif (other == msg.sender) {
\t\t\tother = crytic_owner;
\t\t}
\t\tif (balance >= 1) {
\t\t\tbool transfer_other = transfer(other, 1);
\t\t\treturn (this.balanceOf(msg.sender) == balance-1) && (this.balanceOf(other) >= 1) && transfer_other;
\t\t}
\t\treturn true;""",
type=PropertyType.HIGH_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_revert_transfer_to_user_ERC20PropertiesTransferable()",
description="Transfering more tokens than the balance will revert.",
content="""
\t\tuint balance = this.balanceOf(msg.sender);
\t\tif (balance == (2 ** 256 - 1))
\t\t\treturn true;
\t\tbool transfer_other = transfer(crytic_user, balance+1);
\t\treturn transfer_other;""",
type=PropertyType.HIGH_SEVERITY,
return_type=PropertyReturn.FAIL_OR_THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
]
ERC20_Pausable = [
Property(
name="crytic_revert_transfer_ERC20AlwaysTruePropertiesNotTransferable()",
description="Cannot transfer.",
content="""
\t\treturn transfer(crytic_user, this.balanceOf(msg.sender));""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.FAIL_OR_THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_revert_transferFrom_ERC20AlwaysTruePropertiesNotTransferable()",
description="Cannot execute transferFrom.",
content="""
\t\tapprove(msg.sender, this.balanceOf(msg.sender));
\t\ttransferFrom(msg.sender, msg.sender, this.balanceOf(msg.sender));""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.FAIL_OR_THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_constantBalance()",
description="Cannot change the balance.",
content="""
\t\treturn this.balanceOf(crytic_user) == initialBalance_user && this.balanceOf(crytic_attacker) == initialBalance_attacker;""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
Property(
name="crytic_constantAllowance()",
description="Cannot change the allowance.",
content="""
\t\treturn (this.allowance(crytic_user, crytic_attacker) == initialAllowance_user_attacker) &&
\t\t\t(this.allowance(crytic_attacker, crytic_attacker) == initialAllowance_attacker_attacker);""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
),
]
| 8,295 | Python | .py | 215 | 32.465116 | 130 | 0.681565 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,034 | burn.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/properties/burn.py | from slither.tools.properties.properties.properties import (
Property,
PropertyType,
PropertyReturn,
PropertyCaller,
)
ERC20_NotBurnable = [
Property(
name="crytic_supply_constant_ERC20PropertiesNotBurnable()",
description="The total supply does not decrease.",
content="""
\t\treturn initialTotalSupply == this.totalSupply();""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.SUCCESS,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ANY,
),
]
# Require burn(address) returns()
ERC20_Burnable = [
Property(
name="crytic_supply_constant_ERC20PropertiesNotBurnable()",
description="Cannot burn more than available balance",
content="""
\t\tuint balance = balanceOf(msg.sender);
\t\tburn(balance + 1);
\t\treturn false;""",
type=PropertyType.MEDIUM_SEVERITY,
return_type=PropertyReturn.THROW,
is_unit_test=True,
is_property_test=True,
caller=PropertyCaller.ALL,
)
]
| 1,058 | Python | .py | 35 | 24.571429 | 67 | 0.684314 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,035 | truffle.py | NioTheFirst_ScType/slither/tools/properties/properties/ercs/erc20/unit_tests/truffle.py | import logging
from pathlib import Path
from typing import List
from slither.core.declarations import Contract
from slither.tools.properties.addresses.address import Addresses
from slither.tools.properties.platforms.truffle import (
generate_migration,
generate_unit_test,
)
from slither.tools.properties.properties.ercs.erc20.properties.initialization import ERC20_CONFIG
from slither.tools.properties.properties.properties import Property
logger = logging.getLogger("Slither")
def generate_truffle_test(
contract: Contract,
type_property: str,
unit_tests: List[Property],
addresses: Addresses,
) -> str:
test_contract = f"Test{contract.name}{type_property}"
filename_init = f"Initialization{test_contract}.js"
filename = f"{test_contract}.js"
output_dir = Path(contract.compilation_unit.core.crytic_compile.target)
generate_migration(test_contract, output_dir, addresses.owner)
generate_unit_test(
test_contract,
filename_init,
ERC20_CONFIG,
output_dir,
addresses,
f"Check the constructor of {test_contract}",
)
generate_unit_test(
test_contract,
filename,
unit_tests,
output_dir,
addresses,
)
log_info = "\n"
log_info += "To run the unit tests:\n"
log_info += f"\ttruffle test {Path(output_dir, 'test', 'crytic', filename_init)}\n"
log_info += f"\ttruffle test {Path(output_dir, 'test', 'crytic', filename)}\n"
return log_info
| 1,507 | Python | .py | 43 | 29.930233 | 97 | 0.714089 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,036 | echidna.py | NioTheFirst_ScType/slither/tools/properties/platforms/echidna.py | from pathlib import Path
from slither.tools.properties.addresses.address import Addresses
from slither.tools.properties.utils import write_file
def generate_echidna_config(output_dir: Path, addresses: Addresses) -> str:
"""
Generate the echidna configuration file
:param output_dir:
:param addresses:
:return:
"""
content = "prefix: crytic_\n"
content += f'deployer: "{addresses.owner}"\n'
content += f'sender: ["{addresses.user}", "{addresses.attacker}"]\n'
content += f'psender: "{addresses.user}"\n'
content += "coverage: true\n"
filename = "echidna_config.yaml"
write_file(output_dir, filename, content)
return filename
| 683 | Python | .py | 18 | 33.666667 | 75 | 0.706949 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,037 | truffle.py | NioTheFirst_ScType/slither/tools/properties/platforms/truffle.py | import logging
import re
from pathlib import Path
from typing import List
from slither.tools.properties.addresses.address import Addresses
from slither.tools.properties.properties.properties import (
PropertyReturn,
Property,
PropertyCaller,
)
from slither.tools.properties.utils import write_file
PATTERN_TRUFFLE_MIGRATION = re.compile("^[0-9]*_")
logger = logging.getLogger("Slither")
def _extract_caller(p: PropertyCaller) -> List[str]:
if p == PropertyCaller.OWNER:
return ["owner"]
if p == PropertyCaller.SENDER:
return ["user"]
if p == PropertyCaller.ATTACKER:
return ["attacker"]
if p == PropertyCaller.ALL:
return ["owner", "user", "attacker"]
assert p == PropertyCaller.ANY
return ["user"]
def _helpers() -> str:
"""
Generate two functions:
- catchRevertThrowReturnFalse: check if the call revert/throw or return false
- catchRevertThrow: check if the call revert/throw
:return:
"""
return """
async function catchRevertThrowReturnFalse(promise) {
try {
const ret = await promise;
assert.equal(balance.valueOf(), false, "Expected revert/throw/or return false");
} catch (error) {
// Not considered: 'out of gas', 'invalid JUMP'
if (!error.message.includes("revert")){
if (!error.message.includes("invalid opcode")){
assert(false, "Expected revert/throw/or return false");
}
}
return;
}
};
async function catchRevertThrow(promise) {
try {
await promise;
} catch (error) {
// Not considered: 'out of gas', 'invalid JUMP'
if (!error.message.includes("revert")){
if (!error.message.includes("invalid opcode")){
assert(false, "Expected revert/throw/or return false");
}
}
return;
}
assert(false, "Expected revert/throw/or return false");
};
"""
def generate_unit_test( # pylint: disable=too-many-arguments,too-many-branches
test_contract: str,
filename: str,
unit_tests: List[Property],
output_dir: Path,
addresses: Addresses,
assert_message: str = "",
) -> Path:
"""
Generate unit tests files
:param test_contract:
:param filename:
:param unit_tests:
:param output_dir:
:param addresses:
:param assert_message:
:return:
"""
content = f'{test_contract} = artifacts.require("{test_contract}");\n\n'
content += _helpers()
content += f'contract("{test_contract}", accounts => {{\n'
content += f'\tlet owner = "{addresses.owner}";\n'
content += f'\tlet user = "{addresses.user}";\n'
content += f'\tlet attacker = "{addresses.attacker}";\n'
for unit_test in unit_tests:
content += f'\tit("{unit_test.description}", async () => {{\n'
content += f"\t\tlet instance = await {test_contract}.deployed();\n"
callers = _extract_caller(unit_test.caller)
if unit_test.return_type == PropertyReturn.SUCCESS:
for caller in callers:
content += f"\t\tlet test_{caller} = await instance.{unit_test.name[:-2]}.call({{from: {caller}}});\n"
if assert_message:
content += f'\t\tassert.equal(test_{caller}, true, "{assert_message}");\n'
else:
content += f"\t\tassert.equal(test_{caller}, true);\n"
elif unit_test.return_type == PropertyReturn.FAIL:
for caller in callers:
content += f"\t\tlet test_{caller} = await instance.{unit_test.name[:-2]}.call({{from: {caller}}});\n"
if assert_message:
content += f'\t\tassert.equal(test_{caller}, false, "{assert_message}");\n'
else:
content += f"\t\tassert.equal(test_{caller}, false);\n"
elif unit_test.return_type == PropertyReturn.FAIL_OR_THROW:
for caller in callers:
content += f"\t\tawait catchRevertThrowReturnFalse(instance.{unit_test.name[:-2]}.call({{from: {caller}}}));\n"
elif unit_test.return_type == PropertyReturn.THROW:
callers = _extract_caller(unit_test.caller)
for caller in callers:
content += f"\t\tawait catchRevertThrow(instance.{unit_test.name[:-2]}.call({{from: {caller}}}));\n"
content += "\t});\n"
content += "});\n"
output_dir = Path(output_dir, "test")
output_dir.mkdir(exist_ok=True)
output_dir = Path(output_dir, "crytic")
output_dir.mkdir(exist_ok=True)
write_file(output_dir, filename, content)
return output_dir
def generate_migration(test_contract: str, output_dir: Path, owner_address: str) -> None:
"""
Generate migration file
:param test_contract:
:param output_dir:
:param owner_address:
:return:
"""
content = f"""{test_contract} = artifacts.require("{test_contract}");
module.exports = function(deployer) {{
deployer.deploy({test_contract}, {{from: "{owner_address}"}});
}};
"""
output_dir = Path(output_dir, "migrations")
output_dir.mkdir(exist_ok=True)
migration_files = [
js_file
for js_file in output_dir.iterdir()
if js_file.suffix == ".js" and PATTERN_TRUFFLE_MIGRATION.match(js_file.name)
]
idx = len(migration_files)
filename = f"{idx + 1}_{test_contract}.js"
potential_previous_filename = f"{idx}_{test_contract}.js"
for m in migration_files:
if m.name == potential_previous_filename:
write_file(output_dir, potential_previous_filename, content)
return
if test_contract in m.name:
logger.error(f"Potential conflicts with {m.name}")
write_file(output_dir, filename, content)
| 5,766 | Python | .py | 148 | 31.756757 | 127 | 0.622095 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,038 | __main__.py | NioTheFirst_ScType/slither/tools/slither_format/__main__.py | import sys
import argparse
import logging
from crytic_compile import cryticparser
from slither import Slither
from slither.utils.command_line import read_config_file
from slither.tools.slither_format.slither_format import slither_format
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
# Slither detectors for which slither-format currently works
available_detectors = [
"unused-state",
"solc-version",
"pragma",
"naming-convention",
"external-function",
"constable-states",
"constant-function-asm",
"constatnt-function-state",
]
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(description="slither_format", usage="slither_format filename")
parser.add_argument(
"filename", help="The filename of the contract or truffle directory to analyze."
)
parser.add_argument(
"--verbose-test",
"-v",
help="verbose mode output for testing",
action="store_true",
default=False,
)
parser.add_argument(
"--verbose-json",
"-j",
help="verbose json output",
action="store_true",
default=False,
)
parser.add_argument(
"--version",
help="displays the current version",
version="0.1.0",
action="version",
)
parser.add_argument(
"--config-file",
help="Provide a config file (default: slither.config.json)",
action="store",
dest="config_file",
default="slither.config.json",
)
group_detector = parser.add_argument_group("Detectors")
group_detector.add_argument(
"--detect",
help="Comma-separated list of detectors, defaults to all, "
f"available detectors: {', '.join(d for d in available_detectors)}",
action="store",
dest="detectors_to_run",
default="all",
)
group_detector.add_argument(
"--exclude",
help="Comma-separated list of detectors to exclude,"
"available detectors: {', '.join(d for d in available_detectors)}",
action="store",
dest="detectors_to_exclude",
default="all",
)
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
def main() -> None:
# ------------------------------
# Usage: python3 -m slither_format filename
# Example: python3 -m slither_format contract.sol
# ------------------------------
# Parse all arguments
args = parse_args()
read_config_file(args)
# Perform slither analysis on the given filename
slither = Slither(args.filename, **vars(args))
# Format the input files based on slither analysis
slither_format(slither, **vars(args))
if __name__ == "__main__":
main()
| 2,975 | Python | .py | 92 | 26.304348 | 99 | 0.636173 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,039 | slither_format.py | NioTheFirst_ScType/slither/tools/slither_format/slither_format.py | import logging
from pathlib import Path
from typing import Type, List, Dict
from slither import Slither
from slither.detectors.abstract_detector import AbstractDetector
from slither.detectors.variables.unused_state_variables import UnusedStateVars
from slither.detectors.attributes.incorrect_solc import IncorrectSolc
from slither.detectors.attributes.constant_pragma import ConstantPragma
from slither.detectors.naming_convention.naming_convention import NamingConvention
from slither.detectors.functions.external_function import ExternalFunction
from slither.detectors.variables.could_be_constant import CouldBeConstant
from slither.detectors.variables.could_be_immutable import CouldBeImmutable
from slither.detectors.attributes.const_functions_asm import ConstantFunctionsAsm
from slither.detectors.attributes.const_functions_state import ConstantFunctionsState
from slither.utils.colors import yellow
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("Slither.Format")
all_detectors: Dict[str, Type[AbstractDetector]] = {
"unused-state": UnusedStateVars,
"solc-version": IncorrectSolc,
"pragma": ConstantPragma,
"naming-convention": NamingConvention,
"external-function": ExternalFunction,
"constable-states": CouldBeConstant,
"immutable-states": CouldBeImmutable,
"constant-function-asm": ConstantFunctionsAsm,
"constant-functions-state": ConstantFunctionsState,
}
def slither_format(slither: Slither, **kwargs: Dict) -> None: # pylint: disable=too-many-locals
"""'
Keyword Args:
detectors_to_run (str): Comma-separated list of detectors, defaults to all
"""
detectors_to_run = choose_detectors(
kwargs.get("detectors_to_run", "all"), kwargs.get("detectors_to_exclude", "")
)
for detector in detectors_to_run:
slither.register_detector(detector)
slither.generate_patches = True
detector_results = slither.run_detectors()
detector_results = [x for x in detector_results if x] # remove empty results
detector_results = [item for sublist in detector_results for item in sublist] # flatten
export = Path("crytic-export", "patches")
export.mkdir(parents=True, exist_ok=True)
counter_result = 0
logger.info(yellow("slither-format is in beta, carefully review each patch before merging it."))
for result in detector_results:
if not "patches" in result:
continue
one_line_description = result["description"].split("\n")[0]
export_result = Path(export, f"{counter_result}")
export_result.mkdir(parents=True, exist_ok=True)
counter_result += 1
counter = 0
logger.info(f"Issue: {one_line_description}")
logger.info(f"Generated: ({export_result})")
for (
_,
diff,
) in result["patches_diff"].items():
filename = f"fix_{counter}.patch"
path = Path(export_result, filename)
logger.info(f"\t- {filename}")
with open(path, "w", encoding="utf8") as f:
f.write(diff)
counter += 1
# endregion
###################################################################################
###################################################################################
# region Detectors
###################################################################################
###################################################################################
def choose_detectors(
detectors_to_run: str, detectors_to_exclude: str
) -> List[Type[AbstractDetector]]:
# If detectors are specified, run only these ones
cls_detectors_to_run: List[Type[AbstractDetector]] = []
exclude = detectors_to_exclude.split(",")
if detectors_to_run == "all":
for key, detector in all_detectors.items():
if key in exclude:
continue
cls_detectors_to_run.append(detector)
else:
exclude = detectors_to_exclude.split(",")
for d in detectors_to_run.split(","):
if d in all_detectors:
if d in exclude:
continue
cls_detectors_to_run.append(all_detectors[d])
else:
raise Exception(f"Error: {d} is not a detector")
return cls_detectors_to_run
# endregion
###################################################################################
###################################################################################
# region Debug functions
###################################################################################
###################################################################################
def print_patches(number_of_slither_results: int, patches: Dict) -> None:
logger.info("Number of Slither results: " + str(number_of_slither_results))
number_of_patches = 0
for file in patches:
number_of_patches += len(patches[file])
logger.info("Number of patches: " + str(number_of_patches))
for file in patches:
logger.info("Patch file: " + file)
for patch in patches[file]:
logger.info("Detector: " + patch["detector"])
logger.info("Old string: " + patch["old_string"].replace("\n", ""))
logger.info("New string: " + patch["new_string"].replace("\n", ""))
logger.info("Location start: " + str(patch["start"]))
logger.info("Location end: " + str(patch["end"]))
def print_patches_json(number_of_slither_results: int, patches: Dict) -> None:
print("{", end="")
print('"Number of Slither results":' + '"' + str(number_of_slither_results) + '",')
print('"Number of patchlets":' + '"' + str(len(patches)) + '"', ",")
print('"Patchlets":' + "[")
for index, file in enumerate(patches):
if index > 0:
print(",")
print("{", end="")
print('"Patch file":' + '"' + file + '",')
print('"Number of patches":' + '"' + str(len(patches[file])) + '"', ",")
print('"Patches":' + "[")
for inner_index, patch in enumerate(patches[file]):
if inner_index > 0:
print(",")
print("{", end="")
print('"Detector":' + '"' + patch["detector"] + '",')
print('"Old string":' + '"' + patch["old_string"].replace("\n", "") + '",')
print('"New string":' + '"' + patch["new_string"].replace("\n", "") + '",')
print('"Location start":' + '"' + str(patch["start"]) + '",')
print('"Location end":' + '"' + str(patch["end"]) + '"')
if "overlaps" in patch:
print('"Overlaps":' + "Yes")
print("}", end="")
print("]", end="")
print("}", end="")
print("]", end="")
print("}")
| 6,791 | Python | .py | 141 | 40.985816 | 100 | 0.571795 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,040 | __main__.py | NioTheFirst_ScType/slither/tools/demo/__main__.py | import argparse
import logging
from crytic_compile import cryticparser
from slither import Slither
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
logger = logging.getLogger("Slither-demo")
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(description="Demo", usage="slither-demo filename")
parser.add_argument(
"filename", help="The filename of the contract or truffle directory to analyze."
)
# Add default arguments from crytic-compile
cryticparser.init(parser)
return parser.parse_args()
def main() -> None:
args = parse_args()
# Perform slither analysis on the given filename
_slither = Slither(args.filename, **vars(args))
logger.info("Analysis done!")
if __name__ == "__main__":
main()
| 927 | Python | .py | 26 | 31.538462 | 88 | 0.727477 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,041 | __main__.py | NioTheFirst_ScType/slither/tools/erc_conformance/__main__.py | import argparse
import logging
from collections import defaultdict
from typing import Any, Dict, List
from crytic_compile import cryticparser
from slither import Slither
from slither.utils.erc import ERCS
from slither.utils.output import output_to_json
from .erc.ercs import generic_erc_checks
from .erc.erc20 import check_erc20
from .erc.erc1155 import check_erc1155
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
logger = logging.getLogger("Slither-conformance")
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
logger.addHandler(ch)
logger.handlers[0].setFormatter(formatter)
logger.propagate = False
ADDITIONAL_CHECKS = {"ERC20": check_erc20, "ERC1155": check_erc1155}
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(
description="Check the ERC 20 conformance",
usage="slither-check-erc project contractName",
)
parser.add_argument("project", help="The codebase to be tested.")
parser.add_argument(
"contract_name",
help="The name of the contract. Specify the first case contract that follow the standard. Derived contracts will be checked.",
)
parser.add_argument(
"--erc",
help=f"ERC to be tested, available {','.join(ERCS.keys())} (default ERC20)",
action="store",
default="erc20",
)
parser.add_argument(
"--json",
help='Export the results as a JSON file ("--json -" to export to stdout)',
action="store",
default=False,
)
# Add default arguments from crytic-compile
cryticparser.init(parser)
return parser.parse_args()
def _log_error(err: Any, args: argparse.Namespace) -> None:
if args.json:
output_to_json(args.json, str(err), {"upgradeability-check": []})
logger.error(err)
def main() -> None:
args = parse_args()
# Perform slither analysis on the given filename
slither = Slither(args.project, **vars(args))
ret: Dict[str, List] = defaultdict(list)
if args.erc.upper() in ERCS:
contracts = slither.get_contract_from_name(args.contract_name)
if len(contracts) != 1:
err = f"Contract not found: {args.contract_name}"
_log_error(err, args)
return
contract = contracts[0]
# First elem is the function, second is the event
erc = ERCS[args.erc.upper()]
generic_erc_checks(contract, erc[0], erc[1], ret)
if args.erc.upper() in ADDITIONAL_CHECKS:
ADDITIONAL_CHECKS[args.erc.upper()](contract, ret)
else:
err = f"Incorrect ERC selected {args.erc}"
_log_error(err, args)
return
if args.json:
output_to_json(args.json, None, {"upgradeability-check": ret})
if __name__ == "__main__":
main()
| 3,000 | Python | .py | 80 | 31.85 | 134 | 0.682918 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,042 | ercs.py | NioTheFirst_ScType/slither/tools/erc_conformance/erc/ercs.py | import logging
from typing import Dict, List, Optional, Set
from slither.core.declarations import Contract
from slither.slithir.operations import EventCall
from slither.utils import output
from slither.utils.erc import ERC, ERC_EVENT
from slither.utils.type import (
export_nested_types_from_variable,
export_return_type_from_variable,
)
logger = logging.getLogger("Slither-conformance")
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def _check_signature(erc_function: ERC, contract: Contract, ret: Dict) -> None:
name = erc_function.name
parameters = erc_function.parameters
return_type = erc_function.return_type
view = erc_function.view
required = erc_function.required
events = erc_function.events
sig = f'{name}({",".join(parameters)})'
function = contract.get_function_from_signature(sig)
if not function:
# The check on state variable is needed until we have a better API to handle state variable getters
state_variable_as_function = contract.get_state_variable_from_name(name)
if not state_variable_as_function or not state_variable_as_function.visibility in [
"public",
"external",
]:
txt = f'[ ] {sig} is missing {"" if required else "(optional)"}'
logger.info(txt)
missing_func = output.Output(
txt, additional_fields={"function": sig, "required": required}
)
missing_func.add(contract)
ret["missing_function"].append(missing_func.data)
return
types = [str(x) for x in export_nested_types_from_variable(state_variable_as_function)]
if types != parameters:
txt = f'[ ] {sig} is missing {"" if required else "(optional)"}'
logger.info(txt)
missing_func = output.Output(
txt, additional_fields={"function": sig, "required": required}
)
missing_func.add(contract)
ret["missing_function"].append(missing_func.data)
return
function_return_type = export_return_type_from_variable(state_variable_as_function)
function = state_variable_as_function
function_view = True
else:
function_return_type = function.return_type # pylint: disable=no-member
function_view = function.view # pylint: disable=no-member
txt = f"[✓] {sig} is present"
logger.info(txt)
if function_return_type:
function_return_type = ",".join([str(x) for x in function_return_type])
if function_return_type == return_type:
txt = f"\t[✓] {sig} -> ({function_return_type}) (correct return type)"
logger.info(txt)
else:
txt = f"\t[ ] {sig} -> ({function_return_type}) should return {return_type}"
logger.info(txt)
incorrect_return = output.Output(
txt,
additional_fields={
"expected_return_type": return_type,
"actual_return_type": function_return_type,
},
)
incorrect_return.add(function)
ret["incorrect_return_type"].append(incorrect_return.data)
elif not return_type:
txt = f"\t[✓] {sig} -> () (correct return type)"
logger.info(txt)
else:
txt = f"\t[ ] {sig} -> () should return {return_type}"
logger.info(txt)
incorrect_return = output.Output(
txt,
additional_fields={
"expected_return_type": return_type,
"actual_return_type": function_return_type,
},
)
incorrect_return.add(function)
ret["incorrect_return_type"].append(incorrect_return.data)
if view:
if function_view:
txt = f"\t[✓] {sig} is view"
logger.info(txt)
else:
txt = f"\t[ ] {sig} should be view"
logger.info(txt)
should_be_view = output.Output(txt)
should_be_view.add(function)
ret["should_be_view"].append(should_be_view.data)
if events: # pylint: disable=too-many-nested-blocks
for event in events:
event_sig = f'{event.name}({",".join(event.parameters)})'
if not function:
txt = f"\t[ ] Must emit be view {event_sig}"
logger.info(txt)
missing_event_emmited = output.Output(
txt, additional_fields={"missing_event": event_sig}
)
missing_event_emmited.add(function)
ret["missing_event_emmited"].append(missing_event_emmited.data)
else:
event_found = False
for ir in function.all_slithir_operations():
if isinstance(ir, EventCall):
if ir.name == event.name:
if event.parameters == [str(a.type) for a in ir.arguments]:
event_found = True
break
if event_found:
txt = f"\t[✓] {event_sig} is emitted"
logger.info(txt)
else:
txt = f"\t[ ] Must emit be view {event_sig}"
logger.info(txt)
missing_event_emmited = output.Output(
txt, additional_fields={"missing_event": event_sig}
)
missing_event_emmited.add(function)
ret["missing_event_emmited"].append(missing_event_emmited.data)
def _check_events(erc_event: ERC_EVENT, contract: Contract, ret: Dict[str, List]) -> None:
name = erc_event.name
parameters = erc_event.parameters
indexes = erc_event.indexes
sig = f'{name}({",".join(parameters)})'
event = contract.get_event_from_signature(sig)
if not event:
txt = f"[ ] {sig} is missing"
logger.info(txt)
missing_event = output.Output(txt, additional_fields={"event": sig})
missing_event.add(contract)
ret["missing_event"].append(missing_event.data)
return
txt = f"[✓] {sig} is present"
logger.info(txt)
for i, index in enumerate(indexes):
if index:
if event.elems[i].indexed:
txt = f"\t[✓] parameter {i} is indexed"
logger.info(txt)
else:
txt = f"\t[ ] parameter {i} should be indexed"
logger.info(txt)
missing_event_index = output.Output(txt, additional_fields={"missing_index": i})
missing_event_index.add_event(event)
ret["missing_event_index"].append(missing_event_index.data)
def generic_erc_checks(
contract: Contract,
erc_functions: List[ERC],
erc_events: List[ERC_EVENT],
ret: Dict[str, List],
explored: Optional[Set[Contract]] = None,
) -> None:
if explored is None:
explored = set()
explored.add(contract)
logger.info(f"# Check {contract.name}\n")
logger.info("## Check functions")
for erc_function in erc_functions:
_check_signature(erc_function, contract, ret)
if erc_events:
logger.info("\n## Check events")
for erc_event in erc_events:
_check_events(erc_event, contract, ret)
logger.info("\n")
for derived_contract in contract.derived_contracts:
generic_erc_checks(derived_contract, erc_functions, erc_events, ret, explored)
| 7,555 | Python | .py | 173 | 32.50289 | 107 | 0.58455 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,043 | erc20.py | NioTheFirst_ScType/slither/tools/erc_conformance/erc/erc20.py | import logging
from slither.utils import output
logger = logging.getLogger("Slither-conformance")
def approval_race_condition(contract, ret):
increaseAllowance = contract.get_function_from_signature("increaseAllowance(address,uint256)")
if not increaseAllowance:
increaseAllowance = contract.get_function_from_signature(
"safeIncreaseAllowance(address,uint256)"
)
if increaseAllowance:
txt = f"\t[✓] {contract.name} has {increaseAllowance.full_name}"
logger.info(txt)
else:
txt = f"\t[ ] {contract.name} is not protected for the ERC20 approval race condition"
logger.info(txt)
lack_of_erc20_race_condition_protection = output.Output(txt)
lack_of_erc20_race_condition_protection.add(contract)
ret["lack_of_erc20_race_condition_protection"].append(
lack_of_erc20_race_condition_protection.data
)
def check_erc20(contract, ret, explored=None):
if explored is None:
explored = set()
explored.add(contract)
approval_race_condition(contract, ret)
for derived_contract in contract.derived_contracts:
check_erc20(derived_contract, ret, explored)
return ret
| 1,220 | Python | .py | 28 | 36.535714 | 98 | 0.71162 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,044 | erc1155.py | NioTheFirst_ScType/slither/tools/erc_conformance/erc/erc1155.py | import logging
from slither.slithir.operations import EventCall
from slither.utils import output
logger = logging.getLogger("Slither-conformance")
def events_safeBatchTransferFrom(contract, ret):
function = contract.get_function_from_signature(
"safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)"
)
events = [
{
"name": "TransferSingle",
"parameters": ["address", "address", "address", "uint256", "uint256"],
},
{
"name": "TransferBatch",
"parameters": ["address", "address", "address", "uint256[]", "uint256[]"],
},
]
event_counter_name = 0
event_counter_parameters = 0
if function:
for event in events:
for ir in function.all_slithir_operations():
if isinstance(ir, EventCall) and ir.name == event["name"]:
event_counter_name += 1
if event["parameters"] == [str(a.type) for a in ir.arguments]:
event_counter_parameters += 1
if event_counter_parameters == 1 and event_counter_name == 1:
txt = "[✓] safeBatchTransferFrom emit TransferSingle or TransferBatch"
logger.info(txt)
else:
txt = "[ ] safeBatchTransferFrom must emit TransferSingle or TransferBatch"
logger.info(txt)
erroneous_erc1155_safeBatchTransferFrom_event = output.Output(txt)
erroneous_erc1155_safeBatchTransferFrom_event.add(contract)
ret["erroneous_erc1155_safeBatchTransferFrom_event"].append(
erroneous_erc1155_safeBatchTransferFrom_event.data
)
def check_erc1155(contract, ret, explored=None):
if explored is None:
explored = set()
explored.add(contract)
events_safeBatchTransferFrom(contract, ret)
for derived_contract in contract.derived_contracts:
check_erc1155(derived_contract, ret, explored)
return ret
| 1,945 | Python | .py | 46 | 33.717391 | 86 | 0.651298 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,045 | analysis.py | NioTheFirst_ScType/slither/tools/kspec_coverage/analysis.py | import re
import logging
from typing import Set, Tuple
from slither.core.declarations import Function
from slither.core.variables.variable import Variable
from slither.utils.colors import yellow, green, red
from slither.utils import output
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger("Slither.kspec")
# pylint: disable=anomalous-backslash-in-string
def _refactor_type(targeted_type: str) -> str:
return {"uint": "uint256", "int": "int256"}.get(targeted_type, targeted_type)
def _get_all_covered_kspec_functions(target: str) -> Set[Tuple[str, str]]:
# Create a set of our discovered functions which are covered
covered_functions: Set[Tuple[str, str]] = set()
BEHAVIOUR_PATTERN = re.compile(r"behaviour\s+(\S+)\s+of\s+(\S+)")
INTERFACE_PATTERN = re.compile(r"interface\s+([^\r\n]+)")
# Read the file contents
with open(target, "r", encoding="utf8") as target_file:
lines = target_file.readlines()
# Loop for each line, if a line matches our behaviour regex, and the next one matches our interface regex,
# we add our finding
i = 0
while i < len(lines):
match = BEHAVIOUR_PATTERN.match(lines[i])
if match:
contract_name = match.groups()[1]
match = INTERFACE_PATTERN.match(lines[i + 1])
if match:
function_full_name = match.groups()[0]
start, end = (
function_full_name.index("(") + 1,
function_full_name.index(")"),
)
function_arguments = function_full_name[start:end].split(",")
function_arguments = [
_refactor_type(arg.strip().split(" ")[0]) for arg in function_arguments
]
function_full_name = function_full_name[:start] + ",".join(function_arguments) + ")"
covered_functions.add((contract_name, function_full_name))
i += 1
i += 1
return covered_functions
def _get_slither_functions(slither):
# Use contract == contract_declarer to avoid dupplicate
all_functions_declared = [
f
for f in slither.functions
if (
f.contract == f.contract_declarer
and f.is_implemented
and not f.is_constructor
and not f.is_constructor_variables
)
]
# Use list(set()) because same state variable instances can be shared accross contracts
# TODO: integrate state variables
all_functions_declared += list(
{s for s in slither.state_variables if s.visibility in ["public", "external"]}
)
slither_functions = {
(function.contract.name, function.full_name): function
for function in all_functions_declared
}
return slither_functions
def _generate_output(kspec, message, color, generate_json):
info = ""
for function in kspec:
info += f"{message} {function.contract.name}.{function.full_name}\n"
if info:
logger.info(color(info))
if generate_json:
json_kspec_present = output.Output(info)
for function in kspec:
json_kspec_present.add(function)
return json_kspec_present.data
return None
def _generate_output_unresolved(kspec, message, color, generate_json):
info = ""
for contract, function in kspec:
info += f"{message} {contract}.{function}\n"
if info:
logger.info(color(info))
if generate_json:
json_kspec_present = output.Output(info, additional_fields={"signatures": kspec})
return json_kspec_present.data
return None
def _run_coverage_analysis(args, slither, kspec_functions):
# Collect all slither functions
slither_functions = _get_slither_functions(slither)
# Determine which klab specs were not resolved.
slither_functions_set = set(slither_functions)
kspec_functions_resolved = kspec_functions & slither_functions_set
kspec_functions_unresolved = kspec_functions - kspec_functions_resolved
kspec_missing = []
kspec_present = []
for slither_func_desc in sorted(slither_functions_set):
slither_func = slither_functions[slither_func_desc]
if slither_func_desc in kspec_functions:
kspec_present.append(slither_func)
else:
kspec_missing.append(slither_func)
logger.info("## Check for functions coverage")
json_kspec_present = _generate_output(kspec_present, "[✓]", green, args.json)
json_kspec_missing_functions = _generate_output(
[f for f in kspec_missing if isinstance(f, Function)],
"[ ] (Missing function)",
red,
args.json,
)
json_kspec_missing_variables = _generate_output(
[f for f in kspec_missing if isinstance(f, Variable)],
"[ ] (Missing variable)",
yellow,
args.json,
)
json_kspec_unresolved = _generate_output_unresolved(
kspec_functions_unresolved, "[ ] (Unresolved)", yellow, args.json
)
# Handle unresolved kspecs
if args.json:
output.output_to_json(
args.json,
None,
{
"functions_present": json_kspec_present,
"functions_missing": json_kspec_missing_functions,
"variables_missing": json_kspec_missing_variables,
"functions_unresolved": json_kspec_unresolved,
},
)
def run_analysis(args, slither, kspec_arg):
# Get all of our kspec'd functions (tuple(contract_name, function_name)).
if "," in kspec_arg:
kspecs = kspec_arg.split(",")
kspec_functions = set()
for kspec in kspecs:
kspec_functions |= _get_all_covered_kspec_functions(kspec)
else:
kspec_functions = _get_all_covered_kspec_functions(kspec_arg)
# Run coverage analysis
_run_coverage_analysis(args, slither, kspec_functions)
| 6,090 | Python | .py | 142 | 33.577465 | 111 | 0.628101 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,046 | __main__.py | NioTheFirst_ScType/slither/tools/kspec_coverage/__main__.py | import sys
import logging
import argparse
from crytic_compile import cryticparser
from slither.tools.kspec_coverage.kspec_coverage import kspec_coverage
logging.basicConfig()
logger = logging.getLogger("Slither.kspec")
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
logger.addHandler(ch)
logger.handlers[0].setFormatter(formatter)
logger.propagate = False
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(
description="slither-kspec-coverage",
usage="slither-kspec-coverage contract.sol kspec.md",
)
parser.add_argument(
"contract", help="The filename of the contract or truffle directory to analyze."
)
parser.add_argument(
"kspec",
help="The filename of the Klab spec markdown for the analyzed contract(s)",
)
parser.add_argument(
"--version",
help="displays the current version",
version="0.1.0",
action="version",
)
parser.add_argument(
"--json",
help='Export the results as a JSON file ("--json -" to export to stdout)',
action="store",
default=False,
)
cryticparser.init(parser)
if len(sys.argv) < 2:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
def main() -> None:
# ------------------------------
# Usage: slither-kspec-coverage contract kspec
# Example: slither-kspec-coverage contract.sol kspec.md
# ------------------------------
# Parse all arguments
args = parse_args()
kspec_coverage(args)
if __name__ == "__main__":
main()
| 1,820 | Python | .py | 57 | 26.807018 | 88 | 0.65389 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,047 | kspec_coverage.py | NioTheFirst_ScType/slither/tools/kspec_coverage/kspec_coverage.py | import argparse
from slither.tools.kspec_coverage.analysis import run_analysis
from slither import Slither
def kspec_coverage(args: argparse.Namespace) -> None:
contract = args.contract
kspec = args.kspec
slither = Slither(contract, **vars(args))
compilation_units = slither.compilation_units
if len(compilation_units) != 1:
print("Only single compilation unit supported")
return
# Run the analysis on the Klab specs
run_analysis(args, compilation_units[0], kspec)
| 534 | Python | .py | 13 | 34.769231 | 63 | 0.722986 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,048 | __main__.py | NioTheFirst_ScType/slither/tools/similarity/__main__.py | #!/usr/bin/env python3
import argparse
import logging
import sys
from crytic_compile import cryticparser
from slither.tools.similarity.info import info
from slither.tools.similarity.test import test
from slither.tools.similarity.train import train
from slither.tools.similarity.plot import plot
logging.basicConfig()
logger = logging.getLogger("Slither-simil")
modes = ["info", "test", "train", "plot"]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Code similarity detection tool. For usage, see https://github.com/crytic/slither/wiki/Code-Similarity-detector"
)
parser.add_argument("mode", help="|".join(modes))
parser.add_argument("model", help="model.bin")
parser.add_argument("--filename", action="store", dest="filename", help="contract.sol")
parser.add_argument("--fname", action="store", dest="fname", help="Target function")
parser.add_argument("--ext", action="store", dest="ext", help="Extension to filter contracts")
parser.add_argument(
"--nsamples",
action="store",
type=int,
dest="nsamples",
help="Number of contract samples used for training",
)
parser.add_argument(
"--ntop",
action="store",
type=int,
dest="ntop",
default=10,
help="Number of more similar contracts to show for testing",
)
parser.add_argument(
"--input", action="store", dest="input", help="File or directory used as input"
)
parser.add_argument(
"--version",
help="displays the current version",
version="0.0",
action="version",
)
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args()
return args
# endregion
###################################################################################
###################################################################################
# region Main
###################################################################################
###################################################################################
def main() -> None:
args = parse_args()
default_log = logging.INFO
logger.setLevel(default_log)
mode = args.mode
if mode == "info":
info(args)
elif mode == "train":
train(args)
elif mode == "test":
test(args)
elif mode == "plot":
plot(args)
else:
to_log = f"Invalid mode!. It should be one of these: {', '.join(modes)}"
logger.error(to_log)
sys.exit(-1)
if __name__ == "__main__":
main()
# endregion
| 2,701 | Python | .py | 77 | 29.493506 | 132 | 0.563391 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,049 | test.py | NioTheFirst_ScType/slither/tools/similarity/test.py | import logging
import operator
import sys
import traceback
from slither.tools.similarity.encode import encode_contract, load_and_encode, parse_target
from slither.tools.similarity.model import load_model
from slither.tools.similarity.similarity import similarity
logger = logging.getLogger("Slither-simil")
def test(args):
try:
model = args.model
model = load_model(model)
filename = args.filename
contract, fname = parse_target(args.fname)
infile = args.input
ntop = args.ntop
if filename is None or contract is None or fname is None or infile is None:
logger.error("The test mode requires filename, contract, fname and input parameters.")
sys.exit(-1)
irs = encode_contract(filename, **vars(args))
if len(irs) == 0:
sys.exit(-1)
y = " ".join(irs[(filename, contract, fname)])
fvector = model.get_sentence_vector(y)
cache = load_and_encode(infile, model, **vars(args))
# save_cache("cache.npz", cache)
r = {}
for x, y in cache.items():
r[x] = similarity(fvector, y)
r = sorted(r.items(), key=operator.itemgetter(1), reverse=True)
logger.info("Reviewed %d functions, listing the %d most similar ones:", len(r), ntop)
format_table = "{: <65} {: <20} {: <20} {: <10}"
logger.info(format_table.format(*["filename", "contract", "function", "score"]))
for x, score in r[:ntop]:
score = str(round(score, 3))
logger.info(format_table.format(*(list(x) + [score])))
except Exception: # pylint: disable=broad-except
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)
| 1,775 | Python | .py | 40 | 36.475 | 98 | 0.632618 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,050 | similarity.py | NioTheFirst_ScType/slither/tools/similarity/similarity.py | import sys
try:
import numpy as np
except ImportError:
print("ERROR: in order to use slither-simil, you need to install numpy:")
print("$ pip3 install numpy --user\n")
sys.exit(-1)
def similarity(v1, v2):
n1 = np.linalg.norm(v1)
n2 = np.linalg.norm(v2)
return np.dot(v1, v2) / n1 / n2
| 316 | Python | .py | 11 | 24.909091 | 77 | 0.665563 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,051 | cache.py | NioTheFirst_ScType/slither/tools/similarity/cache.py | import sys
try:
import numpy as np
except ImportError:
print("ERROR: in order to use slither-simil, you need to install numpy")
print("$ pip3 install numpy --user\n")
sys.exit(-1)
def load_cache(infile, nsamples=None):
cache = {}
with np.load(infile, allow_pickle=True) as data:
array = data["arr_0"][0]
for i, (x, y) in enumerate(array):
cache[x] = y
if i == nsamples:
break
return cache
def save_cache(cache, outfile):
np.savez(outfile, [np.array(cache)])
| 552 | Python | .py | 18 | 24.444444 | 76 | 0.61553 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,052 | train.py | NioTheFirst_ScType/slither/tools/similarity/train.py | import argparse
import logging
import os
import sys
import traceback
from slither.tools.similarity.cache import save_cache
from slither.tools.similarity.encode import encode_contract, load_contracts
from slither.tools.similarity.model import train_unsupervised
logger = logging.getLogger("Slither-simil")
def train(args: argparse.Namespace) -> None: # pylint: disable=too-many-locals
try:
last_data_train_filename = "last_data_train.txt"
model_filename = args.model
dirname = args.input
if dirname is None:
logger.error("The train mode requires the input parameter.")
sys.exit(-1)
contracts = load_contracts(dirname, **vars(args))
logger.info("Saving extracted data into %s", last_data_train_filename)
cache = []
with open(last_data_train_filename, "w", encoding="utf8") as f:
for filename in contracts:
# cache[filename] = dict()
for (filename_inner, contract, function), ir in encode_contract(
filename, **vars(args)
).items():
if ir != []:
x = " ".join(ir)
f.write(x + "\n")
cache.append((os.path.split(filename_inner)[-1], contract, function, x))
logger.info("Starting training")
model = train_unsupervised(input=last_data_train_filename, model="skipgram")
logger.info("Training complete")
logger.info("Saving model")
model.save_model(model_filename)
for i, (filename, contract, function, irs) in enumerate(cache):
cache[i] = ((filename, contract, function), model.get_sentence_vector(irs))
logger.info("Saving cache in cache.npz")
save_cache(cache, "cache.npz")
logger.info("Done!")
except Exception: # pylint: disable=broad-except
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)
| 2,018 | Python | .py | 44 | 36.068182 | 96 | 0.625064 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,053 | plot.py | NioTheFirst_ScType/slither/tools/similarity/plot.py | import argparse
import logging
import random
import sys
import traceback
try:
import numpy as np
except ImportError:
print("ERROR: in order to use slither-simil, you need to install numpy:")
print("$ pip3 install numpy --user\n")
sys.exit(-1)
from slither.tools.similarity.encode import load_and_encode, parse_target
from slither.tools.similarity.model import load_model
try:
from sklearn import decomposition
import matplotlib.pyplot as plt
except ImportError:
decomposition = None
plt = None
logger = logging.getLogger("Slither-simil")
def plot(args: argparse.Namespace) -> None: # pylint: disable=too-many-locals
if decomposition is None or plt is None:
logger.error(
"ERROR: In order to use plot mode in slither-simil, you need to install sklearn and matplotlib:"
)
logger.error("$ pip3 install sklearn matplotlib --user")
sys.exit(-1)
try:
model = args.model
model = load_model(model)
# contract = args.contract
contract, fname = parse_target(args.fname)
# solc = args.solc
infile = args.input
# ext = args.filter
# nsamples = args.nsamples
if fname is None or infile is None:
logger.error("The plot mode requieres fname and input parameters.")
sys.exit(-1)
logger.info("Loading data..")
cache = load_and_encode(infile, **vars(args))
data = []
fs = []
logger.info("Procesing data..")
for (f, c, n), y in cache.items():
if (c == contract or contract is None) and n == fname:
fs.append(f)
data.append(y)
if len(data) == 0:
logger.error("No contract was found with function %s", fname)
sys.exit(-1)
data = np.array(data)
pca = decomposition.PCA(n_components=2)
tdata = pca.fit_transform(data)
logger.info("Plotting data..")
plt.figure(figsize=(20, 10))
assert len(tdata) == len(fs)
for ([x, y], l) in zip(tdata, fs):
x = random.gauss(0, 0.01) + x
y = random.gauss(0, 0.01) + y
plt.scatter(x, y, c="blue")
plt.text(x - 0.001, y + 0.001, l)
logger.info("Saving figure to plot.png..")
plt.savefig("plot.png", bbox_inches="tight")
except Exception: # pylint: disable=broad-except
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)
| 2,542 | Python | .py | 68 | 29.470588 | 108 | 0.612785 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,054 | encode.py | NioTheFirst_ScType/slither/tools/similarity/encode.py | import logging
import os
from slither import Slither
from slither.core.declarations import (
Structure,
Enum,
SolidityVariableComposed,
SolidityVariable,
Function,
)
from slither.core.solidity_types import (
ElementaryType,
ArrayType,
MappingType,
UserDefinedType,
)
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.local_variable_init_from_tuple import LocalVariableInitFromTuple
from slither.core.variables.state_variable import StateVariable
from slither.slithir.operations import (
Assignment,
Index,
Member,
Length,
Binary,
Unary,
Condition,
NewArray,
NewStructure,
NewContract,
NewElementaryType,
SolidityCall,
Delete,
EventCall,
LibraryCall,
InternalDynamicCall,
HighLevelCall,
LowLevelCall,
TypeConversion,
Return,
Transfer,
Send,
Unpack,
InitArray,
InternalCall,
)
from slither.slithir.variables import (
TemporaryVariable,
TupleVariable,
Constant,
ReferenceVariable,
)
from .cache import load_cache
simil_logger = logging.getLogger("Slither-simil")
compiler_logger = logging.getLogger("CryticCompile")
compiler_logger.setLevel(logging.CRITICAL)
slither_logger = logging.getLogger("Slither")
slither_logger.setLevel(logging.CRITICAL)
def parse_target(target):
if target is None:
return None, None
parts = target.split(".")
if len(parts) == 1:
return None, parts[0]
if len(parts) == 2:
return parts
simil_logger.error("Invalid target. It should be 'function' or 'Contract.function'")
return None
def load_and_encode(infile: str, vmodel, ext=None, nsamples=None, **kwargs):
r = {}
if infile.endswith(".npz"):
r = load_cache(infile, nsamples=nsamples)
else:
contracts = load_contracts(infile, ext=ext, nsamples=nsamples)
for contract in contracts:
for x, ir in encode_contract(contract, **kwargs).items():
if ir != []:
y = " ".join(ir)
r[x] = vmodel.get_sentence_vector(y)
return r
def load_contracts(dirname, ext=None, nsamples=None):
r = []
walk = list(os.walk(dirname))
for x, y, files in walk:
for f in files:
if ext is None or f.endswith(ext):
r.append(x + "/".join(y) + "/" + f)
if nsamples is None:
return r
# TODO: shuffle
return r[:nsamples]
def ntype(_type): # pylint: disable=too-many-branches
if isinstance(_type, ElementaryType):
_type = str(_type)
elif isinstance(_type, ArrayType):
if isinstance(_type.type, ElementaryType):
_type = str(_type)
else:
_type = "user_defined_array"
elif isinstance(_type, Structure):
_type = str(_type)
elif isinstance(_type, Enum):
_type = str(_type)
elif isinstance(_type, MappingType):
_type = str(_type)
elif isinstance(_type, UserDefinedType):
_type = "user_defined_type" # TODO: this could be Contract, Enum or Struct
else:
_type = str(_type)
_type = _type.replace(" memory", "")
_type = _type.replace(" storage ref", "")
if "struct" in _type:
return "struct"
if "enum" in _type:
return "enum"
if "tuple" in _type:
return "tuple"
if "contract" in _type:
return "contract"
if "mapping" in _type:
return "mapping"
return _type.replace(" ", "_")
def encode_ir(ir): # pylint: disable=too-many-branches
# operations
if isinstance(ir, Assignment):
return f"({encode_ir(ir.lvalue)}):=({encode_ir(ir.rvalue)})"
if isinstance(ir, Index):
return f"index({ntype(ir.index_type)})"
if isinstance(ir, Member):
return "member" # .format(ntype(ir._type))
if isinstance(ir, Length):
return "length"
if isinstance(ir, Binary):
return f"binary({str(ir.type)})"
if isinstance(ir, Unary):
return f"unary({str(ir.type)})"
if isinstance(ir, Condition):
return f"condition({encode_ir(ir.value)})"
if isinstance(ir, NewStructure):
return "new_structure"
if isinstance(ir, NewContract):
return "new_contract"
if isinstance(ir, NewArray):
return f"new_array({ntype(ir.array_type)})"
if isinstance(ir, NewElementaryType):
return f"new_elementary({ntype(ir.type)})"
if isinstance(ir, Delete):
return f"delete({encode_ir(ir.lvalue)},{encode_ir(ir.variable)})"
if isinstance(ir, SolidityCall):
return f"solidity_call({ir.function.full_name})"
if isinstance(ir, InternalCall):
return f"internal_call({ntype(ir.type_call)})"
if isinstance(ir, EventCall): # is this useful?
return "event"
if isinstance(ir, LibraryCall):
return "library_call"
if isinstance(ir, InternalDynamicCall):
return "internal_dynamic_call"
if isinstance(ir, HighLevelCall): # TODO: improve
return "high_level_call"
if isinstance(ir, LowLevelCall): # TODO: improve
return "low_level_call"
if isinstance(ir, TypeConversion):
return f"type_conversion({ntype(ir.type)})"
if isinstance(ir, Return): # this can be improved using values
return "return" # .format(ntype(ir.type))
if isinstance(ir, Transfer):
return f"transfer({encode_ir(ir.call_value)})"
if isinstance(ir, Send):
return f"send({encode_ir(ir.call_value)})"
if isinstance(ir, Unpack): # TODO: improve
return "unpack"
if isinstance(ir, InitArray): # TODO: improve
return "init_array"
if isinstance(ir, Function): # TODO: investigate this
return "function_solc"
# variables
if isinstance(ir, Constant):
return f"constant({ntype(ir.type)})"
if isinstance(ir, SolidityVariableComposed):
return f"solidity_variable_composed({ir.name})"
if isinstance(ir, SolidityVariable):
return f"solidity_variable{ir.name}"
if isinstance(ir, TemporaryVariable):
return "temporary_variable"
if isinstance(ir, ReferenceVariable):
return f"reference({ntype(ir.type)})"
if isinstance(ir, LocalVariable):
return f"local_solc_variable({ir.location})"
if isinstance(ir, StateVariable):
return f"state_solc_variable({ntype(ir.type)})"
if isinstance(ir, LocalVariableInitFromTuple):
return "local_variable_init_tuple"
if isinstance(ir, TupleVariable):
return "tuple_variable"
# default
simil_logger.error(type(ir), "is missing encoding!")
return ""
def encode_contract(cfilename, **kwargs):
r = {}
# Init slither
try:
slither = Slither(cfilename, **kwargs)
except Exception: # pylint: disable=broad-except
simil_logger.error("Compilation failed for %s using %s", cfilename, kwargs["solc"])
return r
# Iterate over all the contracts
for contract in slither.contracts:
# Iterate over all the functions
for function in contract.functions_declared:
if function.nodes == [] or function.is_constructor_variables:
continue
x = (cfilename, contract.name, function.name)
r[x] = []
# Iterate over the nodes of the function
for node in function.nodes:
# Print the Solidity expression of the nodes
# And the SlithIR operations
if node.expression:
for ir in node.irs:
r[x].append(encode_ir(ir))
return r
| 7,643 | Python | .py | 222 | 27.711712 | 92 | 0.64678 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,055 | model.py | NioTheFirst_ScType/slither/tools/similarity/model.py | import sys
try:
# pylint: disable=unused-import
from fastText import load_model
from fastText import train_unsupervised
except ImportError:
print("ERROR: in order to use slither-simil, you need to install fastText 0.2.0:")
print("$ pip3 install https://github.com/facebookresearch/fastText/archive/0.2.0.zip --user\n")
sys.exit(-1)
| 357 | Python | .py | 9 | 35.888889 | 99 | 0.740634 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,056 | info.py | NioTheFirst_ScType/slither/tools/similarity/info.py | import argparse
import logging
import sys
import os.path
import traceback
from .model import load_model
from .encode import parse_target, encode_contract
logging.basicConfig()
logger = logging.getLogger("Slither-simil")
def info(args: argparse.Namespace) -> None:
try:
model = args.model
if os.path.isfile(model):
model = load_model(model)
else:
model = None
filename = args.filename
contract, fname = parse_target(args.fname)
if filename is None and contract is None and fname is None:
logger.info("%s uses the following words:", args.model)
for word in model.get_words():
logger.info(word)
sys.exit(0)
if filename is None or contract is None or fname is None:
logger.error("The encode mode requires filename, contract and fname parameters.")
sys.exit(-1)
irs = encode_contract(filename, **vars(args))
if len(irs) == 0:
sys.exit(-1)
x = (filename, contract, fname)
y = " ".join(irs[x])
to_log = f"Function {fname} in contract {contract} is encoded as:"
logger.info(to_log)
logger.info(y)
if model is not None:
fvector = model.get_sentence_vector(y)
logger.info(fvector)
except Exception: # pylint: disable=broad-except
to_log = f"Error in {args.filename}"
logger.error(to_log)
logger.error(traceback.format_exc())
sys.exit(-1)
| 1,538 | Python | .py | 42 | 28.261905 | 93 | 0.61969 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,057 | __main__.py | NioTheFirst_ScType/slither/tools/flattening/__main__.py | import argparse
import logging
import sys
from crytic_compile import cryticparser
from crytic_compile.utils.zip import ZIP_TYPES_ACCEPTED
from slither import Slither
from slither.tools.flattening.flattening import (
Flattening,
Strategy,
STRATEGIES_NAMES,
DEFAULT_EXPORT_PATH,
)
logging.basicConfig()
logger = logging.getLogger("Slither")
logger.setLevel(logging.INFO)
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(
description="Contracts flattening. See https://github.com/crytic/slither/wiki/Contract-Flattening",
usage="slither-flat filename",
)
parser.add_argument("filename", help="The filename of the contract or project to analyze.")
parser.add_argument("--contract", help="Flatten one contract.", default=None)
parser.add_argument(
"--strategy",
help=f"Flatenning strategy: {STRATEGIES_NAMES} (default: MostDerived).",
default=Strategy.MostDerived.name, # pylint: disable=no-member
)
group_export = parser.add_argument_group("Export options")
group_export.add_argument(
"--dir",
help=f"Export directory (default: {DEFAULT_EXPORT_PATH}).",
default=None,
)
group_export.add_argument(
"--json",
help='Export the results as a JSON file ("--json -" to export to stdout)',
action="store",
default=None,
)
parser.add_argument(
"--zip",
help="Export all the files to a zip file",
action="store",
default=None,
)
parser.add_argument(
"--zip-type",
help=f"Zip compression type. One of {','.join(ZIP_TYPES_ACCEPTED.keys())}. Default lzma",
action="store",
default=None,
)
group_patching = parser.add_argument_group("Patching options")
group_patching.add_argument(
"--convert-external", help="Convert external to public.", action="store_true"
)
group_patching.add_argument(
"--convert-private",
help="Convert private variables to internal.",
action="store_true",
)
group_patching.add_argument(
"--convert-library-to-internal",
help="Convert external or public functions to internal in library.",
action="store_true",
)
group_patching.add_argument(
"--remove-assert", help="Remove call to assert().", action="store_true"
)
group_patching.add_argument(
"--pragma-solidity",
help="Set the solidity pragma with a given version.",
action="store",
default=None,
)
# Add default arguments from crytic-compile
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
def main() -> None:
args = parse_args()
slither = Slither(args.filename, **vars(args))
for compilation_unit in slither.compilation_units:
flat = Flattening(
compilation_unit,
external_to_public=args.convert_external,
remove_assert=args.remove_assert,
convert_library_to_internal=args.convert_library_to_internal,
private_to_internal=args.convert_private,
export_path=args.dir,
pragma_solidity=args.pragma_solidity,
)
try:
strategy = Strategy[args.strategy]
except KeyError:
to_log = f"{args.strategy} is not a valid strategy, use: {STRATEGIES_NAMES} (default MostDerived)"
logger.error(to_log)
return
flat.export(
strategy=strategy,
target=args.contract,
json=args.json,
zip=args.zip,
zip_type=args.zip_type,
)
if __name__ == "__main__":
main()
| 3,903 | Python | .py | 112 | 27.508929 | 110 | 0.64318 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,058 | flattening.py | NioTheFirst_ScType/slither/tools/flattening/flattening.py | import logging
import re
import uuid
from collections import namedtuple
from enum import Enum as PythonEnum
from pathlib import Path
from typing import List, Set, Dict, Optional, Sequence
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.declarations import SolidityFunction, EnumContract, StructureContract
from slither.core.declarations.contract import Contract
from slither.core.declarations.function_top_level import FunctionTopLevel
from slither.core.declarations.top_level import TopLevel
from slither.core.solidity_types import MappingType, ArrayType
from slither.core.solidity_types.type import Type
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.exceptions import SlitherException
from slither.slithir.operations import NewContract, TypeConversion, SolidityCall, InternalCall
from slither.tools.flattening.export.export import (
Export,
export_as_json,
save_to_zip,
save_to_disk,
)
logger = logging.getLogger("Slither-flattening")
# index: where to start
# patch_type:
# - public_to_external: public to external (external-to-public)
# - calldata_to_memory: calldata to memory (external-to-public)
# - line_removal: remove the line (remove-assert)
Patch = namedtuple("PatchExternal", ["index", "patch_type"])
class Strategy(PythonEnum):
MostDerived = 0
OneFile = 1
LocalImport = 2
STRATEGIES_NAMES = ",".join([i.name for i in Strategy])
DEFAULT_EXPORT_PATH = Path("crytic-export/flattening")
class Flattening:
# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-locals,too-few-public-methods
def __init__(
self,
compilation_unit: SlitherCompilationUnit,
external_to_public=False,
remove_assert=False,
convert_library_to_internal=False,
private_to_internal=False,
export_path: Optional[str] = None,
pragma_solidity: Optional[str] = None,
):
self._source_codes: Dict[Contract, str] = {}
self._source_codes_top_level: Dict[TopLevel, str] = {}
self._compilation_unit: SlitherCompilationUnit = compilation_unit
self._external_to_public = external_to_public
self._remove_assert = remove_assert
self._use_abi_encoder_v2 = False
self._convert_library_to_internal = convert_library_to_internal
self._private_to_internal = private_to_internal
self._pragma_solidity = pragma_solidity
self._export_path: Path = DEFAULT_EXPORT_PATH if export_path is None else Path(export_path)
self._check_abi_encoder_v2()
for contract in compilation_unit.contracts:
self._get_source_code(contract)
self._get_source_code_top_level(compilation_unit.structures_top_level)
self._get_source_code_top_level(compilation_unit.enums_top_level)
self._get_source_code_top_level(compilation_unit.variables_top_level)
self._get_source_code_top_level(compilation_unit.functions_top_level)
def _get_source_code_top_level(self, elems: Sequence[TopLevel]) -> None:
for elem in elems:
src_mapping = elem.source_mapping
content = self._compilation_unit.core.source_code[src_mapping.filename.absolute]
start = src_mapping.start
end = src_mapping.start + src_mapping.length
self._source_codes_top_level[elem] = content[start:end]
def _check_abi_encoder_v2(self):
"""
Check if ABIEncoderV2 is required
Set _use_abi_encorder_v2
:return:
"""
for p in self._compilation_unit.pragma_directives:
if "ABIEncoderV2" in str(p.directive):
self._use_abi_encoder_v2 = True
return
def _get_source_code(
self, contract: Contract
): # pylint: disable=too-many-branches,too-many-statements
"""
Save the source code of the contract in self._source_codes
Patch the source code
:param contract:
:return:
"""
src_mapping = contract.source_mapping
content = self._compilation_unit.core.source_code[src_mapping.filename.absolute]
start = src_mapping.start
end = src_mapping.start + src_mapping.length
to_patch = []
# interface must use external
if self._external_to_public and not contract.is_interface:
for f in contract.functions_declared:
# fallback must be external
if f.is_fallback or f.is_constructor_variables:
continue
if f.visibility == "external":
attributes_start = (
f.parameters_src().source_mapping.start
+ f.parameters_src().source_mapping.length
)
attributes_end = f.returns_src().source_mapping.start
attributes = content[attributes_start:attributes_end]
regex = re.search(r"((\sexternal)\s+)|(\sexternal)$|(\)external)$", attributes)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"public_to_external",
)
)
else:
raise SlitherException(f"External keyword not found {f.name} {attributes}")
for var in f.parameters:
if var.location == "calldata":
calldata_start = var.source_mapping.start
calldata_end = calldata_start + var.source_mapping.length
calldata_idx = content[calldata_start:calldata_end].find(" calldata ")
to_patch.append(
Patch(
calldata_start + calldata_idx + 1,
"calldata_to_memory",
)
)
if self._convert_library_to_internal and contract.is_library:
for f in contract.functions_declared:
visibility = ""
if f.visibility in ["external", "public"]:
visibility = f.visibility
attributes_start = (
f.parameters_src().source_mapping["start"]
+ f.parameters_src().source_mapping["length"]
)
attributes_end = f.returns_src().source_mapping["start"]
attributes = content[attributes_start:attributes_end]
regex = (
re.search(r"((\sexternal)\s+)|(\sexternal)$|(\)external)$", attributes)
if visibility == "external"
else re.search(r"((\spublic)\s+)|(\spublic)$|(\)public)$", attributes)
)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"external_to_internal"
if visibility == "external"
else "public_to_internal",
)
)
else:
raise SlitherException(
f"{visibility} keyword not found {f.name} {attributes}"
)
if self._private_to_internal:
for variable in contract.state_variables_declared:
if variable.visibility == "private":
attributes_start = variable.source_mapping.start
attributes_end = attributes_start + variable.source_mapping.length
attributes = content[attributes_start:attributes_end]
regex = re.search(r" private ", attributes)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"private_to_internal",
)
)
else:
raise SlitherException(
f"private keyword not found {variable.name} {attributes}"
)
if self._remove_assert:
for function in contract.functions_and_modifiers_declared:
for node in function.nodes:
for ir in node.irs:
if isinstance(ir, SolidityCall) and ir.function == SolidityFunction(
"assert(bool)"
):
to_patch.append(Patch(node.source_mapping.start, "line_removal"))
logger.info(
f"Code commented: {node.expression} ({node.source_mapping})"
)
to_patch.sort(key=lambda x: x.index, reverse=True)
content = content[start:end]
for patch in to_patch:
patch_type = patch.patch_type
index = patch.index
index = index - start
if patch_type == "public_to_external":
content = content[:index] + "public" + content[index + len("external") :]
elif patch_type == "external_to_internal":
content = content[:index] + "internal" + content[index + len("external") :]
elif patch_type == "public_to_internal":
content = content[:index] + "internal" + content[index + len("public") :]
elif patch_type == "private_to_internal":
content = content[:index] + "internal" + content[index + len("private") :]
elif patch_type == "calldata_to_memory":
content = content[:index] + "memory" + content[index + len("calldata") :]
else:
assert patch_type == "line_removal"
content = content[:index] + " // " + content[index:]
self._source_codes[contract] = content
def _pragmas(self) -> str:
"""
Return the required pragmas
:return:
"""
ret = ""
if self._pragma_solidity:
ret += f"pragma solidity {self._pragma_solidity};\n"
else:
# TODO support multiple compiler version
ret += f"pragma solidity {list(self._compilation_unit.crytic_compile.compilation_units.values())[0].compiler_version.version};\n"
if self._use_abi_encoder_v2:
ret += "pragma experimental ABIEncoderV2;\n"
return ret
def _export_from_type(
self,
t: Type,
contract: Contract,
exported: Set[str],
list_contract: List[Contract],
list_top_level: List[TopLevel],
):
if isinstance(t, UserDefinedType):
t_type = t.type
if isinstance(t_type, (EnumContract, StructureContract)):
if t_type.contract != contract and t_type.contract not in exported:
self._export_list_used_contracts(
t_type.contract, exported, list_contract, list_top_level
)
else:
assert isinstance(t.type, Contract)
if t.type != contract and t.type not in exported:
self._export_list_used_contracts(
t.type, exported, list_contract, list_top_level
)
elif isinstance(t, MappingType):
self._export_from_type(t.type_from, contract, exported, list_contract, list_top_level)
self._export_from_type(t.type_to, contract, exported, list_contract, list_top_level)
elif isinstance(t, ArrayType):
self._export_from_type(t.type, contract, exported, list_contract, list_top_level)
def _export_list_used_contracts( # pylint: disable=too-many-branches
self,
contract: Contract,
exported: Set[str],
list_contract: List[Contract],
list_top_level: List[TopLevel],
):
# TODO: investigate why this happen
if not isinstance(contract, Contract):
return
if contract.name in exported:
return
exported.add(contract.name)
for inherited in contract.inheritance:
self._export_list_used_contracts(inherited, exported, list_contract, list_top_level)
# Find all the external contracts called
externals = contract.all_library_calls + contract.all_high_level_calls
# externals is a list of (contract, function)
# We also filter call to itself to avoid infilite loop
externals = list({e[0] for e in externals if e[0] != contract})
for inherited in externals:
self._export_list_used_contracts(inherited, exported, list_contract, list_top_level)
for list_libs in contract.using_for.values():
for lib_candidate_type in list_libs:
if isinstance(lib_candidate_type, UserDefinedType):
lib_candidate = lib_candidate_type.type
if isinstance(lib_candidate, Contract):
self._export_list_used_contracts(
lib_candidate, exported, list_contract, list_top_level
)
# Find all the external contracts use as a base type
local_vars = []
for f in contract.functions_declared:
local_vars += f.variables
for v in contract.variables + local_vars:
self._export_from_type(v.type, contract, exported, list_contract, list_top_level)
for s in contract.structures:
for elem in s.elems.values():
self._export_from_type(elem.type, contract, exported, list_contract, list_top_level)
# Find all convert and "new" operation that can lead to use an external contract
for f in contract.functions_declared:
for ir in f.slithir_operations:
if isinstance(ir, NewContract):
if ir.contract_created != contract and not ir.contract_created in exported:
self._export_list_used_contracts(
ir.contract_created, exported, list_contract, list_top_level
)
if isinstance(ir, TypeConversion):
self._export_from_type(
ir.type, contract, exported, list_contract, list_top_level
)
for read in ir.read:
if isinstance(read, TopLevel):
if read not in list_top_level:
list_top_level.append(read)
if isinstance(ir, InternalCall):
function_called = ir.function
if isinstance(function_called, FunctionTopLevel):
list_top_level.append(function_called)
if contract not in list_contract:
list_contract.append(contract)
def _export_contract_with_inheritance(self, contract) -> Export:
list_contracts: List[Contract] = [] # will contain contract itself
list_top_level: List[TopLevel] = []
self._export_list_used_contracts(contract, set(), list_contracts, list_top_level)
path = Path(self._export_path, f"{contract.name}_{uuid.uuid4()}.sol")
content = ""
content += self._pragmas()
for listed_top_level in list_top_level:
content += self._source_codes_top_level[listed_top_level]
content += "\n"
for listed_contract in list_contracts:
content += self._source_codes[listed_contract]
content += "\n"
return Export(filename=path, content=content)
def _export_most_derived(self) -> List[Export]:
ret: List[Export] = []
for contract in self._compilation_unit.contracts_derived:
ret.append(self._export_contract_with_inheritance(contract))
return ret
def _export_all(self) -> List[Export]:
path = Path(self._export_path, "export.sol")
content = ""
content += self._pragmas()
for top_level_content in self._source_codes_top_level.values():
content += "\n"
content += top_level_content
content += "\n"
contract_seen = set()
contract_to_explore = list(self._compilation_unit.contracts)
# We only need the inheritance order here, as solc can compile
# a contract that use another contract type (ex: state variable) that he has not seen yet
while contract_to_explore:
next_to_explore = contract_to_explore.pop(0)
if not next_to_explore.inheritance or all(
(father in contract_seen for father in next_to_explore.inheritance)
):
content += "\n"
content += self._source_codes[next_to_explore]
content += "\n"
contract_seen.add(next_to_explore)
else:
contract_to_explore.append(next_to_explore)
return [Export(filename=path, content=content)]
def _export_with_import(self) -> List[Export]:
exports: List[Export] = []
for contract in self._compilation_unit.contracts:
list_contracts: List[Contract] = [] # will contain contract itself
list_top_level: List[TopLevel] = []
self._export_list_used_contracts(contract, set(), list_contracts, list_top_level)
if list_top_level:
logger.info(
"Top level objects are not yet supported with the local import flattening"
)
for elem in list_top_level:
logger.info(f"Missing {elem} for {contract.name}")
path = Path(self._export_path, f"{contract.name}.sol")
content = ""
content += self._pragmas()
for used_contract in list_contracts:
if used_contract != contract:
content += f"import './{used_contract.name}.sol';\n"
content += "\n"
content += self._source_codes[contract]
content += "\n"
exports.append(Export(filename=path, content=content))
return exports
def export( # pylint: disable=too-many-arguments,too-few-public-methods
self,
strategy: Strategy,
target: Optional[str] = None,
json: Optional[str] = None,
zip: Optional[str] = None, # pylint: disable=redefined-builtin
zip_type: Optional[str] = None,
):
if not self._export_path.exists():
self._export_path.mkdir(parents=True)
exports: List[Export] = []
if target is None:
if strategy == Strategy.MostDerived:
exports = self._export_most_derived()
elif strategy == Strategy.OneFile:
exports = self._export_all()
elif strategy == Strategy.LocalImport:
exports = self._export_with_import()
else:
contracts = self._compilation_unit.get_contract_from_name(target)
if len(contracts) == 0:
logger.error(f"{target} not found")
return
exports = []
for contract in contracts:
exports.append(self._export_contract_with_inheritance(contract))
if json:
export_as_json(exports, json)
elif zip:
save_to_zip(exports, zip, zip_type)
else:
save_to_disk(exports)
| 19,871 | Python | .py | 407 | 34.837838 | 141 | 0.569139 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,059 | export.py | NioTheFirst_ScType/slither/tools/flattening/export/export.py | import json
import logging
# https://docs.python.org/3/library/zipfile.html#zipfile-objects
import zipfile
from collections import namedtuple
from typing import List
ZIP_TYPES_ACCEPTED = {
"lzma": zipfile.ZIP_LZMA,
"stored": zipfile.ZIP_STORED,
"deflated": zipfile.ZIP_DEFLATED,
"bzip2": zipfile.ZIP_BZIP2,
}
Export = namedtuple("Export", ["filename", "content"])
logger = logging.getLogger("Slither")
def save_to_zip(files: List[Export], zip_filename: str, zip_type: str = "lzma"):
"""
Save projects to a zip
"""
logger.info(f"Export {zip_filename}")
with zipfile.ZipFile(
zip_filename,
"w",
compression=ZIP_TYPES_ACCEPTED.get(zip_type, zipfile.ZIP_LZMA),
) as file_desc:
for f in files:
file_desc.writestr(str(f.filename), f.content)
def save_to_disk(files: List[Export]):
"""
Save projects to a zip
"""
for file in files:
with open(file.filename, "w", encoding="utf8") as f:
logger.info(f"Export {file.filename}")
f.write(file.content)
def export_as_json(files: List[Export], filename: str):
"""
Save projects to a zip
"""
files_as_dict = {str(f.filename): f.content for f in files}
if filename == "-":
print(json.dumps(files_as_dict))
else:
logger.info(f"Export {filename}")
with open(filename, "w", encoding="utf8") as f:
json.dump(files_as_dict, f)
| 1,459 | Python | .py | 45 | 26.888889 | 80 | 0.644793 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,060 | __main__.py | NioTheFirst_ScType/slither/tools/possible_paths/__main__.py | import sys
import logging
from argparse import ArgumentParser, Namespace
from crytic_compile import cryticparser
from slither import Slither
from slither.core.declarations import FunctionContract
from slither.utils.colors import red
from slither.tools.possible_paths.possible_paths import (
find_target_paths,
resolve_functions,
ResolveFunctionException,
)
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
def parse_args() -> Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser: ArgumentParser = ArgumentParser(
description="PossiblePaths",
usage="possible_paths.py filename [contract.function targets]",
)
parser.add_argument(
"filename", help="The filename of the contract or truffle directory to analyze."
)
parser.add_argument("targets", nargs="+")
cryticparser.init(parser)
return parser.parse_args()
def main() -> None:
# ------------------------------
# PossiblePaths.py
# Usage: python3 possible_paths.py filename targets
# Example: python3 possible_paths.py contract.sol contract1.function1 contract2.function2 contract3.function3
# ------------------------------
# Parse all arguments
args = parse_args()
# Perform slither analysis on the given filename
slither = Slither(args.filename, **vars(args))
try:
targets = resolve_functions(slither, args.targets)
except ResolveFunctionException as resolvefunction:
print(red(resolvefunction))
sys.exit(-1)
# Print out all target functions.
print("Target functions:")
for target in targets:
if isinstance(target, FunctionContract):
print(f"- {target.contract_declarer.name}.{target.full_name}")
else:
pass
# TODO implement me
print("\n")
# Obtain all paths which reach the target functions.
reaching_paths = find_target_paths(slither, targets)
reaching_functions = {y for x in reaching_paths for y in x if y not in targets}
# Print out all function names which can reach the targets.
print("The following functions reach the specified targets:")
for function_desc in sorted([f"{f.canonical_name}" for f in reaching_functions]):
print(f"- {function_desc}")
print("\n")
# Format all function paths.
reaching_paths_str = [
" -> ".join([f"{f.canonical_name}" for f in reaching_path])
for reaching_path in reaching_paths
]
# Print a sorted list of all function paths which can reach the targets.
print("The following paths reach the specified targets:")
for reaching_path in sorted(reaching_paths_str):
print(f"{reaching_path}\n")
if __name__ == "__main__":
main()
| 2,844 | Python | .py | 72 | 34 | 119 | 0.687137 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,061 | possible_paths.py | NioTheFirst_ScType/slither/tools/possible_paths/possible_paths.py | from typing import List, Tuple, Union, Optional, Set
from slither import Slither
from slither.core.declarations import Function, FunctionContract
from slither.core.slither_core import SlitherCore
class ResolveFunctionException(Exception):
pass
def resolve_function(slither: SlitherCore, contract_name: str, function_name: str) -> Function:
"""
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved function, raises an exception otherwise.
"""
# Obtain the target contract
contracts = slither.get_contract_from_name(contract_name)
# Verify the contract was resolved successfully
if len(contracts) != 1:
raise ResolveFunctionException(f"Could not resolve target contract: {contract_name}")
contract = contracts[0]
# Obtain the target function
target_function = next(
(function for function in contract.functions if function.name == function_name),
None,
)
# Verify we have resolved the function specified.
if target_function is None:
raise ResolveFunctionException(
f"Could not resolve target function: {contract_name}.{function_name}"
)
# Add the resolved function to the new list.
return target_function
def resolve_functions(
slither: Slither, functions: List[Union[str, Tuple[str, str]]]
) -> List[Function]:
"""
Resolves the provided function descriptors.
:param functions: A list of tuples (contract_name, function_name) or str (of form "ContractName.FunctionName")
to resolve into function objects.
:return: Returns a list of resolved functions.
"""
# Create the resolved list.
resolved: List[Function] = []
# Verify that the provided argument is a list.
if not isinstance(functions, list):
raise ResolveFunctionException("Provided functions to resolve must be a list type.")
# Loop for each item in the list.
for item in functions:
if isinstance(item, str):
# If the item is a single string, we assume it is of form 'ContractName.FunctionName'.
parts = item.split(".")
if len(parts) < 2:
raise ResolveFunctionException(
"Provided string descriptor must be of form 'ContractName.FunctionName'"
)
resolved.append(resolve_function(slither, parts[0], parts[1]))
elif isinstance(item, tuple):
# If the item is a tuple, it should be a 2-tuple providing contract and function names.
if len(item) != 2:
raise ResolveFunctionException(
"Provided tuple descriptor must provide a contract and function name."
)
resolved.append(resolve_function(slither, item[0], item[1]))
else:
raise ResolveFunctionException(
f"Unexpected function descriptor type to resolve in list: {type(item)}"
)
# Return the resolved list.
return resolved
def all_function_definitions(function: Function) -> List[Function]:
"""
Obtains a list of representing this function and any base definitions
:param function: The function to obtain all definitions at and beneath.
:return: Returns a list composed of the provided function definition and any base definitions.
"""
# TODO implement me
if not isinstance(function, FunctionContract):
return []
ret: List[Function] = [function]
ret += [
f
for c in function.contract.inheritance
for f in c.functions_and_modifiers_declared
if f.full_name == function.full_name
]
return ret
def __find_target_paths(
slither: SlitherCore, target_function: Function, current_path: Optional[List[Function]] = None
) -> Set[Tuple[Function, ...]]:
current_path = current_path if current_path else []
# Create our results list
results: Set[Tuple[Function, ...]] = set()
# Add our current function to the path.
current_path = [target_function] + current_path
# Obtain this target function and any base definitions.
all_target_functions = set(all_function_definitions(target_function))
# Look through all functions
for contract in slither.contracts:
for function in contract.functions_and_modifiers_declared:
# If the function is already in our path, skip it.
if function in current_path:
continue
# Find all function calls in this function (except for low level)
called_functions_list = [
f for (_, f) in function.high_level_calls if isinstance(f, Function)
]
called_functions_list += [f for (_, f) in function.library_calls]
called_functions_list += [f for f in function.internal_calls if isinstance(f, Function)]
called_functions = set(called_functions_list)
# If any of our target functions are reachable from this function, it's a result.
if all_target_functions.intersection(called_functions):
path_results = __find_target_paths(slither, function, current_path.copy())
if path_results:
results = results.union(path_results)
# If this path is external accessible from this point, we add the current path to the list.
if target_function.visibility in ["public", "external"] and len(current_path) > 1:
results.add(tuple(current_path))
return results
def find_target_paths(
slither: SlitherCore, target_functions: List[Function]
) -> Set[Tuple[Function, ...]]:
"""
Obtains all functions which can lead to any of the target functions being called.
:param target_functions: The functions we are interested in reaching.
:return: Returns a list of all functions which can reach any of the target_functions.
"""
# Create our results list
results: Set[Tuple[Function, ...]] = set()
# Loop for each target function
for target_function in target_functions:
results = results.union(__find_target_paths(slither, target_function))
return results
| 6,290 | Python | .py | 131 | 40.259542 | 114 | 0.680914 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,062 | __main__.py | NioTheFirst_ScType/slither/tools/doctor/__main__.py | import argparse
import logging
import sys
from crytic_compile import cryticparser
from slither.tools.doctor.utils import report_section
from slither.tools.doctor.checks import ALL_CHECKS
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(
description="Troubleshoot running Slither on your project",
usage="slither-doctor project",
)
parser.add_argument("project", help="The codebase to be tested.")
# Add default arguments from crytic-compile
cryticparser.init(parser)
return parser.parse_args()
def main():
# log on stdout to keep output in order
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, force=True)
args = parse_args()
kwargs = vars(args)
for check in ALL_CHECKS:
with report_section(check.title):
check.function(**kwargs)
if __name__ == "__main__":
main()
| 1,017 | Python | .py | 29 | 30.172414 | 75 | 0.717949 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,063 | utils.py | NioTheFirst_ScType/slither/tools/doctor/utils.py | from contextlib import contextmanager
import logging
from typing import Optional
from slither.utils.colors import bold, yellow, red
@contextmanager
def snip_section(message: Optional[str]) -> None:
if message:
print(red(message), end="\n\n")
print(yellow("---- snip 8< ----"))
yield
print(yellow("---- >8 snip ----"))
@contextmanager
def report_section(title: str) -> None:
print(bold(f"## {title}"), end="\n\n")
try:
yield
except Exception as e: # pylint: disable=broad-except
with snip_section(
"slither-doctor failed unexpectedly! Please report this on the Slither GitHub issue tracker, and include the output below:"
):
logging.exception(e)
finally:
print(end="\n\n")
| 774 | Python | .py | 23 | 28.26087 | 135 | 0.656836 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,064 | versions.py | NioTheFirst_ScType/slither/tools/doctor/checks/versions.py | from importlib import metadata
import json
from typing import Optional
import urllib
from packaging.version import parse, Version
from slither.utils.colors import yellow, green
def get_installed_version(name: str) -> Optional[Version]:
try:
return parse(metadata.version(name))
except metadata.PackageNotFoundError:
return None
def get_github_version(name: str) -> Optional[Version]:
try:
with urllib.request.urlopen(
f"https://api.github.com/repos/crytic/{name}/releases/latest"
) as response:
text = response.read()
data = json.loads(text)
return parse(data["tag_name"])
except: # pylint: disable=bare-except
return None
def show_versions(**_kwargs) -> None:
versions = {
"Slither": (get_installed_version("slither-analyzer"), get_github_version("slither")),
"crytic-compile": (
get_installed_version("crytic-compile"),
get_github_version("crytic-compile"),
),
"solc-select": (get_installed_version("solc-select"), get_github_version("solc-select")),
}
outdated = {
name
for name, (installed, latest) in versions.items()
if not installed or not latest or latest > installed
}
for name, (installed, latest) in versions.items():
color = yellow if name in outdated else green
print(
f"{name + ':':<16}{color(str(installed) or 'N/A'):<16} (latest is {str(latest) or 'Unknown'})"
)
if len(outdated) > 0:
print()
print(
yellow(
f"Please update {', '.join(outdated)} to the latest release before creating a bug report."
)
)
else:
print()
print(green("Your tools are up to date."))
| 1,816 | Python | .py | 50 | 28.54 | 106 | 0.619373 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,065 | __init__.py | NioTheFirst_ScType/slither/tools/doctor/checks/__init__.py | from typing import Callable, List
from dataclasses import dataclass
from slither.tools.doctor.checks.paths import check_slither_path
from slither.tools.doctor.checks.platform import compile_project, detect_platform
from slither.tools.doctor.checks.versions import show_versions
@dataclass
class Check:
title: str
function: Callable[..., None]
ALL_CHECKS: List[Check] = [
Check("PATH configuration", check_slither_path),
Check("Software versions", show_versions),
Check("Project platform", detect_platform),
Check("Project compilation", compile_project),
]
| 585 | Python | .py | 15 | 36.066667 | 81 | 0.785841 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,066 | platform.py | NioTheFirst_ScType/slither/tools/doctor/checks/platform.py | import logging
from pathlib import Path
from crytic_compile import crytic_compile
from slither.tools.doctor.utils import snip_section
from slither.utils.colors import red, yellow, green
def detect_platform(project: str, **kwargs) -> None:
path = Path(project)
if path.is_file():
print(
yellow(
f"{project!r} is a file. Using it as target will manually compile your code with solc and _not_ use a compilation framework. Is that what you meant to do?"
)
)
return
print(f"Trying to detect project type for {project!r}")
supported_platforms = crytic_compile.get_platforms()
skip_platforms = {"solc", "solc-json", "archive", "standard", "etherscan"}
detected_platforms = {
platform.NAME: platform.is_supported(project, **kwargs)
for platform in supported_platforms
if platform.NAME.lower() not in skip_platforms
}
platform_qty = len([platform for platform, state in detected_platforms.items() if state])
print("Is this project using...")
for platform, state in detected_platforms.items():
print(f" => {platform + '?':<15}{state and green('Yes') or red('No')}")
print()
if platform_qty == 0:
print(red("No platform was detected! This doesn't sound right."))
print(
yellow(
"Are you trying to analyze a folder with standalone solidity files, without using a compilation framework? If that's the case, then this is okay."
)
)
elif platform_qty > 1:
print(red("More than one platform was detected! This doesn't sound right."))
print(
red("Please use `--compile-force-framework` in Slither to force the correct framework.")
)
else:
print(green("A single platform was detected."), yellow("Is it the one you expected?"))
def compile_project(project: str, **kwargs):
print("Invoking crytic-compile on the project, please wait...")
try:
crytic_compile.CryticCompile(project, **kwargs)
except Exception as e: # pylint: disable=broad-except
with snip_section("Project compilation failed :( The following error was generated:"):
logging.exception(e)
| 2,249 | Python | .py | 48 | 39.375 | 171 | 0.661187 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,067 | paths.py | NioTheFirst_ScType/slither/tools/doctor/checks/paths.py | from pathlib import Path
from typing import List, Optional, Tuple
import shutil
import sys
import sysconfig
from slither.utils.colors import yellow, green, red
def path_is_relative_to(path: Path, relative_to: Path) -> bool:
"""
Check if a path is relative to another one.
Compatibility wrapper for Path.is_relative_to
"""
if sys.version_info >= (3, 9, 0):
return path.is_relative_to(relative_to)
path_parts = path.resolve().parts
relative_to_parts = relative_to.resolve().parts
if len(path_parts) < len(relative_to_parts):
return False
for (a, b) in zip(path_parts, relative_to_parts):
if a != b:
return False
return True
def check_path_config(name: str) -> Tuple[bool, Optional[Path], List[Path]]:
"""
Check if a given Python binary/script is in PATH.
:return: Returns if the binary on PATH corresponds to this installation,
its path (if present), and a list of possible paths where this
binary might be found.
"""
binary_path = shutil.which(name)
possible_paths = []
for scheme in sysconfig.get_scheme_names():
script_path = Path(sysconfig.get_path("scripts", scheme))
purelib_path = Path(sysconfig.get_path("purelib", scheme))
script_binary_path = shutil.which(name, path=script_path)
if script_binary_path is not None:
possible_paths.append((script_path, purelib_path))
binary_here = False
if binary_path is not None:
binary_path = Path(binary_path)
this_code = Path(__file__)
this_binary = list(filter(lambda x: path_is_relative_to(this_code, x[1]), possible_paths))
binary_here = len(this_binary) > 0 and all(
path_is_relative_to(binary_path, script) for script, _ in this_binary
)
return binary_here, binary_path, list(set(script for script, _ in possible_paths))
def check_slither_path(**_kwargs) -> None:
binary_here, binary_path, possible_paths = check_path_config("slither")
show_paths = False
if binary_path:
print(green(f"`slither` found in PATH at `{binary_path}`."))
if binary_here:
print(green("Its location matches this slither-doctor installation."))
else:
print(
yellow(
"This path does not correspond to this slither-doctor installation.\n"
+ "Double-check the order of directories in PATH if you have several Slither installations."
)
)
show_paths = True
else:
print(red("`slither` was not found in PATH."))
show_paths = True
if show_paths:
print()
print("Consider adding one of the following directories to PATH:")
for path in possible_paths:
print(f" * {path}")
| 2,857 | Python | .py | 68 | 34.088235 | 112 | 0.638889 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,068 | __main__.py | NioTheFirst_ScType/slither/tools/documentation/__main__.py | import argparse
import logging
import uuid
from typing import Optional, Dict, List
from crytic_compile import cryticparser
from slither import Slither
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.declarations import Function
from slither.formatters.utils.patches import create_patch, apply_patch, create_diff
from slither.utils import codex
logging.basicConfig()
logging.getLogger("Slither").setLevel(logging.INFO)
logger = logging.getLogger("Slither")
def parse_args() -> argparse.Namespace:
"""
Parse the underlying arguments for the program.
:return: Returns the arguments for the program.
"""
parser = argparse.ArgumentParser(description="Demo", usage="slither-documentation filename")
parser.add_argument("project", help="The target directory/Solidity file.")
parser.add_argument(
"--overwrite", help="Overwrite the files (be careful).", action="store_true", default=False
)
parser.add_argument(
"--force-answer-parsing",
help="Apply heuristics to better parse codex output (might lead to incorrect results)",
action="store_true",
default=False,
)
parser.add_argument(
"--retry",
help="Retry failed query (default 1). Each retry increases the temperature by 0.1",
action="store",
default=1,
)
# Add default arguments from crytic-compile
cryticparser.init(parser)
codex.init_parser(parser, always_enable_codex=True)
return parser.parse_args()
def _use_tab(char: str) -> Optional[bool]:
"""
Check if the char is a tab
Args:
char:
Returns:
"""
if char == " ":
return False
if char == "\t":
return True
return None
def _post_processesing(
answer: str, starting_column: int, use_tab: Optional[bool], force_and_stopped: bool
) -> Optional[str]:
"""
Clean answers from codex
Args:
answer:
starting_column:
Returns:
"""
if answer.count("/**") != 1:
return None
# Sometimes codex will miss the */, even if it finished properly the request
# In this case, we allow slither-documentation to force the */
if answer.count("*/") != 1:
if force_and_stopped:
answer += "*/"
else:
return None
if answer.find("/**") > answer.find("*/"):
return None
answer = answer[answer.find("/**") : answer.find("*/") + 2]
answer_lines = answer.splitlines()
# Add indentation to all the lines, aside the first one
space_char = "\t" if use_tab else " "
if len(answer_lines) > 0:
answer = (
answer_lines[0]
+ "\n"
+ "\n".join(
[space_char * (starting_column - 1) + line for line in answer_lines[1:] if line]
)
)
answer += "\n" + space_char * (starting_column - 1)
return answer
return answer_lines[0]
def _handle_codex(
answer: Dict, starting_column: int, use_tab: Optional[bool], force: bool
) -> Optional[str]:
if "choices" in answer:
if answer["choices"]:
if "text" in answer["choices"][0]:
has_stopped = answer["choices"][0].get("finish_reason", "") == "stop"
answer_processed = _post_processesing(
answer["choices"][0]["text"], starting_column, use_tab, force and has_stopped
)
if answer_processed is None:
return None
return answer_processed
return None
# pylint: disable=too-many-locals,too-many-arguments
def _handle_function(
function: Function,
overwrite: bool,
all_patches: Dict,
logging_file: Optional[str],
slither: Slither,
retry: int,
force: bool,
) -> bool:
if (
function.source_mapping.is_dependency
or function.has_documentation
or function.is_constructor_variables
):
return overwrite
prompt = "Create a natpsec documentation for this solidity code with only notice and dev.\n"
src_mapping = function.source_mapping
content = function.compilation_unit.core.source_code[src_mapping.filename.absolute]
start = src_mapping.start
end = src_mapping.start + src_mapping.length
prompt += content[start:end]
use_tab = _use_tab(content[start - 1])
if use_tab is None and src_mapping.starting_column > 1:
logger.info(f"Non standard space indentation found {content[start - 1:end]}")
if overwrite:
logger.info("Disable overwrite to avoid mistakes")
overwrite = False
openai = codex.openai_module() # type: ignore
if openai is None:
raise ImportError
if logging_file:
codex.log_codex(logging_file, "Q: " + prompt)
tentative = 0
answer_processed: Optional[str] = None
while tentative < retry:
tentative += 1
answer = openai.Completion.create( # type: ignore
prompt=prompt,
model=slither.codex_model,
temperature=min(slither.codex_temperature + tentative * 0.1, 1),
max_tokens=slither.codex_max_tokens,
)
if logging_file:
codex.log_codex(logging_file, "A: " + str(answer))
answer_processed = _handle_codex(answer, src_mapping.starting_column, use_tab, force)
if answer_processed:
break
logger.info(
f"Codex could not generate a well formatted answer for {function.canonical_name}"
)
logger.info(answer)
if not answer_processed:
return overwrite
create_patch(all_patches, src_mapping.filename.absolute, start, start, "", answer_processed)
return overwrite
def _handle_compilation_unit(
slither: Slither,
compilation_unit: SlitherCompilationUnit,
overwrite: bool,
force: bool,
retry: int,
) -> None:
logging_file: Optional[str]
if slither.codex_log:
logging_file = str(uuid.uuid4())
else:
logging_file = None
for scope in compilation_unit.scopes.values():
# Dont send tests file
if (
".t.sol" in scope.filename.absolute
or "mock" in scope.filename.absolute.lower()
or "test" in scope.filename.absolute.lower()
):
continue
functions_target: List[Function] = []
for contract in scope.contracts.values():
functions_target += contract.functions_declared
functions_target += list(scope.functions)
all_patches: Dict = {}
for function in functions_target:
overwrite = _handle_function(
function, overwrite, all_patches, logging_file, slither, retry, force
)
# all_patches["patches"] should have only 1 file
if "patches" not in all_patches:
continue
for file in all_patches["patches"]:
original_txt = compilation_unit.core.source_code[file].encode("utf8")
patched_txt = original_txt
patches = all_patches["patches"][file]
offset = 0
patches.sort(key=lambda x: x["start"])
for patch in patches:
patched_txt, offset = apply_patch(patched_txt, patch, offset)
if overwrite:
with open(file, "w", encoding="utf8") as f:
f.write(patched_txt.decode("utf8"))
else:
diff = create_diff(compilation_unit, original_txt, patched_txt, file)
with open(f"{file}.patch", "w", encoding="utf8") as f:
f.write(diff)
def main() -> None:
args = parse_args()
logger.info("This tool is a WIP, use it with cautious")
logger.info("Be aware of OpenAI ToS: https://openai.com/api/policies/terms/")
slither = Slither(args.project, **vars(args))
try:
for compilation_unit in slither.compilation_units:
_handle_compilation_unit(
slither,
compilation_unit,
args.overwrite,
args.force_answer_parsing,
int(args.retry),
)
except ImportError:
pass
if __name__ == "__main__":
main()
| 8,245 | Python | .py | 222 | 28.959459 | 99 | 0.620841 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,069 | __main__.py | NioTheFirst_ScType/slither/tools/mutator/__main__.py | import argparse
import inspect
import logging
import sys
from typing import Type, List, Any
from crytic_compile import cryticparser
from slither import Slither
from slither.tools.mutator.mutators import all_mutators
from .mutators.abstract_mutator import AbstractMutator
from .utils.command_line import output_mutators
logging.basicConfig()
logger = logging.getLogger("Slither")
logger.setLevel(logging.INFO)
###################################################################################
###################################################################################
# region Cli Arguments
###################################################################################
###################################################################################
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Experimental smart contract mutator. Based on https://arxiv.org/abs/2006.11597",
usage="slither-mutate target",
)
parser.add_argument("codebase", help="Codebase to analyze (.sol file, truffle directory, ...)")
parser.add_argument(
"--list-mutators",
help="List available detectors",
action=ListMutators,
nargs=0,
default=False,
)
# Initiate all the crytic config cli options
cryticparser.init(parser)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return parser.parse_args()
def _get_mutators() -> List[Type[AbstractMutator]]:
detectors_ = [getattr(all_mutators, name) for name in dir(all_mutators)]
detectors = [c for c in detectors_ if inspect.isclass(c) and issubclass(c, AbstractMutator)]
return detectors
class ListMutators(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
checks = _get_mutators()
output_mutators(checks)
parser.exit()
# endregion
###################################################################################
###################################################################################
# region Main
###################################################################################
###################################################################################
def main():
args = parse_args()
print(args.codebase)
sl = Slither(args.codebase, **vars(args))
for M in _get_mutators():
m = M(sl)
m.mutate()
# endregion
| 2,565 | Python | .py | 62 | 36.870968 | 101 | 0.516142 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,070 | generic_patching.py | NioTheFirst_ScType/slither/tools/mutator/utils/generic_patching.py | from typing import Dict
from slither.core.declarations import Contract
from slither.core.variables.variable import Variable
from slither.formatters.utils.patches import create_patch
def remove_assignement(variable: Variable, contract: Contract, result: Dict):
"""
Remove the variable's initial assignement
:param variable:
:param contract:
:param result:
:return:
"""
# Retrieve the file
in_file = contract.source_mapping.filename.absolute
# Retrieve the source code
in_file_str = contract.compilation_unit.core.source_code[in_file]
# Get the string
start = variable.source_mapping.start
stop = variable.expression.source_mapping.start
old_str = in_file_str[start:stop]
new_str = old_str[: old_str.find("=")]
create_patch(
result,
in_file,
start,
stop + variable.expression.source_mapping.length,
old_str,
new_str,
)
| 944 | Python | .py | 29 | 27.172414 | 77 | 0.703744 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,071 | command_line.py | NioTheFirst_ScType/slither/tools/mutator/utils/command_line.py | from slither.utils.myprettytable import MyPrettyTable
def output_mutators(mutators_classes):
mutators_list = []
for detector in mutators_classes:
argument = detector.NAME
help_info = detector.HELP
fault_class = detector.FAULTCLASS.name
fault_nature = detector.FAULTNATURE.name
mutators_list.append((argument, help_info, fault_class, fault_nature))
table = MyPrettyTable(["Num", "Name", "What it Does", "Fault Class", "Fault Nature"])
# Sort by class, nature, name
mutators_list = sorted(mutators_list, key=lambda element: (element[2], element[3], element[0]))
idx = 1
for (argument, help_info, fault_class, fault_nature) in mutators_list:
table.add_row([idx, argument, help_info, fault_class, fault_nature])
idx = idx + 1
print(table)
| 826 | Python | .py | 17 | 42.235294 | 99 | 0.687345 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,072 | MIA.py | NioTheFirst_ScType/slither/tools/mutator/mutators/MIA.py | from slither.core.cfg.node import NodeType
from slither.formatters.utils.patches import create_patch
from slither.tools.mutator.mutators.abstract_mutator import AbstractMutator, FaultNature, FaultClass
class MIA(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "MIA"
HELP = '"if" construct around statement'
FAULTCLASS = FaultClass.Checking
FAULTNATURE = FaultNature.Missing
def _mutate(self):
result = {}
for contract in self.slither.contracts:
for function in contract.functions_declared + contract.modifiers_declared:
for node in function.nodes:
if node.type == NodeType.IF:
# Retrieve the file
in_file = contract.source_mapping.filename.absolute
# Retrieve the source code
in_file_str = contract.compilation_unit.core.source_code[in_file]
# Get the string
start = node.source_mapping.start
stop = start + node.source_mapping.length
old_str = in_file_str[start:stop]
# Replace the expression with true
new_str = "true"
create_patch(result, in_file, start, stop, old_str, new_str)
return result
| 1,382 | Python | .py | 26 | 38.038462 | 100 | 0.594796 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,073 | MVIE.py | NioTheFirst_ScType/slither/tools/mutator/mutators/MVIE.py | from slither.core.expressions import Literal
from slither.tools.mutator.mutators.abstract_mutator import AbstractMutator, FaultNature, FaultClass
from slither.tools.mutator.utils.generic_patching import remove_assignement
class MVIE(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "MVIE"
HELP = "variable initialization using an expression"
FAULTCLASS = FaultClass.Assignement
FAULTNATURE = FaultNature.Missing
def _mutate(self):
result = {}
for contract in self.slither.contracts:
# Create fault for state variables declaration
for variable in contract.state_variables_declared:
if variable.initialized:
# Cannot remove the initialization of constant variables
if variable.is_constant:
continue
if not isinstance(variable.expression, Literal):
remove_assignement(variable, contract, result)
for function in contract.functions_declared + contract.modifiers_declared:
for variable in function.local_variables:
if variable.initialized and not isinstance(variable.expression, Literal):
remove_assignement(variable, contract, result)
return result
| 1,336 | Python | .py | 24 | 43.291667 | 100 | 0.676132 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,074 | MVIV.py | NioTheFirst_ScType/slither/tools/mutator/mutators/MVIV.py | from slither.core.expressions import Literal
from slither.tools.mutator.mutators.abstract_mutator import AbstractMutator, FaultNature, FaultClass
from slither.tools.mutator.utils.generic_patching import remove_assignement
class MVIV(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "MVIV"
HELP = "variable initialization using a value"
FAULTCLASS = FaultClass.Assignement
FAULTNATURE = FaultNature.Missing
def _mutate(self):
result = {}
for contract in self.slither.contracts:
# Create fault for state variables declaration
for variable in contract.state_variables_declared:
if variable.initialized:
# Cannot remove the initialization of constant variables
if variable.is_constant:
continue
if isinstance(variable.expression, Literal):
remove_assignement(variable, contract, result)
for function in contract.functions_declared + contract.modifiers_declared:
for variable in function.local_variables:
if variable.initialized and isinstance(variable.expression, Literal):
remove_assignement(variable, contract, result)
return result
| 1,322 | Python | .py | 24 | 42.708333 | 100 | 0.674166 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,075 | abstract_mutator.py | NioTheFirst_ScType/slither/tools/mutator/mutators/abstract_mutator.py | import abc
import logging
from enum import Enum
from typing import Optional, Dict
from slither import Slither
from slither.formatters.utils.patches import apply_patch, create_diff
logger = logging.getLogger("Slither")
class IncorrectMutatorInitialization(Exception):
pass
class FaultClass(Enum):
Assignement = 0
Checking = 1
Interface = 2
Algorithm = 3
Undefined = 100
class FaultNature(Enum):
Missing = 0
Wrong = 1
Extraneous = 2
Undefined = 100
class AbstractMutator(metaclass=abc.ABCMeta): # pylint: disable=too-few-public-methods
NAME = ""
HELP = ""
FAULTCLASS = FaultClass.Undefined
FAULTNATURE = FaultNature.Undefined
def __init__(self, slither: Slither, rate: int = 10, seed: Optional[int] = None):
self.slither = slither
self.seed = seed
self.rate = rate
if not self.NAME:
raise IncorrectMutatorInitialization(
f"NAME is not initialized {self.__class__.__name__}"
)
if not self.HELP:
raise IncorrectMutatorInitialization(
f"HELP is not initialized {self.__class__.__name__}"
)
if self.FAULTCLASS == FaultClass.Undefined:
raise IncorrectMutatorInitialization(
f"FAULTCLASS is not initialized {self.__class__.__name__}"
)
if self.FAULTNATURE == FaultNature.Undefined:
raise IncorrectMutatorInitialization(
f"FAULTNATURE is not initialized {self.__class__.__name__}"
)
if rate < 0 or rate > 100:
raise IncorrectMutatorInitialization(
f"rate must be between 0 and 100 {self.__class__.__name__}"
)
@abc.abstractmethod
def _mutate(self) -> Dict:
"""TODO Documentation"""
return {}
def mutate(self) -> None:
all_patches = self._mutate()
if "patches" not in all_patches:
logger.debug(f"No patches found by {self.NAME}")
return
for file in all_patches["patches"]:
original_txt = self.slither.source_code[file].encode("utf8")
patched_txt = original_txt
offset = 0
patches = all_patches["patches"][file]
patches.sort(key=lambda x: x["start"])
if not all(patches[i]["end"] <= patches[i + 1]["end"] for i in range(len(patches) - 1)):
logger.info(f"Impossible to generate patch; patches collisions: {patches}")
continue
for patch in patches:
patched_txt, offset = apply_patch(patched_txt, patch, offset)
diff = create_diff(self.slither, original_txt, patched_txt, file)
if not diff:
logger.info(f"Impossible to generate patch; empty {patches}")
print(diff)
| 2,856 | Python | .py | 73 | 29.849315 | 100 | 0.609121 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,076 | all_mutators.py | NioTheFirst_ScType/slither/tools/mutator/mutators/all_mutators.py | # pylint: disable=unused-import
from slither.tools.mutator.mutators.MVIV import MVIV
from slither.tools.mutator.mutators.MVIE import MVIE
from slither.tools.mutator.mutators.MIA import MIA
| 189 | Python | .py | 4 | 46.25 | 52 | 0.854054 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,077 | __main__.py | NioTheFirst_ScType/slither/tools/read_storage/__main__.py | """
Tool to read on-chain storage from EVM
"""
import json
import argparse
from crytic_compile import cryticparser
from slither import Slither
from slither.tools.read_storage.read_storage import SlitherReadStorage
def parse_args() -> argparse.Namespace:
"""Parse the underlying arguments for the program.
Returns:
The arguments for the program.
"""
parser = argparse.ArgumentParser(
description="Read a variable's value from storage for a deployed contract",
usage=(
"\nTo retrieve a single variable's value:\n"
+ "\tslither-read-storage $TARGET address --variable-name $NAME\n"
+ "To retrieve a contract's storage layout:\n"
+ "\tslither-read-storage $TARGET address --contract-name $NAME --json storage_layout.json\n"
+ "To retrieve a contract's storage layout and values:\n"
+ "\tslither-read-storage $TARGET address --contract-name $NAME --json storage_layout.json --value\n"
+ "TARGET can be a contract address or project directory"
),
)
parser.add_argument(
"contract_source",
help="The deployed contract address if verified on etherscan. Prepend project directory for unverified contracts.",
nargs="+",
)
parser.add_argument(
"--variable-name",
help="The name of the variable whose value will be returned.",
default=None,
)
parser.add_argument("--rpc-url", help="An endpoint for web3 requests.")
parser.add_argument(
"--key",
help="The key/ index whose value will be returned from a mapping or array.",
default=None,
)
parser.add_argument(
"--deep-key",
help="The key/ index whose value will be returned from a deep mapping or multidimensional array.",
default=None,
)
parser.add_argument(
"--struct-var",
help="The name of the variable whose value will be returned from a struct.",
default=None,
)
parser.add_argument(
"--storage-address",
help="The address of the storage contract (if a proxy pattern is used).",
default=None,
)
parser.add_argument(
"--contract-name",
help="The name of the logic contract.",
default=None,
)
parser.add_argument(
"--json",
action="store",
help="Save the result in a JSON file.",
)
parser.add_argument(
"--value",
action="store_true",
help="Toggle used to include values in output.",
)
parser.add_argument(
"--table",
action="store_true",
help="Print table view of storage layout",
)
parser.add_argument(
"--silent",
action="store_true",
help="Silence log outputs",
)
parser.add_argument("--max-depth", help="Max depth to search in data structure.", default=20)
parser.add_argument(
"--block",
help="The block number to read storage from. Requires an archive node to be provided as the RPC url.",
default="latest",
)
cryticparser.init(parser)
return parser.parse_args()
def main() -> None:
args = parse_args()
if len(args.contract_source) == 2:
# Source code is file.sol or project directory
source_code, target = args.contract_source
slither = Slither(source_code, **vars(args))
else:
# Source code is published and retrieved via etherscan
target = args.contract_source[0]
slither = Slither(target, **vars(args))
if args.contract_name:
contracts = slither.get_contract_from_name(args.contract_name)
else:
contracts = slither.contracts
srs = SlitherReadStorage(contracts, args.max_depth)
try:
srs.block = int(args.block)
except ValueError:
srs.block = str(args.block or "latest")
if args.rpc_url:
# Remove target prefix e.g. rinkeby:0x0 -> 0x0.
address = target[target.find(":") + 1 :]
# Default to implementation address unless a storage address is given.
if not args.storage_address:
args.storage_address = address
srs.storage_address = args.storage_address
srs.rpc = args.rpc_url
if args.variable_name:
# Use a lambda func to only return variables that have same name as target.
# x is a tuple (`Contract`, `StateVariable`).
srs.get_all_storage_variables(lambda x: bool(x[1].name == args.variable_name))
srs.get_target_variables(**vars(args))
else:
srs.get_all_storage_variables()
srs.get_storage_layout()
# To retrieve slot values an rpc url is required.
if args.value:
assert args.rpc_url
srs.walk_slot_info(srs.get_slot_values)
if args.table:
srs.walk_slot_info(srs.convert_slot_info_to_rows)
print(srs.table)
if args.json:
with open(args.json, "w", encoding="utf-8") as file:
slot_infos_json = srs.to_json()
json.dump(slot_infos_json, file, indent=4)
if __name__ == "__main__":
main()
| 5,119 | Python | .py | 137 | 29.89781 | 123 | 0.63561 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,078 | read_storage.py | NioTheFirst_ScType/slither/tools/read_storage/read_storage.py | import logging
import sys
from math import floor
from typing import Callable, Optional, Tuple, Union, List, Dict, Any
try:
from web3 import Web3
from eth_typing.evm import ChecksumAddress
from eth_abi import decode_single, encode_abi
from eth_utils import keccak
from .utils import (
get_offset_value,
get_storage_data,
coerce_type,
)
except ImportError:
print("ERROR: in order to use slither-read-storage, you need to install web3")
print("$ pip3 install web3 --user\n")
sys.exit(-1)
import dataclasses
from slither.utils.myprettytable import MyPrettyTable
from slither.core.solidity_types.type import Type
from slither.core.solidity_types import ArrayType, ElementaryType, UserDefinedType, MappingType
from slither.core.declarations import Contract, Structure
from slither.core.variables.state_variable import StateVariable
from slither.core.variables.structure_variable import StructureVariable
logging.basicConfig()
logger = logging.getLogger("Slither-read-storage")
logger.setLevel(logging.INFO)
Elem = Dict[str, "SlotInfo"]
NestedElem = Dict[str, Elem]
@dataclasses.dataclass
class SlotInfo:
name: str
type_string: str
slot: int
size: int
offset: int
value: Optional[Union[int, bool, str, ChecksumAddress]] = None
# For structure and array, str->SlotInfo
elems: Union[Elem, NestedElem] = dataclasses.field(default_factory=lambda: {}) # type: ignore[assignment]
class SlitherReadStorageException(Exception):
pass
# pylint: disable=too-many-instance-attributes
class SlitherReadStorage:
def __init__(self, contracts: List[Contract], max_depth: int) -> None:
self._checksum_address: Optional[ChecksumAddress] = None
self._contracts: List[Contract] = contracts
self._log: str = ""
self._max_depth: int = max_depth
self._slot_info: Dict[str, SlotInfo] = {}
self._target_variables: List[Tuple[Contract, StateVariable]] = []
self._web3: Optional[Web3] = None
self.block: Union[str, int] = "latest"
self.rpc: Optional[str] = None
self.storage_address: Optional[str] = None
self.table: Optional[MyPrettyTable] = None
@property
def contracts(self) -> List[Contract]:
return self._contracts
@property
def max_depth(self) -> int:
return int(self._max_depth)
@property
def log(self) -> str:
return self._log
@log.setter
def log(self, log: str) -> None:
self._log = log
@property
def web3(self) -> Web3:
if not self._web3:
self._web3 = Web3(Web3.HTTPProvider(self.rpc))
return self._web3
@property
def checksum_address(self) -> ChecksumAddress:
if not self.storage_address:
raise ValueError
if not self._checksum_address:
self._checksum_address = self.web3.toChecksumAddress(self.storage_address)
return self._checksum_address
@property
def target_variables(self) -> List[Tuple[Contract, StateVariable]]:
"""Storage variables (not constant or immutable) and their associated contract."""
return self._target_variables
@property
def slot_info(self) -> Dict[str, SlotInfo]:
"""Contains the location, type, size, offset, and value of contract slots."""
return self._slot_info
def get_storage_layout(self) -> None:
"""Retrieves the storage layout of entire contract."""
tmp: Dict[str, SlotInfo] = {}
for contract, var in self.target_variables:
type_ = var.type
info = self.get_storage_slot(var, contract)
if info:
tmp[var.name] = info
if isinstance(type_, UserDefinedType) and isinstance(type_.type, Structure):
tmp[var.name].elems = self._all_struct_slots(var, type_.type, contract)
elif isinstance(type_, ArrayType):
elems = self._all_array_slots(var, contract, type_, info.slot)
tmp[var.name].elems = elems
self._slot_info = tmp
# TODO: remove this pylint exception (montyly)
# pylint: disable=too-many-locals
def get_storage_slot(
self,
target_variable: StateVariable,
contract: Contract,
**kwargs: Any,
) -> Union[SlotInfo, None]:
"""Finds the storage slot of a variable in a given contract.
Args:
target_variable (`StateVariable`): The variable to retrieve the slot for.
contracts (`Contract`): The contract that contains the given state variable.
**kwargs:
key (int): Key of a mapping or index position if an array.
deep_key (int): Key of a mapping embedded within another mapping or
secondary index if array.
struct_var (str): Structure variable name.
Returns:
(`SlotInfo`) | None : A dictionary of the slot information.
"""
key: Optional[int] = kwargs.get("key", None)
deep_key: Optional[int] = kwargs.get("deep_key", None)
struct_var: Optional[str] = kwargs.get("struct_var", None)
info: str
var_log_name = target_variable.name
try:
int_slot, size, offset, type_to = self.get_variable_info(contract, target_variable)
except KeyError:
# Only the child contract of a parent contract will show up in the storage layout when inheritance is used
logger.info(
f"\nContract {contract} not found in storage layout. It is possibly a parent contract\n"
)
return None
slot = int.to_bytes(int_slot, 32, byteorder="big")
target_variable_type = target_variable.type
if isinstance(target_variable_type, ElementaryType):
type_to = target_variable_type.name
elif isinstance(target_variable_type, ArrayType) and key is not None:
var_log_name = f"{var_log_name}[{key}]"
info, type_to, slot, size, offset = self._find_array_slot(
target_variable_type,
slot,
key,
deep_key=deep_key,
struct_var=struct_var,
)
self.log += info
elif isinstance(target_variable_type, UserDefinedType) and struct_var is not None:
var_log_name = f"{var_log_name}.{struct_var}"
target_variable_type_type = target_variable_type.type
assert isinstance(target_variable_type_type, Structure)
elems = target_variable_type_type.elems_ordered
info, type_to, slot, size, offset = self._find_struct_var_slot(elems, slot, struct_var)
self.log += info
elif isinstance(target_variable_type, MappingType) and key:
info, type_to, slot, size, offset = self._find_mapping_slot(
target_variable_type, slot, key, struct_var=struct_var, deep_key=deep_key
)
self.log += info
int_slot = int.from_bytes(slot, byteorder="big")
self.log += f"\nName: {var_log_name}\nType: {type_to}\nSlot: {int_slot}\n"
logger.info(self.log)
self.log = ""
return SlotInfo(
name=var_log_name,
type_string=type_to,
slot=int_slot,
size=size,
offset=offset,
)
def get_target_variables(self, **kwargs) -> None:
"""
Retrieves every instance of a given variable in a list of contracts.
Should be called after setting `target_variables` with `get_all_storage_variables()`.
**kwargs:
key (str): Key of a mapping or index position if an array.
deep_key (str): Key of a mapping embedded within another mapping or secondary index if array.
struct_var (str): Structure variable name.
"""
for contract, var in self.target_variables:
slot_info = self.get_storage_slot(var, contract, **kwargs)
if slot_info:
self._slot_info[f"{contract.name}.{var.name}"] = slot_info
def walk_slot_info(self, func: Callable) -> None:
stack = list(self.slot_info.values())
while stack:
slot_info = stack.pop()
if isinstance(slot_info, dict): # NestedElem
stack.extend(slot_info.values())
elif slot_info.elems:
stack.extend(list(slot_info.elems.values()))
if isinstance(slot_info, SlotInfo):
func(slot_info)
def get_slot_values(self, slot_info: SlotInfo) -> None:
"""Fetches the slot value of `SlotInfo` object
:param slot_info:
"""
hex_bytes = get_storage_data(
self.web3,
self.checksum_address,
int.to_bytes(slot_info.slot, 32, byteorder="big"),
self.block,
)
slot_info.value = self.convert_value_to_type(
hex_bytes, slot_info.size, slot_info.offset, slot_info.type_string
)
logger.info(f"\nValue: {slot_info.value}\n")
def get_all_storage_variables(self, func: Callable = None) -> None:
"""Fetches all storage variables from a list of contracts.
kwargs:
func (Callable, optional): A criteria to filter functions e.g. name.
"""
for contract in self.contracts:
self._target_variables.extend(
filter(
func,
[
(contract, var)
for var in contract.state_variables_ordered
if not var.is_constant and not var.is_immutable
],
)
)
def convert_slot_info_to_rows(self, slot_info: SlotInfo) -> None:
"""Convert and append slot info to table. Create table if it
does not yet exist
:param slot_info:
"""
field_names = [
field.name for field in dataclasses.fields(SlotInfo) if field.name != "elems"
]
if not self.table:
self.table = MyPrettyTable(field_names)
self.table.add_row([getattr(slot_info, field) for field in field_names])
def to_json(self) -> Dict:
return {key: dataclasses.asdict(value) for key, value in self.slot_info.items()}
@staticmethod
def _find_struct_var_slot(
elems: List[StructureVariable], slot_as_bytes: bytes, struct_var: str
) -> Tuple[str, str, bytes, int, int]:
"""Finds the slot of a structure variable.
Args:
elems (List[StructureVariable]): Ordered list of structure variables.
slot_as_bytes (bytes): The slot of the struct to begin searching at.
struct_var (str): The target structure variable.
Returns:
info (str): Info about the target variable to log.
type_to (str): The type of the target variable.
slot (bytes): The storage location of the target variable.
size (int): The size (in bits) of the target variable.
offset (int): The size of other variables that share the same slot.
"""
slot = int.from_bytes(slot_as_bytes, "big")
offset = 0
type_to = ""
for var in elems:
var_type = var.type
if isinstance(var_type, ElementaryType):
size = var_type.size
if offset >= 256:
slot += 1
offset = 0
if struct_var == var.name:
type_to = var_type.name
break # found struct var
offset += size
else:
logger.info(f"{type(var_type)} is current not implemented in _find_struct_var_slot")
slot_as_bytes = int.to_bytes(slot, 32, byteorder="big")
info = f"\nStruct Variable: {struct_var}"
return info, type_to, slot_as_bytes, size, offset
# pylint: disable=too-many-branches,too-many-statements
@staticmethod
def _find_array_slot(
target_variable_type: ArrayType,
slot: bytes,
key: int,
deep_key: int = None,
struct_var: str = None,
) -> Tuple[str, str, bytes, int, int]:
"""Finds the slot of array's index.
Args:
target_variable (`StateVariable`): The array that contains the target variable.
slot (bytes): The starting slot of the array.
key (int): The target variable's index position.
deep_key (int, optional): Secondary index if nested array.
struct_var (str, optional): Structure variable name.
Returns:
info (str): Info about the target variable to log.
type_to (str): The type of the target variable.
slot (bytes): The storage location of the target variable.
size (int): The size
offset (int): The offset
"""
info = f"\nKey: {key}"
offset = 0
size = 256
target_variable_type_type = target_variable_type.type
if isinstance(
target_variable_type_type, ArrayType
): # multidimensional array uint[i][], , uint[][i], or uint[][]
assert isinstance(target_variable_type_type.type, ElementaryType)
size = target_variable_type_type.type.size
type_to = target_variable_type_type.type.name
if target_variable_type.is_fixed_array: # uint[][i]
slot_int = int.from_bytes(slot, "big") + int(key)
else:
slot = keccak(slot)
key = int(key)
if target_variable_type_type.is_fixed_array: # arr[i][]
key *= int(str(target_variable_type_type.length))
slot_int = int.from_bytes(slot, "big") + key
if not deep_key:
return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset
info += f"\nDeep Key: {deep_key}"
if target_variable_type_type.is_dynamic_array: # uint[][]
# keccak256(keccak256(slot) + index) + floor(j / floor(256 / size))
slot = keccak(int.to_bytes(slot_int, 32, "big"))
slot_int = int.from_bytes(slot, "big")
# keccak256(slot) + index + floor(j / floor(256 / size))
slot_int += floor(int(deep_key) / floor(256 / size)) # uint[i][]
elif target_variable_type.is_fixed_array:
slot_int = int.from_bytes(slot, "big") + int(key)
if isinstance(target_variable_type_type, UserDefinedType) and isinstance(
target_variable_type_type.type, Structure
): # struct[i]
type_to = target_variable_type_type.type.name
if not struct_var:
return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset
elems = target_variable_type_type.type.elems_ordered
slot = int.to_bytes(slot_int, 32, byteorder="big")
info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot(
elems, slot, struct_var
)
info += info_tmp
else:
assert isinstance(target_variable_type_type, ElementaryType)
type_to = target_variable_type_type.name
size = target_variable_type_type.size # bits
elif isinstance(target_variable_type_type, UserDefinedType) and isinstance(
target_variable_type_type.type, Structure
): # struct[]
slot = keccak(slot)
slot_int = int.from_bytes(slot, "big") + int(key)
type_to = target_variable_type_type.type.name
if not struct_var:
return info, type_to, int.to_bytes(slot_int, 32, "big"), size, offset
elems = target_variable_type_type.type.elems_ordered
slot = int.to_bytes(slot_int, 32, byteorder="big")
info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot(
elems, slot, struct_var
)
info += info_tmp
else:
assert isinstance(target_variable_type_type, ElementaryType)
slot = keccak(slot)
slot_int = int.from_bytes(slot, "big") + int(key)
type_to = target_variable_type_type.name
size = target_variable_type_type.size # bits
slot = int.to_bytes(slot_int, 32, byteorder="big")
return info, type_to, slot, size, offset
@staticmethod
def _find_mapping_slot(
target_variable_type: MappingType,
slot: bytes,
key: Union[int, str],
deep_key: Union[int, str] = None,
struct_var: str = None,
) -> Tuple[str, str, bytes, int, int]:
"""Finds the data slot of a target variable within a mapping.
target_variable (`StateVariable`): The mapping that contains the target variable.
slot (bytes): The starting slot of the mapping.
key (Union[int, str]): The key the variable is stored at.
deep_key (int, optional): Key of a mapping embedded within another mapping.
struct_var (str, optional): Structure variable name.
:returns:
log (str): Info about the target variable to log.
type_to (str): The type of the target variable.
slot (bytes): The storage location of the target variable.
size (int): The size (in bits) of the target variable.
offset (int): The size of other variables that share the same slot.
"""
info = ""
offset = 0
if key:
info += f"\nKey: {key}"
if deep_key:
info += f"\nDeep Key: {deep_key}"
assert isinstance(target_variable_type.type_from, ElementaryType)
key_type = target_variable_type.type_from.name
assert key
if "int" in key_type: # without this eth_utils encoding fails
key = int(key)
key = coerce_type(key_type, key)
slot = keccak(encode_abi([key_type, "uint256"], [key, decode_single("uint256", slot)]))
if isinstance(target_variable_type.type_to, UserDefinedType) and isinstance(
target_variable_type.type_to.type, Structure
): # mapping(elem => struct)
assert struct_var
elems = target_variable_type.type_to.type.elems_ordered
info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot(
elems, slot, struct_var
)
info += info_tmp
elif isinstance(
target_variable_type.type_to, MappingType
): # mapping(elem => mapping(elem => ???))
assert deep_key
assert isinstance(target_variable_type.type_to.type_from, ElementaryType)
key_type = target_variable_type.type_to.type_from.name
if "int" in key_type: # without this eth_utils encoding fails
deep_key = int(deep_key)
# If deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))
slot = keccak(encode_abi([key_type, "bytes32"], [deep_key, slot]))
# mapping(elem => mapping(elem => elem))
target_variable_type_type_to_type_to = target_variable_type.type_to.type_to
assert isinstance(
target_variable_type_type_to_type_to, (UserDefinedType, ElementaryType)
)
type_to = str(target_variable_type_type_to_type_to.type)
byte_size, _ = target_variable_type_type_to_type_to.storage_size
size = byte_size * 8 # bits
offset = 0
if isinstance(target_variable_type_type_to_type_to, UserDefinedType) and isinstance(
target_variable_type_type_to_type_to.type, Structure
): # mapping(elem => mapping(elem => struct))
assert struct_var
elems = target_variable_type_type_to_type_to.type.elems_ordered
# If map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth);
info_tmp, type_to, slot, size, offset = SlitherReadStorage._find_struct_var_slot(
elems, slot, struct_var
)
info += info_tmp
# TODO: suppory mapping with dynamic arrays
# mapping(elem => elem)
elif isinstance(target_variable_type.type_to, ElementaryType):
type_to = target_variable_type.type_to.name # the value's elementary type
byte_size, _ = target_variable_type.type_to.storage_size
size = byte_size * 8 # bits
else:
raise NotImplementedError(
f"{target_variable_type} => {target_variable_type.type_to} not implemented"
)
return info, type_to, slot, size, offset
@staticmethod
def get_variable_info(
contract: Contract, target_variable: StateVariable
) -> Tuple[int, int, int, str]:
"""Return slot, size, offset, and type."""
assert isinstance(target_variable.type, Type)
type_to = str(target_variable.type)
byte_size, _ = target_variable.type.storage_size
size = byte_size * 8 # bits
(int_slot, offset) = contract.compilation_unit.storage_layout_of(contract, target_variable)
offset *= 8 # bits
logger.info(
f"\nContract '{contract.name}'\n{target_variable.canonical_name} with type {target_variable.type} is located at slot: {int_slot}\n"
)
return int_slot, size, offset, type_to
@staticmethod
def convert_value_to_type(
hex_bytes: bytes, size: int, offset: int, type_to: str
) -> Union[int, bool, str, ChecksumAddress]:
"""Convert slot data to type representation."""
# Account for storage packing
offset_hex_bytes = get_offset_value(hex_bytes, offset, size)
try:
value = coerce_type(type_to, offset_hex_bytes)
except ValueError:
return coerce_type("int", offset_hex_bytes)
return value
def _all_struct_slots(
self, var: StateVariable, st: Structure, contract: Contract, key: Optional[int] = None
) -> Elem:
"""Retrieves all members of a struct."""
struct_elems = st.elems_ordered
data: Elem = {}
for elem in struct_elems:
info = self.get_storage_slot(
var,
contract,
key=key,
struct_var=elem.name,
)
if info:
data[elem.name] = info
return data
# pylint: disable=too-many-nested-blocks
def _all_array_slots(
self, var: StateVariable, contract: Contract, type_: ArrayType, slot: int
) -> Union[Elem, NestedElem]:
"""Retrieves all members of an array."""
array_length = self._get_array_length(type_, slot)
target_variable_type = type_.type
if isinstance(target_variable_type, UserDefinedType) and isinstance(
target_variable_type.type, Structure
):
nested_elems: NestedElem = {}
for i in range(min(array_length, self.max_depth)):
nested_elems[str(i)] = self._all_struct_slots(
var, target_variable_type.type, contract, key=i
)
return nested_elems
elems: Elem = {}
for i in range(min(array_length, self.max_depth)):
info = self.get_storage_slot(
var,
contract,
key=str(i),
)
if info:
elems[str(i)] = info
if isinstance(target_variable_type, ArrayType): # multidimensional array
array_length = self._get_array_length(target_variable_type, info.slot)
for j in range(min(array_length, self.max_depth)):
info = self.get_storage_slot(
var,
contract,
key=str(i),
deep_key=str(j),
)
if info:
elems[str(i)].elems[str(j)] = info
return elems
def _get_array_length(self, type_: Type, slot: int) -> int:
"""Gets the length of dynamic and fixed arrays.
Args:
type_ (`AbstractType`): The array type.
slot (int): Slot a dynamic array's length is stored at.
Returns:
(int): The length of the array.
"""
val = 0
if self.rpc:
# The length of dynamic arrays is stored at the starting slot.
# Convert from hexadecimal to decimal.
val = int(
get_storage_data(
self.web3,
self.checksum_address,
int.to_bytes(slot, 32, byteorder="big"),
self.block,
).hex(),
16,
)
if isinstance(type_, ArrayType):
if type_.is_fixed_array:
val = int(str(type_.length))
return val
| 25,335 | Python | .py | 551 | 34.61343 | 147 | 0.587785 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,079 | utils.py | NioTheFirst_ScType/slither/tools/read_storage/utils/utils.py | from typing import Union
from eth_typing.evm import ChecksumAddress
from eth_utils import to_int, to_text, to_checksum_address
def get_offset_value(hex_bytes: bytes, offset: int, size: int) -> bytes:
"""
Trims slot data to only contain the target variable's.
Args:
hex_bytes (HexBytes): String representation of type
offset (int): The size (in bits) of other variables that share the same slot.
size (int): The size (in bits) of the target variable.
Returns:
(bytes): The target variable's trimmed data.
"""
size = int(size / 8)
offset = int(offset / 8)
if offset == 0:
value = hex_bytes[-size:]
else:
start = size + offset
value = hex_bytes[-start:-offset]
return value
def coerce_type(
solidity_type: str, value: Union[int, str, bytes]
) -> Union[int, bool, str, ChecksumAddress]:
"""
Converts input to the indicated type.
Args:
solidity_type (str): String representation of type.
value (bytes): The value to be converted.
Returns:
(Union[int, bool, str, ChecksumAddress, hex]): The type representation of the value.
"""
if "int" in solidity_type:
return to_int(value)
if "bool" in solidity_type:
return bool(to_int(value))
if "string" in solidity_type and isinstance(value, bytes):
# length * 2 is stored in lower end bits
# TODO handle bytes and strings greater than 32 bytes
length = int(int.from_bytes(value[-2:], "big") / 2)
return to_text(value[:length])
if "address" in solidity_type:
if not isinstance(value, (str, bytes)):
raise TypeError
return to_checksum_address(value)
if not isinstance(value, bytes):
raise TypeError
return value.hex()
def get_storage_data(
web3, checksum_address: ChecksumAddress, slot: bytes, block: Union[int, str]
) -> bytes:
"""
Retrieves the storage data from the blockchain at target address and slot.
Args:
web3: Web3 instance provider.
checksum_address (ChecksumAddress): The address to query.
slot (bytes): The slot to retrieve data from.
block (optional int|str): The block number to retrieve data from
Returns:
(HexBytes): The slot's storage data.
"""
return bytes(web3.eth.get_storage_at(checksum_address, slot, block)).rjust(
32, bytes(1)
) # pad to 32 bytes
| 2,448 | Python | .py | 64 | 31.921875 | 92 | 0.655158 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,080 | slither_compilation_unit_solc.py | NioTheFirst_ScType/slither/solc_parsing/slither_compilation_unit_solc.py | import json
import logging
import os
import re
from pathlib import Path
from typing import List, Dict
from slither.analyses.data_dependency.data_dependency import compute_dependency
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.declarations import Contract
from slither.core.declarations.custom_error_top_level import CustomErrorTopLevel
from slither.core.declarations.enum_top_level import EnumTopLevel
from slither.core.declarations.function_top_level import FunctionTopLevel
from slither.core.declarations.import_directive import Import
from slither.core.declarations.pragma_directive import Pragma
from slither.core.declarations.structure_top_level import StructureTopLevel
from slither.core.declarations.using_for_top_level import UsingForTopLevel
from slither.core.scope.scope import FileScope
from slither.core.solidity_types import ElementaryType, TypeAliasTopLevel
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.exceptions import SlitherException
from slither.solc_parsing.declarations.contract import ContractSolc
from slither.solc_parsing.declarations.custom_error import CustomErrorSolc
from slither.solc_parsing.declarations.function import FunctionSolc
from slither.solc_parsing.declarations.structure_top_level import StructureTopLevelSolc
from slither.solc_parsing.declarations.using_for_top_level import UsingForTopLevelSolc
from slither.solc_parsing.exceptions import VariableNotFound
from slither.solc_parsing.variables.top_level_variable import TopLevelVariableSolc
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
logging.basicConfig()
logger = logging.getLogger("SlitherSolcParsing")
logger.setLevel(logging.INFO)
def _handle_import_aliases(
symbol_aliases: Dict, import_directive: Import, scope: FileScope
) -> None:
"""
Handle the parsing of import aliases
Args:
symbol_aliases (Dict): json dict from solc
import_directive (Import): current import directive
scope (FileScope): current file scape
Returns:
"""
for symbol_alias in symbol_aliases:
if "foreign" in symbol_alias and "local" in symbol_alias:
if isinstance(symbol_alias["foreign"], dict) and "name" in symbol_alias["foreign"]:
original_name = symbol_alias["foreign"]["name"]
local_name = symbol_alias["local"]
import_directive.renaming[local_name] = original_name
# Assuming that two imports cannot collide in renaming
scope.renaming[local_name] = original_name
# This path should only be hit for the malformed AST of solc 0.5.12 where
# the foreign identifier cannot be found but is required to resolve the alias.
# see https://github.com/crytic/slither/issues/1319
elif symbol_alias["local"]:
raise SlitherException(
"Cannot resolve local alias for import directive due to malformed AST. Please upgrade to solc 0.6.0 or higher."
)
class SlitherCompilationUnitSolc(CallerContextExpression):
# pylint: disable=no-self-use,too-many-instance-attributes
def __init__(self, compilation_unit: SlitherCompilationUnit):
super().__init__()
self._contracts_by_id: Dict[int, ContractSolc] = {}
self._parsed = False
self._analyzed = False
self._underlying_contract_to_parser: Dict[Contract, ContractSolc] = {}
self._structures_top_level_parser: List[StructureTopLevelSolc] = []
self._custom_error_parser: List[CustomErrorSolc] = []
self._variables_top_level_parser: List[TopLevelVariableSolc] = []
self._functions_top_level_parser: List[FunctionSolc] = []
self._using_for_top_level_parser: List[UsingForTopLevelSolc] = []
self._is_compact_ast = False
# self._core: SlitherCore = core
self._compilation_unit = compilation_unit
self._all_functions_and_modifier_parser: List[FunctionSolc] = []
self._top_level_contracts_counter = 0
@property
def compilation_unit(self) -> SlitherCompilationUnit:
return self._compilation_unit
@property
def all_functions_and_modifiers_parser(self) -> List[FunctionSolc]:
return self._all_functions_and_modifier_parser
def add_function_or_modifier_parser(self, f: FunctionSolc):
self._all_functions_and_modifier_parser.append(f)
@property
def underlying_contract_to_parser(self) -> Dict[Contract, ContractSolc]:
return self._underlying_contract_to_parser
@property
def slither_parser(self) -> "SlitherCompilationUnitSolc":
return self
###################################################################################
###################################################################################
# region AST
###################################################################################
###################################################################################
def get_key(self) -> str:
if self._is_compact_ast:
return "nodeType"
return "name"
def get_children(self) -> str:
if self._is_compact_ast:
return "nodes"
return "children"
@property
def is_compact_ast(self) -> bool:
return self._is_compact_ast
# endregion
###################################################################################
###################################################################################
# region Parsing
###################################################################################
###################################################################################
def parse_top_level_from_json(self, json_data: str) -> bool:
try:
data_loaded = json.loads(json_data)
# Truffle AST
if "ast" in data_loaded:
self.parse_top_level_from_loaded_json(data_loaded["ast"], data_loaded["sourcePath"])
return True
# solc AST, where the non-json text was removed
if "attributes" in data_loaded:
filename = data_loaded["attributes"]["absolutePath"]
else:
filename = data_loaded["absolutePath"]
self.parse_top_level_from_loaded_json(data_loaded, filename)
return True
except ValueError:
first = json_data.find("{")
if first != -1:
last = json_data.rfind("}") + 1
filename = json_data[0:first]
json_data = json_data[first:last]
data_loaded = json.loads(json_data)
self.parse_top_level_from_loaded_json(data_loaded, filename)
return True
return False
def _parse_enum(self, top_level_data: Dict, filename: str):
if self.is_compact_ast:
name = top_level_data["name"]
canonicalName = top_level_data["canonicalName"]
else:
name = top_level_data["attributes"][self.get_key()]
if "canonicalName" in top_level_data["attributes"]:
canonicalName = top_level_data["attributes"]["canonicalName"]
else:
canonicalName = name
values = []
children = (
top_level_data["members"]
if "members" in top_level_data
else top_level_data.get("children", [])
)
for child in children:
assert child[self.get_key()] == "EnumValue"
if self.is_compact_ast:
values.append(child["name"])
else:
values.append(child["attributes"][self.get_key()])
scope = self.compilation_unit.get_scope(filename)
enum = EnumTopLevel(name, canonicalName, values, scope)
scope.enums[name] = enum
enum.set_offset(top_level_data["src"], self._compilation_unit)
self._compilation_unit.enums_top_level.append(enum)
def parse_top_level_from_loaded_json(
self, data_loaded: Dict, filename: str
): # pylint: disable=too-many-branches,too-many-statements,too-many-locals
if "nodeType" in data_loaded:
self._is_compact_ast = True
if "sourcePaths" in data_loaded:
for sourcePath in data_loaded["sourcePaths"]:
if os.path.isfile(sourcePath):
self._compilation_unit.core.add_source_code(sourcePath)
if data_loaded[self.get_key()] == "root":
logger.error("solc <0.4 is not supported")
return
if data_loaded[self.get_key()] == "SourceUnit":
self._parse_source_unit(data_loaded, filename)
else:
logger.error("solc version is not supported")
return
if self.get_children() not in data_loaded:
return
scope = self.compilation_unit.get_scope(filename)
for top_level_data in data_loaded[self.get_children()]:
if top_level_data[self.get_key()] == "ContractDefinition":
contract = Contract(self._compilation_unit, scope)
contract_parser = ContractSolc(self, contract, top_level_data)
scope.contracts[contract.name] = contract
if "src" in top_level_data:
contract.set_offset(top_level_data["src"], self._compilation_unit)
self._underlying_contract_to_parser[contract] = contract_parser
elif top_level_data[self.get_key()] == "PragmaDirective":
if self._is_compact_ast:
pragma = Pragma(top_level_data["literals"], scope)
scope.pragmas.add(pragma)
else:
pragma = Pragma(top_level_data["attributes"]["literals"], scope)
scope.pragmas.add(pragma)
pragma.set_offset(top_level_data["src"], self._compilation_unit)
self._compilation_unit.pragma_directives.append(pragma)
elif top_level_data[self.get_key()] == "UsingForDirective":
scope = self.compilation_unit.get_scope(filename)
usingFor = UsingForTopLevel(scope)
usingFor_parser = UsingForTopLevelSolc(usingFor, top_level_data, self)
usingFor.set_offset(top_level_data["src"], self._compilation_unit)
scope.using_for_directives.add(usingFor)
self._compilation_unit.using_for_top_level.append(usingFor)
self._using_for_top_level_parser.append(usingFor_parser)
elif top_level_data[self.get_key()] == "ImportDirective":
if self.is_compact_ast:
import_directive = Import(
Path(
top_level_data["absolutePath"],
),
scope,
)
scope.imports.add(import_directive)
# TODO investigate unitAlias in version < 0.7 and legacy ast
if "unitAlias" in top_level_data:
import_directive.alias = top_level_data["unitAlias"]
if "symbolAliases" in top_level_data:
symbol_aliases = top_level_data["symbolAliases"]
_handle_import_aliases(symbol_aliases, import_directive, scope)
else:
import_directive = Import(
Path(
top_level_data["attributes"].get("absolutePath", ""),
),
scope,
)
scope.imports.add(import_directive)
# TODO investigate unitAlias in version < 0.7 and legacy ast
if (
"attributes" in top_level_data
and "unitAlias" in top_level_data["attributes"]
):
import_directive.alias = top_level_data["attributes"]["unitAlias"]
import_directive.set_offset(top_level_data["src"], self._compilation_unit)
self._compilation_unit.import_directives.append(import_directive)
get_imported_scope = self.compilation_unit.get_scope(import_directive.filename)
scope.accessible_scopes.append(get_imported_scope)
elif top_level_data[self.get_key()] == "StructDefinition":
st = StructureTopLevel(self.compilation_unit, scope)
st.set_offset(top_level_data["src"], self._compilation_unit)
st_parser = StructureTopLevelSolc(st, top_level_data, self)
scope.structures[st.name] = st
self._compilation_unit.structures_top_level.append(st)
self._structures_top_level_parser.append(st_parser)
elif top_level_data[self.get_key()] == "EnumDefinition":
# Note enum don't need a complex parser, so everything is directly done
self._parse_enum(top_level_data, filename)
elif top_level_data[self.get_key()] == "VariableDeclaration":
var = TopLevelVariable(scope)
var_parser = TopLevelVariableSolc(var, top_level_data, self)
var.set_offset(top_level_data["src"], self._compilation_unit)
self._compilation_unit.variables_top_level.append(var)
self._variables_top_level_parser.append(var_parser)
scope.variables[var.name] = var
elif top_level_data[self.get_key()] == "FunctionDefinition":
func = FunctionTopLevel(self._compilation_unit, scope)
scope.functions.add(func)
func.set_offset(top_level_data["src"], self._compilation_unit)
func_parser = FunctionSolc(func, top_level_data, None, self)
self._compilation_unit.functions_top_level.append(func)
self._functions_top_level_parser.append(func_parser)
self.add_function_or_modifier_parser(func_parser)
elif top_level_data[self.get_key()] == "ErrorDefinition":
custom_error = CustomErrorTopLevel(self._compilation_unit, scope)
custom_error.set_offset(top_level_data["src"], self._compilation_unit)
custom_error_parser = CustomErrorSolc(custom_error, top_level_data, self)
scope.custom_errors.add(custom_error)
self._compilation_unit.custom_errors.append(custom_error)
self._custom_error_parser.append(custom_error_parser)
elif top_level_data[self.get_key()] == "UserDefinedValueTypeDefinition":
assert "name" in top_level_data
alias = top_level_data["name"]
assert "underlyingType" in top_level_data
underlying_type = top_level_data["underlyingType"]
assert (
"nodeType" in underlying_type
and underlying_type["nodeType"] == "ElementaryTypeName"
)
assert "name" in underlying_type
original_type = ElementaryType(underlying_type["name"])
user_defined_type = TypeAliasTopLevel(original_type, alias, scope)
user_defined_type.set_offset(top_level_data["src"], self._compilation_unit)
self._compilation_unit.user_defined_value_types[alias] = user_defined_type
scope.user_defined_types[alias] = user_defined_type
else:
raise SlitherException(f"Top level {top_level_data[self.get_key()]} not supported")
def _parse_source_unit(self, data: Dict, filename: str):
if data[self.get_key()] != "SourceUnit":
return # handle solc prior 0.3.6
# match any char for filename
# filename can contain space, /, -, ..
name_candidates = re.findall("=+ (.+) =+", filename)
if name_candidates:
assert len(name_candidates) == 1
name: str = name_candidates[0]
else:
name = filename
sourceUnit = -1 # handle old solc, or error
if "src" in data:
sourceUnit_candidates = re.findall("[0-9]*:[0-9]*:([0-9]*)", data["src"])
if len(sourceUnit_candidates) == 1:
sourceUnit = int(sourceUnit_candidates[0])
if sourceUnit == -1:
# if source unit is not found
# We can still deduce it, by assigning to the last source_code added
# This works only for crytic compile.
# which used --combined-json ast, rather than --ast-json
# As a result -1 is not used as index
if self._compilation_unit.core.crytic_compile is not None:
sourceUnit = len(self._compilation_unit.core.source_code)
self._compilation_unit.source_units[sourceUnit] = name
if os.path.isfile(name) and not name in self._compilation_unit.core.source_code:
self._compilation_unit.core.add_source_code(name)
else:
lib_name = os.path.join("node_modules", name)
if os.path.isfile(lib_name) and not name in self._compilation_unit.core.source_code:
self._compilation_unit.core.add_source_code(lib_name)
# endregion
###################################################################################
###################################################################################
# region Analyze
###################################################################################
###################################################################################
@property
def parsed(self) -> bool:
return self._parsed
@property
def analyzed(self) -> bool:
return self._analyzed
def parse_contracts(self): # pylint: disable=too-many-statements,too-many-branches
if not self._underlying_contract_to_parser:
logger.info(
f"No contract were found in {self._compilation_unit.core.filename}, check the correct compilation"
)
if self._parsed:
raise Exception("Contract analysis can be run only once!")
# First we save all the contracts in a dict
# the key is the contractid
for contract in self._underlying_contract_to_parser:
if (
contract.name.startswith("SlitherInternalTopLevelContract")
and not contract.is_top_level
):
raise SlitherException(
# region multi-line-string
"""Your codebase has a contract named 'SlitherInternalTopLevelContract'.
Please rename it, this name is reserved for Slither's internals"""
# endregion multi-line
)
self._contracts_by_id[contract.id] = contract
self._compilation_unit.contracts.append(contract)
# Update of the inheritance
for contract_parser in self._underlying_contract_to_parser.values():
# remove the first elem in linearizedBaseContracts as it is the contract itself
ancestors = []
fathers = []
father_constructors = []
# try:
# Resolve linearized base contracts.
missing_inheritance = None
for i in contract_parser.linearized_base_contracts[1:]:
if i in contract_parser.remapping:
contract_name = contract_parser.remapping[i]
if contract_name in contract_parser.underlying_contract.file_scope.renaming:
contract_name = contract_parser.underlying_contract.file_scope.renaming[
contract_name
]
target = contract_parser.underlying_contract.file_scope.get_contract_from_name(
contract_name
)
assert target
ancestors.append(target)
elif i in self._contracts_by_id:
ancestors.append(self._contracts_by_id[i])
else:
missing_inheritance = i
# Resolve immediate base contracts
for i in contract_parser.baseContracts:
if i in contract_parser.remapping:
fathers.append(
contract_parser.underlying_contract.file_scope.get_contract_from_name(
contract_parser.remapping[i]
)
# self._compilation_unit.get_contract_from_name(contract_parser.remapping[i])
)
elif i in self._contracts_by_id:
fathers.append(self._contracts_by_id[i])
else:
missing_inheritance = i
# Resolve immediate base constructor calls
for i in contract_parser.baseConstructorContractsCalled:
if i in contract_parser.remapping:
father_constructors.append(
contract_parser.underlying_contract.file_scope.get_contract_from_name(
contract_parser.remapping[i]
)
# self._compilation_unit.get_contract_from_name(contract_parser.remapping[i])
)
elif i in self._contracts_by_id:
father_constructors.append(self._contracts_by_id[i])
else:
missing_inheritance = i
contract_parser.underlying_contract.set_inheritance(
ancestors, fathers, father_constructors
)
if missing_inheritance:
self._compilation_unit.contracts_with_missing_inheritance.add(
contract_parser.underlying_contract
)
txt = f"Missing inheritance {contract_parser.underlying_contract} ({contract_parser.compilation_unit.crytic_compile_compilation_unit.unique_id})\n"
txt += f"Missing inheritance ID: {missing_inheritance}\n"
if contract_parser.underlying_contract.inheritance:
txt += "Inheritance found:\n"
for contract_inherited in contract_parser.underlying_contract.inheritance:
txt += f"\t - {contract_inherited} (ID {contract_inherited.id})\n"
contract_parser.log_incorrect_parsing(txt)
contract_parser.set_is_analyzed(True)
contract_parser.delete_content()
contracts_to_be_analyzed = list(self._underlying_contract_to_parser.values())
# Any contract can refer another contract enum without need for inheritance
self._analyze_all_enums(contracts_to_be_analyzed)
# pylint: disable=expression-not-assigned
[c.set_is_analyzed(False) for c in self._underlying_contract_to_parser.values()]
libraries = [
c for c in contracts_to_be_analyzed if c.underlying_contract.contract_kind == "library"
]
contracts_to_be_analyzed = [
c for c in contracts_to_be_analyzed if c.underlying_contract.contract_kind != "library"
]
# We first parse the struct/variables/functions/contract
self._analyze_first_part(contracts_to_be_analyzed, libraries)
# pylint: disable=expression-not-assigned
[c.set_is_analyzed(False) for c in self._underlying_contract_to_parser.values()]
# We analyze the struct and parse and analyze the events
# A contract can refer in the variables a struct or a event from any contract
# (without inheritance link)
self._analyze_second_part(contracts_to_be_analyzed, libraries)
[c.set_is_analyzed(False) for c in self._underlying_contract_to_parser.values()]
# Then we analyse state variables, functions and modifiers
self._analyze_third_part(contracts_to_be_analyzed, libraries)
[c.set_is_analyzed(False) for c in self._underlying_contract_to_parser.values()]
self._analyze_using_for(contracts_to_be_analyzed, libraries)
self._parsed = True
def analyze_contracts(self): # pylint: disable=too-many-statements,too-many-branches
if not self._parsed:
raise SlitherException("Parse the contract before running analyses")
self._convert_to_slithir()
compute_dependency(self._compilation_unit)
self._compilation_unit.compute_storage_layout()
self._analyzed = True
def _analyze_all_enums(self, contracts_to_be_analyzed: List[ContractSolc]):
while contracts_to_be_analyzed:
contract = contracts_to_be_analyzed[0]
contracts_to_be_analyzed = contracts_to_be_analyzed[1:]
all_father_analyzed = all(
self._underlying_contract_to_parser[father].is_analyzed
for father in contract.underlying_contract.inheritance
)
if not contract.underlying_contract.inheritance or all_father_analyzed:
self._analyze_enums(contract)
else:
contracts_to_be_analyzed += [contract]
def _analyze_first_part(
self,
contracts_to_be_analyzed: List[ContractSolc],
libraries: List[ContractSolc],
):
for lib in libraries:
self._parse_struct_var_modifiers_functions(lib)
# Start with the contracts without inheritance
# Analyze a contract only if all its fathers
# Were analyzed
while contracts_to_be_analyzed:
contract = contracts_to_be_analyzed[0]
contracts_to_be_analyzed = contracts_to_be_analyzed[1:]
all_father_analyzed = all(
self._underlying_contract_to_parser[father].is_analyzed
for father in contract.underlying_contract.inheritance
)
if not contract.underlying_contract.inheritance or all_father_analyzed:
self._parse_struct_var_modifiers_functions(contract)
else:
contracts_to_be_analyzed += [contract]
def _analyze_second_part(
self,
contracts_to_be_analyzed: List[ContractSolc],
libraries: List[ContractSolc],
):
for lib in libraries:
self._analyze_struct_events(lib)
self._analyze_top_level_variables()
self._analyze_top_level_structures()
# Start with the contracts without inheritance
# Analyze a contract only if all its fathers
# Were analyzed
while contracts_to_be_analyzed:
contract = contracts_to_be_analyzed[0]
contracts_to_be_analyzed = contracts_to_be_analyzed[1:]
all_father_analyzed = all(
self._underlying_contract_to_parser[father].is_analyzed
for father in contract.underlying_contract.inheritance
)
if not contract.underlying_contract.inheritance or all_father_analyzed:
self._analyze_struct_events(contract)
else:
contracts_to_be_analyzed += [contract]
def _analyze_third_part(
self,
contracts_to_be_analyzed: List[ContractSolc],
libraries: List[ContractSolc],
):
for lib in libraries:
self._analyze_variables_modifiers_functions(lib)
# Start with the contracts without inheritance
# Analyze a contract only if all its fathers
# Were analyzed
while contracts_to_be_analyzed:
contract = contracts_to_be_analyzed[0]
contracts_to_be_analyzed = contracts_to_be_analyzed[1:]
all_father_analyzed = all(
self._underlying_contract_to_parser[father].is_analyzed
for father in contract.underlying_contract.inheritance
)
if not contract.underlying_contract.inheritance or all_father_analyzed:
self._analyze_variables_modifiers_functions(contract)
else:
contracts_to_be_analyzed += [contract]
def _analyze_using_for(
self, contracts_to_be_analyzed: List[ContractSolc], libraries: List[ContractSolc]
):
self._analyze_top_level_using_for()
for lib in libraries:
lib.analyze_using_for()
while contracts_to_be_analyzed:
contract = contracts_to_be_analyzed[0]
contracts_to_be_analyzed = contracts_to_be_analyzed[1:]
all_father_analyzed = all(
self._underlying_contract_to_parser[father].is_analyzed
for father in contract.underlying_contract.inheritance
)
if not contract.underlying_contract.inheritance or all_father_analyzed:
contract.analyze_using_for()
contract.set_is_analyzed(True)
else:
contracts_to_be_analyzed += [contract]
def _analyze_enums(self, contract: ContractSolc):
# Enum must be analyzed first
contract.analyze_enums()
contract.set_is_analyzed(True)
def _parse_struct_var_modifiers_functions(self, contract: ContractSolc):
contract.parse_structs() # struct can refer another struct
contract.parse_state_variables()
contract.parse_modifiers()
contract.parse_functions()
contract.parse_custom_errors()
contract.set_is_analyzed(True)
def _analyze_struct_events(self, contract: ContractSolc):
contract.analyze_constant_state_variables()
# Struct can refer to enum, or state variables
contract.analyze_structs()
# Event can refer to struct
contract.analyze_events()
contract.analyze_custom_errors()
contract.set_is_analyzed(True)
def _analyze_top_level_structures(self):
try:
for struct in self._structures_top_level_parser:
struct.analyze()
except (VariableNotFound, KeyError) as e:
raise SlitherException(f"Missing struct {e} during top level structure analyze") from e
def _analyze_top_level_variables(self):
try:
for var in self._variables_top_level_parser:
var.analyze(var)
except (VariableNotFound, KeyError) as e:
raise SlitherException(f"Missing {e} during variable analyze") from e
def _analyze_params_top_level_function(self):
for func_parser in self._functions_top_level_parser:
func_parser.analyze_params()
self._compilation_unit.add_function(func_parser.underlying_function)
def _analyze_top_level_using_for(self):
for using_for in self._using_for_top_level_parser:
using_for.analyze()
def _analyze_params_custom_error(self):
for custom_error_parser in self._custom_error_parser:
custom_error_parser.analyze_params()
def _analyze_content_top_level_function(self):
try:
for func_parser in self._functions_top_level_parser:
func_parser.analyze_content()
except (VariableNotFound, KeyError) as e:
raise SlitherException(f"Missing {e} during top level function analyze") from e
def _analyze_variables_modifiers_functions(self, contract: ContractSolc):
# State variables, modifiers and functions can refer to anything
contract.analyze_params_modifiers()
contract.analyze_params_functions()
self._analyze_params_top_level_function()
self._analyze_params_custom_error()
contract.analyze_state_variables()
contract.analyze_content_modifiers()
contract.analyze_content_functions()
self._analyze_content_top_level_function()
contract.set_is_analyzed(True)
def _convert_to_slithir(self):
for contract in self._compilation_unit.contracts:
contract.add_constructor_variables()
for func in contract.functions + contract.modifiers:
try:
func.generate_slithir_and_analyze()
except AttributeError as e:
# This can happens for example if there is a call to an interface
# And the interface is redefined due to contract's name reuse
# But the available version misses some functions
self._underlying_contract_to_parser[contract].log_incorrect_parsing(
f"Impossible to generate IR for {contract.name}.{func.name} ({func.source_mapping}):\n {e}"
)
contract.convert_expression_to_slithir_ssa()
for func in self._compilation_unit.functions_top_level:
func.generate_slithir_and_analyze()
func.generate_slithir_ssa({})
self._compilation_unit.propagate_function_calls()
for contract in self._compilation_unit.contracts:
contract.fix_phi()
contract.update_read_write_using_ssa()
# endregion
| 33,230 | Python | .py | 628 | 40.302548 | 163 | 0.601417 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,081 | exceptions.py | NioTheFirst_ScType/slither/solc_parsing/exceptions.py | from slither.exceptions import SlitherException
class ParsingError(SlitherException):
pass
class VariableNotFound(SlitherException):
pass
| 150 | Python | .py | 5 | 26.6 | 47 | 0.858156 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,082 | find_variable.py | NioTheFirst_ScType/slither/solc_parsing/expressions/find_variable.py | from typing import TYPE_CHECKING, Optional, Union, List, Tuple
from slither.core.declarations import Event, Enum, Structure
from slither.core.declarations.contract import Contract
from slither.core.declarations.custom_error import CustomError
from slither.core.declarations.function import Function
from slither.core.declarations.function_contract import FunctionContract
from slither.core.declarations.function_top_level import FunctionTopLevel
from slither.core.declarations.solidity_import_placeholder import SolidityImportPlaceHolder
from slither.core.declarations.solidity_variables import (
SOLIDITY_FUNCTIONS,
SOLIDITY_VARIABLES,
SolidityFunction,
SolidityVariable,
)
from slither.core.scope.scope import FileScope
from slither.core.solidity_types import (
ArrayType,
FunctionType,
MappingType,
TypeAlias,
)
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.core.variables.variable import Variable
from slither.exceptions import SlitherError
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.exceptions import VariableNotFound
if TYPE_CHECKING:
from slither.solc_parsing.declarations.function import FunctionSolc
from slither.solc_parsing.declarations.contract import ContractSolc
# pylint: disable=import-outside-toplevel,too-many-branches,too-many-locals
# CallerContext =Union["ContractSolc", "FunctionSolc", "CustomErrorSolc", "StructureTopLevelSolc"]
def _get_pointer_name(variable: Variable):
curr_type = variable.type
while isinstance(curr_type, (ArrayType, MappingType)):
if isinstance(curr_type, ArrayType):
curr_type = curr_type.type
else:
assert isinstance(curr_type, MappingType)
curr_type = curr_type.type_to
if isinstance(curr_type, FunctionType):
return variable.name + curr_type.parameters_signature
return None
def _find_variable_from_ref_declaration(
referenced_declaration: Optional[int],
all_contracts: List["Contract"],
all_functions: List["Function"],
) -> Optional[Union[Contract, Function]]:
if referenced_declaration is None:
return None
# id of the contracts is the referenced declaration
# This is not true for the functions, as we dont always have the referenced_declaration
# But maybe we could? (TODO)
for contract_candidate in all_contracts:
if contract_candidate and contract_candidate.id == referenced_declaration:
return contract_candidate
for function_candidate in all_functions:
if function_candidate.id == referenced_declaration and not function_candidate.is_shadowed:
return function_candidate
return None
def _find_variable_in_function_parser(
var_name: str,
function_parser: Optional["FunctionSolc"],
referenced_declaration: Optional[int] = None,
) -> Optional[Variable]:
if function_parser is None:
return None
# We look for variable declared with the referencedDeclaration attr
func_variables_renamed = function_parser.variables_renamed
if referenced_declaration and referenced_declaration in func_variables_renamed:
return func_variables_renamed[referenced_declaration].underlying_variable
# If not found, check for name
func_variables = function_parser.underlying_function.variables_as_dict
if var_name in func_variables:
return func_variables[var_name]
# A local variable can be a pointer
# for example
# function test(function(uint) internal returns(bool) t) interna{
# Will have a local variable t which will match the signature
# t(uint256)
func_variables_ptr = {
_get_pointer_name(f): f for f in function_parser.underlying_function.variables
}
if var_name and var_name in func_variables_ptr:
return func_variables_ptr[var_name]
return None
def find_top_level(
var_name: str, scope: "FileScope"
) -> Tuple[
Optional[Union[Enum, Structure, SolidityImportPlaceHolder, CustomError, TopLevelVariable]], bool
]:
"""
Return the top level variable use, and a boolean indicating if the variable returning was cretead
If the variable was created, it has no source_mapping
:param var_name:
:type var_name:
:param sl:
:type sl:
:return:
:rtype:
"""
if var_name in scope.structures:
return scope.structures[var_name], False
if var_name in scope.enums:
return scope.enums[var_name], False
for import_directive in scope.imports:
if import_directive.alias == var_name:
new_val = SolidityImportPlaceHolder(import_directive)
return new_val, True
if var_name in scope.variables:
return scope.variables[var_name], False
# This path should be reached only after the top level custom error have been parsed
# If not, slither will crash
# It does not seem to be reacheable, but if so, we will have to adapt the order of logic
# This must be at the end, because other top level objects might require to go over "_find_top_level"
# Before the parsing of the top level custom error
# For example, a top variable that use another top level variable
# IF more top level objects are added to Solidity, we have to be careful with the order of the lookup
# in this function
try:
for custom_error in scope.custom_errors:
if custom_error.solidity_signature == var_name:
return custom_error, False
except ValueError:
# This can happen as custom error sol signature might not have been built
# when find_variable was called
# TODO refactor find_variable to prevent this from happening
pass
return None, False
def _find_in_contract(
var_name: str,
contract: Optional[Contract],
contract_declarer: Optional[Contract],
is_super: bool,
is_identifier_path: bool = False,
) -> Optional[Union[Variable, Function, Contract, Event, Enum, Structure, CustomError]]:
if contract is None or contract_declarer is None:
return None
# variable are looked from the contract declarer
contract_variables = contract_declarer.variables_as_dict
if var_name in contract_variables:
return contract_variables[var_name]
# A state variable can be a pointer
conc_variables_ptr = {_get_pointer_name(f): f for f in contract_declarer.variables}
if var_name and var_name in conc_variables_ptr:
return conc_variables_ptr[var_name]
if is_super:
getter_available = lambda f: f.functions_declared
d = {f.canonical_name: f for f in contract.functions}
functions = {
f.full_name: f
for f in contract_declarer.available_elements_from_inheritances(
d, getter_available
).values()
}
else:
functions = {f.full_name: f for f in contract.functions if not f.is_shadowed}
if var_name in functions:
return functions[var_name]
if is_super:
getter_available = lambda m: m.modifiers_declared
d = {m.canonical_name: m for m in contract.modifiers}
modifiers = {
m.full_name: m
for m in contract_declarer.available_elements_from_inheritances(
d, getter_available
).values()
}
else:
modifiers = contract.available_modifiers_as_dict()
if var_name in modifiers:
return modifiers[var_name]
if is_identifier_path:
for sig, modifier in modifiers.items():
if "(" in sig:
sig = sig[0 : sig.find("(")]
if sig == var_name:
return modifier
# structures are looked on the contract declarer
structures = contract.structures_as_dict
if var_name in structures:
return structures[var_name]
events = contract.events_as_dict
if var_name in events:
return events[var_name]
enums = contract.enums_as_dict
if var_name in enums:
return enums[var_name]
# Note: contract.custom_errors_as_dict uses the name (not the sol sig) as key
# This is because when the dic is populated the underlying object is not yet parsed
# As a result, we need to iterate over all the custom errors here instead of using the dict
custom_errors = contract.custom_errors
try:
for custom_error in custom_errors:
if var_name in [custom_error.solidity_signature, custom_error.full_name]:
return custom_error
except ValueError:
# This can happen as custom error sol signature might not have been built
# when find_variable was called
# TODO refactor find_variable to prevent this from happening
pass
# If the enum is refered as its name rather than its canonicalName
enums = {e.name: e for e in contract.enums}
if var_name in enums:
return enums[var_name]
return None
def _find_variable_init(
caller_context: CallerContextExpression,
) -> Tuple[List[Contract], List["Function"], FileScope,]:
from slither.solc_parsing.declarations.contract import ContractSolc
from slither.solc_parsing.declarations.function import FunctionSolc
from slither.solc_parsing.declarations.structure_top_level import StructureTopLevelSolc
from slither.solc_parsing.variables.top_level_variable import TopLevelVariableSolc
direct_contracts: List[Contract]
direct_functions_parser: List[Function]
scope: FileScope
if isinstance(caller_context, FileScope):
direct_contracts = []
direct_functions_parser = []
scope = caller_context
elif isinstance(caller_context, ContractSolc):
direct_contracts = [caller_context.underlying_contract]
direct_functions_parser = [
f.underlying_function
for f in caller_context.functions_parser + caller_context.modifiers_parser
]
scope = caller_context.underlying_contract.file_scope
elif isinstance(caller_context, FunctionSolc):
if caller_context.contract_parser:
direct_contracts = [caller_context.contract_parser.underlying_contract]
direct_functions_parser = [
f.underlying_function
for f in caller_context.contract_parser.functions_parser
+ caller_context.contract_parser.modifiers_parser
]
else:
# Top level functions
direct_contracts = []
direct_functions_parser = []
underlying_function = caller_context.underlying_function
if isinstance(underlying_function, FunctionTopLevel):
scope = underlying_function.file_scope
else:
assert isinstance(underlying_function, FunctionContract)
scope = underlying_function.contract.file_scope
elif isinstance(caller_context, StructureTopLevelSolc):
direct_contracts = []
direct_functions_parser = []
scope = caller_context.underlying_structure.file_scope
elif isinstance(caller_context, TopLevelVariableSolc):
direct_contracts = []
direct_functions_parser = []
scope = caller_context.underlying_variable.file_scope
else:
raise SlitherError(
f"{type(caller_context)} ({caller_context} is not valid for find_variable"
)
return direct_contracts, direct_functions_parser, scope
def find_variable(
var_name: str,
caller_context: CallerContextExpression,
referenced_declaration: Optional[int] = None,
is_super: bool = False,
is_identifier_path: bool = False,
) -> Tuple[
Union[
Variable,
Function,
Contract,
SolidityVariable,
SolidityFunction,
Event,
Enum,
Structure,
CustomError,
TypeAlias,
],
bool,
]:
"""
Return the variable found and a boolean indicating if the variable was created
If the variable was created, it has no source mapping, and it the caller must add it
:param var_name:
:type var_name:
:param caller_context:
:type caller_context:
:param referenced_declaration:
:type referenced_declaration:
:param is_super:
:type is_super:
:param is_identifier_path:
:type is_identifier_path:
:return:
:rtype:
"""
from slither.solc_parsing.declarations.function import FunctionSolc
from slither.solc_parsing.declarations.contract import ContractSolc
# variable are looked from the contract declarer
# functions can be shadowed, but are looked from the contract instance, rather than the contract declarer
# the difference between function and variable come from the fact that an internal call, or an variable access
# in a function does not behave similariy, for example in:
# contract C{
# function f(){
# state_var = 1
# f2()
# }
# state_var will refer to C.state_var, no mater if C is inherited
# while f2() will refer to the function definition of the inherited contract (C.f2() in the context of C, or
# the contract inheriting from C)
# for events it's unclear what should be the behavior, as they can be shadowed, but there is not impact
# structure/enums cannot be shadowed
direct_contracts, direct_functions, current_scope = _find_variable_init(caller_context)
# Only look for reference declaration in the direct contract, see comment at the end
# Reference looked are split between direct and all
# Because functions are copied between contracts, two functions can have the same ref
# So we need to first look with respect to the direct context
if var_name in current_scope.renaming:
var_name = current_scope.renaming[var_name]
if var_name in current_scope.user_defined_types:
return current_scope.user_defined_types[var_name], False
# Use ret0/ret1 to help mypy
ret0 = _find_variable_from_ref_declaration(
referenced_declaration, direct_contracts, direct_functions
)
if ret0:
return ret0, False
function_parser: Optional[FunctionSolc] = (
caller_context if isinstance(caller_context, FunctionSolc) else None
)
ret1 = _find_variable_in_function_parser(var_name, function_parser, referenced_declaration)
if ret1:
return ret1, False
contract: Optional[Contract] = None
contract_declarer: Optional[Contract] = None
if isinstance(caller_context, ContractSolc):
contract = caller_context.underlying_contract
contract_declarer = caller_context.underlying_contract
elif isinstance(caller_context, FunctionSolc):
underlying_func = caller_context.underlying_function
if isinstance(underlying_func, FunctionContract):
contract = underlying_func.contract
contract_declarer = underlying_func.contract_declarer
else:
assert isinstance(underlying_func, FunctionTopLevel)
ret = _find_in_contract(var_name, contract, contract_declarer, is_super, is_identifier_path)
if ret:
return ret, False
# Could refer to any enum
all_enumss = [c.enums_as_dict for c in current_scope.contracts.values()]
all_enums = {k: v for d in all_enumss for k, v in d.items()}
if var_name in all_enums:
return all_enums[var_name], False
contracts = current_scope.contracts
if var_name in contracts:
return contracts[var_name], False
if var_name in SOLIDITY_VARIABLES:
return SolidityVariable(var_name), False
if var_name in SOLIDITY_FUNCTIONS:
return SolidityFunction(var_name), False
# Top level must be at the end, if nothing else was found
ret, var_was_created = find_top_level(var_name, current_scope)
if ret:
return ret, var_was_created
# Look from reference declaration in all the contracts at the end
# Because they are many instances where this can't be trusted
# For example in
# contract A{
# function _f() internal view returns(uint){
# return 1;
# }
#
# function get() public view returns(uint){
# return _f();
# }
# }
#
# contract B is A{
# function _f() internal view returns(uint){
# return 2;
# }
#
# }
# get's AST will say that the ref declaration for _f() is A._f(), but in the context of B, its not
ret = _find_variable_from_ref_declaration(
referenced_declaration,
list(current_scope.contracts.values()),
list(current_scope.functions),
)
if ret:
return ret, False
raise VariableNotFound(f"Variable not found: {var_name} (context {contract})")
| 16,780 | Python | .py | 390 | 36.305128 | 114 | 0.700814 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,083 | expression_parsing.py | NioTheFirst_ScType/slither/solc_parsing/expressions/expression_parsing.py | import logging
import re
from typing import Dict, TYPE_CHECKING
from slither.core.declarations.solidity_variables import (
SOLIDITY_VARIABLES_COMPOSED,
SolidityVariableComposed,
)
from slither.core.expressions.assignment_operation import (
AssignmentOperation,
AssignmentOperationType,
)
from slither.core.expressions.binary_operation import (
BinaryOperation,
BinaryOperationType,
)
from slither.core.expressions import (
CallExpression,
ConditionalExpression,
ElementaryTypeNameExpression,
Identifier,
IndexAccess,
Literal,
MemberAccess,
NewArray,
NewContract,
NewElementaryType,
SuperCallExpression,
SuperIdentifier,
TupleExpression,
TypeConversion,
UnaryOperation,
UnaryOperationType,
)
from slither.core.solidity_types import (
ArrayType,
ElementaryType,
)
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.exceptions import ParsingError, VariableNotFound
from slither.solc_parsing.expressions.find_variable import find_variable
from slither.solc_parsing.solidity_types.type_parsing import UnknownType, parse_type
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
logger = logging.getLogger("ExpressionParsing")
# pylint: disable=anomalous-backslash-in-string,import-outside-toplevel,too-many-branches,too-many-locals
# region Filtering
###################################################################################
###################################################################################
def filter_name(value: str) -> str:
value = value.replace(" memory", "")
value = value.replace(" storage", "")
value = value.replace(" external", "")
value = value.replace(" internal", "")
value = value.replace("struct ", "")
value = value.replace("contract ", "")
value = value.replace("enum ", "")
value = value.replace(" ref", "")
value = value.replace(" pointer", "")
value = value.replace(" pure", "")
value = value.replace(" view", "")
value = value.replace(" constant", "")
value = value.replace(" payable", "")
value = value.replace("function (", "function(")
value = value.replace("returns (", "returns(")
value = value.replace(" calldata", "")
# remove the text remaining after functio(...)
# which should only be ..returns(...)
# nested parenthesis so we use a system of counter on parenthesis
idx = value.find("(")
if idx:
counter = 1
max_idx = len(value)
while counter:
assert idx < max_idx
idx = idx + 1
if value[idx] == "(":
counter += 1
elif value[idx] == ")":
counter -= 1
value = value[: idx + 1]
return value
# endregion
###################################################################################
###################################################################################
# region Parsing
###################################################################################
###################################################################################
def parse_call(expression: Dict, caller_context): # pylint: disable=too-many-statements
src = expression["src"]
if caller_context.is_compact_ast:
attributes = expression
type_conversion = expression["kind"] == "typeConversion"
type_return = attributes["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
type_conversion = attributes["type_conversion"]
type_return = attributes["type"]
if type_conversion:
type_call = parse_type(UnknownType(type_return), caller_context)
if caller_context.is_compact_ast:
assert len(expression["arguments"]) == 1
expression_to_parse = expression["arguments"][0]
else:
children = expression["children"]
assert len(children) == 2
type_info = children[0]
expression_to_parse = children[1]
assert type_info["name"] in [
"ElementaryTypenameExpression",
"ElementaryTypeNameExpression",
"Identifier",
"TupleExpression",
"IndexAccess",
"MemberAccess",
]
expression = parse_expression(expression_to_parse, caller_context)
t = TypeConversion(expression, type_call)
t.set_offset(src, caller_context.compilation_unit)
return t
call_gas = None
call_value = None
call_salt = None
if caller_context.is_compact_ast:
called = parse_expression(expression["expression"], caller_context)
# If the next expression is a FunctionCallOptions
# We can here the gas/value information
# This is only available if the syntax is {gas: , value: }
# For the .gas().value(), the member are considered as function call
# And converted later to the correct info (convert.py)
if expression["expression"][caller_context.get_key()] == "FunctionCallOptions":
call_with_options = expression["expression"]
for idx, name in enumerate(call_with_options.get("names", [])):
option = parse_expression(call_with_options["options"][idx], caller_context)
if name == "value":
call_value = option
if name == "gas":
call_gas = option
if name == "salt":
call_salt = option
arguments = []
if expression["arguments"]:
arguments = [parse_expression(a, caller_context) for a in expression["arguments"]]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
if isinstance(called, SuperCallExpression):
sp = SuperCallExpression(called, arguments, type_return)
sp.set_offset(expression["src"], caller_context.compilation_unit)
return sp
call_expression = CallExpression(called, arguments, type_return)
call_expression.set_offset(src, caller_context.compilation_unit)
# Only available if the syntax {gas:, value:} was used
call_expression.call_gas = call_gas
call_expression.call_value = call_value
call_expression.call_salt = call_salt
return call_expression
def parse_super_name(expression: Dict, is_compact_ast: bool) -> str:
if is_compact_ast:
assert expression["nodeType"] == "MemberAccess"
base_name = expression["memberName"]
arguments = expression["typeDescriptions"]["typeString"]
else:
assert expression["name"] == "MemberAccess"
attributes = expression["attributes"]
base_name = attributes["member_name"]
arguments = attributes["type"]
assert arguments.startswith("function ")
# remove function (...()
arguments = arguments[len("function ") :]
arguments = filter_name(arguments)
if " " in arguments:
arguments = arguments[: arguments.find(" ")]
return base_name + arguments
def _parse_elementary_type_name_expression(
expression: Dict, is_compact_ast: bool, caller_context: CallerContextExpression
) -> ElementaryTypeNameExpression:
# nop exression
# uint;
if is_compact_ast:
value = expression["typeName"]
else:
if "children" in expression:
value = expression["children"][0]["attributes"]["name"]
else:
value = expression["attributes"]["value"]
if isinstance(value, dict):
t = parse_type(value, caller_context)
else:
t = parse_type(UnknownType(value), caller_context)
e = ElementaryTypeNameExpression(t)
e.set_offset(expression["src"], caller_context.compilation_unit)
return e
if TYPE_CHECKING:
from slither.core.scope.scope import FileScope
def parse_expression(expression: Dict, caller_context: CallerContextExpression) -> "Expression":
# pylint: disable=too-many-nested-blocks,too-many-statements
"""
Returns:
str: expression
"""
# Expression
# = Expression ('++' | '--')
# | NewExpression
# | IndexAccess
# | MemberAccess
# | FunctionCall
# | '(' Expression ')'
# | ('!' | '~' | 'delete' | '++' | '--' | '+' | '-') Expression
# | Expression '**' Expression
# | Expression ('*' | '/' | '%') Expression
# | Expression ('+' | '-') Expression
# | Expression ('<<' | '>>') Expression
# | Expression '&' Expression
# | Expression '^' Expression
# | Expression '|' Expression
# | Expression ('<' | '>' | '<=' | '>=') Expression
# | Expression ('==' | '!=') Expression
# | Expression '&&' Expression
# | Expression '||' Expression
# | Expression '?' Expression ':' Expression
# | Expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') Expression
# | PrimaryExpression
# The AST naming does not follow the spec
assert isinstance(caller_context, CallerContextExpression)
name = expression[caller_context.get_key()]
is_compact_ast = caller_context.is_compact_ast
src = expression["src"]
if name == "UnaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
assert "prefix" in attributes
operation_type = UnaryOperationType.get_type(attributes["operator"], attributes["prefix"])
if is_compact_ast:
expression = parse_expression(expression["subExpression"], caller_context)
else:
assert len(expression["children"]) == 1
expression = parse_expression(expression["children"][0], caller_context)
unary_op = UnaryOperation(expression, operation_type)
unary_op.set_offset(src, caller_context.compilation_unit)
return unary_op
if name == "BinaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
operation_type = BinaryOperationType.get_type(attributes["operator"])
if is_compact_ast:
left_expression = parse_expression(expression["leftExpression"], caller_context)
right_expression = parse_expression(expression["rightExpression"], caller_context)
else:
assert len(expression["children"]) == 2
left_expression = parse_expression(expression["children"][0], caller_context)
right_expression = parse_expression(expression["children"][1], caller_context)
binary_op = BinaryOperation(left_expression, right_expression, operation_type)
binary_op.set_offset(src, caller_context.compilation_unit)
return binary_op
if name in "FunctionCall":
return parse_call(expression, caller_context)
if name == "FunctionCallOptions":
# call/gas info are handled in parse_call
if is_compact_ast:
called = parse_expression(expression["expression"], caller_context)
else:
called = parse_expression(expression["children"][0], caller_context)
assert isinstance(called, (MemberAccess, NewContract, Identifier, TupleExpression))
return called
if name == "TupleExpression":
# For expression like
# (a,,c) = (1,2,3)
# the AST provides only two children in the left side
# We check the type provided (tuple(uint256,,uint256))
# To determine that there is an empty variable
# Otherwhise we would not be able to determine that
# a = 1, c = 3, and 2 is lost
#
# Note: this is only possible with Solidity >= 0.4.12
if is_compact_ast:
expressions = [
parse_expression(e, caller_context) if e else None for e in expression["components"]
]
else:
if "children" not in expression:
attributes = expression["attributes"]
components = attributes["components"]
expressions = [
parse_expression(c, caller_context) if c else None for c in components
]
else:
expressions = [parse_expression(e, caller_context) for e in expression["children"]]
# Add none for empty tuple items
if "attributes" in expression:
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if ",," in t or "(," in t or ",)" in t:
t = t[len("tuple(") : -1]
elems = t.split(",")
for idx, _ in enumerate(elems):
if elems[idx] == "":
expressions.insert(idx, None)
t = TupleExpression(expressions)
t.set_offset(src, caller_context.compilation_unit)
return t
if name == "Conditional":
if is_compact_ast:
if_expression = parse_expression(expression["condition"], caller_context)
then_expression = parse_expression(expression["trueExpression"], caller_context)
else_expression = parse_expression(expression["falseExpression"], caller_context)
else:
children = expression["children"]
assert len(children) == 3
if_expression = parse_expression(children[0], caller_context)
then_expression = parse_expression(children[1], caller_context)
else_expression = parse_expression(children[2], caller_context)
conditional = ConditionalExpression(if_expression, then_expression, else_expression)
conditional.set_offset(src, caller_context.compilation_unit)
return conditional
if name == "Assignment":
if is_compact_ast:
left_expression = parse_expression(expression["leftHandSide"], caller_context)
right_expression = parse_expression(expression["rightHandSide"], caller_context)
operation_type = AssignmentOperationType.get_type(expression["operator"])
operation_return_type = expression["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
children = expression["children"]
assert len(expression["children"]) == 2
left_expression = parse_expression(children[0], caller_context)
right_expression = parse_expression(children[1], caller_context)
operation_type = AssignmentOperationType.get_type(attributes["operator"])
operation_return_type = attributes["type"]
assignement = AssignmentOperation(
left_expression, right_expression, operation_type, operation_return_type
)
assignement.set_offset(src, caller_context.compilation_unit)
return assignement
if name == "Literal":
subdenomination = None
assert "children" not in expression
if is_compact_ast:
value = expression.get("value", None)
if value:
if "subdenomination" in expression and expression["subdenomination"]:
subdenomination = expression["subdenomination"]
elif not value and value != "":
value = "0x" + expression["hexValue"]
type_candidate = expression["typeDescriptions"]["typeString"]
# Length declaration for array was None until solc 0.5.5
if type_candidate is None:
if expression["kind"] == "number":
type_candidate = "int_const"
else:
value = expression["attributes"].get("value", None)
if value:
if (
"subdenomination" in expression["attributes"]
and expression["attributes"]["subdenomination"]
):
subdenomination = expression["attributes"]["subdenomination"]
elif value is None:
# for literal declared as hex
# see https://solidity.readthedocs.io/en/v0.4.25/types.html?highlight=hex#hexadecimal-literals
assert "hexvalue" in expression["attributes"]
value = "0x" + expression["attributes"]["hexvalue"]
type_candidate = expression["attributes"]["type"]
if type_candidate is None:
if value.isdecimal():
type_candidate = ElementaryType("uint256")
else:
type_candidate = ElementaryType("string")
elif type_candidate.startswith("int_const "):
type_candidate = ElementaryType("uint256")
elif type_candidate.startswith("bool"):
type_candidate = ElementaryType("bool")
elif type_candidate.startswith("address"):
type_candidate = ElementaryType("address")
else:
type_candidate = ElementaryType("string")
literal = Literal(value, type_candidate, subdenomination)
literal.set_offset(src, caller_context.compilation_unit)
return literal
if name == "Identifier":
assert "children" not in expression
t = None
if caller_context.is_compact_ast:
value = expression["name"]
t = expression["typeDescriptions"]["typeString"]
else:
value = expression["attributes"]["value"]
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if t:
found = re.findall(r"[struct|enum|function|modifier] \(([\[\] ()a-zA-Z0-9\.,_]*)\)", t)
assert len(found) <= 1
if found:
value = value + "(" + found[0] + ")"
value = filter_name(value)
if "referencedDeclaration" in expression:
referenced_declaration = expression["referencedDeclaration"]
else:
referenced_declaration = None
var, was_created = find_variable(value, caller_context, referenced_declaration)
if was_created:
var.set_offset(src, caller_context.compilation_unit)
identifier = Identifier(var)
identifier.set_offset(src, caller_context.compilation_unit)
var.references.append(identifier.source_mapping)
return identifier
if name == "IndexAccess":
if is_compact_ast:
index_type = expression["typeDescriptions"]["typeString"]
left = expression["baseExpression"]
right = expression.get("indexExpression", None)
else:
index_type = expression["attributes"]["type"]
children = expression["children"]
left = children[0]
right = children[1] if len(children) > 1 else None
# IndexAccess is used to describe ElementaryTypeNameExpression
# if abi.decode is used
# For example, abi.decode(data, ...(uint[]) )
if right is None:
ret = parse_expression(left, caller_context)
# Nested array are not yet available in abi.decode
if isinstance(ret, ElementaryTypeNameExpression):
old_type = ret.type
ret.type = ArrayType(old_type, None)
return ret
left_expression = parse_expression(left, caller_context)
right_expression = parse_expression(right, caller_context)
index = IndexAccess(left_expression, right_expression, index_type)
index.set_offset(src, caller_context.compilation_unit)
return index
if name == "MemberAccess":
if caller_context.is_compact_ast:
member_name = expression["memberName"]
member_type = expression["typeDescriptions"]["typeString"]
# member_type = parse_type(
# UnknownType(expression["typeDescriptions"]["typeString"]), caller_context
# )
member_expression = parse_expression(expression["expression"], caller_context)
else:
member_name = expression["attributes"]["member_name"]
member_type = expression["attributes"]["type"]
# member_type = parse_type(UnknownType(expression["attributes"]["type"]), caller_context)
children = expression["children"]
assert len(children) == 1
member_expression = parse_expression(children[0], caller_context)
if str(member_expression) == "super":
super_name = parse_super_name(expression, is_compact_ast)
var, was_created = find_variable(super_name, caller_context, is_super=True)
if var is None:
raise VariableNotFound(f"Variable not found: {super_name}")
if was_created:
var.set_offset(src, caller_context.compilation_unit)
sup = SuperIdentifier(var)
sup.set_offset(src, caller_context.compilation_unit)
var.references.append(sup.source_mapping)
return sup
member_access = MemberAccess(member_name, member_type, member_expression)
member_access.set_offset(src, caller_context.compilation_unit)
if str(member_access) in SOLIDITY_VARIABLES_COMPOSED:
id_idx = Identifier(SolidityVariableComposed(str(member_access)))
id_idx.set_offset(src, caller_context.compilation_unit)
return id_idx
return member_access
if name == "ElementaryTypeNameExpression":
return _parse_elementary_type_name_expression(expression, is_compact_ast, caller_context)
# NewExpression is not a root expression, it's always the child of another expression
if name == "NewExpression":
if is_compact_ast:
type_name = expression["typeName"]
else:
children = expression["children"]
assert len(children) == 1
type_name = children[0]
if type_name[caller_context.get_key()] == "ArrayTypeName":
depth = 0
while type_name[caller_context.get_key()] == "ArrayTypeName":
# Note: dont conserve the size of the array if provided
# We compute it directly
if is_compact_ast:
type_name = type_name["baseType"]
else:
type_name = type_name["children"][0]
depth += 1
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
array_type = ElementaryType(type_name["name"])
else:
array_type = ElementaryType(type_name["attributes"]["name"])
elif type_name[caller_context.get_key()] == "UserDefinedTypeName":
if is_compact_ast:
if "name" not in type_name:
name_type = type_name["pathNode"]["name"]
else:
name_type = type_name["name"]
array_type = parse_type(UnknownType(name_type), caller_context)
else:
array_type = parse_type(
UnknownType(type_name["attributes"]["name"]), caller_context
)
elif type_name[caller_context.get_key()] == "FunctionTypeName":
array_type = parse_type(type_name, caller_context)
else:
raise ParsingError(f"Incorrect type array {type_name}")
array = NewArray(depth, array_type)
array.set_offset(src, caller_context.compilation_unit)
return array
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
elem_type = ElementaryType(type_name["name"])
else:
elem_type = ElementaryType(type_name["attributes"]["name"])
new_elem = NewElementaryType(elem_type)
new_elem.set_offset(src, caller_context.compilation_unit)
return new_elem
assert type_name[caller_context.get_key()] == "UserDefinedTypeName"
if is_compact_ast:
# Changed introduced in Solidity 0.8
# see https://github.com/crytic/slither/issues/794
# TODO explore more the changes introduced in 0.8 and the usage of pathNode/IdentifierPath
if "name" not in type_name:
assert "pathNode" in type_name and "name" in type_name["pathNode"]
contract_name = type_name["pathNode"]["name"]
else:
contract_name = type_name["name"]
else:
contract_name = type_name["attributes"]["name"]
new = NewContract(contract_name)
new.set_offset(src, caller_context.compilation_unit)
return new
if name == "ModifierInvocation":
if is_compact_ast:
called = parse_expression(expression["modifierName"], caller_context)
arguments = []
if expression.get("arguments", None):
arguments = [parse_expression(a, caller_context) for a in expression["arguments"]]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
call = CallExpression(called, arguments, "Modifier")
call.set_offset(src, caller_context.compilation_unit)
return call
if name == "IndexRangeAccess":
# For now, we convert array slices to a direct array access
# As a result the generated IR will lose the slices information
# As far as I understand, array slice are only used in abi.decode
# https://solidity.readthedocs.io/en/v0.6.12/types.html
# TODO: Investigate array slices usage and implication for the IR
base = parse_expression(expression["baseExpression"], caller_context)
return base
# Introduced with solc 0.8
if name == "IdentifierPath":
if caller_context.is_compact_ast:
value = expression["name"]
if "referencedDeclaration" in expression:
referenced_declaration = expression["referencedDeclaration"]
else:
referenced_declaration = None
var, was_created = find_variable(
value, caller_context, referenced_declaration, is_identifier_path=True
)
if was_created:
var.set_offset(src, caller_context.compilation_unit)
identifier = Identifier(var)
identifier.set_offset(src, caller_context.compilation_unit)
var.references.append(identifier.source_mapping)
return identifier
raise ParsingError("IdentifierPath not currently supported for the legacy ast")
raise ParsingError(f"Expression not parsed {name}")
| 27,069 | Python | .py | 574 | 36.940767 | 110 | 0.605271 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,084 | type_parsing.py | NioTheFirst_ScType/slither/solc_parsing/solidity_types/type_parsing.py | import logging
import re
from typing import List, TYPE_CHECKING, Union, Dict, ValuesView
from slither.core.declarations.custom_error_contract import CustomErrorContract
from slither.core.declarations.custom_error_top_level import CustomErrorTopLevel
from slither.core.declarations.function_contract import FunctionContract
from slither.core.expressions.literal import Literal
from slither.core.solidity_types import TypeAlias
from slither.core.solidity_types.array_type import ArrayType
from slither.core.solidity_types.elementary_type import (
ElementaryType,
ElementaryTypeName,
)
from slither.core.solidity_types.function_type import FunctionType
from slither.core.solidity_types.mapping_type import MappingType
from slither.core.solidity_types.type import Type
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.core.variables.function_type_variable import FunctionTypeVariable
from slither.exceptions import SlitherError
from slither.solc_parsing.exceptions import ParsingError
from slither.solc_parsing.expressions.expression_parsing import CallerContextExpression
if TYPE_CHECKING:
from slither.core.declarations import Structure, Enum
from slither.core.declarations.contract import Contract
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
logger = logging.getLogger("TypeParsing")
# pylint: disable=anomalous-backslash-in-string
class UnknownType: # pylint: disable=too-few-public-methods
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def _find_from_type_name( # pylint: disable=too-many-locals,too-many-branches,too-many-statements,too-many-arguments
name: str,
functions_direct_access: List["Function"],
contracts_direct_access: List["Contract"],
structures_direct_access: List["Structure"],
all_structures: ValuesView["Structure"],
enums_direct_access: List["Enum"],
all_enums: ValuesView["Enum"],
) -> Type:
name_elementary = name.split(" ")[0]
if "[" in name_elementary:
name_elementary = name_elementary[0 : name_elementary.find("[")]
if name_elementary in ElementaryTypeName:
depth = name.count("[")
if depth:
return ArrayType(ElementaryType(name_elementary), Literal(depth, "uint256"))
return ElementaryType(name_elementary)
# We first look for contract
# To avoid collision
# Ex: a structure with the name of a contract
name_contract = name
if name_contract.startswith("contract "):
name_contract = name_contract[len("contract ") :]
if name_contract.startswith("library "):
name_contract = name_contract[len("library ") :]
var_type = next((c for c in contracts_direct_access if c.name == name_contract), None)
if not var_type:
var_type = next((st for st in structures_direct_access if st.name == name), None)
if not var_type:
var_type = next((e for e in enums_direct_access if e.name == name), None)
if not var_type:
# any contract can refer to another contract's enum
enum_name = name
if enum_name.startswith("enum "):
enum_name = enum_name[len("enum ") :]
elif enum_name.startswith("type(enum"):
enum_name = enum_name[len("type(enum ") : -1]
# all_enums = [c.enums for c in contracts]
# all_enums = [item for sublist in all_enums for item in sublist]
# all_enums += contract.slither.enums_top_level
var_type = next((e for e in all_enums if e.name == enum_name), None)
if not var_type:
var_type = next((e for e in all_enums if e.canonical_name == enum_name), None)
if not var_type:
# any contract can refer to another contract's structure
name_struct = name
if name_struct.startswith("struct "):
name_struct = name_struct[len("struct ") :]
name_struct = name_struct.split(" ")[0] # remove stuff like storage pointer at the end
# all_structures = [c.structures for c in contracts]
# all_structures = [item for sublist in all_structures for item in sublist]
# all_structures += contract.slither.structures_top_level
var_type = next((st for st in all_structures if st.name == name_struct), None)
if not var_type:
var_type = next((st for st in all_structures if st.canonical_name == name_struct), None)
# case where struct xxx.xx[] where not well formed in the AST
if not var_type:
depth = 0
while name_struct.endswith("[]"):
name_struct = name_struct[0:-2]
depth += 1
var_type = next((st for st in all_structures if st.canonical_name == name_struct), None)
if var_type:
return ArrayType(UserDefinedType(var_type), Literal(depth, "uint256"))
if not var_type:
var_type = next((f for f in functions_direct_access if f.name == name), None)
if not var_type:
if name.startswith("function "):
found = re.findall(
r"function \(([ ()\[\]a-zA-Z0-9\.,]*?)\)(?: payable)?(?: (?:external|internal|pure|view))?(?: returns \(([a-zA-Z0-9() \.,]*)\))?",
name,
)
assert len(found) == 1
params = [v for v in found[0][0].split(",") if v != ""]
return_values = (
[v for v in found[0][1].split(",") if v != ""] if len(found[0]) > 1 else []
)
params = [
_find_from_type_name(
p,
functions_direct_access,
contracts_direct_access,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
for p in params
]
return_values = [
_find_from_type_name(
r,
functions_direct_access,
contracts_direct_access,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
for r in return_values
]
params_vars = []
return_vars = []
for p in params:
var = FunctionTypeVariable()
var.set_type(p)
params_vars.append(var)
for r in return_values:
var = FunctionTypeVariable()
var.set_type(r)
return_vars.append(var)
return FunctionType(params_vars, return_vars)
if not var_type:
if name.startswith("mapping("):
# nested mapping declared with var
if name.count("mapping(") == 1:
found = re.findall(r"mapping\(([a-zA-Z0-9\.]*) => ([ a-zA-Z0-9\.\[\]]*)\)", name)
else:
found = re.findall(
r"mapping\(([a-zA-Z0-9\.]*) => (mapping\([=> a-zA-Z0-9\.\[\]]*\))\)",
name,
)
assert len(found) == 1
from_ = found[0][0]
to_ = found[0][1]
from_type = _find_from_type_name(
from_,
functions_direct_access,
contracts_direct_access,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
to_type = _find_from_type_name(
to_,
functions_direct_access,
contracts_direct_access,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
return MappingType(from_type, to_type)
if not var_type:
raise ParsingError("Type not found " + str(name))
return UserDefinedType(var_type)
def _add_type_references(type_found: Type, src: str, sl: "SlitherCompilationUnit"):
if isinstance(type_found, UserDefinedType):
type_found.type.add_reference_from_raw_source(src, sl)
# TODO: since the add of FileScope, we can probably refactor this function and makes it a lot simpler
def parse_type(
t: Union[Dict, UnknownType],
caller_context: Union[CallerContextExpression, "SlitherCompilationUnitSolc"],
) -> Type:
"""
caller_context can be a SlitherCompilationUnitSolc because we recursively call the function
and go up in the context's scope. If we are really lost we just go over the SlitherCompilationUnitSolc
:param t:
:type t:
:param caller_context:
:type caller_context:
:return:
:rtype:
"""
# local import to avoid circular dependency
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
# pylint: disable=import-outside-toplevel
from slither.solc_parsing.expressions.expression_parsing import parse_expression
from slither.solc_parsing.variables.function_type_variable import FunctionTypeVariableSolc
from slither.solc_parsing.declarations.contract import ContractSolc
from slither.solc_parsing.declarations.function import FunctionSolc
from slither.solc_parsing.declarations.using_for_top_level import UsingForTopLevelSolc
from slither.solc_parsing.declarations.custom_error import CustomErrorSolc
from slither.solc_parsing.declarations.structure_top_level import StructureTopLevelSolc
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
from slither.solc_parsing.variables.top_level_variable import TopLevelVariableSolc
sl: "SlitherCompilationUnit"
renaming: Dict[str, str]
user_defined_types: Dict[str, TypeAlias]
# Note: for convenicence top level functions use the same parser than function in contract
# but contract_parser is set to None
if isinstance(caller_context, SlitherCompilationUnitSolc) or (
isinstance(caller_context, FunctionSolc) and caller_context.contract_parser is None
):
structures_direct_access: List["Structure"]
if isinstance(caller_context, SlitherCompilationUnitSolc):
sl = caller_context.compilation_unit
next_context = caller_context
renaming = {}
user_defined_types = sl.user_defined_value_types
else:
assert isinstance(caller_context, FunctionSolc)
sl = caller_context.underlying_function.compilation_unit
next_context = caller_context.slither_parser
renaming = caller_context.underlying_function.file_scope.renaming
user_defined_types = caller_context.underlying_function.file_scope.user_defined_types
structures_direct_access = sl.structures_top_level
all_structuress = [c.structures for c in sl.contracts]
all_structures = [item for sublist in all_structuress for item in sublist]
all_structures += structures_direct_access
enums_direct_access = sl.enums_top_level
all_enumss = [c.enums for c in sl.contracts]
all_enums = [item for sublist in all_enumss for item in sublist]
all_enums += enums_direct_access
contracts = sl.contracts
functions = []
elif isinstance(
caller_context,
(StructureTopLevelSolc, CustomErrorSolc, TopLevelVariableSolc, UsingForTopLevelSolc),
):
if isinstance(caller_context, StructureTopLevelSolc):
scope = caller_context.underlying_structure.file_scope
elif isinstance(caller_context, TopLevelVariableSolc):
scope = caller_context.underlying_variable.file_scope
elif isinstance(caller_context, UsingForTopLevelSolc):
scope = caller_context.underlying_using_for.file_scope
else:
assert isinstance(caller_context, CustomErrorSolc)
custom_error = caller_context.underlying_custom_error
if isinstance(custom_error, CustomErrorTopLevel):
scope = custom_error.file_scope
else:
assert isinstance(custom_error, CustomErrorContract)
scope = custom_error.contract.file_scope
sl = caller_context.compilation_unit
next_context = caller_context.slither_parser
structures_direct_access = list(scope.structures.values())
all_structuress = [c.structures for c in scope.contracts.values()]
all_structures = [item for sublist in all_structuress for item in sublist]
all_structures += structures_direct_access
enums_direct_access = []
all_enumss = [c.enums for c in scope.contracts.values()]
all_enums = [item for sublist in all_enumss for item in sublist]
all_enums += scope.enums.values()
contracts = scope.contracts.values()
functions = list(scope.functions)
renaming = scope.renaming
user_defined_types = scope.user_defined_types
elif isinstance(caller_context, (ContractSolc, FunctionSolc)):
sl = caller_context.compilation_unit
if isinstance(caller_context, FunctionSolc):
underlying_func = caller_context.underlying_function
# If contract_parser is set to None, then underlying_function is a functionContract
# See note above
assert isinstance(underlying_func, FunctionContract)
contract = underlying_func.contract
next_context = caller_context.contract_parser
scope = caller_context.underlying_function.file_scope
else:
contract = caller_context.underlying_contract
next_context = caller_context
scope = caller_context.underlying_contract.file_scope
structures_direct_access = contract.structures
structures_direct_access += contract.file_scope.structures.values()
all_structuress = [c.structures for c in contract.file_scope.contracts.values()]
all_structures = [item for sublist in all_structuress for item in sublist]
all_structures += contract.file_scope.structures.values()
enums_direct_access: List["Enum"] = contract.enums
enums_direct_access += contract.file_scope.enums.values()
all_enumss = [c.enums for c in contract.file_scope.contracts.values()]
all_enums = [item for sublist in all_enumss for item in sublist]
all_enums += contract.file_scope.enums.values()
contracts = contract.file_scope.contracts.values()
functions = contract.functions + contract.modifiers
renaming = scope.renaming
user_defined_types = scope.user_defined_types
else:
raise ParsingError(f"Incorrect caller context: {type(caller_context)}")
is_compact_ast = caller_context.is_compact_ast
if is_compact_ast:
key = "nodeType"
else:
key = "name"
if isinstance(t, UnknownType):
name = t.name
if name in renaming:
name = renaming[name]
if name in user_defined_types:
return user_defined_types[name]
return _find_from_type_name(
name,
functions,
contracts,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
if t[key] == "ElementaryTypeName":
if is_compact_ast:
return ElementaryType(t["name"])
return ElementaryType(t["attributes"][key])
if t[key] == "UserDefinedTypeName":
if is_compact_ast:
name = t["typeDescriptions"]["typeString"]
if name in renaming:
name = renaming[name]
if name in user_defined_types:
return user_defined_types[name]
type_found = _find_from_type_name(
name,
functions,
contracts,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
_add_type_references(type_found, t["src"], sl)
return type_found
# Determine if we have a type node (otherwise we use the name node, as some older solc did not have 'type').
type_name_key = "type" if "type" in t["attributes"] else key
name = t["attributes"][type_name_key]
if name in renaming:
name = renaming[name]
if name in user_defined_types:
return user_defined_types[name]
type_found = _find_from_type_name(
name,
functions,
contracts,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
_add_type_references(type_found, t["src"], sl)
return type_found
# Introduced with Solidity 0.8
if t[key] == "IdentifierPath":
if is_compact_ast:
name = t["name"]
if name in renaming:
name = renaming[name]
if name in user_defined_types:
return user_defined_types[name]
type_found = _find_from_type_name(
name,
functions,
contracts,
structures_direct_access,
all_structures,
enums_direct_access,
all_enums,
)
_add_type_references(type_found, t["src"], sl)
return type_found
raise SlitherError("Solidity 0.8 not supported with the legacy AST")
if t[key] == "ArrayTypeName":
length = None
if is_compact_ast:
if t.get("length", None):
length = parse_expression(t["length"], caller_context)
array_type = parse_type(t["baseType"], next_context)
else:
if len(t["children"]) == 2:
length = parse_expression(t["children"][1], caller_context)
else:
assert len(t["children"]) == 1
array_type = parse_type(t["children"][0], next_context)
return ArrayType(array_type, length)
if t[key] == "Mapping":
if is_compact_ast:
mappingFrom = parse_type(t["keyType"], next_context)
mappingTo = parse_type(t["valueType"], next_context)
else:
assert len(t["children"]) == 2
mappingFrom = parse_type(t["children"][0], next_context)
mappingTo = parse_type(t["children"][1], next_context)
return MappingType(mappingFrom, mappingTo)
if t[key] == "FunctionTypeName":
if is_compact_ast:
params = t["parameterTypes"]
return_values = t["returnParameterTypes"]
index = "parameters"
else:
assert len(t["children"]) == 2
params = t["children"][0]
return_values = t["children"][1]
index = "children"
assert params[key] == "ParameterList"
assert return_values[key] == "ParameterList"
params_vars: List[FunctionTypeVariable] = []
return_values_vars: List[FunctionTypeVariable] = []
for p in params[index]:
var = FunctionTypeVariable()
var.set_offset(p["src"], caller_context.compilation_unit)
var_parser = FunctionTypeVariableSolc(var, p)
var_parser.analyze(caller_context)
params_vars.append(var)
for p in return_values[index]:
var = FunctionTypeVariable()
var.set_offset(p["src"], caller_context.compilation_unit)
var_parser = FunctionTypeVariableSolc(var, p)
var_parser.analyze(caller_context)
return_values_vars.append(var)
return FunctionType(params_vars, return_values_vars)
raise ParsingError("Type name not found " + str(t))
| 20,012 | Python | .py | 433 | 35.734411 | 146 | 0.624917 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,085 | node.py | NioTheFirst_ScType/slither/solc_parsing/cfg/node.py | from typing import Optional, Dict
from slither.core.cfg.node import Node
from slither.core.cfg.node import NodeType
from slither.core.expressions.assignment_operation import (
AssignmentOperation,
AssignmentOperationType,
)
from slither.core.expressions.identifier import Identifier
from slither.solc_parsing.expressions.expression_parsing import parse_expression
from slither.visitors.expression.find_calls import FindCalls
from slither.visitors.expression.read_var import ReadVar
from slither.visitors.expression.write_var import WriteVar
class NodeSolc:
def __init__(self, node: Node):
self._unparsed_expression: Optional[Dict] = None
self._node = node
@property
def underlying_node(self) -> Node:
return self._node
def add_unparsed_expression(self, expression: Dict):
assert self._unparsed_expression is None
self._unparsed_expression = expression
def analyze_expressions(self, caller_context):
if self._node.type == NodeType.VARIABLE and not self._node.expression:
self._node.add_expression(self._node.variable_declaration.expression)
if self._unparsed_expression:
expression = parse_expression(self._unparsed_expression, caller_context)
self._node.add_expression(expression)
# self._unparsed_expression = None
if self._node.expression:
if self._node.type == NodeType.VARIABLE:
# Update the expression to be an assignement to the variable
_expression = AssignmentOperation(
Identifier(self._node.variable_declaration),
self._node.expression,
AssignmentOperationType.ASSIGN,
self._node.variable_declaration.type,
)
_expression.set_offset(
self._node.expression.source_mapping, self._node.compilation_unit
)
self._node.add_expression(_expression, bypass_verif_empty=True)
expression = self._node.expression
read_var = ReadVar(expression)
self._node.variables_read_as_expression = read_var.result()
write_var = WriteVar(expression)
self._node.variables_written_as_expression = write_var.result()
find_call = FindCalls(expression)
self._node.calls_as_expression = find_call.result()
self._node.external_calls_as_expressions = [
c for c in self._node.calls_as_expression if not isinstance(c.called, Identifier)
]
self._node.internal_calls_as_expressions = [
c for c in self._node.calls_as_expression if isinstance(c.called, Identifier)
]
| 2,761 | Python | .py | 55 | 39.690909 | 97 | 0.665306 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,086 | structure_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/structure_variable.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.structure_variable import StructureVariable
class StructureVariableSolc(VariableDeclarationSolc):
def __init__(self, variable: StructureVariable, variable_data: Dict):
super().__init__(variable, variable_data)
@property
def underlying_variable(self) -> StructureVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, StructureVariable)
return self._variable
| 583 | Python | .py | 11 | 47.636364 | 87 | 0.778169 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,087 | variable_declaration.py | NioTheFirst_ScType/slither/solc_parsing/variables/variable_declaration.py | import logging
import re
from typing import Dict
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.expressions.expression_parsing import parse_expression
from slither.core.variables.variable import Variable
from slither.solc_parsing.solidity_types.type_parsing import parse_type, UnknownType
from slither.core.solidity_types.elementary_type import (
ElementaryType,
NonElementaryType,
)
from slither.solc_parsing.exceptions import ParsingError
logger = logging.getLogger("VariableDeclarationSolcParsing")
class MultipleVariablesDeclaration(Exception):
"""
This is raised on
var (a,b) = ...
It should occur only on local variable definition
"""
# pylint: disable=unnecessary-pass
pass
class VariableDeclarationSolc:
def __init__(
self, variable: Variable, variable_data: Dict
): # pylint: disable=too-many-branches
"""
A variable can be declared through a statement, or directly.
If it is through a statement, the following children may contain
the init value.
It may be possible that the variable is declared through a statement,
but the init value is declared at the VariableDeclaration children level
"""
self._variable = variable
self._was_analyzed = False
self._elem_to_parse = None
self._initializedNotParsed = None
self._is_compact_ast = False
self._reference_id = None
if "nodeType" in variable_data:
self._is_compact_ast = True
nodeType = variable_data["nodeType"]
if nodeType in [
"VariableDeclarationStatement",
"VariableDefinitionStatement",
]:
if len(variable_data["declarations"]) > 1:
raise MultipleVariablesDeclaration
init = None
if "initialValue" in variable_data:
init = variable_data["initialValue"]
self._init_from_declaration(variable_data["declarations"][0], init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, variable_data.get("value", None))
else:
raise ParsingError(f"Incorrect variable declaration type {nodeType}")
else:
nodeType = variable_data["name"]
if nodeType in [
"VariableDeclarationStatement",
"VariableDefinitionStatement",
]:
if len(variable_data["children"]) == 2:
init = variable_data["children"][1]
elif len(variable_data["children"]) == 1:
init = None
elif len(variable_data["children"]) > 2:
raise MultipleVariablesDeclaration
else:
raise ParsingError(
"Variable declaration without children?" + str(variable_data)
)
declaration = variable_data["children"][0]
self._init_from_declaration(declaration, init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, False)
else:
raise ParsingError(f"Incorrect variable declaration type {nodeType}")
@property
def underlying_variable(self) -> Variable:
return self._variable
@property
def reference_id(self) -> int:
"""
Return the solc id. It can be compared with the referencedDeclaration attr
Returns None if it was not parsed (legacy AST)
"""
return self._reference_id
def _handle_comment(self, attributes: Dict):
if "documentation" in attributes and "text" in attributes["documentation"]:
candidates = attributes["documentation"]["text"].split(",")
for candidate in candidates:
if "@custom:security non-reentrant" in candidate:
self._variable.is_reentrant = False
write_protection = re.search(
r'@custom:security write-protection="([\w, ()]*)"', candidate
)
if write_protection:
if self._variable.write_protection is None:
self._variable.write_protection = []
self._variable.write_protection.append(write_protection.group(1))
def _analyze_variable_attributes(self, attributes: Dict):
if "visibility" in attributes:
self._variable.visibility = attributes["visibility"]
else:
self._variable.visibility = "internal"
def _init_from_declaration(self, var: Dict, init: bool): # pylint: disable=too-many-branches
if self._is_compact_ast:
attributes = var
self._typeName = attributes["typeDescriptions"]["typeString"]
else:
assert len(var["children"]) <= 2
assert var["name"] == "VariableDeclaration"
attributes = var["attributes"]
self._typeName = attributes["type"]
self._variable.name = attributes["name"]
# self._arrayDepth = 0
# self._isMapping = False
# self._mappingFrom = None
# self._mappingTo = False
# self._initial_expression = None
# self._type = None
# Only for comapct ast format
# the id can be used later if referencedDeclaration
# is provided
if "id" in var:
self._reference_id = var["id"]
if "constant" in attributes:
self._variable.is_constant = attributes["constant"]
if "mutability" in attributes:
# Note: this checked is not needed if "constant" was already in attribute, but we keep it
# for completion
if attributes["mutability"] == "constant":
self._variable.is_constant = True
if attributes["mutability"] == "immutable":
self._variable.is_immutable = True
self._handle_comment(attributes)
self._analyze_variable_attributes(attributes)
if self._is_compact_ast:
if var["typeName"]:
self._elem_to_parse = var["typeName"]
else:
self._elem_to_parse = UnknownType(var["typeDescriptions"]["typeString"])
else:
if not var["children"]:
# It happens on variable declared inside loop declaration
try:
self._variable.type = ElementaryType(self._typeName)
self._elem_to_parse = None
except NonElementaryType:
self._elem_to_parse = UnknownType(self._typeName)
else:
self._elem_to_parse = var["children"][0]
if self._is_compact_ast:
self._initializedNotParsed = init
if init:
self._variable.initialized = True
else:
if init: # there are two way to init a var local in the AST
assert len(var["children"]) <= 1
self._variable.initialized = True
self._initializedNotParsed = init
elif len(var["children"]) in [0, 1]:
self._variable.initialized = False
self._initializedNotParsed = []
else:
assert len(var["children"]) == 2
self._variable.initialized = True
self._initializedNotParsed = var["children"][1]
def analyze(self, caller_context: CallerContextExpression):
# Can be re-analyzed due to inheritance
if self._was_analyzed:
return
self._was_analyzed = True
if self._elem_to_parse:
self._variable.type = parse_type(self._elem_to_parse, caller_context)
self._elem_to_parse = None
if self._variable.initialized:
self._variable.expression = parse_expression(self._initializedNotParsed, caller_context)
self._initializedNotParsed = None
| 8,123 | Python | .py | 179 | 33.407821 | 101 | 0.597749 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,088 | local_variable_init_from_tuple.py | NioTheFirst_ScType/slither/solc_parsing/variables/local_variable_init_from_tuple.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.local_variable_init_from_tuple import LocalVariableInitFromTuple
class LocalVariableInitFromTupleSolc(VariableDeclarationSolc):
def __init__(self, variable: LocalVariableInitFromTuple, variable_data: Dict, index: int):
super().__init__(variable, variable_data)
variable.tuple_index = index
@property
def underlying_variable(self) -> LocalVariableInitFromTuple:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, LocalVariableInitFromTuple)
return self._variable
| 689 | Python | .py | 12 | 51.75 | 94 | 0.783061 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,089 | state_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/state_variable.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.state_variable import StateVariable
class StateVariableSolc(VariableDeclarationSolc):
def __init__(self, variable: StateVariable, variable_data: Dict):
super().__init__(variable, variable_data)
@property
def underlying_variable(self) -> StateVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, StateVariable)
return self._variable
| 559 | Python | .py | 11 | 45.454545 | 87 | 0.768382 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,090 | top_level_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/top_level_variable.py | from typing import Dict, TYPE_CHECKING
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
if TYPE_CHECKING:
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
from slither.core.compilation_unit import SlitherCompilationUnit
class TopLevelVariableSolc(VariableDeclarationSolc, CallerContextExpression):
def __init__(
self,
variable: TopLevelVariable,
variable_data: Dict,
slither_parser: "SlitherCompilationUnitSolc",
):
super().__init__(variable, variable_data)
self._slither_parser = slither_parser
@property
def is_compact_ast(self) -> bool:
return self._slither_parser.is_compact_ast
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self._slither_parser.compilation_unit
def get_key(self) -> str:
return self._slither_parser.get_key()
@property
def slither_parser(self) -> "SlitherCompilationUnitSolc":
return self._slither_parser
@property
def underlying_variable(self) -> TopLevelVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, TopLevelVariable)
return self._variable
| 1,438 | Python | .py | 32 | 38.78125 | 93 | 0.748747 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,091 | function_type_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/function_type_variable.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.function_type_variable import FunctionTypeVariable
class FunctionTypeVariableSolc(VariableDeclarationSolc):
def __init__(self, variable: FunctionTypeVariable, variable_data: Dict):
super().__init__(variable, variable_data)
@property
def underlying_variable(self) -> FunctionTypeVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, FunctionTypeVariable)
return self._variable
| 602 | Python | .py | 11 | 49.363636 | 87 | 0.783646 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,092 | local_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/local_variable.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.local_variable import LocalVariable
class LocalVariableSolc(VariableDeclarationSolc):
def __init__(self, variable: LocalVariable, variable_data: Dict):
super().__init__(variable, variable_data)
@property
def underlying_variable(self) -> LocalVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, LocalVariable)
return self._variable
def _analyze_variable_attributes(self, attributes: Dict):
"""'
Variable Location
Can be storage/memory or default
"""
if "storageLocation" in attributes:
location = attributes["storageLocation"]
self.underlying_variable.set_location(location)
else:
if "memory" in attributes["type"]:
self.underlying_variable.set_location("memory")
elif "storage" in attributes["type"]:
self.underlying_variable.set_location("storage")
else:
self.underlying_variable.set_location("default")
super()._analyze_variable_attributes(attributes)
| 1,252 | Python | .py | 27 | 37.296296 | 87 | 0.679245 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,093 | event_variable.py | NioTheFirst_ScType/slither/solc_parsing/variables/event_variable.py | from typing import Dict
from slither.solc_parsing.variables.variable_declaration import VariableDeclarationSolc
from slither.core.variables.event_variable import EventVariable
class EventVariableSolc(VariableDeclarationSolc):
def __init__(self, variable: EventVariable, variable_data: Dict):
super().__init__(variable, variable_data)
@property
def underlying_variable(self) -> EventVariable:
# Todo: Not sure how to overcome this with mypy
assert isinstance(self._variable, EventVariable)
return self._variable
def _analyze_variable_attributes(self, attributes: Dict):
"""
Analyze event variable attributes
:param attributes: The event variable attributes to parse.
:return: None
"""
# Check for the indexed attribute
if "indexed" in attributes:
self.underlying_variable.indexed = attributes["indexed"]
super()._analyze_variable_attributes(attributes)
| 983 | Python | .py | 21 | 39.571429 | 87 | 0.718325 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,094 | parse_yul.py | NioTheFirst_ScType/slither/solc_parsing/yul/parse_yul.py | import abc
import json
from typing import Optional, Dict, List, Union
from slither.core.cfg.node import NodeType, Node, link_nodes
from slither.core.cfg.scope import Scope
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.declarations import (
Function,
SolidityFunction,
Contract,
)
from slither.core.declarations.function import FunctionLanguage
from slither.core.declarations.function_contract import FunctionContract
from slither.core.declarations.function_top_level import FunctionTopLevel
from slither.core.expressions import (
Literal,
AssignmentOperation,
AssignmentOperationType,
Identifier,
CallExpression,
TupleExpression,
BinaryOperation,
UnaryOperation,
)
from slither.core.expressions.expression import Expression
from slither.core.scope.scope import FileScope
from slither.core.solidity_types import ElementaryType
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.variables.local_variable import LocalVariable
from slither.exceptions import SlitherException
from slither.solc_parsing.yul.evm_functions import (
format_function_descriptor,
builtins,
YulBuiltin,
unary_ops,
binary_ops,
)
from slither.solc_parsing.expressions.find_variable import find_top_level
from slither.visitors.expression.find_calls import FindCalls
from slither.visitors.expression.read_var import ReadVar
from slither.visitors.expression.write_var import WriteVar
class YulNode:
def __init__(self, node: Node, scope: "YulScope"):
self._node = node
self._scope = scope
self._unparsed_expression: Optional[Dict] = None
@property
def underlying_node(self) -> Node:
return self._node
def add_unparsed_expression(self, expression: Dict) -> None:
assert self._unparsed_expression is None
self._unparsed_expression = expression
def analyze_expressions(self) -> None:
if self._node.type == NodeType.VARIABLE and not self._node.expression:
expression = self._node.variable_declaration.expression
if expression:
self._node.add_expression(expression)
if self._unparsed_expression:
expression = parse_yul(self._scope, self, self._unparsed_expression)
if expression:
self._node.add_expression(expression)
if self._node.expression:
if self._node.type == NodeType.VARIABLE:
# Update the expression to be an assignement to the variable
variable_declaration = self._node.variable_declaration
if variable_declaration:
_expression = AssignmentOperation(
Identifier(self._node.variable_declaration),
self._node.expression,
AssignmentOperationType.ASSIGN,
variable_declaration.type,
)
_expression.set_offset(
self._node.expression.source_mapping, self._node.compilation_unit
)
self._node.add_expression(_expression, bypass_verif_empty=True)
expression = self._node.expression
read_var = ReadVar(expression)
self._node.variables_read_as_expression = read_var.result()
write_var = WriteVar(expression)
self._node.variables_written_as_expression = write_var.result()
find_call = FindCalls(expression)
self._node.calls_as_expression = find_call.result()
self._node.external_calls_as_expressions = [
c for c in self._node.calls_as_expression if not isinstance(c.called, Identifier)
]
self._node.internal_calls_as_expressions = [
c for c in self._node.calls_as_expression if isinstance(c.called, Identifier)
]
def link_underlying_nodes(node1: YulNode, node2: YulNode):
link_nodes(node1.underlying_node, node2.underlying_node)
def _name_to_yul_name(variable_name: str, yul_id: List[str]) -> str:
"""
Translate the variable name to a unique yul name
Within the same function, yul blocks can declare
different variables with the same name
We need to create unique name per variable
to prevent collision during the SSA generation
:param var:
:param yul_id:
:return:
"""
return variable_name + f"_{'_'.join(yul_id)}"
class YulScope(metaclass=abc.ABCMeta):
__slots__ = [
"_contract",
"_id",
"_yul_local_variables",
"_yul_local_functions",
"_parent_func",
]
def __init__(
self, contract: Optional[Contract], yul_id: List[str], parent_func: Function
) -> None:
self._contract = contract
self._id: List[str] = yul_id
self._yul_local_variables: List[YulLocalVariable] = []
self._yul_local_functions: List[YulFunction] = []
self._parent_func: Function = parent_func
@property
def id(self) -> List[str]:
return self._id
@property
def contract(self) -> Optional[Contract]:
return self._contract
@property
def compilation_unit(self) -> SlitherCompilationUnit:
return self._parent_func.compilation_unit
@property
def parent_func(self) -> Optional[Function]:
return self._parent_func
@property
@abc.abstractmethod
def function(self) -> Function:
pass
@abc.abstractmethod
def new_node(self, node_type: NodeType, src: Union[str, Dict]) -> YulNode:
pass
@property
def file_scope(self) -> FileScope:
return self._parent_func.file_scope
def add_yul_local_variable(self, var: "YulLocalVariable") -> None:
self._yul_local_variables.append(var)
def get_yul_local_variable_from_name(self, variable_name: str) -> Optional["YulLocalVariable"]:
return next(
(
v
for v in self._yul_local_variables
if v.underlying.name == _name_to_yul_name(variable_name, self.id)
),
None,
)
def add_yul_local_function(self, func: "YulFunction") -> None:
self._yul_local_functions.append(func)
def get_yul_local_function_from_name(self, func_name: str) -> Optional["YulLocalVariable"]:
return next(
(v for v in self._yul_local_functions if v.underlying.name == func_name),
None,
)
class YulLocalVariable: # pylint: disable=too-few-public-methods
__slots__ = ["_variable", "_root"]
def __init__(self, var: LocalVariable, root: YulScope, ast: Dict):
assert ast["nodeType"] == "YulTypedName"
self._variable = var
self._root = root
# start initializing the underlying variable
var.set_function(root.function)
var.set_offset(ast["src"], root.compilation_unit)
var.name = _name_to_yul_name(ast["name"], root.id)
var.set_type(ElementaryType("uint256"))
var.set_location("memory")
@property
def underlying(self) -> LocalVariable:
return self._variable
class YulFunction(YulScope):
__slots__ = ["_function", "_root", "_ast", "_nodes", "_entrypoint", "node_scope"]
def __init__(
self, func: Function, root: YulScope, ast: Dict, node_scope: Union[Function, Scope]
):
super().__init__(root.contract, root.id + [ast["name"]], parent_func=root.parent_func)
assert ast["nodeType"] == "YulFunctionDefinition"
self._function: Function = func
self._root: YulScope = root
self._ast: Dict = ast
# start initializing the underlying function
func.name = ast["name"]
func.set_visibility("private")
if isinstance(func, SourceMapping):
func.set_offset(ast["src"], root.compilation_unit)
if isinstance(func, FunctionContract):
func.set_contract(root.contract)
func.set_contract_declarer(root.contract)
func.compilation_unit = root.compilation_unit
func.internal_scope = root.id
func.is_implemented = True
self.node_scope = node_scope
self._nodes: List[YulNode] = []
self._entrypoint = self.new_node(NodeType.ASSEMBLY, ast["src"])
func.entry_point = self._entrypoint.underlying_node
self.add_yul_local_function(self)
@property
def underlying(self) -> Function:
return self._function
@property
def function(self) -> Function:
return self._function
def convert_body(self) -> None:
node = self.new_node(NodeType.ENTRYPOINT, self._ast["src"])
link_underlying_nodes(self._entrypoint, node)
for param in self._ast.get("parameters", []):
node = convert_yul(self, node, param, self.node_scope)
self._function.add_parameters(
self.get_yul_local_variable_from_name(param["name"]).underlying
)
for ret in self._ast.get("returnVariables", []):
node = convert_yul(self, node, ret, self.node_scope)
self._function.add_return(self.get_yul_local_variable_from_name(ret["name"]).underlying)
convert_yul(self, node, self._ast["body"], self.node_scope)
def parse_body(self) -> None:
for node in self._nodes:
node.analyze_expressions()
def new_node(self, node_type, src) -> YulNode:
if self._function:
node = self._function.new_node(node_type, src, self.node_scope)
else:
raise SlitherException("standalone yul objects are not supported yet")
yul_node = YulNode(node, self)
self._nodes.append(yul_node)
return yul_node
class YulBlock(YulScope):
"""
A YulBlock represents a standalone yul component.
For example an inline assembly block
"""
# pylint: disable=redefined-slots-in-subclass
__slots__ = ["_entrypoint", "_parent_func", "_nodes", "node_scope"]
def __init__(
self,
contract: Optional[Contract],
entrypoint: Node,
yul_id: List[str],
node_scope: Union[Scope, Function],
):
super().__init__(contract, yul_id, entrypoint.function)
self._entrypoint: YulNode = YulNode(entrypoint, self)
self._nodes: List[YulNode] = []
self.node_scope = node_scope
@property
def entrypoint(self) -> YulNode:
return self._entrypoint
@property
def function(self) -> Function:
return self._parent_func
def new_node(self, node_type: NodeType, src: Union[str, Dict]) -> YulNode:
if self._parent_func:
node = self._parent_func.new_node(node_type, src, self.node_scope)
else:
raise SlitherException("standalone yul objects are not supported yet")
yul_node = YulNode(node, self)
self._nodes.append(yul_node)
return yul_node
def convert(self, ast: Dict) -> YulNode:
return convert_yul(self, self._entrypoint, ast, self.node_scope)
def analyze_expressions(self) -> None:
for node in self._nodes:
node.analyze_expressions()
###################################################################################
###################################################################################
# region Block conversion
###################################################################################
###################################################################################
# The functions in this region, at a high level, will extract the control flow
# structures and metadata from the input AST. These include things like function
# definitions and local variables.
#
# Each function takes three parameters:
# 1) root is the current YulScope, where you can find things like local variables
# 2) parent is the previous YulNode, which you'll have to link to
# 3) ast is a dictionary and is the current node in the Yul ast being converted
#
# Each function must return a single parameter:
# 1) the new YulNode that the CFG ends at
#
# The entrypoint is the function at the end of this region, `convert_yul`, which
# dispatches to a specialized function based on a lookup dictionary.
def convert_yul_block(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
for statement in ast["statements"]:
parent = convert_yul(root, parent, statement, node_scope)
return parent
def convert_yul_function_definition(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
top_node_scope = node_scope
while not isinstance(top_node_scope, Function):
top_node_scope = top_node_scope.father
func: Union[FunctionTopLevel, FunctionContract]
if isinstance(top_node_scope, FunctionTopLevel):
scope = root.file_scope
func = FunctionTopLevel(root.compilation_unit, scope)
# Note: we do not add the function in the scope
# While its a top level function, it is not accessible outside of the function definition
# In practice we should probably have a specific function type for function defined within a function
else:
func = FunctionContract(root.compilation_unit)
func.function_language = FunctionLanguage.Yul
yul_function = YulFunction(func, root, ast, node_scope)
if root.contract:
root.contract.add_function(func)
root.compilation_unit.add_function(func)
root.add_yul_local_function(yul_function)
yul_function.convert_body()
yul_function.parse_body()
return parent
def convert_yul_variable_declaration(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
for variable_ast in ast["variables"]:
parent = convert_yul(root, parent, variable_ast, node_scope)
node = root.new_node(NodeType.EXPRESSION, ast["src"])
node.add_unparsed_expression(ast)
link_underlying_nodes(parent, node)
return node
def convert_yul_assignment(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
node = root.new_node(NodeType.EXPRESSION, ast["src"])
node.add_unparsed_expression(ast)
link_underlying_nodes(parent, node)
return node
def convert_yul_expression_statement(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
src = ast["src"]
expression_ast = ast["expression"]
expression = root.new_node(NodeType.EXPRESSION, src)
expression.add_unparsed_expression(expression_ast)
link_underlying_nodes(parent, expression)
return expression
def convert_yul_if(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
# we're cheating and pretending that yul supports if/else so we can convert switch cleaner
src = ast["src"]
condition_ast = ast["condition"]
true_body_ast = ast["body"]
false_body_ast = ast["false_body"] if "false_body" in ast else None
condition = root.new_node(NodeType.IF, src)
end = root.new_node(NodeType.ENDIF, src)
condition.add_unparsed_expression(condition_ast)
true_body = convert_yul(root, condition, true_body_ast, node_scope)
if false_body_ast:
false_body = convert_yul(root, condition, false_body_ast, node_scope)
link_underlying_nodes(false_body, end)
else:
link_underlying_nodes(condition, end)
link_underlying_nodes(parent, condition)
link_underlying_nodes(true_body, end)
return end
def convert_yul_switch(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
"""
This is unfortunate. We don't really want a switch in our IR so we're going to
translate it into a series of if/else statements.
"""
cases_ast = ast["cases"]
expression_ast = ast["expression"]
# this variable stores the result of the expression so we don't accidentally compute it more than once
switch_expr_var = f"switch_expr_{ast['src'].replace(':', '_')}"
rewritten_switch = {
"nodeType": "YulBlock",
"src": ast["src"],
"statements": [
{
"nodeType": "YulVariableDeclaration",
"src": expression_ast["src"],
"variables": [
{
"nodeType": "YulTypedName",
"src": expression_ast["src"],
"name": switch_expr_var,
"type": "",
},
],
"value": expression_ast,
},
],
}
last_if: Optional[Dict] = None
default_ast = None
for case_ast in cases_ast:
body_ast = case_ast["body"]
value_ast = case_ast["value"]
if value_ast == "default":
default_ast = case_ast
continue
current_if = {
"nodeType": "YulIf",
"src": case_ast["src"],
"condition": {
"nodeType": "YulFunctionCall",
"src": case_ast["src"],
"functionName": {
"nodeType": "YulIdentifier",
"src": case_ast["src"],
"name": "eq",
},
"arguments": [
{
"nodeType": "YulIdentifier",
"src": case_ast["src"],
"name": switch_expr_var,
},
value_ast,
],
},
"body": body_ast,
}
if last_if:
last_if["false_body"] = current_if # pylint: disable=unsupported-assignment-operation
else:
rewritten_switch["statements"].append(current_if)
last_if = current_if
if default_ast:
body_ast = default_ast["body"]
if last_if:
last_if["false_body"] = body_ast
else:
rewritten_switch["statements"].append(body_ast)
return convert_yul(root, parent, rewritten_switch, node_scope)
def convert_yul_for_loop(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
pre_ast = ast["pre"]
condition_ast = ast["condition"]
post_ast = ast["post"]
body_ast = ast["body"]
start_loop = root.new_node(NodeType.STARTLOOP, ast["src"])
end_loop = root.new_node(NodeType.ENDLOOP, ast["src"])
link_underlying_nodes(parent, start_loop)
pre = convert_yul(root, start_loop, pre_ast, node_scope)
condition = root.new_node(NodeType.IFLOOP, condition_ast["src"])
condition.add_unparsed_expression(condition_ast)
link_underlying_nodes(pre, condition)
link_underlying_nodes(condition, end_loop)
body = convert_yul(root, condition, body_ast, node_scope)
post = convert_yul(root, body, post_ast, node_scope)
link_underlying_nodes(post, condition)
return end_loop
def convert_yul_break(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
break_ = root.new_node(NodeType.BREAK, ast["src"])
link_underlying_nodes(parent, break_)
return break_
def convert_yul_continue(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
continue_ = root.new_node(NodeType.CONTINUE, ast["src"])
link_underlying_nodes(parent, continue_)
return continue_
def convert_yul_leave(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
leave = root.new_node(NodeType.RETURN, ast["src"])
link_underlying_nodes(parent, leave)
return leave
def convert_yul_typed_name(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
local_var = LocalVariable()
var = YulLocalVariable(local_var, root, ast)
root.add_yul_local_variable(var)
node = root.new_node(NodeType.VARIABLE, ast["src"])
node.underlying_node.add_variable_declaration(local_var)
link_underlying_nodes(parent, node)
return node
def convert_yul_unsupported(
root: YulScope, parent: YulNode, ast: Dict, _node_scope: Union[Function, Scope]
) -> YulNode:
raise SlitherException(
f"no converter available for {ast['nodeType']} {json.dumps(ast, indent=2)}"
)
def convert_yul(
root: YulScope, parent: YulNode, ast: Dict, node_scope: Union[Function, Scope]
) -> YulNode:
return converters.get(ast["nodeType"], convert_yul_unsupported)(root, parent, ast, node_scope)
converters = {
"YulBlock": convert_yul_block,
"YulFunctionDefinition": convert_yul_function_definition,
"YulVariableDeclaration": convert_yul_variable_declaration,
"YulAssignment": convert_yul_assignment,
"YulExpressionStatement": convert_yul_expression_statement,
"YulIf": convert_yul_if,
"YulSwitch": convert_yul_switch,
"YulForLoop": convert_yul_for_loop,
"YulBreak": convert_yul_break,
"YulContinue": convert_yul_continue,
"YulLeave": convert_yul_leave,
"YulTypedName": convert_yul_typed_name,
}
# endregion
###################################################################################
###################################################################################
###################################################################################
###################################################################################
# region Expression parsing
###################################################################################
###################################################################################
"""
The functions in this region parse the AST into expressions.
Each function takes three parameters:
1) root is the same root as above
2) node is the CFG node which stores this expression
3) ast is the same ast as above
Each function must return a single parameter:
1) The operation that was parsed, or None
The entrypoint is the function at the end of this region, `parse_yul`, which
dispatches to a specialized function based on a lookup dictionary.
"""
def _parse_yul_assignment_common(
root: YulScope, node: YulNode, ast: Dict, key: str
) -> Optional[Expression]:
lhs = [parse_yul(root, node, arg) for arg in ast[key]]
rhs = parse_yul(root, node, ast["value"])
return AssignmentOperation(
vars_to_val(lhs), rhs, AssignmentOperationType.ASSIGN, vars_to_typestr(lhs)
)
def parse_yul_variable_declaration(
root: YulScope, node: YulNode, ast: Dict
) -> Optional[Expression]:
"""
We already created variables in the conversion phase, so just do
the assignment
"""
if "value" not in ast or not ast["value"]:
return None
return _parse_yul_assignment_common(root, node, ast, "variables")
def parse_yul_assignment(root: YulScope, node: YulNode, ast: Dict) -> Optional[Expression]:
return _parse_yul_assignment_common(root, node, ast, "variableNames")
def parse_yul_function_call(root: YulScope, node: YulNode, ast: Dict) -> Optional[Expression]:
args = [parse_yul(root, node, arg) for arg in ast["arguments"]]
ident = parse_yul(root, node, ast["functionName"])
if not isinstance(ident, Identifier):
raise SlitherException("expected identifier from parsing function name")
if isinstance(ident.value, YulBuiltin):
name = ident.value.name
if name in binary_ops:
if name in ["shl", "shr", "sar"]:
# lmao ok
return BinaryOperation(args[1], args[0], binary_ops[name])
return BinaryOperation(args[0], args[1], binary_ops[name])
if name in unary_ops:
return UnaryOperation(args[0], unary_ops[name])
if name == "stop":
name = "return"
ident = Identifier(SolidityFunction(format_function_descriptor(name)))
args = [
Literal("0", ElementaryType("uint256")),
Literal("0", ElementaryType("uint256")),
]
else:
ident = Identifier(SolidityFunction(format_function_descriptor(ident.value.name)))
if isinstance(ident.value, Function):
return CallExpression(ident, args, vars_to_typestr(ident.value.returns))
if isinstance(ident.value, SolidityFunction):
return CallExpression(ident, args, vars_to_typestr(ident.value.return_type))
raise SlitherException(f"unexpected function call target type {str(type(ident.value))}")
def _check_for_state_variable_name(root: YulScope, potential_name: str) -> Optional[Identifier]:
root_function = root.function
if isinstance(root_function, FunctionContract):
var = root_function.contract.get_state_variable_from_name(potential_name)
if var:
return Identifier(var)
return None
def _parse_yul_magic_suffixes(name: str, root: YulScope) -> Optional[Expression]:
# check for magic suffixes
# TODO: the following leads to wrong IR
# Currently SlithIR doesnt support raw access to memory
# So things like .offset/.slot will return the variable
# Instaed of the actual offset/slot
if name.endswith(("_slot", ".slot")):
potential_name = name[:-5]
variable_found = _check_for_state_variable_name(root, potential_name)
if variable_found:
return variable_found
var = root.function.get_local_variable_from_name(potential_name)
if var and var.is_storage:
return Identifier(var)
if name.endswith(("_offset", ".offset")):
potential_name = name[:-7]
variable_found = _check_for_state_variable_name(root, potential_name)
if variable_found:
return variable_found
var = root.function.get_local_variable_from_name(potential_name)
if var and var.location == "calldata":
return Identifier(var)
if name.endswith(".length"):
# TODO: length should create a new IP operation LENGTH var
# The code below is an hotfix to allow slither to process length in yul
# Until we have a better support
potential_name = name[:-7]
var = root.function.get_local_variable_from_name(potential_name)
if var and var.location == "calldata":
return Identifier(var)
return None
def parse_yul_identifier(root: YulScope, _node: YulNode, ast: Dict) -> Optional[Expression]:
name = ast["name"]
if name in builtins:
return Identifier(YulBuiltin(name))
# check function-scoped variables
parent_func = root.parent_func
if parent_func:
local_variable = parent_func.get_local_variable_from_name(name)
if local_variable:
return Identifier(local_variable)
if isinstance(parent_func, FunctionContract):
assert parent_func.contract
state_variable = parent_func.contract.get_state_variable_from_name(name)
if state_variable:
return Identifier(state_variable)
# check yul-scoped variable
variable = root.get_yul_local_variable_from_name(name)
if variable:
return Identifier(variable.underlying)
# check yul-scoped function
func = root.get_yul_local_function_from_name(name)
if func:
return Identifier(func.underlying)
magic_suffix = _parse_yul_magic_suffixes(name, root)
if magic_suffix:
return magic_suffix
ret, _ = find_top_level(name, root.file_scope)
if ret:
return Identifier(ret)
raise SlitherException(f"unresolved reference to identifier {name}")
def parse_yul_literal(_root: YulScope, _node: YulNode, ast: Dict) -> Optional[Expression]:
kind = ast["kind"]
if kind == "string":
# Solc 0.8.0 use value, 0.8.16 use hexValue - not sure when this changed was made
if "value" in ast:
value = ast["value"]
else:
value = ast["hexValue"]
else:
# number/bool
value = ast["value"]
if not kind:
kind = "bool" if value in ["true", "false"] else "uint256"
if kind == "number":
kind = "uint256"
return Literal(value, ElementaryType(kind))
def parse_yul_typed_name(root: YulScope, _node: YulNode, ast: Dict) -> Optional[Expression]:
var = root.get_yul_local_variable_from_name(ast["name"])
i = Identifier(var.underlying)
i.type = var.underlying.type
return i
def parse_yul_unsupported(_root: YulScope, _node: YulNode, ast: Dict) -> Optional[Expression]:
raise SlitherException(f"no parser available for {ast['nodeType']} {json.dumps(ast, indent=2)}")
def parse_yul(root: YulScope, node: YulNode, ast: Dict) -> Optional[Expression]:
op: Expression = parsers.get(ast["nodeType"], parse_yul_unsupported)(root, node, ast)
if op:
op.set_offset(ast["src"], root.compilation_unit)
return op
parsers = {
"YulVariableDeclaration": parse_yul_variable_declaration,
"YulAssignment": parse_yul_assignment,
"YulFunctionCall": parse_yul_function_call,
"YulIdentifier": parse_yul_identifier,
"YulTypedName": parse_yul_typed_name,
"YulLiteral": parse_yul_literal,
}
# endregion
###################################################################################
###################################################################################
def vars_to_typestr(rets: List[Expression]) -> str:
if len(rets) == 0:
return ""
if len(rets) == 1:
return str(rets[0].type)
return f"tuple({','.join(str(ret.type) for ret in rets)})"
def vars_to_val(vars_to_convert):
if len(vars_to_convert) == 1:
return vars_to_convert[0]
return TupleExpression(vars_to_convert)
| 29,865 | Python | .py | 687 | 35.953421 | 109 | 0.63456 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,095 | evm_functions.py | NioTheFirst_ScType/slither/solc_parsing/yul/evm_functions.py | from slither.core.declarations.solidity_variables import SOLIDITY_FUNCTIONS
from slither.core.expressions import BinaryOperationType, UnaryOperationType
# taken from https://github.com/ethereum/solidity/blob/356cc91084114f840da66804b2a9fc1ac2846cff/libevmasm/Instruction.cpp#L180
evm_opcodes = [
"STOP",
"ADD",
"SUB",
"MUL",
"DIV",
"SDIV",
"MOD",
"SMOD",
"EXP",
"NOT",
"LT",
"GT",
"SLT",
"SGT",
"EQ",
"ISZERO",
"AND",
"OR",
"XOR",
"BYTE",
"SHL",
"SHR",
"SAR",
"ADDMOD",
"MULMOD",
"SIGNEXTEND",
"KECCAK256",
"ADDRESS",
"BALANCE",
"ORIGIN",
"CALLER",
"CALLVALUE",
"CALLDATALOAD",
"CALLDATASIZE",
"CALLDATACOPY",
"CODESIZE",
"CODECOPY",
"GASPRICE",
"EXTCODESIZE",
"EXTCODECOPY",
"RETURNDATASIZE",
"RETURNDATACOPY",
"EXTCODEHASH",
"BLOCKHASH",
"COINBASE",
"TIMESTAMP",
"NUMBER",
"DIFFICULTY",
"GASLIMIT",
"CHAINID",
"SELFBALANCE",
"POP",
"MLOAD",
"MSTORE",
"MSTORE8",
"SLOAD",
"SSTORE",
"JUMP",
"JUMPI",
"PC",
"MSIZE",
"GAS",
"JUMPDEST",
"PUSH1",
"PUSH2",
"PUSH3",
"PUSH4",
"PUSH5",
"PUSH6",
"PUSH7",
"PUSH8",
"PUSH9",
"PUSH10",
"PUSH11",
"PUSH12",
"PUSH13",
"PUSH14",
"PUSH15",
"PUSH16",
"PUSH17",
"PUSH18",
"PUSH19",
"PUSH20",
"PUSH21",
"PUSH22",
"PUSH23",
"PUSH24",
"PUSH25",
"PUSH26",
"PUSH27",
"PUSH28",
"PUSH29",
"PUSH30",
"PUSH31",
"PUSH32",
"DUP1",
"DUP2",
"DUP3",
"DUP4",
"DUP5",
"DUP6",
"DUP7",
"DUP8",
"DUP9",
"DUP10",
"DUP11",
"DUP12",
"DUP13",
"DUP14",
"DUP15",
"DUP16",
"SWAP1",
"SWAP2",
"SWAP3",
"SWAP4",
"SWAP5",
"SWAP6",
"SWAP7",
"SWAP8",
"SWAP9",
"SWAP10",
"SWAP11",
"SWAP12",
"SWAP13",
"SWAP14",
"SWAP15",
"SWAP16",
"LOG0",
"LOG1",
"LOG2",
"LOG3",
"LOG4",
"CREATE",
"CALL",
"CALLCODE",
"STATICCALL",
"RETURN",
"DELEGATECALL",
"CREATE2",
"REVERT",
"INVALID",
"SELFDESTRUCT",
]
yul_funcs = [
"datasize",
"dataoffset",
"datacopy",
"setimmutable",
"loadimmutable",
]
builtins = [
x.lower()
for x in evm_opcodes
if not (
x.startswith("PUSH")
or x.startswith("SWAP")
or x.startswith("DUP")
or x == "JUMP"
or x == "JUMPI"
or x == "JUMPDEST"
)
] + yul_funcs
function_args = {
"byte": [2, 1],
"addmod": [3, 1],
"mulmod": [3, 1],
"signextend": [2, 1],
"keccak256": [2, 1],
"pc": [0, 1],
"pop": [1, 0],
"mload": [1, 1],
"mstore": [2, 0],
"mstore8": [2, 0],
"sload": [1, 1],
"sstore": [2, 0],
"msize": [1, 1],
"gas": [0, 1],
"address": [0, 1],
"balance": [1, 1],
"selfbalance": [0, 1],
"caller": [0, 1],
"callvalue": [0, 1],
"calldataload": [1, 1],
"calldatasize": [0, 1],
"calldatacopy": [3, 0],
"codesize": [0, 1],
"codecopy": [3, 0],
"extcodesize": [1, 1],
"extcodecopy": [4, 0],
"returndatasize": [0, 1],
"returndatacopy": [3, 0],
"extcodehash": [1, 1],
"create": [3, 1],
"create2": [4, 1],
"call": [7, 1],
"callcode": [7, 1],
"delegatecall": [6, 1],
"staticcall": [6, 1],
"return": [2, 0],
"revert": [2, 0],
"selfdestruct": [1, 0],
"invalid": [0, 0],
"log0": [2, 0],
"log1": [3, 0],
"log2": [4, 0],
"log3": [5, 0],
"log4": [6, 0],
"chainid": [0, 1],
"origin": [0, 1],
"gasprice": [0, 1],
"blockhash": [1, 1],
"coinbase": [0, 1],
"timestamp": [0, 1],
"number": [0, 1],
"difficulty": [0, 1],
"gaslimit": [0, 1],
}
def format_function_descriptor(name):
if name not in function_args:
return name + "()"
return name + "(" + ",".join(["uint256"] * function_args[name][0]) + ")"
for k, v in function_args.items():
SOLIDITY_FUNCTIONS[format_function_descriptor(k)] = ["uint256"] * v[1]
unary_ops = {
"not": UnaryOperationType.TILD,
"iszero": UnaryOperationType.BANG,
}
binary_ops = {
"add": BinaryOperationType.ADDITION,
"sub": BinaryOperationType.SUBTRACTION,
"mul": BinaryOperationType.MULTIPLICATION,
"div": BinaryOperationType.DIVISION,
"sdiv": BinaryOperationType.DIVISION_SIGNED,
"mod": BinaryOperationType.MODULO,
"smod": BinaryOperationType.MODULO_SIGNED,
"exp": BinaryOperationType.POWER,
"lt": BinaryOperationType.LESS,
"gt": BinaryOperationType.GREATER,
"slt": BinaryOperationType.LESS_SIGNED,
"sgt": BinaryOperationType.GREATER_SIGNED,
"eq": BinaryOperationType.EQUAL,
"and": BinaryOperationType.AND,
"or": BinaryOperationType.OR,
"xor": BinaryOperationType.CARET,
"shl": BinaryOperationType.LEFT_SHIFT,
"shr": BinaryOperationType.RIGHT_SHIFT,
"sar": BinaryOperationType.RIGHT_SHIFT_ARITHMETIC,
}
class YulBuiltin: # pylint: disable=too-few-public-methods
def __init__(self, name: str) -> None:
self._name = name
@property
def name(self) -> str:
return self._name
| 5,287 | Python | .py | 258 | 15.577519 | 126 | 0.542373 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,096 | structure_contract.py | NioTheFirst_ScType/slither/solc_parsing/declarations/structure_contract.py | """
Structure module
"""
from typing import TYPE_CHECKING, Dict
from slither.core.declarations.structure import Structure
from slither.core.variables.structure_variable import StructureVariable
from slither.solc_parsing.variables.structure_variable import StructureVariableSolc
if TYPE_CHECKING:
from slither.solc_parsing.declarations.contract import ContractSolc
class StructureContractSolc: # pylint: disable=too-few-public-methods
"""
Structure class
"""
# elems = [(type, name)]
def __init__( # pylint: disable=too-many-arguments
self,
st: Structure,
struct: Dict,
contract_parser: "ContractSolc",
):
if contract_parser.is_compact_ast:
name = struct["name"]
attributes = struct
else:
name = struct["attributes"][contract_parser.get_key()]
attributes = struct["attributes"]
if "canonicalName" in attributes:
canonicalName = attributes["canonicalName"]
else:
canonicalName = contract_parser.underlying_contract.name + "." + name
children = struct["members"] if "members" in struct else struct.get("children", [])
self._structure = st
st.name = name
st.canonical_name = canonicalName
self._contract_parser = contract_parser
self._elemsNotParsed = children
def analyze(self):
for elem_to_parse in self._elemsNotParsed:
elem = StructureVariable()
elem.set_structure(self._structure)
elem.set_offset(elem_to_parse["src"], self._structure.contract.compilation_unit)
elem_parser = StructureVariableSolc(elem, elem_to_parse)
elem_parser.analyze(self._contract_parser)
self._structure.elems[elem.name] = elem
self._structure.add_elem_in_order(elem.name)
self._elemsNotParsed = []
| 1,909 | Python | .py | 46 | 33.26087 | 92 | 0.662703 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,097 | function.py | NioTheFirst_ScType/slither/solc_parsing/declarations/function.py | import logging
from typing import Dict, Optional, Union, List, TYPE_CHECKING
from slither.core.cfg.node import NodeType, link_nodes, insert_node, Node
from slither.core.cfg.scope import Scope
from slither.core.declarations.contract import Contract
from slither.core.declarations.function import (
Function,
ModifierStatements,
FunctionType,
)
from slither.core.declarations.function_contract import FunctionContract
from slither.core.expressions import AssignmentOperation
from slither.core.source_mapping.source_mapping import Source
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.local_variable_init_from_tuple import LocalVariableInitFromTuple
from slither.solc_parsing.cfg.node import NodeSolc
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.exceptions import ParsingError
from slither.solc_parsing.expressions.expression_parsing import parse_expression
from slither.solc_parsing.variables.local_variable import LocalVariableSolc
from slither.solc_parsing.variables.local_variable_init_from_tuple import (
LocalVariableInitFromTupleSolc,
)
from slither.solc_parsing.variables.variable_declaration import MultipleVariablesDeclaration
from slither.solc_parsing.yul.parse_yul import YulBlock
from slither.utils.expression_manipulations import SplitTernaryExpression
from slither.visitors.expression.export_values import ExportValues
from slither.visitors.expression.has_conditional import HasConditional
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
from slither.solc_parsing.declarations.contract import ContractSolc
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
from slither.core.compilation_unit import SlitherCompilationUnit
LOGGER = logging.getLogger("FunctionSolc")
def link_underlying_nodes(node1: NodeSolc, node2: NodeSolc):
link_nodes(node1.underlying_node, node2.underlying_node)
# pylint: disable=too-many-lines,too-many-branches,too-many-locals,too-many-statements,too-many-instance-attributes
class FunctionSolc(CallerContextExpression):
# elems = [(type, name)]
def __init__(
self,
function: Function,
function_data: Dict,
contract_parser: Optional["ContractSolc"],
slither_parser: "SlitherCompilationUnitSolc",
):
self._slither_parser: "SlitherCompilationUnitSolc" = slither_parser
self._contract_parser = contract_parser
self._function = function
# Only present if compact AST
if self.is_compact_ast:
self._function.name = function_data["name"]
if "id" in function_data:
self._function.id = function_data["id"]
else:
self._function.name = function_data["attributes"][self.get_key()]
self._functionNotParsed = function_data
self._params_was_analyzed = False
self._content_was_analyzed = False
self._counter_scope_local_variables = 0
# variable renamed will map the solc id
# to the variable. It only works for compact format
# Later if an expression provides the referencedDeclaration attr
# we can retrieve the variable
# It only matters if two variables have the same name in the function
# which is only possible with solc > 0.5
self._variables_renamed: Dict[
int, Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
] = {}
self._analyze_type()
self._node_to_nodesolc: Dict[Node, NodeSolc] = {}
self._node_to_yulobject: Dict[Node, YulBlock] = {}
self._local_variables_parser: List[
Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
] = []
if "documentation" in function_data:
function.has_documentation = True
@property
def underlying_function(self) -> Function:
return self._function
@property
def contract_parser(self) -> Optional["ContractSolc"]:
return self._contract_parser
@property
def slither_parser(self) -> "SlitherCompilationUnitSolc":
return self._slither_parser
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self._function.compilation_unit
###################################################################################
###################################################################################
# region AST format
###################################################################################
###################################################################################
def get_key(self) -> str:
return self._slither_parser.get_key()
def get_children(self, key: str) -> str:
if self.is_compact_ast:
return key
return "children"
@property
def is_compact_ast(self):
return self._slither_parser.is_compact_ast
# endregion
###################################################################################
###################################################################################
# region Variables
###################################################################################
###################################################################################
@property
def variables_renamed(
self,
) -> Dict[int, Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]]:
return self._variables_renamed
def _add_local_variable(
self, local_var_parser: Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
):
# If two local variables have the same name
# We add a suffix to the new variable
# This is done to prevent collision during SSA translation
# Use of while in case of collision
# In the worst case, the name will be really long
if local_var_parser.underlying_variable.name:
known_variables = [v.name for v in self._function.variables]
while local_var_parser.underlying_variable.name in known_variables:
local_var_parser.underlying_variable.name += (
f"_scope_{self._counter_scope_local_variables}"
)
self._counter_scope_local_variables += 1
known_variables = [v.name for v in self._function.variables]
if local_var_parser.reference_id is not None:
self._variables_renamed[local_var_parser.reference_id] = local_var_parser
self._function.variables_as_dict[
local_var_parser.underlying_variable.name
] = local_var_parser.underlying_variable
self._local_variables_parser.append(local_var_parser)
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
@property
def function_not_parsed(self) -> Dict:
return self._functionNotParsed
def _analyze_type(self):
"""
Analyz the type of the function
Myst be called in the constructor as the name might change according to the function's type
For example both the fallback and the receiver will have an empty name
:return:
"""
if self.is_compact_ast:
attributes = self._functionNotParsed
else:
attributes = self._functionNotParsed["attributes"]
if self._function.name == "":
self._function.function_type = FunctionType.FALLBACK
# 0.6.x introduced the receiver function
# It has also an empty name, so we need to check the kind attribute
if "kind" in attributes:
if attributes["kind"] == "receive":
self._function.function_type = FunctionType.RECEIVE
else:
self._function.function_type = FunctionType.NORMAL
if isinstance(self._function, FunctionContract):
if self._function.name == self._function.contract_declarer.name:
self._function.function_type = FunctionType.CONSTRUCTOR
def _analyze_attributes(self):
if self.is_compact_ast:
attributes = self._functionNotParsed
else:
attributes = self._functionNotParsed["attributes"]
if "payable" in attributes:
self._function.payable = attributes["payable"]
if "stateMutability" in attributes:
if attributes["stateMutability"] == "payable":
self._function.payable = True
elif attributes["stateMutability"] == "pure":
self._function.pure = True
self._function.view = True
elif attributes["stateMutability"] == "view":
self._function.view = True
if "constant" in attributes:
self._function.view = attributes["constant"]
if "isConstructor" in attributes and attributes["isConstructor"]:
self._function.function_type = FunctionType.CONSTRUCTOR
if "kind" in attributes:
if attributes["kind"] == "constructor":
self._function.function_type = FunctionType.CONSTRUCTOR
if "visibility" in attributes:
self._function.visibility = attributes["visibility"]
# old solc
elif "public" in attributes:
if attributes["public"]:
self._function.visibility = "public"
else:
self._function.visibility = "private"
else:
self._function.visibility = "public"
if "payable" in attributes:
self._function.payable = attributes["payable"]
def analyze_params(self):
# Can be re-analyzed due to inheritance
if self._params_was_analyzed:
return
self._params_was_analyzed = True
self._analyze_attributes()
if self.is_compact_ast:
params = self._functionNotParsed["parameters"]
returns = self._functionNotParsed["returnParameters"]
else:
children = self._functionNotParsed[self.get_children("children")]
# It uses to be
# params = children[0]
# returns = children[1]
# But from Solidity 0.6.3 to 0.6.10 (included)
# Comment above a function might be added in the children
child_iter = iter(
[child for child in children if child[self.get_key()] == "ParameterList"]
)
params = next(child_iter)
returns = next(child_iter)
if params:
self._parse_params(params)
if returns:
self._parse_returns(returns)
def analyze_content(self):
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed.get("body", None)
if body and body[self.get_key()] == "Block":
self._function.is_implemented = True
self._parse_cfg(body)
for modifier in self._functionNotParsed["modifiers"]:
self._parse_modifier(modifier)
else:
children = self._functionNotParsed[self.get_children("children")]
self._function.is_implemented = False
for child in children[2:]:
if child[self.get_key()] == "Block":
self._function.is_implemented = True
self._parse_cfg(child)
# Parse modifier after parsing all the block
# In the case a local variable is used in the modifier
for child in children[2:]:
if child[self.get_key()] == "ModifierInvocation":
self._parse_modifier(child)
for local_var_parser in self._local_variables_parser:
local_var_parser.analyze(self)
for node_parser in self._node_to_nodesolc.values():
node_parser.analyze_expressions(self)
for node_parser in self._node_to_yulobject.values():
node_parser.analyze_expressions()
self._rewrite_ternary_as_if_else()
self._remove_alone_endif()
# endregion
###################################################################################
###################################################################################
# region Nodes
###################################################################################
###################################################################################
def _new_node(
self, node_type: NodeType, src: Union[str, Source], scope: Union[Scope, "Function"]
) -> NodeSolc:
node = self._function.new_node(node_type, src, scope)
node_parser = NodeSolc(node)
self._node_to_nodesolc[node] = node_parser
return node_parser
def _new_yul_block(
self, src: Union[str, Dict], father_scope: Union[Scope, Function]
) -> YulBlock:
scope = Scope(False, True, father_scope)
node = self._function.new_node(NodeType.ASSEMBLY, src, scope)
contract = None
if isinstance(self._function, FunctionContract):
contract = self._function.contract
yul_object = YulBlock(
contract,
node,
[self._function.name, f"asm_{len(self._node_to_yulobject)}"],
scope,
)
self._node_to_yulobject[node] = yul_object
return yul_object
# endregion
###################################################################################
###################################################################################
# region Parsing function
###################################################################################
###################################################################################
def _parse_if(self, if_statement: Dict, node: NodeSolc) -> NodeSolc:
# IfStatement = 'if' '(' Expression ')' Statement ( 'else' Statement )?
falseStatement = None
if self.is_compact_ast:
condition = if_statement["condition"]
# Note: check if the expression could be directly
# parsed here
condition_node = self._new_node(
NodeType.IF, condition["src"], node.underlying_node.scope
)
condition_node.add_unparsed_expression(condition)
link_underlying_nodes(node, condition_node)
true_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
trueStatement = self._parse_statement(
if_statement["trueBody"], condition_node, true_scope
)
if "falseBody" in if_statement and if_statement["falseBody"]:
false_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
falseStatement = self._parse_statement(
if_statement["falseBody"], condition_node, false_scope
)
else:
children = if_statement[self.get_children("children")]
condition = children[0]
# Note: check if the expression could be directly
# parsed here
condition_node = self._new_node(
NodeType.IF, condition["src"], node.underlying_node.scope
)
condition_node.add_unparsed_expression(condition)
link_underlying_nodes(node, condition_node)
true_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
trueStatement = self._parse_statement(children[1], condition_node, true_scope)
if len(children) == 3:
false_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
falseStatement = self._parse_statement(children[2], condition_node, false_scope)
endIf_node = self._new_node(NodeType.ENDIF, if_statement["src"], node.underlying_node.scope)
link_underlying_nodes(trueStatement, endIf_node)
if falseStatement:
link_underlying_nodes(falseStatement, endIf_node)
else:
link_underlying_nodes(condition_node, endIf_node)
return endIf_node
def _parse_while(self, whilte_statement: Dict, node: NodeSolc) -> NodeSolc:
# WhileStatement = 'while' '(' Expression ')' Statement
node_startWhile = self._new_node(
NodeType.STARTLOOP, whilte_statement["src"], node.underlying_node.scope
)
body_scope = Scope(node.underlying_node.scope.is_checked, False, node.underlying_node.scope)
if self.is_compact_ast:
node_condition = self._new_node(
NodeType.IFLOOP, whilte_statement["condition"]["src"], node.underlying_node.scope
)
node_condition.add_unparsed_expression(whilte_statement["condition"])
statement = self._parse_statement(whilte_statement["body"], node_condition, body_scope)
else:
children = whilte_statement[self.get_children("children")]
expression = children[0]
node_condition = self._new_node(
NodeType.IFLOOP, expression["src"], node.underlying_node.scope
)
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition, body_scope)
node_endWhile = self._new_node(
NodeType.ENDLOOP, whilte_statement["src"], node.underlying_node.scope
)
link_underlying_nodes(node, node_startWhile)
link_underlying_nodes(node_startWhile, node_condition)
link_underlying_nodes(statement, node_condition)
link_underlying_nodes(node_condition, node_endWhile)
return node_endWhile
def _parse_for_compact_ast( # pylint: disable=no-self-use
self, statement: Dict
) -> (Optional[Dict], Optional[Dict], Optional[Dict], Dict):
body = statement["body"]
init_expression = statement.get("initializationExpression", None)
condition = statement.get("condition", None)
loop_expression = statement.get("loopExpression", None)
return init_expression, condition, loop_expression, body
def _parse_for_legacy_ast(
self, statement: Dict
) -> (Optional[Dict], Optional[Dict], Optional[Dict], Dict):
# if we're using an old version of solc (anything below and including 0.4.11) or if the user
# explicitly enabled compact ast, we might need to make some best-effort guesses
children = statement[self.get_children("children")]
# there should always be at least one, and never more than 4, children
assert 1 <= len(children) <= 4
# the last element of the children array must be the body, since it's mandatory
# however, it might be a single expression
body = children[-1]
if len(children) == 4:
# handle the first trivial case - if there are four children we know exactly what they are
pre, cond, post = children[0], children[1], children[2]
elif len(children) == 1:
# handle the second trivial case - if there is only one child we know there are no expressions
pre, cond, post = None, None, None
else:
attributes = statement.get("attributes", None)
def has_hint(key):
return key in attributes and not attributes[key]
if attributes and any(
map(
has_hint,
["condition", "initializationExpression", "loopExpression"],
)
):
# if we have attribute hints, rely on those
if len(children) == 2:
# we're missing two expressions, find the one we have
if not has_hint("initializationExpression"):
pre, cond, post = children[0], None, None
elif not has_hint("condition"):
pre, cond, post = None, children[0], None
else: # if not has_hint('loopExpression'):
pre, cond, post = None, None, children[0]
else: # len(children) == 3
# we're missing one expression, figure out what it is
if has_hint("initializationExpression"):
pre, cond, post = None, children[0], children[1]
elif has_hint("condition"):
pre, cond, post = children[0], None, children[1]
else: # if has_hint('loopExpression'):
pre, cond, post = children[0], children[1], None
else:
# we don't have attribute hints, and it's impossible to be 100% accurate here
# let's just try our best
first_type = children[0][self.get_key()]
second_type = children[1][self.get_key()]
# VariableDefinitionStatement is used by solc 0.4.0-0.4.6
# it's changed in 0.4.7 to VariableDeclarationStatement
if first_type in ["VariableDefinitionStatement", "VariableDeclarationStatement"]:
# only the pre statement can be a variable declaration
if len(children) == 2:
# only one child apart from body, it must be pre
pre, cond, post = children[0], None, None
else:
# more than one child, figure out which one is the cond
if second_type == "ExpressionStatement":
# only the post can be an expression statement
pre, cond, post = children[0], None, children[1]
else:
# similarly, the post cannot be anything other than an expression statement
pre, cond, post = children[0], children[1], None
elif first_type == "ExpressionStatement":
# the first element can either be pre or post
if len(children) == 2:
# this is entirely ambiguous, so apply a very dumb heuristic:
# if the statement is closer to the start of the body, it's probably the post
# otherwise, it's probably the pre
# this will work in all cases where the formatting isn't completely borked
node_len = int(children[0]["src"].split(":")[1])
node_start = int(children[0]["src"].split(":")[0])
node_end = node_start + node_len
for_start = int(statement["src"].split(":")[0]) + 3 # trim off the 'for'
body_start = int(body["src"].split(":")[0])
dist_start = node_start - for_start
dist_end = body_start - node_end
if dist_start > dist_end:
pre, cond, post = None, None, children[0]
else:
pre, cond, post = children[0], None, None
else:
# more than one child, we must be the pre
pre, cond, post = children[0], children[1], None
else:
# the first element must be the cond
if len(children) == 2:
pre, cond, post = None, children[0], None
else:
pre, cond, post = None, children[0], children[1]
return pre, cond, post, body
def _parse_for(self, statement: Dict, node: NodeSolc) -> NodeSolc:
# ForStatement = 'for' '(' (SimpleStatement)? ';' (Expression)? ';' (ExpressionStatement)? ')' Statement
if self.is_compact_ast:
pre, cond, post, body = self._parse_for_compact_ast(statement)
else:
pre, cond, post, body = self._parse_for_legacy_ast(statement)
node_startLoop = self._new_node(
NodeType.STARTLOOP, statement["src"], node.underlying_node.scope
)
node_endLoop = self._new_node(
NodeType.ENDLOOP, statement["src"], node.underlying_node.scope
)
last_scope = node.underlying_node.scope
if pre:
pre_scope = Scope(node.underlying_node.scope.is_checked, False, last_scope)
last_scope = pre_scope
node_init_expression = self._parse_statement(pre, node, pre_scope)
link_underlying_nodes(node_init_expression, node_startLoop)
else:
link_underlying_nodes(node, node_startLoop)
if cond:
cond_scope = Scope(node.underlying_node.scope.is_checked, False, last_scope)
last_scope = cond_scope
node_condition = self._new_node(NodeType.IFLOOP, cond["src"], cond_scope)
node_condition.add_unparsed_expression(cond)
link_underlying_nodes(node_startLoop, node_condition)
node_beforeBody = node_condition
else:
node_condition = None
node_beforeBody = node_startLoop
body_scope = Scope(node.underlying_node.scope.is_checked, False, last_scope)
last_scope = body_scope
node_body = self._parse_statement(body, node_beforeBody, body_scope)
if post:
node_loopexpression = self._parse_statement(post, node_body, last_scope)
link_underlying_nodes(node_loopexpression, node_beforeBody)
else:
# node_loopexpression = None
link_underlying_nodes(node_body, node_beforeBody)
if node_condition:
link_underlying_nodes(node_condition, node_endLoop)
else:
link_underlying_nodes(
node_startLoop, node_endLoop
) # this is an infinite loop but we can't break our cfg
return node_endLoop
def _parse_dowhile(self, do_while_statement: Dict, node: NodeSolc) -> NodeSolc:
node_startDoWhile = self._new_node(
NodeType.STARTLOOP, do_while_statement["src"], node.underlying_node.scope
)
condition_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
if self.is_compact_ast:
node_condition = self._new_node(
NodeType.IFLOOP, do_while_statement["condition"]["src"], condition_scope
)
node_condition.add_unparsed_expression(do_while_statement["condition"])
statement = self._parse_statement(
do_while_statement["body"], node_condition, condition_scope
)
else:
children = do_while_statement[self.get_children("children")]
# same order in the AST as while
expression = children[0]
node_condition = self._new_node(NodeType.IFLOOP, expression["src"], condition_scope)
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition, condition_scope)
body_scope = Scope(node.underlying_node.scope.is_checked, False, condition_scope)
node_endDoWhile = self._new_node(NodeType.ENDLOOP, do_while_statement["src"], body_scope)
link_underlying_nodes(node, node_startDoWhile)
# empty block, loop from the start to the condition
if not node_condition.underlying_node.sons:
link_underlying_nodes(node_startDoWhile, node_condition)
else:
link_nodes(
node_startDoWhile.underlying_node,
node_condition.underlying_node.sons[0],
)
link_underlying_nodes(statement, node_condition)
link_underlying_nodes(node_condition, node_endDoWhile)
return node_endDoWhile
def _parse_try_catch(self, statement: Dict, node: NodeSolc) -> NodeSolc:
externalCall = statement.get("externalCall", None)
if externalCall is None:
raise ParsingError(f"Try/Catch not correctly parsed by Slither {statement}")
catch_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
new_node = self._new_node(NodeType.TRY, statement["src"], catch_scope)
new_node.add_unparsed_expression(externalCall)
link_underlying_nodes(node, new_node)
node = new_node
for clause in statement.get("clauses", []):
self._parse_catch(clause, node)
return node
def _parse_catch(self, statement: Dict, node: NodeSolc) -> NodeSolc:
block = statement.get("block", None)
if block is None:
raise ParsingError(f"Catch not correctly parsed by Slither {statement}")
try_scope = Scope(node.underlying_node.scope.is_checked, False, node.underlying_node.scope)
try_node = self._new_node(NodeType.CATCH, statement["src"], try_scope)
link_underlying_nodes(node, try_node)
if self.is_compact_ast:
params = statement.get("parameters", None)
else:
params = statement[self.get_children("children")]
if params:
for param in params.get("parameters", []):
assert param[self.get_key()] == "VariableDeclaration"
self._add_param(param)
return self._parse_statement(block, try_node, try_scope)
def _parse_variable_definition(self, statement: Dict, node: NodeSolc) -> NodeSolc:
try:
local_var = LocalVariable()
local_var.set_function(self._function)
local_var.set_offset(statement["src"], self._function.compilation_unit)
local_var_parser = LocalVariableSolc(local_var, statement)
self._add_local_variable(local_var_parser)
# local_var.analyze(self)
new_node = self._new_node(
NodeType.VARIABLE, statement["src"], node.underlying_node.scope
)
new_node.underlying_node.add_variable_declaration(local_var)
link_underlying_nodes(node, new_node)
return new_node
except MultipleVariablesDeclaration:
# Custom handling of var (a,b) = .. style declaration
if self.is_compact_ast:
variables = statement["declarations"]
count = len(variables)
if (
statement["initialValue"]["nodeType"] == "TupleExpression"
and len(statement["initialValue"]["components"]) == count
):
inits = statement["initialValue"]["components"]
i = 0
new_node = node
for variable in variables:
if variable is None:
continue
init = inits[i]
src = variable["src"]
i = i + 1
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
"initialValue": init,
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
variables = []
i = 0
new_node = node
for variable in statement["declarations"]:
if variable:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
i = i + 1
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
"nodeType": "Identifier",
"src": v["src"],
"name": v["name"],
"typeDescriptions": {"typeString": v["typeDescriptions"]["typeString"]},
}
var_identifiers.append(identifier)
tuple_expression = {
"nodeType": "TupleExpression",
"src": statement["src"],
"components": var_identifiers,
}
expression = {
"nodeType": "Assignment",
"src": statement["src"],
"operator": "=",
"type": "tuple()",
"leftHandSide": tuple_expression,
"rightHandSide": statement["initialValue"],
"typeDescriptions": {"typeString": "tuple()"},
}
node = new_node
new_node = self._new_node(
NodeType.EXPRESSION, statement["src"], node.underlying_node.scope
)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
else:
count = 0
children = statement[self.get_children("children")]
child = children[0]
while child[self.get_key()] == "VariableDeclaration":
count = count + 1
child = children[count]
assert len(children) == (count + 1)
tuple_vars = children[count]
variables_declaration = children[0:count]
i = 0
new_node = node
if tuple_vars[self.get_key()] == "TupleExpression":
assert len(tuple_vars[self.get_children("children")]) == count
for variable in variables_declaration:
init = tuple_vars[self.get_children("children")][i]
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable, init],
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
assert tuple_vars[self.get_key()] in ["FunctionCall", "Conditional"]
variables = []
for variable in variables_declaration:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
i = i + 1
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
self.get_key(): "Identifier",
"src": v["src"],
"attributes": {
"value": v["attributes"][self.get_key()],
"type": v["attributes"]["type"],
},
}
var_identifiers.append(identifier)
expression = {
self.get_key(): "Assignment",
"src": statement["src"],
"attributes": {"operator": "=", "type": "tuple()"},
self.get_children("children"): [
{
self.get_key(): "TupleExpression",
"src": statement["src"],
self.get_children("children"): var_identifiers,
},
tuple_vars,
],
}
node = new_node
new_node = self._new_node(
NodeType.EXPRESSION, statement["src"], node.underlying_node.scope
)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
return new_node
def _parse_variable_definition_init_tuple(
self, statement: Dict, index: int, node: NodeSolc
) -> NodeSolc:
local_var = LocalVariableInitFromTuple()
local_var.set_function(self._function)
local_var.set_offset(statement["src"], self._function.compilation_unit)
local_var_parser = LocalVariableInitFromTupleSolc(local_var, statement, index)
self._add_local_variable(local_var_parser)
new_node = self._new_node(NodeType.VARIABLE, statement["src"], node.underlying_node.scope)
new_node.underlying_node.add_variable_declaration(local_var)
link_underlying_nodes(node, new_node)
return new_node
def _parse_statement(
self, statement: Dict, node: NodeSolc, scope: Union[Scope, Function]
) -> NodeSolc:
"""
Return:
node
"""
# Statement = IfStatement | WhileStatement | ForStatement | Block | InlineAssemblyStatement |
# ( DoWhileStatement | PlaceholderStatement | Continue | Break | Return |
# Throw | EmitStatement | SimpleStatement ) ';'
# SimpleStatement = VariableDefinition | ExpressionStatement
name = statement[self.get_key()]
# SimpleStatement = VariableDefinition | ExpressionStatement
if name == "IfStatement":
node = self._parse_if(statement, node)
elif name == "WhileStatement":
node = self._parse_while(statement, node)
elif name == "ForStatement":
node = self._parse_for(statement, node)
elif name == "Block":
node = self._parse_block(statement, node)
elif name == "UncheckedBlock":
node = self._parse_unchecked_block(statement, node)
elif name == "InlineAssembly":
# Added with solc 0.6 - the yul code is an AST
if "AST" in statement and not self.compilation_unit.core.skip_assembly:
self._function.contains_assembly = True
yul_object = self._new_yul_block(statement["src"], scope)
entrypoint = yul_object.entrypoint
exitpoint = yul_object.convert(statement["AST"])
# technically, entrypoint and exitpoint are YulNodes and we should be returning a NodeSolc here
# but they both expose an underlying_node so oh well
link_underlying_nodes(node, entrypoint)
node = exitpoint
else:
asm_node = self._new_node(NodeType.ASSEMBLY, statement["src"], scope)
self._function.contains_assembly = True
# Added with solc 0.4.12
if "operations" in statement:
asm_node.underlying_node.add_inline_asm(statement["operations"])
link_underlying_nodes(node, asm_node)
node = asm_node
elif name == "DoWhileStatement":
node = self._parse_dowhile(statement, node)
# For Continue / Break / Return / Throw
# The is fixed later
elif name == "Continue":
continue_node = self._new_node(NodeType.CONTINUE, statement["src"], scope)
link_underlying_nodes(node, continue_node)
node = continue_node
elif name == "Break":
break_node = self._new_node(NodeType.BREAK, statement["src"], scope)
link_underlying_nodes(node, break_node)
node = break_node
elif name == "Return":
return_node = self._new_node(NodeType.RETURN, statement["src"], scope)
link_underlying_nodes(node, return_node)
if self.is_compact_ast:
if statement.get("expression", None):
return_node.add_unparsed_expression(statement["expression"])
else:
if (
self.get_children("children") in statement
and statement[self.get_children("children")]
):
assert len(statement[self.get_children("children")]) == 1
expression = statement[self.get_children("children")][0]
return_node.add_unparsed_expression(expression)
node = return_node
elif name == "Throw":
throw_node = self._new_node(NodeType.THROW, statement["src"], scope)
link_underlying_nodes(node, throw_node)
node = throw_node
elif name == "EmitStatement":
# expression = parse_expression(statement[self.get_children('children')][0], self)
if self.is_compact_ast:
expression = statement["eventCall"]
else:
expression = statement[self.get_children("children")][0]
new_node = self._new_node(NodeType.EXPRESSION, statement["src"], scope)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
node = new_node
elif name in ["VariableDefinitionStatement", "VariableDeclarationStatement"]:
node = self._parse_variable_definition(statement, node)
elif name == "ExpressionStatement":
# assert len(statement[self.get_children('expression')]) == 1
# assert not 'attributes' in statement
# expression = parse_expression(statement[self.get_children('children')][0], self)
if self.is_compact_ast:
expression = statement[self.get_children("expression")]
else:
expression = statement[self.get_children("expression")][0]
new_node = self._new_node(NodeType.EXPRESSION, statement["src"], scope)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
node = new_node
elif name == "TryStatement":
node = self._parse_try_catch(statement, node)
# elif name == 'TryCatchClause':
# self._parse_catch(statement, node)
elif name == "RevertStatement":
if self.is_compact_ast:
expression = statement[self.get_children("errorCall")]
else:
expression = statement[self.get_children("errorCall")][0]
new_node = self._new_node(NodeType.EXPRESSION, statement["src"], scope)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
node = new_node
else:
raise ParsingError(f"Statement not parsed {name}")
return node
def _parse_block(self, block: Dict, node: NodeSolc, check_arithmetic: bool = False):
"""
Return:
Node
"""
assert block[self.get_key()] == "Block"
if self.is_compact_ast:
statements = block["statements"]
else:
statements = block[self.get_children("children")]
check_arithmetic = check_arithmetic | node.underlying_node.scope.is_checked
new_scope = Scope(check_arithmetic, False, node.underlying_node.scope)
for statement in statements:
node = self._parse_statement(statement, node, new_scope)
return node
def _parse_unchecked_block(self, block: Dict, node: NodeSolc):
"""
Return:
Node
"""
assert block[self.get_key()] == "UncheckedBlock"
if self.is_compact_ast:
statements = block["statements"]
else:
statements = block[self.get_children("children")]
new_scope = Scope(False, False, node.underlying_node.scope)
for statement in statements:
node = self._parse_statement(statement, node, new_scope)
return node
def _parse_cfg(self, cfg: Dict):
assert cfg[self.get_key()] == "Block"
node = self._new_node(NodeType.ENTRYPOINT, cfg["src"], self.underlying_function)
self._function.entry_point = node.underlying_node
if self.is_compact_ast:
statements = cfg["statements"]
else:
statements = cfg[self.get_children("children")]
if not statements:
self._function.is_empty = True
else:
self._function.is_empty = False
check_arithmetic = self.compilation_unit.solc_version >= "0.8.0"
self._parse_block(cfg, node, check_arithmetic=check_arithmetic)
self._remove_incorrect_edges()
self._remove_alone_endif()
# endregion
###################################################################################
###################################################################################
# region Loops
###################################################################################
###################################################################################
def _find_end_loop(self, node: Node, visited: List[Node], counter: int) -> Optional[Node]:
# counter allows to explore nested loop
if node in visited:
return None
if node.type == NodeType.ENDLOOP:
if counter == 0:
return node
counter -= 1
# nested loop
if node.type == NodeType.STARTLOOP:
counter += 1
visited = visited + [node]
for son in node.sons:
ret = self._find_end_loop(son, visited, counter)
if ret:
return ret
return None
def _find_start_loop(self, node: Node, visited: List[Node]) -> Optional[Node]:
if node in visited:
return None
if node.type == NodeType.STARTLOOP:
return node
visited = visited + [node]
for father in node.fathers:
ret = self._find_start_loop(father, visited)
if ret:
return ret
return None
def _fix_break_node(self, node: Node):
end_node = self._find_end_loop(node, [], 0)
if not end_node:
# If there is not end condition on the loop
# The exploration will reach a STARTLOOP before reaching the endloop
# We start with -1 as counter to catch this corner case
end_node = self._find_end_loop(node, [], -1)
if not end_node:
raise ParsingError(f"Break in no-loop context {node.function}")
for son in node.sons:
son.remove_father(node)
node.set_sons([end_node])
end_node.add_father(node)
def _fix_continue_node(self, node: Node):
start_node = self._find_start_loop(node, [])
if not start_node:
raise ParsingError(f"Continue in no-loop context {node.node_id}")
for son in node.sons:
son.remove_father(node)
node.set_sons([start_node])
start_node.add_father(node)
def _fix_try(self, node: Node):
end_node = next((son for son in node.sons if son.type != NodeType.CATCH), None)
if end_node:
for son in node.sons:
if son.type == NodeType.CATCH:
self._fix_catch(son, end_node)
def _fix_catch(self, node: Node, end_node: Node):
if not node.sons:
link_nodes(node, end_node)
else:
for son in node.sons:
if son != end_node:
self._fix_catch(son, end_node)
def _add_param(self, param: Dict) -> LocalVariableSolc:
local_var = LocalVariable()
local_var.set_function(self._function)
local_var.set_offset(param["src"], self._function.compilation_unit)
local_var_parser = LocalVariableSolc(local_var, param)
local_var_parser.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
self._add_local_variable(local_var_parser)
return local_var_parser
def _parse_params(self, params: Dict):
assert params[self.get_key()] == "ParameterList"
self._function.parameters_src().set_offset(params["src"], self._function.compilation_unit)
if self.is_compact_ast:
params = params["parameters"]
else:
params = params[self.get_children("children")]
for param in params:
assert param[self.get_key()] == "VariableDeclaration"
local_var = self._add_param(param)
self._function.add_parameters(local_var.underlying_variable)
def _parse_returns(self, returns: Dict):
assert returns[self.get_key()] == "ParameterList"
self._function.returns_src().set_offset(returns["src"], self._function.compilation_unit)
if self.is_compact_ast:
returns = returns["parameters"]
else:
returns = returns[self.get_children("children")]
for ret in returns:
assert ret[self.get_key()] == "VariableDeclaration"
local_var = self._add_param(ret)
self._function.add_return(local_var.underlying_variable)
def _parse_modifier(self, modifier: Dict):
m = parse_expression(modifier, self)
# self._expression_modifiers.append(m)
# Do not parse modifier nodes for interfaces
if not self._function.is_implemented:
return
for m in ExportValues(m).result():
if isinstance(m, Function):
node_parser = self._new_node(
NodeType.EXPRESSION, modifier["src"], self.underlying_function
)
node_parser.add_unparsed_expression(modifier)
# The latest entry point is the entry point, or the latest modifier call
if self._function.modifiers:
latest_entry_point = self._function.modifiers_statements[-1].nodes[-1]
else:
latest_entry_point = self._function.entry_point
insert_node(latest_entry_point, node_parser.underlying_node)
self._function.add_modifier(
ModifierStatements(
modifier=m,
entry_point=latest_entry_point,
nodes=[latest_entry_point, node_parser.underlying_node],
)
)
elif isinstance(m, Contract):
node_parser = self._new_node(
NodeType.EXPRESSION, modifier["src"], self.underlying_function
)
node_parser.add_unparsed_expression(modifier)
# The latest entry point is the entry point, or the latest constructor call
if self._function.explicit_base_constructor_calls_statements:
latest_entry_point = self._function.explicit_base_constructor_calls_statements[
-1
].nodes[-1]
else:
latest_entry_point = self._function.entry_point
insert_node(latest_entry_point, node_parser.underlying_node)
self._function.add_explicit_base_constructor_calls_statements(
ModifierStatements(
modifier=m,
entry_point=latest_entry_point,
nodes=[latest_entry_point, node_parser.underlying_node],
)
)
# endregion
###################################################################################
###################################################################################
# region Edges
###################################################################################
###################################################################################
def _remove_incorrect_edges(self):
for node in self._node_to_nodesolc:
if node.type in [NodeType.RETURN, NodeType.THROW]:
for son in node.sons:
son.remove_father(node)
node.set_sons([])
if node.type in [NodeType.BREAK]:
self._fix_break_node(node)
if node.type in [NodeType.CONTINUE]:
self._fix_continue_node(node)
if node.type in [NodeType.TRY]:
self._fix_try(node)
# this step needs to happen after all of the break statements are fixed
# really, we should be passing some sort of context down so the break statement doesn't
# need to be fixed out-of-band in the first place
for node in self._node_to_nodesolc:
if node.type in [NodeType.STARTLOOP]:
# can we prune? only if after pruning, we have at least one son that isn't itself
if (
len([son for son in node.sons if son.type != NodeType.ENDLOOP and son != node])
== 0
):
continue
new_sons = []
for son in node.sons:
if son.type != NodeType.ENDLOOP:
new_sons.append(son)
continue
son.remove_father(node)
node.set_sons(new_sons)
def _remove_alone_endif(self):
"""
Can occur on:
if(..){
return
}
else{
return
}
Iterate until a fix point to remove the ENDIF node
creates on the following pattern
if(){
return
}
else if(){
return
}
"""
prev_nodes = []
while set(prev_nodes) != set(self._node_to_nodesolc.keys()):
prev_nodes = self._node_to_nodesolc.keys()
to_remove: List[Node] = []
for node in self._node_to_nodesolc:
if node.type == NodeType.ENDIF and not node.fathers:
for son in node.sons:
son.remove_father(node)
node.set_sons([])
to_remove.append(node)
self._function.nodes = [n for n in self._function.nodes if n not in to_remove]
for remove in to_remove:
if remove in self._node_to_nodesolc:
del self._node_to_nodesolc[remove]
# endregion
###################################################################################
###################################################################################
# region Ternary
###################################################################################
###################################################################################
def _rewrite_ternary_as_if_else(self) -> bool:
ternary_found = True
updated = False
while ternary_found:
ternary_found = False
for node in self._node_to_nodesolc:
has_cond = HasConditional(node.expression)
if has_cond.result():
st = SplitTernaryExpression(node.expression)
condition = st.condition
if not condition:
raise ParsingError(
f"Incorrect ternary conversion {node.expression} {node.source_mapping}"
)
true_expr = st.true_expression
false_expr = st.false_expression
self._split_ternary_node(node, condition, true_expr, false_expr)
ternary_found = True
updated = True
break
return updated
def _split_ternary_node(
self,
node: Node,
condition: "Expression",
true_expr: "Expression",
false_expr: "Expression",
):
condition_node = self._new_node(NodeType.IF, node.source_mapping, node.scope)
condition_node.underlying_node.add_expression(condition)
condition_node.analyze_expressions(self)
if node.type == NodeType.VARIABLE:
condition_node.underlying_node.add_variable_declaration(node.variable_declaration)
true_node_parser = self._new_node(NodeType.EXPRESSION, node.source_mapping, node.scope)
if node.type == NodeType.VARIABLE:
assert isinstance(true_expr, AssignmentOperation)
# true_expr = true_expr.expression_right
elif node.type == NodeType.RETURN:
true_node_parser.underlying_node.type = NodeType.RETURN
true_node_parser.underlying_node.add_expression(true_expr)
true_node_parser.analyze_expressions(self)
false_node_parser = self._new_node(NodeType.EXPRESSION, node.source_mapping, node.scope)
if node.type == NodeType.VARIABLE:
assert isinstance(false_expr, AssignmentOperation)
elif node.type == NodeType.RETURN:
false_node_parser.underlying_node.type = NodeType.RETURN
# false_expr = false_expr.expression_right
false_node_parser.underlying_node.add_expression(false_expr)
false_node_parser.analyze_expressions(self)
endif_node = self._new_node(NodeType.ENDIF, node.source_mapping, node.scope)
for father in node.fathers:
father.remove_son(node)
father.add_son(condition_node.underlying_node)
condition_node.underlying_node.add_father(father)
for son in node.sons:
son.remove_father(node)
son.add_father(endif_node.underlying_node)
endif_node.underlying_node.add_son(son)
link_underlying_nodes(condition_node, true_node_parser)
link_underlying_nodes(condition_node, false_node_parser)
if true_node_parser.underlying_node.type not in [
NodeType.THROW,
NodeType.RETURN,
]:
link_underlying_nodes(true_node_parser, endif_node)
if false_node_parser.underlying_node.type not in [
NodeType.THROW,
NodeType.RETURN,
]:
link_underlying_nodes(false_node_parser, endif_node)
self._function.nodes = [n for n in self._function.nodes if n.node_id != node.node_id]
del self._node_to_nodesolc[node]
# endregion
| 60,777 | Python | .py | 1,215 | 36.478189 | 115 | 0.547858 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,098 | event.py | NioTheFirst_ScType/slither/solc_parsing/declarations/event.py | """
Event module
"""
from typing import TYPE_CHECKING, Dict
from slither.core.variables.event_variable import EventVariable
from slither.solc_parsing.variables.event_variable import EventVariableSolc
from slither.core.declarations.event import Event
if TYPE_CHECKING:
from slither.solc_parsing.declarations.contract import ContractSolc
class EventSolc:
"""
Event class
"""
def __init__(self, event: Event, event_data: Dict, contract_parser: "ContractSolc"):
self._event = event
event.set_contract(contract_parser.underlying_contract)
self._parser_contract = contract_parser
if self.is_compact_ast:
self._event.name = event_data["name"]
elems = event_data["parameters"]
assert elems["nodeType"] == "ParameterList"
self._elemsNotParsed = elems["parameters"]
else:
self._event.name = event_data["attributes"]["name"]
for elem in event_data["children"]:
# From Solidity 0.6.3 to 0.6.10 (included)
# Comment above a event might be added in the children
# of an event for the legacy ast
if elem["name"] == "ParameterList":
if "children" in elem:
self._elemsNotParsed = elem["children"]
else:
self._elemsNotParsed = []
@property
def is_compact_ast(self) -> bool:
return self._parser_contract.is_compact_ast
def analyze(self, contract: "ContractSolc"):
for elem_to_parse in self._elemsNotParsed:
elem = EventVariable()
# Todo: check if the source offset is always here
if "src" in elem_to_parse:
elem.set_offset(
elem_to_parse["src"], self._parser_contract.underlying_contract.compilation_unit
)
elem_parser = EventVariableSolc(elem, elem_to_parse)
elem_parser.analyze(contract)
self._event.elems.append(elem)
self._elemsNotParsed = []
| 2,087 | Python | .py | 48 | 32.916667 | 100 | 0.612426 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,099 | custom_error.py | NioTheFirst_ScType/slither/solc_parsing/declarations/custom_error.py | from typing import TYPE_CHECKING, Dict
from slither.core.declarations.custom_error import CustomError
from slither.core.declarations.custom_error_contract import CustomErrorContract
from slither.core.declarations.custom_error_top_level import CustomErrorTopLevel
from slither.core.variables.local_variable import LocalVariable
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.variables.local_variable import LocalVariableSolc
if TYPE_CHECKING:
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
from slither.core.compilation_unit import SlitherCompilationUnit
# Part of the code was copied from the function parsing
# In the long term we should refactor these two classes to merge the duplicated code
class CustomErrorSolc(CallerContextExpression):
def __init__(
self,
custom_error: CustomError,
custom_error_data: dict,
slither_parser: "SlitherCompilationUnitSolc",
):
self._slither_parser: "SlitherCompilationUnitSolc" = slither_parser
self._custom_error = custom_error
custom_error.name = custom_error_data["name"]
self._params_was_analyzed = False
if not self._slither_parser.is_compact_ast:
custom_error_data = custom_error_data["attributes"]
self._custom_error_data = custom_error_data
def analyze_params(self):
# Can be re-analyzed due to inheritance
if self._params_was_analyzed:
return
self._params_was_analyzed = True
if self._slither_parser.is_compact_ast:
params = self._custom_error_data["parameters"]
else:
children = self._custom_error_data[self.get_children("children")]
# It uses to be
# params = children[0]
# returns = children[1]
# But from Solidity 0.6.3 to 0.6.10 (included)
# Comment above a function might be added in the children
child_iter = iter(
[child for child in children if child[self.get_key()] == "ParameterList"]
)
params = next(child_iter)
if params:
self._parse_params(params)
@property
def is_compact_ast(self) -> bool:
return self._slither_parser.is_compact_ast
def get_key(self) -> str:
return self._slither_parser.get_key()
def get_children(self, key: str) -> str:
if self._slither_parser.is_compact_ast:
return key
return "children"
def _parse_params(self, params: Dict):
assert params[self.get_key()] == "ParameterList"
if self._slither_parser.is_compact_ast:
params = params["parameters"]
else:
params = params[self.get_children("children")]
for param in params:
assert param[self.get_key()] == "VariableDeclaration"
local_var = self._add_param(param)
self._custom_error.add_parameters(local_var.underlying_variable)
self._custom_error.set_solidity_sig()
def _add_param(self, param: Dict) -> LocalVariableSolc:
local_var = LocalVariable()
local_var.set_offset(param["src"], self._slither_parser.compilation_unit)
local_var_parser = LocalVariableSolc(local_var, param)
if isinstance(self._custom_error, CustomErrorTopLevel):
local_var_parser.analyze(self)
else:
assert isinstance(self._custom_error, CustomErrorContract)
local_var_parser.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
return local_var_parser
@property
def underlying_custom_error(self) -> CustomError:
return self._custom_error
@property
def slither_parser(self) -> "SlitherCompilationUnitSolc":
return self._slither_parser
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self._custom_error.compilation_unit
| 4,157 | Python | .py | 88 | 38.579545 | 110 | 0.678704 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.