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,200 | permit_domain_signature_collision.py | NioTheFirst_ScType/slither/detectors/functions/permit_domain_signature_collision.py | """
Module detecting EIP-2612 domain separator collision
"""
from typing import Union, List
from slither.core.declarations import Function
from slither.core.solidity_types.elementary_type import ElementaryType
from slither.core.variables.state_variable import StateVariable
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.utils.function import get_function_id
class DomainSeparatorCollision(AbstractDetector):
"""
Domain separator collision
"""
ARGUMENT = "domain-separator-collision"
HELP = "Detects ERC20 tokens that have a function whose signature collides with EIP-2612's DOMAIN_SEPARATOR()"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#domain-separator-collision"
)
WIKI_TITLE = "Domain separator collision"
WIKI_DESCRIPTION = "An ERC20 token has a function whose signature collides with EIP-2612's DOMAIN_SEPARATOR(), causing unanticipated behavior for contracts using `permit` functionality."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
function some_collisions() external() {}
}
```
`some_collision` clashes with EIP-2612's DOMAIN_SEPARATOR() and will interfere with contract's using `permit`."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Remove or rename the function that collides with DOMAIN_SEPARATOR()."
def _detect(self):
domain_sig = get_function_id("DOMAIN_SEPARATOR()")
for contract in self.compilation_unit.contracts_derived:
if contract.is_erc20():
funcs_and_vars: List[Union[Function, StateVariable]] = contract.functions_entry_points + contract.state_variables_entry_points # type: ignore
for func_or_var in funcs_and_vars:
# External/ public function names should not collide with DOMAIN_SEPARATOR()
hash_collision = (
func_or_var.solidity_signature != "DOMAIN_SEPARATOR()"
and get_function_id(func_or_var.solidity_signature) == domain_sig
)
# DOMAIN_SEPARATOR() should return bytes32
incorrect_return_type = func_or_var.solidity_signature == "DOMAIN_SEPARATOR()"
if incorrect_return_type:
if isinstance(func_or_var, Function):
incorrect_return_type = (
not func_or_var.return_type
or func_or_var.return_type[0] != ElementaryType("bytes32")
)
else:
assert isinstance(func_or_var, StateVariable)
incorrect_return_type = func_or_var.type != ElementaryType("bytes32")
if hash_collision or incorrect_return_type:
info = [
"The function signature of ",
func_or_var,
" collides with DOMAIN_SEPARATOR and should be renamed or removed.\n",
]
res = self.generate_result(info)
return [res]
return []
| 3,380 | Python | .py | 63 | 40.825397 | 190 | 0.626965 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,201 | dead_code.py | NioTheFirst_ScType/slither/detectors/functions/dead_code.py | """
Module detecting dead code
"""
from typing import List, Tuple
from slither.core.declarations import Function, FunctionContract, Contract
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class DeadCode(AbstractDetector):
"""
Unprotected function detector
"""
ARGUMENT = "dead-code"
HELP = "Functions that are not used"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code"
WIKI_TITLE = "Dead-code"
WIKI_DESCRIPTION = "Functions that are not sued."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Contract{
function dead_code() internal() {}
}
```
`dead_code` is not used in the contract, and make the code's review more difficult."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Remove unused functions."
def _detect(self):
results = []
functions_used = set()
for contract in self.compilation_unit.contracts_derived:
all_functionss_called = [
f.all_internal_calls() for f in contract.functions_entry_points
]
all_functions_called = [item for sublist in all_functionss_called for item in sublist]
functions_used |= {
f.canonical_name for f in all_functions_called if isinstance(f, Function)
}
all_libss_called = [f.all_library_calls() for f in contract.functions_entry_points]
all_libs_called: List[Tuple[Contract, Function]] = [
item for sublist in all_libss_called for item in sublist
]
functions_used |= {
lib[1].canonical_name for lib in all_libs_called if isinstance(lib, tuple)
}
for function in sorted(self.compilation_unit.functions, key=lambda x: x.canonical_name):
if (
function.visibility in ["public", "external"]
or function.is_constructor
or function.is_fallback
or function.is_constructor_variables
):
continue
if function.canonical_name in functions_used:
continue
if isinstance(function, FunctionContract) and (
function.contract_declarer.is_from_dependency()
):
continue
# Continue if the functon is not implemented because it means the contract is abstract
if not function.is_implemented:
continue
info = [function, " is never used and should be removed\n"]
res = self.generate_result(info)
results.append(res)
return results
| 2,811 | Python | .py | 66 | 33.045455 | 98 | 0.640688 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,202 | codex.py | NioTheFirst_ScType/slither/detectors/functions/codex.py | import logging
import uuid
from typing import List, Union
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.utils import codex
from slither.utils.output import Output, SupportedOutput
logger = logging.getLogger("Slither")
VULN_FOUND = "VULN_FOUND"
class Codex(AbstractDetector):
"""
Use codex to detect vulnerability
"""
ARGUMENT = "codex"
HELP = "Use Codex to find vulnerabilities."
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.LOW
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#codex"
WIKI_TITLE = "Codex"
WIKI_DESCRIPTION = "Use [codex](https://openai.com/blog/openai-codex/) to find vulnerabilities"
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """N/A"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Review codex's message."
def _run_codex(self, logging_file: str, prompt: str) -> str:
"""
Handle the codex logic
Args:
logging_file (str): file where to log the queries
prompt (str): prompt to send to codex
Returns:
codex answer (str)
"""
openai_module = codex.openai_module() # type: ignore
if openai_module is None:
return ""
if self.slither.codex_log:
codex.log_codex(logging_file, "Q: " + prompt)
answer = ""
res = {}
try:
res = openai_module.Completion.create(
prompt=prompt,
model=self.slither.codex_model,
temperature=self.slither.codex_temperature,
max_tokens=self.slither.codex_max_tokens,
)
except Exception as e: # pylint: disable=broad-except
logger.info("OpenAI request failed: " + str(e))
# """ OpenAI completion response shape example:
# {
# "choices": [
# {
# "finish_reason": "stop",
# "index": 0,
# "logprobs": null,
# "text": "VULNERABILITIES:. The withdraw() function does not check..."
# }
# ],
# "created": 1670357537,
# "id": "cmpl-6KYaXdA6QIisHlTMM7RCJ1nR5wTKx",
# "model": "text-davinci-003",
# "object": "text_completion",
# "usage": {
# "completion_tokens": 80,
# "prompt_tokens": 249,
# "total_tokens": 329
# }
# } """
if res:
if self.slither.codex_log:
codex.log_codex(logging_file, "A: " + str(res))
else:
codex.log_codex(logging_file, "A: Codex failed")
if res.get("choices", []) and VULN_FOUND in res["choices"][0].get("text", ""):
# remove VULN_FOUND keyword and cleanup
answer = (
res["choices"][0]["text"]
.replace(VULN_FOUND, "")
.replace("\n", "")
.replace(": ", "")
)
return answer
def _detect(self) -> List[Output]:
results: List[Output] = []
if not self.slither.codex_enabled:
return []
logging_file = str(uuid.uuid4())
for contract in self.compilation_unit.contracts:
if (
self.slither.codex_contracts != "all"
and contract.name not in self.slither.codex_contracts.split(",")
):
continue
prompt = f"Analyze this Solidity contract and find the vulnerabilities. If you find any vulnerabilities, begin the response with {VULN_FOUND}\n"
src_mapping = contract.source_mapping
content = contract.compilation_unit.core.source_code[src_mapping.filename.absolute]
start = src_mapping.start
end = src_mapping.start + src_mapping.length
prompt += content[start:end]
answer = self._run_codex(logging_file, prompt)
if answer:
info: List[Union[str, SupportedOutput]] = [
"Codex detected a potential bug in ",
contract,
"\n",
answer,
"\n",
]
new_result = self.generate_result(info)
results.append(new_result)
return results
| 4,446 | Python | .py | 111 | 29.495495 | 156 | 0.553596 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,203 | external_function.py | NioTheFirst_ScType/slither/detectors/functions/external_function.py | from typing import List, Set
from slither.core.declarations import Function, FunctionContract, Contract
from slither.core.declarations.structure import Structure
from slither.core.solidity_types.array_type import ArrayType
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.core.variables.variable import Variable
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
ALL_SOLC_VERSIONS_04,
ALL_SOLC_VERSIONS_05,
make_solc_versions,
)
from slither.formatters.functions.external_function import custom_format
from slither.slithir.operations import InternalCall, InternalDynamicCall
from slither.slithir.operations import SolidityCall
from slither.utils.output import Output
class ExternalFunction(AbstractDetector):
"""
Detect public function that could be declared as external
IMPROVEMENT: Add InternalDynamicCall check
https://github.com/trailofbits/slither/pull/53#issuecomment-432809950
"""
ARGUMENT = "external-function"
HELP = "Public function that could be declared external"
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-external"
WIKI_TITLE = "Public function that could be declared external"
WIKI_DESCRIPTION = "`public` functions that are never called by the contract should be declared `external`, and its immutable parameters should be located in `calldata` to save gas."
WIKI_RECOMMENDATION = "Use the `external` attribute for functions never called from the contract, and change the location of immutable parameters to `calldata` to save gas."
VULNERABLE_SOLC_VERSIONS = (
ALL_SOLC_VERSIONS_04 + ALL_SOLC_VERSIONS_05 + make_solc_versions(6, 0, 8)
)
@staticmethod
def detect_functions_called(contract: Contract) -> List[Function]:
"""Returns a list of InternallCall, SolidityCall
calls made in a function
Returns:
(list): List of all InternallCall, SolidityCall
"""
result = []
# Obtain all functions reachable by this contract.
for func in contract.all_functions_called:
if not isinstance(func, Function):
continue
# Loop through all nodes in the function, add all calls to a list.
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalCall, SolidityCall)):
result.append(ir.function)
return result
@staticmethod
def _contains_internal_dynamic_call(contract: Contract) -> bool:
"""
Checks if a contract contains a dynamic call either in a direct definition, or through inheritance.
Returns:
(boolean): True if this contract contains a dynamic call (including through inheritance).
"""
for func in contract.all_functions_called:
if not isinstance(func, Function):
continue
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalDynamicCall)):
return True
return False
@staticmethod
def get_base_most_function(function: FunctionContract) -> FunctionContract:
"""
Obtains the base function definition for the provided function. This could be used to obtain the original
definition of a function, if the provided function is an override.
Returns:
(function): Returns the base-most function of a provided function. (The original definition).
"""
# Loop through the list of inherited contracts and this contract, to find the first function instance which
# matches this function's signature. Note here that `inheritance` is in order from most basic to most extended.
for contract in function.contract.inheritance + [function.contract]:
# Loop through the functions not inherited (explicitly defined in this contract).
for f in contract.functions_declared:
# If it matches names, this is the base most function.
if f.full_name == function.full_name:
return f
# Somehow we couldn't resolve it, which shouldn't happen, as the provided function should be found if we could
# not find some any more basic.
raise Exception("Could not resolve the base-most function for the provided function.")
@staticmethod
def get_all_function_definitions(
base_most_function: FunctionContract,
) -> List[FunctionContract]:
"""
Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions defined for it.
"""
# We assume the provided function is the base-most function, so we check all derived contracts
# for a redefinition
return [base_most_function] + [
function
for derived_contract in base_most_function.contract.derived_contracts
for function in derived_contract.functions
if function.full_name == base_most_function.full_name
and isinstance(function, FunctionContract)
]
@staticmethod
def function_parameters_written(function: Function) -> bool:
return any(p in function.variables_written for p in function.parameters)
@staticmethod
def is_reference_type(parameter: Variable) -> bool:
parameter_type = parameter.type
if isinstance(parameter_type, ArrayType):
return True
if isinstance(parameter_type, UserDefinedType) and isinstance(
parameter_type.type, Structure
):
return True
if str(parameter_type) in ["bytes", "string"]:
return True
return False
def _detect(self) -> List[Output]: # pylint: disable=too-many-locals,too-many-branches
results: List[Output] = []
# Create a set to track contracts with dynamic calls. All contracts with dynamic calls could potentially be
# calling functions internally, and thus we can't assume any function in such contracts isn't called by them.
dynamic_call_contracts: Set[Contract] = set()
# Create a completed functions set to skip over functions already processed (any functions which are the base
# of, or override hierarchically are processed together).
completed_functions: Set[Function] = set()
# First we build our set of all contracts with dynamic calls
for contract in self.contracts:
if self._contains_internal_dynamic_call(contract):
dynamic_call_contracts.add(contract)
# Loop through all contracts
for contract in self.contracts:
# Filter false-positives: Immediately filter this contract if it's in blacklist
if contract in dynamic_call_contracts:
continue
# Next we'll want to loop through all functions defined directly in this contract.
for function in contract.functions_declared:
# If all of the function arguments are non-reference type or calldata, we skip it.
reference_args = []
for arg in function.parameters:
if self.is_reference_type(arg) and arg.location == "memory":
reference_args.append(arg)
if len(reference_args) == 0:
continue
# If the function is a constructor, or is public, we skip it.
if function.is_constructor or function.visibility != "public":
continue
# Optimization: If this function has already been processed, we stop.
if function in completed_functions:
continue
# If the function has parameters which are written-to in function body, we skip
# because parameters of external functions will be allocated in calldata region which is immutable
if self.function_parameters_written(function):
continue
# Get the base-most function to know our origin of this function.
base_most_function = self.get_base_most_function(function)
# Get all possible contracts which can call this function (or an override).
all_possible_sources = [
base_most_function.contract
] + base_most_function.contract.derived_contracts
# Get all function signatures (overloaded and not), mark as completed and we process them now.
# Note: We mark all function definitions as the same, as they must all share visibility to override.
all_function_definitions = set(
self.get_all_function_definitions(base_most_function)
)
completed_functions = completed_functions.union(all_function_definitions)
# Filter false-positives: Determine if any of these sources have dynamic calls, if so, flag all of these
# function definitions, and then flag all functions in all contracts that make dynamic calls.
sources_with_dynamic_calls = set(all_possible_sources) & dynamic_call_contracts
if sources_with_dynamic_calls:
functions_in_dynamic_call_sources = {
f
for dyn_contract in sources_with_dynamic_calls
for f in dyn_contract.functions
if not f.is_constructor
}
completed_functions = completed_functions.union(
functions_in_dynamic_call_sources
)
continue
# Detect all functions called in each source, if any match our current signature, we skip
# otherwise, this is a candidate (in all sources) to be changed visibility for.
is_called = False
for possible_source in all_possible_sources:
functions_called = self.detect_functions_called(possible_source)
if set(functions_called) & all_function_definitions:
is_called = True
break
# If any of this function's definitions are called, we skip it.
if is_called:
continue
# As we collect all shadowed functions in get_all_function_definitions
# Some function coming from a base might already been declared as external
all_function_definitions: List[FunctionContract] = [
f
for f in all_function_definitions
if isinstance(f, FunctionContract)
and f.visibility == "public"
and f.contract == f.contract_declarer
]
if all_function_definitions:
all_function_definitions = sorted(
all_function_definitions, key=lambda x: x.canonical_name
)
function_definition = all_function_definitions[0]
all_function_definitions = all_function_definitions[1:]
info = [f"{function_definition.full_name} should be declared external:\n"]
info += ["\t- ", function_definition, "\n"]
if self.compilation_unit.solc_version >= "0.5.":
info += [
"Moreover, the following function parameters should change its data location:\n"
]
for reference_arg in reference_args:
info += [f"{reference_arg} location should be calldata\n"]
for other_function_definition in all_function_definitions:
info += ["\t- ", other_function_definition, "\n"]
res = self.generate_result(info)
results.append(res)
return results
@staticmethod
def _format(slither, result):
custom_format(slither, result)
| 12,558 | Python | .py | 224 | 42.915179 | 186 | 0.635039 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,204 | protected_variable.py | NioTheFirst_ScType/slither/detectors/functions/protected_variable.py | """
Module detecting suicidal contract
A suicidal contract is an unprotected function that calls selfdestruct
"""
from typing import List
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.core.declarations import Function, Contract
from slither.utils.output import Output
class ProtectedVariables(AbstractDetector):
ARGUMENT = "protected-vars"
HELP = "Detected unprotected variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#protected-variables"
WIKI_TITLE = "Protected Variables"
WIKI_DESCRIPTION = "Detect unprotected variable that are marked protected"
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Buggy{
/// @custom:security write-protection="onlyOwner()"
address owner;
function set_protected() public onlyOwner(){
owner = msg.sender;
}
function set_not_protected() public{
owner = msg.sender;
}
}
```
`owner` must be always written by function using `onlyOwner` (`write-protection="onlyOwner()"`), however anyone can call `set_not_protected`.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Add access controls to the vulnerable function"
def _analyze_function(self, function: Function, contract: Contract) -> List[Output]:
results = []
for state_variable_written in function.all_state_variables_written():
if state_variable_written.write_protection:
for function_sig in state_variable_written.write_protection:
function_protection = contract.get_function_from_signature(function_sig)
if not function_protection:
function_protection = contract.get_modifier_from_signature(function_sig)
if not function_protection:
self.logger.error(f"{function_sig} not found")
continue
if function_protection not in function.all_internal_calls():
info = [
function,
" should have ",
function_protection,
" to protect ",
state_variable_written,
"\n",
]
res = self.generate_result(info)
results.append(res)
return results
def _detect(self):
"""Detect the suicidal functions"""
results = []
for contract in self.compilation_unit.contracts_derived:
for function in contract.functions_entry_points:
results += self._analyze_function(function, contract)
return results
| 2,901 | Python | .py | 64 | 34.3125 | 141 | 0.634043 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,205 | modifier.py | NioTheFirst_ScType/slither/detectors/functions/modifier.py | """
Module detecting modifiers that are not guaranteed to execute _; or revert()/throw
Note that require()/assert() are not considered here. Even if they
are in the outermost scope, they do not guarantee a revert, so a
default value can still be returned.
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.core.cfg.node import NodeType
def is_revert(node):
return node.type == NodeType.THROW or any(
c.name in ["revert()", "revert(string"] for c in node.internal_calls
)
def _get_false_son(node):
"""Select the son node corresponding to a false branch
Following this node stays on the outer scope of the function
"""
if node.type == NodeType.IF:
return node.sons[1]
if node.type == NodeType.IFLOOP:
return next(s for s in node.sons if s.type == NodeType.ENDLOOP)
return None
class ModifierDefaultDetection(AbstractDetector):
"""
Detector for modifiers that return a default value
"""
ARGUMENT = "incorrect-modifier"
HELP = "Modifiers that can return the default value"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-modifier"
WIKI_TITLE = "Incorrect modifier"
WIKI_DESCRIPTION = "If a modifier does not execute `_` or revert, the execution of the function will return the default value, which can be misleading for the caller."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
modidfier myModif(){
if(..){
_;
}
}
function get() myModif returns(uint){
}
```
If the condition in `myModif` is false, the execution of `get()` will return 0."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "All the paths in a modifier must execute `_` or revert."
def _detect(self):
results = []
for c in self.contracts:
for mod in c.modifiers:
if mod.contract_declarer != c:
continue
# Walk down the tree, only looking at nodes in the outer scope
node = mod.entry_point
while node is not None:
# If any node in the outer scope executes _; or reverts,
# we will never return a default value
if node.type == NodeType.PLACEHOLDER or is_revert(node):
break
# Move down, staying on the outer scope in branches
if len(node.sons) > 0:
node = _get_false_son(node) if node.contains_if() else node.sons[0]
else:
node = None
else:
# Nothing was found in the outer scope
info = ["Modifier ", mod, " does not always execute _; or revert"]
res = self.generate_result(info)
results.append(res)
return results
| 3,059 | Python | .py | 70 | 34.328571 | 171 | 0.627273 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,206 | unimplemented.py | NioTheFirst_ScType/slither/detectors/functions/unimplemented.py | """
Module detecting unimplemented functions
Recursively check the called functions
Collect all the implemented and unimplemented functions of all the contracts
Check for unimplemented functions that are never implemented
Consider public state variables as implemented functions
Do not consider fallback function or constructor
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
# Since 0.5.1, Solidity allows creating state variable matching a function signature.
older_solc_versions = ["0.5.0"] + ["0.4." + str(x) for x in range(0, 27)]
class UnimplementedFunctionDetection(AbstractDetector):
"""
Unimplemented functions detector
"""
ARGUMENT = "unimplemented-functions"
HELP = "Unimplemented functions"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#unimplemented-functions"
WIKI_TITLE = "Unimplemented functions"
WIKI_DESCRIPTION = "Detect functions that are not implemented on derived-most contracts."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
interface BaseInterface {
function f1() external returns(uint);
function f2() external returns(uint);
}
interface BaseInterface2 {
function f3() external returns(uint);
}
contract DerivedContract is BaseInterface, BaseInterface2 {
function f1() external returns(uint){
return 42;
}
}
```
`DerivedContract` does not implement `BaseInterface.f2` or `BaseInterface2.f3`.
As a result, the contract will not properly compile.
All unimplemented functions must be implemented on a contract that is meant to be used."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Implement all unimplemented functions in any contract you intend to use directly (not simply inherit from)."
@staticmethod
def _match_state_variable(contract, f):
return any(s.full_name == f.full_name for s in contract.state_variables)
def _detect_unimplemented_function(self, contract):
"""
Detects any function definitions which are not implemented in the given contract.
:param contract: The contract to search unimplemented functions for.
:return: A list of functions which are not implemented.
"""
# If it's simply a contract signature, we have no functions.
if contract.is_signature_only():
return set()
# Populate our unimplemented functions set with any functions not implemented in this contract, excluding the
# fallback function and constructor.
unimplemented = set()
for f in contract.all_functions_called:
if (
not f.is_implemented
and not f.is_constructor
and not f.is_fallback
and not f.is_constructor_variables
):
if self.compilation_unit.solc_version not in older_solc_versions:
# Since 0.5.1, Solidity allows creating state variable matching a function signature
if not self._match_state_variable(contract, f):
unimplemented.add(f)
else:
unimplemented.add(f)
return unimplemented
def _detect(self):
"""Detect unimplemented functions
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func'}
"""
results = []
for contract in self.compilation_unit.contracts_derived:
functions = self._detect_unimplemented_function(contract)
if functions:
info = [contract, " does not implement functions:\n"]
for function in sorted(functions, key=lambda x: x.full_name):
info += ["\t- ", function, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| 4,011 | Python | .py | 88 | 37.568182 | 135 | 0.686651 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,207 | suicidal.py | NioTheFirst_ScType/slither/detectors/functions/suicidal.py | """
Module detecting suicidal contract
A suicidal contract is an unprotected function that calls selfdestruct
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class Suicidal(AbstractDetector):
"""
Unprotected function detector
"""
ARGUMENT = "suicidal"
HELP = "Functions allowing anyone to destruct the contract"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#suicidal"
WIKI_TITLE = "Suicidal"
WIKI_DESCRIPTION = "Unprotected call to a function executing `selfdestruct`/`suicide`."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Suicidal{
function kill() public{
selfdestruct(msg.sender);
}
}
```
Bob calls `kill` and destructs the contract."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Protect access to all sensitive functions."
@staticmethod
def detect_suicidal_func(func):
"""Detect if the function is suicidal
Detect the public functions calling suicide/selfdestruct without protection
Returns:
(bool): True if the function is suicidal
"""
if func.is_constructor:
return False
if func.visibility not in ["public", "external"]:
return False
calls = [c.name for c in func.internal_calls]
if not ("suicide(address)" in calls or "selfdestruct(address)" in calls):
return False
if func.is_protected():
return False
return True
def detect_suicidal(self, contract):
ret = []
for f in contract.functions_declared:
if self.detect_suicidal_func(f):
ret.append(f)
return ret
def _detect(self):
"""Detect the suicidal functions"""
results = []
for c in self.contracts:
functions = self.detect_suicidal(c)
for func in functions:
info = [func, " allows anyone to destruct the contract\n"]
res = self.generate_result(info)
results.append(res)
return results
| 2,247 | Python | .py | 61 | 29.180328 | 91 | 0.661275 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,208 | storage_signed_integer_array.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/storage_signed_integer_array.py | """
Module detecting storage signed integer array bug
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
make_solc_versions,
)
from slither.core.cfg.node import NodeType
from slither.core.solidity_types import ArrayType
from slither.core.solidity_types.elementary_type import Int, ElementaryType
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.state_variable import StateVariable
from slither.slithir.operations.assignment import Assignment
from slither.slithir.operations.init_array import InitArray
class StorageSignedIntegerArray(AbstractDetector):
"""
Storage signed integer array
"""
ARGUMENT = "storage-array"
HELP = "Signed storage integer array compiler bug"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#storage-signed-integer-array"
)
WIKI_TITLE = "Storage Signed Integer Array"
# region wiki_description
WIKI_DESCRIPTION = """`solc` versions `0.4.7`-`0.5.9` contain [a compiler bug](https://blog.ethereum.org/2019/06/25/solidity-storage-array-bugs)
leading to incorrect values in signed integer arrays."""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract A {
int[3] ether_balances; // storage signed integer array
function bad0() private {
// ...
ether_balances = [-1, -1, -1];
// ...
}
}
```
`bad0()` uses a (storage-allocated) signed integer array state variable to store the ether balances of three accounts.
`-1` is supposed to indicate uninitialized values but the Solidity bug makes these as `1`, which could be exploited by the accounts.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Use a compiler version >= `0.5.10`."
VULNERABLE_SOLC_VERSIONS = make_solc_versions(4, 7, 25) + make_solc_versions(5, 0, 9)
@staticmethod
def _is_vulnerable_type(ir):
"""
Detect if the IR lvalue is a vulnerable type
Must be a storage allocation, and an array of Int
Assume the IR is a InitArray, or an Assignement to an ArrayType
"""
# Storage allocation
# Base type is signed integer
return (
(
isinstance(ir.lvalue, StateVariable)
or (isinstance(ir.lvalue, LocalVariable) and ir.lvalue.is_storage)
)
and isinstance(ir.lvalue.type.type, ElementaryType)
and ir.lvalue.type.type.type in Int
)
def detect_storage_signed_integer_arrays(self, contract):
"""
Detects and returns all nodes with storage-allocated signed integer array init/assignment
:param contract: Contract to detect within
:return: A list of tuples with (function, node) where function node has storage-allocated signed integer array init/assignment
"""
# Create our result set.
results = set()
# Loop for each function and modifier.
for function in contract.functions_and_modifiers_declared:
# Loop for every node in this function, looking for storage-allocated
# signed integer array initializations/assignments
for node in function.nodes:
if node.type == NodeType.EXPRESSION:
for ir in node.irs:
# Storage-allocated signed integer array initialization expression
if isinstance(ir, InitArray) and self._is_vulnerable_type(ir):
results.add((function, node))
# Assignment expression with lvalue being a storage-allocated signed integer array and
# rvalue being a signed integer array of different base type than lvalue
if (
isinstance(ir, Assignment)
and isinstance(ir.lvalue.type, ArrayType)
and self._is_vulnerable_type(ir)
# Base type is signed integer and lvalue base type is different from rvalue base type
and ir.lvalue.type.type != ir.rvalue.type.type
):
results.add((function, node))
# Return the resulting set of tuples
return results
def _detect(self):
"""
Detect storage signed integer array init/assignment
"""
results = []
for contract in self.contracts:
storage_signed_integer_arrays = self.detect_storage_signed_integer_arrays(contract)
for function, node in storage_signed_integer_arrays:
contract_info = ["Contract ", contract, " \n"]
function_info = ["\t- Function ", function, "\n"]
node_info = ["\t\t- ", node, " has a storage signed integer array assignment\n"]
res = self.generate_result(contract_info + function_info + node_info)
results.append(res)
return results
| 5,161 | Python | .py | 110 | 37.390909 | 148 | 0.651509 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,209 | array_by_reference.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/array_by_reference.py | """
Detects the passing of arrays located in memory to functions which expect to modify arrays via storage reference.
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.core.solidity_types.array_type import ArrayType
from slither.core.variables.state_variable import StateVariable
from slither.core.variables.local_variable import LocalVariable
from slither.slithir.operations.high_level_call import HighLevelCall
from slither.slithir.operations.internal_call import InternalCall
class ArrayByReference(AbstractDetector):
"""
Detects passing of arrays located in memory to functions which expect to modify arrays via storage reference.
"""
ARGUMENT = "array-by-reference"
HELP = "Modifying storage array by value"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#modifying-storage-array-by-value"
WIKI_TITLE = "Modifying storage array by value"
WIKI_DESCRIPTION = (
"Detect arrays passed to a function that expects reference to a storage array"
)
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Memory {
uint[1] public x; // storage
function f() public {
f1(x); // update x
f2(x); // do not update x
}
function f1(uint[1] storage arr) internal { // by reference
arr[0] = 1;
}
function f2(uint[1] arr) internal { // by value
arr[0] = 2;
}
}
```
Bob calls `f()`. Bob assumes that at the end of the call `x[0]` is 2, but it is 1.
As a result, Bob's usage of the contract is incorrect."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Ensure the correct usage of `memory` and `storage` in the function parameters. Make all the locations explicit."
@staticmethod
def get_funcs_modifying_array_params(contracts):
"""
Obtains a set of functions which take arrays not located in storage as parameters, and writes to them.
:param contracts: The collection of contracts to check functions in.
:return: A set of functions which take an array not located in storage as a parameter and writes to it.
"""
# Initialize our resulting set of functions which modify non-reference array parameters
results = set()
# Loop through all functions in all contracts.
for contract in contracts:
for function in contract.functions_declared:
# Skip any constructor functions.
if function.is_constructor:
continue
# Determine if this function takes an array as a parameter and the location isn't storage.
# If it has been written to, we know this sets an non-storage-ref array.
for param in function.parameters:
if isinstance(param.type, ArrayType) and param.location != "storage":
if param in function.variables_written:
results.add(function)
break
return results
@staticmethod
def detect_calls_passing_ref_to_function(contracts, array_modifying_funcs):
"""
Obtains all calls passing storage arrays by value to a function which cannot write to them successfully.
:param contracts: The collection of contracts to check for problematic calls in.
:param array_modifying_funcs: The collection of functions which take non-storage arrays as input and writes to
them.
:return: A list of tuples (calling_node, affected_argument, invoked_function) which denote all problematic
nodes invoking a function with some storage array argument where the invoked function seemingly attempts to
write to the array unsuccessfully.
"""
# Define our resulting array.
results = []
# Verify we have functions in our list to check for.
if not array_modifying_funcs:
return results
# Loop for each node in each function/modifier in each contract
# pylint: disable=too-many-nested-blocks
for contract in contracts:
for function in contract.functions_and_modifiers_declared:
for node in function.nodes:
# If this node has no expression, skip it.
if not node.expression:
continue
for ir in node.irs:
# Verify this is a high level call.
if not isinstance(ir, (HighLevelCall, InternalCall)):
continue
# Verify this references a function in our array modifying functions collection.
if ir.function not in array_modifying_funcs:
continue
# Verify one of these parameters is an array in storage.
for arg in ir.arguments:
# Verify this argument is a variable that is an array type.
if not isinstance(arg, (StateVariable, LocalVariable)):
continue
if not isinstance(arg.type, ArrayType):
continue
# If it is a state variable OR a local variable referencing storage, we add it to the list.
if isinstance(arg, StateVariable) or (
isinstance(arg, LocalVariable) and arg.location == "storage"
):
results.append((node, arg, ir.function))
return results
def _detect(self):
"""
Detects passing of arrays located in memory to functions which expect to modify arrays via storage reference.
:return: The JSON results of the detector, which contains the calling_node, affected_argument_variable and
invoked_function for each result found.
"""
results = []
array_modifying_funcs = self.get_funcs_modifying_array_params(self.contracts)
problematic_calls = self.detect_calls_passing_ref_to_function(
self.contracts, array_modifying_funcs
)
if problematic_calls:
for calling_node, affected_argument, invoked_function in problematic_calls:
info = [
calling_node.function,
" passes array ",
affected_argument,
"by reference to ",
invoked_function,
"which only takes arrays by value\n",
]
res = self.generate_result(info)
results.append(res)
return results
| 6,893 | Python | .py | 134 | 39.089552 | 139 | 0.627192 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,210 | reused_base_constructor.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/reused_base_constructor.py | """
Module detecting re-used base constructors in inheritance hierarchy.
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
ALL_SOLC_VERSIONS_04,
)
# Helper: adds explicitly called constructors with arguments to the results lookup.
def _add_constructors_with_args(
base_constructors, called_by_constructor, current_contract, results
):
for explicit_base_constructor in base_constructors:
if len(explicit_base_constructor.parameters) > 0:
if explicit_base_constructor not in results:
results[explicit_base_constructor] = []
results[explicit_base_constructor] += [(current_contract, called_by_constructor)]
class ReusedBaseConstructor(AbstractDetector):
"""
Re-used base constructors
"""
ARGUMENT = "reused-constructor"
HELP = "Reused base constructor"
IMPACT = DetectorClassification.MEDIUM
# The confidence is medium, because prior Solidity 0.4.22, we cant differentiate
# contract C is A() {
# to
# contract C is A {
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#reused-base-constructors"
WIKI_TITLE = "Reused base constructors"
WIKI_DESCRIPTION = "Detects if the same base constructor is called with arguments from two different locations in the same inheritance hierarchy."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
pragma solidity ^0.4.0;
contract A{
uint num = 5;
constructor(uint x) public{
num += x;
}
}
contract B is A{
constructor() A(2) public { /* ... */ }
}
contract C is A {
constructor() A(3) public { /* ... */ }
}
contract D is B, C {
constructor() public { /* ... */ }
}
contract E is B {
constructor() A(1) public { /* ... */ }
}
```
The constructor of `A` is called multiple times in `D` and `E`:
- `D` inherits from `B` and `C`, both of which construct `A`.
- `E` only inherits from `B`, but `B` and `E` construct `A`.
."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Remove the duplicate constructor call."
VULNERABLE_SOLC_VERSIONS = ALL_SOLC_VERSIONS_04
def _detect_explicitly_called_base_constructors(self, contract):
"""
Detects explicitly calls to base constructors with arguments in the inheritance hierarchy.
:param contract: The contract to detect explicit calls to a base constructor with arguments to.
:return: Dictionary of function:list(tuple): { constructor : [(invoking_contract, called_by_constructor]}
"""
results = {}
# Create a set to track all completed contracts
processed_contracts = set()
queued_contracts = [contract] + contract.inheritance
# Loop until there are no queued contracts left.
while len(queued_contracts) > 0:
# Pop a contract off the front of the queue, if it has already been processed, we stop.
current_contract = queued_contracts.pop(0)
if current_contract in processed_contracts:
continue
# Add this contract to the processed contracts
processed_contracts.add(current_contract)
# Prior Solidity 0.4.22, the constructor would appear two times
# Leading to several FPs
# As the result, we might miss some TPs if the reused is due to the constructor called
# In the contract definition
if self.compilation_unit.solc_version >= "0.4.22":
# Find all base constructors explicitly called from the contract definition with arguments.
_add_constructors_with_args(
current_contract.explicit_base_constructor_calls,
False,
current_contract,
results,
)
# Find all base constructors explicitly called from the constructor definition with arguments.
if current_contract.constructors_declared:
_add_constructors_with_args(
current_contract.constructors_declared.explicit_base_constructor_calls,
True,
current_contract,
results,
)
return results
def _detect(self):
"""
Detect reused base constructors.
:return: Returns a list of JSON results.
"""
results = []
# Loop for each contract
for contract in self.contracts:
# Detect all locations which all underlying base constructors with arguments were called from.
called_base_constructors = self._detect_explicitly_called_base_constructors(contract)
for base_constructor, call_list in called_base_constructors.items():
# Only report if there are multiple calls to the same base constructor.
if len(call_list) <= 1:
continue
# Generate data to output.
info = [
contract,
" gives base constructor ",
base_constructor,
" arguments more than once in inheritance hierarchy:\n",
]
for (calling_contract, called_by_constructor) in call_list:
info += [
"\t- From ",
calling_contract,
f" {'constructor' if called_by_constructor else 'contract'} definition\n",
]
res = self.generate_result(info)
results.append(res)
return results
| 5,724 | Python | .py | 131 | 33.870229 | 150 | 0.627225 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,211 | public_mapping_nested.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/public_mapping_nested.py | """
Module detecting public mappings with nested variables (returns incorrect values prior to 0.5.x)
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
ALL_SOLC_VERSIONS_04,
)
from slither.core.solidity_types.mapping_type import MappingType
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.core.declarations.structure import Structure
def detect_public_nested_mappings(contract):
"""
Detect any state variables that are initialized from an immediate function call (prior to constructor run).
:param contract: The contract to detect state variable definitions for.
:return: A list of all state variables defined in the given contract that meet the specified criteria.
"""
results = []
for state_variable in contract.variables:
# Verify this variable is defined in this contract
if state_variable.contract != contract:
continue
# Verify this is a public mapping
if state_variable.visibility != "public" or not isinstance(
state_variable.type, MappingType
):
continue
# Verify the value type is a user defined type (struct)
if not isinstance(state_variable.type.type_to, UserDefinedType) or not isinstance(
state_variable.type.type_to.type, Structure
):
continue
# Obtain the struct
struct_type = state_variable.type.type_to.type
for struct_member in struct_type.elems.values():
if isinstance(struct_member.type, UserDefinedType) and isinstance(
struct_member.type.type, Structure
):
results.append(state_variable)
break
return results
class PublicMappingNested(AbstractDetector):
"""
Detects public mappings with nested variables (returns incorrect values prior to 0.5.x)
"""
ARGUMENT = "public-mappings-nested"
HELP = "Public mappings with nested variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#public-mappings-with-nested-variables"
WIKI_TITLE = "Public mappings with nested variables"
WIKI_DESCRIPTION = "Prior to Solidity 0.5, a public mapping with nested structures returned [incorrect values](https://github.com/ethereum/solidity/issues/5520)."
WIKI_EXPLOIT_SCENARIO = """Bob interacts with a contract that has a public mapping with nested structures. The values returned by the mapping are incorrect, breaking Bob's usage"""
WIKI_RECOMMENDATION = "Do not use public mapping with nested structures."
VULNERABLE_SOLC_VERSIONS = ALL_SOLC_VERSIONS_04
def _detect(self):
"""
Detect public mappings with nested variables (returns incorrect values prior to 0.5.x)
Returns:
list: {'vuln', 'filename,'contract','func', 'public_nested_mappings'}
"""
results = []
for contract in self.contracts:
public_nested_mappings = detect_public_nested_mappings(contract)
if public_nested_mappings:
for public_nested_mapping in public_nested_mappings:
info = [public_nested_mapping, " is a public mapping with nested variables\n"]
json = self.generate_result(info)
results.append(json)
return results
| 3,485 | Python | .py | 70 | 41.542857 | 184 | 0.698469 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,212 | enum_conversion.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/enum_conversion.py | """
Module detecting dangerous conversion to enum
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
make_solc_versions,
)
from slither.slithir.operations import TypeConversion
from slither.core.declarations.enum import Enum
def _detect_dangerous_enum_conversions(contract):
"""Detect dangerous conversion to enum by checking IR
Args:
contract (Contract)
Returns:
list[(node, variable)] (Nodes where a variable is being converted into enum)
"""
return [
(n, ir.variable)
for f in contract.functions_declared
for n in f.nodes
for ir in n.irs
if isinstance(ir, TypeConversion) and isinstance(ir.type.type, Enum)
]
class EnumConversion(AbstractDetector):
"""
Detect dangerous conversion to enum
"""
ARGUMENT = "enum-conversion"
HELP = "Detect dangerous enum conversion"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-enum-conversion"
WIKI_TITLE = "Dangerous enum conversion"
WIKI_DESCRIPTION = "Detect out-of-range `enum` conversion (`solc` < `0.4.5`)."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
pragma solidity 0.4.2;
contract Test{
enum E{a}
function bug(uint a) public returns(E){
return E(a);
}
}
```
Attackers can trigger unexpected behaviour by calling `bug(1)`."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Use a recent compiler version. If `solc` <`0.4.5` is required, check the `enum` conversion range."
VULNERABLE_SOLC_VERSIONS = make_solc_versions(4, 0, 4)
def _detect(self):
"""Detect dangerous conversion to enum"""
results = []
for c in self.compilation_unit.contracts:
ret = _detect_dangerous_enum_conversions(c)
for node, var in ret:
func_info = [node, " has a dangerous enum conversion\n"]
# Output each node with the function info header as a separate result.
variable_info = ["\t- Variable: ", var, f" of type: {str(var.type)}\n"]
node_info = ["\t- Enum conversion: ", node, "\n"]
json = self.generate_result(func_info + variable_info + node_info)
results.append(json)
return results
| 2,455 | Python | .py | 63 | 32.365079 | 125 | 0.66849 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,213 | storage_ABIEncoderV2_array.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/storage_ABIEncoderV2_array.py | """
Module detecting ABIEncoderV2 array bug
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
make_solc_versions,
)
from slither.core.solidity_types import ArrayType
from slither.core.solidity_types import UserDefinedType
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.state_variable import StateVariable
from slither.slithir.operations import SolidityCall
from slither.core.declarations.solidity_variables import SolidityFunction
from slither.slithir.operations import EventCall
from slither.slithir.operations import HighLevelCall
from slither.utils.utils import unroll
class ABIEncoderV2Array(AbstractDetector):
"""
Detects Storage ABIEncoderV2 array bug
"""
ARGUMENT = "abiencoderv2-array"
HELP = "Storage abiencoderv2 array"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#storage-abiencoderv2-array"
)
WIKI_TITLE = "Storage ABIEncoderV2 Array"
WIKI_DESCRIPTION = """`solc` versions `0.4.7`-`0.5.9` contain a [compiler bug](https://blog.ethereum.org/2019/06/25/solidity-storage-array-bugs) leading to incorrect ABI encoder usage."""
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract A {
uint[2][3] bad_arr = [[1, 2], [3, 4], [5, 6]];
/* Array of arrays passed to abi.encode is vulnerable */
function bad() public {
bytes memory b = abi.encode(bad_arr);
}
}
```
`abi.encode(bad_arr)` in a call to `bad()` will incorrectly encode the array as `[[1, 2], [2, 3], [3, 4]]` and lead to unintended behavior.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Use a compiler >= `0.5.10`."
VULNERABLE_SOLC_VERSIONS = make_solc_versions(4, 7, 25) + make_solc_versions(5, 0, 9)
@staticmethod
def _detect_storage_abiencoderv2_arrays(contract):
"""
Detects and returns all nodes with storage-allocated abiencoderv2 arrays of arrays/structs in abi.encode, events or external calls
:param contract: Contract to detect within
:return: A list of tuples with (function, node) where function node has storage-allocated abiencoderv2 arrays of arrays/structs
"""
# Create our result set.
results = set()
# Loop for each function and modifier.
# pylint: disable=too-many-nested-blocks
for function in contract.functions_and_modifiers_declared:
# Loop every node, looking for storage-allocated array of arrays/structs
# in arguments to abi.encode, events or external calls
for node in function.nodes:
for ir in node.irs:
# Call to abi.encode()
if (
isinstance(ir, SolidityCall)
and ir.function == SolidityFunction("abi.encode()")
or
# Call to emit event
# Call to external function
isinstance(ir, (EventCall, HighLevelCall))
):
for arg in unroll(ir.arguments):
# Check if arguments are storage allocated arrays of arrays/structs
if (
isinstance(arg.type, ArrayType)
# Storage allocated
and (
isinstance(arg, StateVariable)
or (isinstance(arg, LocalVariable) and arg.is_storage)
)
# Array of arrays or structs
and isinstance(arg.type.type, (ArrayType, UserDefinedType))
):
results.add((function, node))
break
# Return the resulting set of tuples
return results
def _detect(self):
"""
Detect ABIEncoderV2 array bug
"""
results = []
# Check if pragma experimental ABIEncoderV2 is used
if not any(
(p.directive[0] == "experimental" and p.directive[1] == "ABIEncoderV2")
for p in self.compilation_unit.pragma_directives
):
return results
# Check for storage-allocated abiencoderv2 arrays of arrays/structs
# in arguments of abi.encode, events or external calls
for contract in self.contracts:
storage_abiencoderv2_arrays = self._detect_storage_abiencoderv2_arrays(contract)
for function, node in storage_abiencoderv2_arrays:
info = ["Function ", function, " trigger an abi encoding bug:\n\t- ", node, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| 5,099 | Python | .py | 107 | 35.308411 | 191 | 0.60358 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,214 | multiple_constructor_schemes.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/multiple_constructor_schemes.py | from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class MultipleConstructorSchemes(AbstractDetector):
"""
Module detecting multiple constructors in the same contract.
(This was possible prior to Solidity 0.4.23, using old and new constructor schemes).
"""
ARGUMENT = "multiple-constructors"
HELP = "Multiple constructor schemes"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#multiple-constructor-schemes"
)
WIKI_TITLE = "Multiple constructor schemes"
WIKI_DESCRIPTION = (
"Detect multiple constructor definitions in the same contract (using new and old schemes)."
)
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract A {
uint x;
constructor() public {
x = 0;
}
function A() public {
x = 1;
}
function test() public returns(uint) {
return x;
}
}
```
In Solidity [0.4.22](https://github.com/ethereum/solidity/releases/tag/v0.4.23), a contract with both constructor schemes will compile. The first constructor will take precedence over the second, which may be unintended."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Only declare one constructor, preferably using the new scheme `constructor(...)` instead of `function <contractName>(...)`."
def _detect(self):
"""
Detect multiple constructor schemes in the same contract
:return: Returns a list of contract JSON result, where each result contains all constructor definitions.
"""
results = []
for contract in self.contracts:
# Obtain any constructors defined in this contract
constructors = [f for f in contract.constructors if f.contract_declarer == contract]
# If there is more than one, we encountered the described issue occurring.
if constructors and len(constructors) > 1:
info = [contract, " contains multiple constructors in the same contract:\n"]
for constructor in constructors:
info += ["\t- ", constructor, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| 2,373 | Python | .py | 53 | 37.283019 | 223 | 0.680122 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,215 | uninitialized_function_ptr_in_constructor.py | NioTheFirst_ScType/slither/detectors/compiler_bugs/uninitialized_function_ptr_in_constructor.py | """
Module detecting uninitialized function pointer calls in constructors
"""
from slither.detectors.abstract_detector import (
AbstractDetector,
DetectorClassification,
make_solc_versions,
)
from slither.slithir.operations import InternalDynamicCall, OperationWithLValue
from slither.slithir.variables import ReferenceVariable
from slither.slithir.variables.variable import SlithIRVariable
def _get_variables_entrance(function):
"""
Return the first SSA variables of the function
Catpure the phi operation at the entry point
"""
ret = []
if function.entry_point:
for ir_ssa in function.entry_point.irs_ssa:
if isinstance(ir_ssa, OperationWithLValue):
ret.append(ir_ssa.lvalue)
return ret
def _is_vulnerable(node, variables_entrance):
"""
Vulnerable if an IR ssa:
- It is an internal dynamic call
- The destination has not an index of 0
- The destination is not in the allowed variable
"""
for ir_ssa in node.irs_ssa:
if isinstance(ir_ssa, InternalDynamicCall):
destination = ir_ssa.function
# If it is a reference variable, destination should be the origin variable
# Note: this will create FN if one of the field of a structure is updated, while not begin
# the field of the function pointer. This should be fixed once we have the IR refactoring
if isinstance(destination, ReferenceVariable):
destination = destination.points_to_origin
if isinstance(destination, SlithIRVariable) and ir_ssa.function.index == 0:
return True
if destination in variables_entrance:
return True
return False
class UninitializedFunctionPtrsConstructor(AbstractDetector):
"""
Uninitialized function pointer calls in constructors
"""
ARGUMENT = "uninitialized-fptr-cst"
HELP = "Uninitialized function pointer calls in constructors"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-function-pointers-in-constructors"
WIKI_TITLE = "Uninitialized function pointers in constructors"
WIKI_DESCRIPTION = "solc versions `0.4.5`-`0.4.26` and `0.5.0`-`0.5.8` contain a compiler bug leading to unexpected behavior when calling uninitialized function pointers in constructors."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract bad0 {
constructor() public {
/* Uninitialized function pointer */
function(uint256) internal returns(uint256) a;
a(10);
}
}
```
The call to `a(10)` will lead to unexpected behavior because function pointer `a` is not initialized in the constructor."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = (
"Initialize function pointers before calling. Avoid function pointers if possible."
)
VULNERABLE_SOLC_VERSIONS = make_solc_versions(4, 5, 25) + make_solc_versions(5, 0, 8)
@staticmethod
def _detect_uninitialized_function_ptr_in_constructor(contract):
"""
Detect uninitialized function pointer calls in constructors
:param contract: The contract of interest for detection
:return: A list of nodes with uninitialized function pointer calls in the constructor of given contract
"""
results = []
constructor = contract.constructors_declared
if constructor:
variables_entrance = _get_variables_entrance(constructor)
results = [
node for node in constructor.nodes if _is_vulnerable(node, variables_entrance)
]
return results
def _detect(self):
"""
Detect uninitialized function pointer calls in constructors of contracts
Returns:
list: ['uninitialized function pointer calls in constructors']
"""
results = []
for contract in self.compilation_unit.contracts:
contract_info = ["Contract ", contract, " \n"]
nodes = self._detect_uninitialized_function_ptr_in_constructor(contract)
for node in nodes:
node_info = [
"\t ",
node,
" is an unintialized function pointer call in a constructor\n",
]
json = self.generate_result(contract_info + node_info)
results.append(json)
return results
| 4,554 | Python | .py | 104 | 35.769231 | 191 | 0.681859 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,216 | could_be_constant.py | NioTheFirst_ScType/slither/detectors/variables/could_be_constant.py | from typing import List, Dict
from slither.utils.output import Output
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.formatters.variables.unchanged_state_variables import custom_format
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from .unchanged_state_variables import UnchangedStateVariables
class CouldBeConstant(AbstractDetector):
"""
State variables that could be declared as constant.
Not all types for constants are implemented in Solidity as of 0.4.25.
The only supported types are value types and strings (ElementaryType).
Reference: https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
"""
ARGUMENT = "constable-states"
HELP = "State variables that could be declared constant"
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant"
WIKI_TITLE = "State variables that could be declared constant"
WIKI_DESCRIPTION = "State variables that are not updated following deployment should be declared constant to save gas."
WIKI_RECOMMENDATION = "Add the `constant` attribute to state variables that never change."
def _detect(self) -> List[Output]:
"""Detect state variables that could be constant"""
results = {}
unchanged_state_variables = UnchangedStateVariables(self.compilation_unit)
unchanged_state_variables.detect()
for variable in unchanged_state_variables.constant_candidates:
results[variable.canonical_name] = self.generate_result(
[variable, " should be constant \n"]
)
# Order by canonical name for deterministic results
return [results[k] for k in sorted(results)]
@staticmethod
def _format(compilation_unit: SlitherCompilationUnit, result: Dict) -> None:
custom_format(compilation_unit, result, "constant")
| 2,060 | Python | .py | 35 | 52.657143 | 123 | 0.759801 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,217 | function_init_state_variables.py | NioTheFirst_ScType/slither/detectors/variables/function_init_state_variables.py | """
Module detecting state variables initializing from an immediate function call (prior to constructor run).
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.visitors.expression.export_values import ExportValues
from slither.core.declarations.function import Function
from slither.core.variables.state_variable import StateVariable
def detect_function_init_state_vars(contract):
"""
Detect any state variables that are initialized from an immediate function call (prior to constructor run).
:param contract: The contract to detect state variable definitions for.
:return: A list of all state variables defined in the given contract that meet the specified criteria.
"""
results = []
# Loop for each state variable explicitly defined in this contract.
for state_variable in contract.variables:
# Skip this variable if it is inherited and not explicitly defined in this contract definition.
if state_variable.contract != contract:
continue
# If it has an expression, we try to break it down to identify if it contains a function call, or reference
# to a non-constant state variable.
if state_variable.expression:
exported_values = ExportValues(state_variable.expression).result()
for exported_value in exported_values:
if (
isinstance(exported_value, StateVariable) and not exported_value.is_constant
) or (isinstance(exported_value, Function) and not exported_value.pure):
results.append(state_variable)
break
return results
class FunctionInitializedState(AbstractDetector):
"""
State variables initializing from an immediate function call (prior to constructor run).
"""
ARGUMENT = "function-init-state"
HELP = "Function initializing state variables"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#function-initializing-state"
)
WIKI_TITLE = "Function Initializing State"
WIKI_DESCRIPTION = "Detects the immediate initialization of state variables through function calls that are not pure/constant, or that use non-constant state variable."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract StateVarInitFromFunction {
uint public v = set(); // Initialize from function (sets to 77)
uint public w = 5;
uint public x = set(); // Initialize from function (sets to 88)
address public shouldntBeReported = address(8);
constructor(){
// The constructor is run after all state variables are initialized.
}
function set() public returns(uint) {
// If this function is being used to initialize a state variable declared
// before w, w will be zero. If it is declared after w, w will be set.
if(w == 0) {
return 77;
}
return 88;
}
}
```
In this case, users might intend a function to return a value a state variable can initialize with, without realizing the context for the contract is not fully initialized.
In the example above, the same function sets two different values for state variables because it checks a state variable that is not yet initialized in one case, and is initialized in the other.
Special care must be taken when initializing state variables from an immediate function call so as not to incorrectly assume the state is initialized.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Remove any initialization of state variables via non-constant state variables or function calls. If variables must be set upon contract deployment, locate initialization in the constructor instead."
def _detect(self):
"""
Detect state variables defined from an immediate function call (pre-contract deployment).
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
state_variables = detect_function_init_state_vars(contract)
if state_variables:
for state_variable in state_variables:
info = [
state_variable,
" is set pre-construction with a non-constant function or state variable:\n",
]
info += [f"\t- {state_variable.expression}\n"]
json = self.generate_result(info)
results.append(json)
return results
| 4,759 | Python | .py | 90 | 44.588889 | 225 | 0.698515 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,218 | var_read_using_this.py | NioTheFirst_ScType/slither/detectors/variables/var_read_using_this.py | from typing import List
from slither.core.cfg.node import Node
from slither.core.declarations import Function, SolidityVariable
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.slithir.operations.high_level_call import HighLevelCall
class VarReadUsingThis(AbstractDetector):
ARGUMENT = "var-read-using-this"
HELP = "Contract reads its own variable using `this`"
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Vulnerabilities-Description#public-variable-read-in-external-context"
WIKI_TITLE = "Public variable read in external context"
WIKI_DESCRIPTION = "The contract reads its own variable using `this`, adding overhead of an unnecessary STATICCALL."
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract C {
mapping(uint => address) public myMap;
function test(uint x) external returns(address) {
return this.myMap(x);
}
}
```
"""
WIKI_RECOMMENDATION = "Read the variable directly from storage instead of calling the contract."
def _detect(self):
results = []
for c in self.contracts:
for func in c.functions:
for node in self._detect_var_read_using_this(func):
info = [
"The function ",
func,
" reads ",
node,
" with `this` which adds an extra STATICCALL.\n",
]
json = self.generate_result(info)
results.append(json)
return results
@staticmethod
def _detect_var_read_using_this(func: Function) -> List[Node]:
results: List[Node] = []
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, HighLevelCall):
if (
ir.destination == SolidityVariable("this")
and ir.is_static_call()
and ir.function.visibility == "public"
):
results.append(node)
return sorted(results, key=lambda x: x.node_id)
| 2,248 | Python | .py | 52 | 32.307692 | 120 | 0.611974 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,219 | predeclaration_usage_local.py | NioTheFirst_ScType/slither/detectors/variables/predeclaration_usage_local.py | """
Module detecting any path leading to usage of a local variable before it is declared.
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class PredeclarationUsageLocal(AbstractDetector):
"""
Pre-declaration usage of local variable
"""
ARGUMENT = "variable-scope"
HELP = "Local variables used prior their declaration"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#pre-declaration-usage-of-local-variables"
WIKI_TITLE = "Pre-declaration usage of local variables"
WIKI_DESCRIPTION = "Detects the possible usage of a variable before the declaration is stepped over (either because it is later declared, or declared in another scope)."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract C {
function f(uint z) public returns (uint) {
uint y = x + 9 + z; // 'z' is used pre-declaration
uint x = 7;
if (z % 2 == 0) {
uint max = 5;
// ...
}
// 'max' was intended to be 5, but it was mistakenly declared in a scope and not assigned (so it is zero).
for (uint i = 0; i < max; i++) {
x += 1;
}
return x;
}
}
```
In the case above, the variable `x` is used before its declaration, which may result in unintended consequences.
Additionally, the for-loop uses the variable `max`, which is declared in a previous scope that may not always be reached. This could lead to unintended consequences if the user mistakenly uses a variable prior to any intended declaration assignment. It also may indicate that the user intended to reference a different variable."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Move all variable declarations prior to any usage of the variable, and ensure that reaching a variable declaration does not depend on some conditional if it is used unconditionally."
def detect_predeclared_local_usage(self, node, results, already_declared, visited):
"""
Detects if a given node uses a variable prior to declaration in any code path.
:param node: The node to initiate the scan from (searches recursively through all sons)
:param already_declared: A set of variables already known to be declared in this path currently.
:param already_visited: A set of nodes already visited in this path currently.
:param results: A list of tuple(node, local_variable) denoting nodes which used a variable before declaration.
:return: None
"""
if node in visited:
return
visited = visited | {node}
if node.variable_declaration:
already_declared = already_declared | {node.variable_declaration}
if not node in self.fix_point_information:
self.fix_point_information[node] = []
# If we already explored this node with the same information
if already_declared:
for fix_point in self.fix_point_information[node]:
if fix_point == already_declared:
return
if already_declared:
self.fix_point_information[node] += [already_declared]
for variable in set(node.local_variables_read + node.local_variables_written):
if variable not in already_declared:
result = (node, variable)
if result not in results:
results.append(result)
for son in node.sons:
self.detect_predeclared_local_usage(son, results, already_declared, visited)
def detect_predeclared_in_contract(self, contract):
"""
Detects and returns all nodes in a contract which use a variable before it is declared.
:param contract: Contract to detect pre-declaration usage of locals within.
:return: A list of tuples: (function, list(tuple(node, local_variable)))
"""
# Create our result set.
results = []
# Loop for each function and modifier's nodes and analyze for predeclared local variable usage.
for function in contract.functions_and_modifiers_declared:
predeclared_usage = []
if function.nodes:
self.detect_predeclared_local_usage(
function.nodes[0],
predeclared_usage,
set(function.parameters + function.returns),
set(),
)
if predeclared_usage:
results.append((function, predeclared_usage))
# Return the resulting set of nodes which set array length.
return results
def _detect(self):
"""
Detect usage of a local variable before it is declared.
"""
results = []
# Fix_point_information contains a list of set
# Each set contains the already declared variables saw in one path
# If a path has the same set as a path already explored
# We don't need to continue
# pylint: disable=attribute-defined-outside-init
self.fix_point_information = {}
for contract in self.contracts:
predeclared_usages = self.detect_predeclared_in_contract(contract)
if predeclared_usages:
for (predeclared_usage_function, predeclared_usage_nodes) in predeclared_usages:
for (
predeclared_usage_node,
predeclared_usage_local_variable,
) in predeclared_usage_nodes:
info = [
"Variable '",
predeclared_usage_local_variable,
"' in ",
predeclared_usage_function,
" potentially used before declaration: ",
predeclared_usage_node,
"\n",
]
res = self.generate_result(info)
results.append(res)
return results
| 6,187 | Python | .py | 121 | 39.53719 | 331 | 0.628623 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,220 | uninitialized_state_variables.py | NioTheFirst_ScType/slither/detectors/variables/uninitialized_state_variables.py | """
Module detecting state uninitialized variables
Recursively check the called functions
The heuristic checks:
- state variables including mappings/refs
- LibraryCalls, InternalCalls, InternalDynamicCalls with storage variables
Only analyze "leaf" contracts (contracts that are not inherited by another contract)
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.slithir.operations import InternalCall, LibraryCall
from slither.slithir.variables import ReferenceVariable
class UninitializedStateVarsDetection(AbstractDetector):
"""
Constant function detector
"""
ARGUMENT = "uninitialized-state"
HELP = "Uninitialized state variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-state-variables"
WIKI_TITLE = "Uninitialized state variables"
WIKI_DESCRIPTION = "Uninitialized state variables."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Uninitialized{
address destination;
function transfer() payable public{
destination.transfer(msg.value);
}
}
```
Bob calls `transfer`. As a result, the Ether are sent to the address `0x0` and are lost.
"""
# endregion wiki_exploit_scenario
# region wiki_recommendation
WIKI_RECOMMENDATION = """
Initialize all the variables. If a variable is meant to be initialized to zero, explicitly set it to zero to improve code readability.
"""
# endregion wiki_recommendation
@staticmethod
def _written_variables(contract):
ret = []
# pylint: disable=too-many-nested-blocks
for f in contract.all_functions_called + contract.modifiers:
for n in f.nodes:
ret += n.state_variables_written
for ir in n.irs:
if isinstance(ir, (LibraryCall, InternalCall)):
idx = 0
if ir.function:
for param in ir.function.parameters:
if param.location == "storage":
# If its a storage variable, add either the variable
# Or the variable it points to if its a reference
if isinstance(ir.arguments[idx], ReferenceVariable):
ret.append(ir.arguments[idx].points_to_origin)
else:
ret.append(ir.arguments[idx])
idx = idx + 1
return ret
def _variable_written_in_proxy(self):
# Hack to memoize without having it define in the init
if hasattr(self, "__variables_written_in_proxy"):
# pylint: disable=access-member-before-definition
return self.__variables_written_in_proxy
variables_written_in_proxy = []
for c in self.compilation_unit.contracts:
if c.is_upgradeable_proxy:
variables_written_in_proxy += self._written_variables(c)
# pylint: disable=attribute-defined-outside-init
self.__variables_written_in_proxy = list({v.name for v in variables_written_in_proxy})
return self.__variables_written_in_proxy
def _written_variables_in_proxy(self, contract):
variables = []
if contract.is_upgradeable:
variables_name_written_in_proxy = self._variable_written_in_proxy()
if variables_name_written_in_proxy:
variables_in_contract = [
contract.get_state_variable_from_name(v)
for v in variables_name_written_in_proxy
]
variables_in_contract = [v for v in variables_in_contract if v]
variables += variables_in_contract
return list(set(variables))
@staticmethod
def _read_variables(contract):
ret = []
for f in contract.all_functions_called + contract.modifiers:
ret += f.state_variables_read
return ret
def _detect_uninitialized(self, contract):
written_variables = self._written_variables(contract)
written_variables += self._written_variables_in_proxy(contract)
read_variables = self._read_variables(contract)
return [
(variable, contract.get_functions_reading_from_variable(variable))
for variable in contract.state_variables
if variable not in written_variables
and not variable.expression
and variable in read_variables
]
def _detect(self):
"""Detect uninitialized state variables
Recursively visit the calls
Returns:
dict: [contract name] = set(state variable uninitialized)
"""
results = []
for c in self.compilation_unit.contracts_derived:
ret = self._detect_uninitialized(c)
for variable, functions in ret:
info = [variable, " is never initialized. It is used in:\n"]
for f in functions:
info += ["\t- ", f, "\n"]
json = self.generate_result(info)
results.append(json)
return results
| 5,391 | Python | .py | 118 | 34.542373 | 134 | 0.626715 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,221 | could_be_immutable.py | NioTheFirst_ScType/slither/detectors/variables/could_be_immutable.py | from typing import List, Dict
from slither.utils.output import Output
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.formatters.variables.unchanged_state_variables import custom_format
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from .unchanged_state_variables import UnchangedStateVariables
class CouldBeImmutable(AbstractDetector):
"""
State variables that could be declared immutable.
# Immutable attribute available in Solidity 0.6.5 and above
# https://blog.soliditylang.org/2020/04/06/solidity-0.6.5-release-announcement/
"""
# VULNERABLE_SOLC_VERSIONS =
ARGUMENT = "immutable-states"
HELP = "State variables that could be declared immutable"
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-immutable"
WIKI_TITLE = "State variables that could be declared immutable"
WIKI_DESCRIPTION = "State variables that are not updated following deployment should be declared immutable to save gas."
WIKI_RECOMMENDATION = "Add the `immutable` attribute to state variables that never change or are set only in the constructor."
def _detect(self) -> List[Output]:
"""Detect state variables that could be immutable"""
results = {}
unchanged_state_variables = UnchangedStateVariables(self.compilation_unit)
unchanged_state_variables.detect()
for variable in unchanged_state_variables.immutable_candidates:
results[variable.canonical_name] = self.generate_result(
[variable, " should be immutable \n"]
)
# Order by canonical name for deterministic results
return [results[k] for k in sorted(results)]
@staticmethod
def _format(compilation_unit: SlitherCompilationUnit, result: Dict) -> None:
custom_format(compilation_unit, result, "immutable")
| 2,037 | Python | .py | 35 | 52.028571 | 130 | 0.75715 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,222 | uninitialized_local_variables.py | NioTheFirst_ScType/slither/detectors/variables/uninitialized_local_variables.py | """
Module detecting uninitialized local variables
Recursively explore the CFG to only report uninitialized local variables that are
read before being written
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class UninitializedLocalVars(AbstractDetector):
ARGUMENT = "uninitialized-local"
HELP = "Uninitialized local variables"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-local-variables"
WIKI_TITLE = "Uninitialized local variables"
WIKI_DESCRIPTION = "Uninitialized local variables."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Uninitialized is Owner{
function withdraw() payable public onlyOwner{
address to;
to.transfer(this.balance)
}
}
```
Bob calls `transfer`. As a result, all Ether is sent to the address `0x0` and is lost."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Initialize all the variables. If a variable is meant to be initialized to zero, explicitly set it to zero to improve code readability."
key = "UNINITIALIZEDLOCAL"
def _detect_uninitialized(self, function, node, visited):
if node in visited:
return
visited = visited + [node]
fathers_context = []
for father in node.fathers:
if self.key in father.context:
fathers_context += father.context[self.key]
# Exclude path that dont bring further information
if node in self.visited_all_paths:
if all(f_c in self.visited_all_paths[node] for f_c in fathers_context):
return
else:
self.visited_all_paths[node] = []
self.visited_all_paths[node] = list(set(self.visited_all_paths[node] + fathers_context))
if self.key in node.context:
fathers_context += node.context[self.key]
variables_read = node.variables_read
for uninitialized_local_variable in fathers_context:
if uninitialized_local_variable in variables_read:
self.results.append((function, uninitialized_local_variable))
# Only save the local variables that are not yet written
uninitialized_local_variables = list(set(fathers_context) - set(node.variables_written))
node.context[self.key] = uninitialized_local_variables
for son in node.sons:
self._detect_uninitialized(function, son, visited)
def _detect(self):
"""Detect uninitialized local variables
Recursively visit the calls
Returns:
dict: [contract name] = set(local variable uninitialized)
"""
results = []
# pylint: disable=attribute-defined-outside-init
self.results = []
self.visited_all_paths = {}
for contract in self.compilation_unit.contracts:
for function in contract.functions:
if (
function.is_implemented
and function.contract_declarer == contract
and function.entry_point
):
if function.contains_assembly:
continue
# dont consider storage variable, as they are detected by another detector
uninitialized_local_variables = [
v for v in function.local_variables if not v.is_storage and v.uninitialized
]
function.entry_point.context[self.key] = uninitialized_local_variables
self._detect_uninitialized(function, function.entry_point, [])
all_results = list(set(self.results))
for (function, uninitialized_local_variable) in all_results:
info = [
uninitialized_local_variable,
" is a local variable never initialized\n",
]
json = self.generate_result(info)
results.append(json)
return results
| 4,132 | Python | .py | 88 | 36.522727 | 162 | 0.649826 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,223 | unchanged_state_variables.py | NioTheFirst_ScType/slither/detectors/variables/unchanged_state_variables.py | """
Module detecting state variables that could be declared as constant
"""
from typing import Set, List
from packaging import version
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.solidity_types.elementary_type import ElementaryType
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.core.variables.variable import Variable
from slither.visitors.expression.export_values import ExportValues
from slither.core.declarations import Contract, Function
from slither.core.declarations.solidity_variables import SolidityFunction
from slither.core.variables.state_variable import StateVariable
from slither.core.expressions import CallExpression, NewContract
def _is_valid_type(v: StateVariable) -> bool:
t = v.type
if isinstance(t, ElementaryType):
return True
if isinstance(t, UserDefinedType) and isinstance(t.type, Contract):
return True
return False
def _valid_candidate(v: StateVariable) -> bool:
return _is_valid_type(v) and not (v.is_constant or v.is_immutable)
def _is_constant_var(v: Variable) -> bool:
if isinstance(v, StateVariable):
return v.is_constant
return False
# https://solidity.readthedocs.io/en/v0.5.2/contracts.html#constant-state-variables
valid_solidity_function = [
SolidityFunction("keccak256()"),
SolidityFunction("keccak256(bytes)"),
SolidityFunction("sha256()"),
SolidityFunction("sha256(bytes)"),
SolidityFunction("ripemd160()"),
SolidityFunction("ripemd160(bytes)"),
SolidityFunction("ecrecover(bytes32,uint8,bytes32,bytes32)"),
SolidityFunction("addmod(uint256,uint256,uint256)"),
SolidityFunction("mulmod(uint256,uint256,uint256)"),
]
def _constant_initial_expression(v: Variable) -> bool:
if not v.expression:
return True
# B b = new B(); b cannot be constant, so filter out and recommend it be immutable
if isinstance(v.expression, CallExpression) and isinstance(v.expression.called, NewContract):
return False
export = ExportValues(v.expression)
values = export.result()
if not values:
return True
return all((val in valid_solidity_function or _is_constant_var(val) for val in values))
class UnchangedStateVariables:
"""
Find state variables that could be declared as constant or immutable (not written after deployment).
"""
def __init__(self, compilation_unit: SlitherCompilationUnit):
self.compilation_unit = compilation_unit
self._constant_candidates: List[StateVariable] = []
self._immutable_candidates: List[StateVariable] = []
@property
def immutable_candidates(self) -> List[StateVariable]:
"""Return the immutable candidates"""
return self._immutable_candidates
@property
def constant_candidates(self) -> List[StateVariable]:
"""Return the constant candidates"""
return self._constant_candidates
def detect(self):
"""Detect state variables that could be constant or immutable"""
for c in self.compilation_unit.contracts_derived:
variables = []
functions = []
variables.append(c.state_variables)
functions.append(c.all_functions_called)
valid_candidates: Set[StateVariable] = {
item for sublist in variables for item in sublist if _valid_candidate(item)
}
all_functions: List[Function] = list(
{item1 for sublist in functions for item1 in sublist if isinstance(item1, Function)}
)
variables_written = []
constructor_variables_written = []
variables_initialized = []
for f in all_functions:
if f.is_constructor_variables:
variables_initialized.extend(f.state_variables_written)
elif f.is_constructor:
constructor_variables_written.extend(f.state_variables_written)
else:
variables_written.extend(f.state_variables_written)
for v in valid_candidates:
if v not in variables_written:
if _constant_initial_expression(v) and v not in constructor_variables_written:
self.constant_candidates.append(v)
elif (
v in constructor_variables_written or v in variables_initialized
) and version.parse(self.compilation_unit.solc_version) >= version.parse(
"0.6.5"
):
self.immutable_candidates.append(v)
| 4,660 | Python | .py | 99 | 38.373737 | 104 | 0.68269 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,224 | similar_variables.py | NioTheFirst_ScType/slither/detectors/variables/similar_variables.py | """
Check for state variables too similar
Do not check contract inheritance
"""
import difflib
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class SimilarVarsDetection(AbstractDetector):
"""
Variable similar detector
"""
ARGUMENT = "similar-names"
HELP = "Variable names are too similar"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-too-similar"
)
WIKI_TITLE = "Variable names too similar"
WIKI_DESCRIPTION = "Detect variables with names that are too similar."
WIKI_EXPLOIT_SCENARIO = "Bob uses several variables with similar names. As a result, his code is difficult to review."
WIKI_RECOMMENDATION = "Prevent variables from having similar names."
@staticmethod
def similar(seq1, seq2):
"""Test the name similarity
Two name are similar if difflib.SequenceMatcher on the lowercase
version of the name is greater than 0.90
See: https://docs.python.org/2/library/difflib.html
Args:
seq1 (str): first name
seq2 (str): second name
Returns:
bool: true if names are similar
"""
if len(seq1) != len(seq2):
return False
val = difflib.SequenceMatcher(a=seq1.lower(), b=seq2.lower()).ratio()
ret = val > 0.90
return ret
@staticmethod
def detect_sim(contract):
"""Detect variables with similar name
Returns:
bool: true if variables have similar name
"""
all_var = [x.variables for x in contract.functions]
all_var = [x for l in all_var for x in l]
contract_var = contract.variables
all_var = set(all_var + contract_var)
ret = []
for v1 in all_var:
for v2 in all_var:
if v1.name.lower() != v2.name.lower():
if SimilarVarsDetection.similar(v1.name, v2.name):
if (v2, v1) not in ret:
ret.append((v1, v2))
return set(ret)
def _detect(self):
"""Detect similar variables name
Returns:
list: {'vuln', 'filename,'contract','vars'}
"""
results = []
for c in self.contracts:
allVars = self.detect_sim(c)
if allVars:
for (v1, v2) in sorted(allVars, key=lambda x: (x[0].name, x[1].name)):
v_left = v1 if v1.name < v2.name else v2
v_right = v2 if v_left == v1 else v1
info = ["Variable ", v_left, " is too similar to ", v_right, "\n"]
json = self.generate_result(info)
results.append(json)
return results
| 2,879 | Python | .py | 72 | 30.319444 | 122 | 0.601218 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,225 | uninitialized_storage_variables.py | NioTheFirst_ScType/slither/detectors/variables/uninitialized_storage_variables.py | """
Module detecting uninitialized storage variables
Recursively explore the CFG to only report uninitialized storage variables that are
written before being read
"""
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
class UninitializedStorageVars(AbstractDetector):
ARGUMENT = "uninitialized-storage"
HELP = "Uninitialized storage variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-storage-variables"
WIKI_TITLE = "Uninitialized storage variables"
WIKI_DESCRIPTION = "An uninitialized storage variable will act as a reference to the first state variable, and can override a critical variable."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Uninitialized{
address owner = msg.sender;
struct St{
uint a;
}
function func() {
St st;
st.a = 0x0;
}
}
```
Bob calls `func`. As a result, `owner` is overridden to `0`.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Initialize all storage variables."
# node.context[self.key] contains the uninitialized storage variables
key = "UNINITIALIZEDSTORAGE"
def _detect_uninitialized(self, function, node, visited):
if node in visited:
return
visited = visited + [node]
fathers_context = []
for father in node.fathers:
if self.key in father.context:
fathers_context += father.context[self.key]
# Exclude paths that dont bring further information
if node in self.visited_all_paths:
if all(f_c in self.visited_all_paths[node] for f_c in fathers_context):
return
else:
self.visited_all_paths[node] = []
self.visited_all_paths[node] = list(set(self.visited_all_paths[node] + fathers_context))
if self.key in node.context:
fathers_context += node.context[self.key]
variables_read = node.variables_read
for uninitialized_storage_variable in fathers_context:
if uninitialized_storage_variable in variables_read:
self.results.append((function, uninitialized_storage_variable))
# Only save the storage variables that are not yet written
uninitialized_storage_variables = list(set(fathers_context) - set(node.variables_written))
node.context[self.key] = uninitialized_storage_variables
for son in node.sons:
self._detect_uninitialized(function, son, visited)
def _detect(self):
"""Detect uninitialized storage variables
Recursively visit the calls
Returns:
dict: [contract name] = set(storage variable uninitialized)
"""
results = []
# pylint: disable=attribute-defined-outside-init
self.results = []
self.visited_all_paths = {}
for contract in self.compilation_unit.contracts:
for function in contract.functions:
if function.is_implemented and function.entry_point:
uninitialized_storage_variables = [
v for v in function.local_variables if v.is_storage and v.uninitialized
]
function.entry_point.context[self.key] = uninitialized_storage_variables
self._detect_uninitialized(function, function.entry_point, [])
for (function, uninitialized_storage_variable) in self.results:
info = [
uninitialized_storage_variable,
" is a storage variable never initialized\n",
]
json = self.generate_result(info)
results.append(json)
return results
| 3,877 | Python | .py | 86 | 35.848837 | 149 | 0.665161 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,226 | unused_state_variables.py | NioTheFirst_ScType/slither/detectors/variables/unused_state_variables.py | """
Module detecting unused state variables
"""
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.core.solidity_types import ArrayType
from slither.visitors.expression.export_values import ExportValues
from slither.core.variables.state_variable import StateVariable
from slither.formatters.variables.unused_state_variables import custom_format
def detect_unused(contract):
if contract.is_signature_only():
return None
# Get all the variables read in all the functions and modifiers
all_functions = contract.all_functions_called + contract.modifiers
variables_used = [x.state_variables_read for x in all_functions]
variables_used += [
x.state_variables_written for x in all_functions if not x.is_constructor_variables
]
array_candidates = [x.variables for x in all_functions]
array_candidates = [i for sl in array_candidates for i in sl] + contract.state_variables
array_candidates = [
x.type.length for x in array_candidates if isinstance(x.type, ArrayType) and x.type.length
]
array_candidates = [ExportValues(x).result() for x in array_candidates]
array_candidates = [i for sl in array_candidates for i in sl]
array_candidates = [v for v in array_candidates if isinstance(v, StateVariable)]
# Flat list
variables_used = [item for sublist in variables_used for item in sublist]
variables_used = list(set(variables_used + array_candidates))
# Return the variables unused that are not public
return [x for x in contract.variables if x not in variables_used and x.visibility != "public"]
class UnusedStateVars(AbstractDetector):
"""
Unused state variables detector
"""
ARGUMENT = "unused-state"
HELP = "Unused state variables"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#unused-state-variable"
WIKI_TITLE = "Unused state variable"
WIKI_DESCRIPTION = "Unused state variable."
WIKI_EXPLOIT_SCENARIO = ""
WIKI_RECOMMENDATION = "Remove unused state variables."
def _detect(self):
"""Detect unused state variables"""
results = []
for c in self.compilation_unit.contracts_derived:
unusedVars = detect_unused(c)
if unusedVars:
for var in unusedVars:
info = [var, " is never used in ", c, "\n"]
json = self.generate_result(info)
results.append(json)
return results
@staticmethod
def _format(compilation_unit: SlitherCompilationUnit, result):
custom_format(compilation_unit, result)
| 2,812 | Python | .py | 58 | 42.137931 | 98 | 0.722628 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,227 | tcheck_parser.py | NioTheFirst_ScType/slither/detectors/my_detectors/tcheck_parser.py | #USAGE: parses the type file for:
# - [*c], contract_name :contracts to run
# - [xf], function_name :functions to ignore
# - [sef], contract_name, function_name, [num_types], [denom_types], expected_normalization :external function summary
# - [tref], array/map_name :expected type for one instance to be tested for the array/mapping
# - [t], function_name, variable_name, [num_types], [denom_types], normalization :type information for a specific variable (usually parameters)
#
#
#FUNCTION SUMMARY:
# -parse_type_file(file_name) :given a type file, check for existence and parses
# -
# -get_var_type_tuple(function_name, var_name) :check for existence and returns type tuple for a variable
# -get_func_type_tuple(contract_name, function_name, [parameters]) :check for existence and returns type tuple for an external function call
# -get_ref_type_tuple(ref_name) :check for existence and returns type tuple for a reference (arrays or maps)
import address_handler
from address_handler import address_to_label, label_sets
from slither.sctype_cf_pairs import get_cf_pairh, view_all_cf_pairs
#address_to_label = {}
#label_sets = {}
allowed_contracts = {}
barred_functions = {}
var_type_hash = {} #Exclusively for types/normalizations
var_fin_hash = {} #Exclusively for finance types
in_func_ptr_hash = {}
ex_func_type_hash = {}
ref_type_hash = {}
address_type_hash = {}
tuple_type_hash = {}
field_type_hash = {}
spex_func_type_hash = {}
MAX_PARAMETERS = 5
contract_name_aliases = {}
read_files = {}
reuse_types = True
reuse_types_var = {}
reuse_addr = True
reuse_addr_types = {}
reuse_fin = True
reuse_fin_types = {}
total_annotations = 0
field_tuple_start = 5
update_start = 100
#Update ratios should be reset every single contract
update_ratios = {10: -1,
12: -1,
20: -1,
21: -1}
f_type_num = {
-1: "undef",
0: "raw balance",
1: "net balance",
2: "accrued balance",
3: "final balance",
10: "compound fee ratio (t)",
11: "transaction fee",
12: "simple fee ratio",
13: "transaction fee (n)",
14: "transaction fee (d)",
20: "simple interest ratio",
21: "compound interest ratio",
22: "simple interest",
23: "compound interest",
30: "reserve",
40: "price/exchange rate",
50: "debt",
60: "dividend"
}
f_type_name = {
"undef" : -1,
"raw balance" :0,
"net balance" :1,
"accrued balance" :2,
"final balance" :3,
"compound fee ratio (t)" : 10,
"transaction fee" :11,
"simple fee ratio" : 12,
"transaction fee (n)" : 13,
"transaction fee (d)" : 14,
"simple interest ratio" : 20,
"compound interest ratio" : 21,
"simple interest": 22,
"compound interest" : 23,
"reserve" : 30,
"price/exchange rate" : 40,
"debt": 50,
"dividend": 60
}
def get_total_annotations():
global total_annotations
return(total_annotations)
def gen_finance_instances(line):
_line = line.split(",")
finance_instances = []
for param in _line:
#print(f"Param: {param}")
offset = 0
foundf = False
for i in range(len(param)):
if(param[i] == 'f' and i+1 < len(param) and param[i+1] == ':'):
foundf = True
offset=i+2
break
if(foundf == False):
continue
isolated_param = param[offset:].replace("}", "").strip()
#print(f"Isolated Param: {isolated_param}")
f_res = None
try:
temp = int(isolated_param)
f_res = temp
except ValueError:
if isolated_param in f_type_name:
f_res = f_type_name[isolated_param]
else:
f_res = -1
#if not isinstance(f_res, int):
#print("[x] FINANCE TYPE IS NOT INT")
finance_instances.append(f_res)
#print(f"F num: {f_res}")
return finance_instances
def parse_finance_file(f_file):
global read_files
global total_annotations
global reuse_fin
global reuse_fin_types
#Same structure as token_type parser
if(f_file == None):
return
with open(f_file, 'r') as finance_file:
#print("Reading f file...")
for line in finance_file:
_line = split_line(line)
#Look for "f: "
f_params = gen_finance_instances(line)
#print(_line)
if(len(f_params) == 0):
#No finance parameters, assume all parameters are NULL Type
for i in range(MAX_PARAMETERS):
f_params.append(-1)
#Regular variables
if(_line[0].strip() == "[t]"):
if(not(f_file) in read_files):
#print(_line)
total_annotations+=1
f_name = _line[1].strip()
v_name = _line[2].strip()
if(reuse_fin and not(v_name in reuse_fin_types)):
reuse_fin_types[v_name] = f_params[0]
norm_tt = get_var_type_tuple(f_name, v_name)
if(norm_tt == None):
#Create new "variable" to be propogated by tcheck.querry_type()
add_var(f_name, v_name, (-1, -1, 'u', None, 'u', f_params[0]))
else:
norm_tt+=(f_params[0], )
add_var(f_name, v_name, norm_tt)
elif(_line[0].strip() == "[ta]"):
#addresses
if(not(f_file) in read_files):
total_annotations+=1
#print(_line)
f_name = _line[1].strip()
v_name = _line[2].strip()
if(reuse_fin and not(v_name in reuse_fin_types)):
reuse_fin_types[v_name] = f_params[0]
addr_key = f_name + ":" + v_name
addr = None
if(addr_key in label_sets):
addr = label_sets[addr_key]
addr.finance_type = f_params[0]
else:
if(f_name == "global"):
addr = address_handler.type_file_new_address(addr_key, True)
else:
addr = address_handler.type_file_new_address(addr_key, False)
addr.finance_type = f_params[0]
#print(addr)
elif(_line[0].strip() == "[sefa]"):
c_name = _line[1].strip()
f_name = _line[2].strip()
ef_tts = get_dir_ex_func_type_tuple(c_name, f_name)
if(ef_tts == None):
raise Exception("SEF object not initialized")
cur = 0
new_tts = []
for tt in ef_tts:
tt+=(f_params[cur], )
new_tts.append(tt)
cur+=1
add_ex_func(c_name, f_name, new_tts)
#May be deprecated?
elif(_line[0].strip() == "[tref]"):
if(not(f_file) in read_files):
total_annotations+=1
ref_name = _line[1].strip()
ref_tt = get_ref_type_tuple(ref_name)
ref_tt += (f_params[0], )
add_ref(ref_name, ref_tt)
elif(_line[0].strip() == "[t*]"):
if(not(f_file) in read_files):
total_annotations+=1
#print(_line)
f_name = _line[1].strip()
p_name = _line[2].strip()
v_name = _line[3].strip()
field_tt = get_field(f_name, p_name, v_name)
if(reuse_fin and not(v_name in reuse_fin_types)):
reuse_fin_types[v_name] = f_params[0]
if(field_tt == None):
add_field(f_name, p_name, v_name, (-1, -1, 'u', 'u', 'u'))
field_tt = get_field(f_name, p_name, v_name)
field_tt += (f_params[0], )
add_field(f_name, p_name, v_name, field_tt)
read_files[f_file] = True
def parse_type_file(t_file, f_file = None):
global label_sets
global reuse_addr
global read_files
global reuse_addr_types
global total_annotations
with open (t_file, 'r') as type_file:
lines = []
counter = 0
temp_counter = 0
for line in type_file:
_line = split_line(line)
#NORMAL INPUT
#_line[0] = [t]
#_line[1] = container
#_line[2] = var name
#_line[3] = numerator type (assume one)
#_line[4] = denominator type (assume one)
#_line[5] = normalization amt (power of 10)
#_line[6] = (Optional) linked function if is address
#print(line)
if(_line[0].strip() == "[alias]"):
#Alias for contract names
if(not(t_file in read_files)):
total_annotations+=1
used_name = _line[1].strip()
actual_name = _line[2].strip()
add_alias(used_name, actual_name)
if(_line[0].strip() == "[t]"):
if(not(t_file in read_files)):
total_annotations+=1
#print(_line)
f_name = _line[1].strip()
v_name = _line[2].strip()
#TODO: Check for previous mentions of v_name
if(reuse_types):
if(v_name in reuse_types_var):
add_var(f_name, v_name, get_var_type_tuple(f_name, v_name))
try:
num = -1
den = -1
norm = 'u'
addr = 'u'
value = 'u'
if(len(_line) >= 6):
#Integers (and potentially f-types)
num = _line[3].strip()
den = _line[4].strip()
norm = int(_line[5].strip())
if(len(_line) >= 7):
try:
value = int(_line[6].strip())
except ValueError:
value = 'u'
elif(len(_line) >= 4):
#Addresses
addr = _line[3].strip()
add_var(f_name, v_name, (num, den, norm, value, addr))
if(reuse_types):
reuse_types_var[v_name] = True
except ValueError:
print("Invalid Value read")
continue
#BAR FUNCTION
#_line[0] = [xf]
#_line[1] = function name
if(_line[0].strip() == "[xf]"):
f_name = _line[1].strip()
bar_function(f_name)
continue
#ALLOW CONTRACT
#_line[0] = [*c]
#_line[1] = contract name
if(_line[0].strip() == "[*c]"):
c_name = _line[1].strip()
allow_contract(c_name)
continue
#SUMMARY OF EXTERNAL FUNCTION (ADDRESS VERSION)
#assuming global address
#[sefa], contract_name, function_name
#[sefa], contract_name, function_name, N, ({copy/transfer, isAddress, isField, ...}, ...)
# ({copy/transfer, <Num, ...>, <Den, ...>, Norm, Value})
# ({copy/transfer, T, F, Address})
# ({}) -> assume basic integer null value
if(_line[0].strip() == "[sefa]"):
c_name = _line[1].strip()
f_name = _line[2].strip()
ef_types = []
if(len(_line) <= 3):
add_ex_func(c_name, f_name, ef_types)
continue
ret_val = int(_line[3].strip())
for i in range(ret_val):
ret_type_tuple = _line[4+i]
ret_info = extract_type_tuple(ret_type_tuple)
num = [-1]
denom = [-1]
norm = 'u'
copy = "c"
value = 'u'
addr = 'u'
if(len(ret_info) >= 5):
copy = ret_info[0]
num = extract_address(ret_info[1])
denom = extract_address(ret_info[2])
norm = ret_info[3].strip()
try:
norm = int(norm)
except ValueError:
norm = norm
value = ret_info[4].strip()
try:
value = int(value)
except ValueError:
value = value
elif(len(ret_info) >= 2):
copy = ret_info[0]
addr = ret_info[1].strip() #No longer lf, link_function deprecated. Stores address instead
decimals = None
if(copy == "c"):
#Store the addr as the name_key
_addr = address_handler.type_file_new_address(addr, True)
if(len(ret_info) >= 3):
decimals = int(ret_info[2])
addr = _addr.head
if(decimals != None):
_addr.norm = decimals
norm = decimals
ef_types.append((copy, num, denom, norm, value, addr))
add_ex_func(c_name, f_name, ef_types)
#SPECIAL FUNCTION
if(_line[0].strip() == "[spexf]"):
#Derive information about the parameters
c_name = _line[1].strip()
f_name = _line[2].strip()
param_types = []
#Do not include unless there are parameters in question that are important
num_params = int(_line[3].strip())
for param in range (num_params):
param_tuple = _line[4+param].strip()
tuple_info = extract_type_tuple(param_tuple)
num = [-1]
denom = [-1]
norm = 'u'
copy = "c"
value = 'u'
addr = 'u'
if(len(tuple_info) >= 5):
copy = tuple_info[0]
#num and den are either: concrete addresses (i.e. USDC) or relative parameters (i.e. 1, 2)
num = extract_address(tuple_info[1])
denom = extract_address(tuple_info[2])
#norm is either int, 'u', or 'c'
norm = tuple_info[3].strip()
try:
norm = int(norm)
except ValueError:
norm = norm
#value is just value
value = tuple_info[4].strip()
try:
value = int(value)
except ValueError:
value = value
elif(len(tuple_info) >= 2):
#I don't know if this will get used, hopefully not
copy = tuple_info[0]
addr = tuple_info[1].strip() #No longer lf, link_function deprecated. Stores address instead
decimals = None
if(copy == "c"):
#Store the addr as the name_key
_addr = address_handler.type_file_new_address(addr, True)
if(len(tuple_info) >= 3):
decimals = int(tuple_info[2])
addr = _addr.head
if(decimals != None):
_addr.norm = decimals
param_types.append((copy, num, denom, norm, value, addr))
#SUMMARY OF EXTERNAL FUNCTION
if(_line[0].strip() == "[sef]"):
c_name = _line[1].strip()
f_name = _line[2].strip()
ef_types = []
if(len(_line) <= 3):
add_ex_func(c_name, f_name, ef_types)
continue
ret_val = int(_line[3].strip())
for i in range(ret_val):
ret_type_tuple = _line[4+i]
ret_info = extract_type_tuple(ret_type_tuple)
num = [-1]
denom = [-1]
norm = 'u'
copy = "c"
addr = None
#print(_line[4+i])
#print(ret_info)
if(len(ret_info) >= 4):
copy = ret_info[0]
num = extract_integers(ret_info[1])
denom = extract_integers(ret_info[2])
norm = int(ret_info[3].strip())
if(len(ret_info) >= 5):
addr = ret_info[4] #No longer lf, link_function deprecated. Stores address instead
ef_types.append((copy, num, denom, norm, addr))
add_ex_func(c_name, f_name, ef_types)
#REFERENCE TYPE
if(_line[0].strip() == "[tref]"):
if(not(t_file in read_files)):
#print(_line)
total_annotations+=1
ref_name = _line[1].strip()
num = [-1]
denom = [-1]
norm = ['u']
lf = None
addr = 'u'
value = 'u'
if(len(_line) > 2):
num =extract_address(_line[2].strip())
denom = extract_address(_line[3].strip())
norm = int(_line[4].strip())
if(len(_line) >= 6):
addr = _line[5]
if(len(_line) >= 7):
value = _line[6]
try:
value = int(value)
except ValueError:
value = value
add_ref(ref_name, (num, denom, norm , value, addr))
#ADDRESS TYPE
#func/global, name, norm
#i.e. global, USDC, 6 (positive address)
#i.e. transfer, token, * (negative address)
if(_line[0].strip() == "[ta]"):
if(not(t_file in read_files)):
#print(_line)
total_annotations+=1
func_name = _line[1].strip()
var_name = _line[2].strip()
#Allow third parameter to be global variable if known?
#Automatic propogation...
_norm = _line[3].strip()
addr_key = func_name + ":" + var_name
if(not(addr_key in label_sets)):
if(func_name == "global"):
addr = address_handler.type_file_new_address(addr_key, True)
else:
addr = address_handler.type_file_new_address(addr_key, False)
if(_norm != '*'):
norm = int(_line[3].strip())
else:
norm = _norm
add_addr(func_name, var_name, norm)
if(reuse_addr):
reuse_addr_types[var_name] = norm
#FIELD TYPE
if(_line[0].strip() == "[t*]"):
if(not(t_file in read_files)):
#print(_line)
total_annotations+=1
func_name = _line[1].strip()
parent_name = _line[2].strip()
field_name = _line[3].strip()
num = [-1]
denom = [-1]
norm = ['u']
value = 'u'
addr = 'u'
if(len(_line) >= 8):
num = [_line[4].strip()]
denom = [_line[5].strip()]
norm = [int(_line[6].strip())]
value = _line[7].strip()
try:
value = int(value)
except ValueError:
value = value
elif(len(_line) >= 5):
norm = int(_line[5].strip())
if(isinstance(addr, int)):
addr = _line[4]
else:
if("global" in _line[4]):
addr = address_handler.type_file_new_address(_line[4], True)
addr.norm = norm
else:
addr = address_handler.type_file_new_address(_line[4], False)
addr.norm = norm
addr = addr.head
add_field(func_name, parent_name, field_name, (num, denom, norm, value, addr))
read_files[t_file] = True
parse_finance_file(f_file)
def add_var(function_name, var_name, type_tuple):
key = function_name + '_' + var_name
#(f"Adding {key}: {type_tuple}")
var_type_hash[key] = type_tuple
def get_var_type_tuple(function_name, var_name):
global reuse_fin
global reuse_fin_types
key = function_name + "_" + var_name
if(key in var_type_hash):
#cast num and den
temp = list(var_type_hash[key])
#print(f"List: {temp}")
temp[0] = stringToType(temp[0])
temp[1] = stringToType(temp[1])
#cast addr
if(temp[4] != 'u'):
temp[4] = stringToType(temp[4])
if(len(temp) < 6 and reuse_fin and var_name in reuse_fin_types):
temp.append(reuse_fin_types[var_name])
return tuple(temp)
return None
def add_alias(used_name, actual_name):
contract_name_aliases[used_name] = actual_name
def get_alias(used_name):
if(used_name in contract_name_aliases):
return contract_name_aliases[used_name]
else:
return None
def add_addr(function_name, var_name, norm):
key = function_name + "_" + var_name
#print(f"Addr:{key} : {norm}")
address_type_hash[key] = norm
def get_addr(function_name, var_name, chk_exists = False):
global reuse_addr
global reuse_addr_types
key = function_name + "_" + var_name
if(key in address_type_hash):
return address_type_hash[key]
else:
if(chk_exists):
return None
if(reuse_addr and var_name in reuse_addr_types):
add_addr(function_name, var_name, reuse_addr_types[var_name])
else:
#Add null address (automatic)
add_addr(function_name, var_name, 0)
return address_type_hash[key]
#Deprecated
return None
def add_tuple(tuple_name, type_tuples):
key = tuple_name
tuple_type_hash[key] = type_tuples
def stringToType(string):
global address_to_label
type = -1
if(string == None):
return None
try:
type = int(string)
except ValueError:
#search address
_string = str(string)
gstring = "global:"+str(string)
#(address_to_label)
if gstring in address_to_label:
type = address_to_label[gstring]
elif _string in address_to_label:
type = address_to_label[_string]
else:
#Create new address
type = address_handler.type_file_new_address(gstring, True).head
return type
def get_tuple(tuple_name):
key = tuple_name
if key in tuple_type_hash:
return tuple_type_hash[key]
return None
def add_field(function_name, parent_name, field_name, type_tuples):
key = function_name+'_'+parent_name+'_'+field_name
#print(f"IN KEY: {key}")
field_type_hash[key] = type_tuples
def get_field(function_name, full_parent_name, field_name):
key = function_name + '_' + full_parent_name + '_' + field_name
#print(f"OUT KEY: {key}")
if key in field_type_hash:
temp = list(field_type_hash[key])
#print(f"List: {temp}")
if(isinstance(temp[0], list)):
temp[0][0] = stringToType(temp[0][0])
else:
temp[0] = stringToType(temp[0])
if(isinstance(temp[1], list)):
temp[1][0] = stringToType(temp[1][0])
else:
temp[1] = stringToType(temp[1])
return tuple(temp)
return None
def add_ex_func(contract_name, function_name, type_tuple):
key = contract_name + '_' + function_name
ex_func_type_hash[key] = type_tuple
def get_dir_ex_func_type_tuple(contract_name, function_name):
key = contract_name + '_' + function_name
if(key in ex_func_type_hash):
return(ex_func_type_hash[key])
return None
#Extended Function Tuple Unpacking etc in the Address version
def get_ex_func_type_tuple_a(contract_name, function_name, parameters):
key = contract_name + '_' + function_name
if(key in ex_func_type_hash):
func_tuple = ex_func_type_hash[key]
ret_type_tuples = []
pos = -1
for ret_var in func_tuple:
#print(f"Retvar: {ret_var}")
pos+=1
copy = ret_var[0]
num_trans = ret_var[1]
den_trans = ret_var[2]
norm = ret_var[3]
value = ret_var[4]
addr = ret_var[5]
ftype = -1
if(len(ret_var) >= 7):
ftype = ret_var[6]
ret_num = []
ret_den = []
param = parameters
#for p in parameters:
#print(p.name)
propogate_ftype = False
if(ftype == 1000):
propogate_ftype = True
ftype = -1
if(len(param) == 0 or copy == "c"):
#No parameters, assume that the parameters are directly the types
_num_trans = []
_den_trans = []
for _addr in num_trans:
#May translate from global addresses
_addr = stringToType(_addr)
_num_trans.append(_addr)
for _addr in den_trans:
#May translate from global addresses
_addr = stringToType(_addr)
_den_trans.append(_addr)
ret_type_tuple = (_num_trans, _den_trans, norm , value, addr, ftype)
ret_type_tuples.append(ret_type_tuple)
continue
for num in num_trans:
#Guarantee to be integers, as it represents the index parameter
num = num #int(num.strip())
if(isinstance(num, str)):
num = int(num.strip())
if(num == -1):
ret_num.append(-1)
continue
cur_param = param[num-1].extok
for n in cur_param.num_token_types:
ret_num.append(n)
for d in cur_param.den_token_types:
ret_den.append(d)
if(cur_param.address != 'u'):
ret_num.append(cur_param.address)
if(propogate_ftype):
ftype = tcheck_propagation.pass_ftype_no_ir(ftype, cur_param.finance_type, "mul")
for den in den_trans:
den = den #int(den.strip())
if(isinstance(den, str)):
den = int(den.strip())
if(den == -1):
ret_den.append(-1)
continue
cur_param = param[den-1].extok
for n in cur_param.num_token_types:
ret_den.append(n)
for d in cur_param.den_token_types:
ret_num.append(d)
if(cur_param.address != 'u'):
ret_den.append(cur_param.address)
if(propogate_ftype):
ftype = tcheck_propagation.pass_ftype_no_ir(ftype, cur_param.finance_type, "div")
if(isinstance(norm, int) and norm > 0):
norm = param[norm-1].extok.norm
#print(f"hers norm: {norm}")
if(isinstance(addr, int) and lc > 0):
addr = param[lc-1].extok.address
ret_type_tuple = (ret_num, ret_den, norm, value, addr, ftype)
ret_type_tuples.append(ret_type_tuple)
return ret_type_tuples
return None
def get_ex_func_type_tuple(contract_name, function_name, parameters):
key = contract_name + '_' + function_name
if(key in ex_func_type_hash):
func_tuple = ex_func_type_hash[key]
ret_type_tuples = []
pos = -1
for ret_var in func_tuple:
#print(ret_var)
pos+=1
copy = ret_var[0]
num_trans = ret_var[1]
den_trans = ret_var[2]
norm = ret_var[3]
lc = ret_var[4]
ftype = -1
if(len(ret_var) >= 6):
ftype = ret_var[5]
ret_num = []
ret_den = []
param = parameters
#for p in parameters:
# print(p.name)
if(len(param) == 0 or copy == "c"):
#No parameters, assume that the parameters are directly the types
ret_type_tuple = (num_trans, den_trans, norm , lc, ftype)
ret_type_tuples.append(ret_type_tuple)
continue
for num in num_trans:
if(num == -1):
ret_num.append(-1)
continue
cur_param = param[num-1].extok
for n in cur_param.num_token_types:
ret_num.append(n)
for d in cur_param.den_token_types:
ret_den.append(d)
for den in den_trans:
if(den == -1):
ret_den.append(-1)
continue
cur_param = param[den-1].extok
for n in cur_param.num_token_types:
ret_den.append(n)
for d in cur_param.den_token_types:
ret_num.append(d)
if(isinstance(norm, int) and norm > 0):
norm = param[norm-1].extok.norm
if(isinstance(lc, int) and lc > 0):
lc = param[lc-1].extok.linked_contract
ret_type_tuple = (ret_num, ret_den, norm, lc, ftype)
ret_type_tuples.append(ret_type_tuple)
return ret_type_tuples
return None
def add_ref(ref_name, type_tuple):
key = ref_name
ref_type_hash[key] = type_tuple
def get_ref_type_tuple(ref_name):
key = ref_name
if(key in ref_type_hash):
temp = list(ref_type_hash[key])
#print(temp)
for n in range(len(temp[0])):
#print(temp[0][n])
temp[0][n] = stringToType(temp[0][n])
#temp[0] = stringToType(temp[0])
for d in range(len(temp[1])):
temp[1][n] = stringToType(temp[1][d])
#temp[1] = stringToType(temp[1])
temp[4] = stringToType(temp[4])
return tuple(temp)
return None
def add_in_func(contract_name, function_name, in_func):
#deprecated
return
key = contract_name + '_' + function_name
if(key in in_func_ptr_hash):
#Do not modify thing already in hash.
return
in_func_ptr_hash[key] = in_func
def get_in_func_ptr(contract_name, function_name):
key = contract_name + '_' + function_name
#view_all_cf_pairs()
return get_cf_pairh(contract_name, function_name)
return None
#deprecated
if(key in in_func_ptr_hash):
funcptr = in_func_ptr_hash[key]
if(funcptr.entry_point == None):
return None
return in_func_ptr_hash[key]
return None
def allow_contract(contract_name):
allowed_contracts[contract_name] = True
def check_contract(contract_name):
if(contract_name in allowed_contracts):
return True
return False
def bar_function(function_name):
barred_functions[function_name] = True
def check_function(function_name):
if(function_name in barred_functions):
return True
return False
def reset_update_ratios():
#redo update ratios: seems like there may be some issues
global update_ratios
update_ratios = {10: -1,
12: -1,
20: -1,
21: -1}
def split_line(line):
result = []
buffer = ''
count_brackets = 0
count_parenthesis = 0
for char in line:
if char == '[':
count_brackets += 1
elif char == ']':
count_brackets -= 1
if char == '{':
count_parenthesis += 1
elif char == '}':
count_parenthesis -=1
if char == ',' and count_brackets == 0 and count_parenthesis == 0:
result.append(buffer.strip())
buffer = ''
else:
buffer += char
result.append(buffer.strip())
return result
def extract_type_tuple(input_str):
# Remove the parenthesis
input_str = input_str.strip("{}")
info_list = [str(x) for x in split_line(input_str)]
return info_list
def extract_integers(input_str):
# Remove the brackets
input_str = input_str.strip("[]")
# Split the string by commas and convert to integers
integer_list = [int(x) for x in input_str.split(",")]
return integer_list
def extract_address(input_str):
# Remove the brackets
input_str = input_str.strip("[]")
# Split the string by commas and convert to integers
list = [x for x in input_str.split(",")]
return list
| 34,168 | Python | .py | 845 | 26.680473 | 149 | 0.480004 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,228 | ExtendedType.py | NioTheFirst_ScType/slither/detectors/my_detectors/ExtendedType.py | from collections import defaultdict
import os
import sys
script_dir = os.path.dirname( __file__ )
sys.path.append(script_dir)
#USAGE: file containing the structure representing an Extended type instance
# Extended types have two main subclasses: token types and business types
# Token types follow the default token structure of:
# - numerator type(s)
# - denominator type(s)
# - normalization amt
# - linked contract (for addresses)
# - fields (for objects)
# Business types (usually one) are categorical, i.e. (fee, balance, ...) and their relations will be defined here
from tcheck_parser import f_type_name, f_type_num, update_start
class ExtendedType():
def __init__(self):
#Initialized an 'undefined' data type
self._name: Optional[str] = None
self._function_name: Optional[str] = None
#TODO add the function ir
self._contract_name: Optional[str] = None
#Token type
self._num_token_types = []
self._den_token_types = []
self._base_decimals = 0
self._address = 'u'
self._norm = 'u'
self._value = 'u'
#All references have an assumed type: once they are set on the lhs, they are locked.
self._reference_locked = False
#TODO address lf should automatically be set to its name
self._linked_contract = None
self._fields = []
self._reference_root = None
self._reference_field = None
self._trace = None
#Business type
self._finance_type = -1
self._updated = False
#Getters and setters for the fields
@property
def name(self):
return(self._name)
@name.setter
def name(self, sname):
self._name = sname
@property
def ref_root(self):
return(self._reference_root)
@property
def ref_field(self):
return(self._reference_field)
def ref(self, ref):
self._reference_root = ref[0]
self._reference_field = ref[1]
@property
def address(self):
return(self._address)
@address.setter
def address(self, x):
self._address = x
@property
def function_name(self):
return(self._function_name)
@function_name.setter
def function_name(self, fname):
self._function_name = fname
@property
def value(self):
return(self._value)
@value.setter
def value(self, value):
if(value == None):
value = 'u'
self._value = value
@property
def contract_name(self):
return(self._contract_name)
@contract_name.setter
def contract_name(self, cname):
self._contract_name = cname
#DEPRECATED
def resolve_trace(self, trace_labels):
for n in self._num_token_types:
if n in trace_labels:
n = trace_lables[n]
for d in self._den_token_types:
if d in trace_labels:
d = trace_labels[d]
def resolve_labels(self, label_sets):
for n in self._num_token_types:
if n in label_sets:
n = label_sets[n].head
for d in self._den_token_types:
if d in label_sets:
d = label_sets[d].head
@property
def num_token_types(self):
return(self._num_token_types)
def add_num_token_type(self, token_type):
if(token_type == -1):
if(len(self._num_token_types) != 0 or token_type in self._num_token_types):
return
self._num_token_types.append(token_type)
else:
if(token_type in self._den_token_types):
self._den_token_types.remove(token_type)
else:
if(-1 in self._num_token_types):
self._num_token_types.remove(-1)
self._num_token_types.append(token_type)
def clear_num(self):
self._num_token_types.clear()
@property
def den_token_types(self):
return(self._den_token_types)
def add_den_token_type(self, token_type):
if(token_type == -1):
if(len(self._den_token_types) != 0 or token_type in self._den_token_types):
return
self._den_token_types.append(token_type)
else:
if(token_type in self._num_token_types):
self._num_token_types.remove(token_type)
else:
if(-1 in self._den_token_types):
self._den_token_types.remove(-1)
self._den_token_types.append(token_type)
def clear_den(self):
self._den_token_types.clear()
@property
def norm(self):
return self._norm
@norm.setter
def norm(self, a):
#if(a == -404):
# a = '*'
if(isinstance(a, int) and a < 3):
return
self._norm = a
@property
def base_decimals(self):
return self._base_decimals
@base_decimals.setter
def base_decimals(self, a):
self._base_decimals = a
def total_decimals(self):
if(self._norm == "*"):
return "*"
else:
return(self._base_decimals + self._norm)
@property
def linked_contract(self):
return self._linked_contract
@linked_contract.setter
def linked_contract(self, a):
self._linked_contract = a
@property
def fields(self):
return self._fields
def add_field(self, new_field):
for field in self._fields:
if(field.name == new_field.name):
self._fields.remove(field)
break
self._fields.append(new_field)
def print_fields(self):
print(f"{self._name} Fields:")
for field in self._fields:
print(f"{field.name}")
print("^^^")
def is_undefined(self) -> bool:
if(len(self._num_token_types) == 0 and len(self._den_token_types) == 0 and self._address == 'u'):# and self.finance_type == -1):
return True
return False
def is_constant(self) -> bool:
if(len(self._num_token_types) == 1 and len(self._den_token_types) == 1 and self._num_token_types[0] == -1 and self._den_token_types[0] == -1):
return True
return False
def is_address(self) -> bool:
if(self._address != 'u' and self._address != None):
return True
return False
def token_type_clear(self):
self.clear_num()
self.clear_den()
self._address = 'u'
#self.norm = 'u'
self.link_function = None
#self._updated = False
def init_constant(self):
#if not(self.is_undefined()):
#print("[W] Initializing defined variable to constant")
self.token_type_clear()
self.add_num_token_type(-1)
self.add_den_token_type(-1)
self.norm = 'u';
self._updated = False
@property
def finance_type(self):
return self._finance_type
@property
def pure_type(self):
if(self._finance_type > update_start):
return self._finance_type - update_start
return self._finance_type
@finance_type.setter
def finance_type(self, f_type):
if(f_type > update_start):
self._updated = True
else:
self._updated = False
self._finance_type = f_type
@property
def updated(self):
return self._updated
@updated.setter
def updated(self, is_updated):
self._updated = is_updated
if(self._finance_type <= update_start and is_updated):
self._finance_type += update_start
def __str__(self):
num_token_types_str = ", ".join(str(elem) for elem in self._num_token_types)
den_token_types_str = ", ".join(str(elem) for elem in self._den_token_types)
fields_str = ", ".join(str(elem.name) for elem in self._fields)
if(self._updated == True):
finance_type = "updated " + f_type_num[self._finance_type - update_start]
elif self._finance_type in f_type_num:
finance_type = f_type_num[self._finance_type]
else:
finance_type = None
return (
f"\n"
f"Name: {self._name} Function: {self._function_name}\n"
f"Num: {num_token_types_str}\n"
f"Den: {den_token_types_str}\n"
f"Address: {self._address}\n"
f"Norm: {self._norm}\n"
f"LF: {self._linked_contract}\n"
f"Value: {self._value}\n"
f"Fields: {fields_str}\n"
f"Finance Type: {finance_type}"
)
| 8,708 | Python | .py | 244 | 26.778689 | 150 | 0.575009 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,229 | tcheck.py | NioTheFirst_ScType/slither/detectors/my_detectors/tcheck.py | from collections import defaultdict
from slither.core.variables.local_variable import LocalVariable
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.slithir.operations import Binary, Assignment, BinaryType, LibraryCall, Return, InternalCall, Condition, HighLevelCall, Unpack, Phi, EventCall, TypeConversion, Member, Index
from slither.slithir.variables import Constant, ReferenceVariable, TemporaryVariable, LocalIRVariable, StateIRVariable, TupleVariable
from slither.core.variables.variable import Variable
from slither.core.variables.state_variable import StateVariable
from slither.core.declarations.function import Function
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.function_type_variable import FunctionTypeVariable
from slither.core.declarations.solidity_variables import SolidityVariable
from slither.core.solidity_types import UserDefinedType, ArrayType
from slither.core.declarations import Structure, Contract
from slither.core.solidity_types.elementary_type import ElementaryType
from slither.core.declarations.modifier import Modifier
from slither import tcheck_module
from slither.sctype_cf_pairs import get_cont_with_state_var
import copy
import linecache
import os
import sys
import time
script_dir = os.path.dirname( __file__ )
sys.path.append(script_dir)
import tcheck_parser
from tcheck_parser import update_ratios
import tcheck_propagation
import address_handler
from address_handler import global_address_counter, temp_address_counter, num_to_norm, label_sets, label_to_address, address_to_label
seen_contracts = {}
user_type = False
fill_type = False
mark_iteration = False
current_function_marked = False
type_file = ""
write_typefile = True
maxTokens = 10
debug_pow_pc = None
tempVar = defaultdict(list) #list storing temp variables (refreshed every node call)
strgVar = defaultdict(list) #list storing storage variables (kept through all calls)
currNode = None
errors = []
nErrs = 0
line_no = 1
function_hlc = 0
function_ref = 0
function_count = 0
current_contract_name = "ERR"
type_hashtable = {}
function_bar = {}
function_check = {}
contract_run = {}
contract_function = {}
constant_instance = Variable()
constant_instance.name = "Personal Constant Instance"
constant_instance_counter = 1
#BINOP Labels
Add = 1
Sub = 2
Mul = 3
Div = 4
Pow = 5
Cmp = 6
traces = 0 #trace default is -2
trace_to_label = {}
global_var_types = {}
var_assignment_storage = {}
read_global = {}
debug_print = True
ask_user = False
read_library = False
#IMPORTANT: read internal
read_internal = False
#USAGE: resets update ratios
def reset_update_ratios():
tcheck_parser.reset_update_ratios()
#USAGE: create a
#USAGE: creates and returns a constant instnace
#RETURNS: a constant instance (default constant)
def create_iconstant():
global constant_instance_counter
new_instance = Variable()
new_instance.name = "PIC_" + str(constant_instance_counter)
constant_instance_counter+=1
assign_const(new_instance)
return new_instance
#USAGE: adds token pair to type_hashtable
#RETURNS: composite key of the token pair
def add_hash(function_name, var_name, num, den, norm, lf):
composite_key = function_name + '_' + var_name
values = (num, den, norm, lf)
type_hashtable[composite_key] = values
return composite_key
#USAGE: gets the alias of a contract name for included external functions
def get_alias(used_name):
return tcheck_parser.get_alias(used_name)
#USAGE: adds a contract, function pair
#RETURNS: NULL
def add_cf_pair(contract_name, function_name, function):
if(contract_name == None or function_name == None or function.entry_point == None):
return False
#print(f"Adding function pair: {contract_name}, {function_name}")
tcheck_parser.add_in_func(contract_name, function_name, function)
#USAGE: returns the ir for a contract, function pair
#RETURNS: the specified ir, if it doesn't exist, None is returned
def get_cf_pair(contract_name, function_name):
if(contract_name == None or function_name == None):
return None
return tcheck_parser.get_in_func_ptr(contract_name, function_name)
#USAGE: adds a tuple to the parser file
#RETURNS: NULL
def add_tuple(tuple_name, type_tuples):
if(tuple_name == None or type_tuples == None):
return None
tcheck_parser.add_tuple(tuple_name, type_tuples)
#USAGE: returns a specific element located at index of a tuple
#RETURNS: above
def get_tuple_index(tuple_name, index):
if(tuple_name == None):
return None
temp = tcheck_parser.get_tuple(tuple_name)
if(temp != None and len(temp) > index):
return temp[index]
return None
#USAGE: adds a referecne
#RETURNS: NULL
def add_ref(ref_name, type_tuple):
if(ref_name != None):
tcheck_parser.add_ref(ref_name, type_tuple)
#USAGE: gets the type of a reference
#RETURNS:
def get_ref(ref_name):
if(ref_name == None):
return None
return tcheck_parser.get_ref_type_tuple(ref_name)
#USAGE: views the current address labels
def print_addresses():
for label, address in address_to_label.items():
print(f"Address: {address}, Label: {label}")
for label, addr_label in label_sets.items():
print(addr_label)
#USAGE: given a function name and a var name, return the token pair
#RETURNS: tuple holding the token pair
def get_hash(function_name, var_name):
if(function_name == None or var_name == None):
return None
return tcheck_parser.get_var_type_tuple(function_name, var_name)
#USAGE: adds a field
#RETURNS: NULL
def add_field(function_name, parent_name, field_name, type_tuple):
if(function_name == None or parent_name == None or field_name == None):
return None
tcheck_parser.add_field(function_name, parent_name, field_name, type_tuple)
#USAGE: gets a field
#RETURNS: NULL
def get_field(function_name, parent_name, field_name):
if(function_name == None or parent_name == None or field_name == None):
return None
#Some names will be off due to ssa version/non-ssa version conflict
_parent_name = parent_name.rsplit('_', 1)[0]
temp = tcheck_parser.get_field(function_name, parent_name, field_name)
if(temp == None):
temp = tcheck_parser.get_field(function_name, _parent_name, field_name)
return temp
#USAGE: bar a function from being typechecked
#RETURNS: NULL
def bar_function(function_name):
tcheck_parser.bar_function(function_name)
#USAGE: new address
def new_address(ir, isGlobal = None):
#if (not(isinstance(ir, Variable))):
# return None
if(isGlobal or ir.extok.function_name == "global"):
return address_handler.new_address(ir, True)
else:
return address_handler.new_address(ir, False)
#USAGE: returns if a function should be typechecked
#RETURNS bool
def check_bar(function_name):
return tcheck_parser.check_function(function_name)
#USAGE: selects a contract to typecheck
#RETURNS: NULL
def run_contract(contract_name):
tcheck_parser.allow_contract(contract_name)
#USAGE: returns the type tuple for an external function that has been included
#RETURNS: external function type tuple
def get_external_type_tuple(contract_name, function_name, parameters):
if(contract_name == None or function_name == None):
return None
return tcheck_parser.get_ex_func_type_tuple_a(contract_name, function_name, parameters)
#USAGE: returns if a function should be typechecked
#RETURNS bool
def check_contract(contract_name):
if(tcheck_parser.check_contract(contract_name)):
return True
return False
def print_token_type(ir):
if(isinstance(ir, Variable)):
y = 8008135
#USAGE: passes the finance type
def pass_ftype(dest, left, func, right = None):
if(tcheck_propagation.pass_ftype(dest, left, func, right)):
add_errors(dest)
#USAGE: prints a param_cache
#RETURNS: nothing
def print_param_cache(param_cache):
return
param_no = 0
for param in param_cache:
print("Param: " + str(param_no))
print(f" num: {param[0]}")
print(f" den: {param[1]}")
print(f" norm: {param[2]}")
print(f" link: {param[3]}")
print(f" fields: {param[4]}")
print(f" fintype: {param[5]}")
param_no+=1
#USAGE: given an ir for a function call, generate a param_cache
#RETURNS: retursn a param_cache
def function_call_param_cache(params):
#assumes types have been assigned (any undefined types must be resolved previously)
return(gen_param_cache(params))
#USAGE: given a function, generate a param_cache
#RETURNS: returns a param_cache
def function_param_cache(function):
#assumes types have already been assigned
return(gen_param_cache(function.parameters))
#USAGE: propagates all the fields of an ir
def propagate_fields(ir):
tcheck_propagation.propagate_fields(ir)
#USAGE: given a hlc function, generate a param_cache
#RETURNS: returns a param_cache
def function_hlc_param_cache(function):
#assumes types have already been assigned
return(gen_param_cache(function.arguments))
#USAGE: given a list of parameters, return a param_cache (merge function_param_cache, function_call param_cache, and function_hlc_param_cache
#RETURNS: a para_cache
def gen_param_cache(param_list):
param_cache = []
for param in param_list:
if(not isinstance(param, Variable)):
_param = create_iconstant().extok
else:
_param = param.extok
num = _param.num_token_types
den = _param.den_token_types
norm = _param.norm
link_function = _param.linked_contract
fields = _param.fields
finance_type = _param.finance_type
address = _param.address
value = _param.value
param_type = [num, den, norm, link_function, fields, finance_type, address, value]
param_cache.append(param_type)
return param_cache
#USAGE: given a param_cache, decide whether or not to add it to the parameter_cache
# of a function
#RETURNS: bool (added or not)
def add_param_cache(function, new_param_cache):
global maxTokens
add_param = False
fpc = function.parameter_cache()
match_param = -100
if(len(fpc) == 0):
add_param = True
for a in range(len(fpc)):
cur_param_cache = fpc[a]
paramno = 0
dif_cur_param = False
for cur_param in cur_param_cache:
#compare cur_param with new_param_cache[paramno]
seen_n = {}
seen_d = {}
seen_norm = False
seen_ftype = False
seen_address = False
#compare numerators
for num in cur_param[0]:
if(num in seen_n):
seen_n[num]+=1
else:
seen_n[num] = 1
for num in new_param_cache[paramno][0]:
if(num in seen_n):
seen_n[num]-=1
else:
seen_n[num] = -1
#compare denominators
for num in cur_param[1]:
if(num in seen_d):
seen_d[num]+=1
else:
seen_d[num] = 1
for num in new_param_cache[paramno][1]:
if(num in seen_d):
seen_d[num]-=1
else:
seen_d[num] = -1
#compare norms
if(new_param_cache[paramno][2] != cur_param[2]):
seen_norm = True
#compre finance_type
if(new_param_cache[paramno][5] != cur_param[5]):
seen_ftype = True
#compare address
if(new_param_cache[paramno][6] != cur_param[6]):
seen_address = True
if(seen_ftype or seen_norm or seen_address):
dif_cur_param = True
break
for n in seen_n:
if(seen_n[n] != 0):
dif_cur_param = True
break
for d in seen_d:
if(seen_d[d] != 0):
dif_cur_param = True
break
if(dif_cur_param):
break
paramno+=1
if(dif_cur_param == False):
add_param = False
match_param = a
break
if(add_param):
function.add_parameter_cache(new_param_cache)
return match_param
#USAGE: parses an input file and fills the type_hashtable
#RETURNS: NULL
#parse formula:
#function_name
#var_name
#num
#den
def parse_type_file(t_file, f_file = None):
tcheck_parser.parse_type_file(t_file, f_file)
#USAGE: given a variable ir, return the type tuple
#RETURNS: type tuple
def read_type_file(ir):
_ir = ir.extok
function_name = ir.parent_function
var_name = _ir.name
if(ir.tname != None):
var_name = ir.tname
if(_ir.name == None):
return None
ref_tt = get_ref(var_name)
if(ref_tt):
return(ref_tt)
return tcheck_parser.get_var_type_tuple(function_name, var_name)
#USAGE: gets an address from the type file
def get_addr(ir, chk_exists = False):
_ir = ir.extok
function_name = ir.parent_function
var_name = _ir.name
if(_ir.name == None):
return None
return tcheck_parser.get_addr(function_name, var_name, chk_exists)
def append_typefile(ir, num = None, den = None, norm = None, lf = None):
global write_typefile
global type_file
if(not(write_typefile)):
return
_ir = ir.extok
function_name = ir.parent_function
var_name = _ir.name
newline = "[t], " + function_name + ", " + var_name
if(num == -1 and den == -1 and norm == 0 and lf == None):
#do nothing
y = XXX
else:
newline=newline + ", " + str(num) + ", " + str(den) + ", " + str(norm)
if(lf):
newline = newline + ", " + str(lf)
tfile = open(type_file, "a")
tfile.write(newline+"\n")
tfile.close()
#USAGE: generate a name for temporary addresses in the form: function:name
def generate_temporary_address_name(ir):
parent = ir.parent_function
name = ir.extok.name
new_name = str(parent)+":"+str(name)
return(new_name)
#USAGE: querry the user for a type
#RETURNS: N/A
def querry_type(ir):
global user_type
global type_file
global ask_user
global mark_iteration
global write_typefile
global current_function_marked
global global_address_counter
global temp_address_counter
global num_to_address
global address_to_num
_ir = ir.extok
uxname = _ir.name
if(ir.tname != None):
uxname = ir.tname
uxname = str(uxname)
#print(f"Finding type for {uxname}({ir.type} ... )")
if(str(ir.type) == "bool"):
assign_const(ir)
return
if(str(ir.type) == "bytes"):
return
if(str(ir.type).startswith("address") or "=> address" in str(ir.type) or get_addr(ir, True) != None):
#Address array and Mappings resulting in addressess.
norm = get_addr(ir)
if(norm == None):
input_str = input()
if(input_str != '*'):
norm = int(input_str)
label = new_address(ir)
label.norm = norm
ir.extok.norm = norm
return
#Get type tuple for regular variables
type_tuple = read_type_file(ir)
propagate_fields(ir)
if(type_tuple != None):
_ir.clear_num()
_ir.clear_den()
save_addr = _ir.address
copy_token_tuple(ir, type_tuple)
if(_ir.address == 'u'):
_ir.address = save_addr
#print("[*]Type fetched successfully")
return
#print("[x]Failed to fetch type from type file, defaulting to human interface")
assign_const(ir)
norm = get_norm(ir)
#Assign norm to constants
if(norm != 'u'):
ir.extok.norm = norm
return True
#Turned off for artifact, querries users for type
print("Define num type for \"" + uxname + "\": ")
input_str = input()
num = int(input_str)
_ir.add_num_token_type(num)
print("Define den type for \"" + uxname + "\": ")
input_str = input()
den = int(input_str)
_ir.add_den_token_type(den)
print("Define norm for \"" + uxname + "\": ")
input_str = input()
norm = int(input_str)
_ir.norm = norm
lf = None
if(str(ir.type) == "address"):
print("Define Linked Contract Name for \"" + uxname + "\": ")
lf = input()
ir.link_function = lf
append_typefile(ir, num, den, norm, lf)
def is_constant(ir):
if isinstance(ir, Constant):
return True
return False
def is_function(ir):
if isinstance(ir, Function):
temp = ir.parameters
def is_condition(ir):
if isinstance(ir, Condition):
y = 8008135
def is_function_type_variable(ir):
if isinstance(ir, FunctionTypeVariable):
y = 8008135
def is_type_undef(ir):
if not(is_variable(ir)):
return True
_ir = ir.extok
return _ir.is_undefined()
def is_type_address(ir):
if not(is_variable(ir)):
return False
_ir = ir.extok
return _ir.is_address()
def is_type_const(ir):
if not(is_variable(ir)):
return True
_ir = ir.extok
return _ir.is_constant()
#USAGE: assigns an IR to the constant type (-1)
# ex: 1, 5, 1001
#RETURNS: NULL
def assign_const(ir):
if(is_type_const(ir)):
return
_ir=ir.extok
_ir.init_constant()
ir.token_typen.clear()
ir.token_typed.clear()
ir.add_token_typen(-1)
_ir.value = 'u'
_ir.finance_type = -1
ir.add_token_typed(-1)
#USAGE: assigns an IR to the error type (-2) this stops infinite lioops
#RETURNS: NULL
def assign_err(ir):
assign_const(ir)
#USAGE: copies all the types from a type tuple to an ir node
#RETURNS: null
def copy_token_tuple(ir, tt):
tcheck_propagation.copy_token_tuple(ir, tt)
#USAGE: copies all token types from the 'src' ir node to the 'dest' ir node
#RETURNS: null
def copy_token_type(src, dest):
tcheck_propagation.copy_token_type(dest, src)
#USAGE: copies inverse token types from the 'src' ir node from the 'dest' ir node
#RETURNS: null
def copy_inv_token_type(src, dest):
tcheck_propagation.copy_inv_token_type(src, dest)
#USAGE: copy and replace a token from a param_cache to an ir
#RETURNS: nN/A
def copy_pc_token_type(src, dest):
tcheck_propagation.copy_pc_token_type(src, dest)
#USAGE: copies a finance type
def copy_ftype(src, dest):
tcheck_propagation.copy_ftype(src, dest)
def compare_token_type(src, dest):
return tcheck_propagation.compare_token_type(src, dest)
def add_errors(ir):
global nErrs
global errors
if ir in errors:
assign_err(ir)
return
errors.append(ir)
nErrs+=1
_ir = ir.extok
if(_ir.function_name == None):
_ir.function_name = "None"
print(f"Error with {_ir.name} in function {_ir.function_name}")
print("Error with: " + _ir.name + " in function " + _ir.function_name)
assign_err(ir)
#USAGE: Directly copies a normalization value (WARNING: SKIPS TYPECHECKING)
def copy_norm(src, dest):
return tcheck_propagation.copy_norm(src, dest)
#USAGE: Converts the first ssa instance of a variable (ends with _1)
#RETURNS: NULL
def convert_ssa(ir):
return
if(not(is_variable(ir))):
return
if(is_constant(ir) or ir.name.startswith("PIC") or isinstance(ir, Constant)):
return
non_ssa_ir = ir.non_ssa_version
if(not (is_type_undef(non_ssa_ir))):
ir.token_typen.clear()
ir.token_typed.clear()
_ir = ir.extok
_ir.token_type_clear()
copy_token_type(non_ssa_ir, ir)
copy_norm(non_ssa_ir, ir)
ir.norm = non_ssa_ir.norm
if(non_ssa_ir.extok.function_name):
_ir.function_name = non_ssa_ir.extok.function_name
ir.link_function = non_ssa_ir.link_function
_ir.finance_type = non_ssa_ir.extok.finance_type
_ir.updated = non_ssa_ir.extok.updated
_ir.address = non_ssa_ir.extok.address
#USAGE: updates a non_ssa instance of a variable
#RETURNS: NULL
def update_non_ssa(ir):
return
if(not(is_variable(ir))):
return
if(is_constant(ir)):
return
non_ssa_ir = ir.non_ssa_version
if(not (is_type_undef(ir))):
_non_ssa_ir = non_ssa_ir.extok
_non_ssa_ir.token_type_clear()
non_ssa_ir.token_typen.clear()
non_ssa_ir.token_typed.clear()
copy_token_type(ir, non_ssa_ir)
copy_norm(ir, non_ssa_ir)
non_ssa_ir.norm = ir.norm
non_ssa_ir.link_function = ir.link_function
non_ssa_ir.extok.finance_type = ir.extok.finance_type
non_ssa_ir.updated = ir.extok.updated
non_ssa_ir.address = ir.extok.address
else:
_non_ssa_ir = non_ssa_ir.extok
_non_ssa_ir.token_type_clear()
#USAGE: type checks an IR
#currently handles assignments and Binary
#returns ir if needs to be added back
def check_type(ir) -> bool:
global debug_pow_pc
global global_var_types
global current_contract_name
global var_assignment_storage
addback = False
#Print the IR (debugging statement)
#print(ir)
if isinstance(ir, Assignment):
addback = type_asn(ir.lvalue, ir.rvalue)
#Assign value if constant int assignement
if(is_constant(ir.rvalue)):
ir.lvalue.extok.value = ir.rvalue.value
elif(is_variable(ir.rvalue)):
ir.lvalue.extok.value = ir.rvalue.extok.value
rnorm = get_norm(ir.rvalue)
if(ir.lvalue.extok.norm != '*' and not (is_constant(ir.rvalue) and rnorm == 0)):
asn_norm(ir.lvalue, rnorm)
pass_ftype(ir.lvalue, ir.rvalue, "assign")
elif isinstance(ir, Binary):
#Binary
addback = type_bin(ir)
elif isinstance(ir, Modifier):
addback = False
elif isinstance(ir, InternalCall):
#Function call
addback = type_fc(ir)
elif isinstance(ir, LibraryCall):
addback = type_library_call(ir)
elif isinstance(ir, HighLevelCall):
#High level call
addback = type_hlc(ir)
elif isinstance(ir, TypeConversion):
type_conversion(ir)
elif isinstance(ir, Unpack):
#Unpack tuple
addback = type_upk(ir)
elif isinstance(ir, Phi):
#Phi (ssa) unpack
addback = False
if(is_type_undef(ir.lvalue)):
set = False
temp_rvalues = sorted(ir.rvalues, key=lambda x: str(x), reverse=False)
for rval in temp_rvalues:
if(not(is_type_undef(rval) or is_type_const(rval))):
type_asn(ir.lvalue, rval)
ir.lvalue.extok.norm = rval.extok.norm
if(rval.extok.finance_type != -1):
ir.lvalue.extok.finance_type = rval.extok.finance_type
else:
continue
_rval = rval.extok
for field in _rval.fields:
ir.lvalue.extok.add_field(field)
set = True
break
if(set == False):
for rval in temp_rvalues:
if(isinstance(rval.extok.norm, int)):
ir.lvalue.extok.norm = rval.extok.norm
if(rval.extok.finance_type != -1):
ir.lvalue.extok.finance_type = rval.extok.finance_type
else:
continue
_rval = rval.extok
for field in _rval.fields:
ir.lvalue.extok.add_field(field)
set = True
break
if(set == False):
for rval in temp_rvalues:
if(rval.extok.finance_type != -1):
ir.lvalue.extok.finance_type = rval.extok.finance_type
else:
continue
_rval = rval.extok
for field in _rval.fields:
ir.lvalue.extok.add_field(field)
elif isinstance(ir, EventCall):
return False
elif isinstance(ir, Index):
#print("INDEX")
addback = type_ref(ir)
elif isinstance(ir, Member):
#print("MEMBER")
addback = type_member(ir)
addback = False
elif isinstance(ir, Return):
#print("RETURN")
ir.function._returns_ssa.clear()
for y in ir.values:
if(init_var(y)):
ir.function.add_return_ssa(y)
else:
ir.function.add_return_ssa(create_iconstant())
return False
try:
if ir.lvalue and is_variable(ir.lvalue):
#Debugging statement: lhs variable after operatiom
#print("[i]Type for "+ir.lvalue.name)
#print(ir.lvalue.extok)
if(isinstance(ir.lvalue, ReferenceVariable)):
#Field propogation
ref = ir.lvalue
ref_root = ref.extok.ref_root
ref_field = ref.extok.ref_field
if(ref_root and ref_field):
update_member(ir.lvalue.points_to_origin, ref_field, ir.lvalue)
update_non_ssa(ir.lvalue)
except AttributeError:
#do nothing
y = XXX
return (addback)
#USAGE: typechecks a type conversions (USDC vs IERC20)
#While it has its own address (i.e. address usdc corresponds to global address x),
#The underlying contract will still be the ERC20 contract.
#This represents a limitation of the tool: the interface must be of the form I`Implementation` of i `Implementation`
#RETURNS: nothing
def type_conversion(ir):
global address_to_label
global label_to_address
if(str(ir.variable) == "this" or str(ir.variable) == "block.number" or str(ir.variable) == "msg.sender"):
assign_const(ir.lvalue)
name_key = "global:" + str(ir.variable)
if(name_key in address_to_label):
_addr = address_to_label[name_key]
else:
addr = new_address(ir.lvalue, True)
_addr = addr.head
label_to_address[addr] = name_key
address_to_label[name_key] = _addr
ir.lvalue.extok.address = _addr
ir.lvalue.norm = 0
ir.lvalue.link_function = current_contract_name
addback = False
else:
addback = type_asn(ir.lvalue, ir.variable)
ir.lvalue.extok.value = ir.variable.extok.value
if(ir.lvalue.extok.norm != get_norm(ir.variable)):
asn_norm(ir.lvalue, get_norm(ir.variable))
copy_ftype(ir.variable, ir.lvalue)
if(str(ir.variable.type) == "address"):
#This is a conversion
instance_name = str(ir.type)
contract_name = "UNKNOWN"
pos = 0
for char in instance_name:
if(pos+1 > len(instance_name) - 1):
contract_name = "UNKNOWN"
if(instance_name[pos] == 'i' or instance_name[pos] == 'I'):
contract_name = instance_name[pos+1:]
break
ir.lvalue.link_function = contract_name
#USAGE: typcehcks an unpack functionality (similar to assign)
#RETURNS: nothing (type is querried from user)
def type_upk(ir) ->bool:
#query the user for type info
lval = ir.lvalue
rtup = ir.tuple
rind = ir.index
if(lval.type == "bool"):
assign_const(lval)
return False
if(lval.type == "address"):
new_address(lval, False)
if(isinstance(lval, UserDefinedType)):
print("NOT HANDLED CURRENTLY!")
tup_token_type = get_tuple_index(str(rtup), rind)
if(tup_token_type):
copy_token_tuple(lval, tup_token_type)
else:
querry_type(lval)
return False
#USAGE: typechecks an included external call
#RETURNS: success of typecheck
def type_included_hlc(ir, dest, function, contract_name):
global mark_iteration
global current_function_marked
global current_contract_name
for param in ir.arguments:
init_var(param)
if(is_type_const(param)):
assign_const(param)
#elif(is_type_undef(param)):
#undefined type
# return 1
#generate param cache
new_param_cache = function_hlc_param_cache(ir)
added = -100
added = add_param_cache(function, new_param_cache)
if(added == -100):
save_contract_name = current_contract_name
current_contract_name = contract_name
addback = _tcheck_function_call(function, new_param_cache)
handle_return(ir.lvalue, function)
current_contract_name = save_contract_name
if(len(addback) != 0):
return 2
else:
ret_obj = function.get_parameter_cache_return(added)
if isinstance(ret_obj, Variable):
if(isinstance(ret_obj, list)):
type_asn(ir.lvalue, ret_obj[0])
copy_ftype(ret_obj[0], ir.lvalue)
else:
type_asn(ir.lvalue, ret_obj)
copy_ftype(ret_obj, ir.lvalue)
else:
add_tuple(ir.lvalue.name, ret_obj)
return 2
#USAGE: connects a high-level call with an internal call (cross contract
# function call where both contracts are defined)
#RETURNS: whether or not the function is detected (0)
# whether or not the function has any undef types (1)
# whether or not the function successfully passes (2)
def querry_fc(ir) -> int:
global mark_iteration
global current_function_marked
global address_to_label
if(not (isinstance(ir, HighLevelCall))):
if(handle_balance_functions(ir)):
return 2
return 0
dest = ir.destination
func_name = ir.function.name
cont_name = None
isVar = True
if(not (isinstance(dest, Variable))):
cont_name = str(dest)
isVar = False
if(str(ir.lvalue.type) == "bool"):
assign_const(ir.lvalue)
return 2
if(isVar):
#Contingency for undefined contract instances
cont_name = str(dest.type)
written_func_rets = get_external_type_tuple(cont_name, func_name, ir.arguments)
old_cont_name = cont_name
if(written_func_rets == None):
cont_name = cont_name[1:]
written_func_rets = get_external_type_tuple(cont_name, func_name, ir.arguments)
if(written_func_rets != None):
if(len(written_func_rets) == 0):
assign_const(ir.lvalue)
elif(len(written_func_rets) == 1):
written_func_ret = written_func_rets[0]
copy_token_tuple(ir.lvalue, written_func_ret)
elif(isinstance(ir.lvalue, TupleVariable) and len(written_func_rets) > 1):
add_tuple(ir.lvalue.name, written_func_rets)
else:
y = False
return 2
#Use original contract name instead of reduced name for interfaces etc.
#Special functions:
if(handle_balance_functions(ir)):
return 2
included_func = get_cf_pair(old_cont_name, func_name)
#print(f"Searching for cfpair: {old_cont_name}, {func_name}")
final_name = old_cont_name
if(included_func == None):
included_func = get_cf_pair(cont_name, func_name)
final_name = cont_name
if(included_func == None):
aliased_cont_name = get_alias(old_cont_name)
if(aliased_cont_name == None):
aliased_cont_name = get_alias(cont_name)
if(aliased_cont_name != None):
included_func = get_cf_pair(aliased_cont_name, func_name)
final_name = aliased_cont_name
if(included_func != None):
if(type_included_hlc(ir, dest, included_func, final_name) == 1):
return 2
return 2
'''
#Special functions:
if(handle_balance_functions(ir)):
return 2
'''
return 0
#USAGE: propogates types etc from a set of balance-related functions. Currently supports the functions with names in `balance_funcs`.
#RETURNS: if the balance-related function was executed
def handle_balance_functions(ir):
global address_to_num
global num_to_norm
#global trace_to_label
global traces
func_name = ir.function.name
dest = ir.destination
_dest = dest.extok
token_type = 'u'
norm = 'u'
fin_type = -1
isbfunc = False
if(_dest.address == 'u'):
_dest.address = new_address(dest, True).head
#Use this to check for changes!
ir.lvalue.extok.token_type_clear()
if(func_name == "balanceOf"):
token_type = _dest.address
if(token_type in label_sets):
if(label_sets[token_type].head > 0):
token_type = label_sets[token_type].head
norm = label_sets[token_type].norm
fin_type = label_sets[token_type].finance_type
#balanceOf, no important parameters, assign same type as dest address
ir.lvalue.extok.add_num_token_type(token_type)
ir.lvalue.extok.add_den_token_type(-1)
ir.lvalue.extok.norm = norm
#Financial type
if(fin_type == 30):
ir.lvalue.extok.finance_type = 30
elif(fin_type == 0):
ir.lvalue.extok.finance_type = 0
else:
ir.lvalue.extok.finance_type = 0
isbfunc = True
elif(func_name == "transferFrom" or func_name == "safeTransferFrom"):
token_type = _dest.address
if(token_type in label_sets):
if(label_sets[token_type].head > 0):
token_type = label_sets[token_type].head
norm = label_sets[token_type].norm
fin_type = label_sets[token_type].finance_type
numargs = ir.nbr_arguments
args = ir.arguments
probarg = None
if(numargs >= 3):
probarg = args[2]
if(probarg == None):
return False
#Test for safe
if(not(is_type_const(probarg) or is_type_undef(probarg))):
if(len(probarg.extok.den_token_types) != 0):
add_error(probarg)
return False
probarg.extok.add_num_token_type(token_type)
ir.lvalue.extok.add_den_token_type(-1)
ir.lvalue.extok.norm = norm
#Financial type
if(fin_type == 30):
ir.lvalue.extok.finance_type = 30
elif(fin_type == 0):
ir.lvalue.extok.finance_type = 0
else:
ir.lvalue.extok.finance_type = 0
isbfunc = True
elif(func_name == "decimals"):
token_type = _dest.address
if(token_type in label_sets):
if(label_sets[token_type].head > 0):
token_type = label_sets[token_type].head
norm = label_sets[token_type].norm
fin_type = label_sets[token_type].finance_type
ir.lvalue.extok.value = norm
isbfunc = True
if(isbfunc and token_type < 0):
ir.lvalue.extok.trace = dest
return isbfunc
#USAGE: typecheck for a library call: in this case, we only return special instances, or user-defined calls
#RETURNS: return or not
def type_library_call(ir):
param = ir.arguments
if(not(is_variable(ir.lvalue))):
return False
if(ir.function.name == "add"):
return type_bin_add(ir.lvalue, param[0], param[1])
elif(ir.function.name == "sub"):
return type_bin_sub(ir.lvalue, param[0], param[1])
elif(ir.function.name == "mul"):
return type_bin_mul(ir.lvalue, param[0], param[1])
elif(ir.function.name == "div"):
return type_bin_div(ir.lvalue, param[0], param[1])
if(querry_fc(ir) == 2):
return False
querry_type(ir.lvalue)
return False
#USAGE: typecheck for high-level call (i.e. iERC20(address).balanceof())
#RETURNS: whether or not the high-level call node should be returned (should always return FALSE)
def type_hlc(ir) ->bool:
#just query the user for the data
global function_hlc
param = ir.arguments
if(not(is_variable(ir.lvalue))):
return False
if(ir.function.name == "add"):
return type_bin_add(ir.lvalue, param[0], param[1])
elif(ir.function.name == "sub"):
return type_bin_sub(ir.lvalue, param[0], param[1])
elif(ir.function.name == "mul"):
return type_bin_mul(ir.lvalue, param[0], param[1])
elif(ir.function.name == "div"):
return type_bin_div(ir.lvalue, param[0], param[1])
temp = ir.lvalue.name
#typecheck abnormal function calls
res = querry_fc(ir)
if(res == 2):
return False
x = "hlc_"+str(function_hlc)
ir.lvalue.change_name(x)
querry_type(ir.lvalue)
ir.lvalue.change_name(temp)
function_hlc+=1
return False
#USAGE: creates/updates a new field
def update_member(member, fieldf, copy_ir):
if((isinstance(member, SolidityVariable))):
return
_member = member.extok
added = False
ptfield = None
for field in _member.fields:
_field = field.extok
if(_field.name == fieldf.extok.name):
added = True
ptfield = field
break
if(added):
copy_token_type(copy_ir, ptfield)
asn_norm(ptfield, copy_ir.extok.norm)
pass_ftype(ptfield, copy_ir, "assign")
_field = ptfield.extok
else:
copy_token_type(copy_ir, fieldf)
pass_ftype(fieldf, copy_ir, "assign")
asn_norm(fieldf, copy_ir.extok.norm)
_member.add_field(fieldf)
_field = fieldf.extok
if(not(_field.function_name)):
_field.function_name = _member.function_name
#USAGE: typechecks Members (i.e. a.b or a.b())
#RETURNS: the type for a (temporary handling, will fix if any issues)
def type_member(ir)->bool:
#FIELD WORK
if(isinstance(ir.variable_left, SolidityVariable)):
return False
init_var(ir.variable_left)
init_var(ir.variable_right)
_lv = ir.variable_left.extok
_rv = ir.variable_right.extok
_ir = ir.lvalue.extok
if(_lv.function_name == None):
_lv.function_name = ir.lvalue.extok.function_name
pf_name = _lv.function_name
#Check for field in typefile first:
field_type_tuple = get_field(pf_name, _lv.name, _rv.name)
if(field_type_tuple == None):
#print("No field found")
return True
field_full_name = _lv.name + "." + _rv.name
_ir.name = field_full_name
if(not(is_type_undef(ir.lvalue))):
#Copy backwards from the dest (ir.lvalue) to the field
fieldSet = False
for field in _lv.fields:
_field = field.extok
if(not(_field.function_name)):
_field.function_name = _lv.function_name
if(_field.name == _rv.name):
if(is_type_undef(_field)):
fieldSet = True
type_asn(field, ir.lvalue)
break
return fieldSet
for field in _lv.fields:
_field = field.extok
if(_field.name == _rv.name and not(is_type_undef(field))):
ir.lvalue.extok.token_type_clear()
copy_token_type(field, ir.lvalue)
copy_norm(field, ir.lvalue)
copy_ftype(field, ir.lvalue)
return False
ir.lvalue.extok.token_type_clear()
copy_token_tuple(ir.lvalue, field_type_tuple)
temp = create_iconstant()
copy_token_tuple(temp, field_type_tuple)
temp.name = _rv.name
_lv.add_field(temp)
return False
#USAGE: typechecks for references (i.e. a[0])
#RETURNS: always False
def type_ref(ir)->bool:
global mark_iteration
global current_function_marked
global label_sets
if(mark_iteration and not(current_function_marked)):
assign_const(ir.lvalue)
return False
#check for boolean
_lv = ir.lvalue.extok
_vl = ir.variable_left.extok
_lv.name = _vl.name
_lv.function_name = _vl.function_name
if(str(ir.lvalue.type) == "bool"):
assign_const(ir.lvalue)
return False
ref_tuple = get_ref(ir.variable_left.non_ssa_version.name)
if(ref_tuple != None):
##print("REFERENCE TYPE READ")
copy_token_tuple(ir.lvalue, ref_tuple)
return False
#check if the right value already has a type?
if not(is_type_undef(ir.variable_left) or is_type_const(ir.variable_left)):
ir.lvalue.extok.token_type_clear()
copy_token_type(ir.variable_left, ir.lvalue)
copy_norm(ir.variable_left, ir.lvalue)
copy_ftype(ir.variable_left, ir.lvalue)
return False
#check if the index of the variable has a type that is not a constant
if not(is_type_undef(ir.variable_right) or is_type_const(ir.variable_right)):
if(ir.variable_right.extok.is_address()):
ir.lvalue.extok.token_type_clear()
addr = ir.variable_right.extok.address
head_addr = label_sets[addr].head
norm = label_sets[addr].norm
ir.lvalue.extok.add_num_token_type(head_addr)
ir.lvalue.extok.add_den_token_type(-1)
ir.lvalue.extok.norm = norm
#ir.lvalue.extok.address = head_addr
else:
ir.lvalue.extok.token_type_clear()
copy_token_type(ir.variable_right, ir.lvalue)
copy_norm(ir.variable_right, ir.lvalue)
copy_ftype(ir.variable_right, ir.lvalue)
return False
#check the parser for a pre-user-defined type
if(str(ir.lvalue.type).startswith("address")):
ir.lvalue.extok.address = ir.variable_left.extok.address
return False
#no other options, assign constant
assign_const(ir.lvalue)
return True
#USAGE: typecheck for function call (pass on types etc)
#RETURNS: whether or not the function call node should be returned
def type_fc(ir) -> bool:
global mark_iteration
global current_function_marked
global debug_pow_pc
#check parameters
if(mark_iteration and not(current_function_marked)):
return False
params = []
for param in ir.read:
init_var(param)
if(is_constant(param)):
assign_const(param)
elif(not isinstance(param, Variable)):
param = create_iconstant()
params.append(param)
#generate param cache
new_param_cache = function_call_param_cache(params)
added = add_param_cache(ir.function, new_param_cache)
if(added == -100):
addback = _tcheck_function_call(ir.function, new_param_cache)
handle_return(ir.lvalue, ir.function)
if(len(addback) != 0):
return True
else:
if(not(ir.lvalue)):
return False
ret_obj = ir.function.get_parameter_cache_return(added)
if isinstance( ret_obj, Variable):
if isinstance(ret_obj, list):
type_asn(ir.lvalue, ret_obj[0])
ir.lvalue.extok.norm = ret_obj[0].extok.norm
copy_ftype(ret_obj[0], ir.lvalue)
else:
type_asn(ir.lvalue, ret_obj)
ir.lvalue.extok.norm = ret_obj.extok.norm
copy_ftype(ret_obj, ir.lvalue)
else:
add_tuple(ir.lvalue.name, ret_obj)
return False
#USAGE: given a function, handle the return values
#RETURNS: NULL
def handle_return(dest_ir, function):
global mark_iteration
global current_function_marked
#dest_ir is optional if there is no return destination
tuple_types = []
if(mark_iteration and not(current_function_marked)):
return
added = False
_dest_ir = None
constant_instance = create_iconstant()
if(dest_ir):
_dest_ir = dest_ir.extok
for _x in function.returns_ssa:
if(not isinstance(_x, Variable)):
x = constant_instance
else:
x = _x
__x = x.extok
#Replace the returns_ssa
if(len(function.return_values_ssa) > 1):
#param_type = [num, den, norm, link_function, fields, finance_type, address, value]
tuple_types.append((__x.num_token_types.copy(), __x.den_token_types.copy(), __x.norm, __x.value, __x.address, __x.finance_type))
else:
if(dest_ir != None):
dest_ir.extok.token_type_clear()
copy_token_type(x, dest_ir)
_dest_ir.linked_contract = __x.linked_contract
asn_norm(dest_ir, get_norm(x))
copy_ftype(x, dest_ir)
constant_instance.extok.token_type_clear()
copy_token_type(x, constant_instance)
constant_instance.extok.linked_contract = __x.linked_contract
asn_norm(constant_instance, get_norm(x))
copy_ftype(x, constant_instance)
function.add_parameter_cache_return(constant_instance)
added = True
if(len(tuple_types) > 0):
if(isinstance(dest_ir, TupleVariable)):
add_tuple(dest_ir.name, tuple_types)
elif(isinstance(dest_ir, Variable)):
dest_ir.extok.token_type_clear()
copy_token_tuple(dest_ir, tuple_types[0])
function.add_parameter_cache_return(tuple_types)
added = True
if(added == False):
function.add_parameter_cache_return(constant_instance)
#USAGE: assigns type from dest to sorc
#RETURNS: 'TRUE' if no variables undefined
def type_asn(dest, sorc) -> bool:
init_var(sorc)
if(is_type_undef(sorc)):
return True
elif(is_type_const(sorc)):
if(is_type_undef(dest) or is_type_const(dest)):
copy_token_type(sorc, dest)
return False
else:
if(is_type_undef(dest) or is_type_const(dest)):
copy_token_type(sorc, dest)
elif(not(compare_token_type(sorc, dest)) and handle_trace(sorc, dest) == False):
add_errors(dest)
return False
#USAGE: assigns reverse type from sorc to dest
def type_asni(dest, sorc):
init_var(sorc)
if(is_type_undef(sorc)):
return True
elif(is_type_const(sorc)):
if(is_type_undef(dest)):
copy_inv_token_type(sorc, dest)
return False
else:
tmp = create_iconstant()
tmp = combine_types(tmp, sorc, "div")
if(is_type_undef(dest)):
copy_inv_token_type(sorc, dest)
elif(not(compare_token_type(tmp, dest))):
add_errors(dest)
else:
return False
return False
#USAGE: assign type from dest to sorc, but additive
#RETURNS: 'TRUE' if the type assign is successful (maybe not used consider removing TODO)
def type_asna(dest, sorc) -> bool:
init_var(sorc)
if(is_type_undef(sorc)):
return False
else:
copy_token_type(sorc, dest)
return True
#USAGE: assign type from dest to sorc, but additive and inverse
#RETURNS: 'TRUE' if the type assign is successful (maybe not used consider removing TODO)
def type_asnai(dest, sorc)->bool:
init_var(sorc)
if(is_type_undef(sorc)):
return False
else:
copy_inv_token_type(sorc, dest)
return True
#USAGE: initializes a variable for typechecking
#RETURNS: NULL
def init_var(ir):
#Special variables
if(not(is_variable(ir)) and str(ir) != "msg.value"):
return False
_ir = ir.extok
if(_ir.name == None or _ir.function_name == None):
_ir.name = ir.name
_ir.function_name = ir.parent_function
if(is_constant(ir)):
assign_const(ir)
_ir.norm = get_norm(ir)
else:
convert_ssa(ir)
return True
#USAGE: test any ir for if it is a special constant instead of a variable
#RETURNS: new ir
def init_special(ir):
if((is_variable(ir))):
return ir
if(str(ir) == "block.timestamp"):
return create_iconstant()
else:
return ir
def get_values(ir):
if(is_constant(ir)):
return ir.value
else:
return ir.extok.value
#%dev returns true if the ir needs to be added back also initializes norms
#false otherwise
def type_bin(ir) -> bool:
temp_left = init_special(ir.variable_left)
temp_right = init_special(ir.variable_right)
ret = False
if (ir.type == BinaryType.ADDITION):
ret = type_bin_add(ir.lvalue, temp_left, temp_right)
return ret
elif (ir.type == BinaryType.SUBTRACTION):
ret = type_bin_sub(ir.lvalue, temp_left, temp_right)
return ret
elif (ir.type == BinaryType.MULTIPLICATION):
ret = type_bin_mul(ir.lvalue, temp_left, temp_right)
return ret
elif (ir.type == BinaryType.DIVISION):
ret = type_bin_div(ir.lvalue, temp_left, temp_right)
return type_bin_div(ir.lvalue, temp_left, temp_right)
elif (ir.type == BinaryType.POWER):
return type_bin_pow(ir.lvalue, temp_left, temp_right)
elif (ir.type == BinaryType.GREATER):
return type_bin_gt(ir.lvalue, temp_left, temp_right)
elif (ir.type == BinaryType.GREATER_EQUAL):
return type_bin_ge(ir.lvalue, temp_left, temp_right)
elif (ir.type == BinaryType.LESS):
return type_bin_lt(ir.lvalue, temp_left, temp_right)
elif (ir.type == BinaryType.LESS_EQUAL):
return type_bin_le(ir.lvalue, temp_left, temp_right)
return False
#USAGE: typechecks power statements
#RETURNS 'True' if needs to be added back
def type_bin_pow(dest, lir, rir) -> bool:
if(not (init_var(lir) and init_var(rir))):
return False
#don't assign norm yet
_lir = lir.extok
_rir = rir.extok
if(is_type_undef(lir) or is_type_undef(rir)):
return True
pow_const = -1
pass_ftype(dest, lir, "pow", rir)
if(is_constant(rir)):
pow_const = rir.value
if(is_type_const(lir)):
assign_const(dest)
l_norm = get_norm(lir)
if(pow_const > 0 and isinstance(l_norm, int)):
if(l_norm == 0):
l_norm = 1
asn_norm(dest, pow_const * (l_norm))
elif(pow_const == 0):
asn_norm(dest, pow_const)
else:
if(dest.extok.norm != '*'):
asn_norm(dest, 'u')
else:
type_asn(dest, lir)
l_norm = get_norm(lir)
if(pow_const != -1 and isinstance(l_norm, int)):
if(pow_const > 0):
asn_norm(dest, pow_const*l_norm)
for i in range (pow_const-1):
type_asna(dest, lir)
else:
asn_norm(dest, -pow_const * l_norm)
for i in range(pow_const-1):
type_asnai(dest, lir)
else:
if(dest.extok.norm != '*'):
asn_norm(dest, 'u')
handle_value_binop(dest, lir, rir, Pow)
return False
#USAGE: gets values of a binary operations and generates the result value
def handle_value_binop(dest, lir, rir, func):
global Add
global Sub
global Mul
global Div
global Pow
lval = get_values(lir)
rval = get_values(rir)
fval = 'u'
if(type(lval) != int or type(rval) != int):
if(type(lval) == int):
fval = lval
if(type(rval) == int):
fval = rval
elif(func == Add):
fval = lval + rval
elif(func == Sub):
fval = lval - rval
elif(func == Mul):
fval = lval * rval
elif(func == Div):
if(rval == 0):
fval = 0
else:
fval = (int)(lval / rval)
elif(func == Pow):
fval = lval ** rval
if(lval == 10):
dest.extok.norm = rval
dest.extok.value = fval
#USAGE: typechecks addition statements
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_add(dest, lir, rir) -> bool:
global Add
if(not (init_var(lir) and init_var(rir))):
return False
#Handle errors
if(not(is_type_undef(lir) or is_type_undef(rir) or is_type_const(lir) or is_type_const(rir) or is_type_address(lir) or is_type_address(rir))):
if(not(compare_token_type(rir, lir)) and handle_trace(rir, lir) == False):
#report error, default to left child
add_errors(dest)
return False
bin_norm(dest, lir, rir)
pass_ftype(dest, lir, "add", rir)
if(is_type_undef(lir) or is_type_undef(rir) or is_type_address(lir) or is_type_address(rir)):
if(is_type_undef(lir) or is_type_address(lir)):
type_asn(dest, rir)
else:
type_asn(dest, lir)
handle_value_binop(dest, lir, rir, Add)
return True
elif(is_type_const(lir)):
temp = type_asn(dest, rir)
handle_value_binop(dest, lir, rir, Add)
return temp
elif(is_type_const(rir)):
temp = type_asn(dest, lir)
handle_value_binop(dest, lir, rir, Add)
return temp
else:
temp = type_asn(dest, tcheck_propagation.greater_abstract(rir, lir))
handle_value_binop(dest, lir, rir, Add)
return temp
#USAGE: typechecks subtraction statements
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_sub(dest, lir, rir) -> bool:
global Sub
if(not (init_var(lir) and init_var(rir))):
return False
#Handle errors
if(not(is_type_undef(lir) or is_type_undef(rir) or is_type_const(lir) or is_type_const(rir) or is_type_address(lir) or is_type_address(rir))):
if(not(compare_token_type(rir, lir)) and handle_trace(rir, lir) == False):
#report error, default to left child
add_errors(dest)
return False
bin_norm(dest, lir, rir)
pass_ftype(dest, lir, "sub", rir)
if(is_type_undef(lir) or is_type_undef(rir) or is_type_address(lir) or is_type_address(rir)):
if(is_type_undef(lir) or is_type_address(lir)):
type_asn(dest, rir)
else:
type_asn(dest, lir)
handle_value_binop(dest, lir, rir, Sub)
return True
elif(is_type_const(lir)):
temp = type_asn(dest, rir)
handle_value_binop(dest, lir, rir, Sub)
return temp
elif(is_type_const(rir)):
temp = type_asn(dest, rir)
handle_value_binop(dest, lir, rir, Sub)
return temp
else:
temp = type_asn(dest, tcheck_propagation.greater_abstract(rir, lir))
handle_value_binop(dest, lir, rir, Sub)
return temp
#USAGE: handles traces -> takes the difference in token types and handles traces, placed in the comparison failure branch in type...add and type...sub
#RETURNS: successful handling or not
def handle_trace(rir, lir):
global label_sets
#Save token types
_rir = rir.extok
_lir = lir.extok
rntt = _rir.num_token_types.copy()
rdtt = _rir.den_token_types.copy()
lntt = _lir.num_token_types.copy()
ldtt = _lir.den_token_types.copy()
#Reduce numerators
n_dict = {}
for rn in rntt:
if(rn == -1):
continue
if(rn < -1):
if(rn in label_sets):
rn = label_sets[rn].head
if(rn in n_dict):
n_dict[rn]+=1
else:
n_dict[rn] = 1
for ln in lntt:
if(ln == -1):
continue
if(ln < -1):
if(ln in label_sets):
ln = label_sets[ln].head
if(ln in n_dict):
n_dict[ln]-=1
else:
n_dict[ln] = -1
#Reduce denominators
d_dict = {}
for rd in rdtt:
if(rd == -1):
continue
if(rd < -1):
if(rd in label_sets):
rd = label_sets[rd].head
if(rd in d_dict):
d_dict[rd]+=1
else:
d_dict[rd] = 1
for ld in ldtt:
if(ld == -1):
continue
if(ld < -1):
if(ld in label_sets):
ld = label_sets[ld].head
if(ld in d_dict):
d_dict[ld]-=1
else:
d_dict[ld] = -1
#Generate matchings, or generalize set
all_zeros = True
for n in n_dict:
if (n != 0):
all_zeros = False
break
for d in d_dict:
if(d!= 0 and all_zeros):
all_zeros = False
break
if(all_zeros):
return True
pot_trace = generate_label_trace(n_dict, d_dict)
if(pot_trace == None):
return False
#Just take the first one for now
first_trace = pot_trace[0]
for key,value in first_trace.items():
unioned = label_sets[key].union(label_sets[value])
if(unioned):
continue
return False
_rir.resolve_labels(label_sets)
_lir.resolve_labels(label_sets)
return True
#USAGE: given two dictionaries with x amounts of value y, generate all possible orderings of trace to label
#RETURNS: set of all possible orderings
def generate_label_trace(dictA, dictB):
pot_ordering = []
#Generate for dictA
pos_dict = {}
sum = 0
neg_dict = {}
for i in dictA:
if(i > 0):
pos_dict[i] = dictA[i]
sum+=1
else:
neg_dict[i] = dictA[i]
sum-=1
if(sum > 0):
return None
#Begin matching (dp algorithm)
dp = [[]] #int, ([ordering], [pos_dict])
curn = 0
for n in neg_dict:
dp.append([])
if (curn == 0):
for p in pos_dict:
_pos_dict = copy.deepcopy(pos_dict)
_neg_dict = copy.deepcopy(neg_dict)
_pos_dict[p] += neg_dict[n]
_ordering = {}
_ordering[n] = p
dp[curn].append([_pos_dict, _neg_dict, _ordering])
for n2 in neg_dict:
if(n2 == n):
continue
_pos_dict = copy.deepcopy(pos_dict)
_neg_dict = copy.deepcopy(neg_dict)
_neg_dict[n2] += neg_dict[n]
_ordering = {}
_ordering[n] = n2
dp[curn].append([_pos_dict, _neg_dict, _ordering])
else:
for tuple in dp[curn-1]:
_pos_dict = tuple[0]
_neg_dict = tuple[1]
_ordering = tuple[2]
for p in _pos_dict:
_2pos_dict = copy.deepcopy(_pos_dict)
_2pos_dict[p] += _neg_dict[n]
_2ordering = _ordering.copy()
_2ordering[n] = p
dp[curn].append([_2pos_dict, _neg_dict, _2ordering])
for n2 in _neg_dict:
if(n2 == n):
continue
_2neg_dict = copy.deepcopy(_neg_dict)
_2neg_dict[n2] += _neg_dict[n]
_2ordering = _ordering.copy()
_2ordering[n] = n2
dp[curn].append([_pos_dict, _2neg_dict, _2ordering])
curn+=1
if(curn == 0):
return None
for orderings in dp[curn-1]:
if(check_ordering(orderings[2], dictA) and check_ordering(orderings[2], dictB)):
pot_ordering.append(orderings[2])
if(len(pot_ordering) == 0):
return None
return pot_ordering
#USAGE: checks ordering
#RETURNS: ordering succeeds or not
def check_ordering(order, _dict):
dict = copy.deepcopy(_dict)
return True
for d in dict:
if(d < 0):
dict[order[d]]-=dict[d]
if(dict[order[d]]) < 0:
return False
for d in dict:
if(dict[d] != 0):
return False
#USAGE: given a constant, determine the number of powers of 10 that it includes
#RETURNS: the powers of 10 in the constant, if not, returns -1
def get_norm(ir):
power = -1
if(not(is_variable(ir))):
return 'u'
_ir = ir.extok
if(type(_ir.norm) != int and type(_ir.value) == int):
if(_ir.value % 10 != 0):
return power+1
power = 0
copy_val = _ir.value
while (copy_val > 0 and copy_val%10 == 0):
copy_val = copy_val/10
power+=1
if(power >= 5 or copy_val == 1):
return power
#ir is a constant or undefined
if(not(isinstance(ir, Constant)) or (not(isinstance(ir.value, int)))):
return _ir.norm
else:
if(ir.value % 10 != 0):
return power+1
power = 0
copy_val = ir.value
while (copy_val > 0 and copy_val%10 == 0):
copy_val = copy_val/10
power+=1
if(power >= 5 or copy_val == 1):
##print(power)
return power
return 0
#USAGE: if norm uninitialized, initializes norm (0)
# if initialized, check against norm and throw error
#RETURNS: NULL
def asn_norm(ir, norm):
if(not(is_variable(ir)) or norm == 'u'):
return
_ir = ir.extok
if(_ir.norm == 'u'):
_ir.norm = norm
elif (_ir.norm != norm and norm == '*'):
_ir.norm = '*'
else:
if(_ir.norm != norm or (_ir.norm == norm and norm == '*')):
if(_ir.norm == 0 and norm != '*'):
_ir.norm = norm
return
add_errors(ir)
_ir.norm = 'u'
#USAGE: compares norm values of two variables and throws errors if they are not equal
def compare_norm(lv, varA, varB, func = None):
global mark_iteration
global current_function_marked
if(mark_iteration and not(current_function_marked)):
return True
if(not(isinstance(varA, Variable) and isinstance(varB, Variable))):
return True
_varA = varA.extok
_varB = varB.extok
A_norm = _varA.norm
B_norm = _varB.norm
if(not(func) and (isinstance(varA, Constant) or isinstance(varB, Constant))):
if(isinstance(varA, Constant) and varA.value == 1 and not(_varA.is_undefined() or _varA.is_constant())):
add_errors(lv)
return True
if(isinstance(varB, Constant) and varB.value == 1 and not(_varB.is_undefined() or _varB.is_constant())):
add_errors(lv)
return True
return False
if(A_norm == 'u' or B_norm == 'u'):
return False
elif(A_norm == '*' or B_norm == '*'):
if(A_norm == B_norm or func == "mul" or func == "div"):
add_errors(lv)
return True
else:
if((not(func)) and (A_norm != B_norm)):
add_errors(lv)
return True
return False
#USAGE: append norm (i.e. for multiplication, division, or power)
#RETURNS: NULL
def add_norm(ir, norm):
if(not(is_variable(ir))):
return
_ir = ir.extok
temp = _ir.norm
if(isinstance(temp, int) and isinstance(norm, int)):
temp+=norm
_ir.norm = temp
elif(temp == 'u'):
_ir.norm = norm
elif(temp == '*'):
if(isinstance(norm, str)):
if(norm == '*'):
add_errors(ir)
return(True)
else:
y = False
else:
_ir.norm = '*'
return False
#USAGE: subtract norm (i.e. for multiplication, division, or power)
#RETURNS: NULL
def sub_norm(ir, norm):
if(not(is_variable(ir))):
return
_ir = ir.extok
temp = _ir.norm
if(isinstance(temp, int) and isinstance(norm, int)):
temp-=norm
_ir.norm = temp
elif(temp == 'u'):
_ir.norm = norm
elif(temp == '*'):
if(isinstance(norm, str)):
if(norm == '*'):
add_errors(ir)
return True
else:
y = False
else:
_ir.norm = '*'
return False
def bin_norm(dest, lir, rir, func = None):
err = compare_norm(dest, lir, rir, func)
lnorm = get_norm(lir)
rnorm = get_norm(rir)
if(err):
asn_norm(dest, 'u')
return
if(func == "compare"):
return
if(lnorm == 'u'):
if(func == "div" and isinstance(rnorm, int)):
asn_norm(dest, -rnorm)
else:
asn_norm(dest, rnorm)
elif(rnorm == 'u'):
asn_norm(dest, lnorm)
elif(lnorm == '*' or rnorm == '*' or not(isinstance(lnorm, int)) or not(isinstance(rnorm, int))):
if(dest.extok.norm != '*'):
asn_norm(dest, '*')
else:
#doesn't matter which
if(func == "mul"):
asn_norm(dest, lnorm + rnorm)
elif(func == "div"):
asn_norm(dest, lnorm - rnorm)
else:
asn_norm(dest, lnorm)
def combine_types(lir, rir, func = None):
tmp = create_iconstant()
_tmp = tmp.extok
_lir = lir.extok
_rir = rir.extok
if(func == "mul"):
copy_token_type(lir, tmp)
copy_token_type(rir, tmp)
elif(func == "div"):
copy_token_type(lir, tmp)
copy_inv_token_type(rir, tmp)
return tmp
#USAGE: typechecks a multiplication statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_mul(dest, lir, rir) ->bool:
global Mul
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir, "mul")
pass_ftype(dest, lir, "mul", rir)
if(is_type_undef(lir) or is_type_undef(rir) or is_type_address(lir) or is_type_address(rir)):
if(is_type_undef(dest)):
if(is_type_undef(lir) or is_type_address(lir)):
type_asn(dest, rir)
else:
type_asn(dest, lir)
else:
return(generate_ratios(dest, lir, rir, Mul))
handle_value_binop(dest, lir, rir, Mul)
return True
elif(is_type_const(lir)):
temp = type_asn(dest, rir)
handle_value_binop(dest, lir, rir, Mul)
return temp
elif(is_type_const(rir)):
temp = type_asn(dest, lir)
handle_value_binop(dest, lir, rir, Mul)
return temp
else:
tmp = combine_types(lir, rir, "mul")
type_asn(dest, tmp)
handle_value_binop(dest, lir, rir, Mul)
if(is_type_undef(dest)):
assign_const(dest)
return False
#USAGE: typechecks a division statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_div(dest, lir, rir) ->bool:
global Div
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir, "div")
pass_ftype(dest, lir, "div", rir)
if(is_type_undef(lir) or is_type_undef(rir)):
if(is_type_undef(dest)):
if(is_type_undef(lir)):
type_asni(dest, rir)
else:
type_asn(dest, lir)
else:
return(generate_ratios(dest, lir, rir, Div))
handle_value_binop(dest, lir, rir, Div)
return True
elif(is_type_const(lir)):
temp = type_asni(dest, rir)
handle_value_binop(dest, lir, rir, Div)
return temp
elif(is_type_const(rir)):
temp = type_asn(dest, lir)
handle_value_binop(dest, lir, rir, Div)
return temp
else:
tmp = combine_types(lir, rir, "div")
type_asn(dest, tmp)
handle_value_binop(dest, lir, rir, Div)
if(is_type_undef(dest)):
assign_const(dest)
return False
#USAGE: generate price ratios i.e. USDC/WETH
def generate_ratios(dest, lir, rir, func):
#Currently ignored
return False
global Mul
global Div
_dest = dest.extok
_lir = lir.extok
_rir = rir.extok
if(not(is_type_undef(lir)) and not(is_type_undef(rir))):
return False
if(is_type_undef(dest)):
return False
else:
if(func == Mul):
if(is_type_undef(lir)):
copy_token_type(dest, lir)
copy_inv_token_type(rir, lir)
handle_value_binop(lir, dest, rir, Div)
else:
copy_token_type(dest, rir)
copy_inv_token_type(lir, rir)
handle_value_binop(rir, dest, lir, Div)
else:
if(is_type_undef(lir)):
copy_token_type(dest, lir)
copy_token_type(rir, lir)
handle_value_binop(lir, dest, rir, Mul)
else:
copy_token_type(lir, rir)
copy_inv_token_type(dest, rir)
handle_value_binop(rir, lir, dest, Div)
return True
#USAGE: typechecks '>' statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_gt(dest, lir, rir) -> bool:
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir, "compare")
pass_ftype(dest, lir, "compare", rir)
if(is_type_undef(lir) or is_type_undef(rir)):
if(is_type_undef(lir)):
type_asn(lir, rir)
type_asn(dest, rir)
else:
type_asn(rir, lir)
type_asn(dest, lir)
return True
elif(is_type_const(lir) or is_type_const(rir)):
#assign dest as a constant
assign_const(dest)
return False
elif(not(compare_token_type(lir, rir)) and handle_trace(lir, rir) == False):
add_errors(dest)
return False
assign_const(dest)
return False
#USAGE: typechecks '>=' statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_ge(dest, lir, rir) -> bool:
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir, "compare")
pass_ftype(dest, lir, "compare", rir)
if(is_type_undef(lir) or is_type_undef(rir)):
if(is_type_undef(lir)):
type_asn(dest, rir)
type_asn(lir, rir)
else:
type_asn(dest, lir)
type_asn(rir, lir)
return True
elif(is_type_const(lir) or is_type_const(rir)):
#assign dest as a constant
assign_const(dest)
return False
elif(not(compare_token_type(lir, rir)) and handle_trace(lir, rir) == False):
add_errors(dest)
return False
assign_const(dest)
return False
#USAGE: typechecks '<' statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_lt(dest, lir, rir) -> bool:
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir, "compare")
pass_ftype(dest, lir, "compare", rir)
if(is_type_undef(lir) or is_type_undef(rir)):
if(is_type_undef(lir)):
type_asn(dest, rir)
type_asn(lir, rir)
else:
type_asn(dest, lir)
type_asn(rir, lir)
return True
elif(is_type_const(lir) or is_type_const(rir)):
#assign dest as a constant (although it should not be used in arithmatic)
assign_const(dest)
return False
elif(not(compare_token_type(lir, rir)) and handle_trace(lir, rir) == False):
add_errors(dest)
return False
assign_const(dest)
return False
#USAGE: typechecks '<=' statement
#RETURNS: 'TRUE' if the node needs to be added back to the worklist
def type_bin_le(dest, lir, rir) -> bool:
if(not (init_var(lir) and init_var(rir))):
return False
bin_norm(dest, lir, rir)
pass_ftype(dest, lir, "compare", rir)
if(is_type_undef(lir) or is_type_undef(rir)):
if(is_type_undef(lir)):
type_asn(dest, rir)
type_asn(lir, rir)
else:
type_asn(dest, lir)
type_asn(rir, lir)
return True
elif(is_type_const(lir) or is_type_const(rir)):
#assign dest as a constant (although it should not be used in arithmatic)
assign_const(dest)
return False
elif(not(compare_token_type(lir, rir)) and handle_trace(lir, rir) == False):
add_errors(dest)
return False
assign_const(dest)
return False
def is_variable(ir):
if isinstance(ir, Variable):
return True
return False
def is_internalcall(ir):
if isinstance(ir, InternalCall):
y = False
#def contains_equal(ir):
# if isinstance(ir, Binary):
# if ir.type == BinaryType.
def is_assert(node):
if node.contains_require_or_assert():
return True
# Old Solidity code where using an internal 'assert(bool)' function
# While we dont check that this function is correct, we assume it is
# To avoid too many FP
if "assert(bool)" in [c.full_name for c in node.internal_calls]:
return True
return False
#USAGE: given a list of irs, typecheck
#RETURNS: a list of irs that have undefined types
def _tcheck_ir(irs, function_name) -> []:
newirs = []
for ir in irs:
is_function(ir)
if has_lvalue(ir):
if function_name != None and ir.lvalue != None and is_variable(ir.lvalue):
_ir = ir.lvalue.extok
_ir.name = ir.lvalue.name
_ir.function_name = function_name
if(ir.lvalue.parent_function and ir.lvalue.parent_function == "global"):
_ir.function_name = "global"
else:
ir.lvalue.parent_function = function_name
if isinstance(ir, Function):
continue
if isinstance(ir, Condition):
is_condition(ir)
continue
if isinstance(ir, EventCall):
continue
if isinstance(ir, InternalCall):
is_function(ir.function)
check_type(ir)
continue
if isinstance(ir, Return):
check_type(ir)
continue
addback = check_type(ir)
if(addback):
newirs.append(ir)
return newirs
#USAGE: propogates a local variables with a parameter
def propogate_parameter(lv, function, clear_initial_parameters = False):
if("_1" in lv.ssa_name and (lv.extok.is_undefined() or clear_initial_parameters)):
pos = -1
for i in range(len(lv.ssa_name)-1):
revpos = len(lv.ssa_name)-i-1
if(lv.ssa_name[revpos:revpos+2] == '_1'):
pos = revpos
break
lv_subname = lv.ssa_name[:pos]
for p in function.parameters:
if(p.name == lv_subname):
lv.extok.token_type_clear()
lv.extok.name = lv.ssa_name
lv.extok.function_name = function.name
copy_token_type(p, lv)
lv.extok.norm = p.extok.norm
copy_ftype(p, lv)
return True
return False
#USSAGE: propogates a local variable with a global stored assignment
def propogate_global(lv):
global global_var_types
global current_contract_name
if(lv.extok.is_undefined()):
pos = -1
ssa_name_info = convert_ssa_name(lv.ssa_name)
_name = ssa_name_info[0]
#print(f"global name: {_name}, current_contract_name: {current_contract_name}")
#print(global_var_types)
if((_name, current_contract_name) in global_var_types):
stored_state = global_var_types[(_name, current_contract_name)]
copy_token_type(stored_state, lv)
copy_ftype(stored_state, lv)
lv.extok.norm = stored_state.extok.norm
#USAGE: gets the name and the number of an ssa_name
def convert_ssa_name(name):
_name = None
num = None
for i in range(len(name)-1):
revpos = len(name)-i-1
if(name[revpos] == '_'):
pos = revpos
break
_name = name[:pos]
num = (name[pos+1:])
return [_name, num]
#USAGE: typecheck a node
#RETURNS: list of IR with undefined types
def _tcheck_node(node, function) -> []:
global errors
global current_contract_name
global global_address_counter
function_name = function.name
irs = []
#local vars read
for lv in node.ssa_local_variables_read:
propogate_parameter(lv, function)
propogate_global(lv)
for lv in node.ssa_state_variables_read:
propogate_parameter(lv, function)
propogate_global(lv)
for lv in node.ssa_variables_read:
propogate_parameter(lv, function)
propogate_global(lv)
for lv in node.ssa_variables_written:
propogate_parameter(lv, function)
propogate_global(lv)
for ir in node.irs_ssa:
#DEFINE REFERENCE RELATIONS
ir.dnode = node
if isinstance(ir, Phi):
lv = ir.lvalue
propogate_parameter(lv, function)
propogate_global(lv)
if isinstance(ir, Member):
if isinstance(ir.lvalue, ReferenceVariable):
ir.lvalue.extok.ref([ir.variable_left, ir.variable_right])
irs.append(ir)
newirs = _tcheck_ir(irs, function_name)
#Handle Constructor Varialbes (need to be propagated)
for var in node.ssa_variables_written:
if((var.extok.name, current_contract_name) in global_var_types):
temp = global_var_types[(var.extok.name, current_contract_name)]
if(str(var.type) == "address"):
continue
temp.extok.name = var.extok.name
temp.extok.function_name = function.name #"constructor"
temp.extok.token_type_clear()
copy_token_type(var, temp)
if(temp.extok.finance_type == -1):
copy_ftype(var, temp)
temp.extok.norm = var.extok.norm
global_var_types[(var.extok.name, current_contract_name)] = temp
if(var.extok.address != 'u'):
#Only global addresses
global_address_counter+=1
for error in errors:
if(error.dnode == None):
error.dnode = node
return newirs
#USAGE: returns if the ir has a 'lvalue'
#RETURNS: T/F
def has_lvalue(ir):
if(isinstance(ir, Assignment)):
return True
if(isinstance(ir, Binary)):
return True
if(isinstance(ir, HighLevelCall)):
return True
if(isinstance(ir, LibraryCall)):
return True
if(isinstance(ir, Member)):
return True
if(isinstance(ir, Index)):
return True
if(isinstance(ir, Unpack)):
return True
if(isinstance(ir, Phi)):
return True
if(isinstance(ir, TypeConversion)):
return True
if(isinstance(ir, InternalCall)):
return True
return False
#USAGE: clears a node
#RETURNS: N/A
def _clear_type_node(node):
global debug_pow_pc
for ir in node.irs_ssa:
#Clear lvalue
if(has_lvalue(ir) and is_variable(ir.lvalue)):
if(isinstance(ir.lvalue, TemporaryVariable) or isinstance(ir.lvalue, LocalIRVariable) or isinstance(ir.lvalue, Variable)):
#clear the types for temporary and local variables
_ir = ir.lvalue.extok
_ir.token_type_clear()
_ir.norm = 'u'
_ir.finance_type = -1
for field in _ir.fields:
field.extok.token_type_clear()
#Clear variables
#USAGE: searches a function for a RETURN node, if it doesn't exist, do stuff
#RETURNS: return node
def remap_return(function):
fentry = {function.entry_point}
explored = set()
return_ssa_mapping = {}
for ir_ssa in function.returns_ssa:
try:
return_ssa_mapping[ir_ssa.ssa_name] = None
except AttributeError:
a = 2
fentry = {function.entry_point}
explored = set()
while(fentry):
node = fentry.pop()
if(node in explored):
continue
explored.add(node)
for written_ir in node.ssa_variables_written:
if(written_ir.ssa_name in return_ssa_mapping):
return_ssa_mapping[written_ir.ssa_name] = written_ir
for son in node.sons:
fentry.add(son)
for ir_ssa in function.returns_ssa:
try:
if(not return_ssa_mapping[ir_ssa.ssa_name] == None ):
ir_ssa = return_ssa_mapping[ir_ssa.ssa_name]
except AttributeError:
a = 2
#USAGE: propogates all of the parameters in a function to their first reference in the SSA.
# uses "propogate_parameter"
def _propogate_all_parameters(function):
explored = set()
fentry = {function.entry_point}
while fentry:
node = fentry.pop()
if node in explored:
continue
explored.add(node)
for var in node.ssa_local_variables_read:
propogate_parameter(var, function, True)
for son in node.sons:
fentry.add(son)
#USAGE: typecheck a function call
# given a param_cache for the input data
# check return values:
#RETURNS: list of nodes with undefined types
def _tcheck_function_call(function, param_cache) -> []:
global function_hlc
global function_ref
global function_count
global temp_address_counter
function_hlc = 0
function_ref = 0
explored = set()
addback_nodes = []
#load parameters
paramno = 0
#Append to function count
function_count+=1
#print(f"function: {function.name}, function count: {function_count}")
for param in function.parameters:
if(paramno == len(param_cache)):
break
copy_pc_token_type(param_cache[paramno], param)
paramno+=1
#find return and tack it onto the end
remap_return(function)
#Propogate parameters
_propogate_all_parameters(function)
#WORKLIST ALGORITHM
prevlen = -1
curlen = -1
wl_iter = 0
while((curlen < prevlen and prevlen != -1) or prevlen == -1):
addback_nodes = []
explored = set()
return_node = None
fentry = {function.entry_point}
#load in parameters
paramno = 0
for param in function.parameters:
if(paramno == len(param_cache)):
break
copy_pc_token_type(param_cache[paramno], param)
paramno+=1
while fentry:
node = fentry.pop()
if node in explored:
continue
explored.add(node)
#clear previous nodes
if(prevlen == -1):
_clear_type_node(node)
addback = _tcheck_node(node, function)
if(len(addback) > 0):
addback_nodes.append(node)
for son in node.sons:
temp = True
if return_node == None:
for irs in son.irs:
if(isinstance(irs, Return)):
temp = False
return_node = son
break
if(temp):
fentry.add(son)
if(return_node):
_clear_type_node(return_node)
_tcheck_node(return_node, function)
prevlen = curlen
curlen = len(addback_nodes)
wl_iter+=1
return addback_nodes
#USAGE: typecheck a function
# if external or public function, prompt user for types (local variable parameters)
# no need to care about the function return values here (these check from external calls)
#RETURNS: list of nodes with undefined types
def _tcheck_function(function) -> []:
global function_hlc
global function_ref
global function_count
global mark_iteration
global current_function_marked
global temp_address_counter
function_hlc = 0
function_ref = 0
explored = set()
addback_nodes = []
#print()
#print()
#print()
#print(function.name)
if(check_bar(function.name)):
return addback_nodes
#print("Function name: "+function.name)
fvisibl = function.visibility
new_param_cache = None
if(True):
for fparam in function.parameters:
fparam.parent_function = function.name
querry_type(fparam)
#generate param_cache
new_param_cache = function_param_cache(function)
if(not(mark_iteration) or current_function_marked):
added = add_param_cache(function, new_param_cache)
else:
return addback_nodes
remap_return(function)
#Append to function count
function_count+=1
#print(f"function: {function.name}, function count: {function_count}")
#Propogate parameters
#WORKLIST ALGORITHM
prevlen = -1
curlen = -1
wl_iter = 0
while((prevlen > curlen and prevlen != -1) or prevlen == -1):
addback_nodes = []
fentry = {function.entry_point}
viewfentry = {function.entry_point}
view_ir(viewfentry)
explored = set()
paramno = 0
for param in function.parameters:
copy_pc_token_type(new_param_cache[paramno], param)
paramno+=1
while fentry:
node = fentry.pop()
if node in explored:
continue
explored.add(node)
if(prevlen == -1):
_clear_type_node(node)
addback = _tcheck_node(node, function)
if(len(addback) > 0):
addback_nodes.append(node)
for son in node.sons:
fentry.add(son)
prevlen = curlen
curlen = len(addback_nodes)
wl_iter+=1
#Save return value
handle_return(None, function)
return addback_nodes
def view_ir(fentry):
return
explored = set()
while fentry:
node = fentry.pop()
if node in explored:
continue
explored.add(node)
for ir in node.irs_ssa:
print (ir)
for son in node.sons:
fentry.add(son)
print()
print()
#USAGE: typechecks state (global) variables given a contract
#RETURNS: whether or not the state variable need to be added back.
# the result is always 'FALSE' (querried)
def _tcheck_contract_state_var(contract):
global user_type
global fill_type
global read_global
global global_var_types
global address_to_num
global num_to_address
type_info_name = None
if(user_type and fill_type):
type_info_name = contract.name+"_types.txt"
new_tfile = open(type_info_name, "a")
new_tfile.write(f"[*c], {contract.name}\n")
new_tfile.close()
seen = {}
for state_var in _read_state_variables(contract):
if(state_var.name in seen):
continue
seen[state_var.name] = True
state_var.parent_function = "global"
if(user_type and fill_type):
new_tfile = open(type_info_name, "a")
new_tfile.write(f"[t], global, {state_var.name}\n")
new_tfile.close()
assign_const(state_var)
continue
if(True):
if(not(contract.name in read_global) or not((state_var.extok.name, contract.name) in global_var_types)):
querry_type(state_var)
new_constant = create_iconstant()
copy_token_type(state_var, new_constant)
copy_ftype(state_var, new_constant)
new_constant.extok.norm = state_var.extok.norm
global_var_types[(state_var.extok.name, contract.name)] = new_constant
else:
stored_state = global_var_types[(state_var.extok.name, contract.name)]
copy_token_type(stored_state, state_var)
copy_ftype(stored_state, state_var)
state_var.extok.norm = stored_state.extok.norm
if(isinstance(state_var, ReferenceVariable)):
add_ref(state_var.name, (state_var.token_typen, state_var.token_typed, state_var.norm, state_var.link_function))
read_global[contract.name] = True
#USAGE: labels which contracts that should be read (contains binary operations) also adds contract-function pairs
#RTURNS: NULL
def _mark_functions(contract):
#Check for any external. If none, check internal (TODO add a feature to allow internal function type checking)
hasExternal = read_internal
for function in contract.functions_declared:
if(function.visibility == "external" or function.visibility == "public"):
hasExternal = True
for function in contract.functions_declared:
fentry = {function.entry_point}
#add contract-function pair
add_cf_pair(contract.name, function.name, function)
if(not (function.entry_point and (not(hasExternal) or function.visibility == "external" or function.visibility == "public"))):
function_check[function.name] = False
continue
contains_bin = False
while fentry:
node = fentry.pop()
for ir in node.irs_ssa:
if(isinstance(ir, Binary)):
contains_bin = True
break
if(ir.function and (ir.function.name == "add" or ir.function.name == "sub" or ir.function.name == "mul" or ir.function.name == "div")):
contains_bin = True
break
if(isinstance(ir, InternalCall)):
if(function_check.get(ir.function.name)):
containus_bin = True
break
if contains_bin:
break
for son in node.sons:
fentry.add(son)
function_check[function.name] = contains_bin
continue
if contains_bin:
print("[*]Marked")
else:
print("[X]No Binary")
# USAGE: typechecks an entire contract given the contract
# generates a list of nodes that need to be added back
# RETURNS: returns a list of errors(if any)
def _tcheck_contract(contract):
#contract is the contract passed in by Slither
global errors
global current_contract_name
global mark_iteration
global current_function_marked
global global_var_types
global global_address_counter
global address_to_num
global num_to_address
current_contract_name = contract.name
all_addback_nodes = []
#_mark_functions(contract)
#_tcheck_contract_state_var(contract)
#Reset update ratios
reset_update_ratios()
for function in contract.functions_declared:
if not(function_check[function.name]):
if(mark_iteration):
current_function_marked = False
else:
continue
else:
current_function_marked = True
if not function.entry_point:
continue
addback_nodes = _tcheck_function(function)
#Override state variables only for the constructor
current_function_marked = True
if(function.name != "constructor"):
y = None
else:
continue
if(len(addback_nodes) > 0):
all_addback_nodes+=(addback_nodes)
return errors
#USAGE: returns the state variables of a contract
#RETURNS: the state variables of a contract
def _read_state_variables(contract):
ret = []
for f in contract.all_functions_called + contract.modifiers:
ret += f.state_variables_read
return ret
class tcheck(AbstractDetector):
"""
Detects round up round down functions
"""
ARGUMENT = 'tcheck' # slither will launch the detector with slither.py --detect mydetector
HELP = 'Help printed by slither'
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = 'ScType'
WIKI_TITLE = 'None'
WIKI_DESCRIPTION = 'Static analysis tool for accounting errors'
WIKI_EXPLOIT_SCENARIO = 'See paper'
WIKI_RECOMMENDATION = 'None'
def _detect(self):
results = []
u_provide_type = {}
global user_type
global type_file
global line_no
global constant_instance
global seen_contracts
global function_count
global address_to_label
global label_sets
assign_const(constant_instance)
total_compilations = tcheck_module.get_total_compilations()
start_time = time.time()
for contract in self.contracts:
#print(f"Contracts handled: {contract.name}, compilations: {total_compilations}")
#create hashtable with function name and contract name
type_info_name = contract.name+"_types.txt"
finance_info_name = contract.name+"_ftypes.txt"
#get finance type info
f_file = None
try:
with open(finance_info_name, "r") as _f_file:
f_file = finance_info_name
except FileNotFoundError:
f_file = None
#get type information from file (if there is one)
try:
with open(type_info_name, "r") as t_file:
# File processing code goes here
user_type = False
type_file = type_info_name
parse_type_file(type_file, f_file)
u_provide_type[contract.name] = False
#print(f"opened type file for {contract.name}")
except FileNotFoundError:
# Handle the error gracefully or take appropriate action
u_provide_type[contract.name] = False
user_type = True
if(not (check_contract(contract.name))):
continue
#mark functions
used_contract = get_cont_with_state_var(contract.name)
if(used_contract == None):
used_contract = contract
_mark_functions(used_contract)
#resolve global variables
_tcheck_contract_state_var(used_contract)
for contract in self.contracts:
if(contract.name in seen_contracts):
continue
seen_contracts[contract.name] = True
user_type = u_provide_type[contract.name]
if(not (check_contract(contract.name)) or (user_type and fill_type)):
continue
used_contract = get_cont_with_state_var(contract.name)
if(used_contract == None):
used_contract = contract
errorsx = _tcheck_contract(used_contract)
for ir in errorsx:
_ir = ir.extok
name = _ir.name
func = _ir.function_name
dnode = ir.dnode
if(name == None):
name = "UNKNOWN"
if(func == None):
func = "UNKNOWN"
info = [" typecheck error: " ]
info+=("Var name: " + name + " " + "Func name: " + func + " in " + str(dnode) + "\n")
res = self.generate_result(info)
results.append(res)
end_time = time.time()
print(f"Annotation count: {tcheck_parser.get_total_annotations()}")
print(f"Function count: {function_count}")
return results
| 94,491 | Python | .py | 2,592 | 28.13233 | 185 | 0.605173 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,230 | tcheck_propagation.py | NioTheFirst_ScType/slither/detectors/my_detectors/tcheck_propagation.py | from slither.core.solidity_types import UserDefinedType, ArrayType, MappingType
from slither.core.declarations import Structure, Contract
from slither.core.variables.variable import Variable
import copy
import tcheck_parser
import tcheck
from tcheck import errors
#USAGE: library for functions that help propagate types
# these functions contain handling for ABSTRACT types as well (any type > abs_buf is an ABSTRACT type)
# ABSTRACT types take priority over CONCRETE types (temporary handling for if statements)
# ABSTRACT type comparison to CONCRETE type comparison always holds true
from tcheck_parser import field_tuple_start, f_type_name, f_type_num, update_ratios, update_start
f_type_add = {
(0, 0): 0, #raw balance + raw balance = raw blaance
(1, 1): 1, #net balance + net balance = net balance
(2, 2): 2, #accrud balance + accrued balance = accrued balance
(0, 23): 1, #compound interest + balance = net balance
(23, 0): 1,
(1, 23) : 3, #compound interest + net balance = final balance
(23, 1) : 3,
(10, 10) : 10, #c. fee ratio + c. fee ratio = c.fee ratio
(12, 12) : 12, #s. fee ratio + s. fee ratio = s.fee ratio
(13, 13) : 13, #trans fee + trans fee
(30, 0): 30,#reserve +any balance
(0, 30): 30,
(30, 1): 30,
(1, 30): 30,
(30, 30): 30,
(30, 2): 30,
(30, 3): 30,
(40, 40): 40,
(11, 50): 50, #fee + debt
(50, 11): 50, #debt + fee
(23, 11): 23, #Interest + fee = interest
(23, 50): 50, #interest + debt = debt
(23, 23): 23, #interest + interest = interest
(50, 0): 50, #debt + any balance
(0, 50): 50,
(50, 1): 50,
(1, 50): 50,
(50, 2): 50,
(2, 50): 50,
(50, 3): 50,
(3, 50): 50,
(60, 0): 3, #divident + balances
(0, 60):3,
(1, 60): 3,
(60, 1): 3,
}
f_type_sub = {
(0, 0): 0, #raw balance - raw balance = raw blaance
(1, 1): 1, #net balance - net balance = net balance
(2, 2): 2, #accrud balance - accrued balance = accrued balance
(0, 11): 1, #raw balance - t. fee = net balance
(0, 13): 1, #raw balance - t. fee (n) = net balance
(0,14) : 1, #raw balance - t. fee (d) = net balance
(0, 50): 0, #xraw balance - debt = debt
(1, 50): 1, #xnet balance - debt = net balance
(2, 50): 2, #xacc balance - debt = acc balance
(11, 11): 11, #xt. fee - t.fee
(11, 60): 11, #xt.fee - dividend
(10, 10) : 10, #c. fee ratio - c. fee ratio = c.fee ratio
(12, 12) : 12, #s. fee ratio - s. fee ratio = s.fee ratio
(30, 0): 30,#reserve - any balance
(30, 1): 30,
(30, 2): 30,
(30, 3): 30,
(30, 30): 30,
(30, 60): 30,
(50, 0): 50, #debt - any balance
(50, 1): 50,
(50, 2): 50,
(50, 3): 50,
(60, 11): 60, #dividend - fee = divident
(60, 60): 60, #divident - divident
}
f_type_mul = {
(0, 0): 0,
(1, 1): 1, #net bal / net bal (?)
(0, 10) : 13, #raw balance * compound fee ratio (t)= transaction fee (n)
(10, 0) : 13,
(2, 10) : 13, #accrued balance * compound fee ratio (t) = transaction fee (n)
(10, 2) : 13,
(14, 10):11, #transaction fee (d) * compound fee ratio = transaction fee
(10, 14):11,
(0, 12):1, #raw balance * simple fee ratio = net balance
(0, 12):1,
(0, 20):2, #simple interest ratio * raw balance = accrued balance
(20, 0):2,
(1, 20):3, #net balance * simple interest ratio = final balance
(20, 1):3,
(0, 21):23, #compound interest ratio * raw balance = compound interest
(21, 0):23,
(22, 20):22, #simple intrest * simple interest ratio = simple interest
(20, 22):22,
(30, 30):30,
(23, 21):23, #compound interest * compound interest ratio = compound interest
(21, 23): 23,
(40, 0) : 0, #price/exchange rate * any balance = corresponding balance
(0, 40) : 0, #Reserve
(40, 1) : 1,
(1, 40) : 1,
(40, 2) : 2,
(1, 40) : 2,
(40, 3) : 3,
(3, 40) : 3,
(60, 40) : 40, #price x dividend
(40, 60) : 40, #dividend x price
(40, 30) : 30, #price x reserve
(30, 40) : 30,
}
f_type_div = {
(0, 0) : 40,
(1, 1): 40, #net bal / net bal (?)
(2, 2): 40,
(0, 10) : 14, #raw balance / c. fee ratio (t)= transaction fee (d)
(2, 10) : 14, #accrued balance / c. fee ratio (t) = transaction fee (d)
(13, 10): 11, #t. fee (n) / fee ratio = t. fee
(0, 12):1, #raw balance / simple fee ratio = net balance
(0, 20):2, #simple interest ratio * raw balance = accrued balance
(20, 0):2,
(1, 20):3, #net balance * simple interest ratio = final balance
(20, 1):3,
(0, 21):23, #compound interest ratio * raw balance = compound interest
(21, 0):23,
(22, 20):22, #simple intrest * simple interest ratio = simple interest
(20, 22):22,
(23, 21):23, #compound interest * compound interest ratio = compound interest
(21, 23): 23,
(40, 0) : 0, #price/exchange rate * any balance = corresponding balance
(0, 40) : 0,
(30, 30): 30,
(0, 30): 0,
(40, 1) : 1,
(1, 40) : 1,
(40, 2) : 2,
(1, 40) : 2,
(40, 3) : 3,
(3, 40) : 3,
(30, 40): 30 #resreve / price
}
abs_buf = 10
#USAGE: copies the token types from src variable to dest variable
def copy_token_type(dest, src):
#Does not clear the variables
_dest = dest.extok
_src = src.extok
for n in _src.num_token_types:
_dest.add_num_token_type(n)
for d in _src.den_token_types:
_dest.add_den_token_type(d)
if _src.linked_contract:
_dest.linked_contract = _src.linked_contract
_dest.value = _src.value
#print(f"Source address: {_src.address}")
_dest.address = _src.address
for field in _src.fields:
_dest.add_field(field)
#_dest.finance_type = _src.finance_type
#USAGE: copies inverse token types from the 'src' ir node from the 'dest' ir node
def copy_inv_token_type(src, dest):
_dest = dest.extok
_src = src.extok
for n in _src.num_token_types:
_dest.add_den_token_type(n)
for d in _src.den_token_types:
_dest.add_num_token_type(d)
if _src.linked_contract:
_dest.linked_contract = _src.linked_contract
#_dest.finance_type = _src.finance_type
#USAGE: copy and replace a token from a param_cache to an ir
#RETURNS: nN/A
def copy_pc_token_type(_src, dest):
#src = copy.deepcopy(_src)
#print(_src.extok)
#print(_src)
src = _src
src[0] = _src[0].copy()
src[1] = _src[1].copy()
_dest = dest.extok
_dest.token_type_clear()
#print(src)
for n in src[0]:
#print(n)
_dest.add_num_token_type(n)
for d in src[1]:
_dest.add_den_token_type(d)
if(src[2]!= None):
_dest.norm = src[2]
if(src[3] != None):
_dest.linked_contract = src[3]
if(src[4] != None):
temp = tcheck.create_iconstant()
#copy_token_type(field, temp)
#temp.extok.name = field.extok.name
#temp.extok.function_name = field.extok
for field in src[4]:
_dest.add_field(field)
_dest.finance_type = src[5]
_dest.address = src[6]
_dest.value = src[7]
#print(f"Prop result: {_dest}")
#USAGE: copies a finance type
def copy_ftype(src, dest):
if(not(isinstance(src, Variable) and isinstance(dest, Variable))):
return
_src = src.extok
_dest = dest.extok
_dest.finance_type = _src.finance_type
#USAGE: assigns a finance type
def assign_ftype(ftype, dest):
dest.extok.finance_type = ftype
#USAGE: deals with updates
def pass_update(dest, rsrcl, func, rsrcr = None):
global update_ratios
#Assign updates where dest is a ratio (and rsrcr exists)
_dest = dest.extok
dest_in_ratio = (_dest.finance_type in update_ratios)
#print(f"Dest type: {_dest.finance_type}, Update_ratios: {update_ratios}")
_rl = rsrcl.extok
_rlf = _rl.finance_type
_rlfp = _rl.pure_type
l_in_ratio = (_rlfp in update_ratios)
_rr = None
_rrf = -1
_rrfp = -1
r_in_ratio = False
if(rsrcr):
_rr = rsrcr.extok
_rrf = _rr.finance_type
_rrfp = _rr.pure_type
r_in_ratio = (_rrfp in update_ratios)
if(dest_in_ratio):
#print(f"Dest updated")
_dest.updated = True
update_ratios[_dest.finance_type] = True
#print(f"Right type: {_rrf}, Left type: {_rlf}")
#Checks for unupdated usage
if(not(dest_in_ratio) and (r_in_ratio or l_in_ratio)):
checked_ratio = -1
updated = False
if(r_in_ratio):
checked_ratio = _rrfp
updated = _rr.updated
#print(f"Left side: {_rlfp}, Right side: {_rrfp}, Checked Ratio: {checked_ratio}")
#print(updated)
elif(l_in_ratio):
checked_ratio = _rlfp
updated = _rl.updated
#print(f"Left side: {_rlfp}, Right side: {_rrfp}, Checked Ratio: {checked_ratio}")
if(update_ratios[checked_ratio] == -1):
#Set update ratio
update_ratios[checked_ratio] = updated
elif(update_ratios[checked_ratio] != updated):
#print(f"Inconsistent updating of {checked_ratio} by {_rlf} and {_rrf}")
return True
#Propogate updated usage
#if(_rl.updated or (_rr != None and _rr.updated)):
# _dest.updated = True
#print(f"Final dest type: {_dest.finance_type}")
#USAGE: given two finance types, output the relavant result after the function
# does not deal with updates, main functionality is to deal with function calls
def pass_ftype_no_ir(l_fin_type, r_fin_type, func):
l_pure = -1
r_pure = -1
if(l_fin_type > update_start):
l_pure = l_fin_type - update_start
if(r_fin_type != None and r_fin_type > update_start):
r_pure = r_fin_type - update_start
key = (l_pure, r_pure)
if(func == "add"):
if key in f_type_add:
return f_type_add[key]
return None
if(func == "sub"):
if key in f_type_sub:
return f_type_sub[key]
else:
return None
elif(func == "mul"):
if key in f_type_mul:
return f_type_mul[key]
return None
elif(func == "div"):
if key in f_type_div:
return(f_type_div[key])
return None
elif(func == "compare"):
if(l_pure != r_pure):
return None
return -1
elif(func == "assign"):
return l_pure
elif(func == "pow"):
return l_pure
return None
#USAGE: finance type propogation
def pass_ftype(dest, rsrcl, func, rsrcr = None):
#dest is the finance destination
#rsrcl is the left-most rhand side variable
#rsrcr is the (optional) right-most rhand-side variable
#func is the name of the function
if(not(isinstance(rsrcl, Variable) and (rsrcr == None or isinstance(rsrcr, Variable)))):
return False
_rl = rsrcl.extok
_rlf = _rl.finance_type
_rlfp = _rl.pure_type
_rr = None
_rrf = -1
_rrfp = -1
if(rsrcr):
_rr = rsrcr.extok
_rrf = _rr.finance_type
_rrfp = _rr.pure_type
if(_rrf == -1):
assign_ftype(_rlf, dest)
pass_update(dest, rsrcl, func, rsrcr)
return False
if(_rlf == -1):
assign_ftype(_rrf, dest)
pass_update(dest, rsrcl, func, rsrcr)
return False
key = (_rlfp, _rrfp)
#print(f"Finance type key: {key}")
if(func == "add"):
if key in f_type_add:
assign_ftype(f_type_add[key], dest)
else:
assign_ftype(-1, dest)
return True
if(func == "sub"):
if key in f_type_sub:
assign_ftype(f_type_sub[key], dest)
else:
assign_ftype(-1, dest)
return True
elif(func == "mul"):
if key in f_type_mul:
assign_ftype(f_type_mul[key], dest)
else:
assign_ftype(-1, dest)
return True
elif(func == "div"):
if key in f_type_div:
assign_ftype(f_type_div[key], dest)
else:
assign_ftype(-1, dest)
return True
elif(func == "compare"):
if(_rlf != _rrf):
return True
assign_ftype(-1, dest)
elif(func == "assign"):
#if(_rlf != _rrf):
# return True
assign_ftype(_rlf, dest)
elif(func == "pow"):
assign_ftype(_rlf, dest)
#print(f"Func: {func}")
return(pass_update(dest, rsrcl, func, rsrcr))
#USAGE: directly copies a norm value. WARNING: skips typechecks associated with normalization
def copy_norm(src, dest):
_src = src.extok
_dest = dest.extok
_dest.norm = _src.norm
#USAGE: copies all the types from a type tuple to an ir node
#RETURNS: null
def copy_token_tuple(ir, tt):
#print("Check copy_toekn_tuple")
#print(tt)
_ir = ir.extok
#print("----")
_ir.token_type_clear()
if(isinstance(tt[0], int)):
_ir.add_num_token_type(tt[0])
else:
for n in tt[0]:
_ir.add_num_token_type(n)
if(isinstance(tt[1], int)):
_ir.add_den_token_type(tt[1])
else:
for d in tt[1]:
_ir.add_den_token_type(d)
if(isinstance(tt[2], int)):
if(tt[2] == -404):
_ir.norm = '*'
else:
_ir.norm = tt[2]
elif(isinstance(tt[2], str)):
_ir.norm = tt[2]
else:
_ir.norm = tt[2][0]
_ir.address = tt[4]
_ir.value = tt[3]
if(len(tt) > field_tuple_start):
_ir.finance_type = tt[5]
propagate_fields(ir)
#[DEPRECATED] comapres the token types of two variables. Includes support for checking ABSTRACT types
"""def compare_token_type(varA, varB):
A_num_types = copy_and_sort(varA.token_typen)
A_den_types = copy_and_sort(varA.token_typed)
B_num_types = copy_and_sort(varB.token_typen)
B_den_types = copy_and_sort(varB.token_typed)
if(_compare_token_type(A_num_types, B_num_types)):
return _compare_token_type(A_den_types, B_den_types)
return False
"""
#USAGE: comapres the extended types of two variables. Includes support for checking ABSTRACT types
def compare_token_type(varA, varB):
_varA = varA.extok
_varB = varB.extok
A_num_types = copy_and_sort(_varA.num_token_types)
A_den_types = copy_and_sort(_varA.den_token_types)
B_num_types = copy_and_sort(_varB.num_token_types)
B_den_types = copy_and_sort(_varB.den_token_types)
if(_compare_token_type(A_num_types, B_num_types)):
return _compare_token_type(A_den_types, B_den_types)
return False
#USAGE: helper function for compare_token_type
def _compare_token_type(A_types, B_types):
if(len(A_types) != len(B_types)):
return False
A_buffer = 0
B_buffer = 0
Apos = len(A_types)-1
Bpos = len(B_types)-1
while(Apos >= 0 or Bpos >= 0):
#print(A_types[Apos])
if(Apos > -1 and A_types[Apos]>=abs_buf):
if(A_types[Apos] > B_types[Bpos]):
B_buffer+=1
elif(A_types[Apos] == B_types[Bpos]):
Bpos-=1
else:
while(A_types[Apos] < B_types[Bpos]):
A_buffer+=1
Bpos-=1
if(Bpos < 0):
break
else:
while(Bpos >= 0 and B_types[Bpos] >= abs_buf):
A_buffer+=1
Bpos-=1
if(Bpos < 0):
Apos-=1
continue
if(Apos > -1 and A_types[Apos] > B_types[Bpos]):
A_buffer-=1
elif(Apos > -1 and A_types[Apos] == B_types[Bpos]):
Bpos-=1
else:
while((Apos < 0 and Bpos >= 0) or A_types[Apos] < B_types[Bpos]):
B_buffer-=1
Bpos-=1
if(Bpos == -1):
break
Apos-=1
if(A_buffer != 0 or B_buffer != 0):
return False
return True
def get_raw_type(ir):
ttype = ir.type
changed = False
while(True):
#print(ttype)
changed = False
if(isinstance(ttype, ArrayType)):
changed = True
ttype = ttype.type
elif(isinstance(ttype, MappingType)):
changed = True
ttype = ttype.type_to
if(not(changed)):
return ttype
#USAGE: given an ir, propogate it's fields
def propagate_fields(ir):
_ir = ir.extok
#print(f"Type: {ir.type}")
ttype = get_raw_type(ir)
#print(f"Final Type: {ttype}")
#Field tuple propagation
if(isinstance(ttype, UserDefinedType)):
fields = None
ttype = ttype.type
if isinstance(ttype, Structure):
fields = ttype.elems.items()
#elif isinstance(ttype, Contract):
# fields = ttype.variables_as_dict
if(fields == None):
#print(" NO FIELDS")
return
#is an oobject, may have fields
for field_name, field in fields:
#search for type tuple in type file
#print(_ir.function_name)
#print(_ir.name)
# print(field_name)
if(_ir.function_name == None or _ir.name == None or field_name == None):
continue
field_tt = tcheck_parser.get_field(_ir.function_name, _ir.name, field_name)
if(field_tt):
_field_tt = field.extok
copy_token_tuple(field, field_tt)
_ir.add_field(field)
_field_tt.name = _ir.name+'.'+field_name
_field_tt.function_name = _ir.function_name
propagate_fields(field)
_field_tt.name = field_name
#print("FIELDS:")
#_ir.print_fields()
#USAGE: returns the variable with the higher amount of ABSTRACT variables (used in dest propagation)
def greater_abstract(varA, varB):
if(amt_abstract(varA) > amt_abstract(varB)):
return varA
return varB
#USAGE: returns the variable with the fewer amount of ABSTRACT variables
def lesser_abstract(varA, varB):
if(amt_abstract(varA) < amt_abstract(varB)):
return varA
return varB
#USAGE: returns the amount of ABSTRACT types that a certain variable has
def amt_abstract(var):
amt = 0
for n in var.token_typen:
if(n >= abs_buf):
amt+=1
for d in var.token_typed:
if(d >= abs_buf):
amt+=1
return amt
#USAGE: personal copy and sort
def copy_and_sort(types):
ret = []
for i in types:
ret.append(i)
ret.sort()
return(ret)
| 18,575 | Python | .py | 537 | 27.497207 | 108 | 0.57335 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,231 | address_handler.py | NioTheFirst_ScType/slither/detectors/my_detectors/address_handler.py | #Handles address things
#label to normalization
f_type_num = {
-1: "undef",
0: "raw balance",
1: "net balance",
2: "accrued balance",
3: "final balance",
10: "compound fee ratio (t)",
11: "transaction fee",
12: "simple fee ratio",
13: "transaction fee (n)",
14: "transaction fee (d)",
20: "simple interest ratio",
21: "compound interest ratio",
22: "simple interest",
23: "compound interest",
30: "reserve",
40: "price/exchange rate",
50: "debt",
}
num_to_norm = {}
label_sets = {}
label_to_address = {}
address_to_label = {}
global_address_counter = 0
temp_address_counter = -1000
norm_offsets = {}
class Address_label():
def __init__(self, _head):
self._head = _head
self._set = {_head}
self._norm = 'u'
self._finance_type = '*' #Reserve or balance...
@property
def head(self):
return(self._head)
@head.setter
def head(self, x):
self._head = x
@property
def finance_type(self):
return(self._finance_type)
@finance_type.setter
def finance_type(self, x):
self._finance_type = x
@property
def norm(self):
return(self._norm)
@norm.setter
def norm(self, norm):
self._norm = norm
@property
def set(self):
return(self._set)
@set.setter
def set(self, x):
self._set = x
def union(self, a):
#print(f"Head,Norm: {self.head}, {self._norm} {a.head}, {a.norm}")
if(a.head > 0 and self.head > 0 and a.head != self.head):
return False
if(self.norm != '*' and a.norm != '*' and self.norm != 'u' and a.norm != 'u'):
if(self.norm != a.norm):
return False
if(self.head < 0):
if(a.head < 0 and self.head < a.head):
a.head = self.head
a.norm = self.norm
else:
self.head = a.head
self.norm = a.norm
else:
if(a.head < 0 or self.head < a.head):
a.head = self.head
a.norm = self.norm
else:
self.head = a.head
self.norm = a.norm
temp_set = set()
temp_set = temp_set.union(self._set)
temp_set = temp_set.union(a.set)
self._set = temp_set
a.set = temp_set
return True
def __str__(self):
f_type = "NULL"
if(self._finance_type in f_type_num):
f_type = f_type_num[self._finance_type]
return(f"Head Addr: {self._head}\n"
f" Norm: {self._norm}\n"
f" Set: {str(self._set)}\n"
f" Fin: {f_type}")
def get_address_label(func_name, name):
name_key = str(func_name) + ":" + str(name)
if name_key in address_to_label:
return(label_sets[address_to_label[name_key]])
else:
return None
def type_file_new_address(name_key, isGlobal):
global global_address_counter
global temp_address_counter
global label_sets
global label_to_address
global address_to_label
if(name_key in address_to_label):
return(label_sets[address_to_label[name_key]])
else:
upcounter = None
if(isGlobal):
global_address_counter+=1
upcounter = global_address_counter
else:
temp_address_counter+=1
upcounter = temp_address_counter
label = Address_label(upcounter)
label_to_address[upcounter] = name_key
label_sets[upcounter] = label
address_to_label[name_key] = upcounter
#print(f"Add to address_to_label {address_to_label}")
return label
def new_address(ir, isGlobal):
global global_address_counter
global temp_address_counter
global label_sets
global label_to_address
global address_to_label
_ir = ir.extok
if(not(isinstance(_ir.address, int))):
_ir.address = 'u'
#print(f"prev address? {_ir.address}")
if(_ir.address != 'u' and _ir.address != None):
return label_sets[_ir.address]
name_key = str(_ir.function_name)+":"+str(_ir.name)
if(name_key in address_to_label):
_ir.address = address_to_label[name_key]
return label_sets[_ir.address]
#Create new
if(isGlobal):
global_address_counter+=1
#print(f"global assignment: {global_address_counter}")
_ir.address = global_address_counter
else:
temp_address_counter+=1
_ir.address = temp_address_counter
label = Address_label(_ir.address)
label_sets[_ir.address] = label
name_key = str(_ir.function_name)+":"+str(_ir.name)
label_to_address[_ir.address] = name_key
address_to_label[name_key] = _ir.address
#print(_ir.address)
return label
| 4,845 | Python | .py | 152 | 24.144737 | 86 | 0.574784 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,232 | name_reused.py | NioTheFirst_ScType/slither/detectors/slither/name_reused.py | from collections import defaultdict
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
def _find_missing_inheritance(compilation_unit: SlitherCompilationUnit):
"""
Filter contracts with missing inheritance to return only the "most base" contracts
in the inheritance tree.
:param slither:
:return:
"""
missings = compilation_unit.contracts_with_missing_inheritance
ret = []
for b in missings:
is_most_base = True
for inheritance in b.immediate_inheritance:
if inheritance in missings:
is_most_base = False
if is_most_base:
ret.append(b)
return ret
class NameReused(AbstractDetector):
ARGUMENT = "name-reused"
HELP = "Contract's name reused"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#name-reused"
WIKI_TITLE = "Name reused"
# region wiki_description
WIKI_DESCRIPTION = """If a codebase has two contracts the similar names, the compilation artifacts
will not contain one of the contracts with the duplicate name."""
# endregion wiki_description
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
Bob's `truffle` codebase has two contracts named `ERC20`.
When `truffle compile` runs, only one of the two contracts will generate artifacts in `build/contracts`.
As a result, the second contract cannot be analyzed.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Rename the contract."
def _detect(self): # pylint: disable=too-many-locals,too-many-branches
results = []
compilation_unit = self.compilation_unit
all_contracts = compilation_unit.contracts
all_contracts_name = [c.name for c in all_contracts]
contracts_name_reused = {
contract for contract in all_contracts_name if all_contracts_name.count(contract) > 1
}
names_reused = {
name: compilation_unit.get_contract_from_name(name) for name in contracts_name_reused
}
# First show the contracts that we know are missing
incorrectly_constructed = [
contract
for contract in compilation_unit.contracts
if contract.is_incorrectly_constructed
]
inheritance_corrupted = defaultdict(list)
for contract in incorrectly_constructed:
for father in contract.inheritance:
inheritance_corrupted[father.name].append(contract)
for contract_name, files in names_reused.items():
info = [contract_name, " is re-used:\n"]
for file in files:
if file is None:
info += ["\t- In an file not found, most likely in\n"]
else:
info += ["\t- ", file, "\n"]
if contract_name in inheritance_corrupted:
info += ["\tAs a result, the inherited contracts are not correctly analyzed:\n"]
for corrupted in inheritance_corrupted[contract_name]:
info += ["\t\t- ", corrupted, "\n"]
res = self.generate_result(info)
results.append(res)
# Then show the contracts for which one of the father was not found
# Here we are not able to know
most_base_with_missing_inheritance = _find_missing_inheritance(compilation_unit)
for b in most_base_with_missing_inheritance:
info = [b, " inherits from a contract for which the name is reused.\n"]
if b.inheritance:
info += ["\t- Slither could not determine which contract has a duplicate name:\n"]
for inheritance in b.inheritance:
info += ["\t\t-", inheritance, "\n"]
info += ["\t- Check if:\n"]
info += ["\t\t- A inherited contract is missing from this list,\n"]
info += ["\t\t- The contract are imported from the correct files.\n"]
if b.derived_contracts:
info += [f"\t- This issue impacts the contracts inheriting from {b.name}:\n"]
for derived in b.derived_contracts:
info += ["\t\t-", derived, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| 4,462 | Python | .py | 92 | 38.706522 | 104 | 0.641757 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,233 | rtlo.py | NioTheFirst_ScType/slither/detectors/source/rtlo.py | import re
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
# pylint: disable=bidirectional-unicode
class RightToLeftOverride(AbstractDetector):
"""
Detect the usage of a Right-To-Left-Override (U+202E) character
"""
ARGUMENT = "rtlo"
HELP = "Right-To-Left-Override control character is used"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#right-to-left-override-character"
WIKI_TITLE = "Right-to-Left-Override character"
WIKI_DESCRIPTION = "An attacker can manipulate the logic of the contract by using a right-to-left-override character (`U+202E)`."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Token
{
address payable o; // owner
mapping(address => uint) tokens;
function withdraw() external returns(uint)
{
uint amount = tokens[msg.sender];
address payable d = msg.sender;
tokens[msg.sender] = 0;
_withdraw(/*owner/*noitanitsed*/ d, o/*
/*value */, amount);
}
function _withdraw(address payable fee_receiver, address payable destination, uint value) internal
{
fee_receiver.transfer(1);
destination.transfer(value);
}
}
```
`Token` uses the right-to-left-override character when calling `_withdraw`. As a result, the fee is incorrectly sent to `msg.sender`, and the token balance is sent to the owner.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Special control characters must not be allowed."
RTLO_CHARACTER_ENCODED = "\u202e".encode("utf-8")
STANDARD_JSON = False
def _detect(self):
results = []
pattern = re.compile(".*\u202e.*".encode("utf-8"))
for filename, source in self.slither.source_code.items():
# Attempt to find all RTLO characters in this source file.
original_source_encoded = source.encode("utf-8")
start_index = 0
# Keep searching all file contents for the character.
while True:
source_encoded = original_source_encoded[start_index:]
result_index = source_encoded.find(self.RTLO_CHARACTER_ENCODED)
# If we couldn't find the character in the remainder of source, stop.
if result_index == -1:
break
# We found another instance of the character, define our output
idx = start_index + result_index
relative = self.slither.crytic_compile.filename_lookup(filename).relative
info = f"{relative} contains a unicode right-to-left-override character at byte offset {idx}:\n"
# We have a patch, so pattern.find will return at least one result
info += f"\t- {pattern.findall(source_encoded)[0]}\n"
res = self.generate_result(info)
res.add_other(
"rtlo-character",
(filename, idx, len(self.RTLO_CHARACTER_ENCODED)),
self.compilation_unit,
)
results.append(res)
# Advance the start index for the next iteration
start_index = idx + 1
return results
| 3,350 | Python | .py | 72 | 37.208333 | 177 | 0.644943 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,234 | compilation_unit.py | NioTheFirst_ScType/slither/core/compilation_unit.py | import math
from typing import Optional, Dict, List, Set, Union, TYPE_CHECKING, Tuple
from crytic_compile import CompilationUnit, CryticCompile
from crytic_compile.compiler.compiler import CompilerVersion
from crytic_compile.utils.naming import Filename
from slither.core.context.context import Context
from slither.core.declarations import (
Contract,
Pragma,
Import,
Function,
Modifier,
)
from slither.core.declarations.custom_error import CustomError
from slither.core.declarations.enum_top_level import EnumTopLevel
from slither.core.declarations.function_top_level import FunctionTopLevel
from slither.core.declarations.using_for_top_level import UsingForTopLevel
from slither.core.declarations.structure_top_level import StructureTopLevel
from slither.core.solidity_types.type_alias import TypeAliasTopLevel
from slither.core.scope.scope import FileScope
from slither.core.variables.state_variable import StateVariable
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.slithir.operations import InternalCall
from slither.slithir.variables import Constant
if TYPE_CHECKING:
from slither.core.slither_core import SlitherCore
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class SlitherCompilationUnit(Context):
def __init__(self, core: "SlitherCore", crytic_compilation_unit: CompilationUnit):
super().__init__()
self._core = core
self._crytic_compile_compilation_unit = crytic_compilation_unit
# Top level object
self.contracts: List[Contract] = []
self._structures_top_level: List[StructureTopLevel] = []
self._enums_top_level: List[EnumTopLevel] = []
self._variables_top_level: List[TopLevelVariable] = []
self._functions_top_level: List[FunctionTopLevel] = []
self._using_for_top_level: List[UsingForTopLevel] = []
self._pragma_directives: List[Pragma] = []
self._import_directives: List[Import] = []
self._custom_errors: List[CustomError] = []
self._user_defined_value_types: Dict[str, TypeAliasTopLevel] = {}
self._all_functions: Set[Function] = set()
self._all_modifiers: Set[Modifier] = set()
# Memoize
self._all_state_variables: Optional[Set[StateVariable]] = None
self._storage_layouts: Dict[str, Dict[str, Tuple[int, int]]] = {}
self._contract_with_missing_inheritance = set()
self._source_units: Dict[int, str] = {}
self.counter_slithir_tuple = 0
self.counter_slithir_temporary = 0
self.counter_slithir_reference = 0
self.scopes: Dict[Filename, FileScope] = {}
@property
def core(self) -> "SlitherCore":
return self._core
@property
def source_units(self) -> Dict[int, str]:
return self._source_units
# endregion
###################################################################################
###################################################################################
# region Compiler
###################################################################################
###################################################################################
@property
def compiler_version(self) -> CompilerVersion:
return self._crytic_compile_compilation_unit.compiler_version
@property
def solc_version(self) -> str:
return self._crytic_compile_compilation_unit.compiler_version.version
@property
def crytic_compile_compilation_unit(self) -> CompilationUnit:
return self._crytic_compile_compilation_unit
@property
def crytic_compile(self) -> CryticCompile:
return self._crytic_compile_compilation_unit.crytic_compile
# endregion
###################################################################################
###################################################################################
# region Pragma attributes
###################################################################################
###################################################################################
@property
def pragma_directives(self) -> List[Pragma]:
"""list(core.declarations.Pragma): Pragma directives."""
return self._pragma_directives
@property
def import_directives(self) -> List[Import]:
"""list(core.declarations.Import): Import directives"""
return self._import_directives
# endregion
###################################################################################
###################################################################################
# region Contracts
###################################################################################
###################################################################################
@property
def contracts_derived(self) -> List[Contract]:
"""list(Contract): List of contracts that are derived and not inherited."""
inheritances = [x.inheritance for x in self.contracts]
inheritance = [item for sublist in inheritances for item in sublist]
return [c for c in self.contracts if c not in inheritance and not c.is_top_level]
def get_contract_from_name(self, contract_name: Union[str, Constant]) -> List[Contract]:
"""
Return a list of contract from a name
Args:
contract_name (str): name of the contract
Returns:
List[Contract]
"""
return [c for c in self.contracts if c.name == contract_name]
# endregion
###################################################################################
###################################################################################
# region Functions and modifiers
###################################################################################
###################################################################################
@property
def functions(self) -> List[Function]:
return list(self._all_functions)
def add_function(self, func: Function):
self._all_functions.add(func)
@property
def modifiers(self) -> List[Modifier]:
return list(self._all_modifiers)
def add_modifier(self, modif: Modifier):
self._all_modifiers.add(modif)
@property
def functions_and_modifiers(self) -> List[Function]:
return self.functions + self.modifiers
def propagate_function_calls(self):
for f in self.functions_and_modifiers:
for node in f.nodes:
for ir in node.irs_ssa:
if isinstance(ir, InternalCall):
ir.function.add_reachable_from_node(node, ir)
# endregion
###################################################################################
###################################################################################
# region Variables
###################################################################################
###################################################################################
@property
def state_variables(self) -> List[StateVariable]:
if self._all_state_variables is None:
state_variables = [c.state_variables for c in self.contracts]
state_variables = [item for sublist in state_variables for item in sublist]
self._all_state_variables = set(state_variables)
return list(self._all_state_variables)
# endregion
###################################################################################
###################################################################################
# region Top level
###################################################################################
###################################################################################
@property
def structures_top_level(self) -> List[StructureTopLevel]:
return self._structures_top_level
@property
def enums_top_level(self) -> List[EnumTopLevel]:
return self._enums_top_level
@property
def variables_top_level(self) -> List[TopLevelVariable]:
return self._variables_top_level
@property
def functions_top_level(self) -> List[FunctionTopLevel]:
return self._functions_top_level
@property
def using_for_top_level(self) -> List[UsingForTopLevel]:
return self._using_for_top_level
@property
def custom_errors(self) -> List[CustomError]:
return self._custom_errors
@property
def user_defined_value_types(self) -> Dict[str, TypeAliasTopLevel]:
return self._user_defined_value_types
# endregion
###################################################################################
###################################################################################
# region Internals
###################################################################################
###################################################################################
@property
def contracts_with_missing_inheritance(self) -> Set:
return self._contract_with_missing_inheritance
# endregion
###################################################################################
###################################################################################
# region Scope
###################################################################################
###################################################################################
def get_scope(self, filename_str: str) -> FileScope:
filename = self._crytic_compile_compilation_unit.crytic_compile.filename_lookup(
filename_str
)
if filename not in self.scopes:
self.scopes[filename] = FileScope(filename)
return self.scopes[filename]
# endregion
###################################################################################
###################################################################################
# region Storage Layouts
###################################################################################
###################################################################################
def compute_storage_layout(self):
for contract in self.contracts_derived:
self._storage_layouts[contract.name] = {}
slot = 0
offset = 0
for var in contract.state_variables_ordered:
if var.is_constant or var.is_immutable:
continue
size, new_slot = var.type.storage_size
if new_slot:
if offset > 0:
slot += 1
offset = 0
elif size + offset > 32:
slot += 1
offset = 0
self._storage_layouts[contract.name][var.canonical_name] = (
slot,
offset,
)
if new_slot:
slot += math.ceil(size / 32)
else:
offset += size
def storage_layout_of(self, contract, var) -> Tuple[int, int]:
return self._storage_layouts[contract.name][var.canonical_name]
# endregion
| 11,463 | Python | .py | 233 | 41.407725 | 92 | 0.476996 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,235 | slither_core.py | NioTheFirst_ScType/slither/core/slither_core.py | """
Main module
"""
import json
import logging
import os
import pathlib
import posixpath
import re
from collections import defaultdict
from typing import Optional, Dict, List, Set, Union
from crytic_compile import CryticCompile
from crytic_compile.utils.naming import Filename
from slither.core.children.child_contract import ChildContract
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.context.context import Context
from slither.core.declarations import Contract, FunctionContract
from slither.core.declarations.top_level import TopLevel
from slither.core.source_mapping.source_mapping import SourceMapping, Source
from slither.slithir.variables import Constant
from slither.utils.colors import red
from slither.utils.source_mapping import get_definition, get_references, get_implementation
logger = logging.getLogger("Slither")
logging.basicConfig()
def _relative_path_format(path: str) -> str:
"""
Strip relative paths of "." and ".."
"""
return path.split("..")[-1].strip(".").strip("/")
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class SlitherCore(Context):
"""
Slither static analyzer
"""
def __init__(self):
super().__init__()
self._filename: Optional[str] = None
self._raw_source_code: Dict[str, str] = {}
self._source_code_to_line: Optional[Dict[str, List[str]]] = None
self._previous_results_filename: str = "slither.db.json"
self._results_to_hide: List = []
self._previous_results: List = []
# From triaged result
self._previous_results_ids: Set[str] = set()
# Every slither object has a list of result from detector
# Because of the multiple compilation support, we might analyze
# Multiple time the same result, so we remove duplicates
self._currently_seen_resuts: Set[str] = set()
self._paths_to_filter: Set[str] = set()
self._crytic_compile: Optional[CryticCompile] = None
self._generate_patches = False
self._exclude_dependencies = False
self._markdown_root = ""
# If set to true, slither will not catch errors during parsing
self._disallow_partial: bool = False
self._skip_assembly: bool = False
self._show_ignored_findings = False
# Maps from file to detector name to the start/end ranges for that detector.
# Infinity is used to signal a detector has no end range.
self._ignore_ranges: defaultdict[str, defaultdict[str, List[(int, int)]]] = defaultdict(
lambda: defaultdict(lambda: [])
)
self._compilation_units: List[SlitherCompilationUnit] = []
self._contracts: List[Contract] = []
self._contracts_derived: List[Contract] = []
self._offset_to_objects: Optional[Dict[Filename, Dict[int, Set[SourceMapping]]]] = None
self._offset_to_references: Optional[Dict[Filename, Dict[int, Set[Source]]]] = None
self._offset_to_implementations: Optional[Dict[Filename, Dict[int, Set[Source]]]] = None
self._offset_to_definitions: Optional[Dict[Filename, Dict[int, Set[Source]]]] = None
# Line prefix is used during the source mapping generation
# By default we generate file.sol#1
# But we allow to alter this (ex: file.sol:1) for vscode integration
self.line_prefix: str = "#"
# Use by the echidna printer
# If true, partial analysis is allowed
self.no_fail = False
@property
def compilation_units(self) -> List[SlitherCompilationUnit]:
return list(self._compilation_units)
def add_compilation_unit(self, compilation_unit: SlitherCompilationUnit):
self._compilation_units.append(compilation_unit)
# endregion
###################################################################################
###################################################################################
# region Contracts
###################################################################################
###################################################################################
@property
def contracts(self) -> List[Contract]:
if not self._contracts:
all_contracts = [
compilation_unit.contracts for compilation_unit in self._compilation_units
]
self._contracts = [item for sublist in all_contracts for item in sublist]
return self._contracts
@property
def contracts_derived(self) -> List[Contract]:
if not self._contracts_derived:
all_contracts = [
compilation_unit.contracts_derived for compilation_unit in self._compilation_units
]
self._contracts_derived = [item for sublist in all_contracts for item in sublist]
return self._contracts_derived
def get_contract_from_name(self, contract_name: Union[str, Constant]) -> List[Contract]:
"""
Return a contract from a name
Args:
contract_name (str): name of the contract
Returns:
Contract
"""
contracts = []
for compilation_unit in self._compilation_units:
contracts += compilation_unit.get_contract_from_name(contract_name)
return contracts
###################################################################################
###################################################################################
# region Source code
###################################################################################
###################################################################################
@property
def source_code(self) -> Dict[str, str]:
"""{filename: source_code (str)}: source code"""
return self._raw_source_code
@property
def filename(self) -> Optional[str]:
"""str: Filename."""
return self._filename
@filename.setter
def filename(self, filename: str):
self._filename = filename
def add_source_code(self, path: str) -> None:
"""
:param path:
:return:
"""
if self.crytic_compile and path in self.crytic_compile.src_content:
self.source_code[path] = self.crytic_compile.src_content[path]
else:
with open(path, encoding="utf8", newline="") as f:
self.source_code[path] = f.read()
self.parse_ignore_comments(path)
@property
def markdown_root(self) -> str:
return self._markdown_root
def print_functions(self, d: str):
"""
Export all the functions to dot files
"""
for compilation_unit in self._compilation_units:
for c in compilation_unit.contracts:
for f in c.functions:
f.cfg_to_dot(os.path.join(d, f"{c.name}.{f.name}.dot"))
def offset_to_objects(self, filename_str: str, offset: int) -> Set[SourceMapping]:
if self._offset_to_objects is None:
self._compute_offsets_to_ref_impl_decl()
filename: Filename = self.crytic_compile.filename_lookup(filename_str)
return self._offset_to_objects[filename][offset]
def _compute_offsets_from_thing(self, thing: SourceMapping):
definition = get_definition(thing, self.crytic_compile)
references = get_references(thing)
implementation = get_implementation(thing)
for offset in range(definition.start, definition.end + 1):
if (
isinstance(thing, TopLevel)
or (
isinstance(thing, FunctionContract)
and thing.contract_declarer == thing.contract
)
or (isinstance(thing, ChildContract) and not isinstance(thing, FunctionContract))
):
self._offset_to_objects[definition.filename][offset].add(thing)
self._offset_to_definitions[definition.filename][offset].add(definition)
self._offset_to_implementations[definition.filename][offset].add(implementation)
self._offset_to_references[definition.filename][offset] |= set(references)
for ref in references:
for offset in range(ref.start, ref.end + 1):
if (
isinstance(thing, TopLevel)
or (
isinstance(thing, FunctionContract)
and thing.contract_declarer == thing.contract
)
or (
isinstance(thing, ChildContract) and not isinstance(thing, FunctionContract)
)
):
self._offset_to_objects[definition.filename][offset].add(thing)
self._offset_to_definitions[ref.filename][offset].add(definition)
self._offset_to_implementations[ref.filename][offset].add(implementation)
self._offset_to_references[ref.filename][offset] |= set(references)
def _compute_offsets_to_ref_impl_decl(self): # pylint: disable=too-many-branches
self._offset_to_references = defaultdict(lambda: defaultdict(lambda: set()))
self._offset_to_definitions = defaultdict(lambda: defaultdict(lambda: set()))
self._offset_to_implementations = defaultdict(lambda: defaultdict(lambda: set()))
self._offset_to_objects = defaultdict(lambda: defaultdict(lambda: set()))
for compilation_unit in self._compilation_units:
for contract in compilation_unit.contracts:
self._compute_offsets_from_thing(contract)
for function in contract.functions:
self._compute_offsets_from_thing(function)
for variable in function.local_variables:
self._compute_offsets_from_thing(variable)
for modifier in contract.modifiers:
self._compute_offsets_from_thing(modifier)
for variable in modifier.local_variables:
self._compute_offsets_from_thing(variable)
for st in contract.structures:
self._compute_offsets_from_thing(st)
for enum in contract.enums:
self._compute_offsets_from_thing(enum)
for event in contract.events:
self._compute_offsets_from_thing(event)
for enum in compilation_unit.enums_top_level:
self._compute_offsets_from_thing(enum)
for function in compilation_unit.functions_top_level:
self._compute_offsets_from_thing(function)
for st in compilation_unit.structures_top_level:
self._compute_offsets_from_thing(st)
for import_directive in compilation_unit.import_directives:
self._compute_offsets_from_thing(import_directive)
for pragma in compilation_unit.pragma_directives:
self._compute_offsets_from_thing(pragma)
def offset_to_references(self, filename_str: str, offset: int) -> Set[Source]:
if self._offset_to_references is None:
self._compute_offsets_to_ref_impl_decl()
filename: Filename = self.crytic_compile.filename_lookup(filename_str)
return self._offset_to_references[filename][offset]
def offset_to_implementations(self, filename_str: str, offset: int) -> Set[Source]:
if self._offset_to_implementations is None:
self._compute_offsets_to_ref_impl_decl()
filename: Filename = self.crytic_compile.filename_lookup(filename_str)
return self._offset_to_implementations[filename][offset]
def offset_to_definitions(self, filename_str: str, offset: int) -> Set[Source]:
if self._offset_to_definitions is None:
self._compute_offsets_to_ref_impl_decl()
filename: Filename = self.crytic_compile.filename_lookup(filename_str)
return self._offset_to_definitions[filename][offset]
# endregion
###################################################################################
###################################################################################
# region Filtering results
###################################################################################
###################################################################################
def parse_ignore_comments(self, file: str) -> None:
# The first time we check a file, find all start/end ignore comments and memoize them.
line_number = 1
while True:
line_text = self.crytic_compile.get_code_from_line(file, line_number)
if line_text is None:
break
start_regex = r"^\s*//\s*slither-disable-start\s*([a-zA-Z0-9_,-]*)"
end_regex = r"^\s*//\s*slither-disable-end\s*([a-zA-Z0-9_,-]*)"
start_match = re.findall(start_regex, line_text.decode("utf8"))
end_match = re.findall(end_regex, line_text.decode("utf8"))
if start_match:
ignored = start_match[0].split(",")
if ignored:
for check in ignored:
vals = self._ignore_ranges[file][check]
if len(vals) == 0 or vals[-1][1] != float("inf"):
# First item in the array, or the prior item is fully populated.
self._ignore_ranges[file][check].append((line_number, float("inf")))
else:
logger.error(
f"Consecutive slither-disable-starts without slither-disable-end in {file}#{line_number}"
)
return
if end_match:
ignored = end_match[0].split(",")
if ignored:
for check in ignored:
vals = self._ignore_ranges[file][check]
if len(vals) == 0 or vals[-1][1] != float("inf"):
logger.error(
f"slither-disable-end without slither-disable-start in {file}#{line_number}"
)
return
self._ignore_ranges[file][check][-1] = (vals[-1][0], line_number)
line_number += 1
def has_ignore_comment(self, r: Dict) -> bool:
"""
Check if the result has an ignore comment in the file or on the preceding line, in which
case, it is not valid
"""
if not self.crytic_compile:
return False
mapping_elements_with_lines = (
(
posixpath.normpath(elem["source_mapping"]["filename_absolute"]),
elem["source_mapping"]["lines"],
)
for elem in r["elements"]
if "source_mapping" in elem
and "filename_absolute" in elem["source_mapping"]
and "lines" in elem["source_mapping"]
and len(elem["source_mapping"]["lines"]) > 0
)
for file, lines in mapping_elements_with_lines:
# Check if result is within an ignored range.
ignore_ranges = self._ignore_ranges[file][r["check"]] + self._ignore_ranges[file]["all"]
for start, end in ignore_ranges:
# The full check must be within the ignore range to be ignored.
if start < lines[0] and end > lines[-1]:
return True
# Check for next-line matchers.
ignore_line_index = min(lines) - 1
ignore_line_text = self.crytic_compile.get_code_from_line(file, ignore_line_index)
if ignore_line_text:
match = re.findall(
r"^\s*//\s*slither-disable-next-line\s*([a-zA-Z0-9_,-]*)",
ignore_line_text.decode("utf8"),
)
if match:
ignored = match[0].split(",")
if ignored and ("all" in ignored or any(r["check"] == c for c in ignored)):
return True
return False
def valid_result(self, r: Dict) -> bool:
"""
Check if the result is valid
A result is invalid if:
- All its source paths belong to the source path filtered
- Or a similar result was reported and saved during a previous run
- The --exclude-dependencies flag is set and results are only related to dependencies
- There is an ignore comment on the preceding line or in the file
"""
# Remove duplicate due to the multiple compilation support
if r["id"] in self._currently_seen_resuts:
return False
self._currently_seen_resuts.add(r["id"])
source_mapping_elements = [
elem["source_mapping"].get("filename_absolute", "unknown")
for elem in r["elements"]
if "source_mapping" in elem
]
# Use POSIX-style paths so that filter_paths works across different
# OSes. Convert to a list so elements don't get consumed and are lost
# while evaluating the first pattern
source_mapping_elements = list(
map(lambda x: pathlib.Path(x).resolve().as_posix() if x else x, source_mapping_elements)
)
matching = False
for path in self._paths_to_filter:
try:
if any(
bool(re.search(_relative_path_format(path), src_mapping))
for src_mapping in source_mapping_elements
):
matching = True
break
except re.error:
logger.error(
f"Incorrect regular expression for --filter-paths {path}."
"\nSlither supports the Python re format"
": https://docs.python.org/3/library/re.html"
)
if r["elements"] and matching:
return False
if self._show_ignored_findings:
return True
if self.has_ignore_comment(r):
return False
if r["id"] in self._previous_results_ids:
return False
if r["elements"] and self._exclude_dependencies:
if all(element["source_mapping"]["is_dependency"] for element in r["elements"]):
return False
# Conserve previous result filtering. This is conserved for compatibility, but is meant to be removed
if r["description"] in [pr["description"] for pr in self._previous_results]:
return False
return True
def load_previous_results(self):
filename = self._previous_results_filename
try:
if os.path.isfile(filename):
with open(filename, encoding="utf8") as f:
self._previous_results = json.load(f)
if self._previous_results:
for r in self._previous_results:
if "id" in r:
self._previous_results_ids.add(r["id"])
except json.decoder.JSONDecodeError:
logger.error(red(f"Impossible to decode {filename}. Consider removing the file"))
def write_results_to_hide(self):
if not self._results_to_hide:
return
filename = self._previous_results_filename
with open(filename, "w", encoding="utf8") as f:
results = self._results_to_hide + self._previous_results
json.dump(results, f)
def save_results_to_hide(self, results: List[Dict]):
self._results_to_hide += results
def add_path_to_filter(self, path: str):
"""
Add path to filter
Path are used through direct comparison (no regex)
"""
self._paths_to_filter.add(path)
# endregion
###################################################################################
###################################################################################
# region Crytic compile
###################################################################################
###################################################################################
@property
def crytic_compile(self) -> Optional[CryticCompile]:
return self._crytic_compile
# endregion
###################################################################################
###################################################################################
# region Format
###################################################################################
###################################################################################
@property
def generate_patches(self) -> bool:
return self._generate_patches
@generate_patches.setter
def generate_patches(self, p: bool):
self._generate_patches = p
# endregion
###################################################################################
###################################################################################
# region Internals
###################################################################################
###################################################################################
@property
def disallow_partial(self) -> bool:
"""
Return true if partial analyses are disallowed
For example, codebase with duplicate names will lead to partial analyses
:return:
"""
return self._disallow_partial
@property
def skip_assembly(self) -> bool:
return self._skip_assembly
@property
def show_ignore_findings(self) -> bool:
return self._show_ignored_findings
# endregion
| 21,965 | Python | .py | 441 | 38.496599 | 121 | 0.544712 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,236 | scope.py | NioTheFirst_ScType/slither/core/scope/scope.py | from typing import List, Any, Dict, Optional, Union, Set, TypeVar, Callable
from crytic_compile import CompilationUnit
from crytic_compile.source_unit import SourceUnit
from crytic_compile.utils.naming import Filename
from slither.core.declarations import Contract, Import, Pragma
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.using_for_top_level import UsingForTopLevel
from slither.core.declarations.structure_top_level import StructureTopLevel
from slither.core.solidity_types import TypeAlias
from slither.core.variables.top_level_variable import TopLevelVariable
from slither.slithir.variables import Constant
def _dict_contain(d1: Dict, d2: Dict) -> bool:
"""
Return true if d1 is included in d2
"""
d2_keys = d2.keys()
return all(item in d2_keys for item in d1.keys())
# pylint: disable=too-many-instance-attributes
class FileScope:
def __init__(self, filename: Filename):
self.filename = filename
self.accessible_scopes: List[FileScope] = []
self.contracts: Dict[str, Contract] = {}
# Custom error are a list instead of a dict
# Because we parse the function signature later on
# So we simplify the logic and have the scope fields all populated
self.custom_errors: Set[CustomErrorTopLevel] = set()
self.enums: Dict[str, EnumTopLevel] = {}
# Functions is a list instead of a dict
# Because we parse the function signature later on
# So we simplify the logic and have the scope fields all populated
self.functions: Set[FunctionTopLevel] = set()
self.using_for_directives: Set[UsingForTopLevel] = set()
self.imports: Set[Import] = set()
self.pragmas: Set[Pragma] = set()
self.structures: Dict[str, StructureTopLevel] = {}
self.variables: Dict[str, TopLevelVariable] = {}
# Renamed created by import
# import A as B
# local name -> original name (A -> B)
self.renaming: Dict[str, str] = {}
# User defined types
# Name -> type alias
self.user_defined_types: Dict[str, TypeAlias] = {}
def add_accesible_scopes(self) -> bool:
"""
Add information from accessible scopes. Return true if new information was obtained
:return:
:rtype:
"""
learn_something = False
for new_scope in self.accessible_scopes:
if not _dict_contain(new_scope.contracts, self.contracts):
self.contracts.update(new_scope.contracts)
learn_something = True
if not new_scope.custom_errors.issubset(self.custom_errors):
self.custom_errors |= new_scope.custom_errors
learn_something = True
if not _dict_contain(new_scope.enums, self.enums):
self.enums.update(new_scope.enums)
learn_something = True
if not new_scope.functions.issubset(self.functions):
self.functions |= new_scope.functions
learn_something = True
if not new_scope.using_for_directives.issubset(self.using_for_directives):
self.using_for_directives |= new_scope.using_for_directives
learn_something = True
if not new_scope.imports.issubset(self.imports):
self.imports |= new_scope.imports
learn_something = True
if not new_scope.pragmas.issubset(self.pragmas):
self.pragmas |= new_scope.pragmas
learn_something = True
if not _dict_contain(new_scope.structures, self.structures):
self.structures.update(new_scope.structures)
learn_something = True
if not _dict_contain(new_scope.variables, self.variables):
self.variables.update(new_scope.variables)
learn_something = True
if not _dict_contain(new_scope.renaming, self.renaming):
self.renaming.update(new_scope.renaming)
learn_something = True
if not _dict_contain(new_scope.user_defined_types, self.user_defined_types):
self.user_defined_types.update(new_scope.user_defined_types)
learn_something = True
return learn_something
def get_contract_from_name(self, name: Union[str, Constant]) -> Optional[Contract]:
if isinstance(name, Constant):
return self.contracts.get(name.name, None)
return self.contracts.get(name, None)
AbstractReturnType = TypeVar("AbstractReturnType")
def _generic_source_unit_getter(
self,
crytic_compile_compilation_unit: CompilationUnit,
name: str,
getter: Callable[[SourceUnit], Dict[str, AbstractReturnType]],
) -> Optional[AbstractReturnType]:
assert self.filename in crytic_compile_compilation_unit.source_units
source_unit = crytic_compile_compilation_unit.source_unit(self.filename)
if name in getter(source_unit):
return getter(source_unit)[name]
for scope in self.accessible_scopes:
source_unit = crytic_compile_compilation_unit.source_unit(scope.filename)
if name in getter(source_unit):
return getter(source_unit)[name]
return None
def bytecode_init(
self, crytic_compile_compilation_unit: CompilationUnit, contract_name: str
) -> Optional[str]:
"""
Return the init bytecode
Args:
crytic_compile_compilation_unit:
contract_name:
Returns:
"""
getter: Callable[[SourceUnit], Dict[str, str]] = lambda x: x.bytecodes_init
return self._generic_source_unit_getter(
crytic_compile_compilation_unit, contract_name, getter
)
def bytecode_runtime(
self, crytic_compile_compilation_unit: CompilationUnit, contract_name: str
) -> Optional[str]:
"""
Return the runtime bytecode
Args:
crytic_compile_compilation_unit:
contract_name:
Returns:
"""
getter: Callable[[SourceUnit], Dict[str, str]] = lambda x: x.bytecodes_runtime
return self._generic_source_unit_getter(
crytic_compile_compilation_unit, contract_name, getter
)
def srcmap_init(
self, crytic_compile_compilation_unit: CompilationUnit, contract_name: str
) -> Optional[List[str]]:
"""
Return the init scrmap
Args:
crytic_compile_compilation_unit:
contract_name:
Returns:
"""
getter: Callable[[SourceUnit], Dict[str, List[str]]] = lambda x: x.srcmaps_init
return self._generic_source_unit_getter(
crytic_compile_compilation_unit, contract_name, getter
)
def srcmap_runtime(
self, crytic_compile_compilation_unit: CompilationUnit, contract_name: str
) -> Optional[List[str]]:
"""
Return the runtime srcmap
Args:
crytic_compile_compilation_unit:
contract_name:
Returns:
"""
getter: Callable[[SourceUnit], Dict[str, List[str]]] = lambda x: x.srcmaps_runtime
return self._generic_source_unit_getter(
crytic_compile_compilation_unit, contract_name, getter
)
def abi(self, crytic_compile_compilation_unit: CompilationUnit, contract_name: str) -> Any:
"""
Return the abi
Args:
crytic_compile_compilation_unit:
contract_name:
Returns:
"""
getter: Callable[[SourceUnit], Dict[str, List[str]]] = lambda x: x.abis
return self._generic_source_unit_getter(
crytic_compile_compilation_unit, contract_name, getter
)
# region Built in definitions
###################################################################################
###################################################################################
def __eq__(self, other: Any) -> bool:
if isinstance(other, str):
return other == self.filename
return NotImplemented
def __neq__(self, other: Any) -> bool:
if isinstance(other, str):
return other != self.filename
return NotImplemented
def __str__(self) -> str:
return str(self.filename.relative)
def __hash__(self) -> int:
return hash(self.filename.relative)
# endregion
| 8,693 | Python | .py | 192 | 35.651042 | 95 | 0.630664 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,237 | utils.py | NioTheFirst_ScType/slither/core/dominators/utils.py | from typing import List, TYPE_CHECKING
from slither.core.cfg.node import NodeType
if TYPE_CHECKING:
from slither.core.cfg.node import Node
def intersection_predecessor(node: "Node"):
if not node.fathers:
return set()
ret = node.fathers[0].dominators
for pred in node.fathers[1:]:
ret = ret.intersection(pred.dominators)
return ret
def _compute_dominators(nodes: List["Node"]):
changed = True
while changed:
changed = False
for node in nodes:
new_set = intersection_predecessor(node).union({node})
if new_set != node.dominators:
node.dominators = new_set
changed = True
def _compute_immediate_dominators(nodes: List["Node"]):
for node in nodes:
idom_candidates = set(node.dominators)
idom_candidates.remove(node)
if len(idom_candidates) == 1:
idom = idom_candidates.pop()
node.immediate_dominator = idom
idom.dominator_successors.add(node)
continue
# all_dominators contain all the dominators of all the node's dominators
# But self inclusion is removed
# The idom is then the only node that in idom_candidate that is not in all_dominators
all_dominators = set()
for d in idom_candidates:
# optimization: if a node is already in all_dominators, then
# its dominators are already in too
if d in all_dominators:
continue
all_dominators |= d.dominators - {d}
idom_candidates = all_dominators.symmetric_difference(idom_candidates)
assert len(idom_candidates) <= 1
if idom_candidates:
idom = idom_candidates.pop()
node.immediate_dominator = idom
idom.dominator_successors.add(node)
def compute_dominators(nodes: List["Node"]):
"""
Naive implementation of Cooper, Harvey, Kennedy algo
See 'A Simple,Fast Dominance Algorithm'
Compute strict domniators
"""
for n in nodes:
n.dominators = set(nodes)
_compute_dominators(nodes)
_compute_immediate_dominators(nodes)
def compute_dominance_frontier(nodes: List["Node"]):
"""
Naive implementation of Cooper, Harvey, Kennedy algo
See 'A Simple,Fast Dominance Algorithm'
Compute dominance frontier
"""
for node in nodes:
if len(node.fathers) >= 2:
for father in node.fathers:
runner = father
# Corner case: if there is a if without else
# we need to add update the conditional node
if (
runner == node.immediate_dominator
and runner.type == NodeType.IF
and node.type == NodeType.ENDIF
):
runner.dominance_frontier = runner.dominance_frontier.union({node})
while runner != node.immediate_dominator:
runner.dominance_frontier = runner.dominance_frontier.union({node})
runner = runner.immediate_dominator
| 3,113 | Python | .py | 76 | 31.039474 | 93 | 0.623881 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,238 | node_dominator_tree.py | NioTheFirst_ScType/slither/core/dominators/node_dominator_tree.py | """
Nodes of the dominator tree
"""
from typing import TYPE_CHECKING, Set, List
if TYPE_CHECKING:
from slither.core.cfg.node import Node
class DominatorNode:
def __init__(self):
self._succ: Set["Node"] = set()
self._nodes: List["Node"] = []
def add_node(self, node: "Node"):
self._nodes.append(node)
def add_successor(self, succ: "Node"):
self._succ.add(succ)
@property
def cfg_nodes(self) -> List["Node"]:
return self._nodes
@property
def sucessors(self) -> Set["Node"]:
return self._succ
| 581 | Python | .py | 20 | 23.5 | 43 | 0.617329 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,239 | context.py | NioTheFirst_ScType/slither/core/context/context.py | from collections import defaultdict
from typing import Dict
class Context: # pylint: disable=too-few-public-methods
def __init__(self) -> None:
super().__init__()
self._context: Dict = {"MEMBERS": defaultdict(None)}
@property
def context(self) -> Dict:
"""
Dict used by analysis
"""
return self._context
| 368 | Python | .py | 12 | 24.416667 | 60 | 0.617564 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,240 | super_identifier.py | NioTheFirst_ScType/slither/core/expressions/super_identifier.py | from slither.core.expressions.identifier import Identifier
class SuperIdentifier(Identifier):
def __str__(self):
return "super." + str(self._value)
| 162 | Python | .py | 4 | 36 | 58 | 0.737179 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,241 | binary_operation.py | NioTheFirst_ScType/slither/core/expressions/binary_operation.py | import logging
from enum import Enum
from typing import List
from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression
from slither.core.exceptions import SlitherCoreError
logger = logging.getLogger("BinaryOperation")
class BinaryOperationType(Enum):
POWER = 0 # **
MULTIPLICATION = 1 # *
DIVISION = 2 # /
MODULO = 3 # %
ADDITION = 4 # +
SUBTRACTION = 5 # -
LEFT_SHIFT = 6 # <<
RIGHT_SHIFT = 7 # >>>
AND = 8 # &
CARET = 9 # ^
OR = 10 # |
LESS = 11 # <
GREATER = 12 # >
LESS_EQUAL = 13 # <=
GREATER_EQUAL = 14 # >=
EQUAL = 15 # ==
NOT_EQUAL = 16 # !=
ANDAND = 17 # &&
OROR = 18 # ||
# YUL specific operators
# TODO: investigate if we can remove these
# Find the types earlier on, and do the conversion
DIVISION_SIGNED = 19
MODULO_SIGNED = 20
LESS_SIGNED = 21
GREATER_SIGNED = 22
RIGHT_SHIFT_ARITHMETIC = 23
# pylint: disable=too-many-branches
@staticmethod
def get_type(
operation_type: "BinaryOperation",
) -> "BinaryOperationType":
if operation_type == "**":
return BinaryOperationType.POWER
if operation_type == "*":
return BinaryOperationType.MULTIPLICATION
if operation_type == "/":
return BinaryOperationType.DIVISION
if operation_type == "%":
return BinaryOperationType.MODULO
if operation_type == "+":
return BinaryOperationType.ADDITION
if operation_type == "-":
return BinaryOperationType.SUBTRACTION
if operation_type == "<<":
return BinaryOperationType.LEFT_SHIFT
if operation_type == ">>":
return BinaryOperationType.RIGHT_SHIFT
if operation_type == "&":
return BinaryOperationType.AND
if operation_type == "^":
return BinaryOperationType.CARET
if operation_type == "|":
return BinaryOperationType.OR
if operation_type == "<":
return BinaryOperationType.LESS
if operation_type == ">":
return BinaryOperationType.GREATER
if operation_type == "<=":
return BinaryOperationType.LESS_EQUAL
if operation_type == ">=":
return BinaryOperationType.GREATER_EQUAL
if operation_type == "==":
return BinaryOperationType.EQUAL
if operation_type == "!=":
return BinaryOperationType.NOT_EQUAL
if operation_type == "&&":
return BinaryOperationType.ANDAND
if operation_type == "||":
return BinaryOperationType.OROR
if operation_type == "/'":
return BinaryOperationType.DIVISION_SIGNED
if operation_type == "%'":
return BinaryOperationType.MODULO_SIGNED
if operation_type == "<'":
return BinaryOperationType.LESS_SIGNED
if operation_type == ">'":
return BinaryOperationType.GREATER_SIGNED
if operation_type == ">>'":
return BinaryOperationType.RIGHT_SHIFT_ARITHMETIC
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type})")
def __str__(self) -> str: # pylint: disable=too-many-branches
if self == BinaryOperationType.POWER:
return "**"
if self == BinaryOperationType.MULTIPLICATION:
return "*"
if self == BinaryOperationType.DIVISION:
return "/"
if self == BinaryOperationType.MODULO:
return "%"
if self == BinaryOperationType.ADDITION:
return "+"
if self == BinaryOperationType.SUBTRACTION:
return "-"
if self == BinaryOperationType.LEFT_SHIFT:
return "<<"
if self == BinaryOperationType.RIGHT_SHIFT:
return ">>"
if self == BinaryOperationType.AND:
return "&"
if self == BinaryOperationType.CARET:
return "^"
if self == BinaryOperationType.OR:
return "|"
if self == BinaryOperationType.LESS:
return "<"
if self == BinaryOperationType.GREATER:
return ">"
if self == BinaryOperationType.LESS_EQUAL:
return "<="
if self == BinaryOperationType.GREATER_EQUAL:
return ">="
if self == BinaryOperationType.EQUAL:
return "=="
if self == BinaryOperationType.NOT_EQUAL:
return "!="
if self == BinaryOperationType.ANDAND:
return "&&"
if self == BinaryOperationType.OROR:
return "||"
if self == BinaryOperationType.DIVISION_SIGNED:
return "/'"
if self == BinaryOperationType.MODULO_SIGNED:
return "%'"
if self == BinaryOperationType.LESS_SIGNED:
return "<'"
if self == BinaryOperationType.GREATER_SIGNED:
return ">'"
if self == BinaryOperationType.RIGHT_SHIFT_ARITHMETIC:
return ">>'"
raise SlitherCoreError(f"str: Unknown operation type {self})")
class BinaryOperation(ExpressionTyped):
def __init__(
self,
left_expression: Expression,
right_expression: Expression,
expression_type: BinaryOperationType,
) -> None:
assert isinstance(left_expression, Expression)
assert isinstance(right_expression, Expression)
super().__init__()
self._expressions = [left_expression, right_expression]
self._type: BinaryOperationType = expression_type
@property
def expressions(self) -> List[Expression]:
return self._expressions
@property
def expression_left(self) -> Expression:
return self._expressions[0]
@property
def expression_right(self) -> Expression:
return self._expressions[1]
@property
def type(self) -> BinaryOperationType:
return self._type
def __str__(self) -> str:
return str(self.expression_left) + " " + str(self.type) + " " + str(self.expression_right)
| 6,134 | Python | .py | 165 | 28.393939 | 98 | 0.603225 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,242 | unary_operation.py | NioTheFirst_ScType/slither/core/expressions/unary_operation.py | import logging
from enum import Enum
from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression
from slither.core.exceptions import SlitherCoreError
logger = logging.getLogger("UnaryOperation")
class UnaryOperationType(Enum):
BANG = 0 # !
TILD = 1 # ~
DELETE = 2 # delete
PLUSPLUS_PRE = 3 # ++
MINUSMINUS_PRE = 4 # --
PLUSPLUS_POST = 5 # ++
MINUSMINUS_POST = 6 # --
PLUS_PRE = 7 # for stuff like uint(+1)
MINUS_PRE = 8 # for stuff like uint(-1)
@staticmethod
def get_type(operation_type, isprefix):
if isprefix:
if operation_type == "!":
return UnaryOperationType.BANG
if operation_type == "~":
return UnaryOperationType.TILD
if operation_type == "delete":
return UnaryOperationType.DELETE
if operation_type == "++":
return UnaryOperationType.PLUSPLUS_PRE
if operation_type == "--":
return UnaryOperationType.MINUSMINUS_PRE
if operation_type == "+":
return UnaryOperationType.PLUS_PRE
if operation_type == "-":
return UnaryOperationType.MINUS_PRE
else:
if operation_type == "++":
return UnaryOperationType.PLUSPLUS_POST
if operation_type == "--":
return UnaryOperationType.MINUSMINUS_POST
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type}")
def __str__(self):
if self == UnaryOperationType.BANG:
return "!"
if self == UnaryOperationType.TILD:
return "~"
if self == UnaryOperationType.DELETE:
return "delete"
if self == UnaryOperationType.PLUS_PRE:
return "+"
if self == UnaryOperationType.MINUS_PRE:
return "-"
if self in [UnaryOperationType.PLUSPLUS_PRE, UnaryOperationType.PLUSPLUS_POST]:
return "++"
if self in [
UnaryOperationType.MINUSMINUS_PRE,
UnaryOperationType.MINUSMINUS_POST,
]:
return "--"
raise SlitherCoreError(f"str: Unknown operation type {self}")
@staticmethod
def is_prefix(operation_type):
if operation_type in [
UnaryOperationType.BANG,
UnaryOperationType.TILD,
UnaryOperationType.DELETE,
UnaryOperationType.PLUSPLUS_PRE,
UnaryOperationType.MINUSMINUS_PRE,
UnaryOperationType.PLUS_PRE,
UnaryOperationType.MINUS_PRE,
]:
return True
if operation_type in [
UnaryOperationType.PLUSPLUS_POST,
UnaryOperationType.MINUSMINUS_POST,
]:
return False
raise SlitherCoreError(f"is_prefix: Unknown operation type {operation_type}")
class UnaryOperation(ExpressionTyped):
def __init__(self, expression, expression_type):
assert isinstance(expression, Expression)
super().__init__()
self._expression: Expression = expression
self._type: UnaryOperationType = expression_type
if expression_type in [
UnaryOperationType.DELETE,
UnaryOperationType.PLUSPLUS_PRE,
UnaryOperationType.MINUSMINUS_PRE,
UnaryOperationType.PLUSPLUS_POST,
UnaryOperationType.MINUSMINUS_POST,
UnaryOperationType.PLUS_PRE,
UnaryOperationType.MINUS_PRE,
]:
expression.set_lvalue()
@property
def expression(self) -> Expression:
return self._expression
@property
def type(self) -> UnaryOperationType:
return self._type
@property
def is_prefix(self) -> bool:
return UnaryOperationType.is_prefix(self._type)
def __str__(self):
if self.is_prefix:
return str(self.type) + " " + str(self._expression)
return str(self._expression) + " " + str(self.type)
| 4,049 | Python | .py | 105 | 28.733333 | 87 | 0.614406 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,243 | expression_typed.py | NioTheFirst_ScType/slither/core/expressions/expression_typed.py | from typing import Optional, TYPE_CHECKING
from slither.core.expressions.expression import Expression
if TYPE_CHECKING:
from slither.core.solidity_types.type import Type
class ExpressionTyped(Expression): # pylint: disable=too-few-public-methods
def __init__(self) -> None:
super().__init__()
self._type: Optional["Type"] = None
@property
def type(self) -> Optional["Type"]:
return self._type
@type.setter
def type(self, new_type: "Type"):
self._type = new_type
| 525 | Python | .py | 14 | 32.071429 | 76 | 0.685149 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,244 | identifier.py | NioTheFirst_ScType/slither/core/expressions/identifier.py | from typing import TYPE_CHECKING
from slither.core.expressions.expression_typed import ExpressionTyped
if TYPE_CHECKING:
from slither.core.variables.variable import Variable
class Identifier(ExpressionTyped):
def __init__(self, value) -> None:
super().__init__()
self._value: "Variable" = value
@property
def value(self) -> "Variable":
return self._value
def __str__(self) -> str:
return str(self._value)
| 463 | Python | .py | 13 | 30.153846 | 69 | 0.686937 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,245 | call_expression.py | NioTheFirst_ScType/slither/core/expressions/call_expression.py | from typing import Optional, List
from slither.core.expressions.expression import Expression
class CallExpression(Expression): # pylint: disable=too-many-instance-attributes
def __init__(self, called, arguments, type_call):
assert isinstance(called, Expression)
super().__init__()
self._called: Expression = called
self._arguments: List[Expression] = arguments
self._type_call: str = type_call
# gas and value are 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)
self._gas: Optional[Expression] = None
self._value: Optional[Expression] = None
self._salt: Optional[Expression] = None
@property
def call_value(self) -> Optional[Expression]:
return self._value
@call_value.setter
def call_value(self, v):
self._value = v
@property
def call_gas(self) -> Optional[Expression]:
return self._gas
@call_gas.setter
def call_gas(self, gas):
self._gas = gas
@property
def call_salt(self):
return self._salt
@call_salt.setter
def call_salt(self, salt):
self._salt = salt
@property
def called(self) -> Expression:
return self._called
@property
def arguments(self) -> List[Expression]:
return self._arguments
@property
def type_call(self) -> str:
return self._type_call
def __str__(self):
txt = str(self._called)
if self.call_gas or self.call_value:
gas = f"gas: {self.call_gas}" if self.call_gas else ""
value = f"value: {self.call_value}" if self.call_value else ""
salt = f"salt: {self.call_salt}" if self.call_salt else ""
if gas or value or salt:
options = [gas, value, salt]
txt += "{" + ",".join([o for o in options if o != ""]) + "}"
return txt + "(" + ",".join([str(a) for a in self._arguments]) + ")"
| 2,079 | Python | .py | 52 | 32.115385 | 81 | 0.609235 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,246 | expression.py | NioTheFirst_ScType/slither/core/expressions/expression.py | from slither.core.source_mapping.source_mapping import SourceMapping
class Expression(SourceMapping):
def __init__(self) -> None:
super().__init__()
self._is_lvalue = False
@property
def is_lvalue(self) -> bool:
return self._is_lvalue
def set_lvalue(self) -> None:
self._is_lvalue = True
| 340 | Python | .py | 10 | 27.8 | 68 | 0.644172 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,247 | type_conversion.py | NioTheFirst_ScType/slither/core/expressions/type_conversion.py | from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type
class TypeConversion(ExpressionTyped):
def __init__(self, expression, expression_type):
super().__init__()
assert isinstance(expression, Expression)
assert isinstance(expression_type, Type)
self._expression: Expression = expression
self._type: Type = expression_type
@property
def expression(self) -> Expression:
return self._expression
def __str__(self):
return str(self.type) + "(" + str(self.expression) + ")"
| 668 | Python | .py | 15 | 38.466667 | 69 | 0.713405 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,248 | literal.py | NioTheFirst_ScType/slither/core/expressions/literal.py | from typing import Optional, Union, TYPE_CHECKING
from slither.core.expressions.expression import Expression
from slither.core.solidity_types.elementary_type import Fixed, Int, Ufixed, Uint
from slither.utils.arithmetic import convert_subdenomination
from slither.utils.integer_conversion import convert_string_to_int
if TYPE_CHECKING:
from slither.core.solidity_types.type import Type
class Literal(Expression):
def __init__(
self, value: Union[int, str], custom_type: "Type", subdenomination: Optional[str] = None
):
super().__init__()
self._value = value
self._type = custom_type
self._subdenomination = subdenomination
@property
def value(self) -> Union[int, str]:
return self._value
@property
def converted_value(self) -> Union[int, str]:
"""Return the value of the literal, accounting for subdenomination e.g. ether"""
if self.subdenomination:
return convert_subdenomination(self._value, self.subdenomination)
return self._value
@property
def type(self) -> "Type":
return self._type
@property
def subdenomination(self) -> Optional[str]:
return self._subdenomination
def __str__(self) -> str:
if self.subdenomination:
return str(self.converted_value)
if self.type in Int + Uint + Fixed + Ufixed + ["address"]:
return str(convert_string_to_int(self._value))
# be sure to handle any character
return str(self._value)
def __eq__(self, other) -> bool:
if not isinstance(other, Literal):
return False
return (self.value, self.subdenomination) == (other.value, other.subdenomination)
| 1,731 | Python | .py | 41 | 35.170732 | 96 | 0.675805 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,249 | __init__.py | NioTheFirst_ScType/slither/core/expressions/__init__.py | from .assignment_operation import AssignmentOperation, AssignmentOperationType
from .binary_operation import BinaryOperation, BinaryOperationType
from .call_expression import CallExpression
from .conditional_expression import ConditionalExpression
from .elementary_type_name_expression import ElementaryTypeNameExpression
from .identifier import Identifier
from .index_access import IndexAccess
from .literal import Literal
from .member_access import MemberAccess
from .new_array import NewArray
from .new_contract import NewContract
from .new_elementary_type import NewElementaryType
from .super_call_expression import SuperCallExpression
from .super_identifier import SuperIdentifier
from .tuple_expression import TupleExpression
from .type_conversion import TypeConversion
from .unary_operation import UnaryOperation, UnaryOperationType
| 840 | Python | .py | 17 | 48.411765 | 78 | 0.886999 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,250 | assignment_operation.py | NioTheFirst_ScType/slither/core/expressions/assignment_operation.py | import logging
from enum import Enum
from typing import Optional, TYPE_CHECKING, List
from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression
from slither.core.exceptions import SlitherCoreError
if TYPE_CHECKING:
from slither.core.solidity_types.type import Type
logger = logging.getLogger("AssignmentOperation")
class AssignmentOperationType(Enum):
ASSIGN = 0 # =
ASSIGN_OR = 1 # |=
ASSIGN_CARET = 2 # ^=
ASSIGN_AND = 3 # &=
ASSIGN_LEFT_SHIFT = 4 # <<=
ASSIGN_RIGHT_SHIFT = 5 # >>=
ASSIGN_ADDITION = 6 # +=
ASSIGN_SUBTRACTION = 7 # -=
ASSIGN_MULTIPLICATION = 8 # *=
ASSIGN_DIVISION = 9 # /=
ASSIGN_MODULO = 10 # %=
@staticmethod
def get_type(operation_type: str) -> "AssignmentOperationType":
if operation_type == "=":
return AssignmentOperationType.ASSIGN
if operation_type == "|=":
return AssignmentOperationType.ASSIGN_OR
if operation_type == "^=":
return AssignmentOperationType.ASSIGN_CARET
if operation_type == "&=":
return AssignmentOperationType.ASSIGN_AND
if operation_type == "<<=":
return AssignmentOperationType.ASSIGN_LEFT_SHIFT
if operation_type == ">>=":
return AssignmentOperationType.ASSIGN_RIGHT_SHIFT
if operation_type == "+=":
return AssignmentOperationType.ASSIGN_ADDITION
if operation_type == "-=":
return AssignmentOperationType.ASSIGN_SUBTRACTION
if operation_type == "*=":
return AssignmentOperationType.ASSIGN_MULTIPLICATION
if operation_type == "/=":
return AssignmentOperationType.ASSIGN_DIVISION
if operation_type == "%=":
return AssignmentOperationType.ASSIGN_MODULO
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type})")
def __str__(self) -> str:
if self == AssignmentOperationType.ASSIGN:
return "="
if self == AssignmentOperationType.ASSIGN_OR:
return "|="
if self == AssignmentOperationType.ASSIGN_CARET:
return "^="
if self == AssignmentOperationType.ASSIGN_AND:
return "&="
if self == AssignmentOperationType.ASSIGN_LEFT_SHIFT:
return "<<="
if self == AssignmentOperationType.ASSIGN_RIGHT_SHIFT:
return ">>="
if self == AssignmentOperationType.ASSIGN_ADDITION:
return "+="
if self == AssignmentOperationType.ASSIGN_SUBTRACTION:
return "-="
if self == AssignmentOperationType.ASSIGN_MULTIPLICATION:
return "*="
if self == AssignmentOperationType.ASSIGN_DIVISION:
return "/="
if self == AssignmentOperationType.ASSIGN_MODULO:
return "%="
raise SlitherCoreError(f"str: Unknown operation type {self})")
class AssignmentOperation(ExpressionTyped):
def __init__(
self,
left_expression: Expression,
right_expression: Expression,
expression_type: AssignmentOperationType,
expression_return_type: Optional["Type"],
):
assert isinstance(left_expression, Expression)
assert isinstance(right_expression, Expression)
super().__init__()
left_expression.set_lvalue()
self._expressions = [left_expression, right_expression]
self._type: Optional["AssignmentOperationType"] = expression_type
self._expression_return_type: Optional["Type"] = expression_return_type
@property
def expressions(self) -> List[Expression]:
return self._expressions
@property
def expression_return_type(self) -> Optional["Type"]:
return self._expression_return_type
@property
def expression_left(self) -> Expression:
return self._expressions[0]
@property
def expression_right(self) -> Expression:
return self._expressions[1]
@property
def type(self) -> Optional["AssignmentOperationType"]:
return self._type
def __str__(self) -> str:
return str(self.expression_left) + " " + str(self.type) + " " + str(self.expression_right)
| 4,255 | Python | .py | 102 | 33.578431 | 98 | 0.649021 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,251 | conditional_expression.py | NioTheFirst_ScType/slither/core/expressions/conditional_expression.py | from typing import List
from .expression import Expression
class ConditionalExpression(Expression):
def __init__(self, if_expression, then_expression, else_expression):
assert isinstance(if_expression, Expression)
assert isinstance(then_expression, Expression)
assert isinstance(else_expression, Expression)
super().__init__()
self._if_expression: Expression = if_expression
self._then_expression: Expression = then_expression
self._else_expression: Expression = else_expression
@property
def expressions(self) -> List[Expression]:
return [self._if_expression, self._then_expression, self._else_expression]
@property
def if_expression(self) -> Expression:
return self._if_expression
@property
def else_expression(self) -> Expression:
return self._else_expression
@property
def then_expression(self) -> Expression:
return self._then_expression
def __str__(self):
return (
"if "
+ str(self._if_expression)
+ " then "
+ str(self._then_expression)
+ " else "
+ str(self._else_expression)
)
| 1,210 | Python | .py | 32 | 29.8125 | 82 | 0.646154 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,252 | new_array.py | NioTheFirst_ScType/slither/core/expressions/new_array.py | from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type
class NewArray(Expression):
# note: dont conserve the size of the array if provided
def __init__(self, depth, array_type):
super().__init__()
assert isinstance(array_type, Type)
self._depth: int = depth
self._array_type: Type = array_type
@property
def array_type(self) -> Type:
return self._array_type
@property
def depth(self) -> int:
return self._depth
def __str__(self):
return "new " + str(self._array_type) + "[]" * self._depth
| 633 | Python | .py | 17 | 30.941176 | 66 | 0.647541 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,253 | elementary_type_name_expression.py | NioTheFirst_ScType/slither/core/expressions/elementary_type_name_expression.py | """
This expression does nothing, if a contract used it, its probably a bug
"""
from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type
class ElementaryTypeNameExpression(Expression):
def __init__(self, t):
assert isinstance(t, Type)
super().__init__()
self._type = t
@property
def type(self) -> Type:
return self._type
@type.setter
def type(self, new_type: Type):
assert isinstance(new_type, Type)
self._type = new_type
def __str__(self):
return str(self._type)
| 605 | Python | .py | 19 | 26.157895 | 75 | 0.659208 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,254 | new_contract.py | NioTheFirst_ScType/slither/core/expressions/new_contract.py | from slither.core.expressions.expression import Expression
class NewContract(Expression):
def __init__(self, contract_name):
super().__init__()
self._contract_name: str = contract_name
self._gas = None
self._value = None
self._salt = None
@property
def contract_name(self) -> str:
return self._contract_name
@property
def call_value(self):
return self._value
@call_value.setter
def call_value(self, v):
self._value = v
@property
def call_salt(self):
return self._salt
@call_salt.setter
def call_salt(self, salt):
self._salt = salt
def __str__(self):
return "new " + str(self._contract_name)
| 735 | Python | .py | 25 | 22.64 | 58 | 0.612536 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,255 | new_elementary_type.py | NioTheFirst_ScType/slither/core/expressions/new_elementary_type.py | from slither.core.expressions.expression import Expression
from slither.core.solidity_types.elementary_type import ElementaryType
class NewElementaryType(Expression):
def __init__(self, new_type):
assert isinstance(new_type, ElementaryType)
super().__init__()
self._type = new_type
@property
def type(self) -> ElementaryType:
return self._type
def __str__(self):
return "new " + str(self._type)
| 455 | Python | .py | 12 | 31.916667 | 70 | 0.687927 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,256 | tuple_expression.py | NioTheFirst_ScType/slither/core/expressions/tuple_expression.py | from typing import List
from slither.core.expressions.expression import Expression
class TupleExpression(Expression):
def __init__(self, expressions: List[Expression]) -> None:
assert all(isinstance(x, Expression) for x in expressions if x)
super().__init__()
self._expressions = expressions
@property
def expressions(self) -> List[Expression]:
return self._expressions
def __str__(self) -> str:
expressions_str = [str(e) for e in self.expressions]
return "(" + ",".join(expressions_str) + ")"
| 563 | Python | .py | 13 | 37 | 71 | 0.66789 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,257 | member_access.py | NioTheFirst_ScType/slither/core/expressions/member_access.py | from slither.core.expressions.expression import Expression
from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.solidity_types.type import Type
class MemberAccess(ExpressionTyped):
def __init__(self, member_name, member_type, expression):
# assert isinstance(member_type, Type)
# TODO member_type is not always a Type
assert isinstance(expression, Expression)
super().__init__()
self._type: Type = member_type
self._member_name: str = member_name
self._expression: Expression = expression
@property
def expression(self) -> Expression:
return self._expression
@property
def member_name(self) -> str:
return self._member_name
@property
def type(self) -> Type:
return self._type
def __str__(self):
return str(self.expression) + "." + self.member_name
| 910 | Python | .py | 23 | 33.043478 | 69 | 0.686364 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,258 | index_access.py | NioTheFirst_ScType/slither/core/expressions/index_access.py | from typing import List, TYPE_CHECKING
from slither.core.expressions.expression_typed import ExpressionTyped
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type
class IndexAccess(ExpressionTyped):
def __init__(self, left_expression, right_expression, index_type):
super().__init__()
self._expressions = [left_expression, right_expression]
# TODO type of undexAccess is not always a Type
# assert isinstance(index_type, Type)
self._type: "Type" = index_type
@property
def expressions(self) -> List["Expression"]:
return self._expressions
@property
def expression_left(self) -> "Expression":
return self._expressions[0]
@property
def expression_right(self) -> "Expression":
return self._expressions[1]
@property
def type(self) -> "Type":
return self._type
def __str__(self):
return str(self.expression_left) + "[" + str(self.expression_right) + "]"
| 1,067 | Python | .py | 26 | 34.730769 | 81 | 0.680892 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,259 | mapping_type.py | NioTheFirst_ScType/slither/core/solidity_types/mapping_type.py | from typing import Tuple
from slither.core.solidity_types.type import Type
class MappingType(Type):
def __init__(self, type_from, type_to):
assert isinstance(type_from, Type)
assert isinstance(type_to, Type)
super().__init__()
self._from = type_from
self._to = type_to
@property
def type_from(self) -> Type:
return self._from
@property
def type_to(self) -> Type:
return self._to
@property
def storage_size(self) -> Tuple[int, bool]:
return 32, True
@property
def is_dynamic(self) -> bool:
return True
def __str__(self):
return f"mapping({str(self._from)} => {str(self._to)})"
def __eq__(self, other):
if not isinstance(other, MappingType):
return False
return self.type_from == other.type_from and self.type_to == other.type_to
def __hash__(self):
return hash(str(self))
| 945 | Python | .py | 29 | 25.586207 | 82 | 0.604857 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,260 | array_type.py | NioTheFirst_ScType/slither/core/solidity_types/array_type.py | from typing import Optional, Tuple
from slither.core.expressions import Literal
from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type
from slither.visitors.expression.constants_folding import ConstantFolding
class ArrayType(Type):
def __init__(self, t, length):
assert isinstance(t, Type)
if length:
if isinstance(length, int):
length = Literal(length, "uint256")
assert isinstance(length, Expression)
super().__init__()
self._type: Type = t
self._length: Optional[Expression] = length
if length:
if not isinstance(length, Literal):
cf = ConstantFolding(length, "uint256")
length = cf.result()
self._length_value = length
else:
self._length_value = None
@property
def type(self) -> Type:
return self._type
@property
def is_dynamic(self) -> bool:
return self.length is None
@property
def length(self) -> Optional[Expression]:
return self._length
@property
def length_value(self) -> Optional[Literal]:
return self._length_value
@property
def is_fixed_array(self) -> bool:
return bool(self.length)
@property
def is_dynamic_array(self) -> bool:
return not self.is_fixed_array
@property
def storage_size(self) -> Tuple[int, bool]:
if self._length_value:
elem_size, _ = self._type.storage_size
return elem_size * int(str(self._length_value)), True
return 32, True
def __str__(self):
if self._length:
return str(self._type) + f"[{str(self._length_value)}]"
return str(self._type) + "[]"
def __eq__(self, other):
if not isinstance(other, ArrayType):
return False
return self._type == other.type and self.length == other.length
def __hash__(self):
return hash(str(self))
| 2,019 | Python | .py | 56 | 27.875 | 73 | 0.616727 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,261 | __init__.py | NioTheFirst_ScType/slither/core/solidity_types/__init__.py | from .array_type import ArrayType
from .elementary_type import ElementaryType
from .function_type import FunctionType
from .mapping_type import MappingType
from .user_defined_type import UserDefinedType
from .type import Type
from .type_information import TypeInformation
from .type_alias import TypeAlias, TypeAliasTopLevel, TypeAliasContract
| 344 | Python | .py | 8 | 42 | 71 | 0.869048 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,262 | type.py | NioTheFirst_ScType/slither/core/solidity_types/type.py | import abc
from typing import Tuple
from slither.core.source_mapping.source_mapping import SourceMapping
class Type(SourceMapping, metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def storage_size(self) -> Tuple[int, bool]:
"""
Computes and returns storage layout related metadata
:return: (int, bool) - the number of bytes this type will require, and whether it must start in
a new slot regardless of whether the current slot can still fit it
"""
@property
@abc.abstractmethod
def is_dynamic(self) -> bool:
"""True if the size of the type is dynamic"""
| 636 | Python | .py | 16 | 33.9375 | 103 | 0.704065 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,263 | function_type.py | NioTheFirst_ScType/slither/core/solidity_types/function_type.py | from typing import List, Tuple
from slither.core.solidity_types.type import Type
from slither.core.variables.function_type_variable import FunctionTypeVariable
class FunctionType(Type):
def __init__(
self,
params: List[FunctionTypeVariable],
return_values: List[FunctionTypeVariable],
):
assert all(isinstance(x, FunctionTypeVariable) for x in params)
assert all(isinstance(x, FunctionTypeVariable) for x in return_values)
super().__init__()
self._params: List[FunctionTypeVariable] = params
self._return_values: List[FunctionTypeVariable] = return_values
@property
def params(self) -> List[FunctionTypeVariable]:
return self._params
@property
def return_values(self) -> List[FunctionTypeVariable]:
return self._return_values
@property
def return_type(self) -> List[Type]:
return [x.type for x in self.return_values]
@property
def storage_size(self) -> Tuple[int, bool]:
return 24, False
@property
def is_dynamic(self) -> bool:
return False
def __str__(self):
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return f"function({params}) returns({return_values})"
return f"function({params})"
@property
def parameters_signature(self) -> str:
"""
Return the parameters signature(without the return statetement)
"""
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return f"({params})"
@property
def signature(self) -> str:
"""
Return the signature(with the return statetement if it exists)
"""
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return f"({params}) returns({return_values})"
return f"({params})"
def __eq__(self, other):
if not isinstance(other, FunctionType):
return False
return self.params == other.params and self.return_values == other.return_values
def __hash__(self):
return hash(str(self))
| 2,436 | Python | .py | 64 | 30.359375 | 88 | 0.625265 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,264 | type_information.py | NioTheFirst_ScType/slither/core/solidity_types/type_information.py | from typing import TYPE_CHECKING, Tuple
from slither.core.solidity_types import ElementaryType
from slither.core.solidity_types.type import Type
if TYPE_CHECKING:
from slither.core.declarations.contract import Contract
# Use to model the Type(X) function, which returns an undefined type
# https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#type-information
class TypeInformation(Type):
def __init__(self, c):
# pylint: disable=import-outside-toplevel
from slither.core.declarations.contract import Contract
from slither.core.declarations.enum import Enum
assert isinstance(c, (Contract, ElementaryType, Enum))
super().__init__()
self._type = c
@property
def type(self) -> "Contract":
return self._type
@property
def storage_size(self) -> Tuple[int, bool]:
"""
32 is incorrect, as Type(x) return a kind of structure that can contain
an arbitrary number of value
As Type(x) cannot be directly stored, we are assuming that the correct storage size
will be handled by the fields access
:return:
"""
return 32, True
@property
def is_dynamic(self) -> bool:
raise NotImplementedError
def __str__(self):
return f"type({self.type.name})"
def __eq__(self, other):
if not isinstance(other, TypeInformation):
return False
return self.type == other.type
| 1,480 | Python | .py | 37 | 33.189189 | 92 | 0.682961 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,265 | type_alias.py | NioTheFirst_ScType/slither/core/solidity_types/type_alias.py | from typing import TYPE_CHECKING, Tuple
from slither.core.children.child_contract import ChildContract
from slither.core.declarations.top_level import TopLevel
from slither.core.solidity_types import Type
if TYPE_CHECKING:
from slither.core.declarations import Contract
from slither.core.scope.scope import FileScope
class TypeAlias(Type):
def __init__(self, underlying_type: Type, name: str):
super().__init__()
self.name = name
self.underlying_type = underlying_type
@property
def type(self) -> Type:
"""
Return the underlying type. Alias for underlying_type
Returns:
Type: the underlying type
"""
return self.underlying_type
@property
def storage_size(self) -> Tuple[int, bool]:
return self.underlying_type.storage_size
def __hash__(self):
return hash(str(self))
@property
def is_dynamic(self) -> bool:
return self.underlying_type.is_dynamic
class TypeAliasTopLevel(TypeAlias, TopLevel):
def __init__(self, underlying_type: Type, name: str, scope: "FileScope"):
super().__init__(underlying_type, name)
self.file_scope: "FileScope" = scope
def __str__(self):
return self.name
class TypeAliasContract(TypeAlias, ChildContract):
def __init__(self, underlying_type: Type, name: str, contract: "Contract"):
super().__init__(underlying_type, name)
self._contract: "Contract" = contract
def __str__(self):
return self.contract.name + "." + self.name
| 1,567 | Python | .py | 40 | 32.65 | 79 | 0.67351 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,266 | user_defined_type.py | NioTheFirst_ScType/slither/core/solidity_types/user_defined_type.py | from typing import Union, TYPE_CHECKING, Tuple
import math
from slither.core.solidity_types.type import Type
from slither.exceptions import SlitherException
if TYPE_CHECKING:
from slither.core.declarations.structure import Structure
from slither.core.declarations.enum import Enum
from slither.core.declarations.contract import Contract
# pylint: disable=import-outside-toplevel
class UserDefinedType(Type):
def __init__(self, t):
from slither.core.declarations.structure import Structure
from slither.core.declarations.enum import Enum
from slither.core.declarations.contract import Contract
assert isinstance(t, (Contract, Enum, Structure))
super().__init__()
self._type = t
@property
def is_dynamic(self) -> bool:
return False
@property
def type(self) -> Union["Contract", "Enum", "Structure"]:
return self._type
@property
def storage_size(self) -> Tuple[int, bool]:
from slither.core.declarations.structure import Structure
from slither.core.declarations.enum import Enum
from slither.core.declarations.contract import Contract
if isinstance(self._type, Contract):
return 20, False
if isinstance(self._type, Enum):
return int(math.ceil(math.log2(len(self._type.values)) / 8)), False
if isinstance(self._type, Structure):
# todo there's some duplicate logic here and slither_core, can we refactor this?
slot = 0
offset = 0
for elem in self._type.elems_ordered:
size, new_slot = elem.type.storage_size
if new_slot:
if offset > 0:
slot += 1
offset = 0
elif size + offset > 32:
slot += 1
offset = 0
if new_slot:
slot += math.ceil(size / 32)
else:
offset += size
if offset > 0:
slot += 1
return slot * 32, True
to_log = f"{self} does not have storage size"
raise SlitherException(to_log)
def __str__(self):
from slither.core.declarations.structure_contract import StructureContract
from slither.core.declarations.enum_contract import EnumContract
type_used = self.type
if isinstance(type_used, (EnumContract, StructureContract)):
return str(type_used.contract) + "." + str(type_used.name)
return str(type_used.name)
def __eq__(self, other):
if not isinstance(other, UserDefinedType):
return False
return self.type == other.type
def __hash__(self):
return hash(str(self))
| 2,791 | Python | .py | 67 | 31.38806 | 92 | 0.614533 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,267 | elementary_type.py | NioTheFirst_ScType/slither/core/solidity_types/elementary_type.py | import itertools
from typing import Tuple
from slither.core.solidity_types.type import Type
# see https://solidity.readthedocs.io/en/v0.4.24/miscellaneous.html?highlight=grammar
from slither.exceptions import SlitherException
Int = [
"int",
"int8",
"int16",
"int24",
"int32",
"int40",
"int48",
"int56",
"int64",
"int72",
"int80",
"int88",
"int96",
"int104",
"int112",
"int120",
"int128",
"int136",
"int144",
"int152",
"int160",
"int168",
"int176",
"int184",
"int192",
"int200",
"int208",
"int216",
"int224",
"int232",
"int240",
"int248",
"int256",
]
Max_Int = {k: 2 ** (8 * i - 1) - 1 if i > 0 else 2**255 - 1 for i, k in enumerate(Int)}
Min_Int = {k: -(2 ** (8 * i - 1)) if i > 0 else -(2**255) for i, k in enumerate(Int)}
Uint = [
"uint",
"uint8",
"uint16",
"uint24",
"uint32",
"uint40",
"uint48",
"uint56",
"uint64",
"uint72",
"uint80",
"uint88",
"uint96",
"uint104",
"uint112",
"uint120",
"uint128",
"uint136",
"uint144",
"uint152",
"uint160",
"uint168",
"uint176",
"uint184",
"uint192",
"uint200",
"uint208",
"uint216",
"uint224",
"uint232",
"uint240",
"uint248",
"uint256",
]
Max_Uint = {k: 2 ** (8 * i) - 1 if i > 0 else 2**256 - 1 for i, k in enumerate(Uint)}
Min_Uint = {k: 0 for k in Uint}
Byte = [
"byte",
"bytes",
"bytes1",
"bytes2",
"bytes3",
"bytes4",
"bytes5",
"bytes6",
"bytes7",
"bytes8",
"bytes9",
"bytes10",
"bytes11",
"bytes12",
"bytes13",
"bytes14",
"bytes15",
"bytes16",
"bytes17",
"bytes18",
"bytes19",
"bytes20",
"bytes21",
"bytes22",
"bytes23",
"bytes24",
"bytes25",
"bytes26",
"bytes27",
"bytes28",
"bytes29",
"bytes30",
"bytes31",
"bytes32",
]
Max_Byte = {k: 2 ** (8 * (i + 1)) - 1 for i, k in enumerate(Byte[2:])}
Max_Byte["bytes"] = None
Max_Byte["string"] = None
Max_Byte["byte"] = 255
Min_Byte = {k: 0 for k in Byte}
Min_Byte["bytes"] = 0x0
Min_Byte["string"] = 0x0
Min_Byte["byte"] = 0x0
MaxValues = dict(dict(Max_Int, **Max_Uint), **Max_Byte)
MinValues = dict(dict(Min_Int, **Min_Uint), **Min_Byte)
# https://solidity.readthedocs.io/en/v0.4.24/types.html#fixed-point-numbers
M = list(range(8, 257, 8))
N = list(range(0, 81))
MN = list(itertools.product(M, N))
Fixed = [f"fixed{m}x{n}" for (m, n) in MN] + ["fixed"]
Ufixed = [f"ufixed{m}x{n}" for (m, n) in MN] + ["ufixed"]
ElementaryTypeName = ["address", "bool", "string", "var"] + Int + Uint + Byte + Fixed + Ufixed
class NonElementaryType(Exception):
pass
class ElementaryType(Type):
def __init__(self, t: str) -> None:
if t not in ElementaryTypeName:
raise NonElementaryType
super().__init__()
if t == "uint":
t = "uint256"
elif t == "int":
t = "int256"
elif t == "byte":
t = "bytes1"
self._type = t
@property
def is_dynamic(self) -> bool:
return self._type in ("bytes", "string")
@property
def type(self) -> str:
return self._type
@property
def name(self) -> str:
return self.type
@property
def size(self) -> int:
"""
Return the size in bits
Return None if the size is not known
Returns:
int
"""
t = self._type
if t.startswith("uint"):
return int(t[len("uint") :])
if t.startswith("int"):
return int(t[len("int") :])
if t == "bool":
return int(8)
if t == "address":
return int(160)
if t.startswith("bytes") and t != "bytes":
return int(t[len("bytes") :]) * 8
raise SlitherException(f"{t} does not have a size")
@property
def storage_size(self) -> Tuple[int, bool]:
if self._type in ["string", "bytes"]:
return 32, True
if self.size is None:
return 32, True
return int(self.size / 8), False
@property
def min(self) -> int:
if self.name in MinValues:
return MinValues[self.name]
raise SlitherException(f"{self.name} does not have a min value")
@property
def max(self) -> int:
if self.name in MaxValues:
return MaxValues[self.name]
raise SlitherException(f"{self.name} does not have a max value")
def __str__(self):
return self._type
def __eq__(self, other):
if not isinstance(other, ElementaryType):
return False
return self.type == other.type
def __hash__(self):
return hash(str(self))
| 4,821 | Python | .py | 200 | 18.365 | 94 | 0.545177 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,268 | node.py | NioTheFirst_ScType/slither/core/cfg/node.py | """
Node module
"""
from enum import Enum
from typing import Optional, List, Set, Dict, Tuple, Union, TYPE_CHECKING
from slither.core.children.child_function import ChildFunction
from slither.core.declarations.solidity_variables import (
SolidityVariable,
SolidityFunction,
)
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.state_variable import StateVariable
from slither.core.variables.variable import Variable
from slither.core.solidity_types import ElementaryType
from slither.slithir.convert import convert_expression
from slither.slithir.operations import (
HighLevelCall,
Index,
InternalCall,
Length,
LibraryCall,
LowLevelCall,
Member,
OperationWithLValue,
Phi,
PhiCallback,
SolidityCall,
Return,
Operation,
)
from slither.slithir.variables import (
Constant,
LocalIRVariable,
ReferenceVariable,
StateIRVariable,
TemporaryVariable,
TupleVariable,
)
from slither.all_exceptions import SlitherException
from slither.core.declarations import Contract, Function
from slither.core.expressions.expression import Expression
if TYPE_CHECKING:
from slither.slithir.variables.variable import SlithIRVariable
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.utils.type_helpers import (
InternalCallType,
HighLevelCallType,
LibraryCallType,
LowLevelCallType,
)
from slither.core.cfg.scope import Scope
from slither.core.scope.scope import FileScope
# pylint: disable=too-many-lines,too-many-branches,too-many-instance-attributes
###################################################################################
###################################################################################
# region NodeType
###################################################################################
###################################################################################
class NodeType(Enum):
ENTRYPOINT = 0x0 # no expression
# Node with expression
EXPRESSION = 0x10 # normal case
RETURN = 0x11 # RETURN may contain an expression
IF = 0x12
VARIABLE = 0x13 # Declaration of variable
ASSEMBLY = 0x14
IFLOOP = 0x15
# Merging nodes
# Can have phi IR operation
ENDIF = 0x50 # ENDIF node source mapping points to the if/else body
STARTLOOP = 0x51 # STARTLOOP node source mapping points to the entire loop body
ENDLOOP = 0x52 # ENDLOOP node source mapping points to the entire loop body
# Below the nodes have no expression
# But are used to expression CFG structure
# Absorbing node
THROW = 0x20
# Loop related nodes
BREAK = 0x31
CONTINUE = 0x32
# Only modifier node
PLACEHOLDER = 0x40
TRY = 0x41
CATCH = 0x42
# Node not related to the CFG
# Use for state variable declaration
OTHER_ENTRYPOINT = 0x60
# @staticmethod
def __str__(self):
if self == NodeType.ENTRYPOINT:
return "ENTRY_POINT"
if self == NodeType.EXPRESSION:
return "EXPRESSION"
if self == NodeType.RETURN:
return "RETURN"
if self == NodeType.IF:
return "IF"
if self == NodeType.VARIABLE:
return "NEW VARIABLE"
if self == NodeType.ASSEMBLY:
return "INLINE ASM"
if self == NodeType.IFLOOP:
return "IF_LOOP"
if self == NodeType.THROW:
return "THROW"
if self == NodeType.BREAK:
return "BREAK"
if self == NodeType.CONTINUE:
return "CONTINUE"
if self == NodeType.PLACEHOLDER:
return "_"
if self == NodeType.TRY:
return "TRY"
if self == NodeType.CATCH:
return "CATCH"
if self == NodeType.ENDIF:
return "END_IF"
if self == NodeType.STARTLOOP:
return "BEGIN_LOOP"
if self == NodeType.ENDLOOP:
return "END_LOOP"
if self == NodeType.OTHER_ENTRYPOINT:
return "OTHER_ENTRYPOINT"
return f"Unknown type {hex(self.value)}"
# endregion
# I am not sure why, but pylint reports a lot of "no-member" issue that are not real (Josselin)
# pylint: disable=no-member
class Node(SourceMapping, ChildFunction): # pylint: disable=too-many-public-methods
"""
Node class
"""
def __init__(
self,
node_type: NodeType,
node_id: int,
scope: Union["Scope", "Function"],
file_scope: "FileScope",
):
super().__init__()
self._node_type = node_type
# TODO: rename to explicit CFG
self._sons: List["Node"] = []
self._fathers: List["Node"] = []
## Dominators info
# Dominators nodes
self._dominators: Set["Node"] = set()
self._immediate_dominator: Optional["Node"] = None
## Nodes of the dominators tree
# self._dom_predecessors = set()
self._dom_successors: Set["Node"] = set()
# Dominance frontier
self._dominance_frontier: Set["Node"] = set()
# Phi origin
# key are variable name
self._phi_origins_state_variables: Dict[str, Tuple[StateVariable, Set["Node"]]] = {}
self._phi_origins_local_variables: Dict[str, Tuple[LocalVariable, Set["Node"]]] = {}
# self._phi_origins_member_variables: Dict[str, Tuple[MemberVariable, Set["Node"]]] = {}
self._expression: Optional[Expression] = None
self._variable_declaration: Optional[LocalVariable] = None
self._node_id: int = node_id
self._vars_written: List[Variable] = []
self._vars_read: List[Variable] = []
self._ssa_vars_written: List["SlithIRVariable"] = []
self._ssa_vars_read: List["SlithIRVariable"] = []
self._internal_calls: List["Function"] = []
self._solidity_calls: List[SolidityFunction] = []
self._high_level_calls: List["HighLevelCallType"] = [] # contains library calls
self._library_calls: List["LibraryCallType"] = []
self._low_level_calls: List["LowLevelCallType"] = []
self._external_calls_as_expressions: List[Expression] = []
self._internal_calls_as_expressions: List[Expression] = []
self._irs: List[Operation] = []
self._all_slithir_operations: Optional[List[Operation]] = None
self._irs_ssa: List[Operation] = []
self._state_vars_written: List[StateVariable] = []
self._state_vars_read: List[StateVariable] = []
self._solidity_vars_read: List[SolidityVariable] = []
self._ssa_state_vars_written: List[StateIRVariable] = []
self._ssa_state_vars_read: List[StateIRVariable] = []
self._local_vars_read: List[LocalVariable] = []
self._local_vars_written: List[LocalVariable] = []
self._slithir_vars: Set["SlithIRVariable"] = set() # non SSA
self._ssa_local_vars_read: List[LocalIRVariable] = []
self._ssa_local_vars_written: List[LocalIRVariable] = []
self._expression_vars_written: List[Expression] = []
self._expression_vars_read: List[Expression] = []
self._expression_calls: List[Expression] = []
# Computed on the fly, can be True of False
self._can_reenter: Optional[bool] = None
self._can_send_eth: Optional[bool] = None
self._asm_source_code: Optional[Union[str, Dict]] = None
self.scope: Union["Scope", "Function"] = scope
self.file_scope: "FileScope" = file_scope
###################################################################################
###################################################################################
# region General's properties
###################################################################################
###################################################################################
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self.function.compilation_unit
@property
def node_id(self) -> int:
"""Unique node id."""
return self._node_id
@property
def type(self) -> NodeType:
"""
NodeType: type of the node
"""
return self._node_type
@type.setter
def type(self, new_type: NodeType):
self._node_type = new_type
@property
def will_return(self) -> bool:
if not self.sons and self.type != NodeType.THROW:
if SolidityFunction("revert()") not in self.solidity_calls:
if SolidityFunction("revert(string)") not in self.solidity_calls:
return True
return False
# endregion
###################################################################################
###################################################################################
# region Variables
###################################################################################
###################################################################################
@property
def variables_read(self) -> List[Variable]:
"""
list(Variable): Variables read (local/state/solidity)
"""
return list(self._vars_read)
@property
def state_variables_read(self) -> List[StateVariable]:
"""
list(StateVariable): State variables read
"""
return list(self._state_vars_read)
@property
def local_variables_read(self) -> List[LocalVariable]:
"""
list(LocalVariable): Local variables read
"""
return list(self._local_vars_read)
@property
def solidity_variables_read(self) -> List[SolidityVariable]:
"""
list(SolidityVariable): State variables read
"""
return list(self._solidity_vars_read)
@property
def ssa_variables_read(self) -> List["SlithIRVariable"]:
"""
list(Variable): Variables read (local/state/solidity)
"""
return list(self._ssa_vars_read)
@property
def ssa_state_variables_read(self) -> List[StateIRVariable]:
"""
list(StateVariable): State variables read
"""
return list(self._ssa_state_vars_read)
@property
def ssa_local_variables_read(self) -> List[LocalIRVariable]:
"""
list(LocalVariable): Local variables read
"""
return list(self._ssa_local_vars_read)
@property
def variables_read_as_expression(self) -> List[Expression]:
return self._expression_vars_read
@variables_read_as_expression.setter
def variables_read_as_expression(self, exprs: List[Expression]):
self._expression_vars_read = exprs
@property
def slithir_variables(self) -> List["SlithIRVariable"]:
return list(self._slithir_vars)
@property
def variables_written(self) -> List[Variable]:
"""
list(Variable): Variables written (local/state/solidity)
"""
return list(self._vars_written)
@property
def state_variables_written(self) -> List[StateVariable]:
"""
list(StateVariable): State variables written
"""
return list(self._state_vars_written)
@property
def local_variables_written(self) -> List[LocalVariable]:
"""
list(LocalVariable): Local variables written
"""
return list(self._local_vars_written)
@property
def ssa_variables_written(self) -> List["SlithIRVariable"]:
"""
list(Variable): Variables written (local/state/solidity)
"""
return list(self._ssa_vars_written)
@property
def ssa_state_variables_written(self) -> List[StateIRVariable]:
"""
list(StateVariable): State variables written
"""
return list(self._ssa_state_vars_written)
@property
def ssa_local_variables_written(self) -> List[LocalIRVariable]:
"""
list(LocalVariable): Local variables written
"""
return list(self._ssa_local_vars_written)
@property
def variables_written_as_expression(self) -> List[Expression]:
return self._expression_vars_written
@variables_written_as_expression.setter
def variables_written_as_expression(self, exprs: List[Expression]):
self._expression_vars_written = exprs
# endregion
###################################################################################
###################################################################################
# region Calls
###################################################################################
###################################################################################
@property
def internal_calls(self) -> List["InternalCallType"]:
"""
list(Function or SolidityFunction): List of internal/soldiity function calls
"""
return list(self._internal_calls)
@property
def solidity_calls(self) -> List[SolidityFunction]:
"""
list(SolidityFunction): List of Soldity calls
"""
return list(self._solidity_calls)
@property
def high_level_calls(self) -> List["HighLevelCallType"]:
"""
list((Contract, Function|Variable)):
List of high level calls (external calls).
A variable is called in case of call to a public state variable
Include library calls
"""
return list(self._high_level_calls)
@property
def library_calls(self) -> List["LibraryCallType"]:
"""
list((Contract, Function)):
Include library calls
"""
return list(self._library_calls)
@property
def low_level_calls(self) -> List["LowLevelCallType"]:
"""
list((Variable|SolidityVariable, str)): List of low_level call
A low level call is defined by
- the variable called
- the name of the function (call/delegatecall/codecall)
"""
return list(self._low_level_calls)
@property
def external_calls_as_expressions(self) -> List[Expression]:
"""
list(CallExpression): List of message calls (that creates a transaction)
"""
return self._external_calls_as_expressions
@external_calls_as_expressions.setter
def external_calls_as_expressions(self, exprs: List[Expression]):
self._external_calls_as_expressions = exprs
@property
def internal_calls_as_expressions(self) -> List[Expression]:
"""
list(CallExpression): List of internal calls (that dont create a transaction)
"""
return self._internal_calls_as_expressions
@internal_calls_as_expressions.setter
def internal_calls_as_expressions(self, exprs: List[Expression]):
self._internal_calls_as_expressions = exprs
@property
def calls_as_expression(self) -> List[Expression]:
return list(self._expression_calls)
@calls_as_expression.setter
def calls_as_expression(self, exprs: List[Expression]):
self._expression_calls = exprs
def can_reenter(self, callstack=None) -> bool:
"""
Check if the node can re-enter
Do not consider CREATE as potential re-enter, but check if the
destination's constructor can contain a call (recurs. follow nested CREATE)
For Solidity > 0.5, filter access to public variables and constant/pure/view
For call to this. check if the destination can re-enter
Do not consider Send/Transfer as there is not enough gas
:param callstack: used internally to check for recursion
:return bool:
"""
# pylint: disable=import-outside-toplevel
from slither.slithir.operations import Call
if self._can_reenter is None:
self._can_reenter = False
for ir in self.irs:
if isinstance(ir, Call) and ir.can_reenter(callstack):
self._can_reenter = True
return True
return self._can_reenter
def can_send_eth(self) -> bool:
"""
Check if the node can send eth
:return bool:
"""
# pylint: disable=import-outside-toplevel
from slither.slithir.operations import Call
if self._can_send_eth is None:
self._can_send_eth = False
for ir in self.all_slithir_operations():
if isinstance(ir, Call) and ir.can_send_eth():
self._can_send_eth = True
return True
return self._can_send_eth
# endregion
###################################################################################
###################################################################################
# region Expressions
###################################################################################
###################################################################################
@property
def expression(self) -> Optional[Expression]:
"""
Expression: Expression of the node
"""
return self._expression
def add_expression(self, expression: Expression, bypass_verif_empty: bool = False):
assert self._expression is None or bypass_verif_empty
self._expression = expression
def add_variable_declaration(self, var: LocalVariable):
assert self._variable_declaration is None
self._variable_declaration = var
if var.expression:
self._vars_written += [var]
self._local_vars_written += [var]
@property
def variable_declaration(self) -> Optional[LocalVariable]:
"""
Returns:
LocalVariable
"""
return self._variable_declaration
# endregion
###################################################################################
###################################################################################
# region Summary information
###################################################################################
###################################################################################
def contains_require_or_assert(self) -> bool:
"""
Check if the node has a require or assert call
Returns:
bool: True if the node has a require or assert call
"""
return any(
c.name in ["require(bool)", "require(bool,string)", "assert(bool)"]
for c in self.internal_calls
)
def contains_if(self, include_loop=True) -> bool:
"""
Check if the node is a IF node
Returns:
bool: True if the node is a conditional node (IF or IFLOOP)
"""
if include_loop:
return self.type in [NodeType.IF, NodeType.IFLOOP]
return self.type == NodeType.IF
def is_conditional(self, include_loop=True) -> bool:
"""
Check if the node is a conditional node
A conditional node is either a IF or a require/assert or a RETURN bool
Returns:
bool: True if the node is a conditional node
"""
if self.contains_if(include_loop) or self.contains_require_or_assert():
return True
if self.irs:
last_ir = self.irs[-1]
if last_ir:
if isinstance(last_ir, Return):
for r in last_ir.read:
if r.type == ElementaryType("bool"):
return True
return False
# endregion
###################################################################################
###################################################################################
# region EVM
###################################################################################
###################################################################################
@property
def inline_asm(self) -> Optional[Union[str, Dict]]:
return self._asm_source_code
def add_inline_asm(self, asm: Union[str, Dict]):
self._asm_source_code = asm
# endregion
###################################################################################
###################################################################################
# region Graph
###################################################################################
###################################################################################
def add_father(self, father: "Node"):
"""Add a father node
Args:
father: father to add
"""
self._fathers.append(father)
def set_fathers(self, fathers: List["Node"]):
"""Set the father nodes
Args:
fathers: list of fathers to add
"""
self._fathers = fathers
@property
def fathers(self) -> List["Node"]:
"""Returns the father nodes
Returns:
list(Node): list of fathers
"""
return list(self._fathers)
def remove_father(self, father: "Node"):
"""Remove the father node. Do nothing if the node is not a father
Args:
:param father:
"""
self._fathers = [x for x in self._fathers if x.node_id != father.node_id]
def remove_son(self, son: "Node"):
"""Remove the son node. Do nothing if the node is not a son
Args:
:param son:
"""
self._sons = [x for x in self._sons if x.node_id != son.node_id]
def add_son(self, son: "Node"):
"""Add a son node
Args:
son: son to add
"""
self._sons.append(son)
def set_sons(self, sons: List["Node"]):
"""Set the son nodes
Args:
sons: list of fathers to add
"""
self._sons = sons
@property
def sons(self) -> List["Node"]:
"""Returns the son nodes
Returns:
list(Node): list of sons
"""
return list(self._sons)
@property
def son_true(self) -> Optional["Node"]:
if self.type in [NodeType.IF, NodeType.IFLOOP]:
return self._sons[0]
return None
@property
def son_false(self) -> Optional["Node"]:
if self.type in [NodeType.IF, NodeType.IFLOOP] and len(self._sons) >= 1:
return self._sons[1]
return None
# endregion
###################################################################################
###################################################################################
# region SlithIR
###################################################################################
###################################################################################
@property
def irs(self) -> List[Operation]:
"""Returns the slithIR representation
return
list(slithIR.Operation)
"""
return self._irs
@property
def irs_ssa(self) -> List[Operation]:
"""Returns the slithIR representation with SSA
return
list(slithIR.Operation)
"""
return self._irs_ssa
@irs_ssa.setter
def irs_ssa(self, irs):
self._irs_ssa = irs
def add_ssa_ir(self, ir: Operation):
"""
Use to place phi operation
"""
ir.set_node(self)
self._irs_ssa.append(ir)
def slithir_generation(self):
if self.expression:
expression = self.expression
self._irs = convert_expression(expression, self)
self._find_read_write_call()
def all_slithir_operations(self) -> List[Operation]:
if self._all_slithir_operations is None:
irs = list(self.irs)
for ir in self.irs:
if isinstance(ir, InternalCall):
irs += ir.function.all_slithir_operations()
self._all_slithir_operations = irs
return self._all_slithir_operations
@staticmethod
def _is_non_slithir_var(var: Variable):
return not isinstance(var, (Constant, ReferenceVariable, TemporaryVariable, TupleVariable))
@staticmethod
def _is_valid_slithir_var(var: Variable):
return isinstance(var, (ReferenceVariable, TemporaryVariable, TupleVariable))
# endregion
###################################################################################
###################################################################################
# region Dominators
###################################################################################
###################################################################################
@property
def dominators(self) -> Set["Node"]:
"""
Returns:
set(Node)
"""
return self._dominators
@dominators.setter
def dominators(self, dom: Set["Node"]):
self._dominators = dom
@property
def immediate_dominator(self) -> Optional["Node"]:
"""
Returns:
Node or None
"""
return self._immediate_dominator
@immediate_dominator.setter
def immediate_dominator(self, idom: "Node"):
self._immediate_dominator = idom
@property
def dominance_frontier(self) -> Set["Node"]:
"""
Returns:
set(Node)
"""
return self._dominance_frontier
@dominance_frontier.setter
def dominance_frontier(self, doms: Set["Node"]):
"""
Returns:
set(Node)
"""
self._dominance_frontier = doms
@property
def dominator_successors(self):
return self._dom_successors
@property
def dominance_exploration_ordered(self) -> List["Node"]:
"""
Sorted list of all the nodes to explore to follow the dom
:return: list(nodes)
"""
# Explore direct dominance
to_explore = sorted(list(self.dominator_successors), key=lambda x: x.node_id)
# Explore dominance frontier
# The frontier is the limit where this node dominates
# We need to explore it because the sub of the direct dominance
# Might not be dominator of their own sub
to_explore += sorted(list(self.dominance_frontier), key=lambda x: x.node_id)
return to_explore
# endregion
###################################################################################
###################################################################################
# region Phi operation
###################################################################################
###################################################################################
@property
def phi_origins_local_variables(
self,
) -> Dict[str, Tuple[LocalVariable, Set["Node"]]]:
return self._phi_origins_local_variables
@property
def phi_origins_state_variables(
self,
) -> Dict[str, Tuple[StateVariable, Set["Node"]]]:
return self._phi_origins_state_variables
# @property
# def phi_origin_member_variables(self) -> Dict[str, Tuple[MemberVariable, Set["Node"]]]:
# return self._phi_origins_member_variables
def add_phi_origin_local_variable(self, variable: LocalVariable, node: "Node"):
if variable.name not in self._phi_origins_local_variables:
self._phi_origins_local_variables[variable.name] = (variable, set())
(v, nodes) = self._phi_origins_local_variables[variable.name]
assert v == variable
nodes.add(node)
def add_phi_origin_state_variable(self, variable: StateVariable, node: "Node"):
if variable.canonical_name not in self._phi_origins_state_variables:
self._phi_origins_state_variables[variable.canonical_name] = (
variable,
set(),
)
(v, nodes) = self._phi_origins_state_variables[variable.canonical_name]
assert v == variable
nodes.add(node)
# def add_phi_origin_member_variable(self, variable: MemberVariable, node: "Node"):
# if variable.name not in self._phi_origins_member_variables:
# self._phi_origins_member_variables[variable.name] = (variable, set())
# (v, nodes) = self._phi_origins_member_variables[variable.name]
# assert v == variable
# nodes.add(node)
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
def _find_read_write_call(self): # pylint: disable=too-many-statements
for ir in self.irs:
self._slithir_vars |= {v for v in ir.read if self._is_valid_slithir_var(v)}
if isinstance(ir, OperationWithLValue):
var = ir.lvalue
if var and self._is_valid_slithir_var(var):
self._slithir_vars.add(var)
if not isinstance(ir, (Phi, Index, Member)):
self._vars_read += [v for v in ir.read if self._is_non_slithir_var(v)]
for var in ir.read:
if isinstance(var, ReferenceVariable):
self._vars_read.append(var.points_to_origin)
elif isinstance(ir, (Member, Index)):
var = ir.variable_left if isinstance(ir, Member) else ir.variable_right
if self._is_non_slithir_var(var):
self._vars_read.append(var)
if isinstance(var, ReferenceVariable):
origin = var.points_to_origin
if self._is_non_slithir_var(origin):
self._vars_read.append(origin)
if isinstance(ir, OperationWithLValue):
if isinstance(ir, (Index, Member, Length)):
continue # Don't consider Member and Index operations -> ReferenceVariable
var = ir.lvalue
if isinstance(var, ReferenceVariable):
var = var.points_to_origin
if var and self._is_non_slithir_var(var):
self._vars_written.append(var)
if isinstance(ir, InternalCall):
self._internal_calls.append(ir.function)
if isinstance(ir, SolidityCall):
# TODO: consider removing dependancy of solidity_call to internal_call
self._solidity_calls.append(ir.function)
self._internal_calls.append(ir.function)
if isinstance(ir, LowLevelCall):
assert isinstance(ir.destination, (Variable, SolidityVariable))
self._low_level_calls.append((ir.destination, ir.function_name.value))
elif isinstance(ir, HighLevelCall) and not isinstance(ir, LibraryCall):
if isinstance(ir.destination.type, Contract):
self._high_level_calls.append((ir.destination.type, ir.function))
elif ir.destination == SolidityVariable("this"):
self._high_level_calls.append((self.function.contract, ir.function))
else:
try:
self._high_level_calls.append((ir.destination.type.type, ir.function))
except AttributeError as error:
# pylint: disable=raise-missing-from
raise SlitherException(
f"Function not found on IR: {ir}.\nNode: {self} ({self.source_mapping})\nFunction: {self.function}\nPlease try compiling with a recent Solidity version. {error}"
)
elif isinstance(ir, LibraryCall):
assert isinstance(ir.destination, Contract)
assert isinstance(ir.function, Function)
self._high_level_calls.append((ir.destination, ir.function))
self._library_calls.append((ir.destination, ir.function))
self._vars_read = list(set(self._vars_read))
self._state_vars_read = [v for v in self._vars_read if isinstance(v, StateVariable)]
self._local_vars_read = [v for v in self._vars_read if isinstance(v, LocalVariable)]
self._solidity_vars_read = [v for v in self._vars_read if isinstance(v, SolidityVariable)]
self._vars_written = list(set(self._vars_written))
self._state_vars_written = [v for v in self._vars_written if isinstance(v, StateVariable)]
self._local_vars_written = [v for v in self._vars_written if isinstance(v, LocalVariable)]
self._internal_calls = list(set(self._internal_calls))
self._solidity_calls = list(set(self._solidity_calls))
self._high_level_calls = list(set(self._high_level_calls))
self._library_calls = list(set(self._library_calls))
self._low_level_calls = list(set(self._low_level_calls))
@staticmethod
def _convert_ssa(v: Variable):
if isinstance(v, StateIRVariable):
contract = v.contract
non_ssa_var = contract.get_state_variable_from_name(v.name)
return non_ssa_var
assert isinstance(v, LocalIRVariable)
function = v.function
non_ssa_var = function.get_local_variable_from_name(v.name)
return non_ssa_var
def update_read_write_using_ssa(self):
if not self.expression:
return
for ir in self.irs_ssa:
if isinstance(ir, PhiCallback):
continue
if not isinstance(ir, (Phi, Index, Member)):
self._ssa_vars_read += [
v for v in ir.read if isinstance(v, (StateIRVariable, LocalIRVariable))
]
for var in ir.read:
if isinstance(var, ReferenceVariable):
origin = var.points_to_origin
if isinstance(origin, (StateIRVariable, LocalIRVariable)):
self._ssa_vars_read.append(origin)
elif isinstance(ir, (Member, Index)):
if isinstance(ir.variable_right, (StateIRVariable, LocalIRVariable)):
self._ssa_vars_read.append(ir.variable_right)
if isinstance(ir.variable_right, ReferenceVariable):
origin = ir.variable_right.points_to_origin
if isinstance(origin, (StateIRVariable, LocalIRVariable)):
self._ssa_vars_read.append(origin)
if isinstance(ir, OperationWithLValue):
if isinstance(ir, (Index, Member, Length)):
continue # Don't consider Member and Index operations -> ReferenceVariable
var = ir.lvalue
if isinstance(var, ReferenceVariable):
var = var.points_to_origin
# Only store non-slithIR variables
if var and isinstance(var, (StateIRVariable, LocalIRVariable)):
if isinstance(ir, PhiCallback):
continue
self._ssa_vars_written.append(var)
self._ssa_vars_read = list(set(self._ssa_vars_read))
self._ssa_state_vars_read = [v for v in self._ssa_vars_read if isinstance(v, StateVariable)]
self._ssa_local_vars_read = [v for v in self._ssa_vars_read if isinstance(v, LocalVariable)]
self._ssa_vars_written = list(set(self._ssa_vars_written))
self._ssa_state_vars_written = [
v for v in self._ssa_vars_written if isinstance(v, StateVariable)
]
self._ssa_local_vars_written = [
v for v in self._ssa_vars_written if isinstance(v, LocalVariable)
]
vars_read = [self._convert_ssa(x) for x in self._ssa_vars_read]
vars_written = [self._convert_ssa(x) for x in self._ssa_vars_written]
self._vars_read += [v for v in vars_read if v not in self._vars_read]
self._state_vars_read = [v for v in self._vars_read if isinstance(v, StateVariable)]
self._local_vars_read = [v for v in self._vars_read if isinstance(v, LocalVariable)]
self._vars_written += [v for v in vars_written if v not in self._vars_written]
self._state_vars_written = [v for v in self._vars_written if isinstance(v, StateVariable)]
self._local_vars_written = [v for v in self._vars_written if isinstance(v, LocalVariable)]
# endregion
###################################################################################
###################################################################################
# region Built in definitions
###################################################################################
###################################################################################
def __str__(self):
additional_info = ""
if self.expression:
additional_info += " " + str(self.expression)
elif self.variable_declaration:
additional_info += " " + str(self.variable_declaration)
txt = str(self._node_type) + additional_info
return txt
# endregion
###################################################################################
###################################################################################
# region Utils
###################################################################################
###################################################################################
def link_nodes(node1: Node, node2: Node):
node1.add_son(node2)
node2.add_father(node1)
def insert_node(origin: Node, node_inserted: Node):
sons = origin.sons
link_nodes(origin, node_inserted)
for son in sons:
son.remove_father(origin)
origin.remove_son(son)
link_nodes(node_inserted, son)
def recheable(node: Node) -> Set[Node]:
"""
Return the set of nodes reacheable from the node
:param node:
:return: set(Node)
"""
nodes = node.sons
visited = set()
while nodes:
next_node = nodes[0]
nodes = nodes[1:]
if next_node not in visited:
visited.add(next_node)
for son in next_node.sons:
if son not in visited:
nodes.append(son)
return visited
# endregion
| 38,692 | Python | .py | 895 | 34.311732 | 189 | 0.536315 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,269 | scope.py | NioTheFirst_ScType/slither/core/cfg/scope.py | from typing import List, TYPE_CHECKING, Union
if TYPE_CHECKING:
from slither.core.cfg.node import Node
from slither.core.declarations.function import Function
# pylint: disable=too-few-public-methods
class Scope:
def __init__(self, is_checked: bool, is_yul: bool, scope: Union["Scope", "Function"]):
self.nodes: List["Node"] = []
self.is_checked = is_checked
self.is_yul = is_yul
self.father = scope
| 447 | Python | .py | 11 | 35.363636 | 90 | 0.688222 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,270 | child_function.py | NioTheFirst_ScType/slither/core/children/child_function.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.declarations import Function
class ChildFunction:
def __init__(self) -> None:
super().__init__()
self._function = None
def set_function(self, function: "Function") -> None:
self._function = function
@property
def function(self) -> "Function":
return self._function
| 391 | Python | .py | 12 | 26.833333 | 57 | 0.663102 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,271 | child_structure.py | NioTheFirst_ScType/slither/core/children/child_structure.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.declarations import Structure
class ChildStructure:
def __init__(self):
super().__init__()
self._structure = None
def set_structure(self, structure: "Structure"):
self._structure = structure
@property
def structure(self) -> "Structure":
return self._structure
| 386 | Python | .py | 12 | 26.416667 | 52 | 0.680217 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,272 | child_expression.py | NioTheFirst_ScType/slither/core/children/child_expression.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
class ChildExpression:
def __init__(self):
super().__init__()
self._expression = None
def set_expression(self, expression: "Expression"):
self._expression = expression
@property
def expression(self) -> "Expression":
return self._expression
| 407 | Python | .py | 12 | 28.166667 | 62 | 0.694872 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,273 | child_contract.py | NioTheFirst_ScType/slither/core/children/child_contract.py | from typing import TYPE_CHECKING
from slither.core.source_mapping.source_mapping import SourceMapping
if TYPE_CHECKING:
from slither.core.declarations import Contract
class ChildContract(SourceMapping):
def __init__(self):
super().__init__()
self._contract = None
def set_contract(self, contract: "Contract"):
self._contract = contract
@property
def contract(self) -> "Contract":
return self._contract
| 460 | Python | .py | 13 | 29.923077 | 68 | 0.709751 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,274 | child_event.py | NioTheFirst_ScType/slither/core/children/child_event.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.declarations import Event
class ChildEvent:
def __init__(self):
super().__init__()
self._event = None
def set_event(self, event: "Event"):
self._event = event
@property
def event(self) -> "Event":
return self._event
| 342 | Python | .py | 12 | 22.75 | 47 | 0.636923 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,275 | child_inheritance.py | NioTheFirst_ScType/slither/core/children/child_inheritance.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.declarations import Contract
class ChildInheritance:
def __init__(self):
super().__init__()
self._contract_declarer = None
def set_contract_declarer(self, contract: "Contract"):
self._contract_declarer = contract
@property
def contract_declarer(self) -> "Contract":
return self._contract_declarer
| 423 | Python | .py | 12 | 29.5 | 58 | 0.697044 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,276 | child_node.py | NioTheFirst_ScType/slither/core/children/child_node.py | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.cfg.node import Node
from slither.core.declarations import Function, Contract
class ChildNode:
def __init__(self):
super().__init__()
self._node = None
def set_node(self, node: "Node"):
self._node = node
@property
def node(self) -> "Node":
return self._node
@property
def function(self) -> "Function":
return self.node.function
@property
def contract(self) -> "Contract":
return self.node.function.contract
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self.node.compilation_unit
| 757 | Python | .py | 23 | 26.869565 | 68 | 0.679063 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,277 | structure_variable.py | NioTheFirst_ScType/slither/core/variables/structure_variable.py | from slither.core.variables.variable import Variable
from slither.core.children.child_structure import ChildStructure
class StructureVariable(ChildStructure, Variable):
pass
| 180 | Python | .py | 4 | 42.5 | 64 | 0.867816 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,278 | local_variable_init_from_tuple.py | NioTheFirst_ScType/slither/core/variables/local_variable_init_from_tuple.py | from typing import Optional
from slither.core.variables.local_variable import LocalVariable
class LocalVariableInitFromTuple(LocalVariable):
"""
Use on this pattern:
var(a,b) = f()
It is not possible to split the variable declaration in sigleton and keep the init value
We init a and b with f(). get_tuple_index ret() returns which returns values of f is to be used
"""
def __init__(self):
super().__init__()
self._tuple_index: Optional[int] = None
@property
def tuple_index(self) -> Optional[int]:
return self._tuple_index
@tuple_index.setter
def tuple_index(self, idx: int):
self._tuple_index = idx
| 685 | Python | .py | 18 | 32.388889 | 99 | 0.682853 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,279 | state_variable.py | NioTheFirst_ScType/slither/core/variables/state_variable.py | from typing import Optional, TYPE_CHECKING
from slither.core.children.child_contract import ChildContract
from slither.core.variables.variable import Variable
if TYPE_CHECKING:
from slither.core.cfg.node import Node
from slither.core.declarations import Contract
class StateVariable(ChildContract, Variable):
def __init__(self):
super().__init__()
self._node_initialization: Optional["Node"] = None
def is_declared_by(self, contract: "Contract") -> bool:
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
# endregion
###################################################################################
###################################################################################
# region Name
###################################################################################
###################################################################################
@property
def canonical_name(self) -> str:
return f"{self.contract.name}.{self.name}"
@property
def full_name(self) -> str:
"""
Return the name of the state variable as a function signaure
str: func_name(type1,type2)
:return: the function signature without the return values
"""
name, parameters, _ = self.signature
return name + "(" + ",".join(parameters) + ")"
# endregion
###################################################################################
###################################################################################
# region IRs (initialization)
###################################################################################
###################################################################################
@property
def node_initialization(self) -> Optional["Node"]:
"""
Node for the state variable initalization
:return:
"""
return self._node_initialization
@node_initialization.setter
def node_initialization(self, node_initialization):
self._node_initialization = node_initialization
# endregion
###################################################################################
###################################################################################
| 2,431 | Python | .py | 54 | 38.537037 | 87 | 0.41649 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,280 | top_level_variable.py | NioTheFirst_ScType/slither/core/variables/top_level_variable.py | from typing import Optional, TYPE_CHECKING
from slither.core.declarations.top_level import TopLevel
from slither.core.variables.variable import Variable
if TYPE_CHECKING:
from slither.core.cfg.node import Node
from slither.core.scope.scope import FileScope
class TopLevelVariable(TopLevel, Variable):
def __init__(self, scope: "FileScope"):
super().__init__()
self._node_initialization: Optional["Node"] = None
self.file_scope = scope
# endregion
###################################################################################
###################################################################################
# region IRs (initialization)
###################################################################################
###################################################################################
@property
def node_initialization(self) -> Optional["Node"]:
"""
Node for the state variable initalization
:return:
"""
return self._node_initialization
@node_initialization.setter
def node_initialization(self, node_initialization):
self._node_initialization = node_initialization
# endregion
###################################################################################
###################################################################################
| 1,418 | Python | .py | 30 | 41.466667 | 87 | 0.439855 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,281 | function_type_variable.py | NioTheFirst_ScType/slither/core/variables/function_type_variable.py | """
Variable used with FunctionType
ex:
struct C{
function(uint) my_func;
}
"""
from .variable import Variable
class FunctionTypeVariable(Variable):
pass
| 185 | Python | .py | 10 | 14.4 | 37 | 0.686047 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,282 | local_variable.py | NioTheFirst_ScType/slither/core/variables/local_variable.py | from typing import Optional
from slither.core.variables.variable import Variable
from slither.core.children.child_function import ChildFunction
from slither.core.solidity_types.user_defined_type import UserDefinedType
from slither.core.solidity_types.array_type import ArrayType
from slither.core.solidity_types.mapping_type import MappingType
from slither.core.solidity_types.elementary_type import ElementaryType
from slither.core.declarations.structure import Structure
class LocalVariable(ChildFunction, Variable):
def __init__(self) -> None:
super().__init__()
self._location: Optional[str] = None
#self._token_type = -2
def set_location(self, loc: str) -> None:
self._location = loc
@property
def location(self) -> Optional[str]:
"""
Variable Location
Can be storage/memory or default
Returns:
(str)
"""
return self._location
@property
def is_scalar(self) -> bool:
return isinstance(self.type, ElementaryType) and not self.is_storage
def non_ssa_version(self):
return self
#@property
#def token_type(self) -> int:
# return self._token_type
#
#def token_type(self, a: int) -> None:
# self._token_type = a
@ property
def is_storage(self) -> bool:
"""
Return true if the variable is located in storage
See https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
Returns:
(bool)
"""
if self.location == "memory":
return False
# Use by slithIR SSA
if self.location == "reference_to_storage":
return False
if self.location == "storage":
return True
if isinstance(self.type, (ArrayType, MappingType)):
return True
if isinstance(self.type, UserDefinedType):
return isinstance(self.type.type, Structure)
return False
@property
def canonical_name(self) -> str:
return f"{self.function.canonical_name}.{self.name}"
| 2,141 | Python | .py | 58 | 29.293103 | 112 | 0.651669 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,283 | event_variable.py | NioTheFirst_ScType/slither/core/variables/event_variable.py | from slither.core.variables.variable import Variable
from slither.core.children.child_event import ChildEvent
class EventVariable(ChildEvent, Variable):
def __init__(self):
super().__init__()
self._indexed = False
@property
def indexed(self) -> bool:
"""
Indicates whether the event variable is indexed in the bloom filter.
:return: Returns True if the variable is indexed in bloom filter, False otherwise.
"""
return self._indexed
@indexed.setter
def indexed(self, is_indexed: bool):
self._indexed = is_indexed
| 600 | Python | .py | 16 | 31 | 90 | 0.677586 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,284 | variable.py | NioTheFirst_ScType/slither/core/variables/variable.py | """
Variable module
"""
from typing import Optional, TYPE_CHECKING, List, Union, Tuple
from slither.detectors.my_detectors.ExtendedType import ExtendedType
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.solidity_types.type import Type
from slither.core.solidity_types.elementary_type import ElementaryType
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
# pylint: disable=too-many-instance-attributes
class Variable(SourceMapping):
def __init__(self):
super().__init__()
self._name: Optional[str] = None
self._initial_expression: Optional["Expression"] = None
self._type: Optional[Type] = None
self._dnode = None
self._initialized: Optional[bool] = None
self._dnode = None
self._visibility: Optional[str] = None
self._is_constant = False
self._is_immutable: bool = False
self._is_reentrant: bool = True
self._write_protection: Optional[List[str]] = None
self._token_type = -2
self._token_dim = 0;
self._token_typen : List[int] = []
self._token_typed : List[int] = []
self._norm = 0;
self._parent_function : Optional[str] = None
self._link_function : Optional[str] = None
self._tname: Optional[str] = None
self._et = ExtendedType()
@property
def is_scalar(self) -> bool:
return isinstance(self.type, ElementaryType)
@property
def expression(self) -> Optional["Expression"]:
"""
Expression: Expression of the node (if initialized)
Initial expression may be different than the expression of the node
where the variable is declared, if its used ternary operator
Ex: uint a = b?1:2
The expression associated to a is uint a = b?1:2
But two nodes are created,
one where uint a = 1,
and one where uint a = 2
"""
return self._initial_expression
@expression.setter
def expression(self, expr: "Expression") -> None:
self._initial_expression = expr
@property
def initialized(self) -> Optional[bool]:
"""
boolean: True if the variable is initialized at construction
"""
return self._initialized
@initialized.setter
def initialized(self, is_init: bool):
self._initialized = is_init
@property
def uninitialized(self) -> bool:
"""
boolean: True if the variable is not initialized
"""
return not self._initialized
@property
def dnode(self):
return self._dnode
@dnode.setter
def dnode(self, node):
self._dnode = node
@property
def extok(self):
return self._et
@property
def name(self) -> Optional[str]:
"""
str: variable name
"""
return self._name
@name.setter
def name(self, name):
self._et.name = name
self._name = name
@property
def link_function(self)->Optional[str]:
return self._et.linked_contract
@link_function.setter
def link_function(self, function):
self._link_function = function
self._et.linked_contract = function
def change_name(self, name):
self._tname = name
@property
def norm(self) -> int:
return self._norm
@norm.setter
def norm(self, norm):
self._norm = norm
@property
def tname(self)-> Optional[str]:
return self._tname
@property
def parent_function(self) -> Optional[str]:
"""
str: variable name
"""
return self._parent_function
@parent_function.setter
def parent_function(self, name):
self._et.function_name = name
self._parent_function = name
@property
def token_typen(self) -> Optional[int]:
#return self._token_typen
return self._et.num_token_types
def add_token_typen(self, a):
for denom in self._token_typed:
if(denom == a):
if(a!=-1):
self._token_typed.remove(denom)
return
if((a in self._token_typen and a == -1) or (a==-1 and len(self._token_typen) > 0 and (not(a in self._token_typen)))):
return
if(-1 in self._token_typen and a != -1):
self._token_typen.remove(-1)
self._token_typen.append(a)
self._et.add_num_token_type(a)
@property
def token_typed(self) -> Optional[int]:
#return self._token_typed
return self._et.den_token_types
def add_token_typed(self, a):
for num in self._token_typen:
if(num == a):
if(a != -1):
self._token_typen.remove(num)
return
if((a in self._token_typed and a == -1) or (a==-1 and len(self._token_typed) > 0 and (not(a in self._token_typed)))):
return
if(-1 in self._token_typed and a != -1):
self._token_typed.remove(-1)
self._token_typed.append(a)
self._et.add_den_token_type(a)
@property
def token_type(self):
return self._token_type
@token_type.setter
def token_type(self, toke_type):
self._token_type = toke_type
@property
def token_dim(self):
return self._token_dim
@token_type.setter
def token_dim(self, toke_dim):
self._token_dim = toke_dim
@property
def type(self) -> Optional[Union[Type, List[Type]]]:
return self._type
@type.setter
def type(self, types: Union[Type, List[Type]]):
if(str(types) == "address"):
self._et.linked_contract = self._et.name
self._type = types
@property
def is_constant(self) -> bool:
return self._is_constant
@property
def dnode(self):
return self._dnode
@dnode.setter
def dnode(self, node):
self._dnode = node
@is_constant.setter
def is_constant(self, is_cst: bool):
self._is_constant = is_cst
@property
def is_reentrant(self) -> bool:
return self._is_reentrant
@is_reentrant.setter
def is_reentrant(self, is_reentrant: bool) -> None:
self._is_reentrant = is_reentrant
@property
def write_protection(self) -> Optional[List[str]]:
return self._write_protection
@write_protection.setter
def write_protection(self, write_protection: List[str]) -> None:
self._write_protection = write_protection
@property
def visibility(self) -> Optional[str]:
"""
str: variable visibility
"""
return self._visibility
@visibility.setter
def visibility(self, v: str) -> None:
self._visibility = v
def set_type(self, t: Optional[Union[List, Type, str]]) -> None:
if isinstance(t, str):
self._type = ElementaryType(t)
return
assert isinstance(t, (Type, list)) or t is None
self._type = t
@property
def is_immutable(self) -> bool:
"""
Return true of the variable is immutable
:return:
"""
return self._is_immutable
@is_immutable.setter
def is_immutable(self, immutablility: bool) -> None:
self._is_immutable = immutablility
###################################################################################
###################################################################################
# region Signature
###################################################################################
###################################################################################
@property
def signature(self) -> Tuple[str, List[str], List[str]]:
"""
Return the signature of the state variable as a function signature
:return: (str, list(str), list(str)), as (name, list parameters type, list return values type)
"""
# pylint: disable=import-outside-toplevel
from slither.utils.type import (
export_nested_types_from_variable,
export_return_type_from_variable,
)
return (
self.name,
[str(x) for x in export_nested_types_from_variable(self)],
[str(x) for x in export_return_type_from_variable(self)],
)
@property
def signature_str(self) -> str:
"""
Return the signature of the state variable as a function signature
:return: str: func_name(type1,type2) returns(type3)
"""
name, parameters, returnVars = self.signature
return name + "(" + ",".join(parameters) + ") returns(" + ",".join(returnVars) + ")"
@property
def solidity_signature(self) -> str:
name, parameters, _ = self.signature
return f'{name}({",".join(parameters)})'
def __str__(self) -> str:
return self._name
| 8,930 | Python | .py | 251 | 27.677291 | 125 | 0.58108 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,285 | source_mapping.py | NioTheFirst_ScType/slither/core/source_mapping/source_mapping.py | import re
from abc import ABCMeta
from typing import Dict, Union, List, Tuple, TYPE_CHECKING, Optional
from crytic_compile.utils.naming import Filename
from slither.core.context.context import Context
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
# We split the source mapping into two objects
# The reasoning is to allow any object to just inherit from SourceMapping
# To have then everything accessible through obj.source_mapping._
# All an object needs to do is to inherits from SourceMapping
# And call set_offset at some point
# pylint: disable=too-many-instance-attributes
class Source:
def __init__(self) -> None:
self.start: int = 0
self.length: int = 0
self.filename: Filename = Filename("", "", "", "")
self.is_dependency: bool = False
self.lines: List[int] = []
self.starting_column: int = 0
self.ending_column: int = 0
self.end: int = 0
self.compilation_unit: Optional["SlitherCompilationUnit"] = None
def to_json(self) -> Dict:
return {
"start": self.start,
"length": self.length,
# TODO investigate filename_used usecase
# It creates non-deterministic result
# As it sometimes refer to the relative and sometimes to the absolute
# "filename_used": self.filename.used,
"filename_relative": self.filename.relative,
"filename_absolute": self.filename.absolute,
"filename_short": self.filename.short,
"is_dependency": self.is_dependency,
"lines": self.lines,
"starting_column": self.starting_column,
"ending_column": self.ending_column,
}
def to_markdown(self, markdown_root: str) -> str:
lines = self._get_lines_str(line_descr="L")
filename_relative: str = self.filename.relative if self.filename.relative else ""
return f"{markdown_root}{filename_relative}{lines}"
def to_detailled_str(self) -> str:
lines = self._get_lines_str()
filename_short: str = self.filename.short if self.filename.short else ""
return f"{filename_short}{lines} ({self.starting_column} - {self.ending_column})"
def _get_lines_str(self, line_descr=""):
# If the compilation unit was not initialized, it means that the set_offset was never called
# on the corresponding object, which should not happen
assert self.compilation_unit is not None
line_prefix = self.compilation_unit.core.line_prefix
lines = self.lines
if not lines:
lines = ""
elif len(lines) == 1:
lines = f"{line_prefix}{line_descr}{lines[0]}"
else:
lines = f"{line_prefix}{line_descr}{lines[0]}-{line_descr}{lines[-1]}"
return lines
def __str__(self) -> str:
lines = self._get_lines_str()
filename_short: str = self.filename.short if self.filename.short else ""
return f"{filename_short}{lines}"
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return (
self.start == other.start
and self.length == other.length
and self.filename == other.filename
and self.is_dependency == other.is_dependency
and self.lines == other.lines
and self.starting_column == other.starting_column
and self.ending_column == other.ending_column
and self.end == other.end
)
def _compute_line(
compilation_unit: "SlitherCompilationUnit", filename: Filename, start: int, length: int
) -> Tuple[List[int], int, int]:
"""
Compute line(s) numbers and starting/ending columns
from a start/end offset. All numbers start from 1.
Not done in an efficient way
"""
start_line, starting_column = compilation_unit.core.crytic_compile.get_line_from_offset(
filename, start
)
end_line, ending_column = compilation_unit.core.crytic_compile.get_line_from_offset(
filename, start + length
)
return list(range(start_line, end_line + 1)), starting_column, ending_column
def _convert_source_mapping(
offset: str, compilation_unit: "SlitherCompilationUnit"
) -> Source: # pylint: disable=too-many-locals
"""
Convert a text offset to a real offset
see https://solidity.readthedocs.io/en/develop/miscellaneous.html#source-mappings
Returns:
(dict): {'start':0, 'length':0, 'filename': 'file.sol'}
"""
sourceUnits = compilation_unit.source_units
position = re.findall("([0-9]*):([0-9]*):([-]?[0-9]*)", offset)
if len(position) != 1:
return Source()
s, l, f = position[0]
s = int(s)
l = int(l)
f = int(f)
if f not in sourceUnits:
new_source = Source()
new_source.start = s
new_source.length = l
return new_source
filename_used = sourceUnits[f]
# If possible, convert the filename to its absolute/relative version
assert compilation_unit.core.crytic_compile
filename: Filename = compilation_unit.core.crytic_compile.filename_lookup(filename_used)
is_dependency = compilation_unit.core.crytic_compile.is_dependency(filename.absolute)
(lines, starting_column, ending_column) = _compute_line(compilation_unit, filename, s, l)
new_source = Source()
new_source.start = s
new_source.length = l
new_source.filename = filename
new_source.is_dependency = is_dependency
new_source.lines = lines
new_source.starting_column = starting_column
new_source.ending_column = ending_column
new_source.end = new_source.start + l
return new_source
class SourceMapping(Context, metaclass=ABCMeta):
def __init__(self) -> None:
super().__init__()
# self._source_mapping: Optional[Dict] = None
self.source_mapping: Source = Source()
self.references: List[Source] = []
def set_offset(
self, offset: Union["Source", str], compilation_unit: "SlitherCompilationUnit"
) -> None:
if isinstance(offset, Source):
self.source_mapping.start = offset.start
self.source_mapping.length = offset.length
self.source_mapping.filename = offset.filename
self.source_mapping.is_dependency = offset.is_dependency
self.source_mapping.lines = offset.lines
self.source_mapping.starting_column = offset.starting_column
self.source_mapping.ending_column = offset.ending_column
self.source_mapping.end = offset.end
else:
self.source_mapping = _convert_source_mapping(offset, compilation_unit)
self.source_mapping.compilation_unit = compilation_unit
def add_reference_from_raw_source(
self, offset: str, compilation_unit: "SlitherCompilationUnit"
) -> None:
s = _convert_source_mapping(offset, compilation_unit)
self.references.append(s)
| 7,082 | Python | .py | 159 | 36.773585 | 100 | 0.655348 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,286 | structure_contract.py | NioTheFirst_ScType/slither/core/declarations/structure_contract.py | from slither.core.children.child_contract import ChildContract
from slither.core.declarations import Structure
class StructureContract(Structure, ChildContract):
def is_declared_by(self, contract):
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
| 368 | Python | .py | 10 | 30.4 | 62 | 0.710674 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,287 | solidity_variables.py | NioTheFirst_ScType/slither/core/declarations/solidity_variables.py | # https://solidity.readthedocs.io/en/v0.4.24/units-and-global-variables.html
from typing import List, Dict, Union, TYPE_CHECKING
from slither.core.declarations.custom_error import CustomError
from slither.core.solidity_types import ElementaryType, TypeInformation
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.exceptions import SlitherException
from slither.detectors.my_detectors.ExtendedType import ExtendedType
if TYPE_CHECKING:
pass
SOLIDITY_VARIABLES = {
"now": "uint256",
"this": "address",
"abi": "address", # to simplify the conversion, assume that abi return an address
"msg": "",
"tx": "",
"block": "",
"super": "",
}
SOLIDITY_VARIABLES_COMPOSED = {
"block.basefee": "uint",
"block.coinbase": "address",
"block.difficulty": "uint256",
"block.gaslimit": "uint256",
"block.number": "uint256",
"block.timestamp": "uint256",
"block.blockhash": "uint256", # alias for blockhash. It's a call
"block.chainid": "uint256",
"msg.data": "bytes",
"msg.gas": "uint256",
"msg.sender": "address",
"msg.sig": "bytes4",
"msg.value": "uint256",
"tx.gasprice": "uint256",
"tx.origin": "address",
}
SOLIDITY_FUNCTIONS: Dict[str, List[str]] = {
"gasleft()": ["uint256"],
"assert(bool)": [],
"require(bool)": [],
"require(bool,string)": [],
"revert()": [],
"revert(string)": [],
"revert ": [],
"addmod(uint256,uint256,uint256)": ["uint256"],
"mulmod(uint256,uint256,uint256)": ["uint256"],
"keccak256()": ["bytes32"],
"keccak256(bytes)": ["bytes32"], # Solidity 0.5
"sha256()": ["bytes32"],
"sha256(bytes)": ["bytes32"], # Solidity 0.5
"sha3()": ["bytes32"],
"ripemd160()": ["bytes32"],
"ripemd160(bytes)": ["bytes32"], # Solidity 0.5
"ecrecover(bytes32,uint8,bytes32,bytes32)": ["address"],
"selfdestruct(address)": [],
"suicide(address)": [],
"log0(bytes32)": [],
"log1(bytes32,bytes32)": [],
"log2(bytes32,bytes32,bytes32)": [],
"log3(bytes32,bytes32,bytes32,bytes32)": [],
"blockhash(uint256)": ["bytes32"],
# the following need a special handling
# as they are recognized as a SolidityVariableComposed
# and converted to a SolidityFunction by SlithIR
"this.balance()": ["uint256"],
"abi.encode()": ["bytes"],
"abi.encodePacked()": ["bytes"],
"abi.encodeWithSelector()": ["bytes"],
"abi.encodeWithSignature()": ["bytes"],
"abi.encodeCall()": ["bytes"],
"bytes.concat()": ["bytes"],
"string.concat()": ["string"],
# abi.decode returns an a list arbitrary types
"abi.decode()": [],
"type(address)": [],
"type()": [], # 0.6.8 changed type(address) to type()
# The following are conversion from address.something
"balance(address)": ["uint256"],
"code(address)": ["bytes"],
"codehash(address)": ["bytes32"],
}
def solidity_function_signature(name):
"""
Return the function signature (containing the return value)
It is useful if a solidity function is used as a pointer
(see exoressionParsing.find_variable documentation)
Args:
name(str):
Returns:
str
"""
return name + f" returns({','.join(SOLIDITY_FUNCTIONS[name])})"
class SolidityVariable(SourceMapping):
def __init__(self, name: str):
super().__init__()
self._check_name(name)
self._name = name
self._ef = ExtendedType()
self._ef.name = name
self._parent_function = None
# dev function, will be removed once the code is stable
def _check_name(self, name: str): # pylint: disable=no-self-use
assert name in SOLIDITY_VARIABLES or name.endswith(("_slot", "_offset"))
@property
def extok(self):
return self._extok
@property
def state_variable(self):
if self._name.endswith("_slot"):
return self._name[:-5]
if self._name.endswith("_offset"):
return self._name[:-7]
to_log = f"Incorrect YUL parsing. {self} is not a solidity variable that can be seen as a state variable"
raise SlitherException(to_log)
@property
def name(self) -> str:
return self._name
@property
def type(self) -> ElementaryType:
return ElementaryType(SOLIDITY_VARIABLES[self.name])
def __str__(self):
return self._name
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name
def __hash__(self):
return hash(self.name)
class SolidityVariableComposed(SolidityVariable):
def _check_name(self, name: str):
assert name in SOLIDITY_VARIABLES_COMPOSED
@property
def name(self) -> str:
return self._name
@property
def extok(self):
return self._ef
@property
def parent_function(self):
return self._parent_function
@parent_function.setter
def parent_function(self, name):
self._parent_function = name
@property
def type(self) -> ElementaryType:
return ElementaryType(SOLIDITY_VARIABLES_COMPOSED[self.name])
def __str__(self):
return self._name
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name
def __hash__(self):
return hash(self.name)
class SolidityFunction(SourceMapping):
# Non standard handling of type(address). This function returns an undefined object
# The type is dynamic
# https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#type-information
# As a result, we set return_type during the Ir conversion
def __init__(self, name: str):
super().__init__()
assert name in SOLIDITY_FUNCTIONS
self._name = name
# Can be TypeInformation if type(address) is used
self._return_type: List[Union[TypeInformation, ElementaryType]] = [
ElementaryType(x) for x in SOLIDITY_FUNCTIONS[self.name]
]
@property
def name(self) -> str:
return self._name
@property
def full_name(self) -> str:
return self.name
@property
def return_type(self) -> List[Union[TypeInformation, ElementaryType]]:
return self._return_type
@return_type.setter
def return_type(self, r: List[Union[TypeInformation, ElementaryType]]):
self._return_type = r
def __str__(self):
return self._name
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name
def __hash__(self):
return hash(self.name)
class SolidityCustomRevert(SolidityFunction):
def __init__(self, custom_error: CustomError): # pylint: disable=super-init-not-called
self._name = "revert " + custom_error.solidity_signature
self._custom_error = custom_error
self._return_type: List[Union[TypeInformation, ElementaryType]] = []
def __eq__(self, other):
return (
self.__class__ == other.__class__
and self.name == other.name
and self._custom_error == other._custom_error
)
def __hash__(self):
return hash(hash(self.name) + hash(self._custom_error))
| 7,233 | Python | .py | 193 | 31.373057 | 113 | 0.635662 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,288 | enum.py | NioTheFirst_ScType/slither/core/declarations/enum.py | from typing import List
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.detectors.my_detectors.ExtendedType import ExtendedType
class Enum(SourceMapping):
def __init__(self, name: str, canonical_name: str, values: List[str]):
super().__init__()
self._name = name
self._canonical_name = canonical_name
self._values = values
self._min = 0
self._ex = ExtendedType()
self._ex.name = name
self._ex.function_name = "global"
# The max value of an Enum is the index of the last element
self._max = len(values) - 1
@property
def canonical_name(self) -> str:
return self._canonical_name
@property
def name(self) -> str:
return self._name
@property
def values(self) -> List[str]:
return self._values
@property
def min(self) -> int:
return self._min
@property
def max(self) -> int:
return self._max
@property
def extok(self):
return self._ex
def __str__(self):
return self.name
| 1,101 | Python | .py | 35 | 24.714286 | 74 | 0.625355 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,289 | function.py | NioTheFirst_ScType/slither/core/declarations/function.py | """
Function module
"""
import logging
from abc import abstractmethod, ABCMeta
from collections import namedtuple
from enum import Enum
from itertools import groupby
import copy
from typing import Dict, TYPE_CHECKING, List, Optional, Set, Union, Callable, Tuple
from slither.core.cfg.scope import Scope
from slither.core.declarations.solidity_variables import (
SolidityFunction,
SolidityVariable,
SolidityVariableComposed,
)
from slither.core.expressions import (
Identifier,
IndexAccess,
MemberAccess,
UnaryOperation,
)
from slither.core.solidity_types.type import Type
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.state_variable import StateVariable
from slither.utils.type import convert_type_for_solidity_signature_to_string
from slither.utils.utils import unroll
# pylint: disable=import-outside-toplevel,too-many-instance-attributes,too-many-statements,too-many-lines
if TYPE_CHECKING:
from slither.utils.type_helpers import (
InternalCallType,
LowLevelCallType,
HighLevelCallType,
LibraryCallType,
)
from slither.core.declarations import Contract
from slither.core.cfg.node import Node, NodeType
from slither.core.variables.variable import Variable
from slither.slithir.variables.variable import SlithIRVariable
from slither.slithir.variables import LocalIRVariable
from slither.core.expressions.expression import Expression
from slither.slithir.operations import Operation
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.scope.scope import FileScope
LOGGER = logging.getLogger("Function")
ReacheableNode = namedtuple("ReacheableNode", ["node", "ir"])
class ModifierStatements:
def __init__(
self,
modifier: Union["Contract", "Function"],
entry_point: "Node",
nodes: List["Node"],
):
self._modifier = modifier
self._entry_point = entry_point
self._nodes = nodes
@property
def modifier(self) -> Union["Contract", "Function"]:
return self._modifier
@property
def entry_point(self) -> "Node":
return self._entry_point
@entry_point.setter
def entry_point(self, entry_point: "Node"):
self._entry_point = entry_point
@property
def nodes(self) -> List["Node"]:
return self._nodes
@nodes.setter
def nodes(self, nodes: List["Node"]):
self._nodes = nodes
class FunctionType(Enum):
NORMAL = 0
CONSTRUCTOR = 1
FALLBACK = 2
RECEIVE = 3
CONSTRUCTOR_VARIABLES = 10 # Fake function to hold variable declaration statements
CONSTRUCTOR_CONSTANT_VARIABLES = 11 # Fake function to hold variable declaration statements
def _filter_state_variables_written(expressions: List["Expression"]):
ret = []
for expression in expressions:
if isinstance(expression, Identifier):
ret.append(expression)
if isinstance(expression, UnaryOperation):
ret.append(expression.expression)
if isinstance(expression, MemberAccess):
ret.append(expression.expression)
if isinstance(expression, IndexAccess):
ret.append(expression.expression_left)
return ret
class FunctionLanguage(Enum):
Solidity = 0
Yul = 1
Vyper = 2
class Function(SourceMapping, metaclass=ABCMeta): # pylint: disable=too-many-public-methods
"""
Function class
"""
def __init__(self, compilation_unit: "SlitherCompilationUnit"):
super().__init__()
self._internal_scope: List[str] = []
self._name: Optional[str] = None
self._view: bool = False
self._pure: bool = False
self._payable: bool = False
self._visibility: Optional[str] = None
self._is_implemented: Optional[bool] = None
self._is_empty: Optional[bool] = None
self._entry_point: Optional["Node"] = None
self._nodes: List["Node"] = []
self._variables: Dict[str, "LocalVariable"] = {}
# slithir Temporary and references variables (but not SSA)
self._slithir_variables: Set["SlithIRVariable"] = set()
self._parameters: List["LocalVariable"] = []
self._parameter_cache: List[List[List[List[int]]]] = []
self._parameter_cache_return = []
self._parameters_ssa: List["LocalIRVariable"] = []
self._parameters_src: SourceMapping = SourceMapping()
self._returns: List["LocalVariable"] = []
self._returns_ssa: List["LocalIRVariable"] = []
self._returns_src: SourceMapping = SourceMapping()
self._return_values: Optional[List["SlithIRVariable"]] = None
self._return_values_ssa: Optional[List["SlithIRVariable"]] = None
self._vars_read: List["Variable"] = []
self._vars_written: List["Variable"] = []
self._state_vars_read: List["StateVariable"] = []
self._vars_read_or_written: List["Variable"] = []
self._solidity_vars_read: List["SolidityVariable"] = []
self._state_vars_written: List["StateVariable"] = []
self._internal_calls: List["InternalCallType"] = []
self._solidity_calls: List["SolidityFunction"] = []
self._low_level_calls: List["LowLevelCallType"] = []
self._high_level_calls: List["HighLevelCallType"] = []
self._library_calls: List["LibraryCallType"] = []
self._external_calls_as_expressions: List["Expression"] = []
self._expression_vars_read: List["Expression"] = []
self._expression_vars_written: List["Expression"] = []
self._expression_calls: List["Expression"] = []
# self._expression_modifiers: List["Expression"] = []
self._modifiers: List[ModifierStatements] = []
self._explicit_base_constructor_calls: List[ModifierStatements] = []
self._contains_assembly: bool = False
self._expressions: Optional[List["Expression"]] = None
self._slithir_operations: Optional[List["Operation"]] = None
self._slithir_ssa_operations: Optional[List["Operation"]] = None
self._all_expressions: Optional[List["Expression"]] = None
self._all_slithir_operations: Optional[List["Operation"]] = None
self._all_internals_calls: Optional[List["InternalCallType"]] = None
self._all_high_level_calls: Optional[List["HighLevelCallType"]] = None
self._all_library_calls: Optional[List["LibraryCallType"]] = None
self._all_low_level_calls: Optional[List["LowLevelCallType"]] = None
self._all_solidity_calls: Optional[List["SolidityFunction"]] = None
self._all_state_variables_read: Optional[List["StateVariable"]] = None
self._all_solidity_variables_read: Optional[List["SolidityVariable"]] = None
self._all_state_variables_written: Optional[List["StateVariable"]] = None
self._all_slithir_variables: Optional[List["SlithIRVariable"]] = None
self._all_nodes: Optional[List["Node"]] = None
self._all_conditional_state_variables_read: Optional[List["StateVariable"]] = None
self._all_conditional_state_variables_read_with_loop: Optional[List["StateVariable"]] = None
self._all_conditional_solidity_variables_read: Optional[List["SolidityVariable"]] = None
self._all_conditional_solidity_variables_read_with_loop: Optional[
List["SolidityVariable"]
] = None
self._all_solidity_variables_used_as_args: Optional[List["SolidityVariable"]] = None
self._is_shadowed: bool = False
self._shadows: bool = False
# set(ReacheableNode)
self._reachable_from_nodes: Set[ReacheableNode] = set()
self._reachable_from_functions: Set[Function] = set()
self._all_reachable_from_functions: Optional[Set[Function]] = None
# Constructor, fallback, State variable constructor
self._function_type: Optional[FunctionType] = None
self._is_constructor: Optional[bool] = None
# Computed on the fly, can be True of False
self._can_reenter: Optional[bool] = None
self._can_send_eth: Optional[bool] = None
self._nodes_ordered_dominators: Optional[List["Node"]] = None
self._counter_nodes = 0
# Memoize parameters:
# TODO: identify all the memoize parameters and add a way to undo the memoization
self._full_name: Optional[str] = None
self._signature: Optional[Tuple[str, List[str], List[str]]] = None
self._solidity_signature: Optional[str] = None
self._signature_str: Optional[str] = None
self._canonical_name: Optional[str] = None
self._is_protected: Optional[bool] = None
self.compilation_unit: "SlitherCompilationUnit" = compilation_unit
# Assume we are analyzing Solidity by default
self.function_language: FunctionLanguage = FunctionLanguage.Solidity
self._id: Optional[str] = None
# To be improved with a parsing of the documentation
self.has_documentation: bool = False
###################################################################################
###################################################################################
# region General properties
###################################################################################
###################################################################################
@property
def name(self) -> str:
"""
str: function name
"""
if self._name == "" and self._function_type == FunctionType.CONSTRUCTOR:
return "constructor"
if self._function_type == FunctionType.FALLBACK:
return "fallback"
if self._function_type == FunctionType.RECEIVE:
return "receive"
if self._function_type == FunctionType.CONSTRUCTOR_VARIABLES:
return "slitherConstructorVariables"
if self._function_type == FunctionType.CONSTRUCTOR_CONSTANT_VARIABLES:
return "slitherConstructorConstantVariables"
return self._name
@name.setter
def name(self, new_name: str):
self._name = new_name
@property
def internal_scope(self) -> List[str]:
"""
Return a list of name representing the scope of the function
This is used to model nested functions declared in YUL
:return:
"""
return self._internal_scope
@internal_scope.setter
def internal_scope(self, new_scope: List[str]):
self._internal_scope = new_scope
@property
def full_name(self) -> str:
"""
str: func_name(type1,type2)
Return the function signature without the return values
The difference between this function and solidity_function is that full_name does not translate the underlying
type (ex: structure, contract to address, ...)
"""
if self._full_name is None:
name, parameters, _ = self.signature
full_name = ".".join(self._internal_scope + [name]) + "(" + ",".join(parameters) + ")"
self._full_name = full_name
return self._full_name
@property
@abstractmethod
def canonical_name(self) -> str:
"""
str: contract.func_name(type1,type2)
Return the function signature without the return values
"""
return ""
@property
def contains_assembly(self) -> bool:
return self._contains_assembly
@contains_assembly.setter
def contains_assembly(self, c: bool):
self._contains_assembly = c
def can_reenter(self, callstack=None) -> bool:
"""
Check if the function can re-enter
Follow internal calls.
Do not consider CREATE as potential re-enter, but check if the
destination's constructor can contain a call (recurs. follow nested CREATE)
For Solidity > 0.5, filter access to public variables and constant/pure/view
For call to this. check if the destination can re-enter
Do not consider Send/Transfer as there is not enough gas
:param callstack: used internally to check for recursion
:return bool:
"""
from slither.slithir.operations import Call
if self._can_reenter is None:
self._can_reenter = False
for ir in self.all_slithir_operations():
if isinstance(ir, Call) and ir.can_reenter(callstack):
self._can_reenter = True
return True
return self._can_reenter
def can_send_eth(self) -> bool:
"""
Check if the function or any internal (not external) functions called by it can send eth
:return bool:
"""
from slither.slithir.operations import Call
if self._can_send_eth is None:
self._can_send_eth = False
for ir in self.all_slithir_operations():
if isinstance(ir, Call) and ir.can_send_eth():
self._can_send_eth = True
return True
return self._can_send_eth
@property
def is_checked(self) -> bool:
"""
Return true if the overflow are enabled by default
:return:
"""
return self.compilation_unit.solc_version >= "0.8.0"
@property
def id(self) -> Optional[str]:
"""
Return the ID of the funciton. For Solidity with compact-AST the ID is the reference ID
For other, the ID is None
:return:
:rtype:
"""
return self._id
@id.setter
def id(self, new_id: str):
self._id = new_id
@property
@abstractmethod
def file_scope(self) -> "FileScope":
pass
# endregion
###################################################################################
###################################################################################
# region Type (FunctionType)
###################################################################################
###################################################################################
def set_function_type(self, t: FunctionType):
assert isinstance(t, FunctionType)
self._function_type = t
@property
def function_type(self) -> Optional[FunctionType]:
return self._function_type
@function_type.setter
def function_type(self, t: FunctionType):
self._function_type = t
@property
def is_constructor(self) -> bool:
"""
bool: True if the function is the constructor
"""
return self._function_type == FunctionType.CONSTRUCTOR
@property
def is_constructor_variables(self) -> bool:
"""
bool: True if the function is the constructor of the variables
Slither has inbuilt functions to hold the state variables initialization
"""
return self._function_type in [
FunctionType.CONSTRUCTOR_VARIABLES,
FunctionType.CONSTRUCTOR_CONSTANT_VARIABLES,
]
@property
def is_fallback(self) -> bool:
"""
Determine if the function is the fallback function for the contract
Returns
(bool)
"""
return self._function_type == FunctionType.FALLBACK
@property
def is_receive(self) -> bool:
"""
Determine if the function is the receive function for the contract
Returns
(bool)
"""
return self._function_type == FunctionType.RECEIVE
# endregion
###################################################################################
###################################################################################
# region Payable
###################################################################################
###################################################################################
@property
def payable(self) -> bool:
"""
bool: True if the function is payable
"""
return self._payable
@payable.setter
def payable(self, p: bool):
self._payable = p
# endregion
###################################################################################
###################################################################################
# region Visibility
###################################################################################
###################################################################################
@property
def visibility(self) -> str:
"""
str: Function visibility
"""
assert self._visibility is not None
return self._visibility
@visibility.setter
def visibility(self, v: str):
self._visibility = v
def set_visibility(self, v: str):
self._visibility = v
@property
def view(self) -> bool:
"""
bool: True if the function is declared as view
"""
return self._view
@view.setter
def view(self, v: bool):
self._view = v
@property
def pure(self) -> bool:
"""
bool: True if the function is declared as pure
"""
return self._pure
@pure.setter
def pure(self, p: bool):
self._pure = p
@property
def is_shadowed(self) -> bool:
return self._is_shadowed
@is_shadowed.setter
def is_shadowed(self, is_shadowed):
self._is_shadowed = is_shadowed
@property
def shadows(self) -> bool:
return self._shadows
@shadows.setter
def shadows(self, _shadows: bool):
self._shadows = _shadows
# endregion
###################################################################################
###################################################################################
# region Function's body
###################################################################################
###################################################################################
@property
def is_implemented(self) -> bool:
"""
bool: True if the function is implemented
"""
return self._is_implemented
@is_implemented.setter
def is_implemented(self, is_impl: bool):
self._is_implemented = is_impl
@property
def is_empty(self) -> bool:
"""
bool: True if the function is empty, None if the function is an interface
"""
return self._is_empty
@is_empty.setter
def is_empty(self, empty: bool):
self._is_empty = empty
# endregion
###################################################################################
###################################################################################
# region Nodes
###################################################################################
###################################################################################
@property
def nodes(self) -> List["Node"]:
"""
list(Node): List of the nodes
"""
return list(self._nodes)
@nodes.setter
def nodes(self, nodes: List["Node"]):
self._nodes = nodes
@property
def entry_point(self) -> Optional["Node"]:
"""
Node: Entry point of the function
"""
return self._entry_point
@entry_point.setter
def entry_point(self, node: "Node"):
self._entry_point = node
def add_node(self, node: "Node"):
if not self._entry_point:
self._entry_point = node
self._nodes.append(node)
@property
def nodes_ordered_dominators(self) -> List["Node"]:
# TODO: does not work properly; most likely due to modifier call
# This will not work for modifier call that lead to multiple nodes
# from slither.core.cfg.node import NodeType
if self._nodes_ordered_dominators is None:
self._nodes_ordered_dominators = []
if self.entry_point:
self._compute_nodes_ordered_dominators(self.entry_point)
for node in self.nodes:
# if node.type == NodeType.OTHER_ENTRYPOINT:
if not node in self._nodes_ordered_dominators:
self._compute_nodes_ordered_dominators(node)
return self._nodes_ordered_dominators
def _compute_nodes_ordered_dominators(self, node: "Node"):
assert self._nodes_ordered_dominators is not None
if node in self._nodes_ordered_dominators:
return
self._nodes_ordered_dominators.append(node)
for dom in node.dominance_exploration_ordered:
self._compute_nodes_ordered_dominators(dom)
# endregion
###################################################################################
###################################################################################
# region Parameters
###################################################################################
###################################################################################
@property
def parameters(self) -> List["LocalVariable"]:
"""
list(LocalVariable): List of the parameters
"""
return list(self._parameters)
def parameter_cache(self):
"""
stuff
"""
return (self._parameter_cache)
def add_parameter_cache(self, new_param_cache):
copy_param_cache = []
for pc in new_param_cache:
num = pc[0].copy()
den = pc[1].copy()
norm = pc[2]
lc = pc[3]
field = pc[4].copy()
ftype = pc[5]
adress = pc[6]
x = [num, den, norm, lc, field, ftype, adress]
copy_param_cache.append(x)
self._parameter_cache.append(copy_param_cache)
def add_parameters(self, p: "LocalVariable"):
self._parameters.append(p)
def add_parameter_cache_return(self, ret_obj):
self._parameter_cache_return.append(ret_obj)
def get_parameter_cache_return(self, index):
return(self._parameter_cache_return[index])
@property
def parameters_ssa(self) -> List["LocalIRVariable"]:
"""
list(LocalIRVariable): List of the parameters (SSA form)
"""
return list(self._parameters_ssa)
def add_parameter_ssa(self, var: "LocalIRVariable"):
self._parameters_ssa.append(var)
def parameters_src(self) -> SourceMapping:
return self._parameters_src
# endregion
###################################################################################
###################################################################################
# region Return values
###################################################################################
###################################################################################
@property
def return_type(self) -> Optional[List[Type]]:
"""
Return the list of return type
If no return, return None
"""
returns = self.returns
if returns:
return [r.type for r in returns]
return None
def returns_src(self) -> SourceMapping:
return self._returns_src
@property
def type(self) -> Optional[List[Type]]:
"""
Return the list of return type
If no return, return None
Alias of return_type
"""
return self.return_type
@property
def returns(self) -> List["LocalVariable"]:
"""
list(LocalVariable): List of the return variables
"""
return list(self._returns)
def add_return(self, r: "LocalVariable"):
self._returns.append(r)
@property
def returns_ssa(self) -> List["LocalIRVariable"]:
"""
list(LocalIRVariable): List of the return variables (SSA form)
"""
return list(self._returns_ssa)
def add_return_ssa(self, var: "LocalIRVariable"):
self._returns_ssa.append(var)
def clear_returns_ssa(self):
self._returns_ssa.clear()
# endregion
###################################################################################
###################################################################################
# region Modifiers
###################################################################################
###################################################################################
@property
def modifiers(self) -> List[Union["Contract", "Function"]]:
"""
list(Modifier): List of the modifiers
Can be contract for constructor's calls
"""
return [c.modifier for c in self._modifiers]
def add_modifier(self, modif: "ModifierStatements"):
self._modifiers.append(modif)
@property
def modifiers_statements(self) -> List[ModifierStatements]:
"""
list(ModifierCall): List of the modifiers call (include expression and irs)
"""
return list(self._modifiers)
@property
def explicit_base_constructor_calls(self) -> List["Function"]:
"""
list(Function): List of the base constructors called explicitly by this presumed constructor definition.
Base constructors implicitly or explicitly called by the contract definition will not be
included.
"""
# This is a list of contracts internally, so we convert it to a list of constructor functions.
return [
c.modifier.constructors_declared
for c in self._explicit_base_constructor_calls
if c.modifier.constructors_declared
]
@property
def explicit_base_constructor_calls_statements(self) -> List[ModifierStatements]:
"""
list(ModifierCall): List of the base constructors called explicitly by this presumed constructor definition.
"""
# This is a list of contracts internally, so we convert it to a list of constructor functions.
return list(self._explicit_base_constructor_calls)
def add_explicit_base_constructor_calls_statements(self, modif: ModifierStatements):
self._explicit_base_constructor_calls.append(modif)
# endregion
###################################################################################
###################################################################################
# region Variables
###################################################################################
###################################################################################
@property
def variables(self) -> List[LocalVariable]:
"""
Return all local variables
Include paramters and return values
"""
return list(self._variables.values())
@property
def local_variables(self) -> List[LocalVariable]:
"""
Return all local variables (dont include paramters and return values)
"""
return list(set(self.variables) - set(self.returns) - set(self.parameters))
@property
def variables_as_dict(self) -> Dict[str, LocalVariable]:
return self._variables
@property
def variables_read(self) -> List["Variable"]:
"""
list(Variable): Variables read (local/state/solidity)
"""
return list(self._vars_read)
@property
def variables_written(self) -> List["Variable"]:
"""
list(Variable): Variables written (local/state/solidity)
"""
return list(self._vars_written)
@property
def state_variables_read(self) -> List["StateVariable"]:
"""
list(StateVariable): State variables read
"""
return list(self._state_vars_read)
@property
def solidity_variables_read(self) -> List["SolidityVariable"]:
"""
list(SolidityVariable): Solidity variables read
"""
return list(self._solidity_vars_read)
@property
def state_variables_written(self) -> List["StateVariable"]:
"""
list(StateVariable): State variables written
"""
return list(self._state_vars_written)
@property
def variables_read_or_written(self) -> List["Variable"]:
"""
list(Variable): Variables read or written (local/state/solidity)
"""
return list(self._vars_read_or_written)
@property
def variables_read_as_expression(self) -> List["Expression"]:
return self._expression_vars_read
@property
def variables_written_as_expression(self) -> List["Expression"]:
return self._expression_vars_written
@property
def slithir_variables(self) -> List["SlithIRVariable"]:
"""
Temporary and Reference Variables (not SSA form)
"""
return list(self._slithir_variables)
# endregion
###################################################################################
###################################################################################
# region Calls
###################################################################################
###################################################################################
@property
def internal_calls(self) -> List["InternalCallType"]:
"""
list(Function or SolidityFunction): List of function calls (that does not create a transaction)
"""
return list(self._internal_calls)
@property
def solidity_calls(self) -> List[SolidityFunction]:
"""
list(SolidityFunction): List of Soldity calls
"""
return list(self._solidity_calls)
@property
def high_level_calls(self) -> List["HighLevelCallType"]:
"""
list((Contract, Function|Variable)):
List of high level calls (external calls).
A variable is called in case of call to a public state variable
Include library calls
"""
return list(self._high_level_calls)
@property
def library_calls(self) -> List["LibraryCallType"]:
"""
list((Contract, Function)):
"""
return list(self._library_calls)
@property
def low_level_calls(self) -> List["LowLevelCallType"]:
"""
list((Variable|SolidityVariable, str)): List of low_level call
A low level call is defined by
- the variable called
- the name of the function (call/delegatecall/codecall)
"""
return list(self._low_level_calls)
@property
def external_calls_as_expressions(self) -> List["Expression"]:
"""
list(ExpressionCall): List of message calls (that creates a transaction)
"""
return list(self._external_calls_as_expressions)
# endregion
###################################################################################
###################################################################################
# region Expressions
###################################################################################
###################################################################################
@property
def calls_as_expressions(self) -> List["Expression"]:
return self._expression_calls
@property
def expressions(self) -> List["Expression"]:
"""
list(Expression): List of the expressions
"""
if self._expressions is None:
expressionss = [n.expression for n in self.nodes]
expressions = [e for e in expressionss if e]
self._expressions = expressions
return self._expressions
@property
def return_values(self) -> List["SlithIRVariable"]:
"""
list(Return Values): List of the return values
"""
from slither.core.cfg.node import NodeType
from slither.slithir.operations import Return
from slither.slithir.variables import Constant
if self._return_values is None:
return_values = []
returns = [n for n in self.nodes if n.type == NodeType.RETURN]
[ # pylint: disable=expression-not-assigned
return_values.extend(ir.values)
for node in returns
for ir in node.irs
if isinstance(ir, Return)
]
self._return_values = list({x for x in return_values if not isinstance(x, Constant)})
return self._return_values
@property
def return_values_ssa(self) -> List["SlithIRVariable"]:
"""
list(Return Values in SSA form): List of the return values in ssa form
"""
from slither.core.cfg.node import NodeType
from slither.slithir.operations import Return
from slither.slithir.variables import Constant
if self._return_values_ssa is None:
return_values_ssa = []
returns = [n for n in self.nodes if n.type == NodeType.RETURN]
[ # pylint: disable=expression-not-assigned
return_values_ssa.extend(ir.values)
for node in returns
for ir in node.irs_ssa
if isinstance(ir, Return)
]
self._return_values_ssa = list(
#{x for x in return_values_ssa if not isinstance(x, Constant)}
{x for x in return_values_ssa}
)
return self._return_values_ssa
# endregion
###################################################################################
###################################################################################
# region SlithIR
###################################################################################
###################################################################################
@property
def slithir_operations(self) -> List["Operation"]:
"""
list(Operation): List of the slithir operations
"""
if self._slithir_operations is None:
operationss = [n.irs for n in self.nodes]
operations = [item for sublist in operationss for item in sublist if item]
self._slithir_operations = operations
return self._slithir_operations
@property
def slithir_ssa_operations(self) -> List["Operation"]:
"""
list(Operation): List of the slithir operations (SSA)
"""
if self._slithir_ssa_operations is None:
operationss = [n.irs_ssa for n in self.nodes]
operations = [item for sublist in operationss for item in sublist if item]
self._slithir_ssa_operations = operations
return self._slithir_ssa_operations
# endregion
###################################################################################
###################################################################################
# region Signature
###################################################################################
###################################################################################
@property
def solidity_signature(self) -> str:
"""
Return a signature following the Solidity Standard
Contract and converted into address
It might still keep internal types (ex: structure name) for internal functions.
The reason is that internal functions allows recursive structure definition, which
can't be converted following the Solidity stand ard
:return: the solidity signature
"""
if self._solidity_signature is None:
parameters = [
convert_type_for_solidity_signature_to_string(x.type) for x in self.parameters
]
self._solidity_signature = self.name + "(" + ",".join(parameters) + ")"
return self._solidity_signature
@property
def signature(self) -> Tuple[str, List[str], List[str]]:
"""
(str, list(str), list(str)): Function signature as
(name, list parameters type, list return values type)
"""
if self._signature is None:
signature = (
self.name,
[str(x.type) for x in self.parameters],
[str(x.type) for x in self.returns],
)
self._signature = signature
return self._signature
@property
def signature_str(self) -> str:
"""
str: func_name(type1,type2) returns (type3)
Return the function signature as a str (contains the return values)
"""
if self._signature_str is None:
name, parameters, returnVars = self.signature
self._signature_str = (
name + "(" + ",".join(parameters) + ") returns(" + ",".join(returnVars) + ")"
)
return self._signature_str
# endregion
###################################################################################
###################################################################################
# region Functions
###################################################################################
###################################################################################
@property
@abstractmethod
def functions_shadowed(self) -> List["Function"]:
pass
# endregion
###################################################################################
###################################################################################
# region Reachable
###################################################################################
###################################################################################
@property
def reachable_from_nodes(self) -> Set[ReacheableNode]:
"""
Return
ReacheableNode
"""
return self._reachable_from_nodes
@property
def reachable_from_functions(self) -> Set["Function"]:
return self._reachable_from_functions
@property
def all_reachable_from_functions(self) -> Set["Function"]:
"""
Give the recursive version of reachable_from_functions (all the functions that lead to call self in the CFG)
"""
if self._all_reachable_from_functions is None:
functions: Set["Function"] = set()
new_functions = self.reachable_from_functions
# iterate until we have are finding new functions
while new_functions and not new_functions.issubset(functions):
functions = functions.union(new_functions)
# Use a temporary set, because we iterate over new_functions
new_functionss: Set["Function"] = set()
for f in new_functions:
new_functionss = new_functionss.union(f.reachable_from_functions)
new_functions = new_functionss - functions
self._all_reachable_from_functions = functions
return self._all_reachable_from_functions
def add_reachable_from_node(self, n: "Node", ir: "Operation"):
self._reachable_from_nodes.add(ReacheableNode(n, ir))
self._reachable_from_functions.add(n.function)
# endregion
###################################################################################
###################################################################################
# region Recursive getters
###################################################################################
###################################################################################
def _explore_functions(self, f_new_values: Callable[["Function"], List]):
values = f_new_values(self)
explored = [self]
to_explore = [
c for c in self.internal_calls if isinstance(c, Function) and c not in explored
]
to_explore += [
c for (_, c) in self.library_calls if isinstance(c, Function) and c not in explored
]
to_explore += [m for m in self.modifiers if m not in explored]
while to_explore:
f = to_explore[0]
to_explore = to_explore[1:]
if f in explored:
continue
explored.append(f)
values += f_new_values(f)
to_explore += [
c
for c in f.internal_calls
if isinstance(c, Function) and c not in explored and c not in to_explore
]
to_explore += [
c
for (_, c) in f.library_calls
if isinstance(c, Function) and c not in explored and c not in to_explore
]
to_explore += [m for m in f.modifiers if m not in explored and m not in to_explore]
return list(set(values))
def all_state_variables_read(self) -> List["StateVariable"]:
"""recursive version of variables_read"""
if self._all_state_variables_read is None:
self._all_state_variables_read = self._explore_functions(
lambda x: x.state_variables_read
)
return self._all_state_variables_read
def all_solidity_variables_read(self) -> List[SolidityVariable]:
"""recursive version of solidity_read"""
if self._all_solidity_variables_read is None:
self._all_solidity_variables_read = self._explore_functions(
lambda x: x.solidity_variables_read
)
return self._all_solidity_variables_read
def all_slithir_variables(self) -> List["SlithIRVariable"]:
"""recursive version of slithir_variables"""
if self._all_slithir_variables is None:
self._all_slithir_variables = self._explore_functions(lambda x: x.slithir_variables)
return self._all_slithir_variables
def all_nodes(self) -> List["Node"]:
"""recursive version of nodes"""
if self._all_nodes is None:
self._all_nodes = self._explore_functions(lambda x: x.nodes)
return self._all_nodes
def all_expressions(self) -> List["Expression"]:
"""recursive version of variables_read"""
if self._all_expressions is None:
self._all_expressions = self._explore_functions(lambda x: x.expressions)
return self._all_expressions
def all_slithir_operations(self) -> List["Operation"]:
if self._all_slithir_operations is None:
self._all_slithir_operations = self._explore_functions(lambda x: x.slithir_operations)
return self._all_slithir_operations
def all_state_variables_written(self) -> List[StateVariable]:
"""recursive version of variables_written"""
if self._all_state_variables_written is None:
self._all_state_variables_written = self._explore_functions(
lambda x: x.state_variables_written
)
return self._all_state_variables_written
def all_internal_calls(self) -> List["InternalCallType"]:
"""recursive version of internal_calls"""
if self._all_internals_calls is None:
self._all_internals_calls = self._explore_functions(lambda x: x.internal_calls)
return self._all_internals_calls
def all_low_level_calls(self) -> List["LowLevelCallType"]:
"""recursive version of low_level calls"""
if self._all_low_level_calls is None:
self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls)
return self._all_low_level_calls
def all_high_level_calls(self) -> List["HighLevelCallType"]:
"""recursive version of high_level calls"""
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls
def all_library_calls(self) -> List["LibraryCallType"]:
"""recursive version of library calls"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls
def all_solidity_calls(self) -> List[SolidityFunction]:
"""recursive version of solidity calls"""
if self._all_solidity_calls is None:
self._all_solidity_calls = self._explore_functions(lambda x: x.solidity_calls)
return self._all_solidity_calls
@staticmethod
def _explore_func_cond_read(func: "Function", include_loop: bool) -> List["StateVariable"]:
ret = [n.state_variables_read for n in func.nodes if n.is_conditional(include_loop)]
return [item for sublist in ret for item in sublist]
def all_conditional_state_variables_read(self, include_loop=True) -> List["StateVariable"]:
"""
Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_state_variables_read_with_loop is None:
self._all_conditional_state_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_cond_read(x, include_loop)
)
return self._all_conditional_state_variables_read_with_loop
if self._all_conditional_state_variables_read is None:
self._all_conditional_state_variables_read = self._explore_functions(
lambda x: self._explore_func_cond_read(x, include_loop)
)
return self._all_conditional_state_variables_read
@staticmethod
def _solidity_variable_in_binary(node: "Node") -> List[SolidityVariable]:
from slither.slithir.operations.binary import Binary
ret = []
for ir in node.irs:
if isinstance(ir, Binary):
ret += ir.read
return [var for var in ret if isinstance(var, SolidityVariable)]
@staticmethod
def _explore_func_conditional(
func: "Function",
f: Callable[["Node"], List[SolidityVariable]],
include_loop: bool,
):
ret = [f(n) for n in func.nodes if n.is_conditional(include_loop)]
return [item for sublist in ret for item in sublist]
def all_conditional_solidity_variables_read(self, include_loop=True) -> List[SolidityVariable]:
"""
Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_solidity_variables_read_with_loop is None:
self._all_conditional_solidity_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_conditional(
x, self._solidity_variable_in_binary, include_loop
)
)
return self._all_conditional_solidity_variables_read_with_loop
if self._all_conditional_solidity_variables_read is None:
self._all_conditional_solidity_variables_read = self._explore_functions(
lambda x: self._explore_func_conditional(
x, self._solidity_variable_in_binary, include_loop
)
)
return self._all_conditional_solidity_variables_read
@staticmethod
def _solidity_variable_in_internal_calls(node: "Node") -> List[SolidityVariable]:
from slither.slithir.operations.internal_call import InternalCall
ret = []
for ir in node.irs:
if isinstance(ir, InternalCall):
ret += ir.read
return [var for var in ret if isinstance(var, SolidityVariable)]
@staticmethod
def _explore_func_nodes(func: "Function", f: Callable[["Node"], List[SolidityVariable]]):
ret = [f(n) for n in func.nodes]
return [item for sublist in ret for item in sublist]
def all_solidity_variables_used_as_args(self) -> List[SolidityVariable]:
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solidity_variables_used_as_args = self._explore_functions(
lambda x: self._explore_func_nodes(x, self._solidity_variable_in_internal_calls)
)
return self._all_solidity_variables_used_as_args
# endregion
###################################################################################
###################################################################################
# region Visitor
###################################################################################
###################################################################################
def apply_visitor(self, Visitor: Callable) -> List:
"""
Apply a visitor to all the function expressions
Args:
Visitor: slither.visitors
Returns
list(): results of the visit
"""
expressions = self.expressions
v = [Visitor(e).result() for e in expressions]
return [item for sublist in v for item in sublist]
# endregion
###################################################################################
###################################################################################
# region Getters from/to object
###################################################################################
###################################################################################
def get_local_variable_from_name(self, variable_name: str) -> Optional[LocalVariable]:
"""
Return a local variable from a name
Args:
variable_name (str): name of the variable
Returns:
LocalVariable
"""
return next((v for v in self.variables if v.name == variable_name), None)
# endregion
###################################################################################
###################################################################################
# region Export
###################################################################################
###################################################################################
def cfg_to_dot(self, filename: str):
"""
Export the function to a dot file
Args:
filename (str)
"""
with open(filename, "w", encoding="utf8") as f:
f.write("digraph{\n")
for node in self.nodes:
f.write(f'{node.node_id}[label="{str(node)}"];\n')
for son in node.sons:
f.write(f"{node.node_id}->{son.node_id};\n")
f.write("}\n")
def dominator_tree_to_dot(self, filename: str):
"""
Export the dominator tree of the function to a dot file
Args:
filename (str)
"""
def description(node):
desc = f"{node}\n"
desc += f"id: {node.node_id}"
if node.dominance_frontier:
desc += f"\ndominance frontier: {[n.node_id for n in node.dominance_frontier]}"
return desc
with open(filename, "w", encoding="utf8") as f:
f.write("digraph{\n")
for node in self.nodes:
f.write(f'{node.node_id}[label="{description(node)}"];\n')
if node.immediate_dominator:
f.write(f"{node.immediate_dominator.node_id}->{node.node_id};\n")
f.write("}\n")
def slithir_cfg_to_dot(self, filename: str):
"""
Export the CFG to a DOT file. The nodes includes the Solidity expressions and the IRs
:param filename:
:return:
"""
content = self.slithir_cfg_to_dot_str()
with open(filename, "w", encoding="utf8") as f:
f.write(content)
def slithir_cfg_to_dot_str(self, skip_expressions=False) -> str:
"""
Export the CFG to a DOT format. The nodes includes the Solidity expressions and the IRs
:return: the DOT content
:rtype: str
"""
from slither.core.cfg.node import NodeType
content = ""
content += "digraph{\n"
for node in self.nodes:
label = f"Node Type: {str(node.type)} {node.node_id}\n"
if node.expression and not skip_expressions:
label += f"\nEXPRESSION:\n{node.expression}\n"
if node.irs and not skip_expressions:
label += "\nIRs:\n" + "\n".join([str(ir) for ir in node.irs])
content += f'{node.node_id}[label="{label}"];\n'
if node.type in [NodeType.IF, NodeType.IFLOOP]:
true_node = node.son_true
if true_node:
content += f'{node.node_id}->{true_node.node_id}[label="True"];\n'
false_node = node.son_false
if false_node:
content += f'{node.node_id}->{false_node.node_id}[label="False"];\n'
else:
for son in node.sons:
content += f"{node.node_id}->{son.node_id};\n"
content += "}\n"
return content
# endregion
###################################################################################
###################################################################################
# region Summary information
###################################################################################
###################################################################################
def is_reading(self, variable: "Variable") -> bool:
"""
Check if the function reads the variable
Args:
variable (Variable):
Returns:
bool: True if the variable is read
"""
return variable in self.variables_read
def is_reading_in_conditional_node(self, variable: "Variable") -> bool:
"""
Check if the function reads the variable in a IF node
Args:
variable (Variable):
Returns:
bool: True if the variable is read
"""
variables_reads = [n.variables_read for n in self.nodes if n.contains_if()]
variables_read = [item for sublist in variables_reads for item in sublist]
return variable in variables_read
def is_reading_in_require_or_assert(self, variable: "Variable") -> bool:
"""
Check if the function reads the variable in an require or assert
Args:
variable (Variable):
Returns:
bool: True if the variable is read
"""
variables_reads = [n.variables_read for n in self.nodes if n.contains_require_or_assert()]
variables_read = [item for sublist in variables_reads for item in sublist]
return variable in variables_read
def is_writing(self, variable: "Variable") -> bool:
"""
Check if the function writes the variable
Args:
variable (Variable):
Returns:
bool: True if the variable is written
"""
return variable in self.variables_written
@abstractmethod
def get_summary(
self,
) -> Tuple[str, str, str, List[str], List[str], List[str], List[str], List[str]]:
pass
def is_protected(self) -> bool:
"""
Determine if the function is protected using a check on msg.sender
Consider onlyOwner as a safe modifier.
If the owner functionality is incorrectly implemented, this will lead to incorrectly
classify the function as protected
Otherwise only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool)
"""
if self._is_protected is None:
if self.is_constructor:
self._is_protected = True
return True
if "onlyOwner" in [m.name for m in self.modifiers]:
self._is_protected = True
return True
conditional_vars = self.all_conditional_solidity_variables_read(include_loop=False)
args_vars = self.all_solidity_variables_used_as_args()
self._is_protected = (
SolidityVariableComposed("msg.sender") in conditional_vars + args_vars
)
return self._is_protected
@property
def is_reentrant(self) -> bool:
"""
Determine if the function can be re-entered
"""
# TODO: compare with hash of known nonReentrant modifier instead of the name
if "nonReentrant" in [m.name for m in self.modifiers]:
return False
if self.visibility in ["public", "external"]:
return True
# If it's an internal function, check if all its entry points have the nonReentrant modifier
all_entry_points = [
f for f in self.all_reachable_from_functions if f.visibility in ["public", "external"]
]
if not all_entry_points:
return True
return not all(("nonReentrant" in [m.name for m in f.modifiers] for f in all_entry_points))
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
def _analyze_read_write(self):
"""Compute variables read/written/..."""
write_var = [x.variables_written_as_expression for x in self.nodes]
write_var = [x for x in write_var if x]
write_var = [item for sublist in write_var for item in sublist]
write_var = list(set(write_var))
# Remove dupplicate if they share the same string representation
write_var = [
next(obj)
for i, obj in groupby(sorted(write_var, key=lambda x: str(x)), lambda x: str(x))
]
self._expression_vars_written = write_var
write_var = [x.variables_written for x in self.nodes]
write_var = [x for x in write_var if x]
write_var = [item for sublist in write_var for item in sublist]
write_var = list(set(write_var))
# Remove dupplicate if they share the same string representation
write_var = [
next(obj)
for i, obj in groupby(sorted(write_var, key=lambda x: str(x)), lambda x: str(x))
]
self._vars_written = write_var
read_var = [x.variables_read_as_expression for x in self.nodes]
read_var = [x for x in read_var if x]
read_var = [item for sublist in read_var for item in sublist]
# Remove dupplicate if they share the same string representation
read_var = [
next(obj)
for i, obj in groupby(sorted(read_var, key=lambda x: str(x)), lambda x: str(x))
]
self._expression_vars_read = read_var
read_var = [x.variables_read for x in self.nodes]
read_var = [x for x in read_var if x]
read_var = [item for sublist in read_var for item in sublist]
# Remove dupplicate if they share the same string representation
read_var = [
next(obj)
for i, obj in groupby(sorted(read_var, key=lambda x: str(x)), lambda x: str(x))
]
self._vars_read = read_var
self._state_vars_written = [
x for x in self.variables_written if isinstance(x, StateVariable)
]
self._state_vars_read = [x for x in self.variables_read if isinstance(x, StateVariable)]
self._solidity_vars_read = [
x for x in self.variables_read if isinstance(x, SolidityVariable)
]
self._vars_read_or_written = self._vars_written + self._vars_read
slithir_variables = [x.slithir_variables for x in self.nodes]
slithir_variables = [x for x in slithir_variables if x]
self._slithir_variables = [item for sublist in slithir_variables for item in sublist]
def _analyze_calls(self):
calls = [x.calls_as_expression for x in self.nodes]
calls = [x for x in calls if x]
calls = [item for sublist in calls for item in sublist]
self._expression_calls = list(set(calls))
internal_calls = [x.internal_calls for x in self.nodes]
internal_calls = [x for x in internal_calls if x]
internal_calls = [item for sublist in internal_calls for item in sublist]
self._internal_calls = list(set(internal_calls))
self._solidity_calls = [c for c in internal_calls if isinstance(c, SolidityFunction)]
low_level_calls = [x.low_level_calls for x in self.nodes]
low_level_calls = [x for x in low_level_calls if x]
low_level_calls = [item for sublist in low_level_calls for item in sublist]
self._low_level_calls = list(set(low_level_calls))
high_level_calls = [x.high_level_calls for x in self.nodes]
high_level_calls = [x for x in high_level_calls if x]
high_level_calls = [item for sublist in high_level_calls for item in sublist]
self._high_level_calls = list(set(high_level_calls))
library_calls = [x.library_calls for x in self.nodes]
library_calls = [x for x in library_calls if x]
library_calls = [item for sublist in library_calls for item in sublist]
self._library_calls = list(set(library_calls))
external_calls_as_expressions = [x.external_calls_as_expressions for x in self.nodes]
external_calls_as_expressions = [x for x in external_calls_as_expressions if x]
external_calls_as_expressions = [
item for sublist in external_calls_as_expressions for item in sublist
]
self._external_calls_as_expressions = list(set(external_calls_as_expressions))
# endregion
###################################################################################
###################################################################################
# region Nodes
###################################################################################
###################################################################################
def new_node(
self, node_type: "NodeType", src: Union[str, Dict], scope: Union[Scope, "Function"]
) -> "Node":
from slither.core.cfg.node import Node
node = Node(node_type, self._counter_nodes, scope, self.file_scope)
node.set_offset(src, self.compilation_unit)
self._counter_nodes += 1
node.set_function(self)
self._nodes.append(node)
return node
# endregion
###################################################################################
###################################################################################
# region SlithIr and SSA
###################################################################################
###################################################################################
def _get_last_ssa_variable_instances(
self, target_state: bool, target_local: bool
) -> Dict[str, Set["SlithIRVariable"]]:
# pylint: disable=too-many-locals,too-many-branches
from slither.slithir.variables import ReferenceVariable
from slither.slithir.operations import OperationWithLValue
from slither.core.cfg.node import NodeType
if not self.is_implemented:
return {}
if self._entry_point is None:
return {}
# node, values
to_explore: List[Tuple["Node", Dict]] = [(self._entry_point, {})]
# node -> values
explored: Dict = {}
# name -> instances
ret: Dict = {}
while to_explore:
node, values = to_explore[0]
to_explore = to_explore[1::]
if node.type != NodeType.ENTRYPOINT:
for ir_ssa in node.irs_ssa:
if isinstance(ir_ssa, OperationWithLValue):
lvalue = ir_ssa.lvalue
if isinstance(lvalue, ReferenceVariable):
lvalue = lvalue.points_to_origin
if isinstance(lvalue, StateVariable) and target_state:
values[lvalue.canonical_name] = {lvalue}
if isinstance(lvalue, LocalVariable) and target_local:
values[lvalue.canonical_name] = {lvalue}
# Check for fixpoint
if node in explored:
if values == explored[node]:
continue
for k, instances in values.items():
if k not in explored[node]:
explored[node][k] = set()
explored[node][k] |= instances
values = explored[node]
else:
explored[node] = values
# Return condition
if node.will_return:
for name, instances in values.items():
if name not in ret:
ret[name] = set()
ret[name] |= instances
for son in node.sons:
to_explore.append((son, dict(values)))
return ret
def get_last_ssa_state_variables_instances(
self,
) -> Dict[str, Set["SlithIRVariable"]]:
return self._get_last_ssa_variable_instances(target_state=True, target_local=False)
def get_last_ssa_local_variables_instances(
self,
) -> Dict[str, Set["SlithIRVariable"]]:
return self._get_last_ssa_variable_instances(target_state=False, target_local=True)
@staticmethod
def _unchange_phi(ir: "Operation"):
from slither.slithir.operations import Phi, PhiCallback
if not isinstance(ir, (Phi, PhiCallback)) or len(ir.rvalues) > 1:
return False
if not ir.rvalues:
return True
return ir.rvalues[0] == ir.lvalue
def fix_phi(self, last_state_variables_instances, initial_state_variables_instances):
from slither.slithir.operations import InternalCall, PhiCallback
from slither.slithir.variables import Constant, StateIRVariable
for node in self.nodes:
for ir in node.irs_ssa:
if node == self.entry_point:
if isinstance(ir.lvalue, StateIRVariable):
additional = [initial_state_variables_instances[ir.lvalue.canonical_name]]
additional += last_state_variables_instances[ir.lvalue.canonical_name]
ir.rvalues = list(set(additional + ir.rvalues))
# function parameter
else:
# find index of the parameter
idx = self.parameters.index(ir.lvalue.non_ssa_version)
# find non ssa version of that index
additional = [n.ir.arguments[idx] for n in self.reachable_from_nodes]
additional = unroll(additional)
additional = [a for a in additional if not isinstance(a, Constant)]
ir.rvalues = list(set(additional + ir.rvalues))
if isinstance(ir, PhiCallback):
callee_ir = ir.callee_ir
if isinstance(callee_ir, InternalCall):
last_ssa = callee_ir.function.get_last_ssa_state_variables_instances()
if ir.lvalue.canonical_name in last_ssa:
ir.rvalues = list(last_ssa[ir.lvalue.canonical_name])
else:
ir.rvalues = [ir.lvalue]
else:
additional = last_state_variables_instances[ir.lvalue.canonical_name]
ir.rvalues = list(set(additional + ir.rvalues))
node.irs_ssa = [ir for ir in node.irs_ssa if not self._unchange_phi(ir)]
def generate_slithir_and_analyze(self):
for node in self.nodes:
node.slithir_generation()
self._analyze_read_write()
self._analyze_calls()
@abstractmethod
def generate_slithir_ssa(self, all_ssa_state_variables_instances):
pass
def update_read_write_using_ssa(self):
for node in self.nodes:
node.update_read_write_using_ssa()
self._analyze_read_write()
###################################################################################
###################################################################################
# region Built in definitions
###################################################################################
###################################################################################
def __str__(self):
return self.name
# endregion
| 69,756 | Python | .py | 1,533 | 36.189172 | 118 | 0.538606 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,290 | event.py | NioTheFirst_ScType/slither/core/declarations/event.py | from typing import List, Tuple, TYPE_CHECKING
from slither.core.children.child_contract import ChildContract
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.variables.event_variable import EventVariable
if TYPE_CHECKING:
from slither.core.declarations import Contract
class Event(ChildContract, SourceMapping):
def __init__(self):
super().__init__()
self._name = None
self._elems: List[EventVariable] = []
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, name: str):
self._name = name
@property
def signature(self) -> Tuple[str, List[str]]:
"""Return the function signature
Returns:
(str, list(str)): name, list parameters type
"""
return self.name, [str(x.type) for x in self.elems]
@property
def full_name(self) -> str:
"""Return the function signature as a str
Returns:
str: func_name(type1,type2)
"""
name, parameters = self.signature
return name + "(" + ",".join(parameters) + ")"
@property
def canonical_name(self) -> str:
"""Return the function signature as a str
Returns:
str: contract.func_name(type1,type2)
"""
return self.contract.name + self.full_name
@property
def elems(self) -> List["EventVariable"]:
return self._elems
def is_declared_by(self, contract: "Contract") -> bool:
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
def __str__(self):
return self.name
| 1,732 | Python | .py | 51 | 26.686275 | 68 | 0.625524 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,291 | custom_error.py | NioTheFirst_ScType/slither/core/declarations/custom_error.py | from typing import List, TYPE_CHECKING, Optional, Type, Union
from slither.core.solidity_types import UserDefinedType
from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.variables.local_variable import LocalVariable
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
class CustomError(SourceMapping):
def __init__(self, compilation_unit: "SlitherCompilationUnit"):
super().__init__()
self._name: str = ""
self._parameters: List[LocalVariable] = []
self._compilation_unit = compilation_unit
self._solidity_signature: Optional[str] = None
self._full_name: Optional[str] = None
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, new_name: str) -> None:
self._name = new_name
@property
def parameters(self) -> List[LocalVariable]:
return self._parameters
def add_parameters(self, p: "LocalVariable"):
self._parameters.append(p)
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self._compilation_unit
# region Signature
###################################################################################
###################################################################################
@staticmethod
def _convert_type_for_solidity_signature(t: Optional[Union[Type, List[Type]]]):
# pylint: disable=import-outside-toplevel
from slither.core.declarations import Contract
if isinstance(t, UserDefinedType) and isinstance(t.type, Contract):
return "address"
return str(t)
@property
def solidity_signature(self) -> Optional[str]:
"""
Return a signature following the Solidity Standard
Contract and converted into address
:return: the solidity signature
"""
# Ideally this should be an assert
# But due to a logic limitation in the solc parsing (find_variable)
# We need to raise an error if the custom error sig was not yet built
# (set_solidity_sig was not called before find_variable)
if self._solidity_signature is None:
raise ValueError("Custom Error not yet built")
return self._solidity_signature
def set_solidity_sig(self) -> None:
"""
Function to be called once all the parameters have been set
Returns:
"""
parameters = [x.type for x in self.parameters]
self._full_name = self.name + "(" + ",".join(map(str, parameters)) + ")"
solidity_parameters = map(self._convert_type_for_solidity_signature, parameters)
self._solidity_signature = self.name + "(" + ",".join(solidity_parameters) + ")"
@property
def full_name(self) -> Optional[str]:
"""
Return the error signature without
converting contract into address
:return: the error signature
"""
if self._full_name is None:
raise ValueError("Custom Error not yet built")
return self._full_name
# endregion
###################################################################################
###################################################################################
def __str__(self):
return "revert " + self.solidity_signature
| 3,394 | Python | .py | 76 | 37.184211 | 88 | 0.593996 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,292 | custom_error_top_level.py | NioTheFirst_ScType/slither/core/declarations/custom_error_top_level.py | from typing import TYPE_CHECKING
from slither.core.declarations.custom_error import CustomError
from slither.core.declarations.top_level import TopLevel
if TYPE_CHECKING:
from slither.core.compilation_unit import SlitherCompilationUnit
from slither.core.scope.scope import FileScope
class CustomErrorTopLevel(CustomError, TopLevel):
def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope"):
super().__init__(compilation_unit)
self.file_scope: "FileScope" = scope
| 521 | Python | .py | 10 | 47.9 | 87 | 0.788955 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,293 | solidity_import_placeholder.py | NioTheFirst_ScType/slither/core/declarations/solidity_import_placeholder.py | """
Special variable to model import with renaming
"""
from slither.core.declarations import Import
from slither.core.solidity_types import ElementaryType
from slither.core.variables.variable import Variable
class SolidityImportPlaceHolder(Variable):
"""
Placeholder for import on top level objects
See the example at https://blog.soliditylang.org/2020/09/02/solidity-0.7.1-release-announcement/
In the long term we should remove this and better integrate import aliases
"""
def __init__(self, import_directive: Import):
super().__init__()
assert import_directive.alias is not None
self._import_directive = import_directive
self._name = import_directive.alias
self._type = ElementaryType("string")
self._initialized = True
self._visibility = "private"
self._is_constant = True
@property
def type(self) -> ElementaryType:
return ElementaryType("string")
def __eq__(self, other):
return (
self.__class__ == other.__class__
and self._import_directive.filename == self._import_directive.filename
)
@property
def import_directive(self) -> Import:
return self._import_directive
def __hash__(self):
return hash(str(self.import_directive))
| 1,315 | Python | .py | 34 | 32.294118 | 100 | 0.682889 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,294 | using_for_top_level.py | NioTheFirst_ScType/slither/core/declarations/using_for_top_level.py | from typing import TYPE_CHECKING, List, Dict, Union
from slither.core.solidity_types.type import Type
from slither.core.declarations.top_level import TopLevel
if TYPE_CHECKING:
from slither.core.scope.scope import FileScope
class UsingForTopLevel(TopLevel):
def __init__(self, scope: "FileScope"):
super().__init__()
self._using_for: Dict[Union[str, Type], List[Type]] = {}
self.file_scope: "FileScope" = scope
@property
def using_for(self) -> Dict[Type, List[Type]]:
return self._using_for
| 544 | Python | .py | 13 | 36.769231 | 64 | 0.701521 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,295 | structure.py | NioTheFirst_ScType/slither/core/declarations/structure.py | from typing import List, TYPE_CHECKING, Dict, Optional
from slither.core.source_mapping.source_mapping import SourceMapping
if TYPE_CHECKING:
from slither.core.variables.structure_variable import StructureVariable
from slither.core.compilation_unit import SlitherCompilationUnit
class Structure(SourceMapping):
def __init__(self, compilation_unit: "SlitherCompilationUnit") -> None:
super().__init__()
self._name: Optional[str] = None
self._canonical_name: Optional[str] = None
self._elems: Dict[str, "StructureVariable"] = {}
# Name of the elements in the order of declaration
self._elems_ordered: List[str] = []
self.compilation_unit = compilation_unit
@property
def canonical_name(self) -> str:
assert self._canonical_name
return self._canonical_name
@canonical_name.setter
def canonical_name(self, name: str) -> None:
self._canonical_name = name
@property
def name(self) -> str:
assert self._name
return self._name
@name.setter
def name(self, new_name: str) -> None:
self._name = new_name
@property
def elems(self) -> Dict[str, "StructureVariable"]:
return self._elems
def add_elem_in_order(self, s: str) -> None:
self._elems_ordered.append(s)
@property
def elems_ordered(self) -> List["StructureVariable"]:
ret = []
for e in self._elems_ordered:
ret.append(self._elems[e])
return ret
def __str__(self) -> str:
return self.name
| 1,576 | Python | .py | 41 | 31.487805 | 75 | 0.656599 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,296 | enum_contract.py | NioTheFirst_ScType/slither/core/declarations/enum_contract.py | from typing import TYPE_CHECKING
from slither.core.children.child_contract import ChildContract
from slither.core.declarations import Enum
if TYPE_CHECKING:
from slither.core.declarations import Contract
class EnumContract(Enum, ChildContract):
def is_declared_by(self, contract: "Contract") -> bool:
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
| 477 | Python | .py | 13 | 31.076923 | 62 | 0.723913 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,297 | __init__.py | NioTheFirst_ScType/slither/core/declarations/__init__.py | from .contract import Contract
from .enum import Enum
from .event import Event
from .function import Function
from .import_directive import Import
from .modifier import Modifier
from .pragma_directive import Pragma
from .solidity_variables import (
SolidityVariable,
SolidityVariableComposed,
SolidityFunction,
)
from .structure import Structure
from .enum_contract import EnumContract
from .enum_top_level import EnumTopLevel
from .structure_contract import StructureContract
from .structure_top_level import StructureTopLevel
from .function_contract import FunctionContract
from .function_top_level import FunctionTopLevel
| 637 | Python | .py | 19 | 31.894737 | 50 | 0.855987 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,298 | structure_top_level.py | NioTheFirst_ScType/slither/core/declarations/structure_top_level.py | from typing import TYPE_CHECKING
from slither.core.declarations import Structure
from slither.core.declarations.top_level import TopLevel
if TYPE_CHECKING:
from slither.core.scope.scope import FileScope
from slither.core.compilation_unit import SlitherCompilationUnit
class StructureTopLevel(Structure, TopLevel):
def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope"):
super().__init__(compilation_unit)
self.file_scope: "FileScope" = scope
| 502 | Python | .py | 10 | 46 | 87 | 0.784836 | NioTheFirst/ScType | 8 | 4 | 1 | AGPL-3.0 | 9/5/2024, 10:48:01 PM (Europe/Amsterdam) |
2,286,299 | import_directive.py | NioTheFirst_ScType/slither/core/declarations/import_directive.py | from pathlib import Path
from typing import Optional, TYPE_CHECKING, Dict
from slither.core.source_mapping.source_mapping import SourceMapping
if TYPE_CHECKING:
from slither.core.scope.scope import FileScope
class Import(SourceMapping):
def __init__(self, filename: Path, scope: "FileScope"):
super().__init__()
self._filename: Path = filename
self._alias: Optional[str] = None
self.scope: "FileScope" = scope
# Map local name -> original name
self.renaming: Dict[str, str] = {}
@property
def filename(self) -> str:
"""
Return the absolute filename
:return:
:rtype:
"""
return self._filename.as_posix()
@property
def filename_path(self) -> Path:
"""
Return the absolute filename
:return:
:rtype:
"""
return self._filename
@property
def alias(self) -> Optional[str]:
return self._alias
@alias.setter
def alias(self, a: str):
self._alias = a
def __str__(self):
return self.filename
| 1,104 | Python | .py | 37 | 22.783784 | 68 | 0.611374 | 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.